util.c 33 KB

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