util.c 42 KB

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