util.c 14 KB

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