util.c 33 KB

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