util.c 15 KB

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