util.c 14 KB

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