util.c 82 KB

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