util.c 84 KB

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