util.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. * Copyright 2012 Giel van Schijndel
  6. * Copyright 2012 Gavin Andresen
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <ctype.h>
  17. #include <stdarg.h>
  18. #include <string.h>
  19. #include <pthread.h>
  20. #include <jansson.h>
  21. #include <curl/curl.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include <unistd.h>
  25. #include <sys/types.h>
  26. #ifdef HAVE_SYS_PRCTL_H
  27. # include <sys/prctl.h>
  28. #endif
  29. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  30. # include <pthread_np.h>
  31. #endif
  32. #ifndef WIN32
  33. # ifdef __linux
  34. # include <sys/prctl.h>
  35. # endif
  36. # include <sys/socket.h>
  37. # include <netinet/in.h>
  38. # include <netinet/tcp.h>
  39. # include <netdb.h>
  40. #else
  41. # include <winsock2.h>
  42. # include <mstcpip.h>
  43. # include <ws2tcpip.h>
  44. #endif
  45. #include "miner.h"
  46. #include "elist.h"
  47. #include "compat.h"
  48. #include "util.h"
  49. bool successful_connect = false;
  50. struct timeval nettime;
  51. struct data_buffer {
  52. void *buf;
  53. size_t len;
  54. curl_socket_t *idlemarker;
  55. };
  56. struct upload_buffer {
  57. const void *buf;
  58. size_t len;
  59. };
  60. struct header_info {
  61. char *lp_path;
  62. int rolltime;
  63. char *reason;
  64. char *stratum_url;
  65. bool hadrolltime;
  66. bool canroll;
  67. bool hadexpire;
  68. };
  69. struct tq_ent {
  70. void *data;
  71. struct list_head q_node;
  72. };
  73. static void databuf_free(struct data_buffer *db)
  74. {
  75. if (!db)
  76. return;
  77. free(db->buf);
  78. #ifdef DEBUG_DATABUF
  79. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  80. #endif
  81. memset(db, 0, sizeof(*db));
  82. }
  83. // aka data_buffer_write
  84. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  85. void *user_data)
  86. {
  87. struct data_buffer *db = user_data;
  88. size_t oldlen, newlen;
  89. oldlen = db->len;
  90. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  91. return 0;
  92. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  93. nmemb = (SIZE_MAX - oldlen) / size;
  94. size_t len = size * nmemb;
  95. void *newmem;
  96. static const unsigned char zero = 0;
  97. if (db->idlemarker) {
  98. const unsigned char *cptr = ptr;
  99. for (size_t i = 0; i < len; ++i)
  100. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  101. *db->idlemarker = CURL_SOCKET_BAD;
  102. db->idlemarker = NULL;
  103. break;
  104. }
  105. }
  106. newlen = oldlen + len;
  107. newmem = realloc(db->buf, newlen + 1);
  108. #ifdef DEBUG_DATABUF
  109. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  110. #endif
  111. if (!newmem)
  112. return 0;
  113. db->buf = newmem;
  114. db->len = newlen;
  115. memcpy(db->buf + oldlen, ptr, len);
  116. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  117. return nmemb;
  118. }
  119. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  120. void *user_data)
  121. {
  122. struct upload_buffer *ub = user_data;
  123. unsigned int len = size * nmemb;
  124. if (len > ub->len)
  125. len = ub->len;
  126. if (len) {
  127. memcpy(ptr, ub->buf, len);
  128. ub->buf += len;
  129. ub->len -= len;
  130. }
  131. return len;
  132. }
  133. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  134. {
  135. struct header_info *hi = user_data;
  136. size_t remlen, slen, ptrlen = size * nmemb;
  137. char *rem, *val = NULL, *key = NULL;
  138. void *tmp;
  139. val = calloc(1, ptrlen);
  140. key = calloc(1, ptrlen);
  141. if (!key || !val)
  142. goto out;
  143. tmp = memchr(ptr, ':', ptrlen);
  144. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  145. goto out;
  146. slen = tmp - ptr;
  147. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  148. goto out;
  149. memcpy(key, ptr, slen); /* store & nul term key */
  150. key[slen] = 0;
  151. rem = ptr + slen + 1; /* trim value's leading whitespace */
  152. remlen = ptrlen - slen - 1;
  153. while ((remlen > 0) && (isspace(*rem))) {
  154. remlen--;
  155. rem++;
  156. }
  157. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  158. val[remlen] = 0;
  159. while ((*val) && (isspace(val[strlen(val) - 1])))
  160. val[strlen(val) - 1] = 0;
  161. if (!*val) /* skip blank value */
  162. goto out;
  163. if (opt_protocol)
  164. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  165. if (!strcasecmp("X-Roll-Ntime", key)) {
  166. hi->hadrolltime = true;
  167. if (!strncasecmp("N", val, 1))
  168. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  169. else {
  170. hi->canroll = true;
  171. /* Check to see if expire= is supported and if not, set
  172. * the rolltime to the default scantime */
  173. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  174. sscanf(val + 7, "%d", &hi->rolltime);
  175. hi->hadexpire = true;
  176. } else
  177. hi->rolltime = opt_scantime;
  178. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  179. }
  180. }
  181. if (!strcasecmp("X-Long-Polling", key)) {
  182. hi->lp_path = val; /* steal memory reference */
  183. val = NULL;
  184. }
  185. if (!strcasecmp("X-Reject-Reason", key)) {
  186. hi->reason = val; /* steal memory reference */
  187. val = NULL;
  188. }
  189. if (!strcasecmp("X-Stratum", key)) {
  190. hi->stratum_url = val;
  191. val = NULL;
  192. }
  193. out:
  194. free(key);
  195. free(val);
  196. return ptrlen;
  197. }
  198. static int keep_sockalive(SOCKETTYPE fd)
  199. {
  200. const int tcp_keepidle = 60;
  201. const int tcp_keepintvl = 60;
  202. const int keepalive = 1;
  203. int ret = 0;
  204. #ifndef WIN32
  205. const int tcp_keepcnt = 5;
  206. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  207. ret = 1;
  208. # ifdef __linux
  209. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  210. ret = 1;
  211. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  212. ret = 1;
  213. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  214. ret = 1;
  215. # endif /* __linux */
  216. # ifdef __APPLE_CC__
  217. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  218. ret = 1;
  219. # endif /* __APPLE_CC__ */
  220. #else /* WIN32 */
  221. const int zero = 0;
  222. struct tcp_keepalive vals;
  223. vals.onoff = 1;
  224. vals.keepalivetime = tcp_keepidle * 1000;
  225. vals.keepaliveinterval = tcp_keepintvl * 1000;
  226. DWORD outputBytes;
  227. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&keepalive, sizeof(keepalive))))
  228. ret = 1;
  229. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  230. ret = 1;
  231. /* Windows happily submits indefinitely to the send buffer blissfully
  232. * unaware nothing is getting there without gracefully failing unless
  233. * we disable the send buffer */
  234. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  235. ret = 1;
  236. #endif /* WIN32 */
  237. return ret;
  238. }
  239. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  240. curlsocktype __maybe_unused purpose)
  241. {
  242. return keep_sockalive(fd);
  243. }
  244. static void last_nettime(struct timeval *last)
  245. {
  246. rd_lock(&netacc_lock);
  247. last->tv_sec = nettime.tv_sec;
  248. last->tv_usec = nettime.tv_usec;
  249. rd_unlock(&netacc_lock);
  250. }
  251. static void set_nettime(void)
  252. {
  253. wr_lock(&netacc_lock);
  254. gettimeofday(&nettime, NULL);
  255. wr_unlock(&netacc_lock);
  256. }
  257. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  258. char *data, size_t size,
  259. void *userdata)
  260. {
  261. struct pool *pool = (struct pool *)userdata;
  262. switch(type) {
  263. case CURLINFO_HEADER_IN:
  264. case CURLINFO_DATA_IN:
  265. case CURLINFO_SSL_DATA_IN:
  266. pool->cgminer_pool_stats.bytes_received += size;
  267. total_bytes_xfer += size;
  268. pool->cgminer_pool_stats.net_bytes_received += size;
  269. break;
  270. case CURLINFO_HEADER_OUT:
  271. case CURLINFO_DATA_OUT:
  272. case CURLINFO_SSL_DATA_OUT:
  273. pool->cgminer_pool_stats.bytes_sent += size;
  274. total_bytes_xfer += size;
  275. pool->cgminer_pool_stats.net_bytes_sent += size;
  276. break;
  277. case CURLINFO_TEXT:
  278. {
  279. if (!opt_protocol)
  280. break;
  281. // data is not null-terminated, so we need to copy and terminate it for applog
  282. char datacp[size + 1];
  283. memcpy(datacp, data, size);
  284. while (likely(size) && unlikely(isspace(datacp[size-1])))
  285. --size;
  286. if (unlikely(!size))
  287. break;
  288. datacp[size] = '\0';
  289. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  290. break;
  291. }
  292. default:
  293. break;
  294. }
  295. return 0;
  296. }
  297. struct json_rpc_call_state {
  298. struct data_buffer all_data;
  299. struct header_info hi;
  300. void *priv;
  301. char curl_err_str[CURL_ERROR_SIZE];
  302. struct curl_slist *headers;
  303. struct upload_buffer upload_data;
  304. struct pool *pool;
  305. };
  306. void json_rpc_call_async(CURL *curl, const char *url,
  307. const char *userpass, const char *rpc_req,
  308. bool longpoll,
  309. struct pool *pool, bool share,
  310. void *priv)
  311. {
  312. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  313. *state = (struct json_rpc_call_state){
  314. .priv = priv,
  315. .pool = pool,
  316. };
  317. long timeout = longpoll ? (60 * 60) : 60;
  318. char len_hdr[64], user_agent_hdr[128];
  319. struct curl_slist *headers = NULL;
  320. if (longpoll)
  321. state->all_data.idlemarker = &pool->lp_socket;
  322. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  323. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  324. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  325. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  326. * to enable it */
  327. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  328. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  329. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  330. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  331. curl_easy_setopt(curl, CURLOPT_URL, url);
  332. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  333. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  334. /* Shares are staggered already and delays in submission can be costly
  335. * so do not delay them */
  336. if (!opt_delaynet || share)
  337. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  338. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  339. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  340. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  341. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  342. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  343. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  344. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  345. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  346. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  347. if (pool->rpc_proxy) {
  348. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  349. } else if (opt_socks_proxy) {
  350. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  351. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  352. }
  353. if (userpass) {
  354. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  355. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  356. }
  357. if (longpoll)
  358. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  359. curl_easy_setopt(curl, CURLOPT_POST, 1);
  360. if (opt_protocol)
  361. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  362. state->upload_data.buf = rpc_req;
  363. state->upload_data.len = strlen(rpc_req);
  364. sprintf(len_hdr, "Content-Length: %lu",
  365. (unsigned long) state->upload_data.len);
  366. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  367. headers = curl_slist_append(headers,
  368. "Content-type: application/json");
  369. headers = curl_slist_append(headers,
  370. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  371. if (longpoll)
  372. headers = curl_slist_append(headers,
  373. "X-Minimum-Wait: 0");
  374. if (likely(global_hashrate)) {
  375. char ghashrate[255];
  376. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  377. headers = curl_slist_append(headers, ghashrate);
  378. }
  379. headers = curl_slist_append(headers, len_hdr);
  380. headers = curl_slist_append(headers, user_agent_hdr);
  381. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  382. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  383. state->headers = headers;
  384. if (opt_delaynet) {
  385. /* Don't delay share submission, but still track the nettime */
  386. if (!share) {
  387. long long now_msecs, last_msecs;
  388. struct timeval now, last;
  389. gettimeofday(&now, NULL);
  390. last_nettime(&last);
  391. now_msecs = (long long)now.tv_sec * 1000;
  392. now_msecs += now.tv_usec / 1000;
  393. last_msecs = (long long)last.tv_sec * 1000;
  394. last_msecs += last.tv_usec / 1000;
  395. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  396. struct timespec rgtp;
  397. rgtp.tv_sec = 0;
  398. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  399. nanosleep(&rgtp, NULL);
  400. }
  401. }
  402. set_nettime();
  403. }
  404. }
  405. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  406. {
  407. struct json_rpc_call_state *state;
  408. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
  409. applog(LOG_ERR, "Failed to get private curl data");
  410. if (out_priv)
  411. *(void**)out_priv = NULL;
  412. goto err_out;
  413. }
  414. if (out_priv)
  415. *(void**)out_priv = state->priv;
  416. json_t *val, *err_val, *res_val;
  417. json_error_t err;
  418. struct pool *pool = state->pool;
  419. bool probing = probe && !pool->probed;
  420. if (rc) {
  421. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  422. goto err_out;
  423. }
  424. if (!state->all_data.buf) {
  425. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  426. goto err_out;
  427. }
  428. pool->cgminer_pool_stats.times_sent++;
  429. pool->cgminer_pool_stats.times_received++;
  430. if (probing) {
  431. pool->probed = true;
  432. /* If X-Long-Polling was found, activate long polling */
  433. if (state->hi.lp_path) {
  434. if (pool->hdr_path != NULL)
  435. free(pool->hdr_path);
  436. pool->hdr_path = state->hi.lp_path;
  437. } else
  438. pool->hdr_path = NULL;
  439. if (state->hi.stratum_url) {
  440. pool->stratum_url = state->hi.stratum_url;
  441. state->hi.stratum_url = NULL;
  442. }
  443. } else {
  444. if (state->hi.lp_path) {
  445. free(state->hi.lp_path);
  446. state->hi.lp_path = NULL;
  447. }
  448. if (state->hi.stratum_url) {
  449. free(state->hi.stratum_url);
  450. state->hi.stratum_url = NULL;
  451. }
  452. }
  453. if (pool->force_rollntime)
  454. {
  455. state->hi.canroll = true;
  456. state->hi.hadexpire = true;
  457. state->hi.rolltime = pool->force_rollntime;
  458. }
  459. if (rolltime)
  460. *rolltime = state->hi.rolltime;
  461. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  462. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  463. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  464. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  465. val = JSON_LOADS(state->all_data.buf, &err);
  466. if (!val) {
  467. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  468. if (opt_protocol)
  469. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  470. goto err_out;
  471. }
  472. if (opt_protocol) {
  473. char *s = json_dumps(val, JSON_INDENT(3));
  474. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  475. free(s);
  476. }
  477. /* JSON-RPC valid response returns a non-null 'result',
  478. * and a null 'error'.
  479. */
  480. res_val = json_object_get(val, "result");
  481. err_val = json_object_get(val, "error");
  482. if (!res_val ||(err_val && !json_is_null(err_val))) {
  483. char *s;
  484. if (err_val)
  485. s = json_dumps(err_val, JSON_INDENT(3));
  486. else
  487. s = strdup("(unknown reason)");
  488. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  489. free(s);
  490. json_decref(val);
  491. goto err_out;
  492. }
  493. if (state->hi.reason) {
  494. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  495. free(state->hi.reason);
  496. state->hi.reason = NULL;
  497. }
  498. successful_connect = true;
  499. databuf_free(&state->all_data);
  500. curl_slist_free_all(state->headers);
  501. curl_easy_reset(curl);
  502. free(state);
  503. return val;
  504. err_out:
  505. databuf_free(&state->all_data);
  506. curl_slist_free_all(state->headers);
  507. curl_easy_reset(curl);
  508. if (!successful_connect)
  509. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  510. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  511. free(state);
  512. return NULL;
  513. }
  514. json_t *json_rpc_call(CURL *curl, const char *url,
  515. const char *userpass, const char *rpc_req,
  516. bool probe, bool longpoll, int *rolltime,
  517. struct pool *pool, bool share)
  518. {
  519. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  520. int rc = curl_easy_perform(curl);
  521. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  522. }
  523. bool our_curl_supports_proxy_uris()
  524. {
  525. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  526. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  527. }
  528. // NOTE: This assumes reference URI is a root
  529. char *absolute_uri(char *uri, const char *ref)
  530. {
  531. if (strstr(uri, "://"))
  532. return strdup(uri);
  533. char *copy_start, *abs;
  534. bool need_slash = false;
  535. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  536. if (ref[strlen(ref) - 1] != '/')
  537. need_slash = true;
  538. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  539. if (!abs) {
  540. applog(LOG_ERR, "Malloc failure in absolute_uri");
  541. return NULL;
  542. }
  543. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  544. return abs;
  545. }
  546. /* Returns a malloced array string of a binary value of arbitrary length. The
  547. * array is rounded up to a 4 byte size to appease architectures that need
  548. * aligned array sizes */
  549. char *bin2hex(const unsigned char *p, size_t len)
  550. {
  551. unsigned int i;
  552. ssize_t slen;
  553. char *s;
  554. slen = len * 2 + 1;
  555. if (slen % 4)
  556. slen += 4 - (slen % 4);
  557. s = calloc(slen, 1);
  558. if (unlikely(!s))
  559. quit(1, "Failed to calloc in bin2hex");
  560. for (i = 0; i < len; i++)
  561. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  562. return s;
  563. }
  564. /* Does the reverse of bin2hex but does not allocate any ram */
  565. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  566. {
  567. bool ret = false;
  568. while (*hexstr && len) {
  569. char hex_byte[4];
  570. unsigned int v;
  571. if (unlikely(!hexstr[1])) {
  572. applog(LOG_ERR, "hex2bin str truncated");
  573. return ret;
  574. }
  575. memset(hex_byte, 0, 4);
  576. hex_byte[0] = hexstr[0];
  577. hex_byte[1] = hexstr[1];
  578. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  579. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  580. return ret;
  581. }
  582. *p = (unsigned char) v;
  583. p++;
  584. hexstr += 2;
  585. len--;
  586. }
  587. if (likely(len == 0 && *hexstr == 0))
  588. ret = true;
  589. return ret;
  590. }
  591. void hash_data(unsigned char *out_hash, const unsigned char *data)
  592. {
  593. unsigned char blkheader[80];
  594. // 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
  595. swap32yes(blkheader, data, 80 / 4);
  596. // double-SHA256 to get the block hash
  597. gen_hash(blkheader, out_hash, 80);
  598. }
  599. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  600. void real_block_target(unsigned char *target, const unsigned char *data)
  601. {
  602. uint8_t targetshift;
  603. if (unlikely(data[72] < 3 || data[72] > 0x20))
  604. {
  605. // Invalid (out of bounds) target
  606. memset(target, 0xff, 32);
  607. return;
  608. }
  609. targetshift = data[72] - 3;
  610. memset(target, 0, targetshift);
  611. target[targetshift++] = data[75];
  612. target[targetshift++] = data[74];
  613. target[targetshift++] = data[73];
  614. memset(&target[targetshift], 0, 0x20 - targetshift);
  615. }
  616. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  617. {
  618. const uint32_t *h32 = (uint32_t*)&hash[0];
  619. const uint32_t *t32 = (uint32_t*)&target[0];
  620. for (int i = 7; i >= 0; --i) {
  621. uint32_t h32i = le32toh(h32[i]);
  622. uint32_t t32i = le32toh(t32[i]);
  623. if (h32i > t32i)
  624. return false;
  625. if (h32i < t32i)
  626. return true;
  627. }
  628. return true;
  629. }
  630. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  631. {
  632. bool rc;
  633. rc = hash_target_check(hash, target);
  634. if (opt_debug) {
  635. unsigned char hash_swap[32], target_swap[32];
  636. char *hash_str, *target_str;
  637. for (int i = 0; i < 32; ++i) {
  638. hash_swap[i] = hash[31-i];
  639. target_swap[i] = target[31-i];
  640. }
  641. hash_str = bin2hex(hash_swap, 32);
  642. target_str = bin2hex(target_swap, 32);
  643. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  644. hash_str,
  645. target_str,
  646. rc ? "YES (hash < target)" :
  647. "no (false positive; hash > target)");
  648. free(hash_str);
  649. free(target_str);
  650. }
  651. return rc;
  652. }
  653. // This operates on a native-endian SHA256 state
  654. // In other words, on little endian platforms, every 4 bytes are in reverse order
  655. bool fulltest(const unsigned char *hash, const unsigned char *target)
  656. {
  657. unsigned char hash2[32];
  658. swap32tobe(hash2, hash, 32 / 4);
  659. return hash_target_check_v(hash2, target);
  660. }
  661. struct thread_q *tq_new(void)
  662. {
  663. struct thread_q *tq;
  664. tq = calloc(1, sizeof(*tq));
  665. if (!tq)
  666. return NULL;
  667. INIT_LIST_HEAD(&tq->q);
  668. pthread_mutex_init(&tq->mutex, NULL);
  669. pthread_cond_init(&tq->cond, NULL);
  670. return tq;
  671. }
  672. void tq_free(struct thread_q *tq)
  673. {
  674. struct tq_ent *ent, *iter;
  675. if (!tq)
  676. return;
  677. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  678. list_del(&ent->q_node);
  679. free(ent);
  680. }
  681. pthread_cond_destroy(&tq->cond);
  682. pthread_mutex_destroy(&tq->mutex);
  683. memset(tq, 0, sizeof(*tq)); /* poison */
  684. free(tq);
  685. }
  686. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  687. {
  688. mutex_lock(&tq->mutex);
  689. tq->frozen = frozen;
  690. pthread_cond_signal(&tq->cond);
  691. mutex_unlock(&tq->mutex);
  692. }
  693. void tq_freeze(struct thread_q *tq)
  694. {
  695. tq_freezethaw(tq, true);
  696. }
  697. void tq_thaw(struct thread_q *tq)
  698. {
  699. tq_freezethaw(tq, false);
  700. }
  701. bool tq_push(struct thread_q *tq, void *data)
  702. {
  703. struct tq_ent *ent;
  704. bool rc = true;
  705. ent = calloc(1, sizeof(*ent));
  706. if (!ent)
  707. return false;
  708. ent->data = data;
  709. INIT_LIST_HEAD(&ent->q_node);
  710. mutex_lock(&tq->mutex);
  711. if (!tq->frozen) {
  712. list_add_tail(&ent->q_node, &tq->q);
  713. } else {
  714. free(ent);
  715. rc = false;
  716. }
  717. pthread_cond_signal(&tq->cond);
  718. mutex_unlock(&tq->mutex);
  719. return rc;
  720. }
  721. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  722. {
  723. struct tq_ent *ent;
  724. void *rval = NULL;
  725. int rc;
  726. mutex_lock(&tq->mutex);
  727. if (!list_empty(&tq->q))
  728. goto pop;
  729. if (abstime)
  730. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  731. else
  732. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  733. if (rc)
  734. goto out;
  735. if (list_empty(&tq->q))
  736. goto out;
  737. pop:
  738. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  739. rval = ent->data;
  740. list_del(&ent->q_node);
  741. free(ent);
  742. out:
  743. mutex_unlock(&tq->mutex);
  744. return rval;
  745. }
  746. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  747. {
  748. return pthread_create(&thr->pth, attr, start, arg);
  749. }
  750. void thr_info_freeze(struct thr_info *thr)
  751. {
  752. struct tq_ent *ent, *iter;
  753. struct thread_q *tq;
  754. if (!thr)
  755. return;
  756. tq = thr->q;
  757. if (!tq)
  758. return;
  759. mutex_lock(&tq->mutex);
  760. tq->frozen = true;
  761. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  762. list_del(&ent->q_node);
  763. free(ent);
  764. }
  765. mutex_unlock(&tq->mutex);
  766. }
  767. void thr_info_cancel(struct thr_info *thr)
  768. {
  769. if (!thr)
  770. return;
  771. if (PTH(thr) != 0L) {
  772. pthread_cancel(thr->pth);
  773. PTH(thr) = 0L;
  774. }
  775. }
  776. #ifndef HAVE_PTHREAD_CANCEL
  777. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  778. enum pthread_cancel_workaround_mode {
  779. PCWM_DEFAULT = 0,
  780. PCWM_TERMINATE = 1,
  781. PCWM_ASYNC = 2,
  782. PCWM_DISABLED = 4,
  783. PCWM_CANCELLED = 8,
  784. };
  785. static pthread_key_t key_pcwm;
  786. struct sigaction pcwm_orig_term_handler;
  787. static
  788. void do_pthread_cancel_exit(int flags)
  789. {
  790. if (!(flags & PCWM_ASYNC))
  791. // NOTE: Logging disables cancel while mutex held, so this is safe
  792. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  793. pthread_exit(PTHREAD_CANCELED);
  794. }
  795. static
  796. void sighandler_pthread_cancel(int sig)
  797. {
  798. int flags = (int)pthread_getspecific(key_pcwm);
  799. if (flags & PCWM_TERMINATE) // Main thread
  800. {
  801. // Restore original handler and call it
  802. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  803. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  804. raise(SIGTERM);
  805. quit(1, "pthread_cancel workaround: Original handler returned");
  806. }
  807. if (flags & PCWM_CANCELLED) // Already pending cancel
  808. return;
  809. if (flags & PCWM_DISABLED)
  810. {
  811. flags |= PCWM_CANCELLED;
  812. if (pthread_setspecific(key_pcwm, (void*)flags))
  813. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  814. return;
  815. }
  816. do_pthread_cancel_exit(flags);
  817. }
  818. int pthread_setcancelstate(int state, int *oldstate)
  819. {
  820. int flags = (int)pthread_getspecific(key_pcwm);
  821. if (oldstate)
  822. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  823. if (state == PTHREAD_CANCEL_DISABLE)
  824. flags |= PCWM_DISABLED;
  825. else
  826. {
  827. if (flags & PCWM_CANCELLED)
  828. do_pthread_cancel_exit(flags);
  829. flags &= ~PCWM_DISABLED;
  830. }
  831. if (pthread_setspecific(key_pcwm, (void*)flags))
  832. return -1;
  833. return 0;
  834. }
  835. int pthread_setcanceltype(int type, int *oldtype)
  836. {
  837. int flags = (int)pthread_getspecific(key_pcwm);
  838. if (oldtype)
  839. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  840. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  841. flags |= PCWM_ASYNC;
  842. else
  843. flags &= ~PCWM_ASYNC;
  844. if (pthread_setspecific(key_pcwm, (void*)flags))
  845. return -1;
  846. return 0;
  847. }
  848. void setup_pthread_cancel_workaround()
  849. {
  850. if (pthread_key_create(&key_pcwm, NULL))
  851. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  852. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  853. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  854. struct sigaction new_sigact = {
  855. .sa_handler = sighandler_pthread_cancel,
  856. };
  857. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  858. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  859. }
  860. #endif
  861. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  862. * on SMP machines */
  863. void nmsleep(unsigned int msecs)
  864. {
  865. struct timespec twait, tleft;
  866. int ret;
  867. ldiv_t d;
  868. d = ldiv(msecs, 1000);
  869. tleft.tv_sec = d.quot;
  870. tleft.tv_nsec = d.rem * 1000000;
  871. do {
  872. twait.tv_sec = tleft.tv_sec;
  873. twait.tv_nsec = tleft.tv_nsec;
  874. ret = nanosleep(&twait, &tleft);
  875. } while (ret == -1 && errno == EINTR);
  876. }
  877. /* Returns the microseconds difference between end and start times as a double */
  878. double us_tdiff(struct timeval *end, struct timeval *start)
  879. {
  880. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  881. }
  882. /* Returns the seconds difference between end and start times as a double */
  883. double tdiff(struct timeval *end, struct timeval *start)
  884. {
  885. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  886. }
  887. bool extract_sockaddr(struct pool *pool, char *url)
  888. {
  889. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  890. char url_address[256], port[6];
  891. int url_len, port_len = 0;
  892. url_begin = strstr(url, "//");
  893. if (!url_begin)
  894. url_begin = url;
  895. else
  896. url_begin += 2;
  897. /* Look for numeric ipv6 entries */
  898. ipv6_begin = strstr(url_begin, "[");
  899. ipv6_end = strstr(url_begin, "]");
  900. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  901. url_end = strstr(ipv6_end, ":");
  902. else
  903. url_end = strstr(url_begin, ":");
  904. if (url_end) {
  905. url_len = url_end - url_begin;
  906. port_len = strlen(url_begin) - url_len - 1;
  907. if (port_len < 1)
  908. return false;
  909. port_start = url_end + 1;
  910. } else
  911. url_len = strlen(url_begin);
  912. if (url_len < 1)
  913. return false;
  914. sprintf(url_address, "%.*s", url_len, url_begin);
  915. if (port_len)
  916. snprintf(port, 6, "%.*s", port_len, port_start);
  917. else
  918. strcpy(port, "80");
  919. free(pool->stratum_port);
  920. pool->stratum_port = strdup(port);
  921. free(pool->sockaddr_url);
  922. pool->sockaddr_url = strdup(url_address);
  923. return true;
  924. }
  925. /* Send a single command across a socket, appending \n to it. This should all
  926. * be done under stratum lock except when first establishing the socket */
  927. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  928. {
  929. SOCKETTYPE sock = pool->sock;
  930. ssize_t ssent = 0;
  931. if (opt_protocol)
  932. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  933. strcat(s, "\n");
  934. len++;
  935. while (len > 0 ) {
  936. struct timeval timeout = {0, 0};
  937. ssize_t sent;
  938. fd_set wd;
  939. FD_ZERO(&wd);
  940. FD_SET(sock, &wd);
  941. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  942. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  943. return false;
  944. }
  945. sent = send(pool->sock, s + ssent, len, 0);
  946. if (sent < 0) {
  947. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  948. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  949. return false;
  950. }
  951. sent = 0;
  952. }
  953. ssent += sent;
  954. len -= sent;
  955. }
  956. pool->cgminer_pool_stats.times_sent++;
  957. pool->cgminer_pool_stats.bytes_sent += ssent;
  958. total_bytes_xfer += ssent;
  959. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  960. return true;
  961. }
  962. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  963. {
  964. bool ret = false;
  965. mutex_lock(&pool->stratum_lock);
  966. if (pool->stratum_active)
  967. ret = __stratum_send(pool, s, len);
  968. else
  969. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  970. mutex_unlock(&pool->stratum_lock);
  971. return ret;
  972. }
  973. static bool socket_full(struct pool *pool, bool wait)
  974. {
  975. SOCKETTYPE sock = pool->sock;
  976. struct timeval timeout;
  977. fd_set rd;
  978. FD_ZERO(&rd);
  979. FD_SET(sock, &rd);
  980. timeout.tv_usec = 0;
  981. if (wait)
  982. timeout.tv_sec = 60;
  983. else
  984. timeout.tv_sec = 0;
  985. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  986. return true;
  987. return false;
  988. }
  989. /* Check to see if Santa's been good to you */
  990. bool sock_full(struct pool *pool)
  991. {
  992. if (strlen(pool->sockbuf))
  993. return true;
  994. return (socket_full(pool, false));
  995. }
  996. static void clear_sockbuf(struct pool *pool)
  997. {
  998. strcpy(pool->sockbuf, "");
  999. }
  1000. static void clear_sock(struct pool *pool)
  1001. {
  1002. ssize_t n;
  1003. mutex_lock(&pool->stratum_lock);
  1004. do {
  1005. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1006. } while (n > 0);
  1007. mutex_unlock(&pool->stratum_lock);
  1008. clear_sockbuf(pool);
  1009. }
  1010. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1011. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1012. * and zeroing the new memory */
  1013. static void recalloc_sock(struct pool *pool, size_t len)
  1014. {
  1015. size_t old, new;
  1016. old = strlen(pool->sockbuf);
  1017. new = old + len + 1;
  1018. if (new < pool->sockbuf_size)
  1019. return;
  1020. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1021. applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1022. pool->sockbuf = realloc(pool->sockbuf, new);
  1023. if (!pool->sockbuf)
  1024. quit(1, "Failed to realloc pool sockbuf in recalloc_sock");
  1025. memset(pool->sockbuf + old, 0, new - old);
  1026. pool->sockbuf_size = new;
  1027. }
  1028. /* Peeks at a socket to find the first end of line and then reads just that
  1029. * from the socket and returns that as a malloced char */
  1030. char *recv_line(struct pool *pool)
  1031. {
  1032. ssize_t len, buflen;
  1033. char *tok, *sret = NULL;
  1034. if (!strstr(pool->sockbuf, "\n")) {
  1035. struct timeval rstart, now;
  1036. gettimeofday(&rstart, NULL);
  1037. if (!socket_full(pool, true)) {
  1038. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1039. goto out;
  1040. }
  1041. mutex_lock(&pool->stratum_lock);
  1042. do {
  1043. char s[RBUFSIZE];
  1044. size_t slen;
  1045. ssize_t n;
  1046. memset(s, 0, RBUFSIZE);
  1047. n = recv(pool->sock, s, RECVSIZE, 0);
  1048. if (!n) {
  1049. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1050. break;
  1051. }
  1052. if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
  1053. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1054. break;
  1055. }
  1056. slen = strlen(s);
  1057. recalloc_sock(pool, slen);
  1058. strcat(pool->sockbuf, s);
  1059. gettimeofday(&now, NULL);
  1060. } while (tdiff(&now, &rstart) < 60 && !strstr(pool->sockbuf, "\n"));
  1061. mutex_unlock(&pool->stratum_lock);
  1062. }
  1063. buflen = strlen(pool->sockbuf);
  1064. tok = strtok(pool->sockbuf, "\n");
  1065. if (!tok) {
  1066. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1067. goto out;
  1068. }
  1069. sret = strdup(tok);
  1070. len = strlen(sret);
  1071. /* Copy what's left in the buffer after the \n, including the
  1072. * terminating \0 */
  1073. if (buflen > len + 1)
  1074. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1075. else
  1076. strcpy(pool->sockbuf, "");
  1077. pool->cgminer_pool_stats.times_received++;
  1078. pool->cgminer_pool_stats.bytes_received += len;
  1079. total_bytes_xfer += len;
  1080. pool->cgminer_pool_stats.net_bytes_received += len;
  1081. out:
  1082. if (!sret)
  1083. clear_sock(pool);
  1084. else if (opt_protocol)
  1085. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1086. return sret;
  1087. }
  1088. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1089. * flag, but this is compatible with 2.0. */
  1090. char *json_dumps_ANY(json_t *json, size_t flags)
  1091. {
  1092. switch (json_typeof(json))
  1093. {
  1094. case JSON_ARRAY:
  1095. case JSON_OBJECT:
  1096. return json_dumps(json, flags);
  1097. default:
  1098. break;
  1099. }
  1100. char *rv;
  1101. #ifdef JSON_ENCODE_ANY
  1102. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1103. if (rv)
  1104. return rv;
  1105. #endif
  1106. json_t *tmp = json_array();
  1107. char *s;
  1108. int i;
  1109. size_t len;
  1110. if (!tmp)
  1111. quit(1, "json_dumps_ANY failed to allocate json array");
  1112. if (json_array_append(tmp, json))
  1113. quit(1, "json_dumps_ANY failed to append temporary array");
  1114. s = json_dumps(tmp, flags);
  1115. if (!s)
  1116. return NULL;
  1117. for (i = 0; s[i] != '['; ++i)
  1118. if (unlikely(!(s[i] && isspace(s[i]))))
  1119. quit(1, "json_dumps_ANY failed to find opening bracket in array dump");
  1120. len = strlen(&s[++i]) - 1;
  1121. if (unlikely(s[i+len] != ']'))
  1122. quit(1, "json_dumps_ANY failed to find closing bracket in array dump");
  1123. rv = malloc(len + 1);
  1124. memcpy(rv, &s[i], len);
  1125. rv[len] = '\0';
  1126. free(s);
  1127. json_decref(tmp);
  1128. return rv;
  1129. }
  1130. /* Extracts a string value from a json array with error checking. To be used
  1131. * when the value of the string returned is only examined and not to be stored.
  1132. * See json_array_string below */
  1133. static char *__json_array_string(json_t *val, unsigned int entry)
  1134. {
  1135. json_t *arr_entry;
  1136. if (json_is_null(val))
  1137. return NULL;
  1138. if (!json_is_array(val))
  1139. return NULL;
  1140. if (entry > json_array_size(val))
  1141. return NULL;
  1142. arr_entry = json_array_get(val, entry);
  1143. if (!json_is_string(arr_entry))
  1144. return NULL;
  1145. return (char *)json_string_value(arr_entry);
  1146. }
  1147. /* Creates a freshly malloced dup of __json_array_string */
  1148. static char *json_array_string(json_t *val, unsigned int entry)
  1149. {
  1150. char *buf = __json_array_string(val, entry);
  1151. if (buf)
  1152. return strdup(buf);
  1153. return NULL;
  1154. }
  1155. void stratum_probe_transparency(struct pool *pool)
  1156. {
  1157. // Request transaction data to discourage pools from doing anything shady
  1158. char s[1024];
  1159. int sLen;
  1160. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1161. pool->swork.job_id,
  1162. pool->swork.job_id);
  1163. stratum_send(pool, s, sLen);
  1164. if ((!pool->swork.opaque) && pool->swork.transparency_time == (time_t)-1)
  1165. pool->swork.transparency_time = time(NULL);
  1166. pool->swork.transparency_probed = true;
  1167. }
  1168. static bool parse_notify(struct pool *pool, json_t *val)
  1169. {
  1170. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1171. bool clean, ret = false;
  1172. int merkles, i;
  1173. json_t *arr;
  1174. arr = json_array_get(val, 4);
  1175. if (!arr || !json_is_array(arr))
  1176. goto out;
  1177. merkles = json_array_size(arr);
  1178. job_id = json_array_string(val, 0);
  1179. prev_hash = json_array_string(val, 1);
  1180. coinbase1 = json_array_string(val, 2);
  1181. coinbase2 = json_array_string(val, 3);
  1182. bbversion = json_array_string(val, 5);
  1183. nbit = json_array_string(val, 6);
  1184. ntime = json_array_string(val, 7);
  1185. clean = json_is_true(json_array_get(val, 8));
  1186. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1187. /* Annoying but we must not leak memory */
  1188. if (job_id)
  1189. free(job_id);
  1190. if (prev_hash)
  1191. free(prev_hash);
  1192. if (coinbase1)
  1193. free(coinbase1);
  1194. if (coinbase2)
  1195. free(coinbase2);
  1196. if (bbversion)
  1197. free(bbversion);
  1198. if (nbit)
  1199. free(nbit);
  1200. if (ntime)
  1201. free(ntime);
  1202. goto out;
  1203. }
  1204. mutex_lock(&pool->pool_lock);
  1205. free(pool->swork.job_id);
  1206. free(pool->swork.prev_hash);
  1207. free(pool->swork.coinbase1);
  1208. free(pool->swork.coinbase2);
  1209. free(pool->swork.bbversion);
  1210. free(pool->swork.nbit);
  1211. free(pool->swork.ntime);
  1212. pool->swork.job_id = job_id;
  1213. pool->swork.prev_hash = prev_hash;
  1214. pool->swork.coinbase1 = coinbase1;
  1215. pool->swork.cb1_len = strlen(coinbase1) / 2;
  1216. pool->swork.coinbase2 = coinbase2;
  1217. pool->swork.cb2_len = strlen(coinbase2) / 2;
  1218. pool->swork.bbversion = bbversion;
  1219. pool->swork.nbit = nbit;
  1220. pool->swork.ntime = ntime;
  1221. pool->submit_old = !clean;
  1222. pool->swork.clean = true;
  1223. pool->swork.cb_len = pool->swork.cb1_len + pool->n1_len + pool->n2size + pool->swork.cb2_len;
  1224. for (i = 0; i < pool->swork.merkles; i++)
  1225. free(pool->swork.merkle[i]);
  1226. if (merkles) {
  1227. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  1228. for (i = 0; i < merkles; i++)
  1229. pool->swork.merkle[i] = json_array_string(arr, i);
  1230. }
  1231. pool->swork.merkles = merkles;
  1232. if (clean)
  1233. pool->nonce2 = 0;
  1234. pool->swork.header_len = strlen(pool->swork.bbversion) +
  1235. strlen(pool->swork.prev_hash) +
  1236. strlen(pool->swork.ntime) +
  1237. strlen(pool->swork.nbit) +
  1238. /* merkle_hash */ 32 +
  1239. /* nonce */ 8 +
  1240. /* workpadding */ 96;
  1241. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1242. align_len(&pool->swork.header_len);
  1243. mutex_unlock(&pool->pool_lock);
  1244. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1245. pool->pool_no, job_id);
  1246. if (opt_protocol) {
  1247. applog(LOG_DEBUG, "job_id: %s", job_id);
  1248. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1249. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1250. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1251. for (i = 0; i < merkles; i++)
  1252. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  1253. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1254. applog(LOG_DEBUG, "nbit: %s", nbit);
  1255. applog(LOG_DEBUG, "ntime: %s", ntime);
  1256. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1257. }
  1258. /* A notify message is the closest stratum gets to a getwork */
  1259. pool->getwork_requested++;
  1260. total_getworks++;
  1261. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || pool->swork.transparency_time != (time_t)-1)
  1262. if (pool->stratum_auth)
  1263. stratum_probe_transparency(pool);
  1264. ret = true;
  1265. out:
  1266. return ret;
  1267. }
  1268. static bool parse_diff(struct pool *pool, json_t *val)
  1269. {
  1270. double diff;
  1271. diff = json_number_value(json_array_get(val, 0));
  1272. if (diff == 0)
  1273. return false;
  1274. mutex_lock(&pool->pool_lock);
  1275. pool->swork.diff = diff;
  1276. mutex_unlock(&pool->pool_lock);
  1277. applog(LOG_DEBUG, "Pool %d stratum bdifficulty set to %f", pool->pool_no, diff);
  1278. return true;
  1279. }
  1280. static bool parse_reconnect(struct pool *pool, json_t *val)
  1281. {
  1282. char *url, *port, address[256];
  1283. memset(address, 0, 255);
  1284. url = (char *)json_string_value(json_array_get(val, 0));
  1285. if (!url)
  1286. url = pool->sockaddr_url;
  1287. port = (char *)json_string_value(json_array_get(val, 1));
  1288. if (!port)
  1289. port = pool->stratum_port;
  1290. sprintf(address, "%s:%s", url, port);
  1291. if (!extract_sockaddr(pool, address))
  1292. return false;
  1293. pool->stratum_url = pool->sockaddr_url;
  1294. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1295. if (!restart_stratum(pool))
  1296. return false;
  1297. return true;
  1298. }
  1299. static bool send_version(struct pool *pool, json_t *val)
  1300. {
  1301. char s[RBUFSIZE], *idstr;
  1302. json_t *id = json_object_get(val, "id");
  1303. if (!(id && !json_is_null(id)))
  1304. return false;
  1305. idstr = json_dumps_ANY(id, 0);
  1306. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1307. free(idstr);
  1308. if (!stratum_send(pool, s, strlen(s)))
  1309. return false;
  1310. return true;
  1311. }
  1312. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  1313. {
  1314. char s[RBUFSIZE], *idstr;
  1315. json_t *id = json_object_get(val, "id");
  1316. char *msg = json_array_string(params, 0);
  1317. if (likely(msg))
  1318. {
  1319. free(pool->admin_msg);
  1320. pool->admin_msg = msg;
  1321. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  1322. }
  1323. if (!(id && !json_is_null(id)))
  1324. return true;
  1325. idstr = json_dumps_ANY(id, 0);
  1326. if (likely(msg))
  1327. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  1328. else
  1329. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  1330. free(idstr);
  1331. if (!stratum_send(pool, s, strlen(s)))
  1332. return false;
  1333. return true;
  1334. }
  1335. bool parse_method(struct pool *pool, char *s)
  1336. {
  1337. json_t *val = NULL, *method, *err_val, *params;
  1338. json_error_t err;
  1339. bool ret = false;
  1340. char *buf;
  1341. if (!s)
  1342. goto out;
  1343. val = JSON_LOADS(s, &err);
  1344. if (!val) {
  1345. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1346. goto out;
  1347. }
  1348. method = json_object_get(val, "method");
  1349. if (!method)
  1350. goto out;
  1351. err_val = json_object_get(val, "error");
  1352. params = json_object_get(val, "params");
  1353. if (err_val && !json_is_null(err_val)) {
  1354. char *ss;
  1355. if (err_val)
  1356. ss = json_dumps(err_val, JSON_INDENT(3));
  1357. else
  1358. ss = strdup("(unknown reason)");
  1359. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1360. free(ss);
  1361. goto out;
  1362. }
  1363. buf = (char *)json_string_value(method);
  1364. if (!buf)
  1365. goto out;
  1366. if (!strncasecmp(buf, "mining.notify", 13)) {
  1367. if (parse_notify(pool, params))
  1368. pool->stratum_notify = ret = true;
  1369. else
  1370. pool->stratum_notify = ret = false;
  1371. goto out;
  1372. }
  1373. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1374. ret = true;
  1375. goto out;
  1376. }
  1377. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1378. ret = true;
  1379. goto out;
  1380. }
  1381. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1382. ret = true;
  1383. goto out;
  1384. }
  1385. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  1386. ret = true;
  1387. goto out;
  1388. }
  1389. out:
  1390. if (val)
  1391. json_decref(val);
  1392. return ret;
  1393. }
  1394. extern bool parse_stratum_response(struct pool *, char *s);
  1395. bool auth_stratum(struct pool *pool)
  1396. {
  1397. json_t *val = NULL, *res_val, *err_val;
  1398. char s[RBUFSIZE], *sret = NULL;
  1399. json_error_t err;
  1400. bool ret = false;
  1401. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1402. pool->rpc_user, pool->rpc_pass);
  1403. if (!stratum_send(pool, s, strlen(s)))
  1404. goto out;
  1405. /* Parse all data in the queue and anything left should be auth */
  1406. while (42) {
  1407. sret = recv_line(pool);
  1408. if (!sret)
  1409. goto out;
  1410. if (parse_method(pool, sret))
  1411. free(sret);
  1412. else
  1413. break;
  1414. }
  1415. val = JSON_LOADS(sret, &err);
  1416. free(sret);
  1417. res_val = json_object_get(val, "result");
  1418. err_val = json_object_get(val, "error");
  1419. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1420. char *ss;
  1421. if (err_val)
  1422. ss = json_dumps(err_val, JSON_INDENT(3));
  1423. else
  1424. ss = strdup("(unknown reason)");
  1425. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1426. free(ss);
  1427. goto out;
  1428. }
  1429. ret = true;
  1430. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1431. pool->probed = true;
  1432. pool->stratum_auth = true;
  1433. successful_connect = true;
  1434. out:
  1435. if (val)
  1436. json_decref(val);
  1437. if (pool->stratum_notify)
  1438. stratum_probe_transparency(pool);
  1439. return ret;
  1440. }
  1441. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1442. {
  1443. struct pool *pool = clientp;
  1444. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1445. pool->sock = sck;
  1446. return sck;
  1447. }
  1448. static bool setup_stratum_curl(struct pool *pool)
  1449. {
  1450. char curl_err_str[CURL_ERROR_SIZE];
  1451. CURL *curl = NULL;
  1452. char s[RBUFSIZE];
  1453. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1454. mutex_lock(&pool->stratum_lock);
  1455. pool->swork.transparency_time = (time_t)-1;
  1456. pool->stratum_active = false;
  1457. pool->stratum_auth = false;
  1458. pool->stratum_notify = false;
  1459. pool->swork.transparency_probed = false;
  1460. if (pool->stratum_curl)
  1461. curl_easy_cleanup(pool->stratum_curl);
  1462. pool->stratum_curl = curl_easy_init();
  1463. if (unlikely(!pool->stratum_curl))
  1464. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1465. if (pool->sockbuf)
  1466. pool->sockbuf[0] = '\0';
  1467. mutex_unlock(&pool->stratum_lock);
  1468. curl = pool->stratum_curl;
  1469. if (!pool->sockbuf) {
  1470. pool->sockbuf = calloc(RBUFSIZE, 1);
  1471. if (!pool->sockbuf)
  1472. quit(1, "Failed to calloc pool sockbuf in initiate_stratum");
  1473. pool->sockbuf_size = RBUFSIZE;
  1474. }
  1475. /* Create a http url for use with curl */
  1476. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1477. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1478. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1479. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1480. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1481. curl_easy_setopt(curl, CURLOPT_URL, s);
  1482. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1483. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1484. * to enable it */
  1485. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  1486. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  1487. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1488. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  1489. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  1490. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  1491. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1492. if (pool->rpc_proxy) {
  1493. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1494. } else if (opt_socks_proxy) {
  1495. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1496. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1497. }
  1498. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1499. pool->sock = INVSOCK;
  1500. if (curl_easy_perform(curl)) {
  1501. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1502. curl_easy_cleanup(curl);
  1503. pool->stratum_curl = NULL;
  1504. return false;
  1505. }
  1506. if (pool->sock == INVSOCK)
  1507. {
  1508. pool->stratum_curl = NULL;
  1509. curl_easy_cleanup(curl);
  1510. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  1511. return false;
  1512. }
  1513. keep_sockalive(pool->sock);
  1514. pool->cgminer_pool_stats.times_sent++;
  1515. pool->cgminer_pool_stats.times_received++;
  1516. return true;
  1517. }
  1518. static char *get_sessionid(json_t *val)
  1519. {
  1520. char *ret = NULL;
  1521. json_t *arr_val;
  1522. int arrsize, i;
  1523. arr_val = json_array_get(val, 0);
  1524. if (!arr_val || !json_is_array(arr_val))
  1525. goto out;
  1526. arrsize = json_array_size(arr_val);
  1527. for (i = 0; i < arrsize; i++) {
  1528. json_t *arr = json_array_get(arr_val, i);
  1529. char *notify;
  1530. if (!arr | !json_is_array(arr))
  1531. break;
  1532. notify = __json_array_string(arr, 0);
  1533. if (!notify)
  1534. continue;
  1535. if (!strncasecmp(notify, "mining.notify", 13)) {
  1536. ret = json_array_string(arr, 1);
  1537. break;
  1538. }
  1539. }
  1540. out:
  1541. return ret;
  1542. }
  1543. bool initiate_stratum(struct pool *pool)
  1544. {
  1545. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1546. bool ret = false, recvd = false, noresume = false;
  1547. json_t *val = NULL, *res_val, *err_val;
  1548. json_error_t err;
  1549. int n2size;
  1550. if (!setup_stratum_curl(pool))
  1551. goto out;
  1552. resend:
  1553. if (!noresume) {
  1554. if (pool->sessionid)
  1555. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1556. else
  1557. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1558. } else
  1559. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1560. if (!__stratum_send(pool, s, strlen(s))) {
  1561. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1562. goto out;
  1563. }
  1564. if (!socket_full(pool, true)) {
  1565. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1566. goto out;
  1567. }
  1568. sret = recv_line(pool);
  1569. if (!sret)
  1570. goto out;
  1571. recvd = true;
  1572. val = JSON_LOADS(sret, &err);
  1573. free(sret);
  1574. if (!val) {
  1575. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1576. goto out;
  1577. }
  1578. res_val = json_object_get(val, "result");
  1579. err_val = json_object_get(val, "error");
  1580. if (!res_val || json_is_null(res_val) ||
  1581. (err_val && !json_is_null(err_val))) {
  1582. char *ss;
  1583. if (err_val)
  1584. ss = json_dumps(err_val, JSON_INDENT(3));
  1585. else
  1586. ss = strdup("(unknown reason)");
  1587. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1588. free(ss);
  1589. goto out;
  1590. }
  1591. sessionid = get_sessionid(res_val);
  1592. if (!sessionid)
  1593. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1594. nonce1 = json_array_string(res_val, 1);
  1595. if (!nonce1) {
  1596. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1597. free(sessionid);
  1598. goto out;
  1599. }
  1600. n2size = json_integer_value(json_array_get(res_val, 2));
  1601. if (!n2size) {
  1602. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1603. free(sessionid);
  1604. free(nonce1);
  1605. goto out;
  1606. }
  1607. mutex_lock(&pool->pool_lock);
  1608. free(pool->sessionid);
  1609. pool->sessionid = sessionid;
  1610. free(pool->nonce1);
  1611. pool->nonce1 = nonce1;
  1612. pool->n1_len = strlen(nonce1) / 2;
  1613. pool->n2size = n2size;
  1614. mutex_unlock(&pool->pool_lock);
  1615. if (sessionid)
  1616. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1617. ret = true;
  1618. out:
  1619. if (val)
  1620. json_decref(val);
  1621. if (ret) {
  1622. if (!pool->stratum_url)
  1623. pool->stratum_url = pool->sockaddr_url;
  1624. pool->stratum_active = true;
  1625. pool->swork.diff = 1;
  1626. if (opt_protocol) {
  1627. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1628. pool->pool_no, pool->nonce1, pool->n2size);
  1629. }
  1630. } else {
  1631. if (recvd && !noresume) {
  1632. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1633. noresume = true;
  1634. goto resend;
  1635. }
  1636. applog(LOG_DEBUG, "Initiate stratum failed");
  1637. if (pool->sock != INVSOCK) {
  1638. shutdown(pool->sock, SHUT_RDWR);
  1639. pool->sock = INVSOCK;
  1640. }
  1641. }
  1642. return ret;
  1643. }
  1644. void suspend_stratum(struct pool *pool)
  1645. {
  1646. clear_sockbuf(pool);
  1647. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1648. mutex_lock(&pool->stratum_lock);
  1649. pool->stratum_active = pool->stratum_notify = false;
  1650. pool->stratum_auth = false;
  1651. curl_easy_cleanup(pool->stratum_curl);
  1652. pool->stratum_curl = NULL;
  1653. pool->sock = INVSOCK;
  1654. mutex_unlock(&pool->stratum_lock);
  1655. }
  1656. bool restart_stratum(struct pool *pool)
  1657. {
  1658. if (pool->stratum_active)
  1659. suspend_stratum(pool);
  1660. if (!initiate_stratum(pool))
  1661. return false;
  1662. if (!auth_stratum(pool))
  1663. return false;
  1664. return true;
  1665. }
  1666. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1667. {
  1668. dev->device_last_not_well = time(NULL);
  1669. dev->device_not_well_reason = reason;
  1670. switch (reason) {
  1671. case REASON_THREAD_FAIL_INIT:
  1672. dev->thread_fail_init_count++;
  1673. break;
  1674. case REASON_THREAD_ZERO_HASH:
  1675. dev->thread_zero_hash_count++;
  1676. break;
  1677. case REASON_THREAD_FAIL_QUEUE:
  1678. dev->thread_fail_queue_count++;
  1679. break;
  1680. case REASON_DEV_SICK_IDLE_60:
  1681. dev->dev_sick_idle_60_count++;
  1682. break;
  1683. case REASON_DEV_DEAD_IDLE_600:
  1684. dev->dev_dead_idle_600_count++;
  1685. break;
  1686. case REASON_DEV_NOSTART:
  1687. dev->dev_nostart_count++;
  1688. break;
  1689. case REASON_DEV_OVER_HEAT:
  1690. dev->dev_over_heat_count++;
  1691. break;
  1692. case REASON_DEV_THERMAL_CUTOFF:
  1693. dev->dev_thermal_cutoff_count++;
  1694. break;
  1695. case REASON_DEV_COMMS_ERROR:
  1696. dev->dev_comms_error_count++;
  1697. break;
  1698. case REASON_DEV_THROTTLE:
  1699. dev->dev_throttle_count++;
  1700. break;
  1701. }
  1702. }
  1703. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1704. void *realloc_strcat(char *ptr, char *s)
  1705. {
  1706. size_t old = strlen(ptr), len = strlen(s);
  1707. char *ret;
  1708. if (!len)
  1709. return ptr;
  1710. len += old + 1;
  1711. align_len(&len);
  1712. ret = malloc(len);
  1713. if (unlikely(!ret))
  1714. quit(1, "Failed to malloc in realloc_strcat");
  1715. sprintf(ret, "%s%s", ptr, s);
  1716. free(ptr);
  1717. return ret;
  1718. }
  1719. static
  1720. bool sanechars[] = {
  1721. false, false, false, false, false, false, false, false,
  1722. false, false, false, false, false, false, false, false,
  1723. false, false, false, false, false, false, false, false,
  1724. false, false, false, false, false, false, false, false,
  1725. false, false, false, false, false, false, false, false,
  1726. false, false, false, false, false, false, false, false,
  1727. true , true , true , true , true , true , true , true ,
  1728. true , true , false, false, false, false, false, false,
  1729. false, true , true , true , true , true , true , true ,
  1730. true , true , true , true , true , true , true , true ,
  1731. true , true , true , true , true , true , true , true ,
  1732. true , true , true , false, false, false, false, false,
  1733. false, true , true , true , true , true , true , true ,
  1734. true , true , true , true , true , true , true , true ,
  1735. true , true , true , true , true , true , true , true ,
  1736. true , true , true , false, false, false, false, false,
  1737. };
  1738. char *sanestr(char *o, char *s)
  1739. {
  1740. char *rv = o;
  1741. bool br = false;
  1742. for ( ; s[0]; ++s)
  1743. {
  1744. if (sanechars[s[0] & 0x7f])
  1745. {
  1746. if (br)
  1747. {
  1748. br = false;
  1749. if (s[0] >= '0' && s[0] <= '9')
  1750. (o++)[0] = '_';
  1751. }
  1752. (o++)[0] = s[0];
  1753. }
  1754. else
  1755. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  1756. br = true;
  1757. }
  1758. o[0] = '\0';
  1759. return rv;
  1760. }
  1761. void RenameThread(const char* name)
  1762. {
  1763. #if defined(PR_SET_NAME)
  1764. // Only the first 15 characters are used (16 - NUL terminator)
  1765. prctl(PR_SET_NAME, name, 0, 0, 0);
  1766. #elif defined(__APPLE__)
  1767. pthread_setname_np(name);
  1768. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1769. pthread_set_name_np(pthread_self(), name);
  1770. #else
  1771. // Prevent warnings for unused parameters...
  1772. (void)name;
  1773. #endif
  1774. }
  1775. #ifdef WIN32
  1776. static const char *WindowsErrorStr(DWORD dwMessageId)
  1777. {
  1778. static LPSTR msg = NULL;
  1779. if (msg)
  1780. LocalFree(msg);
  1781. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, dwMessageId, 0, (LPSTR)&msg, 0, 0))
  1782. return msg;
  1783. static const char fmt[] = "Error #%ld";
  1784. signed long ldMsgId = dwMessageId;
  1785. int sz = snprintf((char*)&sz, 0, fmt, ldMsgId) + 1;
  1786. msg = (LPTSTR)LocalAlloc(LMEM_FIXED, sz);
  1787. sprintf((char*)msg, fmt, ldMsgId);
  1788. return msg;
  1789. }
  1790. #endif
  1791. void notifier_init(notifier_t pipefd)
  1792. {
  1793. #ifdef WIN32
  1794. SOCKET listener, connecter, acceptor;
  1795. listener = socket(AF_INET, SOCK_STREAM, 0);
  1796. if (listener == INVALID_SOCKET)
  1797. quit(1, "Failed to create listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1798. connecter = socket(AF_INET, SOCK_STREAM, 0);
  1799. if (connecter == INVALID_SOCKET)
  1800. quit(1, "Failed to create connect socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1801. struct sockaddr_in inaddr = {
  1802. .sin_family = AF_INET,
  1803. .sin_addr = {
  1804. .s_addr = htonl(INADDR_LOOPBACK),
  1805. },
  1806. .sin_port = 0,
  1807. };
  1808. {
  1809. char reuse = 1;
  1810. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  1811. }
  1812. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  1813. quit(1, "Failed to bind listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1814. socklen_t inaddr_sz = sizeof(inaddr);
  1815. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  1816. quit(1, "Failed to getsockname in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1817. if (listen(listener, 1) == SOCKET_ERROR)
  1818. quit(1, "Failed to listen in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1819. inaddr.sin_family = AF_INET;
  1820. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1821. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  1822. quit(1, "Failed to connect in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1823. acceptor = accept(listener, NULL, NULL);
  1824. if (acceptor == INVALID_SOCKET)
  1825. quit(1, "Failed to accept in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1826. closesocket(listener);
  1827. pipefd[0] = connecter;
  1828. pipefd[1] = acceptor;
  1829. #else
  1830. if (pipe(pipefd))
  1831. quit(1, "Failed to create pipe in create_notifier");
  1832. #endif
  1833. }
  1834. void notifier_wake(notifier_t fd)
  1835. {
  1836. if (fd[1] == INVSOCK)
  1837. return;
  1838. #ifdef WIN32
  1839. (void)send(fd[1], "\0", 1, 0);
  1840. #else
  1841. (void)write(fd[1], "\0", 1);
  1842. #endif
  1843. }
  1844. void notifier_read(notifier_t fd)
  1845. {
  1846. char buf[0x10];
  1847. #ifdef WIN32
  1848. (void)recv(fd[0], buf, sizeof(buf), 0);
  1849. #else
  1850. (void)read(fd[0], buf, sizeof(buf));
  1851. #endif
  1852. }
  1853. void notifier_destroy(notifier_t fd)
  1854. {
  1855. #ifdef WIN32
  1856. closesocket(fd[0]);
  1857. closesocket(fd[1]);
  1858. #else
  1859. close(fd[0]);
  1860. close(fd[1]);
  1861. #endif
  1862. fd[0] = fd[1] = INVSOCK;
  1863. }