util.c 55 KB

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