util.c 101 KB

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