util.c 101 KB

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