util.c 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840
  1. /*
  2. * Copyright 2011-2018 Con Kolivas
  3. * Copyright 2011-2015 Andrew Smith
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <ctype.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include <jansson.h>
  18. #ifdef HAVE_LIBCURL
  19. #include <curl/curl.h>
  20. #endif
  21. #include <time.h>
  22. #include <errno.h>
  23. #include <unistd.h>
  24. #include <sys/types.h>
  25. #ifndef WIN32
  26. #include <fcntl.h>
  27. # ifdef __linux
  28. # include <sys/prctl.h>
  29. # endif
  30. # include <sys/socket.h>
  31. # include <netinet/in.h>
  32. # include <netinet/tcp.h>
  33. # include <netdb.h>
  34. #else
  35. # include <winsock2.h>
  36. # include <ws2tcpip.h>
  37. # include <mmsystem.h>
  38. #endif
  39. #include <sched.h>
  40. #include "miner.h"
  41. #include "elist.h"
  42. #include "compat.h"
  43. #include "util.h"
  44. #define DEFAULT_SOCKWAIT 60
  45. #ifndef STRATUM_USER_AGENT
  46. #define STRATUM_USER_AGENT
  47. #endif
  48. bool successful_connect = false;
  49. int no_yield(void)
  50. {
  51. return 0;
  52. }
  53. int (*selective_yield)(void) = &no_yield;
  54. static void keep_sockalive(SOCKETTYPE fd)
  55. {
  56. const int tcp_one = 1;
  57. #ifndef WIN32
  58. const int tcp_keepidle = 45;
  59. const int tcp_keepintvl = 30;
  60. int flags = fcntl(fd, F_GETFL, 0);
  61. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  62. #else
  63. u_long flags = 1;
  64. ioctlsocket(fd, FIONBIO, &flags);
  65. #endif
  66. setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const void *)&tcp_one, sizeof(tcp_one));
  67. if (!opt_delaynet)
  68. #ifndef __linux
  69. setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  70. #else /* __linux */
  71. fcntl(fd, F_SETFD, FD_CLOEXEC);
  72. setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  73. setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one));
  74. setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
  75. setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
  76. #endif /* __linux */
  77. #ifdef __APPLE_CC__
  78. setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
  79. #endif /* __APPLE_CC__ */
  80. }
  81. #ifdef WIN32
  82. /* Generic versions of inet_pton for windows, using different names in case
  83. * it is implemented in ming in the future. */
  84. #define W32NS_INADDRSZ 4
  85. #define W32NS_IN6ADDRSZ 16
  86. #define W32NS_INT16SZ 2
  87. static int Inet_Pton4(const char *src, char *dst)
  88. {
  89. uint8_t tmp[W32NS_INADDRSZ], *tp;
  90. int saw_digit = 0;
  91. int octets = 0;
  92. *(tp = tmp) = 0;
  93. int ch;
  94. while ((ch = *src++) != '\0')
  95. {
  96. if (ch >= '0' && ch <= '9')
  97. {
  98. uint32_t n = *tp * 10 + (ch - '0');
  99. if (saw_digit && *tp == 0)
  100. return 0;
  101. if (n > 255)
  102. return 0;
  103. *tp = n;
  104. if (!saw_digit)
  105. {
  106. if (++octets > 4)
  107. return 0;
  108. saw_digit = 1;
  109. }
  110. }
  111. else if (ch == '.' && saw_digit)
  112. {
  113. if (octets == 4)
  114. return 0;
  115. *++tp = 0;
  116. saw_digit = 0;
  117. }
  118. else
  119. return 0;
  120. }
  121. if (octets < 4)
  122. return 0;
  123. cg_memcpy(dst, tmp, W32NS_INADDRSZ);
  124. return 1;
  125. }
  126. static int Inet_Pton6(const char *src, char *dst)
  127. {
  128. static const char xdigits[] = "0123456789abcdef";
  129. uint8_t tmp[W32NS_IN6ADDRSZ];
  130. uint8_t *tp = (uint8_t*) memset(tmp, '\0', W32NS_IN6ADDRSZ);
  131. uint8_t *endp = tp + W32NS_IN6ADDRSZ;
  132. uint8_t *colonp = NULL;
  133. /* Leading :: requires some special handling. */
  134. if (*src == ':')
  135. {
  136. if (*++src != ':')
  137. return 0;
  138. }
  139. const char *curtok = src;
  140. int saw_xdigit = 0;
  141. uint32_t val = 0;
  142. int ch;
  143. while ((ch = tolower(*src++)) != '\0')
  144. {
  145. const char *pch = strchr(xdigits, ch);
  146. if (pch != NULL)
  147. {
  148. val <<= 4;
  149. val |= (pch - xdigits);
  150. if (val > 0xffff)
  151. return 0;
  152. saw_xdigit = 1;
  153. continue;
  154. }
  155. if (ch == ':')
  156. {
  157. curtok = src;
  158. if (!saw_xdigit)
  159. {
  160. if (colonp)
  161. return 0;
  162. colonp = tp;
  163. continue;
  164. }
  165. else if (*src == '\0')
  166. {
  167. return 0;
  168. }
  169. if (tp + W32NS_INT16SZ > endp)
  170. return 0;
  171. *tp++ = (uint8_t) (val >> 8) & 0xff;
  172. *tp++ = (uint8_t) val & 0xff;
  173. saw_xdigit = 0;
  174. val = 0;
  175. continue;
  176. }
  177. if (ch == '.' && ((tp + W32NS_INADDRSZ) <= endp) &&
  178. Inet_Pton4(curtok, (char*) tp) > 0)
  179. {
  180. tp += W32NS_INADDRSZ;
  181. saw_xdigit = 0;
  182. break; /* '\0' was seen by inet_pton4(). */
  183. }
  184. return 0;
  185. }
  186. if (saw_xdigit)
  187. {
  188. if (tp + W32NS_INT16SZ > endp)
  189. return 0;
  190. *tp++ = (uint8_t) (val >> 8) & 0xff;
  191. *tp++ = (uint8_t) val & 0xff;
  192. }
  193. if (colonp != NULL)
  194. {
  195. int i;
  196. /*
  197. * Since some memmove()'s erroneously fail to handle
  198. * overlapping regions, we'll do the shift by hand.
  199. */
  200. const int n = tp - colonp;
  201. if (tp == endp)
  202. return 0;
  203. for (i = 1; i <= n; i++)
  204. {
  205. endp[-i] = colonp[n - i];
  206. colonp[n - i] = 0;
  207. }
  208. tp = endp;
  209. }
  210. if (tp != endp)
  211. return 0;
  212. cg_memcpy(dst, tmp, W32NS_IN6ADDRSZ);
  213. return 1;
  214. }
  215. int Inet_Pton(int af, const char *src, void *dst)
  216. {
  217. switch (af)
  218. {
  219. case AF_INET:
  220. return Inet_Pton4(src, dst);
  221. case AF_INET6:
  222. return Inet_Pton6(src, dst);
  223. default:
  224. return -1;
  225. }
  226. }
  227. #endif
  228. /* Align a size_t to 4 byte boundaries for fussy arches */
  229. static inline void align_len(size_t *len)
  230. {
  231. if (*len % 4)
  232. *len += 4 - (*len % 4);
  233. }
  234. void *_cgmalloc(size_t size, const char *file, const char *func, const int line)
  235. {
  236. void *ret;
  237. align_len(&size);
  238. ret = malloc(size);
  239. if (unlikely(!ret))
  240. quit(1, "Failed to malloc size %d from %s %s:%d", (int)size, file, func, line);
  241. return ret;
  242. }
  243. void *_cgcalloc(const size_t memb, size_t size, const char *file, const char *func, const int line)
  244. {
  245. void *ret;
  246. align_len(&size);
  247. ret = calloc(memb, size);
  248. if (unlikely(!ret))
  249. quit(1, "Failed to calloc memb %d size %d from %s %s:%d", (int)memb, (int)size, file, func, line);
  250. return ret;
  251. }
  252. void *_cgrealloc(void *ptr, size_t size, const char *file, const char *func, const int line)
  253. {
  254. void *ret;
  255. align_len(&size);
  256. ret = realloc(ptr, size);
  257. if (unlikely(!ret))
  258. quit(1, "Failed to realloc size %d from %s %s:%d", (int)size, file, func, line);
  259. return ret;
  260. }
  261. struct tq_ent {
  262. void *data;
  263. struct list_head q_node;
  264. };
  265. #ifdef HAVE_LIBCURL
  266. struct timeval nettime;
  267. struct data_buffer {
  268. void *buf;
  269. size_t len;
  270. };
  271. struct upload_buffer {
  272. const void *buf;
  273. size_t len;
  274. };
  275. struct header_info {
  276. char *lp_path;
  277. int rolltime;
  278. char *reason;
  279. char *stratum_url;
  280. bool hadrolltime;
  281. bool canroll;
  282. bool hadexpire;
  283. };
  284. static void databuf_free(struct data_buffer *db)
  285. {
  286. if (!db)
  287. return;
  288. free(db->buf);
  289. memset(db, 0, sizeof(*db));
  290. }
  291. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  292. void *user_data)
  293. {
  294. struct data_buffer *db = user_data;
  295. size_t len = size * nmemb;
  296. size_t oldlen, newlen;
  297. void *newmem;
  298. static const unsigned char zero = 0;
  299. oldlen = db->len;
  300. newlen = oldlen + len;
  301. newmem = cgrealloc(db->buf, newlen + 1);
  302. db->buf = newmem;
  303. db->len = newlen;
  304. cg_memcpy(db->buf + oldlen, ptr, len);
  305. cg_memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  306. return len;
  307. }
  308. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  309. void *user_data)
  310. {
  311. struct upload_buffer *ub = user_data;
  312. unsigned int len = size * nmemb;
  313. if (len > ub->len)
  314. len = ub->len;
  315. if (len) {
  316. cg_memcpy(ptr, ub->buf, len);
  317. ub->buf += len;
  318. ub->len -= len;
  319. }
  320. return len;
  321. }
  322. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  323. {
  324. struct header_info *hi = user_data;
  325. size_t remlen, slen, ptrlen = size * nmemb;
  326. char *rem, *val = NULL, *key = NULL;
  327. void *tmp;
  328. val = cgcalloc(1, ptrlen);
  329. key = cgcalloc(1, ptrlen);
  330. tmp = memchr(ptr, ':', ptrlen);
  331. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  332. goto out;
  333. slen = tmp - ptr;
  334. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  335. goto out;
  336. cg_memcpy(key, ptr, slen); /* store & nul term key */
  337. key[slen] = 0;
  338. rem = ptr + slen + 1; /* trim value's leading whitespace */
  339. remlen = ptrlen - slen - 1;
  340. while ((remlen > 0) && (isspace(*rem))) {
  341. remlen--;
  342. rem++;
  343. }
  344. cg_memcpy(val, rem, remlen); /* store value, trim trailing ws */
  345. val[remlen] = 0;
  346. while ((*val) && (isspace(val[strlen(val) - 1])))
  347. val[strlen(val) - 1] = 0;
  348. if (!*val) /* skip blank value */
  349. goto out;
  350. if (opt_protocol)
  351. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  352. if (!strcasecmp("X-Roll-Ntime", key)) {
  353. hi->hadrolltime = true;
  354. if (!strncasecmp("N", val, 1))
  355. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  356. else {
  357. hi->canroll = true;
  358. /* Check to see if expire= is supported and if not, set
  359. * the rolltime to the default scantime */
  360. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  361. sscanf(val + 7, "%d", &hi->rolltime);
  362. hi->hadexpire = true;
  363. } else
  364. hi->rolltime = max_scantime;
  365. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  366. }
  367. }
  368. if (!strcasecmp("X-Long-Polling", key)) {
  369. hi->lp_path = val; /* steal memory reference */
  370. val = NULL;
  371. }
  372. if (!strcasecmp("X-Reject-Reason", key)) {
  373. hi->reason = val; /* steal memory reference */
  374. val = NULL;
  375. }
  376. if (!strcasecmp("X-Stratum", key)) {
  377. hi->stratum_url = val;
  378. val = NULL;
  379. }
  380. out:
  381. free(key);
  382. free(val);
  383. return ptrlen;
  384. }
  385. static void last_nettime(struct timeval *last)
  386. {
  387. rd_lock(&netacc_lock);
  388. last->tv_sec = nettime.tv_sec;
  389. last->tv_usec = nettime.tv_usec;
  390. rd_unlock(&netacc_lock);
  391. }
  392. static void set_nettime(void)
  393. {
  394. wr_lock(&netacc_lock);
  395. cgtime(&nettime);
  396. wr_unlock(&netacc_lock);
  397. }
  398. #if CURL_HAS_KEEPALIVE
  399. static void keep_curlalive(CURL *curl)
  400. {
  401. const int tcp_keepidle = 45;
  402. const int tcp_keepintvl = 30;
  403. const long int keepalive = 1;
  404. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
  405. curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, tcp_keepidle);
  406. curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, tcp_keepintvl);
  407. }
  408. #else
  409. static void keep_curlalive(CURL *curl)
  410. {
  411. SOCKETTYPE sock;
  412. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
  413. keep_sockalive(sock);
  414. }
  415. #endif
  416. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  417. __maybe_unused char *data, size_t size, void *userdata)
  418. {
  419. struct pool *pool = (struct pool *)userdata;
  420. switch(type) {
  421. case CURLINFO_HEADER_IN:
  422. case CURLINFO_DATA_IN:
  423. case CURLINFO_SSL_DATA_IN:
  424. pool->cgminer_pool_stats.net_bytes_received += size;
  425. break;
  426. case CURLINFO_HEADER_OUT:
  427. case CURLINFO_DATA_OUT:
  428. case CURLINFO_SSL_DATA_OUT:
  429. pool->cgminer_pool_stats.net_bytes_sent += size;
  430. break;
  431. case CURLINFO_TEXT:
  432. default:
  433. break;
  434. }
  435. return 0;
  436. }
  437. json_t *json_web_config(const char *url)
  438. {
  439. struct data_buffer all_data = {NULL, 0};
  440. char curl_err_str[CURL_ERROR_SIZE];
  441. long timeout = 60;
  442. json_error_t err;
  443. json_t *val;
  444. CURL *curl;
  445. int rc;
  446. memset(&err, 0, sizeof(err));
  447. curl = curl_easy_init();
  448. if (unlikely(!curl))
  449. quithere(1, "CURL initialisation failed");
  450. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  451. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  452. curl_easy_setopt(curl, CURLOPT_URL, url);
  453. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  454. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  455. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  456. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  457. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  458. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  459. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  460. val = NULL;
  461. rc = curl_easy_perform(curl);
  462. curl_easy_cleanup(curl);
  463. if (rc) {
  464. applog(LOG_ERR, "HTTP config request of '%s' failed: %s", url, curl_err_str);
  465. goto c_out;
  466. }
  467. if (!all_data.buf) {
  468. applog(LOG_ERR, "Empty config data received from '%s'", url);
  469. goto c_out;
  470. }
  471. val = JSON_LOADS(all_data.buf, &err);
  472. if (!val) {
  473. applog(LOG_ERR, "JSON config decode of '%s' failed(%d): %s", url,
  474. err.line, err.text);
  475. }
  476. databuf_free(&all_data);
  477. c_out:
  478. return val;
  479. }
  480. json_t *json_rpc_call(CURL *curl, const char *url,
  481. const char *userpass, const char *rpc_req,
  482. bool probe, bool longpoll, int *rolltime,
  483. struct pool *pool, bool share)
  484. {
  485. long timeout = longpoll ? (60 * 60) : 60;
  486. struct data_buffer all_data = {NULL, 0};
  487. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  488. char len_hdr[64], user_agent_hdr[128];
  489. char curl_err_str[CURL_ERROR_SIZE];
  490. struct curl_slist *headers = NULL;
  491. struct upload_buffer upload_data;
  492. json_t *val, *err_val, *res_val;
  493. bool probing = false;
  494. double byte_count;
  495. json_error_t err;
  496. int rc;
  497. memset(&err, 0, sizeof(err));
  498. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  499. if (probe)
  500. probing = !pool->probed;
  501. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  502. // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
  503. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  504. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  505. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  506. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  507. curl_easy_setopt(curl, CURLOPT_URL, url);
  508. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  509. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  510. /* Shares are staggered already and delays in submission can be costly
  511. * so do not delay them */
  512. if (!opt_delaynet || share)
  513. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  514. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  515. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  516. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  517. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  518. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  519. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  520. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  521. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  522. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  523. if (pool->rpc_proxy) {
  524. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  525. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  526. } else if (opt_socks_proxy) {
  527. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  528. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  529. }
  530. if (userpass) {
  531. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  532. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  533. }
  534. if (longpoll)
  535. keep_curlalive(curl);
  536. curl_easy_setopt(curl, CURLOPT_POST, 1);
  537. if (opt_protocol)
  538. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  539. upload_data.buf = rpc_req;
  540. upload_data.len = strlen(rpc_req);
  541. sprintf(len_hdr, "Content-Length: %lu",
  542. (unsigned long) upload_data.len);
  543. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  544. headers = curl_slist_append(headers,
  545. "Content-type: application/json");
  546. headers = curl_slist_append(headers,
  547. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  548. if (likely(global_hashrate)) {
  549. char ghashrate[255];
  550. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, global_hashrate);
  551. headers = curl_slist_append(headers, ghashrate);
  552. }
  553. headers = curl_slist_append(headers, len_hdr);
  554. headers = curl_slist_append(headers, user_agent_hdr);
  555. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  556. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  557. if (opt_delaynet) {
  558. /* Don't delay share submission, but still track the nettime */
  559. if (!share) {
  560. long long now_msecs, last_msecs;
  561. struct timeval now, last;
  562. cgtime(&now);
  563. last_nettime(&last);
  564. now_msecs = (long long)now.tv_sec * 1000;
  565. now_msecs += now.tv_usec / 1000;
  566. last_msecs = (long long)last.tv_sec * 1000;
  567. last_msecs += last.tv_usec / 1000;
  568. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  569. struct timespec rgtp;
  570. rgtp.tv_sec = 0;
  571. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  572. nanosleep(&rgtp, NULL);
  573. }
  574. }
  575. set_nettime();
  576. }
  577. rc = curl_easy_perform(curl);
  578. if (rc) {
  579. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  580. goto err_out;
  581. }
  582. if (!all_data.buf) {
  583. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  584. goto err_out;
  585. }
  586. pool->cgminer_pool_stats.times_sent++;
  587. if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
  588. pool->cgminer_pool_stats.bytes_sent += byte_count;
  589. pool->cgminer_pool_stats.times_received++;
  590. if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
  591. pool->cgminer_pool_stats.bytes_received += byte_count;
  592. if (probing) {
  593. pool->probed = true;
  594. /* If X-Long-Polling was found, activate long polling */
  595. if (hi.lp_path) {
  596. if (pool->hdr_path != NULL)
  597. free(pool->hdr_path);
  598. pool->hdr_path = hi.lp_path;
  599. } else
  600. pool->hdr_path = NULL;
  601. if (hi.stratum_url) {
  602. pool->stratum_url = hi.stratum_url;
  603. hi.stratum_url = NULL;
  604. }
  605. } else {
  606. if (hi.lp_path) {
  607. free(hi.lp_path);
  608. hi.lp_path = NULL;
  609. }
  610. if (hi.stratum_url) {
  611. free(hi.stratum_url);
  612. hi.stratum_url = NULL;
  613. }
  614. }
  615. *rolltime = hi.rolltime;
  616. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  617. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  618. pool->cgminer_pool_stats.canroll = hi.canroll;
  619. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  620. val = JSON_LOADS(all_data.buf, &err);
  621. if (!val) {
  622. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  623. if (opt_protocol)
  624. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
  625. goto err_out;
  626. }
  627. if (opt_protocol) {
  628. char *s = json_dumps(val, JSON_INDENT(3));
  629. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  630. free(s);
  631. }
  632. /* JSON-RPC valid response returns a non-null 'result',
  633. * and a null 'error'.
  634. */
  635. res_val = json_object_get(val, "result");
  636. err_val = json_object_get(val, "error");
  637. if (!res_val ||(err_val && !json_is_null(err_val))) {
  638. char *s;
  639. if (err_val)
  640. s = json_dumps(err_val, JSON_INDENT(3));
  641. else
  642. s = strdup("(unknown reason)");
  643. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  644. free(s);
  645. goto err_out;
  646. }
  647. if (hi.reason) {
  648. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  649. free(hi.reason);
  650. hi.reason = NULL;
  651. }
  652. successful_connect = true;
  653. databuf_free(&all_data);
  654. curl_slist_free_all(headers);
  655. curl_easy_reset(curl);
  656. return val;
  657. err_out:
  658. databuf_free(&all_data);
  659. curl_slist_free_all(headers);
  660. curl_easy_reset(curl);
  661. if (!successful_connect)
  662. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  663. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  664. return NULL;
  665. }
  666. #define PROXY_HTTP CURLPROXY_HTTP
  667. #define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0
  668. #define PROXY_SOCKS4 CURLPROXY_SOCKS4
  669. #define PROXY_SOCKS5 CURLPROXY_SOCKS5
  670. #define PROXY_SOCKS4A CURLPROXY_SOCKS4A
  671. #define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME
  672. #else /* HAVE_LIBCURL */
  673. #define PROXY_HTTP 0
  674. #define PROXY_HTTP_1_0 1
  675. #define PROXY_SOCKS4 2
  676. #define PROXY_SOCKS5 3
  677. #define PROXY_SOCKS4A 4
  678. #define PROXY_SOCKS5H 5
  679. #endif /* HAVE_LIBCURL */
  680. static struct {
  681. const char *name;
  682. proxytypes_t proxytype;
  683. } proxynames[] = {
  684. { "http:", PROXY_HTTP },
  685. { "http0:", PROXY_HTTP_1_0 },
  686. { "socks4:", PROXY_SOCKS4 },
  687. { "socks5:", PROXY_SOCKS5 },
  688. { "socks4a:", PROXY_SOCKS4A },
  689. { "socks5h:", PROXY_SOCKS5H },
  690. { NULL, 0 }
  691. };
  692. const char *proxytype(proxytypes_t proxytype)
  693. {
  694. int i;
  695. for (i = 0; proxynames[i].name; i++)
  696. if (proxynames[i].proxytype == proxytype)
  697. return proxynames[i].name;
  698. return "invalid";
  699. }
  700. char *get_proxy(char *url, struct pool *pool)
  701. {
  702. pool->rpc_proxy = NULL;
  703. char *split;
  704. int plen, len, i;
  705. for (i = 0; proxynames[i].name; i++) {
  706. plen = strlen(proxynames[i].name);
  707. if (strncmp(url, proxynames[i].name, plen) == 0) {
  708. if (!(split = strchr(url, '|')))
  709. return url;
  710. *split = '\0';
  711. len = split - url;
  712. pool->rpc_proxy = cgmalloc(1 + len - plen);
  713. strcpy(pool->rpc_proxy, url + plen);
  714. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  715. pool->rpc_proxytype = proxynames[i].proxytype;
  716. url = split + 1;
  717. break;
  718. }
  719. }
  720. return url;
  721. }
  722. /* Adequate size s==len*2 + 1 must be alloced to use this variant */
  723. void __bin2hex(char *s, const unsigned char *p, size_t len)
  724. {
  725. int i;
  726. static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  727. for (i = 0; i < (int)len; i++) {
  728. *s++ = hex[p[i] >> 4];
  729. *s++ = hex[p[i] & 0xF];
  730. }
  731. *s++ = '\0';
  732. }
  733. /* Returns a malloced array string of a binary value of arbitrary length. The
  734. * array is rounded up to a 4 byte size to appease architectures that need
  735. * aligned array sizes */
  736. char *bin2hex(const unsigned char *p, size_t len)
  737. {
  738. ssize_t slen;
  739. char *s;
  740. slen = len * 2 + 1;
  741. if (slen % 4)
  742. slen += 4 - (slen % 4);
  743. s = cgcalloc(slen, 1);
  744. __bin2hex(s, p, len);
  745. return s;
  746. }
  747. static const int hex2bin_tbl[256] = {
  748. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  749. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  750. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  751. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  752. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  753. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  754. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  755. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  756. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  757. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  758. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  759. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  760. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  761. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  762. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  763. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  764. };
  765. /* Does the reverse of bin2hex but does not allocate any ram */
  766. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  767. {
  768. int nibble1, nibble2;
  769. unsigned char idx;
  770. bool ret = false;
  771. while (*hexstr && len) {
  772. if (unlikely(!hexstr[1])) {
  773. applog(LOG_ERR, "hex2bin str truncated");
  774. return ret;
  775. }
  776. idx = *hexstr++;
  777. nibble1 = hex2bin_tbl[idx];
  778. idx = *hexstr++;
  779. nibble2 = hex2bin_tbl[idx];
  780. if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
  781. applog(LOG_ERR, "hex2bin scan failed");
  782. return ret;
  783. }
  784. *p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
  785. --len;
  786. }
  787. if (likely(len == 0 && *hexstr == 0))
  788. ret = true;
  789. return ret;
  790. }
  791. static bool _valid_hex(char *s, const char *file, const char *func, const int line)
  792. {
  793. bool ret = false;
  794. int i, len;
  795. if (unlikely(!s)) {
  796. applog(LOG_ERR, "Null string passed to valid_hex from"IN_FMT_FFL, file, func, line);
  797. return ret;
  798. }
  799. len = strlen(s);
  800. for (i = 0; i < len; i++) {
  801. unsigned char idx = s[i];
  802. if (unlikely(hex2bin_tbl[idx] < 0)) {
  803. applog(LOG_ERR, "Invalid char 0x%x passed to valid_hex from"IN_FMT_FFL, idx, file, func, line);
  804. return ret;
  805. }
  806. }
  807. ret = true;
  808. return ret;
  809. }
  810. #define valid_hex(s) _valid_hex(s, __FILE__, __func__, __LINE__)
  811. static bool _valid_ascii(char *s, const char *file, const char *func, const int line)
  812. {
  813. bool ret = false;
  814. int i, len;
  815. if (unlikely(!s)) {
  816. applog(LOG_ERR, "Null string passed to valid_ascii from"IN_FMT_FFL, file, func, line);
  817. return ret;
  818. }
  819. len = strlen(s);
  820. if (unlikely(!len)) {
  821. applog(LOG_ERR, "Zero length string passed to valid_ascii from"IN_FMT_FFL, file, func, line);
  822. return ret;
  823. }
  824. for (i = 0; i < len; i++) {
  825. unsigned char idx = s[i];
  826. if (unlikely(idx < 32 || idx > 126)) {
  827. applog(LOG_ERR, "Invalid char 0x%x passed to valid_ascii from"IN_FMT_FFL, idx, file, func, line);
  828. return ret;
  829. }
  830. }
  831. ret = true;
  832. return ret;
  833. }
  834. #define valid_ascii(s) _valid_ascii(s, __FILE__, __func__, __LINE__)
  835. static const int b58tobin_tbl[] = {
  836. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  837. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  838. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  839. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1,
  840. -1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1,
  841. 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1,
  842. -1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46,
  843. 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57
  844. };
  845. /* b58bin should always be at least 25 bytes long and already checked to be
  846. * valid. */
  847. void b58tobin(unsigned char *b58bin, const char *b58)
  848. {
  849. uint32_t c, bin32[7];
  850. int len, i, j;
  851. uint64_t t;
  852. memset(bin32, 0, 7 * sizeof(uint32_t));
  853. len = strlen(b58);
  854. for (i = 0; i < len; i++) {
  855. c = b58[i];
  856. c = b58tobin_tbl[c];
  857. for (j = 6; j >= 0; j--) {
  858. t = ((uint64_t)bin32[j]) * 58 + c;
  859. c = (t & 0x3f00000000ull) >> 32;
  860. bin32[j] = t & 0xffffffffull;
  861. }
  862. }
  863. *(b58bin++) = bin32[0] & 0xff;
  864. for (i = 1; i < 7; i++) {
  865. *((uint32_t *)b58bin) = htobe32(bin32[i]);
  866. b58bin += sizeof(uint32_t);
  867. }
  868. }
  869. void address_to_pubkeyhash(unsigned char *pkh, const char *addr)
  870. {
  871. unsigned char b58bin[25];
  872. memset(b58bin, 0, 25);
  873. b58tobin(b58bin, addr);
  874. pkh[0] = 0x76;
  875. pkh[1] = 0xa9;
  876. pkh[2] = 0x14;
  877. cg_memcpy(&pkh[3], &b58bin[1], 20);
  878. pkh[23] = 0x88;
  879. pkh[24] = 0xac;
  880. }
  881. /* For encoding nHeight into coinbase, return how many bytes were used */
  882. int ser_number(unsigned char *s, int32_t val)
  883. {
  884. int32_t *i32 = (int32_t *)&s[1];
  885. int len;
  886. if (val < 17) {
  887. s[0] = 0x50 + val;
  888. return 1;
  889. }
  890. if (val < 128)
  891. len = 1;
  892. else if (val < 32768)
  893. len = 2;
  894. else if (val < 8388608)
  895. len = 3;
  896. else
  897. len = 4;
  898. *i32 = htole32(val);
  899. s[0] = len++;
  900. return len;
  901. }
  902. /* For encoding variable length strings */
  903. unsigned char *ser_string(char *s, int *slen)
  904. {
  905. size_t len = strlen(s);
  906. unsigned char *ret;
  907. ret = cgmalloc(1 + len + 8); // Leave room for largest size
  908. if (len < 253) {
  909. ret[0] = len;
  910. cg_memcpy(ret + 1, s, len);
  911. *slen = len + 1;
  912. } else if (len < 0x10000) {
  913. uint16_t *u16 = (uint16_t *)&ret[1];
  914. ret[0] = 253;
  915. *u16 = htobe16(len);
  916. cg_memcpy(ret + 3, s, len);
  917. *slen = len + 3;
  918. } else {
  919. /* size_t is only 32 bit on many platforms anyway */
  920. uint32_t *u32 = (uint32_t *)&ret[1];
  921. ret[0] = 254;
  922. *u32 = htobe32(len);
  923. cg_memcpy(ret + 5, s, len);
  924. *slen = len + 5;
  925. }
  926. return ret;
  927. }
  928. bool fulltest(const unsigned char *hash, const unsigned char *target)
  929. {
  930. uint32_t *hash32 = (uint32_t *)hash;
  931. uint32_t *target32 = (uint32_t *)target;
  932. bool rc = true;
  933. int i;
  934. for (i = 28 / 4; i >= 0; i--) {
  935. uint32_t h32tmp = le32toh(hash32[i]);
  936. uint32_t t32tmp = le32toh(target32[i]);
  937. if (h32tmp > t32tmp) {
  938. rc = false;
  939. break;
  940. }
  941. if (h32tmp < t32tmp) {
  942. rc = true;
  943. break;
  944. }
  945. }
  946. if (opt_debug) {
  947. unsigned char hash_swap[32], target_swap[32];
  948. char *hash_str, *target_str;
  949. swab256(hash_swap, hash);
  950. swab256(target_swap, target);
  951. hash_str = bin2hex(hash_swap, 32);
  952. target_str = bin2hex(target_swap, 32);
  953. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  954. hash_str,
  955. target_str,
  956. rc ? "YES (hash <= target)" :
  957. "no (false positive; hash > target)");
  958. free(hash_str);
  959. free(target_str);
  960. }
  961. return rc;
  962. }
  963. struct thread_q *tq_new(void)
  964. {
  965. struct thread_q *tq;
  966. tq = cgcalloc(1, sizeof(*tq));
  967. INIT_LIST_HEAD(&tq->q);
  968. pthread_mutex_init(&tq->mutex, NULL);
  969. pthread_cond_init(&tq->cond, NULL);
  970. return tq;
  971. }
  972. void tq_free(struct thread_q *tq)
  973. {
  974. struct tq_ent *ent, *iter;
  975. if (!tq)
  976. return;
  977. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  978. list_del(&ent->q_node);
  979. free(ent);
  980. }
  981. pthread_cond_destroy(&tq->cond);
  982. pthread_mutex_destroy(&tq->mutex);
  983. memset(tq, 0, sizeof(*tq)); /* poison */
  984. free(tq);
  985. }
  986. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  987. {
  988. mutex_lock(&tq->mutex);
  989. tq->frozen = frozen;
  990. pthread_cond_signal(&tq->cond);
  991. mutex_unlock(&tq->mutex);
  992. }
  993. void tq_freeze(struct thread_q *tq)
  994. {
  995. tq_freezethaw(tq, true);
  996. }
  997. void tq_thaw(struct thread_q *tq)
  998. {
  999. tq_freezethaw(tq, false);
  1000. }
  1001. bool tq_push(struct thread_q *tq, void *data)
  1002. {
  1003. struct tq_ent *ent;
  1004. bool rc = true;
  1005. ent = cgcalloc(1, sizeof(*ent));
  1006. ent->data = data;
  1007. INIT_LIST_HEAD(&ent->q_node);
  1008. mutex_lock(&tq->mutex);
  1009. if (!tq->frozen) {
  1010. list_add_tail(&ent->q_node, &tq->q);
  1011. } else {
  1012. free(ent);
  1013. rc = false;
  1014. }
  1015. pthread_cond_signal(&tq->cond);
  1016. mutex_unlock(&tq->mutex);
  1017. return rc;
  1018. }
  1019. void *tq_pop(struct thread_q *tq)
  1020. {
  1021. struct tq_ent *ent;
  1022. void *rval = NULL;
  1023. int rc;
  1024. mutex_lock(&tq->mutex);
  1025. if (!list_empty(&tq->q))
  1026. goto pop;
  1027. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  1028. if (rc)
  1029. goto out;
  1030. if (list_empty(&tq->q))
  1031. goto out;
  1032. pop:
  1033. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  1034. rval = ent->data;
  1035. list_del(&ent->q_node);
  1036. free(ent);
  1037. out:
  1038. mutex_unlock(&tq->mutex);
  1039. return rval;
  1040. }
  1041. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  1042. {
  1043. cgsem_init(&thr->sem);
  1044. return pthread_create(&thr->pth, attr, start, arg);
  1045. }
  1046. void thr_info_cancel(struct thr_info *thr)
  1047. {
  1048. if (!thr)
  1049. return;
  1050. if (PTH(thr) != 0L) {
  1051. pthread_cancel(thr->pth);
  1052. PTH(thr) = 0L;
  1053. }
  1054. cgsem_destroy(&thr->sem);
  1055. }
  1056. void subtime(struct timeval *a, struct timeval *b)
  1057. {
  1058. timersub(a, b, b);
  1059. }
  1060. void addtime(struct timeval *a, struct timeval *b)
  1061. {
  1062. timeradd(a, b, b);
  1063. }
  1064. bool time_more(struct timeval *a, struct timeval *b)
  1065. {
  1066. return timercmp(a, b, >);
  1067. }
  1068. bool time_less(struct timeval *a, struct timeval *b)
  1069. {
  1070. return timercmp(a, b, <);
  1071. }
  1072. void copy_time(struct timeval *dest, const struct timeval *src)
  1073. {
  1074. cg_memcpy(dest, src, sizeof(struct timeval));
  1075. }
  1076. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  1077. {
  1078. val->tv_sec = spec->tv_sec;
  1079. val->tv_usec = spec->tv_nsec / 1000;
  1080. }
  1081. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  1082. {
  1083. spec->tv_sec = val->tv_sec;
  1084. spec->tv_nsec = val->tv_usec * 1000;
  1085. }
  1086. void us_to_timeval(struct timeval *val, int64_t us)
  1087. {
  1088. lldiv_t tvdiv = lldiv(us, 1000000);
  1089. val->tv_sec = tvdiv.quot;
  1090. val->tv_usec = tvdiv.rem;
  1091. }
  1092. void us_to_timespec(struct timespec *spec, int64_t us)
  1093. {
  1094. lldiv_t tvdiv = lldiv(us, 1000000);
  1095. spec->tv_sec = tvdiv.quot;
  1096. spec->tv_nsec = tvdiv.rem * 1000;
  1097. }
  1098. void ms_to_timespec(struct timespec *spec, int64_t ms)
  1099. {
  1100. lldiv_t tvdiv = lldiv(ms, 1000);
  1101. spec->tv_sec = tvdiv.quot;
  1102. spec->tv_nsec = tvdiv.rem * 1000000;
  1103. }
  1104. void ms_to_timeval(struct timeval *val, int64_t ms)
  1105. {
  1106. lldiv_t tvdiv = lldiv(ms, 1000);
  1107. val->tv_sec = tvdiv.quot;
  1108. val->tv_usec = tvdiv.rem * 1000;
  1109. }
  1110. static void spec_nscheck(struct timespec *ts)
  1111. {
  1112. while (ts->tv_nsec >= 1000000000) {
  1113. ts->tv_nsec -= 1000000000;
  1114. ts->tv_sec++;
  1115. }
  1116. while (ts->tv_nsec < 0) {
  1117. ts->tv_nsec += 1000000000;
  1118. ts->tv_sec--;
  1119. }
  1120. }
  1121. void timeraddspec(struct timespec *a, const struct timespec *b)
  1122. {
  1123. a->tv_sec += b->tv_sec;
  1124. a->tv_nsec += b->tv_nsec;
  1125. spec_nscheck(a);
  1126. }
  1127. #ifdef USE_BITMAIN_SOC
  1128. static int __maybe_unused timespec_to_ms(struct timespec *ts)
  1129. {
  1130. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  1131. }
  1132. /* Subtract b from a */
  1133. static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
  1134. {
  1135. a->tv_sec -= b->tv_sec;
  1136. a->tv_nsec -= b->tv_nsec;
  1137. spec_nscheck(a);
  1138. }
  1139. #else /* USE_BITMAIN_SOC */
  1140. static int timespec_to_ms(struct timespec *ts)
  1141. {
  1142. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  1143. }
  1144. static int64_t timespec_to_us(struct timespec *ts)
  1145. {
  1146. return (int64_t)ts->tv_sec * 1000000 + ts->tv_nsec / 1000;
  1147. }
  1148. /* Subtract b from a */
  1149. static void timersubspec(struct timespec *a, const struct timespec *b)
  1150. {
  1151. a->tv_sec -= b->tv_sec;
  1152. a->tv_nsec -= b->tv_nsec;
  1153. spec_nscheck(a);
  1154. }
  1155. #endif /* USE_BITMAIN_SOC */
  1156. char *Strcasestr(char *haystack, const char *needle)
  1157. {
  1158. char *lowhay, *lowneedle, *ret;
  1159. int hlen, nlen, i, ofs;
  1160. if (unlikely(!haystack || !needle))
  1161. return NULL;
  1162. hlen = strlen(haystack);
  1163. nlen = strlen(needle);
  1164. if (!hlen || !nlen)
  1165. return NULL;
  1166. lowhay = alloca(hlen);
  1167. lowneedle = alloca(nlen);
  1168. for (i = 0; i < hlen; i++)
  1169. lowhay[i] = tolower(haystack[i]);
  1170. for (i = 0; i < nlen; i++)
  1171. lowneedle[i] = tolower(needle[i]);
  1172. ret = strstr(lowhay, lowneedle);
  1173. if (!ret)
  1174. return ret;
  1175. ofs = ret - lowhay;
  1176. return haystack + ofs;
  1177. }
  1178. char *Strsep(char **stringp, const char *delim)
  1179. {
  1180. char *ret = *stringp;
  1181. char *p;
  1182. p = (ret != NULL) ? strpbrk(ret, delim) : NULL;
  1183. if (p == NULL)
  1184. *stringp = NULL;
  1185. else {
  1186. *p = '\0';
  1187. *stringp = p + 1;
  1188. }
  1189. return ret;
  1190. }
  1191. /* Get timespec specifically for use by cond_timedwait functions which use
  1192. * CLOCK_REALTIME for expiry */
  1193. void cgcond_time(struct timespec *abstime)
  1194. {
  1195. clock_gettime(CLOCK_REALTIME, abstime);
  1196. }
  1197. /* Get CLOCK_REALTIME for display purposes */
  1198. void cgtime_real(struct timeval *tv)
  1199. {
  1200. struct timespec tp;
  1201. clock_gettime(CLOCK_REALTIME, &tp);
  1202. tv->tv_sec = tp.tv_sec;
  1203. tv->tv_usec = tp.tv_nsec / 1000;
  1204. }
  1205. #ifdef WIN32
  1206. /* Mingw32 has no strsep so create our own custom one */
  1207. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  1208. #define EPOCHFILETIME (116444736000000000LL)
  1209. /* These are cgminer specific sleep functions that use an absolute nanosecond
  1210. * resolution timer to avoid poor usleep accuracy and overruns. */
  1211. /* Return the system time as an lldiv_t in decimicroseconds. */
  1212. static void decius_time(lldiv_t *lidiv)
  1213. {
  1214. FILETIME ft;
  1215. LARGE_INTEGER li;
  1216. GetSystemTimeAsFileTime(&ft);
  1217. li.LowPart = ft.dwLowDateTime;
  1218. li.HighPart = ft.dwHighDateTime;
  1219. li.QuadPart -= EPOCHFILETIME;
  1220. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1221. *lidiv = lldiv(li.QuadPart, 10000000);
  1222. }
  1223. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  1224. * with tz set to NULL, and windows' default resolution is only 15ms, this
  1225. * gives us higher resolution times on windows. */
  1226. void cgtime(struct timeval *tv)
  1227. {
  1228. lldiv_t lidiv;
  1229. decius_time(&lidiv);
  1230. tv->tv_sec = lidiv.quot;
  1231. tv->tv_usec = lidiv.rem / 10;
  1232. }
  1233. #else /* WIN32 */
  1234. void cgtime(struct timeval *tv)
  1235. {
  1236. cgtimer_t cgt;
  1237. cgtimer_time(&cgt);
  1238. timespec_to_val(tv, &cgt);
  1239. }
  1240. int cgtimer_to_ms(cgtimer_t *cgt)
  1241. {
  1242. return timespec_to_ms(cgt);
  1243. }
  1244. /* Subtracts b from a and stores it in res. */
  1245. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1246. {
  1247. res->tv_sec = a->tv_sec - b->tv_sec;
  1248. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  1249. if (res->tv_nsec < 0) {
  1250. res->tv_nsec += 1000000000;
  1251. res->tv_sec--;
  1252. }
  1253. }
  1254. #endif /* WIN32 */
  1255. #if defined(CLOCK_MONOTONIC) && !defined(__FreeBSD__) && !defined(__APPLE__) && !defined(WIN32) /* Essentially just linux */
  1256. //#ifdef CLOCK_MONOTONIC /* Essentially just linux */
  1257. void cgtimer_time(cgtimer_t *ts_start)
  1258. {
  1259. clock_gettime(CLOCK_MONOTONIC, ts_start);
  1260. }
  1261. static void nanosleep_abstime(struct timespec *ts_end)
  1262. {
  1263. int ret;
  1264. do {
  1265. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  1266. } while (ret == EINTR);
  1267. }
  1268. /* Reentrant version of cgsleep functions allow start time to be set separately
  1269. * from the beginning of the actual sleep, allowing scheduling delays to be
  1270. * counted in the sleep. */
  1271. #ifdef USE_BITMAIN_SOC
  1272. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1273. {
  1274. struct timespec ts_end;
  1275. ms_to_timespec(&ts_end, ms);
  1276. timeraddspec(&ts_end, ts_start);
  1277. nanosleep_abstime(&ts_end);
  1278. }
  1279. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1280. {
  1281. struct timespec ts_end;
  1282. us_to_timespec(&ts_end, us);
  1283. timeraddspec(&ts_end, ts_start);
  1284. nanosleep_abstime(&ts_end);
  1285. }
  1286. #else /* USE_BITMAIN_SOC */
  1287. int cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1288. {
  1289. struct timespec ts_end, ts_diff;
  1290. int msdiff;
  1291. ms_to_timespec(&ts_end, ms);
  1292. timeraddspec(&ts_end, ts_start);
  1293. cgtimer_time(&ts_diff);
  1294. /* Should be a negative value if we still have to sleep */
  1295. timersubspec(&ts_diff, &ts_end);
  1296. msdiff = -timespec_to_ms(&ts_diff);
  1297. if (msdiff <= 0)
  1298. return 0;
  1299. nanosleep_abstime(&ts_end);
  1300. return msdiff;
  1301. }
  1302. int64_t cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1303. {
  1304. struct timespec ts_end, ts_diff;
  1305. int64_t usdiff;
  1306. us_to_timespec(&ts_end, us);
  1307. timeraddspec(&ts_end, ts_start);
  1308. cgtimer_time(&ts_diff);
  1309. usdiff = -timespec_to_us(&ts_diff);
  1310. if (usdiff <= 0)
  1311. return 0;
  1312. nanosleep_abstime(&ts_end);
  1313. return usdiff;
  1314. }
  1315. #endif /* USE_BITMAIN_SOC */
  1316. #else /* CLOCK_MONOTONIC */
  1317. #ifdef __MACH__
  1318. #include <mach/clock.h>
  1319. #include <mach/mach.h>
  1320. void cgtimer_time(cgtimer_t *ts_start)
  1321. {
  1322. clock_serv_t cclock;
  1323. mach_timespec_t mts;
  1324. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  1325. clock_get_time(cclock, &mts);
  1326. mach_port_deallocate(mach_task_self(), cclock);
  1327. ts_start->tv_sec = mts.tv_sec;
  1328. ts_start->tv_nsec = mts.tv_nsec;
  1329. }
  1330. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  1331. void cgtimer_time(cgtimer_t *ts_start)
  1332. {
  1333. struct timeval tv;
  1334. cgtime(&tv);
  1335. ts_start->tv_sec = tv.tv_sec;
  1336. ts_start->tv_nsec = tv.tv_usec * 1000;
  1337. }
  1338. #endif /* __MACH__ */
  1339. #ifdef WIN32
  1340. /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
  1341. * typedef, allowing us to have sub-microsecond resolution for times, do simple
  1342. * arithmetic for timer calculations, and use windows' own hTimers to get
  1343. * accurate absolute timeouts. */
  1344. int cgtimer_to_ms(cgtimer_t *cgt)
  1345. {
  1346. return (int)(cgt->QuadPart / 10000LL);
  1347. }
  1348. /* Subtracts b from a and stores it in res. */
  1349. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1350. {
  1351. res->QuadPart = a->QuadPart - b->QuadPart;
  1352. }
  1353. /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
  1354. * timeouts with hTimers. */
  1355. void cgtimer_time(cgtimer_t *ts_start)
  1356. {
  1357. FILETIME ft;
  1358. GetSystemTimeAsFileTime(&ft);
  1359. ts_start->LowPart = ft.dwLowDateTime;
  1360. ts_start->HighPart = ft.dwHighDateTime;
  1361. }
  1362. static void liSleep(LARGE_INTEGER *li, int timeout)
  1363. {
  1364. HANDLE hTimer;
  1365. DWORD ret;
  1366. if (unlikely(timeout <= 0))
  1367. return;
  1368. hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  1369. if (unlikely(!hTimer))
  1370. quit(1, "Failed to create hTimer in liSleep");
  1371. ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
  1372. if (unlikely(!ret))
  1373. quit(1, "Failed to SetWaitableTimer in liSleep");
  1374. /* We still use a timeout as a sanity check in case the system time
  1375. * is changed while we're running */
  1376. ret = WaitForSingleObject(hTimer, timeout);
  1377. if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
  1378. quit(1, "Failed to WaitForSingleObject in liSleep");
  1379. CloseHandle(hTimer);
  1380. }
  1381. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1382. {
  1383. LARGE_INTEGER li;
  1384. li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
  1385. liSleep(&li, ms);
  1386. }
  1387. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1388. {
  1389. LARGE_INTEGER li;
  1390. int ms;
  1391. li.QuadPart = ts_start->QuadPart + us * 10LL;
  1392. ms = us / 1000;
  1393. if (!ms)
  1394. ms = 1;
  1395. liSleep(&li, ms);
  1396. }
  1397. #else /* WIN32 */
  1398. static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  1399. {
  1400. struct timespec now;
  1401. timeraddspec(ts_diff, ts_start);
  1402. cgtimer_time(&now);
  1403. timersubspec(ts_diff, &now);
  1404. if (unlikely(ts_diff->tv_sec < 0))
  1405. return;
  1406. nanosleep(ts_diff, NULL);
  1407. }
  1408. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1409. {
  1410. struct timespec ts_diff;
  1411. ms_to_timespec(&ts_diff, ms);
  1412. cgsleep_spec(&ts_diff, ts_start);
  1413. }
  1414. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1415. {
  1416. struct timespec ts_diff;
  1417. us_to_timespec(&ts_diff, us);
  1418. cgsleep_spec(&ts_diff, ts_start);
  1419. }
  1420. #endif /* WIN32 */
  1421. #endif /* CLOCK_MONOTONIC */
  1422. void cgsleep_ms(int ms)
  1423. {
  1424. cgtimer_t ts_start;
  1425. cgsleep_prepare_r(&ts_start);
  1426. cgsleep_ms_r(&ts_start, ms);
  1427. }
  1428. static void busywait_us(int64_t us)
  1429. {
  1430. struct timeval diff, end, now;
  1431. cgtime(&end);
  1432. us_to_timeval(&diff, us);
  1433. addtime(&diff, &end);
  1434. do {
  1435. sched_yield();
  1436. cgtime(&now);
  1437. } while (time_less(&now, &end));
  1438. }
  1439. void cgsleep_us(int64_t us)
  1440. {
  1441. cgtimer_t ts_start;
  1442. /* Most timer resolution is unlikely to be able to sleep accurately
  1443. * for less than 1ms so busywait instead. */
  1444. if (us < 1000)
  1445. return busywait_us(us);
  1446. cgsleep_prepare_r(&ts_start);
  1447. cgsleep_us_r(&ts_start, us);
  1448. }
  1449. /* Returns the microseconds difference between end and start times as a double */
  1450. double us_tdiff(struct timeval *end, struct timeval *start)
  1451. {
  1452. /* Sanity check. We should only be using this for small differences so
  1453. * limit the max to 60 seconds. */
  1454. if (unlikely(end->tv_sec - start->tv_sec > 60))
  1455. return 60000000;
  1456. return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
  1457. }
  1458. /* Returns the milliseconds difference between end and start times */
  1459. int ms_tdiff(struct timeval *end, struct timeval *start)
  1460. {
  1461. /* Like us_tdiff, limit to 1 hour. */
  1462. if (unlikely(end->tv_sec - start->tv_sec > 3600))
  1463. return 3600000;
  1464. return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
  1465. }
  1466. /* Returns the seconds difference between end and start times as a double */
  1467. double tdiff(struct timeval *end, struct timeval *start)
  1468. {
  1469. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1470. }
  1471. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1472. {
  1473. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1474. char url_address[256], port[6];
  1475. int url_len, port_len = 0;
  1476. *sockaddr_url = url;
  1477. url_begin = strstr(url, "//");
  1478. if (!url_begin)
  1479. url_begin = url;
  1480. else
  1481. url_begin += 2;
  1482. /* Look for numeric ipv6 entries */
  1483. ipv6_begin = strstr(url_begin, "[");
  1484. ipv6_end = strstr(url_begin, "]");
  1485. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1486. url_end = strstr(ipv6_end, ":");
  1487. else
  1488. url_end = strstr(url_begin, ":");
  1489. if (url_end) {
  1490. url_len = url_end - url_begin;
  1491. port_len = strlen(url_begin) - url_len - 1;
  1492. if (port_len < 1)
  1493. return false;
  1494. port_start = url_end + 1;
  1495. } else
  1496. url_len = strlen(url_begin);
  1497. if (url_len < 1)
  1498. return false;
  1499. /* Get rid of the [] */
  1500. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) {
  1501. url_len -= 2;
  1502. url_begin++;
  1503. }
  1504. snprintf(url_address, 254, "%.*s", url_len, url_begin);
  1505. if (port_len) {
  1506. char *slash;
  1507. snprintf(port, 6, "%.*s", port_len, port_start);
  1508. slash = strpbrk(port, "/#");
  1509. if (slash)
  1510. *slash = '\0';
  1511. } else
  1512. strcpy(port, "80");
  1513. *sockaddr_port = strdup(port);
  1514. *sockaddr_url = strdup(url_address);
  1515. return true;
  1516. }
  1517. enum send_ret {
  1518. SEND_OK,
  1519. SEND_SELECTFAIL,
  1520. SEND_SENDFAIL,
  1521. SEND_INACTIVE
  1522. };
  1523. /* Send a single command across a socket, appending \n to it. This should all
  1524. * be done under stratum lock except when first establishing the socket */
  1525. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1526. {
  1527. SOCKETTYPE sock = pool->sock;
  1528. ssize_t ssent = 0;
  1529. strcat(s, "\n");
  1530. len++;
  1531. while (len > 0 ) {
  1532. struct timeval timeout = {1, 0};
  1533. ssize_t sent;
  1534. fd_set wd;
  1535. retry:
  1536. FD_ZERO(&wd);
  1537. FD_SET(sock, &wd);
  1538. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1539. if (interrupted())
  1540. goto retry;
  1541. return SEND_SELECTFAIL;
  1542. }
  1543. #ifdef __APPLE__
  1544. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1545. #elif WIN32
  1546. sent = send(pool->sock, s + ssent, len, 0);
  1547. #else
  1548. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1549. #endif
  1550. if (sent < 0) {
  1551. if (!sock_blocks())
  1552. return SEND_SENDFAIL;
  1553. sent = 0;
  1554. }
  1555. ssent += sent;
  1556. len -= sent;
  1557. }
  1558. pool->cgminer_pool_stats.times_sent++;
  1559. pool->cgminer_pool_stats.bytes_sent += ssent;
  1560. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1561. return SEND_OK;
  1562. }
  1563. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1564. {
  1565. enum send_ret ret = SEND_INACTIVE;
  1566. if (opt_protocol)
  1567. applog(LOG_DEBUG, "SEND: %s", s);
  1568. mutex_lock(&pool->stratum_lock);
  1569. if (pool->stratum_active)
  1570. ret = __stratum_send(pool, s, len);
  1571. mutex_unlock(&pool->stratum_lock);
  1572. /* This is to avoid doing applog under stratum_lock */
  1573. switch (ret) {
  1574. default:
  1575. case SEND_OK:
  1576. break;
  1577. case SEND_SELECTFAIL:
  1578. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1579. suspend_stratum(pool);
  1580. break;
  1581. case SEND_SENDFAIL:
  1582. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1583. suspend_stratum(pool);
  1584. break;
  1585. case SEND_INACTIVE:
  1586. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1587. break;
  1588. }
  1589. return (ret == SEND_OK);
  1590. }
  1591. static bool socket_full(struct pool *pool, int wait)
  1592. {
  1593. SOCKETTYPE sock = pool->sock;
  1594. struct timeval timeout;
  1595. fd_set rd;
  1596. if (unlikely(wait < 0))
  1597. wait = 0;
  1598. FD_ZERO(&rd);
  1599. FD_SET(sock, &rd);
  1600. timeout.tv_usec = 0;
  1601. timeout.tv_sec = wait;
  1602. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1603. return true;
  1604. return false;
  1605. }
  1606. /* Check to see if Santa's been good to you */
  1607. bool sock_full(struct pool *pool)
  1608. {
  1609. if (strlen(pool->sockbuf))
  1610. return true;
  1611. return (socket_full(pool, 0));
  1612. }
  1613. static void clear_sockbuf(struct pool *pool)
  1614. {
  1615. if (likely(pool->sockbuf))
  1616. strcpy(pool->sockbuf, "");
  1617. }
  1618. static void clear_sock(struct pool *pool)
  1619. {
  1620. ssize_t n;
  1621. mutex_lock(&pool->stratum_lock);
  1622. do {
  1623. if (pool->sock)
  1624. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1625. else
  1626. n = 0;
  1627. } while (n > 0);
  1628. mutex_unlock(&pool->stratum_lock);
  1629. clear_sockbuf(pool);
  1630. }
  1631. /* Realloc memory to new size and zero any extra memory added */
  1632. void ckrecalloc(void **ptr, size_t old, size_t new, const char *file, const char *func, const int line)
  1633. {
  1634. if (new == old)
  1635. return;
  1636. *ptr = _cgrealloc(*ptr, new, file, func, line);
  1637. if (new > old)
  1638. memset(*ptr + old, 0, new - old);
  1639. }
  1640. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1641. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1642. * and zeroing the new memory */
  1643. static void recalloc_sock(struct pool *pool, size_t len)
  1644. {
  1645. size_t old, new;
  1646. old = strlen(pool->sockbuf);
  1647. new = old + len + 1;
  1648. if (new < pool->sockbuf_size)
  1649. return;
  1650. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1651. // Avoid potentially recursive locking
  1652. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1653. pool->sockbuf = cgrealloc(pool->sockbuf, new);
  1654. memset(pool->sockbuf + old, 0, new - old);
  1655. pool->sockbuf_size = new;
  1656. }
  1657. /* Peeks at a socket to find the first end of line and then reads just that
  1658. * from the socket and returns that as a malloced char */
  1659. char *recv_line(struct pool *pool)
  1660. {
  1661. char *tok, *sret = NULL;
  1662. ssize_t len, buflen;
  1663. int waited = 0;
  1664. if (!strstr(pool->sockbuf, "\n")) {
  1665. struct timeval rstart, now;
  1666. cgtime(&rstart);
  1667. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1668. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1669. goto out;
  1670. }
  1671. do {
  1672. char s[RBUFSIZE];
  1673. size_t slen;
  1674. ssize_t n;
  1675. memset(s, 0, RBUFSIZE);
  1676. n = recv(pool->sock, s, RECVSIZE, 0);
  1677. if (!n) {
  1678. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1679. suspend_stratum(pool);
  1680. break;
  1681. }
  1682. cgtime(&now);
  1683. waited = tdiff(&now, &rstart);
  1684. if (n < 0) {
  1685. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1686. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1687. suspend_stratum(pool);
  1688. break;
  1689. }
  1690. } else {
  1691. slen = strlen(s);
  1692. recalloc_sock(pool, slen);
  1693. strcat(pool->sockbuf, s);
  1694. }
  1695. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1696. }
  1697. buflen = strlen(pool->sockbuf);
  1698. tok = strtok(pool->sockbuf, "\n");
  1699. if (!tok) {
  1700. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1701. goto out;
  1702. }
  1703. sret = strdup(tok);
  1704. len = strlen(sret);
  1705. /* Copy what's left in the buffer after the \n, including the
  1706. * terminating \0 */
  1707. if (buflen > len + 1)
  1708. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1709. else
  1710. strcpy(pool->sockbuf, "");
  1711. pool->cgminer_pool_stats.times_received++;
  1712. pool->cgminer_pool_stats.bytes_received += len;
  1713. pool->cgminer_pool_stats.net_bytes_received += len;
  1714. out:
  1715. if (!sret)
  1716. clear_sock(pool);
  1717. else if (opt_protocol)
  1718. applog(LOG_DEBUG, "RECVD: %s", sret);
  1719. return sret;
  1720. }
  1721. /* Extracts a string value from a json array with error checking. To be used
  1722. * when the value of the string returned is only examined and not to be stored.
  1723. * See json_array_string below */
  1724. static char *__json_array_string(json_t *val, unsigned int entry)
  1725. {
  1726. json_t *arr_entry;
  1727. if (json_is_null(val))
  1728. return NULL;
  1729. if (!json_is_array(val))
  1730. return NULL;
  1731. if (entry > json_array_size(val))
  1732. return NULL;
  1733. arr_entry = json_array_get(val, entry);
  1734. if (!json_is_string(arr_entry))
  1735. return NULL;
  1736. return (char *)json_string_value(arr_entry);
  1737. }
  1738. /* Creates a freshly malloced dup of __json_array_string */
  1739. static char *json_array_string(json_t *val, unsigned int entry)
  1740. {
  1741. char *buf = __json_array_string(val, entry);
  1742. if (buf)
  1743. return strdup(buf);
  1744. return NULL;
  1745. }
  1746. static char *blank_merkle = "0000000000000000000000000000000000000000000000000000000000000000";
  1747. #ifdef HAVE_LIBCURL
  1748. static void decode_exit(struct pool *pool, char *cb)
  1749. {
  1750. CURL *curl = curl_easy_init();
  1751. char *decreq, *s;
  1752. json_t *val;
  1753. int dummy;
  1754. if (!opt_btcd && !sleep(3) && !opt_btcd) {
  1755. applog(LOG_ERR, "No bitcoind specified, unable to decode coinbase.");
  1756. exit(1);
  1757. }
  1758. decreq = cgmalloc(strlen(cb) + 256);
  1759. sprintf(decreq, "{\"id\": 0, \"method\": \"decoderawtransaction\", \"params\": [\"%s\"]}\n",
  1760. cb);
  1761. val = json_rpc_call(curl, opt_btcd->rpc_url, opt_btcd->rpc_userpass, decreq,
  1762. false, false, &dummy, opt_btcd, false);
  1763. free(decreq);
  1764. if (!val) {
  1765. applog(LOG_ERR, "Failed json_rpc_call to btcd %s", opt_btcd->rpc_url);
  1766. exit(1);
  1767. }
  1768. s = json_dumps(val, JSON_INDENT(4));
  1769. printf("Pool %s:\n%s\n", pool->rpc_url, s);
  1770. free(s);
  1771. exit(0);
  1772. }
  1773. #else
  1774. static void decode_exit(struct pool __maybe_unused *pool, char __maybe_unused *b)
  1775. {
  1776. }
  1777. #endif
  1778. static int calculate_num_bits(int num)
  1779. {
  1780. int ret=0;
  1781. while(num != 0)
  1782. {
  1783. ret++;
  1784. num /= 16;
  1785. }
  1786. return ret;
  1787. }
  1788. static void get_vmask(struct pool *pool, char *bbversion)
  1789. {
  1790. char defaultStr[9]= "00000000";
  1791. int bversion, num_bits, i, j;
  1792. uint8_t buffer[4] = {};
  1793. uint32_t uiMagicNum;
  1794. char *tmpstr;
  1795. uint32_t *p1;
  1796. p1 = (uint32_t *)buffer;
  1797. bversion = strtol(bbversion, NULL, 16);
  1798. for (i = 0; i < 4; i++) {
  1799. uiMagicNum = bversion | pool->vmask_003[i];
  1800. //printf("[ccx]uiMagicNum:0x%x. \n", uiMagicNum);
  1801. *p1 = bswap_32(uiMagicNum);
  1802. //printf("[ccx]*p1:0x%x. \n", *p1);
  1803. switch(i) {
  1804. case 0:
  1805. pool->vmask_001[8] = *p1;
  1806. break;
  1807. case 1:
  1808. pool->vmask_001[4] = *p1;
  1809. break;
  1810. case 2:
  1811. pool->vmask_001[2] = *p1;
  1812. break;
  1813. case 3:
  1814. pool->vmask_001[0] = *p1;
  1815. break;
  1816. default:
  1817. break;
  1818. }
  1819. }
  1820. for (i = 0; i < 16; i++) {
  1821. if ((i!= 2) && (i!=4) && (i!=8))
  1822. pool->vmask_001[i] = pool->vmask_001[0];
  1823. }
  1824. for (i = 0; i < 16; i++)
  1825. memcpy(pool->vmask_002[i], defaultStr, 9);
  1826. for (i = 0; i < 3; i++) {
  1827. char cMask[12];
  1828. tmpstr = (char *)cgcalloc(9, 1);
  1829. num_bits = calculate_num_bits(pool->vmask_003[i]);
  1830. for (j = 0; j < (8-num_bits); j++)
  1831. tmpstr[j] = '0';
  1832. snprintf(cMask, 9, "%x", pool->vmask_003[i]);
  1833. memcpy(tmpstr + 8 - num_bits, cMask, num_bits);
  1834. tmpstr[8] = '\0';
  1835. //printf("[ccx]tmpstr:%s. \n", tmpstr);
  1836. switch(i) {
  1837. case 0:
  1838. memcpy(pool->vmask_002[8], tmpstr, 9);
  1839. break;
  1840. case 1:
  1841. memcpy(pool->vmask_002[4], tmpstr, 9);
  1842. break;
  1843. case 2:
  1844. memcpy(pool->vmask_002[2], tmpstr, 9);
  1845. break;
  1846. default:
  1847. break;
  1848. }
  1849. free(tmpstr);
  1850. }
  1851. }
  1852. static bool set_vmask(struct pool *pool, json_t *val)
  1853. {
  1854. int mask, tmpMask = 0, cnt = 0, i, rem;
  1855. const char *version_mask;
  1856. version_mask = json_string_value(val);
  1857. applog(LOG_INFO, "Pool %d version_mask:%s.", pool->pool_no, version_mask);
  1858. mask = strtol(version_mask, NULL, 16);
  1859. if (!mask)
  1860. return false;
  1861. pool->vmask_003[0] = mask;
  1862. while (mask % 16 == 0) {
  1863. cnt++;
  1864. mask /= 16;
  1865. }
  1866. if ((rem = mask % 16))
  1867. tmpMask = rem;
  1868. else if ((rem = mask % 8))
  1869. tmpMask = rem;
  1870. else if ((rem = mask % 4))
  1871. tmpMask = rem;
  1872. else if ((rem = mask % 2))
  1873. tmpMask = rem;
  1874. for (i = 0; i < cnt; i++)
  1875. tmpMask *= 16;
  1876. pool->vmask_003[2] = tmpMask;
  1877. pool->vmask_003[1] = pool->vmask_003[0] - tmpMask;
  1878. return true;
  1879. }
  1880. #ifdef USE_VMASK
  1881. #define STRATUM_VERSION_ROLLING "version-rolling"
  1882. #define STRATUM_VERSION_ROLLING_LEN (sizeof(STRATUM_VERSION_ROLLING) - 1)
  1883. /**
  1884. * Configures stratum mining based on connected hardware capabilities
  1885. * (version rolling etc.)
  1886. *
  1887. * Sample communication
  1888. * Request:
  1889. * {"id": 1, "method": "mining.configure", "params": [ ["version-rolling"], "version-rolling.mask": "ffffffff" }]}\n
  1890. * Response:
  1891. * {"id": 1, "result": { "version-rolling": True, "version-rolling.mask": "00003000" }, "error": null}\n
  1892. *
  1893. * @param pool
  1894. *
  1895. *
  1896. * @return
  1897. */
  1898. static bool configure_stratum_mining(struct pool *pool)
  1899. {
  1900. char s[RBUFSIZE];
  1901. char *response_str = NULL;
  1902. bool config_status = false;
  1903. bool version_rolling_status = false;
  1904. bool version_mask_valid = false;
  1905. const char *key;
  1906. json_t *response, *value, *res_val, *err_val;
  1907. json_error_t err;
  1908. #ifdef USE_GEKKO
  1909. if (!opt_gekko_boost)
  1910. return true;
  1911. #endif
  1912. snprintf(s, RBUFSIZE,
  1913. "{\"id\": %d, \"method\": \"mining.configure\", \"params\": "
  1914. "[[\""STRATUM_VERSION_ROLLING"\"], "
  1915. "{\""STRATUM_VERSION_ROLLING".mask\": \"%x\""
  1916. "}]}",
  1917. swork_id++, 0xffffffff);
  1918. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1919. applog(LOG_DEBUG, "Failed to send mining.configure");
  1920. goto out;
  1921. }
  1922. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1923. applog(LOG_DEBUG, "Timed out waiting for response in %s", __FUNCTION__);
  1924. goto out;
  1925. }
  1926. response_str = recv_line(pool);
  1927. if (!response_str)
  1928. goto out;
  1929. response = JSON_LOADS(response_str, &err);
  1930. free(response_str);
  1931. res_val = json_object_get(response, "result");
  1932. err_val = json_object_get(response, "error");
  1933. if (!res_val || json_is_null(res_val) ||
  1934. (err_val && !json_is_null(err_val))) {
  1935. char *ss;
  1936. if (err_val)
  1937. ss = json_dumps(err_val, JSON_INDENT(3));
  1938. else
  1939. ss = strdup("(unknown reason)");
  1940. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1941. free(ss);
  1942. goto json_response_error;
  1943. }
  1944. json_object_foreach(res_val, key, value) {
  1945. if (!strcasecmp(key, STRATUM_VERSION_ROLLING) &&
  1946. strlen(key) == STRATUM_VERSION_ROLLING_LEN)
  1947. version_rolling_status = json_boolean_value(value);
  1948. else if (!strcasecmp(key, STRATUM_VERSION_ROLLING ".mask"))
  1949. pool->vmask = version_mask_valid = set_vmask(pool, value);
  1950. else
  1951. applog(LOG_ERR, "JSON-RPC unexpected mining.configure value: %s", key);
  1952. }
  1953. /* Valid configuration for now only requires enabled version rolling and valid bit mask */
  1954. config_status = version_rolling_status && version_mask_valid;
  1955. json_response_error:
  1956. json_decref(response);
  1957. out:
  1958. return config_status;
  1959. }
  1960. #else
  1961. static inline bool configure_stratum_mining(struct pool __maybe_unused *pool)
  1962. {
  1963. return true;
  1964. }
  1965. #endif
  1966. static bool parse_notify(struct pool *pool, json_t *val)
  1967. {
  1968. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1969. *ntime, header[260];
  1970. unsigned char *cb1 = NULL, *cb2 = NULL;
  1971. size_t cb1_len, cb2_len, alloc_len;
  1972. bool clean, ret = false;
  1973. int merkles, i;
  1974. json_t *arr;
  1975. arr = json_array_get(val, 4);
  1976. if (!arr || !json_is_array(arr))
  1977. goto out;
  1978. merkles = json_array_size(arr);
  1979. job_id = json_array_string(val, 0);
  1980. prev_hash = __json_array_string(val, 1);
  1981. coinbase1 = json_array_string(val, 2);
  1982. coinbase2 = json_array_string(val, 3);
  1983. bbversion = __json_array_string(val, 5);
  1984. nbit = __json_array_string(val, 6);
  1985. ntime = __json_array_string(val, 7);
  1986. clean = json_is_true(json_array_get(val, 8));
  1987. get_vmask(pool, bbversion);
  1988. if (!valid_ascii(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||
  1989. !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||
  1990. !valid_hex(ntime)) {
  1991. /* Annoying but we must not leak memory */
  1992. free(job_id);
  1993. free(coinbase1);
  1994. free(coinbase2);
  1995. goto out;
  1996. }
  1997. cg_wlock(&pool->data_lock);
  1998. free(pool->swork.job_id);
  1999. pool->swork.job_id = job_id;
  2000. if (memcmp(pool->prev_hash, prev_hash, 64)) {
  2001. pool->swork.clean = true;
  2002. } else {
  2003. pool->swork.clean = clean;
  2004. }
  2005. snprintf(pool->prev_hash, 65, "%s", prev_hash);
  2006. cb1_len = strlen(coinbase1) / 2;
  2007. cb2_len = strlen(coinbase2) / 2;
  2008. snprintf(pool->bbversion, 9, "%s", bbversion);
  2009. snprintf(pool->nbit, 9, "%s", nbit);
  2010. snprintf(pool->ntime, 9, "%s", ntime);
  2011. if (pool->next_diff > 0) {
  2012. pool->sdiff = pool->next_diff;
  2013. pool->next_diff = pool->diff_after;
  2014. pool->diff_after = 0;
  2015. }
  2016. alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  2017. pool->nonce2_offset = cb1_len + pool->n1_len;
  2018. for (i = 0; i < pool->merkles; i++)
  2019. free(pool->swork.merkle_bin[i]);
  2020. if (merkles) {
  2021. pool->swork.merkle_bin = cgrealloc(pool->swork.merkle_bin,
  2022. sizeof(char *) * merkles + 1);
  2023. for (i = 0; i < merkles; i++) {
  2024. char *merkle = json_array_string(arr, i);
  2025. pool->swork.merkle_bin[i] = cgmalloc(32);
  2026. if (opt_protocol)
  2027. applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
  2028. ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  2029. free(merkle);
  2030. if (unlikely(!ret)) {
  2031. applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
  2032. goto out_unlock;
  2033. }
  2034. }
  2035. }
  2036. pool->merkles = merkles;
  2037. if (pool->merkles < 2)
  2038. pool->bad_work++;
  2039. if (clean)
  2040. pool->nonce2 = 0;
  2041. #if 0
  2042. header_len = strlen(pool->bbversion) +
  2043. strlen(pool->prev_hash);
  2044. /* merkle_hash */ 32 +
  2045. strlen(pool->ntime) +
  2046. strlen(pool->nbit) +
  2047. /* nonce */ 8 +
  2048. /* workpadding */ 96;
  2049. #endif
  2050. snprintf(header, 257,
  2051. "%s%s%s%s%s%s%s",
  2052. pool->bbversion,
  2053. pool->prev_hash,
  2054. blank_merkle,
  2055. pool->ntime,
  2056. pool->nbit,
  2057. "00000000", /* nonce */
  2058. workpadding);
  2059. ret = hex2bin(pool->header_bin, header, 128);
  2060. if (unlikely(!ret)) {
  2061. applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
  2062. goto out_unlock;
  2063. }
  2064. cb1 = alloca(cb1_len);
  2065. ret = hex2bin(cb1, coinbase1, cb1_len);
  2066. if (unlikely(!ret)) {
  2067. applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
  2068. goto out_unlock;
  2069. }
  2070. cb2 = alloca(cb2_len);
  2071. ret = hex2bin(cb2, coinbase2, cb2_len);
  2072. if (unlikely(!ret)) {
  2073. applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
  2074. goto out_unlock;
  2075. }
  2076. free(pool->coinbase);
  2077. pool->coinbase = cgcalloc(alloc_len, 1);
  2078. cg_memcpy(pool->coinbase, cb1, cb1_len);
  2079. if (pool->n1_len)
  2080. cg_memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  2081. cg_memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  2082. if (opt_debug || opt_decode) {
  2083. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  2084. if (opt_decode)
  2085. decode_exit(pool, cb);
  2086. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  2087. free(cb);
  2088. }
  2089. out_unlock:
  2090. cg_wunlock(&pool->data_lock);
  2091. if (opt_protocol) {
  2092. applog(LOG_DEBUG, "job_id: %s", job_id);
  2093. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  2094. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  2095. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  2096. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  2097. applog(LOG_DEBUG, "nbit: %s", nbit);
  2098. applog(LOG_DEBUG, "ntime: %s", ntime);
  2099. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  2100. }
  2101. free(coinbase1);
  2102. free(coinbase2);
  2103. /* A notify message is the closest stratum gets to a getwork */
  2104. pool->getwork_requested++;
  2105. total_getworks++;
  2106. if (pool == current_pool())
  2107. opt_work_update = true;
  2108. out:
  2109. return ret;
  2110. }
  2111. static bool parse_diff(struct pool *pool, json_t *val)
  2112. {
  2113. double old_diff, diff;
  2114. diff = json_number_value(json_array_get(val, 0));
  2115. if (diff <= 0)
  2116. return false;
  2117. /* We can only change one diff per notify so assume diffs are being
  2118. * stacked for successive notifies. */
  2119. cg_wlock(&pool->data_lock);
  2120. if (pool->next_diff)
  2121. pool->diff_after = diff;
  2122. else
  2123. pool->next_diff = diff;
  2124. old_diff = pool->sdiff;
  2125. cg_wunlock(&pool->data_lock);
  2126. if (old_diff != diff) {
  2127. int idiff = diff;
  2128. if ((double)idiff == diff)
  2129. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  2130. pool->pool_no, idiff);
  2131. else
  2132. applog(LOG_NOTICE, "Pool %d difficulty changed to %.1f",
  2133. pool->pool_no, diff);
  2134. } else
  2135. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  2136. diff);
  2137. return true;
  2138. }
  2139. static bool parse_extranonce(struct pool *pool, json_t *val)
  2140. {
  2141. char s[RBUFSIZE], *nonce1;
  2142. int n2size;
  2143. nonce1 = json_array_string(val, 0);
  2144. if (!valid_hex(nonce1)) {
  2145. applog(LOG_INFO, "Failed to get valid nonce1 in parse_extranonce");
  2146. return false;
  2147. }
  2148. n2size = json_integer_value(json_array_get(val, 1));
  2149. if (!n2size) {
  2150. applog(LOG_INFO, "Failed to get valid n2size in parse_extranonce");
  2151. free(nonce1);
  2152. return false;
  2153. }
  2154. cg_wlock(&pool->data_lock);
  2155. free(pool->nonce1);
  2156. pool->nonce1 = nonce1;
  2157. pool->n1_len = strlen(nonce1) / 2;
  2158. free(pool->nonce1bin);
  2159. pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
  2160. if (unlikely(!pool->nonce1bin))
  2161. quithere(1, "Failed to calloc pool->nonce1bin");
  2162. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2163. pool->n2size = n2size;
  2164. cg_wunlock(&pool->data_lock);
  2165. applog(LOG_NOTICE, "Pool %d extranonce change requested", pool->pool_no);
  2166. return true;
  2167. }
  2168. static void __suspend_stratum(struct pool *pool)
  2169. {
  2170. clear_sockbuf(pool);
  2171. pool->stratum_active = pool->stratum_notify = false;
  2172. if (pool->sock)
  2173. CLOSESOCKET(pool->sock);
  2174. pool->sock = 0;
  2175. }
  2176. static bool parse_reconnect(struct pool *pool, json_t *val)
  2177. {
  2178. char *sockaddr_url, *stratum_port, *tmp;
  2179. char *url, *port, address[256];
  2180. int port_no;
  2181. memset(address, 0, 255);
  2182. url = (char *)json_string_value(json_array_get(val, 0));
  2183. if (!url)
  2184. url = pool->sockaddr_url;
  2185. else {
  2186. char *dot_pool, *dot_reconnect;
  2187. dot_pool = strchr(pool->sockaddr_url, '.');
  2188. if (!dot_pool) {
  2189. applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
  2190. pool->sockaddr_url);
  2191. return false;
  2192. }
  2193. dot_reconnect = strchr(url, '.');
  2194. if (!dot_reconnect) {
  2195. applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
  2196. url);
  2197. return false;
  2198. }
  2199. if (strcmp(dot_pool, dot_reconnect)) {
  2200. applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
  2201. pool->sockaddr_url);
  2202. return false;
  2203. }
  2204. }
  2205. port_no = json_integer_value(json_array_get(val, 1));
  2206. if (port_no) {
  2207. port = alloca(256);
  2208. sprintf(port, "%d", port_no);
  2209. } else {
  2210. port = (char *)json_string_value(json_array_get(val, 1));
  2211. if (!port)
  2212. port = pool->stratum_port;
  2213. }
  2214. snprintf(address, 254, "%s:%s", url, port);
  2215. if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
  2216. return false;
  2217. applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
  2218. clear_pool_work(pool);
  2219. mutex_lock(&pool->stratum_lock);
  2220. __suspend_stratum(pool);
  2221. tmp = pool->sockaddr_url;
  2222. pool->sockaddr_url = sockaddr_url;
  2223. pool->stratum_url = pool->sockaddr_url;
  2224. free(tmp);
  2225. tmp = pool->stratum_port;
  2226. pool->stratum_port = stratum_port;
  2227. free(tmp);
  2228. mutex_unlock(&pool->stratum_lock);
  2229. return restart_stratum(pool);
  2230. }
  2231. static bool send_version(struct pool *pool, json_t *val)
  2232. {
  2233. json_t *id_val = json_object_get(val, "id");
  2234. char s[RBUFSIZE];
  2235. int id;
  2236. if (!id_val)
  2237. return false;
  2238. id = json_integer_value(json_object_get(val, "id"));
  2239. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\", \"error\": null}", id);
  2240. if (!stratum_send(pool, s, strlen(s)))
  2241. return false;
  2242. return true;
  2243. }
  2244. static bool send_pong(struct pool *pool, json_t *val)
  2245. {
  2246. json_t *id_val = json_object_get(val, "id");
  2247. char s[RBUFSIZE];
  2248. int id;
  2249. if (!id_val)
  2250. return false;
  2251. id = json_integer_value(json_object_get(val, "id"));
  2252. sprintf(s, "{\"id\": %d, \"result\": \"pong\", \"error\": null}", id);
  2253. if (!stratum_send(pool, s, strlen(s)))
  2254. return false;
  2255. return true;
  2256. }
  2257. static bool show_message(struct pool *pool, json_t *val)
  2258. {
  2259. char *msg;
  2260. if (!json_is_array(val))
  2261. return false;
  2262. msg = (char *)json_string_value(json_array_get(val, 0));
  2263. if (!msg)
  2264. return false;
  2265. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  2266. return true;
  2267. }
  2268. static bool parse_vmask(struct pool *pool, json_t *params)
  2269. {
  2270. bool ret = false;
  2271. if (!params) {
  2272. applog(LOG_INFO, "No params with parse_vmask given for pool %d",
  2273. pool->pool_no);
  2274. goto out;
  2275. }
  2276. if (json_is_array(params))
  2277. params = json_array_get(params, 0);
  2278. //if (!json_is_string(params) || !json_string_length(params)) { //wait cgliner fix this error
  2279. if (!json_is_string(params)) {
  2280. applog(LOG_INFO, "Params invalid string for parse_vmask for pool %d",
  2281. pool->pool_no);
  2282. goto out;
  2283. }
  2284. pool->vmask = set_vmask(pool, params);
  2285. ret = true;
  2286. out:
  2287. return ret;
  2288. }
  2289. bool parse_method(struct pool *pool, char *s)
  2290. {
  2291. json_t *val = NULL, *method, *err_val, *params;
  2292. json_error_t err;
  2293. bool ret = false;
  2294. char *buf;
  2295. if (!s)
  2296. goto out;
  2297. val = JSON_LOADS(s, &err);
  2298. if (!val) {
  2299. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2300. goto out;
  2301. }
  2302. method = json_object_get(val, "method");
  2303. if (!method)
  2304. goto out_decref;
  2305. err_val = json_object_get(val, "error");
  2306. params = json_object_get(val, "params");
  2307. if (err_val && !json_is_null(err_val)) {
  2308. char *ss;
  2309. if (err_val)
  2310. ss = json_dumps(err_val, JSON_INDENT(3));
  2311. else
  2312. ss = strdup("(unknown reason)");
  2313. applog(LOG_INFO, "JSON-RPC method decode of %s failed: %s", s, ss);
  2314. free(ss);
  2315. goto out_decref;
  2316. }
  2317. buf = (char *)json_string_value(method);
  2318. if (!buf)
  2319. goto out_decref;
  2320. if (!strncasecmp(buf, "mining.notify", 13)) {
  2321. if (parse_notify(pool, params))
  2322. pool->stratum_notify = ret = true;
  2323. else
  2324. pool->stratum_notify = ret = false;
  2325. goto out_decref;
  2326. }
  2327. if (!strncasecmp(buf, "mining.set_difficulty", 21)) {
  2328. ret = parse_diff(pool, params);
  2329. goto out_decref;
  2330. }
  2331. if (!strncasecmp(buf, "mining.set_extranonce", 21)) {
  2332. ret = parse_extranonce(pool, params);
  2333. goto out_decref;
  2334. }
  2335. if (!strncasecmp(buf, "client.reconnect", 16)) {
  2336. ret = parse_reconnect(pool, params);
  2337. goto out_decref;
  2338. }
  2339. if (!strncasecmp(buf, "client.get_version", 18)) {
  2340. ret = send_version(pool, val);
  2341. goto out_decref;
  2342. }
  2343. if (!strncasecmp(buf, "client.show_message", 19)) {
  2344. ret = show_message(pool, params);
  2345. goto out_decref;
  2346. }
  2347. if (!strncasecmp(buf, "mining.ping", 11)) {
  2348. applog(LOG_INFO, "Pool %d ping", pool->pool_no);
  2349. ret = send_pong(pool, val);
  2350. goto out_decref;
  2351. }
  2352. if (!strncasecmp(buf, "mining.set_version_mask", 23)) {
  2353. ret = parse_vmask(pool, params);
  2354. goto out_decref;
  2355. }
  2356. applog(LOG_INFO, "Unknown JSON-RPC from pool %d: %s", pool->pool_no, s);
  2357. out_decref:
  2358. json_decref(val);
  2359. out:
  2360. return ret;
  2361. }
  2362. bool subscribe_extranonce(struct pool *pool)
  2363. {
  2364. json_t *val = NULL, *res_val, *err_val;
  2365. char s[RBUFSIZE], *sret = NULL;
  2366. json_error_t err;
  2367. bool ret = false;
  2368. sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}",
  2369. swork_id++);
  2370. if (!stratum_send(pool, s, strlen(s)))
  2371. return ret;
  2372. /* Parse all data in the queue and anything left should be the response */
  2373. while (42) {
  2374. if (!socket_full(pool, DEFAULT_SOCKWAIT / 30)) {
  2375. applog(LOG_DEBUG, "Timed out waiting for response extranonce.subscribe");
  2376. /* some pool doesnt send anything, so this is normal */
  2377. ret = true;
  2378. goto out;
  2379. }
  2380. sret = recv_line(pool);
  2381. if (!sret)
  2382. return ret;
  2383. if (parse_method(pool, sret))
  2384. free(sret);
  2385. else
  2386. break;
  2387. }
  2388. val = JSON_LOADS(sret, &err);
  2389. free(sret);
  2390. res_val = json_object_get(val, "result");
  2391. err_val = json_object_get(val, "error");
  2392. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2393. char *ss;
  2394. if (err_val) {
  2395. ss = __json_array_string(err_val, 1);
  2396. if (!ss)
  2397. ss = (char *)json_string_value(err_val);
  2398. if (ss && (strcmp(ss, "Method 'subscribe' not found for service 'mining.extranonce'") == 0)) {
  2399. applog(LOG_INFO, "Cannot subscribe to mining.extranonce for pool %d", pool->pool_no);
  2400. ret = true;
  2401. goto out;
  2402. }
  2403. if (ss && (strcmp(ss, "Unrecognized request provided") == 0)) {
  2404. applog(LOG_INFO, "Cannot subscribe to mining.extranonce for pool %d", pool->pool_no);
  2405. ret = true;
  2406. goto out;
  2407. }
  2408. ss = json_dumps(err_val, JSON_INDENT(3));
  2409. }
  2410. else
  2411. ss = strdup("(unknown reason)");
  2412. applog(LOG_INFO, "Pool %d JSON extranonce subscribe failed: %s", pool->pool_no, ss);
  2413. free(ss);
  2414. goto out;
  2415. }
  2416. ret = true;
  2417. applog(LOG_INFO, "Stratum extranonce subscribe for pool %d", pool->pool_no);
  2418. out:
  2419. json_decref(val);
  2420. return ret;
  2421. }
  2422. bool auth_stratum(struct pool *pool)
  2423. {
  2424. json_t *val = NULL, *res_val, *err_val;
  2425. char s[RBUFSIZE], *sret = NULL;
  2426. json_error_t err;
  2427. bool ret = false;
  2428. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  2429. swork_id++, pool->rpc_user, pool->rpc_pass);
  2430. if (!stratum_send(pool, s, strlen(s)))
  2431. return ret;
  2432. /* Parse all data in the queue and anything left should be auth */
  2433. while (42) {
  2434. sret = recv_line(pool);
  2435. if (!sret)
  2436. return ret;
  2437. if (parse_method(pool, sret))
  2438. free(sret);
  2439. else
  2440. break;
  2441. }
  2442. val = JSON_LOADS(sret, &err);
  2443. free(sret);
  2444. res_val = json_object_get(val, "result");
  2445. err_val = json_object_get(val, "error");
  2446. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2447. char *ss;
  2448. if (err_val)
  2449. ss = json_dumps(err_val, JSON_INDENT(3));
  2450. else
  2451. ss = strdup("(unknown reason)");
  2452. applog(LOG_INFO, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  2453. free(ss);
  2454. suspend_stratum(pool);
  2455. goto out;
  2456. }
  2457. ret = true;
  2458. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  2459. pool->probed = true;
  2460. successful_connect = true;
  2461. if (opt_suggest_diff) {
  2462. sprintf(s, "{\"id\": %d, \"method\": \"mining.suggest_difficulty\", \"params\": [%d]}",
  2463. swork_id++, opt_suggest_diff);
  2464. stratum_send(pool, s, strlen(s));
  2465. }
  2466. out:
  2467. json_decref(val);
  2468. return ret;
  2469. }
  2470. static int recv_byte(int sockd)
  2471. {
  2472. char c;
  2473. if (recv(sockd, &c, 1, 0) != -1)
  2474. return c;
  2475. return -1;
  2476. }
  2477. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  2478. {
  2479. char buf[1024];
  2480. int i, len;
  2481. if (http0) {
  2482. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  2483. pool->sockaddr_url, pool->stratum_port);
  2484. } else {
  2485. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  2486. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  2487. pool->stratum_port);
  2488. }
  2489. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  2490. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2491. send(sockd, buf, strlen(buf), 0);
  2492. len = recv(sockd, buf, 12, 0);
  2493. if (len <= 0) {
  2494. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  2495. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2496. return false;
  2497. }
  2498. buf[len] = '\0';
  2499. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  2500. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2501. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  2502. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  2503. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2504. return false;
  2505. }
  2506. /* Ignore unwanted headers till we get desired response */
  2507. for (i = 0; i < 4; i++) {
  2508. buf[i] = recv_byte(sockd);
  2509. if (buf[i] == (char)-1) {
  2510. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2511. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2512. return false;
  2513. }
  2514. }
  2515. while (strncmp(buf, "\r\n\r\n", 4)) {
  2516. for (i = 0; i < 3; i++)
  2517. buf[i] = buf[i + 1];
  2518. buf[3] = recv_byte(sockd);
  2519. if (buf[3] == (char)-1) {
  2520. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2521. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2522. return false;
  2523. }
  2524. }
  2525. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  2526. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2527. return true;
  2528. }
  2529. static bool socks5_negotiate(struct pool *pool, int sockd)
  2530. {
  2531. unsigned char atyp, uclen;
  2532. unsigned short port;
  2533. char buf[515];
  2534. int i, len;
  2535. buf[0] = 0x05;
  2536. buf[1] = 0x01;
  2537. buf[2] = 0x00;
  2538. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  2539. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2540. send(sockd, buf, 3, 0);
  2541. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  2542. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2543. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2544. return false;
  2545. }
  2546. buf[0] = 0x05;
  2547. buf[1] = 0x01;
  2548. buf[2] = 0x00;
  2549. buf[3] = 0x03;
  2550. len = (strlen(pool->sockaddr_url));
  2551. if (len > 255)
  2552. len = 255;
  2553. uclen = len;
  2554. buf[4] = (uclen & 0xff);
  2555. cg_memcpy(buf + 5, pool->sockaddr_url, len);
  2556. port = atoi(pool->stratum_port);
  2557. buf[5 + len] = (port >> 8);
  2558. buf[6 + len] = (port & 0xff);
  2559. send(sockd, buf, (7 + len), 0);
  2560. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  2561. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2562. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2563. return false;
  2564. }
  2565. recv_byte(sockd);
  2566. atyp = recv_byte(sockd);
  2567. if (atyp == 0x01) {
  2568. for (i = 0; i < 4; i++)
  2569. recv_byte(sockd);
  2570. } else if (atyp == 0x03) {
  2571. len = recv_byte(sockd);
  2572. for (i = 0; i < len; i++)
  2573. recv_byte(sockd);
  2574. } else {
  2575. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2576. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2577. return false;
  2578. }
  2579. for (i = 0; i < 2; i++)
  2580. recv_byte(sockd);
  2581. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  2582. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2583. return true;
  2584. }
  2585. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  2586. {
  2587. unsigned short port;
  2588. in_addr_t inp;
  2589. char buf[515];
  2590. int i, len;
  2591. buf[0] = 0x04;
  2592. buf[1] = 0x01;
  2593. port = atoi(pool->stratum_port);
  2594. buf[2] = port >> 8;
  2595. buf[3] = port & 0xff;
  2596. sprintf(&buf[8], "CGMINER");
  2597. /* See if we've been given an IP address directly to avoid needing to
  2598. * resolve it. */
  2599. inp = inet_addr(pool->sockaddr_url);
  2600. inp = ntohl(inp);
  2601. if ((int)inp != -1)
  2602. socks4a = false;
  2603. else {
  2604. /* Try to extract the IP address ourselves first */
  2605. struct addrinfo servinfobase, *servinfo, hints;
  2606. servinfo = &servinfobase;
  2607. memset(&hints, 0, sizeof(struct addrinfo));
  2608. hints.ai_family = AF_INET; /* IPV4 only */
  2609. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  2610. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  2611. inp = ntohl(saddr_in->sin_addr.s_addr);
  2612. socks4a = false;
  2613. freeaddrinfo(servinfo);
  2614. }
  2615. }
  2616. if (!socks4a) {
  2617. if ((int)inp == -1) {
  2618. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  2619. pool->sockaddr_url);
  2620. return false;
  2621. }
  2622. buf[4] = (inp >> 24) & 0xFF;
  2623. buf[5] = (inp >> 16) & 0xFF;
  2624. buf[6] = (inp >> 8) & 0xFF;
  2625. buf[7] = (inp >> 0) & 0xFF;
  2626. send(sockd, buf, 16, 0);
  2627. } else {
  2628. /* This appears to not be working but hopefully most will be
  2629. * able to resolve IP addresses themselves. */
  2630. buf[4] = 0;
  2631. buf[5] = 0;
  2632. buf[6] = 0;
  2633. buf[7] = 1;
  2634. len = strlen(pool->sockaddr_url);
  2635. if (len > 255)
  2636. len = 255;
  2637. cg_memcpy(&buf[16], pool->sockaddr_url, len);
  2638. len += 16;
  2639. buf[len++] = '\0';
  2640. send(sockd, buf, len, 0);
  2641. }
  2642. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  2643. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  2644. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2645. return false;
  2646. }
  2647. for (i = 0; i < 6; i++)
  2648. recv_byte(sockd);
  2649. return true;
  2650. }
  2651. static void noblock_socket(SOCKETTYPE fd)
  2652. {
  2653. #ifndef WIN32
  2654. int flags = fcntl(fd, F_GETFL, 0);
  2655. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  2656. #else
  2657. u_long flags = 1;
  2658. ioctlsocket(fd, FIONBIO, &flags);
  2659. #endif
  2660. }
  2661. static void block_socket(SOCKETTYPE fd)
  2662. {
  2663. #ifndef WIN32
  2664. int flags = fcntl(fd, F_GETFL, 0);
  2665. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  2666. #else
  2667. u_long flags = 0;
  2668. ioctlsocket(fd, FIONBIO, &flags);
  2669. #endif
  2670. }
  2671. static bool sock_connecting(void)
  2672. {
  2673. #ifndef WIN32
  2674. return errno == EINPROGRESS;
  2675. #else
  2676. return WSAGetLastError() == WSAEWOULDBLOCK;
  2677. #endif
  2678. }
  2679. static bool setup_stratum_socket(struct pool *pool)
  2680. {
  2681. struct addrinfo *servinfo, hints, *p;
  2682. char *sockaddr_url, *sockaddr_port;
  2683. int sockd;
  2684. mutex_lock(&pool->stratum_lock);
  2685. pool->stratum_active = false;
  2686. if (pool->sock)
  2687. CLOSESOCKET(pool->sock);
  2688. pool->sock = 0;
  2689. mutex_unlock(&pool->stratum_lock);
  2690. memset(&hints, 0, sizeof(struct addrinfo));
  2691. hints.ai_family = AF_UNSPEC;
  2692. hints.ai_socktype = SOCK_STREAM;
  2693. if (!pool->rpc_proxy && opt_socks_proxy) {
  2694. pool->rpc_proxy = opt_socks_proxy;
  2695. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  2696. pool->rpc_proxytype = PROXY_SOCKS5;
  2697. }
  2698. if (pool->rpc_proxy) {
  2699. sockaddr_url = pool->sockaddr_proxy_url;
  2700. sockaddr_port = pool->sockaddr_proxy_port;
  2701. } else {
  2702. sockaddr_url = pool->sockaddr_url;
  2703. sockaddr_port = pool->stratum_port;
  2704. }
  2705. if (getaddrinfo(sockaddr_url, sockaddr_port, &hints, &servinfo) != 0) {
  2706. if (!pool->probed) {
  2707. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  2708. sockaddr_url, sockaddr_port);
  2709. pool->probed = true;
  2710. } else {
  2711. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  2712. sockaddr_url, sockaddr_port);
  2713. }
  2714. return false;
  2715. }
  2716. for (p = servinfo; p != NULL; p = p->ai_next) {
  2717. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  2718. if (sockd == -1) {
  2719. applog(LOG_DEBUG, "Failed socket");
  2720. continue;
  2721. }
  2722. /* Iterate non blocking over entries returned by getaddrinfo
  2723. * to cope with round robin DNS entries, finding the first one
  2724. * we can connect to quickly. */
  2725. noblock_socket(sockd);
  2726. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  2727. struct timeval tv_timeout = {1, 0};
  2728. int selret;
  2729. fd_set rw;
  2730. if (!sock_connecting()) {
  2731. CLOSESOCKET(sockd);
  2732. applog(LOG_DEBUG, "Failed sock connect");
  2733. continue;
  2734. }
  2735. retry:
  2736. FD_ZERO(&rw);
  2737. FD_SET(sockd, &rw);
  2738. selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
  2739. if (selret > 0 && FD_ISSET(sockd, &rw)) {
  2740. socklen_t len;
  2741. int err, n;
  2742. len = sizeof(err);
  2743. n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);
  2744. if (!n && !err) {
  2745. applog(LOG_DEBUG, "Succeeded delayed connect");
  2746. block_socket(sockd);
  2747. break;
  2748. }
  2749. }
  2750. if (selret < 0 && interrupted())
  2751. goto retry;
  2752. CLOSESOCKET(sockd);
  2753. applog(LOG_DEBUG, "Select timeout/failed connect");
  2754. continue;
  2755. }
  2756. applog(LOG_WARNING, "Succeeded immediate connect");
  2757. block_socket(sockd);
  2758. break;
  2759. }
  2760. if (p == NULL) {
  2761. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  2762. sockaddr_url, sockaddr_port);
  2763. freeaddrinfo(servinfo);
  2764. return false;
  2765. }
  2766. freeaddrinfo(servinfo);
  2767. if (pool->rpc_proxy) {
  2768. switch (pool->rpc_proxytype) {
  2769. case PROXY_HTTP_1_0:
  2770. if (!http_negotiate(pool, sockd, true))
  2771. return false;
  2772. break;
  2773. case PROXY_HTTP:
  2774. if (!http_negotiate(pool, sockd, false))
  2775. return false;
  2776. break;
  2777. case PROXY_SOCKS5:
  2778. case PROXY_SOCKS5H:
  2779. if (!socks5_negotiate(pool, sockd))
  2780. return false;
  2781. break;
  2782. case PROXY_SOCKS4:
  2783. if (!socks4_negotiate(pool, sockd, false))
  2784. return false;
  2785. break;
  2786. case PROXY_SOCKS4A:
  2787. if (!socks4_negotiate(pool, sockd, true))
  2788. return false;
  2789. break;
  2790. default:
  2791. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  2792. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2793. return false;
  2794. break;
  2795. }
  2796. }
  2797. if (!pool->sockbuf) {
  2798. pool->sockbuf = cgcalloc(RBUFSIZE, 1);
  2799. pool->sockbuf_size = RBUFSIZE;
  2800. }
  2801. pool->sock = sockd;
  2802. keep_sockalive(sockd);
  2803. return true;
  2804. }
  2805. static char *get_sessionid(json_t *val)
  2806. {
  2807. char *ret = NULL;
  2808. json_t *arr_val;
  2809. int arrsize, i;
  2810. arr_val = json_array_get(val, 0);
  2811. if (!arr_val || !json_is_array(arr_val))
  2812. goto out;
  2813. arrsize = json_array_size(arr_val);
  2814. for (i = 0; i < arrsize; i++) {
  2815. json_t *arr = json_array_get(arr_val, i);
  2816. char *notify;
  2817. if (!arr | !json_is_array(arr))
  2818. break;
  2819. notify = __json_array_string(arr, 0);
  2820. if (!notify)
  2821. continue;
  2822. if (!strncasecmp(notify, "mining.notify", 13)) {
  2823. ret = json_array_string(arr, 1);
  2824. break;
  2825. }
  2826. }
  2827. out:
  2828. return ret;
  2829. }
  2830. void suspend_stratum(struct pool *pool)
  2831. {
  2832. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2833. mutex_lock(&pool->stratum_lock);
  2834. __suspend_stratum(pool);
  2835. mutex_unlock(&pool->stratum_lock);
  2836. }
  2837. bool initiate_stratum(struct pool *pool)
  2838. {
  2839. bool ret = false, recvd = false, noresume = false, sockd = false;
  2840. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid, *tmp;
  2841. json_t *val = NULL, *res_val, *err_val;
  2842. json_error_t err;
  2843. int n2size;
  2844. resend:
  2845. if (!setup_stratum_socket(pool)) {
  2846. sockd = false;
  2847. goto out;
  2848. }
  2849. sockd = true;
  2850. if (recvd) {
  2851. /* Get rid of any crap lying around if we're resending */
  2852. clear_sock(pool);
  2853. }
  2854. /* Attempt to configure stratum protocol feature set first. */
  2855. if (!configure_stratum_mining(pool))
  2856. goto out;
  2857. if (recvd) {
  2858. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2859. } else {
  2860. if (pool->sessionid)
  2861. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\", \"%s\"]}", swork_id++, pool->sessionid);
  2862. else
  2863. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\"]}", swork_id++);
  2864. }
  2865. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  2866. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2867. goto out;
  2868. }
  2869. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2870. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2871. goto out;
  2872. }
  2873. rereceive:
  2874. sret = recv_line(pool);
  2875. if (!sret)
  2876. goto out;
  2877. recvd = true;
  2878. val = JSON_LOADS(sret, &err);
  2879. if (!val) {
  2880. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2881. goto out;
  2882. }
  2883. res_val = json_object_get(val, "result");
  2884. err_val = json_object_get(val, "error");
  2885. if (!res_val) {
  2886. /* Check for a method just in case */
  2887. json_t *method_val = json_object_get(val, "method");
  2888. if (method_val && parse_method(pool, sret)) {
  2889. free(sret);
  2890. sret = NULL;
  2891. goto rereceive;
  2892. }
  2893. }
  2894. if (!res_val || json_is_null(res_val) ||
  2895. (err_val && !json_is_null(err_val))) {
  2896. char *ss;
  2897. if (err_val)
  2898. ss = json_dumps(err_val, JSON_INDENT(3));
  2899. else
  2900. ss = strdup("(unknown reason)");
  2901. applog(LOG_INFO, "JSON-RPC decode of message %s failed: %s", sret, ss);
  2902. free(ss);
  2903. goto out;
  2904. }
  2905. sessionid = get_sessionid(res_val);
  2906. if (!sessionid)
  2907. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2908. nonce1 = json_array_string(res_val, 1);
  2909. if (!valid_hex(nonce1)) {
  2910. applog(LOG_INFO, "Failed to get valid nonce1 in initiate_stratum");
  2911. free(sessionid);
  2912. free(nonce1);
  2913. goto out;
  2914. }
  2915. n2size = json_integer_value(json_array_get(res_val, 2));
  2916. if (n2size < 2 || n2size > 16) {
  2917. applog(LOG_INFO, "Failed to get valid n2size in initiate_stratum");
  2918. free(sessionid);
  2919. free(nonce1);
  2920. goto out;
  2921. }
  2922. if (sessionid && pool->sessionid && !strcmp(sessionid, pool->sessionid)) {
  2923. applog(LOG_NOTICE, "Pool %d successfully negotiated resume with the same session ID",
  2924. pool->pool_no);
  2925. }
  2926. cg_wlock(&pool->data_lock);
  2927. tmp = pool->sessionid;
  2928. pool->sessionid = sessionid;
  2929. free(tmp);
  2930. tmp = pool->nonce1;
  2931. pool->nonce1 = nonce1;
  2932. free(tmp);
  2933. pool->n1_len = strlen(nonce1) / 2;
  2934. free(pool->nonce1bin);
  2935. pool->nonce1bin = cgcalloc(pool->n1_len, 1);
  2936. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2937. pool->n2size = n2size;
  2938. cg_wunlock(&pool->data_lock);
  2939. if (sessionid)
  2940. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2941. ret = true;
  2942. out:
  2943. if (ret) {
  2944. if (!pool->stratum_url)
  2945. pool->stratum_url = pool->sockaddr_url;
  2946. pool->stratum_active = true;
  2947. pool->next_diff = pool->diff_after = 0;
  2948. pool->sdiff = 1;
  2949. if (opt_protocol) {
  2950. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2951. pool->pool_no, pool->nonce1, pool->n2size);
  2952. }
  2953. } else {
  2954. if (recvd && !noresume) {
  2955. /* Reset the sessionid used for stratum resuming in case the pool
  2956. * does not support it, or does not know how to respond to the
  2957. * presence of the sessionid parameter. */
  2958. cg_wlock(&pool->data_lock);
  2959. free(pool->sessionid);
  2960. free(pool->nonce1);
  2961. pool->sessionid = pool->nonce1 = NULL;
  2962. cg_wunlock(&pool->data_lock);
  2963. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2964. noresume = true;
  2965. json_decref(val);
  2966. goto resend;
  2967. }
  2968. applog(LOG_DEBUG, "Initiate stratum failed");
  2969. if (sockd)
  2970. suspend_stratum(pool);
  2971. }
  2972. json_decref(val);
  2973. free(sret);
  2974. return ret;
  2975. }
  2976. bool restart_stratum(struct pool *pool)
  2977. {
  2978. bool ret = false;
  2979. if (pool->stratum_active)
  2980. suspend_stratum(pool);
  2981. if (!initiate_stratum(pool))
  2982. goto out;
  2983. if (pool->extranonce_subscribe && !subscribe_extranonce(pool))
  2984. goto out;
  2985. if (!auth_stratum(pool))
  2986. goto out;
  2987. ret = true;
  2988. out:
  2989. if (!ret)
  2990. pool_died(pool);
  2991. else
  2992. stratum_resumed(pool);
  2993. return ret;
  2994. }
  2995. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2996. {
  2997. dev->device_last_not_well = time(NULL);
  2998. dev->device_not_well_reason = reason;
  2999. switch (reason) {
  3000. case REASON_THREAD_FAIL_INIT:
  3001. dev->thread_fail_init_count++;
  3002. break;
  3003. case REASON_THREAD_ZERO_HASH:
  3004. dev->thread_zero_hash_count++;
  3005. break;
  3006. case REASON_THREAD_FAIL_QUEUE:
  3007. dev->thread_fail_queue_count++;
  3008. break;
  3009. case REASON_DEV_SICK_IDLE_60:
  3010. dev->dev_sick_idle_60_count++;
  3011. break;
  3012. case REASON_DEV_DEAD_IDLE_600:
  3013. dev->dev_dead_idle_600_count++;
  3014. break;
  3015. case REASON_DEV_NOSTART:
  3016. dev->dev_nostart_count++;
  3017. break;
  3018. case REASON_DEV_OVER_HEAT:
  3019. dev->dev_over_heat_count++;
  3020. break;
  3021. case REASON_DEV_THERMAL_CUTOFF:
  3022. dev->dev_thermal_cutoff_count++;
  3023. break;
  3024. case REASON_DEV_COMMS_ERROR:
  3025. dev->dev_comms_error_count++;
  3026. break;
  3027. case REASON_DEV_THROTTLE:
  3028. dev->dev_throttle_count++;
  3029. break;
  3030. }
  3031. }
  3032. /* Realloc an existing string to fit an extra string s, appending s to it. */
  3033. void *realloc_strcat(char *ptr, char *s)
  3034. {
  3035. size_t old = 0, len = strlen(s);
  3036. char *ret;
  3037. if (!len)
  3038. return ptr;
  3039. if (ptr)
  3040. old = strlen(ptr);
  3041. len += old + 1;
  3042. ret = cgmalloc(len);
  3043. if (ptr) {
  3044. sprintf(ret, "%s%s", ptr, s);
  3045. free(ptr);
  3046. } else
  3047. sprintf(ret, "%s", s);
  3048. return ret;
  3049. }
  3050. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  3051. * Including 0x00 at the end
  3052. * You must free the result yourself */
  3053. void *str_text(char *ptr)
  3054. {
  3055. unsigned char *uptr;
  3056. char *ret, *txt;
  3057. if (ptr == NULL) {
  3058. ret = strdup("(null)");
  3059. if (unlikely(!ret))
  3060. quithere(1, "Failed to malloc null");
  3061. }
  3062. uptr = (unsigned char *)ptr;
  3063. ret = txt = cgmalloc(strlen(ptr) * 4 + 5); // Guaranteed >= needed
  3064. do {
  3065. if (*uptr < ' ' || *uptr > '~') {
  3066. sprintf(txt, "0x%02x", *uptr);
  3067. txt += 4;
  3068. } else
  3069. *(txt++) = *uptr;
  3070. } while (*(uptr++));
  3071. *txt = '\0';
  3072. return ret;
  3073. }
  3074. void RenameThread(const char* name)
  3075. {
  3076. char buf[16];
  3077. snprintf(buf, sizeof(buf), "cg@%s", name);
  3078. #if defined(PR_SET_NAME)
  3079. // Only the first 15 characters are used (16 - NUL terminator)
  3080. prctl(PR_SET_NAME, buf, 0, 0, 0);
  3081. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  3082. pthread_set_name_np(pthread_self(), buf);
  3083. #elif defined(MAC_OSX)
  3084. pthread_setname_np(buf);
  3085. #else
  3086. // Prevent warnings
  3087. (void)buf;
  3088. #endif
  3089. }
  3090. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  3091. * that support them and for apple which does not. We use a single byte across
  3092. * a pipe to emulate semaphore behaviour there. */
  3093. #ifdef __APPLE__
  3094. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3095. {
  3096. int flags, fd, i;
  3097. if (pipe(cgsem->pipefd) == -1)
  3098. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  3099. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  3100. * execv on restart. */
  3101. for (i = 0; i < 2; i++) {
  3102. fd = cgsem->pipefd[i];
  3103. flags = fcntl(fd, F_GETFD, 0);
  3104. flags |= FD_CLOEXEC;
  3105. if (fcntl(fd, F_SETFD, flags) == -1)
  3106. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  3107. }
  3108. }
  3109. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3110. {
  3111. const char buf = 1;
  3112. int ret;
  3113. retry:
  3114. ret = write(cgsem->pipefd[1], &buf, 1);
  3115. if (unlikely(ret == 0))
  3116. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  3117. else if (unlikely(ret < 0 && interrupted))
  3118. goto retry;
  3119. }
  3120. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3121. {
  3122. char buf;
  3123. int ret;
  3124. retry:
  3125. ret = read(cgsem->pipefd[0], &buf, 1);
  3126. if (unlikely(ret == 0))
  3127. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  3128. else if (unlikely(ret < 0 && interrupted))
  3129. goto retry;
  3130. }
  3131. void cgsem_destroy(cgsem_t *cgsem)
  3132. {
  3133. close(cgsem->pipefd[1]);
  3134. close(cgsem->pipefd[0]);
  3135. }
  3136. /* This is similar to sem_timedwait but takes a millisecond value */
  3137. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  3138. {
  3139. struct timeval timeout;
  3140. int ret, fd;
  3141. fd_set rd;
  3142. char buf;
  3143. retry:
  3144. fd = cgsem->pipefd[0];
  3145. FD_ZERO(&rd);
  3146. FD_SET(fd, &rd);
  3147. ms_to_timeval(&timeout, ms);
  3148. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  3149. if (ret > 0) {
  3150. ret = read(fd, &buf, 1);
  3151. return 0;
  3152. }
  3153. if (likely(!ret))
  3154. return ETIMEDOUT;
  3155. if (interrupted())
  3156. goto retry;
  3157. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  3158. /* We don't reach here */
  3159. return 0;
  3160. }
  3161. /* Reset semaphore count back to zero */
  3162. void cgsem_reset(cgsem_t *cgsem)
  3163. {
  3164. int ret, fd;
  3165. fd_set rd;
  3166. char buf;
  3167. fd = cgsem->pipefd[0];
  3168. FD_ZERO(&rd);
  3169. FD_SET(fd, &rd);
  3170. do {
  3171. struct timeval timeout = {0, 0};
  3172. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  3173. if (ret > 0)
  3174. ret = read(fd, &buf, 1);
  3175. else if (unlikely(ret < 0 && interrupted()))
  3176. ret = 1;
  3177. } while (ret > 0);
  3178. }
  3179. #else
  3180. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3181. {
  3182. int ret;
  3183. if ((ret = sem_init(cgsem, 0, 0)))
  3184. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  3185. }
  3186. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3187. {
  3188. if (unlikely(sem_post(cgsem)))
  3189. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  3190. }
  3191. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3192. {
  3193. retry:
  3194. if (unlikely(sem_wait(cgsem))) {
  3195. if (interrupted())
  3196. goto retry;
  3197. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  3198. }
  3199. }
  3200. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  3201. {
  3202. struct timespec abs_timeout, tdiff;
  3203. int ret;
  3204. cgcond_time(&abs_timeout);
  3205. ms_to_timespec(&tdiff, ms);
  3206. timeraddspec(&abs_timeout, &tdiff);
  3207. retry:
  3208. ret = sem_timedwait(cgsem, &abs_timeout);
  3209. if (ret) {
  3210. if (likely(sock_timeout()))
  3211. return ETIMEDOUT;
  3212. if (interrupted())
  3213. goto retry;
  3214. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  3215. }
  3216. return 0;
  3217. }
  3218. void cgsem_reset(cgsem_t *cgsem)
  3219. {
  3220. int ret;
  3221. do {
  3222. ret = sem_trywait(cgsem);
  3223. if (unlikely(ret < 0 && interrupted()))
  3224. ret = 0;
  3225. } while (!ret);
  3226. }
  3227. void cgsem_destroy(cgsem_t *cgsem)
  3228. {
  3229. sem_destroy(cgsem);
  3230. }
  3231. #endif
  3232. /* Provide a completion_timeout helper function for unreliable functions that
  3233. * may die due to driver issues etc that time out if the function fails and
  3234. * can then reliably return. */
  3235. struct cg_completion {
  3236. cgsem_t cgsem;
  3237. void (*fn)(void *fnarg);
  3238. void *fnarg;
  3239. };
  3240. void *completion_thread(void *arg)
  3241. {
  3242. struct cg_completion *cgc = (struct cg_completion *)arg;
  3243. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3244. cgc->fn(cgc->fnarg);
  3245. cgsem_post(&cgc->cgsem);
  3246. return NULL;
  3247. }
  3248. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  3249. {
  3250. struct cg_completion *cgc;
  3251. pthread_t pthread;
  3252. bool ret = false;
  3253. cgc = cgmalloc(sizeof(struct cg_completion));
  3254. cgsem_init(&cgc->cgsem);
  3255. cgc->fn = fn;
  3256. cgc->fnarg = fnarg;
  3257. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  3258. ret = cgsem_mswait(&cgc->cgsem, timeout);
  3259. if (!ret) {
  3260. pthread_join(pthread, NULL);
  3261. free(cgc);
  3262. } else
  3263. pthread_cancel(pthread);
  3264. return !ret;
  3265. }
  3266. void _cg_memcpy(void *dest, const void *src, unsigned int n, const char *file, const char *func, const int line)
  3267. {
  3268. if (unlikely(n < 1 || n > (1ul << 31))) {
  3269. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from %s %s():%d",
  3270. n, file, func, line);
  3271. return;
  3272. }
  3273. if (unlikely(!dest)) {
  3274. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes to NULL from %s %s():%d",
  3275. n, file, func, line);
  3276. return;
  3277. }
  3278. if (unlikely(!src)) {
  3279. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from NULL from %s %s():%d",
  3280. n, file, func, line);
  3281. return;
  3282. }
  3283. memcpy(dest, src, n);
  3284. }