util.c 93 KB

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