util.c 40 KB

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