util.c 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. * Copyright 2012 Giel van Schijndel
  6. * Copyright 2012 Gavin Andresen
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <ctype.h>
  19. #include <stdarg.h>
  20. #include <string.h>
  21. #include <pthread.h>
  22. #include <jansson.h>
  23. #include <curl/curl.h>
  24. #include <time.h>
  25. #include <errno.h>
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #ifdef HAVE_SYS_PRCTL_H
  29. # include <sys/prctl.h>
  30. #endif
  31. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  32. # include <pthread_np.h>
  33. #endif
  34. #ifndef WIN32
  35. #include <fcntl.h>
  36. # ifdef __linux
  37. # include <sys/prctl.h>
  38. # endif
  39. # include <sys/socket.h>
  40. # include <netinet/in.h>
  41. # include <netinet/tcp.h>
  42. # include <netdb.h>
  43. #else
  44. # include <windows.h>
  45. # include <winsock2.h>
  46. # include <mstcpip.h>
  47. # include <ws2tcpip.h>
  48. # include <mmsystem.h>
  49. #endif
  50. #include <utlist.h>
  51. #ifdef NEED_BFG_LOWL_VCOM
  52. #include "lowl-vcom.h"
  53. #endif
  54. #include "miner.h"
  55. #include "compat.h"
  56. #include "util.h"
  57. #define DEFAULT_SOCKWAIT 60
  58. bool successful_connect = false;
  59. struct timeval nettime;
  60. struct data_buffer {
  61. void *buf;
  62. size_t len;
  63. curl_socket_t *idlemarker;
  64. };
  65. struct upload_buffer {
  66. const void *buf;
  67. size_t len;
  68. };
  69. struct header_info {
  70. char *lp_path;
  71. int rolltime;
  72. char *reason;
  73. char *stratum_url;
  74. bool hadrolltime;
  75. bool canroll;
  76. bool hadexpire;
  77. };
  78. struct tq_ent {
  79. void *data;
  80. struct tq_ent *prev;
  81. struct tq_ent *next;
  82. };
  83. static void databuf_free(struct data_buffer *db)
  84. {
  85. if (!db)
  86. return;
  87. free(db->buf);
  88. #ifdef DEBUG_DATABUF
  89. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  90. #endif
  91. memset(db, 0, sizeof(*db));
  92. }
  93. // aka data_buffer_write
  94. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  95. void *user_data)
  96. {
  97. struct data_buffer *db = user_data;
  98. size_t oldlen, newlen;
  99. oldlen = db->len;
  100. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  101. return 0;
  102. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  103. nmemb = (SIZE_MAX - oldlen) / size;
  104. size_t len = size * nmemb;
  105. void *newmem;
  106. static const unsigned char zero = 0;
  107. if (db->idlemarker) {
  108. const unsigned char *cptr = ptr;
  109. for (size_t i = 0; i < len; ++i)
  110. if (!(isCspace(cptr[i]) || cptr[i] == '{')) {
  111. *db->idlemarker = CURL_SOCKET_BAD;
  112. db->idlemarker = NULL;
  113. break;
  114. }
  115. }
  116. newlen = oldlen + len;
  117. newmem = realloc(db->buf, newlen + 1);
  118. #ifdef DEBUG_DATABUF
  119. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  120. #endif
  121. if (!newmem)
  122. return 0;
  123. db->buf = newmem;
  124. db->len = newlen;
  125. memcpy(db->buf + oldlen, ptr, len);
  126. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  127. return nmemb;
  128. }
  129. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  130. void *user_data)
  131. {
  132. struct upload_buffer *ub = user_data;
  133. unsigned int len = size * nmemb;
  134. if (len > ub->len)
  135. len = ub->len;
  136. if (len) {
  137. memcpy(ptr, ub->buf, len);
  138. ub->buf += len;
  139. ub->len -= len;
  140. }
  141. return len;
  142. }
  143. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  144. {
  145. struct header_info *hi = user_data;
  146. size_t remlen, slen, ptrlen = size * nmemb;
  147. char *rem, *val = NULL, *key = NULL;
  148. void *tmp;
  149. val = calloc(1, ptrlen);
  150. key = calloc(1, ptrlen);
  151. if (!key || !val)
  152. goto out;
  153. tmp = memchr(ptr, ':', ptrlen);
  154. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  155. goto out;
  156. slen = tmp - ptr;
  157. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  158. goto out;
  159. memcpy(key, ptr, slen); /* store & nul term key */
  160. key[slen] = 0;
  161. rem = ptr + slen + 1; /* trim value's leading whitespace */
  162. remlen = ptrlen - slen - 1;
  163. while ((remlen > 0) && (isCspace(*rem))) {
  164. remlen--;
  165. rem++;
  166. }
  167. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  168. val[remlen] = 0;
  169. while ((*val) && (isCspace(val[strlen(val) - 1])))
  170. val[strlen(val) - 1] = 0;
  171. if (!*val) /* skip blank value */
  172. goto out;
  173. if (opt_protocol)
  174. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  175. if (!strcasecmp("X-Roll-Ntime", key)) {
  176. hi->hadrolltime = true;
  177. if (!strncasecmp("N", val, 1))
  178. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  179. else {
  180. hi->canroll = true;
  181. /* Check to see if expire= is supported and if not, set
  182. * the rolltime to the default scantime */
  183. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  184. sscanf(val + 7, "%d", &hi->rolltime);
  185. hi->hadexpire = true;
  186. } else
  187. hi->rolltime = opt_scantime;
  188. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  189. }
  190. }
  191. if (!strcasecmp("X-Long-Polling", key)) {
  192. hi->lp_path = val; /* steal memory reference */
  193. val = NULL;
  194. }
  195. if (!strcasecmp("X-Reject-Reason", key)) {
  196. hi->reason = val; /* steal memory reference */
  197. val = NULL;
  198. }
  199. if (!strcasecmp("X-Stratum", key)) {
  200. hi->stratum_url = val;
  201. val = NULL;
  202. }
  203. out:
  204. free(key);
  205. free(val);
  206. return ptrlen;
  207. }
  208. static int keep_sockalive(SOCKETTYPE fd)
  209. {
  210. const int tcp_one = 1;
  211. const int tcp_keepidle = 45;
  212. const int tcp_keepintvl = 30;
  213. int ret = 0;
  214. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one))))
  215. ret = 1;
  216. #ifndef WIN32
  217. int flags = fcntl(fd, F_GETFL, 0);
  218. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  219. #else
  220. u_long flags = 1;
  221. ioctlsocket(fd, FIONBIO, &flags);
  222. #endif
  223. if (!opt_delaynet)
  224. #ifndef __linux
  225. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  226. #else /* __linux */
  227. if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  228. #endif /* __linux */
  229. ret = 1;
  230. #ifdef __linux
  231. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one))))
  232. ret = 1;
  233. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  234. ret = 1;
  235. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  236. ret = 1;
  237. #endif /* __linux */
  238. #ifdef __APPLE_CC__
  239. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  240. ret = 1;
  241. #endif /* __APPLE_CC__ */
  242. #ifdef WIN32
  243. const int zero = 0;
  244. struct tcp_keepalive vals;
  245. vals.onoff = 1;
  246. vals.keepalivetime = tcp_keepidle * 1000;
  247. vals.keepaliveinterval = tcp_keepintvl * 1000;
  248. DWORD outputBytes;
  249. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  250. ret = 1;
  251. /* Windows happily submits indefinitely to the send buffer blissfully
  252. * unaware nothing is getting there without gracefully failing unless
  253. * we disable the send buffer */
  254. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  255. ret = 1;
  256. #endif /* WIN32 */
  257. return ret;
  258. }
  259. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  260. curlsocktype __maybe_unused purpose)
  261. {
  262. return keep_sockalive(fd);
  263. }
  264. static void last_nettime(struct timeval *last)
  265. {
  266. rd_lock(&netacc_lock);
  267. last->tv_sec = nettime.tv_sec;
  268. last->tv_usec = nettime.tv_usec;
  269. rd_unlock(&netacc_lock);
  270. }
  271. static void set_nettime(void)
  272. {
  273. wr_lock(&netacc_lock);
  274. cgtime(&nettime);
  275. wr_unlock(&netacc_lock);
  276. }
  277. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  278. char *data, size_t size,
  279. void *userdata)
  280. {
  281. struct pool *pool = (struct pool *)userdata;
  282. switch(type) {
  283. case CURLINFO_HEADER_IN:
  284. case CURLINFO_DATA_IN:
  285. case CURLINFO_SSL_DATA_IN:
  286. pool->cgminer_pool_stats.bytes_received += size;
  287. total_bytes_rcvd += size;
  288. pool->cgminer_pool_stats.net_bytes_received += size;
  289. break;
  290. case CURLINFO_HEADER_OUT:
  291. case CURLINFO_DATA_OUT:
  292. case CURLINFO_SSL_DATA_OUT:
  293. pool->cgminer_pool_stats.bytes_sent += size;
  294. total_bytes_sent += size;
  295. pool->cgminer_pool_stats.net_bytes_sent += size;
  296. break;
  297. case CURLINFO_TEXT:
  298. {
  299. if (!opt_protocol)
  300. break;
  301. // data is not null-terminated, so we need to copy and terminate it for applog
  302. char datacp[size + 1];
  303. memcpy(datacp, data, size);
  304. while (likely(size) && unlikely(isCspace(datacp[size-1])))
  305. --size;
  306. if (unlikely(!size))
  307. break;
  308. datacp[size] = '\0';
  309. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  310. break;
  311. }
  312. default:
  313. break;
  314. }
  315. return 0;
  316. }
  317. struct json_rpc_call_state {
  318. struct data_buffer all_data;
  319. struct header_info hi;
  320. void *priv;
  321. char curl_err_str[CURL_ERROR_SIZE];
  322. struct curl_slist *headers;
  323. struct upload_buffer upload_data;
  324. struct pool *pool;
  325. };
  326. void json_rpc_call_async(CURL *curl, const char *url,
  327. const char *userpass, const char *rpc_req,
  328. bool longpoll,
  329. struct pool *pool, bool share,
  330. void *priv)
  331. {
  332. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  333. *state = (struct json_rpc_call_state){
  334. .priv = priv,
  335. .pool = pool,
  336. };
  337. long timeout = longpoll ? (60 * 60) : 60;
  338. char len_hdr[64], user_agent_hdr[128];
  339. struct curl_slist *headers = NULL;
  340. if (longpoll)
  341. state->all_data.idlemarker = &pool->lp_socket;
  342. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  343. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  344. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  345. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  346. * to enable it */
  347. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  348. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  349. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  350. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  351. curl_easy_setopt(curl, CURLOPT_URL, url);
  352. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  353. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  354. /* Shares are staggered already and delays in submission can be costly
  355. * so do not delay them */
  356. if (!opt_delaynet || share)
  357. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  358. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  359. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  360. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  361. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  362. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  363. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  364. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  365. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  366. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  367. if (pool->rpc_proxy) {
  368. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  369. } else if (opt_socks_proxy) {
  370. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  371. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  372. }
  373. if (userpass) {
  374. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  375. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  376. }
  377. if (longpoll)
  378. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  379. curl_easy_setopt(curl, CURLOPT_POST, 1);
  380. if (opt_protocol)
  381. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  382. state->upload_data.buf = rpc_req;
  383. state->upload_data.len = strlen(rpc_req);
  384. sprintf(len_hdr, "Content-Length: %lu",
  385. (unsigned long) state->upload_data.len);
  386. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  387. headers = curl_slist_append(headers,
  388. "Content-type: application/json");
  389. headers = curl_slist_append(headers,
  390. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  391. if (longpoll)
  392. headers = curl_slist_append(headers,
  393. "X-Minimum-Wait: 0");
  394. if (likely(global_hashrate)) {
  395. char ghashrate[255];
  396. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  397. headers = curl_slist_append(headers, ghashrate);
  398. }
  399. headers = curl_slist_append(headers, len_hdr);
  400. headers = curl_slist_append(headers, user_agent_hdr);
  401. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  402. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  403. state->headers = headers;
  404. if (opt_delaynet) {
  405. /* Don't delay share submission, but still track the nettime */
  406. if (!share) {
  407. long long now_msecs, last_msecs;
  408. struct timeval now, last;
  409. cgtime(&now);
  410. last_nettime(&last);
  411. now_msecs = (long long)now.tv_sec * 1000;
  412. now_msecs += now.tv_usec / 1000;
  413. last_msecs = (long long)last.tv_sec * 1000;
  414. last_msecs += last.tv_usec / 1000;
  415. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  416. struct timespec rgtp;
  417. rgtp.tv_sec = 0;
  418. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  419. nanosleep(&rgtp, NULL);
  420. }
  421. }
  422. set_nettime();
  423. }
  424. }
  425. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  426. {
  427. struct json_rpc_call_state *state;
  428. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, (void*)&state) != CURLE_OK) {
  429. applog(LOG_ERR, "Failed to get private curl data");
  430. if (out_priv)
  431. *(void**)out_priv = NULL;
  432. goto err_out;
  433. }
  434. if (out_priv)
  435. *(void**)out_priv = state->priv;
  436. json_t *val, *err_val, *res_val;
  437. json_error_t err;
  438. struct pool *pool = state->pool;
  439. bool probing = probe && !pool->probed;
  440. if (rc) {
  441. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  442. goto err_out;
  443. }
  444. if (!state->all_data.buf) {
  445. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  446. goto err_out;
  447. }
  448. pool->cgminer_pool_stats.times_sent++;
  449. pool->cgminer_pool_stats.times_received++;
  450. if (probing) {
  451. pool->probed = true;
  452. /* If X-Long-Polling was found, activate long polling */
  453. if (state->hi.lp_path) {
  454. if (pool->hdr_path != NULL)
  455. free(pool->hdr_path);
  456. pool->hdr_path = state->hi.lp_path;
  457. } else
  458. pool->hdr_path = NULL;
  459. if (state->hi.stratum_url) {
  460. pool->stratum_url = state->hi.stratum_url;
  461. state->hi.stratum_url = NULL;
  462. }
  463. } else {
  464. if (state->hi.lp_path) {
  465. free(state->hi.lp_path);
  466. state->hi.lp_path = NULL;
  467. }
  468. if (state->hi.stratum_url) {
  469. free(state->hi.stratum_url);
  470. state->hi.stratum_url = NULL;
  471. }
  472. }
  473. if (pool->force_rollntime)
  474. {
  475. state->hi.canroll = true;
  476. state->hi.hadexpire = true;
  477. state->hi.rolltime = pool->force_rollntime;
  478. }
  479. if (rolltime)
  480. *rolltime = state->hi.rolltime;
  481. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  482. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  483. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  484. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  485. val = JSON_LOADS(state->all_data.buf, &err);
  486. if (!val) {
  487. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  488. if (opt_protocol)
  489. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  490. goto err_out;
  491. }
  492. if (opt_protocol) {
  493. char *s = json_dumps(val, JSON_INDENT(3));
  494. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  495. free(s);
  496. }
  497. /* JSON-RPC valid response returns a non-null 'result',
  498. * and a null 'error'.
  499. */
  500. res_val = json_object_get(val, "result");
  501. err_val = json_object_get(val, "error");
  502. if (!res_val ||(err_val && !json_is_null(err_val))) {
  503. char *s;
  504. if (err_val)
  505. s = json_dumps(err_val, JSON_INDENT(3));
  506. else
  507. s = strdup("(unknown reason)");
  508. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  509. free(s);
  510. json_decref(val);
  511. goto err_out;
  512. }
  513. if (state->hi.reason) {
  514. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  515. free(state->hi.reason);
  516. state->hi.reason = NULL;
  517. }
  518. successful_connect = true;
  519. databuf_free(&state->all_data);
  520. curl_slist_free_all(state->headers);
  521. curl_easy_reset(curl);
  522. free(state);
  523. return val;
  524. err_out:
  525. databuf_free(&state->all_data);
  526. curl_slist_free_all(state->headers);
  527. curl_easy_reset(curl);
  528. if (!successful_connect)
  529. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  530. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  531. free(state);
  532. return NULL;
  533. }
  534. json_t *json_rpc_call(CURL *curl, const char *url,
  535. const char *userpass, const char *rpc_req,
  536. bool probe, bool longpoll, int *rolltime,
  537. struct pool *pool, bool share)
  538. {
  539. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  540. int rc = curl_easy_perform(curl);
  541. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  542. }
  543. bool our_curl_supports_proxy_uris()
  544. {
  545. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  546. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  547. }
  548. // NOTE: This assumes reference URI is a root
  549. char *absolute_uri(char *uri, const char *ref)
  550. {
  551. if (strstr(uri, "://"))
  552. return strdup(uri);
  553. char *copy_start, *abs;
  554. bool need_slash = false;
  555. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  556. if (ref[strlen(ref) - 1] != '/')
  557. need_slash = true;
  558. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  559. if (!abs) {
  560. applog(LOG_ERR, "Malloc failure in absolute_uri");
  561. return NULL;
  562. }
  563. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  564. return abs;
  565. }
  566. static const char _hexchars[0x10] = "0123456789abcdef";
  567. void bin2hex(char *out, const void *in, size_t len)
  568. {
  569. const unsigned char *p = in;
  570. while (len--)
  571. {
  572. (out++)[0] = _hexchars[p[0] >> 4];
  573. (out++)[0] = _hexchars[p[0] & 0xf];
  574. ++p;
  575. }
  576. out[0] = '\0';
  577. }
  578. static inline
  579. int _hex2bin_char(const char c)
  580. {
  581. if (c >= '0' && c <= '9')
  582. return c - '0';
  583. if (c >= 'a' && c <= 'f')
  584. return (c - 'a') + 10;
  585. if (c >= 'A' && c <= 'F')
  586. return (c - 'A') + 10;
  587. return -1;
  588. }
  589. /* Does the reverse of bin2hex but does not allocate any ram */
  590. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  591. {
  592. int n, o;
  593. while (len--)
  594. {
  595. n = _hex2bin_char((hexstr++)[0]);
  596. if (unlikely(n == -1))
  597. {
  598. badchar:
  599. if (!hexstr[-1])
  600. applog(LOG_ERR, "hex2bin: str truncated");
  601. else
  602. applog(LOG_ERR, "hex2bin: invalid character 0x%02x", (int)hexstr[-1]);
  603. return false;
  604. }
  605. o = _hex2bin_char((hexstr++)[0]);
  606. if (unlikely(o == -1))
  607. goto badchar;
  608. (p++)[0] = (n << 4) | o;
  609. }
  610. return likely(!hexstr[0]);
  611. }
  612. size_t ucs2_to_utf8(char * const out, const uint16_t * const in, const size_t sz)
  613. {
  614. uint8_t *p = (void*)out;
  615. for (int i = 0; i < sz; ++i)
  616. {
  617. const uint16_t c = in[i];
  618. if (c < 0x80)
  619. p++[0] = c;
  620. else
  621. {
  622. if (c < 0x800)
  623. p++[0] = 0xc0 | (c >> 6);
  624. else
  625. {
  626. p++[0] = 0xe0 | (c >> 12);
  627. p++[0] = 0x80 | ((c >> 6) & 0x3f);
  628. }
  629. p++[0] = 0x80 | (c & 0x3f);
  630. }
  631. }
  632. return p - (uint8_t*)(void*)out;
  633. }
  634. char *ucs2_to_utf8_dup(uint16_t * const in, size_t sz)
  635. {
  636. char * const out = malloc((sz * 4) + 1);
  637. sz = ucs2_to_utf8(out, in, sz);
  638. out[sz] = '\0';
  639. return out;
  640. }
  641. void hash_data(unsigned char *out_hash, const unsigned char *data)
  642. {
  643. unsigned char blkheader[80];
  644. // data is past the first SHA256 step (padding and interpreting as big endian on a little endian platform), so we need to flip each 32-bit chunk around to get the original input block header
  645. swap32yes(blkheader, data, 80 / 4);
  646. // double-SHA256 to get the block hash
  647. gen_hash(blkheader, out_hash, 80);
  648. }
  649. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  650. void real_block_target(unsigned char *target, const unsigned char *data)
  651. {
  652. uint8_t targetshift;
  653. if (unlikely(data[72] < 3 || data[72] > 0x20))
  654. {
  655. // Invalid (out of bounds) target
  656. memset(target, 0xff, 32);
  657. return;
  658. }
  659. targetshift = data[72] - 3;
  660. memset(target, 0, targetshift);
  661. target[targetshift++] = data[75];
  662. target[targetshift++] = data[74];
  663. target[targetshift++] = data[73];
  664. memset(&target[targetshift], 0, 0x20 - targetshift);
  665. }
  666. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  667. {
  668. const uint32_t *h32 = (uint32_t*)&hash[0];
  669. const uint32_t *t32 = (uint32_t*)&target[0];
  670. for (int i = 7; i >= 0; --i) {
  671. uint32_t h32i = le32toh(h32[i]);
  672. uint32_t t32i = le32toh(t32[i]);
  673. if (h32i > t32i)
  674. return false;
  675. if (h32i < t32i)
  676. return true;
  677. }
  678. return true;
  679. }
  680. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  681. {
  682. bool rc;
  683. rc = hash_target_check(hash, target);
  684. if (opt_debug) {
  685. unsigned char hash_swap[32], target_swap[32];
  686. char hash_str[65];
  687. char target_str[65];
  688. for (int i = 0; i < 32; ++i) {
  689. hash_swap[i] = hash[31-i];
  690. target_swap[i] = target[31-i];
  691. }
  692. bin2hex(hash_str, hash_swap, 32);
  693. bin2hex(target_str, target_swap, 32);
  694. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  695. hash_str,
  696. target_str,
  697. rc ? "YES (hash <= target)" :
  698. "no (false positive; hash > target)");
  699. }
  700. return rc;
  701. }
  702. // This operates on a native-endian SHA256 state
  703. // In other words, on little endian platforms, every 4 bytes are in reverse order
  704. bool fulltest(const unsigned char *hash, const unsigned char *target)
  705. {
  706. unsigned char hash2[32];
  707. swap32tobe(hash2, hash, 32 / 4);
  708. return hash_target_check_v(hash2, target);
  709. }
  710. struct thread_q *tq_new(void)
  711. {
  712. struct thread_q *tq;
  713. tq = calloc(1, sizeof(*tq));
  714. if (!tq)
  715. return NULL;
  716. pthread_mutex_init(&tq->mutex, NULL);
  717. pthread_cond_init(&tq->cond, NULL);
  718. return tq;
  719. }
  720. void tq_free(struct thread_q *tq)
  721. {
  722. struct tq_ent *ent, *iter;
  723. if (!tq)
  724. return;
  725. DL_FOREACH_SAFE(tq->q, ent, iter) {
  726. DL_DELETE(tq->q, ent);
  727. free(ent);
  728. }
  729. pthread_cond_destroy(&tq->cond);
  730. pthread_mutex_destroy(&tq->mutex);
  731. memset(tq, 0, sizeof(*tq)); /* poison */
  732. free(tq);
  733. }
  734. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  735. {
  736. mutex_lock(&tq->mutex);
  737. tq->frozen = frozen;
  738. pthread_cond_signal(&tq->cond);
  739. mutex_unlock(&tq->mutex);
  740. }
  741. void tq_freeze(struct thread_q *tq)
  742. {
  743. tq_freezethaw(tq, true);
  744. }
  745. void tq_thaw(struct thread_q *tq)
  746. {
  747. tq_freezethaw(tq, false);
  748. }
  749. bool tq_push(struct thread_q *tq, void *data)
  750. {
  751. struct tq_ent *ent;
  752. bool rc = true;
  753. ent = calloc(1, sizeof(*ent));
  754. if (!ent)
  755. return false;
  756. ent->data = data;
  757. mutex_lock(&tq->mutex);
  758. if (!tq->frozen) {
  759. DL_APPEND(tq->q, ent);
  760. } else {
  761. free(ent);
  762. rc = false;
  763. }
  764. pthread_cond_signal(&tq->cond);
  765. mutex_unlock(&tq->mutex);
  766. return rc;
  767. }
  768. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  769. {
  770. struct tq_ent *ent;
  771. void *rval = NULL;
  772. int rc;
  773. mutex_lock(&tq->mutex);
  774. if (tq->q)
  775. goto pop;
  776. if (abstime)
  777. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  778. else
  779. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  780. if (rc)
  781. goto out;
  782. if (!tq->q)
  783. goto out;
  784. pop:
  785. ent = tq->q;
  786. rval = ent->data;
  787. DL_DELETE(tq->q, ent);
  788. free(ent);
  789. out:
  790. mutex_unlock(&tq->mutex);
  791. return rval;
  792. }
  793. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  794. {
  795. int rv = pthread_create(&thr->pth, attr, start, arg);
  796. if (likely(!rv))
  797. thr->has_pth = true;
  798. return rv;
  799. }
  800. void thr_info_freeze(struct thr_info *thr)
  801. {
  802. struct tq_ent *ent, *iter;
  803. struct thread_q *tq;
  804. if (!thr)
  805. return;
  806. tq = thr->q;
  807. if (!tq)
  808. return;
  809. mutex_lock(&tq->mutex);
  810. tq->frozen = true;
  811. DL_FOREACH_SAFE(tq->q, ent, iter) {
  812. DL_DELETE(tq->q, ent);
  813. free(ent);
  814. }
  815. mutex_unlock(&tq->mutex);
  816. }
  817. void thr_info_cancel(struct thr_info *thr)
  818. {
  819. if (!thr)
  820. return;
  821. if (thr->has_pth) {
  822. pthread_cancel(thr->pth);
  823. thr->has_pth = false;
  824. }
  825. }
  826. #ifndef HAVE_PTHREAD_CANCEL
  827. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  828. enum pthread_cancel_workaround_mode {
  829. PCWM_DEFAULT = 0,
  830. PCWM_TERMINATE = 1,
  831. PCWM_ASYNC = 2,
  832. PCWM_DISABLED = 4,
  833. PCWM_CANCELLED = 8,
  834. };
  835. static pthread_key_t key_pcwm;
  836. struct sigaction pcwm_orig_term_handler;
  837. static
  838. void do_pthread_cancel_exit(int flags)
  839. {
  840. if (!(flags & PCWM_ASYNC))
  841. // NOTE: Logging disables cancel while mutex held, so this is safe
  842. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  843. pthread_exit(PTHREAD_CANCELED);
  844. }
  845. static
  846. void sighandler_pthread_cancel(int sig)
  847. {
  848. int flags = (int)pthread_getspecific(key_pcwm);
  849. if (flags & PCWM_TERMINATE) // Main thread
  850. {
  851. // Restore original handler and call it
  852. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  853. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  854. raise(SIGTERM);
  855. quit(1, "pthread_cancel workaround: Original handler returned");
  856. }
  857. if (flags & PCWM_CANCELLED) // Already pending cancel
  858. return;
  859. if (flags & PCWM_DISABLED)
  860. {
  861. flags |= PCWM_CANCELLED;
  862. if (pthread_setspecific(key_pcwm, (void*)flags))
  863. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  864. return;
  865. }
  866. do_pthread_cancel_exit(flags);
  867. }
  868. void pthread_testcancel(void)
  869. {
  870. int flags = (int)pthread_getspecific(key_pcwm);
  871. if (flags & PCWM_CANCELLED && !(flags & PCWM_DISABLED))
  872. do_pthread_cancel_exit(flags);
  873. }
  874. int pthread_setcancelstate(int state, int *oldstate)
  875. {
  876. int flags = (int)pthread_getspecific(key_pcwm);
  877. if (oldstate)
  878. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  879. if (state == PTHREAD_CANCEL_DISABLE)
  880. flags |= PCWM_DISABLED;
  881. else
  882. {
  883. if (flags & PCWM_CANCELLED)
  884. do_pthread_cancel_exit(flags);
  885. flags &= ~PCWM_DISABLED;
  886. }
  887. if (pthread_setspecific(key_pcwm, (void*)flags))
  888. return -1;
  889. return 0;
  890. }
  891. int pthread_setcanceltype(int type, int *oldtype)
  892. {
  893. int flags = (int)pthread_getspecific(key_pcwm);
  894. if (oldtype)
  895. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  896. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  897. flags |= PCWM_ASYNC;
  898. else
  899. flags &= ~PCWM_ASYNC;
  900. if (pthread_setspecific(key_pcwm, (void*)flags))
  901. return -1;
  902. return 0;
  903. }
  904. void setup_pthread_cancel_workaround()
  905. {
  906. if (pthread_key_create(&key_pcwm, NULL))
  907. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  908. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  909. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  910. struct sigaction new_sigact = {
  911. .sa_handler = sighandler_pthread_cancel,
  912. };
  913. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  914. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  915. }
  916. #endif
  917. static void _now_gettimeofday(struct timeval *);
  918. static void _cgsleep_us_r_nanosleep(cgtimer_t *, int64_t);
  919. #ifdef HAVE_POOR_GETTIMEOFDAY
  920. static struct timeval tv_timeofday_offset;
  921. static struct timeval _tv_timeofday_lastchecked;
  922. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  923. static
  924. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  925. {
  926. struct timeval actual, delta;
  927. timeradd(expected, &tv_timeofday_offset, expected);
  928. _now_gettimeofday(&actual);
  929. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  930. // Within reason - no change necessary
  931. return;
  932. timersub(&actual, expected, &delta);
  933. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  934. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  935. *expected = actual;
  936. }
  937. void bfg_gettimeofday(struct timeval *out)
  938. {
  939. char buf[64] = "";
  940. timer_set_now(out);
  941. mutex_lock(&_tv_timeofday_mutex);
  942. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  943. bfg_calibrate_timeofday(out, buf);
  944. else
  945. timeradd(out, &tv_timeofday_offset, out);
  946. mutex_unlock(&_tv_timeofday_mutex);
  947. if (unlikely(buf[0]))
  948. applog(LOG_WARNING, "%s", buf);
  949. }
  950. #endif
  951. #ifdef WIN32
  952. static LARGE_INTEGER _perffreq;
  953. static
  954. void _now_queryperformancecounter(struct timeval *tv)
  955. {
  956. LARGE_INTEGER now;
  957. if (unlikely(!QueryPerformanceCounter(&now)))
  958. quit(1, "QueryPerformanceCounter failed");
  959. *tv = (struct timeval){
  960. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  961. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  962. };
  963. }
  964. #endif
  965. static void bfg_init_time();
  966. static
  967. void _now_is_not_set(__maybe_unused struct timeval *tv)
  968. {
  969. bfg_init_time();
  970. timer_set_now(tv);
  971. }
  972. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  973. void (*cgsleep_us_r)(cgtimer_t *, int64_t) = _cgsleep_us_r_nanosleep;
  974. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  975. static clockid_t bfg_timer_clk;
  976. static
  977. void _now_clock_gettime(struct timeval *tv)
  978. {
  979. struct timespec ts;
  980. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  981. quit(1, "clock_gettime failed");
  982. *tv = (struct timeval){
  983. .tv_sec = ts.tv_sec,
  984. .tv_usec = ts.tv_nsec / 1000,
  985. };
  986. }
  987. #ifdef HAVE_CLOCK_NANOSLEEP
  988. static
  989. void _cgsleep_us_r_monotonic(cgtimer_t *tv_start, int64_t us)
  990. {
  991. struct timeval tv_end[1];
  992. struct timespec ts_end[1];
  993. int ret;
  994. timer_set_delay(tv_end, tv_start, us);
  995. timeval_to_spec(ts_end, tv_end);
  996. do {
  997. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  998. } while (ret == EINTR);
  999. }
  1000. #endif
  1001. static
  1002. bool _bfg_try_clock_gettime(clockid_t clk)
  1003. {
  1004. struct timespec ts;
  1005. if (clock_gettime(clk, &ts))
  1006. return false;
  1007. bfg_timer_clk = clk;
  1008. timer_set_now = _now_clock_gettime;
  1009. return true;
  1010. }
  1011. #endif
  1012. static
  1013. void bfg_init_time()
  1014. {
  1015. if (timer_set_now != _now_is_not_set)
  1016. return;
  1017. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1018. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1019. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1020. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1021. else
  1022. #endif
  1023. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1024. {
  1025. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1026. #ifdef HAVE_CLOCK_NANOSLEEP
  1027. cgsleep_us_r = _cgsleep_us_r_monotonic;
  1028. #endif
  1029. }
  1030. else
  1031. #endif
  1032. #ifdef WIN32
  1033. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1034. {
  1035. timer_set_now = _now_queryperformancecounter;
  1036. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1037. }
  1038. else
  1039. #endif
  1040. {
  1041. timer_set_now = _now_gettimeofday;
  1042. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1043. }
  1044. #ifdef HAVE_POOR_GETTIMEOFDAY
  1045. char buf[64] = "";
  1046. struct timeval tv;
  1047. timer_set_now(&tv);
  1048. bfg_calibrate_timeofday(&tv, buf);
  1049. applog(LOG_DEBUG, "%s", buf);
  1050. #endif
  1051. }
  1052. void subtime(struct timeval *a, struct timeval *b)
  1053. {
  1054. timersub(a, b, b);
  1055. }
  1056. void addtime(struct timeval *a, struct timeval *b)
  1057. {
  1058. timeradd(a, b, b);
  1059. }
  1060. bool time_more(struct timeval *a, struct timeval *b)
  1061. {
  1062. return timercmp(a, b, >);
  1063. }
  1064. bool time_less(struct timeval *a, struct timeval *b)
  1065. {
  1066. return timercmp(a, b, <);
  1067. }
  1068. void copy_time(struct timeval *dest, const struct timeval *src)
  1069. {
  1070. memcpy(dest, src, sizeof(struct timeval));
  1071. }
  1072. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  1073. {
  1074. val->tv_sec = spec->tv_sec;
  1075. val->tv_usec = spec->tv_nsec / 1000;
  1076. }
  1077. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  1078. {
  1079. spec->tv_sec = val->tv_sec;
  1080. spec->tv_nsec = val->tv_usec * 1000;
  1081. }
  1082. void us_to_timeval(struct timeval *val, int64_t us)
  1083. {
  1084. lldiv_t tvdiv = lldiv(us, 1000000);
  1085. val->tv_sec = tvdiv.quot;
  1086. val->tv_usec = tvdiv.rem;
  1087. }
  1088. void us_to_timespec(struct timespec *spec, int64_t us)
  1089. {
  1090. lldiv_t tvdiv = lldiv(us, 1000000);
  1091. spec->tv_sec = tvdiv.quot;
  1092. spec->tv_nsec = tvdiv.rem * 1000;
  1093. }
  1094. void ms_to_timespec(struct timespec *spec, int64_t ms)
  1095. {
  1096. lldiv_t tvdiv = lldiv(ms, 1000);
  1097. spec->tv_sec = tvdiv.quot;
  1098. spec->tv_nsec = tvdiv.rem * 1000000;
  1099. }
  1100. void timeraddspec(struct timespec *a, const struct timespec *b)
  1101. {
  1102. a->tv_sec += b->tv_sec;
  1103. a->tv_nsec += b->tv_nsec;
  1104. if (a->tv_nsec >= 1000000000) {
  1105. a->tv_nsec -= 1000000000;
  1106. a->tv_sec++;
  1107. }
  1108. }
  1109. #ifndef WIN32
  1110. static
  1111. void _now_gettimeofday(struct timeval *tv)
  1112. {
  1113. gettimeofday(tv, NULL);
  1114. }
  1115. #else
  1116. /* Windows start time is since 1601 lol so convert it to unix epoch 1970. */
  1117. #define EPOCHFILETIME (116444736000000000LL)
  1118. void _now_gettimeofday(struct timeval *tv)
  1119. {
  1120. FILETIME ft;
  1121. LARGE_INTEGER li;
  1122. GetSystemTimeAsFileTime(&ft);
  1123. li.LowPart = ft.dwLowDateTime;
  1124. li.HighPart = ft.dwHighDateTime;
  1125. li.QuadPart -= EPOCHFILETIME;
  1126. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1127. tv->tv_sec = li.QuadPart / 10000000;
  1128. tv->tv_usec = li.QuadPart % 10000000;
  1129. }
  1130. #endif
  1131. void cgsleep_ms_r(cgtimer_t *tv_start, int ms)
  1132. {
  1133. cgsleep_us_r(tv_start, ((int64_t)ms) * 1000);
  1134. }
  1135. static
  1136. void _cgsleep_us_r_nanosleep(cgtimer_t *tv_start, int64_t us)
  1137. {
  1138. struct timeval tv_timer[1], tv[1];
  1139. struct timespec ts[1];
  1140. timer_set_delay(tv_timer, tv_start, us);
  1141. while (true)
  1142. {
  1143. timer_set_now(tv);
  1144. if (!timercmp(tv_timer, tv, >))
  1145. return;
  1146. timersub(tv_timer, tv, tv);
  1147. timeval_to_spec(ts, tv);
  1148. nanosleep(ts, NULL);
  1149. }
  1150. }
  1151. void cgsleep_ms(int ms)
  1152. {
  1153. cgtimer_t ts_start;
  1154. cgsleep_prepare_r(&ts_start);
  1155. cgsleep_ms_r(&ts_start, ms);
  1156. }
  1157. void cgsleep_us(int64_t us)
  1158. {
  1159. cgtimer_t ts_start;
  1160. cgsleep_prepare_r(&ts_start);
  1161. cgsleep_us_r(&ts_start, us);
  1162. }
  1163. /* Returns the microseconds difference between end and start times as a double */
  1164. double us_tdiff(struct timeval *end, struct timeval *start)
  1165. {
  1166. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1167. }
  1168. /* Returns the seconds difference between end and start times as a double */
  1169. double tdiff(struct timeval *end, struct timeval *start)
  1170. {
  1171. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1172. }
  1173. int utf8_len(const uint8_t b)
  1174. {
  1175. if (!(b & 0x80))
  1176. return 1;
  1177. if (!(b & 0x20))
  1178. return 2;
  1179. else
  1180. if (!(b & 0x10))
  1181. return 3;
  1182. else
  1183. return 4;
  1184. }
  1185. int32_t utf8_decode(const void *b, int *out_len)
  1186. {
  1187. int32_t w;
  1188. const unsigned char *s = b;
  1189. *out_len = utf8_len(s[0]);
  1190. if (*out_len == 1)
  1191. // ASCII
  1192. return s[0];
  1193. #ifdef STRICT_UTF8
  1194. if (unlikely(!(s[0] & 0x40)))
  1195. goto invalid;
  1196. if (unlikely(s[0] & 0x38 == 0x38))
  1197. goto invalid;
  1198. #endif
  1199. w = s[0] & ((2 << (6 - *out_len)) - 1);
  1200. for (int i = 1; i < *out_len; ++i)
  1201. {
  1202. #ifdef STRICT_UTF8
  1203. if (unlikely((s[i] & 0xc0) != 0x80))
  1204. goto invalid;
  1205. #endif
  1206. w = (w << 6) | (s[i] & 0x3f);
  1207. }
  1208. #if defined(STRICT_UTF8)
  1209. if (unlikely(w > 0x10FFFF))
  1210. goto invalid;
  1211. // FIXME: UTF-8 requires smallest possible encoding; check it
  1212. #endif
  1213. return w;
  1214. #ifdef STRICT_UTF8
  1215. invalid:
  1216. *out_len = 1;
  1217. return REPLACEMENT_CHAR;
  1218. #endif
  1219. }
  1220. size_t utf8_strlen(const void * const b)
  1221. {
  1222. const uint8_t *s = b;
  1223. size_t c = 0;
  1224. int clen, i;
  1225. while (s[0])
  1226. {
  1227. clen = utf8_len(s[0]);
  1228. for (i = 0; i < clen; ++i)
  1229. if (!s[i])
  1230. clen = 1;
  1231. ++c;
  1232. s += clen;
  1233. }
  1234. return c;
  1235. }
  1236. static
  1237. void _utf8_test(const char *s, const wchar_t expected, int expectedlen)
  1238. {
  1239. int len;
  1240. wchar_t r;
  1241. if (expected != REPLACEMENT_CHAR)
  1242. {
  1243. len = utf8_len(((uint8_t*)s)[0]);
  1244. if (len != expectedlen)
  1245. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_len=>%d", (unsigned long)expected, expectedlen, len);
  1246. len = utf8_strlen(s);
  1247. if (len != (s[0] ? 1 : 0))
  1248. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got utf8_strlen=>%d", (unsigned long)expected, expectedlen, len);
  1249. len = -1;
  1250. }
  1251. r = utf8_decode(s, &len);
  1252. if (unlikely(r != expected || expectedlen != len))
  1253. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got U+%06lX (len %d)", (unsigned long)expected, expectedlen, (unsigned long)r, len);
  1254. }
  1255. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1256. void utf8_test()
  1257. {
  1258. _utf8_test("", 0, 1);
  1259. _utf8_test("\1", 1, 1);
  1260. _utf8_test("\x7f", 0x7f, 1);
  1261. #if WCHAR_MAX >= 0x80
  1262. _utf8_test("\xc2\x80", 0x80, 2);
  1263. #if WCHAR_MAX >= 0xff
  1264. _utf8_test("\xc3\xbf", 0xff, 2);
  1265. #if WCHAR_MAX >= 0x7ff
  1266. _utf8_test("\xdf\xbf", 0x7ff, 2);
  1267. #if WCHAR_MAX >= 0x800
  1268. _utf8_test("\xe0\xa0\x80", 0x800, 3);
  1269. #if WCHAR_MAX >= 0xffff
  1270. _utf8_test("\xef\xbf\xbf", 0xffff, 3);
  1271. #if WCHAR_MAX >= 0x10000
  1272. _utf8_test("\xf0\x90\x80\x80", 0x10000, 4);
  1273. #if WCHAR_MAX >= 0x10ffff
  1274. _utf8_test("\xf4\x8f\xbf\xbf", 0x10ffff, 4);
  1275. #endif
  1276. #endif
  1277. #endif
  1278. #endif
  1279. #endif
  1280. #endif
  1281. #endif
  1282. #ifdef STRICT_UTF8
  1283. _utf8_test("\x80", REPLACEMENT_CHAR, 1);
  1284. _utf8_test("\xbf", REPLACEMENT_CHAR, 1);
  1285. _utf8_test("\xfe", REPLACEMENT_CHAR, 1);
  1286. _utf8_test("\xff", REPLACEMENT_CHAR, 1);
  1287. #endif
  1288. }
  1289. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1290. {
  1291. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1292. char url_address[256], port[6];
  1293. int url_len, port_len = 0;
  1294. url_begin = strstr(url, "//");
  1295. if (!url_begin)
  1296. url_begin = url;
  1297. else
  1298. url_begin += 2;
  1299. /* Look for numeric ipv6 entries */
  1300. ipv6_begin = strstr(url_begin, "[");
  1301. ipv6_end = strstr(url_begin, "]");
  1302. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1303. url_end = strstr(ipv6_end, ":");
  1304. else
  1305. url_end = strstr(url_begin, ":");
  1306. if (url_end) {
  1307. url_len = url_end - url_begin;
  1308. port_len = strlen(url_begin) - url_len - 1;
  1309. if (port_len < 1)
  1310. return false;
  1311. port_start = url_end + 1;
  1312. } else
  1313. url_len = strlen(url_begin);
  1314. if (url_len < 1)
  1315. return false;
  1316. sprintf(url_address, "%.*s", url_len, url_begin);
  1317. if (port_len) {
  1318. char *slash;
  1319. snprintf(port, 6, "%.*s", port_len, port_start);
  1320. slash = strchr(port, '/');
  1321. if (slash)
  1322. *slash = '\0';
  1323. } else
  1324. strcpy(port, "80");
  1325. free(*sockaddr_port);
  1326. *sockaddr_port = strdup(port);
  1327. free(*sockaddr_url);
  1328. *sockaddr_url = strdup(url_address);
  1329. return true;
  1330. }
  1331. enum send_ret {
  1332. SEND_OK,
  1333. SEND_SELECTFAIL,
  1334. SEND_SENDFAIL,
  1335. SEND_INACTIVE
  1336. };
  1337. /* Send a single command across a socket, appending \n to it. This should all
  1338. * be done under stratum lock except when first establishing the socket */
  1339. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1340. {
  1341. SOCKETTYPE sock = pool->sock;
  1342. ssize_t ssent = 0;
  1343. strcat(s, "\n");
  1344. len++;
  1345. while (len > 0 ) {
  1346. struct timeval timeout = {1, 0};
  1347. ssize_t sent;
  1348. fd_set wd;
  1349. retry:
  1350. FD_ZERO(&wd);
  1351. FD_SET(sock, &wd);
  1352. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1353. if (interrupted())
  1354. goto retry;
  1355. return SEND_SELECTFAIL;
  1356. }
  1357. #ifdef __APPLE__
  1358. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1359. #elif WIN32
  1360. sent = send(pool->sock, s + ssent, len, 0);
  1361. #else
  1362. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1363. #endif
  1364. if (sent < 0) {
  1365. if (!sock_blocks())
  1366. return SEND_SENDFAIL;
  1367. sent = 0;
  1368. }
  1369. ssent += sent;
  1370. len -= sent;
  1371. }
  1372. pool->cgminer_pool_stats.times_sent++;
  1373. pool->cgminer_pool_stats.bytes_sent += ssent;
  1374. total_bytes_sent += ssent;
  1375. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1376. return SEND_OK;
  1377. }
  1378. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1379. {
  1380. enum send_ret ret = SEND_INACTIVE;
  1381. if (opt_protocol)
  1382. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1383. mutex_lock(&pool->stratum_lock);
  1384. if (pool->stratum_active || force)
  1385. ret = __stratum_send(pool, s, len);
  1386. mutex_unlock(&pool->stratum_lock);
  1387. /* This is to avoid doing applog under stratum_lock */
  1388. switch (ret) {
  1389. default:
  1390. case SEND_OK:
  1391. break;
  1392. case SEND_SELECTFAIL:
  1393. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1394. suspend_stratum(pool);
  1395. break;
  1396. case SEND_SENDFAIL:
  1397. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1398. suspend_stratum(pool);
  1399. break;
  1400. case SEND_INACTIVE:
  1401. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1402. break;
  1403. }
  1404. return (ret == SEND_OK);
  1405. }
  1406. static bool socket_full(struct pool *pool, int wait)
  1407. {
  1408. SOCKETTYPE sock = pool->sock;
  1409. struct timeval timeout;
  1410. fd_set rd;
  1411. if (sock == INVSOCK)
  1412. return true;
  1413. if (unlikely(wait < 0))
  1414. wait = 0;
  1415. FD_ZERO(&rd);
  1416. FD_SET(sock, &rd);
  1417. timeout.tv_usec = 0;
  1418. timeout.tv_sec = wait;
  1419. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1420. return true;
  1421. return false;
  1422. }
  1423. /* Check to see if Santa's been good to you */
  1424. bool sock_full(struct pool *pool)
  1425. {
  1426. if (strlen(pool->sockbuf))
  1427. return true;
  1428. return (socket_full(pool, 0));
  1429. }
  1430. static void clear_sockbuf(struct pool *pool)
  1431. {
  1432. strcpy(pool->sockbuf, "");
  1433. }
  1434. static void clear_sock(struct pool *pool)
  1435. {
  1436. ssize_t n;
  1437. mutex_lock(&pool->stratum_lock);
  1438. do {
  1439. if (pool->sock)
  1440. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1441. else
  1442. n = 0;
  1443. } while (n > 0);
  1444. mutex_unlock(&pool->stratum_lock);
  1445. clear_sockbuf(pool);
  1446. }
  1447. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1448. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1449. * and zeroing the new memory */
  1450. static void recalloc_sock(struct pool *pool, size_t len)
  1451. {
  1452. size_t old, new;
  1453. old = strlen(pool->sockbuf);
  1454. new = old + len + 1;
  1455. if (new < pool->sockbuf_size)
  1456. return;
  1457. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1458. // Avoid potentially recursive locking
  1459. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1460. pool->sockbuf = realloc(pool->sockbuf, new);
  1461. if (!pool->sockbuf)
  1462. quithere(1, "Failed to realloc pool sockbuf");
  1463. memset(pool->sockbuf + old, 0, new - old);
  1464. pool->sockbuf_size = new;
  1465. }
  1466. /* Peeks at a socket to find the first end of line and then reads just that
  1467. * from the socket and returns that as a malloced char */
  1468. char *recv_line(struct pool *pool)
  1469. {
  1470. char *tok, *sret = NULL;
  1471. ssize_t len, buflen;
  1472. int waited = 0;
  1473. if (!strstr(pool->sockbuf, "\n")) {
  1474. struct timeval rstart, now;
  1475. cgtime(&rstart);
  1476. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1477. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1478. goto out;
  1479. }
  1480. do {
  1481. char s[RBUFSIZE];
  1482. size_t slen;
  1483. ssize_t n;
  1484. memset(s, 0, RBUFSIZE);
  1485. n = recv(pool->sock, s, RECVSIZE, 0);
  1486. if (!n) {
  1487. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1488. suspend_stratum(pool);
  1489. break;
  1490. }
  1491. cgtime(&now);
  1492. waited = tdiff(&now, &rstart);
  1493. if (n < 0) {
  1494. //Save errno from being overweitten bei socket_ commands
  1495. int socket_recv_errno;
  1496. socket_recv_errno = SOCKERR;
  1497. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1498. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %s", bfg_strerror(socket_recv_errno, BST_SOCKET));
  1499. suspend_stratum(pool);
  1500. break;
  1501. }
  1502. } else {
  1503. slen = strlen(s);
  1504. recalloc_sock(pool, slen);
  1505. strcat(pool->sockbuf, s);
  1506. }
  1507. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1508. }
  1509. buflen = strlen(pool->sockbuf);
  1510. tok = strtok(pool->sockbuf, "\n");
  1511. if (!tok) {
  1512. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1513. goto out;
  1514. }
  1515. sret = strdup(tok);
  1516. len = strlen(sret);
  1517. /* Copy what's left in the buffer after the \n, including the
  1518. * terminating \0 */
  1519. if (buflen > len + 1)
  1520. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1521. else
  1522. strcpy(pool->sockbuf, "");
  1523. pool->cgminer_pool_stats.times_received++;
  1524. pool->cgminer_pool_stats.bytes_received += len;
  1525. total_bytes_rcvd += len;
  1526. pool->cgminer_pool_stats.net_bytes_received += len;
  1527. out:
  1528. if (!sret)
  1529. clear_sock(pool);
  1530. else if (opt_protocol)
  1531. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1532. return sret;
  1533. }
  1534. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1535. * flag, but this is compatible with 2.0. */
  1536. char *json_dumps_ANY(json_t *json, size_t flags)
  1537. {
  1538. switch (json_typeof(json))
  1539. {
  1540. case JSON_ARRAY:
  1541. case JSON_OBJECT:
  1542. return json_dumps(json, flags);
  1543. default:
  1544. break;
  1545. }
  1546. char *rv;
  1547. #ifdef JSON_ENCODE_ANY
  1548. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1549. if (rv)
  1550. return rv;
  1551. #endif
  1552. json_t *tmp = json_array();
  1553. char *s;
  1554. int i;
  1555. size_t len;
  1556. if (!tmp)
  1557. quithere(1, "Failed to allocate json array");
  1558. if (json_array_append(tmp, json))
  1559. quithere(1, "Failed to append temporary array");
  1560. s = json_dumps(tmp, flags);
  1561. if (!s)
  1562. return NULL;
  1563. for (i = 0; s[i] != '['; ++i)
  1564. if (unlikely(!(s[i] && isCspace(s[i]))))
  1565. quithere(1, "Failed to find opening bracket in array dump");
  1566. len = strlen(&s[++i]) - 1;
  1567. if (unlikely(s[i+len] != ']'))
  1568. quithere(1, "Failed to find closing bracket in array dump");
  1569. rv = malloc(len + 1);
  1570. memcpy(rv, &s[i], len);
  1571. rv[len] = '\0';
  1572. free(s);
  1573. json_decref(tmp);
  1574. return rv;
  1575. }
  1576. /* Extracts a string value from a json array with error checking. To be used
  1577. * when the value of the string returned is only examined and not to be stored.
  1578. * See json_array_string below */
  1579. const char *__json_array_string(json_t *val, unsigned int entry)
  1580. {
  1581. json_t *arr_entry;
  1582. if (json_is_null(val))
  1583. return NULL;
  1584. if (!json_is_array(val))
  1585. return NULL;
  1586. if (entry > json_array_size(val))
  1587. return NULL;
  1588. arr_entry = json_array_get(val, entry);
  1589. if (!json_is_string(arr_entry))
  1590. return NULL;
  1591. return json_string_value(arr_entry);
  1592. }
  1593. /* Creates a freshly malloced dup of __json_array_string */
  1594. static char *json_array_string(json_t *val, unsigned int entry)
  1595. {
  1596. const char *buf = __json_array_string(val, entry);
  1597. if (buf)
  1598. return strdup(buf);
  1599. return NULL;
  1600. }
  1601. void stratum_probe_transparency(struct pool *pool)
  1602. {
  1603. // Request transaction data to discourage pools from doing anything shady
  1604. char s[1024];
  1605. int sLen;
  1606. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1607. pool->swork.job_id,
  1608. pool->swork.job_id);
  1609. stratum_send(pool, s, sLen);
  1610. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  1611. timer_set_delay_from_now(&pool->swork.tv_transparency, 21093750L);
  1612. pool->swork.transparency_probed = true;
  1613. }
  1614. static bool parse_notify(struct pool *pool, json_t *val)
  1615. {
  1616. const char *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1617. char *job_id;
  1618. bool clean, ret = false;
  1619. int merkles, i;
  1620. size_t cb1_len, cb2_len;
  1621. json_t *arr;
  1622. arr = json_array_get(val, 4);
  1623. if (!arr || !json_is_array(arr))
  1624. goto out;
  1625. merkles = json_array_size(arr);
  1626. for (i = 0; i < merkles; i++)
  1627. if (!json_is_string(json_array_get(arr, i)))
  1628. goto out;
  1629. prev_hash = __json_array_string(val, 1);
  1630. coinbase1 = __json_array_string(val, 2);
  1631. coinbase2 = __json_array_string(val, 3);
  1632. bbversion = __json_array_string(val, 5);
  1633. nbit = __json_array_string(val, 6);
  1634. ntime = __json_array_string(val, 7);
  1635. clean = json_is_true(json_array_get(val, 8));
  1636. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  1637. goto out;
  1638. job_id = json_array_string(val, 0);
  1639. if (!job_id)
  1640. goto out;
  1641. cg_wlock(&pool->data_lock);
  1642. cgtime(&pool->swork.tv_received);
  1643. free(pool->swork.job_id);
  1644. pool->swork.job_id = job_id;
  1645. pool->submit_old = !clean;
  1646. pool->swork.clean = true;
  1647. hex2bin(&pool->swork.header1[0], bbversion, 4);
  1648. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  1649. hex2bin((void*)&pool->swork.ntime, ntime, 4);
  1650. pool->swork.ntime = be32toh(pool->swork.ntime);
  1651. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  1652. cb1_len = strlen(coinbase1) / 2;
  1653. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  1654. cb2_len = strlen(coinbase2) / 2;
  1655. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->n2size + cb2_len);
  1656. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  1657. hex2bin(coinbase, coinbase1, cb1_len);
  1658. hex2bin(&coinbase[cb1_len], pool->nonce1, pool->n1_len);
  1659. // NOTE: gap for nonce2, filled at work generation time
  1660. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->n2size], coinbase2, cb2_len);
  1661. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  1662. for (i = 0; i < merkles; i++)
  1663. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  1664. pool->swork.merkles = merkles;
  1665. pool->nonce2 = 0;
  1666. cg_wunlock(&pool->data_lock);
  1667. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1668. pool->pool_no, job_id);
  1669. if (opt_debug && opt_protocol)
  1670. {
  1671. applog(LOG_DEBUG, "job_id: %s", job_id);
  1672. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1673. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1674. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1675. for (i = 0; i < merkles; i++)
  1676. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  1677. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1678. applog(LOG_DEBUG, "nbit: %s", nbit);
  1679. applog(LOG_DEBUG, "ntime: %s", ntime);
  1680. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1681. }
  1682. /* A notify message is the closest stratum gets to a getwork */
  1683. pool->getwork_requested++;
  1684. total_getworks++;
  1685. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  1686. if (pool->probed)
  1687. stratum_probe_transparency(pool);
  1688. ret = true;
  1689. out:
  1690. return ret;
  1691. }
  1692. static bool parse_diff(struct pool *pool, json_t *val)
  1693. {
  1694. double diff;
  1695. diff = json_number_value(json_array_get(val, 0));
  1696. if (diff == 0)
  1697. return false;
  1698. cg_wlock(&pool->data_lock);
  1699. pool->swork.diff = diff;
  1700. cg_wunlock(&pool->data_lock);
  1701. applog(LOG_DEBUG, "Pool %d stratum bdifficulty set to %f", pool->pool_no, diff);
  1702. return true;
  1703. }
  1704. static bool parse_reconnect(struct pool *pool, json_t *val)
  1705. {
  1706. if (opt_disable_client_reconnect)
  1707. return false;
  1708. const char *url;
  1709. char address[256];
  1710. json_t *port_json;
  1711. url = __json_array_string(val, 0);
  1712. if (!url)
  1713. url = pool->sockaddr_url;
  1714. port_json = json_array_get(val, 1);
  1715. if (json_is_number(port_json))
  1716. {
  1717. const unsigned port = json_number_value(port_json);
  1718. snprintf(address, sizeof(address), "%s:%u", url, port);
  1719. }
  1720. else
  1721. {
  1722. const char *port;
  1723. if (json_is_string(port_json))
  1724. port = json_string_value(port_json);
  1725. else
  1726. port = pool->stratum_port;
  1727. snprintf(address, sizeof(address), "%s:%s", url, port);
  1728. }
  1729. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  1730. return false;
  1731. pool->stratum_url = pool->sockaddr_url;
  1732. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1733. if (!restart_stratum(pool))
  1734. return false;
  1735. return true;
  1736. }
  1737. static bool send_version(struct pool *pool, json_t *val)
  1738. {
  1739. char s[RBUFSIZE], *idstr;
  1740. json_t *id = json_object_get(val, "id");
  1741. if (!(id && !json_is_null(id)))
  1742. return false;
  1743. idstr = json_dumps_ANY(id, 0);
  1744. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1745. free(idstr);
  1746. if (!stratum_send(pool, s, strlen(s)))
  1747. return false;
  1748. return true;
  1749. }
  1750. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  1751. {
  1752. char *msg;
  1753. char s[RBUFSIZE], *idstr;
  1754. json_t *id = json_object_get(val, "id");
  1755. msg = json_array_string(params, 0);
  1756. if (likely(msg))
  1757. {
  1758. free(pool->admin_msg);
  1759. pool->admin_msg = msg;
  1760. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  1761. }
  1762. if (!(id && !json_is_null(id)))
  1763. return true;
  1764. idstr = json_dumps_ANY(id, 0);
  1765. if (likely(msg))
  1766. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  1767. else
  1768. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  1769. free(idstr);
  1770. if (!stratum_send(pool, s, strlen(s)))
  1771. return false;
  1772. return true;
  1773. }
  1774. bool parse_method(struct pool *pool, char *s)
  1775. {
  1776. json_t *val = NULL, *method, *err_val, *params;
  1777. json_error_t err;
  1778. bool ret = false;
  1779. const char *buf;
  1780. if (!s)
  1781. goto out;
  1782. val = JSON_LOADS(s, &err);
  1783. if (!val) {
  1784. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1785. goto out;
  1786. }
  1787. method = json_object_get(val, "method");
  1788. if (!method)
  1789. goto out;
  1790. err_val = json_object_get(val, "error");
  1791. params = json_object_get(val, "params");
  1792. if (err_val && !json_is_null(err_val)) {
  1793. char *ss;
  1794. if (err_val)
  1795. ss = json_dumps(err_val, JSON_INDENT(3));
  1796. else
  1797. ss = strdup("(unknown reason)");
  1798. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1799. free(ss);
  1800. goto out;
  1801. }
  1802. buf = json_string_value(method);
  1803. if (!buf)
  1804. goto out;
  1805. if (!strncasecmp(buf, "mining.notify", 13)) {
  1806. if (parse_notify(pool, params))
  1807. pool->stratum_notify = ret = true;
  1808. else
  1809. pool->stratum_notify = ret = false;
  1810. goto out;
  1811. }
  1812. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1813. ret = true;
  1814. goto out;
  1815. }
  1816. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1817. ret = true;
  1818. goto out;
  1819. }
  1820. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1821. ret = true;
  1822. goto out;
  1823. }
  1824. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  1825. ret = true;
  1826. goto out;
  1827. }
  1828. out:
  1829. if (val)
  1830. json_decref(val);
  1831. return ret;
  1832. }
  1833. extern bool parse_stratum_response(struct pool *, char *s);
  1834. bool auth_stratum(struct pool *pool)
  1835. {
  1836. json_t *val = NULL, *res_val, *err_val;
  1837. char s[RBUFSIZE], *sret = NULL;
  1838. json_error_t err;
  1839. bool ret = false;
  1840. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1841. pool->rpc_user, pool->rpc_pass);
  1842. if (!stratum_send(pool, s, strlen(s)))
  1843. goto out;
  1844. /* Parse all data in the queue and anything left should be auth */
  1845. while (42) {
  1846. sret = recv_line(pool);
  1847. if (!sret)
  1848. goto out;
  1849. if (parse_method(pool, sret))
  1850. free(sret);
  1851. else
  1852. break;
  1853. }
  1854. val = JSON_LOADS(sret, &err);
  1855. free(sret);
  1856. res_val = json_object_get(val, "result");
  1857. err_val = json_object_get(val, "error");
  1858. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1859. char *ss;
  1860. if (err_val)
  1861. ss = json_dumps(err_val, JSON_INDENT(3));
  1862. else
  1863. ss = strdup("(unknown reason)");
  1864. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1865. free(ss);
  1866. goto out;
  1867. }
  1868. ret = true;
  1869. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1870. pool->probed = true;
  1871. successful_connect = true;
  1872. out:
  1873. if (val)
  1874. json_decref(val);
  1875. if (pool->stratum_notify)
  1876. stratum_probe_transparency(pool);
  1877. return ret;
  1878. }
  1879. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1880. {
  1881. struct pool *pool = clientp;
  1882. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1883. pool->sock = sck;
  1884. return sck;
  1885. }
  1886. static bool setup_stratum_curl(struct pool *pool)
  1887. {
  1888. char curl_err_str[CURL_ERROR_SIZE];
  1889. CURL *curl = NULL;
  1890. char s[RBUFSIZE];
  1891. bool ret = false;
  1892. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1893. mutex_lock(&pool->stratum_lock);
  1894. timer_unset(&pool->swork.tv_transparency);
  1895. pool->stratum_active = false;
  1896. pool->stratum_notify = false;
  1897. pool->swork.transparency_probed = false;
  1898. if (pool->stratum_curl)
  1899. curl_easy_cleanup(pool->stratum_curl);
  1900. pool->stratum_curl = curl_easy_init();
  1901. if (unlikely(!pool->stratum_curl))
  1902. quithere(1, "Failed to curl_easy_init");
  1903. if (pool->sockbuf)
  1904. pool->sockbuf[0] = '\0';
  1905. curl = pool->stratum_curl;
  1906. if (!pool->sockbuf) {
  1907. pool->sockbuf = calloc(RBUFSIZE, 1);
  1908. if (!pool->sockbuf)
  1909. quithere(1, "Failed to calloc pool sockbuf");
  1910. pool->sockbuf_size = RBUFSIZE;
  1911. }
  1912. /* Create a http url for use with curl */
  1913. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1914. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1915. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1916. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1917. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1918. curl_easy_setopt(curl, CURLOPT_URL, s);
  1919. if (!opt_delaynet)
  1920. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1921. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1922. * to enable it */
  1923. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  1924. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  1925. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1926. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  1927. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  1928. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  1929. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1930. if (pool->rpc_proxy) {
  1931. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  1932. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1933. } else if (opt_socks_proxy) {
  1934. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  1935. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1936. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  1937. }
  1938. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1939. pool->sock = INVSOCK;
  1940. if (curl_easy_perform(curl)) {
  1941. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1942. errout:
  1943. curl_easy_cleanup(curl);
  1944. pool->stratum_curl = NULL;
  1945. goto out;
  1946. }
  1947. if (pool->sock == INVSOCK)
  1948. {
  1949. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  1950. goto errout;
  1951. }
  1952. keep_sockalive(pool->sock);
  1953. pool->cgminer_pool_stats.times_sent++;
  1954. pool->cgminer_pool_stats.times_received++;
  1955. ret = true;
  1956. out:
  1957. mutex_unlock(&pool->stratum_lock);
  1958. return ret;
  1959. }
  1960. static char *get_sessionid(json_t *val)
  1961. {
  1962. char *ret = NULL;
  1963. json_t *arr_val;
  1964. int arrsize, i;
  1965. arr_val = json_array_get(val, 0);
  1966. if (!arr_val || !json_is_array(arr_val))
  1967. goto out;
  1968. arrsize = json_array_size(arr_val);
  1969. for (i = 0; i < arrsize; i++) {
  1970. json_t *arr = json_array_get(arr_val, i);
  1971. const char *notify;
  1972. if (!arr | !json_is_array(arr))
  1973. break;
  1974. notify = __json_array_string(arr, 0);
  1975. if (!notify)
  1976. continue;
  1977. if (!strncasecmp(notify, "mining.notify", 13)) {
  1978. ret = json_array_string(arr, 1);
  1979. break;
  1980. }
  1981. }
  1982. out:
  1983. return ret;
  1984. }
  1985. void suspend_stratum(struct pool *pool)
  1986. {
  1987. clear_sockbuf(pool);
  1988. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1989. mutex_lock(&pool->stratum_lock);
  1990. pool->stratum_active = pool->stratum_notify = false;
  1991. if (pool->stratum_curl) {
  1992. curl_easy_cleanup(pool->stratum_curl);
  1993. }
  1994. pool->stratum_curl = NULL;
  1995. pool->sock = INVSOCK;
  1996. mutex_unlock(&pool->stratum_lock);
  1997. }
  1998. bool initiate_stratum(struct pool *pool)
  1999. {
  2000. bool ret = false, recvd = false, noresume = false, sockd = false;
  2001. bool trysuggest = request_target_str;
  2002. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  2003. json_t *val = NULL, *res_val, *err_val;
  2004. json_error_t err;
  2005. int n2size;
  2006. resend:
  2007. if (!setup_stratum_curl(pool)) {
  2008. sockd = false;
  2009. goto out;
  2010. }
  2011. sockd = true;
  2012. clear_sock(pool);
  2013. if (trysuggest)
  2014. {
  2015. int sz = sprintf(s, "{\"id\": null, \"method\": \"mining.suggest_target\", \"params\": [\"%s\"]}", request_target_str);
  2016. if (!_stratum_send(pool, s, sz, true))
  2017. {
  2018. applog(LOG_DEBUG, "Pool %u: Failed to send suggest_target in initiate_stratum", pool->pool_no);
  2019. goto out;
  2020. }
  2021. recvd = true;
  2022. }
  2023. if (noresume) {
  2024. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2025. } else {
  2026. if (pool->sessionid)
  2027. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2028. else
  2029. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  2030. }
  2031. if (!_stratum_send(pool, s, strlen(s), true)) {
  2032. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2033. goto out;
  2034. }
  2035. recvd = true;
  2036. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2037. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2038. goto out;
  2039. }
  2040. sret = recv_line(pool);
  2041. if (!sret)
  2042. goto out;
  2043. val = JSON_LOADS(sret, &err);
  2044. free(sret);
  2045. if (!val) {
  2046. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2047. goto out;
  2048. }
  2049. res_val = json_object_get(val, "result");
  2050. err_val = json_object_get(val, "error");
  2051. if (!res_val || json_is_null(res_val) ||
  2052. (err_val && !json_is_null(err_val))) {
  2053. char *ss;
  2054. if (err_val)
  2055. ss = json_dumps(err_val, JSON_INDENT(3));
  2056. else
  2057. ss = strdup("(unknown reason)");
  2058. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2059. free(ss);
  2060. goto out;
  2061. }
  2062. sessionid = get_sessionid(res_val);
  2063. if (!sessionid)
  2064. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2065. nonce1 = json_array_string(res_val, 1);
  2066. if (!nonce1) {
  2067. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  2068. free(sessionid);
  2069. goto out;
  2070. }
  2071. n2size = json_integer_value(json_array_get(res_val, 2));
  2072. if (!n2size) {
  2073. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  2074. free(sessionid);
  2075. free(nonce1);
  2076. goto out;
  2077. }
  2078. cg_wlock(&pool->data_lock);
  2079. free(pool->sessionid);
  2080. pool->sessionid = sessionid;
  2081. free(pool->nonce1);
  2082. pool->nonce1 = nonce1;
  2083. pool->n1_len = strlen(nonce1) / 2;
  2084. pool->n2size = n2size;
  2085. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  2086. #ifdef WORDS_BIGENDIAN
  2087. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  2088. #endif
  2089. cg_wunlock(&pool->data_lock);
  2090. if (sessionid)
  2091. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2092. ret = true;
  2093. out:
  2094. if (val)
  2095. {
  2096. json_decref(val);
  2097. val = NULL;
  2098. }
  2099. if (ret) {
  2100. if (!pool->stratum_url)
  2101. pool->stratum_url = pool->sockaddr_url;
  2102. pool->stratum_active = true;
  2103. pool->swork.diff = 1;
  2104. if (opt_protocol) {
  2105. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2106. pool->pool_no, pool->nonce1, pool->n2size);
  2107. }
  2108. } else {
  2109. if (recvd)
  2110. {
  2111. if (trysuggest)
  2112. {
  2113. applog(LOG_DEBUG, "Pool %u: Failed to connect stratum with mining.suggest_target, retrying without", pool->pool_no);
  2114. trysuggest = false;
  2115. goto resend;
  2116. }
  2117. if (!noresume)
  2118. {
  2119. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2120. noresume = true;
  2121. goto resend;
  2122. }
  2123. }
  2124. applog(LOG_DEBUG, "Initiate stratum failed");
  2125. if (sockd)
  2126. suspend_stratum(pool);
  2127. }
  2128. return ret;
  2129. }
  2130. bool restart_stratum(struct pool *pool)
  2131. {
  2132. if (pool->stratum_active)
  2133. suspend_stratum(pool);
  2134. if (!initiate_stratum(pool))
  2135. return false;
  2136. if (!auth_stratum(pool))
  2137. return false;
  2138. return true;
  2139. }
  2140. void dev_error_update(struct cgpu_info *dev, enum dev_reason reason)
  2141. {
  2142. dev->device_last_not_well = time(NULL);
  2143. cgtime(&dev->tv_device_last_not_well);
  2144. dev->device_not_well_reason = reason;
  2145. }
  2146. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2147. {
  2148. dev_error_update(dev, reason);
  2149. switch (reason) {
  2150. case REASON_THREAD_FAIL_INIT:
  2151. dev->thread_fail_init_count++;
  2152. break;
  2153. case REASON_THREAD_ZERO_HASH:
  2154. dev->thread_zero_hash_count++;
  2155. break;
  2156. case REASON_THREAD_FAIL_QUEUE:
  2157. dev->thread_fail_queue_count++;
  2158. break;
  2159. case REASON_DEV_SICK_IDLE_60:
  2160. dev->dev_sick_idle_60_count++;
  2161. break;
  2162. case REASON_DEV_DEAD_IDLE_600:
  2163. dev->dev_dead_idle_600_count++;
  2164. break;
  2165. case REASON_DEV_NOSTART:
  2166. dev->dev_nostart_count++;
  2167. break;
  2168. case REASON_DEV_OVER_HEAT:
  2169. dev->dev_over_heat_count++;
  2170. break;
  2171. case REASON_DEV_THERMAL_CUTOFF:
  2172. dev->dev_thermal_cutoff_count++;
  2173. break;
  2174. case REASON_DEV_COMMS_ERROR:
  2175. dev->dev_comms_error_count++;
  2176. break;
  2177. case REASON_DEV_THROTTLE:
  2178. dev->dev_throttle_count++;
  2179. break;
  2180. }
  2181. }
  2182. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2183. void *realloc_strcat(char *ptr, char *s)
  2184. {
  2185. size_t old = strlen(ptr), len = strlen(s);
  2186. char *ret;
  2187. if (!len)
  2188. return ptr;
  2189. len += old + 1;
  2190. align_len(&len);
  2191. ret = malloc(len);
  2192. if (unlikely(!ret))
  2193. quithere(1, "Failed to malloc");
  2194. sprintf(ret, "%s%s", ptr, s);
  2195. free(ptr);
  2196. return ret;
  2197. }
  2198. static
  2199. bool sanechars[] = {
  2200. false, false, false, false, false, false, false, false,
  2201. false, false, false, false, false, false, false, false,
  2202. false, false, false, false, false, false, false, false,
  2203. false, false, false, false, false, false, false, false,
  2204. false, false, false, false, false, false, false, false,
  2205. false, false, false, false, false, true , false, false,
  2206. true , true , true , true , true , true , true , true ,
  2207. true , true , false, false, false, false, false, false,
  2208. false, true , true , true , true , true , true , true ,
  2209. true , true , true , true , true , true , true , true ,
  2210. true , true , true , true , true , true , true , true ,
  2211. true , true , true , false, false, false, false, false,
  2212. false, true , true , true , true , true , true , true ,
  2213. true , true , true , true , true , true , true , true ,
  2214. true , true , true , true , true , true , true , true ,
  2215. true , true , true , false, false, false, false, false,
  2216. };
  2217. char *sanestr(char *o, char *s)
  2218. {
  2219. char *rv = o;
  2220. bool br = false;
  2221. for ( ; s[0]; ++s)
  2222. {
  2223. if (sanechars[s[0] & 0x7f])
  2224. {
  2225. if (br)
  2226. {
  2227. br = false;
  2228. if (s[0] >= '0' && s[0] <= '9')
  2229. (o++)[0] = '_';
  2230. }
  2231. (o++)[0] = s[0];
  2232. }
  2233. else
  2234. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  2235. br = true;
  2236. }
  2237. o[0] = '\0';
  2238. return rv;
  2239. }
  2240. void RenameThread(const char* name)
  2241. {
  2242. #if defined(PR_SET_NAME)
  2243. // Only the first 15 characters are used (16 - NUL terminator)
  2244. prctl(PR_SET_NAME, name, 0, 0, 0);
  2245. #elif defined(__APPLE__)
  2246. pthread_setname_np(name);
  2247. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2248. pthread_set_name_np(pthread_self(), name);
  2249. #else
  2250. // Prevent warnings for unused parameters...
  2251. (void)name;
  2252. #endif
  2253. }
  2254. static pthread_key_t key_bfgtls;
  2255. struct bfgtls_data {
  2256. char *bfg_strerror_result;
  2257. size_t bfg_strerror_resultsz;
  2258. #ifdef WIN32
  2259. LPSTR bfg_strerror_socketresult;
  2260. #endif
  2261. #ifdef NEED_BFG_LOWL_VCOM
  2262. struct detectone_meta_info_t __detectone_meta_info;
  2263. #endif
  2264. };
  2265. static
  2266. struct bfgtls_data *get_bfgtls()
  2267. {
  2268. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  2269. if (bfgtls)
  2270. return bfgtls;
  2271. void *p;
  2272. bfgtls = malloc(sizeof(*bfgtls));
  2273. if (!bfgtls)
  2274. quithere(1, "malloc bfgtls failed");
  2275. p = malloc(64);
  2276. if (!p)
  2277. quithere(1, "malloc bfg_strerror_result failed");
  2278. *bfgtls = (struct bfgtls_data){
  2279. .bfg_strerror_resultsz = 64,
  2280. .bfg_strerror_result = p,
  2281. };
  2282. if (pthread_setspecific(key_bfgtls, bfgtls))
  2283. quithere(1, "pthread_setspecific failed");
  2284. return bfgtls;
  2285. }
  2286. static
  2287. void bfgtls_free(void * const p)
  2288. {
  2289. struct bfgtls_data * const bfgtls = p;
  2290. free(bfgtls->bfg_strerror_result);
  2291. #ifdef WIN32
  2292. if (bfgtls->bfg_strerror_socketresult)
  2293. LocalFree(bfgtls->bfg_strerror_socketresult);
  2294. #endif
  2295. free(bfgtls);
  2296. }
  2297. #ifdef NEED_BFG_LOWL_VCOM
  2298. struct detectone_meta_info_t *_detectone_meta_info()
  2299. {
  2300. return &get_bfgtls()->__detectone_meta_info;
  2301. }
  2302. #endif
  2303. void bfg_init_threadlocal()
  2304. {
  2305. if (pthread_key_create(&key_bfgtls, bfgtls_free))
  2306. quithere(1, "pthread_key_create failed");
  2307. }
  2308. static
  2309. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  2310. {
  2311. if (minimum <= *bufszp)
  2312. return false;
  2313. while (minimum > *bufszp)
  2314. *bufszp = 2;
  2315. *bufp = realloc(*bufp, *bufszp);
  2316. if (unlikely(!*bufp))
  2317. quithere(1, "realloc failed");
  2318. return true;
  2319. }
  2320. static
  2321. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  2322. {
  2323. if (!src)
  2324. return NULL;
  2325. const size_t srcsz = strlen(src) + 1;
  2326. bfg_grow_buffer(bufp, bufszp, srcsz);
  2327. memcpy(*bufp, src, srcsz);
  2328. return *bufp;
  2329. }
  2330. // Guaranteed to always return some string (or quit)
  2331. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  2332. {
  2333. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2334. struct bfgtls_data *bfgtls = get_bfgtls();
  2335. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  2336. char ** const bufp = &bfgtls->bfg_strerror_result;
  2337. const char *have = NULL;
  2338. switch (type) {
  2339. case BST_LIBUSB:
  2340. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  2341. #ifdef HAVE_LIBUSB
  2342. # if HAVE_DECL_LIBUSB_ERROR_NAME
  2343. // libusb makes no guarantees for thread-safety or persistence
  2344. mutex_lock(&mutex);
  2345. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  2346. mutex_unlock(&mutex);
  2347. # endif
  2348. #endif
  2349. break;
  2350. case BST_SOCKET:
  2351. case BST_SYSTEM:
  2352. {
  2353. #ifdef WIN32
  2354. // Windows has a different namespace for system and socket errors
  2355. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  2356. if (*msg)
  2357. LocalFree(*msg);
  2358. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  2359. {
  2360. LPSTR msgp = *msg;
  2361. size_t n = strlen(msgp);
  2362. while (isCspace(msgp[--n]))
  2363. msgp[n] = '\0';
  2364. return *msg;
  2365. }
  2366. *msg = NULL;
  2367. break;
  2368. #endif
  2369. }
  2370. // Fallthru on non-WIN32
  2371. case BST_ERRNO:
  2372. {
  2373. #ifdef __STRERROR_S_WORKS
  2374. // FIXME: Not sure how to get this on MingW64
  2375. retry:
  2376. if (likely(!strerror_s(*bufp, *bufszp, e)))
  2377. {
  2378. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  2379. goto retry;
  2380. return *bufp;
  2381. }
  2382. // TODO: XSI strerror_r
  2383. // TODO: GNU strerror_r
  2384. #else
  2385. mutex_lock(&mutex);
  2386. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  2387. mutex_unlock(&mutex);
  2388. #endif
  2389. }
  2390. }
  2391. if (have)
  2392. return *bufp;
  2393. // Failback: Stringify the number
  2394. static const char fmt[] = "%s error #%d", *typestr;
  2395. switch (type) {
  2396. case BST_ERRNO:
  2397. typestr = "System";
  2398. break;
  2399. case BST_SOCKET:
  2400. typestr = "Socket";
  2401. break;
  2402. case BST_LIBUSB:
  2403. typestr = "libusb";
  2404. break;
  2405. default:
  2406. typestr = "Unexpected";
  2407. }
  2408. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  2409. bfg_grow_buffer(bufp, bufszp, sz);
  2410. sprintf(*bufp, fmt, typestr, e);
  2411. return *bufp;
  2412. }
  2413. void notifier_init(notifier_t pipefd)
  2414. {
  2415. #ifdef WIN32
  2416. #define WindowsErrorStr(e) bfg_strerror(e, BST_SOCKET)
  2417. SOCKET listener, connecter, acceptor;
  2418. listener = socket(AF_INET, SOCK_STREAM, 0);
  2419. if (listener == INVALID_SOCKET)
  2420. quit(1, "Failed to create listener socket"IN_FMT_FFL": %s",
  2421. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2422. connecter = socket(AF_INET, SOCK_STREAM, 0);
  2423. if (connecter == INVALID_SOCKET)
  2424. quit(1, "Failed to create connect socket"IN_FMT_FFL": %s",
  2425. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2426. struct sockaddr_in inaddr = {
  2427. .sin_family = AF_INET,
  2428. .sin_addr = {
  2429. .s_addr = htonl(INADDR_LOOPBACK),
  2430. },
  2431. .sin_port = 0,
  2432. };
  2433. {
  2434. static const int reuse = 1;
  2435. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
  2436. }
  2437. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  2438. quit(1, "Failed to bind listener socket"IN_FMT_FFL": %s",
  2439. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2440. socklen_t inaddr_sz = sizeof(inaddr);
  2441. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  2442. quit(1, "Failed to getsockname"IN_FMT_FFL": %s",
  2443. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2444. if (listen(listener, 1) == SOCKET_ERROR)
  2445. quit(1, "Failed to listen"IN_FMT_FFL": %s",
  2446. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2447. inaddr.sin_family = AF_INET;
  2448. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2449. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  2450. quit(1, "Failed to connect"IN_FMT_FFL": %s",
  2451. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2452. acceptor = accept(listener, NULL, NULL);
  2453. if (acceptor == INVALID_SOCKET)
  2454. quit(1, "Failed to accept"IN_FMT_FFL": %s",
  2455. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2456. closesocket(listener);
  2457. pipefd[0] = connecter;
  2458. pipefd[1] = acceptor;
  2459. #else
  2460. if (pipe(pipefd))
  2461. quithere(1, "Failed to create pipe");
  2462. #endif
  2463. }
  2464. void *bfg_slurp_file(void * const bufp, size_t bufsz, const char * const filename)
  2465. {
  2466. char *buf = bufp;
  2467. FILE * const F = fopen(filename, "r");
  2468. if (!F)
  2469. goto err;
  2470. if (!buf)
  2471. {
  2472. fseek(F, 0, SEEK_END);
  2473. const long filesz = ftell(F);
  2474. if (unlikely(filesz < 0))
  2475. {
  2476. fclose(F);
  2477. goto err;
  2478. }
  2479. rewind(F);
  2480. bufsz = filesz + 1;
  2481. buf = malloc(bufsz);
  2482. }
  2483. const size_t rsz = fread(buf, 1, bufsz - 1, F);
  2484. fclose(F);
  2485. buf[rsz] = '\0';
  2486. return buf;
  2487. err:
  2488. if (buf)
  2489. buf[0] = '\0';
  2490. return NULL;
  2491. }
  2492. void notifier_wake(notifier_t fd)
  2493. {
  2494. if (fd[1] == INVSOCK)
  2495. return;
  2496. if (1 !=
  2497. #ifdef WIN32
  2498. send(fd[1], "\0", 1, 0)
  2499. #else
  2500. write(fd[1], "\0", 1)
  2501. #endif
  2502. )
  2503. applog(LOG_WARNING, "Error trying to wake notifier");
  2504. }
  2505. void notifier_read(notifier_t fd)
  2506. {
  2507. char buf[0x10];
  2508. #ifdef WIN32
  2509. IGNORE_RETURN_VALUE(recv(fd[0], buf, sizeof(buf), 0));
  2510. #else
  2511. IGNORE_RETURN_VALUE(read(fd[0], buf, sizeof(buf)));
  2512. #endif
  2513. }
  2514. bool notifier_wait(notifier_t notifier, const struct timeval *tvp_timeout)
  2515. {
  2516. struct timeval tv_now, tv_timeout;
  2517. fd_set rfds;
  2518. int e;
  2519. while (true)
  2520. {
  2521. FD_ZERO(&rfds);
  2522. FD_SET(notifier[0], &rfds);
  2523. tv_timeout = *tvp_timeout;
  2524. timer_set_now(&tv_now);
  2525. e = select(notifier[0]+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now));
  2526. if (e > 0)
  2527. return true;
  2528. if (e == 0)
  2529. return false;
  2530. }
  2531. }
  2532. bool notifier_wait_us(notifier_t notifier, const unsigned long long usecs)
  2533. {
  2534. struct timeval tv_timeout = TIMEVAL_USECS(usecs);
  2535. return notifier_wait(notifier, &tv_timeout);
  2536. }
  2537. void notifier_reset(notifier_t notifier)
  2538. {
  2539. fd_set rfds;
  2540. struct timeval tv_timeout = { .tv_sec = 0, };
  2541. FD_ZERO(&rfds);
  2542. FD_SET(notifier[0], &rfds);
  2543. while (select(notifier[0]+1, &rfds, NULL, NULL, &tv_timeout) != 0)
  2544. notifier_read(notifier);
  2545. }
  2546. void notifier_init_invalid(notifier_t fd)
  2547. {
  2548. fd[0] = fd[1] = INVSOCK;
  2549. }
  2550. void notifier_destroy(notifier_t fd)
  2551. {
  2552. #ifdef WIN32
  2553. closesocket(fd[0]);
  2554. closesocket(fd[1]);
  2555. #else
  2556. close(fd[0]);
  2557. close(fd[1]);
  2558. #endif
  2559. fd[0] = fd[1] = INVSOCK;
  2560. }
  2561. void _bytes_alloc_failure(size_t sz)
  2562. {
  2563. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  2564. }
  2565. char *trimmed_strdup(const char *s)
  2566. {
  2567. size_t n;
  2568. char *c;
  2569. while (isspace(s[0]))
  2570. ++s;
  2571. n = strlen(s) - 1;
  2572. while (isspace(s[n]))
  2573. --n;
  2574. ++n;
  2575. c = malloc(n + 1);
  2576. c[n] = '\0';
  2577. memcpy(c, s, n);
  2578. return c;
  2579. }
  2580. void *cmd_thread(void *cmdp)
  2581. {
  2582. const char *cmd = cmdp;
  2583. applog(LOG_DEBUG, "Executing command: %s", cmd);
  2584. int rc = system(cmd);
  2585. if (rc)
  2586. applog(LOG_WARNING, "Command returned %d exit code: %s", rc, cmd);
  2587. return NULL;
  2588. }
  2589. void run_cmd(const char *cmd)
  2590. {
  2591. if (!cmd)
  2592. return;
  2593. pthread_t pth;
  2594. pthread_create(&pth, NULL, cmd_thread, (void*)cmd);
  2595. }
  2596. uint8_t crc5usb(unsigned char *ptr, uint8_t len)
  2597. {
  2598. uint8_t i, j, k;
  2599. uint8_t crc = 0x1f;
  2600. uint8_t crcin[5] = {1, 1, 1, 1, 1};
  2601. uint8_t crcout[5] = {1, 1, 1, 1, 1};
  2602. uint8_t din = 0;
  2603. j = 0x80;
  2604. k = 0;
  2605. for (i = 0; i < len; i++)
  2606. {
  2607. if (*ptr & j)
  2608. din = 1;
  2609. else
  2610. din = 0;
  2611. crcout[0] = crcin[4] ^ din;
  2612. crcout[1] = crcin[0];
  2613. crcout[2] = crcin[1] ^ crcin[4] ^ din;
  2614. crcout[3] = crcin[2];
  2615. crcout[4] = crcin[3];
  2616. j = j >> 1;
  2617. k++;
  2618. if (k == 8)
  2619. {
  2620. j = 0x80;
  2621. k = 0;
  2622. ptr++;
  2623. }
  2624. memcpy(crcin, crcout, 5);
  2625. }
  2626. crc = 0;
  2627. if(crcin[4])
  2628. crc |= 0x10;
  2629. if(crcin[3])
  2630. crc |= 0x08;
  2631. if(crcin[2])
  2632. crc |= 0x04;
  2633. if(crcin[1])
  2634. crc |= 0x02;
  2635. if(crcin[0])
  2636. crc |= 0x01;
  2637. return crc;
  2638. }
  2639. static uint8_t _crc8ccitt_table[0x100];
  2640. void bfg_init_checksums(void)
  2641. {
  2642. for (int i = 0; i < 0x100; ++i)
  2643. {
  2644. uint8_t crc = i;
  2645. for (int j = 0; j < 8; ++j)
  2646. crc = (crc << 1) ^ ((crc & 0x80) ? 7 : 0);
  2647. _crc8ccitt_table[i] = crc & 0xff;
  2648. }
  2649. }
  2650. uint8_t crc8ccitt(const void * const buf, const size_t buflen)
  2651. {
  2652. const uint8_t *p = buf;
  2653. uint8_t crc = 0xff;
  2654. for (int i = 0; i < buflen; ++i)
  2655. crc = _crc8ccitt_table[crc ^ *p++];
  2656. return crc;
  2657. }