util.c 14 KB

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