util.c 87 KB

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