util.c 82 KB

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