util.c 101 KB

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