util.c 56 KB

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