util.c 87 KB

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