util.c 72 KB

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