util.c 100 KB

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