util.c 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637
  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 <utlist.h>
  49. #include "miner.h"
  50. #include "compat.h"
  51. #include "util.h"
  52. #define DEFAULT_SOCKWAIT 60
  53. bool successful_connect = false;
  54. struct timeval nettime;
  55. struct data_buffer {
  56. void *buf;
  57. size_t len;
  58. curl_socket_t *idlemarker;
  59. };
  60. struct upload_buffer {
  61. const void *buf;
  62. size_t len;
  63. };
  64. struct header_info {
  65. char *lp_path;
  66. int rolltime;
  67. char *reason;
  68. char *stratum_url;
  69. bool hadrolltime;
  70. bool canroll;
  71. bool hadexpire;
  72. };
  73. struct tq_ent {
  74. void *data;
  75. struct tq_ent *prev;
  76. struct tq_ent *next;
  77. };
  78. static void databuf_free(struct data_buffer *db)
  79. {
  80. if (!db)
  81. return;
  82. free(db->buf);
  83. #ifdef DEBUG_DATABUF
  84. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  85. #endif
  86. memset(db, 0, sizeof(*db));
  87. }
  88. // aka data_buffer_write
  89. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  90. void *user_data)
  91. {
  92. struct data_buffer *db = user_data;
  93. size_t oldlen, newlen;
  94. oldlen = db->len;
  95. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  96. return 0;
  97. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  98. nmemb = (SIZE_MAX - oldlen) / size;
  99. size_t len = size * nmemb;
  100. void *newmem;
  101. static const unsigned char zero = 0;
  102. if (db->idlemarker) {
  103. const unsigned char *cptr = ptr;
  104. for (size_t i = 0; i < len; ++i)
  105. if (!(isCspace(cptr[i]) || cptr[i] == '{')) {
  106. *db->idlemarker = CURL_SOCKET_BAD;
  107. db->idlemarker = NULL;
  108. break;
  109. }
  110. }
  111. newlen = oldlen + len;
  112. newmem = realloc(db->buf, newlen + 1);
  113. #ifdef DEBUG_DATABUF
  114. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  115. #endif
  116. if (!newmem)
  117. return 0;
  118. db->buf = newmem;
  119. db->len = newlen;
  120. memcpy(db->buf + oldlen, ptr, len);
  121. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  122. return nmemb;
  123. }
  124. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  125. void *user_data)
  126. {
  127. struct upload_buffer *ub = user_data;
  128. unsigned int len = size * nmemb;
  129. if (len > ub->len)
  130. len = ub->len;
  131. if (len) {
  132. memcpy(ptr, ub->buf, len);
  133. ub->buf += len;
  134. ub->len -= len;
  135. }
  136. return len;
  137. }
  138. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  139. {
  140. struct header_info *hi = user_data;
  141. size_t remlen, slen, ptrlen = size * nmemb;
  142. char *rem, *val = NULL, *key = NULL;
  143. void *tmp;
  144. val = calloc(1, ptrlen);
  145. key = calloc(1, ptrlen);
  146. if (!key || !val)
  147. goto out;
  148. tmp = memchr(ptr, ':', ptrlen);
  149. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  150. goto out;
  151. slen = tmp - ptr;
  152. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  153. goto out;
  154. memcpy(key, ptr, slen); /* store & nul term key */
  155. key[slen] = 0;
  156. rem = ptr + slen + 1; /* trim value's leading whitespace */
  157. remlen = ptrlen - slen - 1;
  158. while ((remlen > 0) && (isCspace(*rem))) {
  159. remlen--;
  160. rem++;
  161. }
  162. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  163. val[remlen] = 0;
  164. while ((*val) && (isCspace(val[strlen(val) - 1])))
  165. val[strlen(val) - 1] = 0;
  166. if (!*val) /* skip blank value */
  167. goto out;
  168. if (opt_protocol)
  169. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  170. if (!strcasecmp("X-Roll-Ntime", key)) {
  171. hi->hadrolltime = true;
  172. if (!strncasecmp("N", val, 1))
  173. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  174. else {
  175. hi->canroll = true;
  176. /* Check to see if expire= is supported and if not, set
  177. * the rolltime to the default scantime */
  178. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  179. sscanf(val + 7, "%d", &hi->rolltime);
  180. hi->hadexpire = true;
  181. } else
  182. hi->rolltime = opt_scantime;
  183. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  184. }
  185. }
  186. if (!strcasecmp("X-Long-Polling", key)) {
  187. hi->lp_path = val; /* steal memory reference */
  188. val = NULL;
  189. }
  190. if (!strcasecmp("X-Reject-Reason", key)) {
  191. hi->reason = val; /* steal memory reference */
  192. val = NULL;
  193. }
  194. if (!strcasecmp("X-Stratum", key)) {
  195. hi->stratum_url = val;
  196. val = NULL;
  197. }
  198. out:
  199. free(key);
  200. free(val);
  201. return ptrlen;
  202. }
  203. static int keep_sockalive(SOCKETTYPE fd)
  204. {
  205. const int tcp_one = 1;
  206. const int tcp_keepidle = 45;
  207. const int tcp_keepintvl = 30;
  208. int ret = 0;
  209. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one))))
  210. ret = 1;
  211. #ifndef WIN32
  212. int flags = fcntl(fd, F_GETFL, 0);
  213. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  214. #else
  215. u_long flags = 1;
  216. ioctlsocket(fd, FIONBIO, &flags);
  217. #endif
  218. if (!opt_delaynet)
  219. #ifndef __linux
  220. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  221. #else /* __linux */
  222. if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  223. #endif /* __linux */
  224. ret = 1;
  225. #ifdef __linux
  226. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one))))
  227. ret = 1;
  228. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  229. ret = 1;
  230. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  231. ret = 1;
  232. #endif /* __linux */
  233. #ifdef __APPLE_CC__
  234. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  235. ret = 1;
  236. #endif /* __APPLE_CC__ */
  237. #ifdef WIN32
  238. const int zero = 0;
  239. struct tcp_keepalive vals;
  240. vals.onoff = 1;
  241. vals.keepalivetime = tcp_keepidle * 1000;
  242. vals.keepaliveinterval = tcp_keepintvl * 1000;
  243. DWORD outputBytes;
  244. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  245. ret = 1;
  246. /* Windows happily submits indefinitely to the send buffer blissfully
  247. * unaware nothing is getting there without gracefully failing unless
  248. * we disable the send buffer */
  249. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  250. ret = 1;
  251. #endif /* WIN32 */
  252. return ret;
  253. }
  254. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  255. curlsocktype __maybe_unused purpose)
  256. {
  257. return keep_sockalive(fd);
  258. }
  259. static void last_nettime(struct timeval *last)
  260. {
  261. rd_lock(&netacc_lock);
  262. last->tv_sec = nettime.tv_sec;
  263. last->tv_usec = nettime.tv_usec;
  264. rd_unlock(&netacc_lock);
  265. }
  266. static void set_nettime(void)
  267. {
  268. wr_lock(&netacc_lock);
  269. cgtime(&nettime);
  270. wr_unlock(&netacc_lock);
  271. }
  272. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  273. char *data, size_t size,
  274. void *userdata)
  275. {
  276. struct pool *pool = (struct pool *)userdata;
  277. switch(type) {
  278. case CURLINFO_HEADER_IN:
  279. case CURLINFO_DATA_IN:
  280. case CURLINFO_SSL_DATA_IN:
  281. pool->cgminer_pool_stats.bytes_received += size;
  282. total_bytes_rcvd += size;
  283. pool->cgminer_pool_stats.net_bytes_received += size;
  284. break;
  285. case CURLINFO_HEADER_OUT:
  286. case CURLINFO_DATA_OUT:
  287. case CURLINFO_SSL_DATA_OUT:
  288. pool->cgminer_pool_stats.bytes_sent += size;
  289. total_bytes_sent += size;
  290. pool->cgminer_pool_stats.net_bytes_sent += size;
  291. break;
  292. case CURLINFO_TEXT:
  293. {
  294. if (!opt_protocol)
  295. break;
  296. // data is not null-terminated, so we need to copy and terminate it for applog
  297. char datacp[size + 1];
  298. memcpy(datacp, data, size);
  299. while (likely(size) && unlikely(isCspace(datacp[size-1])))
  300. --size;
  301. if (unlikely(!size))
  302. break;
  303. datacp[size] = '\0';
  304. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  305. break;
  306. }
  307. default:
  308. break;
  309. }
  310. return 0;
  311. }
  312. struct json_rpc_call_state {
  313. struct data_buffer all_data;
  314. struct header_info hi;
  315. void *priv;
  316. char curl_err_str[CURL_ERROR_SIZE];
  317. struct curl_slist *headers;
  318. struct upload_buffer upload_data;
  319. struct pool *pool;
  320. };
  321. void json_rpc_call_async(CURL *curl, const char *url,
  322. const char *userpass, const char *rpc_req,
  323. bool longpoll,
  324. struct pool *pool, bool share,
  325. void *priv)
  326. {
  327. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  328. *state = (struct json_rpc_call_state){
  329. .priv = priv,
  330. .pool = pool,
  331. };
  332. long timeout = longpoll ? (60 * 60) : 60;
  333. char len_hdr[64], user_agent_hdr[128];
  334. struct curl_slist *headers = NULL;
  335. if (longpoll)
  336. state->all_data.idlemarker = &pool->lp_socket;
  337. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  338. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  339. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  340. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  341. * to enable it */
  342. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  343. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  344. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  345. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  346. curl_easy_setopt(curl, CURLOPT_URL, url);
  347. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  348. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  349. /* Shares are staggered already and delays in submission can be costly
  350. * so do not delay them */
  351. if (!opt_delaynet || share)
  352. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  353. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  354. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  355. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  356. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  357. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  358. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  359. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  360. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  361. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  362. if (pool->rpc_proxy) {
  363. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  364. } else if (opt_socks_proxy) {
  365. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  366. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  367. }
  368. if (userpass) {
  369. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  370. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  371. }
  372. if (longpoll)
  373. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  374. curl_easy_setopt(curl, CURLOPT_POST, 1);
  375. if (opt_protocol)
  376. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  377. state->upload_data.buf = rpc_req;
  378. state->upload_data.len = strlen(rpc_req);
  379. sprintf(len_hdr, "Content-Length: %lu",
  380. (unsigned long) state->upload_data.len);
  381. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  382. headers = curl_slist_append(headers,
  383. "Content-type: application/json");
  384. headers = curl_slist_append(headers,
  385. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  386. if (longpoll)
  387. headers = curl_slist_append(headers,
  388. "X-Minimum-Wait: 0");
  389. if (likely(global_hashrate)) {
  390. char ghashrate[255];
  391. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  392. headers = curl_slist_append(headers, ghashrate);
  393. }
  394. headers = curl_slist_append(headers, len_hdr);
  395. headers = curl_slist_append(headers, user_agent_hdr);
  396. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  397. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  398. state->headers = headers;
  399. if (opt_delaynet) {
  400. /* Don't delay share submission, but still track the nettime */
  401. if (!share) {
  402. long long now_msecs, last_msecs;
  403. struct timeval now, last;
  404. cgtime(&now);
  405. last_nettime(&last);
  406. now_msecs = (long long)now.tv_sec * 1000;
  407. now_msecs += now.tv_usec / 1000;
  408. last_msecs = (long long)last.tv_sec * 1000;
  409. last_msecs += last.tv_usec / 1000;
  410. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  411. struct timespec rgtp;
  412. rgtp.tv_sec = 0;
  413. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  414. nanosleep(&rgtp, NULL);
  415. }
  416. }
  417. set_nettime();
  418. }
  419. }
  420. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  421. {
  422. struct json_rpc_call_state *state;
  423. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
  424. applog(LOG_ERR, "Failed to get private curl data");
  425. if (out_priv)
  426. *(void**)out_priv = NULL;
  427. goto err_out;
  428. }
  429. if (out_priv)
  430. *(void**)out_priv = state->priv;
  431. json_t *val, *err_val, *res_val;
  432. json_error_t err;
  433. struct pool *pool = state->pool;
  434. bool probing = probe && !pool->probed;
  435. if (rc) {
  436. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  437. goto err_out;
  438. }
  439. if (!state->all_data.buf) {
  440. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  441. goto err_out;
  442. }
  443. pool->cgminer_pool_stats.times_sent++;
  444. pool->cgminer_pool_stats.times_received++;
  445. if (probing) {
  446. pool->probed = true;
  447. /* If X-Long-Polling was found, activate long polling */
  448. if (state->hi.lp_path) {
  449. if (pool->hdr_path != NULL)
  450. free(pool->hdr_path);
  451. pool->hdr_path = state->hi.lp_path;
  452. } else
  453. pool->hdr_path = NULL;
  454. if (state->hi.stratum_url) {
  455. pool->stratum_url = state->hi.stratum_url;
  456. state->hi.stratum_url = NULL;
  457. }
  458. } else {
  459. if (state->hi.lp_path) {
  460. free(state->hi.lp_path);
  461. state->hi.lp_path = NULL;
  462. }
  463. if (state->hi.stratum_url) {
  464. free(state->hi.stratum_url);
  465. state->hi.stratum_url = NULL;
  466. }
  467. }
  468. if (pool->force_rollntime)
  469. {
  470. state->hi.canroll = true;
  471. state->hi.hadexpire = true;
  472. state->hi.rolltime = pool->force_rollntime;
  473. }
  474. if (rolltime)
  475. *rolltime = state->hi.rolltime;
  476. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  477. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  478. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  479. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  480. val = JSON_LOADS(state->all_data.buf, &err);
  481. if (!val) {
  482. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  483. if (opt_protocol)
  484. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  485. goto err_out;
  486. }
  487. if (opt_protocol) {
  488. char *s = json_dumps(val, JSON_INDENT(3));
  489. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  490. free(s);
  491. }
  492. /* JSON-RPC valid response returns a non-null 'result',
  493. * and a null 'error'.
  494. */
  495. res_val = json_object_get(val, "result");
  496. err_val = json_object_get(val, "error");
  497. if (!res_val ||(err_val && !json_is_null(err_val))) {
  498. char *s;
  499. if (err_val)
  500. s = json_dumps(err_val, JSON_INDENT(3));
  501. else
  502. s = strdup("(unknown reason)");
  503. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  504. free(s);
  505. json_decref(val);
  506. goto err_out;
  507. }
  508. if (state->hi.reason) {
  509. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  510. free(state->hi.reason);
  511. state->hi.reason = NULL;
  512. }
  513. successful_connect = true;
  514. databuf_free(&state->all_data);
  515. curl_slist_free_all(state->headers);
  516. curl_easy_reset(curl);
  517. free(state);
  518. return val;
  519. err_out:
  520. databuf_free(&state->all_data);
  521. curl_slist_free_all(state->headers);
  522. curl_easy_reset(curl);
  523. if (!successful_connect)
  524. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  525. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  526. free(state);
  527. return NULL;
  528. }
  529. json_t *json_rpc_call(CURL *curl, const char *url,
  530. const char *userpass, const char *rpc_req,
  531. bool probe, bool longpoll, int *rolltime,
  532. struct pool *pool, bool share)
  533. {
  534. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  535. int rc = curl_easy_perform(curl);
  536. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  537. }
  538. bool our_curl_supports_proxy_uris()
  539. {
  540. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  541. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  542. }
  543. // NOTE: This assumes reference URI is a root
  544. char *absolute_uri(char *uri, const char *ref)
  545. {
  546. if (strstr(uri, "://"))
  547. return strdup(uri);
  548. char *copy_start, *abs;
  549. bool need_slash = false;
  550. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  551. if (ref[strlen(ref) - 1] != '/')
  552. need_slash = true;
  553. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  554. if (!abs) {
  555. applog(LOG_ERR, "Malloc failure in absolute_uri");
  556. return NULL;
  557. }
  558. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  559. return abs;
  560. }
  561. static const char _hexchars[0x10] = "0123456789abcdef";
  562. void bin2hex(char *out, const void *in, size_t len)
  563. {
  564. const unsigned char *p = in;
  565. while (len--)
  566. {
  567. (out++)[0] = _hexchars[p[0] >> 4];
  568. (out++)[0] = _hexchars[p[0] & 0xf];
  569. ++p;
  570. }
  571. out[0] = '\0';
  572. }
  573. static inline
  574. int _hex2bin_char(const char c)
  575. {
  576. if (c >= '0' && c <= '9')
  577. return c - '0';
  578. if (c >= 'a' && c <= 'f')
  579. return (c - 'a') + 10;
  580. if (c >= 'A' && c <= 'F')
  581. return (c - 'A') + 10;
  582. return -1;
  583. }
  584. /* Does the reverse of bin2hex but does not allocate any ram */
  585. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  586. {
  587. int n, o;
  588. while (len--)
  589. {
  590. n = _hex2bin_char((hexstr++)[0]);
  591. if (unlikely(n == -1))
  592. {
  593. badchar:
  594. if (!hexstr[-1])
  595. applog(LOG_ERR, "hex2bin: str truncated");
  596. else
  597. applog(LOG_ERR, "hex2bin: invalid character 0x%02x", (int)hexstr[-1]);
  598. return false;
  599. }
  600. o = _hex2bin_char((hexstr++)[0]);
  601. if (unlikely(o == -1))
  602. goto badchar;
  603. (p++)[0] = (n << 4) | o;
  604. }
  605. return likely(!hexstr[0]);
  606. }
  607. void hash_data(unsigned char *out_hash, const unsigned char *data)
  608. {
  609. unsigned char blkheader[80];
  610. // 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
  611. swap32yes(blkheader, data, 80 / 4);
  612. // double-SHA256 to get the block hash
  613. gen_hash(blkheader, out_hash, 80);
  614. }
  615. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  616. void real_block_target(unsigned char *target, const unsigned char *data)
  617. {
  618. uint8_t targetshift;
  619. if (unlikely(data[72] < 3 || data[72] > 0x20))
  620. {
  621. // Invalid (out of bounds) target
  622. memset(target, 0xff, 32);
  623. return;
  624. }
  625. targetshift = data[72] - 3;
  626. memset(target, 0, targetshift);
  627. target[targetshift++] = data[75];
  628. target[targetshift++] = data[74];
  629. target[targetshift++] = data[73];
  630. memset(&target[targetshift], 0, 0x20 - targetshift);
  631. }
  632. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  633. {
  634. const uint32_t *h32 = (uint32_t*)&hash[0];
  635. const uint32_t *t32 = (uint32_t*)&target[0];
  636. for (int i = 7; i >= 0; --i) {
  637. uint32_t h32i = le32toh(h32[i]);
  638. uint32_t t32i = le32toh(t32[i]);
  639. if (h32i > t32i)
  640. return false;
  641. if (h32i < t32i)
  642. return true;
  643. }
  644. return true;
  645. }
  646. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  647. {
  648. bool rc;
  649. rc = hash_target_check(hash, target);
  650. if (opt_debug) {
  651. unsigned char hash_swap[32], target_swap[32];
  652. char hash_str[65];
  653. char target_str[65];
  654. for (int i = 0; i < 32; ++i) {
  655. hash_swap[i] = hash[31-i];
  656. target_swap[i] = target[31-i];
  657. }
  658. bin2hex(hash_str, hash_swap, 32);
  659. bin2hex(target_str, target_swap, 32);
  660. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  661. hash_str,
  662. target_str,
  663. rc ? "YES (hash <= target)" :
  664. "no (false positive; hash > target)");
  665. }
  666. return rc;
  667. }
  668. // This operates on a native-endian SHA256 state
  669. // In other words, on little endian platforms, every 4 bytes are in reverse order
  670. bool fulltest(const unsigned char *hash, const unsigned char *target)
  671. {
  672. unsigned char hash2[32];
  673. swap32tobe(hash2, hash, 32 / 4);
  674. return hash_target_check_v(hash2, target);
  675. }
  676. struct thread_q *tq_new(void)
  677. {
  678. struct thread_q *tq;
  679. tq = calloc(1, sizeof(*tq));
  680. if (!tq)
  681. return NULL;
  682. pthread_mutex_init(&tq->mutex, NULL);
  683. pthread_cond_init(&tq->cond, NULL);
  684. return tq;
  685. }
  686. void tq_free(struct thread_q *tq)
  687. {
  688. struct tq_ent *ent, *iter;
  689. if (!tq)
  690. return;
  691. DL_FOREACH_SAFE(tq->q, ent, iter) {
  692. DL_DELETE(tq->q, ent);
  693. free(ent);
  694. }
  695. pthread_cond_destroy(&tq->cond);
  696. pthread_mutex_destroy(&tq->mutex);
  697. memset(tq, 0, sizeof(*tq)); /* poison */
  698. free(tq);
  699. }
  700. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  701. {
  702. mutex_lock(&tq->mutex);
  703. tq->frozen = frozen;
  704. pthread_cond_signal(&tq->cond);
  705. mutex_unlock(&tq->mutex);
  706. }
  707. void tq_freeze(struct thread_q *tq)
  708. {
  709. tq_freezethaw(tq, true);
  710. }
  711. void tq_thaw(struct thread_q *tq)
  712. {
  713. tq_freezethaw(tq, false);
  714. }
  715. bool tq_push(struct thread_q *tq, void *data)
  716. {
  717. struct tq_ent *ent;
  718. bool rc = true;
  719. ent = calloc(1, sizeof(*ent));
  720. if (!ent)
  721. return false;
  722. ent->data = data;
  723. mutex_lock(&tq->mutex);
  724. if (!tq->frozen) {
  725. DL_APPEND(tq->q, ent);
  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 (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 (!tq->q)
  749. goto out;
  750. pop:
  751. ent = tq->q;
  752. rval = ent->data;
  753. DL_DELETE(tq->q, ent);
  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. DL_FOREACH_SAFE(tq->q, ent, iter) {
  778. DL_DELETE(tq->q, ent);
  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. /* Same for usecs */
  906. void nusleep(unsigned int usecs)
  907. {
  908. struct timespec twait, tleft;
  909. int ret;
  910. ldiv_t d;
  911. #ifdef WIN32
  912. timeBeginPeriod(1);
  913. #endif
  914. d = ldiv(usecs, 1000000);
  915. tleft.tv_sec = d.quot;
  916. tleft.tv_nsec = d.rem * 1000;
  917. do {
  918. twait.tv_sec = tleft.tv_sec;
  919. twait.tv_nsec = tleft.tv_nsec;
  920. ret = nanosleep(&twait, &tleft);
  921. } while (ret == -1 && errno == EINTR);
  922. #ifdef WIN32
  923. timeEndPeriod(1);
  924. #endif
  925. }
  926. static
  927. void _now_gettimeofday(struct timeval *tv)
  928. {
  929. #ifdef WIN32
  930. // Windows' default resolution is only 15ms. This requests 1ms.
  931. timeBeginPeriod(1);
  932. #endif
  933. gettimeofday(tv, NULL);
  934. #ifdef WIN32
  935. timeEndPeriod(1);
  936. #endif
  937. }
  938. #ifdef HAVE_POOR_GETTIMEOFDAY
  939. static struct timeval tv_timeofday_offset;
  940. static struct timeval _tv_timeofday_lastchecked;
  941. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  942. static
  943. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  944. {
  945. struct timeval actual, delta;
  946. timeradd(expected, &tv_timeofday_offset, expected);
  947. _now_gettimeofday(&actual);
  948. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  949. // Within reason - no change necessary
  950. return;
  951. timersub(&actual, expected, &delta);
  952. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  953. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  954. *expected = actual;
  955. }
  956. void bfg_gettimeofday(struct timeval *out)
  957. {
  958. char buf[64] = "";
  959. timer_set_now(out);
  960. mutex_lock(&_tv_timeofday_mutex);
  961. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  962. bfg_calibrate_timeofday(out, buf);
  963. else
  964. timeradd(out, &tv_timeofday_offset, out);
  965. mutex_unlock(&_tv_timeofday_mutex);
  966. if (unlikely(buf[0]))
  967. applog(LOG_WARNING, "%s", buf);
  968. }
  969. #endif
  970. #ifdef WIN32
  971. static LARGE_INTEGER _perffreq;
  972. static
  973. void _now_queryperformancecounter(struct timeval *tv)
  974. {
  975. LARGE_INTEGER now;
  976. if (unlikely(!QueryPerformanceCounter(&now)))
  977. quit(1, "QueryPerformanceCounter failed");
  978. *tv = (struct timeval){
  979. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  980. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  981. };
  982. }
  983. #endif
  984. static
  985. void _now_is_not_set(__maybe_unused struct timeval *tv)
  986. {
  987. // Might be unclean to swap algorithms after getting a timer
  988. quit(1, "timer_set_now called before bfg_init_time");
  989. }
  990. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  991. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  992. static clockid_t bfg_timer_clk;
  993. static
  994. void _now_clock_gettime(struct timeval *tv)
  995. {
  996. struct timespec ts;
  997. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  998. quit(1, "clock_gettime failed");
  999. *tv = (struct timeval){
  1000. .tv_sec = ts.tv_sec,
  1001. .tv_usec = ts.tv_nsec / 1000,
  1002. };
  1003. }
  1004. static
  1005. bool _bfg_try_clock_gettime(clockid_t clk)
  1006. {
  1007. struct timespec ts;
  1008. if (clock_gettime(clk, &ts))
  1009. return false;
  1010. bfg_timer_clk = clk;
  1011. timer_set_now = _now_clock_gettime;
  1012. return true;
  1013. }
  1014. #endif
  1015. void bfg_init_time()
  1016. {
  1017. if (timer_set_now != _now_is_not_set)
  1018. return;
  1019. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1020. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1021. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1022. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1023. else
  1024. #endif
  1025. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1026. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1027. else
  1028. #endif
  1029. #ifdef WIN32
  1030. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1031. {
  1032. timer_set_now = _now_queryperformancecounter;
  1033. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1034. }
  1035. else
  1036. #endif
  1037. {
  1038. timer_set_now = _now_gettimeofday;
  1039. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1040. }
  1041. #ifdef HAVE_POOR_GETTIMEOFDAY
  1042. char buf[64] = "";
  1043. struct timeval tv;
  1044. timer_set_now(&tv);
  1045. bfg_calibrate_timeofday(&tv, buf);
  1046. applog(LOG_DEBUG, "%s", buf);
  1047. #endif
  1048. }
  1049. void subtime(struct timeval *a, struct timeval *b)
  1050. {
  1051. timersub(a, b, b);
  1052. }
  1053. void addtime(struct timeval *a, struct timeval *b)
  1054. {
  1055. timeradd(a, b, b);
  1056. }
  1057. bool time_more(struct timeval *a, struct timeval *b)
  1058. {
  1059. return timercmp(a, b, >);
  1060. }
  1061. bool time_less(struct timeval *a, struct timeval *b)
  1062. {
  1063. return timercmp(a, b, <);
  1064. }
  1065. void copy_time(struct timeval *dest, const struct timeval *src)
  1066. {
  1067. memcpy(dest, src, sizeof(struct timeval));
  1068. }
  1069. /* Returns the microseconds difference between end and start times as a double */
  1070. double us_tdiff(struct timeval *end, struct timeval *start)
  1071. {
  1072. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1073. }
  1074. /* Returns the seconds difference between end and start times as a double */
  1075. double tdiff(struct timeval *end, struct timeval *start)
  1076. {
  1077. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1078. }
  1079. bool extract_sockaddr(struct pool *pool, char *url)
  1080. {
  1081. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1082. char url_address[256], port[6];
  1083. int url_len, port_len = 0;
  1084. url_begin = strstr(url, "//");
  1085. if (!url_begin)
  1086. url_begin = url;
  1087. else
  1088. url_begin += 2;
  1089. /* Look for numeric ipv6 entries */
  1090. ipv6_begin = strstr(url_begin, "[");
  1091. ipv6_end = strstr(url_begin, "]");
  1092. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1093. url_end = strstr(ipv6_end, ":");
  1094. else
  1095. url_end = strstr(url_begin, ":");
  1096. if (url_end) {
  1097. url_len = url_end - url_begin;
  1098. port_len = strlen(url_begin) - url_len - 1;
  1099. if (port_len < 1)
  1100. return false;
  1101. port_start = url_end + 1;
  1102. } else
  1103. url_len = strlen(url_begin);
  1104. if (url_len < 1)
  1105. return false;
  1106. sprintf(url_address, "%.*s", url_len, url_begin);
  1107. if (port_len)
  1108. snprintf(port, 6, "%.*s", port_len, port_start);
  1109. else
  1110. strcpy(port, "80");
  1111. free(pool->stratum_port);
  1112. pool->stratum_port = strdup(port);
  1113. free(pool->sockaddr_url);
  1114. pool->sockaddr_url = strdup(url_address);
  1115. return true;
  1116. }
  1117. enum send_ret {
  1118. SEND_OK,
  1119. SEND_SELECTFAIL,
  1120. SEND_SENDFAIL,
  1121. SEND_INACTIVE
  1122. };
  1123. /* Send a single command across a socket, appending \n to it. This should all
  1124. * be done under stratum lock except when first establishing the socket */
  1125. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1126. {
  1127. SOCKETTYPE sock = pool->sock;
  1128. ssize_t ssent = 0;
  1129. strcat(s, "\n");
  1130. len++;
  1131. while (len > 0 ) {
  1132. struct timeval timeout = {1, 0};
  1133. ssize_t sent;
  1134. fd_set wd;
  1135. FD_ZERO(&wd);
  1136. FD_SET(sock, &wd);
  1137. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  1138. return SEND_SELECTFAIL;
  1139. #ifdef __APPLE__
  1140. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1141. #elif WIN32
  1142. sent = send(pool->sock, s + ssent, len, 0);
  1143. #else
  1144. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1145. #endif
  1146. if (sent < 0) {
  1147. if (!sock_blocks())
  1148. return SEND_SENDFAIL;
  1149. sent = 0;
  1150. }
  1151. ssent += sent;
  1152. len -= sent;
  1153. }
  1154. pool->cgminer_pool_stats.times_sent++;
  1155. pool->cgminer_pool_stats.bytes_sent += ssent;
  1156. total_bytes_sent += ssent;
  1157. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1158. return SEND_OK;
  1159. }
  1160. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1161. {
  1162. enum send_ret ret = SEND_INACTIVE;
  1163. if (opt_protocol)
  1164. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1165. mutex_lock(&pool->stratum_lock);
  1166. if (pool->stratum_active || force)
  1167. ret = __stratum_send(pool, s, len);
  1168. mutex_unlock(&pool->stratum_lock);
  1169. /* This is to avoid doing applog under stratum_lock */
  1170. switch (ret) {
  1171. default:
  1172. case SEND_OK:
  1173. break;
  1174. case SEND_SELECTFAIL:
  1175. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1176. suspend_stratum(pool);
  1177. break;
  1178. case SEND_SENDFAIL:
  1179. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1180. suspend_stratum(pool);
  1181. break;
  1182. case SEND_INACTIVE:
  1183. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1184. break;
  1185. }
  1186. return (ret == SEND_OK);
  1187. }
  1188. static bool socket_full(struct pool *pool, int wait)
  1189. {
  1190. SOCKETTYPE sock = pool->sock;
  1191. struct timeval timeout;
  1192. fd_set rd;
  1193. if (unlikely(wait < 0))
  1194. wait = 0;
  1195. FD_ZERO(&rd);
  1196. FD_SET(sock, &rd);
  1197. timeout.tv_usec = 0;
  1198. timeout.tv_sec = wait;
  1199. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1200. return true;
  1201. return false;
  1202. }
  1203. /* Check to see if Santa's been good to you */
  1204. bool sock_full(struct pool *pool)
  1205. {
  1206. if (strlen(pool->sockbuf))
  1207. return true;
  1208. return (socket_full(pool, 0));
  1209. }
  1210. static void clear_sockbuf(struct pool *pool)
  1211. {
  1212. strcpy(pool->sockbuf, "");
  1213. }
  1214. static void clear_sock(struct pool *pool)
  1215. {
  1216. ssize_t n;
  1217. mutex_lock(&pool->stratum_lock);
  1218. do {
  1219. if (pool->sock)
  1220. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1221. else
  1222. n = 0;
  1223. } while (n > 0);
  1224. mutex_unlock(&pool->stratum_lock);
  1225. clear_sockbuf(pool);
  1226. }
  1227. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1228. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1229. * and zeroing the new memory */
  1230. static void recalloc_sock(struct pool *pool, size_t len)
  1231. {
  1232. size_t old, new;
  1233. old = strlen(pool->sockbuf);
  1234. new = old + len + 1;
  1235. if (new < pool->sockbuf_size)
  1236. return;
  1237. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1238. // Avoid potentially recursive locking
  1239. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1240. pool->sockbuf = realloc(pool->sockbuf, new);
  1241. if (!pool->sockbuf)
  1242. quithere(1, "Failed to realloc pool sockbuf");
  1243. memset(pool->sockbuf + old, 0, new - old);
  1244. pool->sockbuf_size = new;
  1245. }
  1246. /* Peeks at a socket to find the first end of line and then reads just that
  1247. * from the socket and returns that as a malloced char */
  1248. char *recv_line(struct pool *pool)
  1249. {
  1250. char *tok, *sret = NULL;
  1251. ssize_t len, buflen;
  1252. int waited = 0;
  1253. if (!strstr(pool->sockbuf, "\n")) {
  1254. struct timeval rstart, now;
  1255. cgtime(&rstart);
  1256. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1257. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1258. goto out;
  1259. }
  1260. do {
  1261. char s[RBUFSIZE];
  1262. size_t slen;
  1263. ssize_t n;
  1264. memset(s, 0, RBUFSIZE);
  1265. n = recv(pool->sock, s, RECVSIZE, 0);
  1266. if (!n) {
  1267. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1268. suspend_stratum(pool);
  1269. break;
  1270. }
  1271. cgtime(&now);
  1272. waited = tdiff(&now, &rstart);
  1273. if (n < 0) {
  1274. //Save errno from being overweitten bei socket_ commands
  1275. int socket_recv_errno;
  1276. socket_recv_errno = SOCKERR;
  1277. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1278. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %s", bfg_strerror(socket_recv_errno, BST_SOCKET));
  1279. suspend_stratum(pool);
  1280. break;
  1281. }
  1282. } else {
  1283. slen = strlen(s);
  1284. recalloc_sock(pool, slen);
  1285. strcat(pool->sockbuf, s);
  1286. }
  1287. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1288. }
  1289. buflen = strlen(pool->sockbuf);
  1290. tok = strtok(pool->sockbuf, "\n");
  1291. if (!tok) {
  1292. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1293. goto out;
  1294. }
  1295. sret = strdup(tok);
  1296. len = strlen(sret);
  1297. /* Copy what's left in the buffer after the \n, including the
  1298. * terminating \0 */
  1299. if (buflen > len + 1)
  1300. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1301. else
  1302. strcpy(pool->sockbuf, "");
  1303. pool->cgminer_pool_stats.times_received++;
  1304. pool->cgminer_pool_stats.bytes_received += len;
  1305. total_bytes_rcvd += len;
  1306. pool->cgminer_pool_stats.net_bytes_received += len;
  1307. out:
  1308. if (!sret)
  1309. clear_sock(pool);
  1310. else if (opt_protocol)
  1311. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1312. return sret;
  1313. }
  1314. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1315. * flag, but this is compatible with 2.0. */
  1316. char *json_dumps_ANY(json_t *json, size_t flags)
  1317. {
  1318. switch (json_typeof(json))
  1319. {
  1320. case JSON_ARRAY:
  1321. case JSON_OBJECT:
  1322. return json_dumps(json, flags);
  1323. default:
  1324. break;
  1325. }
  1326. char *rv;
  1327. #ifdef JSON_ENCODE_ANY
  1328. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1329. if (rv)
  1330. return rv;
  1331. #endif
  1332. json_t *tmp = json_array();
  1333. char *s;
  1334. int i;
  1335. size_t len;
  1336. if (!tmp)
  1337. quithere(1, "Failed to allocate json array");
  1338. if (json_array_append(tmp, json))
  1339. quithere(1, "Failed to append temporary array");
  1340. s = json_dumps(tmp, flags);
  1341. if (!s)
  1342. return NULL;
  1343. for (i = 0; s[i] != '['; ++i)
  1344. if (unlikely(!(s[i] && isCspace(s[i]))))
  1345. quithere(1, "Failed to find opening bracket in array dump");
  1346. len = strlen(&s[++i]) - 1;
  1347. if (unlikely(s[i+len] != ']'))
  1348. quithere(1, "Failed to find closing bracket in array dump");
  1349. rv = malloc(len + 1);
  1350. memcpy(rv, &s[i], len);
  1351. rv[len] = '\0';
  1352. free(s);
  1353. json_decref(tmp);
  1354. return rv;
  1355. }
  1356. /* Extracts a string value from a json array with error checking. To be used
  1357. * when the value of the string returned is only examined and not to be stored.
  1358. * See json_array_string below */
  1359. char *__json_array_string(json_t *val, unsigned int entry)
  1360. {
  1361. json_t *arr_entry;
  1362. if (json_is_null(val))
  1363. return NULL;
  1364. if (!json_is_array(val))
  1365. return NULL;
  1366. if (entry > json_array_size(val))
  1367. return NULL;
  1368. arr_entry = json_array_get(val, entry);
  1369. if (!json_is_string(arr_entry))
  1370. return NULL;
  1371. return (char *)json_string_value(arr_entry);
  1372. }
  1373. /* Creates a freshly malloced dup of __json_array_string */
  1374. static char *json_array_string(json_t *val, unsigned int entry)
  1375. {
  1376. char *buf = __json_array_string(val, entry);
  1377. if (buf)
  1378. return strdup(buf);
  1379. return NULL;
  1380. }
  1381. void stratum_probe_transparency(struct pool *pool)
  1382. {
  1383. // Request transaction data to discourage pools from doing anything shady
  1384. char s[1024];
  1385. int sLen;
  1386. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1387. pool->swork.job_id,
  1388. pool->swork.job_id);
  1389. stratum_send(pool, s, sLen);
  1390. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  1391. cgtime(&pool->swork.tv_transparency);
  1392. pool->swork.transparency_probed = true;
  1393. }
  1394. static bool parse_notify(struct pool *pool, json_t *val)
  1395. {
  1396. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1397. bool clean, ret = false;
  1398. int merkles, i;
  1399. size_t cb1_len, cb2_len;
  1400. json_t *arr;
  1401. arr = json_array_get(val, 4);
  1402. if (!arr || !json_is_array(arr))
  1403. goto out;
  1404. merkles = json_array_size(arr);
  1405. for (i = 0; i < merkles; i++)
  1406. if (!json_is_string(json_array_get(arr, i)))
  1407. goto out;
  1408. prev_hash = __json_array_string(val, 1);
  1409. coinbase1 = __json_array_string(val, 2);
  1410. coinbase2 = __json_array_string(val, 3);
  1411. bbversion = __json_array_string(val, 5);
  1412. nbit = __json_array_string(val, 6);
  1413. ntime = __json_array_string(val, 7);
  1414. clean = json_is_true(json_array_get(val, 8));
  1415. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  1416. goto out;
  1417. job_id = json_array_string(val, 0);
  1418. if (!job_id)
  1419. goto out;
  1420. cg_wlock(&pool->data_lock);
  1421. cgtime(&pool->swork.tv_received);
  1422. free(pool->swork.job_id);
  1423. pool->swork.job_id = job_id;
  1424. pool->submit_old = !clean;
  1425. pool->swork.clean = true;
  1426. hex2bin(&pool->swork.header1[0], bbversion, 4);
  1427. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  1428. hex2bin((void*)&pool->swork.ntime, ntime, 4);
  1429. pool->swork.ntime = be32toh(pool->swork.ntime);
  1430. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  1431. cb1_len = strlen(coinbase1) / 2;
  1432. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  1433. cb2_len = strlen(coinbase2) / 2;
  1434. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->n2size + cb2_len);
  1435. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  1436. hex2bin(coinbase, coinbase1, cb1_len);
  1437. hex2bin(&coinbase[cb1_len], pool->nonce1, pool->n1_len);
  1438. // NOTE: gap for nonce2, filled at work generation time
  1439. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->n2size], coinbase2, cb2_len);
  1440. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  1441. for (i = 0; i < merkles; i++)
  1442. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  1443. pool->swork.merkles = merkles;
  1444. if (clean)
  1445. pool->nonce2 = 0;
  1446. cg_wunlock(&pool->data_lock);
  1447. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1448. pool->pool_no, job_id);
  1449. if (opt_debug && opt_protocol)
  1450. {
  1451. applog(LOG_DEBUG, "job_id: %s", job_id);
  1452. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1453. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1454. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1455. for (i = 0; i < merkles; i++)
  1456. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  1457. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1458. applog(LOG_DEBUG, "nbit: %s", nbit);
  1459. applog(LOG_DEBUG, "ntime: %s", ntime);
  1460. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1461. }
  1462. /* A notify message is the closest stratum gets to a getwork */
  1463. pool->getwork_requested++;
  1464. total_getworks++;
  1465. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  1466. if (pool->probed)
  1467. stratum_probe_transparency(pool);
  1468. ret = true;
  1469. out:
  1470. return ret;
  1471. }
  1472. static bool parse_diff(struct pool *pool, json_t *val)
  1473. {
  1474. double diff;
  1475. diff = json_number_value(json_array_get(val, 0));
  1476. if (diff == 0)
  1477. return false;
  1478. cg_wlock(&pool->data_lock);
  1479. pool->swork.diff = diff;
  1480. cg_wunlock(&pool->data_lock);
  1481. applog(LOG_DEBUG, "Pool %d stratum bdifficulty set to %f", pool->pool_no, diff);
  1482. return true;
  1483. }
  1484. static bool parse_reconnect(struct pool *pool, json_t *val)
  1485. {
  1486. char *url, *port, address[256];
  1487. memset(address, 0, 255);
  1488. url = (char *)json_string_value(json_array_get(val, 0));
  1489. if (!url)
  1490. url = pool->sockaddr_url;
  1491. port = (char *)json_string_value(json_array_get(val, 1));
  1492. if (!port)
  1493. port = pool->stratum_port;
  1494. sprintf(address, "%s:%s", url, port);
  1495. if (!extract_sockaddr(pool, address))
  1496. return false;
  1497. pool->stratum_url = pool->sockaddr_url;
  1498. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1499. if (!restart_stratum(pool))
  1500. return false;
  1501. return true;
  1502. }
  1503. static bool send_version(struct pool *pool, json_t *val)
  1504. {
  1505. char s[RBUFSIZE], *idstr;
  1506. json_t *id = json_object_get(val, "id");
  1507. if (!(id && !json_is_null(id)))
  1508. return false;
  1509. idstr = json_dumps_ANY(id, 0);
  1510. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1511. free(idstr);
  1512. if (!stratum_send(pool, s, strlen(s)))
  1513. return false;
  1514. return true;
  1515. }
  1516. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  1517. {
  1518. char *msg;
  1519. char s[RBUFSIZE], *idstr;
  1520. json_t *id = json_object_get(val, "id");
  1521. msg = json_array_string(params, 0);
  1522. if (likely(msg))
  1523. {
  1524. free(pool->admin_msg);
  1525. pool->admin_msg = msg;
  1526. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  1527. }
  1528. if (!(id && !json_is_null(id)))
  1529. return true;
  1530. idstr = json_dumps_ANY(id, 0);
  1531. if (likely(msg))
  1532. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  1533. else
  1534. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  1535. free(idstr);
  1536. if (!stratum_send(pool, s, strlen(s)))
  1537. return false;
  1538. return true;
  1539. }
  1540. bool parse_method(struct pool *pool, char *s)
  1541. {
  1542. json_t *val = NULL, *method, *err_val, *params;
  1543. json_error_t err;
  1544. bool ret = false;
  1545. char *buf;
  1546. if (!s)
  1547. goto out;
  1548. val = JSON_LOADS(s, &err);
  1549. if (!val) {
  1550. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1551. goto out;
  1552. }
  1553. method = json_object_get(val, "method");
  1554. if (!method)
  1555. goto out;
  1556. err_val = json_object_get(val, "error");
  1557. params = json_object_get(val, "params");
  1558. if (err_val && !json_is_null(err_val)) {
  1559. char *ss;
  1560. if (err_val)
  1561. ss = json_dumps(err_val, JSON_INDENT(3));
  1562. else
  1563. ss = strdup("(unknown reason)");
  1564. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1565. free(ss);
  1566. goto out;
  1567. }
  1568. buf = (char *)json_string_value(method);
  1569. if (!buf)
  1570. goto out;
  1571. if (!strncasecmp(buf, "mining.notify", 13)) {
  1572. if (parse_notify(pool, params))
  1573. pool->stratum_notify = ret = true;
  1574. else
  1575. pool->stratum_notify = ret = false;
  1576. goto out;
  1577. }
  1578. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1579. ret = true;
  1580. goto out;
  1581. }
  1582. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1583. ret = true;
  1584. goto out;
  1585. }
  1586. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1587. ret = true;
  1588. goto out;
  1589. }
  1590. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  1591. ret = true;
  1592. goto out;
  1593. }
  1594. out:
  1595. if (val)
  1596. json_decref(val);
  1597. return ret;
  1598. }
  1599. extern bool parse_stratum_response(struct pool *, char *s);
  1600. bool auth_stratum(struct pool *pool)
  1601. {
  1602. json_t *val = NULL, *res_val, *err_val;
  1603. char s[RBUFSIZE], *sret = NULL;
  1604. json_error_t err;
  1605. bool ret = false;
  1606. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1607. pool->rpc_user, pool->rpc_pass);
  1608. if (!stratum_send(pool, s, strlen(s)))
  1609. goto out;
  1610. /* Parse all data in the queue and anything left should be auth */
  1611. while (42) {
  1612. sret = recv_line(pool);
  1613. if (!sret)
  1614. goto out;
  1615. if (parse_method(pool, sret))
  1616. free(sret);
  1617. else
  1618. break;
  1619. }
  1620. val = JSON_LOADS(sret, &err);
  1621. free(sret);
  1622. res_val = json_object_get(val, "result");
  1623. err_val = json_object_get(val, "error");
  1624. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1625. char *ss;
  1626. if (err_val)
  1627. ss = json_dumps(err_val, JSON_INDENT(3));
  1628. else
  1629. ss = strdup("(unknown reason)");
  1630. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1631. free(ss);
  1632. goto out;
  1633. }
  1634. ret = true;
  1635. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1636. pool->probed = true;
  1637. successful_connect = true;
  1638. out:
  1639. if (val)
  1640. json_decref(val);
  1641. if (pool->stratum_notify)
  1642. stratum_probe_transparency(pool);
  1643. return ret;
  1644. }
  1645. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1646. {
  1647. struct pool *pool = clientp;
  1648. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1649. pool->sock = sck;
  1650. return sck;
  1651. }
  1652. static bool setup_stratum_curl(struct pool *pool)
  1653. {
  1654. char curl_err_str[CURL_ERROR_SIZE];
  1655. CURL *curl = NULL;
  1656. char s[RBUFSIZE];
  1657. bool ret = false;
  1658. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1659. mutex_lock(&pool->stratum_lock);
  1660. timer_unset(&pool->swork.tv_transparency);
  1661. pool->stratum_active = false;
  1662. pool->stratum_notify = false;
  1663. pool->swork.transparency_probed = false;
  1664. if (pool->stratum_curl)
  1665. curl_easy_cleanup(pool->stratum_curl);
  1666. pool->stratum_curl = curl_easy_init();
  1667. if (unlikely(!pool->stratum_curl))
  1668. quithere(1, "Failed to curl_easy_init");
  1669. if (pool->sockbuf)
  1670. pool->sockbuf[0] = '\0';
  1671. curl = pool->stratum_curl;
  1672. if (!pool->sockbuf) {
  1673. pool->sockbuf = calloc(RBUFSIZE, 1);
  1674. if (!pool->sockbuf)
  1675. quithere(1, "Failed to calloc pool sockbuf");
  1676. pool->sockbuf_size = RBUFSIZE;
  1677. }
  1678. /* Create a http url for use with curl */
  1679. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1680. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1681. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1682. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1683. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1684. curl_easy_setopt(curl, CURLOPT_URL, s);
  1685. if (!opt_delaynet)
  1686. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1687. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1688. * to enable it */
  1689. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  1690. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  1691. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1692. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  1693. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  1694. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  1695. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1696. if (pool->rpc_proxy) {
  1697. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1698. } else if (opt_socks_proxy) {
  1699. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1700. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1701. }
  1702. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1703. pool->sock = INVSOCK;
  1704. if (curl_easy_perform(curl)) {
  1705. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1706. errout:
  1707. curl_easy_cleanup(curl);
  1708. pool->stratum_curl = NULL;
  1709. goto out;
  1710. }
  1711. if (pool->sock == INVSOCK)
  1712. {
  1713. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  1714. goto errout;
  1715. }
  1716. keep_sockalive(pool->sock);
  1717. pool->cgminer_pool_stats.times_sent++;
  1718. pool->cgminer_pool_stats.times_received++;
  1719. ret = true;
  1720. out:
  1721. mutex_unlock(&pool->stratum_lock);
  1722. return ret;
  1723. }
  1724. static char *get_sessionid(json_t *val)
  1725. {
  1726. char *ret = NULL;
  1727. json_t *arr_val;
  1728. int arrsize, i;
  1729. arr_val = json_array_get(val, 0);
  1730. if (!arr_val || !json_is_array(arr_val))
  1731. goto out;
  1732. arrsize = json_array_size(arr_val);
  1733. for (i = 0; i < arrsize; i++) {
  1734. json_t *arr = json_array_get(arr_val, i);
  1735. char *notify;
  1736. if (!arr | !json_is_array(arr))
  1737. break;
  1738. notify = __json_array_string(arr, 0);
  1739. if (!notify)
  1740. continue;
  1741. if (!strncasecmp(notify, "mining.notify", 13)) {
  1742. ret = json_array_string(arr, 1);
  1743. break;
  1744. }
  1745. }
  1746. out:
  1747. return ret;
  1748. }
  1749. void suspend_stratum(struct pool *pool)
  1750. {
  1751. clear_sockbuf(pool);
  1752. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1753. mutex_lock(&pool->stratum_lock);
  1754. pool->stratum_active = pool->stratum_notify = false;
  1755. if (pool->stratum_curl) {
  1756. curl_easy_cleanup(pool->stratum_curl);
  1757. }
  1758. pool->stratum_curl = NULL;
  1759. pool->sock = INVSOCK;
  1760. mutex_unlock(&pool->stratum_lock);
  1761. }
  1762. bool initiate_stratum(struct pool *pool)
  1763. {
  1764. bool ret = false, recvd = false, noresume = false, sockd = false;
  1765. bool trysuggest = request_target_str;
  1766. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1767. json_t *val = NULL, *res_val, *err_val;
  1768. json_error_t err;
  1769. int n2size;
  1770. resend:
  1771. if (!setup_stratum_curl(pool)) {
  1772. sockd = false;
  1773. goto out;
  1774. }
  1775. sockd = true;
  1776. clear_sock(pool);
  1777. if (trysuggest)
  1778. {
  1779. int sz = sprintf(s, "{\"id\": null, \"method\": \"mining.suggest_target\", \"params\": [\"%s\"]}", request_target_str);
  1780. if (!_stratum_send(pool, s, sz, true))
  1781. {
  1782. applog(LOG_DEBUG, "Pool %u: Failed to send suggest_target in initiate_stratum", pool->pool_no);
  1783. goto out;
  1784. }
  1785. recvd = true;
  1786. }
  1787. if (noresume) {
  1788. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1789. } else {
  1790. if (pool->sessionid)
  1791. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1792. else
  1793. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1794. }
  1795. if (!_stratum_send(pool, s, strlen(s), true)) {
  1796. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1797. goto out;
  1798. }
  1799. recvd = true;
  1800. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1801. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1802. goto out;
  1803. }
  1804. sret = recv_line(pool);
  1805. if (!sret)
  1806. goto out;
  1807. val = JSON_LOADS(sret, &err);
  1808. free(sret);
  1809. if (!val) {
  1810. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1811. goto out;
  1812. }
  1813. res_val = json_object_get(val, "result");
  1814. err_val = json_object_get(val, "error");
  1815. if (!res_val || json_is_null(res_val) ||
  1816. (err_val && !json_is_null(err_val))) {
  1817. char *ss;
  1818. if (err_val)
  1819. ss = json_dumps(err_val, JSON_INDENT(3));
  1820. else
  1821. ss = strdup("(unknown reason)");
  1822. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1823. free(ss);
  1824. goto out;
  1825. }
  1826. sessionid = get_sessionid(res_val);
  1827. if (!sessionid)
  1828. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1829. nonce1 = json_array_string(res_val, 1);
  1830. if (!nonce1) {
  1831. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1832. free(sessionid);
  1833. goto out;
  1834. }
  1835. n2size = json_integer_value(json_array_get(res_val, 2));
  1836. if (!n2size) {
  1837. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1838. free(sessionid);
  1839. free(nonce1);
  1840. goto out;
  1841. }
  1842. cg_wlock(&pool->data_lock);
  1843. free(pool->sessionid);
  1844. pool->sessionid = sessionid;
  1845. free(pool->nonce1);
  1846. pool->nonce1 = nonce1;
  1847. pool->n1_len = strlen(nonce1) / 2;
  1848. pool->n2size = n2size;
  1849. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  1850. #ifdef WORDS_BIGENDIAN
  1851. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  1852. #endif
  1853. cg_wunlock(&pool->data_lock);
  1854. if (sessionid)
  1855. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1856. ret = true;
  1857. out:
  1858. if (val)
  1859. json_decref(val);
  1860. if (ret) {
  1861. if (!pool->stratum_url)
  1862. pool->stratum_url = pool->sockaddr_url;
  1863. pool->stratum_active = true;
  1864. pool->swork.diff = 1;
  1865. if (opt_protocol) {
  1866. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1867. pool->pool_no, pool->nonce1, pool->n2size);
  1868. }
  1869. } else {
  1870. if (recvd)
  1871. {
  1872. if (trysuggest)
  1873. {
  1874. applog(LOG_DEBUG, "Pool %u: Failed to connect stratum with mining.suggest_target, retrying without", pool->pool_no);
  1875. trysuggest = false;
  1876. goto resend;
  1877. }
  1878. if (!noresume)
  1879. {
  1880. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1881. noresume = true;
  1882. goto resend;
  1883. }
  1884. }
  1885. applog(LOG_DEBUG, "Initiate stratum failed");
  1886. if (sockd)
  1887. suspend_stratum(pool);
  1888. }
  1889. return ret;
  1890. }
  1891. bool restart_stratum(struct pool *pool)
  1892. {
  1893. if (pool->stratum_active)
  1894. suspend_stratum(pool);
  1895. if (!initiate_stratum(pool))
  1896. return false;
  1897. if (!auth_stratum(pool))
  1898. return false;
  1899. return true;
  1900. }
  1901. void dev_error_update(struct cgpu_info *dev, enum dev_reason reason)
  1902. {
  1903. dev->device_last_not_well = time(NULL);
  1904. cgtime(&dev->tv_device_last_not_well);
  1905. dev->device_not_well_reason = reason;
  1906. }
  1907. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1908. {
  1909. dev_error_update(dev, reason);
  1910. switch (reason) {
  1911. case REASON_THREAD_FAIL_INIT:
  1912. dev->thread_fail_init_count++;
  1913. break;
  1914. case REASON_THREAD_ZERO_HASH:
  1915. dev->thread_zero_hash_count++;
  1916. break;
  1917. case REASON_THREAD_FAIL_QUEUE:
  1918. dev->thread_fail_queue_count++;
  1919. break;
  1920. case REASON_DEV_SICK_IDLE_60:
  1921. dev->dev_sick_idle_60_count++;
  1922. break;
  1923. case REASON_DEV_DEAD_IDLE_600:
  1924. dev->dev_dead_idle_600_count++;
  1925. break;
  1926. case REASON_DEV_NOSTART:
  1927. dev->dev_nostart_count++;
  1928. break;
  1929. case REASON_DEV_OVER_HEAT:
  1930. dev->dev_over_heat_count++;
  1931. break;
  1932. case REASON_DEV_THERMAL_CUTOFF:
  1933. dev->dev_thermal_cutoff_count++;
  1934. break;
  1935. case REASON_DEV_COMMS_ERROR:
  1936. dev->dev_comms_error_count++;
  1937. break;
  1938. case REASON_DEV_THROTTLE:
  1939. dev->dev_throttle_count++;
  1940. break;
  1941. }
  1942. }
  1943. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1944. void *realloc_strcat(char *ptr, char *s)
  1945. {
  1946. size_t old = strlen(ptr), len = strlen(s);
  1947. char *ret;
  1948. if (!len)
  1949. return ptr;
  1950. len += old + 1;
  1951. align_len(&len);
  1952. ret = malloc(len);
  1953. if (unlikely(!ret))
  1954. quithere(1, "Failed to malloc");
  1955. sprintf(ret, "%s%s", ptr, s);
  1956. free(ptr);
  1957. return ret;
  1958. }
  1959. static
  1960. bool sanechars[] = {
  1961. false, false, false, false, false, false, false, false,
  1962. false, false, false, false, false, false, false, false,
  1963. false, false, false, false, false, false, false, false,
  1964. false, false, false, false, false, false, false, false,
  1965. false, false, false, false, false, false, false, false,
  1966. false, false, false, false, false, false, false, false,
  1967. true , true , true , true , true , true , true , true ,
  1968. true , true , false, false, false, false, false, false,
  1969. false, true , true , true , true , true , true , true ,
  1970. true , true , true , true , true , true , true , true ,
  1971. true , true , true , true , true , true , true , true ,
  1972. true , true , true , false, false, false, false, false,
  1973. false, true , true , true , true , true , true , true ,
  1974. true , true , true , true , true , true , true , true ,
  1975. true , true , true , true , true , true , true , true ,
  1976. true , true , true , false, false, false, false, false,
  1977. };
  1978. char *sanestr(char *o, char *s)
  1979. {
  1980. char *rv = o;
  1981. bool br = false;
  1982. for ( ; s[0]; ++s)
  1983. {
  1984. if (sanechars[s[0] & 0x7f])
  1985. {
  1986. if (br)
  1987. {
  1988. br = false;
  1989. if (s[0] >= '0' && s[0] <= '9')
  1990. (o++)[0] = '_';
  1991. }
  1992. (o++)[0] = s[0];
  1993. }
  1994. else
  1995. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  1996. br = true;
  1997. }
  1998. o[0] = '\0';
  1999. return rv;
  2000. }
  2001. void RenameThread(const char* name)
  2002. {
  2003. #if defined(PR_SET_NAME)
  2004. // Only the first 15 characters are used (16 - NUL terminator)
  2005. prctl(PR_SET_NAME, name, 0, 0, 0);
  2006. #elif defined(__APPLE__)
  2007. pthread_setname_np(name);
  2008. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2009. pthread_set_name_np(pthread_self(), name);
  2010. #else
  2011. // Prevent warnings for unused parameters...
  2012. (void)name;
  2013. #endif
  2014. }
  2015. static pthread_key_t key_bfgtls;
  2016. struct bfgtls_data {
  2017. char *bfg_strerror_result;
  2018. size_t bfg_strerror_resultsz;
  2019. #ifdef WIN32
  2020. LPSTR bfg_strerror_socketresult;
  2021. #endif
  2022. };
  2023. static
  2024. struct bfgtls_data *get_bfgtls()
  2025. {
  2026. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  2027. if (bfgtls)
  2028. return bfgtls;
  2029. void *p;
  2030. bfgtls = malloc(sizeof(*bfgtls));
  2031. if (!bfgtls)
  2032. quithere(1, "malloc bfgtls failed");
  2033. p = malloc(64);
  2034. if (!p)
  2035. quithere(1, "malloc bfg_strerror_result failed");
  2036. *bfgtls = (struct bfgtls_data){
  2037. .bfg_strerror_resultsz = 64,
  2038. .bfg_strerror_result = p,
  2039. };
  2040. if (pthread_setspecific(key_bfgtls, bfgtls))
  2041. quithere(1, "pthread_setspecific failed");
  2042. return bfgtls;
  2043. }
  2044. void bfg_init_threadlocal()
  2045. {
  2046. if (pthread_key_create(&key_bfgtls, NULL))
  2047. quithere(1, "pthread_key_create failed");
  2048. }
  2049. static
  2050. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  2051. {
  2052. if (minimum <= *bufszp)
  2053. return false;
  2054. while (minimum > *bufszp)
  2055. *bufszp = 2;
  2056. *bufp = realloc(*bufp, *bufszp);
  2057. if (unlikely(!*bufp))
  2058. quithere(1, "realloc failed");
  2059. return true;
  2060. }
  2061. static
  2062. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  2063. {
  2064. if (!src)
  2065. return NULL;
  2066. const size_t srcsz = strlen(src) + 1;
  2067. bfg_grow_buffer(bufp, bufszp, srcsz);
  2068. memcpy(*bufp, src, srcsz);
  2069. return *bufp;
  2070. }
  2071. // Guaranteed to always return some string (or quit)
  2072. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  2073. {
  2074. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2075. struct bfgtls_data *bfgtls = get_bfgtls();
  2076. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  2077. char ** const bufp = &bfgtls->bfg_strerror_result;
  2078. const char *have = NULL;
  2079. switch (type) {
  2080. case BST_LIBUSB:
  2081. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  2082. #ifdef HAVE_LIBUSB
  2083. # if HAVE_DECL_LIBUSB_ERROR_NAME
  2084. // libusb makes no guarantees for thread-safety or persistence
  2085. mutex_lock(&mutex);
  2086. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  2087. mutex_unlock(&mutex);
  2088. # endif
  2089. #endif
  2090. break;
  2091. case BST_SOCKET:
  2092. {
  2093. #ifdef WIN32
  2094. // Windows has a different namespace for socket errors
  2095. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  2096. if (*msg)
  2097. LocalFree(*msg);
  2098. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  2099. return *msg;
  2100. *msg = NULL;
  2101. break;
  2102. #endif
  2103. }
  2104. // Fallthru on non-WIN32
  2105. case BST_ERRNO:
  2106. {
  2107. #ifdef __STRERROR_S_WORKS
  2108. // FIXME: Not sure how to get this on MingW64
  2109. retry:
  2110. if (likely(!strerror_s(*bufp, *bufszp, e)))
  2111. {
  2112. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  2113. goto retry;
  2114. return *bufp;
  2115. }
  2116. // TODO: XSI strerror_r
  2117. // TODO: GNU strerror_r
  2118. #else
  2119. mutex_lock(&mutex);
  2120. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  2121. mutex_unlock(&mutex);
  2122. #endif
  2123. }
  2124. }
  2125. if (have)
  2126. return *bufp;
  2127. // Failback: Stringify the number
  2128. static const char fmt[] = "%s error #%d", *typestr;
  2129. switch (type) {
  2130. case BST_ERRNO:
  2131. typestr = "System";
  2132. break;
  2133. case BST_SOCKET:
  2134. typestr = "Socket";
  2135. break;
  2136. case BST_LIBUSB:
  2137. typestr = "libusb";
  2138. break;
  2139. default:
  2140. typestr = "Unexpected";
  2141. }
  2142. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  2143. bfg_grow_buffer(bufp, bufszp, sz);
  2144. sprintf(*bufp, fmt, typestr, e);
  2145. return *bufp;
  2146. }
  2147. void notifier_init(notifier_t pipefd)
  2148. {
  2149. #ifdef WIN32
  2150. #define WindowsErrorStr(e) bfg_strerror(e, BST_SOCKET)
  2151. SOCKET listener, connecter, acceptor;
  2152. listener = socket(AF_INET, SOCK_STREAM, 0);
  2153. if (listener == INVALID_SOCKET)
  2154. quit(1, "Failed to create listener socket"IN_FMT_FFL": %s",
  2155. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2156. connecter = socket(AF_INET, SOCK_STREAM, 0);
  2157. if (connecter == INVALID_SOCKET)
  2158. quit(1, "Failed to create connect socket"IN_FMT_FFL": %s",
  2159. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2160. struct sockaddr_in inaddr = {
  2161. .sin_family = AF_INET,
  2162. .sin_addr = {
  2163. .s_addr = htonl(INADDR_LOOPBACK),
  2164. },
  2165. .sin_port = 0,
  2166. };
  2167. {
  2168. static const int reuse = 1;
  2169. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
  2170. }
  2171. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  2172. quit(1, "Failed to bind listener socket"IN_FMT_FFL": %s",
  2173. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2174. socklen_t inaddr_sz = sizeof(inaddr);
  2175. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  2176. quit(1, "Failed to getsockname"IN_FMT_FFL": %s",
  2177. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2178. if (listen(listener, 1) == SOCKET_ERROR)
  2179. quit(1, "Failed to listen"IN_FMT_FFL": %s",
  2180. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2181. inaddr.sin_family = AF_INET;
  2182. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2183. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  2184. quit(1, "Failed to connect"IN_FMT_FFL": %s",
  2185. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2186. acceptor = accept(listener, NULL, NULL);
  2187. if (acceptor == INVALID_SOCKET)
  2188. quit(1, "Failed to accept"IN_FMT_FFL": %s",
  2189. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2190. closesocket(listener);
  2191. pipefd[0] = connecter;
  2192. pipefd[1] = acceptor;
  2193. #else
  2194. if (pipe(pipefd))
  2195. quithere(1, "Failed to create pipe");
  2196. #endif
  2197. }
  2198. void notifier_wake(notifier_t fd)
  2199. {
  2200. if (fd[1] == INVSOCK)
  2201. return;
  2202. #ifdef WIN32
  2203. (void)send(fd[1], "\0", 1, 0);
  2204. #else
  2205. (void)write(fd[1], "\0", 1);
  2206. #endif
  2207. }
  2208. void notifier_read(notifier_t fd)
  2209. {
  2210. char buf[0x10];
  2211. #ifdef WIN32
  2212. (void)recv(fd[0], buf, sizeof(buf), 0);
  2213. #else
  2214. (void)read(fd[0], buf, sizeof(buf));
  2215. #endif
  2216. }
  2217. void notifier_destroy(notifier_t fd)
  2218. {
  2219. #ifdef WIN32
  2220. closesocket(fd[0]);
  2221. closesocket(fd[1]);
  2222. #else
  2223. close(fd[0]);
  2224. close(fd[1]);
  2225. #endif
  2226. fd[0] = fd[1] = INVSOCK;
  2227. }
  2228. void _bytes_alloc_failure(size_t sz)
  2229. {
  2230. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  2231. }
  2232. void *cmd_thread(void *cmdp)
  2233. {
  2234. const char *cmd = cmdp;
  2235. applog(LOG_DEBUG, "Executing command: %s", cmd);
  2236. system(cmd);
  2237. return NULL;
  2238. }
  2239. void run_cmd(const char *cmd)
  2240. {
  2241. if (!cmd)
  2242. return;
  2243. pthread_t pth;
  2244. pthread_create(&pth, NULL, cmd_thread, (void*)cmd);
  2245. }