util.c 100 KB

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