util.c 103 KB

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