util.c 37 KB

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