util.c 33 KB

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