util.c 31 KB

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