util.c 78 KB

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