util.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. /*
  2. * Copyright 2011-2012 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 3 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 <errno.h>
  21. #include <unistd.h>
  22. #include <sys/types.h>
  23. #ifndef WIN32
  24. # include <sys/socket.h>
  25. # include <netinet/in.h>
  26. # include <netinet/tcp.h>
  27. #else
  28. # include <winsock2.h>
  29. # include <mstcpip.h>
  30. #endif
  31. #include <netdb.h>
  32. #include "miner.h"
  33. #include "elist.h"
  34. #include "compat.h"
  35. #if JANSSON_MAJOR_VERSION >= 2
  36. #define JSON_LOADS(str, err_ptr) json_loads((str), 0, (err_ptr))
  37. #else
  38. #define JSON_LOADS(str, err_ptr) json_loads((str), (err_ptr))
  39. #endif
  40. bool successful_connect = false;
  41. struct timeval nettime;
  42. struct data_buffer {
  43. void *buf;
  44. size_t len;
  45. };
  46. struct upload_buffer {
  47. const void *buf;
  48. size_t len;
  49. };
  50. struct header_info {
  51. char *lp_path;
  52. int rolltime;
  53. char *reason;
  54. bool hadrolltime;
  55. bool canroll;
  56. bool hadexpire;
  57. };
  58. struct tq_ent {
  59. void *data;
  60. struct list_head q_node;
  61. };
  62. static void databuf_free(struct data_buffer *db)
  63. {
  64. if (!db)
  65. return;
  66. free(db->buf);
  67. memset(db, 0, sizeof(*db));
  68. }
  69. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  70. void *user_data)
  71. {
  72. struct data_buffer *db = user_data;
  73. size_t len = size * nmemb;
  74. size_t oldlen, newlen;
  75. void *newmem;
  76. static const unsigned char zero = 0;
  77. oldlen = db->len;
  78. newlen = oldlen + len;
  79. newmem = realloc(db->buf, newlen + 1);
  80. if (!newmem)
  81. return 0;
  82. db->buf = newmem;
  83. db->len = newlen;
  84. memcpy(db->buf + oldlen, ptr, len);
  85. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  86. return len;
  87. }
  88. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  89. void *user_data)
  90. {
  91. struct upload_buffer *ub = user_data;
  92. unsigned int len = size * nmemb;
  93. if (len > ub->len)
  94. len = ub->len;
  95. if (len) {
  96. memcpy(ptr, ub->buf, len);
  97. ub->buf += len;
  98. ub->len -= len;
  99. }
  100. return len;
  101. }
  102. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  103. {
  104. struct header_info *hi = user_data;
  105. size_t remlen, slen, ptrlen = size * nmemb;
  106. char *rem, *val = NULL, *key = NULL;
  107. void *tmp;
  108. val = calloc(1, ptrlen);
  109. key = calloc(1, ptrlen);
  110. if (!key || !val)
  111. goto out;
  112. tmp = memchr(ptr, ':', ptrlen);
  113. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  114. goto out;
  115. slen = tmp - ptr;
  116. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  117. goto out;
  118. memcpy(key, ptr, slen); /* store & nul term key */
  119. key[slen] = 0;
  120. rem = ptr + slen + 1; /* trim value's leading whitespace */
  121. remlen = ptrlen - slen - 1;
  122. while ((remlen > 0) && (isspace(*rem))) {
  123. remlen--;
  124. rem++;
  125. }
  126. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  127. val[remlen] = 0;
  128. while ((*val) && (isspace(val[strlen(val) - 1])))
  129. val[strlen(val) - 1] = 0;
  130. if (!*val) /* skip blank value */
  131. goto out;
  132. if (opt_protocol)
  133. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  134. if (!strcasecmp("X-Roll-Ntime", key)) {
  135. hi->hadrolltime = true;
  136. if (!strncasecmp("N", val, 1))
  137. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  138. else {
  139. hi->canroll = true;
  140. /* Check to see if expire= is supported and if not, set
  141. * the rolltime to the default scantime */
  142. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  143. sscanf(val + 7, "%d", &hi->rolltime);
  144. hi->hadexpire = true;
  145. } else
  146. hi->rolltime = opt_scantime;
  147. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  148. }
  149. }
  150. if (!strcasecmp("X-Long-Polling", key)) {
  151. hi->lp_path = val; /* steal memory reference */
  152. val = NULL;
  153. }
  154. if (!strcasecmp("X-Reject-Reason", key)) {
  155. hi->reason = val; /* steal memory reference */
  156. val = NULL;
  157. }
  158. out:
  159. free(key);
  160. free(val);
  161. return ptrlen;
  162. }
  163. #ifdef CURL_HAS_SOCKOPT
  164. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  165. curlsocktype __maybe_unused purpose)
  166. {
  167. int tcp_keepidle = 120;
  168. int tcp_keepintvl = 120;
  169. #ifndef WIN32
  170. int keepalive = 1;
  171. int tcp_keepcnt = 5;
  172. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  173. return 1;
  174. # ifdef __linux
  175. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  176. return 1;
  177. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  178. return 1;
  179. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  180. return 1;
  181. # endif /* __linux */
  182. # ifdef __APPLE_CC__
  183. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  184. return 1;
  185. # endif /* __APPLE_CC__ */
  186. #else /* WIN32 */
  187. struct tcp_keepalive vals;
  188. vals.onoff = 1;
  189. vals.keepalivetime = tcp_keepidle * 1000;
  190. vals.keepaliveinterval = tcp_keepintvl * 1000;
  191. DWORD outputBytes;
  192. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  193. return 1;
  194. #endif /* WIN32 */
  195. return 0;
  196. }
  197. #endif
  198. static void last_nettime(struct timeval *last)
  199. {
  200. rd_lock(&netacc_lock);
  201. last->tv_sec = nettime.tv_sec;
  202. last->tv_usec = nettime.tv_usec;
  203. rd_unlock(&netacc_lock);
  204. }
  205. static void set_nettime(void)
  206. {
  207. wr_lock(&netacc_lock);
  208. gettimeofday(&nettime, NULL);
  209. wr_unlock(&netacc_lock);
  210. }
  211. json_t *json_rpc_call(CURL *curl, const char *url,
  212. const char *userpass, const char *rpc_req,
  213. bool probe, bool longpoll, int *rolltime,
  214. struct pool *pool, bool share)
  215. {
  216. long timeout = longpoll ? (60 * 60) : 60;
  217. struct data_buffer all_data = {NULL, 0};
  218. struct header_info hi = {NULL, 0, NULL, false, false, false};
  219. char len_hdr[64], user_agent_hdr[128];
  220. char curl_err_str[CURL_ERROR_SIZE];
  221. struct curl_slist *headers = NULL;
  222. struct upload_buffer upload_data;
  223. json_t *val, *err_val, *res_val;
  224. bool probing = false;
  225. json_error_t err;
  226. int rc;
  227. memset(&err, 0, sizeof(err));
  228. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  229. if (probe)
  230. probing = !pool->probed;
  231. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  232. #if 0 /* Disable curl debugging since it spews to stderr */
  233. if (opt_protocol)
  234. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  235. #endif
  236. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  237. curl_easy_setopt(curl, CURLOPT_URL, url);
  238. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  239. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  240. /* Shares are staggered already and delays in submission can be costly
  241. * so do not delay them */
  242. if (!opt_delaynet || share)
  243. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  244. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  245. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  246. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  247. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  248. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  249. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  250. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  251. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  252. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  253. if (pool->rpc_proxy) {
  254. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  255. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  256. } else if (opt_socks_proxy) {
  257. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  258. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  259. }
  260. if (userpass) {
  261. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  262. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  263. }
  264. #ifdef CURL_HAS_SOCKOPT
  265. if (longpoll)
  266. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  267. #endif
  268. curl_easy_setopt(curl, CURLOPT_POST, 1);
  269. if (opt_protocol)
  270. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  271. upload_data.buf = rpc_req;
  272. upload_data.len = strlen(rpc_req);
  273. sprintf(len_hdr, "Content-Length: %lu",
  274. (unsigned long) upload_data.len);
  275. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  276. headers = curl_slist_append(headers,
  277. "Content-type: application/json");
  278. headers = curl_slist_append(headers,
  279. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  280. if (likely(global_hashrate)) {
  281. char ghashrate[255];
  282. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  283. headers = curl_slist_append(headers, ghashrate);
  284. }
  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. if (opt_delaynet) {
  290. /* Don't delay share submission, but still track the nettime */
  291. if (!share) {
  292. long long now_msecs, last_msecs;
  293. struct timeval now, last;
  294. gettimeofday(&now, NULL);
  295. last_nettime(&last);
  296. now_msecs = (long long)now.tv_sec * 1000;
  297. now_msecs += now.tv_usec / 1000;
  298. last_msecs = (long long)last.tv_sec * 1000;
  299. last_msecs += last.tv_usec / 1000;
  300. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  301. struct timespec rgtp;
  302. rgtp.tv_sec = 0;
  303. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  304. nanosleep(&rgtp, NULL);
  305. }
  306. }
  307. set_nettime();
  308. }
  309. rc = curl_easy_perform(curl);
  310. if (rc) {
  311. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  312. goto err_out;
  313. }
  314. if (!all_data.buf) {
  315. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  316. goto err_out;
  317. }
  318. if (probing) {
  319. pool->probed = true;
  320. /* If X-Long-Polling was found, activate long polling */
  321. if (hi.lp_path) {
  322. if (pool->hdr_path != NULL)
  323. free(pool->hdr_path);
  324. pool->hdr_path = hi.lp_path;
  325. } else
  326. pool->hdr_path = NULL;
  327. } else if (hi.lp_path) {
  328. free(hi.lp_path);
  329. hi.lp_path = NULL;
  330. }
  331. *rolltime = hi.rolltime;
  332. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  333. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  334. pool->cgminer_pool_stats.canroll = hi.canroll;
  335. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  336. val = JSON_LOADS(all_data.buf, &err);
  337. if (!val) {
  338. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  339. if (opt_protocol)
  340. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  341. goto err_out;
  342. }
  343. if (opt_protocol) {
  344. char *s = json_dumps(val, JSON_INDENT(3));
  345. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  346. free(s);
  347. }
  348. /* JSON-RPC valid response returns a non-null 'result',
  349. * and a null 'error'.
  350. */
  351. res_val = json_object_get(val, "result");
  352. err_val = json_object_get(val, "error");
  353. if (!res_val || json_is_null(res_val) ||
  354. (err_val && !json_is_null(err_val))) {
  355. char *s;
  356. if (err_val)
  357. s = json_dumps(err_val, JSON_INDENT(3));
  358. else
  359. s = strdup("(unknown reason)");
  360. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  361. free(s);
  362. goto err_out;
  363. }
  364. if (hi.reason) {
  365. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  366. free(hi.reason);
  367. hi.reason = NULL;
  368. }
  369. successful_connect = true;
  370. databuf_free(&all_data);
  371. curl_slist_free_all(headers);
  372. curl_easy_reset(curl);
  373. return val;
  374. err_out:
  375. databuf_free(&all_data);
  376. curl_slist_free_all(headers);
  377. curl_easy_reset(curl);
  378. if (!successful_connect)
  379. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  380. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  381. return NULL;
  382. }
  383. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  384. static struct {
  385. const char *name;
  386. curl_proxytype proxytype;
  387. } proxynames[] = {
  388. { "http:", CURLPROXY_HTTP },
  389. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  390. { "http0:", CURLPROXY_HTTP_1_0 },
  391. #endif
  392. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  393. { "socks4:", CURLPROXY_SOCKS4 },
  394. #endif
  395. { "socks5:", CURLPROXY_SOCKS5 },
  396. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  397. { "socks4a:", CURLPROXY_SOCKS4A },
  398. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  399. #endif
  400. { NULL, 0 }
  401. };
  402. #endif
  403. const char *proxytype(curl_proxytype proxytype)
  404. {
  405. int i;
  406. for (i = 0; proxynames[i].name; i++)
  407. if (proxynames[i].proxytype == proxytype)
  408. return proxynames[i].name;
  409. return "invalid";
  410. }
  411. char *get_proxy(char *url, struct pool *pool)
  412. {
  413. pool->rpc_proxy = NULL;
  414. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  415. char *split;
  416. int plen, len, i;
  417. for (i = 0; proxynames[i].name; i++) {
  418. plen = strlen(proxynames[i].name);
  419. if (strncmp(url, proxynames[i].name, plen) == 0) {
  420. if (!(split = strchr(url, '|')))
  421. return url;
  422. *split = '\0';
  423. len = split - url;
  424. pool->rpc_proxy = malloc(1 + len - plen);
  425. if (!(pool->rpc_proxy))
  426. quit(1, "Failed to malloc rpc_proxy");
  427. strcpy(pool->rpc_proxy, url + plen);
  428. pool->rpc_proxytype = proxynames[i].proxytype;
  429. url = split + 1;
  430. break;
  431. }
  432. }
  433. #endif
  434. return url;
  435. }
  436. char *bin2hex(const unsigned char *p, size_t len)
  437. {
  438. char *s = malloc((len * 2) + 1);
  439. unsigned int i;
  440. if (!s)
  441. return NULL;
  442. for (i = 0; i < len; i++)
  443. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  444. return s;
  445. }
  446. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  447. {
  448. while (*hexstr && len) {
  449. char hex_byte[3];
  450. unsigned int v;
  451. if (!hexstr[1]) {
  452. applog(LOG_ERR, "hex2bin str truncated");
  453. return false;
  454. }
  455. hex_byte[0] = hexstr[0];
  456. hex_byte[1] = hexstr[1];
  457. hex_byte[2] = 0;
  458. if (sscanf(hex_byte, "%x", &v) != 1) {
  459. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  460. return false;
  461. }
  462. *p = (unsigned char) v;
  463. p++;
  464. hexstr += 2;
  465. len--;
  466. }
  467. return (len == 0 && *hexstr == 0) ? true : false;
  468. }
  469. bool fulltest(const unsigned char *hash, const unsigned char *target)
  470. {
  471. unsigned char hash_swap[32], target_swap[32];
  472. uint32_t *hash32 = (uint32_t *) hash_swap;
  473. uint32_t *target32 = (uint32_t *) target_swap;
  474. char *hash_str, *target_str;
  475. bool rc = true;
  476. int i;
  477. swap256(hash_swap, hash);
  478. swap256(target_swap, target);
  479. for (i = 0; i < 32/4; i++) {
  480. uint32_t h32tmp = swab32(hash32[i]);
  481. uint32_t t32tmp = target32[i];
  482. target32[i] = swab32(target32[i]); /* for printing */
  483. if (h32tmp > t32tmp) {
  484. rc = false;
  485. break;
  486. }
  487. if (h32tmp < t32tmp) {
  488. rc = true;
  489. break;
  490. }
  491. }
  492. if (opt_debug) {
  493. hash_str = bin2hex(hash_swap, 32);
  494. target_str = bin2hex(target_swap, 32);
  495. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  496. hash_str,
  497. target_str,
  498. rc ? "YES (hash < target)" :
  499. "no (false positive; hash > target)");
  500. free(hash_str);
  501. free(target_str);
  502. }
  503. return rc;
  504. }
  505. struct thread_q *tq_new(void)
  506. {
  507. struct thread_q *tq;
  508. tq = calloc(1, sizeof(*tq));
  509. if (!tq)
  510. return NULL;
  511. INIT_LIST_HEAD(&tq->q);
  512. pthread_mutex_init(&tq->mutex, NULL);
  513. pthread_cond_init(&tq->cond, NULL);
  514. return tq;
  515. }
  516. void tq_free(struct thread_q *tq)
  517. {
  518. struct tq_ent *ent, *iter;
  519. if (!tq)
  520. return;
  521. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  522. list_del(&ent->q_node);
  523. free(ent);
  524. }
  525. pthread_cond_destroy(&tq->cond);
  526. pthread_mutex_destroy(&tq->mutex);
  527. memset(tq, 0, sizeof(*tq)); /* poison */
  528. free(tq);
  529. }
  530. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  531. {
  532. mutex_lock(&tq->mutex);
  533. tq->frozen = frozen;
  534. pthread_cond_signal(&tq->cond);
  535. mutex_unlock(&tq->mutex);
  536. }
  537. void tq_freeze(struct thread_q *tq)
  538. {
  539. tq_freezethaw(tq, true);
  540. }
  541. void tq_thaw(struct thread_q *tq)
  542. {
  543. tq_freezethaw(tq, false);
  544. }
  545. bool tq_push(struct thread_q *tq, void *data)
  546. {
  547. struct tq_ent *ent;
  548. bool rc = true;
  549. ent = calloc(1, sizeof(*ent));
  550. if (!ent)
  551. return false;
  552. ent->data = data;
  553. INIT_LIST_HEAD(&ent->q_node);
  554. mutex_lock(&tq->mutex);
  555. if (!tq->frozen) {
  556. list_add_tail(&ent->q_node, &tq->q);
  557. } else {
  558. free(ent);
  559. rc = false;
  560. }
  561. pthread_cond_signal(&tq->cond);
  562. mutex_unlock(&tq->mutex);
  563. return rc;
  564. }
  565. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  566. {
  567. struct tq_ent *ent;
  568. void *rval = NULL;
  569. int rc;
  570. mutex_lock(&tq->mutex);
  571. if (!list_empty(&tq->q))
  572. goto pop;
  573. if (abstime)
  574. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  575. else
  576. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  577. if (rc)
  578. goto out;
  579. if (list_empty(&tq->q))
  580. goto out;
  581. pop:
  582. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  583. rval = ent->data;
  584. list_del(&ent->q_node);
  585. free(ent);
  586. out:
  587. mutex_unlock(&tq->mutex);
  588. return rval;
  589. }
  590. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  591. {
  592. return pthread_create(&thr->pth, attr, start, arg);
  593. }
  594. void thr_info_freeze(struct thr_info *thr)
  595. {
  596. struct tq_ent *ent, *iter;
  597. struct thread_q *tq;
  598. if (!thr)
  599. return;
  600. tq = thr->q;
  601. if (!tq)
  602. return;
  603. mutex_lock(&tq->mutex);
  604. tq->frozen = true;
  605. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  606. list_del(&ent->q_node);
  607. free(ent);
  608. }
  609. mutex_unlock(&tq->mutex);
  610. }
  611. void thr_info_cancel(struct thr_info *thr)
  612. {
  613. if (!thr)
  614. return;
  615. if (PTH(thr) != 0L) {
  616. pthread_cancel(thr->pth);
  617. PTH(thr) = 0L;
  618. }
  619. }
  620. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  621. * on SMP machines */
  622. void nmsleep(unsigned int msecs)
  623. {
  624. struct timespec twait, tleft;
  625. int ret;
  626. ldiv_t d;
  627. d = ldiv(msecs, 1000);
  628. tleft.tv_sec = d.quot;
  629. tleft.tv_nsec = d.rem * 1000000;
  630. do {
  631. twait.tv_sec = tleft.tv_sec;
  632. twait.tv_nsec = tleft.tv_nsec;
  633. ret = nanosleep(&twait, &tleft);
  634. } while (ret == -1 && errno == EINTR);
  635. }
  636. /* Returns the microseconds difference between end and start times as a double */
  637. double us_tdiff(struct timeval *end, struct timeval *start)
  638. {
  639. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  640. }
  641. /* Returns the seconds difference between end and start times as a double */
  642. double tdiff(struct timeval *end, struct timeval *start)
  643. {
  644. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  645. }
  646. bool extract_sockaddr(struct pool *pool, char *url)
  647. {
  648. char *url_begin, *url_end, *port_start;
  649. char *url_address, *port;
  650. struct addrinfo hints, *res;
  651. size_t url_len, port_len = 0;
  652. url_begin = strstr(url, "//");
  653. if (!url_begin)
  654. url_begin = url;
  655. else
  656. url_begin += 2;
  657. url_end = strstr(url_begin, ":");
  658. if (url_end) {
  659. url_len = url_end - url_begin;
  660. port_len = strlen(url_begin) - url_len - 1;
  661. if (port_len < 1)
  662. return false;
  663. port_start = url_end + 1;
  664. } else
  665. url_len = strlen(url_begin);
  666. if (url_len < 1)
  667. return false;
  668. url_address = alloca(url_len + 1);
  669. sprintf(url_address, "%.*s", url_len, url_begin);
  670. if (port_len) {
  671. port = alloca(port_len + 1);
  672. sprintf(port, "%.*s", port_len, port_start);
  673. } else {
  674. port = alloca(4);
  675. strcpy(port, "80");
  676. }
  677. memset(&hints, 0, sizeof(struct addrinfo));
  678. hints.ai_family = AF_UNSPEC;
  679. hints.ai_socktype = SOCK_STREAM;
  680. hints.ai_protocol = IPPROTO_TCP;
  681. if (getaddrinfo(url_address, port, &hints, &res)) {
  682. applog(LOG_DEBUG, "Failed to extract sock addr");
  683. return false;
  684. }
  685. pool->server = (struct sockaddr_in *)res->ai_addr;
  686. return true;
  687. }
  688. static bool sock_send(int sock, char *s, ssize_t len)
  689. {
  690. size_t sent = 0;
  691. while (len > 0 ) {
  692. sent = send(sock, s + sent, len, 0);
  693. if (SOCKETFAIL(sent))
  694. return false;
  695. len -= sent;
  696. }
  697. fsync(sock);
  698. return true;
  699. }
  700. #define RECVSIZE 8192
  701. bool initiate_stratum(struct pool *pool)
  702. {
  703. json_t *val, *res_val, *err_val, *notify_val;
  704. char *s, *buf, *sret = NULL;
  705. struct timeval timeout;
  706. json_error_t err;
  707. bool ret = false;
  708. ssize_t len;
  709. fd_set rd;
  710. s = alloca(RECVSIZE);
  711. sprintf(s, "{\"id\": 0, \"method\": \"mining.subscribe\", \"params\": []}\n");
  712. pool->sock = socket(AF_INET, SOCK_STREAM, 0);
  713. if (pool->sock == INVSOCK)
  714. quit(1, "Failed to create pool socket in initiate_stratum");
  715. if (SOCKETFAIL(connect(pool->sock, (struct sockaddr *)pool->server, sizeof(struct sockaddr)))) {
  716. applog(LOG_DEBUG, "Failed to connect socket to pool");
  717. goto out;
  718. }
  719. if (!sock_send(pool->sock, s, strlen(s))) {
  720. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  721. goto out;
  722. }
  723. /* Use select to timeout instead of waiting forever for a response */
  724. FD_ZERO(&rd);
  725. FD_SET(pool->sock, &rd);
  726. timeout.tv_sec = 60;
  727. if (select(pool->sock + 1, &rd, NULL, NULL, &timeout) < 1) {
  728. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  729. goto out;
  730. }
  731. if (SOCKETFAIL(recv(pool->sock, s, RECVSIZE, MSG_PEEK | MSG_DONTWAIT))) {
  732. applog(LOG_DEBUG, "Failed to recv sock in initiate_stratum");
  733. goto out;
  734. }
  735. sret = strtok(s, "\n");
  736. if (!sret) {
  737. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in initiate_stratum");
  738. goto out;
  739. }
  740. /* We know how much data is in the buffer so this read should not fail */
  741. len = strlen(sret);
  742. read(pool->sock, s, len);
  743. val = JSON_LOADS(s, &err);
  744. if (!val) {
  745. applog(LOG_DEBUG, "JSON decode failed(%d): %s", err.line, err.text);
  746. goto out;
  747. }
  748. res_val = json_object_get(val, "result");
  749. err_val = json_object_get(val, "error");
  750. if (!res_val || json_is_null(res_val) ||
  751. (err_val && !json_is_null(err_val))) {
  752. char *ss;
  753. if (err_val)
  754. ss = json_dumps(err_val, JSON_INDENT(3));
  755. else
  756. ss = strdup("(unknown reason)");
  757. applog(LOG_INFO, "JSON-RPC call failed: %s", ss);
  758. free(ss);
  759. goto out;
  760. }
  761. notify_val = json_array_get(res_val, 0);
  762. if (!notify_val || json_is_null(notify_val)) {
  763. applog(LOG_WARNING, "Failed to parse notify_val in initiate_stratum");
  764. goto out;
  765. }
  766. buf = (char *)json_string_value(json_array_get(notify_val, 0));
  767. if (!buf || strcasecmp(buf, "mining.notify")) {
  768. applog(LOG_WARNING, "Failed to get mining notify in initiate_stratum");
  769. goto out;
  770. }
  771. pool->subscription = (char *)json_string_value(json_array_get(notify_val, 1));
  772. if (!pool->subscription) {
  773. applog(LOG_WARNING, "Failed to get a subscription in initiate_stratum");
  774. goto out;
  775. }
  776. pool->nonce1 = (char *)json_string_value(json_array_get(res_val, 1));
  777. if (!pool->nonce1) {
  778. applog(LOG_WARNING, "Failed to get nonce1 in initiate_stratum");
  779. goto out;
  780. }
  781. pool->nonce2 = json_integer_value(json_array_get(res_val, 2));
  782. if (!pool->nonce2) {
  783. applog(LOG_WARNING, "Failed to get nonce2 in initiate_stratum");
  784. goto out;
  785. }
  786. ret = true;
  787. out:
  788. if (!ret) {
  789. CLOSESOCKET(pool->sock);
  790. if (val)
  791. json_decref(val);
  792. } else if (opt_protocol)
  793. applog(LOG_DEBUG, "Pool %d confirmed mining.notify with subscription %s extranonce1 %s extranonce2 %d",
  794. pool->pool_no, pool->subscription, pool->nonce1, pool->nonce2);
  795. return ret;
  796. }