util.c 56 KB

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