util.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  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. *rolltime = hi.rolltime;
  371. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  372. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  373. pool->cgminer_pool_stats.canroll = hi.canroll;
  374. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  375. val = JSON_LOADS(all_data.buf, &err);
  376. if (!val) {
  377. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  378. if (opt_protocol)
  379. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  380. goto err_out;
  381. }
  382. if (opt_protocol) {
  383. char *s = json_dumps(val, JSON_INDENT(3));
  384. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  385. free(s);
  386. }
  387. /* JSON-RPC valid response returns a non-null 'result',
  388. * and a null 'error'.
  389. */
  390. res_val = json_object_get(val, "result");
  391. err_val = json_object_get(val, "error");
  392. if (!res_val ||(err_val && !json_is_null(err_val))) {
  393. char *s;
  394. if (err_val)
  395. s = json_dumps(err_val, JSON_INDENT(3));
  396. else
  397. s = strdup("(unknown reason)");
  398. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  399. free(s);
  400. json_decref(val);
  401. goto err_out;
  402. }
  403. if (hi.reason) {
  404. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  405. free(hi.reason);
  406. hi.reason = NULL;
  407. }
  408. successful_connect = true;
  409. databuf_free(&all_data);
  410. curl_slist_free_all(headers);
  411. curl_easy_reset(curl);
  412. return val;
  413. err_out:
  414. databuf_free(&all_data);
  415. curl_slist_free_all(headers);
  416. curl_easy_reset(curl);
  417. if (!successful_connect)
  418. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  419. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  420. return NULL;
  421. }
  422. bool our_curl_supports_proxy_uris()
  423. {
  424. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  425. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  426. }
  427. /* Returns a malloced array string of a binary value of arbitrary length. The
  428. * array is rounded up to a 4 byte size to appease architectures that need
  429. * aligned array sizes */
  430. char *bin2hex(const unsigned char *p, size_t len)
  431. {
  432. unsigned int i;
  433. ssize_t slen;
  434. char *s;
  435. slen = len * 2 + 1;
  436. if (slen % 4)
  437. slen += 4 - (slen % 4);
  438. s = calloc(slen, 1);
  439. if (unlikely(!s))
  440. quit(1, "Failed to calloc in bin2hex");
  441. for (i = 0; i < len; i++)
  442. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  443. return s;
  444. }
  445. /* Does the reverse of bin2hex but does not allocate any ram */
  446. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  447. {
  448. bool ret = false;
  449. while (*hexstr && len) {
  450. char hex_byte[4];
  451. unsigned int v;
  452. if (unlikely(!hexstr[1])) {
  453. applog(LOG_ERR, "hex2bin str truncated");
  454. return ret;
  455. }
  456. memset(hex_byte, 0, 4);
  457. hex_byte[0] = hexstr[0];
  458. hex_byte[1] = hexstr[1];
  459. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  460. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  461. return ret;
  462. }
  463. *p = (unsigned char) v;
  464. p++;
  465. hexstr += 2;
  466. len--;
  467. }
  468. if (likely(len == 0 && *hexstr == 0))
  469. ret = true;
  470. return ret;
  471. }
  472. bool fulltest(const unsigned char *hash, const unsigned char *target)
  473. {
  474. unsigned char hash_swap[32], target_swap[32];
  475. uint32_t *hash32 = (uint32_t *) hash_swap;
  476. uint32_t *target32 = (uint32_t *) target_swap;
  477. char *hash_str, *target_str;
  478. bool rc = true;
  479. int i;
  480. swap256(hash_swap, hash);
  481. swap256(target_swap, target);
  482. for (i = 0; i < 32/4; i++) {
  483. uint32_t h32tmp = htobe32(hash32[i]);
  484. uint32_t t32tmp = htole32(target32[i]);
  485. target32[i] = swab32(target32[i]); /* for printing */
  486. if (h32tmp > t32tmp) {
  487. rc = false;
  488. break;
  489. }
  490. if (h32tmp < t32tmp) {
  491. rc = true;
  492. break;
  493. }
  494. }
  495. if (opt_debug) {
  496. hash_str = bin2hex(hash_swap, 32);
  497. target_str = bin2hex(target_swap, 32);
  498. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  499. hash_str,
  500. target_str,
  501. rc ? "YES (hash < target)" :
  502. "no (false positive; hash > target)");
  503. free(hash_str);
  504. free(target_str);
  505. }
  506. return rc;
  507. }
  508. struct thread_q *tq_new(void)
  509. {
  510. struct thread_q *tq;
  511. tq = calloc(1, sizeof(*tq));
  512. if (!tq)
  513. return NULL;
  514. INIT_LIST_HEAD(&tq->q);
  515. pthread_mutex_init(&tq->mutex, NULL);
  516. pthread_cond_init(&tq->cond, NULL);
  517. return tq;
  518. }
  519. void tq_free(struct thread_q *tq)
  520. {
  521. struct tq_ent *ent, *iter;
  522. if (!tq)
  523. return;
  524. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  525. list_del(&ent->q_node);
  526. free(ent);
  527. }
  528. pthread_cond_destroy(&tq->cond);
  529. pthread_mutex_destroy(&tq->mutex);
  530. memset(tq, 0, sizeof(*tq)); /* poison */
  531. free(tq);
  532. }
  533. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  534. {
  535. mutex_lock(&tq->mutex);
  536. tq->frozen = frozen;
  537. pthread_cond_signal(&tq->cond);
  538. mutex_unlock(&tq->mutex);
  539. }
  540. void tq_freeze(struct thread_q *tq)
  541. {
  542. tq_freezethaw(tq, true);
  543. }
  544. void tq_thaw(struct thread_q *tq)
  545. {
  546. tq_freezethaw(tq, false);
  547. }
  548. bool tq_push(struct thread_q *tq, void *data)
  549. {
  550. struct tq_ent *ent;
  551. bool rc = true;
  552. ent = calloc(1, sizeof(*ent));
  553. if (!ent)
  554. return false;
  555. ent->data = data;
  556. INIT_LIST_HEAD(&ent->q_node);
  557. mutex_lock(&tq->mutex);
  558. if (!tq->frozen) {
  559. list_add_tail(&ent->q_node, &tq->q);
  560. } else {
  561. free(ent);
  562. rc = false;
  563. }
  564. pthread_cond_signal(&tq->cond);
  565. mutex_unlock(&tq->mutex);
  566. return rc;
  567. }
  568. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  569. {
  570. struct tq_ent *ent;
  571. void *rval = NULL;
  572. int rc;
  573. mutex_lock(&tq->mutex);
  574. if (!list_empty(&tq->q))
  575. goto pop;
  576. if (abstime)
  577. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  578. else
  579. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  580. if (rc)
  581. goto out;
  582. if (list_empty(&tq->q))
  583. goto out;
  584. pop:
  585. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  586. rval = ent->data;
  587. list_del(&ent->q_node);
  588. free(ent);
  589. out:
  590. mutex_unlock(&tq->mutex);
  591. return rval;
  592. }
  593. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  594. {
  595. return pthread_create(&thr->pth, attr, start, arg);
  596. }
  597. void thr_info_freeze(struct thr_info *thr)
  598. {
  599. struct tq_ent *ent, *iter;
  600. struct thread_q *tq;
  601. if (!thr)
  602. return;
  603. tq = thr->q;
  604. if (!tq)
  605. return;
  606. mutex_lock(&tq->mutex);
  607. tq->frozen = true;
  608. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  609. list_del(&ent->q_node);
  610. free(ent);
  611. }
  612. mutex_unlock(&tq->mutex);
  613. }
  614. void thr_info_cancel(struct thr_info *thr)
  615. {
  616. if (!thr)
  617. return;
  618. if (PTH(thr) != 0L) {
  619. pthread_cancel(thr->pth);
  620. PTH(thr) = 0L;
  621. }
  622. }
  623. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  624. * on SMP machines */
  625. void nmsleep(unsigned int msecs)
  626. {
  627. struct timespec twait, tleft;
  628. int ret;
  629. ldiv_t d;
  630. d = ldiv(msecs, 1000);
  631. tleft.tv_sec = d.quot;
  632. tleft.tv_nsec = d.rem * 1000000;
  633. do {
  634. twait.tv_sec = tleft.tv_sec;
  635. twait.tv_nsec = tleft.tv_nsec;
  636. ret = nanosleep(&twait, &tleft);
  637. } while (ret == -1 && errno == EINTR);
  638. }
  639. /* Returns the microseconds difference between end and start times as a double */
  640. double us_tdiff(struct timeval *end, struct timeval *start)
  641. {
  642. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  643. }
  644. /* Returns the seconds difference between end and start times as a double */
  645. double tdiff(struct timeval *end, struct timeval *start)
  646. {
  647. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  648. }
  649. bool extract_sockaddr(struct pool *pool, char *url)
  650. {
  651. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  652. char url_address[256], port[6];
  653. int url_len, port_len = 0;
  654. url_begin = strstr(url, "//");
  655. if (!url_begin)
  656. url_begin = url;
  657. else
  658. url_begin += 2;
  659. /* Look for numeric ipv6 entries */
  660. ipv6_begin = strstr(url_begin, "[");
  661. ipv6_end = strstr(url_begin, "]");
  662. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  663. url_end = strstr(ipv6_end, ":");
  664. else
  665. url_end = strstr(url_begin, ":");
  666. if (url_end) {
  667. url_len = url_end - url_begin;
  668. port_len = strlen(url_begin) - url_len - 1;
  669. if (port_len < 1)
  670. return false;
  671. port_start = url_end + 1;
  672. } else
  673. url_len = strlen(url_begin);
  674. if (url_len < 1)
  675. return false;
  676. sprintf(url_address, "%.*s", url_len, url_begin);
  677. if (port_len)
  678. snprintf(port, 6, "%.*s", port_len, port_start);
  679. else
  680. strcpy(port, "80");
  681. free(pool->stratum_port);
  682. pool->stratum_port = strdup(port);
  683. free(pool->sockaddr_url);
  684. pool->sockaddr_url = strdup(url_address);
  685. return true;
  686. }
  687. /* Send a single command across a socket, appending \n to it. This should all
  688. * be done under stratum lock except when first establishing the socket */
  689. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  690. {
  691. SOCKETTYPE sock = pool->sock;
  692. ssize_t ssent = 0;
  693. if (opt_protocol)
  694. applog(LOG_DEBUG, "SEND: %s", s);
  695. strcat(s, "\n");
  696. len++;
  697. while (len > 0 ) {
  698. struct timeval timeout = {0, 0};
  699. size_t sent = 0;
  700. CURLcode rc;
  701. fd_set wd;
  702. FD_ZERO(&wd);
  703. FD_SET(sock, &wd);
  704. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  705. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  706. return false;
  707. }
  708. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  709. if (rc != CURLE_OK) {
  710. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  711. return false;
  712. }
  713. ssent += sent;
  714. len -= ssent;
  715. }
  716. return true;
  717. }
  718. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  719. {
  720. bool ret = false;
  721. mutex_lock(&pool->stratum_lock);
  722. if (pool->stratum_active)
  723. ret = __stratum_send(pool, s, len);
  724. else
  725. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  726. mutex_unlock(&pool->stratum_lock);
  727. return ret;
  728. }
  729. static void clear_sock(struct pool *pool)
  730. {
  731. size_t n = 0;
  732. char buf[RECVSIZE];
  733. mutex_lock(&pool->stratum_lock);
  734. while (CURLE_OK == curl_easy_recv(pool->stratum_curl, buf, RECVSIZE, &n))
  735. {}
  736. mutex_unlock(&pool->stratum_lock);
  737. }
  738. /* Check to see if Santa's been good to you */
  739. static bool sock_full(struct pool *pool, bool wait)
  740. {
  741. SOCKETTYPE sock = pool->sock;
  742. struct timeval timeout;
  743. fd_set rd;
  744. if (pool->readbuf.buf && memchr(pool->readbuf.buf, '\n', pool->readbuf.len))
  745. return true;
  746. FD_ZERO(&rd);
  747. FD_SET(sock, &rd);
  748. timeout.tv_usec = 0;
  749. if (wait)
  750. timeout.tv_sec = 60;
  751. else
  752. timeout.tv_sec = 0;
  753. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  754. return true;
  755. return false;
  756. }
  757. /* Peeks at a socket to find the first end of line and then reads just that
  758. * from the socket and returns that as a malloced char */
  759. char *recv_line(struct pool *pool)
  760. {
  761. ssize_t len;
  762. char *tok, *sret = NULL;
  763. size_t n = 0;
  764. while (!(pool->readbuf.buf && memchr(pool->readbuf.buf, '\n', pool->readbuf.len))) {
  765. char s[RBUFSIZE];
  766. CURLcode rc;
  767. if (!sock_full(pool, true)) {
  768. applog(LOG_DEBUG, "Timed out waiting for data on sock_full");
  769. goto out;
  770. }
  771. memset(s, 0, RBUFSIZE);
  772. mutex_lock(&pool->stratum_lock);
  773. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  774. mutex_unlock(&pool->stratum_lock);
  775. if (rc != CURLE_OK) {
  776. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %d", rc);
  777. goto out;
  778. }
  779. len = all_data_cb(s, n, 1, &pool->readbuf);
  780. if (n != (size_t)len) {
  781. applog(LOG_DEBUG, "Error appending readbuf in recv_line");
  782. goto out;
  783. }
  784. }
  785. // Assuming the bulk of the data will be in the line, steal the buffer and return it
  786. tok = memchr(pool->readbuf.buf, '\n', pool->readbuf.len);
  787. *tok = '\0';
  788. len = tok - (char*)pool->readbuf.buf;
  789. pool->readbuf.len -= len + 1;
  790. tok = memcpy(malloc(pool->readbuf.len), tok + 1, pool->readbuf.len);
  791. sret = realloc(pool->readbuf.buf, len + 1);
  792. pool->readbuf.buf = tok;
  793. out:
  794. if (!sret)
  795. clear_sock(pool);
  796. else if (opt_protocol)
  797. applog(LOG_DEBUG, "RECVD: %s", sret);
  798. return sret;
  799. }
  800. /* Extracts a string value from a json array with error checking. To be used
  801. * when the value of the string returned is only examined and not to be stored.
  802. * See json_array_string below */
  803. static char *__json_array_string(json_t *val, unsigned int entry)
  804. {
  805. json_t *arr_entry;
  806. if (json_is_null(val))
  807. return NULL;
  808. if (!json_is_array(val))
  809. return NULL;
  810. if (entry > json_array_size(val))
  811. return NULL;
  812. arr_entry = json_array_get(val, entry);
  813. if (!json_is_string(arr_entry))
  814. return NULL;
  815. return (char *)json_string_value(arr_entry);
  816. }
  817. /* Creates a freshly malloced dup of __json_array_string */
  818. static char *json_array_string(json_t *val, unsigned int entry)
  819. {
  820. char *buf = __json_array_string(val, entry);
  821. if (buf)
  822. return strdup(buf);
  823. return NULL;
  824. }
  825. static bool parse_notify(struct pool *pool, json_t *val)
  826. {
  827. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  828. int merkles, i;
  829. json_t *arr;
  830. bool clean;
  831. arr = json_array_get(val, 4);
  832. if (!arr || !json_is_array(arr))
  833. return false;
  834. merkles = json_array_size(arr);
  835. job_id = json_array_string(val, 0);
  836. prev_hash = json_array_string(val, 1);
  837. coinbase1 = json_array_string(val, 2);
  838. coinbase2 = json_array_string(val, 3);
  839. bbversion = json_array_string(val, 5);
  840. nbit = json_array_string(val, 6);
  841. ntime = json_array_string(val, 7);
  842. clean = json_is_true(json_array_get(val, 8));
  843. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  844. /* Annoying but we must not leak memory */
  845. if (job_id)
  846. free(job_id);
  847. if (prev_hash)
  848. free(prev_hash);
  849. if (coinbase1)
  850. free(coinbase1);
  851. if (coinbase2)
  852. free(coinbase2);
  853. if (bbversion)
  854. free(bbversion);
  855. if (nbit)
  856. free(nbit);
  857. if (ntime)
  858. free(ntime);
  859. return false;
  860. }
  861. mutex_lock(&pool->pool_lock);
  862. free(pool->swork.job_id);
  863. free(pool->swork.prev_hash);
  864. free(pool->swork.coinbase1);
  865. free(pool->swork.coinbase2);
  866. free(pool->swork.bbversion);
  867. free(pool->swork.nbit);
  868. free(pool->swork.ntime);
  869. pool->swork.job_id = job_id;
  870. pool->swork.prev_hash = prev_hash;
  871. pool->swork.coinbase1 = coinbase1;
  872. pool->swork.coinbase2 = coinbase2;
  873. pool->swork.bbversion = bbversion;
  874. pool->swork.nbit = nbit;
  875. pool->swork.ntime = ntime;
  876. pool->submit_old = !clean;
  877. pool->swork.clean = true;
  878. for (i = 0; i < pool->swork.merkles; i++)
  879. free(pool->swork.merkle[i]);
  880. if (merkles) {
  881. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  882. for (i = 0; i < merkles; i++)
  883. pool->swork.merkle[i] = json_array_string(arr, i);
  884. }
  885. pool->swork.merkles = merkles;
  886. if (clean)
  887. pool->nonce2 = 0;
  888. mutex_unlock(&pool->pool_lock);
  889. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  890. pool->pool_no, job_id);
  891. if (opt_protocol) {
  892. applog(LOG_DEBUG, "job_id: %s", job_id);
  893. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  894. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  895. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  896. for (i = 0; i < merkles; i++)
  897. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  898. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  899. applog(LOG_DEBUG, "nbit: %s", nbit);
  900. applog(LOG_DEBUG, "ntime: %s", ntime);
  901. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  902. }
  903. /* A notify message is the closest stratum gets to a getwork */
  904. pool->getwork_requested++;
  905. total_getworks++;
  906. {
  907. // Request transaction data to discourage pools from doing anything shady
  908. char s[1024];
  909. int sLen;
  910. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  911. pool->swork.job_id,
  912. pool->swork.job_id);
  913. stratum_send(pool, s, sLen);
  914. if ((!pool->swork.opaque) && pool->swork.transparency_time == (time_t)-1)
  915. pool->swork.transparency_time = time(NULL);
  916. }
  917. return true;
  918. }
  919. static bool parse_diff(struct pool *pool, json_t *val)
  920. {
  921. double diff;
  922. diff = json_number_value(json_array_get(val, 0));
  923. if (diff == 0)
  924. return false;
  925. mutex_lock(&pool->pool_lock);
  926. pool->swork.diff = diff;
  927. mutex_unlock(&pool->pool_lock);
  928. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no, diff);
  929. return true;
  930. }
  931. static bool parse_reconnect(struct pool *pool, json_t *val)
  932. {
  933. char *url, *port, address[256];
  934. memset(address, 0, 255);
  935. url = (char *)json_string_value(json_array_get(val, 0));
  936. if (!url)
  937. url = pool->sockaddr_url;
  938. port = (char *)json_string_value(json_array_get(val, 1));
  939. if (!port)
  940. port = pool->stratum_port;
  941. sprintf(address, "%s:%s", url, port);
  942. if (!extract_sockaddr(pool, address))
  943. return false;
  944. pool->stratum_url = pool->sockaddr_url;
  945. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  946. if (!initiate_stratum(pool) || !auth_stratum(pool))
  947. return false;
  948. return true;
  949. }
  950. static bool send_version(struct pool *pool, json_t *val)
  951. {
  952. char s[RBUFSIZE];
  953. int id = json_integer_value(json_object_get(val, "id"));
  954. if (!id)
  955. return false;
  956. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  957. if (!stratum_send(pool, s, strlen(s)))
  958. return false;
  959. return true;
  960. }
  961. bool parse_method(struct pool *pool, char *s)
  962. {
  963. json_t *val = NULL, *method, *err_val, *params;
  964. json_error_t err;
  965. bool ret = false;
  966. char *buf;
  967. if (!s)
  968. goto out;
  969. val = JSON_LOADS(s, &err);
  970. if (!val) {
  971. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  972. goto out;
  973. }
  974. method = json_object_get(val, "method");
  975. if (!method)
  976. goto out;
  977. err_val = json_object_get(val, "error");
  978. params = json_object_get(val, "params");
  979. if (err_val && !json_is_null(err_val)) {
  980. char *ss;
  981. if (err_val)
  982. ss = json_dumps(err_val, JSON_INDENT(3));
  983. else
  984. ss = strdup("(unknown reason)");
  985. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  986. free(ss);
  987. goto out;
  988. }
  989. buf = (char *)json_string_value(method);
  990. if (!buf)
  991. goto out;
  992. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  993. ret = true;
  994. goto out;
  995. }
  996. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  997. ret = true;
  998. goto out;
  999. }
  1000. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1001. ret = true;
  1002. goto out;
  1003. }
  1004. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1005. ret = true;
  1006. goto out;
  1007. }
  1008. out:
  1009. if (val)
  1010. json_decref(val);
  1011. return ret;
  1012. }
  1013. extern bool parse_stratum_response(struct pool *, char *s);
  1014. bool auth_stratum(struct pool *pool)
  1015. {
  1016. json_t *val = NULL, *res_val, *err_val;
  1017. char s[RBUFSIZE], *sret = NULL;
  1018. json_error_t err;
  1019. bool ret = false;
  1020. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1021. pool->rpc_user, pool->rpc_pass);
  1022. if (!stratum_send(pool, s, strlen(s)))
  1023. goto out;
  1024. /* Parse all data in the queue and anything left should be auth */
  1025. while (42) {
  1026. sret = recv_line(pool);
  1027. if (!sret)
  1028. goto out;
  1029. if (parse_method(pool, sret))
  1030. free(sret);
  1031. else
  1032. break;
  1033. }
  1034. val = JSON_LOADS(sret, &err);
  1035. free(sret);
  1036. res_val = json_object_get(val, "result");
  1037. err_val = json_object_get(val, "error");
  1038. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1039. char *ss;
  1040. if (err_val)
  1041. ss = json_dumps(err_val, JSON_INDENT(3));
  1042. else
  1043. ss = strdup("(unknown reason)");
  1044. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1045. free(ss);
  1046. goto out;
  1047. }
  1048. ret = true;
  1049. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1050. out:
  1051. if (val)
  1052. json_decref(val);
  1053. return ret;
  1054. }
  1055. bool initiate_stratum(struct pool *pool)
  1056. {
  1057. json_t *val = NULL, *res_val, *err_val;
  1058. char curl_err_str[CURL_ERROR_SIZE];
  1059. char s[RBUFSIZE], *sret = NULL;
  1060. CURL *curl = NULL;
  1061. json_error_t err;
  1062. bool ret = false;
  1063. mutex_lock(&pool->stratum_lock);
  1064. pool->stratum_active = false;
  1065. if (!pool->stratum_curl) {
  1066. pool->stratum_curl = curl_easy_init();
  1067. if (unlikely(!pool->stratum_curl))
  1068. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1069. }
  1070. mutex_unlock(&pool->stratum_lock);
  1071. curl = pool->stratum_curl;
  1072. /* Create a http url for use with curl */
  1073. memset(s, 0, RBUFSIZE);
  1074. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1075. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1076. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1077. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1078. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1079. curl_easy_setopt(curl, CURLOPT_URL, s);
  1080. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1081. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1082. if (pool->rpc_proxy) {
  1083. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1084. } else if (opt_socks_proxy) {
  1085. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1086. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1087. }
  1088. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1089. if (curl_easy_perform(curl)) {
  1090. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1091. goto out;
  1092. }
  1093. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1094. keep_sockalive(pool->sock);
  1095. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1096. if (!__stratum_send(pool, s, strlen(s))) {
  1097. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1098. goto out;
  1099. }
  1100. if (!sock_full(pool, true)) {
  1101. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1102. goto out;
  1103. }
  1104. sret = recv_line(pool);
  1105. if (!sret)
  1106. goto out;
  1107. val = JSON_LOADS(sret, &err);
  1108. free(sret);
  1109. if (!val) {
  1110. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1111. goto out;
  1112. }
  1113. res_val = json_object_get(val, "result");
  1114. err_val = json_object_get(val, "error");
  1115. if (!res_val || json_is_null(res_val) ||
  1116. (err_val && !json_is_null(err_val))) {
  1117. char *ss;
  1118. if (err_val)
  1119. ss = json_dumps(err_val, JSON_INDENT(3));
  1120. else
  1121. ss = strdup("(unknown reason)");
  1122. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1123. free(ss);
  1124. goto out;
  1125. }
  1126. pool->nonce1 = json_array_string(res_val, 1);
  1127. if (!pool->nonce1) {
  1128. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1129. goto out;
  1130. }
  1131. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1132. if (!pool->n2size) {
  1133. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1134. goto out;
  1135. }
  1136. ret = true;
  1137. out:
  1138. if (val)
  1139. json_decref(val);
  1140. if (ret) {
  1141. if (!pool->stratum_url)
  1142. pool->stratum_url = pool->sockaddr_url;
  1143. pool->stratum_active = true;
  1144. pool->swork.diff = 1;
  1145. if (opt_protocol) {
  1146. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1147. pool->pool_no, pool->nonce1, pool->n2size);
  1148. }
  1149. } else
  1150. applog(LOG_DEBUG, "Initiate stratum failed");
  1151. return ret;
  1152. }
  1153. void suspend_stratum(struct pool *pool)
  1154. {
  1155. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1156. mutex_lock(&pool->stratum_lock);
  1157. pool->stratum_active = false;
  1158. mutex_unlock(&pool->stratum_lock);
  1159. CLOSESOCKET(pool->sock);
  1160. }
  1161. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1162. {
  1163. dev->device_last_not_well = time(NULL);
  1164. dev->device_not_well_reason = reason;
  1165. switch (reason) {
  1166. case REASON_THREAD_FAIL_INIT:
  1167. dev->thread_fail_init_count++;
  1168. break;
  1169. case REASON_THREAD_ZERO_HASH:
  1170. dev->thread_zero_hash_count++;
  1171. break;
  1172. case REASON_THREAD_FAIL_QUEUE:
  1173. dev->thread_fail_queue_count++;
  1174. break;
  1175. case REASON_DEV_SICK_IDLE_60:
  1176. dev->dev_sick_idle_60_count++;
  1177. break;
  1178. case REASON_DEV_DEAD_IDLE_600:
  1179. dev->dev_dead_idle_600_count++;
  1180. break;
  1181. case REASON_DEV_NOSTART:
  1182. dev->dev_nostart_count++;
  1183. break;
  1184. case REASON_DEV_OVER_HEAT:
  1185. dev->dev_over_heat_count++;
  1186. break;
  1187. case REASON_DEV_THERMAL_CUTOFF:
  1188. dev->dev_thermal_cutoff_count++;
  1189. break;
  1190. case REASON_DEV_COMMS_ERROR:
  1191. dev->dev_comms_error_count++;
  1192. break;
  1193. case REASON_DEV_THROTTLE:
  1194. dev->dev_throttle_count++;
  1195. break;
  1196. }
  1197. }
  1198. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1199. void *realloc_strcat(char *ptr, char *s)
  1200. {
  1201. size_t old = strlen(ptr), len = strlen(s);
  1202. char *ret;
  1203. if (!len)
  1204. return ptr;
  1205. len += old + 1;
  1206. if (len % 4)
  1207. len += 4 - (len % 4);
  1208. ret = malloc(len);
  1209. if (unlikely(!ret))
  1210. quit(1, "Failed to malloc in realloc_strcat");
  1211. sprintf(ret, "%s%s", ptr, s);
  1212. free(ptr);
  1213. return ret;
  1214. }
  1215. void RenameThread(const char* name)
  1216. {
  1217. #if defined(PR_SET_NAME)
  1218. // Only the first 15 characters are used (16 - NUL terminator)
  1219. prctl(PR_SET_NAME, name, 0, 0, 0);
  1220. #elif defined(__APPLE__)
  1221. pthread_setname_np(name);
  1222. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1223. pthread_set_name_np(pthread_self(), name);
  1224. #else
  1225. // Prevent warnings for unused parameters...
  1226. (void)name;
  1227. #endif
  1228. }