util.c 85 KB

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