util.c 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2014 Nate Woolls
  5. * Copyright 2010-2011 Jeff Garzik
  6. * Copyright 2012 Giel van Schijndel
  7. * Copyright 2012 Gavin Andresen
  8. * Copyright 2013 Lingchao Xu
  9. *
  10. * This program is free software; you can redistribute it and/or modify it
  11. * under the terms of the GNU General Public License as published by the Free
  12. * Software Foundation; either version 3 of the License, or (at your option)
  13. * any later version. See COPYING for more details.
  14. */
  15. #include "config.h"
  16. #include <math.h>
  17. #include <stdbool.h>
  18. #include <stdint.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <ctype.h>
  22. #include <stdarg.h>
  23. #include <string.h>
  24. #include <pthread.h>
  25. #include <jansson.h>
  26. #include <curl/curl.h>
  27. #include <time.h>
  28. #include <errno.h>
  29. #include <unistd.h>
  30. #include <sys/types.h>
  31. #ifdef HAVE_SYS_PRCTL_H
  32. # include <sys/prctl.h>
  33. #endif
  34. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  35. # include <pthread_np.h>
  36. #endif
  37. #ifndef WIN32
  38. #include <fcntl.h>
  39. # ifdef __linux
  40. # include <sys/prctl.h>
  41. # endif
  42. # include <sys/socket.h>
  43. # include <netinet/in.h>
  44. # include <netinet/tcp.h>
  45. # include <netdb.h>
  46. #else
  47. # include <windows.h>
  48. # include <winsock2.h>
  49. # include <mstcpip.h>
  50. # include <ws2tcpip.h>
  51. # include <mmsystem.h>
  52. #endif
  53. #include <libbase58.h>
  54. #include <utlist.h>
  55. #ifdef NEED_BFG_LOWL_VCOM
  56. #include "lowl-vcom.h"
  57. #endif
  58. #include "miner.h"
  59. #include "compat.h"
  60. #include "util.h"
  61. #include "version.h"
  62. #define DEFAULT_SOCKWAIT 60
  63. bool successful_connect = false;
  64. struct timeval nettime;
  65. struct data_buffer {
  66. void *buf;
  67. size_t len;
  68. curl_socket_t *idlemarker;
  69. };
  70. struct upload_buffer {
  71. const void *buf;
  72. size_t len;
  73. };
  74. struct header_info {
  75. char *lp_path;
  76. int rolltime;
  77. char *reason;
  78. char *stratum_url;
  79. bool hadrolltime;
  80. bool canroll;
  81. bool hadexpire;
  82. };
  83. struct tq_ent {
  84. void *data;
  85. struct tq_ent *prev;
  86. struct tq_ent *next;
  87. };
  88. static void databuf_free(struct data_buffer *db)
  89. {
  90. if (!db)
  91. return;
  92. free(db->buf);
  93. #ifdef DEBUG_DATABUF
  94. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  95. #endif
  96. memset(db, 0, sizeof(*db));
  97. }
  98. struct json_rpc_call_state {
  99. struct data_buffer all_data;
  100. struct header_info hi;
  101. void *priv;
  102. char curl_err_str[CURL_ERROR_SIZE];
  103. struct curl_slist *headers;
  104. struct upload_buffer upload_data;
  105. struct pool *pool;
  106. bool longpoll;
  107. };
  108. // aka data_buffer_write
  109. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  110. void *user_data)
  111. {
  112. struct data_buffer *db = user_data;
  113. size_t oldlen, newlen;
  114. oldlen = db->len;
  115. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  116. return 0;
  117. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  118. nmemb = (SIZE_MAX - oldlen) / size;
  119. size_t len = size * nmemb;
  120. void *newmem;
  121. static const unsigned char zero = 0;
  122. if (db->idlemarker) {
  123. const unsigned char *cptr = ptr;
  124. for (size_t i = 0; i < len; ++i)
  125. if (!(isCspace(cptr[i]) || cptr[i] == '{')) {
  126. *db->idlemarker = CURL_SOCKET_BAD;
  127. db->idlemarker = NULL;
  128. break;
  129. }
  130. }
  131. newlen = oldlen + len;
  132. newmem = realloc(db->buf, newlen + 1);
  133. #ifdef DEBUG_DATABUF
  134. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  135. #endif
  136. if (!newmem)
  137. return 0;
  138. db->buf = newmem;
  139. db->len = newlen;
  140. memcpy(db->buf + oldlen, ptr, len);
  141. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  142. return nmemb;
  143. }
  144. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  145. void *user_data)
  146. {
  147. struct json_rpc_call_state * const state = user_data;
  148. struct upload_buffer * const ub = &state->upload_data;
  149. unsigned int len = size * nmemb;
  150. if (state->longpoll)
  151. {
  152. struct pool * const pool = state->pool;
  153. pool->lp_active = true;
  154. }
  155. if (len > ub->len)
  156. len = ub->len;
  157. if (len) {
  158. memcpy(ptr, ub->buf, len);
  159. ub->buf += len;
  160. ub->len -= len;
  161. }
  162. return len;
  163. }
  164. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  165. {
  166. struct header_info *hi = user_data;
  167. size_t remlen, slen, ptrlen = size * nmemb;
  168. char *rem, *val = NULL, *key = NULL;
  169. void *tmp;
  170. val = calloc(1, ptrlen);
  171. key = calloc(1, ptrlen);
  172. if (!key || !val)
  173. goto out;
  174. tmp = memchr(ptr, ':', ptrlen);
  175. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  176. goto out;
  177. slen = tmp - ptr;
  178. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  179. goto out;
  180. memcpy(key, ptr, slen); /* store & nul term key */
  181. key[slen] = 0;
  182. rem = ptr + slen + 1; /* trim value's leading whitespace */
  183. remlen = ptrlen - slen - 1;
  184. while ((remlen > 0) && (isCspace(*rem))) {
  185. remlen--;
  186. rem++;
  187. }
  188. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  189. val[remlen] = 0;
  190. while ((*val) && (isCspace(val[strlen(val) - 1])))
  191. val[strlen(val) - 1] = 0;
  192. if (!*val) /* skip blank value */
  193. goto out;
  194. if (opt_protocol)
  195. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  196. if (!strcasecmp("X-Roll-Ntime", key)) {
  197. hi->hadrolltime = true;
  198. if (!strncasecmp("N", val, 1))
  199. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  200. else {
  201. hi->canroll = true;
  202. /* Check to see if expire= is supported and if not, set
  203. * the rolltime to the default scantime */
  204. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  205. sscanf(val + 7, "%d", &hi->rolltime);
  206. hi->hadexpire = true;
  207. } else
  208. hi->rolltime = opt_scantime;
  209. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  210. }
  211. }
  212. if (!strcasecmp("X-Long-Polling", key)) {
  213. hi->lp_path = val; /* steal memory reference */
  214. val = NULL;
  215. }
  216. if (!strcasecmp("X-Reject-Reason", key)) {
  217. hi->reason = val; /* steal memory reference */
  218. val = NULL;
  219. }
  220. if (!strcasecmp("X-Stratum", key)) {
  221. hi->stratum_url = val;
  222. val = NULL;
  223. }
  224. out:
  225. free(key);
  226. free(val);
  227. return ptrlen;
  228. }
  229. static int keep_sockalive(SOCKETTYPE fd)
  230. {
  231. const int tcp_one = 1;
  232. const int tcp_keepidle = 45;
  233. const int tcp_keepintvl = 30;
  234. int ret = 0;
  235. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one))))
  236. ret = 1;
  237. #ifndef WIN32
  238. int flags = fcntl(fd, F_GETFL, 0);
  239. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  240. #else
  241. u_long flags = 1;
  242. ioctlsocket(fd, FIONBIO, &flags);
  243. #endif
  244. if (!opt_delaynet)
  245. #ifndef __linux
  246. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  247. #else /* __linux */
  248. if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  249. #endif /* __linux */
  250. ret = 1;
  251. #ifdef __linux
  252. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one))))
  253. ret = 1;
  254. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  255. ret = 1;
  256. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  257. ret = 1;
  258. #endif /* __linux */
  259. #ifdef __APPLE_CC__
  260. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  261. ret = 1;
  262. #endif /* __APPLE_CC__ */
  263. #ifdef WIN32
  264. const int zero = 0;
  265. struct tcp_keepalive vals;
  266. vals.onoff = 1;
  267. vals.keepalivetime = tcp_keepidle * 1000;
  268. vals.keepaliveinterval = tcp_keepintvl * 1000;
  269. DWORD outputBytes;
  270. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  271. ret = 1;
  272. /* Windows happily submits indefinitely to the send buffer blissfully
  273. * unaware nothing is getting there without gracefully failing unless
  274. * we disable the send buffer */
  275. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  276. ret = 1;
  277. #endif /* WIN32 */
  278. return ret;
  279. }
  280. void set_cloexec_socket(SOCKETTYPE sock, const bool cloexec)
  281. {
  282. #ifdef WIN32
  283. SetHandleInformation((HANDLE)sock, HANDLE_FLAG_INHERIT, cloexec ? 0 : HANDLE_FLAG_INHERIT);
  284. #elif defined(F_GETFD) && defined(F_SETFD) && defined(O_CLOEXEC)
  285. const int curflags = fcntl(sock, F_GETFD);
  286. int flags = curflags;
  287. if (cloexec)
  288. flags |= FD_CLOEXEC;
  289. else
  290. flags &= ~FD_CLOEXEC;
  291. if (flags != curflags)
  292. fcntl(sock, F_SETFD, flags);
  293. #endif
  294. }
  295. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  296. curlsocktype __maybe_unused purpose)
  297. {
  298. return keep_sockalive(fd);
  299. }
  300. static void last_nettime(struct timeval *last)
  301. {
  302. rd_lock(&netacc_lock);
  303. last->tv_sec = nettime.tv_sec;
  304. last->tv_usec = nettime.tv_usec;
  305. rd_unlock(&netacc_lock);
  306. }
  307. static void set_nettime(void)
  308. {
  309. wr_lock(&netacc_lock);
  310. cgtime(&nettime);
  311. wr_unlock(&netacc_lock);
  312. }
  313. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  314. char *data, size_t size,
  315. void *userdata)
  316. {
  317. struct pool *pool = (struct pool *)userdata;
  318. switch(type) {
  319. case CURLINFO_HEADER_IN:
  320. case CURLINFO_DATA_IN:
  321. case CURLINFO_SSL_DATA_IN:
  322. pool->cgminer_pool_stats.bytes_received += size;
  323. total_bytes_rcvd += size;
  324. pool->cgminer_pool_stats.net_bytes_received += size;
  325. break;
  326. case CURLINFO_HEADER_OUT:
  327. case CURLINFO_DATA_OUT:
  328. case CURLINFO_SSL_DATA_OUT:
  329. pool->cgminer_pool_stats.bytes_sent += size;
  330. total_bytes_sent += size;
  331. pool->cgminer_pool_stats.net_bytes_sent += size;
  332. break;
  333. case CURLINFO_TEXT:
  334. {
  335. if (!opt_protocol)
  336. break;
  337. // data is not null-terminated, so we need to copy and terminate it for applog
  338. char datacp[size + 1];
  339. memcpy(datacp, data, size);
  340. while (likely(size) && unlikely(isCspace(datacp[size-1])))
  341. --size;
  342. if (unlikely(!size))
  343. break;
  344. datacp[size] = '\0';
  345. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  346. break;
  347. }
  348. default:
  349. break;
  350. }
  351. return 0;
  352. }
  353. void json_rpc_call_async(CURL *curl, const char *url,
  354. const char *userpass, const char *rpc_req,
  355. bool longpoll,
  356. struct pool *pool, bool share,
  357. void *priv)
  358. {
  359. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  360. *state = (struct json_rpc_call_state){
  361. .priv = priv,
  362. .pool = pool,
  363. };
  364. long timeout = longpoll ? (60 * 60) : 60;
  365. char len_hdr[64], user_agent_hdr[128];
  366. struct curl_slist *headers = NULL;
  367. if (longpoll)
  368. {
  369. state->all_data.idlemarker = &pool->lp_socket;
  370. state->longpoll = true;
  371. }
  372. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  373. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  374. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  375. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  376. * to enable it */
  377. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  378. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  379. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  380. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  381. curl_easy_setopt(curl, CURLOPT_URL, url);
  382. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  383. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  384. /* Shares are staggered already and delays in submission can be costly
  385. * so do not delay them */
  386. if (!opt_delaynet || share)
  387. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  388. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  389. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  390. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  391. curl_easy_setopt(curl, CURLOPT_READDATA, state);
  392. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  393. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  394. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  395. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  396. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  397. if (pool->rpc_proxy) {
  398. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  399. } else if (opt_socks_proxy) {
  400. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  401. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  402. }
  403. if (userpass) {
  404. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  405. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  406. }
  407. if (longpoll)
  408. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  409. curl_easy_setopt(curl, CURLOPT_POST, 1);
  410. if (opt_protocol)
  411. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  412. state->upload_data.buf = rpc_req;
  413. state->upload_data.len = strlen(rpc_req);
  414. sprintf(len_hdr, "Content-Length: %lu",
  415. (unsigned long) state->upload_data.len);
  416. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  417. headers = curl_slist_append(headers,
  418. "Content-type: application/json");
  419. headers = curl_slist_append(headers,
  420. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  421. if (longpoll)
  422. headers = curl_slist_append(headers,
  423. "X-Minimum-Wait: 0");
  424. if (likely(global_hashrate)) {
  425. char ghashrate[255];
  426. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  427. headers = curl_slist_append(headers, ghashrate);
  428. }
  429. headers = curl_slist_append(headers, len_hdr);
  430. headers = curl_slist_append(headers, user_agent_hdr);
  431. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  432. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  433. state->headers = headers;
  434. if (opt_delaynet) {
  435. /* Don't delay share submission, but still track the nettime */
  436. if (!share) {
  437. long long now_msecs, last_msecs;
  438. struct timeval now, last;
  439. cgtime(&now);
  440. last_nettime(&last);
  441. now_msecs = (long long)now.tv_sec * 1000;
  442. now_msecs += now.tv_usec / 1000;
  443. last_msecs = (long long)last.tv_sec * 1000;
  444. last_msecs += last.tv_usec / 1000;
  445. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  446. struct timespec rgtp;
  447. rgtp.tv_sec = 0;
  448. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  449. nanosleep(&rgtp, NULL);
  450. }
  451. }
  452. set_nettime();
  453. }
  454. }
  455. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  456. {
  457. struct json_rpc_call_state *state;
  458. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, (void*)&state) != CURLE_OK) {
  459. applog(LOG_ERR, "Failed to get private curl data");
  460. if (out_priv)
  461. *(void**)out_priv = NULL;
  462. goto err_out;
  463. }
  464. if (out_priv)
  465. *(void**)out_priv = state->priv;
  466. json_t *val, *err_val, *res_val;
  467. json_error_t err;
  468. struct pool *pool = state->pool;
  469. bool probing = probe && !pool->probed;
  470. if (rc) {
  471. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  472. goto err_out;
  473. }
  474. if (!state->all_data.buf) {
  475. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  476. goto err_out;
  477. }
  478. pool->cgminer_pool_stats.times_sent++;
  479. pool->cgminer_pool_stats.times_received++;
  480. if (probing) {
  481. pool->probed = true;
  482. /* If X-Long-Polling was found, activate long polling */
  483. if (state->hi.lp_path) {
  484. if (pool->hdr_path != NULL)
  485. free(pool->hdr_path);
  486. pool->hdr_path = state->hi.lp_path;
  487. } else
  488. pool->hdr_path = NULL;
  489. if (state->hi.stratum_url) {
  490. pool->stratum_url = state->hi.stratum_url;
  491. state->hi.stratum_url = NULL;
  492. }
  493. } else {
  494. if (state->hi.lp_path) {
  495. free(state->hi.lp_path);
  496. state->hi.lp_path = NULL;
  497. }
  498. if (state->hi.stratum_url) {
  499. free(state->hi.stratum_url);
  500. state->hi.stratum_url = NULL;
  501. }
  502. }
  503. if (pool->force_rollntime)
  504. {
  505. state->hi.canroll = true;
  506. state->hi.hadexpire = true;
  507. state->hi.rolltime = pool->force_rollntime;
  508. }
  509. if (rolltime)
  510. *rolltime = state->hi.rolltime;
  511. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  512. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  513. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  514. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  515. val = JSON_LOADS(state->all_data.buf, &err);
  516. if (!val) {
  517. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  518. if (opt_protocol)
  519. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  520. goto err_out;
  521. }
  522. if (opt_protocol) {
  523. char *s = json_dumps(val, JSON_INDENT(3));
  524. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  525. free(s);
  526. }
  527. /* JSON-RPC valid response returns a non-null 'result',
  528. * and a null 'error'.
  529. */
  530. res_val = json_object_get(val, "result");
  531. err_val = json_object_get(val, "error");
  532. if (!res_val ||(err_val && !json_is_null(err_val))) {
  533. char *s;
  534. if (err_val)
  535. s = json_dumps(err_val, JSON_INDENT(3));
  536. else
  537. s = strdup("(unknown reason)");
  538. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  539. free(s);
  540. json_decref(val);
  541. goto err_out;
  542. }
  543. if (state->hi.reason) {
  544. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  545. free(state->hi.reason);
  546. state->hi.reason = NULL;
  547. }
  548. successful_connect = true;
  549. databuf_free(&state->all_data);
  550. curl_slist_free_all(state->headers);
  551. curl_easy_reset(curl);
  552. free(state);
  553. return val;
  554. err_out:
  555. databuf_free(&state->all_data);
  556. curl_slist_free_all(state->headers);
  557. curl_easy_reset(curl);
  558. if (!successful_connect)
  559. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  560. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  561. free(state);
  562. return NULL;
  563. }
  564. json_t *json_rpc_call(CURL *curl, const char *url,
  565. const char *userpass, const char *rpc_req,
  566. bool probe, bool longpoll, int *rolltime,
  567. struct pool *pool, bool share)
  568. {
  569. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  570. int rc = curl_easy_perform(curl);
  571. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  572. }
  573. bool our_curl_supports_proxy_uris()
  574. {
  575. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  576. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  577. }
  578. // NOTE: This assumes reference URI is a root
  579. char *absolute_uri(char *uri, const char *ref)
  580. {
  581. if (strstr(uri, "://"))
  582. return strdup(uri);
  583. char *copy_start, *abs;
  584. bool need_slash = false;
  585. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  586. if (ref[strlen(ref) - 1] != '/')
  587. need_slash = true;
  588. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  589. if (!abs) {
  590. applog(LOG_ERR, "Malloc failure in absolute_uri");
  591. return NULL;
  592. }
  593. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  594. return abs;
  595. }
  596. static const char _hexchars[0x10] = "0123456789abcdef";
  597. void bin2hex(char *out, const void *in, size_t len)
  598. {
  599. const unsigned char *p = in;
  600. while (len--)
  601. {
  602. (out++)[0] = _hexchars[p[0] >> 4];
  603. (out++)[0] = _hexchars[p[0] & 0xf];
  604. ++p;
  605. }
  606. out[0] = '\0';
  607. }
  608. static inline
  609. int _hex2bin_char(const char c)
  610. {
  611. if (c >= '0' && c <= '9')
  612. return c - '0';
  613. if (c >= 'a' && c <= 'f')
  614. return (c - 'a') + 10;
  615. if (c >= 'A' && c <= 'F')
  616. return (c - 'A') + 10;
  617. return -1;
  618. }
  619. /* Does the reverse of bin2hex but does not allocate any ram */
  620. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  621. {
  622. int n, o;
  623. while (len--)
  624. {
  625. n = _hex2bin_char((hexstr++)[0]);
  626. if (unlikely(n == -1))
  627. {
  628. badchar:
  629. if (!hexstr[-1])
  630. applog(LOG_ERR, "hex2bin: str truncated");
  631. else
  632. applog(LOG_ERR, "hex2bin: invalid character 0x%02x", (int)hexstr[-1]);
  633. return false;
  634. }
  635. o = _hex2bin_char((hexstr++)[0]);
  636. if (unlikely(o == -1))
  637. goto badchar;
  638. (p++)[0] = (n << 4) | o;
  639. }
  640. return likely(!hexstr[0]);
  641. }
  642. size_t ucs2_to_utf8(char * const out, const uint16_t * const in, const size_t sz)
  643. {
  644. uint8_t *p = (void*)out;
  645. for (int i = 0; i < sz; ++i)
  646. {
  647. const uint16_t c = in[i];
  648. if (c < 0x80)
  649. p++[0] = c;
  650. else
  651. {
  652. if (c < 0x800)
  653. p++[0] = 0xc0 | (c >> 6);
  654. else
  655. {
  656. p++[0] = 0xe0 | (c >> 12);
  657. p++[0] = 0x80 | ((c >> 6) & 0x3f);
  658. }
  659. p++[0] = 0x80 | (c & 0x3f);
  660. }
  661. }
  662. return p - (uint8_t*)(void*)out;
  663. }
  664. char *ucs2_to_utf8_dup(uint16_t * const in, size_t sz)
  665. {
  666. char * const out = malloc((sz * 4) + 1);
  667. sz = ucs2_to_utf8(out, in, sz);
  668. out[sz] = '\0';
  669. return out;
  670. }
  671. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  672. void real_block_target(unsigned char *target, const unsigned char *data)
  673. {
  674. uint8_t targetshift;
  675. if (unlikely(data[72] < 3 || data[72] > 0x20))
  676. {
  677. // Invalid (out of bounds) target
  678. memset(target, 0xff, 32);
  679. return;
  680. }
  681. targetshift = data[72] - 3;
  682. memset(target, 0, targetshift);
  683. target[targetshift++] = data[75];
  684. target[targetshift++] = data[74];
  685. target[targetshift++] = data[73];
  686. memset(&target[targetshift], 0, 0x20 - targetshift);
  687. }
  688. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  689. {
  690. const uint32_t *h32 = (uint32_t*)&hash[0];
  691. const uint32_t *t32 = (uint32_t*)&target[0];
  692. for (int i = 7; i >= 0; --i) {
  693. uint32_t h32i = le32toh(h32[i]);
  694. uint32_t t32i = le32toh(t32[i]);
  695. if (h32i > t32i)
  696. return false;
  697. if (h32i < t32i)
  698. return true;
  699. }
  700. return true;
  701. }
  702. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  703. {
  704. bool rc;
  705. rc = hash_target_check(hash, target);
  706. if (opt_debug) {
  707. unsigned char hash_swap[32], target_swap[32];
  708. char hash_str[65];
  709. char target_str[65];
  710. for (int i = 0; i < 32; ++i) {
  711. hash_swap[i] = hash[31-i];
  712. target_swap[i] = target[31-i];
  713. }
  714. bin2hex(hash_str, hash_swap, 32);
  715. bin2hex(target_str, target_swap, 32);
  716. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  717. hash_str,
  718. target_str,
  719. rc ? "YES (hash <= target)" :
  720. "no (false positive; hash > target)");
  721. }
  722. return rc;
  723. }
  724. struct thread_q *tq_new(void)
  725. {
  726. struct thread_q *tq;
  727. tq = calloc(1, sizeof(*tq));
  728. if (!tq)
  729. return NULL;
  730. pthread_mutex_init(&tq->mutex, NULL);
  731. pthread_cond_init(&tq->cond, bfg_condattr);
  732. return tq;
  733. }
  734. void tq_free(struct thread_q *tq)
  735. {
  736. struct tq_ent *ent, *iter;
  737. if (!tq)
  738. return;
  739. DL_FOREACH_SAFE(tq->q, ent, iter) {
  740. DL_DELETE(tq->q, ent);
  741. free(ent);
  742. }
  743. pthread_cond_destroy(&tq->cond);
  744. pthread_mutex_destroy(&tq->mutex);
  745. memset(tq, 0, sizeof(*tq)); /* poison */
  746. free(tq);
  747. }
  748. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  749. {
  750. mutex_lock(&tq->mutex);
  751. tq->frozen = frozen;
  752. pthread_cond_signal(&tq->cond);
  753. mutex_unlock(&tq->mutex);
  754. }
  755. void tq_freeze(struct thread_q *tq)
  756. {
  757. tq_freezethaw(tq, true);
  758. }
  759. void tq_thaw(struct thread_q *tq)
  760. {
  761. tq_freezethaw(tq, false);
  762. }
  763. bool tq_push(struct thread_q *tq, void *data)
  764. {
  765. struct tq_ent *ent;
  766. bool rc = true;
  767. ent = calloc(1, sizeof(*ent));
  768. if (!ent)
  769. return false;
  770. ent->data = data;
  771. mutex_lock(&tq->mutex);
  772. if (!tq->frozen) {
  773. DL_APPEND(tq->q, ent);
  774. } else {
  775. free(ent);
  776. rc = false;
  777. }
  778. pthread_cond_signal(&tq->cond);
  779. mutex_unlock(&tq->mutex);
  780. return rc;
  781. }
  782. void *tq_pop(struct thread_q * const tq)
  783. {
  784. struct tq_ent *ent;
  785. void *rval = NULL;
  786. int rc;
  787. mutex_lock(&tq->mutex);
  788. if (tq->q)
  789. goto pop;
  790. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  791. if (rc)
  792. goto out;
  793. if (!tq->q)
  794. goto out;
  795. pop:
  796. ent = tq->q;
  797. rval = ent->data;
  798. DL_DELETE(tq->q, ent);
  799. free(ent);
  800. out:
  801. mutex_unlock(&tq->mutex);
  802. return rval;
  803. }
  804. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  805. {
  806. int rv = pthread_create(&thr->pth, attr, start, arg);
  807. if (likely(!rv))
  808. thr->has_pth = true;
  809. return rv;
  810. }
  811. void thr_info_freeze(struct thr_info *thr)
  812. {
  813. struct tq_ent *ent, *iter;
  814. struct thread_q *tq;
  815. if (!thr)
  816. return;
  817. tq = thr->q;
  818. if (!tq)
  819. return;
  820. mutex_lock(&tq->mutex);
  821. tq->frozen = true;
  822. DL_FOREACH_SAFE(tq->q, ent, iter) {
  823. DL_DELETE(tq->q, ent);
  824. free(ent);
  825. }
  826. mutex_unlock(&tq->mutex);
  827. }
  828. void thr_info_cancel(struct thr_info *thr)
  829. {
  830. if (!thr)
  831. return;
  832. if (thr->has_pth) {
  833. pthread_cancel(thr->pth);
  834. thr->has_pth = false;
  835. }
  836. }
  837. #ifndef HAVE_PTHREAD_CANCEL
  838. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  839. enum pthread_cancel_workaround_mode {
  840. PCWM_DEFAULT = 0,
  841. PCWM_TERMINATE = 1,
  842. PCWM_ASYNC = 2,
  843. PCWM_DISABLED = 4,
  844. PCWM_CANCELLED = 8,
  845. };
  846. static pthread_key_t key_pcwm;
  847. struct sigaction pcwm_orig_term_handler;
  848. static
  849. void do_pthread_cancel_exit(int flags)
  850. {
  851. if (!(flags & PCWM_ASYNC))
  852. // NOTE: Logging disables cancel while mutex held, so this is safe
  853. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  854. pthread_exit(PTHREAD_CANCELED);
  855. }
  856. static
  857. void sighandler_pthread_cancel(int sig)
  858. {
  859. int flags = (int)pthread_getspecific(key_pcwm);
  860. if (flags & PCWM_TERMINATE) // Main thread
  861. {
  862. // Restore original handler and call it
  863. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  864. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  865. raise(SIGTERM);
  866. quit(1, "pthread_cancel workaround: Original handler returned");
  867. }
  868. if (flags & PCWM_CANCELLED) // Already pending cancel
  869. return;
  870. if (flags & PCWM_DISABLED)
  871. {
  872. flags |= PCWM_CANCELLED;
  873. if (pthread_setspecific(key_pcwm, (void*)flags))
  874. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  875. return;
  876. }
  877. do_pthread_cancel_exit(flags);
  878. }
  879. void pthread_testcancel(void)
  880. {
  881. int flags = (int)pthread_getspecific(key_pcwm);
  882. if (flags & PCWM_CANCELLED && !(flags & PCWM_DISABLED))
  883. do_pthread_cancel_exit(flags);
  884. }
  885. int pthread_setcancelstate(int state, int *oldstate)
  886. {
  887. int flags = (int)pthread_getspecific(key_pcwm);
  888. if (oldstate)
  889. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  890. if (state == PTHREAD_CANCEL_DISABLE)
  891. flags |= PCWM_DISABLED;
  892. else
  893. {
  894. if (flags & PCWM_CANCELLED)
  895. do_pthread_cancel_exit(flags);
  896. flags &= ~PCWM_DISABLED;
  897. }
  898. if (pthread_setspecific(key_pcwm, (void*)flags))
  899. return -1;
  900. return 0;
  901. }
  902. int pthread_setcanceltype(int type, int *oldtype)
  903. {
  904. int flags = (int)pthread_getspecific(key_pcwm);
  905. if (oldtype)
  906. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  907. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  908. flags |= PCWM_ASYNC;
  909. else
  910. flags &= ~PCWM_ASYNC;
  911. if (pthread_setspecific(key_pcwm, (void*)flags))
  912. return -1;
  913. return 0;
  914. }
  915. void setup_pthread_cancel_workaround()
  916. {
  917. if (pthread_key_create(&key_pcwm, NULL))
  918. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  919. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  920. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  921. struct sigaction new_sigact = {
  922. .sa_handler = sighandler_pthread_cancel,
  923. };
  924. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  925. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  926. }
  927. #endif
  928. static void _now_gettimeofday(struct timeval *);
  929. static void _cgsleep_us_r_nanosleep(cgtimer_t *, int64_t);
  930. #ifdef HAVE_POOR_GETTIMEOFDAY
  931. static struct timeval tv_timeofday_offset;
  932. static struct timeval _tv_timeofday_lastchecked;
  933. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  934. static
  935. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  936. {
  937. struct timeval actual, delta;
  938. timeradd(expected, &tv_timeofday_offset, expected);
  939. _now_gettimeofday(&actual);
  940. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  941. // Within reason - no change necessary
  942. return;
  943. timersub(&actual, expected, &delta);
  944. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  945. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  946. *expected = actual;
  947. }
  948. void bfg_gettimeofday(struct timeval *out)
  949. {
  950. char buf[64] = "";
  951. timer_set_now(out);
  952. mutex_lock(&_tv_timeofday_mutex);
  953. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  954. bfg_calibrate_timeofday(out, buf);
  955. else
  956. timeradd(out, &tv_timeofday_offset, out);
  957. mutex_unlock(&_tv_timeofday_mutex);
  958. if (unlikely(buf[0]))
  959. applog(LOG_WARNING, "%s", buf);
  960. }
  961. #endif
  962. #ifdef WIN32
  963. static LARGE_INTEGER _perffreq;
  964. static
  965. void _now_queryperformancecounter(struct timeval *tv)
  966. {
  967. LARGE_INTEGER now;
  968. if (unlikely(!QueryPerformanceCounter(&now)))
  969. quit(1, "QueryPerformanceCounter failed");
  970. *tv = (struct timeval){
  971. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  972. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  973. };
  974. }
  975. #endif
  976. static void bfg_init_time();
  977. static
  978. void _now_is_not_set(__maybe_unused struct timeval *tv)
  979. {
  980. bfg_init_time();
  981. timer_set_now(tv);
  982. }
  983. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  984. void (*cgsleep_us_r)(cgtimer_t *, int64_t) = _cgsleep_us_r_nanosleep;
  985. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  986. static clockid_t bfg_timer_clk;
  987. static
  988. void _now_clock_gettime(struct timeval *tv)
  989. {
  990. struct timespec ts;
  991. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  992. quit(1, "clock_gettime failed");
  993. *tv = (struct timeval){
  994. .tv_sec = ts.tv_sec,
  995. .tv_usec = ts.tv_nsec / 1000,
  996. };
  997. }
  998. #ifdef HAVE_CLOCK_NANOSLEEP
  999. static
  1000. void _cgsleep_us_r_monotonic(cgtimer_t *tv_start, int64_t us)
  1001. {
  1002. struct timeval tv_end[1];
  1003. struct timespec ts_end[1];
  1004. int ret;
  1005. timer_set_delay(tv_end, tv_start, us);
  1006. timeval_to_spec(ts_end, tv_end);
  1007. do {
  1008. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  1009. } while (ret == EINTR);
  1010. }
  1011. #endif
  1012. static
  1013. bool _bfg_try_clock_gettime(clockid_t clk)
  1014. {
  1015. struct timespec ts;
  1016. if (clock_gettime(clk, &ts))
  1017. return false;
  1018. bfg_timer_clk = clk;
  1019. timer_set_now = _now_clock_gettime;
  1020. return true;
  1021. }
  1022. #endif
  1023. pthread_condattr_t *bfg_condattr_()
  1024. {
  1025. return NULL;
  1026. }
  1027. static
  1028. void bfg_init_time()
  1029. {
  1030. if (timer_set_now != _now_is_not_set)
  1031. return;
  1032. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1033. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1034. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1035. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1036. else
  1037. #endif
  1038. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1039. {
  1040. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1041. #ifdef HAVE_CLOCK_NANOSLEEP
  1042. cgsleep_us_r = _cgsleep_us_r_monotonic;
  1043. #endif
  1044. }
  1045. else
  1046. #endif
  1047. #ifdef WIN32
  1048. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1049. {
  1050. timer_set_now = _now_queryperformancecounter;
  1051. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1052. }
  1053. else
  1054. #endif
  1055. {
  1056. timer_set_now = _now_gettimeofday;
  1057. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1058. }
  1059. #ifdef HAVE_POOR_GETTIMEOFDAY
  1060. char buf[64] = "";
  1061. struct timeval tv;
  1062. timer_set_now(&tv);
  1063. bfg_calibrate_timeofday(&tv, buf);
  1064. applog(LOG_DEBUG, "%s", buf);
  1065. #endif
  1066. }
  1067. void subtime(struct timeval *a, struct timeval *b)
  1068. {
  1069. timersub(a, b, b);
  1070. }
  1071. void addtime(struct timeval *a, struct timeval *b)
  1072. {
  1073. timeradd(a, b, b);
  1074. }
  1075. bool time_more(struct timeval *a, struct timeval *b)
  1076. {
  1077. return timercmp(a, b, >);
  1078. }
  1079. bool time_less(struct timeval *a, struct timeval *b)
  1080. {
  1081. return timercmp(a, b, <);
  1082. }
  1083. void copy_time(struct timeval *dest, const struct timeval *src)
  1084. {
  1085. memcpy(dest, src, sizeof(struct timeval));
  1086. }
  1087. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  1088. {
  1089. val->tv_sec = spec->tv_sec;
  1090. val->tv_usec = spec->tv_nsec / 1000;
  1091. }
  1092. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  1093. {
  1094. spec->tv_sec = val->tv_sec;
  1095. spec->tv_nsec = val->tv_usec * 1000;
  1096. }
  1097. void us_to_timeval(struct timeval *val, int64_t us)
  1098. {
  1099. lldiv_t tvdiv = lldiv(us, 1000000);
  1100. val->tv_sec = tvdiv.quot;
  1101. val->tv_usec = tvdiv.rem;
  1102. }
  1103. void us_to_timespec(struct timespec *spec, int64_t us)
  1104. {
  1105. lldiv_t tvdiv = lldiv(us, 1000000);
  1106. spec->tv_sec = tvdiv.quot;
  1107. spec->tv_nsec = tvdiv.rem * 1000;
  1108. }
  1109. void ms_to_timespec(struct timespec *spec, int64_t ms)
  1110. {
  1111. lldiv_t tvdiv = lldiv(ms, 1000);
  1112. spec->tv_sec = tvdiv.quot;
  1113. spec->tv_nsec = tvdiv.rem * 1000000;
  1114. }
  1115. void timeraddspec(struct timespec *a, const struct timespec *b)
  1116. {
  1117. a->tv_sec += b->tv_sec;
  1118. a->tv_nsec += b->tv_nsec;
  1119. if (a->tv_nsec >= 1000000000) {
  1120. a->tv_nsec -= 1000000000;
  1121. a->tv_sec++;
  1122. }
  1123. }
  1124. #ifndef WIN32
  1125. static
  1126. void _now_gettimeofday(struct timeval *tv)
  1127. {
  1128. gettimeofday(tv, NULL);
  1129. }
  1130. #else
  1131. /* Windows start time is since 1601 lol so convert it to unix epoch 1970. */
  1132. #define EPOCHFILETIME (116444736000000000LL)
  1133. void _now_gettimeofday(struct timeval *tv)
  1134. {
  1135. FILETIME ft;
  1136. LARGE_INTEGER li;
  1137. GetSystemTimeAsFileTime(&ft);
  1138. li.LowPart = ft.dwLowDateTime;
  1139. li.HighPart = ft.dwHighDateTime;
  1140. li.QuadPart -= EPOCHFILETIME;
  1141. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1142. tv->tv_sec = li.QuadPart / 10000000;
  1143. tv->tv_usec = li.QuadPart % 10000000;
  1144. }
  1145. #endif
  1146. void cgsleep_ms_r(cgtimer_t *tv_start, int ms)
  1147. {
  1148. cgsleep_us_r(tv_start, ((int64_t)ms) * 1000);
  1149. }
  1150. static
  1151. void _cgsleep_us_r_nanosleep(cgtimer_t *tv_start, int64_t us)
  1152. {
  1153. struct timeval tv_timer[1], tv[1];
  1154. struct timespec ts[1];
  1155. timer_set_delay(tv_timer, tv_start, us);
  1156. while (true)
  1157. {
  1158. timer_set_now(tv);
  1159. if (!timercmp(tv_timer, tv, >))
  1160. return;
  1161. timersub(tv_timer, tv, tv);
  1162. timeval_to_spec(ts, tv);
  1163. nanosleep(ts, NULL);
  1164. }
  1165. }
  1166. void cgsleep_ms(int ms)
  1167. {
  1168. cgtimer_t ts_start;
  1169. cgsleep_prepare_r(&ts_start);
  1170. cgsleep_ms_r(&ts_start, ms);
  1171. }
  1172. void cgsleep_us(int64_t us)
  1173. {
  1174. cgtimer_t ts_start;
  1175. cgsleep_prepare_r(&ts_start);
  1176. cgsleep_us_r(&ts_start, us);
  1177. }
  1178. /* Returns the microseconds difference between end and start times as a double */
  1179. double us_tdiff(struct timeval *end, struct timeval *start)
  1180. {
  1181. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1182. }
  1183. /* Returns the seconds difference between end and start times as a double */
  1184. double tdiff(struct timeval *end, struct timeval *start)
  1185. {
  1186. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1187. }
  1188. int double_find_precision(double f, const double base)
  1189. {
  1190. int rv = 0;
  1191. for ( ; floor(f) != f; ++rv)
  1192. f *= base;
  1193. return rv;
  1194. }
  1195. int utf8_len(const uint8_t b)
  1196. {
  1197. if (!(b & 0x80))
  1198. return 1;
  1199. if (!(b & 0x20))
  1200. return 2;
  1201. else
  1202. if (!(b & 0x10))
  1203. return 3;
  1204. else
  1205. return 4;
  1206. }
  1207. int32_t utf8_decode(const void *b, int *out_len)
  1208. {
  1209. int32_t w;
  1210. const unsigned char *s = b;
  1211. *out_len = utf8_len(s[0]);
  1212. if (*out_len == 1)
  1213. // ASCII
  1214. return s[0];
  1215. #ifdef STRICT_UTF8
  1216. if (unlikely(!(s[0] & 0x40)))
  1217. goto invalid;
  1218. if (unlikely(s[0] & 0x38 == 0x38))
  1219. goto invalid;
  1220. #endif
  1221. w = s[0] & ((2 << (6 - *out_len)) - 1);
  1222. for (int i = 1; i < *out_len; ++i)
  1223. {
  1224. #ifdef STRICT_UTF8
  1225. if (unlikely((s[i] & 0xc0) != 0x80))
  1226. goto invalid;
  1227. #endif
  1228. w = (w << 6) | (s[i] & 0x3f);
  1229. }
  1230. #if defined(STRICT_UTF8)
  1231. if (unlikely(w > 0x10FFFF))
  1232. goto invalid;
  1233. // FIXME: UTF-8 requires smallest possible encoding; check it
  1234. #endif
  1235. return w;
  1236. #ifdef STRICT_UTF8
  1237. invalid:
  1238. *out_len = 1;
  1239. return REPLACEMENT_CHAR;
  1240. #endif
  1241. }
  1242. size_t utf8_strlen(const void * const b)
  1243. {
  1244. const uint8_t *s = b;
  1245. size_t c = 0;
  1246. int clen, i;
  1247. while (s[0])
  1248. {
  1249. clen = utf8_len(s[0]);
  1250. for (i = 0; i < clen; ++i)
  1251. if (!s[i])
  1252. clen = 1;
  1253. ++c;
  1254. s += clen;
  1255. }
  1256. return c;
  1257. }
  1258. static
  1259. void _utf8_test(const char *s, const wchar_t expected, int expectedlen)
  1260. {
  1261. int len;
  1262. wchar_t r;
  1263. if (expected != REPLACEMENT_CHAR)
  1264. {
  1265. len = utf8_len(((uint8_t*)s)[0]);
  1266. if (len != expectedlen)
  1267. {
  1268. ++unittest_failures;
  1269. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_len=>%d", (unsigned long)expected, expectedlen, len);
  1270. }
  1271. len = utf8_strlen(s);
  1272. if (len != (s[0] ? 1 : 0))
  1273. {
  1274. ++unittest_failures;
  1275. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_strlen=>%d", (unsigned long)expected, expectedlen, len);
  1276. }
  1277. len = -1;
  1278. }
  1279. r = utf8_decode(s, &len);
  1280. if (unlikely(r != expected || expectedlen != len))
  1281. {
  1282. ++unittest_failures;
  1283. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got U+%06lX (len %d)", (unsigned long)expected, expectedlen, (unsigned long)r, len);
  1284. }
  1285. }
  1286. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1287. void utf8_test()
  1288. {
  1289. _utf8_test("", 0, 1);
  1290. _utf8_test("\1", 1, 1);
  1291. _utf8_test("\x7f", 0x7f, 1);
  1292. #if WCHAR_MAX >= 0x80
  1293. _utf8_test("\xc2\x80", 0x80, 2);
  1294. #if WCHAR_MAX >= 0xff
  1295. _utf8_test("\xc3\xbf", 0xff, 2);
  1296. #if WCHAR_MAX >= 0x7ff
  1297. _utf8_test("\xdf\xbf", 0x7ff, 2);
  1298. #if WCHAR_MAX >= 0x800
  1299. _utf8_test("\xe0\xa0\x80", 0x800, 3);
  1300. #if WCHAR_MAX >= 0xffff
  1301. _utf8_test("\xef\xbf\xbf", 0xffff, 3);
  1302. #if WCHAR_MAX >= 0x10000
  1303. _utf8_test("\xf0\x90\x80\x80", 0x10000, 4);
  1304. #if WCHAR_MAX >= 0x10ffff
  1305. _utf8_test("\xf4\x8f\xbf\xbf", 0x10ffff, 4);
  1306. #endif
  1307. #endif
  1308. #endif
  1309. #endif
  1310. #endif
  1311. #endif
  1312. #endif
  1313. #ifdef STRICT_UTF8
  1314. _utf8_test("\x80", REPLACEMENT_CHAR, 1);
  1315. _utf8_test("\xbf", REPLACEMENT_CHAR, 1);
  1316. _utf8_test("\xfe", REPLACEMENT_CHAR, 1);
  1317. _utf8_test("\xff", REPLACEMENT_CHAR, 1);
  1318. #endif
  1319. }
  1320. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1321. {
  1322. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1323. char url_address[256], port[6];
  1324. int url_len, port_len = 0;
  1325. url_begin = strstr(url, "//");
  1326. if (!url_begin)
  1327. url_begin = url;
  1328. else
  1329. url_begin += 2;
  1330. /* Look for numeric ipv6 entries */
  1331. ipv6_begin = strstr(url_begin, "[");
  1332. ipv6_end = strstr(url_begin, "]");
  1333. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1334. url_end = strstr(ipv6_end, ":");
  1335. else
  1336. url_end = strstr(url_begin, ":");
  1337. if (url_end) {
  1338. url_len = url_end - url_begin;
  1339. port_len = strlen(url_begin) - url_len - 1;
  1340. if (port_len < 1)
  1341. return false;
  1342. port_start = url_end + 1;
  1343. } else
  1344. url_len = strlen(url_begin);
  1345. if (url_len < 1)
  1346. return false;
  1347. if (url_len >= sizeof(url_address))
  1348. {
  1349. applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'",
  1350. __func__, url_len, url_begin);
  1351. url_len = sizeof(url_address) - 1;
  1352. }
  1353. sprintf(url_address, "%.*s", url_len, url_begin);
  1354. if (port_len) {
  1355. char *slash;
  1356. snprintf(port, 6, "%.*s", port_len, port_start);
  1357. slash = strchr(port, '/');
  1358. if (slash)
  1359. *slash = '\0';
  1360. } else
  1361. strcpy(port, "80");
  1362. free(*sockaddr_port);
  1363. *sockaddr_port = strdup(port);
  1364. free(*sockaddr_url);
  1365. *sockaddr_url = strdup(url_address);
  1366. return true;
  1367. }
  1368. enum send_ret {
  1369. SEND_OK,
  1370. SEND_SELECTFAIL,
  1371. SEND_SENDFAIL,
  1372. SEND_INACTIVE
  1373. };
  1374. /* Send a single command across a socket, appending \n to it. This should all
  1375. * be done under stratum lock except when first establishing the socket */
  1376. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1377. {
  1378. SOCKETTYPE sock = pool->sock;
  1379. ssize_t ssent = 0;
  1380. strcat(s, "\n");
  1381. len++;
  1382. while (len > 0 ) {
  1383. struct timeval timeout = {1, 0};
  1384. size_t sent = 0;
  1385. CURLcode rc;
  1386. fd_set wd;
  1387. retry:
  1388. FD_ZERO(&wd);
  1389. FD_SET(sock, &wd);
  1390. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1391. if (interrupted())
  1392. goto retry;
  1393. return SEND_SELECTFAIL;
  1394. }
  1395. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  1396. if (rc != CURLE_OK)
  1397. {
  1398. if (rc != CURLE_AGAIN)
  1399. return SEND_SENDFAIL;
  1400. sent = 0;
  1401. }
  1402. ssent += sent;
  1403. len -= sent;
  1404. }
  1405. pool->cgminer_pool_stats.times_sent++;
  1406. pool->cgminer_pool_stats.bytes_sent += ssent;
  1407. total_bytes_sent += ssent;
  1408. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1409. return SEND_OK;
  1410. }
  1411. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1412. {
  1413. enum send_ret ret = SEND_INACTIVE;
  1414. if (opt_protocol)
  1415. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1416. mutex_lock(&pool->stratum_lock);
  1417. if (pool->stratum_active || force)
  1418. ret = __stratum_send(pool, s, len);
  1419. mutex_unlock(&pool->stratum_lock);
  1420. /* This is to avoid doing applog under stratum_lock */
  1421. switch (ret) {
  1422. default:
  1423. case SEND_OK:
  1424. break;
  1425. case SEND_SELECTFAIL:
  1426. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1427. suspend_stratum(pool);
  1428. break;
  1429. case SEND_SENDFAIL:
  1430. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1431. suspend_stratum(pool);
  1432. break;
  1433. case SEND_INACTIVE:
  1434. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1435. break;
  1436. }
  1437. return (ret == SEND_OK);
  1438. }
  1439. static bool socket_full(struct pool *pool, int wait)
  1440. {
  1441. SOCKETTYPE sock = pool->sock;
  1442. struct timeval timeout;
  1443. fd_set rd;
  1444. if (sock == INVSOCK)
  1445. return true;
  1446. if (unlikely(wait < 0))
  1447. wait = 0;
  1448. FD_ZERO(&rd);
  1449. FD_SET(sock, &rd);
  1450. timeout.tv_usec = 0;
  1451. timeout.tv_sec = wait;
  1452. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1453. return true;
  1454. return false;
  1455. }
  1456. /* Check to see if Santa's been good to you */
  1457. bool sock_full(struct pool *pool)
  1458. {
  1459. if (strlen(pool->sockbuf))
  1460. return true;
  1461. return (socket_full(pool, 0));
  1462. }
  1463. static void clear_sockbuf(struct pool *pool)
  1464. {
  1465. strcpy(pool->sockbuf, "");
  1466. }
  1467. static void clear_sock(struct pool *pool)
  1468. {
  1469. size_t n = 0;
  1470. mutex_lock(&pool->stratum_lock);
  1471. do {
  1472. n = 0;
  1473. if (pool->sock)
  1474. curl_easy_recv(pool->stratum_curl, pool->sockbuf, RECVSIZE, &n);
  1475. } while (n > 0);
  1476. mutex_unlock(&pool->stratum_lock);
  1477. clear_sockbuf(pool);
  1478. }
  1479. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1480. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1481. * and zeroing the new memory */
  1482. static void recalloc_sock(struct pool *pool, size_t len)
  1483. {
  1484. size_t old, new;
  1485. old = strlen(pool->sockbuf);
  1486. new = old + len + 1;
  1487. if (new < pool->sockbuf_size)
  1488. return;
  1489. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1490. // Avoid potentially recursive locking
  1491. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1492. pool->sockbuf = realloc(pool->sockbuf, new);
  1493. if (!pool->sockbuf)
  1494. quithere(1, "Failed to realloc pool sockbuf");
  1495. memset(pool->sockbuf + old, 0, new - old);
  1496. pool->sockbuf_size = new;
  1497. }
  1498. /* Peeks at a socket to find the first end of line and then reads just that
  1499. * from the socket and returns that as a malloced char */
  1500. char *recv_line(struct pool *pool)
  1501. {
  1502. char *tok, *sret = NULL;
  1503. ssize_t len, buflen;
  1504. int waited = 0;
  1505. if (!strstr(pool->sockbuf, "\n")) {
  1506. struct timeval rstart, now;
  1507. cgtime(&rstart);
  1508. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1509. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1510. goto out;
  1511. }
  1512. do {
  1513. char s[RBUFSIZE];
  1514. size_t slen;
  1515. size_t n = 0;
  1516. CURLcode rc;
  1517. memset(s, 0, RBUFSIZE);
  1518. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  1519. if (rc == CURLE_OK && !n)
  1520. {
  1521. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1522. suspend_stratum(pool);
  1523. break;
  1524. }
  1525. cgtime(&now);
  1526. waited = tdiff(&now, &rstart);
  1527. if (rc != CURLE_OK)
  1528. {
  1529. if (rc != CURLE_AGAIN || !socket_full(pool, DEFAULT_SOCKWAIT - waited))
  1530. {
  1531. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1532. suspend_stratum(pool);
  1533. break;
  1534. }
  1535. } else {
  1536. slen = strlen(s);
  1537. recalloc_sock(pool, slen);
  1538. strcat(pool->sockbuf, s);
  1539. }
  1540. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1541. }
  1542. buflen = strlen(pool->sockbuf);
  1543. tok = strtok(pool->sockbuf, "\n");
  1544. if (!tok) {
  1545. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1546. goto out;
  1547. }
  1548. sret = strdup(tok);
  1549. len = strlen(sret);
  1550. /* Copy what's left in the buffer after the \n, including the
  1551. * terminating \0 */
  1552. if (buflen > len + 1)
  1553. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1554. else
  1555. strcpy(pool->sockbuf, "");
  1556. pool->cgminer_pool_stats.times_received++;
  1557. pool->cgminer_pool_stats.bytes_received += len;
  1558. total_bytes_rcvd += len;
  1559. pool->cgminer_pool_stats.net_bytes_received += len;
  1560. out:
  1561. if (!sret)
  1562. clear_sock(pool);
  1563. else if (opt_protocol)
  1564. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1565. return sret;
  1566. }
  1567. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1568. * flag, but this is compatible with 2.0. */
  1569. char *json_dumps_ANY(json_t *json, size_t flags)
  1570. {
  1571. switch (json_typeof(json))
  1572. {
  1573. case JSON_ARRAY:
  1574. case JSON_OBJECT:
  1575. return json_dumps(json, flags);
  1576. default:
  1577. break;
  1578. }
  1579. char *rv;
  1580. #ifdef JSON_ENCODE_ANY
  1581. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1582. if (rv)
  1583. return rv;
  1584. #endif
  1585. json_t *tmp = json_array();
  1586. char *s;
  1587. int i;
  1588. size_t len;
  1589. if (!tmp)
  1590. quithere(1, "Failed to allocate json array");
  1591. if (json_array_append(tmp, json))
  1592. quithere(1, "Failed to append temporary array");
  1593. s = json_dumps(tmp, flags);
  1594. if (!s)
  1595. return NULL;
  1596. for (i = 0; s[i] != '['; ++i)
  1597. if (unlikely(!(s[i] && isCspace(s[i]))))
  1598. quithere(1, "Failed to find opening bracket in array dump");
  1599. len = strlen(&s[++i]) - 1;
  1600. if (unlikely(s[i+len] != ']'))
  1601. quithere(1, "Failed to find closing bracket in array dump");
  1602. rv = malloc(len + 1);
  1603. memcpy(rv, &s[i], len);
  1604. rv[len] = '\0';
  1605. free(s);
  1606. json_decref(tmp);
  1607. return rv;
  1608. }
  1609. /* Extracts a string value from a json array with error checking. To be used
  1610. * when the value of the string returned is only examined and not to be stored.
  1611. * See json_array_string below */
  1612. const char *__json_array_string(json_t *val, unsigned int entry)
  1613. {
  1614. json_t *arr_entry;
  1615. if (json_is_null(val))
  1616. return NULL;
  1617. if (!json_is_array(val))
  1618. return NULL;
  1619. if (entry > json_array_size(val))
  1620. return NULL;
  1621. arr_entry = json_array_get(val, entry);
  1622. if (!json_is_string(arr_entry))
  1623. return NULL;
  1624. return json_string_value(arr_entry);
  1625. }
  1626. /* Creates a freshly malloced dup of __json_array_string */
  1627. static char *json_array_string(json_t *val, unsigned int entry)
  1628. {
  1629. const char *buf = __json_array_string(val, entry);
  1630. if (buf)
  1631. return strdup(buf);
  1632. return NULL;
  1633. }
  1634. void *my_memrchr(const void * const datap, const int c, const size_t sz)
  1635. {
  1636. const uint8_t *data = datap;
  1637. const uint8_t *p = &data[sz];
  1638. while (p > data)
  1639. if (*--p == c)
  1640. return (void *)p;
  1641. return NULL;
  1642. }
  1643. bool isCalpha(const int c)
  1644. {
  1645. if (c >= 'A' && c <= 'Z')
  1646. return true;
  1647. if (c >= 'a' && c <= 'z')
  1648. return true;
  1649. return false;
  1650. }
  1651. bool match_strtok(const char * const optlist, const char * const delim, const char * const needle)
  1652. {
  1653. const size_t optlist_sz = strlen(optlist) + 1;
  1654. char opts[optlist_sz];
  1655. memcpy(opts, optlist, optlist_sz);
  1656. for (char *el, *nextptr, *s = opts; (el = strtok_r(s, delim, &nextptr)); s = NULL)
  1657. if (!strcasecmp(el, needle))
  1658. return true;
  1659. return false;
  1660. }
  1661. static
  1662. bool _appdata_file_call(const char * const appname, const char * const filename, const appdata_file_callback_t cb, void * const userp, const char * const path)
  1663. {
  1664. if (!(path && path[0]))
  1665. return false;
  1666. char filepath[PATH_MAX];
  1667. snprintf(filepath, sizeof(filepath), "%s/%s/%s", path, appname, filename);
  1668. if (!access(filepath, R_OK))
  1669. return cb(filepath, userp);
  1670. return false;
  1671. }
  1672. #define _APPDATA_FILE_CALL(appname, path) do{ \
  1673. if (_appdata_file_call(appname, filename, cb, userp, path)) \
  1674. return true; \
  1675. }while(0)
  1676. bool appdata_file_call(const char *appname, const char * const filename, const appdata_file_callback_t cb, void * const userp)
  1677. {
  1678. size_t appname_len = strlen(appname);
  1679. char appname_lcd[appname_len + 1];
  1680. appname_lcd[0] = '.';
  1681. char *appname_lc = &appname_lcd[1];
  1682. for (size_t i = 0; i <= appname_len; ++i)
  1683. appname_lc[i] = tolower(appname[i]);
  1684. appname_lc[appname_len] = '\0';
  1685. const char * const HOME = getenv("HOME");
  1686. _APPDATA_FILE_CALL(".", ".");
  1687. #ifdef WIN32
  1688. _APPDATA_FILE_CALL(appname, getenv("APPDATA"));
  1689. #elif defined(__APPLE__)
  1690. if (HOME && HOME[0])
  1691. {
  1692. char AppSupport[strlen(HOME) + 28 + 1];
  1693. snprintf(AppSupport, sizeof(AppSupport), "%s/Library/Application Support", HOME);
  1694. _APPDATA_FILE_CALL(appname, AppSupport);
  1695. }
  1696. #endif
  1697. _APPDATA_FILE_CALL(appname_lcd, HOME);
  1698. #ifdef WIN32
  1699. _APPDATA_FILE_CALL(appname, getenv("ALLUSERSAPPDATA"));
  1700. #elif defined(__APPLE__)
  1701. _APPDATA_FILE_CALL(appname, "/Library/Application Support");
  1702. #endif
  1703. #ifndef WIN32
  1704. _APPDATA_FILE_CALL(appname_lc, "/etc");
  1705. #endif
  1706. return false;
  1707. }
  1708. static
  1709. bool _appdata_file_find_first(const char * const filepath, void *userp)
  1710. {
  1711. char **rv = userp;
  1712. *rv = strdup(filepath);
  1713. return true;
  1714. }
  1715. char *appdata_file_find_first(const char * const appname, const char * const filename)
  1716. {
  1717. char *rv;
  1718. if (appdata_file_call(appname, filename, _appdata_file_find_first, &rv))
  1719. return rv;
  1720. return NULL;
  1721. }
  1722. const char *get_registered_domain(size_t * const out_domainlen, const char * const fqdn, const size_t fqdnlen)
  1723. {
  1724. const char *s;
  1725. int dots = 0;
  1726. for (s = &fqdn[fqdnlen-1]; s >= fqdn; --s)
  1727. {
  1728. if (s[0] == '.')
  1729. {
  1730. *out_domainlen = fqdnlen - (&s[1] - fqdn);
  1731. if (++dots >= 2 && *out_domainlen > 5)
  1732. return &s[1];
  1733. }
  1734. else
  1735. if (!(dots || isCalpha(s[0])))
  1736. {
  1737. *out_domainlen = fqdnlen;
  1738. return fqdn;
  1739. }
  1740. }
  1741. *out_domainlen = fqdnlen;
  1742. return fqdn;
  1743. }
  1744. const char *extract_domain(size_t * const out_domainlen, const char * const uri, const size_t urilen)
  1745. {
  1746. const char *p = uri, *b, *q, *s;
  1747. bool alldigit;
  1748. p = memchr(&p[1], '/', urilen - (&p[1] - uri));
  1749. if (p)
  1750. {
  1751. if (p[-1] == ':')
  1752. {
  1753. // part of the URI scheme, ignore it
  1754. while (p[0] == '/')
  1755. ++p;
  1756. p = memchr(p, '/', urilen - (p - uri)) ?: &uri[urilen];
  1757. }
  1758. }
  1759. else
  1760. p = &uri[urilen];
  1761. s = p;
  1762. q = my_memrchr(uri, ':', p - uri);
  1763. if (q)
  1764. {
  1765. alldigit = true;
  1766. for (q = b = &q[1]; q < p; ++q)
  1767. if (!isdigit(q[0]))
  1768. {
  1769. alldigit = false;
  1770. break;
  1771. }
  1772. if (alldigit && p != b)
  1773. p = &b[-1];
  1774. }
  1775. alldigit = true;
  1776. for (b = uri; b < p; ++b)
  1777. {
  1778. if (b[0] == ':')
  1779. break;
  1780. if (alldigit && !isdigit(b[0]))
  1781. alldigit = false;
  1782. }
  1783. if ((b < p && b[0] == ':') && (b == uri || !alldigit))
  1784. b = &b[1];
  1785. else
  1786. b = uri;
  1787. while (b <= p && b[0] == '/')
  1788. ++b;
  1789. if (p - b > 1 && b[0] == '[' && p[-1] == ']')
  1790. {
  1791. ++b;
  1792. --p;
  1793. }
  1794. else
  1795. if (memchr(b, ':', p - b))
  1796. p = s;
  1797. if (p > b && p[-1] == '.')
  1798. --p;
  1799. *out_domainlen = p - b;
  1800. return b;
  1801. }
  1802. bool match_domains(const char * const a, const size_t alen, const char * const b, const size_t blen)
  1803. {
  1804. size_t a_domainlen, b_domainlen;
  1805. const char *a_domain, *b_domain;
  1806. a_domain = extract_domain(&a_domainlen, a, alen);
  1807. a_domain = get_registered_domain(&a_domainlen, a_domain, a_domainlen);
  1808. b_domain = extract_domain(&b_domainlen, b, blen);
  1809. b_domain = get_registered_domain(&b_domainlen, b_domain, b_domainlen);
  1810. if (a_domainlen != b_domainlen)
  1811. return false;
  1812. return !strncasecmp(a_domain, b_domain, a_domainlen);
  1813. }
  1814. static
  1815. void _test_extract_domain(const char * const expect, const char * const uri)
  1816. {
  1817. size_t sz;
  1818. const char * const d = extract_domain(&sz, uri, strlen(uri));
  1819. if (sz != strlen(expect) || strncasecmp(d, expect, sz))
  1820. {
  1821. ++unittest_failures;
  1822. applog(LOG_WARNING, "extract_domain \"%s\" test failed; got \"%.*s\" instead of \"%s\"",
  1823. uri, (int)sz, d, expect);
  1824. }
  1825. }
  1826. static
  1827. void _test_get_regd_domain(const char * const expect, const char * const fqdn)
  1828. {
  1829. size_t sz;
  1830. const char * const d = get_registered_domain(&sz, fqdn, strlen(fqdn));
  1831. if (d == NULL || sz != strlen(expect) || strncasecmp(d, expect, sz))
  1832. {
  1833. ++unittest_failures;
  1834. applog(LOG_WARNING, "get_registered_domain \"%s\" test failed; got \"%.*s\" instead of \"%s\"",
  1835. fqdn, (int)sz, d, expect);
  1836. }
  1837. }
  1838. void test_domain_funcs()
  1839. {
  1840. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334");
  1841. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334/abc/abc/");
  1842. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st/abc/abc/");
  1843. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st");
  1844. _test_extract_domain("s.m.eligius.st", "http:s.m.eligius.st");
  1845. _test_extract_domain("s.m.eligius.st", "stratum+tcp:s.m.eligius.st");
  1846. _test_extract_domain("s.m.eligius.st", "stratum+tcp:s.m.eligius.st:3334");
  1847. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st:3334");
  1848. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st:3334///");
  1849. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st.:3334///");
  1850. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334");
  1851. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334///");
  1852. _test_extract_domain("foohost", "foohost:3334");
  1853. _test_extract_domain("foohost", "foohost:3334///");
  1854. _test_extract_domain("foohost", "foohost:3334/abc.com//");
  1855. _test_extract_domain("", "foohost:");
  1856. _test_extract_domain("3334", "foohost://3334/abc.com//");
  1857. _test_extract_domain("192.0.2.0", "foohost:192.0.2.0");
  1858. _test_extract_domain("192.0.2.0", "192.0.2.0:3334");
  1859. _test_extract_domain("192.0.2.0", "192.0.2.0:3334///");
  1860. _test_extract_domain("2001:db8::1", "2001:db8::1");
  1861. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]");
  1862. _test_extract_domain("2001:db8::1", "http:[2001:db8::1]");
  1863. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]:42");
  1864. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]:42/abc//def/ghi");
  1865. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]");
  1866. _test_extract_domain("2001:db8::cafe", "http:[2001:db8::cafe]");
  1867. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]:42");
  1868. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]:42/abc//def/ghi");
  1869. _test_get_regd_domain("eligius.st", "s.m.eligius.st");
  1870. _test_get_regd_domain("eligius.st", "eligius.st");
  1871. _test_get_regd_domain("foohost.co.uk", "myserver.foohost.co.uk");
  1872. _test_get_regd_domain("foohost", "foohost");
  1873. _test_get_regd_domain("192.0.2.0", "192.0.2.0");
  1874. _test_get_regd_domain("2001:db8::1", "2001:db8::1");
  1875. }
  1876. struct bfg_strtobool_keyword {
  1877. bool val;
  1878. const char *keyword;
  1879. };
  1880. bool bfg_strtobool(const char * const s, char ** const endptr, __maybe_unused const int opts)
  1881. {
  1882. struct bfg_strtobool_keyword keywords[] = {
  1883. {false, "false"},
  1884. {false, "never"},
  1885. {false, "none"},
  1886. {false, "off"},
  1887. {false, "no"},
  1888. {false, "0"},
  1889. {true , "always"},
  1890. {true , "true"},
  1891. {true , "yes"},
  1892. {true , "on"},
  1893. };
  1894. const int total_keywords = sizeof(keywords) / sizeof(*keywords);
  1895. for (int i = 0; i < total_keywords; ++i)
  1896. {
  1897. const size_t kwlen = strlen(keywords[i].keyword);
  1898. if (!strncasecmp(keywords[i].keyword, s, kwlen))
  1899. {
  1900. if (endptr)
  1901. *endptr = (char*)&s[kwlen];
  1902. return keywords[i].val;
  1903. }
  1904. }
  1905. char *lend;
  1906. strtol(s, &lend, 0);
  1907. if (lend > s)
  1908. {
  1909. if (endptr)
  1910. *endptr = lend;
  1911. // Any number other than "0" is intentionally considered true, including 0x0
  1912. return true;
  1913. }
  1914. *endptr = (char*)s;
  1915. return false;
  1916. }
  1917. #define URI_FIND_PARAM_FOUND ((const char *)uri_find_param)
  1918. const char *uri_find_param(const char * const uri, const char * const param, bool * const invert_p)
  1919. {
  1920. const char *start = strchr(uri, '#');
  1921. if (invert_p)
  1922. *invert_p = false;
  1923. if (!start)
  1924. return NULL;
  1925. const char *p = start;
  1926. ++start;
  1927. nextmatch:
  1928. p = strstr(&p[1], param);
  1929. if (!p)
  1930. return NULL;
  1931. const char *q = &p[strlen(param)];
  1932. if (isCalpha(q[0]))
  1933. goto nextmatch;
  1934. if (invert_p && p - start >= 2 && (!strncasecmp(&p[-2], "no", 2)) && !isCalpha(p[-3]))
  1935. *invert_p = true;
  1936. else
  1937. if (isCalpha(p[-1]))
  1938. goto nextmatch;
  1939. if (q[0] == '=')
  1940. return &q[1];
  1941. return URI_FIND_PARAM_FOUND;
  1942. }
  1943. enum bfg_tristate uri_get_param_bool2(const char * const uri, const char * const param)
  1944. {
  1945. bool invert, foundval = true;
  1946. const char *q = uri_find_param(uri, param, &invert);
  1947. if (!q)
  1948. return BTS_UNKNOWN;
  1949. else
  1950. if (q != URI_FIND_PARAM_FOUND)
  1951. {
  1952. char *end;
  1953. bool v = bfg_strtobool(q, &end, 0);
  1954. if (end > q && !isCalpha(end[0]))
  1955. foundval = v;
  1956. }
  1957. if (invert)
  1958. foundval = !foundval;
  1959. return foundval;
  1960. }
  1961. bool uri_get_param_bool(const char * const uri, const char * const param, const bool defval)
  1962. {
  1963. const enum bfg_tristate rv = uri_get_param_bool2(uri, param);
  1964. if (rv == BTS_UNKNOWN)
  1965. return defval;
  1966. return rv;
  1967. }
  1968. static
  1969. void _test_uri_find_param(const char * const uri, const char * const param, const int expect_offset, const int expect_invert)
  1970. {
  1971. bool invert;
  1972. const char *actual = uri_find_param(uri, param, (expect_invert >= 0) ? &invert : NULL);
  1973. int actual_offset;
  1974. if (actual == URI_FIND_PARAM_FOUND)
  1975. actual_offset = -1;
  1976. else
  1977. if (!actual)
  1978. actual_offset = -2;
  1979. else
  1980. actual_offset = actual - uri;
  1981. int actual_invert = (expect_invert >= 0) ? (invert ? 1 : 0) : -1;
  1982. if (actual_offset != expect_offset || expect_invert != actual_invert)
  1983. {
  1984. ++unittest_failures;
  1985. applog(LOG_WARNING, "%s(\"%s\", \"%s\", %s) test failed (offset: expect=%d actual=%d; invert: expect=%d actual=%d)",
  1986. "uri_find_param", uri, param, (expect_invert >= 0) ? "(invert)" : "NULL",
  1987. expect_offset, actual_offset,
  1988. expect_invert, actual_invert);
  1989. }
  1990. }
  1991. static
  1992. void _test_uri_get_param(const char * const uri, const char * const param, const bool defval, const bool expect)
  1993. {
  1994. const bool actual = uri_get_param_bool(uri, param, defval);
  1995. if (actual != expect)
  1996. {
  1997. ++unittest_failures;
  1998. applog(LOG_WARNING, "%s(\"%s\", \"%s\", %s) test failed",
  1999. "uri_get_param_bool", uri, param, defval ? "true" : "false");
  2000. }
  2001. }
  2002. void test_uri_get_param()
  2003. {
  2004. _test_uri_find_param("stratum+tcp://footest/#redirect", "redirect", -1, -1);
  2005. _test_uri_find_param("stratum+tcp://footest/#redirectme", "redirect", -2, -1);
  2006. _test_uri_find_param("stratum+tcp://footest/#noredirect", "redirect", -2, -1);
  2007. _test_uri_find_param("stratum+tcp://footest/#noredirect", "redirect", -1, 1);
  2008. _test_uri_find_param("stratum+tcp://footest/#redirect", "redirect", -1, 0);
  2009. _test_uri_find_param("stratum+tcp://footest/#redirect=", "redirect", 32, -1);
  2010. _test_uri_find_param("stratum+tcp://footest/#noredirect=", "redirect", 34, 1);
  2011. _test_uri_get_param("stratum+tcp://footest/#redirect", "redirect", false, true);
  2012. _test_uri_get_param("stratum+tcp://footest/#redirectme", "redirect", false, false);
  2013. _test_uri_get_param("stratum+tcp://footest/#noredirect", "redirect", false, false);
  2014. _test_uri_get_param("stratum+tcp://footest/#redirect=0", "redirect", false, false);
  2015. _test_uri_get_param("stratum+tcp://footest/#redirect=1", "redirect", false, true);
  2016. _test_uri_get_param("stratum+tcp://footest/#redirect", "redirect", true, true);
  2017. _test_uri_get_param("stratum+tcp://footest/#redirectme", "redirect", true, true);
  2018. _test_uri_get_param("stratum+tcp://footest/#noredirect", "redirect", true, false);
  2019. _test_uri_get_param("stratum+tcp://footest/#redirect=0", "redirect", true, false);
  2020. _test_uri_get_param("stratum+tcp://footest/#redirect=1", "redirect", true, true);
  2021. _test_uri_get_param("stratum+tcp://footest/#redirect=0,foo=1", "redirect", true, false);
  2022. _test_uri_get_param("stratum+tcp://footest/#redirect=1,foo=0", "redirect", false, true);
  2023. _test_uri_get_param("stratum+tcp://footest/#foo=1,noredirect=0,foo=1", "redirect", false, true);
  2024. _test_uri_get_param("stratum+tcp://footest/#bar=0,noredirect=1,foo=0", "redirect", true, false);
  2025. _test_uri_get_param("stratum+tcp://footest/#redirect=false", "redirect", true, false);
  2026. _test_uri_get_param("stratum+tcp://footest/#redirect=no", "redirect", true, false);
  2027. _test_uri_get_param("stratum+tcp://footest/#redirect=yes", "redirect", false, true);
  2028. }
  2029. void stratum_probe_transparency(struct pool *pool)
  2030. {
  2031. // Request transaction data to discourage pools from doing anything shady
  2032. char s[1024];
  2033. int sLen;
  2034. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  2035. pool->swork.job_id,
  2036. pool->swork.job_id);
  2037. stratum_send(pool, s, sLen);
  2038. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  2039. timer_set_delay_from_now(&pool->swork.tv_transparency, 21093750L);
  2040. pool->swork.transparency_probed = true;
  2041. }
  2042. size_t script_to_address(char *out, size_t outsz, const uint8_t *script, size_t scriptsz, bool testnet)
  2043. {
  2044. char addr[35];
  2045. size_t size = sizeof(addr);
  2046. bool bok = false;
  2047. if (scriptsz == 25 && script[0] == 0x76 && script[1] == 0xa9 && script[2] == 0x14 && script[23] == 0x88 && script[24] == 0xac)
  2048. bok = b58check_enc(addr, &size, testnet ? 0x6f : 0x00, &script[3], 20);
  2049. else if (scriptsz == 23 && script[0] == 0xa9 && script[1] == 0x14 && script[22] == 0x87)
  2050. bok = b58check_enc(addr, &size, testnet ? 0xc4 : 0x05, &script[2], 20);
  2051. if (!bok)
  2052. return 0;
  2053. if (outsz >= size)
  2054. strcpy(out, addr);
  2055. return size;
  2056. }
  2057. size_t varint_decode(const uint8_t *p, size_t size, uint64_t *n)
  2058. {
  2059. if (size > 8 && p[0] == 0xff)
  2060. {
  2061. *n = upk_u64le(p, 0);
  2062. return 9;
  2063. }
  2064. if (size > 4 && p[0] == 0xfe)
  2065. {
  2066. *n = upk_u32le(p, 0);
  2067. return 5;
  2068. }
  2069. if (size > 2 && p[0] == 0xfd)
  2070. {
  2071. *n = upk_u16le(p, 0);
  2072. return 3;
  2073. }
  2074. if (size > 0)
  2075. {
  2076. *n = p[0];
  2077. return 1;
  2078. }
  2079. return 0;
  2080. }
  2081. /* Caller ensure cb_param is an valid pointer */
  2082. bool check_coinbase(const uint8_t *coinbase, size_t cbsize, const struct coinbase_param *cb_param)
  2083. {
  2084. int i;
  2085. size_t pos;
  2086. uint64_t len, total, target, amount, curr_pk_script_len;
  2087. bool found_target = false;
  2088. if (cbsize < 62)
  2089. /* Smallest possible length */
  2090. applogr(false, LOG_ERR, "Coinbase check: invalid length -- %lu", (unsigned long)cbsize);
  2091. pos = 4; /* Skip the version */
  2092. if (coinbase[pos] != 1)
  2093. applogr(false, LOG_ERR, "Coinbase check: multiple inputs in coinbase: 0x%02x", coinbase[pos]);
  2094. pos += 1 /* varint length */ + 32 /* prevhash */ + 4 /* 0xffffffff */;
  2095. if (coinbase[pos] < 2 || coinbase[pos] > 100)
  2096. applogr(false, LOG_ERR, "Coinbase check: invalid input script sig length: 0x%02x", coinbase[pos]);
  2097. pos += 1 /* varint length */ + coinbase[pos] + 4 /* 0xffffffff */;
  2098. if (cbsize <= pos)
  2099. incomplete_cb:
  2100. applogr(false, LOG_ERR, "Coinbase check: incomplete coinbase for payout check");
  2101. total = target = 0;
  2102. i = varint_decode(coinbase + pos, cbsize - pos, &len);
  2103. if (!i)
  2104. goto incomplete_cb;
  2105. pos += i;
  2106. while (len-- > 0)
  2107. {
  2108. if (cbsize <= pos + 8)
  2109. goto incomplete_cb;
  2110. amount = upk_u64le(coinbase, pos);
  2111. pos += 8; /* amount length */
  2112. total += amount;
  2113. i = varint_decode(coinbase + pos, cbsize - pos, &curr_pk_script_len);
  2114. if (!i || cbsize <= pos + i + curr_pk_script_len)
  2115. goto incomplete_cb;
  2116. pos += i;
  2117. struct bytes_hashtbl *ah = NULL;
  2118. HASH_FIND(hh, cb_param->scripts, &coinbase[pos], curr_pk_script_len, ah);
  2119. if (ah)
  2120. {
  2121. found_target = true;
  2122. target += amount;
  2123. }
  2124. if (opt_debug)
  2125. {
  2126. char s[(curr_pk_script_len * 2) + 3];
  2127. i = script_to_address(s, sizeof(s), &coinbase[pos], curr_pk_script_len, cb_param->testnet);
  2128. if (!(i && i <= sizeof(s)))
  2129. {
  2130. s[0] = '[';
  2131. bin2hex(&s[1], &coinbase[pos], curr_pk_script_len);
  2132. strcpy(&s[(curr_pk_script_len * 2) + 1], "]");
  2133. }
  2134. applog(LOG_DEBUG, "Coinbase output: %10"PRIu64" -- %s%s", amount, s, ah ? "*" : "");
  2135. }
  2136. pos += curr_pk_script_len;
  2137. }
  2138. if (total < cb_param->total)
  2139. applogr(false, LOG_ERR, "Coinbase check: lopsided total output amount = %"PRIu64", expecting >=%"PRIu64, total, cb_param->total);
  2140. if (cb_param->scripts)
  2141. {
  2142. if (cb_param->perc && !(total && (float)((double)target / total) >= cb_param->perc))
  2143. applogr(false, LOG_ERR, "Coinbase check: lopsided target/total = %g(%"PRIu64"/%"PRIu64"), expecting >=%g", (total ? (double)target / total : (double)0), target, total, cb_param->perc);
  2144. else
  2145. if (!found_target)
  2146. applogr(false, LOG_ERR, "Coinbase check: not found any target addr");
  2147. }
  2148. if (cbsize < pos + 4)
  2149. applogr(false, LOG_ERR, "Coinbase check: No room for locktime");
  2150. pos += 4;
  2151. if (opt_debug)
  2152. applog(LOG_DEBUG, "Coinbase: (size, pos, addr_count, target, total) = (%lu, %lu, %d, %"PRIu64", %"PRIu64")", (unsigned long)cbsize, (unsigned long)pos, (int)(HASH_COUNT(cb_param->scripts)), target, total);
  2153. return true;
  2154. }
  2155. static bool parse_notify(struct pool *pool, json_t *val)
  2156. {
  2157. const char *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  2158. char *job_id;
  2159. bool clean, ret = false;
  2160. int merkles, i;
  2161. size_t cb1_len, cb2_len;
  2162. json_t *arr;
  2163. arr = json_array_get(val, 4);
  2164. if (!arr || !json_is_array(arr))
  2165. goto out;
  2166. merkles = json_array_size(arr);
  2167. for (i = 0; i < merkles; i++)
  2168. if (!json_is_string(json_array_get(arr, i)))
  2169. goto out;
  2170. prev_hash = __json_array_string(val, 1);
  2171. coinbase1 = __json_array_string(val, 2);
  2172. coinbase2 = __json_array_string(val, 3);
  2173. bbversion = __json_array_string(val, 5);
  2174. nbit = __json_array_string(val, 6);
  2175. ntime = __json_array_string(val, 7);
  2176. clean = json_is_true(json_array_get(val, 8));
  2177. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  2178. goto out;
  2179. job_id = json_array_string(val, 0);
  2180. if (!job_id)
  2181. goto out;
  2182. cg_wlock(&pool->data_lock);
  2183. cgtime(&pool->swork.tv_received);
  2184. free(pool->swork.job_id);
  2185. pool->swork.job_id = job_id;
  2186. if (pool->swork.tr)
  2187. {
  2188. tmpl_decref(pool->swork.tr);
  2189. pool->swork.tr = NULL;
  2190. }
  2191. pool->submit_old = !clean;
  2192. pool->swork.clean = true;
  2193. // stratum_set_goal ensures these are the same pointer if they match
  2194. if (pool->goalname != pool->next_goalname)
  2195. {
  2196. free(pool->goalname);
  2197. pool->goalname = pool->next_goalname;
  2198. mining_goal_reset(pool->goal);
  2199. }
  2200. if (pool->next_goal_malgo)
  2201. {
  2202. goal_set_malgo(pool->goal, pool->next_goal_malgo);
  2203. pool->next_goal_malgo = NULL;
  2204. }
  2205. if (pool->next_nonce1)
  2206. {
  2207. free(pool->swork.nonce1);
  2208. pool->n1_len = strlen(pool->next_nonce1) / 2;
  2209. pool->swork.nonce1 = pool->next_nonce1;
  2210. pool->next_nonce1 = NULL;
  2211. }
  2212. int n2size = pool->swork.n2size = pool->next_n2size;
  2213. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  2214. #ifdef WORDS_BIGENDIAN
  2215. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  2216. #endif
  2217. hex2bin(&pool->swork.header1[0], bbversion, 4);
  2218. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  2219. hex2bin((void*)&pool->swork.ntime, ntime, 4);
  2220. pool->swork.ntime = be32toh(pool->swork.ntime);
  2221. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  2222. /* Nominally allow a driver to ntime roll 60 seconds */
  2223. set_simple_ntime_roll_limit(&pool->swork.ntime_roll_limits, pool->swork.ntime, 60, &pool->swork.tv_received);
  2224. cb1_len = strlen(coinbase1) / 2;
  2225. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  2226. cb2_len = strlen(coinbase2) / 2;
  2227. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->swork.n2size + cb2_len);
  2228. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  2229. hex2bin(coinbase, coinbase1, cb1_len);
  2230. hex2bin(&coinbase[cb1_len], pool->swork.nonce1, pool->n1_len);
  2231. // NOTE: gap for nonce2, filled at work generation time
  2232. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->swork.n2size], coinbase2, cb2_len);
  2233. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  2234. for (i = 0; i < merkles; i++)
  2235. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  2236. pool->swork.merkles = merkles;
  2237. pool->nonce2 = 0;
  2238. memcpy(pool->swork.target, pool->next_target, 0x20);
  2239. pool_check_coinbase(pool, coinbase, bytes_len(&pool->swork.coinbase));
  2240. cg_wunlock(&pool->data_lock);
  2241. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  2242. pool->pool_no, job_id);
  2243. if (opt_debug && opt_protocol)
  2244. {
  2245. applog(LOG_DEBUG, "job_id: %s", job_id);
  2246. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  2247. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  2248. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  2249. for (i = 0; i < merkles; i++)
  2250. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  2251. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  2252. applog(LOG_DEBUG, "nbit: %s", nbit);
  2253. applog(LOG_DEBUG, "ntime: %s", ntime);
  2254. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  2255. }
  2256. /* A notify message is the closest stratum gets to a getwork */
  2257. pool->getwork_requested++;
  2258. total_getworks++;
  2259. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  2260. if (pool->probed)
  2261. stratum_probe_transparency(pool);
  2262. ret = true;
  2263. out:
  2264. return ret;
  2265. }
  2266. static bool parse_diff(struct pool *pool, json_t *val)
  2267. {
  2268. const struct mining_goal_info * const goal = pool->goal;
  2269. const struct mining_algorithm * const malgo = goal->malgo;
  2270. double diff;
  2271. diff = json_number_value(json_array_get(val, 0));
  2272. if (diff == 0)
  2273. return false;
  2274. if ((int64_t)diff != diff)
  2275. {
  2276. // Assume fractional values are proper bdiff per specification
  2277. // Allow integers to be interpreted as pdiff, since the difference is trivial and some pools see it this way
  2278. diff = bdiff_to_pdiff(diff);
  2279. }
  2280. #ifdef USE_SHA256D
  2281. if (malgo->algo == POW_SHA256D && diff < 1 && diff > 0.999)
  2282. diff = 1;
  2283. #endif
  2284. #ifdef USE_SCRYPT
  2285. // Broken Scrypt pools multiply difficulty by 0x10000
  2286. const double broken_scrypt_diff_multiplier = 0x10000;
  2287. /* 7/12/2014: P2Pool code was fixed: https://github.com/forrestv/p2pool/pull/210
  2288. 7/15/2014: Popular pools unfixed: wemineltc, dogehouse, p2pool.org
  2289. Cannot find a broken Scrypt pool that will dispense diff lower than 16 */
  2290. // Ideally pools will fix their implementation and we can remove this
  2291. // This should suffice until miners are hashing Scrypt at ~1-7 Gh/s (based on a share rate target of 10-60s)
  2292. const double minimum_broken_scrypt_diff = 16;
  2293. // Diff 16 at 1.15 Gh/s = 1 share / 60s
  2294. // Diff 16 at 7.00 Gh/s = 1 share / 10s
  2295. if (malgo->algo == POW_SCRYPT && (diff >= minimum_broken_scrypt_diff))
  2296. diff /= broken_scrypt_diff_multiplier;
  2297. #endif
  2298. cg_wlock(&pool->data_lock);
  2299. set_target_to_pdiff(pool->next_target, diff);
  2300. cg_wunlock(&pool->data_lock);
  2301. applog(LOG_DEBUG, "Pool %d stratum difficulty set to %g", pool->pool_no, diff);
  2302. return true;
  2303. }
  2304. static
  2305. bool stratum_set_extranonce(struct pool * const pool, json_t * const val, json_t * const params)
  2306. {
  2307. char *nonce1 = NULL;
  2308. int n2size = 0;
  2309. json_t *j;
  2310. if (!json_is_array(params))
  2311. goto err;
  2312. switch (json_array_size(params))
  2313. {
  2314. default: // >=2
  2315. // n2size
  2316. j = json_array_get(params, 1);
  2317. if (json_is_number(j))
  2318. {
  2319. n2size = json_integer_value(j);
  2320. if (n2size < 1)
  2321. goto err;
  2322. }
  2323. else
  2324. if (!json_is_null(j))
  2325. goto err;
  2326. // fallthru
  2327. case 1:
  2328. // nonce1
  2329. j = json_array_get(params, 0);
  2330. if (json_is_string(j))
  2331. nonce1 = strdup(json_string_value(j));
  2332. else
  2333. if (!json_is_null(j))
  2334. goto err;
  2335. break;
  2336. case 0:
  2337. applog(LOG_WARNING, "Pool %u: No-op mining.set_extranonce?", pool->pool_no);
  2338. return true;
  2339. }
  2340. cg_wlock(&pool->data_lock);
  2341. if (nonce1)
  2342. {
  2343. free(pool->next_nonce1);
  2344. pool->next_nonce1 = nonce1;
  2345. }
  2346. if (n2size)
  2347. pool->next_n2size = n2size;
  2348. cg_wunlock(&pool->data_lock);
  2349. return true;
  2350. err:
  2351. applog(LOG_ERR, "Pool %u: Invalid mining.set_extranonce", pool->pool_no);
  2352. json_t *id = json_object_get(val, "id");
  2353. if (id && !json_is_null(id))
  2354. {
  2355. char s[RBUFSIZE], *idstr;
  2356. idstr = json_dumps_ANY(id, 0);
  2357. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [20, \"Invalid params\"]}", idstr);
  2358. free(idstr);
  2359. stratum_send(pool, s, strlen(s));
  2360. }
  2361. return true;
  2362. }
  2363. static
  2364. bool stratum_set_goal(struct pool * const pool, json_t * const val, json_t * const params)
  2365. {
  2366. if (!uri_get_param_bool(pool->rpc_url, "goalreset", false))
  2367. return false;
  2368. const char * const new_goalname = __json_array_string(params, 0);
  2369. struct mining_algorithm *new_malgo = NULL;
  2370. const char *emsg = NULL;
  2371. if (json_is_array(params) && json_array_size(params) > 1)
  2372. {
  2373. json_t * const j_goaldesc = json_array_get(params, 1);
  2374. if (json_is_object(j_goaldesc))
  2375. {
  2376. json_t * const j_malgo = json_object_get(j_goaldesc, "malgo");
  2377. if (j_malgo && json_is_string(j_malgo))
  2378. {
  2379. const char * const newvalue = json_string_value(j_malgo);
  2380. new_malgo = mining_algorithm_by_alias(newvalue);
  2381. // Even if it's the current malgo, we should reset next_goal_malgo in case of a prior set_goal
  2382. if (new_malgo == pool->goal->malgo)
  2383. {} // Do nothing, assignment takes place below
  2384. if (new_malgo && uri_get_param_bool(pool->rpc_url, "change_goal_malgo", false))
  2385. {} // Do nothing, assignment takes place below
  2386. else
  2387. {
  2388. emsg = "Mining algorithm not supported";
  2389. // Ignore even the goal name, if we are failing
  2390. goto out;
  2391. }
  2392. if (new_malgo == pool->goal->malgo)
  2393. new_malgo = NULL;
  2394. }
  2395. }
  2396. }
  2397. // Even if the goal name is not changing, we need to adopt and configuration change
  2398. pool->next_goal_malgo = new_malgo;
  2399. if (pool->next_goalname && pool->next_goalname != pool->goalname)
  2400. free(pool->next_goalname);
  2401. // This compares goalname to new_goalname, but matches NULL correctly :)
  2402. if (pool->goalname ? !strcmp(pool->goalname, new_goalname) : !new_goalname)
  2403. pool->next_goalname = pool->goalname;
  2404. else
  2405. pool->next_goalname = maybe_strdup(new_goalname);
  2406. out: ;
  2407. json_t * const j_id = json_object_get(val, "id");
  2408. if (j_id && !json_is_null(j_id))
  2409. {
  2410. char * const idstr = json_dumps_ANY(j_id, 0);
  2411. char buf[0x80];
  2412. if (unlikely(emsg))
  2413. snprintf(buf, sizeof(buf), "{\"id\":%s,\"result\":true,\"error\":null}", idstr);
  2414. else
  2415. snprintf(buf, sizeof(buf), "{\"id\":%s,\"result\":null,\"error\":[-1,\"%s\",null]}", idstr, emsg);
  2416. free(idstr);
  2417. stratum_send(pool, buf, strlen(buf));
  2418. }
  2419. return true;
  2420. }
  2421. static bool parse_reconnect(struct pool *pool, json_t *val)
  2422. {
  2423. if (opt_disable_client_reconnect)
  2424. return false;
  2425. const char *url;
  2426. char address[256];
  2427. json_t *port_json;
  2428. url = __json_array_string(val, 0);
  2429. if (!url)
  2430. url = pool->sockaddr_url;
  2431. else
  2432. if (!pool_may_redirect_to(pool, url))
  2433. return false;
  2434. port_json = json_array_get(val, 1);
  2435. if (json_is_number(port_json))
  2436. {
  2437. const unsigned port = json_number_value(port_json);
  2438. snprintf(address, sizeof(address), "%s:%u", url, port);
  2439. }
  2440. else
  2441. {
  2442. const char *port;
  2443. if (json_is_string(port_json))
  2444. port = json_string_value(port_json);
  2445. else
  2446. port = pool->stratum_port;
  2447. snprintf(address, sizeof(address), "%s:%s", url, port);
  2448. }
  2449. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  2450. return false;
  2451. pool->stratum_url = pool->sockaddr_url;
  2452. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  2453. if (!restart_stratum(pool))
  2454. return false;
  2455. return true;
  2456. }
  2457. static bool send_version(struct pool *pool, json_t *val)
  2458. {
  2459. char s[RBUFSIZE], *idstr;
  2460. json_t *id = json_object_get(val, "id");
  2461. if (!(id && !json_is_null(id)))
  2462. return false;
  2463. idstr = json_dumps_ANY(id, 0);
  2464. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  2465. free(idstr);
  2466. if (!stratum_send(pool, s, strlen(s)))
  2467. return false;
  2468. return true;
  2469. }
  2470. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  2471. {
  2472. char *msg;
  2473. char s[RBUFSIZE], *idstr;
  2474. json_t *id = json_object_get(val, "id");
  2475. msg = json_array_string(params, 0);
  2476. if (likely(msg))
  2477. {
  2478. free(pool->admin_msg);
  2479. pool->admin_msg = msg;
  2480. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  2481. }
  2482. if (!(id && !json_is_null(id)))
  2483. return true;
  2484. idstr = json_dumps_ANY(id, 0);
  2485. if (likely(msg))
  2486. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  2487. else
  2488. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  2489. free(idstr);
  2490. if (!stratum_send(pool, s, strlen(s)))
  2491. return false;
  2492. return true;
  2493. }
  2494. bool parse_method(struct pool *pool, char *s)
  2495. {
  2496. json_t *val = NULL, *method, *err_val, *params;
  2497. json_error_t err;
  2498. bool ret = false;
  2499. const char *buf;
  2500. if (!s)
  2501. goto out;
  2502. val = JSON_LOADS(s, &err);
  2503. if (!val) {
  2504. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2505. goto out;
  2506. }
  2507. method = json_object_get(val, "method");
  2508. if (!method)
  2509. goto out;
  2510. err_val = json_object_get(val, "error");
  2511. params = json_object_get(val, "params");
  2512. if (err_val && !json_is_null(err_val)) {
  2513. char *ss;
  2514. if (err_val)
  2515. ss = json_dumps(err_val, JSON_INDENT(3));
  2516. else
  2517. ss = strdup("(unknown reason)");
  2518. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  2519. free(ss);
  2520. goto out;
  2521. }
  2522. buf = json_string_value(method);
  2523. if (!buf)
  2524. goto out;
  2525. if (!strncasecmp(buf, "mining.notify", 13)) {
  2526. if (parse_notify(pool, params))
  2527. pool->stratum_notify = ret = true;
  2528. else
  2529. pool->stratum_notify = ret = false;
  2530. goto out;
  2531. }
  2532. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  2533. ret = true;
  2534. goto out;
  2535. }
  2536. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  2537. ret = true;
  2538. goto out;
  2539. }
  2540. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  2541. ret = true;
  2542. goto out;
  2543. }
  2544. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  2545. ret = true;
  2546. goto out;
  2547. }
  2548. if (!strncasecmp(buf, "mining.set_extranonce", 21) && stratum_set_extranonce(pool, val, params)) {
  2549. ret = true;
  2550. goto out;
  2551. }
  2552. // Usage: mining.set_goal("goal name", {"malgo":"SHA256d", ...})
  2553. if (!strncasecmp(buf, "mining.set_goal", 15) && stratum_set_goal(pool, val, params))
  2554. return_via(out, ret = true);
  2555. out:
  2556. if (val)
  2557. json_decref(val);
  2558. return ret;
  2559. }
  2560. extern bool parse_stratum_response(struct pool *, char *s);
  2561. bool auth_stratum(struct pool *pool)
  2562. {
  2563. json_t *val = NULL, *res_val, *err_val;
  2564. char s[RBUFSIZE], *sret = NULL;
  2565. json_error_t err;
  2566. bool ret = false;
  2567. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  2568. pool->rpc_user, pool->rpc_pass);
  2569. if (!stratum_send(pool, s, strlen(s)))
  2570. goto out;
  2571. /* Parse all data in the queue and anything left should be auth */
  2572. while (42) {
  2573. sret = recv_line(pool);
  2574. if (!sret)
  2575. goto out;
  2576. if (parse_method(pool, sret))
  2577. free(sret);
  2578. else
  2579. {
  2580. bool unknown = true;
  2581. val = JSON_LOADS(sret, &err);
  2582. json_t *j_id = json_object_get(val, "id");
  2583. if (json_is_string(j_id))
  2584. {
  2585. if (!strcmp(json_string_value(j_id), "auth"))
  2586. break;
  2587. else
  2588. if (!strcmp(json_string_value(j_id), "xnsub"))
  2589. unknown = false;
  2590. }
  2591. if (unknown)
  2592. applog(LOG_WARNING, "Pool %u: Unknown stratum msg: %s", pool->pool_no, sret);
  2593. free(sret);
  2594. }
  2595. }
  2596. free(sret);
  2597. res_val = json_object_get(val, "result");
  2598. err_val = json_object_get(val, "error");
  2599. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2600. char *ss;
  2601. if (err_val)
  2602. ss = json_dumps(err_val, JSON_INDENT(3));
  2603. else
  2604. ss = strdup("(unknown reason)");
  2605. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  2606. free(ss);
  2607. goto out;
  2608. }
  2609. ret = true;
  2610. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  2611. pool->probed = true;
  2612. successful_connect = true;
  2613. out:
  2614. if (val)
  2615. json_decref(val);
  2616. if (pool->stratum_notify)
  2617. stratum_probe_transparency(pool);
  2618. return ret;
  2619. }
  2620. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  2621. {
  2622. struct pool *pool = clientp;
  2623. curl_socket_t sck = bfg_socket(addr->family, addr->socktype, addr->protocol);
  2624. pool->sock = sck;
  2625. return sck;
  2626. }
  2627. static bool setup_stratum_curl(struct pool *pool)
  2628. {
  2629. CURL *curl = NULL;
  2630. char s[RBUFSIZE];
  2631. bool ret = false;
  2632. bool tls_only = false, try_tls = true;
  2633. bool tlsca = uri_get_param_bool(pool->rpc_url, "tlsca", false);
  2634. {
  2635. const enum bfg_tristate tlsparam = uri_get_param_bool2(pool->rpc_url, "tls");
  2636. if (tlsparam != BTS_UNKNOWN)
  2637. try_tls = tls_only = tlsparam;
  2638. else
  2639. if (tlsca)
  2640. // If tlsca is enabled, require TLS by default
  2641. tls_only = true;
  2642. }
  2643. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  2644. mutex_lock(&pool->stratum_lock);
  2645. timer_unset(&pool->swork.tv_transparency);
  2646. pool->stratum_active = false;
  2647. pool->stratum_notify = false;
  2648. pool->swork.transparency_probed = false;
  2649. if (pool->stratum_curl)
  2650. curl_easy_cleanup(pool->stratum_curl);
  2651. pool->stratum_curl = curl_easy_init();
  2652. if (unlikely(!pool->stratum_curl))
  2653. quithere(1, "Failed to curl_easy_init");
  2654. if (pool->sockbuf)
  2655. pool->sockbuf[0] = '\0';
  2656. curl = pool->stratum_curl;
  2657. if (!pool->sockbuf) {
  2658. pool->sockbuf = calloc(RBUFSIZE, 1);
  2659. if (!pool->sockbuf)
  2660. quithere(1, "Failed to calloc pool sockbuf");
  2661. pool->sockbuf_size = RBUFSIZE;
  2662. }
  2663. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  2664. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  2665. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, pool->curl_err_str);
  2666. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  2667. if (!opt_delaynet)
  2668. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  2669. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  2670. * to enable it */
  2671. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  2672. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  2673. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2674. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  2675. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  2676. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  2677. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  2678. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, (long)(tlsca ? 2 : 0));
  2679. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, (long)(tlsca ? 1 : 0));
  2680. if (pool->rpc_proxy) {
  2681. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  2682. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  2683. } else if (opt_socks_proxy) {
  2684. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  2685. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  2686. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  2687. }
  2688. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  2689. retry:
  2690. /* Create a http url for use with curl */
  2691. sprintf(s, "http%s://%s:%s", try_tls ? "s" : "",
  2692. pool->sockaddr_url, pool->stratum_port);
  2693. curl_easy_setopt(curl, CURLOPT_URL, s);
  2694. pool->sock = INVSOCK;
  2695. if (curl_easy_perform(curl)) {
  2696. if (try_tls)
  2697. {
  2698. applog(LOG_DEBUG, "Stratum connect failed with TLS to pool %u: %s",
  2699. pool->pool_no, pool->curl_err_str);
  2700. if (!tls_only)
  2701. {
  2702. try_tls = false;
  2703. goto retry;
  2704. }
  2705. }
  2706. else
  2707. applog(LOG_INFO, "Stratum connect failed to pool %d: %s",
  2708. pool->pool_no, pool->curl_err_str);
  2709. errout:
  2710. curl_easy_cleanup(curl);
  2711. pool->stratum_curl = NULL;
  2712. goto out;
  2713. }
  2714. if (pool->sock == INVSOCK)
  2715. {
  2716. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  2717. goto errout;
  2718. }
  2719. keep_sockalive(pool->sock);
  2720. pool->cgminer_pool_stats.times_sent++;
  2721. pool->cgminer_pool_stats.times_received++;
  2722. ret = true;
  2723. out:
  2724. mutex_unlock(&pool->stratum_lock);
  2725. return ret;
  2726. }
  2727. static char *get_sessionid(json_t *val)
  2728. {
  2729. char *ret = NULL;
  2730. json_t *arr_val;
  2731. int arrsize, i;
  2732. arr_val = json_array_get(val, 0);
  2733. if (!arr_val || !json_is_array(arr_val))
  2734. goto out;
  2735. arrsize = json_array_size(arr_val);
  2736. for (i = 0; i < arrsize; i++) {
  2737. json_t *arr = json_array_get(arr_val, i);
  2738. const char *notify;
  2739. if (!arr | !json_is_array(arr))
  2740. break;
  2741. notify = __json_array_string(arr, 0);
  2742. if (!notify)
  2743. continue;
  2744. if (!strncasecmp(notify, "mining.notify", 13)) {
  2745. ret = json_array_string(arr, 1);
  2746. break;
  2747. }
  2748. }
  2749. out:
  2750. return ret;
  2751. }
  2752. void suspend_stratum(struct pool *pool)
  2753. {
  2754. clear_sockbuf(pool);
  2755. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2756. mutex_lock(&pool->stratum_lock);
  2757. pool->stratum_active = pool->stratum_notify = false;
  2758. if (pool->stratum_curl) {
  2759. curl_easy_cleanup(pool->stratum_curl);
  2760. }
  2761. pool->stratum_curl = NULL;
  2762. pool->sock = INVSOCK;
  2763. mutex_unlock(&pool->stratum_lock);
  2764. }
  2765. bool initiate_stratum(struct pool *pool)
  2766. {
  2767. bool ret = false, recvd = false, noresume = false, sockd = false;
  2768. bool trysuggest = request_target_str;
  2769. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  2770. json_t *val = NULL, *res_val, *err_val;
  2771. json_error_t err;
  2772. int n2size;
  2773. resend:
  2774. if (!setup_stratum_curl(pool)) {
  2775. sockd = false;
  2776. goto out;
  2777. }
  2778. sockd = true;
  2779. clear_sock(pool);
  2780. if (trysuggest)
  2781. {
  2782. int sz = sprintf(s, "{\"id\": null, \"method\": \"mining.suggest_target\", \"params\": [\"%s\"]}", request_target_str);
  2783. if (!_stratum_send(pool, s, sz, true))
  2784. {
  2785. applog(LOG_DEBUG, "Pool %u: Failed to send suggest_target in initiate_stratum", pool->pool_no);
  2786. goto out;
  2787. }
  2788. recvd = true;
  2789. }
  2790. if (uri_get_param_bool(pool->rpc_url, "goalreset", false))
  2791. {
  2792. // Default: ["notify", "set_difficulty"] (but these must be explicit if mining.capabilities is used)
  2793. snprintf(s, sizeof(s), "{\"id\":null,\"method\":\"mining.capabilities\",\"params\":[{\"notify\":[],\"set_difficulty\":{},\"set_goal\":[],\"malgo\":{");
  2794. struct mining_algorithm *malgo;
  2795. LL_FOREACH(mining_algorithms, malgo)
  2796. {
  2797. tailsprintf(s, sizeof(s), "\"%s\":{}%c", malgo->name, malgo->next ? ',' : '}');
  2798. }
  2799. if (request_target_str)
  2800. tailsprintf(s, sizeof(s), ",\"suggested_target\":\"%s\"", request_target_str);
  2801. tailsprintf(s, sizeof(s), "}]}");
  2802. _stratum_send(pool, s, strlen(s), true);
  2803. }
  2804. if (noresume) {
  2805. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2806. } else {
  2807. if (pool->sessionid)
  2808. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2809. else
  2810. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  2811. }
  2812. if (!_stratum_send(pool, s, strlen(s), true)) {
  2813. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2814. goto out;
  2815. }
  2816. recvd = true;
  2817. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2818. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2819. goto out;
  2820. }
  2821. sret = recv_line(pool);
  2822. if (!sret)
  2823. goto out;
  2824. val = JSON_LOADS(sret, &err);
  2825. free(sret);
  2826. if (!val) {
  2827. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2828. goto out;
  2829. }
  2830. res_val = json_object_get(val, "result");
  2831. err_val = json_object_get(val, "error");
  2832. if (!res_val || json_is_null(res_val) ||
  2833. (err_val && !json_is_null(err_val))) {
  2834. char *ss;
  2835. if (err_val)
  2836. ss = json_dumps(err_val, JSON_INDENT(3));
  2837. else
  2838. ss = strdup("(unknown reason)");
  2839. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2840. free(ss);
  2841. goto out;
  2842. }
  2843. sessionid = get_sessionid(res_val);
  2844. if (!sessionid)
  2845. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2846. nonce1 = json_array_string(res_val, 1);
  2847. if (!nonce1) {
  2848. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  2849. free(sessionid);
  2850. goto out;
  2851. }
  2852. n2size = json_integer_value(json_array_get(res_val, 2));
  2853. if (n2size < 1)
  2854. {
  2855. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  2856. free(sessionid);
  2857. free(nonce1);
  2858. goto out;
  2859. }
  2860. cg_wlock(&pool->data_lock);
  2861. free(pool->sessionid);
  2862. pool->sessionid = sessionid;
  2863. free(pool->next_nonce1);
  2864. pool->next_nonce1 = nonce1;
  2865. pool->next_n2size = n2size;
  2866. cg_wunlock(&pool->data_lock);
  2867. if (sessionid)
  2868. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2869. ret = true;
  2870. out:
  2871. if (val)
  2872. {
  2873. json_decref(val);
  2874. val = NULL;
  2875. }
  2876. if (ret) {
  2877. if (!pool->stratum_url)
  2878. pool->stratum_url = pool->sockaddr_url;
  2879. pool->stratum_active = true;
  2880. set_target_to_pdiff(pool->next_target, 1);
  2881. if (opt_protocol) {
  2882. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2883. pool->pool_no, pool->next_nonce1, pool->next_n2size);
  2884. }
  2885. if (uri_get_param_bool(pool->rpc_url, "xnsub", false))
  2886. {
  2887. sprintf(s, "{\"id\": \"xnsub\", \"method\": \"mining.extranonce.subscribe\", \"params\": []}");
  2888. _stratum_send(pool, s, strlen(s), true);
  2889. }
  2890. } else {
  2891. if (recvd)
  2892. {
  2893. if (trysuggest)
  2894. {
  2895. applog(LOG_DEBUG, "Pool %u: Failed to connect stratum with mining.suggest_target, retrying without", pool->pool_no);
  2896. trysuggest = false;
  2897. goto resend;
  2898. }
  2899. if (!noresume)
  2900. {
  2901. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2902. noresume = true;
  2903. goto resend;
  2904. }
  2905. }
  2906. applog(LOG_DEBUG, "Initiate stratum failed");
  2907. if (sockd)
  2908. suspend_stratum(pool);
  2909. }
  2910. return ret;
  2911. }
  2912. bool restart_stratum(struct pool *pool)
  2913. {
  2914. bool ret = true;
  2915. mutex_lock(&pool->pool_test_lock);
  2916. if (pool->stratum_active)
  2917. suspend_stratum(pool);
  2918. if (!initiate_stratum(pool))
  2919. return_via(out, ret = false);
  2920. if (!auth_stratum(pool))
  2921. return_via(out, ret = false);
  2922. out:
  2923. mutex_unlock(&pool->pool_test_lock);
  2924. return ret;
  2925. }
  2926. void dev_error_update(struct cgpu_info *dev, enum dev_reason reason)
  2927. {
  2928. dev->device_last_not_well = time(NULL);
  2929. cgtime(&dev->tv_device_last_not_well);
  2930. dev->device_not_well_reason = reason;
  2931. }
  2932. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2933. {
  2934. dev_error_update(dev, reason);
  2935. switch (reason) {
  2936. case REASON_THREAD_FAIL_INIT:
  2937. dev->thread_fail_init_count++;
  2938. break;
  2939. case REASON_THREAD_ZERO_HASH:
  2940. dev->thread_zero_hash_count++;
  2941. break;
  2942. case REASON_THREAD_FAIL_QUEUE:
  2943. dev->thread_fail_queue_count++;
  2944. break;
  2945. case REASON_DEV_SICK_IDLE_60:
  2946. dev->dev_sick_idle_60_count++;
  2947. break;
  2948. case REASON_DEV_DEAD_IDLE_600:
  2949. dev->dev_dead_idle_600_count++;
  2950. break;
  2951. case REASON_DEV_NOSTART:
  2952. dev->dev_nostart_count++;
  2953. break;
  2954. case REASON_DEV_OVER_HEAT:
  2955. dev->dev_over_heat_count++;
  2956. break;
  2957. case REASON_DEV_THERMAL_CUTOFF:
  2958. dev->dev_thermal_cutoff_count++;
  2959. break;
  2960. case REASON_DEV_COMMS_ERROR:
  2961. dev->dev_comms_error_count++;
  2962. break;
  2963. case REASON_DEV_THROTTLE:
  2964. dev->dev_throttle_count++;
  2965. break;
  2966. }
  2967. }
  2968. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2969. void *realloc_strcat(char *ptr, char *s)
  2970. {
  2971. size_t old = strlen(ptr), len = strlen(s);
  2972. char *ret;
  2973. if (!len)
  2974. return ptr;
  2975. len += old + 1;
  2976. align_len(&len);
  2977. ret = malloc(len);
  2978. if (unlikely(!ret))
  2979. quithere(1, "Failed to malloc");
  2980. sprintf(ret, "%s%s", ptr, s);
  2981. free(ptr);
  2982. return ret;
  2983. }
  2984. static
  2985. bool sanechars[] = {
  2986. false, false, false, false, false, false, false, false,
  2987. false, false, false, false, false, false, false, false,
  2988. false, false, false, false, false, false, false, false,
  2989. false, false, false, false, false, false, false, false,
  2990. false, false, false, false, false, false, false, false,
  2991. false, false, false, false, false, true , false, false,
  2992. true , true , true , true , true , true , true , true ,
  2993. true , true , false, false, false, false, false, false,
  2994. false, true , true , true , true , true , true , true ,
  2995. true , true , true , true , true , true , true , true ,
  2996. true , true , true , true , true , true , true , true ,
  2997. true , true , true , false, false, false, false, false,
  2998. false, true , true , true , true , true , true , true ,
  2999. true , true , true , true , true , true , true , true ,
  3000. true , true , true , true , true , true , true , true ,
  3001. true , true , true , false, false, false, false, false,
  3002. };
  3003. char *sanestr(char *o, char *s)
  3004. {
  3005. char *rv = o;
  3006. bool br = false;
  3007. for ( ; s[0]; ++s)
  3008. {
  3009. if (sanechars[s[0] & 0x7f])
  3010. {
  3011. if (br)
  3012. {
  3013. br = false;
  3014. if (s[0] >= '0' && s[0] <= '9')
  3015. (o++)[0] = '_';
  3016. }
  3017. (o++)[0] = s[0];
  3018. }
  3019. else
  3020. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  3021. br = true;
  3022. }
  3023. o[0] = '\0';
  3024. return rv;
  3025. }
  3026. void RenameThread(const char* name)
  3027. {
  3028. #if defined(PR_SET_NAME)
  3029. // Only the first 15 characters are used (16 - NUL terminator)
  3030. prctl(PR_SET_NAME, name, 0, 0, 0);
  3031. #elif defined(__APPLE__)
  3032. pthread_setname_np(name);
  3033. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  3034. pthread_set_name_np(pthread_self(), name);
  3035. #else
  3036. // Prevent warnings for unused parameters...
  3037. (void)name;
  3038. #endif
  3039. }
  3040. static pthread_key_t key_bfgtls;
  3041. struct bfgtls_data {
  3042. char *bfg_strerror_result;
  3043. size_t bfg_strerror_resultsz;
  3044. #ifdef WIN32
  3045. LPSTR bfg_strerror_socketresult;
  3046. #endif
  3047. #ifdef NEED_BFG_LOWL_VCOM
  3048. struct detectone_meta_info_t __detectone_meta_info;
  3049. #endif
  3050. unsigned probe_result_flags;
  3051. };
  3052. static
  3053. struct bfgtls_data *get_bfgtls()
  3054. {
  3055. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  3056. if (bfgtls)
  3057. return bfgtls;
  3058. void *p;
  3059. bfgtls = malloc(sizeof(*bfgtls));
  3060. if (!bfgtls)
  3061. quithere(1, "malloc bfgtls failed");
  3062. p = malloc(64);
  3063. if (!p)
  3064. quithere(1, "malloc bfg_strerror_result failed");
  3065. *bfgtls = (struct bfgtls_data){
  3066. .bfg_strerror_resultsz = 64,
  3067. .bfg_strerror_result = p,
  3068. };
  3069. if (pthread_setspecific(key_bfgtls, bfgtls))
  3070. quithere(1, "pthread_setspecific failed");
  3071. return bfgtls;
  3072. }
  3073. static
  3074. void bfgtls_free(void * const p)
  3075. {
  3076. struct bfgtls_data * const bfgtls = p;
  3077. free(bfgtls->bfg_strerror_result);
  3078. #ifdef WIN32
  3079. if (bfgtls->bfg_strerror_socketresult)
  3080. LocalFree(bfgtls->bfg_strerror_socketresult);
  3081. #endif
  3082. free(bfgtls);
  3083. }
  3084. #ifdef NEED_BFG_LOWL_VCOM
  3085. struct detectone_meta_info_t *_detectone_meta_info()
  3086. {
  3087. return &get_bfgtls()->__detectone_meta_info;
  3088. }
  3089. #endif
  3090. unsigned *_bfg_probe_result_flags()
  3091. {
  3092. return &get_bfgtls()->probe_result_flags;
  3093. }
  3094. void bfg_init_threadlocal()
  3095. {
  3096. if (pthread_key_create(&key_bfgtls, bfgtls_free))
  3097. quithere(1, "pthread_key_create failed");
  3098. }
  3099. static
  3100. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  3101. {
  3102. if (minimum <= *bufszp)
  3103. return false;
  3104. while (minimum > *bufszp)
  3105. *bufszp = 2;
  3106. *bufp = realloc(*bufp, *bufszp);
  3107. if (unlikely(!*bufp))
  3108. quithere(1, "realloc failed");
  3109. return true;
  3110. }
  3111. static
  3112. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  3113. {
  3114. if (!src)
  3115. return NULL;
  3116. const size_t srcsz = strlen(src) + 1;
  3117. bfg_grow_buffer(bufp, bufszp, srcsz);
  3118. memcpy(*bufp, src, srcsz);
  3119. return *bufp;
  3120. }
  3121. // Guaranteed to always return some string (or quit)
  3122. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  3123. {
  3124. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  3125. struct bfgtls_data *bfgtls = get_bfgtls();
  3126. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  3127. char ** const bufp = &bfgtls->bfg_strerror_result;
  3128. const char *have = NULL;
  3129. switch (type) {
  3130. case BST_LIBUSB:
  3131. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  3132. #ifdef HAVE_LIBUSB
  3133. # if HAVE_DECL_LIBUSB_ERROR_NAME
  3134. // libusb makes no guarantees for thread-safety or persistence
  3135. mutex_lock(&mutex);
  3136. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  3137. mutex_unlock(&mutex);
  3138. # endif
  3139. #endif
  3140. break;
  3141. case BST_SOCKET:
  3142. case BST_SYSTEM:
  3143. {
  3144. #ifdef WIN32
  3145. // Windows has a different namespace for system and socket errors
  3146. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  3147. if (*msg)
  3148. LocalFree(*msg);
  3149. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  3150. {
  3151. LPSTR msgp = *msg;
  3152. size_t n = strlen(msgp);
  3153. while (isCspace(msgp[--n]))
  3154. msgp[n] = '\0';
  3155. return *msg;
  3156. }
  3157. *msg = NULL;
  3158. break;
  3159. #endif
  3160. }
  3161. // Fallthru on non-WIN32
  3162. case BST_ERRNO:
  3163. {
  3164. #ifdef __STRERROR_S_WORKS
  3165. // FIXME: Not sure how to get this on MingW64
  3166. retry:
  3167. if (likely(!strerror_s(*bufp, *bufszp, e)))
  3168. {
  3169. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  3170. goto retry;
  3171. return *bufp;
  3172. }
  3173. // TODO: XSI strerror_r
  3174. // TODO: GNU strerror_r
  3175. #else
  3176. mutex_lock(&mutex);
  3177. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  3178. mutex_unlock(&mutex);
  3179. #endif
  3180. }
  3181. }
  3182. if (have)
  3183. return *bufp;
  3184. // Failback: Stringify the number
  3185. static const char fmt[] = "%s error #%d", *typestr;
  3186. switch (type) {
  3187. case BST_ERRNO:
  3188. typestr = "System";
  3189. break;
  3190. case BST_SOCKET:
  3191. typestr = "Socket";
  3192. break;
  3193. case BST_LIBUSB:
  3194. typestr = "libusb";
  3195. break;
  3196. default:
  3197. typestr = "Unexpected";
  3198. }
  3199. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  3200. bfg_grow_buffer(bufp, bufszp, sz);
  3201. sprintf(*bufp, fmt, typestr, e);
  3202. return *bufp;
  3203. }
  3204. void notifier_init(notifier_t pipefd)
  3205. {
  3206. #ifdef WIN32
  3207. #define WindowsErrorStr(e) bfg_strerror(e, BST_SOCKET)
  3208. SOCKET listener, connecter, acceptor;
  3209. listener = bfg_socket(AF_INET, SOCK_STREAM, 0);
  3210. if (listener == INVALID_SOCKET)
  3211. quit(1, "Failed to create listener socket"IN_FMT_FFL": %s",
  3212. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3213. connecter = bfg_socket(AF_INET, SOCK_STREAM, 0);
  3214. if (connecter == INVALID_SOCKET)
  3215. quit(1, "Failed to create connect socket"IN_FMT_FFL": %s",
  3216. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3217. struct sockaddr_in inaddr = {
  3218. .sin_family = AF_INET,
  3219. .sin_addr = {
  3220. .s_addr = htonl(INADDR_LOOPBACK),
  3221. },
  3222. .sin_port = 0,
  3223. };
  3224. {
  3225. static const int reuse = 1;
  3226. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
  3227. }
  3228. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  3229. quit(1, "Failed to bind listener socket"IN_FMT_FFL": %s",
  3230. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3231. socklen_t inaddr_sz = sizeof(inaddr);
  3232. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  3233. quit(1, "Failed to getsockname"IN_FMT_FFL": %s",
  3234. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3235. if (listen(listener, 1) == SOCKET_ERROR)
  3236. quit(1, "Failed to listen"IN_FMT_FFL": %s",
  3237. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3238. inaddr.sin_family = AF_INET;
  3239. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3240. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  3241. quit(1, "Failed to connect"IN_FMT_FFL": %s",
  3242. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3243. acceptor = accept(listener, NULL, NULL);
  3244. if (acceptor == INVALID_SOCKET)
  3245. quit(1, "Failed to accept"IN_FMT_FFL": %s",
  3246. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3247. closesocket(listener);
  3248. pipefd[0] = connecter;
  3249. pipefd[1] = acceptor;
  3250. #else
  3251. if (pipe(pipefd))
  3252. quithere(1, "Failed to create pipe");
  3253. #endif
  3254. }
  3255. void *bfg_slurp_file(void * const bufp, size_t bufsz, const char * const filename)
  3256. {
  3257. char *buf = bufp;
  3258. FILE * const F = fopen(filename, "r");
  3259. if (!F)
  3260. goto err;
  3261. if (!buf)
  3262. {
  3263. fseek(F, 0, SEEK_END);
  3264. const long filesz = ftell(F);
  3265. if (unlikely(filesz < 0))
  3266. {
  3267. fclose(F);
  3268. goto err;
  3269. }
  3270. rewind(F);
  3271. bufsz = filesz + 1;
  3272. buf = malloc(bufsz);
  3273. }
  3274. const size_t rsz = fread(buf, 1, bufsz - 1, F);
  3275. fclose(F);
  3276. buf[rsz] = '\0';
  3277. return buf;
  3278. err:
  3279. if (buf)
  3280. buf[0] = '\0';
  3281. return NULL;
  3282. }
  3283. void notifier_wake(notifier_t fd)
  3284. {
  3285. if (fd[1] == INVSOCK)
  3286. return;
  3287. if (1 !=
  3288. #ifdef WIN32
  3289. send(fd[1], "\0", 1, 0)
  3290. #else
  3291. write(fd[1], "\0", 1)
  3292. #endif
  3293. )
  3294. applog(LOG_WARNING, "Error trying to wake notifier");
  3295. }
  3296. void notifier_read(notifier_t fd)
  3297. {
  3298. char buf[0x10];
  3299. #ifdef WIN32
  3300. IGNORE_RETURN_VALUE(recv(fd[0], buf, sizeof(buf), 0));
  3301. #else
  3302. IGNORE_RETURN_VALUE(read(fd[0], buf, sizeof(buf)));
  3303. #endif
  3304. }
  3305. bool notifier_wait(notifier_t notifier, const struct timeval *tvp_timeout)
  3306. {
  3307. struct timeval tv_now, tv_timeout;
  3308. fd_set rfds;
  3309. int e;
  3310. while (true)
  3311. {
  3312. FD_ZERO(&rfds);
  3313. FD_SET(notifier[0], &rfds);
  3314. tv_timeout = *tvp_timeout;
  3315. timer_set_now(&tv_now);
  3316. e = select(notifier[0]+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now));
  3317. if (e > 0)
  3318. return true;
  3319. if (e == 0)
  3320. return false;
  3321. }
  3322. }
  3323. bool notifier_wait_us(notifier_t notifier, const unsigned long long usecs)
  3324. {
  3325. struct timeval tv_timeout = TIMEVAL_USECS(usecs);
  3326. return notifier_wait(notifier, &tv_timeout);
  3327. }
  3328. void notifier_reset(notifier_t notifier)
  3329. {
  3330. fd_set rfds;
  3331. struct timeval tv_timeout = { .tv_sec = 0, };
  3332. FD_ZERO(&rfds);
  3333. FD_SET(notifier[0], &rfds);
  3334. while (select(notifier[0]+1, &rfds, NULL, NULL, &tv_timeout) != 0)
  3335. notifier_read(notifier);
  3336. }
  3337. void notifier_init_invalid(notifier_t fd)
  3338. {
  3339. fd[0] = fd[1] = INVSOCK;
  3340. }
  3341. void notifier_destroy(notifier_t fd)
  3342. {
  3343. #ifdef WIN32
  3344. closesocket(fd[0]);
  3345. closesocket(fd[1]);
  3346. #else
  3347. close(fd[0]);
  3348. close(fd[1]);
  3349. #endif
  3350. fd[0] = fd[1] = INVSOCK;
  3351. }
  3352. void _bytes_alloc_failure(size_t sz)
  3353. {
  3354. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  3355. }
  3356. char *trimmed_strdup(const char *s)
  3357. {
  3358. size_t n;
  3359. char *c;
  3360. while (isspace(s[0]))
  3361. ++s;
  3362. n = strlen(s) - 1;
  3363. while (isspace(s[n]))
  3364. --n;
  3365. ++n;
  3366. c = malloc(n + 1);
  3367. c[n] = '\0';
  3368. memcpy(c, s, n);
  3369. return c;
  3370. }
  3371. void *cmd_thread(void *cmdp)
  3372. {
  3373. const char *cmd = cmdp;
  3374. applog(LOG_DEBUG, "Executing command: %s", cmd);
  3375. int rc = system(cmd);
  3376. if (rc)
  3377. applog(LOG_WARNING, "Command returned %d exit code: %s", rc, cmd);
  3378. return NULL;
  3379. }
  3380. void run_cmd(const char *cmd)
  3381. {
  3382. if (!cmd)
  3383. return;
  3384. pthread_t pth;
  3385. pthread_create(&pth, NULL, cmd_thread, (void*)cmd);
  3386. }
  3387. uint8_t crc5usb(unsigned char *ptr, uint8_t len)
  3388. {
  3389. uint8_t i, j, k;
  3390. uint8_t crc = 0x1f;
  3391. uint8_t crcin[5] = {1, 1, 1, 1, 1};
  3392. uint8_t crcout[5] = {1, 1, 1, 1, 1};
  3393. uint8_t din = 0;
  3394. j = 0x80;
  3395. k = 0;
  3396. for (i = 0; i < len; i++)
  3397. {
  3398. if (*ptr & j)
  3399. din = 1;
  3400. else
  3401. din = 0;
  3402. crcout[0] = crcin[4] ^ din;
  3403. crcout[1] = crcin[0];
  3404. crcout[2] = crcin[1] ^ crcin[4] ^ din;
  3405. crcout[3] = crcin[2];
  3406. crcout[4] = crcin[3];
  3407. j = j >> 1;
  3408. k++;
  3409. if (k == 8)
  3410. {
  3411. j = 0x80;
  3412. k = 0;
  3413. ptr++;
  3414. }
  3415. memcpy(crcin, crcout, 5);
  3416. }
  3417. crc = 0;
  3418. if(crcin[4])
  3419. crc |= 0x10;
  3420. if(crcin[3])
  3421. crc |= 0x08;
  3422. if(crcin[2])
  3423. crc |= 0x04;
  3424. if(crcin[1])
  3425. crc |= 0x02;
  3426. if(crcin[0])
  3427. crc |= 0x01;
  3428. return crc;
  3429. }
  3430. static uint8_t _crc8ccitt_table[0x100];
  3431. void bfg_init_checksums(void)
  3432. {
  3433. for (int i = 0; i < 0x100; ++i)
  3434. {
  3435. uint8_t crc = i;
  3436. for (int j = 0; j < 8; ++j)
  3437. crc = (crc << 1) ^ ((crc & 0x80) ? 7 : 0);
  3438. _crc8ccitt_table[i] = crc & 0xff;
  3439. }
  3440. }
  3441. uint8_t crc8ccitt(const void * const buf, const size_t buflen)
  3442. {
  3443. const uint8_t *p = buf;
  3444. uint8_t crc = 0xff;
  3445. for (int i = 0; i < buflen; ++i)
  3446. crc = _crc8ccitt_table[crc ^ *p++];
  3447. return crc;
  3448. }
  3449. static uint16_t crc16tab[] = {
  3450. 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
  3451. 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
  3452. 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
  3453. 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
  3454. 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
  3455. 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
  3456. 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
  3457. 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
  3458. 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
  3459. 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
  3460. 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
  3461. 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
  3462. 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
  3463. 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
  3464. 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
  3465. 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
  3466. 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
  3467. 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
  3468. 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
  3469. 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
  3470. 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
  3471. 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
  3472. 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
  3473. 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
  3474. 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
  3475. 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
  3476. 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
  3477. 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
  3478. 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
  3479. 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
  3480. 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
  3481. 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0,
  3482. };
  3483. static
  3484. uint16_t crc16_floating(uint16_t next_byte, uint16_t seed)
  3485. {
  3486. return ((seed << 8) ^ crc16tab[(seed >> 8) ^ next_byte]) & 0xFFFF;
  3487. }
  3488. uint16_t crc16(const void *p, size_t sz, uint16_t crc)
  3489. {
  3490. const uint8_t * const s = p;
  3491. for (size_t i = 0; i < sz; ++i)
  3492. crc = crc16_floating(s[i], crc);
  3493. return crc;
  3494. }