util.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  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. static int keep_sockalive(SOCKETTYPE fd)
  166. {
  167. int tcp_keepidle = 60;
  168. int tcp_keepintvl = 60;
  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. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  198. curlsocktype __maybe_unused purpose)
  199. {
  200. return keep_sockalive(fd);
  201. }
  202. static void last_nettime(struct timeval *last)
  203. {
  204. rd_lock(&netacc_lock);
  205. last->tv_sec = nettime.tv_sec;
  206. last->tv_usec = nettime.tv_usec;
  207. rd_unlock(&netacc_lock);
  208. }
  209. static void set_nettime(void)
  210. {
  211. wr_lock(&netacc_lock);
  212. gettimeofday(&nettime, NULL);
  213. wr_unlock(&netacc_lock);
  214. }
  215. json_t *json_rpc_call(CURL *curl, const char *url,
  216. const char *userpass, const char *rpc_req,
  217. bool probe, bool longpoll, int *rolltime,
  218. struct pool *pool, bool share)
  219. {
  220. long timeout = longpoll ? (60 * 60) : 60;
  221. struct data_buffer all_data = {NULL, 0};
  222. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  223. char len_hdr[64], user_agent_hdr[128];
  224. char curl_err_str[CURL_ERROR_SIZE];
  225. struct curl_slist *headers = NULL;
  226. struct upload_buffer upload_data;
  227. json_t *val, *err_val, *res_val;
  228. bool probing = false;
  229. json_error_t err;
  230. int rc;
  231. memset(&err, 0, sizeof(err));
  232. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  233. if (probe)
  234. probing = !pool->probed;
  235. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  236. #if 0 /* Disable curl debugging since it spews to stderr */
  237. if (opt_protocol)
  238. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  239. #endif
  240. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  241. curl_easy_setopt(curl, CURLOPT_URL, url);
  242. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  243. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  244. /* Shares are staggered already and delays in submission can be costly
  245. * so do not delay them */
  246. if (!opt_delaynet || share)
  247. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  248. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  249. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  250. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  251. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  252. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  253. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  254. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  255. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  256. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  257. if (pool->rpc_proxy) {
  258. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  259. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  260. } else if (opt_socks_proxy) {
  261. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  262. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  263. }
  264. if (userpass) {
  265. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  266. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  267. }
  268. if (longpoll)
  269. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  270. curl_easy_setopt(curl, CURLOPT_POST, 1);
  271. if (opt_protocol)
  272. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  273. upload_data.buf = rpc_req;
  274. upload_data.len = strlen(rpc_req);
  275. sprintf(len_hdr, "Content-Length: %lu",
  276. (unsigned long) upload_data.len);
  277. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  278. headers = curl_slist_append(headers,
  279. "Content-type: application/json");
  280. headers = curl_slist_append(headers,
  281. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  282. if (likely(global_hashrate)) {
  283. char ghashrate[255];
  284. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  285. headers = curl_slist_append(headers, ghashrate);
  286. }
  287. headers = curl_slist_append(headers, len_hdr);
  288. headers = curl_slist_append(headers, user_agent_hdr);
  289. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  290. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  291. if (opt_delaynet) {
  292. /* Don't delay share submission, but still track the nettime */
  293. if (!share) {
  294. long long now_msecs, last_msecs;
  295. struct timeval now, last;
  296. gettimeofday(&now, NULL);
  297. last_nettime(&last);
  298. now_msecs = (long long)now.tv_sec * 1000;
  299. now_msecs += now.tv_usec / 1000;
  300. last_msecs = (long long)last.tv_sec * 1000;
  301. last_msecs += last.tv_usec / 1000;
  302. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  303. struct timespec rgtp;
  304. rgtp.tv_sec = 0;
  305. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  306. nanosleep(&rgtp, NULL);
  307. }
  308. }
  309. set_nettime();
  310. }
  311. rc = curl_easy_perform(curl);
  312. if (rc) {
  313. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  314. goto err_out;
  315. }
  316. if (!all_data.buf) {
  317. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  318. goto err_out;
  319. }
  320. if (probing) {
  321. pool->probed = true;
  322. /* If X-Long-Polling was found, activate long polling */
  323. if (hi.lp_path) {
  324. if (pool->hdr_path != NULL)
  325. free(pool->hdr_path);
  326. pool->hdr_path = hi.lp_path;
  327. } else
  328. pool->hdr_path = NULL;
  329. if (hi.stratum_url) {
  330. pool->stratum_url = hi.stratum_url;
  331. hi.stratum_url = NULL;
  332. }
  333. } else {
  334. if (hi.lp_path) {
  335. free(hi.lp_path);
  336. hi.lp_path = NULL;
  337. }
  338. if (hi.stratum_url) {
  339. free(hi.stratum_url);
  340. hi.stratum_url = NULL;
  341. }
  342. }
  343. *rolltime = hi.rolltime;
  344. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  345. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  346. pool->cgminer_pool_stats.canroll = hi.canroll;
  347. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  348. val = JSON_LOADS(all_data.buf, &err);
  349. if (!val) {
  350. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  351. if (opt_protocol)
  352. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  353. goto err_out;
  354. }
  355. if (opt_protocol) {
  356. char *s = json_dumps(val, JSON_INDENT(3));
  357. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  358. free(s);
  359. }
  360. /* JSON-RPC valid response returns a non-null 'result',
  361. * and a null 'error'.
  362. */
  363. res_val = json_object_get(val, "result");
  364. err_val = json_object_get(val, "error");
  365. if (!res_val || json_is_null(res_val) ||
  366. (err_val && !json_is_null(err_val))) {
  367. char *s;
  368. if (err_val)
  369. s = json_dumps(err_val, JSON_INDENT(3));
  370. else
  371. s = strdup("(unknown reason)");
  372. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  373. free(s);
  374. goto err_out;
  375. }
  376. if (hi.reason) {
  377. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  378. free(hi.reason);
  379. hi.reason = NULL;
  380. }
  381. successful_connect = true;
  382. databuf_free(&all_data);
  383. curl_slist_free_all(headers);
  384. curl_easy_reset(curl);
  385. return val;
  386. err_out:
  387. databuf_free(&all_data);
  388. curl_slist_free_all(headers);
  389. curl_easy_reset(curl);
  390. if (!successful_connect)
  391. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  392. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  393. return NULL;
  394. }
  395. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  396. static struct {
  397. const char *name;
  398. curl_proxytype proxytype;
  399. } proxynames[] = {
  400. { "http:", CURLPROXY_HTTP },
  401. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  402. { "http0:", CURLPROXY_HTTP_1_0 },
  403. #endif
  404. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  405. { "socks4:", CURLPROXY_SOCKS4 },
  406. #endif
  407. { "socks5:", CURLPROXY_SOCKS5 },
  408. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  409. { "socks4a:", CURLPROXY_SOCKS4A },
  410. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  411. #endif
  412. { NULL, 0 }
  413. };
  414. #endif
  415. const char *proxytype(curl_proxytype proxytype)
  416. {
  417. int i;
  418. for (i = 0; proxynames[i].name; i++)
  419. if (proxynames[i].proxytype == proxytype)
  420. return proxynames[i].name;
  421. return "invalid";
  422. }
  423. char *get_proxy(char *url, struct pool *pool)
  424. {
  425. pool->rpc_proxy = NULL;
  426. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  427. char *split;
  428. int plen, len, i;
  429. for (i = 0; proxynames[i].name; i++) {
  430. plen = strlen(proxynames[i].name);
  431. if (strncmp(url, proxynames[i].name, plen) == 0) {
  432. if (!(split = strchr(url, '|')))
  433. return url;
  434. *split = '\0';
  435. len = split - url;
  436. pool->rpc_proxy = malloc(1 + len - plen);
  437. if (!(pool->rpc_proxy))
  438. quit(1, "Failed to malloc rpc_proxy");
  439. strcpy(pool->rpc_proxy, url + plen);
  440. pool->rpc_proxytype = proxynames[i].proxytype;
  441. url = split + 1;
  442. break;
  443. }
  444. }
  445. #endif
  446. return url;
  447. }
  448. /* Returns a malloced array string of a binary value of arbitrary length. The
  449. * array is rounded up to a 4 byte size to appease architectures that need
  450. * aligned array sizes */
  451. char *bin2hex(const unsigned char *p, size_t len)
  452. {
  453. unsigned int i;
  454. ssize_t slen;
  455. char *s;
  456. slen = len * 2 + 1;
  457. if (slen % 4)
  458. slen += 4 - (slen % 4);
  459. s = calloc(slen, 1);
  460. if (unlikely(!s))
  461. quit(1, "Failed to calloc in bin2hex");
  462. for (i = 0; i < len; i++)
  463. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  464. return s;
  465. }
  466. /* Does the reverse of bin2hex but does not allocate any ram */
  467. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  468. {
  469. bool ret = false;
  470. while (*hexstr && len) {
  471. char hex_byte[4];
  472. unsigned int v;
  473. if (unlikely(!hexstr[1])) {
  474. applog(LOG_ERR, "hex2bin str truncated");
  475. return ret;
  476. }
  477. memset(hex_byte, 0, 4);
  478. hex_byte[0] = hexstr[0];
  479. hex_byte[1] = hexstr[1];
  480. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  481. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  482. return ret;
  483. }
  484. *p = (unsigned char) v;
  485. p++;
  486. hexstr += 2;
  487. len--;
  488. }
  489. if (likely(len == 0 && *hexstr == 0))
  490. ret = true;
  491. return ret;
  492. }
  493. bool fulltest(const unsigned char *hash, const unsigned char *target)
  494. {
  495. unsigned char hash_swap[32], target_swap[32];
  496. uint32_t *hash32 = (uint32_t *) hash_swap;
  497. uint32_t *target32 = (uint32_t *) target_swap;
  498. char *hash_str, *target_str;
  499. bool rc = true;
  500. int i;
  501. swap256(hash_swap, hash);
  502. swap256(target_swap, target);
  503. for (i = 0; i < 32/4; i++) {
  504. uint32_t h32tmp = swab32(hash32[i]);
  505. uint32_t t32tmp = target32[i];
  506. target32[i] = swab32(target32[i]); /* for printing */
  507. if (h32tmp > t32tmp) {
  508. rc = false;
  509. break;
  510. }
  511. if (h32tmp < t32tmp) {
  512. rc = true;
  513. break;
  514. }
  515. }
  516. if (opt_debug) {
  517. hash_str = bin2hex(hash_swap, 32);
  518. target_str = bin2hex(target_swap, 32);
  519. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  520. hash_str,
  521. target_str,
  522. rc ? "YES (hash < target)" :
  523. "no (false positive; hash > target)");
  524. free(hash_str);
  525. free(target_str);
  526. }
  527. return rc;
  528. }
  529. struct thread_q *tq_new(void)
  530. {
  531. struct thread_q *tq;
  532. tq = calloc(1, sizeof(*tq));
  533. if (!tq)
  534. return NULL;
  535. INIT_LIST_HEAD(&tq->q);
  536. pthread_mutex_init(&tq->mutex, NULL);
  537. pthread_cond_init(&tq->cond, NULL);
  538. return tq;
  539. }
  540. void tq_free(struct thread_q *tq)
  541. {
  542. struct tq_ent *ent, *iter;
  543. if (!tq)
  544. return;
  545. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  546. list_del(&ent->q_node);
  547. free(ent);
  548. }
  549. pthread_cond_destroy(&tq->cond);
  550. pthread_mutex_destroy(&tq->mutex);
  551. memset(tq, 0, sizeof(*tq)); /* poison */
  552. free(tq);
  553. }
  554. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  555. {
  556. mutex_lock(&tq->mutex);
  557. tq->frozen = frozen;
  558. pthread_cond_signal(&tq->cond);
  559. mutex_unlock(&tq->mutex);
  560. }
  561. void tq_freeze(struct thread_q *tq)
  562. {
  563. tq_freezethaw(tq, true);
  564. }
  565. void tq_thaw(struct thread_q *tq)
  566. {
  567. tq_freezethaw(tq, false);
  568. }
  569. bool tq_push(struct thread_q *tq, void *data)
  570. {
  571. struct tq_ent *ent;
  572. bool rc = true;
  573. ent = calloc(1, sizeof(*ent));
  574. if (!ent)
  575. return false;
  576. ent->data = data;
  577. INIT_LIST_HEAD(&ent->q_node);
  578. mutex_lock(&tq->mutex);
  579. if (!tq->frozen) {
  580. list_add_tail(&ent->q_node, &tq->q);
  581. } else {
  582. free(ent);
  583. rc = false;
  584. }
  585. pthread_cond_signal(&tq->cond);
  586. mutex_unlock(&tq->mutex);
  587. return rc;
  588. }
  589. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  590. {
  591. struct tq_ent *ent;
  592. void *rval = NULL;
  593. int rc;
  594. mutex_lock(&tq->mutex);
  595. if (!list_empty(&tq->q))
  596. goto pop;
  597. if (abstime)
  598. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  599. else
  600. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  601. if (rc)
  602. goto out;
  603. if (list_empty(&tq->q))
  604. goto out;
  605. pop:
  606. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  607. rval = ent->data;
  608. list_del(&ent->q_node);
  609. free(ent);
  610. out:
  611. mutex_unlock(&tq->mutex);
  612. return rval;
  613. }
  614. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  615. {
  616. return pthread_create(&thr->pth, attr, start, arg);
  617. }
  618. void thr_info_freeze(struct thr_info *thr)
  619. {
  620. struct tq_ent *ent, *iter;
  621. struct thread_q *tq;
  622. if (!thr)
  623. return;
  624. tq = thr->q;
  625. if (!tq)
  626. return;
  627. mutex_lock(&tq->mutex);
  628. tq->frozen = true;
  629. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  630. list_del(&ent->q_node);
  631. free(ent);
  632. }
  633. mutex_unlock(&tq->mutex);
  634. }
  635. void thr_info_cancel(struct thr_info *thr)
  636. {
  637. if (!thr)
  638. return;
  639. if (PTH(thr) != 0L) {
  640. pthread_cancel(thr->pth);
  641. PTH(thr) = 0L;
  642. }
  643. }
  644. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  645. * on SMP machines */
  646. void nmsleep(unsigned int msecs)
  647. {
  648. struct timespec twait, tleft;
  649. int ret;
  650. ldiv_t d;
  651. d = ldiv(msecs, 1000);
  652. tleft.tv_sec = d.quot;
  653. tleft.tv_nsec = d.rem * 1000000;
  654. do {
  655. twait.tv_sec = tleft.tv_sec;
  656. twait.tv_nsec = tleft.tv_nsec;
  657. ret = nanosleep(&twait, &tleft);
  658. } while (ret == -1 && errno == EINTR);
  659. }
  660. /* Returns the microseconds difference between end and start times as a double */
  661. double us_tdiff(struct timeval *end, struct timeval *start)
  662. {
  663. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  664. }
  665. /* Returns the seconds difference between end and start times as a double */
  666. double tdiff(struct timeval *end, struct timeval *start)
  667. {
  668. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  669. }
  670. bool extract_sockaddr(struct pool *pool, char *url)
  671. {
  672. char *url_begin, *url_end, *port_start = NULL;
  673. char url_address[256], port[6];
  674. struct addrinfo hints, *res;
  675. int url_len, port_len = 0;
  676. pool->sockaddr_url = url;
  677. url_begin = strstr(url, "//");
  678. if (!url_begin)
  679. url_begin = url;
  680. else
  681. url_begin += 2;
  682. url_end = strstr(url_begin, ":");
  683. if (url_end) {
  684. url_len = url_end - url_begin;
  685. port_len = strlen(url_begin) - url_len - 1;
  686. if (port_len < 1)
  687. return false;
  688. port_start = url_end + 1;
  689. } else
  690. url_len = strlen(url_begin);
  691. if (url_len < 1)
  692. return false;
  693. sprintf(url_address, "%.*s", url_len, url_begin);
  694. if (port_len)
  695. snprintf(port, 6, "%.*s", port_len, port_start);
  696. else
  697. strcpy(port, "80");
  698. pool->stratum_port = strdup(port);
  699. memset(&hints, 0, sizeof(struct addrinfo));
  700. hints.ai_family = AF_UNSPEC;
  701. hints.ai_socktype = SOCK_STREAM;
  702. hints.ai_protocol = IPPROTO_TCP;
  703. if (getaddrinfo(url_address, port, &hints, &res)) {
  704. applog(LOG_DEBUG, "Failed to extract sock addr");
  705. return false;
  706. }
  707. pool->server = (struct sockaddr_in *)res->ai_addr;
  708. pool->sockaddr_url = strdup(url_address);
  709. return true;
  710. }
  711. /* Send a single command across a socket, appending \n to it. This should all
  712. * be done under stratum lock except when first establishing the socket */
  713. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  714. {
  715. SOCKETTYPE sock = pool->sock;
  716. ssize_t ssent = 0;
  717. if (opt_protocol)
  718. applog(LOG_DEBUG, "SEND: %s", s);
  719. strcat(s, "\n");
  720. len++;
  721. while (len > 0 ) {
  722. struct timeval timeout = {0, 0};
  723. CURLcode rc = CURLE_SEND_ERROR;
  724. size_t sent = 0;
  725. fd_set wd;
  726. FD_ZERO(&wd);
  727. FD_SET(sock, &wd);
  728. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  729. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  730. return false;
  731. }
  732. if (likely(pool->stratum_curl))
  733. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  734. if (rc != CURLE_OK) {
  735. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  736. return false;
  737. }
  738. ssent += sent;
  739. len -= ssent;
  740. }
  741. return true;
  742. }
  743. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  744. {
  745. bool ret = false;
  746. mutex_lock(&pool->stratum_lock);
  747. if (pool->stratum_active)
  748. ret = __stratum_send(pool, s, len);
  749. else
  750. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  751. mutex_unlock(&pool->stratum_lock);
  752. return ret;
  753. }
  754. static void clear_sock(struct pool *pool)
  755. {
  756. size_t n = 0;
  757. mutex_lock(&pool->stratum_lock);
  758. /* Ignore return code of curl_easy_recv since we're just clearing
  759. * anything in the socket if it's still alive */
  760. if (likely(pool->stratum_curl))
  761. curl_easy_recv(pool->stratum_curl, pool->sockbuf, RECVSIZE, &n);
  762. mutex_unlock(&pool->stratum_lock);
  763. strcpy(pool->sockbuf, "");
  764. }
  765. /* Check to see if Santa's been good to you */
  766. static bool sock_full(struct pool *pool, bool wait)
  767. {
  768. SOCKETTYPE sock = pool->sock;
  769. struct timeval timeout;
  770. fd_set rd;
  771. if (strlen(pool->sockbuf))
  772. return true;
  773. FD_ZERO(&rd);
  774. FD_SET(sock, &rd);
  775. timeout.tv_usec = 0;
  776. if (wait)
  777. timeout.tv_sec = 60;
  778. else
  779. timeout.tv_sec = 0;
  780. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  781. return true;
  782. return false;
  783. }
  784. /* Peeks at a socket to find the first end of line and then reads just that
  785. * from the socket and returns that as a malloced char */
  786. char *recv_line(struct pool *pool)
  787. {
  788. ssize_t len, buflen;
  789. char *tok, *sret = NULL;
  790. size_t n = 0;
  791. if (!strstr(pool->sockbuf, "\n")) {
  792. CURLcode rc = CURLE_RECV_ERROR;
  793. char s[RBUFSIZE];
  794. size_t sspace;
  795. if (!sock_full(pool, true)) {
  796. applog(LOG_DEBUG, "Timed out waiting for data on sock_full");
  797. goto out;
  798. }
  799. memset(s, 0, RBUFSIZE);
  800. mutex_lock(&pool->stratum_lock);
  801. if (likely(pool->stratum_curl))
  802. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  803. mutex_unlock(&pool->stratum_lock);
  804. if (rc != CURLE_OK) {
  805. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  806. goto out;
  807. }
  808. /* Prevent buffer overflows, but if 8k is still not enough,
  809. * likely we have had some comms issues and the data is all
  810. * useless anyway */
  811. sspace = RECVSIZE - strlen(pool->sockbuf);
  812. strncat(pool->sockbuf, s, sspace);
  813. }
  814. buflen = strlen(pool->sockbuf);
  815. tok = strtok(pool->sockbuf, "\n");
  816. if (!tok) {
  817. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  818. goto out;
  819. }
  820. sret = strdup(tok);
  821. len = strlen(sret);
  822. /* Copy what's left in the buffer after the \n, including the
  823. * terminating \0 */
  824. if (buflen > len + 1)
  825. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  826. else
  827. strcpy(pool->sockbuf, "");
  828. out:
  829. if (!sret)
  830. clear_sock(pool);
  831. else if (opt_protocol)
  832. applog(LOG_DEBUG, "RECVD: %s", sret);
  833. return sret;
  834. }
  835. /* Extracts a string value from a json array with error checking. To be used
  836. * when the value of the string returned is only examined and not to be stored.
  837. * See json_array_string below */
  838. static char *__json_array_string(json_t *val, unsigned int entry)
  839. {
  840. json_t *arr_entry;
  841. if (json_is_null(val))
  842. return NULL;
  843. if (!json_is_array(val))
  844. return NULL;
  845. if (entry > json_array_size(val))
  846. return NULL;
  847. arr_entry = json_array_get(val, entry);
  848. if (!json_is_string(arr_entry))
  849. return NULL;
  850. return (char *)json_string_value(arr_entry);
  851. }
  852. /* Creates a freshly malloced dup of __json_array_string */
  853. static char *json_array_string(json_t *val, unsigned int entry)
  854. {
  855. char *buf = __json_array_string(val, entry);
  856. if (buf)
  857. return strdup(buf);
  858. return NULL;
  859. }
  860. static bool parse_notify(struct pool *pool, json_t *val)
  861. {
  862. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  863. int merkles, i;
  864. json_t *arr;
  865. bool clean;
  866. arr = json_array_get(val, 4);
  867. if (!arr || !json_is_array(arr))
  868. return false;
  869. merkles = json_array_size(arr);
  870. job_id = json_array_string(val, 0);
  871. prev_hash = json_array_string(val, 1);
  872. coinbase1 = json_array_string(val, 2);
  873. coinbase2 = json_array_string(val, 3);
  874. bbversion = json_array_string(val, 5);
  875. nbit = json_array_string(val, 6);
  876. ntime = json_array_string(val, 7);
  877. clean = json_is_true(json_array_get(val, 8));
  878. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  879. /* Annoying but we must not leak memory */
  880. if (job_id)
  881. free(job_id);
  882. if (prev_hash)
  883. free(prev_hash);
  884. if (coinbase1)
  885. free(coinbase1);
  886. if (coinbase2)
  887. free(coinbase2);
  888. if (bbversion)
  889. free(bbversion);
  890. if (nbit)
  891. free(nbit);
  892. if (ntime)
  893. free(ntime);
  894. return false;
  895. }
  896. mutex_lock(&pool->pool_lock);
  897. pool->swork.job_id = job_id;
  898. pool->swork.prev_hash = prev_hash;
  899. pool->swork.coinbase1 = coinbase1;
  900. pool->swork.coinbase2 = coinbase2;
  901. pool->swork.bbversion = bbversion;
  902. pool->swork.nbit = nbit;
  903. pool->swork.ntime = ntime;
  904. pool->swork.clean = clean;
  905. for (i = 0; i < pool->swork.merkles; i++)
  906. free(pool->swork.merkle[i]);
  907. if (merkles) {
  908. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  909. for (i = 0; i < merkles; i++)
  910. pool->swork.merkle[i] = json_array_string(arr, i);
  911. }
  912. pool->swork.merkles = merkles;
  913. if (clean)
  914. pool->nonce2 = 0;
  915. mutex_unlock(&pool->pool_lock);
  916. if (opt_protocol) {
  917. applog(LOG_DEBUG, "job_id: %s", job_id);
  918. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  919. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  920. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  921. for (i = 0; i < merkles; i++)
  922. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  923. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  924. applog(LOG_DEBUG, "nbit: %s", nbit);
  925. applog(LOG_DEBUG, "ntime: %s", ntime);
  926. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  927. }
  928. /* A notify message is the closest stratum gets to a getwork */
  929. pool->getwork_requested++;
  930. total_getworks++;
  931. return true;
  932. }
  933. static bool parse_diff(struct pool *pool, json_t *val)
  934. {
  935. int diff;
  936. diff = json_integer_value(json_array_get(val, 0));
  937. if (diff < 1)
  938. return false;
  939. mutex_lock(&pool->pool_lock);
  940. pool->swork.diff = diff;
  941. mutex_unlock(&pool->pool_lock);
  942. applog(LOG_DEBUG, "Pool %d difficulty set to %d", pool->pool_no, diff);
  943. return true;
  944. }
  945. static bool parse_reconnect(struct pool *pool, json_t *val)
  946. {
  947. char *url, *port, address[256];
  948. memset(address, 0, 255);
  949. url = (char *)json_string_value(json_array_get(val, 0));
  950. if (!url)
  951. url = pool->sockaddr_url;
  952. port = (char *)json_string_value(json_array_get(val, 1));
  953. if (!port)
  954. port = pool->stratum_port;
  955. sprintf(address, "%s:%s", url, port);
  956. if (!extract_sockaddr(pool, address))
  957. return false;
  958. pool->stratum_url = pool->sockaddr_url;
  959. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  960. if (!initiate_stratum(pool) || !auth_stratum(pool))
  961. return false;
  962. return true;
  963. }
  964. static bool send_version(struct pool *pool, json_t *val)
  965. {
  966. char s[RBUFSIZE];
  967. int id = json_integer_value(json_object_get(val, "id"));
  968. if (!id)
  969. return false;
  970. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  971. if (!stratum_send(pool, s, strlen(s)))
  972. return false;
  973. return true;
  974. }
  975. bool parse_method(struct pool *pool, char *s)
  976. {
  977. json_t *val = NULL, *method, *err_val, *params;
  978. json_error_t err;
  979. bool ret = false;
  980. char *buf;
  981. if (!s)
  982. goto out;
  983. val = JSON_LOADS(s, &err);
  984. if (!val) {
  985. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  986. goto out;
  987. }
  988. method = json_object_get(val, "method");
  989. if (!method)
  990. goto out;
  991. err_val = json_object_get(val, "error");
  992. params = json_object_get(val, "params");
  993. if (err_val && !json_is_null(err_val)) {
  994. char *ss;
  995. if (err_val)
  996. ss = json_dumps(err_val, JSON_INDENT(3));
  997. else
  998. ss = strdup("(unknown reason)");
  999. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1000. free(ss);
  1001. goto out;
  1002. }
  1003. buf = (char *)json_string_value(method);
  1004. if (!buf)
  1005. goto out;
  1006. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  1007. ret = true;
  1008. goto out;
  1009. }
  1010. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1011. ret = true;
  1012. goto out;
  1013. }
  1014. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1015. ret = true;
  1016. goto out;
  1017. }
  1018. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1019. ret = true;
  1020. goto out;
  1021. }
  1022. out:
  1023. if (val)
  1024. json_decref(val);
  1025. return ret;
  1026. }
  1027. bool auth_stratum(struct pool *pool)
  1028. {
  1029. json_t *val = NULL, *res_val, *err_val;
  1030. char s[RBUFSIZE], *sret = NULL;
  1031. json_error_t err;
  1032. bool ret = false;
  1033. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1034. swork_id++, pool->rpc_user, pool->rpc_pass);
  1035. /* Parse all data prior sending auth request */
  1036. while (sock_full(pool, false)) {
  1037. sret = recv_line(pool);
  1038. if (!parse_method(pool, sret)) {
  1039. clear_sock(pool);
  1040. applog(LOG_INFO, "Failed to parse stratum buffer");
  1041. free(sret);
  1042. return ret;
  1043. }
  1044. free(sret);
  1045. }
  1046. if (!stratum_send(pool, s, strlen(s)))
  1047. goto out;
  1048. sret = recv_line(pool);
  1049. if (!sret)
  1050. goto out;
  1051. val = JSON_LOADS(sret, &err);
  1052. free(sret);
  1053. res_val = json_object_get(val, "result");
  1054. err_val = json_object_get(val, "error");
  1055. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1056. char *ss;
  1057. if (err_val)
  1058. ss = json_dumps(err_val, JSON_INDENT(3));
  1059. else
  1060. ss = strdup("(unknown reason)");
  1061. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1062. free(ss);
  1063. goto out;
  1064. }
  1065. ret = true;
  1066. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1067. out:
  1068. if (val)
  1069. json_decref(val);
  1070. return ret;
  1071. }
  1072. bool initiate_stratum(struct pool *pool)
  1073. {
  1074. json_t *val = NULL, *res_val, *err_val;
  1075. char curl_err_str[CURL_ERROR_SIZE];
  1076. char s[RBUFSIZE], *sret = NULL;
  1077. CURL *curl = NULL;
  1078. json_error_t err;
  1079. bool ret = false;
  1080. mutex_lock(&pool->stratum_lock);
  1081. pool->stratum_active = false;
  1082. if (!pool->stratum_curl) {
  1083. pool->stratum_curl = curl_easy_init();
  1084. if (unlikely(!pool->stratum_curl))
  1085. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1086. }
  1087. mutex_unlock(&pool->stratum_lock);
  1088. curl = pool->stratum_curl;
  1089. /* Create a http url for use with curl */
  1090. memset(s, 0, RBUFSIZE);
  1091. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1092. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 60);
  1093. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1094. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1095. curl_easy_setopt(curl, CURLOPT_URL, s);
  1096. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1097. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1098. if (pool->rpc_proxy) {
  1099. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1100. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  1101. } else if (opt_socks_proxy) {
  1102. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1103. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1104. }
  1105. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1106. if (curl_easy_perform(curl)) {
  1107. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1108. goto out;
  1109. }
  1110. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1111. keep_sockalive(pool->sock);
  1112. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1113. if (!__stratum_send(pool, s, strlen(s))) {
  1114. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1115. goto out;
  1116. }
  1117. if (!sock_full(pool, true)) {
  1118. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1119. goto out;
  1120. }
  1121. sret = recv_line(pool);
  1122. if (!sret)
  1123. goto out;
  1124. val = JSON_LOADS(sret, &err);
  1125. free(sret);
  1126. if (!val) {
  1127. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1128. goto out;
  1129. }
  1130. res_val = json_object_get(val, "result");
  1131. err_val = json_object_get(val, "error");
  1132. if (!res_val || json_is_null(res_val) ||
  1133. (err_val && !json_is_null(err_val))) {
  1134. char *ss;
  1135. if (err_val)
  1136. ss = json_dumps(err_val, JSON_INDENT(3));
  1137. else
  1138. ss = strdup("(unknown reason)");
  1139. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1140. free(ss);
  1141. goto out;
  1142. }
  1143. pool->nonce1 = json_array_string(res_val, 1);
  1144. if (!pool->nonce1) {
  1145. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1146. goto out;
  1147. }
  1148. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1149. if (!pool->n2size) {
  1150. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1151. goto out;
  1152. }
  1153. ret = true;
  1154. out:
  1155. if (val)
  1156. json_decref(val);
  1157. if (ret) {
  1158. if (!pool->stratum_url)
  1159. pool->stratum_url = pool->sockaddr_url;
  1160. pool->stratum_active = true;
  1161. pool->swork.diff = 1;
  1162. if (opt_protocol) {
  1163. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1164. pool->pool_no, pool->nonce1, pool->n2size);
  1165. }
  1166. } else {
  1167. applog(LOG_DEBUG, "Initiate stratum failed, disabling stratum_active");
  1168. mutex_lock(&pool->stratum_lock);
  1169. if (curl) {
  1170. curl_easy_cleanup(curl);
  1171. pool->stratum_curl = NULL;
  1172. }
  1173. mutex_unlock(&pool->stratum_lock);
  1174. }
  1175. return ret;
  1176. }