util.c 98 KB

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