util.c 35 KB

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