util.c 91 KB

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