util.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982
  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 <stdarg.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <ctype.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. bool successful_connect = false;
  53. struct timeval nettime;
  54. struct data_buffer {
  55. void *buf;
  56. size_t len;
  57. curl_socket_t *idlemarker;
  58. };
  59. struct upload_buffer {
  60. const void *buf;
  61. size_t len;
  62. };
  63. struct header_info {
  64. char *lp_path;
  65. int rolltime;
  66. char *reason;
  67. char *stratum_url;
  68. bool hadrolltime;
  69. bool canroll;
  70. bool hadexpire;
  71. };
  72. struct tq_ent {
  73. void *data;
  74. struct tq_ent *prev;
  75. struct tq_ent *next;
  76. };
  77. static void databuf_free(struct data_buffer *db)
  78. {
  79. if (!db)
  80. return;
  81. free(db->buf);
  82. #ifdef DEBUG_DATABUF
  83. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  84. #endif
  85. memset(db, 0, sizeof(*db));
  86. }
  87. // aka data_buffer_write
  88. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  89. void *user_data)
  90. {
  91. struct data_buffer *db = user_data;
  92. size_t oldlen, newlen;
  93. oldlen = db->len;
  94. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  95. return 0;
  96. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  97. nmemb = (SIZE_MAX - oldlen) / size;
  98. size_t len = size * nmemb;
  99. void *newmem;
  100. static const unsigned char zero = 0;
  101. if (db->idlemarker) {
  102. const unsigned char *cptr = ptr;
  103. for (size_t i = 0; i < len; ++i)
  104. if (!(isCspace(cptr[i]) || cptr[i] == '{')) {
  105. *db->idlemarker = CURL_SOCKET_BAD;
  106. db->idlemarker = NULL;
  107. break;
  108. }
  109. }
  110. newlen = oldlen + len;
  111. newmem = realloc(db->buf, newlen + 1);
  112. #ifdef DEBUG_DATABUF
  113. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  114. #endif
  115. if (!newmem)
  116. return 0;
  117. db->buf = newmem;
  118. db->len = newlen;
  119. memcpy(db->buf + oldlen, ptr, len);
  120. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  121. return nmemb;
  122. }
  123. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  124. void *user_data)
  125. {
  126. struct upload_buffer *ub = user_data;
  127. unsigned int len = size * nmemb;
  128. if (len > ub->len)
  129. len = ub->len;
  130. if (len) {
  131. memcpy(ptr, ub->buf, len);
  132. ub->buf += len;
  133. ub->len -= len;
  134. }
  135. return len;
  136. }
  137. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  138. {
  139. struct header_info *hi = user_data;
  140. size_t remlen, slen, ptrlen = size * nmemb;
  141. char *rem, *val = NULL, *key = NULL;
  142. void *tmp;
  143. val = calloc(1, ptrlen);
  144. key = calloc(1, ptrlen);
  145. if (!key || !val)
  146. goto out;
  147. tmp = memchr(ptr, ':', ptrlen);
  148. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  149. goto out;
  150. slen = tmp - ptr;
  151. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  152. goto out;
  153. memcpy(key, ptr, slen); /* store & nul term key */
  154. key[slen] = 0;
  155. rem = ptr + slen + 1; /* trim value's leading whitespace */
  156. remlen = ptrlen - slen - 1;
  157. while ((remlen > 0) && (isCspace(*rem))) {
  158. remlen--;
  159. rem++;
  160. }
  161. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  162. val[remlen] = 0;
  163. while ((*val) && (isCspace(val[strlen(val) - 1])))
  164. val[strlen(val) - 1] = 0;
  165. if (!*val) /* skip blank value */
  166. goto out;
  167. if (opt_protocol)
  168. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  169. if (!strcasecmp("X-Roll-Ntime", key)) {
  170. hi->hadrolltime = true;
  171. if (!strncasecmp("N", val, 1))
  172. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  173. else {
  174. hi->canroll = true;
  175. /* Check to see if expire= is supported and if not, set
  176. * the rolltime to the default scantime */
  177. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  178. sscanf(val + 7, "%d", &hi->rolltime);
  179. hi->hadexpire = true;
  180. } else
  181. hi->rolltime = opt_scantime;
  182. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  183. }
  184. }
  185. if (!strcasecmp("X-Long-Polling", key)) {
  186. hi->lp_path = val; /* steal memory reference */
  187. val = NULL;
  188. }
  189. if (!strcasecmp("X-Reject-Reason", key)) {
  190. hi->reason = val; /* steal memory reference */
  191. val = NULL;
  192. }
  193. if (!strcasecmp("X-Stratum", key)) {
  194. hi->stratum_url = val;
  195. val = NULL;
  196. }
  197. out:
  198. free(key);
  199. free(val);
  200. return ptrlen;
  201. }
  202. static int keep_sockalive(SOCKETTYPE fd)
  203. {
  204. const int tcp_one = 1;
  205. const int tcp_keepidle = 45;
  206. const int tcp_keepintvl = 30;
  207. int ret = 0;
  208. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one))))
  209. ret = 1;
  210. #ifndef WIN32
  211. int flags = fcntl(fd, F_GETFL, 0);
  212. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  213. #else
  214. u_long flags = 1;
  215. ioctlsocket(fd, FIONBIO, &flags);
  216. #endif
  217. if (!opt_delaynet)
  218. #ifndef __linux
  219. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  220. #else /* __linux */
  221. if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  222. #endif /* __linux */
  223. ret = 1;
  224. #ifdef __linux
  225. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one))))
  226. ret = 1;
  227. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  228. ret = 1;
  229. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  230. ret = 1;
  231. #endif /* __linux */
  232. #ifdef __APPLE_CC__
  233. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  234. ret = 1;
  235. #endif /* __APPLE_CC__ */
  236. #ifdef WIN32
  237. const int zero = 0;
  238. struct tcp_keepalive vals;
  239. vals.onoff = 1;
  240. vals.keepalivetime = tcp_keepidle * 1000;
  241. vals.keepaliveinterval = tcp_keepintvl * 1000;
  242. DWORD outputBytes;
  243. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  244. ret = 1;
  245. /* Windows happily submits indefinitely to the send buffer blissfully
  246. * unaware nothing is getting there without gracefully failing unless
  247. * we disable the send buffer */
  248. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  249. ret = 1;
  250. #endif /* WIN32 */
  251. return ret;
  252. }
  253. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  254. curlsocktype __maybe_unused purpose)
  255. {
  256. return keep_sockalive(fd);
  257. }
  258. static void last_nettime(struct timeval *last)
  259. {
  260. rd_lock(&netacc_lock);
  261. last->tv_sec = nettime.tv_sec;
  262. last->tv_usec = nettime.tv_usec;
  263. rd_unlock(&netacc_lock);
  264. }
  265. static void set_nettime(void)
  266. {
  267. wr_lock(&netacc_lock);
  268. cgtime(&nettime);
  269. wr_unlock(&netacc_lock);
  270. }
  271. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  272. char *data, size_t size,
  273. void *userdata)
  274. {
  275. struct pool *pool = (struct pool *)userdata;
  276. switch(type) {
  277. case CURLINFO_HEADER_IN:
  278. case CURLINFO_DATA_IN:
  279. case CURLINFO_SSL_DATA_IN:
  280. pool->cgminer_pool_stats.bytes_received += size;
  281. total_bytes_rcvd += size;
  282. pool->cgminer_pool_stats.net_bytes_received += size;
  283. break;
  284. case CURLINFO_HEADER_OUT:
  285. case CURLINFO_DATA_OUT:
  286. case CURLINFO_SSL_DATA_OUT:
  287. pool->cgminer_pool_stats.bytes_sent += size;
  288. total_bytes_sent += size;
  289. pool->cgminer_pool_stats.net_bytes_sent += size;
  290. break;
  291. case CURLINFO_TEXT:
  292. {
  293. if (!opt_protocol)
  294. break;
  295. // data is not null-terminated, so we need to copy and terminate it for applog
  296. char datacp[size + 1];
  297. memcpy(datacp, data, size);
  298. while (likely(size) && unlikely(isCspace(datacp[size-1])))
  299. --size;
  300. if (unlikely(!size))
  301. break;
  302. datacp[size] = '\0';
  303. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  304. break;
  305. }
  306. default:
  307. break;
  308. }
  309. return 0;
  310. }
  311. struct json_rpc_call_state {
  312. struct data_buffer all_data;
  313. struct header_info hi;
  314. void *priv;
  315. char curl_err_str[CURL_ERROR_SIZE];
  316. struct curl_slist *headers;
  317. struct upload_buffer upload_data;
  318. struct pool *pool;
  319. };
  320. void json_rpc_call_async(CURL *curl, const char *url,
  321. const char *userpass, const char *rpc_req,
  322. bool longpoll,
  323. struct pool *pool, bool share,
  324. void *priv)
  325. {
  326. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  327. *state = (struct json_rpc_call_state){
  328. .priv = priv,
  329. .pool = pool,
  330. };
  331. long timeout = longpoll ? (60 * 60) : 60;
  332. char len_hdr[64], user_agent_hdr[128];
  333. struct curl_slist *headers = NULL;
  334. if (longpoll)
  335. state->all_data.idlemarker = &pool->lp_socket;
  336. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  337. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  338. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  339. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  340. * to enable it */
  341. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  342. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  343. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  344. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  345. curl_easy_setopt(curl, CURLOPT_URL, url);
  346. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  347. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  348. /* Shares are staggered already and delays in submission can be costly
  349. * so do not delay them */
  350. if (!opt_delaynet || share)
  351. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  352. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  353. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  354. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  355. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  356. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  357. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  358. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  359. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  360. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  361. if (pool->rpc_proxy) {
  362. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  363. } else if (opt_socks_proxy) {
  364. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  365. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  366. }
  367. if (userpass) {
  368. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  369. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  370. }
  371. if (longpoll)
  372. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  373. curl_easy_setopt(curl, CURLOPT_POST, 1);
  374. if (opt_protocol)
  375. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  376. state->upload_data.buf = rpc_req;
  377. state->upload_data.len = strlen(rpc_req);
  378. sprintf(len_hdr, "Content-Length: %lu",
  379. (unsigned long) state->upload_data.len);
  380. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  381. headers = curl_slist_append(headers,
  382. "Content-type: application/json");
  383. headers = curl_slist_append(headers,
  384. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  385. if (longpoll)
  386. headers = curl_slist_append(headers,
  387. "X-Minimum-Wait: 0");
  388. if (likely(global_hashrate)) {
  389. char ghashrate[255];
  390. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  391. headers = curl_slist_append(headers, ghashrate);
  392. }
  393. headers = curl_slist_append(headers, len_hdr);
  394. headers = curl_slist_append(headers, user_agent_hdr);
  395. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  396. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  397. state->headers = headers;
  398. if (opt_delaynet) {
  399. /* Don't delay share submission, but still track the nettime */
  400. if (!share) {
  401. long long now_msecs, last_msecs;
  402. struct timeval now, last;
  403. cgtime(&now);
  404. last_nettime(&last);
  405. now_msecs = (long long)now.tv_sec * 1000;
  406. now_msecs += now.tv_usec / 1000;
  407. last_msecs = (long long)last.tv_sec * 1000;
  408. last_msecs += last.tv_usec / 1000;
  409. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  410. struct timespec rgtp;
  411. rgtp.tv_sec = 0;
  412. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  413. nanosleep(&rgtp, NULL);
  414. }
  415. }
  416. set_nettime();
  417. }
  418. }
  419. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  420. {
  421. struct json_rpc_call_state *state;
  422. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
  423. applog(LOG_ERR, "Failed to get private curl data");
  424. if (out_priv)
  425. *(void**)out_priv = NULL;
  426. goto err_out;
  427. }
  428. if (out_priv)
  429. *(void**)out_priv = state->priv;
  430. json_t *val, *err_val, *res_val;
  431. json_error_t err;
  432. struct pool *pool = state->pool;
  433. bool probing = probe && !pool->probed;
  434. if (rc) {
  435. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  436. goto err_out;
  437. }
  438. if (!state->all_data.buf) {
  439. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  440. goto err_out;
  441. }
  442. pool->cgminer_pool_stats.times_sent++;
  443. pool->cgminer_pool_stats.times_received++;
  444. if (probing) {
  445. pool->probed = true;
  446. /* If X-Long-Polling was found, activate long polling */
  447. if (state->hi.lp_path) {
  448. if (pool->hdr_path != NULL)
  449. free(pool->hdr_path);
  450. pool->hdr_path = state->hi.lp_path;
  451. } else
  452. pool->hdr_path = NULL;
  453. if (state->hi.stratum_url) {
  454. pool->stratum_url = state->hi.stratum_url;
  455. state->hi.stratum_url = NULL;
  456. }
  457. } else {
  458. if (state->hi.lp_path) {
  459. free(state->hi.lp_path);
  460. state->hi.lp_path = NULL;
  461. }
  462. if (state->hi.stratum_url) {
  463. free(state->hi.stratum_url);
  464. state->hi.stratum_url = NULL;
  465. }
  466. }
  467. if (pool->force_rollntime)
  468. {
  469. state->hi.canroll = true;
  470. state->hi.hadexpire = true;
  471. state->hi.rolltime = pool->force_rollntime;
  472. }
  473. if (rolltime)
  474. *rolltime = state->hi.rolltime;
  475. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  476. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  477. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  478. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  479. val = JSON_LOADS(state->all_data.buf, &err);
  480. if (!val) {
  481. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  482. if (opt_protocol)
  483. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  484. goto err_out;
  485. }
  486. if (opt_protocol) {
  487. char *s = json_dumps(val, JSON_INDENT(3));
  488. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  489. free(s);
  490. }
  491. /* JSON-RPC valid response returns a non-null 'result',
  492. * and a null 'error'.
  493. */
  494. res_val = json_object_get(val, "result");
  495. err_val = json_object_get(val, "error");
  496. if (!res_val ||(err_val && !json_is_null(err_val))) {
  497. char *s;
  498. if (err_val)
  499. s = json_dumps(err_val, JSON_INDENT(3));
  500. else
  501. s = strdup("(unknown reason)");
  502. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  503. free(s);
  504. json_decref(val);
  505. goto err_out;
  506. }
  507. if (state->hi.reason) {
  508. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  509. free(state->hi.reason);
  510. state->hi.reason = NULL;
  511. }
  512. successful_connect = true;
  513. databuf_free(&state->all_data);
  514. curl_slist_free_all(state->headers);
  515. curl_easy_reset(curl);
  516. free(state);
  517. return val;
  518. err_out:
  519. databuf_free(&state->all_data);
  520. curl_slist_free_all(state->headers);
  521. curl_easy_reset(curl);
  522. if (!successful_connect)
  523. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  524. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  525. free(state);
  526. return NULL;
  527. }
  528. json_t *json_rpc_call(CURL *curl, const char *url,
  529. const char *userpass, const char *rpc_req,
  530. bool probe, bool longpoll, int *rolltime,
  531. struct pool *pool, bool share)
  532. {
  533. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  534. int rc = curl_easy_perform(curl);
  535. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  536. }
  537. bool our_curl_supports_proxy_uris()
  538. {
  539. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  540. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  541. }
  542. // NOTE: This assumes reference URI is a root
  543. char *absolute_uri(char *uri, const char *ref)
  544. {
  545. if (strstr(uri, "://"))
  546. return strdup(uri);
  547. char *copy_start, *abs;
  548. bool need_slash = false;
  549. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  550. if (ref[strlen(ref) - 1] != '/')
  551. need_slash = true;
  552. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  553. if (!abs) {
  554. applog(LOG_ERR, "Malloc failure in absolute_uri");
  555. return NULL;
  556. }
  557. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  558. return abs;
  559. }
  560. static const char _hexchars[0x10] = "0123456789abcdef";
  561. void bin2hex(char *out, const void *in, size_t len)
  562. {
  563. const unsigned char *p = in;
  564. while (len--)
  565. {
  566. (out++)[0] = _hexchars[p[0] >> 4];
  567. (out++)[0] = _hexchars[p[0] & 0xf];
  568. ++p;
  569. }
  570. out[0] = '\0';
  571. }
  572. static inline
  573. int _hex2bin_char(const char c)
  574. {
  575. if (c >= '0' && c <= '9')
  576. return c - '0';
  577. if (c >= 'a' && c <= 'f')
  578. return (c - 'a') + 10;
  579. if (c >= 'A' && c <= 'F')
  580. return (c - 'A') + 10;
  581. return -1;
  582. }
  583. /* Does the reverse of bin2hex but does not allocate any ram */
  584. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  585. {
  586. int n, o;
  587. while (len--)
  588. {
  589. n = _hex2bin_char((hexstr++)[0]);
  590. if (unlikely(n == -1))
  591. {
  592. badchar:
  593. if (!hexstr[-1])
  594. applog(LOG_ERR, "hex2bin: str truncated");
  595. else
  596. applog(LOG_ERR, "hex2bin: invalid character 0x%02x", (int)hexstr[-1]);
  597. return false;
  598. }
  599. o = _hex2bin_char((hexstr++)[0]);
  600. if (unlikely(o == -1))
  601. goto badchar;
  602. (p++)[0] = (n << 4) | o;
  603. }
  604. return likely(!hexstr[0]);
  605. }
  606. void hash_data(unsigned char *out_hash, const unsigned char *data)
  607. {
  608. unsigned char blkheader[80];
  609. // 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
  610. swap32yes(blkheader, data, 80 / 4);
  611. // double-SHA256 to get the block hash
  612. gen_hash(blkheader, out_hash, 80);
  613. }
  614. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  615. void real_block_target(unsigned char *target, const unsigned char *data)
  616. {
  617. uint8_t targetshift;
  618. if (unlikely(data[72] < 3 || data[72] > 0x20))
  619. {
  620. // Invalid (out of bounds) target
  621. memset(target, 0xff, 32);
  622. return;
  623. }
  624. targetshift = data[72] - 3;
  625. memset(target, 0, targetshift);
  626. target[targetshift++] = data[75];
  627. target[targetshift++] = data[74];
  628. target[targetshift++] = data[73];
  629. memset(&target[targetshift], 0, 0x20 - targetshift);
  630. }
  631. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  632. {
  633. const uint32_t *h32 = (uint32_t*)&hash[0];
  634. const uint32_t *t32 = (uint32_t*)&target[0];
  635. for (int i = 7; i >= 0; --i) {
  636. uint32_t h32i = le32toh(h32[i]);
  637. uint32_t t32i = le32toh(t32[i]);
  638. if (h32i > t32i)
  639. return false;
  640. if (h32i < t32i)
  641. return true;
  642. }
  643. return true;
  644. }
  645. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  646. {
  647. bool rc;
  648. rc = hash_target_check(hash, target);
  649. if (opt_debug) {
  650. unsigned char hash_swap[32], target_swap[32];
  651. char hash_str[65];
  652. char target_str[65];
  653. for (int i = 0; i < 32; ++i) {
  654. hash_swap[i] = hash[31-i];
  655. target_swap[i] = target[31-i];
  656. }
  657. bin2hex(hash_str, hash_swap, 32);
  658. bin2hex(target_str, target_swap, 32);
  659. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  660. hash_str,
  661. target_str,
  662. rc ? "YES (hash <= target)" :
  663. "no (false positive; hash > target)");
  664. }
  665. return rc;
  666. }
  667. // This operates on a native-endian SHA256 state
  668. // In other words, on little endian platforms, every 4 bytes are in reverse order
  669. bool fulltest(const unsigned char *hash, const unsigned char *target)
  670. {
  671. unsigned char hash2[32];
  672. swap32tobe(hash2, hash, 32 / 4);
  673. return hash_target_check_v(hash2, target);
  674. }
  675. struct thread_q *tq_new(void)
  676. {
  677. struct thread_q *tq;
  678. tq = calloc(1, sizeof(*tq));
  679. if (!tq)
  680. return NULL;
  681. pthread_mutex_init(&tq->mutex, NULL);
  682. pthread_cond_init(&tq->cond, NULL);
  683. return tq;
  684. }
  685. void tq_free(struct thread_q *tq)
  686. {
  687. struct tq_ent *ent, *iter;
  688. if (!tq)
  689. return;
  690. DL_FOREACH_SAFE(tq->q, ent, iter) {
  691. DL_DELETE(tq->q, ent);
  692. free(ent);
  693. }
  694. pthread_cond_destroy(&tq->cond);
  695. pthread_mutex_destroy(&tq->mutex);
  696. memset(tq, 0, sizeof(*tq)); /* poison */
  697. free(tq);
  698. }
  699. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  700. {
  701. mutex_lock(&tq->mutex);
  702. tq->frozen = frozen;
  703. pthread_cond_signal(&tq->cond);
  704. mutex_unlock(&tq->mutex);
  705. }
  706. void tq_freeze(struct thread_q *tq)
  707. {
  708. tq_freezethaw(tq, true);
  709. }
  710. void tq_thaw(struct thread_q *tq)
  711. {
  712. tq_freezethaw(tq, false);
  713. }
  714. bool tq_push(struct thread_q *tq, void *data)
  715. {
  716. struct tq_ent *ent;
  717. bool rc = true;
  718. ent = calloc(1, sizeof(*ent));
  719. if (!ent)
  720. return false;
  721. ent->data = data;
  722. mutex_lock(&tq->mutex);
  723. if (!tq->frozen) {
  724. DL_APPEND(tq->q, ent);
  725. } else {
  726. free(ent);
  727. rc = false;
  728. }
  729. pthread_cond_signal(&tq->cond);
  730. mutex_unlock(&tq->mutex);
  731. return rc;
  732. }
  733. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  734. {
  735. struct tq_ent *ent;
  736. void *rval = NULL;
  737. int rc;
  738. mutex_lock(&tq->mutex);
  739. if (tq->q)
  740. goto pop;
  741. if (abstime)
  742. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  743. else
  744. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  745. if (rc)
  746. goto out;
  747. if (!tq->q)
  748. goto out;
  749. pop:
  750. ent = tq->q;
  751. rval = ent->data;
  752. DL_DELETE(tq->q, ent);
  753. free(ent);
  754. out:
  755. mutex_unlock(&tq->mutex);
  756. return rval;
  757. }
  758. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  759. {
  760. int rv = pthread_create(&thr->pth, attr, start, arg);
  761. if (likely(!rv))
  762. thr->has_pth = true;
  763. return rv;
  764. }
  765. void thr_info_freeze(struct thr_info *thr)
  766. {
  767. struct tq_ent *ent, *iter;
  768. struct thread_q *tq;
  769. if (!thr)
  770. return;
  771. tq = thr->q;
  772. if (!tq)
  773. return;
  774. mutex_lock(&tq->mutex);
  775. tq->frozen = true;
  776. DL_FOREACH_SAFE(tq->q, ent, iter) {
  777. DL_DELETE(tq->q, ent);
  778. free(ent);
  779. }
  780. mutex_unlock(&tq->mutex);
  781. }
  782. void thr_info_cancel(struct thr_info *thr)
  783. {
  784. if (!thr)
  785. return;
  786. if (thr->has_pth) {
  787. pthread_cancel(thr->pth);
  788. thr->has_pth = false;
  789. }
  790. }
  791. #ifndef HAVE_PTHREAD_CANCEL
  792. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  793. enum pthread_cancel_workaround_mode {
  794. PCWM_DEFAULT = 0,
  795. PCWM_TERMINATE = 1,
  796. PCWM_ASYNC = 2,
  797. PCWM_DISABLED = 4,
  798. PCWM_CANCELLED = 8,
  799. };
  800. static pthread_key_t key_pcwm;
  801. struct sigaction pcwm_orig_term_handler;
  802. static
  803. void do_pthread_cancel_exit(int flags)
  804. {
  805. if (!(flags & PCWM_ASYNC))
  806. // NOTE: Logging disables cancel while mutex held, so this is safe
  807. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  808. pthread_exit(PTHREAD_CANCELED);
  809. }
  810. static
  811. void sighandler_pthread_cancel(int sig)
  812. {
  813. int flags = (int)pthread_getspecific(key_pcwm);
  814. if (flags & PCWM_TERMINATE) // Main thread
  815. {
  816. // Restore original handler and call it
  817. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  818. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  819. raise(SIGTERM);
  820. quit(1, "pthread_cancel workaround: Original handler returned");
  821. }
  822. if (flags & PCWM_CANCELLED) // Already pending cancel
  823. return;
  824. if (flags & PCWM_DISABLED)
  825. {
  826. flags |= PCWM_CANCELLED;
  827. if (pthread_setspecific(key_pcwm, (void*)flags))
  828. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  829. return;
  830. }
  831. do_pthread_cancel_exit(flags);
  832. }
  833. void pthread_testcancel(void)
  834. {
  835. int flags = (int)pthread_getspecific(key_pcwm);
  836. if (flags & PCWM_CANCELLED && !(flags & PCWM_DISABLED))
  837. do_pthread_cancel_exit(flags);
  838. }
  839. int pthread_setcancelstate(int state, int *oldstate)
  840. {
  841. int flags = (int)pthread_getspecific(key_pcwm);
  842. if (oldstate)
  843. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  844. if (state == PTHREAD_CANCEL_DISABLE)
  845. flags |= PCWM_DISABLED;
  846. else
  847. {
  848. if (flags & PCWM_CANCELLED)
  849. do_pthread_cancel_exit(flags);
  850. flags &= ~PCWM_DISABLED;
  851. }
  852. if (pthread_setspecific(key_pcwm, (void*)flags))
  853. return -1;
  854. return 0;
  855. }
  856. int pthread_setcanceltype(int type, int *oldtype)
  857. {
  858. int flags = (int)pthread_getspecific(key_pcwm);
  859. if (oldtype)
  860. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  861. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  862. flags |= PCWM_ASYNC;
  863. else
  864. flags &= ~PCWM_ASYNC;
  865. if (pthread_setspecific(key_pcwm, (void*)flags))
  866. return -1;
  867. return 0;
  868. }
  869. void setup_pthread_cancel_workaround()
  870. {
  871. if (pthread_key_create(&key_pcwm, NULL))
  872. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  873. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  874. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  875. struct sigaction new_sigact = {
  876. .sa_handler = sighandler_pthread_cancel,
  877. };
  878. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  879. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  880. }
  881. #endif
  882. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  883. * on SMP machines */
  884. void nmsleep(unsigned int msecs)
  885. {
  886. struct timespec twait, tleft;
  887. int ret;
  888. ldiv_t d;
  889. #ifdef WIN32
  890. timeBeginPeriod(1);
  891. #endif
  892. d = ldiv(msecs, 1000);
  893. tleft.tv_sec = d.quot;
  894. tleft.tv_nsec = d.rem * 1000000;
  895. do {
  896. twait.tv_sec = tleft.tv_sec;
  897. twait.tv_nsec = tleft.tv_nsec;
  898. ret = nanosleep(&twait, &tleft);
  899. } while (ret == -1 && errno == EINTR);
  900. #ifdef WIN32
  901. timeEndPeriod(1);
  902. #endif
  903. }
  904. /* Same for usecs */
  905. void nusleep(unsigned int usecs)
  906. {
  907. struct timespec twait, tleft;
  908. int ret;
  909. ldiv_t d;
  910. #ifdef WIN32
  911. timeBeginPeriod(1);
  912. #endif
  913. d = ldiv(usecs, 1000000);
  914. tleft.tv_sec = d.quot;
  915. tleft.tv_nsec = d.rem * 1000;
  916. do {
  917. twait.tv_sec = tleft.tv_sec;
  918. twait.tv_nsec = tleft.tv_nsec;
  919. ret = nanosleep(&twait, &tleft);
  920. } while (ret == -1 && errno == EINTR);
  921. #ifdef WIN32
  922. timeEndPeriod(1);
  923. #endif
  924. }
  925. static
  926. void _now_gettimeofday(struct timeval *tv)
  927. {
  928. #ifdef WIN32
  929. // Windows' default resolution is only 15ms. This requests 1ms.
  930. timeBeginPeriod(1);
  931. #endif
  932. gettimeofday(tv, NULL);
  933. #ifdef WIN32
  934. timeEndPeriod(1);
  935. #endif
  936. }
  937. #ifdef HAVE_POOR_GETTIMEOFDAY
  938. static struct timeval tv_timeofday_offset;
  939. static struct timeval _tv_timeofday_lastchecked;
  940. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  941. static
  942. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  943. {
  944. struct timeval actual, delta;
  945. timeradd(expected, &tv_timeofday_offset, expected);
  946. _now_gettimeofday(&actual);
  947. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  948. // Within reason - no change necessary
  949. return;
  950. timersub(&actual, expected, &delta);
  951. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  952. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  953. *expected = actual;
  954. }
  955. void bfg_gettimeofday(struct timeval *out)
  956. {
  957. char buf[64] = "";
  958. timer_set_now(out);
  959. mutex_lock(&_tv_timeofday_mutex);
  960. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  961. bfg_calibrate_timeofday(out, buf);
  962. else
  963. timeradd(out, &tv_timeofday_offset, out);
  964. mutex_unlock(&_tv_timeofday_mutex);
  965. if (unlikely(buf[0]))
  966. applog(LOG_WARNING, "%s", buf);
  967. }
  968. #endif
  969. #ifdef WIN32
  970. static LARGE_INTEGER _perffreq;
  971. static
  972. void _now_queryperformancecounter(struct timeval *tv)
  973. {
  974. LARGE_INTEGER now;
  975. if (unlikely(!QueryPerformanceCounter(&now)))
  976. quit(1, "QueryPerformanceCounter failed");
  977. *tv = (struct timeval){
  978. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  979. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  980. };
  981. }
  982. #endif
  983. static
  984. void _now_is_not_set(__maybe_unused struct timeval *tv)
  985. {
  986. // Might be unclean to swap algorithms after getting a timer
  987. quit(1, "timer_set_now called before bfg_init_time");
  988. }
  989. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  990. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  991. static clockid_t bfg_timer_clk;
  992. static
  993. void _now_clock_gettime(struct timeval *tv)
  994. {
  995. struct timespec ts;
  996. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  997. quit(1, "clock_gettime failed");
  998. *tv = (struct timeval){
  999. .tv_sec = ts.tv_sec,
  1000. .tv_usec = ts.tv_nsec / 1000,
  1001. };
  1002. }
  1003. static
  1004. bool _bfg_try_clock_gettime(clockid_t clk)
  1005. {
  1006. struct timespec ts;
  1007. if (clock_gettime(clk, &ts))
  1008. return false;
  1009. bfg_timer_clk = clk;
  1010. timer_set_now = _now_clock_gettime;
  1011. return true;
  1012. }
  1013. #endif
  1014. void bfg_init_time()
  1015. {
  1016. if (timer_set_now != _now_is_not_set)
  1017. return;
  1018. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1019. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1020. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1021. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1022. else
  1023. #endif
  1024. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1025. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1026. else
  1027. #endif
  1028. #ifdef WIN32
  1029. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1030. {
  1031. timer_set_now = _now_queryperformancecounter;
  1032. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1033. }
  1034. else
  1035. #endif
  1036. {
  1037. timer_set_now = _now_gettimeofday;
  1038. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1039. }
  1040. #ifdef HAVE_POOR_GETTIMEOFDAY
  1041. char buf[64] = "";
  1042. struct timeval tv;
  1043. timer_set_now(&tv);
  1044. bfg_calibrate_timeofday(&tv, buf);
  1045. applog(LOG_DEBUG, "%s", buf);
  1046. #endif
  1047. }
  1048. // NOTE: Only supports (BTF_BRACKETS | BTF_DATE | BTF_TIME) for now
  1049. int format_elapsed2(char * const buf, size_t sz, const int fmt, int elapsed)
  1050. {
  1051. unsigned int days, hours;
  1052. div_t d;
  1053. d = div(elapsed, 86400);
  1054. days = d.quot;
  1055. d = div(d.rem, 3600);
  1056. hours = d.quot;
  1057. d = div(d.rem, 60);
  1058. return
  1059. snprintf(buf, sz, "[%3u day%c %02d:%02d:%02d]"
  1060. , days
  1061. , (days == 1) ? ' ' : 's'
  1062. , hours
  1063. , d.quot
  1064. , d.rem
  1065. );
  1066. }
  1067. int format_tm2(char * const buf, size_t sz, const int fmt, const struct tm * const tm, const long usecs)
  1068. {
  1069. char *s = buf;
  1070. int rv = 0;
  1071. if (fmt & BTF_BRACKETS)
  1072. _SNP("[");
  1073. if (fmt & BTF_DATE)
  1074. _SNP("%d-%02d-%02d%s",
  1075. tm->tm_year + 1900,
  1076. tm->tm_mon + 1,
  1077. tm->tm_mday,
  1078. (fmt & 3 /* any time */) ? " " : "");
  1079. if (fmt & 3 /* any time */)
  1080. {
  1081. _SNP("%02d:%02d",
  1082. tm->tm_hour,
  1083. tm->tm_min);
  1084. if (fmt & 1 /* with seconds */)
  1085. {
  1086. _SNP(":%02d", tm->tm_sec);
  1087. if ((fmt & BTF_HRTIME) == BTF_HRTIME)
  1088. _SNP(".%06ld", usecs);
  1089. }
  1090. }
  1091. if (fmt & BTF_BRACKETS)
  1092. _SNP("]");
  1093. return rv;
  1094. }
  1095. int format_timestamp2(char * const buf, size_t sz, const int fmt, const struct timeval * const tv)
  1096. {
  1097. struct tm tm;
  1098. time_t tt = tv->tv_sec;
  1099. localtime_r(&tt, &tm);
  1100. return format_tm2(buf, sz, fmt, &tm, tv->tv_usec);
  1101. }
  1102. void subtime(struct timeval *a, struct timeval *b)
  1103. {
  1104. timersub(a, b, b);
  1105. }
  1106. void addtime(struct timeval *a, struct timeval *b)
  1107. {
  1108. timeradd(a, b, b);
  1109. }
  1110. bool time_more(struct timeval *a, struct timeval *b)
  1111. {
  1112. return timercmp(a, b, >);
  1113. }
  1114. bool time_less(struct timeval *a, struct timeval *b)
  1115. {
  1116. return timercmp(a, b, <);
  1117. }
  1118. void copy_time(struct timeval *dest, const struct timeval *src)
  1119. {
  1120. memcpy(dest, src, sizeof(struct timeval));
  1121. }
  1122. /* Returns the microseconds difference between end and start times as a double */
  1123. double us_tdiff(struct timeval *end, struct timeval *start)
  1124. {
  1125. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1126. }
  1127. /* Returns the seconds difference between end and start times as a double */
  1128. double tdiff(struct timeval *end, struct timeval *start)
  1129. {
  1130. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1131. }
  1132. int32_t utf8_decode(const void *b, int *out_len)
  1133. {
  1134. int32_t w;
  1135. const unsigned char *s = b;
  1136. if (!(s[0] & 0x80))
  1137. {
  1138. // ASCII
  1139. *out_len = 1;
  1140. return s[0];
  1141. }
  1142. #ifdef STRICT_UTF8
  1143. if (unlikely(!(s[0] & 0x40)))
  1144. goto invalid;
  1145. #endif
  1146. if (!(s[0] & 0x20))
  1147. *out_len = 2;
  1148. else
  1149. if (!(s[0] & 0x10))
  1150. *out_len = 3;
  1151. else
  1152. if (likely(!(s[0] & 8)))
  1153. *out_len = 4;
  1154. else
  1155. goto invalid;
  1156. w = s[0] & ((2 << (6 - *out_len)) - 1);
  1157. for (int i = 1; i < *out_len; ++i)
  1158. {
  1159. #ifdef STRICT_UTF8
  1160. if (unlikely((s[i] & 0xc0) != 0x80))
  1161. goto invalid;
  1162. #endif
  1163. w = (w << 6) | (s[i] & 0x3f);
  1164. }
  1165. #if defined(STRICT_UTF8)
  1166. if (unlikely(w > 0x10FFFF))
  1167. goto invalid;
  1168. // FIXME: UTF-8 requires smallest possible encoding; check it
  1169. #endif
  1170. return w;
  1171. invalid:
  1172. *out_len = 1;
  1173. return REPLACEMENT_CHAR;
  1174. }
  1175. static
  1176. void _utf8_test(const char *s, const wchar_t expected, int expectedlen)
  1177. {
  1178. int len;
  1179. wchar_t r;
  1180. r = utf8_decode(s, &len);
  1181. if (unlikely(r != expected || expectedlen != len))
  1182. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got U+%06lX (len %d)", (unsigned long)expected, expectedlen, (unsigned long)r, len);
  1183. }
  1184. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1185. void utf8_test()
  1186. {
  1187. _utf8_test("", 0, 1);
  1188. _utf8_test("\1", 1, 1);
  1189. _utf8_test("\x7f", 0x7f, 1);
  1190. #if WCHAR_MAX >= 0x80
  1191. _utf8_test("\xc2\x80", 0x80, 2);
  1192. #if WCHAR_MAX >= 0xff
  1193. _utf8_test("\xc3\xbf", 0xff, 2);
  1194. #if WCHAR_MAX >= 0x7ff
  1195. _utf8_test("\xdf\xbf", 0x7ff, 2);
  1196. #if WCHAR_MAX >= 0x800
  1197. _utf8_test("\xe0\xa0\x80", 0x800, 3);
  1198. #if WCHAR_MAX >= 0xffff
  1199. _utf8_test("\xef\xbf\xbf", 0xffff, 3);
  1200. #if WCHAR_MAX >= 0x10000
  1201. _utf8_test("\xf0\x90\x80\x80", 0x10000, 4);
  1202. #if WCHAR_MAX >= 0x10ffff
  1203. _utf8_test("\xf4\x8f\xbf\xbf", 0x10ffff, 4);
  1204. #endif
  1205. #endif
  1206. #endif
  1207. #endif
  1208. #endif
  1209. #endif
  1210. #endif
  1211. #ifdef STRICT_UTF8
  1212. _utf8_test("\x80", REPLACEMENT_CHAR, 1);
  1213. _utf8_test("\xbf", REPLACEMENT_CHAR, 1);
  1214. _utf8_test("\xfe", REPLACEMENT_CHAR, 1);
  1215. _utf8_test("\xff", REPLACEMENT_CHAR, 1);
  1216. #endif
  1217. }
  1218. int format_temperature2(char * const buf, size_t sz, const int pad, const bool highprecision, const bool unicode, const float temp)
  1219. {
  1220. return
  1221. snprintf(buf, sz, "%*.*f%sC"
  1222. , pad
  1223. , (highprecision ? 1 : 0)
  1224. , temp
  1225. , (unicode ? U8_DEGREE : "")
  1226. );
  1227. }
  1228. int format_temperature_sz(const int numsz, const bool unicode)
  1229. {
  1230. return numsz + (unicode ? 2 : 1);
  1231. }
  1232. int bfg_vsnprintf(char * const buf, size_t sz, const char *fmt, va_list ap)
  1233. {
  1234. char *s = buf;
  1235. size_t L;
  1236. int arg_d, arg_d_2;
  1237. void *arg_p;
  1238. long arg_ld;
  1239. int64_t arg_d64;
  1240. double arg_f, arg_f_2;
  1241. int rv = 0;
  1242. for (const char *p = fmt; ; ++p)
  1243. {
  1244. switch (p[0])
  1245. {
  1246. case '\0':
  1247. case '\b':
  1248. case '%':
  1249. if ( (L = (p - fmt)) )
  1250. {
  1251. char fmtcp[L+1];
  1252. memcpy(fmtcp, fmt, L);
  1253. fmtcp[L] = '\0';
  1254. _SNP2(vsnprintf, fmtcp, ap);
  1255. fmt += L;
  1256. }
  1257. if (!fmt[0])
  1258. return (s - buf);
  1259. if (fmt[0] == '\b')
  1260. {
  1261. // BFGMiner custom formatting
  1262. switch (fmt[1])
  1263. {
  1264. case 1: // format_tm
  1265. arg_d = va_arg(ap, int);
  1266. arg_p = va_arg(ap, void*);
  1267. arg_ld = va_arg(ap, long);
  1268. _SNP2(format_tm2, arg_d, arg_p, arg_ld);
  1269. L = sizeof(BPRItm);
  1270. break;
  1271. case 2: // format_timestamp
  1272. arg_d = va_arg(ap, int);
  1273. arg_p = va_arg(ap, void*);
  1274. _SNP2(format_timestamp2, arg_d, arg_p);
  1275. L = sizeof(BPRIts);
  1276. break;
  1277. case 3: // format_time_t
  1278. arg_d = va_arg(ap, int);
  1279. arg_d64 = va_arg(ap, int64_t);
  1280. _SNP2(format_time_t2, arg_d, arg_d64);
  1281. L = sizeof(BPRItt);
  1282. break;
  1283. case 4: // format_elapsed
  1284. arg_d = va_arg(ap, int);
  1285. arg_d_2 = va_arg(ap, int);
  1286. _SNP2(format_elapsed2, arg_d, arg_d_2);
  1287. L = sizeof(BPRIte);
  1288. break;
  1289. case 5: // format_unit (int-precision)
  1290. case 6: // format_unit (float-precision)
  1291. arg_p = va_arg(ap, void*);
  1292. arg_d = va_arg(ap, int);
  1293. arg_f = va_arg(ap, double);
  1294. arg_d_2 = va_arg(ap, int);
  1295. _SNP2(format_unit2, (fmt[1] == 6), arg_p, arg_d, arg_f, arg_d_2);
  1296. L = sizeof(BPRInd);
  1297. break;
  1298. case 7: // temperature
  1299. arg_f = va_arg(ap, double);
  1300. _SNP2(format_temperature2, 0, false, true, arg_f);
  1301. L = sizeof(BPRItp);
  1302. break;
  1303. case 8: // percentage, 2nd arg is OTHERS
  1304. case 9: // percentage, 2nd arg is TOTAL
  1305. arg_f = va_arg(ap, double);
  1306. arg_f_2 = va_arg(ap, double);
  1307. if (fmt[1] == 8)
  1308. arg_f_2 += arg_f;
  1309. _SNP2(percentf3, arg_f, arg_f_2);
  1310. L = sizeof(BPRIpgo);
  1311. break;
  1312. }
  1313. fmt += (L - 1);
  1314. p = fmt - 1;
  1315. break;
  1316. }
  1317. // Pass anything else through vsprintf above
  1318. }
  1319. }
  1320. }
  1321. int bfg_snprintf(char * const buf, size_t sz, const char * const fmt, ...)
  1322. {
  1323. va_list ap;
  1324. va_start(ap, fmt);
  1325. int rv = bfg_vsnprintf(buf, sz, fmt, ap);
  1326. va_end(ap);
  1327. return rv;
  1328. }
  1329. static
  1330. void _test_bfg_sprintf(const char * const testname, const char * const fmt, const char * const expected, ...)
  1331. {
  1332. int len = strlen(expected), rv;
  1333. char buf[len + 3];
  1334. va_list ap, ap2;
  1335. va_start(ap, expected);
  1336. buf[len + 2] = '\0';
  1337. // NOTE: Some systems error on 0-sized buffers :(
  1338. for (int i = 1; i < len + 2; ++i)
  1339. {
  1340. memset(buf, 'X', len + 2);
  1341. va_copy(ap2, ap);
  1342. rv = bfg_vsnprintf(buf, i, fmt, ap2);
  1343. va_end(ap2);
  1344. if ( (len != rv) // Return value must be full length
  1345. || ((i > 1) ? memcmp(buf, expected, i - 1) : 0) // Data before end point must match expectations
  1346. || (buf[i - 1]) ) // Final byte in buffer must be null
  1347. applog(LOG_WARNING, "bfg_snprintf test %s/%d failed: returned %d bytes \"%s\" with size %d", testname, i, strlen(buf), buf, rv);
  1348. }
  1349. // Check extra buffer
  1350. rv = bfg_vsnprintf(buf, len + 2, fmt, ap2);
  1351. if (len != rv || memcmp(buf, expected, len + 1))
  1352. applog(LOG_WARNING, "bfg_snprintf test %s/x failed: returned %d bytes \"%s\" with size %d", testname, strlen(buf), buf, rv);
  1353. }
  1354. #define _test_bfg_sprintf(fmt, ...) _test_bfg_sprintf(#fmt, fmt, __VA_ARGS__)
  1355. void test_bfg_snprintf()
  1356. {
  1357. struct tm tm = {
  1358. .tm_year = 115,
  1359. .tm_mon = 5,
  1360. .tm_mday = 3,
  1361. .tm_hour = 13,
  1362. .tm_min = 44,
  1363. .tm_sec = 22,
  1364. };
  1365. struct timeval tv;
  1366. time_t tt;
  1367. _test_bfg_sprintf("abc", "abc");
  1368. _test_bfg_sprintf("a%dbc", "a4bc", 4);
  1369. _test_bfg_sprintf("a%2dbc", "a 4bc", 4);
  1370. _test_bfg_sprintf("a%-2dbc", "a4 bc", 4);
  1371. _test_bfg_sprintf("a%02dbc1", "a04bc1", 4);
  1372. _test_bfg_sprintf("a%02dbc2", "a44bc2", 44);
  1373. _test_bfg_sprintf("a%sbc", "axyzbc", "xyz");
  1374. _test_bfg_sprintf("a%ubc", "a255bc", 255);
  1375. _test_bfg_sprintf("a"BPRItm"bc1", "a[2015-06-03 13:44:22.000001]bc1", (BTF_BRACKETS | BTF_DATE | BTF_HRTIME), &tm, 1L);
  1376. _test_bfg_sprintf("a"BPRItm"bc2", "a[2015-06-03 13:44:22]bc2", (BTF_BRACKETS | BTF_DATE | BTF_TIME), &tm, 0L);
  1377. _test_bfg_sprintf("a"BPRItm"bc3", "a[2015-06-03 13:44]bc3", (BTF_BRACKETS | BTF_DATE | BTF_LRTIME), &tm, 0L);
  1378. _test_bfg_sprintf("a"BPRItm"bc4", "a[13:44:22.123456]bc4", (BTF_BRACKETS | BTF_HRTIME), &tm, 123456L);
  1379. _test_bfg_sprintf("a"BPRItm"bc5", "a13:44:22.999999bc5", (BTF_HRTIME), &tm, 999999L);
  1380. _test_bfg_sprintf("a"BPRItm"bc6", "a[2015-06-03]bc6", (BTF_BRACKETS | BTF_DATE), &tm, 0L);
  1381. _test_bfg_sprintf("a"BPRItm"bc7", "a2015-06-03bc7", (BTF_DATE), &tm, 0L);
  1382. tt = mktime(&tm);
  1383. _test_bfg_sprintf("a"BPRItt"bc", "a[2015-06-03 13:44:22.000000]bc", (BTF_BRACKETS | BTF_DATE | BTF_HRTIME), (int64_t)tt);
  1384. tv = (struct timeval){
  1385. .tv_sec = tt,
  1386. .tv_usec = 987654,
  1387. };
  1388. _test_bfg_sprintf("a"BPRIts"bc", "a[2015-06-03 13:44:22.987654]bc", (BTF_BRACKETS | BTF_DATE | BTF_HRTIME), &tv);
  1389. _test_bfg_sprintf("a"BPRIte"bc", "a[ 1 day 05:04:03]bc", (BTF_BRACKETS | BTF_DATE | BTF_TIME), 104643);
  1390. _test_bfg_sprintf("a"BPRIte"bc", "a[ 2 days 05:04:03]bc", (BTF_BRACKETS | BTF_DATE | BTF_TIME), 191043);
  1391. _test_bfg_sprintf("a"BPRInd"bc1", "a 1bc1", "x/y", H2B_NOUNIT, 1., -1);
  1392. _test_bfg_sprintf("a"BPRInd"bc2", "a 1 x/ybc2", "x/y", H2B_SHORT, 1., -1);
  1393. _test_bfg_sprintf("a"BPRInd"bc3", "a 1 x/ybc3", "x/y", H2B_SPACED, 1., -1);
  1394. _test_bfg_sprintf("a"BPRInd"bc4", "a 1 x/ybc4", "x/y", H2B_SHORT, 1., 0);
  1395. _test_bfg_sprintf("a"BPRInd"bc5", "a 0kx/ybc5", "x/y", H2B_SHORT, 1., 1);
  1396. _test_bfg_sprintf("a"BPRInd"bc6", "a 0Mx/ybc6", "x/y", H2B_SHORT, 1., 2);
  1397. _test_bfg_sprintf("a"BPRInd"bc7", "a 0Gx/ybc7", "x/y", H2B_SHORT, 1., 3);
  1398. _test_bfg_sprintf("a"BPRInd"bc8", "a 0Tx/ybc8", "x/y", H2B_SHORT, 1., 4);
  1399. _test_bfg_sprintf("a"BPRInd"bc9", "a 1kx/ybc9", "x/y", H2B_SHORT, 1e3, -1);
  1400. _test_bfg_sprintf("a"BPRInd"bcA", "a 1Mx/ybcA", "x/y", H2B_SHORT, 1e6, -1);
  1401. _test_bfg_sprintf("a"BPRInd"bcB", "a 1Gx/ybcB", "x/y", H2B_SHORT, 1e9, -1);
  1402. _test_bfg_sprintf("a"BPRInd"bcC", "a 1Tx/ybcC", "x/y", H2B_SHORT, 1e12, -1);
  1403. _test_bfg_sprintf("a"BPRInf"bc1", "a 1.0bc1", "x/y", H2B_NOUNIT, 1., -1);
  1404. _test_bfg_sprintf("a"BPRInf"bc2", "a 1.0 x/ybc2", "x/y", H2B_SHORT, 1., -1);
  1405. _test_bfg_sprintf("a"BPRInf"bc3", "a 1.0 x/ybc3", "x/y", H2B_SPACED, 1., -1);
  1406. _test_bfg_sprintf("a"BPRInf"bc4", "a 1.0 x/ybc4", "x/y", H2B_SHORT, 1., 0);
  1407. _test_bfg_sprintf("a"BPRInf"bc5", "a 0.0kx/ybc5", "x/y", H2B_SHORT, 1., 1);
  1408. _test_bfg_sprintf("a"BPRInf"bc6", "a 0.00Mx/ybc6", "x/y", H2B_SHORT, 1., 2);
  1409. _test_bfg_sprintf("a"BPRInf"bc7", "a 0.00Gx/ybc7", "x/y", H2B_SHORT, 1., 3);
  1410. _test_bfg_sprintf("a"BPRInf"bc8", "a 0.00Tx/ybc8", "x/y", H2B_SHORT, 1., 4);
  1411. _test_bfg_sprintf("a"BPRInf"bc9", "a 1.0kx/ybc9", "x/y", H2B_SHORT, 1e3, -1);
  1412. _test_bfg_sprintf("a"BPRInf"bcA", "a 1.00Mx/ybcA", "x/y", H2B_SHORT, 1e6, -1);
  1413. _test_bfg_sprintf("a"BPRInf"bcB", "a 1.00Gx/ybcB", "x/y", H2B_SHORT, 1e9, -1);
  1414. _test_bfg_sprintf("a"BPRInf"bcC", "a 1.00Tx/ybcC", "x/y", H2B_SHORT, 1e12, -1);
  1415. _test_bfg_sprintf("a"BPRItp"bc", "a80"U8_DEGREE"Cbc", 80.);
  1416. _test_bfg_sprintf("a"BPRIpgo"bc1", "anonebc1", 0., 40.);
  1417. _test_bfg_sprintf("a"BPRIpgo"bc2", "a100%bc2", 10., 0.);
  1418. _test_bfg_sprintf("a"BPRIpgo"bc3", "a 20%bc3", 10., 40.);
  1419. _test_bfg_sprintf("a"BPRIpgo"bc4", "a 80%bc4", 40., 10.);
  1420. _test_bfg_sprintf("a"BPRIpgo"bc5", "a2.4%bc5", 1., 40.);
  1421. _test_bfg_sprintf("a"BPRIpgo"bc6", "a.24%bc6", 1., 414.);
  1422. _test_bfg_sprintf("a"BPRIpgt"bc1", "anonebc1", 0., 40.);
  1423. _test_bfg_sprintf("a"BPRIpgt"bc2", "a100%bc2", 10., 10.);
  1424. _test_bfg_sprintf("a"BPRIpgt"bc3", "a 25%bc3", 10., 40.);
  1425. _test_bfg_sprintf("a"BPRIpgt"bc4", "a 40%bc4", 40., 100.);
  1426. _test_bfg_sprintf("a"BPRIpgt"bc5", "a2.5%bc5", 1., 40.);
  1427. _test_bfg_sprintf("a"BPRIpgt"bc6", "a.24%bc6", 1., 414.);
  1428. }
  1429. bool extract_sockaddr(struct pool *pool, char *url)
  1430. {
  1431. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1432. char url_address[256], port[6];
  1433. int url_len, port_len = 0;
  1434. url_begin = strstr(url, "//");
  1435. if (!url_begin)
  1436. url_begin = url;
  1437. else
  1438. url_begin += 2;
  1439. /* Look for numeric ipv6 entries */
  1440. ipv6_begin = strstr(url_begin, "[");
  1441. ipv6_end = strstr(url_begin, "]");
  1442. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1443. url_end = strstr(ipv6_end, ":");
  1444. else
  1445. url_end = strstr(url_begin, ":");
  1446. if (url_end) {
  1447. url_len = url_end - url_begin;
  1448. port_len = strlen(url_begin) - url_len - 1;
  1449. if (port_len < 1)
  1450. return false;
  1451. port_start = url_end + 1;
  1452. } else
  1453. url_len = strlen(url_begin);
  1454. if (url_len < 1)
  1455. return false;
  1456. sprintf(url_address, "%.*s", url_len, url_begin);
  1457. if (port_len)
  1458. snprintf(port, 6, "%.*s", port_len, port_start);
  1459. else
  1460. strcpy(port, "80");
  1461. free(pool->stratum_port);
  1462. pool->stratum_port = strdup(port);
  1463. free(pool->sockaddr_url);
  1464. pool->sockaddr_url = strdup(url_address);
  1465. return true;
  1466. }
  1467. enum send_ret {
  1468. SEND_OK,
  1469. SEND_SELECTFAIL,
  1470. SEND_SENDFAIL,
  1471. SEND_INACTIVE
  1472. };
  1473. /* Send a single command across a socket, appending \n to it. This should all
  1474. * be done under stratum lock except when first establishing the socket */
  1475. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1476. {
  1477. SOCKETTYPE sock = pool->sock;
  1478. ssize_t ssent = 0;
  1479. strcat(s, "\n");
  1480. len++;
  1481. while (len > 0 ) {
  1482. struct timeval timeout = {1, 0};
  1483. ssize_t sent;
  1484. fd_set wd;
  1485. FD_ZERO(&wd);
  1486. FD_SET(sock, &wd);
  1487. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  1488. return SEND_SELECTFAIL;
  1489. #ifdef __APPLE__
  1490. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1491. #elif WIN32
  1492. sent = send(pool->sock, s + ssent, len, 0);
  1493. #else
  1494. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1495. #endif
  1496. if (sent < 0) {
  1497. if (!sock_blocks())
  1498. return SEND_SENDFAIL;
  1499. sent = 0;
  1500. }
  1501. ssent += sent;
  1502. len -= sent;
  1503. }
  1504. pool->cgminer_pool_stats.times_sent++;
  1505. pool->cgminer_pool_stats.bytes_sent += ssent;
  1506. total_bytes_sent += ssent;
  1507. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1508. return SEND_OK;
  1509. }
  1510. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1511. {
  1512. enum send_ret ret = SEND_INACTIVE;
  1513. if (opt_protocol)
  1514. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1515. mutex_lock(&pool->stratum_lock);
  1516. if (pool->stratum_active || force)
  1517. ret = __stratum_send(pool, s, len);
  1518. mutex_unlock(&pool->stratum_lock);
  1519. /* This is to avoid doing applog under stratum_lock */
  1520. switch (ret) {
  1521. default:
  1522. case SEND_OK:
  1523. break;
  1524. case SEND_SELECTFAIL:
  1525. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1526. suspend_stratum(pool);
  1527. break;
  1528. case SEND_SENDFAIL:
  1529. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1530. suspend_stratum(pool);
  1531. break;
  1532. case SEND_INACTIVE:
  1533. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1534. break;
  1535. }
  1536. return (ret == SEND_OK);
  1537. }
  1538. static bool socket_full(struct pool *pool, bool wait)
  1539. {
  1540. SOCKETTYPE sock = pool->sock;
  1541. struct timeval timeout;
  1542. fd_set rd;
  1543. FD_ZERO(&rd);
  1544. FD_SET(sock, &rd);
  1545. timeout.tv_usec = 0;
  1546. if (wait)
  1547. timeout.tv_sec = 60;
  1548. else
  1549. timeout.tv_sec = 1;
  1550. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1551. return true;
  1552. return false;
  1553. }
  1554. /* Check to see if Santa's been good to you */
  1555. bool sock_full(struct pool *pool)
  1556. {
  1557. if (strlen(pool->sockbuf))
  1558. return true;
  1559. return (socket_full(pool, false));
  1560. }
  1561. static void clear_sockbuf(struct pool *pool)
  1562. {
  1563. strcpy(pool->sockbuf, "");
  1564. }
  1565. static void clear_sock(struct pool *pool)
  1566. {
  1567. ssize_t n;
  1568. mutex_lock(&pool->stratum_lock);
  1569. do {
  1570. if (pool->sock)
  1571. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1572. else
  1573. n = 0;
  1574. } while (n > 0);
  1575. mutex_unlock(&pool->stratum_lock);
  1576. clear_sockbuf(pool);
  1577. }
  1578. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1579. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1580. * and zeroing the new memory */
  1581. static void recalloc_sock(struct pool *pool, size_t len)
  1582. {
  1583. size_t old, new;
  1584. old = strlen(pool->sockbuf);
  1585. new = old + len + 1;
  1586. if (new < pool->sockbuf_size)
  1587. return;
  1588. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1589. // Avoid potentially recursive locking
  1590. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1591. pool->sockbuf = realloc(pool->sockbuf, new);
  1592. if (!pool->sockbuf)
  1593. quit(1, "Failed to realloc pool sockbuf in recalloc_sock");
  1594. memset(pool->sockbuf + old, 0, new - old);
  1595. pool->sockbuf_size = new;
  1596. }
  1597. /* Peeks at a socket to find the first end of line and then reads just that
  1598. * from the socket and returns that as a malloced char */
  1599. char *recv_line(struct pool *pool)
  1600. {
  1601. ssize_t len, buflen;
  1602. char *tok, *sret = NULL;
  1603. if (!strstr(pool->sockbuf, "\n")) {
  1604. struct timeval rstart, now;
  1605. cgtime(&rstart);
  1606. if (!socket_full(pool, true)) {
  1607. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1608. goto out;
  1609. }
  1610. do {
  1611. char s[RBUFSIZE];
  1612. size_t slen;
  1613. ssize_t n;
  1614. memset(s, 0, RBUFSIZE);
  1615. n = recv(pool->sock, s, RECVSIZE, 0);
  1616. if (!n) {
  1617. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1618. suspend_stratum(pool);
  1619. break;
  1620. }
  1621. if (n < 0) {
  1622. //Save errno from being overweitten bei socket_ commands
  1623. int socket_recv_errno;
  1624. socket_recv_errno = SOCKERR;
  1625. if (!sock_blocks() || !socket_full(pool, true)) {
  1626. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %s", bfg_strerror(socket_recv_errno, BST_SOCKET));
  1627. suspend_stratum(pool);
  1628. break;
  1629. }
  1630. } else {
  1631. slen = strlen(s);
  1632. recalloc_sock(pool, slen);
  1633. strcat(pool->sockbuf, s);
  1634. }
  1635. cgtime(&now);
  1636. } while (tdiff(&now, &rstart) < 60 && !strstr(pool->sockbuf, "\n"));
  1637. }
  1638. buflen = strlen(pool->sockbuf);
  1639. tok = strtok(pool->sockbuf, "\n");
  1640. if (!tok) {
  1641. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1642. goto out;
  1643. }
  1644. sret = strdup(tok);
  1645. len = strlen(sret);
  1646. /* Copy what's left in the buffer after the \n, including the
  1647. * terminating \0 */
  1648. if (buflen > len + 1)
  1649. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1650. else
  1651. strcpy(pool->sockbuf, "");
  1652. pool->cgminer_pool_stats.times_received++;
  1653. pool->cgminer_pool_stats.bytes_received += len;
  1654. total_bytes_rcvd += len;
  1655. pool->cgminer_pool_stats.net_bytes_received += len;
  1656. out:
  1657. if (!sret)
  1658. clear_sock(pool);
  1659. else if (opt_protocol)
  1660. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1661. return sret;
  1662. }
  1663. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1664. * flag, but this is compatible with 2.0. */
  1665. char *json_dumps_ANY(json_t *json, size_t flags)
  1666. {
  1667. switch (json_typeof(json))
  1668. {
  1669. case JSON_ARRAY:
  1670. case JSON_OBJECT:
  1671. return json_dumps(json, flags);
  1672. default:
  1673. break;
  1674. }
  1675. char *rv;
  1676. #ifdef JSON_ENCODE_ANY
  1677. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1678. if (rv)
  1679. return rv;
  1680. #endif
  1681. json_t *tmp = json_array();
  1682. char *s;
  1683. int i;
  1684. size_t len;
  1685. if (!tmp)
  1686. quit(1, "json_dumps_ANY failed to allocate json array");
  1687. if (json_array_append(tmp, json))
  1688. quit(1, "json_dumps_ANY failed to append temporary array");
  1689. s = json_dumps(tmp, flags);
  1690. if (!s)
  1691. return NULL;
  1692. for (i = 0; s[i] != '['; ++i)
  1693. if (unlikely(!(s[i] && isCspace(s[i]))))
  1694. quit(1, "json_dumps_ANY failed to find opening bracket in array dump");
  1695. len = strlen(&s[++i]) - 1;
  1696. if (unlikely(s[i+len] != ']'))
  1697. quit(1, "json_dumps_ANY failed to find closing bracket in array dump");
  1698. rv = malloc(len + 1);
  1699. memcpy(rv, &s[i], len);
  1700. rv[len] = '\0';
  1701. free(s);
  1702. json_decref(tmp);
  1703. return rv;
  1704. }
  1705. /* Extracts a string value from a json array with error checking. To be used
  1706. * when the value of the string returned is only examined and not to be stored.
  1707. * See json_array_string below */
  1708. static char *__json_array_string(json_t *val, unsigned int entry)
  1709. {
  1710. json_t *arr_entry;
  1711. if (json_is_null(val))
  1712. return NULL;
  1713. if (!json_is_array(val))
  1714. return NULL;
  1715. if (entry > json_array_size(val))
  1716. return NULL;
  1717. arr_entry = json_array_get(val, entry);
  1718. if (!json_is_string(arr_entry))
  1719. return NULL;
  1720. return (char *)json_string_value(arr_entry);
  1721. }
  1722. /* Creates a freshly malloced dup of __json_array_string */
  1723. static char *json_array_string(json_t *val, unsigned int entry)
  1724. {
  1725. char *buf = __json_array_string(val, entry);
  1726. if (buf)
  1727. return strdup(buf);
  1728. return NULL;
  1729. }
  1730. void stratum_probe_transparency(struct pool *pool)
  1731. {
  1732. // Request transaction data to discourage pools from doing anything shady
  1733. char s[1024];
  1734. int sLen;
  1735. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1736. pool->swork.job_id,
  1737. pool->swork.job_id);
  1738. stratum_send(pool, s, sLen);
  1739. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  1740. cgtime(&pool->swork.tv_transparency);
  1741. pool->swork.transparency_probed = true;
  1742. }
  1743. static bool parse_notify(struct pool *pool, json_t *val)
  1744. {
  1745. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1746. bool clean, ret = false;
  1747. int merkles, i;
  1748. size_t cb1_len, cb2_len;
  1749. json_t *arr;
  1750. arr = json_array_get(val, 4);
  1751. if (!arr || !json_is_array(arr))
  1752. goto out;
  1753. merkles = json_array_size(arr);
  1754. for (i = 0; i < merkles; i++)
  1755. if (!json_is_string(json_array_get(arr, i)))
  1756. goto out;
  1757. prev_hash = __json_array_string(val, 1);
  1758. coinbase1 = __json_array_string(val, 2);
  1759. coinbase2 = __json_array_string(val, 3);
  1760. bbversion = __json_array_string(val, 5);
  1761. nbit = __json_array_string(val, 6);
  1762. ntime = __json_array_string(val, 7);
  1763. clean = json_is_true(json_array_get(val, 8));
  1764. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  1765. goto out;
  1766. job_id = json_array_string(val, 0);
  1767. if (!job_id)
  1768. goto out;
  1769. cg_wlock(&pool->data_lock);
  1770. cgtime(&pool->swork.tv_received);
  1771. free(pool->swork.job_id);
  1772. pool->swork.job_id = job_id;
  1773. pool->submit_old = !clean;
  1774. pool->swork.clean = true;
  1775. hex2bin(&pool->swork.header1[0], bbversion, 4);
  1776. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  1777. hex2bin((void*)&pool->swork.ntime, ntime, 4);
  1778. pool->swork.ntime = be32toh(pool->swork.ntime);
  1779. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  1780. cb1_len = strlen(coinbase1) / 2;
  1781. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  1782. cb2_len = strlen(coinbase2) / 2;
  1783. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->n2size + cb2_len);
  1784. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  1785. hex2bin(coinbase, coinbase1, cb1_len);
  1786. hex2bin(&coinbase[cb1_len], pool->nonce1, pool->n1_len);
  1787. // NOTE: gap for nonce2, filled at work generation time
  1788. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->n2size], coinbase2, cb2_len);
  1789. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  1790. for (i = 0; i < merkles; i++)
  1791. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  1792. pool->swork.merkles = merkles;
  1793. if (clean)
  1794. pool->nonce2 = 0;
  1795. cg_wunlock(&pool->data_lock);
  1796. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1797. pool->pool_no, job_id);
  1798. if (opt_debug && opt_protocol)
  1799. {
  1800. applog(LOG_DEBUG, "job_id: %s", job_id);
  1801. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1802. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1803. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1804. for (i = 0; i < merkles; i++)
  1805. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  1806. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1807. applog(LOG_DEBUG, "nbit: %s", nbit);
  1808. applog(LOG_DEBUG, "ntime: %s", ntime);
  1809. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1810. }
  1811. /* A notify message is the closest stratum gets to a getwork */
  1812. pool->getwork_requested++;
  1813. total_getworks++;
  1814. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  1815. if (pool->stratum_init)
  1816. stratum_probe_transparency(pool);
  1817. ret = true;
  1818. out:
  1819. return ret;
  1820. }
  1821. static bool parse_diff(struct pool *pool, json_t *val)
  1822. {
  1823. double diff;
  1824. diff = json_number_value(json_array_get(val, 0));
  1825. if (diff == 0)
  1826. return false;
  1827. cg_wlock(&pool->data_lock);
  1828. pool->swork.diff = diff;
  1829. cg_wunlock(&pool->data_lock);
  1830. applog(LOG_DEBUG, "Pool %d stratum bdifficulty set to %f", pool->pool_no, diff);
  1831. return true;
  1832. }
  1833. static bool parse_reconnect(struct pool *pool, json_t *val)
  1834. {
  1835. char *url, *port, address[256];
  1836. memset(address, 0, 255);
  1837. url = (char *)json_string_value(json_array_get(val, 0));
  1838. if (!url)
  1839. url = pool->sockaddr_url;
  1840. port = (char *)json_string_value(json_array_get(val, 1));
  1841. if (!port)
  1842. port = pool->stratum_port;
  1843. sprintf(address, "%s:%s", url, port);
  1844. if (!extract_sockaddr(pool, address))
  1845. return false;
  1846. pool->stratum_url = pool->sockaddr_url;
  1847. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1848. if (!restart_stratum(pool))
  1849. return false;
  1850. return true;
  1851. }
  1852. static bool send_version(struct pool *pool, json_t *val)
  1853. {
  1854. char s[RBUFSIZE], *idstr;
  1855. json_t *id = json_object_get(val, "id");
  1856. if (!(id && !json_is_null(id)))
  1857. return false;
  1858. idstr = json_dumps_ANY(id, 0);
  1859. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1860. free(idstr);
  1861. if (!stratum_send(pool, s, strlen(s)))
  1862. return false;
  1863. return true;
  1864. }
  1865. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  1866. {
  1867. char *msg;
  1868. char s[RBUFSIZE], *idstr;
  1869. json_t *id = json_object_get(val, "id");
  1870. msg = json_array_string(params, 0);
  1871. if (likely(msg))
  1872. {
  1873. free(pool->admin_msg);
  1874. pool->admin_msg = msg;
  1875. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  1876. }
  1877. if (!(id && !json_is_null(id)))
  1878. return true;
  1879. idstr = json_dumps_ANY(id, 0);
  1880. if (likely(msg))
  1881. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  1882. else
  1883. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  1884. free(idstr);
  1885. if (!stratum_send(pool, s, strlen(s)))
  1886. return false;
  1887. return true;
  1888. }
  1889. bool parse_method(struct pool *pool, char *s)
  1890. {
  1891. json_t *val = NULL, *method, *err_val, *params;
  1892. json_error_t err;
  1893. bool ret = false;
  1894. char *buf;
  1895. if (!s)
  1896. goto out;
  1897. val = JSON_LOADS(s, &err);
  1898. if (!val) {
  1899. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1900. goto out;
  1901. }
  1902. method = json_object_get(val, "method");
  1903. if (!method)
  1904. goto out;
  1905. err_val = json_object_get(val, "error");
  1906. params = json_object_get(val, "params");
  1907. if (err_val && !json_is_null(err_val)) {
  1908. char *ss;
  1909. if (err_val)
  1910. ss = json_dumps(err_val, JSON_INDENT(3));
  1911. else
  1912. ss = strdup("(unknown reason)");
  1913. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1914. free(ss);
  1915. goto out;
  1916. }
  1917. buf = (char *)json_string_value(method);
  1918. if (!buf)
  1919. goto out;
  1920. if (!strncasecmp(buf, "mining.notify", 13)) {
  1921. if (parse_notify(pool, params))
  1922. pool->stratum_notify = ret = true;
  1923. else
  1924. pool->stratum_notify = ret = false;
  1925. goto out;
  1926. }
  1927. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1928. ret = true;
  1929. goto out;
  1930. }
  1931. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1932. ret = true;
  1933. goto out;
  1934. }
  1935. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1936. ret = true;
  1937. goto out;
  1938. }
  1939. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  1940. ret = true;
  1941. goto out;
  1942. }
  1943. out:
  1944. if (val)
  1945. json_decref(val);
  1946. return ret;
  1947. }
  1948. extern bool parse_stratum_response(struct pool *, char *s);
  1949. bool auth_stratum(struct pool *pool)
  1950. {
  1951. json_t *val = NULL, *res_val, *err_val;
  1952. char s[RBUFSIZE], *sret = NULL;
  1953. json_error_t err;
  1954. bool ret = false;
  1955. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1956. pool->rpc_user, pool->rpc_pass);
  1957. if (!stratum_send(pool, s, strlen(s)))
  1958. goto out;
  1959. /* Parse all data in the queue and anything left should be auth */
  1960. while (42) {
  1961. sret = recv_line(pool);
  1962. if (!sret)
  1963. goto out;
  1964. if (parse_method(pool, sret))
  1965. free(sret);
  1966. else
  1967. break;
  1968. }
  1969. val = JSON_LOADS(sret, &err);
  1970. free(sret);
  1971. res_val = json_object_get(val, "result");
  1972. err_val = json_object_get(val, "error");
  1973. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1974. char *ss;
  1975. if (err_val)
  1976. ss = json_dumps(err_val, JSON_INDENT(3));
  1977. else
  1978. ss = strdup("(unknown reason)");
  1979. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1980. free(ss);
  1981. goto out;
  1982. }
  1983. ret = true;
  1984. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1985. pool->probed = true;
  1986. successful_connect = true;
  1987. out:
  1988. if (val)
  1989. json_decref(val);
  1990. if (pool->stratum_notify)
  1991. stratum_probe_transparency(pool);
  1992. return ret;
  1993. }
  1994. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1995. {
  1996. struct pool *pool = clientp;
  1997. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1998. pool->sock = sck;
  1999. return sck;
  2000. }
  2001. static bool setup_stratum_curl(struct pool *pool)
  2002. {
  2003. char curl_err_str[CURL_ERROR_SIZE];
  2004. CURL *curl = NULL;
  2005. char s[RBUFSIZE];
  2006. bool ret = false;
  2007. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  2008. mutex_lock(&pool->stratum_lock);
  2009. timer_unset(&pool->swork.tv_transparency);
  2010. pool->stratum_active = false;
  2011. pool->stratum_notify = false;
  2012. pool->swork.transparency_probed = false;
  2013. if (pool->stratum_curl)
  2014. curl_easy_cleanup(pool->stratum_curl);
  2015. pool->stratum_curl = curl_easy_init();
  2016. if (unlikely(!pool->stratum_curl))
  2017. quit(1, "Failed to curl_easy_init in initiate_stratum");
  2018. if (pool->sockbuf)
  2019. pool->sockbuf[0] = '\0';
  2020. curl = pool->stratum_curl;
  2021. if (!pool->sockbuf) {
  2022. pool->sockbuf = calloc(RBUFSIZE, 1);
  2023. if (!pool->sockbuf)
  2024. quit(1, "Failed to calloc pool sockbuf in initiate_stratum");
  2025. pool->sockbuf_size = RBUFSIZE;
  2026. }
  2027. /* Create a http url for use with curl */
  2028. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  2029. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  2030. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  2031. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  2032. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  2033. curl_easy_setopt(curl, CURLOPT_URL, s);
  2034. if (!opt_delaynet)
  2035. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  2036. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  2037. * to enable it */
  2038. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  2039. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  2040. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2041. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  2042. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  2043. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  2044. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  2045. if (pool->rpc_proxy) {
  2046. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  2047. } else if (opt_socks_proxy) {
  2048. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  2049. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  2050. }
  2051. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  2052. pool->sock = INVSOCK;
  2053. if (curl_easy_perform(curl)) {
  2054. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  2055. errout:
  2056. curl_easy_cleanup(curl);
  2057. pool->stratum_curl = NULL;
  2058. goto out;
  2059. }
  2060. if (pool->sock == INVSOCK)
  2061. {
  2062. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  2063. goto errout;
  2064. }
  2065. keep_sockalive(pool->sock);
  2066. pool->cgminer_pool_stats.times_sent++;
  2067. pool->cgminer_pool_stats.times_received++;
  2068. ret = true;
  2069. out:
  2070. mutex_unlock(&pool->stratum_lock);
  2071. return ret;
  2072. }
  2073. static char *get_sessionid(json_t *val)
  2074. {
  2075. char *ret = NULL;
  2076. json_t *arr_val;
  2077. int arrsize, i;
  2078. arr_val = json_array_get(val, 0);
  2079. if (!arr_val || !json_is_array(arr_val))
  2080. goto out;
  2081. arrsize = json_array_size(arr_val);
  2082. for (i = 0; i < arrsize; i++) {
  2083. json_t *arr = json_array_get(arr_val, i);
  2084. char *notify;
  2085. if (!arr | !json_is_array(arr))
  2086. break;
  2087. notify = __json_array_string(arr, 0);
  2088. if (!notify)
  2089. continue;
  2090. if (!strncasecmp(notify, "mining.notify", 13)) {
  2091. ret = json_array_string(arr, 1);
  2092. break;
  2093. }
  2094. }
  2095. out:
  2096. return ret;
  2097. }
  2098. void suspend_stratum(struct pool *pool)
  2099. {
  2100. clear_sockbuf(pool);
  2101. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2102. mutex_lock(&pool->stratum_lock);
  2103. pool->stratum_active = pool->stratum_notify = false;
  2104. if (pool->stratum_curl) {
  2105. curl_easy_cleanup(pool->stratum_curl);
  2106. }
  2107. pool->stratum_curl = NULL;
  2108. pool->sock = INVSOCK;
  2109. mutex_unlock(&pool->stratum_lock);
  2110. }
  2111. bool initiate_stratum(struct pool *pool)
  2112. {
  2113. bool ret = false, recvd = false, noresume = false, sockd = false;
  2114. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  2115. json_t *val = NULL, *res_val, *err_val;
  2116. json_error_t err;
  2117. int n2size;
  2118. resend:
  2119. if (!setup_stratum_curl(pool)) {
  2120. sockd = false;
  2121. goto out;
  2122. }
  2123. sockd = true;
  2124. if (noresume) {
  2125. /* Get rid of any crap lying around if we're resending */
  2126. clear_sock(pool);
  2127. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2128. } else {
  2129. if (pool->sessionid)
  2130. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2131. else
  2132. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  2133. }
  2134. if (!_stratum_send(pool, s, strlen(s), true)) {
  2135. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2136. goto out;
  2137. }
  2138. if (!socket_full(pool, true)) {
  2139. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2140. goto out;
  2141. }
  2142. sret = recv_line(pool);
  2143. if (!sret)
  2144. goto out;
  2145. recvd = true;
  2146. val = JSON_LOADS(sret, &err);
  2147. free(sret);
  2148. if (!val) {
  2149. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2150. goto out;
  2151. }
  2152. res_val = json_object_get(val, "result");
  2153. err_val = json_object_get(val, "error");
  2154. if (!res_val || json_is_null(res_val) ||
  2155. (err_val && !json_is_null(err_val))) {
  2156. char *ss;
  2157. if (err_val)
  2158. ss = json_dumps(err_val, JSON_INDENT(3));
  2159. else
  2160. ss = strdup("(unknown reason)");
  2161. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2162. free(ss);
  2163. goto out;
  2164. }
  2165. sessionid = get_sessionid(res_val);
  2166. if (!sessionid)
  2167. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2168. nonce1 = json_array_string(res_val, 1);
  2169. if (!nonce1) {
  2170. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  2171. free(sessionid);
  2172. goto out;
  2173. }
  2174. n2size = json_integer_value(json_array_get(res_val, 2));
  2175. if (!n2size) {
  2176. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  2177. free(sessionid);
  2178. free(nonce1);
  2179. goto out;
  2180. }
  2181. cg_wlock(&pool->data_lock);
  2182. free(pool->sessionid);
  2183. pool->sessionid = sessionid;
  2184. free(pool->nonce1);
  2185. pool->nonce1 = nonce1;
  2186. pool->n1_len = strlen(nonce1) / 2;
  2187. pool->n2size = n2size;
  2188. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  2189. #ifdef WORDS_BIGENDIAN
  2190. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  2191. #endif
  2192. cg_wunlock(&pool->data_lock);
  2193. if (sessionid)
  2194. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2195. ret = true;
  2196. out:
  2197. if (val)
  2198. json_decref(val);
  2199. if (ret) {
  2200. if (!pool->stratum_url)
  2201. pool->stratum_url = pool->sockaddr_url;
  2202. pool->stratum_active = true;
  2203. pool->swork.diff = 1;
  2204. if (opt_protocol) {
  2205. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2206. pool->pool_no, pool->nonce1, pool->n2size);
  2207. }
  2208. } else {
  2209. if (recvd && !noresume) {
  2210. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2211. noresume = true;
  2212. goto resend;
  2213. }
  2214. applog(LOG_DEBUG, "Initiate stratum failed");
  2215. if (sockd)
  2216. suspend_stratum(pool);
  2217. }
  2218. return ret;
  2219. }
  2220. bool restart_stratum(struct pool *pool)
  2221. {
  2222. if (pool->stratum_active)
  2223. suspend_stratum(pool);
  2224. if (!initiate_stratum(pool))
  2225. return false;
  2226. if (!auth_stratum(pool))
  2227. return false;
  2228. return true;
  2229. }
  2230. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2231. {
  2232. dev->device_last_not_well = time(NULL);
  2233. cgtime(&dev->tv_device_last_not_well);
  2234. dev->device_not_well_reason = reason;
  2235. switch (reason) {
  2236. case REASON_THREAD_FAIL_INIT:
  2237. dev->thread_fail_init_count++;
  2238. break;
  2239. case REASON_THREAD_ZERO_HASH:
  2240. dev->thread_zero_hash_count++;
  2241. break;
  2242. case REASON_THREAD_FAIL_QUEUE:
  2243. dev->thread_fail_queue_count++;
  2244. break;
  2245. case REASON_DEV_SICK_IDLE_60:
  2246. dev->dev_sick_idle_60_count++;
  2247. break;
  2248. case REASON_DEV_DEAD_IDLE_600:
  2249. dev->dev_dead_idle_600_count++;
  2250. break;
  2251. case REASON_DEV_NOSTART:
  2252. dev->dev_nostart_count++;
  2253. break;
  2254. case REASON_DEV_OVER_HEAT:
  2255. dev->dev_over_heat_count++;
  2256. break;
  2257. case REASON_DEV_THERMAL_CUTOFF:
  2258. dev->dev_thermal_cutoff_count++;
  2259. break;
  2260. case REASON_DEV_COMMS_ERROR:
  2261. dev->dev_comms_error_count++;
  2262. break;
  2263. case REASON_DEV_THROTTLE:
  2264. dev->dev_throttle_count++;
  2265. break;
  2266. }
  2267. }
  2268. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2269. void *realloc_strcat(char *ptr, char *s)
  2270. {
  2271. size_t old = strlen(ptr), len = strlen(s);
  2272. char *ret;
  2273. if (!len)
  2274. return ptr;
  2275. len += old + 1;
  2276. align_len(&len);
  2277. ret = malloc(len);
  2278. if (unlikely(!ret))
  2279. quit(1, "Failed to malloc in realloc_strcat");
  2280. sprintf(ret, "%s%s", ptr, s);
  2281. free(ptr);
  2282. return ret;
  2283. }
  2284. static
  2285. bool sanechars[] = {
  2286. false, false, false, false, false, false, false, false,
  2287. false, false, false, false, false, false, false, false,
  2288. false, false, false, false, false, false, false, false,
  2289. false, false, false, false, false, false, false, false,
  2290. false, false, false, false, false, false, false, false,
  2291. false, false, false, false, false, false, false, false,
  2292. true , true , true , true , true , true , true , true ,
  2293. true , true , false, false, false, false, false, false,
  2294. false, true , true , true , true , true , true , true ,
  2295. true , true , true , true , true , true , true , true ,
  2296. true , true , true , true , true , true , true , true ,
  2297. true , true , true , false, false, false, false, false,
  2298. false, true , true , true , true , true , true , true ,
  2299. true , true , true , true , true , true , true , true ,
  2300. true , true , true , true , true , true , true , true ,
  2301. true , true , true , false, false, false, false, false,
  2302. };
  2303. char *sanestr(char *o, char *s)
  2304. {
  2305. char *rv = o;
  2306. bool br = false;
  2307. for ( ; s[0]; ++s)
  2308. {
  2309. if (sanechars[s[0] & 0x7f])
  2310. {
  2311. if (br)
  2312. {
  2313. br = false;
  2314. if (s[0] >= '0' && s[0] <= '9')
  2315. (o++)[0] = '_';
  2316. }
  2317. (o++)[0] = s[0];
  2318. }
  2319. else
  2320. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  2321. br = true;
  2322. }
  2323. o[0] = '\0';
  2324. return rv;
  2325. }
  2326. void RenameThread(const char* name)
  2327. {
  2328. #if defined(PR_SET_NAME)
  2329. // Only the first 15 characters are used (16 - NUL terminator)
  2330. prctl(PR_SET_NAME, name, 0, 0, 0);
  2331. #elif defined(__APPLE__)
  2332. pthread_setname_np(name);
  2333. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2334. pthread_set_name_np(pthread_self(), name);
  2335. #else
  2336. // Prevent warnings for unused parameters...
  2337. (void)name;
  2338. #endif
  2339. }
  2340. static pthread_key_t key_bfgtls;
  2341. struct bfgtls_data {
  2342. char *bfg_strerror_result;
  2343. size_t bfg_strerror_resultsz;
  2344. #ifdef WIN32
  2345. LPSTR bfg_strerror_socketresult;
  2346. #endif
  2347. };
  2348. static
  2349. struct bfgtls_data *get_bfgtls()
  2350. {
  2351. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  2352. if (bfgtls)
  2353. return bfgtls;
  2354. void *p;
  2355. bfgtls = malloc(sizeof(*bfgtls));
  2356. if (!bfgtls)
  2357. quit(1, "malloc bfgtls failed");
  2358. p = malloc(64);
  2359. if (!p)
  2360. quit(1, "malloc bfg_strerror_result failed");
  2361. *bfgtls = (struct bfgtls_data){
  2362. .bfg_strerror_resultsz = 64,
  2363. .bfg_strerror_result = p,
  2364. };
  2365. if (pthread_setspecific(key_bfgtls, bfgtls))
  2366. quit(1, "pthread_setspecific failed");
  2367. return bfgtls;
  2368. }
  2369. void bfg_init_threadlocal()
  2370. {
  2371. if (pthread_key_create(&key_bfgtls, NULL))
  2372. quit(1, "pthread_key_create failed");
  2373. }
  2374. static
  2375. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  2376. {
  2377. if (minimum <= *bufszp)
  2378. return false;
  2379. while (minimum > *bufszp)
  2380. *bufszp = 2;
  2381. *bufp = realloc(*bufp, *bufszp);
  2382. if (unlikely(!*bufp))
  2383. quit(1, "realloc failed in bfg_grow_buffer");
  2384. return true;
  2385. }
  2386. static
  2387. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  2388. {
  2389. if (!src)
  2390. return NULL;
  2391. const size_t srcsz = strlen(src) + 1;
  2392. bfg_grow_buffer(bufp, bufszp, srcsz);
  2393. memcpy(*bufp, src, srcsz);
  2394. return *bufp;
  2395. }
  2396. // Guaranteed to always return some string (or quit)
  2397. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  2398. {
  2399. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2400. struct bfgtls_data *bfgtls = get_bfgtls();
  2401. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  2402. char ** const bufp = &bfgtls->bfg_strerror_result;
  2403. const char *have = NULL;
  2404. switch (type) {
  2405. case BST_LIBUSB:
  2406. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  2407. #ifdef HAVE_LIBUSB
  2408. # if HAVE_DECL_LIBUSB_ERROR_NAME
  2409. // libusb makes no guarantees for thread-safety or persistence
  2410. mutex_lock(&mutex);
  2411. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  2412. mutex_unlock(&mutex);
  2413. # endif
  2414. #endif
  2415. break;
  2416. case BST_SOCKET:
  2417. {
  2418. #ifdef WIN32
  2419. // Windows has a different namespace for socket errors
  2420. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  2421. if (*msg)
  2422. LocalFree(*msg);
  2423. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  2424. return *msg;
  2425. *msg = NULL;
  2426. break;
  2427. #endif
  2428. }
  2429. // Fallthru on non-WIN32
  2430. case BST_ERRNO:
  2431. {
  2432. #ifdef __STRERROR_S_WORKS
  2433. // FIXME: Not sure how to get this on MingW64
  2434. retry:
  2435. if (likely(!strerror_s(*bufp, *bufszp, e)))
  2436. {
  2437. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  2438. goto retry;
  2439. return *bufp;
  2440. }
  2441. // TODO: XSI strerror_r
  2442. // TODO: GNU strerror_r
  2443. #else
  2444. mutex_lock(&mutex);
  2445. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  2446. mutex_unlock(&mutex);
  2447. #endif
  2448. }
  2449. }
  2450. if (have)
  2451. return *bufp;
  2452. // Failback: Stringify the number
  2453. static const char fmt[] = "%s error #%d", *typestr;
  2454. switch (type) {
  2455. case BST_ERRNO:
  2456. typestr = "System";
  2457. break;
  2458. case BST_SOCKET:
  2459. typestr = "Socket";
  2460. break;
  2461. case BST_LIBUSB:
  2462. typestr = "libusb";
  2463. break;
  2464. default:
  2465. typestr = "Unexpected";
  2466. }
  2467. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  2468. bfg_grow_buffer(bufp, bufszp, sz);
  2469. sprintf(*bufp, fmt, typestr, e);
  2470. return *bufp;
  2471. }
  2472. void notifier_init(notifier_t pipefd)
  2473. {
  2474. #ifdef WIN32
  2475. #define WindowsErrorStr(e) bfg_strerror(e, true)
  2476. SOCKET listener, connecter, acceptor;
  2477. listener = socket(AF_INET, SOCK_STREAM, 0);
  2478. if (listener == INVALID_SOCKET)
  2479. quit(1, "Failed to create listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2480. connecter = socket(AF_INET, SOCK_STREAM, 0);
  2481. if (connecter == INVALID_SOCKET)
  2482. quit(1, "Failed to create connect socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2483. struct sockaddr_in inaddr = {
  2484. .sin_family = AF_INET,
  2485. .sin_addr = {
  2486. .s_addr = htonl(INADDR_LOOPBACK),
  2487. },
  2488. .sin_port = 0,
  2489. };
  2490. {
  2491. char reuse = 1;
  2492. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  2493. }
  2494. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  2495. quit(1, "Failed to bind listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2496. socklen_t inaddr_sz = sizeof(inaddr);
  2497. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  2498. quit(1, "Failed to getsockname in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2499. if (listen(listener, 1) == SOCKET_ERROR)
  2500. quit(1, "Failed to listen in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2501. inaddr.sin_family = AF_INET;
  2502. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2503. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  2504. quit(1, "Failed to connect in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2505. acceptor = accept(listener, NULL, NULL);
  2506. if (acceptor == INVALID_SOCKET)
  2507. quit(1, "Failed to accept in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2508. closesocket(listener);
  2509. pipefd[0] = connecter;
  2510. pipefd[1] = acceptor;
  2511. #else
  2512. if (pipe(pipefd))
  2513. quit(1, "Failed to create pipe in create_notifier");
  2514. #endif
  2515. }
  2516. void notifier_wake(notifier_t fd)
  2517. {
  2518. if (fd[1] == INVSOCK)
  2519. return;
  2520. #ifdef WIN32
  2521. (void)send(fd[1], "\0", 1, 0);
  2522. #else
  2523. (void)write(fd[1], "\0", 1);
  2524. #endif
  2525. }
  2526. void notifier_read(notifier_t fd)
  2527. {
  2528. char buf[0x10];
  2529. #ifdef WIN32
  2530. (void)recv(fd[0], buf, sizeof(buf), 0);
  2531. #else
  2532. (void)read(fd[0], buf, sizeof(buf));
  2533. #endif
  2534. }
  2535. void notifier_destroy(notifier_t fd)
  2536. {
  2537. #ifdef WIN32
  2538. closesocket(fd[0]);
  2539. closesocket(fd[1]);
  2540. #else
  2541. close(fd[0]);
  2542. close(fd[1]);
  2543. #endif
  2544. fd[0] = fd[1] = INVSOCK;
  2545. }
  2546. void _bytes_alloc_failure(size_t sz)
  2547. {
  2548. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  2549. }