util.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. * Copyright 2012 Giel van Schijndel
  5. * Copyright 2012 Gavin Andresen
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #define _GNU_SOURCE
  13. #include "config.h"
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <ctype.h>
  17. #include <stdarg.h>
  18. #include <string.h>
  19. #include <pthread.h>
  20. #include <jansson.h>
  21. #include <curl/curl.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include <unistd.h>
  25. #include <sys/types.h>
  26. #ifdef HAVE_SYS_PRCTL_H
  27. # include <sys/prctl.h>
  28. #endif
  29. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  30. # include <pthread_np.h>
  31. #endif
  32. #ifndef WIN32
  33. # include <sys/socket.h>
  34. # include <netinet/in.h>
  35. # include <netinet/tcp.h>
  36. # include <netdb.h>
  37. #else
  38. # include <winsock2.h>
  39. # include <mstcpip.h>
  40. # include <ws2tcpip.h>
  41. #endif
  42. #include "miner.h"
  43. #include "elist.h"
  44. #include "compat.h"
  45. #include "util.h"
  46. bool successful_connect = false;
  47. struct timeval nettime;
  48. struct data_buffer {
  49. void *buf;
  50. size_t len;
  51. curl_socket_t *idlemarker;
  52. };
  53. struct upload_buffer {
  54. const void *buf;
  55. size_t len;
  56. };
  57. struct header_info {
  58. char *lp_path;
  59. int rolltime;
  60. char *reason;
  61. char *stratum_url;
  62. bool hadrolltime;
  63. bool canroll;
  64. bool hadexpire;
  65. };
  66. struct tq_ent {
  67. void *data;
  68. struct list_head q_node;
  69. };
  70. static void databuf_free(struct data_buffer *db)
  71. {
  72. if (!db)
  73. return;
  74. free(db->buf);
  75. memset(db, 0, sizeof(*db));
  76. }
  77. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  78. void *user_data)
  79. {
  80. struct data_buffer *db = user_data;
  81. size_t len = size * nmemb;
  82. size_t oldlen, newlen;
  83. void *newmem;
  84. static const unsigned char zero = 0;
  85. if (db->idlemarker) {
  86. const unsigned char *cptr = ptr;
  87. for (size_t i = 0; i < len; ++i)
  88. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  89. *db->idlemarker = CURL_SOCKET_BAD;
  90. db->idlemarker = NULL;
  91. break;
  92. }
  93. }
  94. oldlen = db->len;
  95. newlen = oldlen + len;
  96. newmem = realloc(db->buf, newlen + 1);
  97. if (!newmem)
  98. return 0;
  99. db->buf = newmem;
  100. db->len = newlen;
  101. memcpy(db->buf + oldlen, ptr, len);
  102. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  103. return len;
  104. }
  105. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  106. void *user_data)
  107. {
  108. struct upload_buffer *ub = user_data;
  109. unsigned int len = size * nmemb;
  110. if (len > ub->len)
  111. len = ub->len;
  112. if (len) {
  113. memcpy(ptr, ub->buf, len);
  114. ub->buf += len;
  115. ub->len -= len;
  116. }
  117. return len;
  118. }
  119. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  120. {
  121. struct header_info *hi = user_data;
  122. size_t remlen, slen, ptrlen = size * nmemb;
  123. char *rem, *val = NULL, *key = NULL;
  124. void *tmp;
  125. val = calloc(1, ptrlen);
  126. key = calloc(1, ptrlen);
  127. if (!key || !val)
  128. goto out;
  129. tmp = memchr(ptr, ':', ptrlen);
  130. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  131. goto out;
  132. slen = tmp - ptr;
  133. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  134. goto out;
  135. memcpy(key, ptr, slen); /* store & nul term key */
  136. key[slen] = 0;
  137. rem = ptr + slen + 1; /* trim value's leading whitespace */
  138. remlen = ptrlen - slen - 1;
  139. while ((remlen > 0) && (isspace(*rem))) {
  140. remlen--;
  141. rem++;
  142. }
  143. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  144. val[remlen] = 0;
  145. while ((*val) && (isspace(val[strlen(val) - 1])))
  146. val[strlen(val) - 1] = 0;
  147. if (!*val) /* skip blank value */
  148. goto out;
  149. if (opt_protocol)
  150. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  151. if (!strcasecmp("X-Roll-Ntime", key)) {
  152. hi->hadrolltime = true;
  153. if (!strncasecmp("N", val, 1))
  154. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  155. else {
  156. hi->canroll = true;
  157. /* Check to see if expire= is supported and if not, set
  158. * the rolltime to the default scantime */
  159. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  160. sscanf(val + 7, "%d", &hi->rolltime);
  161. hi->hadexpire = true;
  162. } else
  163. hi->rolltime = opt_scantime;
  164. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  165. }
  166. }
  167. if (!strcasecmp("X-Long-Polling", key)) {
  168. hi->lp_path = val; /* steal memory reference */
  169. val = NULL;
  170. }
  171. if (!strcasecmp("X-Reject-Reason", key)) {
  172. hi->reason = val; /* steal memory reference */
  173. val = NULL;
  174. }
  175. if (!strcasecmp("X-Stratum", key)) {
  176. hi->stratum_url = val;
  177. val = NULL;
  178. }
  179. out:
  180. free(key);
  181. free(val);
  182. return ptrlen;
  183. }
  184. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  185. curlsocktype __maybe_unused purpose)
  186. {
  187. int tcp_keepidle = 120;
  188. int tcp_keepintvl = 120;
  189. #ifndef WIN32
  190. int keepalive = 1;
  191. int tcp_keepcnt = 5;
  192. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  193. return 1;
  194. # ifdef __linux
  195. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  196. return 1;
  197. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  198. return 1;
  199. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  200. return 1;
  201. # endif /* __linux */
  202. # ifdef __APPLE_CC__
  203. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  204. return 1;
  205. # endif /* __APPLE_CC__ */
  206. #else /* WIN32 */
  207. struct tcp_keepalive vals;
  208. vals.onoff = 1;
  209. vals.keepalivetime = tcp_keepidle * 1000;
  210. vals.keepaliveinterval = tcp_keepintvl * 1000;
  211. DWORD outputBytes;
  212. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  213. return 1;
  214. #endif /* WIN32 */
  215. return 0;
  216. }
  217. static void last_nettime(struct timeval *last)
  218. {
  219. rd_lock(&netacc_lock);
  220. last->tv_sec = nettime.tv_sec;
  221. last->tv_usec = nettime.tv_usec;
  222. rd_unlock(&netacc_lock);
  223. }
  224. static void set_nettime(void)
  225. {
  226. wr_lock(&netacc_lock);
  227. gettimeofday(&nettime, NULL);
  228. wr_unlock(&netacc_lock);
  229. }
  230. json_t *json_rpc_call(CURL *curl, const char *url,
  231. const char *userpass, const char *rpc_req,
  232. bool probe, bool longpoll, int *rolltime,
  233. struct pool *pool, bool share)
  234. {
  235. long timeout = longpoll ? (60 * 60) : 60;
  236. struct data_buffer all_data = {NULL, 0, NULL};
  237. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  238. char len_hdr[64], user_agent_hdr[128];
  239. char curl_err_str[CURL_ERROR_SIZE];
  240. struct curl_slist *headers = NULL;
  241. struct upload_buffer upload_data;
  242. json_t *val, *err_val, *res_val;
  243. bool probing = false;
  244. json_error_t err;
  245. int rc;
  246. memset(&err, 0, sizeof(err));
  247. if (longpoll)
  248. all_data.idlemarker = &pool->lp_socket;
  249. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  250. if (probe)
  251. probing = !pool->probed;
  252. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  253. #if 0 /* Disable curl debugging since it spews to stderr */
  254. if (opt_protocol)
  255. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  256. #endif
  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. /* Shares are staggered already and delays in submission can be costly
  262. * so do not delay them */
  263. if (!opt_delaynet || share)
  264. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  265. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  266. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  267. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  268. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  269. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  270. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  271. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  272. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  273. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  274. if (pool->rpc_proxy) {
  275. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  276. } else if (opt_socks_proxy) {
  277. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  278. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  279. }
  280. if (userpass) {
  281. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  282. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  283. }
  284. if (longpoll)
  285. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  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,
  297. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  298. if (longpoll)
  299. headers = curl_slist_append(headers,
  300. "X-Minimum-Wait: 0");
  301. if (likely(global_hashrate)) {
  302. char ghashrate[255];
  303. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  304. headers = curl_slist_append(headers, ghashrate);
  305. }
  306. headers = curl_slist_append(headers, len_hdr);
  307. headers = curl_slist_append(headers, user_agent_hdr);
  308. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  309. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  310. if (opt_delaynet) {
  311. /* Don't delay share submission, but still track the nettime */
  312. if (!share) {
  313. long long now_msecs, last_msecs;
  314. struct timeval now, last;
  315. gettimeofday(&now, NULL);
  316. last_nettime(&last);
  317. now_msecs = (long long)now.tv_sec * 1000;
  318. now_msecs += now.tv_usec / 1000;
  319. last_msecs = (long long)last.tv_sec * 1000;
  320. last_msecs += last.tv_usec / 1000;
  321. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  322. struct timespec rgtp;
  323. rgtp.tv_sec = 0;
  324. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  325. nanosleep(&rgtp, NULL);
  326. }
  327. }
  328. set_nettime();
  329. }
  330. rc = curl_easy_perform(curl);
  331. if (rc) {
  332. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  333. goto err_out;
  334. }
  335. if (!all_data.buf) {
  336. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  337. goto err_out;
  338. }
  339. if (probing) {
  340. pool->probed = true;
  341. /* If X-Long-Polling was found, activate long polling */
  342. if (hi.lp_path) {
  343. if (pool->hdr_path != NULL)
  344. free(pool->hdr_path);
  345. pool->hdr_path = hi.lp_path;
  346. } else
  347. pool->hdr_path = NULL;
  348. if (hi.stratum_url) {
  349. pool->stratum_url = hi.stratum_url;
  350. hi.stratum_url = NULL;
  351. }
  352. } else {
  353. if (hi.lp_path) {
  354. free(hi.lp_path);
  355. hi.lp_path = NULL;
  356. }
  357. if (hi.stratum_url) {
  358. free(hi.stratum_url);
  359. hi.stratum_url = NULL;
  360. }
  361. }
  362. *rolltime = hi.rolltime;
  363. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  364. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  365. pool->cgminer_pool_stats.canroll = hi.canroll;
  366. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  367. val = JSON_LOADS(all_data.buf, &err);
  368. if (!val) {
  369. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  370. if (opt_protocol)
  371. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  372. goto err_out;
  373. }
  374. if (opt_protocol) {
  375. char *s = json_dumps(val, JSON_INDENT(3));
  376. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  377. free(s);
  378. }
  379. /* JSON-RPC valid response returns a non-null 'result',
  380. * and a null 'error'.
  381. */
  382. res_val = json_object_get(val, "result");
  383. err_val = json_object_get(val, "error");
  384. if (!res_val ||
  385. (err_val && !json_is_null(err_val))) {
  386. char *s;
  387. if (err_val)
  388. s = json_dumps(err_val, JSON_INDENT(3));
  389. else
  390. s = strdup("(unknown reason)");
  391. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  392. free(s);
  393. goto err_out;
  394. }
  395. if (hi.reason) {
  396. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  397. free(hi.reason);
  398. hi.reason = NULL;
  399. }
  400. successful_connect = true;
  401. databuf_free(&all_data);
  402. curl_slist_free_all(headers);
  403. curl_easy_reset(curl);
  404. return val;
  405. err_out:
  406. databuf_free(&all_data);
  407. curl_slist_free_all(headers);
  408. curl_easy_reset(curl);
  409. if (!successful_connect)
  410. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  411. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  412. return NULL;
  413. }
  414. bool our_curl_supports_proxy_uris()
  415. {
  416. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  417. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  418. }
  419. /* Returns a malloced array string of a binary value of arbitrary length. The
  420. * array is rounded up to a 4 byte size to appease architectures that need
  421. * aligned array sizes */
  422. char *bin2hex(const unsigned char *p, size_t len)
  423. {
  424. unsigned int i;
  425. ssize_t slen;
  426. char *s;
  427. slen = len * 2 + 1;
  428. if (slen % 4)
  429. slen += 4 - (slen % 4);
  430. s = calloc(slen, 1);
  431. if (unlikely(!s))
  432. quit(1, "Failed to calloc in bin2hex");
  433. for (i = 0; i < len; i++)
  434. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  435. return s;
  436. }
  437. /* Does the reverse of bin2hex but does not allocate any ram */
  438. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  439. {
  440. bool ret = false;
  441. while (*hexstr && len) {
  442. char hex_byte[4];
  443. unsigned int v;
  444. if (unlikely(!hexstr[1])) {
  445. applog(LOG_ERR, "hex2bin str truncated");
  446. return ret;
  447. }
  448. memset(hex_byte, 0, 4);
  449. hex_byte[0] = hexstr[0];
  450. hex_byte[1] = hexstr[1];
  451. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  452. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  453. return ret;
  454. }
  455. *p = (unsigned char) v;
  456. p++;
  457. hexstr += 2;
  458. len--;
  459. }
  460. if (likely(len == 0 && *hexstr == 0))
  461. ret = true;
  462. return ret;
  463. }
  464. bool fulltest(const unsigned char *hash, const unsigned char *target)
  465. {
  466. unsigned char hash_swap[32], target_swap[32];
  467. uint32_t *hash32 = (uint32_t *) hash_swap;
  468. uint32_t *target32 = (uint32_t *) target_swap;
  469. char *hash_str, *target_str;
  470. bool rc = true;
  471. int i;
  472. swap256(hash_swap, hash);
  473. swap256(target_swap, target);
  474. for (i = 0; i < 32/4; i++) {
  475. uint32_t h32tmp = swab32(hash32[i]);
  476. uint32_t t32tmp = target32[i];
  477. target32[i] = swab32(target32[i]); /* for printing */
  478. if (h32tmp > t32tmp) {
  479. rc = false;
  480. break;
  481. }
  482. if (h32tmp < t32tmp) {
  483. rc = true;
  484. break;
  485. }
  486. }
  487. if (opt_debug) {
  488. hash_str = bin2hex(hash_swap, 32);
  489. target_str = bin2hex(target_swap, 32);
  490. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  491. hash_str,
  492. target_str,
  493. rc ? "YES (hash < target)" :
  494. "no (false positive; hash > target)");
  495. free(hash_str);
  496. free(target_str);
  497. }
  498. return rc;
  499. }
  500. struct thread_q *tq_new(void)
  501. {
  502. struct thread_q *tq;
  503. tq = calloc(1, sizeof(*tq));
  504. if (!tq)
  505. return NULL;
  506. INIT_LIST_HEAD(&tq->q);
  507. pthread_mutex_init(&tq->mutex, NULL);
  508. pthread_cond_init(&tq->cond, NULL);
  509. return tq;
  510. }
  511. void tq_free(struct thread_q *tq)
  512. {
  513. struct tq_ent *ent, *iter;
  514. if (!tq)
  515. return;
  516. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  517. list_del(&ent->q_node);
  518. free(ent);
  519. }
  520. pthread_cond_destroy(&tq->cond);
  521. pthread_mutex_destroy(&tq->mutex);
  522. memset(tq, 0, sizeof(*tq)); /* poison */
  523. free(tq);
  524. }
  525. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  526. {
  527. mutex_lock(&tq->mutex);
  528. tq->frozen = frozen;
  529. pthread_cond_signal(&tq->cond);
  530. mutex_unlock(&tq->mutex);
  531. }
  532. void tq_freeze(struct thread_q *tq)
  533. {
  534. tq_freezethaw(tq, true);
  535. }
  536. void tq_thaw(struct thread_q *tq)
  537. {
  538. tq_freezethaw(tq, false);
  539. }
  540. bool tq_push(struct thread_q *tq, void *data)
  541. {
  542. struct tq_ent *ent;
  543. bool rc = true;
  544. ent = calloc(1, sizeof(*ent));
  545. if (!ent)
  546. return false;
  547. ent->data = data;
  548. INIT_LIST_HEAD(&ent->q_node);
  549. mutex_lock(&tq->mutex);
  550. if (!tq->frozen) {
  551. list_add_tail(&ent->q_node, &tq->q);
  552. } else {
  553. free(ent);
  554. rc = false;
  555. }
  556. pthread_cond_signal(&tq->cond);
  557. mutex_unlock(&tq->mutex);
  558. return rc;
  559. }
  560. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  561. {
  562. struct tq_ent *ent;
  563. void *rval = NULL;
  564. int rc;
  565. mutex_lock(&tq->mutex);
  566. if (!list_empty(&tq->q))
  567. goto pop;
  568. if (abstime)
  569. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  570. else
  571. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  572. if (rc)
  573. goto out;
  574. if (list_empty(&tq->q))
  575. goto out;
  576. pop:
  577. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  578. rval = ent->data;
  579. list_del(&ent->q_node);
  580. free(ent);
  581. out:
  582. mutex_unlock(&tq->mutex);
  583. return rval;
  584. }
  585. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  586. {
  587. return pthread_create(&thr->pth, attr, start, arg);
  588. }
  589. void thr_info_freeze(struct thr_info *thr)
  590. {
  591. struct tq_ent *ent, *iter;
  592. struct thread_q *tq;
  593. if (!thr)
  594. return;
  595. tq = thr->q;
  596. if (!tq)
  597. return;
  598. mutex_lock(&tq->mutex);
  599. tq->frozen = true;
  600. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  601. list_del(&ent->q_node);
  602. free(ent);
  603. }
  604. mutex_unlock(&tq->mutex);
  605. }
  606. void thr_info_cancel(struct thr_info *thr)
  607. {
  608. if (!thr)
  609. return;
  610. if (PTH(thr) != 0L) {
  611. pthread_cancel(thr->pth);
  612. PTH(thr) = 0L;
  613. }
  614. }
  615. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  616. * on SMP machines */
  617. void nmsleep(unsigned int msecs)
  618. {
  619. struct timespec twait, tleft;
  620. int ret;
  621. ldiv_t d;
  622. d = ldiv(msecs, 1000);
  623. tleft.tv_sec = d.quot;
  624. tleft.tv_nsec = d.rem * 1000000;
  625. do {
  626. twait.tv_sec = tleft.tv_sec;
  627. twait.tv_nsec = tleft.tv_nsec;
  628. ret = nanosleep(&twait, &tleft);
  629. } while (ret == -1 && errno == EINTR);
  630. }
  631. /* Returns the microseconds difference between end and start times as a double */
  632. double us_tdiff(struct timeval *end, struct timeval *start)
  633. {
  634. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  635. }
  636. void rename_thr(const char* name) {
  637. #if defined(PR_SET_NAME)
  638. // Only the first 15 characters are used (16 - NUL terminator)
  639. prctl(PR_SET_NAME, name, 0, 0, 0);
  640. #elif defined(__APPLE__)
  641. pthread_setname_np(name);
  642. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  643. pthread_set_name_np(pthread_self(), name);
  644. #else
  645. // Prevent warnings for unused parameters...
  646. (void)name;
  647. #endif
  648. }
  649. /* Returns the seconds difference between end and start times as a double */
  650. double tdiff(struct timeval *end, struct timeval *start)
  651. {
  652. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  653. }
  654. bool extract_sockaddr(struct pool *pool, char *url)
  655. {
  656. char *url_begin, *url_end, *port_start = NULL;
  657. char url_address[256], port[6];
  658. struct addrinfo hints, *res;
  659. int url_len, port_len = 0;
  660. url_begin = strstr(url, "//");
  661. if (!url_begin)
  662. url_begin = url;
  663. else
  664. url_begin += 2;
  665. url_end = strstr(url_begin, ":");
  666. if (url_end) {
  667. url_len = url_end - url_begin;
  668. port_len = strlen(url_begin) - url_len - 1;
  669. if (port_len < 1)
  670. return false;
  671. port_start = url_end + 1;
  672. } else
  673. url_len = strlen(url_begin);
  674. if (url_len < 1)
  675. return false;
  676. sprintf(url_address, "%.*s", url_len, url_begin);
  677. if (port_len)
  678. snprintf(port, 6, "%.*s", port_len, port_start);
  679. else
  680. strcpy(port, "80");
  681. pool->stratum_port = strdup(port);
  682. memset(&hints, 0, sizeof(struct addrinfo));
  683. hints.ai_family = AF_UNSPEC;
  684. hints.ai_socktype = SOCK_STREAM;
  685. hints.ai_protocol = IPPROTO_TCP;
  686. if (getaddrinfo(url_address, port, &hints, &res)) {
  687. applog(LOG_DEBUG, "Failed to extract sock addr");
  688. return false;
  689. }
  690. pool->server = (struct sockaddr_in *)res->ai_addr;
  691. pool->sockaddr_url = strdup(url_address);
  692. return true;
  693. }
  694. /* Send a single command across a socket, appending \n to it */
  695. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  696. {
  697. SOCKETTYPE sock = pool->sock;
  698. ssize_t ssent = 0;
  699. if (opt_protocol)
  700. applog(LOG_DEBUG, "SEND: %s", s);
  701. strcat(s, "\n");
  702. len++;
  703. while (len > 0 ) {
  704. struct timeval timeout = {0, 0};
  705. size_t sent = 0;
  706. fd_set wd;
  707. FD_ZERO(&wd);
  708. FD_SET(sock, &wd);
  709. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  710. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  711. return false;
  712. }
  713. if (curl_easy_send(pool->stratum_curl, s + ssent, len, &sent) != CURLE_OK) {
  714. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  715. return false;
  716. }
  717. ssent += sent;
  718. len -= ssent;
  719. }
  720. return true;
  721. }
  722. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  723. {
  724. bool ret = false;
  725. mutex_lock(&pool->stratum_lock);
  726. if (pool->stratum_active)
  727. ret = __stratum_send(pool, s, len);
  728. else
  729. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  730. mutex_unlock(&pool->stratum_lock);
  731. return ret;
  732. }
  733. #define RECVSIZE 8191
  734. #define RBUFSIZE (RECVSIZE + 1)
  735. static void clear_sock(struct pool *pool)
  736. {
  737. SOCKETTYPE sock = pool->sock;
  738. recv(sock, pool->sockbuf, RECVSIZE, MSG_DONTWAIT);
  739. strcpy(pool->sockbuf, "");
  740. }
  741. /* Check to see if Santa's been good to you */
  742. static bool sock_full(struct pool *pool, bool wait)
  743. {
  744. SOCKETTYPE sock = pool->sock;
  745. struct timeval timeout;
  746. fd_set rd;
  747. if (strlen(pool->sockbuf))
  748. return true;
  749. FD_ZERO(&rd);
  750. FD_SET(sock, &rd);
  751. timeout.tv_usec = 0;
  752. if (wait)
  753. timeout.tv_sec = 60;
  754. else
  755. timeout.tv_sec = 0;
  756. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  757. return true;
  758. return false;
  759. }
  760. /* Peeks at a socket to find the first end of line and then reads just that
  761. * from the socket and returns that as a malloced char */
  762. char *recv_line(struct pool *pool)
  763. {
  764. ssize_t len, buflen;
  765. char *tok, *sret = NULL;
  766. size_t n;
  767. if (!strstr(pool->sockbuf, "\n")) {
  768. char s[RBUFSIZE];
  769. size_t sspace;
  770. CURLcode rc;
  771. if (!sock_full(pool, true)) {
  772. applog(LOG_DEBUG, "Timed out waiting for data on sock_full");
  773. goto out;
  774. }
  775. memset(s, 0, RBUFSIZE);
  776. mutex_lock(&pool->stratum_lock);
  777. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  778. mutex_unlock(&pool->stratum_lock);
  779. if (rc != CURLE_OK) {
  780. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  781. goto out;
  782. }
  783. /* Prevent buffer overflows, but if 8k is still not enough,
  784. * likely we have had some comms issues and the data is all
  785. * useless anyway */
  786. sspace = RECVSIZE - strlen(pool->sockbuf);
  787. strncat(pool->sockbuf, s, sspace);
  788. }
  789. buflen = strlen(pool->sockbuf);
  790. tok = strtok(pool->sockbuf, "\n");
  791. if (!tok) {
  792. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  793. goto out;
  794. }
  795. sret = strdup(tok);
  796. len = strlen(sret);
  797. /* Copy what's left in the buffer after the \n, including the
  798. * terminating \0 */
  799. if (buflen > len + 1)
  800. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  801. else
  802. strcpy(pool->sockbuf, "");
  803. out:
  804. if (!sret)
  805. clear_sock(pool);
  806. else if (opt_protocol)
  807. applog(LOG_DEBUG, "RECVD: %s", sret);
  808. return sret;
  809. }
  810. /* Extracts a string value from a json array with error checking. To be used
  811. * when the value of the string returned is only examined and not to be stored.
  812. * See json_array_string below */
  813. static char *__json_array_string(json_t *val, unsigned int entry)
  814. {
  815. json_t *arr_entry;
  816. if (json_is_null(val))
  817. return NULL;
  818. if (!json_is_array(val))
  819. return NULL;
  820. if (entry > json_array_size(val))
  821. return NULL;
  822. arr_entry = json_array_get(val, entry);
  823. if (!json_is_string(arr_entry))
  824. return NULL;
  825. return (char *)json_string_value(arr_entry);
  826. }
  827. /* Creates a freshly malloced dup of __json_array_string */
  828. static char *json_array_string(json_t *val, unsigned int entry)
  829. {
  830. char *buf = __json_array_string(val, entry);
  831. if (buf)
  832. return strdup(buf);
  833. return NULL;
  834. }
  835. static bool parse_notify(struct pool *pool, json_t *val)
  836. {
  837. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  838. int merkles, i;
  839. json_t *arr;
  840. bool clean;
  841. arr = json_array_get(val, 4);
  842. if (!arr || !json_is_array(arr))
  843. return false;
  844. merkles = json_array_size(arr);
  845. job_id = json_array_string(val, 0);
  846. prev_hash = json_array_string(val, 1);
  847. coinbase1 = json_array_string(val, 2);
  848. coinbase2 = json_array_string(val, 3);
  849. bbversion = json_array_string(val, 5);
  850. nbit = json_array_string(val, 6);
  851. ntime = json_array_string(val, 7);
  852. clean = json_is_true(json_array_get(val, 8));
  853. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  854. /* Annoying but we must not leak memory */
  855. if (job_id)
  856. free(job_id);
  857. if (prev_hash)
  858. free(prev_hash);
  859. if (coinbase1)
  860. free(coinbase1);
  861. if (coinbase2)
  862. free(coinbase2);
  863. if (bbversion)
  864. free(bbversion);
  865. if (nbit)
  866. free(nbit);
  867. if (ntime)
  868. free(ntime);
  869. return false;
  870. }
  871. mutex_lock(&pool->pool_lock);
  872. pool->swork.job_id = job_id;
  873. pool->swork.prev_hash = prev_hash;
  874. pool->swork.coinbase1 = coinbase1;
  875. pool->swork.coinbase2 = coinbase2;
  876. pool->swork.bbversion = bbversion;
  877. pool->swork.nbit = nbit;
  878. pool->swork.ntime = ntime;
  879. pool->swork.clean = clean;
  880. for (i = 0; i < pool->swork.merkles; i++)
  881. free(pool->swork.merkle[i]);
  882. if (merkles) {
  883. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  884. for (i = 0; i < merkles; i++)
  885. pool->swork.merkle[i] = json_array_string(arr, i);
  886. }
  887. pool->swork.merkles = merkles;
  888. if (clean)
  889. pool->nonce2 = 0;
  890. mutex_unlock(&pool->pool_lock);
  891. if (opt_protocol) {
  892. applog(LOG_DEBUG, "job_id: %s", job_id);
  893. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  894. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  895. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  896. for (i = 0; i < merkles; i++)
  897. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  898. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  899. applog(LOG_DEBUG, "nbit: %s", nbit);
  900. applog(LOG_DEBUG, "ntime: %s", ntime);
  901. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  902. }
  903. /* A notify message is the closest stratum gets to a getwork */
  904. pool->getwork_requested++;
  905. total_getworks++;
  906. return true;
  907. }
  908. static bool parse_diff(struct pool *pool, json_t *val)
  909. {
  910. int diff;
  911. diff = json_integer_value(json_array_get(val, 0));
  912. if (diff < 1)
  913. return false;
  914. mutex_lock(&pool->pool_lock);
  915. pool->swork.diff = diff;
  916. mutex_unlock(&pool->pool_lock);
  917. applog(LOG_DEBUG, "Pool %d difficulty set to %d", pool->pool_no, diff);
  918. return true;
  919. }
  920. static bool parse_reconnect(struct pool *pool, json_t *val)
  921. {
  922. char *url, *port, address[256];
  923. memset(address, 0, 255);
  924. url = (char *)json_string_value(json_array_get(val, 0));
  925. if (!url)
  926. url = pool->sockaddr_url;
  927. port = (char *)json_string_value(json_array_get(val, 1));
  928. if (!port)
  929. port = pool->stratum_port;
  930. sprintf(address, "%s:%s", url, port);
  931. if (!extract_sockaddr(pool, address))
  932. return false;
  933. pool->stratum_url = pool->sockaddr_url;
  934. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  935. if (!initiate_stratum(pool) || !auth_stratum(pool))
  936. return false;
  937. return true;
  938. }
  939. static bool send_version(struct pool *pool, json_t *val)
  940. {
  941. char s[RBUFSIZE];
  942. int id = json_integer_value(json_object_get(val, "id"));
  943. if (!id)
  944. return false;
  945. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  946. if (!stratum_send(pool, s, strlen(s)))
  947. return false;
  948. return true;
  949. }
  950. bool parse_method(struct pool *pool, char *s)
  951. {
  952. json_t *val = NULL, *method, *err_val, *params;
  953. json_error_t err;
  954. bool ret = false;
  955. char *buf;
  956. if (!s)
  957. goto out;
  958. val = JSON_LOADS(s, &err);
  959. if (!val) {
  960. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  961. goto out;
  962. }
  963. method = json_object_get(val, "method");
  964. if (!method)
  965. goto out;
  966. err_val = json_object_get(val, "error");
  967. params = json_object_get(val, "params");
  968. if (err_val && !json_is_null(err_val)) {
  969. char *ss;
  970. if (err_val)
  971. ss = json_dumps(err_val, JSON_INDENT(3));
  972. else
  973. ss = strdup("(unknown reason)");
  974. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  975. free(ss);
  976. goto out;
  977. }
  978. buf = (char *)json_string_value(method);
  979. if (!buf)
  980. goto out;
  981. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  982. ret = true;
  983. goto out;
  984. }
  985. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  986. ret = true;
  987. goto out;
  988. }
  989. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  990. ret = true;
  991. goto out;
  992. }
  993. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  994. ret = true;
  995. goto out;
  996. }
  997. out:
  998. if (val)
  999. json_decref(val);
  1000. return ret;
  1001. }
  1002. bool auth_stratum(struct pool *pool)
  1003. {
  1004. json_t *val = NULL, *res_val, *err_val;
  1005. char s[RBUFSIZE], *sret = NULL;
  1006. json_error_t err;
  1007. bool ret = false;
  1008. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1009. swork_id++, pool->rpc_user, pool->rpc_pass);
  1010. /* Parse all data prior sending auth request */
  1011. while (sock_full(pool, false)) {
  1012. sret = recv_line(pool);
  1013. if (!parse_method(pool, sret)) {
  1014. clear_sock(pool);
  1015. applog(LOG_INFO, "Failed to parse stratum buffer");
  1016. free(sret);
  1017. return ret;
  1018. }
  1019. free(sret);
  1020. }
  1021. if (!stratum_send(pool, s, strlen(s)))
  1022. goto out;
  1023. sret = recv_line(pool);
  1024. if (!sret)
  1025. goto out;
  1026. val = JSON_LOADS(sret, &err);
  1027. free(sret);
  1028. res_val = json_object_get(val, "result");
  1029. err_val = json_object_get(val, "error");
  1030. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1031. char *ss;
  1032. if (err_val)
  1033. ss = json_dumps(err_val, JSON_INDENT(3));
  1034. else
  1035. ss = strdup("(unknown reason)");
  1036. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1037. free(ss);
  1038. goto out;
  1039. }
  1040. ret = true;
  1041. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1042. out:
  1043. if (val)
  1044. json_decref(val);
  1045. return ret;
  1046. }
  1047. bool initiate_stratum(struct pool *pool)
  1048. {
  1049. json_t *val = NULL, *res_val, *err_val;
  1050. char curl_err_str[CURL_ERROR_SIZE];
  1051. char s[RBUFSIZE], *sret = NULL;
  1052. CURL *curl = NULL;
  1053. json_error_t err;
  1054. bool ret = false;
  1055. mutex_lock(&pool->stratum_lock);
  1056. pool->stratum_active = false;
  1057. if (!pool->stratum_curl) {
  1058. pool->stratum_curl = curl_easy_init();
  1059. if (unlikely(!pool->stratum_curl))
  1060. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1061. }
  1062. mutex_unlock(&pool->stratum_lock);
  1063. curl = pool->stratum_curl;
  1064. /* Create a http url for use with curl */
  1065. memset(s, 0, RBUFSIZE);
  1066. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1067. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 60);
  1068. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1069. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1070. curl_easy_setopt(curl, CURLOPT_URL, s);
  1071. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1072. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1073. if (pool->rpc_proxy) {
  1074. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1075. } else if (opt_socks_proxy) {
  1076. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1077. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1078. }
  1079. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1080. if (curl_easy_perform(curl)) {
  1081. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1082. goto out;
  1083. }
  1084. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1085. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1086. if (!__stratum_send(pool, s, strlen(s))) {
  1087. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1088. goto out;
  1089. }
  1090. if (!sock_full(pool, true)) {
  1091. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1092. goto out;
  1093. }
  1094. sret = recv_line(pool);
  1095. if (!sret)
  1096. goto out;
  1097. val = JSON_LOADS(sret, &err);
  1098. free(sret);
  1099. if (!val) {
  1100. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1101. goto out;
  1102. }
  1103. res_val = json_object_get(val, "result");
  1104. err_val = json_object_get(val, "error");
  1105. if (!res_val || json_is_null(res_val) ||
  1106. (err_val && !json_is_null(err_val))) {
  1107. char *ss;
  1108. if (err_val)
  1109. ss = json_dumps(err_val, JSON_INDENT(3));
  1110. else
  1111. ss = strdup("(unknown reason)");
  1112. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1113. free(ss);
  1114. goto out;
  1115. }
  1116. pool->nonce1 = json_array_string(res_val, 1);
  1117. if (!pool->nonce1) {
  1118. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1119. goto out;
  1120. }
  1121. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1122. if (!pool->n2size) {
  1123. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1124. goto out;
  1125. }
  1126. ret = true;
  1127. out:
  1128. if (val)
  1129. json_decref(val);
  1130. if (ret) {
  1131. if (!pool->stratum_url)
  1132. pool->stratum_url = pool->sockaddr_url;
  1133. pool->stratum_active = true;
  1134. pool->swork.diff = 1;
  1135. if (opt_protocol) {
  1136. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1137. pool->pool_no, pool->nonce1, pool->n2size);
  1138. }
  1139. } else {
  1140. applog(LOG_DEBUG, "Initiate stratum failed, disabling stratum_active");
  1141. mutex_lock(&pool->stratum_lock);
  1142. if (curl) {
  1143. curl_easy_cleanup(curl);
  1144. pool->stratum_curl = NULL;
  1145. }
  1146. mutex_unlock(&pool->stratum_lock);
  1147. }
  1148. return ret;
  1149. }