util.c 82 KB

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