util.c 100 KB

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