util.c 34 KB

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