util.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #define _GNU_SOURCE
  11. #include "config.h"
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <ctype.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include <jansson.h>
  18. #include <curl/curl.h>
  19. #include <time.h>
  20. #include <curses.h>
  21. #include "miner.h"
  22. #include "elist.h"
  23. #if JANSSON_MAJOR_VERSION >= 2
  24. #define JSON_LOADS(str, err_ptr) json_loads((str), 0, (err_ptr))
  25. #else
  26. #define JSON_LOADS(str, err_ptr) json_loads((str), (err_ptr))
  27. #endif
  28. struct data_buffer {
  29. void *buf;
  30. size_t len;
  31. };
  32. struct upload_buffer {
  33. const void *buf;
  34. size_t len;
  35. };
  36. struct header_info {
  37. char *lp_path;
  38. };
  39. struct tq_ent {
  40. void *data;
  41. struct list_head q_node;
  42. };
  43. struct thread_q {
  44. struct list_head q;
  45. bool frozen;
  46. pthread_mutex_t mutex;
  47. pthread_cond_t cond;
  48. };
  49. void vapplog(int prio, const char *fmt, va_list ap)
  50. {
  51. #ifdef HAVE_SYSLOG_H
  52. if (use_syslog) {
  53. vsyslog(prio, fmt, ap);
  54. }
  55. #else
  56. if (0) {}
  57. #endif
  58. else if (opt_log_output || prio == LOG_WARNING || prio == LOG_ERR) {
  59. char *f;
  60. int len;
  61. struct timeval tv = { };
  62. struct tm tm, *tm_p;
  63. gettimeofday(&tv, NULL);
  64. pthread_mutex_lock(&time_lock);
  65. tm_p = localtime(&tv.tv_sec);
  66. memcpy(&tm, tm_p, sizeof(tm));
  67. pthread_mutex_unlock(&time_lock);
  68. len = 40 + strlen(fmt) + 2;
  69. f = alloca(len);
  70. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d] %s\n",
  71. tm.tm_year + 1900,
  72. tm.tm_mon + 1,
  73. tm.tm_mday,
  74. tm.tm_hour,
  75. tm.tm_min,
  76. tm.tm_sec,
  77. fmt);
  78. /* Only output to stderr if it's not going to the screen as well */
  79. if (opt_log_output && !isatty(fileno((FILE *)stderr))) {
  80. va_list apc;
  81. va_copy(apc, ap);
  82. vfprintf(stderr, f, apc); /* atomic write to stderr */
  83. fflush(stderr);
  84. }
  85. log_curses(f, ap);
  86. }
  87. }
  88. void applog(int prio, const char *fmt, ...)
  89. {
  90. va_list ap;
  91. va_start(ap, fmt);
  92. vapplog(prio, fmt, ap);
  93. va_end(ap);
  94. }
  95. static void databuf_free(struct data_buffer *db)
  96. {
  97. if (!db)
  98. return;
  99. free(db->buf);
  100. memset(db, 0, sizeof(*db));
  101. }
  102. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  103. void *user_data)
  104. {
  105. struct data_buffer *db = user_data;
  106. size_t len = size * nmemb;
  107. size_t oldlen, newlen;
  108. void *newmem;
  109. static const unsigned char zero = 0;
  110. oldlen = db->len;
  111. newlen = oldlen + len;
  112. newmem = realloc(db->buf, newlen + 1);
  113. if (!newmem)
  114. return 0;
  115. db->buf = newmem;
  116. db->len = newlen;
  117. memcpy(db->buf + oldlen, ptr, len);
  118. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  119. return len;
  120. }
  121. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  122. void *user_data)
  123. {
  124. struct upload_buffer *ub = user_data;
  125. int len = size * nmemb;
  126. if (len > ub->len)
  127. len = ub->len;
  128. if (len) {
  129. memcpy(ptr, ub->buf, len);
  130. ub->buf += len;
  131. ub->len -= len;
  132. }
  133. return len;
  134. }
  135. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  136. {
  137. struct header_info *hi = user_data;
  138. size_t remlen, slen, ptrlen = size * nmemb;
  139. char *rem, *val = NULL, *key = NULL;
  140. void *tmp;
  141. val = calloc(1, ptrlen);
  142. key = calloc(1, ptrlen);
  143. if (!key || !val)
  144. goto out;
  145. tmp = memchr(ptr, ':', ptrlen);
  146. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  147. goto out;
  148. slen = tmp - ptr;
  149. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  150. goto out;
  151. memcpy(key, ptr, slen); /* store & nul term key */
  152. key[slen] = 0;
  153. rem = ptr + slen + 1; /* trim value's leading whitespace */
  154. remlen = ptrlen - slen - 1;
  155. while ((remlen > 0) && (isspace(*rem))) {
  156. remlen--;
  157. rem++;
  158. }
  159. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  160. val[remlen] = 0;
  161. while ((*val) && (isspace(val[strlen(val) - 1]))) {
  162. val[strlen(val) - 1] = 0;
  163. }
  164. if (!*val) /* skip blank value */
  165. goto out;
  166. if (opt_protocol)
  167. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  168. if (!strcasecmp("X-Long-Polling", key)) {
  169. hi->lp_path = val; /* steal memory reference */
  170. val = NULL;
  171. }
  172. out:
  173. free(key);
  174. free(val);
  175. return ptrlen;
  176. }
  177. static bool comms_error = false;
  178. json_t *json_rpc_call(CURL *curl, const char *url,
  179. const char *userpass, const char *rpc_req,
  180. bool longpoll_scan, bool longpoll)
  181. {
  182. json_t *val, *err_val, *res_val;
  183. int rc;
  184. struct data_buffer all_data = { };
  185. struct upload_buffer upload_data;
  186. json_error_t err = { };
  187. struct curl_slist *headers = NULL;
  188. char len_hdr[64], user_agent_hdr[128];
  189. char curl_err_str[CURL_ERROR_SIZE];
  190. long timeout = longpoll ? (60 * 60) : (60 * 10);
  191. struct header_info hi = { };
  192. bool lp_scanning = false;
  193. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  194. if (longpoll_scan)
  195. lp_scanning = want_longpoll && !have_longpoll;
  196. if (opt_protocol)
  197. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  198. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  199. curl_easy_setopt(curl, CURLOPT_URL, url);
  200. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  201. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  202. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  203. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  204. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  205. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  206. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  207. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  208. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  209. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  210. if (lp_scanning) {
  211. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  212. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  213. }
  214. if (userpass) {
  215. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  216. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  217. }
  218. curl_easy_setopt(curl, CURLOPT_POST, 1);
  219. if (opt_protocol)
  220. applog(LOG_DEBUG, "JSON protocol request:\n%s\n", rpc_req);
  221. upload_data.buf = rpc_req;
  222. upload_data.len = strlen(rpc_req);
  223. sprintf(len_hdr, "Content-Length: %lu",
  224. (unsigned long) upload_data.len);
  225. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  226. headers = curl_slist_append(headers,
  227. "Content-type: application/json");
  228. headers = curl_slist_append(headers, len_hdr);
  229. headers = curl_slist_append(headers, user_agent_hdr);
  230. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  231. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  232. rc = curl_easy_perform(curl);
  233. if (rc) {
  234. if (!comms_error)
  235. applog(LOG_ERR, "HTTP request failed: %s", curl_err_str);
  236. comms_error = true;
  237. goto err_out;
  238. }
  239. /* If X-Long-Polling was found, activate long polling */
  240. if (hi.lp_path) {
  241. have_longpoll = true;
  242. tq_push(thr_info[longpoll_thr_id].q, hi.lp_path);
  243. } else
  244. free(hi.lp_path);
  245. hi.lp_path = NULL;
  246. val = JSON_LOADS(all_data.buf, &err);
  247. if (!val) {
  248. if (!comms_error)
  249. applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
  250. comms_error = true;
  251. if (opt_protocol)
  252. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  253. goto err_out;
  254. }
  255. if (opt_protocol) {
  256. char *s = json_dumps(val, JSON_INDENT(3));
  257. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  258. free(s);
  259. }
  260. /* JSON-RPC valid response returns a non-null 'result',
  261. * and a null 'error'.
  262. */
  263. res_val = json_object_get(val, "result");
  264. err_val = json_object_get(val, "error");
  265. if (!res_val || json_is_null(res_val) ||
  266. (err_val && !json_is_null(err_val))) {
  267. char *s;
  268. if (err_val)
  269. s = json_dumps(err_val, JSON_INDENT(3));
  270. else
  271. s = strdup("(unknown reason)");
  272. if (!comms_error)
  273. applog(LOG_ERR, "JSON-RPC call failed: %s", s);
  274. comms_error = true;
  275. free(s);
  276. goto err_out;
  277. }
  278. comms_error = false;
  279. databuf_free(&all_data);
  280. curl_slist_free_all(headers);
  281. curl_easy_reset(curl);
  282. return val;
  283. err_out:
  284. databuf_free(&all_data);
  285. curl_slist_free_all(headers);
  286. curl_easy_reset(curl);
  287. return NULL;
  288. }
  289. char *bin2hex(const unsigned char *p, size_t len)
  290. {
  291. int i;
  292. char *s = malloc((len * 2) + 1);
  293. if (!s)
  294. return NULL;
  295. for (i = 0; i < len; i++)
  296. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  297. return s;
  298. }
  299. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  300. {
  301. while (*hexstr && len) {
  302. char hex_byte[3];
  303. unsigned int v;
  304. if (!hexstr[1]) {
  305. applog(LOG_ERR, "hex2bin str truncated");
  306. return false;
  307. }
  308. hex_byte[0] = hexstr[0];
  309. hex_byte[1] = hexstr[1];
  310. hex_byte[2] = 0;
  311. if (sscanf(hex_byte, "%x", &v) != 1) {
  312. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  313. return false;
  314. }
  315. *p = (unsigned char) v;
  316. p++;
  317. hexstr += 2;
  318. len--;
  319. }
  320. return (len == 0 && *hexstr == 0) ? true : false;
  321. }
  322. /* Subtract the `struct timeval' values X and Y,
  323. storing the result in RESULT.
  324. Return 1 if the difference is negative, otherwise 0. */
  325. int
  326. timeval_subtract (
  327. struct timeval *result, struct timeval *x, struct timeval *y)
  328. {
  329. /* Perform the carry for the later subtraction by updating Y. */
  330. if (x->tv_usec < y->tv_usec) {
  331. int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
  332. y->tv_usec -= 1000000 * nsec;
  333. y->tv_sec += nsec;
  334. }
  335. if (x->tv_usec - y->tv_usec > 1000000) {
  336. int nsec = (x->tv_usec - y->tv_usec) / 1000000;
  337. y->tv_usec += 1000000 * nsec;
  338. y->tv_sec -= nsec;
  339. }
  340. /* Compute the time remaining to wait.
  341. `tv_usec' is certainly positive. */
  342. result->tv_sec = x->tv_sec - y->tv_sec;
  343. result->tv_usec = x->tv_usec - y->tv_usec;
  344. /* Return 1 if result is negative. */
  345. return x->tv_sec < y->tv_sec;
  346. }
  347. bool fulltest(const unsigned char *hash, const unsigned char *target)
  348. {
  349. unsigned char hash_swap[32], target_swap[32];
  350. uint32_t *hash32 = (uint32_t *) hash_swap;
  351. uint32_t *target32 = (uint32_t *) target_swap;
  352. int i;
  353. bool rc = true;
  354. char *hash_str, *target_str;
  355. swap256(hash_swap, hash);
  356. swap256(target_swap, target);
  357. for (i = 0; i < 32/4; i++) {
  358. uint32_t h32tmp = swab32(hash32[i]);
  359. uint32_t t32tmp = target32[i];
  360. target32[i] = swab32(target32[i]); /* for printing */
  361. if (h32tmp > t32tmp) {
  362. rc = false;
  363. break;
  364. }
  365. if (h32tmp < t32tmp) {
  366. rc = true;
  367. break;
  368. }
  369. }
  370. if (opt_debug) {
  371. hash_str = bin2hex(hash_swap, 32);
  372. target_str = bin2hex(target_swap, 32);
  373. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  374. hash_str,
  375. target_str,
  376. rc ? "YES (hash < target)" :
  377. "no (false positive; hash > target)");
  378. free(hash_str);
  379. free(target_str);
  380. }
  381. return true; /* FIXME: return rc; */
  382. }
  383. struct thread_q *tq_new(void)
  384. {
  385. struct thread_q *tq;
  386. tq = calloc(1, sizeof(*tq));
  387. if (!tq)
  388. return NULL;
  389. INIT_LIST_HEAD(&tq->q);
  390. pthread_mutex_init(&tq->mutex, NULL);
  391. pthread_cond_init(&tq->cond, NULL);
  392. return tq;
  393. }
  394. void tq_free(struct thread_q *tq)
  395. {
  396. struct tq_ent *ent, *iter;
  397. if (!tq)
  398. return;
  399. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  400. list_del(&ent->q_node);
  401. free(ent);
  402. }
  403. pthread_cond_destroy(&tq->cond);
  404. pthread_mutex_destroy(&tq->mutex);
  405. memset(tq, 0, sizeof(*tq)); /* poison */
  406. free(tq);
  407. }
  408. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  409. {
  410. pthread_mutex_lock(&tq->mutex);
  411. tq->frozen = frozen;
  412. pthread_cond_signal(&tq->cond);
  413. pthread_mutex_unlock(&tq->mutex);
  414. }
  415. void tq_freeze(struct thread_q *tq)
  416. {
  417. tq_freezethaw(tq, true);
  418. }
  419. void tq_thaw(struct thread_q *tq)
  420. {
  421. tq_freezethaw(tq, false);
  422. }
  423. bool tq_push(struct thread_q *tq, void *data)
  424. {
  425. struct tq_ent *ent;
  426. bool rc = true;
  427. ent = calloc(1, sizeof(*ent));
  428. if (!ent)
  429. return false;
  430. ent->data = data;
  431. INIT_LIST_HEAD(&ent->q_node);
  432. pthread_mutex_lock(&tq->mutex);
  433. if (!tq->frozen) {
  434. list_add_tail(&ent->q_node, &tq->q);
  435. } else {
  436. free(ent);
  437. rc = false;
  438. }
  439. pthread_cond_signal(&tq->cond);
  440. pthread_mutex_unlock(&tq->mutex);
  441. return rc;
  442. }
  443. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  444. {
  445. struct tq_ent *ent;
  446. void *rval = NULL;
  447. int rc;
  448. pthread_mutex_lock(&tq->mutex);
  449. if (!list_empty(&tq->q))
  450. goto pop;
  451. if (abstime)
  452. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  453. else
  454. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  455. if (rc)
  456. goto out;
  457. if (list_empty(&tq->q))
  458. goto out;
  459. pop:
  460. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  461. rval = ent->data;
  462. list_del(&ent->q_node);
  463. free(ent);
  464. out:
  465. pthread_mutex_unlock(&tq->mutex);
  466. return rval;
  467. }