util.c 34 KB

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