util.c 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846
  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. {
  1175. ofs = ret - lowhay;
  1176. ret = haystack + ofs;
  1177. }
  1178. free(lowhay);
  1179. free(lowneedle);
  1180. return ret;
  1181. }
  1182. char *Strsep(char **stringp, const char *delim)
  1183. {
  1184. char *ret = *stringp;
  1185. char *p;
  1186. p = (ret != NULL) ? strpbrk(ret, delim) : NULL;
  1187. if (p == NULL)
  1188. *stringp = NULL;
  1189. else {
  1190. *p = '\0';
  1191. *stringp = p + 1;
  1192. }
  1193. return ret;
  1194. }
  1195. /* Get timespec specifically for use by cond_timedwait functions which use
  1196. * CLOCK_REALTIME for expiry */
  1197. void cgcond_time(struct timespec *abstime)
  1198. {
  1199. clock_gettime(CLOCK_REALTIME, abstime);
  1200. }
  1201. /* Get CLOCK_REALTIME for display purposes */
  1202. void cgtime_real(struct timeval *tv)
  1203. {
  1204. struct timespec tp;
  1205. clock_gettime(CLOCK_REALTIME, &tp);
  1206. tv->tv_sec = tp.tv_sec;
  1207. tv->tv_usec = tp.tv_nsec / 1000;
  1208. }
  1209. #ifdef WIN32
  1210. /* Mingw32 has no strsep so create our own custom one */
  1211. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  1212. #define EPOCHFILETIME (116444736000000000LL)
  1213. /* These are cgminer specific sleep functions that use an absolute nanosecond
  1214. * resolution timer to avoid poor usleep accuracy and overruns. */
  1215. /* Return the system time as an lldiv_t in decimicroseconds. */
  1216. static void decius_time(lldiv_t *lidiv)
  1217. {
  1218. FILETIME ft;
  1219. LARGE_INTEGER li;
  1220. GetSystemTimeAsFileTime(&ft);
  1221. li.LowPart = ft.dwLowDateTime;
  1222. li.HighPart = ft.dwHighDateTime;
  1223. li.QuadPart -= EPOCHFILETIME;
  1224. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1225. *lidiv = lldiv(li.QuadPart, 10000000);
  1226. }
  1227. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  1228. * with tz set to NULL, and windows' default resolution is only 15ms, this
  1229. * gives us higher resolution times on windows. */
  1230. void cgtime(struct timeval *tv)
  1231. {
  1232. lldiv_t lidiv;
  1233. decius_time(&lidiv);
  1234. tv->tv_sec = lidiv.quot;
  1235. tv->tv_usec = lidiv.rem / 10;
  1236. }
  1237. #else /* WIN32 */
  1238. void cgtime(struct timeval *tv)
  1239. {
  1240. cgtimer_t cgt;
  1241. cgtimer_time(&cgt);
  1242. timespec_to_val(tv, &cgt);
  1243. }
  1244. int cgtimer_to_ms(cgtimer_t *cgt)
  1245. {
  1246. return timespec_to_ms(cgt);
  1247. }
  1248. /* Subtracts b from a and stores it in res. */
  1249. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1250. {
  1251. res->tv_sec = a->tv_sec - b->tv_sec;
  1252. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  1253. if (res->tv_nsec < 0) {
  1254. res->tv_nsec += 1000000000;
  1255. res->tv_sec--;
  1256. }
  1257. }
  1258. #endif /* WIN32 */
  1259. #if defined(CLOCK_MONOTONIC) && !defined(__FreeBSD__) && !defined(__APPLE__) && !defined(WIN32) /* Essentially just linux */
  1260. //#ifdef CLOCK_MONOTONIC /* Essentially just linux */
  1261. void cgtimer_time(cgtimer_t *ts_start)
  1262. {
  1263. clock_gettime(CLOCK_MONOTONIC, ts_start);
  1264. }
  1265. static void nanosleep_abstime(struct timespec *ts_end)
  1266. {
  1267. int ret;
  1268. do {
  1269. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  1270. } while (ret == EINTR);
  1271. }
  1272. /* Reentrant version of cgsleep functions allow start time to be set separately
  1273. * from the beginning of the actual sleep, allowing scheduling delays to be
  1274. * counted in the sleep. */
  1275. #ifdef USE_BITMAIN_SOC
  1276. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1277. {
  1278. struct timespec ts_end;
  1279. ms_to_timespec(&ts_end, ms);
  1280. timeraddspec(&ts_end, ts_start);
  1281. nanosleep_abstime(&ts_end);
  1282. }
  1283. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1284. {
  1285. struct timespec ts_end;
  1286. us_to_timespec(&ts_end, us);
  1287. timeraddspec(&ts_end, ts_start);
  1288. nanosleep_abstime(&ts_end);
  1289. }
  1290. #else /* USE_BITMAIN_SOC */
  1291. int cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1292. {
  1293. struct timespec ts_end, ts_diff;
  1294. int msdiff;
  1295. ms_to_timespec(&ts_end, ms);
  1296. timeraddspec(&ts_end, ts_start);
  1297. cgtimer_time(&ts_diff);
  1298. /* Should be a negative value if we still have to sleep */
  1299. timersubspec(&ts_diff, &ts_end);
  1300. msdiff = -timespec_to_ms(&ts_diff);
  1301. if (msdiff <= 0)
  1302. return 0;
  1303. nanosleep_abstime(&ts_end);
  1304. return msdiff;
  1305. }
  1306. int64_t cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1307. {
  1308. struct timespec ts_end, ts_diff;
  1309. int64_t usdiff;
  1310. us_to_timespec(&ts_end, us);
  1311. timeraddspec(&ts_end, ts_start);
  1312. cgtimer_time(&ts_diff);
  1313. usdiff = -timespec_to_us(&ts_diff);
  1314. if (usdiff <= 0)
  1315. return 0;
  1316. nanosleep_abstime(&ts_end);
  1317. return usdiff;
  1318. }
  1319. #endif /* USE_BITMAIN_SOC */
  1320. #else /* CLOCK_MONOTONIC */
  1321. #ifdef __MACH__
  1322. #include <mach/clock.h>
  1323. #include <mach/mach.h>
  1324. void cgtimer_time(cgtimer_t *ts_start)
  1325. {
  1326. clock_serv_t cclock;
  1327. mach_timespec_t mts;
  1328. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  1329. clock_get_time(cclock, &mts);
  1330. mach_port_deallocate(mach_task_self(), cclock);
  1331. ts_start->tv_sec = mts.tv_sec;
  1332. ts_start->tv_nsec = mts.tv_nsec;
  1333. }
  1334. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  1335. void cgtimer_time(cgtimer_t *ts_start)
  1336. {
  1337. struct timeval tv;
  1338. cgtime(&tv);
  1339. ts_start->tv_sec = tv.tv_sec;
  1340. ts_start->tv_nsec = tv.tv_usec * 1000;
  1341. }
  1342. #endif /* __MACH__ */
  1343. #ifdef WIN32
  1344. /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
  1345. * typedef, allowing us to have sub-microsecond resolution for times, do simple
  1346. * arithmetic for timer calculations, and use windows' own hTimers to get
  1347. * accurate absolute timeouts. */
  1348. int cgtimer_to_ms(cgtimer_t *cgt)
  1349. {
  1350. return (int)(cgt->QuadPart / 10000LL);
  1351. }
  1352. /* Subtracts b from a and stores it in res. */
  1353. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1354. {
  1355. res->QuadPart = a->QuadPart - b->QuadPart;
  1356. }
  1357. /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
  1358. * timeouts with hTimers. */
  1359. void cgtimer_time(cgtimer_t *ts_start)
  1360. {
  1361. FILETIME ft;
  1362. GetSystemTimeAsFileTime(&ft);
  1363. ts_start->LowPart = ft.dwLowDateTime;
  1364. ts_start->HighPart = ft.dwHighDateTime;
  1365. }
  1366. static void liSleep(LARGE_INTEGER *li, int timeout)
  1367. {
  1368. HANDLE hTimer;
  1369. DWORD ret;
  1370. if (unlikely(timeout <= 0))
  1371. return;
  1372. hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  1373. if (unlikely(!hTimer))
  1374. quit(1, "Failed to create hTimer in liSleep");
  1375. ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
  1376. if (unlikely(!ret))
  1377. quit(1, "Failed to SetWaitableTimer in liSleep");
  1378. /* We still use a timeout as a sanity check in case the system time
  1379. * is changed while we're running */
  1380. ret = WaitForSingleObject(hTimer, timeout);
  1381. if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
  1382. quit(1, "Failed to WaitForSingleObject in liSleep");
  1383. CloseHandle(hTimer);
  1384. }
  1385. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1386. {
  1387. LARGE_INTEGER li;
  1388. li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
  1389. liSleep(&li, ms);
  1390. }
  1391. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1392. {
  1393. LARGE_INTEGER li;
  1394. int ms;
  1395. li.QuadPart = ts_start->QuadPart + us * 10LL;
  1396. ms = us / 1000;
  1397. if (!ms)
  1398. ms = 1;
  1399. liSleep(&li, ms);
  1400. }
  1401. #else /* WIN32 */
  1402. static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  1403. {
  1404. struct timespec now;
  1405. timeraddspec(ts_diff, ts_start);
  1406. cgtimer_time(&now);
  1407. timersubspec(ts_diff, &now);
  1408. if (unlikely(ts_diff->tv_sec < 0))
  1409. return;
  1410. nanosleep(ts_diff, NULL);
  1411. }
  1412. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1413. {
  1414. struct timespec ts_diff;
  1415. ms_to_timespec(&ts_diff, ms);
  1416. cgsleep_spec(&ts_diff, ts_start);
  1417. }
  1418. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1419. {
  1420. struct timespec ts_diff;
  1421. us_to_timespec(&ts_diff, us);
  1422. cgsleep_spec(&ts_diff, ts_start);
  1423. }
  1424. #endif /* WIN32 */
  1425. #endif /* CLOCK_MONOTONIC */
  1426. void cgsleep_ms(int ms)
  1427. {
  1428. cgtimer_t ts_start;
  1429. cgsleep_prepare_r(&ts_start);
  1430. cgsleep_ms_r(&ts_start, ms);
  1431. }
  1432. static void busywait_us(int64_t us)
  1433. {
  1434. struct timeval diff, end, now;
  1435. cgtime(&end);
  1436. us_to_timeval(&diff, us);
  1437. addtime(&diff, &end);
  1438. do {
  1439. sched_yield();
  1440. cgtime(&now);
  1441. } while (time_less(&now, &end));
  1442. }
  1443. void cgsleep_us(int64_t us)
  1444. {
  1445. cgtimer_t ts_start;
  1446. /* Most timer resolution is unlikely to be able to sleep accurately
  1447. * for less than 1ms so busywait instead. */
  1448. if (us < 1000)
  1449. return busywait_us(us);
  1450. cgsleep_prepare_r(&ts_start);
  1451. cgsleep_us_r(&ts_start, us);
  1452. }
  1453. /* Returns the microseconds difference between end and start times as a double */
  1454. double us_tdiff(struct timeval *end, struct timeval *start)
  1455. {
  1456. /* Sanity check. We should only be using this for small differences so
  1457. * limit the max to 60 seconds. */
  1458. if (unlikely(end->tv_sec - start->tv_sec > 60))
  1459. return 60000000;
  1460. return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
  1461. }
  1462. /* Returns the milliseconds difference between end and start times */
  1463. int ms_tdiff(struct timeval *end, struct timeval *start)
  1464. {
  1465. /* Like us_tdiff, limit to 1 hour. */
  1466. if (unlikely(end->tv_sec - start->tv_sec > 3600))
  1467. return 3600000;
  1468. return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
  1469. }
  1470. /* Returns the seconds difference between end and start times as a double */
  1471. double tdiff(struct timeval *end, struct timeval *start)
  1472. {
  1473. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1474. }
  1475. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1476. {
  1477. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1478. char url_address[256], port[6];
  1479. int url_len, port_len = 0;
  1480. *sockaddr_url = url;
  1481. url_begin = strstr(url, "//");
  1482. if (!url_begin)
  1483. url_begin = url;
  1484. else
  1485. url_begin += 2;
  1486. /* Look for numeric ipv6 entries */
  1487. ipv6_begin = strstr(url_begin, "[");
  1488. ipv6_end = strstr(url_begin, "]");
  1489. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1490. url_end = strstr(ipv6_end, ":");
  1491. else
  1492. url_end = strstr(url_begin, ":");
  1493. if (url_end) {
  1494. url_len = url_end - url_begin;
  1495. port_len = strlen(url_begin) - url_len - 1;
  1496. if (port_len < 1)
  1497. return false;
  1498. port_start = url_end + 1;
  1499. } else
  1500. url_len = strlen(url_begin);
  1501. if (url_len < 1)
  1502. return false;
  1503. /* Get rid of the [] */
  1504. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) {
  1505. url_len -= 2;
  1506. url_begin++;
  1507. }
  1508. snprintf(url_address, 254, "%.*s", url_len, url_begin);
  1509. if (port_len) {
  1510. char *slash;
  1511. snprintf(port, 6, "%.*s", port_len, port_start);
  1512. slash = strpbrk(port, "/#");
  1513. if (slash)
  1514. *slash = '\0';
  1515. } else
  1516. strcpy(port, "80");
  1517. *sockaddr_port = strdup(port);
  1518. *sockaddr_url = strdup(url_address);
  1519. return true;
  1520. }
  1521. enum send_ret {
  1522. SEND_OK,
  1523. SEND_SELECTFAIL,
  1524. SEND_SENDFAIL,
  1525. SEND_INACTIVE
  1526. };
  1527. /* Send a single command across a socket, appending \n to it. This should all
  1528. * be done under stratum lock except when first establishing the socket */
  1529. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1530. {
  1531. SOCKETTYPE sock = pool->sock;
  1532. ssize_t ssent = 0;
  1533. strcat(s, "\n");
  1534. len++;
  1535. while (len > 0 ) {
  1536. struct timeval timeout = {1, 0};
  1537. ssize_t sent;
  1538. fd_set wd;
  1539. retry:
  1540. FD_ZERO(&wd);
  1541. FD_SET(sock, &wd);
  1542. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1543. if (interrupted())
  1544. goto retry;
  1545. return SEND_SELECTFAIL;
  1546. }
  1547. #ifdef __APPLE__
  1548. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1549. #elif WIN32
  1550. sent = send(pool->sock, s + ssent, len, 0);
  1551. #else
  1552. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1553. #endif
  1554. if (sent < 0) {
  1555. if (!sock_blocks())
  1556. return SEND_SENDFAIL;
  1557. sent = 0;
  1558. }
  1559. ssent += sent;
  1560. len -= sent;
  1561. }
  1562. pool->cgminer_pool_stats.times_sent++;
  1563. pool->cgminer_pool_stats.bytes_sent += ssent;
  1564. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1565. return SEND_OK;
  1566. }
  1567. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1568. {
  1569. enum send_ret ret = SEND_INACTIVE;
  1570. if (opt_protocol)
  1571. applog(LOG_DEBUG, "SEND: %s", s);
  1572. mutex_lock(&pool->stratum_lock);
  1573. if (pool->stratum_active)
  1574. ret = __stratum_send(pool, s, len);
  1575. mutex_unlock(&pool->stratum_lock);
  1576. /* This is to avoid doing applog under stratum_lock */
  1577. switch (ret) {
  1578. default:
  1579. case SEND_OK:
  1580. break;
  1581. case SEND_SELECTFAIL:
  1582. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1583. suspend_stratum(pool);
  1584. break;
  1585. case SEND_SENDFAIL:
  1586. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1587. suspend_stratum(pool);
  1588. break;
  1589. case SEND_INACTIVE:
  1590. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1591. break;
  1592. }
  1593. return (ret == SEND_OK);
  1594. }
  1595. static bool socket_full(struct pool *pool, int wait)
  1596. {
  1597. SOCKETTYPE sock = pool->sock;
  1598. struct timeval timeout;
  1599. fd_set rd;
  1600. if (unlikely(wait < 0))
  1601. wait = 0;
  1602. FD_ZERO(&rd);
  1603. FD_SET(sock, &rd);
  1604. timeout.tv_usec = 0;
  1605. timeout.tv_sec = wait;
  1606. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1607. return true;
  1608. return false;
  1609. }
  1610. /* Check to see if Santa's been good to you */
  1611. bool sock_full(struct pool *pool)
  1612. {
  1613. if (strlen(pool->sockbuf))
  1614. return true;
  1615. return (socket_full(pool, 0));
  1616. }
  1617. static void clear_sockbuf(struct pool *pool)
  1618. {
  1619. if (likely(pool->sockbuf))
  1620. strcpy(pool->sockbuf, "");
  1621. }
  1622. static void clear_sock(struct pool *pool)
  1623. {
  1624. ssize_t n;
  1625. mutex_lock(&pool->stratum_lock);
  1626. do {
  1627. if (pool->sock)
  1628. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1629. else
  1630. n = 0;
  1631. } while (n > 0);
  1632. mutex_unlock(&pool->stratum_lock);
  1633. clear_sockbuf(pool);
  1634. }
  1635. /* Realloc memory to new size and zero any extra memory added */
  1636. void ckrecalloc(void **ptr, size_t old, size_t new, const char *file, const char *func, const int line)
  1637. {
  1638. if (new == old)
  1639. return;
  1640. *ptr = _cgrealloc(*ptr, new, file, func, line);
  1641. if (new > old)
  1642. memset(*ptr + old, 0, new - old);
  1643. }
  1644. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1645. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1646. * and zeroing the new memory */
  1647. static void recalloc_sock(struct pool *pool, size_t len)
  1648. {
  1649. size_t old, new;
  1650. old = strlen(pool->sockbuf);
  1651. new = old + len + 1;
  1652. if (new < pool->sockbuf_size)
  1653. return;
  1654. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1655. // Avoid potentially recursive locking
  1656. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1657. pool->sockbuf = cgrealloc(pool->sockbuf, new);
  1658. memset(pool->sockbuf + old, 0, new - old);
  1659. pool->sockbuf_size = new;
  1660. }
  1661. /* Peeks at a socket to find the first end of line and then reads just that
  1662. * from the socket and returns that as a malloced char */
  1663. char *recv_line(struct pool *pool)
  1664. {
  1665. char *tok, *sret = NULL;
  1666. ssize_t len, buflen;
  1667. int waited = 0;
  1668. if (!strstr(pool->sockbuf, "\n")) {
  1669. struct timeval rstart, now;
  1670. cgtime(&rstart);
  1671. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1672. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1673. goto out;
  1674. }
  1675. do {
  1676. char s[RBUFSIZE];
  1677. size_t slen;
  1678. ssize_t n;
  1679. memset(s, 0, RBUFSIZE);
  1680. n = recv(pool->sock, s, RECVSIZE, 0);
  1681. if (!n) {
  1682. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1683. suspend_stratum(pool);
  1684. break;
  1685. }
  1686. cgtime(&now);
  1687. waited = tdiff(&now, &rstart);
  1688. if (n < 0) {
  1689. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1690. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1691. suspend_stratum(pool);
  1692. break;
  1693. }
  1694. } else {
  1695. slen = strlen(s);
  1696. recalloc_sock(pool, slen);
  1697. strcat(pool->sockbuf, s);
  1698. }
  1699. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1700. }
  1701. buflen = strlen(pool->sockbuf);
  1702. tok = strtok(pool->sockbuf, "\n");
  1703. if (!tok) {
  1704. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1705. goto out;
  1706. }
  1707. sret = strdup(tok);
  1708. len = strlen(sret);
  1709. /* Copy what's left in the buffer after the \n, including the
  1710. * terminating \0 */
  1711. if (buflen > len + 1)
  1712. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1713. else
  1714. strcpy(pool->sockbuf, "");
  1715. pool->cgminer_pool_stats.times_received++;
  1716. pool->cgminer_pool_stats.bytes_received += len;
  1717. pool->cgminer_pool_stats.net_bytes_received += len;
  1718. out:
  1719. if (!sret)
  1720. clear_sock(pool);
  1721. else if (opt_protocol)
  1722. applog(LOG_DEBUG, "RECVD: %s", sret);
  1723. return sret;
  1724. }
  1725. /* Extracts a string value from a json array with error checking. To be used
  1726. * when the value of the string returned is only examined and not to be stored.
  1727. * See json_array_string below */
  1728. static char *__json_array_string(json_t *val, unsigned int entry)
  1729. {
  1730. json_t *arr_entry;
  1731. if (json_is_null(val))
  1732. return NULL;
  1733. if (!json_is_array(val))
  1734. return NULL;
  1735. if (entry > json_array_size(val))
  1736. return NULL;
  1737. arr_entry = json_array_get(val, entry);
  1738. if (!json_is_string(arr_entry))
  1739. return NULL;
  1740. return (char *)json_string_value(arr_entry);
  1741. }
  1742. /* Creates a freshly malloced dup of __json_array_string */
  1743. static char *json_array_string(json_t *val, unsigned int entry)
  1744. {
  1745. char *buf = __json_array_string(val, entry);
  1746. if (buf)
  1747. return strdup(buf);
  1748. return NULL;
  1749. }
  1750. static char *blank_merkle = "0000000000000000000000000000000000000000000000000000000000000000";
  1751. #ifdef HAVE_LIBCURL
  1752. static void decode_exit(struct pool *pool, char *cb)
  1753. {
  1754. CURL *curl = curl_easy_init();
  1755. char *decreq, *s;
  1756. json_t *val;
  1757. int dummy;
  1758. if (!opt_btcd && !sleep(3) && !opt_btcd) {
  1759. applog(LOG_ERR, "No bitcoind specified, unable to decode coinbase.");
  1760. exit(1);
  1761. }
  1762. decreq = cgmalloc(strlen(cb) + 256);
  1763. sprintf(decreq, "{\"id\": 0, \"method\": \"decoderawtransaction\", \"params\": [\"%s\"]}\n",
  1764. cb);
  1765. val = json_rpc_call(curl, opt_btcd->rpc_url, opt_btcd->rpc_userpass, decreq,
  1766. false, false, &dummy, opt_btcd, false);
  1767. free(decreq);
  1768. if (!val) {
  1769. applog(LOG_ERR, "Failed json_rpc_call to btcd %s", opt_btcd->rpc_url);
  1770. exit(1);
  1771. }
  1772. s = json_dumps(val, JSON_INDENT(4));
  1773. printf("Pool %s:\n%s\n", pool->rpc_url, s);
  1774. free(s);
  1775. exit(0);
  1776. }
  1777. #else
  1778. static void decode_exit(struct pool __maybe_unused *pool, char __maybe_unused *b)
  1779. {
  1780. }
  1781. #endif
  1782. static int calculate_num_bits(int num)
  1783. {
  1784. int ret=0;
  1785. while(num != 0)
  1786. {
  1787. ret++;
  1788. num /= 16;
  1789. }
  1790. return ret;
  1791. }
  1792. static void get_vmask(struct pool *pool, char *bbversion)
  1793. {
  1794. char defaultStr[9]= "00000000";
  1795. int bversion, num_bits, i, j;
  1796. uint8_t buffer[4] = {};
  1797. uint32_t uiMagicNum;
  1798. char *tmpstr;
  1799. uint32_t *p1;
  1800. p1 = (uint32_t *)buffer;
  1801. bversion = strtol(bbversion, NULL, 16);
  1802. for (i = 0; i < 4; i++) {
  1803. uiMagicNum = bversion | pool->vmask_003[i];
  1804. //printf("[ccx]uiMagicNum:0x%x. \n", uiMagicNum);
  1805. *p1 = bswap_32(uiMagicNum);
  1806. //printf("[ccx]*p1:0x%x. \n", *p1);
  1807. switch(i) {
  1808. case 0:
  1809. pool->vmask_001[8] = *p1;
  1810. break;
  1811. case 1:
  1812. pool->vmask_001[4] = *p1;
  1813. break;
  1814. case 2:
  1815. pool->vmask_001[2] = *p1;
  1816. break;
  1817. case 3:
  1818. pool->vmask_001[0] = *p1;
  1819. break;
  1820. default:
  1821. break;
  1822. }
  1823. }
  1824. for (i = 0; i < 16; i++) {
  1825. if ((i!= 2) && (i!=4) && (i!=8))
  1826. pool->vmask_001[i] = pool->vmask_001[0];
  1827. }
  1828. for (i = 0; i < 16; i++)
  1829. memcpy(pool->vmask_002[i], defaultStr, 9);
  1830. for (i = 0; i < 3; i++) {
  1831. char cMask[12];
  1832. tmpstr = (char *)cgcalloc(9, 1);
  1833. num_bits = calculate_num_bits(pool->vmask_003[i]);
  1834. for (j = 0; j < (8-num_bits); j++)
  1835. tmpstr[j] = '0';
  1836. snprintf(cMask, 9, "%x", pool->vmask_003[i]);
  1837. memcpy(tmpstr + 8 - num_bits, cMask, num_bits);
  1838. tmpstr[8] = '\0';
  1839. //printf("[ccx]tmpstr:%s. \n", tmpstr);
  1840. switch(i) {
  1841. case 0:
  1842. memcpy(pool->vmask_002[8], tmpstr, 9);
  1843. break;
  1844. case 1:
  1845. memcpy(pool->vmask_002[4], tmpstr, 9);
  1846. break;
  1847. case 2:
  1848. memcpy(pool->vmask_002[2], tmpstr, 9);
  1849. break;
  1850. default:
  1851. break;
  1852. }
  1853. free(tmpstr);
  1854. }
  1855. }
  1856. static bool set_vmask(struct pool *pool, json_t *val)
  1857. {
  1858. int mask, tmpMask = 0, cnt = 0, i, rem;
  1859. const char *version_mask;
  1860. version_mask = json_string_value(val);
  1861. applog(LOG_INFO, "Pool %d version_mask:%s.", pool->pool_no, version_mask);
  1862. mask = strtol(version_mask, NULL, 16);
  1863. if (!mask)
  1864. return false;
  1865. pool->vmask_003[0] = mask;
  1866. while (mask % 16 == 0) {
  1867. cnt++;
  1868. mask /= 16;
  1869. }
  1870. if ((rem = mask % 16))
  1871. tmpMask = rem;
  1872. else if ((rem = mask % 8))
  1873. tmpMask = rem;
  1874. else if ((rem = mask % 4))
  1875. tmpMask = rem;
  1876. else if ((rem = mask % 2))
  1877. tmpMask = rem;
  1878. for (i = 0; i < cnt; i++)
  1879. tmpMask *= 16;
  1880. pool->vmask_003[2] = tmpMask;
  1881. pool->vmask_003[1] = pool->vmask_003[0] - tmpMask;
  1882. return true;
  1883. }
  1884. #ifdef USE_VMASK
  1885. #define STRATUM_VERSION_ROLLING "version-rolling"
  1886. #define STRATUM_VERSION_ROLLING_LEN (sizeof(STRATUM_VERSION_ROLLING) - 1)
  1887. /**
  1888. * Configures stratum mining based on connected hardware capabilities
  1889. * (version rolling etc.)
  1890. *
  1891. * Sample communication
  1892. * Request:
  1893. * {"id": 1, "method": "mining.configure", "params": [ ["version-rolling"], "version-rolling.mask": "ffffffff" }]}\n
  1894. * Response:
  1895. * {"id": 1, "result": { "version-rolling": True, "version-rolling.mask": "00003000" }, "error": null}\n
  1896. *
  1897. * @param pool
  1898. *
  1899. *
  1900. * @return
  1901. */
  1902. static bool configure_stratum_mining(struct pool *pool)
  1903. {
  1904. char s[RBUFSIZE];
  1905. char *response_str = NULL;
  1906. bool config_status = false;
  1907. bool version_rolling_status = false;
  1908. bool version_mask_valid = false;
  1909. const char *key;
  1910. json_t *response, *value, *res_val, *err_val;
  1911. json_error_t err;
  1912. #ifdef USE_GEKKO
  1913. if (!opt_gekko_boost)
  1914. return true;
  1915. #endif
  1916. snprintf(s, RBUFSIZE,
  1917. "{\"id\": %d, \"method\": \"mining.configure\", \"params\": "
  1918. "[[\""STRATUM_VERSION_ROLLING"\"], "
  1919. "{\""STRATUM_VERSION_ROLLING".mask\": \"%x\""
  1920. "}]}",
  1921. swork_id++, 0xffffffff);
  1922. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1923. applog(LOG_DEBUG, "Failed to send mining.configure");
  1924. goto out;
  1925. }
  1926. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1927. applog(LOG_DEBUG, "Timed out waiting for response in %s", __FUNCTION__);
  1928. goto out;
  1929. }
  1930. response_str = recv_line(pool);
  1931. if (!response_str)
  1932. goto out;
  1933. response = JSON_LOADS(response_str, &err);
  1934. free(response_str);
  1935. res_val = json_object_get(response, "result");
  1936. err_val = json_object_get(response, "error");
  1937. if (!res_val || json_is_null(res_val) ||
  1938. (err_val && !json_is_null(err_val))) {
  1939. char *ss;
  1940. if (err_val)
  1941. ss = json_dumps(err_val, JSON_INDENT(3));
  1942. else
  1943. ss = strdup("(unknown reason)");
  1944. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1945. free(ss);
  1946. goto json_response_error;
  1947. }
  1948. json_object_foreach(res_val, key, value) {
  1949. if (!strcasecmp(key, STRATUM_VERSION_ROLLING) &&
  1950. strlen(key) == STRATUM_VERSION_ROLLING_LEN)
  1951. version_rolling_status = json_boolean_value(value);
  1952. else if (!strcasecmp(key, STRATUM_VERSION_ROLLING ".mask"))
  1953. pool->vmask = version_mask_valid = set_vmask(pool, value);
  1954. else
  1955. applog(LOG_ERR, "JSON-RPC unexpected mining.configure value: %s", key);
  1956. }
  1957. /* Valid configuration for now only requires enabled version rolling and valid bit mask */
  1958. config_status = version_rolling_status && version_mask_valid;
  1959. json_response_error:
  1960. json_decref(response);
  1961. out:
  1962. return config_status;
  1963. }
  1964. #else
  1965. static inline bool configure_stratum_mining(struct pool __maybe_unused *pool)
  1966. {
  1967. return true;
  1968. }
  1969. #endif
  1970. static bool parse_notify(struct pool *pool, json_t *val)
  1971. {
  1972. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1973. *ntime, header[260];
  1974. unsigned char *cb1 = NULL, *cb2 = NULL;
  1975. size_t cb1_len, cb2_len, alloc_len;
  1976. bool clean, ret = false;
  1977. int merkles, i;
  1978. json_t *arr;
  1979. arr = json_array_get(val, 4);
  1980. if (!arr || !json_is_array(arr))
  1981. goto out;
  1982. merkles = json_array_size(arr);
  1983. job_id = json_array_string(val, 0);
  1984. prev_hash = __json_array_string(val, 1);
  1985. coinbase1 = json_array_string(val, 2);
  1986. coinbase2 = json_array_string(val, 3);
  1987. bbversion = __json_array_string(val, 5);
  1988. nbit = __json_array_string(val, 6);
  1989. ntime = __json_array_string(val, 7);
  1990. clean = json_is_true(json_array_get(val, 8));
  1991. get_vmask(pool, bbversion);
  1992. if (!valid_ascii(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||
  1993. !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||
  1994. !valid_hex(ntime)) {
  1995. /* Annoying but we must not leak memory */
  1996. free(job_id);
  1997. free(coinbase1);
  1998. free(coinbase2);
  1999. goto out;
  2000. }
  2001. cg_wlock(&pool->data_lock);
  2002. free(pool->swork.job_id);
  2003. pool->swork.job_id = job_id;
  2004. if (memcmp(pool->prev_hash, prev_hash, 64)) {
  2005. pool->swork.clean = true;
  2006. } else {
  2007. pool->swork.clean = clean;
  2008. }
  2009. snprintf(pool->prev_hash, 65, "%s", prev_hash);
  2010. cb1_len = strlen(coinbase1) / 2;
  2011. cb2_len = strlen(coinbase2) / 2;
  2012. snprintf(pool->bbversion, 9, "%s", bbversion);
  2013. snprintf(pool->nbit, 9, "%s", nbit);
  2014. snprintf(pool->ntime, 9, "%s", ntime);
  2015. if (pool->next_diff > 0) {
  2016. pool->sdiff = pool->next_diff;
  2017. pool->next_diff = pool->diff_after;
  2018. pool->diff_after = 0;
  2019. }
  2020. alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  2021. pool->nonce2_offset = cb1_len + pool->n1_len;
  2022. for (i = 0; i < pool->merkles; i++)
  2023. free(pool->swork.merkle_bin[i]);
  2024. if (merkles) {
  2025. pool->swork.merkle_bin = cgrealloc(pool->swork.merkle_bin,
  2026. sizeof(char *) * merkles + 1);
  2027. for (i = 0; i < merkles; i++) {
  2028. char *merkle = json_array_string(arr, i);
  2029. pool->swork.merkle_bin[i] = cgmalloc(32);
  2030. if (opt_protocol)
  2031. applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
  2032. ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  2033. free(merkle);
  2034. if (unlikely(!ret)) {
  2035. applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
  2036. goto out_unlock;
  2037. }
  2038. }
  2039. }
  2040. pool->merkles = merkles;
  2041. if (pool->merkles < 2)
  2042. pool->bad_work++;
  2043. if (clean)
  2044. pool->nonce2 = 0;
  2045. #if 0
  2046. header_len = strlen(pool->bbversion) +
  2047. strlen(pool->prev_hash);
  2048. /* merkle_hash */ 32 +
  2049. strlen(pool->ntime) +
  2050. strlen(pool->nbit) +
  2051. /* nonce */ 8 +
  2052. /* workpadding */ 96;
  2053. #endif
  2054. snprintf(header, 257,
  2055. "%s%s%s%s%s%s%s",
  2056. pool->bbversion,
  2057. pool->prev_hash,
  2058. blank_merkle,
  2059. pool->ntime,
  2060. pool->nbit,
  2061. "00000000", /* nonce */
  2062. workpadding);
  2063. ret = hex2bin(pool->header_bin, header, 128);
  2064. if (unlikely(!ret)) {
  2065. applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
  2066. goto out_unlock;
  2067. }
  2068. cb1 = alloca(cb1_len);
  2069. ret = hex2bin(cb1, coinbase1, cb1_len);
  2070. if (unlikely(!ret)) {
  2071. applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
  2072. goto out_unlock;
  2073. }
  2074. cb2 = alloca(cb2_len);
  2075. ret = hex2bin(cb2, coinbase2, cb2_len);
  2076. if (unlikely(!ret)) {
  2077. applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
  2078. goto out_unlock;
  2079. }
  2080. free(pool->coinbase);
  2081. pool->coinbase = cgcalloc(alloc_len, 1);
  2082. cg_memcpy(pool->coinbase, cb1, cb1_len);
  2083. if (pool->n1_len)
  2084. cg_memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  2085. cg_memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  2086. if (opt_debug || opt_decode) {
  2087. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  2088. if (opt_decode)
  2089. decode_exit(pool, cb);
  2090. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  2091. free(cb);
  2092. }
  2093. out_unlock:
  2094. cg_wunlock(&pool->data_lock);
  2095. if (opt_protocol) {
  2096. applog(LOG_DEBUG, "job_id: %s", job_id);
  2097. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  2098. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  2099. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  2100. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  2101. applog(LOG_DEBUG, "nbit: %s", nbit);
  2102. applog(LOG_DEBUG, "ntime: %s", ntime);
  2103. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  2104. }
  2105. free(coinbase1);
  2106. free(coinbase2);
  2107. /* A notify message is the closest stratum gets to a getwork */
  2108. pool->getwork_requested++;
  2109. total_getworks++;
  2110. if (pool == current_pool())
  2111. opt_work_update = true;
  2112. out:
  2113. return ret;
  2114. }
  2115. static bool parse_diff(struct pool *pool, json_t *val)
  2116. {
  2117. double old_diff, diff;
  2118. diff = json_number_value(json_array_get(val, 0));
  2119. if (diff <= 0)
  2120. return false;
  2121. /* We can only change one diff per notify so assume diffs are being
  2122. * stacked for successive notifies. */
  2123. cg_wlock(&pool->data_lock);
  2124. if (pool->next_diff)
  2125. pool->diff_after = diff;
  2126. else
  2127. pool->next_diff = diff;
  2128. old_diff = pool->sdiff;
  2129. cg_wunlock(&pool->data_lock);
  2130. if (old_diff != diff) {
  2131. int idiff = diff;
  2132. if ((double)idiff == diff)
  2133. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  2134. pool->pool_no, idiff);
  2135. else
  2136. applog(LOG_NOTICE, "Pool %d difficulty changed to %.1f",
  2137. pool->pool_no, diff);
  2138. } else
  2139. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  2140. diff);
  2141. return true;
  2142. }
  2143. static bool parse_extranonce(struct pool *pool, json_t *val)
  2144. {
  2145. char s[RBUFSIZE], *nonce1;
  2146. int n2size;
  2147. nonce1 = json_array_string(val, 0);
  2148. if (!valid_hex(nonce1)) {
  2149. applog(LOG_INFO, "Failed to get valid nonce1 in parse_extranonce");
  2150. return false;
  2151. }
  2152. n2size = json_integer_value(json_array_get(val, 1));
  2153. if (!n2size) {
  2154. applog(LOG_INFO, "Failed to get valid n2size in parse_extranonce");
  2155. free(nonce1);
  2156. return false;
  2157. }
  2158. cg_wlock(&pool->data_lock);
  2159. free(pool->nonce1);
  2160. pool->nonce1 = nonce1;
  2161. pool->n1_len = strlen(nonce1) / 2;
  2162. free(pool->nonce1bin);
  2163. pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
  2164. if (unlikely(!pool->nonce1bin))
  2165. quithere(1, "Failed to calloc pool->nonce1bin");
  2166. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2167. pool->n2size = n2size;
  2168. cg_wunlock(&pool->data_lock);
  2169. applog(LOG_NOTICE, "Pool %d extranonce change requested", pool->pool_no);
  2170. return true;
  2171. }
  2172. static void __suspend_stratum(struct pool *pool)
  2173. {
  2174. clear_sockbuf(pool);
  2175. pool->stratum_active = pool->stratum_notify = false;
  2176. if (pool->sock)
  2177. CLOSESOCKET(pool->sock);
  2178. pool->sock = 0;
  2179. }
  2180. static bool parse_reconnect(struct pool *pool, json_t *val)
  2181. {
  2182. char *sockaddr_url, *stratum_port, *tmp;
  2183. char *url, *port, address[256];
  2184. int port_no;
  2185. memset(address, 0, 255);
  2186. url = (char *)json_string_value(json_array_get(val, 0));
  2187. if (!url)
  2188. url = pool->sockaddr_url;
  2189. else {
  2190. char *dot_pool, *dot_reconnect;
  2191. dot_pool = strchr(pool->sockaddr_url, '.');
  2192. if (!dot_pool) {
  2193. applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
  2194. pool->sockaddr_url);
  2195. return false;
  2196. }
  2197. dot_reconnect = strchr(url, '.');
  2198. if (!dot_reconnect) {
  2199. applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
  2200. url);
  2201. return false;
  2202. }
  2203. if (strcmp(dot_pool, dot_reconnect)) {
  2204. applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
  2205. pool->sockaddr_url);
  2206. return false;
  2207. }
  2208. }
  2209. port_no = json_integer_value(json_array_get(val, 1));
  2210. if (port_no) {
  2211. port = alloca(256);
  2212. sprintf(port, "%d", port_no);
  2213. } else {
  2214. port = (char *)json_string_value(json_array_get(val, 1));
  2215. if (!port)
  2216. port = pool->stratum_port;
  2217. }
  2218. snprintf(address, 254, "%s:%s", url, port);
  2219. if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
  2220. return false;
  2221. applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
  2222. clear_pool_work(pool);
  2223. mutex_lock(&pool->stratum_lock);
  2224. __suspend_stratum(pool);
  2225. tmp = pool->sockaddr_url;
  2226. pool->sockaddr_url = sockaddr_url;
  2227. pool->stratum_url = pool->sockaddr_url;
  2228. free(tmp);
  2229. tmp = pool->stratum_port;
  2230. pool->stratum_port = stratum_port;
  2231. free(tmp);
  2232. mutex_unlock(&pool->stratum_lock);
  2233. return restart_stratum(pool);
  2234. }
  2235. static bool send_version(struct pool *pool, json_t *val)
  2236. {
  2237. json_t *id_val = json_object_get(val, "id");
  2238. char s[RBUFSIZE];
  2239. int id;
  2240. if (!id_val)
  2241. return false;
  2242. id = json_integer_value(json_object_get(val, "id"));
  2243. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\", \"error\": null}", id);
  2244. if (!stratum_send(pool, s, strlen(s)))
  2245. return false;
  2246. return true;
  2247. }
  2248. static bool send_pong(struct pool *pool, json_t *val)
  2249. {
  2250. json_t *id_val = json_object_get(val, "id");
  2251. char s[RBUFSIZE];
  2252. int id;
  2253. if (!id_val)
  2254. return false;
  2255. id = json_integer_value(json_object_get(val, "id"));
  2256. sprintf(s, "{\"id\": %d, \"result\": \"pong\", \"error\": null}", id);
  2257. if (!stratum_send(pool, s, strlen(s)))
  2258. return false;
  2259. return true;
  2260. }
  2261. static bool show_message(struct pool *pool, json_t *val)
  2262. {
  2263. char *msg;
  2264. if (!json_is_array(val))
  2265. return false;
  2266. msg = (char *)json_string_value(json_array_get(val, 0));
  2267. if (!msg)
  2268. return false;
  2269. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  2270. return true;
  2271. }
  2272. static bool parse_vmask(struct pool *pool, json_t *params)
  2273. {
  2274. bool ret = false;
  2275. if (!params) {
  2276. applog(LOG_INFO, "No params with parse_vmask given for pool %d",
  2277. pool->pool_no);
  2278. goto out;
  2279. }
  2280. if (json_is_array(params))
  2281. params = json_array_get(params, 0);
  2282. //if (!json_is_string(params) || !json_string_length(params)) { //wait cgliner fix this error
  2283. if (!json_is_string(params)) {
  2284. applog(LOG_INFO, "Params invalid string for parse_vmask for pool %d",
  2285. pool->pool_no);
  2286. goto out;
  2287. }
  2288. pool->vmask = set_vmask(pool, params);
  2289. ret = true;
  2290. out:
  2291. return ret;
  2292. }
  2293. bool parse_method(struct pool *pool, char *s)
  2294. {
  2295. json_t *val = NULL, *method, *err_val, *params;
  2296. json_error_t err;
  2297. bool ret = false;
  2298. char *buf;
  2299. if (!s)
  2300. goto out;
  2301. val = JSON_LOADS(s, &err);
  2302. if (!val) {
  2303. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2304. goto out;
  2305. }
  2306. method = json_object_get(val, "method");
  2307. if (!method)
  2308. goto out_decref;
  2309. err_val = json_object_get(val, "error");
  2310. params = json_object_get(val, "params");
  2311. if (err_val && !json_is_null(err_val)) {
  2312. char *ss;
  2313. if (err_val)
  2314. ss = json_dumps(err_val, JSON_INDENT(3));
  2315. else
  2316. ss = strdup("(unknown reason)");
  2317. applog(LOG_INFO, "JSON-RPC method decode of %s failed: %s", s, ss);
  2318. free(ss);
  2319. goto out_decref;
  2320. }
  2321. buf = (char *)json_string_value(method);
  2322. if (!buf)
  2323. goto out_decref;
  2324. if (!strncasecmp(buf, "mining.notify", 13)) {
  2325. if (parse_notify(pool, params))
  2326. pool->stratum_notify = ret = true;
  2327. else
  2328. pool->stratum_notify = ret = false;
  2329. goto out_decref;
  2330. }
  2331. if (!strncasecmp(buf, "mining.set_difficulty", 21)) {
  2332. ret = parse_diff(pool, params);
  2333. goto out_decref;
  2334. }
  2335. if (!strncasecmp(buf, "mining.set_extranonce", 21)) {
  2336. ret = parse_extranonce(pool, params);
  2337. goto out_decref;
  2338. }
  2339. if (!strncasecmp(buf, "client.reconnect", 16)) {
  2340. ret = parse_reconnect(pool, params);
  2341. goto out_decref;
  2342. }
  2343. if (!strncasecmp(buf, "client.get_version", 18)) {
  2344. ret = send_version(pool, val);
  2345. goto out_decref;
  2346. }
  2347. if (!strncasecmp(buf, "client.show_message", 19)) {
  2348. ret = show_message(pool, params);
  2349. goto out_decref;
  2350. }
  2351. if (!strncasecmp(buf, "mining.ping", 11)) {
  2352. applog(LOG_INFO, "Pool %d ping", pool->pool_no);
  2353. ret = send_pong(pool, val);
  2354. goto out_decref;
  2355. }
  2356. if (!strncasecmp(buf, "mining.set_version_mask", 23)) {
  2357. ret = parse_vmask(pool, params);
  2358. goto out_decref;
  2359. }
  2360. applog(LOG_INFO, "Unknown JSON-RPC from pool %d: %s", pool->pool_no, s);
  2361. out_decref:
  2362. json_decref(val);
  2363. out:
  2364. return ret;
  2365. }
  2366. bool subscribe_extranonce(struct pool *pool)
  2367. {
  2368. json_t *val = NULL, *res_val, *err_val;
  2369. char s[RBUFSIZE], *sret = NULL;
  2370. json_error_t err;
  2371. bool ret = false;
  2372. sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}",
  2373. swork_id++);
  2374. if (!stratum_send(pool, s, strlen(s)))
  2375. return ret;
  2376. /* Parse all data in the queue and anything left should be the response */
  2377. while (42) {
  2378. if (!socket_full(pool, DEFAULT_SOCKWAIT / 30)) {
  2379. applog(LOG_DEBUG, "Timed out waiting for response extranonce.subscribe");
  2380. /* some pool doesnt send anything, so this is normal */
  2381. ret = true;
  2382. goto out;
  2383. }
  2384. sret = recv_line(pool);
  2385. if (!sret)
  2386. return ret;
  2387. if (parse_method(pool, sret))
  2388. free(sret);
  2389. else
  2390. break;
  2391. }
  2392. val = JSON_LOADS(sret, &err);
  2393. free(sret);
  2394. res_val = json_object_get(val, "result");
  2395. err_val = json_object_get(val, "error");
  2396. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2397. char *ss;
  2398. if (err_val) {
  2399. ss = __json_array_string(err_val, 1);
  2400. if (!ss)
  2401. ss = (char *)json_string_value(err_val);
  2402. if (ss && (strcmp(ss, "Method 'subscribe' not found for service 'mining.extranonce'") == 0)) {
  2403. applog(LOG_INFO, "Cannot subscribe to mining.extranonce for pool %d", pool->pool_no);
  2404. ret = true;
  2405. goto out;
  2406. }
  2407. if (ss && (strcmp(ss, "Unrecognized request provided") == 0)) {
  2408. applog(LOG_INFO, "Cannot subscribe to mining.extranonce for pool %d", pool->pool_no);
  2409. ret = true;
  2410. goto out;
  2411. }
  2412. ss = json_dumps(err_val, JSON_INDENT(3));
  2413. }
  2414. else
  2415. ss = strdup("(unknown reason)");
  2416. applog(LOG_INFO, "Pool %d JSON extranonce subscribe failed: %s", pool->pool_no, ss);
  2417. free(ss);
  2418. goto out;
  2419. }
  2420. ret = true;
  2421. applog(LOG_INFO, "Stratum extranonce subscribe for pool %d", pool->pool_no);
  2422. out:
  2423. json_decref(val);
  2424. return ret;
  2425. }
  2426. bool auth_stratum(struct pool *pool)
  2427. {
  2428. json_t *val = NULL, *res_val, *err_val;
  2429. char s[RBUFSIZE], *sret = NULL;
  2430. json_error_t err;
  2431. bool ret = false;
  2432. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  2433. swork_id++, pool->rpc_user, pool->rpc_pass);
  2434. if (!stratum_send(pool, s, strlen(s)))
  2435. return ret;
  2436. /* Parse all data in the queue and anything left should be auth */
  2437. while (42) {
  2438. sret = recv_line(pool);
  2439. if (!sret)
  2440. return ret;
  2441. if (parse_method(pool, sret))
  2442. free(sret);
  2443. else
  2444. break;
  2445. }
  2446. val = JSON_LOADS(sret, &err);
  2447. free(sret);
  2448. res_val = json_object_get(val, "result");
  2449. err_val = json_object_get(val, "error");
  2450. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2451. char *ss;
  2452. if (err_val)
  2453. ss = json_dumps(err_val, JSON_INDENT(3));
  2454. else
  2455. ss = strdup("(unknown reason)");
  2456. applog(LOG_INFO, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  2457. free(ss);
  2458. suspend_stratum(pool);
  2459. goto out;
  2460. }
  2461. ret = true;
  2462. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  2463. pool->probed = true;
  2464. successful_connect = true;
  2465. if (opt_suggest_diff) {
  2466. sprintf(s, "{\"id\": %d, \"method\": \"mining.suggest_difficulty\", \"params\": [%d]}",
  2467. swork_id++, opt_suggest_diff);
  2468. stratum_send(pool, s, strlen(s));
  2469. }
  2470. out:
  2471. json_decref(val);
  2472. return ret;
  2473. }
  2474. static int recv_byte(int sockd)
  2475. {
  2476. char c;
  2477. if (recv(sockd, &c, 1, 0) != -1)
  2478. return c;
  2479. return -1;
  2480. }
  2481. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  2482. {
  2483. char buf[1024];
  2484. int i, len;
  2485. if (http0) {
  2486. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  2487. pool->sockaddr_url, pool->stratum_port);
  2488. } else {
  2489. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  2490. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  2491. pool->stratum_port);
  2492. }
  2493. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  2494. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2495. send(sockd, buf, strlen(buf), 0);
  2496. len = recv(sockd, buf, 12, 0);
  2497. if (len <= 0) {
  2498. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  2499. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2500. return false;
  2501. }
  2502. buf[len] = '\0';
  2503. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  2504. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2505. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  2506. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  2507. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2508. return false;
  2509. }
  2510. /* Ignore unwanted headers till we get desired response */
  2511. for (i = 0; i < 4; i++) {
  2512. buf[i] = recv_byte(sockd);
  2513. if (buf[i] == (char)-1) {
  2514. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2515. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2516. return false;
  2517. }
  2518. }
  2519. while (strncmp(buf, "\r\n\r\n", 4)) {
  2520. for (i = 0; i < 3; i++)
  2521. buf[i] = buf[i + 1];
  2522. buf[3] = recv_byte(sockd);
  2523. if (buf[3] == (char)-1) {
  2524. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2525. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2526. return false;
  2527. }
  2528. }
  2529. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  2530. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2531. return true;
  2532. }
  2533. static bool socks5_negotiate(struct pool *pool, int sockd)
  2534. {
  2535. unsigned char atyp, uclen;
  2536. unsigned short port;
  2537. char buf[515];
  2538. int i, len;
  2539. buf[0] = 0x05;
  2540. buf[1] = 0x01;
  2541. buf[2] = 0x00;
  2542. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  2543. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2544. send(sockd, buf, 3, 0);
  2545. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  2546. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2547. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2548. return false;
  2549. }
  2550. buf[0] = 0x05;
  2551. buf[1] = 0x01;
  2552. buf[2] = 0x00;
  2553. buf[3] = 0x03;
  2554. len = (strlen(pool->sockaddr_url));
  2555. if (len > 255)
  2556. len = 255;
  2557. uclen = len;
  2558. buf[4] = (uclen & 0xff);
  2559. cg_memcpy(buf + 5, pool->sockaddr_url, len);
  2560. port = atoi(pool->stratum_port);
  2561. buf[5 + len] = (port >> 8);
  2562. buf[6 + len] = (port & 0xff);
  2563. send(sockd, buf, (7 + len), 0);
  2564. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  2565. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2566. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2567. return false;
  2568. }
  2569. recv_byte(sockd);
  2570. atyp = recv_byte(sockd);
  2571. if (atyp == 0x01) {
  2572. for (i = 0; i < 4; i++)
  2573. recv_byte(sockd);
  2574. } else if (atyp == 0x03) {
  2575. len = recv_byte(sockd);
  2576. for (i = 0; i < len; i++)
  2577. recv_byte(sockd);
  2578. } else {
  2579. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2580. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2581. return false;
  2582. }
  2583. for (i = 0; i < 2; i++)
  2584. recv_byte(sockd);
  2585. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  2586. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2587. return true;
  2588. }
  2589. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  2590. {
  2591. unsigned short port;
  2592. in_addr_t inp;
  2593. char buf[515];
  2594. int i, len;
  2595. buf[0] = 0x04;
  2596. buf[1] = 0x01;
  2597. port = atoi(pool->stratum_port);
  2598. buf[2] = port >> 8;
  2599. buf[3] = port & 0xff;
  2600. sprintf(&buf[8], "CGMINER");
  2601. /* See if we've been given an IP address directly to avoid needing to
  2602. * resolve it. */
  2603. inp = inet_addr(pool->sockaddr_url);
  2604. inp = ntohl(inp);
  2605. if ((int)inp != -1)
  2606. socks4a = false;
  2607. else {
  2608. /* Try to extract the IP address ourselves first */
  2609. struct addrinfo servinfobase, *servinfo, hints;
  2610. servinfo = &servinfobase;
  2611. memset(&hints, 0, sizeof(struct addrinfo));
  2612. hints.ai_family = AF_INET; /* IPV4 only */
  2613. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  2614. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  2615. inp = ntohl(saddr_in->sin_addr.s_addr);
  2616. socks4a = false;
  2617. freeaddrinfo(servinfo);
  2618. }
  2619. }
  2620. if (!socks4a) {
  2621. if ((int)inp == -1) {
  2622. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  2623. pool->sockaddr_url);
  2624. return false;
  2625. }
  2626. buf[4] = (inp >> 24) & 0xFF;
  2627. buf[5] = (inp >> 16) & 0xFF;
  2628. buf[6] = (inp >> 8) & 0xFF;
  2629. buf[7] = (inp >> 0) & 0xFF;
  2630. send(sockd, buf, 16, 0);
  2631. } else {
  2632. /* This appears to not be working but hopefully most will be
  2633. * able to resolve IP addresses themselves. */
  2634. buf[4] = 0;
  2635. buf[5] = 0;
  2636. buf[6] = 0;
  2637. buf[7] = 1;
  2638. len = strlen(pool->sockaddr_url);
  2639. if (len > 255)
  2640. len = 255;
  2641. cg_memcpy(&buf[16], pool->sockaddr_url, len);
  2642. len += 16;
  2643. buf[len++] = '\0';
  2644. send(sockd, buf, len, 0);
  2645. }
  2646. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  2647. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  2648. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2649. return false;
  2650. }
  2651. for (i = 0; i < 6; i++)
  2652. recv_byte(sockd);
  2653. return true;
  2654. }
  2655. static void noblock_socket(SOCKETTYPE fd)
  2656. {
  2657. #ifndef WIN32
  2658. int flags = fcntl(fd, F_GETFL, 0);
  2659. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  2660. #else
  2661. u_long flags = 1;
  2662. ioctlsocket(fd, FIONBIO, &flags);
  2663. #endif
  2664. }
  2665. static void block_socket(SOCKETTYPE fd)
  2666. {
  2667. #ifndef WIN32
  2668. int flags = fcntl(fd, F_GETFL, 0);
  2669. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  2670. #else
  2671. u_long flags = 0;
  2672. ioctlsocket(fd, FIONBIO, &flags);
  2673. #endif
  2674. }
  2675. static bool sock_connecting(void)
  2676. {
  2677. #ifndef WIN32
  2678. return errno == EINPROGRESS;
  2679. #else
  2680. return WSAGetLastError() == WSAEWOULDBLOCK;
  2681. #endif
  2682. }
  2683. static bool setup_stratum_socket(struct pool *pool)
  2684. {
  2685. struct addrinfo *servinfo, hints, *p;
  2686. char *sockaddr_url, *sockaddr_port;
  2687. int sockd;
  2688. mutex_lock(&pool->stratum_lock);
  2689. pool->stratum_active = false;
  2690. if (pool->sock)
  2691. CLOSESOCKET(pool->sock);
  2692. pool->sock = 0;
  2693. mutex_unlock(&pool->stratum_lock);
  2694. memset(&hints, 0, sizeof(struct addrinfo));
  2695. hints.ai_family = AF_UNSPEC;
  2696. hints.ai_socktype = SOCK_STREAM;
  2697. if (!pool->rpc_proxy && opt_socks_proxy) {
  2698. pool->rpc_proxy = opt_socks_proxy;
  2699. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  2700. pool->rpc_proxytype = PROXY_SOCKS5;
  2701. }
  2702. if (pool->rpc_proxy) {
  2703. sockaddr_url = pool->sockaddr_proxy_url;
  2704. sockaddr_port = pool->sockaddr_proxy_port;
  2705. } else {
  2706. sockaddr_url = pool->sockaddr_url;
  2707. sockaddr_port = pool->stratum_port;
  2708. }
  2709. if (getaddrinfo(sockaddr_url, sockaddr_port, &hints, &servinfo) != 0) {
  2710. if (!pool->probed) {
  2711. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  2712. sockaddr_url, sockaddr_port);
  2713. pool->probed = true;
  2714. } else {
  2715. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  2716. sockaddr_url, sockaddr_port);
  2717. }
  2718. return false;
  2719. }
  2720. for (p = servinfo; p != NULL; p = p->ai_next) {
  2721. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  2722. if (sockd == -1) {
  2723. applog(LOG_DEBUG, "Failed socket");
  2724. continue;
  2725. }
  2726. /* Iterate non blocking over entries returned by getaddrinfo
  2727. * to cope with round robin DNS entries, finding the first one
  2728. * we can connect to quickly. */
  2729. noblock_socket(sockd);
  2730. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  2731. struct timeval tv_timeout = {1, 0};
  2732. int selret;
  2733. fd_set rw;
  2734. if (!sock_connecting()) {
  2735. CLOSESOCKET(sockd);
  2736. applog(LOG_DEBUG, "Failed sock connect");
  2737. continue;
  2738. }
  2739. retry:
  2740. FD_ZERO(&rw);
  2741. FD_SET(sockd, &rw);
  2742. selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
  2743. if (selret > 0 && FD_ISSET(sockd, &rw)) {
  2744. socklen_t len;
  2745. int err, n;
  2746. len = sizeof(err);
  2747. n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);
  2748. if (!n && !err) {
  2749. applog(LOG_DEBUG, "Succeeded delayed connect");
  2750. block_socket(sockd);
  2751. break;
  2752. }
  2753. }
  2754. if (selret < 0 && interrupted())
  2755. goto retry;
  2756. CLOSESOCKET(sockd);
  2757. applog(LOG_DEBUG, "Select timeout/failed connect");
  2758. continue;
  2759. }
  2760. applog(LOG_WARNING, "Succeeded immediate connect");
  2761. block_socket(sockd);
  2762. break;
  2763. }
  2764. if (p == NULL) {
  2765. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  2766. sockaddr_url, sockaddr_port);
  2767. freeaddrinfo(servinfo);
  2768. return false;
  2769. }
  2770. freeaddrinfo(servinfo);
  2771. if (pool->rpc_proxy) {
  2772. switch (pool->rpc_proxytype) {
  2773. case PROXY_HTTP_1_0:
  2774. if (!http_negotiate(pool, sockd, true))
  2775. return false;
  2776. break;
  2777. case PROXY_HTTP:
  2778. if (!http_negotiate(pool, sockd, false))
  2779. return false;
  2780. break;
  2781. case PROXY_SOCKS5:
  2782. case PROXY_SOCKS5H:
  2783. if (!socks5_negotiate(pool, sockd))
  2784. return false;
  2785. break;
  2786. case PROXY_SOCKS4:
  2787. if (!socks4_negotiate(pool, sockd, false))
  2788. return false;
  2789. break;
  2790. case PROXY_SOCKS4A:
  2791. if (!socks4_negotiate(pool, sockd, true))
  2792. return false;
  2793. break;
  2794. default:
  2795. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  2796. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2797. return false;
  2798. break;
  2799. }
  2800. }
  2801. if (!pool->sockbuf) {
  2802. pool->sockbuf = cgcalloc(RBUFSIZE, 1);
  2803. pool->sockbuf_size = RBUFSIZE;
  2804. }
  2805. pool->sock = sockd;
  2806. keep_sockalive(sockd);
  2807. return true;
  2808. }
  2809. static char *get_sessionid(json_t *val)
  2810. {
  2811. char *ret = NULL;
  2812. json_t *arr_val;
  2813. int arrsize, i;
  2814. arr_val = json_array_get(val, 0);
  2815. if (!arr_val || !json_is_array(arr_val))
  2816. goto out;
  2817. arrsize = json_array_size(arr_val);
  2818. for (i = 0; i < arrsize; i++) {
  2819. json_t *arr = json_array_get(arr_val, i);
  2820. char *notify;
  2821. if (!arr | !json_is_array(arr))
  2822. break;
  2823. notify = __json_array_string(arr, 0);
  2824. if (!notify)
  2825. continue;
  2826. if (!strncasecmp(notify, "mining.notify", 13)) {
  2827. ret = json_array_string(arr, 1);
  2828. break;
  2829. }
  2830. }
  2831. out:
  2832. return ret;
  2833. }
  2834. void suspend_stratum(struct pool *pool)
  2835. {
  2836. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2837. mutex_lock(&pool->stratum_lock);
  2838. __suspend_stratum(pool);
  2839. mutex_unlock(&pool->stratum_lock);
  2840. }
  2841. bool initiate_stratum(struct pool *pool)
  2842. {
  2843. bool ret = false, recvd = false, noresume = false, sockd = false;
  2844. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid, *tmp;
  2845. json_t *val = NULL, *res_val, *err_val;
  2846. json_error_t err;
  2847. int n2size;
  2848. resend:
  2849. if (!setup_stratum_socket(pool)) {
  2850. sockd = false;
  2851. goto out;
  2852. }
  2853. sockd = true;
  2854. if (recvd) {
  2855. /* Get rid of any crap lying around if we're resending */
  2856. clear_sock(pool);
  2857. }
  2858. /* Attempt to configure stratum protocol feature set first. */
  2859. if (!configure_stratum_mining(pool))
  2860. goto out;
  2861. if (recvd) {
  2862. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2863. } else {
  2864. if (pool->sessionid)
  2865. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\", \"%s\"]}", swork_id++, pool->sessionid);
  2866. else
  2867. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\"]}", swork_id++);
  2868. }
  2869. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  2870. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2871. goto out;
  2872. }
  2873. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2874. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2875. goto out;
  2876. }
  2877. rereceive:
  2878. sret = recv_line(pool);
  2879. if (!sret)
  2880. goto out;
  2881. recvd = true;
  2882. val = JSON_LOADS(sret, &err);
  2883. if (!val) {
  2884. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2885. goto out;
  2886. }
  2887. res_val = json_object_get(val, "result");
  2888. err_val = json_object_get(val, "error");
  2889. if (!res_val) {
  2890. /* Check for a method just in case */
  2891. json_t *method_val = json_object_get(val, "method");
  2892. if (method_val && parse_method(pool, sret)) {
  2893. free(sret);
  2894. sret = NULL;
  2895. goto rereceive;
  2896. }
  2897. }
  2898. if (!res_val || json_is_null(res_val) ||
  2899. (err_val && !json_is_null(err_val))) {
  2900. char *ss;
  2901. if (err_val)
  2902. ss = json_dumps(err_val, JSON_INDENT(3));
  2903. else
  2904. ss = strdup("(unknown reason)");
  2905. applog(LOG_INFO, "JSON-RPC decode of message %s failed: %s", sret, ss);
  2906. free(ss);
  2907. goto out;
  2908. }
  2909. sessionid = get_sessionid(res_val);
  2910. if (!sessionid)
  2911. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2912. nonce1 = json_array_string(res_val, 1);
  2913. if (!valid_hex(nonce1)) {
  2914. applog(LOG_INFO, "Failed to get valid nonce1 in initiate_stratum");
  2915. free(sessionid);
  2916. free(nonce1);
  2917. goto out;
  2918. }
  2919. n2size = json_integer_value(json_array_get(res_val, 2));
  2920. if (n2size < 2 || n2size > 16) {
  2921. applog(LOG_INFO, "Failed to get valid n2size in initiate_stratum");
  2922. free(sessionid);
  2923. free(nonce1);
  2924. goto out;
  2925. }
  2926. if (sessionid && pool->sessionid && !strcmp(sessionid, pool->sessionid)) {
  2927. applog(LOG_NOTICE, "Pool %d successfully negotiated resume with the same session ID",
  2928. pool->pool_no);
  2929. }
  2930. cg_wlock(&pool->data_lock);
  2931. tmp = pool->sessionid;
  2932. pool->sessionid = sessionid;
  2933. free(tmp);
  2934. tmp = pool->nonce1;
  2935. pool->nonce1 = nonce1;
  2936. free(tmp);
  2937. pool->n1_len = strlen(nonce1) / 2;
  2938. free(pool->nonce1bin);
  2939. pool->nonce1bin = cgcalloc(pool->n1_len, 1);
  2940. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2941. pool->n2size = n2size;
  2942. cg_wunlock(&pool->data_lock);
  2943. if (sessionid)
  2944. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2945. ret = true;
  2946. out:
  2947. if (ret) {
  2948. if (!pool->stratum_url)
  2949. pool->stratum_url = pool->sockaddr_url;
  2950. pool->stratum_active = true;
  2951. pool->next_diff = pool->diff_after = 0;
  2952. pool->sdiff = 1;
  2953. if (opt_protocol) {
  2954. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2955. pool->pool_no, pool->nonce1, pool->n2size);
  2956. }
  2957. } else {
  2958. if (recvd && !noresume) {
  2959. /* Reset the sessionid used for stratum resuming in case the pool
  2960. * does not support it, or does not know how to respond to the
  2961. * presence of the sessionid parameter. */
  2962. cg_wlock(&pool->data_lock);
  2963. free(pool->sessionid);
  2964. free(pool->nonce1);
  2965. pool->sessionid = pool->nonce1 = NULL;
  2966. cg_wunlock(&pool->data_lock);
  2967. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2968. noresume = true;
  2969. json_decref(val);
  2970. goto resend;
  2971. }
  2972. applog(LOG_DEBUG, "Initiate stratum failed");
  2973. if (sockd)
  2974. suspend_stratum(pool);
  2975. }
  2976. json_decref(val);
  2977. free(sret);
  2978. return ret;
  2979. }
  2980. bool restart_stratum(struct pool *pool)
  2981. {
  2982. bool ret = false;
  2983. if (pool->stratum_active)
  2984. suspend_stratum(pool);
  2985. if (!initiate_stratum(pool))
  2986. goto out;
  2987. if (pool->extranonce_subscribe && !subscribe_extranonce(pool))
  2988. goto out;
  2989. if (!auth_stratum(pool))
  2990. goto out;
  2991. ret = true;
  2992. out:
  2993. if (!ret)
  2994. pool_died(pool);
  2995. else
  2996. stratum_resumed(pool);
  2997. return ret;
  2998. }
  2999. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  3000. {
  3001. dev->device_last_not_well = time(NULL);
  3002. dev->device_not_well_reason = reason;
  3003. switch (reason) {
  3004. case REASON_THREAD_FAIL_INIT:
  3005. dev->thread_fail_init_count++;
  3006. break;
  3007. case REASON_THREAD_ZERO_HASH:
  3008. dev->thread_zero_hash_count++;
  3009. break;
  3010. case REASON_THREAD_FAIL_QUEUE:
  3011. dev->thread_fail_queue_count++;
  3012. break;
  3013. case REASON_DEV_SICK_IDLE_60:
  3014. dev->dev_sick_idle_60_count++;
  3015. break;
  3016. case REASON_DEV_DEAD_IDLE_600:
  3017. dev->dev_dead_idle_600_count++;
  3018. break;
  3019. case REASON_DEV_NOSTART:
  3020. dev->dev_nostart_count++;
  3021. break;
  3022. case REASON_DEV_OVER_HEAT:
  3023. dev->dev_over_heat_count++;
  3024. break;
  3025. case REASON_DEV_THERMAL_CUTOFF:
  3026. dev->dev_thermal_cutoff_count++;
  3027. break;
  3028. case REASON_DEV_COMMS_ERROR:
  3029. dev->dev_comms_error_count++;
  3030. break;
  3031. case REASON_DEV_THROTTLE:
  3032. dev->dev_throttle_count++;
  3033. break;
  3034. }
  3035. }
  3036. /* Realloc an existing string to fit an extra string s, appending s to it. */
  3037. void *realloc_strcat(char *ptr, char *s)
  3038. {
  3039. size_t old = 0, len = strlen(s);
  3040. char *ret;
  3041. if (!len)
  3042. return ptr;
  3043. if (ptr)
  3044. old = strlen(ptr);
  3045. len += old + 1;
  3046. ret = cgmalloc(len);
  3047. if (ptr) {
  3048. sprintf(ret, "%s%s", ptr, s);
  3049. free(ptr);
  3050. } else
  3051. sprintf(ret, "%s", s);
  3052. return ret;
  3053. }
  3054. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  3055. * Including 0x00 at the end
  3056. * You must free the result yourself */
  3057. void *str_text(char *ptr)
  3058. {
  3059. unsigned char *uptr;
  3060. char *ret, *txt;
  3061. if (ptr == NULL) {
  3062. ret = strdup("(null)");
  3063. if (unlikely(!ret))
  3064. quithere(1, "Failed to malloc null");
  3065. }
  3066. uptr = (unsigned char *)ptr;
  3067. ret = txt = cgmalloc(strlen(ptr) * 4 + 5); // Guaranteed >= needed
  3068. do {
  3069. if (*uptr < ' ' || *uptr > '~') {
  3070. sprintf(txt, "0x%02x", *uptr);
  3071. txt += 4;
  3072. } else
  3073. *(txt++) = *uptr;
  3074. } while (*(uptr++));
  3075. *txt = '\0';
  3076. return ret;
  3077. }
  3078. void RenameThread(const char* name)
  3079. {
  3080. char buf[16];
  3081. snprintf(buf, sizeof(buf), "cg@%s", name);
  3082. #if defined(PR_SET_NAME)
  3083. // Only the first 15 characters are used (16 - NUL terminator)
  3084. prctl(PR_SET_NAME, buf, 0, 0, 0);
  3085. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  3086. pthread_set_name_np(pthread_self(), buf);
  3087. #elif defined(MAC_OSX)
  3088. pthread_setname_np(buf);
  3089. #else
  3090. // Prevent warnings
  3091. (void)buf;
  3092. #endif
  3093. }
  3094. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  3095. * that support them and for apple which does not. We use a single byte across
  3096. * a pipe to emulate semaphore behaviour there. */
  3097. #ifdef __APPLE__
  3098. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3099. {
  3100. int flags, fd, i;
  3101. if (pipe(cgsem->pipefd) == -1)
  3102. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  3103. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  3104. * execv on restart. */
  3105. for (i = 0; i < 2; i++) {
  3106. fd = cgsem->pipefd[i];
  3107. flags = fcntl(fd, F_GETFD, 0);
  3108. flags |= FD_CLOEXEC;
  3109. if (fcntl(fd, F_SETFD, flags) == -1)
  3110. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  3111. }
  3112. }
  3113. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3114. {
  3115. const char buf = 1;
  3116. int ret;
  3117. retry:
  3118. ret = write(cgsem->pipefd[1], &buf, 1);
  3119. if (unlikely(ret == 0))
  3120. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  3121. else if (unlikely(ret < 0 && interrupted))
  3122. goto retry;
  3123. }
  3124. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3125. {
  3126. char buf;
  3127. int ret;
  3128. retry:
  3129. ret = read(cgsem->pipefd[0], &buf, 1);
  3130. if (unlikely(ret == 0))
  3131. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  3132. else if (unlikely(ret < 0 && interrupted))
  3133. goto retry;
  3134. }
  3135. void cgsem_destroy(cgsem_t *cgsem)
  3136. {
  3137. close(cgsem->pipefd[1]);
  3138. close(cgsem->pipefd[0]);
  3139. }
  3140. /* This is similar to sem_timedwait but takes a millisecond value */
  3141. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  3142. {
  3143. struct timeval timeout;
  3144. int ret, fd;
  3145. fd_set rd;
  3146. char buf;
  3147. retry:
  3148. fd = cgsem->pipefd[0];
  3149. FD_ZERO(&rd);
  3150. FD_SET(fd, &rd);
  3151. ms_to_timeval(&timeout, ms);
  3152. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  3153. if (ret > 0) {
  3154. ret = read(fd, &buf, 1);
  3155. return 0;
  3156. }
  3157. if (likely(!ret))
  3158. return ETIMEDOUT;
  3159. if (interrupted())
  3160. goto retry;
  3161. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  3162. /* We don't reach here */
  3163. return 0;
  3164. }
  3165. /* Reset semaphore count back to zero */
  3166. void cgsem_reset(cgsem_t *cgsem)
  3167. {
  3168. int ret, fd;
  3169. fd_set rd;
  3170. char buf;
  3171. fd = cgsem->pipefd[0];
  3172. FD_ZERO(&rd);
  3173. FD_SET(fd, &rd);
  3174. do {
  3175. struct timeval timeout = {0, 0};
  3176. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  3177. if (ret > 0)
  3178. ret = read(fd, &buf, 1);
  3179. else if (unlikely(ret < 0 && interrupted()))
  3180. ret = 1;
  3181. } while (ret > 0);
  3182. }
  3183. #else
  3184. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3185. {
  3186. int ret;
  3187. if ((ret = sem_init(cgsem, 0, 0)))
  3188. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  3189. }
  3190. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3191. {
  3192. if (unlikely(sem_post(cgsem)))
  3193. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  3194. }
  3195. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3196. {
  3197. retry:
  3198. if (unlikely(sem_wait(cgsem))) {
  3199. if (interrupted())
  3200. goto retry;
  3201. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  3202. }
  3203. }
  3204. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  3205. {
  3206. struct timespec abs_timeout, tdiff;
  3207. int ret;
  3208. cgcond_time(&abs_timeout);
  3209. ms_to_timespec(&tdiff, ms);
  3210. timeraddspec(&abs_timeout, &tdiff);
  3211. retry:
  3212. ret = sem_timedwait(cgsem, &abs_timeout);
  3213. if (ret) {
  3214. if (likely(sock_timeout()))
  3215. return ETIMEDOUT;
  3216. if (interrupted())
  3217. goto retry;
  3218. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  3219. }
  3220. return 0;
  3221. }
  3222. void cgsem_reset(cgsem_t *cgsem)
  3223. {
  3224. int ret;
  3225. do {
  3226. ret = sem_trywait(cgsem);
  3227. if (unlikely(ret < 0 && interrupted()))
  3228. ret = 0;
  3229. } while (!ret);
  3230. }
  3231. void cgsem_destroy(cgsem_t *cgsem)
  3232. {
  3233. sem_destroy(cgsem);
  3234. }
  3235. #endif
  3236. /* Provide a completion_timeout helper function for unreliable functions that
  3237. * may die due to driver issues etc that time out if the function fails and
  3238. * can then reliably return. */
  3239. struct cg_completion {
  3240. cgsem_t cgsem;
  3241. void (*fn)(void *fnarg);
  3242. void *fnarg;
  3243. };
  3244. void *completion_thread(void *arg)
  3245. {
  3246. struct cg_completion *cgc = (struct cg_completion *)arg;
  3247. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3248. cgc->fn(cgc->fnarg);
  3249. cgsem_post(&cgc->cgsem);
  3250. return NULL;
  3251. }
  3252. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  3253. {
  3254. struct cg_completion *cgc;
  3255. pthread_t pthread;
  3256. bool ret = false;
  3257. cgc = cgmalloc(sizeof(struct cg_completion));
  3258. cgsem_init(&cgc->cgsem);
  3259. cgc->fn = fn;
  3260. cgc->fnarg = fnarg;
  3261. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  3262. ret = cgsem_mswait(&cgc->cgsem, timeout);
  3263. if (!ret) {
  3264. pthread_join(pthread, NULL);
  3265. free(cgc);
  3266. } else
  3267. pthread_cancel(pthread);
  3268. return !ret;
  3269. }
  3270. void _cg_memcpy(void *dest, const void *src, unsigned int n, const char *file, const char *func, const int line)
  3271. {
  3272. if (unlikely(n < 1 || n > (1ul << 31))) {
  3273. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from %s %s():%d",
  3274. n, file, func, line);
  3275. return;
  3276. }
  3277. if (unlikely(!dest)) {
  3278. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes to NULL from %s %s():%d",
  3279. n, file, func, line);
  3280. return;
  3281. }
  3282. if (unlikely(!src)) {
  3283. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from NULL from %s %s():%d",
  3284. n, file, func, line);
  3285. return;
  3286. }
  3287. memcpy(dest, src, n);
  3288. }