util.c 14 KB

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