util.c 87 KB

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