util.c 34 KB

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