util.c 102 KB

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