util.c 96 KB

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