util.c 13 KB

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