util.c 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948
  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. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_len=>%d", (unsigned long)expected, expectedlen, len);
  1284. len = utf8_strlen(s);
  1285. if (len != (s[0] ? 1 : 0))
  1286. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_strlen=>%d", (unsigned long)expected, expectedlen, len);
  1287. len = -1;
  1288. }
  1289. r = utf8_decode(s, &len);
  1290. if (unlikely(r != expected || expectedlen != len))
  1291. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got U+%06lX (len %d)", (unsigned long)expected, expectedlen, (unsigned long)r, len);
  1292. }
  1293. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1294. void utf8_test()
  1295. {
  1296. _utf8_test("", 0, 1);
  1297. _utf8_test("\1", 1, 1);
  1298. _utf8_test("\x7f", 0x7f, 1);
  1299. #if WCHAR_MAX >= 0x80
  1300. _utf8_test("\xc2\x80", 0x80, 2);
  1301. #if WCHAR_MAX >= 0xff
  1302. _utf8_test("\xc3\xbf", 0xff, 2);
  1303. #if WCHAR_MAX >= 0x7ff
  1304. _utf8_test("\xdf\xbf", 0x7ff, 2);
  1305. #if WCHAR_MAX >= 0x800
  1306. _utf8_test("\xe0\xa0\x80", 0x800, 3);
  1307. #if WCHAR_MAX >= 0xffff
  1308. _utf8_test("\xef\xbf\xbf", 0xffff, 3);
  1309. #if WCHAR_MAX >= 0x10000
  1310. _utf8_test("\xf0\x90\x80\x80", 0x10000, 4);
  1311. #if WCHAR_MAX >= 0x10ffff
  1312. _utf8_test("\xf4\x8f\xbf\xbf", 0x10ffff, 4);
  1313. #endif
  1314. #endif
  1315. #endif
  1316. #endif
  1317. #endif
  1318. #endif
  1319. #endif
  1320. #ifdef STRICT_UTF8
  1321. _utf8_test("\x80", REPLACEMENT_CHAR, 1);
  1322. _utf8_test("\xbf", REPLACEMENT_CHAR, 1);
  1323. _utf8_test("\xfe", REPLACEMENT_CHAR, 1);
  1324. _utf8_test("\xff", REPLACEMENT_CHAR, 1);
  1325. #endif
  1326. }
  1327. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1328. {
  1329. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1330. char url_address[256], port[6];
  1331. int url_len, port_len = 0;
  1332. url_begin = strstr(url, "//");
  1333. if (!url_begin)
  1334. url_begin = url;
  1335. else
  1336. url_begin += 2;
  1337. /* Look for numeric ipv6 entries */
  1338. ipv6_begin = strstr(url_begin, "[");
  1339. ipv6_end = strstr(url_begin, "]");
  1340. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1341. url_end = strstr(ipv6_end, ":");
  1342. else
  1343. url_end = strstr(url_begin, ":");
  1344. if (url_end) {
  1345. url_len = url_end - url_begin;
  1346. port_len = strlen(url_begin) - url_len - 1;
  1347. if (port_len < 1)
  1348. return false;
  1349. port_start = url_end + 1;
  1350. } else
  1351. url_len = strlen(url_begin);
  1352. if (url_len < 1)
  1353. return false;
  1354. if (url_len >= sizeof(url_address))
  1355. {
  1356. applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'",
  1357. __func__, url_len, url_begin);
  1358. url_len = sizeof(url_address) - 1;
  1359. }
  1360. sprintf(url_address, "%.*s", url_len, url_begin);
  1361. if (port_len) {
  1362. char *slash;
  1363. snprintf(port, 6, "%.*s", port_len, port_start);
  1364. slash = strchr(port, '/');
  1365. if (slash)
  1366. *slash = '\0';
  1367. } else
  1368. strcpy(port, "80");
  1369. free(*sockaddr_port);
  1370. *sockaddr_port = strdup(port);
  1371. free(*sockaddr_url);
  1372. *sockaddr_url = strdup(url_address);
  1373. return true;
  1374. }
  1375. enum send_ret {
  1376. SEND_OK,
  1377. SEND_SELECTFAIL,
  1378. SEND_SENDFAIL,
  1379. SEND_INACTIVE
  1380. };
  1381. /* Send a single command across a socket, appending \n to it. This should all
  1382. * be done under stratum lock except when first establishing the socket */
  1383. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1384. {
  1385. SOCKETTYPE sock = pool->sock;
  1386. ssize_t ssent = 0;
  1387. strcat(s, "\n");
  1388. len++;
  1389. while (len > 0 ) {
  1390. struct timeval timeout = {1, 0};
  1391. size_t sent = 0;
  1392. CURLcode rc;
  1393. fd_set wd;
  1394. retry:
  1395. FD_ZERO(&wd);
  1396. FD_SET(sock, &wd);
  1397. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1398. if (interrupted())
  1399. goto retry;
  1400. return SEND_SELECTFAIL;
  1401. }
  1402. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  1403. if (rc != CURLE_OK)
  1404. {
  1405. if (rc != CURLE_AGAIN)
  1406. return SEND_SENDFAIL;
  1407. sent = 0;
  1408. }
  1409. ssent += sent;
  1410. len -= sent;
  1411. }
  1412. pool->cgminer_pool_stats.times_sent++;
  1413. pool->cgminer_pool_stats.bytes_sent += ssent;
  1414. total_bytes_sent += ssent;
  1415. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1416. return SEND_OK;
  1417. }
  1418. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1419. {
  1420. enum send_ret ret = SEND_INACTIVE;
  1421. if (opt_protocol)
  1422. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1423. mutex_lock(&pool->stratum_lock);
  1424. if (pool->stratum_active || force)
  1425. ret = __stratum_send(pool, s, len);
  1426. mutex_unlock(&pool->stratum_lock);
  1427. /* This is to avoid doing applog under stratum_lock */
  1428. switch (ret) {
  1429. default:
  1430. case SEND_OK:
  1431. break;
  1432. case SEND_SELECTFAIL:
  1433. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1434. suspend_stratum(pool);
  1435. break;
  1436. case SEND_SENDFAIL:
  1437. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1438. suspend_stratum(pool);
  1439. break;
  1440. case SEND_INACTIVE:
  1441. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1442. break;
  1443. }
  1444. return (ret == SEND_OK);
  1445. }
  1446. static bool socket_full(struct pool *pool, int wait)
  1447. {
  1448. SOCKETTYPE sock = pool->sock;
  1449. struct timeval timeout;
  1450. fd_set rd;
  1451. if (sock == INVSOCK)
  1452. return true;
  1453. if (unlikely(wait < 0))
  1454. wait = 0;
  1455. FD_ZERO(&rd);
  1456. FD_SET(sock, &rd);
  1457. timeout.tv_usec = 0;
  1458. timeout.tv_sec = wait;
  1459. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1460. return true;
  1461. return false;
  1462. }
  1463. /* Check to see if Santa's been good to you */
  1464. bool sock_full(struct pool *pool)
  1465. {
  1466. if (strlen(pool->sockbuf))
  1467. return true;
  1468. return (socket_full(pool, 0));
  1469. }
  1470. static void clear_sockbuf(struct pool *pool)
  1471. {
  1472. strcpy(pool->sockbuf, "");
  1473. }
  1474. static void clear_sock(struct pool *pool)
  1475. {
  1476. size_t n = 0;
  1477. mutex_lock(&pool->stratum_lock);
  1478. do {
  1479. n = 0;
  1480. if (pool->sock)
  1481. curl_easy_recv(pool->stratum_curl, pool->sockbuf, RECVSIZE, &n);
  1482. } while (n > 0);
  1483. mutex_unlock(&pool->stratum_lock);
  1484. clear_sockbuf(pool);
  1485. }
  1486. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1487. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1488. * and zeroing the new memory */
  1489. static void recalloc_sock(struct pool *pool, size_t len)
  1490. {
  1491. size_t old, new;
  1492. old = strlen(pool->sockbuf);
  1493. new = old + len + 1;
  1494. if (new < pool->sockbuf_size)
  1495. return;
  1496. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1497. // Avoid potentially recursive locking
  1498. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1499. pool->sockbuf = realloc(pool->sockbuf, new);
  1500. if (!pool->sockbuf)
  1501. quithere(1, "Failed to realloc pool sockbuf");
  1502. memset(pool->sockbuf + old, 0, new - old);
  1503. pool->sockbuf_size = new;
  1504. }
  1505. /* Peeks at a socket to find the first end of line and then reads just that
  1506. * from the socket and returns that as a malloced char */
  1507. char *recv_line(struct pool *pool)
  1508. {
  1509. char *tok, *sret = NULL;
  1510. ssize_t len, buflen;
  1511. int waited = 0;
  1512. if (!strstr(pool->sockbuf, "\n")) {
  1513. struct timeval rstart, now;
  1514. cgtime(&rstart);
  1515. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1516. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1517. goto out;
  1518. }
  1519. do {
  1520. char s[RBUFSIZE];
  1521. size_t slen;
  1522. size_t n = 0;
  1523. CURLcode rc;
  1524. memset(s, 0, RBUFSIZE);
  1525. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  1526. if (rc == CURLE_OK && !n)
  1527. {
  1528. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1529. suspend_stratum(pool);
  1530. break;
  1531. }
  1532. cgtime(&now);
  1533. waited = tdiff(&now, &rstart);
  1534. if (rc != CURLE_OK)
  1535. {
  1536. if (rc != CURLE_AGAIN || !socket_full(pool, DEFAULT_SOCKWAIT - waited))
  1537. {
  1538. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1539. suspend_stratum(pool);
  1540. break;
  1541. }
  1542. } else {
  1543. slen = strlen(s);
  1544. recalloc_sock(pool, slen);
  1545. strcat(pool->sockbuf, s);
  1546. }
  1547. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1548. }
  1549. buflen = strlen(pool->sockbuf);
  1550. tok = strtok(pool->sockbuf, "\n");
  1551. if (!tok) {
  1552. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1553. goto out;
  1554. }
  1555. sret = strdup(tok);
  1556. len = strlen(sret);
  1557. /* Copy what's left in the buffer after the \n, including the
  1558. * terminating \0 */
  1559. if (buflen > len + 1)
  1560. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1561. else
  1562. strcpy(pool->sockbuf, "");
  1563. pool->cgminer_pool_stats.times_received++;
  1564. pool->cgminer_pool_stats.bytes_received += len;
  1565. total_bytes_rcvd += len;
  1566. pool->cgminer_pool_stats.net_bytes_received += len;
  1567. out:
  1568. if (!sret)
  1569. clear_sock(pool);
  1570. else if (opt_protocol)
  1571. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1572. return sret;
  1573. }
  1574. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1575. * flag, but this is compatible with 2.0. */
  1576. char *json_dumps_ANY(json_t *json, size_t flags)
  1577. {
  1578. switch (json_typeof(json))
  1579. {
  1580. case JSON_ARRAY:
  1581. case JSON_OBJECT:
  1582. return json_dumps(json, flags);
  1583. default:
  1584. break;
  1585. }
  1586. char *rv;
  1587. #ifdef JSON_ENCODE_ANY
  1588. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1589. if (rv)
  1590. return rv;
  1591. #endif
  1592. json_t *tmp = json_array();
  1593. char *s;
  1594. int i;
  1595. size_t len;
  1596. if (!tmp)
  1597. quithere(1, "Failed to allocate json array");
  1598. if (json_array_append(tmp, json))
  1599. quithere(1, "Failed to append temporary array");
  1600. s = json_dumps(tmp, flags);
  1601. if (!s)
  1602. return NULL;
  1603. for (i = 0; s[i] != '['; ++i)
  1604. if (unlikely(!(s[i] && isCspace(s[i]))))
  1605. quithere(1, "Failed to find opening bracket in array dump");
  1606. len = strlen(&s[++i]) - 1;
  1607. if (unlikely(s[i+len] != ']'))
  1608. quithere(1, "Failed to find closing bracket in array dump");
  1609. rv = malloc(len + 1);
  1610. memcpy(rv, &s[i], len);
  1611. rv[len] = '\0';
  1612. free(s);
  1613. json_decref(tmp);
  1614. return rv;
  1615. }
  1616. /* Extracts a string value from a json array with error checking. To be used
  1617. * when the value of the string returned is only examined and not to be stored.
  1618. * See json_array_string below */
  1619. const char *__json_array_string(json_t *val, unsigned int entry)
  1620. {
  1621. json_t *arr_entry;
  1622. if (json_is_null(val))
  1623. return NULL;
  1624. if (!json_is_array(val))
  1625. return NULL;
  1626. if (entry > json_array_size(val))
  1627. return NULL;
  1628. arr_entry = json_array_get(val, entry);
  1629. if (!json_is_string(arr_entry))
  1630. return NULL;
  1631. return json_string_value(arr_entry);
  1632. }
  1633. /* Creates a freshly malloced dup of __json_array_string */
  1634. static char *json_array_string(json_t *val, unsigned int entry)
  1635. {
  1636. const char *buf = __json_array_string(val, entry);
  1637. if (buf)
  1638. return strdup(buf);
  1639. return NULL;
  1640. }
  1641. void *my_memrchr(const void * const datap, const int c, const size_t sz)
  1642. {
  1643. const uint8_t *data = datap;
  1644. const uint8_t *p = &data[sz];
  1645. while (p > data)
  1646. if (*--p == c)
  1647. return (void *)p;
  1648. return NULL;
  1649. }
  1650. bool isCalpha(const int c)
  1651. {
  1652. if (c >= 'A' && c <= 'Z')
  1653. return true;
  1654. if (c >= 'a' && c <= 'z')
  1655. return true;
  1656. return false;
  1657. }
  1658. static
  1659. 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)
  1660. {
  1661. if (!(path && path[0]))
  1662. return false;
  1663. char filepath[PATH_MAX];
  1664. snprintf(filepath, sizeof(filepath), "%s/%s/%s", path, appname, filename);
  1665. if (!access(filepath, R_OK))
  1666. return cb(filepath, userp);
  1667. return false;
  1668. }
  1669. #define _APPDATA_FILE_CALL(appname, path) do{ \
  1670. if (_appdata_file_call(appname, filename, cb, userp, path)) \
  1671. return true; \
  1672. }while(0)
  1673. bool appdata_file_call(const char *appname, const char * const filename, const appdata_file_callback_t cb, void * const userp)
  1674. {
  1675. size_t appname_len = strlen(appname);
  1676. char appname_lcd[appname_len + 1];
  1677. appname_lcd[0] = '.';
  1678. char *appname_lc = &appname_lcd[1];
  1679. for (size_t i = 0; i <= appname_len; ++i)
  1680. appname_lc[i] = tolower(appname[i]);
  1681. appname_lc[appname_len] = '\0';
  1682. const char * const HOME = getenv("HOME");
  1683. _APPDATA_FILE_CALL(".", ".");
  1684. #ifdef WIN32
  1685. _APPDATA_FILE_CALL(appname, getenv("APPDATA"));
  1686. #elif defined(__APPLE__)
  1687. if (HOME && HOME[0])
  1688. {
  1689. char AppSupport[strlen(HOME) + 28 + 1];
  1690. snprintf(AppSupport, sizeof(AppSupport), "%s/Library/Application Support", HOME);
  1691. _APPDATA_FILE_CALL(appname, AppSupport);
  1692. }
  1693. #endif
  1694. _APPDATA_FILE_CALL(appname_lcd, HOME);
  1695. #ifdef WIN32
  1696. _APPDATA_FILE_CALL(appname, getenv("ALLUSERSAPPDATA"));
  1697. #elif defined(__APPLE__)
  1698. _APPDATA_FILE_CALL(appname, "/Library/Application Support");
  1699. #endif
  1700. #ifndef WIN32
  1701. _APPDATA_FILE_CALL(appname_lc, "/etc");
  1702. #endif
  1703. return false;
  1704. }
  1705. static
  1706. bool _appdata_file_find_first(const char * const filepath, void *userp)
  1707. {
  1708. char **rv = userp;
  1709. *rv = strdup(filepath);
  1710. return true;
  1711. }
  1712. char *appdata_file_find_first(const char * const appname, const char * const filename)
  1713. {
  1714. char *rv;
  1715. if (appdata_file_call(appname, filename, _appdata_file_find_first, &rv))
  1716. return rv;
  1717. return NULL;
  1718. }
  1719. const char *get_registered_domain(size_t * const out_domainlen, const char * const fqdn, const size_t fqdnlen)
  1720. {
  1721. const char *s;
  1722. int dots = 0;
  1723. for (s = &fqdn[fqdnlen-1]; s >= fqdn; --s)
  1724. {
  1725. if (s[0] == '.')
  1726. {
  1727. *out_domainlen = fqdnlen - (&s[1] - fqdn);
  1728. if (++dots >= 2 && *out_domainlen > 5)
  1729. return &s[1];
  1730. }
  1731. else
  1732. if (!(dots || isCalpha(s[0])))
  1733. {
  1734. *out_domainlen = fqdnlen;
  1735. return fqdn;
  1736. }
  1737. }
  1738. *out_domainlen = fqdnlen;
  1739. return fqdn;
  1740. }
  1741. const char *extract_domain(size_t * const out_domainlen, const char * const uri, const size_t urilen)
  1742. {
  1743. const char *p = uri, *b, *q, *s;
  1744. bool alldigit;
  1745. p = memchr(&p[1], '/', urilen - (&p[1] - uri));
  1746. if (p)
  1747. {
  1748. if (p[-1] == ':')
  1749. {
  1750. // part of the URI scheme, ignore it
  1751. while (p[0] == '/')
  1752. ++p;
  1753. p = memchr(p, '/', urilen - (p - uri)) ?: &uri[urilen];
  1754. }
  1755. }
  1756. else
  1757. p = &uri[urilen];
  1758. s = p;
  1759. q = my_memrchr(uri, ':', p - uri);
  1760. if (q)
  1761. {
  1762. alldigit = true;
  1763. for (q = b = &q[1]; q < p; ++q)
  1764. if (!isdigit(q[0]))
  1765. {
  1766. alldigit = false;
  1767. break;
  1768. }
  1769. if (alldigit && p != b)
  1770. p = &b[-1];
  1771. }
  1772. alldigit = true;
  1773. for (b = uri; b < p; ++b)
  1774. {
  1775. if (b[0] == ':')
  1776. break;
  1777. if (alldigit && !isdigit(b[0]))
  1778. alldigit = false;
  1779. }
  1780. if ((b < p && b[0] == ':') && (b == uri || !alldigit))
  1781. b = &b[1];
  1782. else
  1783. b = uri;
  1784. while (b <= p && b[0] == '/')
  1785. ++b;
  1786. if (p - b > 1 && b[0] == '[' && p[-1] == ']')
  1787. {
  1788. ++b;
  1789. --p;
  1790. }
  1791. else
  1792. if (memchr(b, ':', p - b))
  1793. p = s;
  1794. if (p > b && p[-1] == '.')
  1795. --p;
  1796. *out_domainlen = p - b;
  1797. return b;
  1798. }
  1799. bool match_domains(const char * const a, const size_t alen, const char * const b, const size_t blen)
  1800. {
  1801. size_t a_domainlen, b_domainlen;
  1802. const char *a_domain, *b_domain;
  1803. a_domain = extract_domain(&a_domainlen, a, alen);
  1804. a_domain = get_registered_domain(&a_domainlen, a_domain, a_domainlen);
  1805. b_domain = extract_domain(&b_domainlen, b, blen);
  1806. b_domain = get_registered_domain(&b_domainlen, b_domain, b_domainlen);
  1807. if (a_domainlen != b_domainlen)
  1808. return false;
  1809. return !strncasecmp(a_domain, b_domain, a_domainlen);
  1810. }
  1811. static
  1812. void _test_extract_domain(const char * const expect, const char * const uri)
  1813. {
  1814. size_t sz;
  1815. const char * const d = extract_domain(&sz, uri, strlen(uri));
  1816. if (sz != strlen(expect) || strncasecmp(d, expect, sz))
  1817. applog(LOG_WARNING, "extract_domain \"%s\" test failed; got \"%.*s\" instead of \"%s\"",
  1818. uri, (int)sz, d, expect);
  1819. }
  1820. static
  1821. void _test_get_regd_domain(const char * const expect, const char * const fqdn)
  1822. {
  1823. size_t sz;
  1824. const char * const d = get_registered_domain(&sz, fqdn, strlen(fqdn));
  1825. if (d == NULL || sz != strlen(expect) || strncasecmp(d, expect, sz))
  1826. applog(LOG_WARNING, "get_registered_domain \"%s\" test failed; got \"%.*s\" instead of \"%s\"",
  1827. fqdn, (int)sz, d, expect);
  1828. }
  1829. void test_domain_funcs()
  1830. {
  1831. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334");
  1832. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334/abc/abc/");
  1833. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st/abc/abc/");
  1834. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st");
  1835. _test_extract_domain("s.m.eligius.st", "http:s.m.eligius.st");
  1836. _test_extract_domain("s.m.eligius.st", "stratum+tcp:s.m.eligius.st");
  1837. _test_extract_domain("s.m.eligius.st", "stratum+tcp:s.m.eligius.st:3334");
  1838. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st:3334");
  1839. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st:3334///");
  1840. _test_extract_domain("s.m.eligius.st", "stratum+tcp://s.m.eligius.st.:3334///");
  1841. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334");
  1842. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334///");
  1843. _test_extract_domain("foohost", "foohost:3334");
  1844. _test_extract_domain("foohost", "foohost:3334///");
  1845. _test_extract_domain("foohost", "foohost:3334/abc.com//");
  1846. _test_extract_domain("", "foohost:");
  1847. _test_extract_domain("3334", "foohost://3334/abc.com//");
  1848. _test_extract_domain("192.0.2.0", "foohost:192.0.2.0");
  1849. _test_extract_domain("192.0.2.0", "192.0.2.0:3334");
  1850. _test_extract_domain("192.0.2.0", "192.0.2.0:3334///");
  1851. _test_extract_domain("2001:db8::1", "2001:db8::1");
  1852. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]");
  1853. _test_extract_domain("2001:db8::1", "http:[2001:db8::1]");
  1854. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]:42");
  1855. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]:42/abc//def/ghi");
  1856. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]");
  1857. _test_extract_domain("2001:db8::cafe", "http:[2001:db8::cafe]");
  1858. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]:42");
  1859. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]:42/abc//def/ghi");
  1860. _test_get_regd_domain("eligius.st", "s.m.eligius.st");
  1861. _test_get_regd_domain("eligius.st", "eligius.st");
  1862. _test_get_regd_domain("foohost.co.uk", "myserver.foohost.co.uk");
  1863. _test_get_regd_domain("foohost", "foohost");
  1864. _test_get_regd_domain("192.0.2.0", "192.0.2.0");
  1865. _test_get_regd_domain("2001:db8::1", "2001:db8::1");
  1866. }
  1867. struct bfg_strtobool_keyword {
  1868. bool val;
  1869. const char *keyword;
  1870. };
  1871. bool bfg_strtobool(const char * const s, char ** const endptr, __maybe_unused const int opts)
  1872. {
  1873. struct bfg_strtobool_keyword keywords[] = {
  1874. {false, "false"},
  1875. {false, "never"},
  1876. {false, "none"},
  1877. {false, "off"},
  1878. {false, "no"},
  1879. {false, "0"},
  1880. {true , "always"},
  1881. {true , "true"},
  1882. {true , "yes"},
  1883. {true , "on"},
  1884. };
  1885. const int total_keywords = sizeof(keywords) / sizeof(*keywords);
  1886. for (int i = 0; i < total_keywords; ++i)
  1887. {
  1888. const size_t kwlen = strlen(keywords[i].keyword);
  1889. if (!strncasecmp(keywords[i].keyword, s, kwlen))
  1890. {
  1891. if (endptr)
  1892. *endptr = (char*)&s[kwlen];
  1893. return keywords[i].val;
  1894. }
  1895. }
  1896. char *lend;
  1897. strtol(s, &lend, 0);
  1898. if (lend > s)
  1899. {
  1900. if (endptr)
  1901. *endptr = lend;
  1902. // Any number other than "0" is intentionally considered true, including 0x0
  1903. return true;
  1904. }
  1905. *endptr = (char*)s;
  1906. return false;
  1907. }
  1908. #define URI_FIND_PARAM_FOUND ((const char *)uri_find_param)
  1909. const char *uri_find_param(const char * const uri, const char * const param, bool * const invert_p)
  1910. {
  1911. const char *start = strchr(uri, '#');
  1912. if (invert_p)
  1913. *invert_p = false;
  1914. if (!start)
  1915. return NULL;
  1916. const char *p = start;
  1917. ++start;
  1918. nextmatch:
  1919. p = strstr(&p[1], param);
  1920. if (!p)
  1921. return NULL;
  1922. const char *q = &p[strlen(param)];
  1923. if (isCalpha(q[0]))
  1924. goto nextmatch;
  1925. if (invert_p && p - start >= 2 && (!strncasecmp(&p[-2], "no", 2)) && !isCalpha(p[-3]))
  1926. *invert_p = true;
  1927. else
  1928. if (isCalpha(p[-1]))
  1929. goto nextmatch;
  1930. if (q[0] == '=')
  1931. return &q[1];
  1932. return URI_FIND_PARAM_FOUND;
  1933. }
  1934. enum bfg_tristate uri_get_param_bool2(const char * const uri, const char * const param)
  1935. {
  1936. bool invert, foundval = true;
  1937. const char *q = uri_find_param(uri, param, &invert);
  1938. if (!q)
  1939. return BTS_UNKNOWN;
  1940. else
  1941. if (q != URI_FIND_PARAM_FOUND)
  1942. {
  1943. char *end;
  1944. bool v = bfg_strtobool(q, &end, 0);
  1945. if (end > q && !isCalpha(end[0]))
  1946. foundval = v;
  1947. }
  1948. if (invert)
  1949. foundval = !foundval;
  1950. return foundval;
  1951. }
  1952. bool uri_get_param_bool(const char * const uri, const char * const param, const bool defval)
  1953. {
  1954. const enum bfg_tristate rv = uri_get_param_bool2(uri, param);
  1955. if (rv == BTS_UNKNOWN)
  1956. return defval;
  1957. return rv;
  1958. }
  1959. static
  1960. void _test_uri_find_param(const char * const uri, const char * const param, const int expect_offset, const int expect_invert)
  1961. {
  1962. bool invert;
  1963. const char *actual = uri_find_param(uri, param, (expect_invert >= 0) ? &invert : NULL);
  1964. int actual_offset;
  1965. if (actual == URI_FIND_PARAM_FOUND)
  1966. actual_offset = -1;
  1967. else
  1968. if (!actual)
  1969. actual_offset = -2;
  1970. else
  1971. actual_offset = actual - uri;
  1972. int actual_invert = (expect_invert >= 0) ? (invert ? 1 : 0) : -1;
  1973. if (actual_offset != expect_offset || expect_invert != actual_invert)
  1974. applog(LOG_WARNING, "%s(\"%s\", \"%s\", %s) test failed (offset: expect=%d actual=%d; invert: expect=%d actual=%d)",
  1975. "uri_find_param", uri, param, (expect_invert >= 0) ? "(invert)" : "NULL",
  1976. expect_offset, actual_offset,
  1977. expect_invert, actual_invert);
  1978. }
  1979. static
  1980. void _test_uri_get_param(const char * const uri, const char * const param, const bool defval, const bool expect)
  1981. {
  1982. const bool actual = uri_get_param_bool(uri, param, defval);
  1983. if (actual != expect)
  1984. applog(LOG_WARNING, "%s(\"%s\", \"%s\", %s) test failed",
  1985. "uri_get_param_bool", uri, param, defval ? "true" : "false");
  1986. }
  1987. void test_uri_get_param()
  1988. {
  1989. _test_uri_find_param("stratum+tcp://footest/#redirect", "redirect", -1, -1);
  1990. _test_uri_find_param("stratum+tcp://footest/#redirectme", "redirect", -2, -1);
  1991. _test_uri_find_param("stratum+tcp://footest/#noredirect", "redirect", -2, -1);
  1992. _test_uri_find_param("stratum+tcp://footest/#noredirect", "redirect", -1, 1);
  1993. _test_uri_find_param("stratum+tcp://footest/#redirect", "redirect", -1, 0);
  1994. _test_uri_find_param("stratum+tcp://footest/#redirect=", "redirect", 32, -1);
  1995. _test_uri_find_param("stratum+tcp://footest/#noredirect=", "redirect", 34, 1);
  1996. _test_uri_get_param("stratum+tcp://footest/#redirect", "redirect", false, true);
  1997. _test_uri_get_param("stratum+tcp://footest/#redirectme", "redirect", false, false);
  1998. _test_uri_get_param("stratum+tcp://footest/#noredirect", "redirect", false, false);
  1999. _test_uri_get_param("stratum+tcp://footest/#redirect=0", "redirect", false, false);
  2000. _test_uri_get_param("stratum+tcp://footest/#redirect=1", "redirect", false, true);
  2001. _test_uri_get_param("stratum+tcp://footest/#redirect", "redirect", true, true);
  2002. _test_uri_get_param("stratum+tcp://footest/#redirectme", "redirect", true, true);
  2003. _test_uri_get_param("stratum+tcp://footest/#noredirect", "redirect", true, false);
  2004. _test_uri_get_param("stratum+tcp://footest/#redirect=0", "redirect", true, false);
  2005. _test_uri_get_param("stratum+tcp://footest/#redirect=1", "redirect", true, true);
  2006. _test_uri_get_param("stratum+tcp://footest/#redirect=0,foo=1", "redirect", true, false);
  2007. _test_uri_get_param("stratum+tcp://footest/#redirect=1,foo=0", "redirect", false, true);
  2008. _test_uri_get_param("stratum+tcp://footest/#foo=1,noredirect=0,foo=1", "redirect", false, true);
  2009. _test_uri_get_param("stratum+tcp://footest/#bar=0,noredirect=1,foo=0", "redirect", true, false);
  2010. _test_uri_get_param("stratum+tcp://footest/#redirect=false", "redirect", true, false);
  2011. _test_uri_get_param("stratum+tcp://footest/#redirect=no", "redirect", true, false);
  2012. _test_uri_get_param("stratum+tcp://footest/#redirect=yes", "redirect", false, true);
  2013. }
  2014. void stratum_probe_transparency(struct pool *pool)
  2015. {
  2016. // Request transaction data to discourage pools from doing anything shady
  2017. char s[1024];
  2018. int sLen;
  2019. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  2020. pool->swork.job_id,
  2021. pool->swork.job_id);
  2022. stratum_send(pool, s, sLen);
  2023. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  2024. timer_set_delay_from_now(&pool->swork.tv_transparency, 21093750L);
  2025. pool->swork.transparency_probed = true;
  2026. }
  2027. size_t script_to_address(char *out, size_t outsz, const uint8_t *script, size_t scriptsz, bool testnet)
  2028. {
  2029. char addr[35];
  2030. size_t size = sizeof(addr);
  2031. bool bok = false;
  2032. if (scriptsz == 25 && script[0] == 0x76 && script[1] == 0xa9 && script[2] == 0x14 && script[23] == 0x88 && script[24] == 0xac)
  2033. bok = b58check_enc(addr, &size, testnet ? 0x6f : 0x00, &script[3], 20);
  2034. else if (scriptsz == 23 && script[0] == 0xa9 && script[1] == 0x14 && script[22] == 0x87)
  2035. bok = b58check_enc(addr, &size, testnet ? 0xc4 : 0x05, &script[2], 20);
  2036. if (!bok)
  2037. return 0;
  2038. if (outsz >= size)
  2039. strcpy(out, addr);
  2040. return size;
  2041. }
  2042. size_t varint_decode(const uint8_t *p, size_t size, uint64_t *n)
  2043. {
  2044. if (size > 8 && p[0] == 0xff)
  2045. {
  2046. *n = upk_u64le(p, 0);
  2047. return 9;
  2048. }
  2049. if (size > 4 && p[0] == 0xfe)
  2050. {
  2051. *n = upk_u32le(p, 0);
  2052. return 5;
  2053. }
  2054. if (size > 2 && p[0] == 0xfd)
  2055. {
  2056. *n = upk_u16le(p, 0);
  2057. return 3;
  2058. }
  2059. if (size > 0)
  2060. {
  2061. *n = p[0];
  2062. return 1;
  2063. }
  2064. return 0;
  2065. }
  2066. /* Caller ensure cb_param is an valid pointer */
  2067. bool check_coinbase(const uint8_t *coinbase, size_t cbsize, const struct coinbase_param *cb_param)
  2068. {
  2069. int i;
  2070. size_t pos;
  2071. uint64_t len, total, target, amount, curr_pk_script_len;
  2072. bool found_target = false;
  2073. if (cbsize < 62)
  2074. /* Smallest possible length */
  2075. applogr(false, LOG_ERR, "Coinbase check: invalid length -- %lu", (unsigned long)cbsize);
  2076. pos = 4; /* Skip the version */
  2077. if (coinbase[pos] != 1)
  2078. applogr(false, LOG_ERR, "Coinbase check: multiple inputs in coinbase: 0x%02x", coinbase[pos]);
  2079. pos += 1 /* varint length */ + 32 /* prevhash */ + 4 /* 0xffffffff */;
  2080. if (coinbase[pos] < 2 || coinbase[pos] > 100)
  2081. applogr(false, LOG_ERR, "Coinbase check: invalid input script sig length: 0x%02x", coinbase[pos]);
  2082. pos += 1 /* varint length */ + coinbase[pos] + 4 /* 0xffffffff */;
  2083. if (cbsize <= pos)
  2084. incomplete_cb:
  2085. applogr(false, LOG_ERR, "Coinbase check: incomplete coinbase for payout check");
  2086. total = target = 0;
  2087. i = varint_decode(coinbase + pos, cbsize - pos, &len);
  2088. if (!i)
  2089. goto incomplete_cb;
  2090. pos += i;
  2091. while (len-- > 0)
  2092. {
  2093. if (cbsize <= pos + 8)
  2094. goto incomplete_cb;
  2095. amount = upk_u64le(coinbase, pos);
  2096. pos += 8; /* amount length */
  2097. total += amount;
  2098. i = varint_decode(coinbase + pos, cbsize - pos, &curr_pk_script_len);
  2099. if (!i || cbsize <= pos + i + curr_pk_script_len)
  2100. goto incomplete_cb;
  2101. pos += i;
  2102. struct bytes_hashtbl *ah = NULL;
  2103. HASH_FIND(hh, cb_param->scripts, &coinbase[pos], curr_pk_script_len, ah);
  2104. if (ah)
  2105. {
  2106. found_target = true;
  2107. target += amount;
  2108. }
  2109. if (opt_debug)
  2110. {
  2111. char s[(curr_pk_script_len * 2) + 3];
  2112. i = script_to_address(s, sizeof(s), &coinbase[pos], curr_pk_script_len, cb_param->testnet);
  2113. if (!(i && i <= sizeof(s)))
  2114. {
  2115. s[0] = '[';
  2116. bin2hex(&s[1], &coinbase[pos], curr_pk_script_len);
  2117. strcpy(&s[(curr_pk_script_len * 2) + 1], "]");
  2118. }
  2119. applog(LOG_DEBUG, "Coinbase output: %10"PRIu64" -- %s%s", amount, s, ah ? "*" : "");
  2120. }
  2121. pos += curr_pk_script_len;
  2122. }
  2123. if (total < cb_param->total)
  2124. applogr(false, LOG_ERR, "Coinbase check: lopsided total output amount = %"PRIu64", expecting >=%"PRIu64, total, cb_param->total);
  2125. if (cb_param->scripts)
  2126. {
  2127. if (cb_param->perc && !(total && (float)((double)target / total) >= cb_param->perc))
  2128. 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);
  2129. else
  2130. if (!found_target)
  2131. applogr(false, LOG_ERR, "Coinbase check: not found any target addr");
  2132. }
  2133. if (cbsize < pos + 4)
  2134. applogr(false, LOG_ERR, "Coinbase check: No room for locktime");
  2135. pos += 4;
  2136. if (opt_debug)
  2137. 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);
  2138. return true;
  2139. }
  2140. static bool parse_notify(struct pool *pool, json_t *val)
  2141. {
  2142. const char *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  2143. char *job_id;
  2144. bool clean, ret = false;
  2145. int merkles, i;
  2146. size_t cb1_len, cb2_len;
  2147. json_t *arr;
  2148. arr = json_array_get(val, 4);
  2149. if (!arr || !json_is_array(arr))
  2150. goto out;
  2151. merkles = json_array_size(arr);
  2152. for (i = 0; i < merkles; i++)
  2153. if (!json_is_string(json_array_get(arr, i)))
  2154. goto out;
  2155. prev_hash = __json_array_string(val, 1);
  2156. coinbase1 = __json_array_string(val, 2);
  2157. coinbase2 = __json_array_string(val, 3);
  2158. bbversion = __json_array_string(val, 5);
  2159. nbit = __json_array_string(val, 6);
  2160. ntime = __json_array_string(val, 7);
  2161. clean = json_is_true(json_array_get(val, 8));
  2162. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  2163. goto out;
  2164. job_id = json_array_string(val, 0);
  2165. if (!job_id)
  2166. goto out;
  2167. cg_wlock(&pool->data_lock);
  2168. cgtime(&pool->swork.tv_received);
  2169. free(pool->swork.job_id);
  2170. pool->swork.job_id = job_id;
  2171. if (pool->swork.tr)
  2172. {
  2173. tmpl_decref(pool->swork.tr);
  2174. pool->swork.tr = NULL;
  2175. }
  2176. pool->submit_old = !clean;
  2177. pool->swork.clean = true;
  2178. if (pool->next_nonce1)
  2179. {
  2180. free(pool->swork.nonce1);
  2181. pool->n1_len = strlen(pool->next_nonce1) / 2;
  2182. pool->swork.nonce1 = pool->next_nonce1;
  2183. pool->next_nonce1 = NULL;
  2184. }
  2185. int n2size = pool->swork.n2size = pool->next_n2size;
  2186. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  2187. #ifdef WORDS_BIGENDIAN
  2188. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  2189. #endif
  2190. hex2bin(&pool->swork.header1[0], bbversion, 4);
  2191. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  2192. hex2bin((void*)&pool->swork.ntime, ntime, 4);
  2193. pool->swork.ntime = be32toh(pool->swork.ntime);
  2194. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  2195. /* Nominally allow a driver to ntime roll 60 seconds */
  2196. set_simple_ntime_roll_limit(&pool->swork.ntime_roll_limits, pool->swork.ntime, 60, &pool->swork.tv_received);
  2197. cb1_len = strlen(coinbase1) / 2;
  2198. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  2199. cb2_len = strlen(coinbase2) / 2;
  2200. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->swork.n2size + cb2_len);
  2201. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  2202. hex2bin(coinbase, coinbase1, cb1_len);
  2203. hex2bin(&coinbase[cb1_len], pool->swork.nonce1, pool->n1_len);
  2204. // NOTE: gap for nonce2, filled at work generation time
  2205. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->swork.n2size], coinbase2, cb2_len);
  2206. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  2207. for (i = 0; i < merkles; i++)
  2208. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  2209. pool->swork.merkles = merkles;
  2210. pool->nonce2 = 0;
  2211. memcpy(pool->swork.target, pool->next_target, 0x20);
  2212. pool_check_coinbase(pool, coinbase, bytes_len(&pool->swork.coinbase));
  2213. cg_wunlock(&pool->data_lock);
  2214. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  2215. pool->pool_no, job_id);
  2216. if (opt_debug && opt_protocol)
  2217. {
  2218. applog(LOG_DEBUG, "job_id: %s", job_id);
  2219. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  2220. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  2221. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  2222. for (i = 0; i < merkles; i++)
  2223. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  2224. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  2225. applog(LOG_DEBUG, "nbit: %s", nbit);
  2226. applog(LOG_DEBUG, "ntime: %s", ntime);
  2227. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  2228. }
  2229. /* A notify message is the closest stratum gets to a getwork */
  2230. pool->getwork_requested++;
  2231. total_getworks++;
  2232. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  2233. if (pool->probed)
  2234. stratum_probe_transparency(pool);
  2235. ret = true;
  2236. out:
  2237. return ret;
  2238. }
  2239. static bool parse_diff(struct pool *pool, json_t *val)
  2240. {
  2241. double diff;
  2242. diff = json_number_value(json_array_get(val, 0));
  2243. if (diff == 0)
  2244. return false;
  2245. if ((int64_t)diff != diff)
  2246. {
  2247. // Assume fractional values are proper bdiff per specification
  2248. // Allow integers to be interpreted as pdiff, since the difference is trivial and some pools see it this way
  2249. diff = bdiff_to_pdiff(diff);
  2250. }
  2251. if ((!opt_scrypt) && diff < 1 && diff > 0.999)
  2252. diff = 1;
  2253. #ifdef USE_SCRYPT
  2254. // Broken Scrypt pools multiply difficulty by 0x10000
  2255. const double broken_scrypt_diff_multiplier = 0x10000;
  2256. /* 7/12/2014: P2Pool code was fixed: https://github.com/forrestv/p2pool/pull/210
  2257. 7/15/2014: Popular pools unfixed: wemineltc, dogehouse, p2pool.org
  2258. Cannot find a broken Scrypt pool that will dispense diff lower than 16 */
  2259. // Ideally pools will fix their implementation and we can remove this
  2260. // This should suffice until miners are hashing Scrypt at ~1-7 Gh/s (based on a share rate target of 10-60s)
  2261. const double minimum_broken_scrypt_diff = 16;
  2262. // Diff 16 at 1.15 Gh/s = 1 share / 60s
  2263. // Diff 16 at 7.00 Gh/s = 1 share / 10s
  2264. if (opt_scrypt && (diff >= minimum_broken_scrypt_diff))
  2265. diff /= broken_scrypt_diff_multiplier;
  2266. #endif
  2267. cg_wlock(&pool->data_lock);
  2268. set_target_to_pdiff(pool->next_target, diff);
  2269. cg_wunlock(&pool->data_lock);
  2270. applog(LOG_DEBUG, "Pool %d stratum difficulty set to %g", pool->pool_no, diff);
  2271. return true;
  2272. }
  2273. static
  2274. bool stratum_set_extranonce(struct pool * const pool, json_t * const val, json_t * const params)
  2275. {
  2276. char *nonce1 = NULL;
  2277. int n2size = 0;
  2278. json_t *j;
  2279. if (!json_is_array(params))
  2280. goto err;
  2281. switch (json_array_size(params))
  2282. {
  2283. default: // >=2
  2284. // n2size
  2285. j = json_array_get(params, 1);
  2286. if (json_is_number(j))
  2287. {
  2288. n2size = json_integer_value(j);
  2289. if (n2size < 1)
  2290. goto err;
  2291. }
  2292. else
  2293. if (!json_is_null(j))
  2294. goto err;
  2295. // fallthru
  2296. case 1:
  2297. // nonce1
  2298. j = json_array_get(params, 0);
  2299. if (json_is_string(j))
  2300. nonce1 = strdup(json_string_value(j));
  2301. else
  2302. if (!json_is_null(j))
  2303. goto err;
  2304. break;
  2305. case 0:
  2306. applog(LOG_WARNING, "Pool %u: No-op mining.set_extranonce?", pool->pool_no);
  2307. return true;
  2308. }
  2309. cg_wlock(&pool->data_lock);
  2310. if (nonce1)
  2311. {
  2312. free(pool->next_nonce1);
  2313. pool->next_nonce1 = nonce1;
  2314. }
  2315. if (n2size)
  2316. pool->next_n2size = n2size;
  2317. cg_wunlock(&pool->data_lock);
  2318. return true;
  2319. err:
  2320. applog(LOG_ERR, "Pool %u: Invalid mining.set_extranonce", pool->pool_no);
  2321. json_t *id = json_object_get(val, "id");
  2322. if (id && !json_is_null(id))
  2323. {
  2324. char s[RBUFSIZE], *idstr;
  2325. idstr = json_dumps_ANY(id, 0);
  2326. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [20, \"Invalid params\"]}", idstr);
  2327. free(idstr);
  2328. stratum_send(pool, s, strlen(s));
  2329. }
  2330. return true;
  2331. }
  2332. static bool parse_reconnect(struct pool *pool, json_t *val)
  2333. {
  2334. if (opt_disable_client_reconnect)
  2335. return false;
  2336. const char *url;
  2337. char address[256];
  2338. json_t *port_json;
  2339. url = __json_array_string(val, 0);
  2340. if (!url)
  2341. url = pool->sockaddr_url;
  2342. else
  2343. if (!pool_may_redirect_to(pool, url))
  2344. return false;
  2345. port_json = json_array_get(val, 1);
  2346. if (json_is_number(port_json))
  2347. {
  2348. const unsigned port = json_number_value(port_json);
  2349. snprintf(address, sizeof(address), "%s:%u", url, port);
  2350. }
  2351. else
  2352. {
  2353. const char *port;
  2354. if (json_is_string(port_json))
  2355. port = json_string_value(port_json);
  2356. else
  2357. port = pool->stratum_port;
  2358. snprintf(address, sizeof(address), "%s:%s", url, port);
  2359. }
  2360. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  2361. return false;
  2362. pool->stratum_url = pool->sockaddr_url;
  2363. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  2364. if (!restart_stratum(pool))
  2365. return false;
  2366. return true;
  2367. }
  2368. static bool send_version(struct pool *pool, json_t *val)
  2369. {
  2370. char s[RBUFSIZE], *idstr;
  2371. json_t *id = json_object_get(val, "id");
  2372. if (!(id && !json_is_null(id)))
  2373. return false;
  2374. idstr = json_dumps_ANY(id, 0);
  2375. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  2376. free(idstr);
  2377. if (!stratum_send(pool, s, strlen(s)))
  2378. return false;
  2379. return true;
  2380. }
  2381. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  2382. {
  2383. char *msg;
  2384. char s[RBUFSIZE], *idstr;
  2385. json_t *id = json_object_get(val, "id");
  2386. msg = json_array_string(params, 0);
  2387. if (likely(msg))
  2388. {
  2389. free(pool->admin_msg);
  2390. pool->admin_msg = msg;
  2391. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  2392. }
  2393. if (!(id && !json_is_null(id)))
  2394. return true;
  2395. idstr = json_dumps_ANY(id, 0);
  2396. if (likely(msg))
  2397. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  2398. else
  2399. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  2400. free(idstr);
  2401. if (!stratum_send(pool, s, strlen(s)))
  2402. return false;
  2403. return true;
  2404. }
  2405. bool parse_method(struct pool *pool, char *s)
  2406. {
  2407. json_t *val = NULL, *method, *err_val, *params;
  2408. json_error_t err;
  2409. bool ret = false;
  2410. const char *buf;
  2411. if (!s)
  2412. goto out;
  2413. val = JSON_LOADS(s, &err);
  2414. if (!val) {
  2415. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2416. goto out;
  2417. }
  2418. method = json_object_get(val, "method");
  2419. if (!method)
  2420. goto out;
  2421. err_val = json_object_get(val, "error");
  2422. params = json_object_get(val, "params");
  2423. if (err_val && !json_is_null(err_val)) {
  2424. char *ss;
  2425. if (err_val)
  2426. ss = json_dumps(err_val, JSON_INDENT(3));
  2427. else
  2428. ss = strdup("(unknown reason)");
  2429. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  2430. free(ss);
  2431. goto out;
  2432. }
  2433. buf = json_string_value(method);
  2434. if (!buf)
  2435. goto out;
  2436. if (!strncasecmp(buf, "mining.notify", 13)) {
  2437. if (parse_notify(pool, params))
  2438. pool->stratum_notify = ret = true;
  2439. else
  2440. pool->stratum_notify = ret = false;
  2441. goto out;
  2442. }
  2443. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  2444. ret = true;
  2445. goto out;
  2446. }
  2447. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  2448. ret = true;
  2449. goto out;
  2450. }
  2451. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  2452. ret = true;
  2453. goto out;
  2454. }
  2455. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  2456. ret = true;
  2457. goto out;
  2458. }
  2459. if (!strncasecmp(buf, "mining.set_extranonce", 21) && stratum_set_extranonce(pool, val, params)) {
  2460. ret = true;
  2461. goto out;
  2462. }
  2463. out:
  2464. if (val)
  2465. json_decref(val);
  2466. return ret;
  2467. }
  2468. extern bool parse_stratum_response(struct pool *, char *s);
  2469. bool auth_stratum(struct pool *pool)
  2470. {
  2471. json_t *val = NULL, *res_val, *err_val;
  2472. char s[RBUFSIZE], *sret = NULL;
  2473. json_error_t err;
  2474. bool ret = false;
  2475. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  2476. pool->rpc_user, pool->rpc_pass);
  2477. if (!stratum_send(pool, s, strlen(s)))
  2478. goto out;
  2479. /* Parse all data in the queue and anything left should be auth */
  2480. while (42) {
  2481. sret = recv_line(pool);
  2482. if (!sret)
  2483. goto out;
  2484. if (parse_method(pool, sret))
  2485. free(sret);
  2486. else
  2487. {
  2488. bool unknown = true;
  2489. val = JSON_LOADS(sret, &err);
  2490. json_t *j_id = json_object_get(val, "id");
  2491. if (json_is_string(j_id))
  2492. {
  2493. if (!strcmp(json_string_value(j_id), "auth"))
  2494. break;
  2495. else
  2496. if (!strcmp(json_string_value(j_id), "xnsub"))
  2497. unknown = false;
  2498. }
  2499. if (unknown)
  2500. applog(LOG_WARNING, "Pool %u: Unknown stratum msg: %s", pool->pool_no, sret);
  2501. free(sret);
  2502. }
  2503. }
  2504. free(sret);
  2505. res_val = json_object_get(val, "result");
  2506. err_val = json_object_get(val, "error");
  2507. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2508. char *ss;
  2509. if (err_val)
  2510. ss = json_dumps(err_val, JSON_INDENT(3));
  2511. else
  2512. ss = strdup("(unknown reason)");
  2513. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  2514. free(ss);
  2515. goto out;
  2516. }
  2517. ret = true;
  2518. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  2519. pool->probed = true;
  2520. successful_connect = true;
  2521. out:
  2522. if (val)
  2523. json_decref(val);
  2524. if (pool->stratum_notify)
  2525. stratum_probe_transparency(pool);
  2526. return ret;
  2527. }
  2528. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  2529. {
  2530. struct pool *pool = clientp;
  2531. curl_socket_t sck = bfg_socket(addr->family, addr->socktype, addr->protocol);
  2532. pool->sock = sck;
  2533. return sck;
  2534. }
  2535. static bool setup_stratum_curl(struct pool *pool)
  2536. {
  2537. CURL *curl = NULL;
  2538. char s[RBUFSIZE];
  2539. bool ret = false;
  2540. bool tls_only = false, try_tls = true;
  2541. bool tlsca = uri_get_param_bool(pool->rpc_url, "tlsca", false);
  2542. {
  2543. const enum bfg_tristate tlsparam = uri_get_param_bool2(pool->rpc_url, "tls");
  2544. if (tlsparam != BTS_UNKNOWN)
  2545. try_tls = tls_only = tlsparam;
  2546. else
  2547. if (tlsca)
  2548. // If tlsca is enabled, require TLS by default
  2549. tls_only = true;
  2550. }
  2551. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  2552. mutex_lock(&pool->stratum_lock);
  2553. timer_unset(&pool->swork.tv_transparency);
  2554. pool->stratum_active = false;
  2555. pool->stratum_notify = false;
  2556. pool->swork.transparency_probed = false;
  2557. if (pool->stratum_curl)
  2558. curl_easy_cleanup(pool->stratum_curl);
  2559. pool->stratum_curl = curl_easy_init();
  2560. if (unlikely(!pool->stratum_curl))
  2561. quithere(1, "Failed to curl_easy_init");
  2562. if (pool->sockbuf)
  2563. pool->sockbuf[0] = '\0';
  2564. curl = pool->stratum_curl;
  2565. if (!pool->sockbuf) {
  2566. pool->sockbuf = calloc(RBUFSIZE, 1);
  2567. if (!pool->sockbuf)
  2568. quithere(1, "Failed to calloc pool sockbuf");
  2569. pool->sockbuf_size = RBUFSIZE;
  2570. }
  2571. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  2572. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  2573. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, pool->curl_err_str);
  2574. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  2575. if (!opt_delaynet)
  2576. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  2577. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  2578. * to enable it */
  2579. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  2580. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  2581. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2582. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  2583. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  2584. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  2585. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  2586. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, (long)(tlsca ? 2 : 0));
  2587. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, (long)(tlsca ? 1 : 0));
  2588. if (pool->rpc_proxy) {
  2589. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  2590. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  2591. } else if (opt_socks_proxy) {
  2592. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  2593. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  2594. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  2595. }
  2596. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  2597. retry:
  2598. /* Create a http url for use with curl */
  2599. sprintf(s, "http%s://%s:%s", try_tls ? "s" : "",
  2600. pool->sockaddr_url, pool->stratum_port);
  2601. curl_easy_setopt(curl, CURLOPT_URL, s);
  2602. pool->sock = INVSOCK;
  2603. if (curl_easy_perform(curl)) {
  2604. if (try_tls)
  2605. {
  2606. applog(LOG_DEBUG, "Stratum connect failed with TLS to pool %u: %s",
  2607. pool->pool_no, pool->curl_err_str);
  2608. if (!tls_only)
  2609. {
  2610. try_tls = false;
  2611. goto retry;
  2612. }
  2613. }
  2614. else
  2615. applog(LOG_INFO, "Stratum connect failed to pool %d: %s",
  2616. pool->pool_no, pool->curl_err_str);
  2617. errout:
  2618. curl_easy_cleanup(curl);
  2619. pool->stratum_curl = NULL;
  2620. goto out;
  2621. }
  2622. if (pool->sock == INVSOCK)
  2623. {
  2624. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  2625. goto errout;
  2626. }
  2627. keep_sockalive(pool->sock);
  2628. pool->cgminer_pool_stats.times_sent++;
  2629. pool->cgminer_pool_stats.times_received++;
  2630. ret = true;
  2631. out:
  2632. mutex_unlock(&pool->stratum_lock);
  2633. return ret;
  2634. }
  2635. static char *get_sessionid(json_t *val)
  2636. {
  2637. char *ret = NULL;
  2638. json_t *arr_val;
  2639. int arrsize, i;
  2640. arr_val = json_array_get(val, 0);
  2641. if (!arr_val || !json_is_array(arr_val))
  2642. goto out;
  2643. arrsize = json_array_size(arr_val);
  2644. for (i = 0; i < arrsize; i++) {
  2645. json_t *arr = json_array_get(arr_val, i);
  2646. const char *notify;
  2647. if (!arr | !json_is_array(arr))
  2648. break;
  2649. notify = __json_array_string(arr, 0);
  2650. if (!notify)
  2651. continue;
  2652. if (!strncasecmp(notify, "mining.notify", 13)) {
  2653. ret = json_array_string(arr, 1);
  2654. break;
  2655. }
  2656. }
  2657. out:
  2658. return ret;
  2659. }
  2660. void suspend_stratum(struct pool *pool)
  2661. {
  2662. clear_sockbuf(pool);
  2663. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2664. mutex_lock(&pool->stratum_lock);
  2665. pool->stratum_active = pool->stratum_notify = false;
  2666. if (pool->stratum_curl) {
  2667. curl_easy_cleanup(pool->stratum_curl);
  2668. }
  2669. pool->stratum_curl = NULL;
  2670. pool->sock = INVSOCK;
  2671. mutex_unlock(&pool->stratum_lock);
  2672. }
  2673. bool initiate_stratum(struct pool *pool)
  2674. {
  2675. bool ret = false, recvd = false, noresume = false, sockd = false;
  2676. bool trysuggest = request_target_str;
  2677. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  2678. json_t *val = NULL, *res_val, *err_val;
  2679. json_error_t err;
  2680. int n2size;
  2681. resend:
  2682. if (!setup_stratum_curl(pool)) {
  2683. sockd = false;
  2684. goto out;
  2685. }
  2686. sockd = true;
  2687. clear_sock(pool);
  2688. if (trysuggest)
  2689. {
  2690. int sz = sprintf(s, "{\"id\": null, \"method\": \"mining.suggest_target\", \"params\": [\"%s\"]}", request_target_str);
  2691. if (!_stratum_send(pool, s, sz, true))
  2692. {
  2693. applog(LOG_DEBUG, "Pool %u: Failed to send suggest_target in initiate_stratum", pool->pool_no);
  2694. goto out;
  2695. }
  2696. recvd = true;
  2697. }
  2698. if (noresume) {
  2699. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2700. } else {
  2701. if (pool->sessionid)
  2702. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2703. else
  2704. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  2705. }
  2706. if (!_stratum_send(pool, s, strlen(s), true)) {
  2707. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2708. goto out;
  2709. }
  2710. recvd = true;
  2711. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2712. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2713. goto out;
  2714. }
  2715. sret = recv_line(pool);
  2716. if (!sret)
  2717. goto out;
  2718. val = JSON_LOADS(sret, &err);
  2719. free(sret);
  2720. if (!val) {
  2721. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2722. goto out;
  2723. }
  2724. res_val = json_object_get(val, "result");
  2725. err_val = json_object_get(val, "error");
  2726. if (!res_val || json_is_null(res_val) ||
  2727. (err_val && !json_is_null(err_val))) {
  2728. char *ss;
  2729. if (err_val)
  2730. ss = json_dumps(err_val, JSON_INDENT(3));
  2731. else
  2732. ss = strdup("(unknown reason)");
  2733. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2734. free(ss);
  2735. goto out;
  2736. }
  2737. sessionid = get_sessionid(res_val);
  2738. if (!sessionid)
  2739. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2740. nonce1 = json_array_string(res_val, 1);
  2741. if (!nonce1) {
  2742. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  2743. free(sessionid);
  2744. goto out;
  2745. }
  2746. n2size = json_integer_value(json_array_get(res_val, 2));
  2747. if (n2size < 1)
  2748. {
  2749. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  2750. free(sessionid);
  2751. free(nonce1);
  2752. goto out;
  2753. }
  2754. cg_wlock(&pool->data_lock);
  2755. free(pool->sessionid);
  2756. pool->sessionid = sessionid;
  2757. free(pool->next_nonce1);
  2758. pool->next_nonce1 = nonce1;
  2759. pool->next_n2size = n2size;
  2760. cg_wunlock(&pool->data_lock);
  2761. if (sessionid)
  2762. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2763. ret = true;
  2764. out:
  2765. if (val)
  2766. {
  2767. json_decref(val);
  2768. val = NULL;
  2769. }
  2770. if (ret) {
  2771. if (!pool->stratum_url)
  2772. pool->stratum_url = pool->sockaddr_url;
  2773. pool->stratum_active = true;
  2774. set_target_to_pdiff(pool->next_target, 1);
  2775. if (opt_protocol) {
  2776. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2777. pool->pool_no, pool->next_nonce1, pool->next_n2size);
  2778. }
  2779. if (uri_get_param_bool(pool->rpc_url, "xnsub", false))
  2780. {
  2781. sprintf(s, "{\"id\": \"xnsub\", \"method\": \"mining.extranonce.subscribe\", \"params\": []}");
  2782. _stratum_send(pool, s, strlen(s), true);
  2783. }
  2784. } else {
  2785. if (recvd)
  2786. {
  2787. if (trysuggest)
  2788. {
  2789. applog(LOG_DEBUG, "Pool %u: Failed to connect stratum with mining.suggest_target, retrying without", pool->pool_no);
  2790. trysuggest = false;
  2791. goto resend;
  2792. }
  2793. if (!noresume)
  2794. {
  2795. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2796. noresume = true;
  2797. goto resend;
  2798. }
  2799. }
  2800. applog(LOG_DEBUG, "Initiate stratum failed");
  2801. if (sockd)
  2802. suspend_stratum(pool);
  2803. }
  2804. return ret;
  2805. }
  2806. bool restart_stratum(struct pool *pool)
  2807. {
  2808. bool ret = true;
  2809. mutex_lock(&pool->pool_test_lock);
  2810. if (pool->stratum_active)
  2811. suspend_stratum(pool);
  2812. if (!initiate_stratum(pool))
  2813. return_via(out, ret = false);
  2814. if (!auth_stratum(pool))
  2815. return_via(out, ret = false);
  2816. out:
  2817. mutex_unlock(&pool->pool_test_lock);
  2818. return ret;
  2819. }
  2820. void dev_error_update(struct cgpu_info *dev, enum dev_reason reason)
  2821. {
  2822. dev->device_last_not_well = time(NULL);
  2823. cgtime(&dev->tv_device_last_not_well);
  2824. dev->device_not_well_reason = reason;
  2825. }
  2826. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2827. {
  2828. dev_error_update(dev, reason);
  2829. switch (reason) {
  2830. case REASON_THREAD_FAIL_INIT:
  2831. dev->thread_fail_init_count++;
  2832. break;
  2833. case REASON_THREAD_ZERO_HASH:
  2834. dev->thread_zero_hash_count++;
  2835. break;
  2836. case REASON_THREAD_FAIL_QUEUE:
  2837. dev->thread_fail_queue_count++;
  2838. break;
  2839. case REASON_DEV_SICK_IDLE_60:
  2840. dev->dev_sick_idle_60_count++;
  2841. break;
  2842. case REASON_DEV_DEAD_IDLE_600:
  2843. dev->dev_dead_idle_600_count++;
  2844. break;
  2845. case REASON_DEV_NOSTART:
  2846. dev->dev_nostart_count++;
  2847. break;
  2848. case REASON_DEV_OVER_HEAT:
  2849. dev->dev_over_heat_count++;
  2850. break;
  2851. case REASON_DEV_THERMAL_CUTOFF:
  2852. dev->dev_thermal_cutoff_count++;
  2853. break;
  2854. case REASON_DEV_COMMS_ERROR:
  2855. dev->dev_comms_error_count++;
  2856. break;
  2857. case REASON_DEV_THROTTLE:
  2858. dev->dev_throttle_count++;
  2859. break;
  2860. }
  2861. }
  2862. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2863. void *realloc_strcat(char *ptr, char *s)
  2864. {
  2865. size_t old = strlen(ptr), len = strlen(s);
  2866. char *ret;
  2867. if (!len)
  2868. return ptr;
  2869. len += old + 1;
  2870. align_len(&len);
  2871. ret = malloc(len);
  2872. if (unlikely(!ret))
  2873. quithere(1, "Failed to malloc");
  2874. sprintf(ret, "%s%s", ptr, s);
  2875. free(ptr);
  2876. return ret;
  2877. }
  2878. static
  2879. bool sanechars[] = {
  2880. false, false, false, false, false, false, false, false,
  2881. false, false, false, false, false, false, false, false,
  2882. false, false, false, false, false, false, false, false,
  2883. false, false, false, false, false, false, false, false,
  2884. false, false, false, false, false, false, false, false,
  2885. false, false, false, false, false, true , false, false,
  2886. true , true , true , true , true , true , true , true ,
  2887. true , true , false, false, false, false, false, false,
  2888. false, true , true , true , true , true , true , true ,
  2889. true , true , true , true , true , true , true , true ,
  2890. true , true , true , true , true , true , true , true ,
  2891. true , true , true , false, false, false, false, false,
  2892. false, true , true , true , true , true , true , true ,
  2893. true , true , true , true , true , true , true , true ,
  2894. true , true , true , true , true , true , true , true ,
  2895. true , true , true , false, false, false, false, false,
  2896. };
  2897. char *sanestr(char *o, char *s)
  2898. {
  2899. char *rv = o;
  2900. bool br = false;
  2901. for ( ; s[0]; ++s)
  2902. {
  2903. if (sanechars[s[0] & 0x7f])
  2904. {
  2905. if (br)
  2906. {
  2907. br = false;
  2908. if (s[0] >= '0' && s[0] <= '9')
  2909. (o++)[0] = '_';
  2910. }
  2911. (o++)[0] = s[0];
  2912. }
  2913. else
  2914. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  2915. br = true;
  2916. }
  2917. o[0] = '\0';
  2918. return rv;
  2919. }
  2920. void RenameThread(const char* name)
  2921. {
  2922. #if defined(PR_SET_NAME)
  2923. // Only the first 15 characters are used (16 - NUL terminator)
  2924. prctl(PR_SET_NAME, name, 0, 0, 0);
  2925. #elif defined(__APPLE__)
  2926. pthread_setname_np(name);
  2927. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2928. pthread_set_name_np(pthread_self(), name);
  2929. #else
  2930. // Prevent warnings for unused parameters...
  2931. (void)name;
  2932. #endif
  2933. }
  2934. static pthread_key_t key_bfgtls;
  2935. struct bfgtls_data {
  2936. char *bfg_strerror_result;
  2937. size_t bfg_strerror_resultsz;
  2938. #ifdef WIN32
  2939. LPSTR bfg_strerror_socketresult;
  2940. #endif
  2941. #ifdef NEED_BFG_LOWL_VCOM
  2942. struct detectone_meta_info_t __detectone_meta_info;
  2943. #endif
  2944. unsigned probe_result_flags;
  2945. };
  2946. static
  2947. struct bfgtls_data *get_bfgtls()
  2948. {
  2949. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  2950. if (bfgtls)
  2951. return bfgtls;
  2952. void *p;
  2953. bfgtls = malloc(sizeof(*bfgtls));
  2954. if (!bfgtls)
  2955. quithere(1, "malloc bfgtls failed");
  2956. p = malloc(64);
  2957. if (!p)
  2958. quithere(1, "malloc bfg_strerror_result failed");
  2959. *bfgtls = (struct bfgtls_data){
  2960. .bfg_strerror_resultsz = 64,
  2961. .bfg_strerror_result = p,
  2962. };
  2963. if (pthread_setspecific(key_bfgtls, bfgtls))
  2964. quithere(1, "pthread_setspecific failed");
  2965. return bfgtls;
  2966. }
  2967. static
  2968. void bfgtls_free(void * const p)
  2969. {
  2970. struct bfgtls_data * const bfgtls = p;
  2971. free(bfgtls->bfg_strerror_result);
  2972. #ifdef WIN32
  2973. if (bfgtls->bfg_strerror_socketresult)
  2974. LocalFree(bfgtls->bfg_strerror_socketresult);
  2975. #endif
  2976. free(bfgtls);
  2977. }
  2978. #ifdef NEED_BFG_LOWL_VCOM
  2979. struct detectone_meta_info_t *_detectone_meta_info()
  2980. {
  2981. return &get_bfgtls()->__detectone_meta_info;
  2982. }
  2983. #endif
  2984. unsigned *_bfg_probe_result_flags()
  2985. {
  2986. return &get_bfgtls()->probe_result_flags;
  2987. }
  2988. void bfg_init_threadlocal()
  2989. {
  2990. if (pthread_key_create(&key_bfgtls, bfgtls_free))
  2991. quithere(1, "pthread_key_create failed");
  2992. }
  2993. static
  2994. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  2995. {
  2996. if (minimum <= *bufszp)
  2997. return false;
  2998. while (minimum > *bufszp)
  2999. *bufszp = 2;
  3000. *bufp = realloc(*bufp, *bufszp);
  3001. if (unlikely(!*bufp))
  3002. quithere(1, "realloc failed");
  3003. return true;
  3004. }
  3005. static
  3006. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  3007. {
  3008. if (!src)
  3009. return NULL;
  3010. const size_t srcsz = strlen(src) + 1;
  3011. bfg_grow_buffer(bufp, bufszp, srcsz);
  3012. memcpy(*bufp, src, srcsz);
  3013. return *bufp;
  3014. }
  3015. // Guaranteed to always return some string (or quit)
  3016. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  3017. {
  3018. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  3019. struct bfgtls_data *bfgtls = get_bfgtls();
  3020. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  3021. char ** const bufp = &bfgtls->bfg_strerror_result;
  3022. const char *have = NULL;
  3023. switch (type) {
  3024. case BST_LIBUSB:
  3025. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  3026. #ifdef HAVE_LIBUSB
  3027. # if HAVE_DECL_LIBUSB_ERROR_NAME
  3028. // libusb makes no guarantees for thread-safety or persistence
  3029. mutex_lock(&mutex);
  3030. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  3031. mutex_unlock(&mutex);
  3032. # endif
  3033. #endif
  3034. break;
  3035. case BST_SOCKET:
  3036. case BST_SYSTEM:
  3037. {
  3038. #ifdef WIN32
  3039. // Windows has a different namespace for system and socket errors
  3040. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  3041. if (*msg)
  3042. LocalFree(*msg);
  3043. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  3044. {
  3045. LPSTR msgp = *msg;
  3046. size_t n = strlen(msgp);
  3047. while (isCspace(msgp[--n]))
  3048. msgp[n] = '\0';
  3049. return *msg;
  3050. }
  3051. *msg = NULL;
  3052. break;
  3053. #endif
  3054. }
  3055. // Fallthru on non-WIN32
  3056. case BST_ERRNO:
  3057. {
  3058. #ifdef __STRERROR_S_WORKS
  3059. // FIXME: Not sure how to get this on MingW64
  3060. retry:
  3061. if (likely(!strerror_s(*bufp, *bufszp, e)))
  3062. {
  3063. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  3064. goto retry;
  3065. return *bufp;
  3066. }
  3067. // TODO: XSI strerror_r
  3068. // TODO: GNU strerror_r
  3069. #else
  3070. mutex_lock(&mutex);
  3071. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  3072. mutex_unlock(&mutex);
  3073. #endif
  3074. }
  3075. }
  3076. if (have)
  3077. return *bufp;
  3078. // Failback: Stringify the number
  3079. static const char fmt[] = "%s error #%d", *typestr;
  3080. switch (type) {
  3081. case BST_ERRNO:
  3082. typestr = "System";
  3083. break;
  3084. case BST_SOCKET:
  3085. typestr = "Socket";
  3086. break;
  3087. case BST_LIBUSB:
  3088. typestr = "libusb";
  3089. break;
  3090. default:
  3091. typestr = "Unexpected";
  3092. }
  3093. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  3094. bfg_grow_buffer(bufp, bufszp, sz);
  3095. sprintf(*bufp, fmt, typestr, e);
  3096. return *bufp;
  3097. }
  3098. void notifier_init(notifier_t pipefd)
  3099. {
  3100. #ifdef WIN32
  3101. #define WindowsErrorStr(e) bfg_strerror(e, BST_SOCKET)
  3102. SOCKET listener, connecter, acceptor;
  3103. listener = bfg_socket(AF_INET, SOCK_STREAM, 0);
  3104. if (listener == INVALID_SOCKET)
  3105. quit(1, "Failed to create listener socket"IN_FMT_FFL": %s",
  3106. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3107. connecter = bfg_socket(AF_INET, SOCK_STREAM, 0);
  3108. if (connecter == INVALID_SOCKET)
  3109. quit(1, "Failed to create connect socket"IN_FMT_FFL": %s",
  3110. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3111. struct sockaddr_in inaddr = {
  3112. .sin_family = AF_INET,
  3113. .sin_addr = {
  3114. .s_addr = htonl(INADDR_LOOPBACK),
  3115. },
  3116. .sin_port = 0,
  3117. };
  3118. {
  3119. static const int reuse = 1;
  3120. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
  3121. }
  3122. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  3123. quit(1, "Failed to bind listener socket"IN_FMT_FFL": %s",
  3124. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3125. socklen_t inaddr_sz = sizeof(inaddr);
  3126. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  3127. quit(1, "Failed to getsockname"IN_FMT_FFL": %s",
  3128. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3129. if (listen(listener, 1) == SOCKET_ERROR)
  3130. quit(1, "Failed to listen"IN_FMT_FFL": %s",
  3131. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3132. inaddr.sin_family = AF_INET;
  3133. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3134. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  3135. quit(1, "Failed to connect"IN_FMT_FFL": %s",
  3136. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3137. acceptor = accept(listener, NULL, NULL);
  3138. if (acceptor == INVALID_SOCKET)
  3139. quit(1, "Failed to accept"IN_FMT_FFL": %s",
  3140. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  3141. closesocket(listener);
  3142. pipefd[0] = connecter;
  3143. pipefd[1] = acceptor;
  3144. #else
  3145. if (pipe(pipefd))
  3146. quithere(1, "Failed to create pipe");
  3147. #endif
  3148. }
  3149. void *bfg_slurp_file(void * const bufp, size_t bufsz, const char * const filename)
  3150. {
  3151. char *buf = bufp;
  3152. FILE * const F = fopen(filename, "r");
  3153. if (!F)
  3154. goto err;
  3155. if (!buf)
  3156. {
  3157. fseek(F, 0, SEEK_END);
  3158. const long filesz = ftell(F);
  3159. if (unlikely(filesz < 0))
  3160. {
  3161. fclose(F);
  3162. goto err;
  3163. }
  3164. rewind(F);
  3165. bufsz = filesz + 1;
  3166. buf = malloc(bufsz);
  3167. }
  3168. const size_t rsz = fread(buf, 1, bufsz - 1, F);
  3169. fclose(F);
  3170. buf[rsz] = '\0';
  3171. return buf;
  3172. err:
  3173. if (buf)
  3174. buf[0] = '\0';
  3175. return NULL;
  3176. }
  3177. void notifier_wake(notifier_t fd)
  3178. {
  3179. if (fd[1] == INVSOCK)
  3180. return;
  3181. if (1 !=
  3182. #ifdef WIN32
  3183. send(fd[1], "\0", 1, 0)
  3184. #else
  3185. write(fd[1], "\0", 1)
  3186. #endif
  3187. )
  3188. applog(LOG_WARNING, "Error trying to wake notifier");
  3189. }
  3190. void notifier_read(notifier_t fd)
  3191. {
  3192. char buf[0x10];
  3193. #ifdef WIN32
  3194. IGNORE_RETURN_VALUE(recv(fd[0], buf, sizeof(buf), 0));
  3195. #else
  3196. IGNORE_RETURN_VALUE(read(fd[0], buf, sizeof(buf)));
  3197. #endif
  3198. }
  3199. bool notifier_wait(notifier_t notifier, const struct timeval *tvp_timeout)
  3200. {
  3201. struct timeval tv_now, tv_timeout;
  3202. fd_set rfds;
  3203. int e;
  3204. while (true)
  3205. {
  3206. FD_ZERO(&rfds);
  3207. FD_SET(notifier[0], &rfds);
  3208. tv_timeout = *tvp_timeout;
  3209. timer_set_now(&tv_now);
  3210. e = select(notifier[0]+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now));
  3211. if (e > 0)
  3212. return true;
  3213. if (e == 0)
  3214. return false;
  3215. }
  3216. }
  3217. bool notifier_wait_us(notifier_t notifier, const unsigned long long usecs)
  3218. {
  3219. struct timeval tv_timeout = TIMEVAL_USECS(usecs);
  3220. return notifier_wait(notifier, &tv_timeout);
  3221. }
  3222. void notifier_reset(notifier_t notifier)
  3223. {
  3224. fd_set rfds;
  3225. struct timeval tv_timeout = { .tv_sec = 0, };
  3226. FD_ZERO(&rfds);
  3227. FD_SET(notifier[0], &rfds);
  3228. while (select(notifier[0]+1, &rfds, NULL, NULL, &tv_timeout) != 0)
  3229. notifier_read(notifier);
  3230. }
  3231. void notifier_init_invalid(notifier_t fd)
  3232. {
  3233. fd[0] = fd[1] = INVSOCK;
  3234. }
  3235. void notifier_destroy(notifier_t fd)
  3236. {
  3237. #ifdef WIN32
  3238. closesocket(fd[0]);
  3239. closesocket(fd[1]);
  3240. #else
  3241. close(fd[0]);
  3242. close(fd[1]);
  3243. #endif
  3244. fd[0] = fd[1] = INVSOCK;
  3245. }
  3246. void _bytes_alloc_failure(size_t sz)
  3247. {
  3248. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  3249. }
  3250. char *trimmed_strdup(const char *s)
  3251. {
  3252. size_t n;
  3253. char *c;
  3254. while (isspace(s[0]))
  3255. ++s;
  3256. n = strlen(s) - 1;
  3257. while (isspace(s[n]))
  3258. --n;
  3259. ++n;
  3260. c = malloc(n + 1);
  3261. c[n] = '\0';
  3262. memcpy(c, s, n);
  3263. return c;
  3264. }
  3265. void *cmd_thread(void *cmdp)
  3266. {
  3267. const char *cmd = cmdp;
  3268. applog(LOG_DEBUG, "Executing command: %s", cmd);
  3269. int rc = system(cmd);
  3270. if (rc)
  3271. applog(LOG_WARNING, "Command returned %d exit code: %s", rc, cmd);
  3272. return NULL;
  3273. }
  3274. void run_cmd(const char *cmd)
  3275. {
  3276. if (!cmd)
  3277. return;
  3278. pthread_t pth;
  3279. pthread_create(&pth, NULL, cmd_thread, (void*)cmd);
  3280. }
  3281. uint8_t crc5usb(unsigned char *ptr, uint8_t len)
  3282. {
  3283. uint8_t i, j, k;
  3284. uint8_t crc = 0x1f;
  3285. uint8_t crcin[5] = {1, 1, 1, 1, 1};
  3286. uint8_t crcout[5] = {1, 1, 1, 1, 1};
  3287. uint8_t din = 0;
  3288. j = 0x80;
  3289. k = 0;
  3290. for (i = 0; i < len; i++)
  3291. {
  3292. if (*ptr & j)
  3293. din = 1;
  3294. else
  3295. din = 0;
  3296. crcout[0] = crcin[4] ^ din;
  3297. crcout[1] = crcin[0];
  3298. crcout[2] = crcin[1] ^ crcin[4] ^ din;
  3299. crcout[3] = crcin[2];
  3300. crcout[4] = crcin[3];
  3301. j = j >> 1;
  3302. k++;
  3303. if (k == 8)
  3304. {
  3305. j = 0x80;
  3306. k = 0;
  3307. ptr++;
  3308. }
  3309. memcpy(crcin, crcout, 5);
  3310. }
  3311. crc = 0;
  3312. if(crcin[4])
  3313. crc |= 0x10;
  3314. if(crcin[3])
  3315. crc |= 0x08;
  3316. if(crcin[2])
  3317. crc |= 0x04;
  3318. if(crcin[1])
  3319. crc |= 0x02;
  3320. if(crcin[0])
  3321. crc |= 0x01;
  3322. return crc;
  3323. }
  3324. static uint8_t _crc8ccitt_table[0x100];
  3325. void bfg_init_checksums(void)
  3326. {
  3327. for (int i = 0; i < 0x100; ++i)
  3328. {
  3329. uint8_t crc = i;
  3330. for (int j = 0; j < 8; ++j)
  3331. crc = (crc << 1) ^ ((crc & 0x80) ? 7 : 0);
  3332. _crc8ccitt_table[i] = crc & 0xff;
  3333. }
  3334. }
  3335. uint8_t crc8ccitt(const void * const buf, const size_t buflen)
  3336. {
  3337. const uint8_t *p = buf;
  3338. uint8_t crc = 0xff;
  3339. for (int i = 0; i < buflen; ++i)
  3340. crc = _crc8ccitt_table[crc ^ *p++];
  3341. return crc;
  3342. }
  3343. static uint16_t crc16tab[] = {
  3344. 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
  3345. 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
  3346. 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
  3347. 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
  3348. 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
  3349. 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
  3350. 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
  3351. 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
  3352. 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
  3353. 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
  3354. 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
  3355. 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
  3356. 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
  3357. 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
  3358. 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
  3359. 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
  3360. 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
  3361. 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
  3362. 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
  3363. 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
  3364. 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
  3365. 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
  3366. 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
  3367. 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
  3368. 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
  3369. 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
  3370. 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
  3371. 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
  3372. 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
  3373. 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
  3374. 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
  3375. 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0,
  3376. };
  3377. static
  3378. uint16_t crc16_floating(uint16_t next_byte, uint16_t seed)
  3379. {
  3380. return ((seed << 8) ^ crc16tab[(seed >> 8) ^ next_byte]) & 0xFFFF;
  3381. }
  3382. uint16_t crc16(const void *p, size_t sz, uint16_t crc)
  3383. {
  3384. const uint8_t * const s = p;
  3385. for (size_t i = 0; i < sz; ++i)
  3386. crc = crc16_floating(s[i], crc);
  3387. return crc;
  3388. }