util.c 35 KB

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