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. #include "version.h"
  62. #define DEFAULT_SOCKWAIT 60
  63. bool successful_connect = false;
  64. struct timeval nettime;
  65. struct data_buffer {
  66. void *buf;
  67. size_t len;
  68. curl_socket_t *idlemarker;
  69. };
  70. struct upload_buffer {
  71. const void *buf;
  72. size_t len;
  73. size_t pos;
  74. };
  75. struct header_info {
  76. char *lp_path;
  77. int rolltime;
  78. char *reason;
  79. char *stratum_url;
  80. bool hadrolltime;
  81. bool canroll;
  82. bool hadexpire;
  83. };
  84. struct tq_ent {
  85. void *data;
  86. struct tq_ent *prev;
  87. struct tq_ent *next;
  88. };
  89. static void databuf_free(struct data_buffer *db)
  90. {
  91. if (!db)
  92. return;
  93. free(db->buf);
  94. #ifdef DEBUG_DATABUF
  95. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  96. #endif
  97. memset(db, 0, sizeof(*db));
  98. }
  99. struct json_rpc_call_state {
  100. struct data_buffer all_data;
  101. struct header_info hi;
  102. void *priv;
  103. char curl_err_str[CURL_ERROR_SIZE];
  104. struct curl_slist *headers;
  105. struct upload_buffer upload_data;
  106. struct pool *pool;
  107. bool longpoll;
  108. };
  109. // aka data_buffer_write
  110. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  111. void *user_data)
  112. {
  113. struct data_buffer *db = user_data;
  114. size_t oldlen, newlen;
  115. oldlen = db->len;
  116. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  117. return 0;
  118. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  119. nmemb = (SIZE_MAX - oldlen) / size;
  120. size_t len = size * nmemb;
  121. void *newmem;
  122. static const unsigned char zero = 0;
  123. if (db->idlemarker) {
  124. const unsigned char *cptr = ptr;
  125. for (size_t i = 0; i < len; ++i)
  126. if (!(isCspace(cptr[i]) || cptr[i] == '{')) {
  127. *db->idlemarker = CURL_SOCKET_BAD;
  128. db->idlemarker = NULL;
  129. break;
  130. }
  131. }
  132. newlen = oldlen + len;
  133. newmem = realloc(db->buf, newlen + 1);
  134. #ifdef DEBUG_DATABUF
  135. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  136. #endif
  137. if (!newmem)
  138. return 0;
  139. db->buf = newmem;
  140. db->len = newlen;
  141. memcpy(db->buf + oldlen, ptr, len);
  142. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  143. return nmemb;
  144. }
  145. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  146. void *user_data)
  147. {
  148. struct json_rpc_call_state * const state = user_data;
  149. struct upload_buffer * const ub = &state->upload_data;
  150. unsigned int len = size * nmemb;
  151. if (state->longpoll)
  152. {
  153. struct pool * const pool = state->pool;
  154. pool->lp_active = true;
  155. }
  156. if (len > ub->len - ub->pos)
  157. len = ub->len - ub->pos;
  158. if (len) {
  159. memcpy(ptr, ub->buf + ub->pos, len);
  160. ub->pos += len;
  161. }
  162. return len;
  163. }
  164. #if LIBCURL_VERSION_NUM >= 0x071200
  165. static int seek_data_cb(void *user_data, curl_off_t offset, int origin)
  166. {
  167. struct json_rpc_call_state * const state = user_data;
  168. struct upload_buffer * const ub = &state->upload_data;
  169. switch (origin) {
  170. case SEEK_SET:
  171. if (offset < 0 || offset > ub->len)
  172. return 1;
  173. ub->pos = offset;
  174. break;
  175. case SEEK_CUR:
  176. // Check the offset is valid, taking care to avoid overflows or negative unsigned numbers
  177. if (offset < 0 && ub->pos < (size_t)-offset)
  178. return 1;
  179. if (ub->len < offset)
  180. return 1;
  181. if (ub->pos > ub->len - offset)
  182. return 1;
  183. ub->pos += offset;
  184. break;
  185. case SEEK_END:
  186. if (offset > 0 || (size_t)-offset > ub->len)
  187. return 1;
  188. ub->pos = ub->len + offset;
  189. break;
  190. default:
  191. return 1; /* CURL_SEEKFUNC_FAIL */
  192. }
  193. return 0; /* CURL_SEEKFUNC_OK */
  194. }
  195. #endif
  196. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  197. {
  198. struct header_info *hi = user_data;
  199. size_t remlen, slen, ptrlen = size * nmemb;
  200. char *rem, *val = NULL, *key = NULL;
  201. void *tmp;
  202. val = calloc(1, ptrlen);
  203. key = calloc(1, ptrlen);
  204. if (!key || !val)
  205. goto out;
  206. tmp = memchr(ptr, ':', ptrlen);
  207. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  208. goto out;
  209. slen = tmp - ptr;
  210. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  211. goto out;
  212. memcpy(key, ptr, slen); /* store & nul term key */
  213. key[slen] = 0;
  214. rem = ptr + slen + 1; /* trim value's leading whitespace */
  215. remlen = ptrlen - slen - 1;
  216. while ((remlen > 0) && (isCspace(*rem))) {
  217. remlen--;
  218. rem++;
  219. }
  220. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  221. val[remlen] = 0;
  222. while ((*val) && (isCspace(val[strlen(val) - 1])))
  223. val[strlen(val) - 1] = 0;
  224. if (!*val) /* skip blank value */
  225. goto out;
  226. if (opt_protocol)
  227. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  228. if (!strcasecmp("X-Roll-Ntime", key)) {
  229. hi->hadrolltime = true;
  230. if (!strncasecmp("N", val, 1))
  231. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  232. else {
  233. hi->canroll = true;
  234. /* Check to see if expire= is supported and if not, set
  235. * the rolltime to the default scantime */
  236. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  237. sscanf(val + 7, "%d", &hi->rolltime);
  238. hi->hadexpire = true;
  239. } else
  240. hi->rolltime = opt_scantime;
  241. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  242. }
  243. }
  244. if (!strcasecmp("X-Long-Polling", key)) {
  245. hi->lp_path = val; /* steal memory reference */
  246. val = NULL;
  247. }
  248. if (!strcasecmp("X-Reject-Reason", key)) {
  249. hi->reason = val; /* steal memory reference */
  250. val = NULL;
  251. }
  252. if (!strcasecmp("X-Stratum", key)) {
  253. hi->stratum_url = val;
  254. val = NULL;
  255. }
  256. out:
  257. free(key);
  258. free(val);
  259. return ptrlen;
  260. }
  261. static int keep_sockalive(SOCKETTYPE fd)
  262. {
  263. const int tcp_one = 1;
  264. const int tcp_keepidle = 45;
  265. const int tcp_keepintvl = 30;
  266. int ret = 0;
  267. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one))))
  268. ret = 1;
  269. #ifndef WIN32
  270. int flags = fcntl(fd, F_GETFL, 0);
  271. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  272. #else
  273. u_long flags = 1;
  274. ioctlsocket(fd, FIONBIO, &flags);
  275. #endif
  276. if (!opt_delaynet)
  277. #ifndef __linux
  278. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  279. #else /* __linux */
  280. if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  281. #endif /* __linux */
  282. ret = 1;
  283. #ifdef __linux
  284. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one))))
  285. ret = 1;
  286. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  287. ret = 1;
  288. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  289. ret = 1;
  290. #endif /* __linux */
  291. #ifdef __APPLE_CC__
  292. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  293. ret = 1;
  294. #endif /* __APPLE_CC__ */
  295. #ifdef WIN32
  296. const int zero = 0;
  297. struct tcp_keepalive vals;
  298. vals.onoff = 1;
  299. vals.keepalivetime = tcp_keepidle * 1000;
  300. vals.keepaliveinterval = tcp_keepintvl * 1000;
  301. DWORD outputBytes;
  302. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  303. ret = 1;
  304. /* Windows happily submits indefinitely to the send buffer blissfully
  305. * unaware nothing is getting there without gracefully failing unless
  306. * we disable the send buffer */
  307. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  308. ret = 1;
  309. #endif /* WIN32 */
  310. return ret;
  311. }
  312. void set_cloexec_socket(SOCKETTYPE sock, const bool cloexec)
  313. {
  314. #ifdef WIN32
  315. SetHandleInformation((HANDLE)sock, HANDLE_FLAG_INHERIT, cloexec ? 0 : HANDLE_FLAG_INHERIT);
  316. #elif defined(F_GETFD) && defined(F_SETFD) && defined(O_CLOEXEC)
  317. const int curflags = fcntl(sock, F_GETFD);
  318. int flags = curflags;
  319. if (cloexec)
  320. flags |= FD_CLOEXEC;
  321. else
  322. flags &= ~FD_CLOEXEC;
  323. if (flags != curflags)
  324. fcntl(sock, F_SETFD, flags);
  325. #endif
  326. }
  327. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  328. curlsocktype __maybe_unused purpose)
  329. {
  330. return keep_sockalive(fd);
  331. }
  332. static void last_nettime(struct timeval *last)
  333. {
  334. rd_lock(&netacc_lock);
  335. last->tv_sec = nettime.tv_sec;
  336. last->tv_usec = nettime.tv_usec;
  337. rd_unlock(&netacc_lock);
  338. }
  339. static void set_nettime(void)
  340. {
  341. wr_lock(&netacc_lock);
  342. cgtime(&nettime);
  343. wr_unlock(&netacc_lock);
  344. }
  345. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  346. char *data, size_t size,
  347. void *userdata)
  348. {
  349. struct pool *pool = (struct pool *)userdata;
  350. switch(type) {
  351. case CURLINFO_HEADER_IN:
  352. case CURLINFO_DATA_IN:
  353. case CURLINFO_SSL_DATA_IN:
  354. pool->cgminer_pool_stats.bytes_received += size;
  355. total_bytes_rcvd += size;
  356. pool->cgminer_pool_stats.net_bytes_received += size;
  357. break;
  358. case CURLINFO_HEADER_OUT:
  359. case CURLINFO_DATA_OUT:
  360. case CURLINFO_SSL_DATA_OUT:
  361. pool->cgminer_pool_stats.bytes_sent += size;
  362. total_bytes_sent += size;
  363. pool->cgminer_pool_stats.net_bytes_sent += size;
  364. break;
  365. case CURLINFO_TEXT:
  366. {
  367. if (!opt_protocol)
  368. break;
  369. // data is not null-terminated, so we need to copy and terminate it for applog
  370. char datacp[size + 1];
  371. memcpy(datacp, data, size);
  372. while (likely(size) && unlikely(isCspace(datacp[size-1])))
  373. --size;
  374. if (unlikely(!size))
  375. break;
  376. datacp[size] = '\0';
  377. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  378. break;
  379. }
  380. default:
  381. break;
  382. }
  383. return 0;
  384. }
  385. void json_rpc_call_async(CURL *curl, const char *url,
  386. const char *userpass, const char *rpc_req,
  387. bool longpoll,
  388. struct pool *pool, bool share,
  389. void *priv)
  390. {
  391. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  392. *state = (struct json_rpc_call_state){
  393. .priv = priv,
  394. .pool = pool,
  395. };
  396. long timeout = longpoll ? (60 * 60) : 60;
  397. char len_hdr[64], user_agent_hdr[128];
  398. struct curl_slist *headers = NULL;
  399. if (longpoll)
  400. {
  401. state->all_data.idlemarker = &pool->lp_socket;
  402. state->longpoll = true;
  403. }
  404. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  405. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  406. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  407. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  408. * to enable it */
  409. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  410. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  411. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  412. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  413. curl_easy_setopt(curl, CURLOPT_URL, url);
  414. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  415. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  416. /* Shares are staggered already and delays in submission can be costly
  417. * so do not delay them */
  418. if (!opt_delaynet || share)
  419. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  420. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  421. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  422. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  423. curl_easy_setopt(curl, CURLOPT_READDATA, state);
  424. #if LIBCURL_VERSION_NUM >= 0x071200
  425. curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, &seek_data_cb);
  426. curl_easy_setopt(curl, CURLOPT_SEEKDATA, state);
  427. #endif
  428. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  429. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  430. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  431. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  432. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  433. if (pool->rpc_proxy) {
  434. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  435. } else if (opt_socks_proxy) {
  436. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  437. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  438. }
  439. if (userpass) {
  440. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  441. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  442. }
  443. if (longpoll)
  444. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  445. curl_easy_setopt(curl, CURLOPT_POST, 1);
  446. if (opt_protocol)
  447. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  448. state->upload_data.buf = rpc_req;
  449. state->upload_data.len = strlen(rpc_req);
  450. state->upload_data.pos = 0;
  451. sprintf(len_hdr, "Content-Length: %lu",
  452. (unsigned long) state->upload_data.len);
  453. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  454. headers = curl_slist_append(headers,
  455. "Content-type: application/json");
  456. headers = curl_slist_append(headers,
  457. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  458. if (longpoll)
  459. headers = curl_slist_append(headers,
  460. "X-Minimum-Wait: 0");
  461. if (likely(global_hashrate)) {
  462. char ghashrate[255];
  463. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  464. headers = curl_slist_append(headers, ghashrate);
  465. }
  466. headers = curl_slist_append(headers, len_hdr);
  467. headers = curl_slist_append(headers, user_agent_hdr);
  468. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  469. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  470. state->headers = headers;
  471. if (opt_delaynet) {
  472. /* Don't delay share submission, but still track the nettime */
  473. if (!share) {
  474. long long now_msecs, last_msecs;
  475. struct timeval now, last;
  476. cgtime(&now);
  477. last_nettime(&last);
  478. now_msecs = (long long)now.tv_sec * 1000;
  479. now_msecs += now.tv_usec / 1000;
  480. last_msecs = (long long)last.tv_sec * 1000;
  481. last_msecs += last.tv_usec / 1000;
  482. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  483. struct timespec rgtp;
  484. rgtp.tv_sec = 0;
  485. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  486. nanosleep(&rgtp, NULL);
  487. }
  488. }
  489. set_nettime();
  490. }
  491. }
  492. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  493. {
  494. struct json_rpc_call_state *state;
  495. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, (void*)&state) != CURLE_OK) {
  496. applog(LOG_ERR, "Failed to get private curl data");
  497. if (out_priv)
  498. *(void**)out_priv = NULL;
  499. goto err_out;
  500. }
  501. if (out_priv)
  502. *(void**)out_priv = state->priv;
  503. json_t *val, *err_val, *res_val;
  504. json_error_t err;
  505. struct pool *pool = state->pool;
  506. bool probing = probe && !pool->probed;
  507. if (rc) {
  508. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  509. goto err_out;
  510. }
  511. if (!state->all_data.buf) {
  512. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  513. goto err_out;
  514. }
  515. pool->cgminer_pool_stats.times_sent++;
  516. pool->cgminer_pool_stats.times_received++;
  517. if (probing) {
  518. pool->probed = true;
  519. /* If X-Long-Polling was found, activate long polling */
  520. if (state->hi.lp_path) {
  521. if (pool->hdr_path != NULL)
  522. free(pool->hdr_path);
  523. pool->hdr_path = state->hi.lp_path;
  524. } else
  525. pool->hdr_path = NULL;
  526. if (state->hi.stratum_url) {
  527. pool->stratum_url = state->hi.stratum_url;
  528. state->hi.stratum_url = NULL;
  529. }
  530. } else {
  531. if (state->hi.lp_path) {
  532. free(state->hi.lp_path);
  533. state->hi.lp_path = NULL;
  534. }
  535. if (state->hi.stratum_url) {
  536. free(state->hi.stratum_url);
  537. state->hi.stratum_url = NULL;
  538. }
  539. }
  540. if (pool->force_rollntime)
  541. {
  542. state->hi.canroll = true;
  543. state->hi.hadexpire = true;
  544. state->hi.rolltime = pool->force_rollntime;
  545. }
  546. if (rolltime)
  547. *rolltime = state->hi.rolltime;
  548. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  549. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  550. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  551. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  552. val = JSON_LOADS(state->all_data.buf, &err);
  553. if (!val) {
  554. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  555. if (opt_protocol)
  556. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  557. goto err_out;
  558. }
  559. if (opt_protocol) {
  560. char *s = json_dumps(val, JSON_INDENT(3));
  561. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  562. free(s);
  563. }
  564. /* JSON-RPC valid response returns a non-null 'result',
  565. * and a null 'error'.
  566. */
  567. res_val = json_object_get(val, "result");
  568. err_val = json_object_get(val, "error");
  569. if (!res_val ||(err_val && !json_is_null(err_val))) {
  570. char *s;
  571. if (err_val)
  572. s = json_dumps(err_val, JSON_INDENT(3));
  573. else
  574. s = strdup("(unknown reason)");
  575. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  576. free(s);
  577. json_decref(val);
  578. goto err_out;
  579. }
  580. if (state->hi.reason) {
  581. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  582. free(state->hi.reason);
  583. state->hi.reason = NULL;
  584. }
  585. successful_connect = true;
  586. databuf_free(&state->all_data);
  587. curl_slist_free_all(state->headers);
  588. curl_easy_reset(curl);
  589. free(state);
  590. return val;
  591. err_out:
  592. databuf_free(&state->all_data);
  593. curl_slist_free_all(state->headers);
  594. curl_easy_reset(curl);
  595. if (!successful_connect)
  596. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  597. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  598. free(state);
  599. return NULL;
  600. }
  601. json_t *json_rpc_call(CURL *curl, const char *url,
  602. const char *userpass, const char *rpc_req,
  603. bool probe, bool longpoll, int *rolltime,
  604. struct pool *pool, bool share)
  605. {
  606. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  607. int rc = curl_easy_perform(curl);
  608. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  609. }
  610. bool our_curl_supports_proxy_uris()
  611. {
  612. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  613. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  614. }
  615. // NOTE: This assumes reference URI is a root
  616. char *absolute_uri(char *uri, const char *ref)
  617. {
  618. if (strstr(uri, "://"))
  619. return strdup(uri);
  620. char *copy_start, *abs;
  621. bool need_slash = false;
  622. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  623. if (ref[strlen(ref) - 1] != '/')
  624. need_slash = true;
  625. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  626. if (!abs) {
  627. applog(LOG_ERR, "Malloc failure in absolute_uri");
  628. return NULL;
  629. }
  630. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  631. return abs;
  632. }
  633. static const char _hexchars[0x10] = "0123456789abcdef";
  634. void bin2hex(char *out, const void *in, size_t len)
  635. {
  636. const unsigned char *p = in;
  637. while (len--)
  638. {
  639. (out++)[0] = _hexchars[p[0] >> 4];
  640. (out++)[0] = _hexchars[p[0] & 0xf];
  641. ++p;
  642. }
  643. out[0] = '\0';
  644. }
  645. static inline
  646. int _hex2bin_char(const char c)
  647. {
  648. if (c >= '0' && c <= '9')
  649. return c - '0';
  650. if (c >= 'a' && c <= 'f')
  651. return (c - 'a') + 10;
  652. if (c >= 'A' && c <= 'F')
  653. return (c - 'A') + 10;
  654. return -1;
  655. }
  656. /* Does the reverse of bin2hex but does not allocate any ram */
  657. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  658. {
  659. int n, o;
  660. while (len--)
  661. {
  662. n = _hex2bin_char((hexstr++)[0]);
  663. if (unlikely(n == -1))
  664. {
  665. badchar:
  666. if (!hexstr[-1])
  667. applog(LOG_ERR, "hex2bin: str truncated");
  668. else
  669. applog(LOG_ERR, "hex2bin: invalid character 0x%02x", (int)hexstr[-1]);
  670. return false;
  671. }
  672. o = _hex2bin_char((hexstr++)[0]);
  673. if (unlikely(o == -1))
  674. goto badchar;
  675. (p++)[0] = (n << 4) | o;
  676. }
  677. return likely(!hexstr[0]);
  678. }
  679. size_t ucs2_to_utf8(char * const out, const uint16_t * const in, const size_t sz)
  680. {
  681. uint8_t *p = (void*)out;
  682. for (int i = 0; i < sz; ++i)
  683. {
  684. const uint16_t c = in[i];
  685. if (c < 0x80)
  686. p++[0] = c;
  687. else
  688. {
  689. if (c < 0x800)
  690. p++[0] = 0xc0 | (c >> 6);
  691. else
  692. {
  693. p++[0] = 0xe0 | (c >> 12);
  694. p++[0] = 0x80 | ((c >> 6) & 0x3f);
  695. }
  696. p++[0] = 0x80 | (c & 0x3f);
  697. }
  698. }
  699. return p - (uint8_t*)(void*)out;
  700. }
  701. char *ucs2_to_utf8_dup(uint16_t * const in, size_t sz)
  702. {
  703. char * const out = malloc((sz * 4) + 1);
  704. sz = ucs2_to_utf8(out, in, sz);
  705. out[sz] = '\0';
  706. return out;
  707. }
  708. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  709. void real_block_target(unsigned char *target, const unsigned char *data)
  710. {
  711. uint8_t targetshift;
  712. if (unlikely(data[72] < 3 || data[72] > 0x20))
  713. {
  714. // Invalid (out of bounds) target
  715. memset(target, 0xff, 32);
  716. return;
  717. }
  718. targetshift = data[72] - 3;
  719. memset(target, 0, targetshift);
  720. target[targetshift++] = data[75];
  721. target[targetshift++] = data[74];
  722. target[targetshift++] = data[73];
  723. memset(&target[targetshift], 0, 0x20 - targetshift);
  724. }
  725. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  726. {
  727. const uint32_t *h32 = (uint32_t*)&hash[0];
  728. const uint32_t *t32 = (uint32_t*)&target[0];
  729. for (int i = 7; i >= 0; --i) {
  730. uint32_t h32i = le32toh(h32[i]);
  731. uint32_t t32i = le32toh(t32[i]);
  732. if (h32i > t32i)
  733. return false;
  734. if (h32i < t32i)
  735. return true;
  736. }
  737. return true;
  738. }
  739. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  740. {
  741. bool rc;
  742. rc = hash_target_check(hash, target);
  743. if (opt_debug) {
  744. unsigned char hash_swap[32], target_swap[32];
  745. char hash_str[65];
  746. char target_str[65];
  747. for (int i = 0; i < 32; ++i) {
  748. hash_swap[i] = hash[31-i];
  749. target_swap[i] = target[31-i];
  750. }
  751. bin2hex(hash_str, hash_swap, 32);
  752. bin2hex(target_str, target_swap, 32);
  753. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  754. hash_str,
  755. target_str,
  756. rc ? "YES (hash <= target)" :
  757. "no (false positive; hash > target)");
  758. }
  759. return rc;
  760. }
  761. struct thread_q *tq_new(void)
  762. {
  763. struct thread_q *tq;
  764. tq = calloc(1, sizeof(*tq));
  765. if (!tq)
  766. return NULL;
  767. pthread_mutex_init(&tq->mutex, NULL);
  768. pthread_cond_init(&tq->cond, bfg_condattr);
  769. return tq;
  770. }
  771. void tq_free(struct thread_q *tq)
  772. {
  773. struct tq_ent *ent, *iter;
  774. if (!tq)
  775. return;
  776. DL_FOREACH_SAFE(tq->q, ent, iter) {
  777. DL_DELETE(tq->q, ent);
  778. free(ent);
  779. }
  780. pthread_cond_destroy(&tq->cond);
  781. pthread_mutex_destroy(&tq->mutex);
  782. memset(tq, 0, sizeof(*tq)); /* poison */
  783. free(tq);
  784. }
  785. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  786. {
  787. mutex_lock(&tq->mutex);
  788. tq->frozen = frozen;
  789. pthread_cond_signal(&tq->cond);
  790. mutex_unlock(&tq->mutex);
  791. }
  792. void tq_freeze(struct thread_q *tq)
  793. {
  794. tq_freezethaw(tq, true);
  795. }
  796. void tq_thaw(struct thread_q *tq)
  797. {
  798. tq_freezethaw(tq, false);
  799. }
  800. bool tq_push(struct thread_q *tq, void *data)
  801. {
  802. struct tq_ent *ent;
  803. bool rc = true;
  804. ent = calloc(1, sizeof(*ent));
  805. if (!ent)
  806. return false;
  807. ent->data = data;
  808. mutex_lock(&tq->mutex);
  809. if (!tq->frozen) {
  810. DL_APPEND(tq->q, ent);
  811. } else {
  812. free(ent);
  813. rc = false;
  814. }
  815. pthread_cond_signal(&tq->cond);
  816. mutex_unlock(&tq->mutex);
  817. return rc;
  818. }
  819. void *tq_pop(struct thread_q * const tq)
  820. {
  821. struct tq_ent *ent;
  822. void *rval = NULL;
  823. int rc;
  824. mutex_lock(&tq->mutex);
  825. if (tq->q)
  826. goto pop;
  827. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  828. if (rc)
  829. goto out;
  830. if (!tq->q)
  831. goto out;
  832. pop:
  833. ent = tq->q;
  834. rval = ent->data;
  835. DL_DELETE(tq->q, ent);
  836. free(ent);
  837. out:
  838. mutex_unlock(&tq->mutex);
  839. return rval;
  840. }
  841. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  842. {
  843. int rv = pthread_create(&thr->pth, attr, start, arg);
  844. if (likely(!rv))
  845. thr->has_pth = true;
  846. return rv;
  847. }
  848. void thr_info_freeze(struct thr_info *thr)
  849. {
  850. struct tq_ent *ent, *iter;
  851. struct thread_q *tq;
  852. if (!thr)
  853. return;
  854. tq = thr->q;
  855. if (!tq)
  856. return;
  857. mutex_lock(&tq->mutex);
  858. tq->frozen = true;
  859. DL_FOREACH_SAFE(tq->q, ent, iter) {
  860. DL_DELETE(tq->q, ent);
  861. free(ent);
  862. }
  863. mutex_unlock(&tq->mutex);
  864. }
  865. void thr_info_cancel(struct thr_info *thr)
  866. {
  867. if (!thr)
  868. return;
  869. if (thr->has_pth) {
  870. pthread_cancel(thr->pth);
  871. thr->has_pth = false;
  872. }
  873. }
  874. #ifndef HAVE_PTHREAD_CANCEL
  875. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  876. enum pthread_cancel_workaround_mode {
  877. PCWM_DEFAULT = 0,
  878. PCWM_TERMINATE = 1,
  879. PCWM_ASYNC = 2,
  880. PCWM_DISABLED = 4,
  881. PCWM_CANCELLED = 8,
  882. };
  883. static pthread_key_t key_pcwm;
  884. struct sigaction pcwm_orig_term_handler;
  885. static
  886. void do_pthread_cancel_exit(int flags)
  887. {
  888. if (!(flags & PCWM_ASYNC))
  889. // NOTE: Logging disables cancel while mutex held, so this is safe
  890. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  891. pthread_exit(PTHREAD_CANCELED);
  892. }
  893. static
  894. void sighandler_pthread_cancel(int sig)
  895. {
  896. int flags = (int)pthread_getspecific(key_pcwm);
  897. if (flags & PCWM_TERMINATE) // Main thread
  898. {
  899. // Restore original handler and call it
  900. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  901. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  902. raise(SIGTERM);
  903. quit(1, "pthread_cancel workaround: Original handler returned");
  904. }
  905. if (flags & PCWM_CANCELLED) // Already pending cancel
  906. return;
  907. if (flags & PCWM_DISABLED)
  908. {
  909. flags |= PCWM_CANCELLED;
  910. if (pthread_setspecific(key_pcwm, (void*)flags))
  911. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  912. return;
  913. }
  914. do_pthread_cancel_exit(flags);
  915. }
  916. void pthread_testcancel(void)
  917. {
  918. int flags = (int)pthread_getspecific(key_pcwm);
  919. if (flags & PCWM_CANCELLED && !(flags & PCWM_DISABLED))
  920. do_pthread_cancel_exit(flags);
  921. }
  922. int pthread_setcancelstate(int state, int *oldstate)
  923. {
  924. int flags = (int)pthread_getspecific(key_pcwm);
  925. if (oldstate)
  926. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  927. if (state == PTHREAD_CANCEL_DISABLE)
  928. flags |= PCWM_DISABLED;
  929. else
  930. {
  931. if (flags & PCWM_CANCELLED)
  932. do_pthread_cancel_exit(flags);
  933. flags &= ~PCWM_DISABLED;
  934. }
  935. if (pthread_setspecific(key_pcwm, (void*)flags))
  936. return -1;
  937. return 0;
  938. }
  939. int pthread_setcanceltype(int type, int *oldtype)
  940. {
  941. int flags = (int)pthread_getspecific(key_pcwm);
  942. if (oldtype)
  943. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  944. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  945. flags |= PCWM_ASYNC;
  946. else
  947. flags &= ~PCWM_ASYNC;
  948. if (pthread_setspecific(key_pcwm, (void*)flags))
  949. return -1;
  950. return 0;
  951. }
  952. void setup_pthread_cancel_workaround()
  953. {
  954. if (pthread_key_create(&key_pcwm, NULL))
  955. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  956. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  957. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  958. struct sigaction new_sigact = {
  959. .sa_handler = sighandler_pthread_cancel,
  960. };
  961. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  962. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  963. }
  964. #endif
  965. static void _now_gettimeofday(struct timeval *);
  966. static void _cgsleep_us_r_nanosleep(cgtimer_t *, int64_t);
  967. #ifdef HAVE_POOR_GETTIMEOFDAY
  968. static struct timeval tv_timeofday_offset;
  969. static struct timeval _tv_timeofday_lastchecked;
  970. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  971. static
  972. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  973. {
  974. struct timeval actual, delta;
  975. timeradd(expected, &tv_timeofday_offset, expected);
  976. _now_gettimeofday(&actual);
  977. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  978. // Within reason - no change necessary
  979. return;
  980. timersub(&actual, expected, &delta);
  981. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  982. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  983. *expected = actual;
  984. }
  985. void bfg_gettimeofday(struct timeval *out)
  986. {
  987. char buf[64] = "";
  988. timer_set_now(out);
  989. mutex_lock(&_tv_timeofday_mutex);
  990. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  991. bfg_calibrate_timeofday(out, buf);
  992. else
  993. timeradd(out, &tv_timeofday_offset, out);
  994. mutex_unlock(&_tv_timeofday_mutex);
  995. if (unlikely(buf[0]))
  996. applog(LOG_WARNING, "%s", buf);
  997. }
  998. #endif
  999. #ifdef WIN32
  1000. static LARGE_INTEGER _perffreq;
  1001. static
  1002. void _now_queryperformancecounter(struct timeval *tv)
  1003. {
  1004. LARGE_INTEGER now;
  1005. if (unlikely(!QueryPerformanceCounter(&now)))
  1006. quit(1, "QueryPerformanceCounter failed");
  1007. *tv = (struct timeval){
  1008. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  1009. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  1010. };
  1011. }
  1012. #endif
  1013. static void bfg_init_time();
  1014. static
  1015. void _now_is_not_set(__maybe_unused struct timeval *tv)
  1016. {
  1017. bfg_init_time();
  1018. timer_set_now(tv);
  1019. }
  1020. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  1021. void (*cgsleep_us_r)(cgtimer_t *, int64_t) = _cgsleep_us_r_nanosleep;
  1022. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1023. static clockid_t bfg_timer_clk;
  1024. static
  1025. void _now_clock_gettime(struct timeval *tv)
  1026. {
  1027. struct timespec ts;
  1028. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  1029. quit(1, "clock_gettime failed");
  1030. *tv = (struct timeval){
  1031. .tv_sec = ts.tv_sec,
  1032. .tv_usec = ts.tv_nsec / 1000,
  1033. };
  1034. }
  1035. #ifdef HAVE_CLOCK_NANOSLEEP
  1036. static
  1037. void _cgsleep_us_r_monotonic(cgtimer_t *tv_start, int64_t us)
  1038. {
  1039. struct timeval tv_end[1];
  1040. struct timespec ts_end[1];
  1041. int ret;
  1042. timer_set_delay(tv_end, tv_start, us);
  1043. timeval_to_spec(ts_end, tv_end);
  1044. do {
  1045. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  1046. } while (ret == EINTR);
  1047. }
  1048. #endif
  1049. static
  1050. bool _bfg_try_clock_gettime(clockid_t clk)
  1051. {
  1052. struct timespec ts;
  1053. if (clock_gettime(clk, &ts))
  1054. return false;
  1055. bfg_timer_clk = clk;
  1056. timer_set_now = _now_clock_gettime;
  1057. return true;
  1058. }
  1059. #endif
  1060. pthread_condattr_t *bfg_condattr_()
  1061. {
  1062. return NULL;
  1063. }
  1064. static
  1065. void bfg_init_time()
  1066. {
  1067. if (timer_set_now != _now_is_not_set)
  1068. return;
  1069. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1070. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1071. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1072. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1073. else
  1074. #endif
  1075. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1076. {
  1077. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1078. #ifdef HAVE_CLOCK_NANOSLEEP
  1079. cgsleep_us_r = _cgsleep_us_r_monotonic;
  1080. #endif
  1081. }
  1082. else
  1083. #endif
  1084. #ifdef WIN32
  1085. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1086. {
  1087. timer_set_now = _now_queryperformancecounter;
  1088. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1089. }
  1090. else
  1091. #endif
  1092. {
  1093. timer_set_now = _now_gettimeofday;
  1094. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1095. }
  1096. #ifdef HAVE_POOR_GETTIMEOFDAY
  1097. char buf[64] = "";
  1098. struct timeval tv;
  1099. timer_set_now(&tv);
  1100. bfg_calibrate_timeofday(&tv, buf);
  1101. applog(LOG_DEBUG, "%s", buf);
  1102. #endif
  1103. }
  1104. void subtime(struct timeval *a, struct timeval *b)
  1105. {
  1106. timersub(a, b, b);
  1107. }
  1108. void addtime(struct timeval *a, struct timeval *b)
  1109. {
  1110. timeradd(a, b, b);
  1111. }
  1112. bool time_more(struct timeval *a, struct timeval *b)
  1113. {
  1114. return timercmp(a, b, >);
  1115. }
  1116. bool time_less(struct timeval *a, struct timeval *b)
  1117. {
  1118. return timercmp(a, b, <);
  1119. }
  1120. void copy_time(struct timeval *dest, const struct timeval *src)
  1121. {
  1122. memcpy(dest, src, sizeof(struct timeval));
  1123. }
  1124. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  1125. {
  1126. val->tv_sec = spec->tv_sec;
  1127. val->tv_usec = spec->tv_nsec / 1000;
  1128. }
  1129. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  1130. {
  1131. spec->tv_sec = val->tv_sec;
  1132. spec->tv_nsec = val->tv_usec * 1000;
  1133. }
  1134. void us_to_timeval(struct timeval *val, int64_t us)
  1135. {
  1136. lldiv_t tvdiv = lldiv(us, 1000000);
  1137. val->tv_sec = tvdiv.quot;
  1138. val->tv_usec = tvdiv.rem;
  1139. }
  1140. void us_to_timespec(struct timespec *spec, int64_t us)
  1141. {
  1142. lldiv_t tvdiv = lldiv(us, 1000000);
  1143. spec->tv_sec = tvdiv.quot;
  1144. spec->tv_nsec = tvdiv.rem * 1000;
  1145. }
  1146. void ms_to_timespec(struct timespec *spec, int64_t ms)
  1147. {
  1148. lldiv_t tvdiv = lldiv(ms, 1000);
  1149. spec->tv_sec = tvdiv.quot;
  1150. spec->tv_nsec = tvdiv.rem * 1000000;
  1151. }
  1152. void timeraddspec(struct timespec *a, const struct timespec *b)
  1153. {
  1154. a->tv_sec += b->tv_sec;
  1155. a->tv_nsec += b->tv_nsec;
  1156. if (a->tv_nsec >= 1000000000) {
  1157. a->tv_nsec -= 1000000000;
  1158. a->tv_sec++;
  1159. }
  1160. }
  1161. #ifndef WIN32
  1162. static
  1163. void _now_gettimeofday(struct timeval *tv)
  1164. {
  1165. gettimeofday(tv, NULL);
  1166. }
  1167. #else
  1168. /* Windows start time is since 1601 lol so convert it to unix epoch 1970. */
  1169. #define EPOCHFILETIME (116444736000000000LL)
  1170. void _now_gettimeofday(struct timeval *tv)
  1171. {
  1172. FILETIME ft;
  1173. LARGE_INTEGER li;
  1174. GetSystemTimeAsFileTime(&ft);
  1175. li.LowPart = ft.dwLowDateTime;
  1176. li.HighPart = ft.dwHighDateTime;
  1177. li.QuadPart -= EPOCHFILETIME;
  1178. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1179. tv->tv_sec = li.QuadPart / 10000000;
  1180. tv->tv_usec = li.QuadPart % 10000000;
  1181. }
  1182. #endif
  1183. void cgsleep_ms_r(cgtimer_t *tv_start, int ms)
  1184. {
  1185. cgsleep_us_r(tv_start, ((int64_t)ms) * 1000);
  1186. }
  1187. static
  1188. void _cgsleep_us_r_nanosleep(cgtimer_t *tv_start, int64_t us)
  1189. {
  1190. struct timeval tv_timer[1], tv[1];
  1191. struct timespec ts[1];
  1192. timer_set_delay(tv_timer, tv_start, us);
  1193. while (true)
  1194. {
  1195. timer_set_now(tv);
  1196. if (!timercmp(tv_timer, tv, >))
  1197. return;
  1198. timersub(tv_timer, tv, tv);
  1199. timeval_to_spec(ts, tv);
  1200. nanosleep(ts, NULL);
  1201. }
  1202. }
  1203. void cgsleep_ms(int ms)
  1204. {
  1205. cgtimer_t ts_start;
  1206. cgsleep_prepare_r(&ts_start);
  1207. cgsleep_ms_r(&ts_start, ms);
  1208. }
  1209. void cgsleep_us(int64_t us)
  1210. {
  1211. cgtimer_t ts_start;
  1212. cgsleep_prepare_r(&ts_start);
  1213. cgsleep_us_r(&ts_start, us);
  1214. }
  1215. /* Returns the microseconds difference between end and start times as a double */
  1216. double us_tdiff(struct timeval *end, struct timeval *start)
  1217. {
  1218. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1219. }
  1220. /* Returns the seconds difference between end and start times as a double */
  1221. double tdiff(struct timeval *end, struct timeval *start)
  1222. {
  1223. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1224. }
  1225. int double_find_precision(double f, const double base)
  1226. {
  1227. int rv = 0;
  1228. for ( ; floor(f) != f; ++rv)
  1229. f *= base;
  1230. return rv;
  1231. }
  1232. int utf8_len(const uint8_t b)
  1233. {
  1234. if (!(b & 0x80))
  1235. return 1;
  1236. if (!(b & 0x20))
  1237. return 2;
  1238. else
  1239. if (!(b & 0x10))
  1240. return 3;
  1241. else
  1242. return 4;
  1243. }
  1244. int32_t utf8_decode(const void *b, int *out_len)
  1245. {
  1246. int32_t w;
  1247. const unsigned char *s = b;
  1248. *out_len = utf8_len(s[0]);
  1249. if (*out_len == 1)
  1250. // ASCII
  1251. return s[0];
  1252. #ifdef STRICT_UTF8
  1253. if (unlikely(!(s[0] & 0x40)))
  1254. goto invalid;
  1255. if (unlikely(s[0] & 0x38 == 0x38))
  1256. goto invalid;
  1257. #endif
  1258. w = s[0] & ((2 << (6 - *out_len)) - 1);
  1259. for (int i = 1; i < *out_len; ++i)
  1260. {
  1261. #ifdef STRICT_UTF8
  1262. if (unlikely((s[i] & 0xc0) != 0x80))
  1263. goto invalid;
  1264. #endif
  1265. w = (w << 6) | (s[i] & 0x3f);
  1266. }
  1267. #if defined(STRICT_UTF8)
  1268. if (unlikely(w > 0x10FFFF))
  1269. goto invalid;
  1270. // FIXME: UTF-8 requires smallest possible encoding; check it
  1271. #endif
  1272. return w;
  1273. #ifdef STRICT_UTF8
  1274. invalid:
  1275. *out_len = 1;
  1276. return REPLACEMENT_CHAR;
  1277. #endif
  1278. }
  1279. size_t utf8_strlen(const void * const b)
  1280. {
  1281. const uint8_t *s = b;
  1282. size_t c = 0;
  1283. int clen, i;
  1284. while (s[0])
  1285. {
  1286. clen = utf8_len(s[0]);
  1287. for (i = 0; i < clen; ++i)
  1288. if (!s[i])
  1289. clen = 1;
  1290. ++c;
  1291. s += clen;
  1292. }
  1293. return c;
  1294. }
  1295. static
  1296. void _utf8_test(const char *s, const wchar_t expected, int expectedlen)
  1297. {
  1298. int len;
  1299. wchar_t r;
  1300. if (expected != REPLACEMENT_CHAR)
  1301. {
  1302. len = utf8_len(((uint8_t*)s)[0]);
  1303. if (len != expectedlen)
  1304. {
  1305. ++unittest_failures;
  1306. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_len=>%d", (unsigned long)expected, expectedlen, len);
  1307. }
  1308. len = utf8_strlen(s);
  1309. if (len != (s[0] ? 1 : 0))
  1310. {
  1311. ++unittest_failures;
  1312. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_strlen=>%d", (unsigned long)expected, expectedlen, len);
  1313. }
  1314. len = -1;
  1315. }
  1316. r = utf8_decode(s, &len);
  1317. if (unlikely(r != expected || expectedlen != len))
  1318. {
  1319. ++unittest_failures;
  1320. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got U+%06lX (len %d)", (unsigned long)expected, expectedlen, (unsigned long)r, len);
  1321. }
  1322. }
  1323. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1324. void utf8_test()
  1325. {
  1326. _utf8_test("", 0, 1);
  1327. _utf8_test("\1", 1, 1);
  1328. _utf8_test("\x7f", 0x7f, 1);
  1329. #if WCHAR_MAX >= 0x80
  1330. _utf8_test("\xc2\x80", 0x80, 2);
  1331. #if WCHAR_MAX >= 0xff
  1332. _utf8_test("\xc3\xbf", 0xff, 2);
  1333. #if WCHAR_MAX >= 0x7ff
  1334. _utf8_test("\xdf\xbf", 0x7ff, 2);
  1335. #if WCHAR_MAX >= 0x800
  1336. _utf8_test("\xe0\xa0\x80", 0x800, 3);
  1337. #if WCHAR_MAX >= 0xffff
  1338. _utf8_test("\xef\xbf\xbf", 0xffff, 3);
  1339. #if WCHAR_MAX >= 0x10000
  1340. _utf8_test("\xf0\x90\x80\x80", 0x10000, 4);
  1341. #if WCHAR_MAX >= 0x10ffff
  1342. _utf8_test("\xf4\x8f\xbf\xbf", 0x10ffff, 4);
  1343. #endif
  1344. #endif
  1345. #endif
  1346. #endif
  1347. #endif
  1348. #endif
  1349. #endif
  1350. #ifdef STRICT_UTF8
  1351. _utf8_test("\x80", REPLACEMENT_CHAR, 1);
  1352. _utf8_test("\xbf", REPLACEMENT_CHAR, 1);
  1353. _utf8_test("\xfe", REPLACEMENT_CHAR, 1);
  1354. _utf8_test("\xff", REPLACEMENT_CHAR, 1);
  1355. #endif
  1356. }
  1357. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1358. {
  1359. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1360. char url_address[256], port[6];
  1361. int url_len, port_len = 0;
  1362. url_begin = strstr(url, "//");
  1363. if (!url_begin)
  1364. url_begin = url;
  1365. else
  1366. url_begin += 2;
  1367. /* Look for numeric ipv6 entries */
  1368. ipv6_begin = strstr(url_begin, "[");
  1369. ipv6_end = strstr(url_begin, "]");
  1370. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1371. url_end = strstr(ipv6_end, ":");
  1372. else
  1373. url_end = strstr(url_begin, ":");
  1374. if (url_end) {
  1375. url_len = url_end - url_begin;
  1376. port_len = strlen(url_begin) - url_len - 1;
  1377. if (port_len < 1)
  1378. return false;
  1379. port_start = url_end + 1;
  1380. } else
  1381. url_len = strlen(url_begin);
  1382. if (url_len < 1)
  1383. return false;
  1384. if (url_len >= sizeof(url_address))
  1385. {
  1386. applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'",
  1387. __func__, url_len, url_begin);
  1388. url_len = sizeof(url_address) - 1;
  1389. }
  1390. sprintf(url_address, "%.*s", url_len, url_begin);
  1391. if (port_len) {
  1392. char *slash;
  1393. snprintf(port, 6, "%.*s", port_len, port_start);
  1394. slash = strchr(port, '/');
  1395. if (slash)
  1396. *slash = '\0';
  1397. } else
  1398. strcpy(port, "80");
  1399. free(*sockaddr_port);
  1400. *sockaddr_port = strdup(port);
  1401. free(*sockaddr_url);
  1402. *sockaddr_url = strdup(url_address);
  1403. return true;
  1404. }
  1405. enum send_ret {
  1406. SEND_OK,
  1407. SEND_SELECTFAIL,
  1408. SEND_SENDFAIL,
  1409. SEND_INACTIVE
  1410. };
  1411. /* Send a single command across a socket, appending \n to it. This should all
  1412. * be done under stratum lock except when first establishing the socket */
  1413. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1414. {
  1415. SOCKETTYPE sock = pool->sock;
  1416. ssize_t ssent = 0;
  1417. strcat(s, "\n");
  1418. len++;
  1419. while (len > 0 ) {
  1420. struct timeval timeout = {1, 0};
  1421. size_t sent = 0;
  1422. CURLcode rc;
  1423. fd_set wd;
  1424. retry:
  1425. FD_ZERO(&wd);
  1426. FD_SET(sock, &wd);
  1427. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1428. if (interrupted())
  1429. goto retry;
  1430. return SEND_SELECTFAIL;
  1431. }
  1432. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  1433. if (rc != CURLE_OK)
  1434. {
  1435. if (rc != CURLE_AGAIN)
  1436. return SEND_SENDFAIL;
  1437. sent = 0;
  1438. }
  1439. ssent += sent;
  1440. len -= sent;
  1441. }
  1442. pool->cgminer_pool_stats.times_sent++;
  1443. pool->cgminer_pool_stats.bytes_sent += ssent;
  1444. total_bytes_sent += ssent;
  1445. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1446. return SEND_OK;
  1447. }
  1448. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1449. {
  1450. enum send_ret ret = SEND_INACTIVE;
  1451. if (opt_protocol)
  1452. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1453. mutex_lock(&pool->stratum_lock);
  1454. if (pool->stratum_active || force)
  1455. ret = __stratum_send(pool, s, len);
  1456. mutex_unlock(&pool->stratum_lock);
  1457. /* This is to avoid doing applog under stratum_lock */
  1458. switch (ret) {
  1459. default:
  1460. case SEND_OK:
  1461. break;
  1462. case SEND_SELECTFAIL:
  1463. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1464. suspend_stratum(pool);
  1465. break;
  1466. case SEND_SENDFAIL:
  1467. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1468. suspend_stratum(pool);
  1469. break;
  1470. case SEND_INACTIVE:
  1471. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1472. break;
  1473. }
  1474. return (ret == SEND_OK);
  1475. }
  1476. static bool socket_full(struct pool *pool, int wait)
  1477. {
  1478. SOCKETTYPE sock = pool->sock;
  1479. struct timeval timeout;
  1480. fd_set rd;
  1481. if (sock == INVSOCK)
  1482. return true;
  1483. if (unlikely(wait < 0))
  1484. wait = 0;
  1485. FD_ZERO(&rd);
  1486. FD_SET(sock, &rd);
  1487. timeout.tv_usec = 0;
  1488. timeout.tv_sec = wait;
  1489. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1490. return true;
  1491. return false;
  1492. }
  1493. /* Check to see if Santa's been good to you */
  1494. bool sock_full(struct pool *pool)
  1495. {
  1496. if (strlen(pool->sockbuf))
  1497. return true;
  1498. return (socket_full(pool, 0));
  1499. }
  1500. static void clear_sockbuf(struct pool *pool)
  1501. {
  1502. strcpy(pool->sockbuf, "");
  1503. }
  1504. static void clear_sock(struct pool *pool)
  1505. {
  1506. size_t n = 0;
  1507. mutex_lock(&pool->stratum_lock);
  1508. do {
  1509. n = 0;
  1510. if (pool->sock)
  1511. curl_easy_recv(pool->stratum_curl, pool->sockbuf, RECVSIZE, &n);
  1512. } while (n > 0);
  1513. mutex_unlock(&pool->stratum_lock);
  1514. clear_sockbuf(pool);
  1515. }
  1516. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1517. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1518. * and zeroing the new memory */
  1519. static void recalloc_sock(struct pool *pool, size_t len)
  1520. {
  1521. size_t old, new;
  1522. old = strlen(pool->sockbuf);
  1523. new = old + len + 1;
  1524. if (new < pool->sockbuf_size)
  1525. return;
  1526. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1527. // Avoid potentially recursive locking
  1528. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1529. pool->sockbuf = realloc(pool->sockbuf, new);
  1530. if (!pool->sockbuf)
  1531. quithere(1, "Failed to realloc pool sockbuf");
  1532. memset(pool->sockbuf + old, 0, new - old);
  1533. pool->sockbuf_size = new;
  1534. }
  1535. /* Peeks at a socket to find the first end of line and then reads just that
  1536. * from the socket and returns that as a malloced char */
  1537. char *recv_line(struct pool *pool)
  1538. {
  1539. char *tok, *sret = NULL;
  1540. ssize_t len, buflen;
  1541. int waited = 0;
  1542. if (!strstr(pool->sockbuf, "\n")) {
  1543. struct timeval rstart, now;
  1544. cgtime(&rstart);
  1545. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1546. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1547. goto out;
  1548. }
  1549. do {
  1550. char s[RBUFSIZE];
  1551. size_t slen;
  1552. size_t n = 0;
  1553. CURLcode rc;
  1554. memset(s, 0, RBUFSIZE);
  1555. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  1556. if (rc == CURLE_OK && !n)
  1557. {
  1558. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1559. suspend_stratum(pool);
  1560. break;
  1561. }
  1562. cgtime(&now);
  1563. waited = tdiff(&now, &rstart);
  1564. if (rc != CURLE_OK)
  1565. {
  1566. if (rc != CURLE_AGAIN || !socket_full(pool, DEFAULT_SOCKWAIT - waited))
  1567. {
  1568. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1569. suspend_stratum(pool);
  1570. break;
  1571. }
  1572. } else {
  1573. slen = strlen(s);
  1574. recalloc_sock(pool, slen);
  1575. strcat(pool->sockbuf, s);
  1576. }
  1577. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1578. }
  1579. buflen = strlen(pool->sockbuf);
  1580. tok = strtok(pool->sockbuf, "\n");
  1581. if (!tok) {
  1582. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1583. goto out;
  1584. }
  1585. sret = strdup(tok);
  1586. len = strlen(sret);
  1587. /* Copy what's left in the buffer after the \n, including the
  1588. * terminating \0 */
  1589. if (buflen > len + 1)
  1590. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1591. else
  1592. strcpy(pool->sockbuf, "");
  1593. pool->cgminer_pool_stats.times_received++;
  1594. pool->cgminer_pool_stats.bytes_received += len;
  1595. total_bytes_rcvd += len;
  1596. pool->cgminer_pool_stats.net_bytes_received += len;
  1597. out:
  1598. if (!sret)
  1599. clear_sock(pool);
  1600. else if (opt_protocol)
  1601. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1602. return sret;
  1603. }
  1604. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1605. * flag, but this is compatible with 2.0. */
  1606. char *json_dumps_ANY(json_t *json, size_t flags)
  1607. {
  1608. switch (json_typeof(json))
  1609. {
  1610. case JSON_ARRAY:
  1611. case JSON_OBJECT:
  1612. return json_dumps(json, flags);
  1613. default:
  1614. break;
  1615. }
  1616. char *rv;
  1617. #ifdef JSON_ENCODE_ANY
  1618. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1619. if (rv)
  1620. return rv;
  1621. #endif
  1622. json_t *tmp = json_array();
  1623. char *s;
  1624. int i;
  1625. size_t len;
  1626. if (!tmp)
  1627. quithere(1, "Failed to allocate json array");
  1628. if (json_array_append(tmp, json))
  1629. quithere(1, "Failed to append temporary array");
  1630. s = json_dumps(tmp, flags);
  1631. if (!s)
  1632. return NULL;
  1633. for (i = 0; s[i] != '['; ++i)
  1634. if (unlikely(!(s[i] && isCspace(s[i]))))
  1635. quithere(1, "Failed to find opening bracket in array dump");
  1636. len = strlen(&s[++i]) - 1;
  1637. if (unlikely(s[i+len] != ']'))
  1638. quithere(1, "Failed to find closing bracket in array dump");
  1639. rv = malloc(len + 1);
  1640. memcpy(rv, &s[i], len);
  1641. rv[len] = '\0';
  1642. free(s);
  1643. json_decref(tmp);
  1644. return rv;
  1645. }
  1646. /* Extracts a string value from a json array with error checking. To be used
  1647. * when the value of the string returned is only examined and not to be stored.
  1648. * See json_array_string below */
  1649. const char *__json_array_string(json_t *val, unsigned int entry)
  1650. {
  1651. json_t *arr_entry;
  1652. if (json_is_null(val))
  1653. return NULL;
  1654. if (!json_is_array(val))
  1655. return NULL;
  1656. if (entry > json_array_size(val))
  1657. return NULL;
  1658. arr_entry = json_array_get(val, entry);
  1659. if (!json_is_string(arr_entry))
  1660. return NULL;
  1661. return json_string_value(arr_entry);
  1662. }
  1663. /* Creates a freshly malloced dup of __json_array_string */
  1664. static char *json_array_string(json_t *val, unsigned int entry)
  1665. {
  1666. const char *buf = __json_array_string(val, entry);
  1667. if (buf)
  1668. return strdup(buf);
  1669. return NULL;
  1670. }
  1671. void *my_memrchr(const void * const datap, const int c, const size_t sz)
  1672. {
  1673. const uint8_t *data = datap;
  1674. const uint8_t *p = &data[sz];
  1675. while (p > data)
  1676. if (*--p == c)
  1677. return (void *)p;
  1678. return NULL;
  1679. }
  1680. bool isCalpha(const int c)
  1681. {
  1682. if (c >= 'A' && c <= 'Z')
  1683. return true;
  1684. if (c >= 'a' && c <= 'z')
  1685. return true;
  1686. return false;
  1687. }
  1688. bool match_strtok(const char * const optlist, const char * const delim, const char * const needle)
  1689. {
  1690. const size_t optlist_sz = strlen(optlist) + 1;
  1691. char opts[optlist_sz];
  1692. memcpy(opts, optlist, optlist_sz);
  1693. for (char *el, *nextptr, *s = opts; (el = strtok_r(s, delim, &nextptr)); s = NULL)
  1694. if (!strcasecmp(el, needle))
  1695. return true;
  1696. return false;
  1697. }
  1698. static
  1699. 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)
  1700. {
  1701. if (!(path && path[0]))
  1702. return false;
  1703. char filepath[PATH_MAX];
  1704. snprintf(filepath, sizeof(filepath), "%s/%s/%s", path, appname, filename);
  1705. if (!access(filepath, R_OK))
  1706. return cb(filepath, userp);
  1707. return false;
  1708. }
  1709. #define _APPDATA_FILE_CALL(appname, path) do{ \
  1710. if (_appdata_file_call(appname, filename, cb, userp, path)) \
  1711. return true; \
  1712. }while(0)
  1713. bool appdata_file_call(const char *appname, const char * const filename, const appdata_file_callback_t cb, void * const userp)
  1714. {
  1715. size_t appname_len = strlen(appname);
  1716. char appname_lcd[appname_len + 1];
  1717. appname_lcd[0] = '.';
  1718. char *appname_lc = &appname_lcd[1];
  1719. for (size_t i = 0; i <= appname_len; ++i)
  1720. appname_lc[i] = tolower(appname[i]);
  1721. appname_lc[appname_len] = '\0';
  1722. const char * const HOME = getenv("HOME");
  1723. _APPDATA_FILE_CALL(".", ".");
  1724. #ifdef WIN32
  1725. _APPDATA_FILE_CALL(appname, getenv("APPDATA"));
  1726. #elif defined(__APPLE__)
  1727. if (HOME && HOME[0])
  1728. {
  1729. char AppSupport[strlen(HOME) + 28 + 1];
  1730. snprintf(AppSupport, sizeof(AppSupport), "%s/Library/Application Support", HOME);
  1731. _APPDATA_FILE_CALL(appname, AppSupport);
  1732. }
  1733. #endif
  1734. _APPDATA_FILE_CALL(appname_lcd, HOME);
  1735. #ifdef WIN32
  1736. _APPDATA_FILE_CALL(appname, getenv("ALLUSERSAPPDATA"));
  1737. #elif defined(__APPLE__)
  1738. _APPDATA_FILE_CALL(appname, "/Library/Application Support");
  1739. #endif
  1740. #ifndef WIN32
  1741. _APPDATA_FILE_CALL(appname_lc, "/etc");
  1742. #endif
  1743. return false;
  1744. }
  1745. static
  1746. bool _appdata_file_find_first(const char * const filepath, void *userp)
  1747. {
  1748. char **rv = userp;
  1749. *rv = strdup(filepath);
  1750. return true;
  1751. }
  1752. char *appdata_file_find_first(const char * const appname, const char * const filename)
  1753. {
  1754. char *rv;
  1755. if (appdata_file_call(appname, filename, _appdata_file_find_first, &rv))
  1756. return rv;
  1757. return NULL;
  1758. }
  1759. const char *get_registered_domain(size_t * const out_domainlen, const char * const fqdn, const size_t fqdnlen)
  1760. {
  1761. const char *s;
  1762. int dots = 0;
  1763. for (s = &fqdn[fqdnlen-1]; s >= fqdn; --s)
  1764. {
  1765. if (s[0] == '.')
  1766. {
  1767. *out_domainlen = fqdnlen - (&s[1] - fqdn);
  1768. if (++dots >= 2 && *out_domainlen > 5)
  1769. return &s[1];
  1770. }
  1771. else
  1772. if (!(dots || isCalpha(s[0])))
  1773. {
  1774. *out_domainlen = fqdnlen;
  1775. return fqdn;
  1776. }
  1777. }
  1778. *out_domainlen = fqdnlen;
  1779. return fqdn;
  1780. }
  1781. const char *extract_domain(size_t * const out_domainlen, const char * const uri, const size_t urilen)
  1782. {
  1783. const char *p = uri, *b, *q, *s;
  1784. bool alldigit;
  1785. p = memchr(&p[1], '/', urilen - (&p[1] - uri));
  1786. if (p)
  1787. {
  1788. if (p[-1] == ':')
  1789. {
  1790. // part of the URI scheme, ignore it
  1791. while (p[0] == '/')
  1792. ++p;
  1793. p = memchr(p, '/', urilen - (p - uri)) ?: &uri[urilen];
  1794. }
  1795. }
  1796. else
  1797. p = &uri[urilen];
  1798. s = p;
  1799. q = my_memrchr(uri, ':', p - uri);
  1800. if (q)
  1801. {
  1802. alldigit = true;
  1803. for (q = b = &q[1]; q < p; ++q)
  1804. if (!isdigit(q[0]))
  1805. {
  1806. alldigit = false;
  1807. break;
  1808. }
  1809. if (alldigit && p != b)
  1810. p = &b[-1];
  1811. }
  1812. alldigit = true;
  1813. for (b = uri; b < p; ++b)
  1814. {
  1815. if (b[0] == ':')
  1816. break;
  1817. if (alldigit && !isdigit(b[0]))
  1818. alldigit = false;
  1819. }
  1820. if ((b < p && b[0] == ':') && (b == uri || !alldigit))
  1821. b = &b[1];
  1822. else
  1823. b = uri;
  1824. while (b <= p && b[0] == '/')
  1825. ++b;
  1826. if (p - b > 1 && b[0] == '[' && p[-1] == ']')
  1827. {
  1828. ++b;
  1829. --p;
  1830. }
  1831. else
  1832. if (memchr(b, ':', p - b))
  1833. p = s;
  1834. if (p > b && p[-1] == '.')
  1835. --p;
  1836. *out_domainlen = p - b;
  1837. return b;
  1838. }
  1839. bool match_domains(const char * const a, const size_t alen, const char * const b, const size_t blen)
  1840. {
  1841. size_t a_domainlen, b_domainlen;
  1842. const char *a_domain, *b_domain;
  1843. a_domain = extract_domain(&a_domainlen, a, alen);
  1844. a_domain = get_registered_domain(&a_domainlen, a_domain, a_domainlen);
  1845. b_domain = extract_domain(&b_domainlen, b, blen);
  1846. b_domain = get_registered_domain(&b_domainlen, b_domain, b_domainlen);
  1847. if (a_domainlen != b_domainlen)
  1848. return false;
  1849. return !strncasecmp(a_domain, b_domain, a_domainlen);
  1850. }
  1851. static
  1852. void _test_extract_domain(const char * const expect, const char * const uri)
  1853. {
  1854. size_t sz;
  1855. const char * const d = extract_domain(&sz, uri, strlen(uri));
  1856. if (sz != strlen(expect) || strncasecmp(d, expect, sz))
  1857. {
  1858. ++unittest_failures;
  1859. applog(LOG_WARNING, "extract_domain \"%s\" test failed; got \"%.*s\" instead of \"%s\"",
  1860. uri, (int)sz, d, expect);
  1861. }
  1862. }
  1863. static
  1864. void _test_get_regd_domain(const char * const expect, const char * const fqdn)
  1865. {
  1866. size_t sz;
  1867. const char * const d = get_registered_domain(&sz, fqdn, strlen(fqdn));
  1868. if (d == NULL || sz != strlen(expect) || strncasecmp(d, expect, sz))
  1869. {
  1870. ++unittest_failures;
  1871. applog(LOG_WARNING, "get_registered_domain \"%s\" test failed; got \"%.*s\" instead of \"%s\"",
  1872. fqdn, (int)sz, d, expect);
  1873. }
  1874. }
  1875. void test_domain_funcs()
  1876. {
  1877. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334");
  1878. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st:3334/abc/abc/");
  1879. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st/abc/abc/");
  1880. _test_extract_domain("s.m.eligius.st", "http://s.m.eligius.st");
  1881. _test_extract_domain("s.m.eligius.st", "http:s.m.eligius.st");
  1882. _test_extract_domain("s.m.eligius.st", "stratum+tcp:s.m.eligius.st");
  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", "stratum+tcp://s.m.eligius.st.:3334///");
  1887. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334");
  1888. _test_extract_domain("s.m.eligius.st", "s.m.eligius.st:3334///");
  1889. _test_extract_domain("foohost", "foohost:3334");
  1890. _test_extract_domain("foohost", "foohost:3334///");
  1891. _test_extract_domain("foohost", "foohost:3334/abc.com//");
  1892. _test_extract_domain("", "foohost:");
  1893. _test_extract_domain("3334", "foohost://3334/abc.com//");
  1894. _test_extract_domain("192.0.2.0", "foohost:192.0.2.0");
  1895. _test_extract_domain("192.0.2.0", "192.0.2.0:3334");
  1896. _test_extract_domain("192.0.2.0", "192.0.2.0:3334///");
  1897. _test_extract_domain("2001:db8::1", "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]");
  1900. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]:42");
  1901. _test_extract_domain("2001:db8::1", "http://[2001:db8::1]:42/abc//def/ghi");
  1902. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]");
  1903. _test_extract_domain("2001:db8::cafe", "http:[2001:db8::cafe]");
  1904. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]:42");
  1905. _test_extract_domain("2001:db8::cafe", "http://[2001:db8::cafe]:42/abc//def/ghi");
  1906. _test_get_regd_domain("eligius.st", "s.m.eligius.st");
  1907. _test_get_regd_domain("eligius.st", "eligius.st");
  1908. _test_get_regd_domain("foohost.co.uk", "myserver.foohost.co.uk");
  1909. _test_get_regd_domain("foohost", "foohost");
  1910. _test_get_regd_domain("192.0.2.0", "192.0.2.0");
  1911. _test_get_regd_domain("2001:db8::1", "2001:db8::1");
  1912. }
  1913. struct bfg_strtobool_keyword {
  1914. bool val;
  1915. const char *keyword;
  1916. };
  1917. bool bfg_strtobool(const char * const s, char ** const endptr, __maybe_unused const int opts)
  1918. {
  1919. struct bfg_strtobool_keyword keywords[] = {
  1920. {false, "disable"},
  1921. {false, "false"},
  1922. {false, "never"},
  1923. {false, "none"},
  1924. {false, "off"},
  1925. {false, "no"},
  1926. {false, "0"},
  1927. {true , "enable"},
  1928. {true , "always"},
  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\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  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\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2848. else
  2849. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  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. }