util.c 105 KB

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