util.c 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981
  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. void hash_data(unsigned char *out_hash, const unsigned char *data)
  672. {
  673. unsigned char blkheader[80];
  674. // data is past the first SHA256 step (padding and interpreting as big endian on a little endian platform), so we need to flip each 32-bit chunk around to get the original input block header
  675. swap32yes(blkheader, data, 80 / 4);
  676. // double-SHA256 to get the block hash
  677. gen_hash(blkheader, out_hash, 80);
  678. }
  679. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  680. void real_block_target(unsigned char *target, const unsigned char *data)
  681. {
  682. uint8_t targetshift;
  683. if (unlikely(data[72] < 3 || data[72] > 0x20))
  684. {
  685. // Invalid (out of bounds) target
  686. memset(target, 0xff, 32);
  687. return;
  688. }
  689. targetshift = data[72] - 3;
  690. memset(target, 0, targetshift);
  691. target[targetshift++] = data[75];
  692. target[targetshift++] = data[74];
  693. target[targetshift++] = data[73];
  694. memset(&target[targetshift], 0, 0x20 - targetshift);
  695. }
  696. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  697. {
  698. const uint32_t *h32 = (uint32_t*)&hash[0];
  699. const uint32_t *t32 = (uint32_t*)&target[0];
  700. for (int i = 7; i >= 0; --i) {
  701. uint32_t h32i = le32toh(h32[i]);
  702. uint32_t t32i = le32toh(t32[i]);
  703. if (h32i > t32i)
  704. return false;
  705. if (h32i < t32i)
  706. return true;
  707. }
  708. return true;
  709. }
  710. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  711. {
  712. bool rc;
  713. rc = hash_target_check(hash, target);
  714. if (opt_debug) {
  715. unsigned char hash_swap[32], target_swap[32];
  716. char hash_str[65];
  717. char target_str[65];
  718. for (int i = 0; i < 32; ++i) {
  719. hash_swap[i] = hash[31-i];
  720. target_swap[i] = target[31-i];
  721. }
  722. bin2hex(hash_str, hash_swap, 32);
  723. bin2hex(target_str, target_swap, 32);
  724. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  725. hash_str,
  726. target_str,
  727. rc ? "YES (hash <= target)" :
  728. "no (false positive; hash > target)");
  729. }
  730. return rc;
  731. }
  732. // This operates on a native-endian SHA256 state
  733. // In other words, on little endian platforms, every 4 bytes are in reverse order
  734. bool fulltest(const unsigned char *hash, const unsigned char *target)
  735. {
  736. unsigned char hash2[32];
  737. swap32tobe(hash2, hash, 32 / 4);
  738. return hash_target_check_v(hash2, target);
  739. }
  740. struct thread_q *tq_new(void)
  741. {
  742. struct thread_q *tq;
  743. tq = calloc(1, sizeof(*tq));
  744. if (!tq)
  745. return NULL;
  746. pthread_mutex_init(&tq->mutex, NULL);
  747. pthread_cond_init(&tq->cond, bfg_condattr);
  748. return tq;
  749. }
  750. void tq_free(struct thread_q *tq)
  751. {
  752. struct tq_ent *ent, *iter;
  753. if (!tq)
  754. return;
  755. DL_FOREACH_SAFE(tq->q, ent, iter) {
  756. DL_DELETE(tq->q, ent);
  757. free(ent);
  758. }
  759. pthread_cond_destroy(&tq->cond);
  760. pthread_mutex_destroy(&tq->mutex);
  761. memset(tq, 0, sizeof(*tq)); /* poison */
  762. free(tq);
  763. }
  764. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  765. {
  766. mutex_lock(&tq->mutex);
  767. tq->frozen = frozen;
  768. pthread_cond_signal(&tq->cond);
  769. mutex_unlock(&tq->mutex);
  770. }
  771. void tq_freeze(struct thread_q *tq)
  772. {
  773. tq_freezethaw(tq, true);
  774. }
  775. void tq_thaw(struct thread_q *tq)
  776. {
  777. tq_freezethaw(tq, false);
  778. }
  779. bool tq_push(struct thread_q *tq, void *data)
  780. {
  781. struct tq_ent *ent;
  782. bool rc = true;
  783. ent = calloc(1, sizeof(*ent));
  784. if (!ent)
  785. return false;
  786. ent->data = data;
  787. mutex_lock(&tq->mutex);
  788. if (!tq->frozen) {
  789. DL_APPEND(tq->q, ent);
  790. } else {
  791. free(ent);
  792. rc = false;
  793. }
  794. pthread_cond_signal(&tq->cond);
  795. mutex_unlock(&tq->mutex);
  796. return rc;
  797. }
  798. void *tq_pop(struct thread_q * const tq)
  799. {
  800. struct tq_ent *ent;
  801. void *rval = NULL;
  802. int rc;
  803. mutex_lock(&tq->mutex);
  804. if (tq->q)
  805. goto pop;
  806. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  807. if (rc)
  808. goto out;
  809. if (!tq->q)
  810. goto out;
  811. pop:
  812. ent = tq->q;
  813. rval = ent->data;
  814. DL_DELETE(tq->q, ent);
  815. free(ent);
  816. out:
  817. mutex_unlock(&tq->mutex);
  818. return rval;
  819. }
  820. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  821. {
  822. int rv = pthread_create(&thr->pth, attr, start, arg);
  823. if (likely(!rv))
  824. thr->has_pth = true;
  825. return rv;
  826. }
  827. void thr_info_freeze(struct thr_info *thr)
  828. {
  829. struct tq_ent *ent, *iter;
  830. struct thread_q *tq;
  831. if (!thr)
  832. return;
  833. tq = thr->q;
  834. if (!tq)
  835. return;
  836. mutex_lock(&tq->mutex);
  837. tq->frozen = true;
  838. DL_FOREACH_SAFE(tq->q, ent, iter) {
  839. DL_DELETE(tq->q, ent);
  840. free(ent);
  841. }
  842. mutex_unlock(&tq->mutex);
  843. }
  844. void thr_info_cancel(struct thr_info *thr)
  845. {
  846. if (!thr)
  847. return;
  848. if (thr->has_pth) {
  849. pthread_cancel(thr->pth);
  850. thr->has_pth = false;
  851. }
  852. }
  853. #ifndef HAVE_PTHREAD_CANCEL
  854. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  855. enum pthread_cancel_workaround_mode {
  856. PCWM_DEFAULT = 0,
  857. PCWM_TERMINATE = 1,
  858. PCWM_ASYNC = 2,
  859. PCWM_DISABLED = 4,
  860. PCWM_CANCELLED = 8,
  861. };
  862. static pthread_key_t key_pcwm;
  863. struct sigaction pcwm_orig_term_handler;
  864. static
  865. void do_pthread_cancel_exit(int flags)
  866. {
  867. if (!(flags & PCWM_ASYNC))
  868. // NOTE: Logging disables cancel while mutex held, so this is safe
  869. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  870. pthread_exit(PTHREAD_CANCELED);
  871. }
  872. static
  873. void sighandler_pthread_cancel(int sig)
  874. {
  875. int flags = (int)pthread_getspecific(key_pcwm);
  876. if (flags & PCWM_TERMINATE) // Main thread
  877. {
  878. // Restore original handler and call it
  879. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  880. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  881. raise(SIGTERM);
  882. quit(1, "pthread_cancel workaround: Original handler returned");
  883. }
  884. if (flags & PCWM_CANCELLED) // Already pending cancel
  885. return;
  886. if (flags & PCWM_DISABLED)
  887. {
  888. flags |= PCWM_CANCELLED;
  889. if (pthread_setspecific(key_pcwm, (void*)flags))
  890. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  891. return;
  892. }
  893. do_pthread_cancel_exit(flags);
  894. }
  895. void pthread_testcancel(void)
  896. {
  897. int flags = (int)pthread_getspecific(key_pcwm);
  898. if (flags & PCWM_CANCELLED && !(flags & PCWM_DISABLED))
  899. do_pthread_cancel_exit(flags);
  900. }
  901. int pthread_setcancelstate(int state, int *oldstate)
  902. {
  903. int flags = (int)pthread_getspecific(key_pcwm);
  904. if (oldstate)
  905. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  906. if (state == PTHREAD_CANCEL_DISABLE)
  907. flags |= PCWM_DISABLED;
  908. else
  909. {
  910. if (flags & PCWM_CANCELLED)
  911. do_pthread_cancel_exit(flags);
  912. flags &= ~PCWM_DISABLED;
  913. }
  914. if (pthread_setspecific(key_pcwm, (void*)flags))
  915. return -1;
  916. return 0;
  917. }
  918. int pthread_setcanceltype(int type, int *oldtype)
  919. {
  920. int flags = (int)pthread_getspecific(key_pcwm);
  921. if (oldtype)
  922. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  923. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  924. flags |= PCWM_ASYNC;
  925. else
  926. flags &= ~PCWM_ASYNC;
  927. if (pthread_setspecific(key_pcwm, (void*)flags))
  928. return -1;
  929. return 0;
  930. }
  931. void setup_pthread_cancel_workaround()
  932. {
  933. if (pthread_key_create(&key_pcwm, NULL))
  934. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  935. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  936. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  937. struct sigaction new_sigact = {
  938. .sa_handler = sighandler_pthread_cancel,
  939. };
  940. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  941. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  942. }
  943. #endif
  944. static void _now_gettimeofday(struct timeval *);
  945. static void _cgsleep_us_r_nanosleep(cgtimer_t *, int64_t);
  946. #ifdef HAVE_POOR_GETTIMEOFDAY
  947. static struct timeval tv_timeofday_offset;
  948. static struct timeval _tv_timeofday_lastchecked;
  949. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  950. static
  951. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  952. {
  953. struct timeval actual, delta;
  954. timeradd(expected, &tv_timeofday_offset, expected);
  955. _now_gettimeofday(&actual);
  956. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  957. // Within reason - no change necessary
  958. return;
  959. timersub(&actual, expected, &delta);
  960. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  961. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  962. *expected = actual;
  963. }
  964. void bfg_gettimeofday(struct timeval *out)
  965. {
  966. char buf[64] = "";
  967. timer_set_now(out);
  968. mutex_lock(&_tv_timeofday_mutex);
  969. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  970. bfg_calibrate_timeofday(out, buf);
  971. else
  972. timeradd(out, &tv_timeofday_offset, out);
  973. mutex_unlock(&_tv_timeofday_mutex);
  974. if (unlikely(buf[0]))
  975. applog(LOG_WARNING, "%s", buf);
  976. }
  977. #endif
  978. #ifdef WIN32
  979. static LARGE_INTEGER _perffreq;
  980. static
  981. void _now_queryperformancecounter(struct timeval *tv)
  982. {
  983. LARGE_INTEGER now;
  984. if (unlikely(!QueryPerformanceCounter(&now)))
  985. quit(1, "QueryPerformanceCounter failed");
  986. *tv = (struct timeval){
  987. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  988. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  989. };
  990. }
  991. #endif
  992. static void bfg_init_time();
  993. static
  994. void _now_is_not_set(__maybe_unused struct timeval *tv)
  995. {
  996. bfg_init_time();
  997. timer_set_now(tv);
  998. }
  999. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  1000. void (*cgsleep_us_r)(cgtimer_t *, int64_t) = _cgsleep_us_r_nanosleep;
  1001. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1002. static clockid_t bfg_timer_clk;
  1003. static
  1004. void _now_clock_gettime(struct timeval *tv)
  1005. {
  1006. struct timespec ts;
  1007. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  1008. quit(1, "clock_gettime failed");
  1009. *tv = (struct timeval){
  1010. .tv_sec = ts.tv_sec,
  1011. .tv_usec = ts.tv_nsec / 1000,
  1012. };
  1013. }
  1014. #ifdef HAVE_CLOCK_NANOSLEEP
  1015. static
  1016. void _cgsleep_us_r_monotonic(cgtimer_t *tv_start, int64_t us)
  1017. {
  1018. struct timeval tv_end[1];
  1019. struct timespec ts_end[1];
  1020. int ret;
  1021. timer_set_delay(tv_end, tv_start, us);
  1022. timeval_to_spec(ts_end, tv_end);
  1023. do {
  1024. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  1025. } while (ret == EINTR);
  1026. }
  1027. #endif
  1028. static
  1029. bool _bfg_try_clock_gettime(clockid_t clk)
  1030. {
  1031. struct timespec ts;
  1032. if (clock_gettime(clk, &ts))
  1033. return false;
  1034. bfg_timer_clk = clk;
  1035. timer_set_now = _now_clock_gettime;
  1036. return true;
  1037. }
  1038. #endif
  1039. pthread_condattr_t *bfg_condattr_()
  1040. {
  1041. return NULL;
  1042. }
  1043. static
  1044. void bfg_init_time()
  1045. {
  1046. if (timer_set_now != _now_is_not_set)
  1047. return;
  1048. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1049. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1050. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1051. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1052. else
  1053. #endif
  1054. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1055. {
  1056. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1057. #ifdef HAVE_CLOCK_NANOSLEEP
  1058. cgsleep_us_r = _cgsleep_us_r_monotonic;
  1059. #endif
  1060. }
  1061. else
  1062. #endif
  1063. #ifdef WIN32
  1064. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1065. {
  1066. timer_set_now = _now_queryperformancecounter;
  1067. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1068. }
  1069. else
  1070. #endif
  1071. {
  1072. timer_set_now = _now_gettimeofday;
  1073. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1074. }
  1075. #ifdef HAVE_POOR_GETTIMEOFDAY
  1076. char buf[64] = "";
  1077. struct timeval tv;
  1078. timer_set_now(&tv);
  1079. bfg_calibrate_timeofday(&tv, buf);
  1080. applog(LOG_DEBUG, "%s", buf);
  1081. #endif
  1082. }
  1083. void subtime(struct timeval *a, struct timeval *b)
  1084. {
  1085. timersub(a, b, b);
  1086. }
  1087. void addtime(struct timeval *a, struct timeval *b)
  1088. {
  1089. timeradd(a, b, b);
  1090. }
  1091. bool time_more(struct timeval *a, struct timeval *b)
  1092. {
  1093. return timercmp(a, b, >);
  1094. }
  1095. bool time_less(struct timeval *a, struct timeval *b)
  1096. {
  1097. return timercmp(a, b, <);
  1098. }
  1099. void copy_time(struct timeval *dest, const struct timeval *src)
  1100. {
  1101. memcpy(dest, src, sizeof(struct timeval));
  1102. }
  1103. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  1104. {
  1105. val->tv_sec = spec->tv_sec;
  1106. val->tv_usec = spec->tv_nsec / 1000;
  1107. }
  1108. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  1109. {
  1110. spec->tv_sec = val->tv_sec;
  1111. spec->tv_nsec = val->tv_usec * 1000;
  1112. }
  1113. void us_to_timeval(struct timeval *val, int64_t us)
  1114. {
  1115. lldiv_t tvdiv = lldiv(us, 1000000);
  1116. val->tv_sec = tvdiv.quot;
  1117. val->tv_usec = tvdiv.rem;
  1118. }
  1119. void us_to_timespec(struct timespec *spec, int64_t us)
  1120. {
  1121. lldiv_t tvdiv = lldiv(us, 1000000);
  1122. spec->tv_sec = tvdiv.quot;
  1123. spec->tv_nsec = tvdiv.rem * 1000;
  1124. }
  1125. void ms_to_timespec(struct timespec *spec, int64_t ms)
  1126. {
  1127. lldiv_t tvdiv = lldiv(ms, 1000);
  1128. spec->tv_sec = tvdiv.quot;
  1129. spec->tv_nsec = tvdiv.rem * 1000000;
  1130. }
  1131. void timeraddspec(struct timespec *a, const struct timespec *b)
  1132. {
  1133. a->tv_sec += b->tv_sec;
  1134. a->tv_nsec += b->tv_nsec;
  1135. if (a->tv_nsec >= 1000000000) {
  1136. a->tv_nsec -= 1000000000;
  1137. a->tv_sec++;
  1138. }
  1139. }
  1140. #ifndef WIN32
  1141. static
  1142. void _now_gettimeofday(struct timeval *tv)
  1143. {
  1144. gettimeofday(tv, NULL);
  1145. }
  1146. #else
  1147. /* Windows start time is since 1601 lol so convert it to unix epoch 1970. */
  1148. #define EPOCHFILETIME (116444736000000000LL)
  1149. void _now_gettimeofday(struct timeval *tv)
  1150. {
  1151. FILETIME ft;
  1152. LARGE_INTEGER li;
  1153. GetSystemTimeAsFileTime(&ft);
  1154. li.LowPart = ft.dwLowDateTime;
  1155. li.HighPart = ft.dwHighDateTime;
  1156. li.QuadPart -= EPOCHFILETIME;
  1157. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1158. tv->tv_sec = li.QuadPart / 10000000;
  1159. tv->tv_usec = li.QuadPart % 10000000;
  1160. }
  1161. #endif
  1162. void cgsleep_ms_r(cgtimer_t *tv_start, int ms)
  1163. {
  1164. cgsleep_us_r(tv_start, ((int64_t)ms) * 1000);
  1165. }
  1166. static
  1167. void _cgsleep_us_r_nanosleep(cgtimer_t *tv_start, int64_t us)
  1168. {
  1169. struct timeval tv_timer[1], tv[1];
  1170. struct timespec ts[1];
  1171. timer_set_delay(tv_timer, tv_start, us);
  1172. while (true)
  1173. {
  1174. timer_set_now(tv);
  1175. if (!timercmp(tv_timer, tv, >))
  1176. return;
  1177. timersub(tv_timer, tv, tv);
  1178. timeval_to_spec(ts, tv);
  1179. nanosleep(ts, NULL);
  1180. }
  1181. }
  1182. void cgsleep_ms(int ms)
  1183. {
  1184. cgtimer_t ts_start;
  1185. cgsleep_prepare_r(&ts_start);
  1186. cgsleep_ms_r(&ts_start, ms);
  1187. }
  1188. void cgsleep_us(int64_t us)
  1189. {
  1190. cgtimer_t ts_start;
  1191. cgsleep_prepare_r(&ts_start);
  1192. cgsleep_us_r(&ts_start, us);
  1193. }
  1194. /* Returns the microseconds difference between end and start times as a double */
  1195. double us_tdiff(struct timeval *end, struct timeval *start)
  1196. {
  1197. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1198. }
  1199. /* Returns the seconds difference between end and start times as a double */
  1200. double tdiff(struct timeval *end, struct timeval *start)
  1201. {
  1202. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1203. }
  1204. int double_find_precision(double f, const double base)
  1205. {
  1206. int rv = 0;
  1207. for ( ; floor(f) != f; ++rv)
  1208. f *= base;
  1209. return rv;
  1210. }
  1211. int utf8_len(const uint8_t b)
  1212. {
  1213. if (!(b & 0x80))
  1214. return 1;
  1215. if (!(b & 0x20))
  1216. return 2;
  1217. else
  1218. if (!(b & 0x10))
  1219. return 3;
  1220. else
  1221. return 4;
  1222. }
  1223. int32_t utf8_decode(const void *b, int *out_len)
  1224. {
  1225. int32_t w;
  1226. const unsigned char *s = b;
  1227. *out_len = utf8_len(s[0]);
  1228. if (*out_len == 1)
  1229. // ASCII
  1230. return s[0];
  1231. #ifdef STRICT_UTF8
  1232. if (unlikely(!(s[0] & 0x40)))
  1233. goto invalid;
  1234. if (unlikely(s[0] & 0x38 == 0x38))
  1235. goto invalid;
  1236. #endif
  1237. w = s[0] & ((2 << (6 - *out_len)) - 1);
  1238. for (int i = 1; i < *out_len; ++i)
  1239. {
  1240. #ifdef STRICT_UTF8
  1241. if (unlikely((s[i] & 0xc0) != 0x80))
  1242. goto invalid;
  1243. #endif
  1244. w = (w << 6) | (s[i] & 0x3f);
  1245. }
  1246. #if defined(STRICT_UTF8)
  1247. if (unlikely(w > 0x10FFFF))
  1248. goto invalid;
  1249. // FIXME: UTF-8 requires smallest possible encoding; check it
  1250. #endif
  1251. return w;
  1252. #ifdef STRICT_UTF8
  1253. invalid:
  1254. *out_len = 1;
  1255. return REPLACEMENT_CHAR;
  1256. #endif
  1257. }
  1258. size_t utf8_strlen(const void * const b)
  1259. {
  1260. const uint8_t *s = b;
  1261. size_t c = 0;
  1262. int clen, i;
  1263. while (s[0])
  1264. {
  1265. clen = utf8_len(s[0]);
  1266. for (i = 0; i < clen; ++i)
  1267. if (!s[i])
  1268. clen = 1;
  1269. ++c;
  1270. s += clen;
  1271. }
  1272. return c;
  1273. }
  1274. static
  1275. void _utf8_test(const char *s, const wchar_t expected, int expectedlen)
  1276. {
  1277. int len;
  1278. wchar_t r;
  1279. if (expected != REPLACEMENT_CHAR)
  1280. {
  1281. len = utf8_len(((uint8_t*)s)[0]);
  1282. if (len != expectedlen)
  1283. {
  1284. ++unittest_failures;
  1285. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_len=>%d", (unsigned long)expected, expectedlen, len);
  1286. }
  1287. len = utf8_strlen(s);
  1288. if (len != (s[0] ? 1 : 0))
  1289. {
  1290. ++unittest_failures;
  1291. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_strlen=>%d", (unsigned long)expected, expectedlen, len);
  1292. }
  1293. len = -1;
  1294. }
  1295. r = utf8_decode(s, &len);
  1296. if (unlikely(r != expected || expectedlen != len))
  1297. {
  1298. ++unittest_failures;
  1299. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got U+%06lX (len %d)", (unsigned long)expected, expectedlen, (unsigned long)r, len);
  1300. }
  1301. }
  1302. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1303. void utf8_test()
  1304. {
  1305. _utf8_test("", 0, 1);
  1306. _utf8_test("\1", 1, 1);
  1307. _utf8_test("\x7f", 0x7f, 1);
  1308. #if WCHAR_MAX >= 0x80
  1309. _utf8_test("\xc2\x80", 0x80, 2);
  1310. #if WCHAR_MAX >= 0xff
  1311. _utf8_test("\xc3\xbf", 0xff, 2);
  1312. #if WCHAR_MAX >= 0x7ff
  1313. _utf8_test("\xdf\xbf", 0x7ff, 2);
  1314. #if WCHAR_MAX >= 0x800
  1315. _utf8_test("\xe0\xa0\x80", 0x800, 3);
  1316. #if WCHAR_MAX >= 0xffff
  1317. _utf8_test("\xef\xbf\xbf", 0xffff, 3);
  1318. #if WCHAR_MAX >= 0x10000
  1319. _utf8_test("\xf0\x90\x80\x80", 0x10000, 4);
  1320. #if WCHAR_MAX >= 0x10ffff
  1321. _utf8_test("\xf4\x8f\xbf\xbf", 0x10ffff, 4);
  1322. #endif
  1323. #endif
  1324. #endif
  1325. #endif
  1326. #endif
  1327. #endif
  1328. #endif
  1329. #ifdef STRICT_UTF8
  1330. _utf8_test("\x80", REPLACEMENT_CHAR, 1);
  1331. _utf8_test("\xbf", REPLACEMENT_CHAR, 1);
  1332. _utf8_test("\xfe", REPLACEMENT_CHAR, 1);
  1333. _utf8_test("\xff", REPLACEMENT_CHAR, 1);
  1334. #endif
  1335. }
  1336. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1337. {
  1338. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1339. char url_address[256], port[6];
  1340. int url_len, port_len = 0;
  1341. url_begin = strstr(url, "//");
  1342. if (!url_begin)
  1343. url_begin = url;
  1344. else
  1345. url_begin += 2;
  1346. /* Look for numeric ipv6 entries */
  1347. ipv6_begin = strstr(url_begin, "[");
  1348. ipv6_end = strstr(url_begin, "]");
  1349. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1350. url_end = strstr(ipv6_end, ":");
  1351. else
  1352. url_end = strstr(url_begin, ":");
  1353. if (url_end) {
  1354. url_len = url_end - url_begin;
  1355. port_len = strlen(url_begin) - url_len - 1;
  1356. if (port_len < 1)
  1357. return false;
  1358. port_start = url_end + 1;
  1359. } else
  1360. url_len = strlen(url_begin);
  1361. if (url_len < 1)
  1362. return false;
  1363. if (url_len >= sizeof(url_address))
  1364. {
  1365. applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'",
  1366. __func__, url_len, url_begin);
  1367. url_len = sizeof(url_address) - 1;
  1368. }
  1369. sprintf(url_address, "%.*s", url_len, url_begin);
  1370. if (port_len) {
  1371. char *slash;
  1372. snprintf(port, 6, "%.*s", port_len, port_start);
  1373. slash = strchr(port, '/');
  1374. if (slash)
  1375. *slash = '\0';
  1376. } else
  1377. strcpy(port, "80");
  1378. free(*sockaddr_port);
  1379. *sockaddr_port = strdup(port);
  1380. free(*sockaddr_url);
  1381. *sockaddr_url = strdup(url_address);
  1382. return true;
  1383. }
  1384. enum send_ret {
  1385. SEND_OK,
  1386. SEND_SELECTFAIL,
  1387. SEND_SENDFAIL,
  1388. SEND_INACTIVE
  1389. };
  1390. /* Send a single command across a socket, appending \n to it. This should all
  1391. * be done under stratum lock except when first establishing the socket */
  1392. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1393. {
  1394. SOCKETTYPE sock = pool->sock;
  1395. ssize_t ssent = 0;
  1396. strcat(s, "\n");
  1397. len++;
  1398. while (len > 0 ) {
  1399. struct timeval timeout = {1, 0};
  1400. size_t sent = 0;
  1401. CURLcode rc;
  1402. fd_set wd;
  1403. retry:
  1404. FD_ZERO(&wd);
  1405. FD_SET(sock, &wd);
  1406. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1407. if (interrupted())
  1408. goto retry;
  1409. return SEND_SELECTFAIL;
  1410. }
  1411. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  1412. if (rc != CURLE_OK)
  1413. {
  1414. if (rc != CURLE_AGAIN)
  1415. return SEND_SENDFAIL;
  1416. sent = 0;
  1417. }
  1418. ssent += sent;
  1419. len -= sent;
  1420. }
  1421. pool->cgminer_pool_stats.times_sent++;
  1422. pool->cgminer_pool_stats.bytes_sent += ssent;
  1423. total_bytes_sent += ssent;
  1424. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1425. return SEND_OK;
  1426. }
  1427. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1428. {
  1429. enum send_ret ret = SEND_INACTIVE;
  1430. if (opt_protocol)
  1431. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1432. mutex_lock(&pool->stratum_lock);
  1433. if (pool->stratum_active || force)
  1434. ret = __stratum_send(pool, s, len);
  1435. mutex_unlock(&pool->stratum_lock);
  1436. /* This is to avoid doing applog under stratum_lock */
  1437. switch (ret) {
  1438. default:
  1439. case SEND_OK:
  1440. break;
  1441. case SEND_SELECTFAIL:
  1442. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1443. suspend_stratum(pool);
  1444. break;
  1445. case SEND_SENDFAIL:
  1446. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1447. suspend_stratum(pool);
  1448. break;
  1449. case SEND_INACTIVE:
  1450. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1451. break;
  1452. }
  1453. return (ret == SEND_OK);
  1454. }
  1455. static bool socket_full(struct pool *pool, int wait)
  1456. {
  1457. SOCKETTYPE sock = pool->sock;
  1458. struct timeval timeout;
  1459. fd_set rd;
  1460. if (sock == INVSOCK)
  1461. return true;
  1462. if (unlikely(wait < 0))
  1463. wait = 0;
  1464. FD_ZERO(&rd);
  1465. FD_SET(sock, &rd);
  1466. timeout.tv_usec = 0;
  1467. timeout.tv_sec = wait;
  1468. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1469. return true;
  1470. return false;
  1471. }
  1472. /* Check to see if Santa's been good to you */
  1473. bool sock_full(struct pool *pool)
  1474. {
  1475. if (strlen(pool->sockbuf))
  1476. return true;
  1477. return (socket_full(pool, 0));
  1478. }
  1479. static void clear_sockbuf(struct pool *pool)
  1480. {
  1481. strcpy(pool->sockbuf, "");
  1482. }
  1483. static void clear_sock(struct pool *pool)
  1484. {
  1485. size_t n = 0;
  1486. mutex_lock(&pool->stratum_lock);
  1487. do {
  1488. n = 0;
  1489. if (pool->sock)
  1490. curl_easy_recv(pool->stratum_curl, pool->sockbuf, RECVSIZE, &n);
  1491. } while (n > 0);
  1492. mutex_unlock(&pool->stratum_lock);
  1493. clear_sockbuf(pool);
  1494. }
  1495. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1496. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1497. * and zeroing the new memory */
  1498. static void recalloc_sock(struct pool *pool, size_t len)
  1499. {
  1500. size_t old, new;
  1501. old = strlen(pool->sockbuf);
  1502. new = old + len + 1;
  1503. if (new < pool->sockbuf_size)
  1504. return;
  1505. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1506. // Avoid potentially recursive locking
  1507. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1508. pool->sockbuf = realloc(pool->sockbuf, new);
  1509. if (!pool->sockbuf)
  1510. quithere(1, "Failed to realloc pool sockbuf");
  1511. memset(pool->sockbuf + old, 0, new - old);
  1512. pool->sockbuf_size = new;
  1513. }
  1514. /* Peeks at a socket to find the first end of line and then reads just that
  1515. * from the socket and returns that as a malloced char */
  1516. char *recv_line(struct pool *pool)
  1517. {
  1518. char *tok, *sret = NULL;
  1519. ssize_t len, buflen;
  1520. int waited = 0;
  1521. if (!strstr(pool->sockbuf, "\n")) {
  1522. struct timeval rstart, now;
  1523. cgtime(&rstart);
  1524. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1525. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1526. goto out;
  1527. }
  1528. do {
  1529. char s[RBUFSIZE];
  1530. size_t slen;
  1531. size_t n = 0;
  1532. CURLcode rc;
  1533. memset(s, 0, RBUFSIZE);
  1534. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  1535. if (rc == CURLE_OK && !n)
  1536. {
  1537. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1538. suspend_stratum(pool);
  1539. break;
  1540. }
  1541. cgtime(&now);
  1542. waited = tdiff(&now, &rstart);
  1543. if (rc != CURLE_OK)
  1544. {
  1545. if (rc != CURLE_AGAIN || !socket_full(pool, DEFAULT_SOCKWAIT - waited))
  1546. {
  1547. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1548. suspend_stratum(pool);
  1549. break;
  1550. }
  1551. } else {
  1552. slen = strlen(s);
  1553. recalloc_sock(pool, slen);
  1554. strcat(pool->sockbuf, s);
  1555. }
  1556. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1557. }
  1558. buflen = strlen(pool->sockbuf);
  1559. tok = strtok(pool->sockbuf, "\n");
  1560. if (!tok) {
  1561. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1562. goto out;
  1563. }
  1564. sret = strdup(tok);
  1565. len = strlen(sret);
  1566. /* Copy what's left in the buffer after the \n, including the
  1567. * terminating \0 */
  1568. if (buflen > len + 1)
  1569. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1570. else
  1571. strcpy(pool->sockbuf, "");
  1572. pool->cgminer_pool_stats.times_received++;
  1573. pool->cgminer_pool_stats.bytes_received += len;
  1574. total_bytes_rcvd += len;
  1575. pool->cgminer_pool_stats.net_bytes_received += len;
  1576. out:
  1577. if (!sret)
  1578. clear_sock(pool);
  1579. else if (opt_protocol)
  1580. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1581. return sret;
  1582. }
  1583. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1584. * flag, but this is compatible with 2.0. */
  1585. char *json_dumps_ANY(json_t *json, size_t flags)
  1586. {
  1587. switch (json_typeof(json))
  1588. {
  1589. case JSON_ARRAY:
  1590. case JSON_OBJECT:
  1591. return json_dumps(json, flags);
  1592. default:
  1593. break;
  1594. }
  1595. char *rv;
  1596. #ifdef JSON_ENCODE_ANY
  1597. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1598. if (rv)
  1599. return rv;
  1600. #endif
  1601. json_t *tmp = json_array();
  1602. char *s;
  1603. int i;
  1604. size_t len;
  1605. if (!tmp)
  1606. quithere(1, "Failed to allocate json array");
  1607. if (json_array_append(tmp, json))
  1608. quithere(1, "Failed to append temporary array");
  1609. s = json_dumps(tmp, flags);
  1610. if (!s)
  1611. return NULL;
  1612. for (i = 0; s[i] != '['; ++i)
  1613. if (unlikely(!(s[i] && isCspace(s[i]))))
  1614. quithere(1, "Failed to find opening bracket in array dump");
  1615. len = strlen(&s[++i]) - 1;
  1616. if (unlikely(s[i+len] != ']'))
  1617. quithere(1, "Failed to find closing bracket in array dump");
  1618. rv = malloc(len + 1);
  1619. memcpy(rv, &s[i], len);
  1620. rv[len] = '\0';
  1621. free(s);
  1622. json_decref(tmp);
  1623. return rv;
  1624. }
  1625. /* Extracts a string value from a json array with error checking. To be used
  1626. * when the value of the string returned is only examined and not to be stored.
  1627. * See json_array_string below */
  1628. const char *__json_array_string(json_t *val, unsigned int entry)
  1629. {
  1630. json_t *arr_entry;
  1631. if (json_is_null(val))
  1632. return NULL;
  1633. if (!json_is_array(val))
  1634. return NULL;
  1635. if (entry > json_array_size(val))
  1636. return NULL;
  1637. arr_entry = json_array_get(val, entry);
  1638. if (!json_is_string(arr_entry))
  1639. return NULL;
  1640. return json_string_value(arr_entry);
  1641. }
  1642. /* Creates a freshly malloced dup of __json_array_string */
  1643. static char *json_array_string(json_t *val, unsigned int entry)
  1644. {
  1645. const char *buf = __json_array_string(val, entry);
  1646. if (buf)
  1647. return strdup(buf);
  1648. return NULL;
  1649. }
  1650. void *my_memrchr(const void * const datap, const int c, const size_t sz)
  1651. {
  1652. const uint8_t *data = datap;
  1653. const uint8_t *p = &data[sz];
  1654. while (p > data)
  1655. if (*--p == c)
  1656. return (void *)p;
  1657. return NULL;
  1658. }
  1659. bool isCalpha(const int c)
  1660. {
  1661. if (c >= 'A' && c <= 'Z')
  1662. return true;
  1663. if (c >= 'a' && c <= 'z')
  1664. return true;
  1665. return false;
  1666. }
  1667. static
  1668. 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)
  1669. {
  1670. if (!(path && path[0]))
  1671. return false;
  1672. char filepath[PATH_MAX];
  1673. snprintf(filepath, sizeof(filepath), "%s/%s/%s", path, appname, filename);
  1674. if (!access(filepath, R_OK))
  1675. return cb(filepath, userp);
  1676. return false;
  1677. }
  1678. #define _APPDATA_FILE_CALL(appname, path) do{ \
  1679. if (_appdata_file_call(appname, filename, cb, userp, path)) \
  1680. return true; \
  1681. }while(0)
  1682. bool appdata_file_call(const char *appname, const char * const filename, const appdata_file_callback_t cb, void * const userp)
  1683. {
  1684. size_t appname_len = strlen(appname);
  1685. char appname_lcd[appname_len + 1];
  1686. appname_lcd[0] = '.';
  1687. char *appname_lc = &appname_lcd[1];
  1688. for (size_t i = 0; i <= appname_len; ++i)
  1689. appname_lc[i] = tolower(appname[i]);
  1690. appname_lc[appname_len] = '\0';
  1691. const char * const HOME = getenv("HOME");
  1692. _APPDATA_FILE_CALL(".", ".");
  1693. #ifdef WIN32
  1694. _APPDATA_FILE_CALL(appname, getenv("APPDATA"));
  1695. #elif defined(__APPLE__)
  1696. if (HOME && HOME[0])
  1697. {
  1698. char AppSupport[strlen(HOME) + 28 + 1];
  1699. snprintf(AppSupport, sizeof(AppSupport), "%s/Library/Application Support", HOME);
  1700. _APPDATA_FILE_CALL(appname, AppSupport);
  1701. }
  1702. #endif
  1703. _APPDATA_FILE_CALL(appname_lcd, HOME);
  1704. #ifdef WIN32
  1705. _APPDATA_FILE_CALL(appname, getenv("ALLUSERSAPPDATA"));
  1706. #elif defined(__APPLE__)
  1707. _APPDATA_FILE_CALL(appname, "/Library/Application Support");
  1708. #endif
  1709. #ifndef WIN32
  1710. _APPDATA_FILE_CALL(appname_lc, "/etc");
  1711. #endif
  1712. return false;
  1713. }
  1714. static
  1715. bool _appdata_file_find_first(const char * const filepath, void *userp)
  1716. {
  1717. char **rv = userp;
  1718. *rv = strdup(filepath);
  1719. return true;
  1720. }
  1721. char *appdata_file_find_first(const char * const appname, const char * const filename)
  1722. {
  1723. char *rv;
  1724. if (appdata_file_call(appname, filename, _appdata_file_find_first, &rv))
  1725. return rv;
  1726. return NULL;
  1727. }
  1728. const char *get_registered_domain(size_t * const out_domainlen, const char * const fqdn, const size_t fqdnlen)
  1729. {
  1730. const char *s;
  1731. int dots = 0;
  1732. for (s = &fqdn[fqdnlen-1]; s >= fqdn; --s)
  1733. {
  1734. if (s[0] == '.')
  1735. {
  1736. *out_domainlen = fqdnlen - (&s[1] - fqdn);
  1737. if (++dots >= 2 && *out_domainlen > 5)
  1738. return &s[1];
  1739. }
  1740. else
  1741. if (!(dots || isCalpha(s[0])))
  1742. {
  1743. *out_domainlen = fqdnlen;
  1744. return fqdn;
  1745. }
  1746. }
  1747. *out_domainlen = fqdnlen;
  1748. return fqdn;
  1749. }
  1750. const char *extract_domain(size_t * const out_domainlen, const char * const uri, const size_t urilen)
  1751. {
  1752. const char *p = uri, *b, *q, *s;
  1753. bool alldigit;
  1754. p = memchr(&p[1], '/', urilen - (&p[1] - uri));
  1755. if (p)
  1756. {
  1757. if (p[-1] == ':')
  1758. {
  1759. // part of the URI scheme, ignore it
  1760. while (p[0] == '/')
  1761. ++p;
  1762. p = memchr(p, '/', urilen - (p - uri));
  1763. }
  1764. }
  1765. if (!p)
  1766. {
  1767. p = memchr(uri, '?', urilen) ?:
  1768. memchr(uri, '#', urilen) ?:
  1769. &uri[urilen];
  1770. }
  1771. s = p;
  1772. q = my_memrchr(uri, ':', p - uri);
  1773. if (q)
  1774. {
  1775. alldigit = true;
  1776. for (q = b = &q[1]; q < p; ++q)
  1777. if (!isdigit(q[0]))
  1778. {
  1779. alldigit = false;
  1780. break;
  1781. }
  1782. if (alldigit && p != b)
  1783. p = &b[-1];
  1784. }
  1785. alldigit = true;
  1786. for (b = uri; b < p; ++b)
  1787. {
  1788. if (b[0] == ':')
  1789. break;
  1790. if (alldigit && !isdigit(b[0]))
  1791. alldigit = false;
  1792. }
  1793. if ((b < p && b[0] == ':') && (b == uri || !alldigit))
  1794. b = &b[1];
  1795. else
  1796. b = uri;
  1797. while (b <= p && b[0] == '/')
  1798. ++b;
  1799. if (p - b > 1 && b[0] == '[' && p[-1] == ']')
  1800. {
  1801. ++b;
  1802. --p;
  1803. }
  1804. else
  1805. if (memchr(b, ':', p - b))
  1806. p = s;
  1807. if (p > b && p[-1] == '.')
  1808. --p;
  1809. *out_domainlen = p - b;
  1810. return b;
  1811. }
  1812. bool match_domains(const char * const a, const size_t alen, const char * const b, const size_t blen)
  1813. {
  1814. size_t a_domainlen, b_domainlen;
  1815. const char *a_domain, *b_domain;
  1816. a_domain = extract_domain(&a_domainlen, a, alen);
  1817. a_domain = get_registered_domain(&a_domainlen, a_domain, a_domainlen);
  1818. b_domain = extract_domain(&b_domainlen, b, blen);
  1819. b_domain = get_registered_domain(&b_domainlen, b_domain, b_domainlen);
  1820. if (a_domainlen != b_domainlen)
  1821. return false;
  1822. return !strncasecmp(a_domain, b_domain, a_domainlen);
  1823. }
  1824. static
  1825. void _test_extract_domain(const char * const expect, const char * const uri)
  1826. {
  1827. size_t sz;
  1828. const char * const d = extract_domain(&sz, uri, strlen(uri));
  1829. if (sz != strlen(expect) || strncasecmp(d, expect, sz))
  1830. {
  1831. ++unittest_failures;
  1832. applog(LOG_WARNING, "extract_domain \"%s\" test failed; got \"%.*s\" instead of \"%s\"",
  1833. uri, (int)sz, d, expect);
  1834. }
  1835. }
  1836. static
  1837. void _test_get_regd_domain(const char * const expect, const char * const fqdn)
  1838. {
  1839. size_t sz;
  1840. const char * const d = get_registered_domain(&sz, fqdn, strlen(fqdn));
  1841. if (d == NULL || sz != strlen(expect) || strncasecmp(d, expect, sz))
  1842. {
  1843. ++unittest_failures;
  1844. applog(LOG_WARNING, "get_registered_domain \"%s\" test failed; got \"%.*s\" instead of \"%s\"",
  1845. fqdn, (int)sz, d, expect);
  1846. }
  1847. }
  1848. void test_domain_funcs()
  1849. {
  1850. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334");
  1851. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334/abc/abc/");
  1852. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st/abc/abc/");
  1853. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st");
  1854. _test_extract_domain("s.m.eligius.st", "http:s.m.eligius.st");
  1855. _test_extract_domain("s.m.eligius.st", "stratum+tcp:s.m.eligius.st");
  1856. _test_extract_domain("s.m.eligius.st", "stratum+tcp:s.m.eligius.st:3334");
  1857. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st:3334");
  1858. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st:3334///");
  1859. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st.:3334///");
  1860. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334");
  1861. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334///");
  1862. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334#foo");
  1863. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334?foo");
  1864. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st#foo");
  1865. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st?foo");
  1866. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st#foo");
  1867. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st?foo");
  1868. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334#foo");
  1869. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334?foo");
  1870. _test_extract_domain("foohost", "foohost:3334");
  1871. _test_extract_domain("foohost", "foohost:3334///");
  1872. _test_extract_domain("foohost", "foohost:3334/abc.com//");
  1873. _test_extract_domain("", "foohost:");
  1874. _test_extract_domain("3334", "foohost://3334/abc.com//");
  1875. _test_extract_domain("192.0.2.0", "foohost:192.0.2.0");
  1876. _test_extract_domain("192.0.2.0", "192.0.2.0:3334");
  1877. _test_extract_domain("192.0.2.0", "192.0.2.0:3334///");
  1878. _test_extract_domain("2001:db8::1", "2001:db8::1");
  1879. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]");
  1880. _test_extract_domain("2001:db8::1", "http:[2001:db8::1]");
  1881. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]:42");
  1882. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]:42/abc//def/ghi");
  1883. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]");
  1884. _test_extract_domain("2001:db8::cafe", "http:[2001:db8::cafe]");
  1885. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]:42");
  1886. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]:42/abc//def/ghi");
  1887. _test_get_regd_domain("eligius.st", "s.m.eligius.st");
  1888. _test_get_regd_domain("eligius.st", "eligius.st");
  1889. _test_get_regd_domain("foohost.co.uk", "myserver.foohost.co.uk");
  1890. _test_get_regd_domain("foohost", "foohost");
  1891. _test_get_regd_domain("192.0.2.0", "192.0.2.0");
  1892. _test_get_regd_domain("2001:db8::1", "2001:db8::1");
  1893. }
  1894. struct bfg_strtobool_keyword {
  1895. bool val;
  1896. const char *keyword;
  1897. };
  1898. bool bfg_strtobool(const char * const s, char ** const endptr, __maybe_unused const int opts)
  1899. {
  1900. struct bfg_strtobool_keyword keywords[] = {
  1901. {false, "false"},
  1902. {false, "never"},
  1903. {false, "none"},
  1904. {false, "off"},
  1905. {false, "no"},
  1906. {false, "0"},
  1907. {true , "always"},
  1908. {true , "true"},
  1909. {true , "yes"},
  1910. {true , "on"},
  1911. };
  1912. const int total_keywords = sizeof(keywords) / sizeof(*keywords);
  1913. for (int i = 0; i < total_keywords; ++i)
  1914. {
  1915. const size_t kwlen = strlen(keywords[i].keyword);
  1916. if (!strncasecmp(keywords[i].keyword, s, kwlen))
  1917. {
  1918. if (endptr)
  1919. *endptr = (char*)&s[kwlen];
  1920. return keywords[i].val;
  1921. }
  1922. }
  1923. char *lend;
  1924. strtol(s, &lend, 0);
  1925. if (lend > s)
  1926. {
  1927. if (endptr)
  1928. *endptr = lend;
  1929. // Any number other than "0" is intentionally considered true, including 0x0
  1930. return true;
  1931. }
  1932. *endptr = (char*)s;
  1933. return false;
  1934. }
  1935. #define URI_FIND_PARAM_FOUND ((const char *)uri_find_param)
  1936. const char *uri_find_param(const char * const uri, const char * const param, bool * const invert_p)
  1937. {
  1938. const char *start = strchr(uri, '#');
  1939. if (invert_p)
  1940. *invert_p = false;
  1941. if (!start)
  1942. return NULL;
  1943. const char *p = start;
  1944. ++start;
  1945. nextmatch:
  1946. p = strstr(&p[1], param);
  1947. if (!p)
  1948. return NULL;
  1949. const char *q = &p[strlen(param)];
  1950. if (isCalpha(q[0]))
  1951. goto nextmatch;
  1952. if (invert_p && p - start >= 2 && (!strncasecmp(&p[-2], "no", 2)) && !isCalpha(p[-3]))
  1953. *invert_p = true;
  1954. else
  1955. if (isCalpha(p[-1]))
  1956. goto nextmatch;
  1957. if (q[0] == '=')
  1958. return &q[1];
  1959. return URI_FIND_PARAM_FOUND;
  1960. }
  1961. enum bfg_tristate uri_get_param_bool2(const char * const uri, const char * const param)
  1962. {
  1963. bool invert, foundval = true;
  1964. const char *q = uri_find_param(uri, param, &invert);
  1965. if (!q)
  1966. return BTS_UNKNOWN;
  1967. else
  1968. if (q != URI_FIND_PARAM_FOUND)
  1969. {
  1970. char *end;
  1971. bool v = bfg_strtobool(q, &end, 0);
  1972. if (end > q && !isCalpha(end[0]))
  1973. foundval = v;
  1974. }
  1975. if (invert)
  1976. foundval = !foundval;
  1977. return foundval;
  1978. }
  1979. bool uri_get_param_bool(const char * const uri, const char * const param, const bool defval)
  1980. {
  1981. const enum bfg_tristate rv = uri_get_param_bool2(uri, param);
  1982. if (rv == BTS_UNKNOWN)
  1983. return defval;
  1984. return rv;
  1985. }
  1986. static
  1987. void _test_uri_find_param(const char * const uri, const char * const param, const int expect_offset, const int expect_invert)
  1988. {
  1989. bool invert;
  1990. const char *actual = uri_find_param(uri, param, (expect_invert >= 0) ? &invert : NULL);
  1991. int actual_offset;
  1992. if (actual == URI_FIND_PARAM_FOUND)
  1993. actual_offset = -1;
  1994. else
  1995. if (!actual)
  1996. actual_offset = -2;
  1997. else
  1998. actual_offset = actual - uri;
  1999. int actual_invert = (expect_invert >= 0) ? (invert ? 1 : 0) : -1;
  2000. if (actual_offset != expect_offset || expect_invert != actual_invert)
  2001. {
  2002. ++unittest_failures;
  2003. applog(LOG_WARNING, "%s(\"%s\", \"%s\", %s) test failed (offset: expect=%d actual=%d; invert: expect=%d actual=%d)",
  2004. "uri_find_param", uri, param, (expect_invert >= 0) ? "(invert)" : "NULL",
  2005. expect_offset, actual_offset,
  2006. expect_invert, actual_invert);
  2007. }
  2008. }
  2009. static
  2010. void _test_uri_get_param(const char * const uri, const char * const param, const bool defval, const bool expect)
  2011. {
  2012. const bool actual = uri_get_param_bool(uri, param, defval);
  2013. if (actual != expect)
  2014. {
  2015. ++unittest_failures;
  2016. applog(LOG_WARNING, "%s(\"%s\", \"%s\", %s) test failed",
  2017. "uri_get_param_bool", uri, param, defval ? "true" : "false");
  2018. }
  2019. }
  2020. void test_uri_get_param()
  2021. {
  2022. _test_uri_find_param("stratum+tcp://footest/#redirect", "redirect", -1, -1);
  2023. _test_uri_find_param("stratum+tcp://footest/#redirectme", "redirect", -2, -1);
  2024. _test_uri_find_param("stratum+tcp://footest/#noredirect", "redirect", -2, -1);
  2025. _test_uri_find_param("stratum+tcp://footest/#noredirect", "redirect", -1, 1);
  2026. _test_uri_find_param("stratum+tcp://footest/#redirect", "redirect", -1, 0);
  2027. _test_uri_find_param("stratum+tcp://footest/#redirect=", "redirect", 32, -1);
  2028. _test_uri_find_param("stratum+tcp://footest/#noredirect=", "redirect", 34, 1);
  2029. _test_uri_get_param("stratum+tcp://footest/#redirect", "redirect", false, true);
  2030. _test_uri_get_param("stratum+tcp://footest/#redirectme", "redirect", false, false);
  2031. _test_uri_get_param("stratum+tcp://footest/#noredirect", "redirect", false, false);
  2032. _test_uri_get_param("stratum+tcp://footest/#redirect=0", "redirect", false, false);
  2033. _test_uri_get_param("stratum+tcp://footest/#redirect=1", "redirect", false, true);
  2034. _test_uri_get_param("stratum+tcp://footest/#redirect", "redirect", true, true);
  2035. _test_uri_get_param("stratum+tcp://footest/#redirectme", "redirect", true, true);
  2036. _test_uri_get_param("stratum+tcp://footest/#noredirect", "redirect", true, false);
  2037. _test_uri_get_param("stratum+tcp://footest/#redirect=0", "redirect", true, false);
  2038. _test_uri_get_param("stratum+tcp://footest/#redirect=1", "redirect", true, true);
  2039. _test_uri_get_param("stratum+tcp://footest/#redirect=0,foo=1", "redirect", true, false);
  2040. _test_uri_get_param("stratum+tcp://footest/#redirect=1,foo=0", "redirect", false, true);
  2041. _test_uri_get_param("stratum+tcp://footest/#foo=1,noredirect=0,foo=1", "redirect", false, true);
  2042. _test_uri_get_param("stratum+tcp://footest/#bar=0,noredirect=1,foo=0", "redirect", true, false);
  2043. _test_uri_get_param("stratum+tcp://footest/#redirect=false", "redirect", true, false);
  2044. _test_uri_get_param("stratum+tcp://footest/#redirect=no", "redirect", true, false);
  2045. _test_uri_get_param("stratum+tcp://footest/#redirect=yes", "redirect", false, true);
  2046. }
  2047. void stratum_probe_transparency(struct pool *pool)
  2048. {
  2049. // Request transaction data to discourage pools from doing anything shady
  2050. char s[1024];
  2051. int sLen;
  2052. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  2053. pool->swork.job_id,
  2054. pool->swork.job_id);
  2055. stratum_send(pool, s, sLen);
  2056. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  2057. timer_set_delay_from_now(&pool->swork.tv_transparency, 21093750L);
  2058. pool->swork.transparency_probed = true;
  2059. }
  2060. size_t script_to_address(char *out, size_t outsz, const uint8_t *script, size_t scriptsz, bool testnet)
  2061. {
  2062. char addr[35];
  2063. size_t size = sizeof(addr);
  2064. bool bok = false;
  2065. if (scriptsz == 25 && script[0] == 0x76 && script[1] == 0xa9 && script[2] == 0x14 && script[23] == 0x88 && script[24] == 0xac)
  2066. bok = b58check_enc(addr, &size, testnet ? 0x6f : 0x00, &script[3], 20);
  2067. else if (scriptsz == 23 && script[0] == 0xa9 && script[1] == 0x14 && script[22] == 0x87)
  2068. bok = b58check_enc(addr, &size, testnet ? 0xc4 : 0x05, &script[2], 20);
  2069. if (!bok)
  2070. return 0;
  2071. if (outsz >= size)
  2072. strcpy(out, addr);
  2073. return size;
  2074. }
  2075. size_t varint_decode(const uint8_t *p, size_t size, uint64_t *n)
  2076. {
  2077. if (size > 8 && p[0] == 0xff)
  2078. {
  2079. *n = upk_u64le(p, 1);
  2080. return 9;
  2081. }
  2082. if (size > 4 && p[0] == 0xfe)
  2083. {
  2084. *n = upk_u32le(p, 1);
  2085. return 5;
  2086. }
  2087. if (size > 2 && p[0] == 0xfd)
  2088. {
  2089. *n = upk_u16le(p, 1);
  2090. return 3;
  2091. }
  2092. if (size > 0 && p[0] <= 0xfc)
  2093. {
  2094. *n = p[0];
  2095. return 1;
  2096. }
  2097. return 0;
  2098. }
  2099. /* Caller ensure cb_param is an valid pointer */
  2100. bool check_coinbase(const uint8_t *coinbase, size_t cbsize, const struct coinbase_param *cb_param)
  2101. {
  2102. int i;
  2103. size_t pos;
  2104. uint64_t len, total, target, amount, curr_pk_script_len;
  2105. bool found_target = false;
  2106. if (cbsize < 62)
  2107. /* Smallest possible length */
  2108. applogr(false, LOG_ERR, "Coinbase check: invalid length -- %lu", (unsigned long)cbsize);
  2109. pos = 4; /* Skip the version */
  2110. if (coinbase[pos] != 1)
  2111. applogr(false, LOG_ERR, "Coinbase check: multiple inputs in coinbase: 0x%02x", coinbase[pos]);
  2112. pos += 1 /* varint length */ + 32 /* prevhash */ + 4 /* 0xffffffff */;
  2113. if (coinbase[pos] < 2 || coinbase[pos] > 100)
  2114. applogr(false, LOG_ERR, "Coinbase check: invalid input script sig length: 0x%02x", coinbase[pos]);
  2115. pos += 1 /* varint length */ + coinbase[pos] + 4 /* 0xffffffff */;
  2116. if (cbsize <= pos)
  2117. incomplete_cb:
  2118. applogr(false, LOG_ERR, "Coinbase check: incomplete coinbase for payout check");
  2119. total = target = 0;
  2120. i = varint_decode(coinbase + pos, cbsize - pos, &len);
  2121. if (!i)
  2122. goto incomplete_cb;
  2123. pos += i;
  2124. while (len-- > 0)
  2125. {
  2126. if (cbsize <= pos + 8)
  2127. goto incomplete_cb;
  2128. amount = upk_u64le(coinbase, pos);
  2129. pos += 8; /* amount length */
  2130. total += amount;
  2131. i = varint_decode(coinbase + pos, cbsize - pos, &curr_pk_script_len);
  2132. if (!i || cbsize <= pos + i + curr_pk_script_len)
  2133. goto incomplete_cb;
  2134. pos += i;
  2135. struct bytes_hashtbl *ah = NULL;
  2136. HASH_FIND(hh, cb_param->scripts, &coinbase[pos], curr_pk_script_len, ah);
  2137. if (ah)
  2138. {
  2139. found_target = true;
  2140. target += amount;
  2141. }
  2142. if (opt_debug)
  2143. {
  2144. char s[(curr_pk_script_len * 2) + 3];
  2145. i = script_to_address(s, sizeof(s), &coinbase[pos], curr_pk_script_len, cb_param->testnet);
  2146. if (!(i && i <= sizeof(s)))
  2147. {
  2148. s[0] = '[';
  2149. bin2hex(&s[1], &coinbase[pos], curr_pk_script_len);
  2150. strcpy(&s[(curr_pk_script_len * 2) + 1], "]");
  2151. }
  2152. applog(LOG_DEBUG, "Coinbase output: %10"PRIu64" -- %s%s", amount, s, ah ? "*" : "");
  2153. }
  2154. pos += curr_pk_script_len;
  2155. }
  2156. if (total < cb_param->total)
  2157. applogr(false, LOG_ERR, "Coinbase check: lopsided total output amount = %"PRIu64", expecting >=%"PRIu64, total, cb_param->total);
  2158. if (cb_param->scripts)
  2159. {
  2160. if (cb_param->perc && !(total && (float)((double)target / total) >= cb_param->perc))
  2161. 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);
  2162. else
  2163. if (!found_target)
  2164. applogr(false, LOG_ERR, "Coinbase check: not found any target addr");
  2165. }
  2166. if (cbsize < pos + 4)
  2167. applogr(false, LOG_ERR, "Coinbase check: No room for locktime");
  2168. pos += 4;
  2169. if (opt_debug)
  2170. 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);
  2171. return true;
  2172. }
  2173. static bool parse_notify(struct pool *pool, json_t *val)
  2174. {
  2175. const char *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  2176. char *job_id;
  2177. bool clean, ret = false;
  2178. int merkles, i;
  2179. size_t cb1_len, cb2_len;
  2180. json_t *arr;
  2181. arr = json_array_get(val, 4);
  2182. if (!arr || !json_is_array(arr))
  2183. goto out;
  2184. merkles = json_array_size(arr);
  2185. for (i = 0; i < merkles; i++)
  2186. if (!json_is_string(json_array_get(arr, i)))
  2187. goto out;
  2188. prev_hash = __json_array_string(val, 1);
  2189. coinbase1 = __json_array_string(val, 2);
  2190. coinbase2 = __json_array_string(val, 3);
  2191. bbversion = __json_array_string(val, 5);
  2192. nbit = __json_array_string(val, 6);
  2193. ntime = __json_array_string(val, 7);
  2194. clean = json_is_true(json_array_get(val, 8));
  2195. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  2196. goto out;
  2197. job_id = json_array_string(val, 0);
  2198. if (!job_id)
  2199. goto out;
  2200. cg_wlock(&pool->data_lock);
  2201. cgtime(&pool->swork.tv_received);
  2202. free(pool->swork.job_id);
  2203. pool->swork.job_id = job_id;
  2204. if (pool->swork.tr)
  2205. {
  2206. tmpl_decref(pool->swork.tr);
  2207. pool->swork.tr = NULL;
  2208. }
  2209. pool->submit_old = !clean;
  2210. pool->swork.clean = true;
  2211. if (pool->next_nonce1)
  2212. {
  2213. free(pool->swork.nonce1);
  2214. pool->n1_len = strlen(pool->next_nonce1) / 2;
  2215. pool->swork.nonce1 = pool->next_nonce1;
  2216. pool->next_nonce1 = NULL;
  2217. }
  2218. int n2size = pool->swork.n2size = pool->next_n2size;
  2219. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  2220. #ifdef WORDS_BIGENDIAN
  2221. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  2222. #endif
  2223. hex2bin(&pool->swork.header1[0], bbversion, 4);
  2224. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  2225. hex2bin((void*)&pool->swork.ntime, ntime, 4);
  2226. pool->swork.ntime = be32toh(pool->swork.ntime);
  2227. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  2228. /* Nominally allow a driver to ntime roll 60 seconds */
  2229. set_simple_ntime_roll_limit(&pool->swork.ntime_roll_limits, pool->swork.ntime, 60, &pool->swork.tv_received);
  2230. cb1_len = strlen(coinbase1) / 2;
  2231. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  2232. cb2_len = strlen(coinbase2) / 2;
  2233. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->swork.n2size + cb2_len);
  2234. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  2235. hex2bin(coinbase, coinbase1, cb1_len);
  2236. hex2bin(&coinbase[cb1_len], pool->swork.nonce1, pool->n1_len);
  2237. // NOTE: gap for nonce2, filled at work generation time
  2238. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->swork.n2size], coinbase2, cb2_len);
  2239. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  2240. for (i = 0; i < merkles; i++)
  2241. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  2242. pool->swork.merkles = merkles;
  2243. pool->nonce2 = 0;
  2244. memcpy(pool->swork.target, pool->next_target, 0x20);
  2245. pool_check_coinbase(pool, coinbase, bytes_len(&pool->swork.coinbase));
  2246. cg_wunlock(&pool->data_lock);
  2247. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  2248. pool->pool_no, job_id);
  2249. if (opt_debug && opt_protocol)
  2250. {
  2251. applog(LOG_DEBUG, "job_id: %s", job_id);
  2252. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  2253. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  2254. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  2255. for (i = 0; i < merkles; i++)
  2256. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  2257. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  2258. applog(LOG_DEBUG, "nbit: %s", nbit);
  2259. applog(LOG_DEBUG, "ntime: %s", ntime);
  2260. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  2261. }
  2262. /* A notify message is the closest stratum gets to a getwork */
  2263. pool->getwork_requested++;
  2264. total_getworks++;
  2265. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  2266. if (pool->probed)
  2267. stratum_probe_transparency(pool);
  2268. ret = true;
  2269. out:
  2270. return ret;
  2271. }
  2272. static bool parse_diff(struct pool *pool, json_t *val)
  2273. {
  2274. double diff;
  2275. diff = json_number_value(json_array_get(val, 0));
  2276. if (diff == 0)
  2277. return false;
  2278. if ((int64_t)diff != diff)
  2279. {
  2280. // Assume fractional values are proper bdiff per specification
  2281. // Allow integers to be interpreted as pdiff, since the difference is trivial and some pools see it this way
  2282. diff = bdiff_to_pdiff(diff);
  2283. }
  2284. if ((!opt_scrypt) && diff < 1 && diff > 0.999)
  2285. diff = 1;
  2286. #ifdef USE_SCRYPT
  2287. // Broken Scrypt pools multiply difficulty by 0x10000
  2288. const double broken_scrypt_diff_multiplier = 0x10000;
  2289. /* 7/12/2014: P2Pool code was fixed: https://github.com/forrestv/p2pool/pull/210
  2290. 7/15/2014: Popular pools unfixed: wemineltc, dogehouse, p2pool.org
  2291. Cannot find a broken Scrypt pool that will dispense diff lower than 16 */
  2292. // Ideally pools will fix their implementation and we can remove this
  2293. // This should suffice until miners are hashing Scrypt at ~1-7 Gh/s (based on a share rate target of 10-60s)
  2294. const double minimum_broken_scrypt_diff = 16;
  2295. // Diff 16 at 1.15 Gh/s = 1 share / 60s
  2296. // Diff 16 at 7.00 Gh/s = 1 share / 10s
  2297. if (opt_scrypt && (diff >= minimum_broken_scrypt_diff))
  2298. diff /= broken_scrypt_diff_multiplier;
  2299. #endif
  2300. cg_wlock(&pool->data_lock);
  2301. set_target_to_pdiff(pool->next_target, diff);
  2302. cg_wunlock(&pool->data_lock);
  2303. applog(LOG_DEBUG, "Pool %d stratum difficulty set to %g", pool->pool_no, diff);
  2304. return true;
  2305. }
  2306. static
  2307. bool stratum_set_extranonce(struct pool * const pool, json_t * const val, json_t * const params)
  2308. {
  2309. char *nonce1 = NULL;
  2310. int n2size = 0;
  2311. json_t *j;
  2312. if (!json_is_array(params))
  2313. goto err;
  2314. switch (json_array_size(params))
  2315. {
  2316. default: // >=2
  2317. // n2size
  2318. j = json_array_get(params, 1);
  2319. if (json_is_number(j))
  2320. {
  2321. n2size = json_integer_value(j);
  2322. if (n2size < 1)
  2323. goto err;
  2324. }
  2325. else
  2326. if (!json_is_null(j))
  2327. goto err;
  2328. // fallthru
  2329. case 1:
  2330. // nonce1
  2331. j = json_array_get(params, 0);
  2332. if (json_is_string(j))
  2333. nonce1 = strdup(json_string_value(j));
  2334. else
  2335. if (!json_is_null(j))
  2336. goto err;
  2337. break;
  2338. case 0:
  2339. applog(LOG_WARNING, "Pool %u: No-op mining.set_extranonce?", pool->pool_no);
  2340. return true;
  2341. }
  2342. cg_wlock(&pool->data_lock);
  2343. if (nonce1)
  2344. {
  2345. free(pool->next_nonce1);
  2346. pool->next_nonce1 = nonce1;
  2347. }
  2348. if (n2size)
  2349. pool->next_n2size = n2size;
  2350. cg_wunlock(&pool->data_lock);
  2351. return true;
  2352. err:
  2353. applog(LOG_ERR, "Pool %u: Invalid mining.set_extranonce", pool->pool_no);
  2354. json_t *id = json_object_get(val, "id");
  2355. if (id && !json_is_null(id))
  2356. {
  2357. char s[RBUFSIZE], *idstr;
  2358. idstr = json_dumps_ANY(id, 0);
  2359. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [20, \"Invalid params\"]}", idstr);
  2360. free(idstr);
  2361. stratum_send(pool, s, strlen(s));
  2362. }
  2363. return true;
  2364. }
  2365. static bool parse_reconnect(struct pool *pool, json_t *val)
  2366. {
  2367. if (opt_disable_client_reconnect)
  2368. return false;
  2369. const char *url;
  2370. char address[256];
  2371. json_t *port_json;
  2372. url = __json_array_string(val, 0);
  2373. if (!url)
  2374. url = pool->sockaddr_url;
  2375. else
  2376. if (!pool_may_redirect_to(pool, url))
  2377. return false;
  2378. port_json = json_array_get(val, 1);
  2379. if (json_is_number(port_json))
  2380. {
  2381. const unsigned port = json_number_value(port_json);
  2382. snprintf(address, sizeof(address), "%s:%u", url, port);
  2383. }
  2384. else
  2385. {
  2386. const char *port;
  2387. if (json_is_string(port_json))
  2388. port = json_string_value(port_json);
  2389. else
  2390. port = pool->stratum_port;
  2391. snprintf(address, sizeof(address), "%s:%s", url, port);
  2392. }
  2393. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  2394. return false;
  2395. pool->stratum_url = pool->sockaddr_url;
  2396. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  2397. if (!restart_stratum(pool))
  2398. return false;
  2399. return true;
  2400. }
  2401. static bool send_version(struct pool *pool, json_t *val)
  2402. {
  2403. char s[RBUFSIZE], *idstr;
  2404. json_t *id = json_object_get(val, "id");
  2405. if (!(id && !json_is_null(id)))
  2406. return false;
  2407. idstr = json_dumps_ANY(id, 0);
  2408. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  2409. free(idstr);
  2410. if (!stratum_send(pool, s, strlen(s)))
  2411. return false;
  2412. return true;
  2413. }
  2414. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  2415. {
  2416. char *msg;
  2417. char s[RBUFSIZE], *idstr;
  2418. json_t *id = json_object_get(val, "id");
  2419. msg = json_array_string(params, 0);
  2420. if (likely(msg))
  2421. {
  2422. free(pool->admin_msg);
  2423. pool->admin_msg = msg;
  2424. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  2425. }
  2426. if (!(id && !json_is_null(id)))
  2427. return true;
  2428. idstr = json_dumps_ANY(id, 0);
  2429. if (likely(msg))
  2430. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  2431. else
  2432. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  2433. free(idstr);
  2434. if (!stratum_send(pool, s, strlen(s)))
  2435. return false;
  2436. return true;
  2437. }
  2438. bool parse_method(struct pool *pool, char *s)
  2439. {
  2440. json_t *val = NULL, *method, *err_val, *params;
  2441. json_error_t err;
  2442. bool ret = false;
  2443. const char *buf;
  2444. if (!s)
  2445. goto out;
  2446. val = JSON_LOADS(s, &err);
  2447. if (!val) {
  2448. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2449. goto out;
  2450. }
  2451. method = json_object_get(val, "method");
  2452. if (!method)
  2453. goto out;
  2454. err_val = json_object_get(val, "error");
  2455. params = json_object_get(val, "params");
  2456. if (err_val && !json_is_null(err_val)) {
  2457. char *ss;
  2458. if (err_val)
  2459. ss = json_dumps(err_val, JSON_INDENT(3));
  2460. else
  2461. ss = strdup("(unknown reason)");
  2462. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  2463. free(ss);
  2464. goto out;
  2465. }
  2466. buf = json_string_value(method);
  2467. if (!buf)
  2468. goto out;
  2469. if (!strncasecmp(buf, "mining.notify", 13)) {
  2470. if (parse_notify(pool, params))
  2471. pool->stratum_notify = ret = true;
  2472. else
  2473. pool->stratum_notify = ret = false;
  2474. goto out;
  2475. }
  2476. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  2477. ret = true;
  2478. goto out;
  2479. }
  2480. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  2481. ret = true;
  2482. goto out;
  2483. }
  2484. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  2485. ret = true;
  2486. goto out;
  2487. }
  2488. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  2489. ret = true;
  2490. goto out;
  2491. }
  2492. if (!strncasecmp(buf, "mining.set_extranonce", 21) && stratum_set_extranonce(pool, val, params)) {
  2493. ret = true;
  2494. goto out;
  2495. }
  2496. out:
  2497. if (val)
  2498. json_decref(val);
  2499. return ret;
  2500. }
  2501. extern bool parse_stratum_response(struct pool *, char *s);
  2502. bool auth_stratum(struct pool *pool)
  2503. {
  2504. json_t *val = NULL, *res_val, *err_val;
  2505. char s[RBUFSIZE], *sret = NULL;
  2506. json_error_t err;
  2507. bool ret = false;
  2508. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  2509. pool->rpc_user, pool->rpc_pass);
  2510. if (!stratum_send(pool, s, strlen(s)))
  2511. goto out;
  2512. /* Parse all data in the queue and anything left should be auth */
  2513. while (42) {
  2514. sret = recv_line(pool);
  2515. if (!sret)
  2516. goto out;
  2517. if (parse_method(pool, sret))
  2518. free(sret);
  2519. else
  2520. {
  2521. bool unknown = true;
  2522. val = JSON_LOADS(sret, &err);
  2523. json_t *j_id = json_object_get(val, "id");
  2524. if (json_is_string(j_id))
  2525. {
  2526. if (!strcmp(json_string_value(j_id), "auth"))
  2527. break;
  2528. else
  2529. if (!strcmp(json_string_value(j_id), "xnsub"))
  2530. unknown = false;
  2531. }
  2532. if (unknown)
  2533. applog(LOG_WARNING, "Pool %u: Unknown stratum msg: %s", pool->pool_no, sret);
  2534. free(sret);
  2535. }
  2536. }
  2537. free(sret);
  2538. res_val = json_object_get(val, "result");
  2539. err_val = json_object_get(val, "error");
  2540. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2541. char *ss;
  2542. if (err_val)
  2543. ss = json_dumps(err_val, JSON_INDENT(3));
  2544. else
  2545. ss = strdup("(unknown reason)");
  2546. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  2547. free(ss);
  2548. goto out;
  2549. }
  2550. ret = true;
  2551. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  2552. pool->probed = true;
  2553. successful_connect = true;
  2554. out:
  2555. if (val)
  2556. json_decref(val);
  2557. if (pool->stratum_notify)
  2558. stratum_probe_transparency(pool);
  2559. return ret;
  2560. }
  2561. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  2562. {
  2563. struct pool *pool = clientp;
  2564. curl_socket_t sck = bfg_socket(addr->family, addr->socktype, addr->protocol);
  2565. pool->sock = sck;
  2566. return sck;
  2567. }
  2568. static bool setup_stratum_curl(struct pool *pool)
  2569. {
  2570. CURL *curl = NULL;
  2571. char s[RBUFSIZE];
  2572. bool ret = false;
  2573. bool tls_only = false, try_tls = true;
  2574. bool tlsca = uri_get_param_bool(pool->rpc_url, "tlsca", false);
  2575. {
  2576. const enum bfg_tristate tlsparam = uri_get_param_bool2(pool->rpc_url, "tls");
  2577. if (tlsparam != BTS_UNKNOWN)
  2578. try_tls = tls_only = tlsparam;
  2579. else
  2580. if (tlsca)
  2581. // If tlsca is enabled, require TLS by default
  2582. tls_only = true;
  2583. }
  2584. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  2585. mutex_lock(&pool->stratum_lock);
  2586. timer_unset(&pool->swork.tv_transparency);
  2587. pool->stratum_active = false;
  2588. pool->stratum_notify = false;
  2589. pool->swork.transparency_probed = false;
  2590. if (pool->stratum_curl)
  2591. curl_easy_cleanup(pool->stratum_curl);
  2592. pool->stratum_curl = curl_easy_init();
  2593. if (unlikely(!pool->stratum_curl))
  2594. quithere(1, "Failed to curl_easy_init");
  2595. if (pool->sockbuf)
  2596. pool->sockbuf[0] = '\0';
  2597. curl = pool->stratum_curl;
  2598. if (!pool->sockbuf) {
  2599. pool->sockbuf = calloc(RBUFSIZE, 1);
  2600. if (!pool->sockbuf)
  2601. quithere(1, "Failed to calloc pool sockbuf");
  2602. pool->sockbuf_size = RBUFSIZE;
  2603. }
  2604. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  2605. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  2606. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, pool->curl_err_str);
  2607. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  2608. if (!opt_delaynet)
  2609. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  2610. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  2611. * to enable it */
  2612. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  2613. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  2614. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2615. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  2616. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  2617. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  2618. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  2619. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, (long)(tlsca ? 2 : 0));
  2620. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, (long)(tlsca ? 1 : 0));
  2621. if (pool->rpc_proxy) {
  2622. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  2623. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  2624. } else if (opt_socks_proxy) {
  2625. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  2626. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  2627. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  2628. }
  2629. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  2630. retry:
  2631. /* Create a http url for use with curl */
  2632. sprintf(s, "http%s://%s:%s", try_tls ? "s" : "",
  2633. pool->sockaddr_url, pool->stratum_port);
  2634. curl_easy_setopt(curl, CURLOPT_URL, s);
  2635. pool->sock = INVSOCK;
  2636. if (curl_easy_perform(curl)) {
  2637. if (try_tls)
  2638. {
  2639. applog(LOG_DEBUG, "Stratum connect failed with TLS to pool %u: %s",
  2640. pool->pool_no, pool->curl_err_str);
  2641. if (!tls_only)
  2642. {
  2643. try_tls = false;
  2644. goto retry;
  2645. }
  2646. }
  2647. else
  2648. applog(LOG_INFO, "Stratum connect failed to pool %d: %s",
  2649. pool->pool_no, pool->curl_err_str);
  2650. errout:
  2651. curl_easy_cleanup(curl);
  2652. pool->stratum_curl = NULL;
  2653. goto out;
  2654. }
  2655. if (pool->sock == INVSOCK)
  2656. {
  2657. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  2658. goto errout;
  2659. }
  2660. keep_sockalive(pool->sock);
  2661. pool->cgminer_pool_stats.times_sent++;
  2662. pool->cgminer_pool_stats.times_received++;
  2663. ret = true;
  2664. out:
  2665. mutex_unlock(&pool->stratum_lock);
  2666. return ret;
  2667. }
  2668. static char *get_sessionid(json_t *val)
  2669. {
  2670. char *ret = NULL;
  2671. json_t *arr_val;
  2672. int arrsize, i;
  2673. arr_val = json_array_get(val, 0);
  2674. if (!arr_val || !json_is_array(arr_val))
  2675. goto out;
  2676. arrsize = json_array_size(arr_val);
  2677. for (i = 0; i < arrsize; i++) {
  2678. json_t *arr = json_array_get(arr_val, i);
  2679. const char *notify;
  2680. if (!arr | !json_is_array(arr))
  2681. break;
  2682. notify = __json_array_string(arr, 0);
  2683. if (!notify)
  2684. continue;
  2685. if (!strncasecmp(notify, "mining.notify", 13)) {
  2686. ret = json_array_string(arr, 1);
  2687. break;
  2688. }
  2689. }
  2690. out:
  2691. return ret;
  2692. }
  2693. void suspend_stratum(struct pool *pool)
  2694. {
  2695. clear_sockbuf(pool);
  2696. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2697. mutex_lock(&pool->stratum_lock);
  2698. pool->stratum_active = pool->stratum_notify = false;
  2699. if (pool->stratum_curl) {
  2700. curl_easy_cleanup(pool->stratum_curl);
  2701. }
  2702. pool->stratum_curl = NULL;
  2703. pool->sock = INVSOCK;
  2704. mutex_unlock(&pool->stratum_lock);
  2705. }
  2706. bool initiate_stratum(struct pool *pool)
  2707. {
  2708. bool ret = false, recvd = false, noresume = false, sockd = false;
  2709. bool trysuggest = request_target_str;
  2710. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  2711. json_t *val = NULL, *res_val, *err_val;
  2712. json_error_t err;
  2713. int n2size;
  2714. resend:
  2715. if (!setup_stratum_curl(pool)) {
  2716. sockd = false;
  2717. goto out;
  2718. }
  2719. sockd = true;
  2720. clear_sock(pool);
  2721. if (trysuggest)
  2722. {
  2723. int sz = sprintf(s, "{\"id\": null, \"method\": \"mining.suggest_target\", \"params\": [\"%s\"]}", request_target_str);
  2724. if (!_stratum_send(pool, s, sz, true))
  2725. {
  2726. applog(LOG_DEBUG, "Pool %u: Failed to send suggest_target in initiate_stratum", pool->pool_no);
  2727. goto out;
  2728. }
  2729. recvd = true;
  2730. }
  2731. if (noresume) {
  2732. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2733. } else {
  2734. if (pool->sessionid)
  2735. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2736. else
  2737. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  2738. }
  2739. if (!_stratum_send(pool, s, strlen(s), true)) {
  2740. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2741. goto out;
  2742. }
  2743. recvd = true;
  2744. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2745. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2746. goto out;
  2747. }
  2748. sret = recv_line(pool);
  2749. if (!sret)
  2750. goto out;
  2751. val = JSON_LOADS(sret, &err);
  2752. free(sret);
  2753. if (!val) {
  2754. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2755. goto out;
  2756. }
  2757. res_val = json_object_get(val, "result");
  2758. err_val = json_object_get(val, "error");
  2759. if (!res_val || json_is_null(res_val) ||
  2760. (err_val && !json_is_null(err_val))) {
  2761. char *ss;
  2762. if (err_val)
  2763. ss = json_dumps(err_val, JSON_INDENT(3));
  2764. else
  2765. ss = strdup("(unknown reason)");
  2766. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2767. free(ss);
  2768. goto out;
  2769. }
  2770. sessionid = get_sessionid(res_val);
  2771. if (!sessionid)
  2772. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2773. nonce1 = json_array_string(res_val, 1);
  2774. if (!nonce1) {
  2775. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  2776. free(sessionid);
  2777. goto out;
  2778. }
  2779. n2size = json_integer_value(json_array_get(res_val, 2));
  2780. if (n2size < 1)
  2781. {
  2782. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  2783. free(sessionid);
  2784. free(nonce1);
  2785. goto out;
  2786. }
  2787. cg_wlock(&pool->data_lock);
  2788. free(pool->sessionid);
  2789. pool->sessionid = sessionid;
  2790. free(pool->next_nonce1);
  2791. pool->next_nonce1 = nonce1;
  2792. pool->next_n2size = n2size;
  2793. cg_wunlock(&pool->data_lock);
  2794. if (sessionid)
  2795. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2796. ret = true;
  2797. out:
  2798. if (val)
  2799. {
  2800. json_decref(val);
  2801. val = NULL;
  2802. }
  2803. if (ret) {
  2804. if (!pool->stratum_url)
  2805. pool->stratum_url = pool->sockaddr_url;
  2806. pool->stratum_active = true;
  2807. set_target_to_pdiff(pool->next_target, 1);
  2808. if (opt_protocol) {
  2809. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2810. pool->pool_no, pool->next_nonce1, pool->next_n2size);
  2811. }
  2812. if (uri_get_param_bool(pool->rpc_url, "xnsub", false))
  2813. {
  2814. sprintf(s, "{\"id\": \"xnsub\", \"method\": \"mining.extranonce.subscribe\", \"params\": []}");
  2815. _stratum_send(pool, s, strlen(s), true);
  2816. }
  2817. } else {
  2818. if (recvd)
  2819. {
  2820. if (trysuggest)
  2821. {
  2822. applog(LOG_DEBUG, "Pool %u: Failed to connect stratum with mining.suggest_target, retrying without", pool->pool_no);
  2823. trysuggest = false;
  2824. goto resend;
  2825. }
  2826. if (!noresume)
  2827. {
  2828. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2829. noresume = true;
  2830. goto resend;
  2831. }
  2832. }
  2833. applog(LOG_DEBUG, "Initiate stratum failed");
  2834. if (sockd)
  2835. suspend_stratum(pool);
  2836. }
  2837. return ret;
  2838. }
  2839. bool restart_stratum(struct pool *pool)
  2840. {
  2841. bool ret = true;
  2842. mutex_lock(&pool->pool_test_lock);
  2843. if (pool->stratum_active)
  2844. suspend_stratum(pool);
  2845. if (!initiate_stratum(pool))
  2846. return_via(out, ret = false);
  2847. if (!auth_stratum(pool))
  2848. return_via(out, ret = false);
  2849. out:
  2850. mutex_unlock(&pool->pool_test_lock);
  2851. return ret;
  2852. }
  2853. void dev_error_update(struct cgpu_info *dev, enum dev_reason reason)
  2854. {
  2855. dev->device_last_not_well = time(NULL);
  2856. cgtime(&dev->tv_device_last_not_well);
  2857. dev->device_not_well_reason = reason;
  2858. }
  2859. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2860. {
  2861. dev_error_update(dev, reason);
  2862. switch (reason) {
  2863. case REASON_THREAD_FAIL_INIT:
  2864. dev->thread_fail_init_count++;
  2865. break;
  2866. case REASON_THREAD_ZERO_HASH:
  2867. dev->thread_zero_hash_count++;
  2868. break;
  2869. case REASON_THREAD_FAIL_QUEUE:
  2870. dev->thread_fail_queue_count++;
  2871. break;
  2872. case REASON_DEV_SICK_IDLE_60:
  2873. dev->dev_sick_idle_60_count++;
  2874. break;
  2875. case REASON_DEV_DEAD_IDLE_600:
  2876. dev->dev_dead_idle_600_count++;
  2877. break;
  2878. case REASON_DEV_NOSTART:
  2879. dev->dev_nostart_count++;
  2880. break;
  2881. case REASON_DEV_OVER_HEAT:
  2882. dev->dev_over_heat_count++;
  2883. break;
  2884. case REASON_DEV_THERMAL_CUTOFF:
  2885. dev->dev_thermal_cutoff_count++;
  2886. break;
  2887. case REASON_DEV_COMMS_ERROR:
  2888. dev->dev_comms_error_count++;
  2889. break;
  2890. case REASON_DEV_THROTTLE:
  2891. dev->dev_throttle_count++;
  2892. break;
  2893. }
  2894. }
  2895. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2896. void *realloc_strcat(char *ptr, char *s)
  2897. {
  2898. size_t old = strlen(ptr), len = strlen(s);
  2899. char *ret;
  2900. if (!len)
  2901. return ptr;
  2902. len += old + 1;
  2903. align_len(&len);
  2904. ret = malloc(len);
  2905. if (unlikely(!ret))
  2906. quithere(1, "Failed to malloc");
  2907. sprintf(ret, "%s%s", ptr, s);
  2908. free(ptr);
  2909. return ret;
  2910. }
  2911. static
  2912. bool sanechars[] = {
  2913. false, false, false, false, false, false, false, false,
  2914. false, false, false, false, false, false, false, false,
  2915. false, false, false, false, false, false, false, false,
  2916. false, false, false, false, false, false, false, false,
  2917. false, false, false, false, false, false, false, false,
  2918. false, false, false, false, false, true , false, false,
  2919. true , true , true , true , true , true , true , true ,
  2920. true , true , false, false, false, false, false, false,
  2921. false, true , true , true , true , true , true , true ,
  2922. true , true , true , true , true , true , true , true ,
  2923. true , true , true , true , true , true , true , true ,
  2924. true , true , true , false, false, false, false, false,
  2925. false, true , true , true , true , true , true , true ,
  2926. true , true , true , true , true , true , true , true ,
  2927. true , true , true , true , true , true , true , true ,
  2928. true , true , true , false, false, false, false, false,
  2929. };
  2930. char *sanestr(char *o, char *s)
  2931. {
  2932. char *rv = o;
  2933. bool br = false;
  2934. for ( ; s[0]; ++s)
  2935. {
  2936. if (sanechars[s[0] & 0x7f])
  2937. {
  2938. if (br)
  2939. {
  2940. br = false;
  2941. if (s[0] >= '0' && s[0] <= '9')
  2942. (o++)[0] = '_';
  2943. }
  2944. (o++)[0] = s[0];
  2945. }
  2946. else
  2947. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  2948. br = true;
  2949. }
  2950. o[0] = '\0';
  2951. return rv;
  2952. }
  2953. void RenameThread(const char* name)
  2954. {
  2955. #if defined(PR_SET_NAME)
  2956. // Only the first 15 characters are used (16 - NUL terminator)
  2957. prctl(PR_SET_NAME, name, 0, 0, 0);
  2958. #elif defined(__APPLE__)
  2959. pthread_setname_np(name);
  2960. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2961. pthread_set_name_np(pthread_self(), name);
  2962. #else
  2963. // Prevent warnings for unused parameters...
  2964. (void)name;
  2965. #endif
  2966. }
  2967. static pthread_key_t key_bfgtls;
  2968. struct bfgtls_data {
  2969. char *bfg_strerror_result;
  2970. size_t bfg_strerror_resultsz;
  2971. #ifdef WIN32
  2972. LPSTR bfg_strerror_socketresult;
  2973. #endif
  2974. #ifdef NEED_BFG_LOWL_VCOM
  2975. struct detectone_meta_info_t __detectone_meta_info;
  2976. #endif
  2977. unsigned probe_result_flags;
  2978. };
  2979. static
  2980. struct bfgtls_data *get_bfgtls()
  2981. {
  2982. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  2983. if (bfgtls)
  2984. return bfgtls;
  2985. void *p;
  2986. bfgtls = malloc(sizeof(*bfgtls));
  2987. if (!bfgtls)
  2988. quithere(1, "malloc bfgtls failed");
  2989. p = malloc(64);
  2990. if (!p)
  2991. quithere(1, "malloc bfg_strerror_result failed");
  2992. *bfgtls = (struct bfgtls_data){
  2993. .bfg_strerror_resultsz = 64,
  2994. .bfg_strerror_result = p,
  2995. };
  2996. if (pthread_setspecific(key_bfgtls, bfgtls))
  2997. quithere(1, "pthread_setspecific failed");
  2998. return bfgtls;
  2999. }
  3000. static
  3001. void bfgtls_free(void * const p)
  3002. {
  3003. struct bfgtls_data * const bfgtls = p;
  3004. free(bfgtls->bfg_strerror_result);
  3005. #ifdef WIN32
  3006. if (bfgtls->bfg_strerror_socketresult)
  3007. LocalFree(bfgtls->bfg_strerror_socketresult);
  3008. #endif
  3009. free(bfgtls);
  3010. }
  3011. #ifdef NEED_BFG_LOWL_VCOM
  3012. struct detectone_meta_info_t *_detectone_meta_info()
  3013. {
  3014. return &get_bfgtls()->__detectone_meta_info;
  3015. }
  3016. #endif
  3017. unsigned *_bfg_probe_result_flags()
  3018. {
  3019. return &get_bfgtls()->probe_result_flags;
  3020. }
  3021. void bfg_init_threadlocal()
  3022. {
  3023. if (pthread_key_create(&key_bfgtls, bfgtls_free))
  3024. quithere(1, "pthread_key_create failed");
  3025. }
  3026. static
  3027. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  3028. {
  3029. if (minimum <= *bufszp)
  3030. return false;
  3031. while (minimum > *bufszp)
  3032. *bufszp = 2;
  3033. *bufp = realloc(*bufp, *bufszp);
  3034. if (unlikely(!*bufp))
  3035. quithere(1, "realloc failed");
  3036. return true;
  3037. }
  3038. static
  3039. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  3040. {
  3041. if (!src)
  3042. return NULL;
  3043. const size_t srcsz = strlen(src) + 1;
  3044. bfg_grow_buffer(bufp, bufszp, srcsz);
  3045. memcpy(*bufp, src, srcsz);
  3046. return *bufp;
  3047. }
  3048. // Guaranteed to always return some string (or quit)
  3049. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  3050. {
  3051. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  3052. struct bfgtls_data *bfgtls = get_bfgtls();
  3053. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  3054. char ** const bufp = &bfgtls->bfg_strerror_result;
  3055. const char *have = NULL;
  3056. switch (type) {
  3057. case BST_LIBUSB:
  3058. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  3059. #ifdef HAVE_LIBUSB
  3060. # if HAVE_DECL_LIBUSB_ERROR_NAME
  3061. // libusb makes no guarantees for thread-safety or persistence
  3062. mutex_lock(&mutex);
  3063. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  3064. mutex_unlock(&mutex);
  3065. # endif
  3066. #endif
  3067. break;
  3068. case BST_SOCKET:
  3069. case BST_SYSTEM:
  3070. {
  3071. #ifdef WIN32
  3072. // Windows has a different namespace for system and socket errors
  3073. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  3074. if (*msg)
  3075. LocalFree(*msg);
  3076. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  3077. {
  3078. LPSTR msgp = *msg;
  3079. size_t n = strlen(msgp);
  3080. while (isCspace(msgp[--n]))
  3081. msgp[n] = '\0';
  3082. return *msg;
  3083. }
  3084. *msg = NULL;
  3085. break;
  3086. #endif
  3087. }
  3088. // Fallthru on non-WIN32
  3089. case BST_ERRNO:
  3090. {
  3091. #ifdef __STRERROR_S_WORKS
  3092. // FIXME: Not sure how to get this on MingW64
  3093. retry:
  3094. if (likely(!strerror_s(*bufp, *bufszp, e)))
  3095. {
  3096. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  3097. goto retry;
  3098. return *bufp;
  3099. }
  3100. // TODO: XSI strerror_r
  3101. // TODO: GNU strerror_r
  3102. #else
  3103. mutex_lock(&mutex);
  3104. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  3105. mutex_unlock(&mutex);
  3106. #endif
  3107. }
  3108. }
  3109. if (have)
  3110. return *bufp;
  3111. // Failback: Stringify the number
  3112. static const char fmt[] = "%s error #%d", *typestr;
  3113. switch (type) {
  3114. case BST_ERRNO:
  3115. typestr = "System";
  3116. break;
  3117. case BST_SOCKET:
  3118. typestr = "Socket";
  3119. break;
  3120. case BST_LIBUSB:
  3121. typestr = "libusb";
  3122. break;
  3123. default:
  3124. typestr = "Unexpected";
  3125. }
  3126. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  3127. bfg_grow_buffer(bufp, bufszp, sz);
  3128. sprintf(*bufp, fmt, typestr, e);
  3129. return *bufp;
  3130. }
  3131. void notifier_init(notifier_t pipefd)
  3132. {
  3133. #ifdef WIN32
  3134. #define WindowsErrorStr(e) bfg_strerror(e, BST_SOCKET)
  3135. SOCKET listener, connecter, acceptor;
  3136. listener = bfg_socket(AF_INET, SOCK_STREAM, 0);
  3137. if (listener == INVALID_SOCKET)
  3138. quit(1, "Failed to create listener socket"IN_FMT_FFL": %s",
  3139. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3140. connecter = bfg_socket(AF_INET, SOCK_STREAM, 0);
  3141. if (connecter == INVALID_SOCKET)
  3142. quit(1, "Failed to create connect socket"IN_FMT_FFL": %s",
  3143. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3144. struct sockaddr_in inaddr = {
  3145. .sin_family = AF_INET,
  3146. .sin_addr = {
  3147. .s_addr = htonl(INADDR_LOOPBACK),
  3148. },
  3149. .sin_port = 0,
  3150. };
  3151. {
  3152. static const int reuse = 1;
  3153. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
  3154. }
  3155. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  3156. quit(1, "Failed to bind listener socket"IN_FMT_FFL": %s",
  3157. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3158. socklen_t inaddr_sz = sizeof(inaddr);
  3159. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  3160. quit(1, "Failed to getsockname"IN_FMT_FFL": %s",
  3161. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3162. if (listen(listener, 1) == SOCKET_ERROR)
  3163. quit(1, "Failed to listen"IN_FMT_FFL": %s",
  3164. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3165. inaddr.sin_family = AF_INET;
  3166. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3167. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  3168. quit(1, "Failed to connect"IN_FMT_FFL": %s",
  3169. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3170. acceptor = accept(listener, NULL, NULL);
  3171. if (acceptor == INVALID_SOCKET)
  3172. quit(1, "Failed to accept"IN_FMT_FFL": %s",
  3173. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3174. closesocket(listener);
  3175. pipefd[0] = connecter;
  3176. pipefd[1] = acceptor;
  3177. #else
  3178. if (pipe(pipefd))
  3179. quithere(1, "Failed to create pipe");
  3180. #endif
  3181. }
  3182. void *bfg_slurp_file(void * const bufp, size_t bufsz, const char * const filename)
  3183. {
  3184. char *buf = bufp;
  3185. FILE * const F = fopen(filename, "r");
  3186. if (!F)
  3187. goto err;
  3188. if (!buf)
  3189. {
  3190. fseek(F, 0, SEEK_END);
  3191. const long filesz = ftell(F);
  3192. if (unlikely(filesz < 0))
  3193. {
  3194. fclose(F);
  3195. goto err;
  3196. }
  3197. rewind(F);
  3198. bufsz = filesz + 1;
  3199. buf = malloc(bufsz);
  3200. }
  3201. const size_t rsz = fread(buf, 1, bufsz - 1, F);
  3202. fclose(F);
  3203. buf[rsz] = '\0';
  3204. return buf;
  3205. err:
  3206. if (buf)
  3207. buf[0] = '\0';
  3208. return NULL;
  3209. }
  3210. void notifier_wake(notifier_t fd)
  3211. {
  3212. if (fd[1] == INVSOCK)
  3213. return;
  3214. if (1 !=
  3215. #ifdef WIN32
  3216. send(fd[1], "\0", 1, 0)
  3217. #else
  3218. write(fd[1], "\0", 1)
  3219. #endif
  3220. )
  3221. applog(LOG_WARNING, "Error trying to wake notifier");
  3222. }
  3223. void notifier_read(notifier_t fd)
  3224. {
  3225. char buf[0x10];
  3226. #ifdef WIN32
  3227. IGNORE_RETURN_VALUE(recv(fd[0], buf, sizeof(buf), 0));
  3228. #else
  3229. IGNORE_RETURN_VALUE(read(fd[0], buf, sizeof(buf)));
  3230. #endif
  3231. }
  3232. bool notifier_wait(notifier_t notifier, const struct timeval *tvp_timeout)
  3233. {
  3234. struct timeval tv_now, tv_timeout;
  3235. fd_set rfds;
  3236. int e;
  3237. while (true)
  3238. {
  3239. FD_ZERO(&rfds);
  3240. FD_SET(notifier[0], &rfds);
  3241. tv_timeout = *tvp_timeout;
  3242. timer_set_now(&tv_now);
  3243. e = select(notifier[0]+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now));
  3244. if (e > 0)
  3245. return true;
  3246. if (e == 0)
  3247. return false;
  3248. }
  3249. }
  3250. bool notifier_wait_us(notifier_t notifier, const unsigned long long usecs)
  3251. {
  3252. struct timeval tv_timeout = TIMEVAL_USECS(usecs);
  3253. return notifier_wait(notifier, &tv_timeout);
  3254. }
  3255. void notifier_reset(notifier_t notifier)
  3256. {
  3257. fd_set rfds;
  3258. struct timeval tv_timeout = { .tv_sec = 0, };
  3259. FD_ZERO(&rfds);
  3260. FD_SET(notifier[0], &rfds);
  3261. while (select(notifier[0]+1, &rfds, NULL, NULL, &tv_timeout) != 0)
  3262. notifier_read(notifier);
  3263. }
  3264. void notifier_init_invalid(notifier_t fd)
  3265. {
  3266. fd[0] = fd[1] = INVSOCK;
  3267. }
  3268. void notifier_destroy(notifier_t fd)
  3269. {
  3270. #ifdef WIN32
  3271. closesocket(fd[0]);
  3272. closesocket(fd[1]);
  3273. #else
  3274. close(fd[0]);
  3275. close(fd[1]);
  3276. #endif
  3277. fd[0] = fd[1] = INVSOCK;
  3278. }
  3279. void _bytes_alloc_failure(size_t sz)
  3280. {
  3281. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  3282. }
  3283. char *trimmed_strdup(const char *s)
  3284. {
  3285. size_t n;
  3286. char *c;
  3287. while (isspace(s[0]))
  3288. ++s;
  3289. n = strlen(s) - 1;
  3290. while (isspace(s[n]))
  3291. --n;
  3292. ++n;
  3293. c = malloc(n + 1);
  3294. c[n] = '\0';
  3295. memcpy(c, s, n);
  3296. return c;
  3297. }
  3298. void *cmd_thread(void *cmdp)
  3299. {
  3300. const char *cmd = cmdp;
  3301. applog(LOG_DEBUG, "Executing command: %s", cmd);
  3302. int rc = system(cmd);
  3303. if (rc)
  3304. applog(LOG_WARNING, "Command returned %d exit code: %s", rc, cmd);
  3305. return NULL;
  3306. }
  3307. void run_cmd(const char *cmd)
  3308. {
  3309. if (!cmd)
  3310. return;
  3311. pthread_t pth;
  3312. pthread_create(&pth, NULL, cmd_thread, (void*)cmd);
  3313. }
  3314. uint8_t crc5usb(unsigned char *ptr, uint8_t len)
  3315. {
  3316. uint8_t i, j, k;
  3317. uint8_t crc = 0x1f;
  3318. uint8_t crcin[5] = {1, 1, 1, 1, 1};
  3319. uint8_t crcout[5] = {1, 1, 1, 1, 1};
  3320. uint8_t din = 0;
  3321. j = 0x80;
  3322. k = 0;
  3323. for (i = 0; i < len; i++)
  3324. {
  3325. if (*ptr & j)
  3326. din = 1;
  3327. else
  3328. din = 0;
  3329. crcout[0] = crcin[4] ^ din;
  3330. crcout[1] = crcin[0];
  3331. crcout[2] = crcin[1] ^ crcin[4] ^ din;
  3332. crcout[3] = crcin[2];
  3333. crcout[4] = crcin[3];
  3334. j = j >> 1;
  3335. k++;
  3336. if (k == 8)
  3337. {
  3338. j = 0x80;
  3339. k = 0;
  3340. ptr++;
  3341. }
  3342. memcpy(crcin, crcout, 5);
  3343. }
  3344. crc = 0;
  3345. if(crcin[4])
  3346. crc |= 0x10;
  3347. if(crcin[3])
  3348. crc |= 0x08;
  3349. if(crcin[2])
  3350. crc |= 0x04;
  3351. if(crcin[1])
  3352. crc |= 0x02;
  3353. if(crcin[0])
  3354. crc |= 0x01;
  3355. return crc;
  3356. }
  3357. static uint8_t _crc8ccitt_table[0x100];
  3358. void bfg_init_checksums(void)
  3359. {
  3360. for (int i = 0; i < 0x100; ++i)
  3361. {
  3362. uint8_t crc = i;
  3363. for (int j = 0; j < 8; ++j)
  3364. crc = (crc << 1) ^ ((crc & 0x80) ? 7 : 0);
  3365. _crc8ccitt_table[i] = crc & 0xff;
  3366. }
  3367. }
  3368. uint8_t crc8ccitt(const void * const buf, const size_t buflen)
  3369. {
  3370. const uint8_t *p = buf;
  3371. uint8_t crc = 0xff;
  3372. for (int i = 0; i < buflen; ++i)
  3373. crc = _crc8ccitt_table[crc ^ *p++];
  3374. return crc;
  3375. }
  3376. static uint16_t crc16tab[] = {
  3377. 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
  3378. 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
  3379. 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
  3380. 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
  3381. 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
  3382. 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
  3383. 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
  3384. 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
  3385. 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
  3386. 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
  3387. 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
  3388. 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
  3389. 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
  3390. 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
  3391. 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
  3392. 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
  3393. 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
  3394. 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
  3395. 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
  3396. 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
  3397. 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
  3398. 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
  3399. 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
  3400. 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
  3401. 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
  3402. 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
  3403. 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
  3404. 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
  3405. 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
  3406. 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
  3407. 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
  3408. 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0,
  3409. };
  3410. static
  3411. uint16_t crc16_floating(uint16_t next_byte, uint16_t seed)
  3412. {
  3413. return ((seed << 8) ^ crc16tab[(seed >> 8) ^ next_byte]) & 0xFFFF;
  3414. }
  3415. uint16_t crc16(const void *p, size_t sz, uint16_t crc)
  3416. {
  3417. const uint8_t * const s = p;
  3418. for (size_t i = 0; i < sz; ++i)
  3419. crc = crc16_floating(s[i], crc);
  3420. return crc;
  3421. }