util.c 92 KB

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