util.c 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847
  1. /*
  2. * Copyright 2011-2018 Con Kolivas
  3. * Copyright 2011-2015 Andrew Smith
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <ctype.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include <jansson.h>
  18. #ifdef HAVE_LIBCURL
  19. #include <curl/curl.h>
  20. #endif
  21. #include <time.h>
  22. #include <errno.h>
  23. #include <unistd.h>
  24. #include <sys/types.h>
  25. #ifndef WIN32
  26. #include <fcntl.h>
  27. # ifdef __linux
  28. # include <sys/prctl.h>
  29. # endif
  30. # include <sys/socket.h>
  31. # include <netinet/in.h>
  32. # include <netinet/tcp.h>
  33. # include <netdb.h>
  34. #else
  35. # include <winsock2.h>
  36. # include <ws2tcpip.h>
  37. # include <mmsystem.h>
  38. #endif
  39. #include <sched.h>
  40. #include "miner.h"
  41. #include "elist.h"
  42. #include "compat.h"
  43. #include "util.h"
  44. #define DEFAULT_SOCKWAIT 60
  45. #ifndef STRATUM_USER_AGENT
  46. #define STRATUM_USER_AGENT
  47. #endif
  48. bool successful_connect = false;
  49. int no_yield(void)
  50. {
  51. return 0;
  52. }
  53. int (*selective_yield)(void) = &no_yield;
  54. static void keep_sockalive(SOCKETTYPE fd)
  55. {
  56. const int tcp_one = 1;
  57. #ifndef WIN32
  58. const int tcp_keepidle = 45;
  59. const int tcp_keepintvl = 30;
  60. int flags = fcntl(fd, F_GETFL, 0);
  61. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  62. #else
  63. u_long flags = 1;
  64. ioctlsocket(fd, FIONBIO, &flags);
  65. #endif
  66. setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const void *)&tcp_one, sizeof(tcp_one));
  67. if (!opt_delaynet)
  68. #ifndef __linux
  69. setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  70. #else /* __linux */
  71. fcntl(fd, F_SETFD, FD_CLOEXEC);
  72. setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  73. setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one));
  74. setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
  75. setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
  76. #endif /* __linux */
  77. #ifdef __APPLE_CC__
  78. setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
  79. #endif /* __APPLE_CC__ */
  80. }
  81. #ifdef WIN32
  82. /* Generic versions of inet_pton for windows, using different names in case
  83. * it is implemented in ming in the future. */
  84. #define W32NS_INADDRSZ 4
  85. #define W32NS_IN6ADDRSZ 16
  86. #define W32NS_INT16SZ 2
  87. static int Inet_Pton4(const char *src, char *dst)
  88. {
  89. uint8_t tmp[W32NS_INADDRSZ], *tp;
  90. int saw_digit = 0;
  91. int octets = 0;
  92. *(tp = tmp) = 0;
  93. int ch;
  94. while ((ch = *src++) != '\0')
  95. {
  96. if (ch >= '0' && ch <= '9')
  97. {
  98. uint32_t n = *tp * 10 + (ch - '0');
  99. if (saw_digit && *tp == 0)
  100. return 0;
  101. if (n > 255)
  102. return 0;
  103. *tp = n;
  104. if (!saw_digit)
  105. {
  106. if (++octets > 4)
  107. return 0;
  108. saw_digit = 1;
  109. }
  110. }
  111. else if (ch == '.' && saw_digit)
  112. {
  113. if (octets == 4)
  114. return 0;
  115. *++tp = 0;
  116. saw_digit = 0;
  117. }
  118. else
  119. return 0;
  120. }
  121. if (octets < 4)
  122. return 0;
  123. cg_memcpy(dst, tmp, W32NS_INADDRSZ);
  124. return 1;
  125. }
  126. static int Inet_Pton6(const char *src, char *dst)
  127. {
  128. static const char xdigits[] = "0123456789abcdef";
  129. uint8_t tmp[W32NS_IN6ADDRSZ];
  130. uint8_t *tp = (uint8_t*) memset(tmp, '\0', W32NS_IN6ADDRSZ);
  131. uint8_t *endp = tp + W32NS_IN6ADDRSZ;
  132. uint8_t *colonp = NULL;
  133. /* Leading :: requires some special handling. */
  134. if (*src == ':')
  135. {
  136. if (*++src != ':')
  137. return 0;
  138. }
  139. const char *curtok = src;
  140. int saw_xdigit = 0;
  141. uint32_t val = 0;
  142. int ch;
  143. while ((ch = tolower(*src++)) != '\0')
  144. {
  145. const char *pch = strchr(xdigits, ch);
  146. if (pch != NULL)
  147. {
  148. val <<= 4;
  149. val |= (pch - xdigits);
  150. if (val > 0xffff)
  151. return 0;
  152. saw_xdigit = 1;
  153. continue;
  154. }
  155. if (ch == ':')
  156. {
  157. curtok = src;
  158. if (!saw_xdigit)
  159. {
  160. if (colonp)
  161. return 0;
  162. colonp = tp;
  163. continue;
  164. }
  165. else if (*src == '\0')
  166. {
  167. return 0;
  168. }
  169. if (tp + W32NS_INT16SZ > endp)
  170. return 0;
  171. *tp++ = (uint8_t) (val >> 8) & 0xff;
  172. *tp++ = (uint8_t) val & 0xff;
  173. saw_xdigit = 0;
  174. val = 0;
  175. continue;
  176. }
  177. if (ch == '.' && ((tp + W32NS_INADDRSZ) <= endp) &&
  178. Inet_Pton4(curtok, (char*) tp) > 0)
  179. {
  180. tp += W32NS_INADDRSZ;
  181. saw_xdigit = 0;
  182. break; /* '\0' was seen by inet_pton4(). */
  183. }
  184. return 0;
  185. }
  186. if (saw_xdigit)
  187. {
  188. if (tp + W32NS_INT16SZ > endp)
  189. return 0;
  190. *tp++ = (uint8_t) (val >> 8) & 0xff;
  191. *tp++ = (uint8_t) val & 0xff;
  192. }
  193. if (colonp != NULL)
  194. {
  195. int i;
  196. /*
  197. * Since some memmove()'s erroneously fail to handle
  198. * overlapping regions, we'll do the shift by hand.
  199. */
  200. const int n = tp - colonp;
  201. if (tp == endp)
  202. return 0;
  203. for (i = 1; i <= n; i++)
  204. {
  205. endp[-i] = colonp[n - i];
  206. colonp[n - i] = 0;
  207. }
  208. tp = endp;
  209. }
  210. if (tp != endp)
  211. return 0;
  212. cg_memcpy(dst, tmp, W32NS_IN6ADDRSZ);
  213. return 1;
  214. }
  215. int Inet_Pton(int af, const char *src, void *dst)
  216. {
  217. switch (af)
  218. {
  219. case AF_INET:
  220. return Inet_Pton4(src, dst);
  221. case AF_INET6:
  222. return Inet_Pton6(src, dst);
  223. default:
  224. return -1;
  225. }
  226. }
  227. #endif
  228. /* Align a size_t to 4 byte boundaries for fussy arches */
  229. static inline void align_len(size_t *len)
  230. {
  231. if (*len % 4)
  232. *len += 4 - (*len % 4);
  233. }
  234. void *_cgmalloc(size_t size, const char *file, const char *func, const int line)
  235. {
  236. void *ret;
  237. align_len(&size);
  238. ret = malloc(size);
  239. if (unlikely(!ret))
  240. quit(1, "Failed to malloc size %d from %s %s:%d", (int)size, file, func, line);
  241. return ret;
  242. }
  243. void *_cgcalloc(const size_t memb, size_t size, const char *file, const char *func, const int line)
  244. {
  245. void *ret;
  246. align_len(&size);
  247. ret = calloc(memb, size);
  248. if (unlikely(!ret))
  249. quit(1, "Failed to calloc memb %d size %d from %s %s:%d", (int)memb, (int)size, file, func, line);
  250. return ret;
  251. }
  252. void *_cgrealloc(void *ptr, size_t size, const char *file, const char *func, const int line)
  253. {
  254. void *ret;
  255. align_len(&size);
  256. ret = realloc(ptr, size);
  257. if (unlikely(!ret))
  258. quit(1, "Failed to realloc size %d from %s %s:%d", (int)size, file, func, line);
  259. return ret;
  260. }
  261. struct tq_ent {
  262. void *data;
  263. struct list_head q_node;
  264. };
  265. #ifdef HAVE_LIBCURL
  266. struct timeval nettime;
  267. struct data_buffer {
  268. void *buf;
  269. size_t len;
  270. };
  271. struct upload_buffer {
  272. const void *buf;
  273. size_t len;
  274. };
  275. struct header_info {
  276. char *lp_path;
  277. int rolltime;
  278. char *reason;
  279. char *stratum_url;
  280. bool hadrolltime;
  281. bool canroll;
  282. bool hadexpire;
  283. };
  284. static void databuf_free(struct data_buffer *db)
  285. {
  286. if (!db)
  287. return;
  288. free(db->buf);
  289. memset(db, 0, sizeof(*db));
  290. }
  291. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  292. void *user_data)
  293. {
  294. struct data_buffer *db = user_data;
  295. size_t len = size * nmemb;
  296. size_t oldlen, newlen;
  297. void *newmem;
  298. static const unsigned char zero = 0;
  299. oldlen = db->len;
  300. newlen = oldlen + len;
  301. newmem = cgrealloc(db->buf, newlen + 1);
  302. db->buf = newmem;
  303. db->len = newlen;
  304. cg_memcpy(db->buf + oldlen, ptr, len);
  305. cg_memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  306. return len;
  307. }
  308. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  309. void *user_data)
  310. {
  311. struct upload_buffer *ub = user_data;
  312. unsigned int len = size * nmemb;
  313. if (len > ub->len)
  314. len = ub->len;
  315. if (len) {
  316. cg_memcpy(ptr, ub->buf, len);
  317. ub->buf += len;
  318. ub->len -= len;
  319. }
  320. return len;
  321. }
  322. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  323. {
  324. struct header_info *hi = user_data;
  325. size_t remlen, slen, ptrlen = size * nmemb;
  326. char *rem, *val = NULL, *key = NULL;
  327. void *tmp;
  328. val = cgcalloc(1, ptrlen);
  329. key = cgcalloc(1, ptrlen);
  330. tmp = memchr(ptr, ':', ptrlen);
  331. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  332. goto out;
  333. slen = tmp - ptr;
  334. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  335. goto out;
  336. cg_memcpy(key, ptr, slen); /* store & nul term key */
  337. key[slen] = 0;
  338. rem = ptr + slen + 1; /* trim value's leading whitespace */
  339. remlen = ptrlen - slen - 1;
  340. while ((remlen > 0) && (isspace(*rem))) {
  341. remlen--;
  342. rem++;
  343. }
  344. cg_memcpy(val, rem, remlen); /* store value, trim trailing ws */
  345. val[remlen] = 0;
  346. while ((*val) && (isspace(val[strlen(val) - 1])))
  347. val[strlen(val) - 1] = 0;
  348. if (!*val) /* skip blank value */
  349. goto out;
  350. if (opt_protocol)
  351. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  352. if (!strcasecmp("X-Roll-Ntime", key)) {
  353. hi->hadrolltime = true;
  354. if (!strncasecmp("N", val, 1))
  355. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  356. else {
  357. hi->canroll = true;
  358. /* Check to see if expire= is supported and if not, set
  359. * the rolltime to the default scantime */
  360. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  361. sscanf(val + 7, "%d", &hi->rolltime);
  362. hi->hadexpire = true;
  363. } else
  364. hi->rolltime = max_scantime;
  365. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  366. }
  367. }
  368. if (!strcasecmp("X-Long-Polling", key)) {
  369. hi->lp_path = val; /* steal memory reference */
  370. val = NULL;
  371. }
  372. if (!strcasecmp("X-Reject-Reason", key)) {
  373. hi->reason = val; /* steal memory reference */
  374. val = NULL;
  375. }
  376. if (!strcasecmp("X-Stratum", key)) {
  377. hi->stratum_url = val;
  378. val = NULL;
  379. }
  380. out:
  381. free(key);
  382. free(val);
  383. return ptrlen;
  384. }
  385. static void last_nettime(struct timeval *last)
  386. {
  387. rd_lock(&netacc_lock);
  388. last->tv_sec = nettime.tv_sec;
  389. last->tv_usec = nettime.tv_usec;
  390. rd_unlock(&netacc_lock);
  391. }
  392. static void set_nettime(void)
  393. {
  394. wr_lock(&netacc_lock);
  395. cgtime(&nettime);
  396. wr_unlock(&netacc_lock);
  397. }
  398. #if CURL_HAS_KEEPALIVE
  399. static void keep_curlalive(CURL *curl)
  400. {
  401. const int tcp_keepidle = 45;
  402. const int tcp_keepintvl = 30;
  403. const long int keepalive = 1;
  404. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
  405. curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, tcp_keepidle);
  406. curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, tcp_keepintvl);
  407. }
  408. #else
  409. static void keep_curlalive(CURL *curl)
  410. {
  411. SOCKETTYPE sock;
  412. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
  413. keep_sockalive(sock);
  414. }
  415. #endif
  416. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  417. __maybe_unused char *data, size_t size, void *userdata)
  418. {
  419. struct pool *pool = (struct pool *)userdata;
  420. switch(type) {
  421. case CURLINFO_HEADER_IN:
  422. case CURLINFO_DATA_IN:
  423. case CURLINFO_SSL_DATA_IN:
  424. pool->cgminer_pool_stats.net_bytes_received += size;
  425. break;
  426. case CURLINFO_HEADER_OUT:
  427. case CURLINFO_DATA_OUT:
  428. case CURLINFO_SSL_DATA_OUT:
  429. pool->cgminer_pool_stats.net_bytes_sent += size;
  430. break;
  431. case CURLINFO_TEXT:
  432. default:
  433. break;
  434. }
  435. return 0;
  436. }
  437. json_t *json_web_config(const char *url)
  438. {
  439. struct data_buffer all_data = {NULL, 0};
  440. char curl_err_str[CURL_ERROR_SIZE];
  441. long timeout = 60;
  442. json_error_t err;
  443. json_t *val;
  444. CURL *curl;
  445. int rc;
  446. memset(&err, 0, sizeof(err));
  447. curl = curl_easy_init();
  448. if (unlikely(!curl))
  449. quithere(1, "CURL initialisation failed");
  450. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  451. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  452. curl_easy_setopt(curl, CURLOPT_URL, url);
  453. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  454. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  455. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  456. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  457. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  458. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  459. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  460. val = NULL;
  461. rc = curl_easy_perform(curl);
  462. curl_easy_cleanup(curl);
  463. if (rc) {
  464. applog(LOG_ERR, "HTTP config request of '%s' failed: %s", url, curl_err_str);
  465. goto c_out;
  466. }
  467. if (!all_data.buf) {
  468. applog(LOG_ERR, "Empty config data received from '%s'", url);
  469. goto c_out;
  470. }
  471. val = JSON_LOADS(all_data.buf, &err);
  472. if (!val) {
  473. applog(LOG_ERR, "JSON config decode of '%s' failed(%d): %s", url,
  474. err.line, err.text);
  475. }
  476. databuf_free(&all_data);
  477. c_out:
  478. return val;
  479. }
  480. json_t *json_rpc_call(CURL *curl, const char *url,
  481. const char *userpass, const char *rpc_req,
  482. bool probe, bool longpoll, int *rolltime,
  483. struct pool *pool, bool share)
  484. {
  485. long timeout = longpoll ? (60 * 60) : 60;
  486. struct data_buffer all_data = {NULL, 0};
  487. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  488. char len_hdr[64], user_agent_hdr[128];
  489. char curl_err_str[CURL_ERROR_SIZE];
  490. struct curl_slist *headers = NULL;
  491. struct upload_buffer upload_data;
  492. json_t *val, *err_val, *res_val;
  493. bool probing = false;
  494. double byte_count;
  495. json_error_t err;
  496. int rc;
  497. memset(&err, 0, sizeof(err));
  498. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  499. if (probe)
  500. probing = !pool->probed;
  501. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  502. // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
  503. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  504. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  505. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  506. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  507. curl_easy_setopt(curl, CURLOPT_URL, url);
  508. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  509. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  510. /* Shares are staggered already and delays in submission can be costly
  511. * so do not delay them */
  512. if (!opt_delaynet || share)
  513. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  514. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  515. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  516. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  517. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  518. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  519. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  520. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  521. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  522. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  523. if (pool->rpc_proxy) {
  524. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  525. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  526. } else if (opt_socks_proxy) {
  527. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  528. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  529. }
  530. if (userpass) {
  531. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  532. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  533. }
  534. if (longpoll)
  535. keep_curlalive(curl);
  536. curl_easy_setopt(curl, CURLOPT_POST, 1);
  537. if (opt_protocol)
  538. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  539. upload_data.buf = rpc_req;
  540. upload_data.len = strlen(rpc_req);
  541. sprintf(len_hdr, "Content-Length: %lu",
  542. (unsigned long) upload_data.len);
  543. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  544. headers = curl_slist_append(headers,
  545. "Content-type: application/json");
  546. headers = curl_slist_append(headers,
  547. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  548. if (likely(global_hashrate)) {
  549. char ghashrate[255];
  550. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, global_hashrate);
  551. headers = curl_slist_append(headers, ghashrate);
  552. }
  553. headers = curl_slist_append(headers, len_hdr);
  554. headers = curl_slist_append(headers, user_agent_hdr);
  555. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  556. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  557. if (opt_delaynet) {
  558. /* Don't delay share submission, but still track the nettime */
  559. if (!share) {
  560. long long now_msecs, last_msecs;
  561. struct timeval now, last;
  562. cgtime(&now);
  563. last_nettime(&last);
  564. now_msecs = (long long)now.tv_sec * 1000;
  565. now_msecs += now.tv_usec / 1000;
  566. last_msecs = (long long)last.tv_sec * 1000;
  567. last_msecs += last.tv_usec / 1000;
  568. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  569. struct timespec rgtp;
  570. rgtp.tv_sec = 0;
  571. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  572. nanosleep(&rgtp, NULL);
  573. }
  574. }
  575. set_nettime();
  576. }
  577. rc = curl_easy_perform(curl);
  578. if (rc) {
  579. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  580. goto err_out;
  581. }
  582. if (!all_data.buf) {
  583. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  584. goto err_out;
  585. }
  586. pool->cgminer_pool_stats.times_sent++;
  587. if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
  588. pool->cgminer_pool_stats.bytes_sent += byte_count;
  589. pool->cgminer_pool_stats.times_received++;
  590. if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
  591. pool->cgminer_pool_stats.bytes_received += byte_count;
  592. if (probing) {
  593. pool->probed = true;
  594. /* If X-Long-Polling was found, activate long polling */
  595. if (hi.lp_path) {
  596. if (pool->hdr_path != NULL)
  597. free(pool->hdr_path);
  598. pool->hdr_path = hi.lp_path;
  599. } else
  600. pool->hdr_path = NULL;
  601. if (hi.stratum_url) {
  602. pool->stratum_url = hi.stratum_url;
  603. hi.stratum_url = NULL;
  604. }
  605. } else {
  606. if (hi.lp_path) {
  607. free(hi.lp_path);
  608. hi.lp_path = NULL;
  609. }
  610. if (hi.stratum_url) {
  611. free(hi.stratum_url);
  612. hi.stratum_url = NULL;
  613. }
  614. }
  615. *rolltime = hi.rolltime;
  616. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  617. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  618. pool->cgminer_pool_stats.canroll = hi.canroll;
  619. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  620. val = JSON_LOADS(all_data.buf, &err);
  621. if (!val) {
  622. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  623. if (opt_protocol)
  624. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
  625. goto err_out;
  626. }
  627. if (opt_protocol) {
  628. char *s = json_dumps(val, JSON_INDENT(3));
  629. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  630. free(s);
  631. }
  632. /* JSON-RPC valid response returns a non-null 'result',
  633. * and a null 'error'.
  634. */
  635. res_val = json_object_get(val, "result");
  636. err_val = json_object_get(val, "error");
  637. if (!res_val ||(err_val && !json_is_null(err_val))) {
  638. char *s;
  639. if (err_val)
  640. s = json_dumps(err_val, JSON_INDENT(3));
  641. else
  642. s = strdup("(unknown reason)");
  643. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  644. free(s);
  645. goto err_out;
  646. }
  647. if (hi.reason) {
  648. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  649. free(hi.reason);
  650. hi.reason = NULL;
  651. }
  652. successful_connect = true;
  653. databuf_free(&all_data);
  654. curl_slist_free_all(headers);
  655. curl_easy_reset(curl);
  656. return val;
  657. err_out:
  658. databuf_free(&all_data);
  659. curl_slist_free_all(headers);
  660. curl_easy_reset(curl);
  661. if (!successful_connect)
  662. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  663. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  664. return NULL;
  665. }
  666. #define PROXY_HTTP CURLPROXY_HTTP
  667. #define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0
  668. #define PROXY_SOCKS4 CURLPROXY_SOCKS4
  669. #define PROXY_SOCKS5 CURLPROXY_SOCKS5
  670. #define PROXY_SOCKS4A CURLPROXY_SOCKS4A
  671. #define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME
  672. #else /* HAVE_LIBCURL */
  673. #define PROXY_HTTP 0
  674. #define PROXY_HTTP_1_0 1
  675. #define PROXY_SOCKS4 2
  676. #define PROXY_SOCKS5 3
  677. #define PROXY_SOCKS4A 4
  678. #define PROXY_SOCKS5H 5
  679. #endif /* HAVE_LIBCURL */
  680. static struct {
  681. const char *name;
  682. proxytypes_t proxytype;
  683. } proxynames[] = {
  684. { "http:", PROXY_HTTP },
  685. { "http0:", PROXY_HTTP_1_0 },
  686. { "socks4:", PROXY_SOCKS4 },
  687. { "socks5:", PROXY_SOCKS5 },
  688. { "socks4a:", PROXY_SOCKS4A },
  689. { "socks5h:", PROXY_SOCKS5H },
  690. { NULL, 0 }
  691. };
  692. const char *proxytype(proxytypes_t proxytype)
  693. {
  694. int i;
  695. for (i = 0; proxynames[i].name; i++)
  696. if (proxynames[i].proxytype == proxytype)
  697. return proxynames[i].name;
  698. return "invalid";
  699. }
  700. char *get_proxy(char *url, struct pool *pool)
  701. {
  702. pool->rpc_proxy = NULL;
  703. char *split;
  704. int plen, len, i;
  705. for (i = 0; proxynames[i].name; i++) {
  706. plen = strlen(proxynames[i].name);
  707. if (strncmp(url, proxynames[i].name, plen) == 0) {
  708. if (!(split = strchr(url, '|')))
  709. return url;
  710. *split = '\0';
  711. len = split - url;
  712. pool->rpc_proxy = cgmalloc(1 + len - plen);
  713. strcpy(pool->rpc_proxy, url + plen);
  714. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  715. pool->rpc_proxytype = proxynames[i].proxytype;
  716. url = split + 1;
  717. break;
  718. }
  719. }
  720. return url;
  721. }
  722. /* Adequate size s==len*2 + 1 must be alloced to use this variant */
  723. void __bin2hex(char *s, const unsigned char *p, size_t len)
  724. {
  725. int i;
  726. static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  727. for (i = 0; i < (int)len; i++) {
  728. *s++ = hex[p[i] >> 4];
  729. *s++ = hex[p[i] & 0xF];
  730. }
  731. *s++ = '\0';
  732. }
  733. /* Returns a malloced array string of a binary value of arbitrary length. The
  734. * array is rounded up to a 4 byte size to appease architectures that need
  735. * aligned array sizes */
  736. char *bin2hex(const unsigned char *p, size_t len)
  737. {
  738. ssize_t slen;
  739. char *s;
  740. slen = len * 2 + 1;
  741. if (slen % 4)
  742. slen += 4 - (slen % 4);
  743. s = cgcalloc(slen, 1);
  744. __bin2hex(s, p, len);
  745. return s;
  746. }
  747. static const int hex2bin_tbl[256] = {
  748. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  749. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  750. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  751. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  752. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  753. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  754. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  755. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  756. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  757. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  758. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  759. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  760. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  761. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  762. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  763. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  764. };
  765. /* Does the reverse of bin2hex but does not allocate any ram */
  766. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  767. {
  768. int nibble1, nibble2;
  769. unsigned char idx;
  770. bool ret = false;
  771. while (*hexstr && len) {
  772. if (unlikely(!hexstr[1])) {
  773. applog(LOG_ERR, "hex2bin str truncated");
  774. return ret;
  775. }
  776. idx = *hexstr++;
  777. nibble1 = hex2bin_tbl[idx];
  778. idx = *hexstr++;
  779. nibble2 = hex2bin_tbl[idx];
  780. if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
  781. applog(LOG_ERR, "hex2bin scan failed");
  782. return ret;
  783. }
  784. *p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
  785. --len;
  786. }
  787. if (likely(len == 0 && *hexstr == 0))
  788. ret = true;
  789. return ret;
  790. }
  791. static bool _valid_hex(char *s, const char *file, const char *func, const int line)
  792. {
  793. bool ret = false;
  794. int i, len;
  795. if (unlikely(!s)) {
  796. applog(LOG_ERR, "Null string passed to valid_hex from"IN_FMT_FFL, file, func, line);
  797. return ret;
  798. }
  799. len = strlen(s);
  800. for (i = 0; i < len; i++) {
  801. unsigned char idx = s[i];
  802. if (unlikely(hex2bin_tbl[idx] < 0)) {
  803. applog(LOG_ERR, "Invalid char 0x%x passed to valid_hex from"IN_FMT_FFL, idx, file, func, line);
  804. return ret;
  805. }
  806. }
  807. ret = true;
  808. return ret;
  809. }
  810. #define valid_hex(s) _valid_hex(s, __FILE__, __func__, __LINE__)
  811. static bool _valid_ascii(char *s, const char *file, const char *func, const int line)
  812. {
  813. bool ret = false;
  814. int i, len;
  815. if (unlikely(!s)) {
  816. applog(LOG_ERR, "Null string passed to valid_ascii from"IN_FMT_FFL, file, func, line);
  817. return ret;
  818. }
  819. len = strlen(s);
  820. if (unlikely(!len)) {
  821. applog(LOG_ERR, "Zero length string passed to valid_ascii from"IN_FMT_FFL, file, func, line);
  822. return ret;
  823. }
  824. for (i = 0; i < len; i++) {
  825. unsigned char idx = s[i];
  826. if (unlikely(idx < 32 || idx > 126)) {
  827. applog(LOG_ERR, "Invalid char 0x%x passed to valid_ascii from"IN_FMT_FFL, idx, file, func, line);
  828. return ret;
  829. }
  830. }
  831. ret = true;
  832. return ret;
  833. }
  834. #define valid_ascii(s) _valid_ascii(s, __FILE__, __func__, __LINE__)
  835. static const int b58tobin_tbl[] = {
  836. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  837. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  838. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  839. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1,
  840. -1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1,
  841. 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1,
  842. -1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46,
  843. 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57
  844. };
  845. /* b58bin should always be at least 25 bytes long and already checked to be
  846. * valid. */
  847. void b58tobin(unsigned char *b58bin, const char *b58)
  848. {
  849. uint32_t c, bin32[7];
  850. int len, i, j;
  851. uint64_t t;
  852. memset(bin32, 0, 7 * sizeof(uint32_t));
  853. len = strlen(b58);
  854. for (i = 0; i < len; i++) {
  855. c = b58[i];
  856. c = b58tobin_tbl[c];
  857. for (j = 6; j >= 0; j--) {
  858. t = ((uint64_t)bin32[j]) * 58 + c;
  859. c = (t & 0x3f00000000ull) >> 32;
  860. bin32[j] = t & 0xffffffffull;
  861. }
  862. }
  863. *(b58bin++) = bin32[0] & 0xff;
  864. for (i = 1; i < 7; i++) {
  865. *((uint32_t *)b58bin) = htobe32(bin32[i]);
  866. b58bin += sizeof(uint32_t);
  867. }
  868. }
  869. void address_to_pubkeyhash(unsigned char *pkh, const char *addr)
  870. {
  871. unsigned char b58bin[25];
  872. memset(b58bin, 0, 25);
  873. b58tobin(b58bin, addr);
  874. pkh[0] = 0x76;
  875. pkh[1] = 0xa9;
  876. pkh[2] = 0x14;
  877. cg_memcpy(&pkh[3], &b58bin[1], 20);
  878. pkh[23] = 0x88;
  879. pkh[24] = 0xac;
  880. }
  881. /* For encoding nHeight into coinbase, return how many bytes were used */
  882. int ser_number(unsigned char *s, int32_t val)
  883. {
  884. int32_t *i32 = (int32_t *)&s[1];
  885. int len;
  886. if (val < 17) {
  887. s[0] = 0x50 + val;
  888. return 1;
  889. }
  890. if (val < 128)
  891. len = 1;
  892. else if (val < 32768)
  893. len = 2;
  894. else if (val < 8388608)
  895. len = 3;
  896. else
  897. len = 4;
  898. *i32 = htole32(val);
  899. s[0] = len++;
  900. return len;
  901. }
  902. /* For encoding variable length strings */
  903. unsigned char *ser_string(char *s, int *slen)
  904. {
  905. size_t len = strlen(s);
  906. unsigned char *ret;
  907. ret = cgmalloc(1 + len + 8); // Leave room for largest size
  908. if (len < 253) {
  909. ret[0] = len;
  910. cg_memcpy(ret + 1, s, len);
  911. *slen = len + 1;
  912. } else if (len < 0x10000) {
  913. uint16_t *u16 = (uint16_t *)&ret[1];
  914. ret[0] = 253;
  915. *u16 = htobe16(len);
  916. cg_memcpy(ret + 3, s, len);
  917. *slen = len + 3;
  918. } else {
  919. /* size_t is only 32 bit on many platforms anyway */
  920. uint32_t *u32 = (uint32_t *)&ret[1];
  921. ret[0] = 254;
  922. *u32 = htobe32(len);
  923. cg_memcpy(ret + 5, s, len);
  924. *slen = len + 5;
  925. }
  926. return ret;
  927. }
  928. bool fulltest(const unsigned char *hash, const unsigned char *target)
  929. {
  930. uint32_t *hash32 = (uint32_t *)hash;
  931. uint32_t *target32 = (uint32_t *)target;
  932. bool rc = true;
  933. int i;
  934. for (i = 28 / 4; i >= 0; i--) {
  935. uint32_t h32tmp = le32toh(hash32[i]);
  936. uint32_t t32tmp = le32toh(target32[i]);
  937. if (h32tmp > t32tmp) {
  938. rc = false;
  939. break;
  940. }
  941. if (h32tmp < t32tmp) {
  942. rc = true;
  943. break;
  944. }
  945. }
  946. if (opt_debug) {
  947. unsigned char hash_swap[32], target_swap[32];
  948. char *hash_str, *target_str;
  949. swab256(hash_swap, hash);
  950. swab256(target_swap, target);
  951. hash_str = bin2hex(hash_swap, 32);
  952. target_str = bin2hex(target_swap, 32);
  953. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  954. hash_str,
  955. target_str,
  956. rc ? "YES (hash <= target)" :
  957. "no (false positive; hash > target)");
  958. free(hash_str);
  959. free(target_str);
  960. }
  961. return rc;
  962. }
  963. struct thread_q *tq_new(void)
  964. {
  965. struct thread_q *tq;
  966. tq = cgcalloc(1, sizeof(*tq));
  967. INIT_LIST_HEAD(&tq->q);
  968. pthread_mutex_init(&tq->mutex, NULL);
  969. pthread_cond_init(&tq->cond, NULL);
  970. return tq;
  971. }
  972. void tq_free(struct thread_q *tq)
  973. {
  974. struct tq_ent *ent, *iter;
  975. if (!tq)
  976. return;
  977. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  978. list_del(&ent->q_node);
  979. free(ent);
  980. }
  981. pthread_cond_destroy(&tq->cond);
  982. pthread_mutex_destroy(&tq->mutex);
  983. memset(tq, 0, sizeof(*tq)); /* poison */
  984. free(tq);
  985. }
  986. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  987. {
  988. mutex_lock(&tq->mutex);
  989. tq->frozen = frozen;
  990. pthread_cond_signal(&tq->cond);
  991. mutex_unlock(&tq->mutex);
  992. }
  993. void tq_freeze(struct thread_q *tq)
  994. {
  995. tq_freezethaw(tq, true);
  996. }
  997. void tq_thaw(struct thread_q *tq)
  998. {
  999. tq_freezethaw(tq, false);
  1000. }
  1001. bool tq_push(struct thread_q *tq, void *data)
  1002. {
  1003. struct tq_ent *ent;
  1004. bool rc = true;
  1005. ent = cgcalloc(1, sizeof(*ent));
  1006. ent->data = data;
  1007. INIT_LIST_HEAD(&ent->q_node);
  1008. mutex_lock(&tq->mutex);
  1009. if (!tq->frozen) {
  1010. list_add_tail(&ent->q_node, &tq->q);
  1011. } else {
  1012. free(ent);
  1013. rc = false;
  1014. }
  1015. pthread_cond_signal(&tq->cond);
  1016. mutex_unlock(&tq->mutex);
  1017. return rc;
  1018. }
  1019. void *tq_pop(struct thread_q *tq)
  1020. {
  1021. struct tq_ent *ent;
  1022. void *rval = NULL;
  1023. int rc;
  1024. mutex_lock(&tq->mutex);
  1025. if (!list_empty(&tq->q))
  1026. goto pop;
  1027. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  1028. if (rc)
  1029. goto out;
  1030. if (list_empty(&tq->q))
  1031. goto out;
  1032. pop:
  1033. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  1034. rval = ent->data;
  1035. list_del(&ent->q_node);
  1036. free(ent);
  1037. out:
  1038. mutex_unlock(&tq->mutex);
  1039. return rval;
  1040. }
  1041. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  1042. {
  1043. cgsem_init(&thr->sem);
  1044. return pthread_create(&thr->pth, attr, start, arg);
  1045. }
  1046. void thr_info_cancel(struct thr_info *thr)
  1047. {
  1048. if (!thr)
  1049. return;
  1050. if (PTH(thr) != 0L) {
  1051. pthread_cancel(thr->pth);
  1052. PTH(thr) = 0L;
  1053. }
  1054. cgsem_destroy(&thr->sem);
  1055. }
  1056. void subtime(struct timeval *a, struct timeval *b)
  1057. {
  1058. timersub(a, b, b);
  1059. }
  1060. void addtime(struct timeval *a, struct timeval *b)
  1061. {
  1062. timeradd(a, b, b);
  1063. }
  1064. bool time_more(struct timeval *a, struct timeval *b)
  1065. {
  1066. return timercmp(a, b, >);
  1067. }
  1068. bool time_less(struct timeval *a, struct timeval *b)
  1069. {
  1070. return timercmp(a, b, <);
  1071. }
  1072. void copy_time(struct timeval *dest, const struct timeval *src)
  1073. {
  1074. cg_memcpy(dest, src, sizeof(struct timeval));
  1075. }
  1076. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  1077. {
  1078. val->tv_sec = spec->tv_sec;
  1079. val->tv_usec = spec->tv_nsec / 1000;
  1080. }
  1081. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  1082. {
  1083. spec->tv_sec = val->tv_sec;
  1084. spec->tv_nsec = val->tv_usec * 1000;
  1085. }
  1086. void us_to_timeval(struct timeval *val, int64_t us)
  1087. {
  1088. lldiv_t tvdiv = lldiv(us, 1000000);
  1089. val->tv_sec = tvdiv.quot;
  1090. val->tv_usec = tvdiv.rem;
  1091. }
  1092. void us_to_timespec(struct timespec *spec, int64_t us)
  1093. {
  1094. lldiv_t tvdiv = lldiv(us, 1000000);
  1095. spec->tv_sec = tvdiv.quot;
  1096. spec->tv_nsec = tvdiv.rem * 1000;
  1097. }
  1098. void ms_to_timespec(struct timespec *spec, int64_t ms)
  1099. {
  1100. lldiv_t tvdiv = lldiv(ms, 1000);
  1101. spec->tv_sec = tvdiv.quot;
  1102. spec->tv_nsec = tvdiv.rem * 1000000;
  1103. }
  1104. void ms_to_timeval(struct timeval *val, int64_t ms)
  1105. {
  1106. lldiv_t tvdiv = lldiv(ms, 1000);
  1107. val->tv_sec = tvdiv.quot;
  1108. val->tv_usec = tvdiv.rem * 1000;
  1109. }
  1110. static void spec_nscheck(struct timespec *ts)
  1111. {
  1112. while (ts->tv_nsec >= 1000000000) {
  1113. ts->tv_nsec -= 1000000000;
  1114. ts->tv_sec++;
  1115. }
  1116. while (ts->tv_nsec < 0) {
  1117. ts->tv_nsec += 1000000000;
  1118. ts->tv_sec--;
  1119. }
  1120. }
  1121. void timeraddspec(struct timespec *a, const struct timespec *b)
  1122. {
  1123. a->tv_sec += b->tv_sec;
  1124. a->tv_nsec += b->tv_nsec;
  1125. spec_nscheck(a);
  1126. }
  1127. #ifdef USE_BITMAIN_SOC
  1128. static int __maybe_unused timespec_to_ms(struct timespec *ts)
  1129. {
  1130. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  1131. }
  1132. /* Subtract b from a */
  1133. static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
  1134. {
  1135. a->tv_sec -= b->tv_sec;
  1136. a->tv_nsec -= b->tv_nsec;
  1137. spec_nscheck(a);
  1138. }
  1139. #else /* USE_BITMAIN_SOC */
  1140. static int timespec_to_ms(struct timespec *ts)
  1141. {
  1142. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  1143. }
  1144. static int64_t timespec_to_us(struct timespec *ts)
  1145. {
  1146. return (int64_t)ts->tv_sec * 1000000 + ts->tv_nsec / 1000;
  1147. }
  1148. /* Subtract b from a */
  1149. static void timersubspec(struct timespec *a, const struct timespec *b)
  1150. {
  1151. a->tv_sec -= b->tv_sec;
  1152. a->tv_nsec -= b->tv_nsec;
  1153. spec_nscheck(a);
  1154. }
  1155. #endif /* USE_BITMAIN_SOC */
  1156. char *Strcasestr(char *haystack, const char *needle)
  1157. {
  1158. char *lowhay, *lowneedle, *ret;
  1159. int hlen, nlen, i, ofs;
  1160. if (unlikely(!haystack || !needle))
  1161. return NULL;
  1162. hlen = strlen(haystack);
  1163. nlen = strlen(needle);
  1164. if (!hlen || !nlen)
  1165. return NULL;
  1166. lowhay = alloca(hlen);
  1167. lowneedle = alloca(nlen);
  1168. for (i = 0; i < hlen; i++)
  1169. lowhay[i] = tolower(haystack[i]);
  1170. for (i = 0; i < nlen; i++)
  1171. lowneedle[i] = tolower(needle[i]);
  1172. ret = strstr(lowhay, lowneedle);
  1173. if (ret)
  1174. {
  1175. ofs = ret - lowhay;
  1176. ret = haystack + ofs;
  1177. }
  1178. free(lowhay);
  1179. free(lowneedle);
  1180. return ret;
  1181. }
  1182. char *Strsep(char **stringp, const char *delim)
  1183. {
  1184. char *ret = *stringp;
  1185. char *p;
  1186. p = (ret != NULL) ? strpbrk(ret, delim) : NULL;
  1187. if (p == NULL)
  1188. *stringp = NULL;
  1189. else {
  1190. *p = '\0';
  1191. *stringp = p + 1;
  1192. }
  1193. return ret;
  1194. }
  1195. /* Get timespec specifically for use by cond_timedwait functions which use
  1196. * CLOCK_REALTIME for expiry */
  1197. void cgcond_time(struct timespec *abstime)
  1198. {
  1199. clock_gettime(CLOCK_REALTIME, abstime);
  1200. }
  1201. #ifdef USE_GEKKO
  1202. /* Get CLOCK_REALTIME for display purposes */
  1203. void cgtime_real(struct timeval *tv)
  1204. {
  1205. struct timespec tp;
  1206. clock_gettime(CLOCK_REALTIME, &tp);
  1207. tv->tv_sec = tp.tv_sec;
  1208. tv->tv_usec = tp.tv_nsec / 1000;
  1209. }
  1210. #endif
  1211. #ifdef WIN32
  1212. /* Mingw32 has no strsep so create our own custom one */
  1213. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  1214. #define EPOCHFILETIME (116444736000000000LL)
  1215. /* These are cgminer specific sleep functions that use an absolute nanosecond
  1216. * resolution timer to avoid poor usleep accuracy and overruns. */
  1217. /* Return the system time as an lldiv_t in decimicroseconds. */
  1218. static void decius_time(lldiv_t *lidiv)
  1219. {
  1220. FILETIME ft;
  1221. LARGE_INTEGER li;
  1222. GetSystemTimeAsFileTime(&ft);
  1223. li.LowPart = ft.dwLowDateTime;
  1224. li.HighPart = ft.dwHighDateTime;
  1225. li.QuadPart -= EPOCHFILETIME;
  1226. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1227. *lidiv = lldiv(li.QuadPart, 10000000);
  1228. }
  1229. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  1230. * with tz set to NULL, and windows' default resolution is only 15ms, this
  1231. * gives us higher resolution times on windows. */
  1232. void cgtime(struct timeval *tv)
  1233. {
  1234. lldiv_t lidiv;
  1235. decius_time(&lidiv);
  1236. tv->tv_sec = lidiv.quot;
  1237. tv->tv_usec = lidiv.rem / 10;
  1238. }
  1239. #else /* WIN32 */
  1240. void cgtime(struct timeval *tv)
  1241. {
  1242. cgtimer_t cgt;
  1243. cgtimer_time(&cgt);
  1244. timespec_to_val(tv, &cgt);
  1245. }
  1246. int cgtimer_to_ms(cgtimer_t *cgt)
  1247. {
  1248. return timespec_to_ms(cgt);
  1249. }
  1250. /* Subtracts b from a and stores it in res. */
  1251. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1252. {
  1253. res->tv_sec = a->tv_sec - b->tv_sec;
  1254. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  1255. if (res->tv_nsec < 0) {
  1256. res->tv_nsec += 1000000000;
  1257. res->tv_sec--;
  1258. }
  1259. }
  1260. #endif /* WIN32 */
  1261. #if defined(CLOCK_MONOTONIC) && !defined(__FreeBSD__) && !defined(__APPLE__) && !defined(WIN32) /* Essentially just linux */
  1262. //#ifdef CLOCK_MONOTONIC /* Essentially just linux */
  1263. void cgtimer_time(cgtimer_t *ts_start)
  1264. {
  1265. clock_gettime(CLOCK_MONOTONIC, ts_start);
  1266. }
  1267. static void nanosleep_abstime(struct timespec *ts_end)
  1268. {
  1269. int ret;
  1270. do {
  1271. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  1272. } while (ret == EINTR);
  1273. }
  1274. /* Reentrant version of cgsleep functions allow start time to be set separately
  1275. * from the beginning of the actual sleep, allowing scheduling delays to be
  1276. * counted in the sleep. */
  1277. #ifdef USE_BITMAIN_SOC
  1278. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1279. {
  1280. struct timespec ts_end;
  1281. ms_to_timespec(&ts_end, ms);
  1282. timeraddspec(&ts_end, ts_start);
  1283. nanosleep_abstime(&ts_end);
  1284. }
  1285. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1286. {
  1287. struct timespec ts_end;
  1288. us_to_timespec(&ts_end, us);
  1289. timeraddspec(&ts_end, ts_start);
  1290. nanosleep_abstime(&ts_end);
  1291. }
  1292. #else /* USE_BITMAIN_SOC */
  1293. int cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1294. {
  1295. struct timespec ts_end, ts_diff;
  1296. int msdiff;
  1297. ms_to_timespec(&ts_end, ms);
  1298. timeraddspec(&ts_end, ts_start);
  1299. cgtimer_time(&ts_diff);
  1300. /* Should be a negative value if we still have to sleep */
  1301. timersubspec(&ts_diff, &ts_end);
  1302. msdiff = -timespec_to_ms(&ts_diff);
  1303. if (msdiff <= 0)
  1304. return 0;
  1305. nanosleep_abstime(&ts_end);
  1306. return msdiff;
  1307. }
  1308. int64_t cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1309. {
  1310. struct timespec ts_end, ts_diff;
  1311. int64_t usdiff;
  1312. us_to_timespec(&ts_end, us);
  1313. timeraddspec(&ts_end, ts_start);
  1314. cgtimer_time(&ts_diff);
  1315. usdiff = -timespec_to_us(&ts_diff);
  1316. if (usdiff <= 0)
  1317. return 0;
  1318. nanosleep_abstime(&ts_end);
  1319. return usdiff;
  1320. }
  1321. #endif /* USE_BITMAIN_SOC */
  1322. #else /* CLOCK_MONOTONIC */
  1323. #ifdef __MACH__
  1324. #include <mach/clock.h>
  1325. #include <mach/mach.h>
  1326. void cgtimer_time(cgtimer_t *ts_start)
  1327. {
  1328. clock_serv_t cclock;
  1329. mach_timespec_t mts;
  1330. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  1331. clock_get_time(cclock, &mts);
  1332. mach_port_deallocate(mach_task_self(), cclock);
  1333. ts_start->tv_sec = mts.tv_sec;
  1334. ts_start->tv_nsec = mts.tv_nsec;
  1335. }
  1336. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  1337. void cgtimer_time(cgtimer_t *ts_start)
  1338. {
  1339. struct timeval tv;
  1340. cgtime(&tv);
  1341. ts_start->tv_sec = tv.tv_sec;
  1342. ts_start->tv_nsec = tv.tv_usec * 1000;
  1343. }
  1344. #endif /* __MACH__ */
  1345. #ifdef WIN32
  1346. /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
  1347. * typedef, allowing us to have sub-microsecond resolution for times, do simple
  1348. * arithmetic for timer calculations, and use windows' own hTimers to get
  1349. * accurate absolute timeouts. */
  1350. int cgtimer_to_ms(cgtimer_t *cgt)
  1351. {
  1352. return (int)(cgt->QuadPart / 10000LL);
  1353. }
  1354. /* Subtracts b from a and stores it in res. */
  1355. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1356. {
  1357. res->QuadPart = a->QuadPart - b->QuadPart;
  1358. }
  1359. /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
  1360. * timeouts with hTimers. */
  1361. void cgtimer_time(cgtimer_t *ts_start)
  1362. {
  1363. FILETIME ft;
  1364. GetSystemTimeAsFileTime(&ft);
  1365. ts_start->LowPart = ft.dwLowDateTime;
  1366. ts_start->HighPart = ft.dwHighDateTime;
  1367. }
  1368. static void liSleep(LARGE_INTEGER *li, int timeout)
  1369. {
  1370. HANDLE hTimer;
  1371. DWORD ret;
  1372. if (unlikely(timeout <= 0))
  1373. return;
  1374. hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  1375. if (unlikely(!hTimer))
  1376. quit(1, "Failed to create hTimer in liSleep");
  1377. ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
  1378. if (unlikely(!ret))
  1379. quit(1, "Failed to SetWaitableTimer in liSleep");
  1380. /* We still use a timeout as a sanity check in case the system time
  1381. * is changed while we're running */
  1382. ret = WaitForSingleObject(hTimer, timeout);
  1383. if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
  1384. quit(1, "Failed to WaitForSingleObject in liSleep");
  1385. CloseHandle(hTimer);
  1386. }
  1387. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1388. {
  1389. LARGE_INTEGER li;
  1390. li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
  1391. liSleep(&li, ms);
  1392. }
  1393. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1394. {
  1395. LARGE_INTEGER li;
  1396. int ms;
  1397. li.QuadPart = ts_start->QuadPart + us * 10LL;
  1398. ms = us / 1000;
  1399. if (!ms)
  1400. ms = 1;
  1401. liSleep(&li, ms);
  1402. }
  1403. #else /* WIN32 */
  1404. static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  1405. {
  1406. struct timespec now;
  1407. timeraddspec(ts_diff, ts_start);
  1408. cgtimer_time(&now);
  1409. timersubspec(ts_diff, &now);
  1410. if (unlikely(ts_diff->tv_sec < 0))
  1411. return;
  1412. nanosleep(ts_diff, NULL);
  1413. }
  1414. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1415. {
  1416. struct timespec ts_diff;
  1417. ms_to_timespec(&ts_diff, ms);
  1418. cgsleep_spec(&ts_diff, ts_start);
  1419. }
  1420. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1421. {
  1422. struct timespec ts_diff;
  1423. us_to_timespec(&ts_diff, us);
  1424. cgsleep_spec(&ts_diff, ts_start);
  1425. }
  1426. #endif /* WIN32 */
  1427. #endif /* CLOCK_MONOTONIC */
  1428. void cgsleep_ms(int ms)
  1429. {
  1430. cgtimer_t ts_start;
  1431. cgsleep_prepare_r(&ts_start);
  1432. cgsleep_ms_r(&ts_start, ms);
  1433. }
  1434. static void busywait_us(int64_t us)
  1435. {
  1436. struct timeval diff, end, now;
  1437. cgtime(&end);
  1438. us_to_timeval(&diff, us);
  1439. addtime(&diff, &end);
  1440. do {
  1441. sched_yield();
  1442. cgtime(&now);
  1443. } while (time_less(&now, &end));
  1444. }
  1445. void cgsleep_us(int64_t us)
  1446. {
  1447. cgtimer_t ts_start;
  1448. /* Most timer resolution is unlikely to be able to sleep accurately
  1449. * for less than 1ms so busywait instead. */
  1450. if (us < 1000)
  1451. return busywait_us(us);
  1452. cgsleep_prepare_r(&ts_start);
  1453. cgsleep_us_r(&ts_start, us);
  1454. }
  1455. /* Returns the microseconds difference between end and start times as a double */
  1456. double us_tdiff(struct timeval *end, struct timeval *start)
  1457. {
  1458. /* Sanity check. We should only be using this for small differences so
  1459. * limit the max to 60 seconds. */
  1460. if (unlikely(end->tv_sec - start->tv_sec > 60))
  1461. return 60000000;
  1462. return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
  1463. }
  1464. /* Returns the milliseconds difference between end and start times */
  1465. int ms_tdiff(struct timeval *end, struct timeval *start)
  1466. {
  1467. /* Like us_tdiff, limit to 1 hour. */
  1468. if (unlikely(end->tv_sec - start->tv_sec > 3600))
  1469. return 3600000;
  1470. return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
  1471. }
  1472. /* Returns the seconds difference between end and start times as a double */
  1473. double tdiff(struct timeval *end, struct timeval *start)
  1474. {
  1475. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1476. }
  1477. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1478. {
  1479. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1480. char url_address[256], port[6];
  1481. int url_len, port_len = 0;
  1482. *sockaddr_url = url;
  1483. url_begin = strstr(url, "//");
  1484. if (!url_begin)
  1485. url_begin = url;
  1486. else
  1487. url_begin += 2;
  1488. /* Look for numeric ipv6 entries */
  1489. ipv6_begin = strstr(url_begin, "[");
  1490. ipv6_end = strstr(url_begin, "]");
  1491. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1492. url_end = strstr(ipv6_end, ":");
  1493. else
  1494. url_end = strstr(url_begin, ":");
  1495. if (url_end) {
  1496. url_len = url_end - url_begin;
  1497. port_len = strlen(url_begin) - url_len - 1;
  1498. if (port_len < 1)
  1499. return false;
  1500. port_start = url_end + 1;
  1501. } else
  1502. url_len = strlen(url_begin);
  1503. if (url_len < 1)
  1504. return false;
  1505. /* Get rid of the [] */
  1506. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) {
  1507. url_len -= 2;
  1508. url_begin++;
  1509. }
  1510. snprintf(url_address, 254, "%.*s", url_len, url_begin);
  1511. if (port_len) {
  1512. char *slash;
  1513. snprintf(port, 6, "%.*s", port_len, port_start);
  1514. slash = strpbrk(port, "/#");
  1515. if (slash)
  1516. *slash = '\0';
  1517. } else
  1518. strcpy(port, "80");
  1519. *sockaddr_port = strdup(port);
  1520. *sockaddr_url = strdup(url_address);
  1521. return true;
  1522. }
  1523. enum send_ret {
  1524. SEND_OK,
  1525. SEND_SELECTFAIL,
  1526. SEND_SENDFAIL,
  1527. SEND_INACTIVE
  1528. };
  1529. /* Send a single command across a socket, appending \n to it. This should all
  1530. * be done under stratum lock except when first establishing the socket */
  1531. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1532. {
  1533. SOCKETTYPE sock = pool->sock;
  1534. ssize_t ssent = 0;
  1535. strcat(s, "\n");
  1536. len++;
  1537. while (len > 0 ) {
  1538. struct timeval timeout = {1, 0};
  1539. ssize_t sent;
  1540. fd_set wd;
  1541. retry:
  1542. FD_ZERO(&wd);
  1543. FD_SET(sock, &wd);
  1544. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1545. if (interrupted())
  1546. goto retry;
  1547. return SEND_SELECTFAIL;
  1548. }
  1549. #ifdef __APPLE__
  1550. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1551. #elif WIN32
  1552. sent = send(pool->sock, s + ssent, len, 0);
  1553. #else
  1554. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1555. #endif
  1556. if (sent < 0) {
  1557. if (!sock_blocks())
  1558. return SEND_SENDFAIL;
  1559. sent = 0;
  1560. }
  1561. ssent += sent;
  1562. len -= sent;
  1563. }
  1564. pool->cgminer_pool_stats.times_sent++;
  1565. pool->cgminer_pool_stats.bytes_sent += ssent;
  1566. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1567. return SEND_OK;
  1568. }
  1569. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1570. {
  1571. enum send_ret ret = SEND_INACTIVE;
  1572. if (opt_protocol)
  1573. applog(LOG_DEBUG, "SEND: %s", s);
  1574. mutex_lock(&pool->stratum_lock);
  1575. if (pool->stratum_active)
  1576. ret = __stratum_send(pool, s, len);
  1577. mutex_unlock(&pool->stratum_lock);
  1578. /* This is to avoid doing applog under stratum_lock */
  1579. switch (ret) {
  1580. default:
  1581. case SEND_OK:
  1582. break;
  1583. case SEND_SELECTFAIL:
  1584. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1585. suspend_stratum(pool);
  1586. break;
  1587. case SEND_SENDFAIL:
  1588. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1589. suspend_stratum(pool);
  1590. break;
  1591. case SEND_INACTIVE:
  1592. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1593. break;
  1594. }
  1595. return (ret == SEND_OK);
  1596. }
  1597. static bool socket_full(struct pool *pool, int wait)
  1598. {
  1599. SOCKETTYPE sock = pool->sock;
  1600. struct timeval timeout;
  1601. fd_set rd;
  1602. if (unlikely(wait < 0))
  1603. wait = 0;
  1604. FD_ZERO(&rd);
  1605. FD_SET(sock, &rd);
  1606. timeout.tv_usec = 0;
  1607. timeout.tv_sec = wait;
  1608. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1609. return true;
  1610. return false;
  1611. }
  1612. /* Check to see if Santa's been good to you */
  1613. bool sock_full(struct pool *pool)
  1614. {
  1615. if (strlen(pool->sockbuf))
  1616. return true;
  1617. return (socket_full(pool, 0));
  1618. }
  1619. static void clear_sockbuf(struct pool *pool)
  1620. {
  1621. if (likely(pool->sockbuf))
  1622. strcpy(pool->sockbuf, "");
  1623. }
  1624. static void clear_sock(struct pool *pool)
  1625. {
  1626. ssize_t n;
  1627. mutex_lock(&pool->stratum_lock);
  1628. do {
  1629. if (pool->sock)
  1630. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1631. else
  1632. n = 0;
  1633. } while (n > 0);
  1634. mutex_unlock(&pool->stratum_lock);
  1635. clear_sockbuf(pool);
  1636. }
  1637. /* Realloc memory to new size and zero any extra memory added */
  1638. void ckrecalloc(void **ptr, size_t old, size_t new, const char *file, const char *func, const int line)
  1639. {
  1640. if (new == old)
  1641. return;
  1642. *ptr = _cgrealloc(*ptr, new, file, func, line);
  1643. if (new > old)
  1644. memset(*ptr + old, 0, new - old);
  1645. }
  1646. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1647. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1648. * and zeroing the new memory */
  1649. static void recalloc_sock(struct pool *pool, size_t len)
  1650. {
  1651. size_t old, new;
  1652. old = strlen(pool->sockbuf);
  1653. new = old + len + 1;
  1654. if (new < pool->sockbuf_size)
  1655. return;
  1656. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1657. // Avoid potentially recursive locking
  1658. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1659. pool->sockbuf = cgrealloc(pool->sockbuf, new);
  1660. memset(pool->sockbuf + old, 0, new - old);
  1661. pool->sockbuf_size = new;
  1662. }
  1663. /* Peeks at a socket to find the first end of line and then reads just that
  1664. * from the socket and returns that as a malloced char */
  1665. char *recv_line(struct pool *pool)
  1666. {
  1667. char *tok, *sret = NULL;
  1668. ssize_t len, buflen;
  1669. int waited = 0;
  1670. if (!strstr(pool->sockbuf, "\n")) {
  1671. struct timeval rstart, now;
  1672. cgtime(&rstart);
  1673. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1674. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1675. goto out;
  1676. }
  1677. do {
  1678. char s[RBUFSIZE];
  1679. size_t slen;
  1680. ssize_t n;
  1681. memset(s, 0, RBUFSIZE);
  1682. n = recv(pool->sock, s, RECVSIZE, 0);
  1683. if (!n) {
  1684. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1685. suspend_stratum(pool);
  1686. break;
  1687. }
  1688. cgtime(&now);
  1689. waited = tdiff(&now, &rstart);
  1690. if (n < 0) {
  1691. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1692. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1693. suspend_stratum(pool);
  1694. break;
  1695. }
  1696. } else {
  1697. slen = strlen(s);
  1698. recalloc_sock(pool, slen);
  1699. strcat(pool->sockbuf, s);
  1700. }
  1701. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1702. }
  1703. buflen = strlen(pool->sockbuf);
  1704. tok = strtok(pool->sockbuf, "\n");
  1705. if (!tok) {
  1706. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1707. goto out;
  1708. }
  1709. sret = strdup(tok);
  1710. len = strlen(sret);
  1711. /* Copy what's left in the buffer after the \n, including the
  1712. * terminating \0 */
  1713. if (buflen > len + 1)
  1714. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1715. else
  1716. strcpy(pool->sockbuf, "");
  1717. pool->cgminer_pool_stats.times_received++;
  1718. pool->cgminer_pool_stats.bytes_received += len;
  1719. pool->cgminer_pool_stats.net_bytes_received += len;
  1720. out:
  1721. if (!sret)
  1722. clear_sock(pool);
  1723. else if (opt_protocol)
  1724. applog(LOG_DEBUG, "RECVD: %s", sret);
  1725. return sret;
  1726. }
  1727. /* Extracts a string value from a json array with error checking. To be used
  1728. * when the value of the string returned is only examined and not to be stored.
  1729. * See json_array_string below */
  1730. static char *__json_array_string(json_t *val, unsigned int entry)
  1731. {
  1732. json_t *arr_entry;
  1733. if (json_is_null(val))
  1734. return NULL;
  1735. if (!json_is_array(val))
  1736. return NULL;
  1737. if (entry > json_array_size(val))
  1738. return NULL;
  1739. arr_entry = json_array_get(val, entry);
  1740. if (!json_is_string(arr_entry))
  1741. return NULL;
  1742. return (char *)json_string_value(arr_entry);
  1743. }
  1744. /* Creates a freshly malloced dup of __json_array_string */
  1745. static char *json_array_string(json_t *val, unsigned int entry)
  1746. {
  1747. char *buf = __json_array_string(val, entry);
  1748. if (buf)
  1749. return strdup(buf);
  1750. return NULL;
  1751. }
  1752. static char *blank_merkle = "0000000000000000000000000000000000000000000000000000000000000000";
  1753. #ifdef HAVE_LIBCURL
  1754. static void decode_exit(struct pool *pool, char *cb)
  1755. {
  1756. CURL *curl = curl_easy_init();
  1757. char *decreq, *s;
  1758. json_t *val;
  1759. int dummy;
  1760. if (!opt_btcd && !sleep(3) && !opt_btcd) {
  1761. applog(LOG_ERR, "No bitcoind specified, unable to decode coinbase.");
  1762. exit(1);
  1763. }
  1764. decreq = cgmalloc(strlen(cb) + 256);
  1765. sprintf(decreq, "{\"id\": 0, \"method\": \"decoderawtransaction\", \"params\": [\"%s\"]}\n",
  1766. cb);
  1767. val = json_rpc_call(curl, opt_btcd->rpc_url, opt_btcd->rpc_userpass, decreq,
  1768. false, false, &dummy, opt_btcd, false);
  1769. free(decreq);
  1770. if (!val) {
  1771. applog(LOG_ERR, "Failed json_rpc_call to btcd %s", opt_btcd->rpc_url);
  1772. exit(1);
  1773. }
  1774. s = json_dumps(val, JSON_INDENT(4));
  1775. printf("Pool %s:\n%s\n", pool->rpc_url, s);
  1776. free(s);
  1777. exit(0);
  1778. }
  1779. #else
  1780. static void decode_exit(struct pool __maybe_unused *pool, char __maybe_unused *b)
  1781. {
  1782. }
  1783. #endif
  1784. static int calculate_num_bits(int num)
  1785. {
  1786. int ret=0;
  1787. while(num != 0)
  1788. {
  1789. ret++;
  1790. num /= 16;
  1791. }
  1792. return ret;
  1793. }
  1794. static void get_vmask(struct pool *pool, char *bbversion)
  1795. {
  1796. char defaultStr[9]= "00000000";
  1797. int bversion, num_bits, i, j;
  1798. uint8_t buffer[4] = {};
  1799. uint32_t uiMagicNum;
  1800. char *tmpstr;
  1801. uint32_t *p1;
  1802. p1 = (uint32_t *)buffer;
  1803. bversion = strtol(bbversion, NULL, 16);
  1804. for (i = 0; i < 4; i++) {
  1805. uiMagicNum = bversion | pool->vmask_003[i];
  1806. //printf("[ccx]uiMagicNum:0x%x. \n", uiMagicNum);
  1807. *p1 = bswap_32(uiMagicNum);
  1808. //printf("[ccx]*p1:0x%x. \n", *p1);
  1809. switch(i) {
  1810. case 0:
  1811. pool->vmask_001[8] = *p1;
  1812. break;
  1813. case 1:
  1814. pool->vmask_001[4] = *p1;
  1815. break;
  1816. case 2:
  1817. pool->vmask_001[2] = *p1;
  1818. break;
  1819. case 3:
  1820. pool->vmask_001[0] = *p1;
  1821. break;
  1822. default:
  1823. break;
  1824. }
  1825. }
  1826. for (i = 0; i < 16; i++) {
  1827. if ((i!= 2) && (i!=4) && (i!=8))
  1828. pool->vmask_001[i] = pool->vmask_001[0];
  1829. }
  1830. for (i = 0; i < 16; i++)
  1831. memcpy(pool->vmask_002[i], defaultStr, 9);
  1832. for (i = 0; i < 3; i++) {
  1833. char cMask[12];
  1834. tmpstr = (char *)cgcalloc(9, 1);
  1835. num_bits = calculate_num_bits(pool->vmask_003[i]);
  1836. for (j = 0; j < (8-num_bits); j++)
  1837. tmpstr[j] = '0';
  1838. snprintf(cMask, 9, "%x", pool->vmask_003[i]);
  1839. memcpy(tmpstr + 8 - num_bits, cMask, num_bits);
  1840. tmpstr[8] = '\0';
  1841. //printf("[ccx]tmpstr:%s. \n", tmpstr);
  1842. switch(i) {
  1843. case 0:
  1844. memcpy(pool->vmask_002[8], tmpstr, 9);
  1845. break;
  1846. case 1:
  1847. memcpy(pool->vmask_002[4], tmpstr, 9);
  1848. break;
  1849. case 2:
  1850. memcpy(pool->vmask_002[2], tmpstr, 9);
  1851. break;
  1852. default:
  1853. break;
  1854. }
  1855. free(tmpstr);
  1856. }
  1857. }
  1858. static bool set_vmask(struct pool *pool, json_t *val)
  1859. {
  1860. int mask, tmpMask = 0, cnt = 0, i, rem;
  1861. const char *version_mask;
  1862. version_mask = json_string_value(val);
  1863. applog(LOG_INFO, "Pool %d version_mask:%s.", pool->pool_no, version_mask);
  1864. mask = strtol(version_mask, NULL, 16);
  1865. if (!mask)
  1866. return false;
  1867. pool->vmask_003[0] = mask;
  1868. while (mask % 16 == 0) {
  1869. cnt++;
  1870. mask /= 16;
  1871. }
  1872. if ((rem = mask % 16))
  1873. tmpMask = rem;
  1874. else if ((rem = mask % 8))
  1875. tmpMask = rem;
  1876. else if ((rem = mask % 4))
  1877. tmpMask = rem;
  1878. else if ((rem = mask % 2))
  1879. tmpMask = rem;
  1880. for (i = 0; i < cnt; i++)
  1881. tmpMask *= 16;
  1882. pool->vmask_003[2] = tmpMask;
  1883. pool->vmask_003[1] = pool->vmask_003[0] - tmpMask;
  1884. return true;
  1885. }
  1886. #ifdef USE_VMASK
  1887. #define STRATUM_VERSION_ROLLING "version-rolling"
  1888. #define STRATUM_VERSION_ROLLING_LEN (sizeof(STRATUM_VERSION_ROLLING) - 1)
  1889. /**
  1890. * Configures stratum mining based on connected hardware capabilities
  1891. * (version rolling etc.)
  1892. *
  1893. * Sample communication
  1894. * Request:
  1895. * {"id": 1, "method": "mining.configure", "params": [ ["version-rolling"], "version-rolling.mask": "ffffffff" }]}\n
  1896. * Response:
  1897. * {"id": 1, "result": { "version-rolling": True, "version-rolling.mask": "00003000" }, "error": null}\n
  1898. *
  1899. * @param pool
  1900. *
  1901. *
  1902. * @return
  1903. */
  1904. static bool configure_stratum_mining(struct pool *pool)
  1905. {
  1906. char s[RBUFSIZE];
  1907. char *response_str = NULL;
  1908. bool config_status = false;
  1909. bool version_rolling_status = false;
  1910. bool version_mask_valid = false;
  1911. const char *key;
  1912. json_t *response, *value, *res_val, *err_val;
  1913. json_error_t err;
  1914. #ifdef USE_GEKKO
  1915. if (!opt_gekko_boost)
  1916. return true;
  1917. #endif
  1918. snprintf(s, RBUFSIZE,
  1919. "{\"id\": %d, \"method\": \"mining.configure\", \"params\": "
  1920. "[[\""STRATUM_VERSION_ROLLING"\"], "
  1921. "{\""STRATUM_VERSION_ROLLING".mask\": \"%x\""
  1922. "}]}",
  1923. swork_id++, 0xffffffff);
  1924. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1925. applog(LOG_DEBUG, "Failed to send mining.configure");
  1926. goto out;
  1927. }
  1928. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1929. applog(LOG_DEBUG, "Timed out waiting for response in %s", __FUNCTION__);
  1930. goto out;
  1931. }
  1932. response_str = recv_line(pool);
  1933. if (!response_str)
  1934. goto out;
  1935. response = JSON_LOADS(response_str, &err);
  1936. free(response_str);
  1937. res_val = json_object_get(response, "result");
  1938. err_val = json_object_get(response, "error");
  1939. if (!res_val || json_is_null(res_val) ||
  1940. (err_val && !json_is_null(err_val))) {
  1941. char *ss;
  1942. if (err_val)
  1943. ss = json_dumps(err_val, JSON_INDENT(3));
  1944. else
  1945. ss = strdup("(unknown reason)");
  1946. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1947. free(ss);
  1948. goto json_response_error;
  1949. }
  1950. json_object_foreach(res_val, key, value) {
  1951. if (!strcasecmp(key, STRATUM_VERSION_ROLLING) &&
  1952. strlen(key) == STRATUM_VERSION_ROLLING_LEN)
  1953. version_rolling_status = json_boolean_value(value);
  1954. else if (!strcasecmp(key, STRATUM_VERSION_ROLLING ".mask"))
  1955. pool->vmask = version_mask_valid = set_vmask(pool, value);
  1956. else
  1957. applog(LOG_ERR, "JSON-RPC unexpected mining.configure value: %s", key);
  1958. }
  1959. /* Valid configuration for now only requires enabled version rolling and valid bit mask */
  1960. config_status = version_rolling_status && version_mask_valid;
  1961. json_response_error:
  1962. json_decref(response);
  1963. out:
  1964. return config_status;
  1965. }
  1966. #else
  1967. static inline bool configure_stratum_mining(struct pool __maybe_unused *pool)
  1968. {
  1969. return true;
  1970. }
  1971. #endif
  1972. static bool parse_notify(struct pool *pool, json_t *val)
  1973. {
  1974. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1975. *ntime, header[260];
  1976. unsigned char *cb1 = NULL, *cb2 = NULL;
  1977. size_t cb1_len, cb2_len, alloc_len;
  1978. bool clean, ret = false;
  1979. int merkles, i;
  1980. json_t *arr;
  1981. arr = json_array_get(val, 4);
  1982. if (!arr || !json_is_array(arr))
  1983. goto out;
  1984. merkles = json_array_size(arr);
  1985. job_id = json_array_string(val, 0);
  1986. prev_hash = __json_array_string(val, 1);
  1987. coinbase1 = json_array_string(val, 2);
  1988. coinbase2 = json_array_string(val, 3);
  1989. bbversion = __json_array_string(val, 5);
  1990. nbit = __json_array_string(val, 6);
  1991. ntime = __json_array_string(val, 7);
  1992. clean = json_is_true(json_array_get(val, 8));
  1993. get_vmask(pool, bbversion);
  1994. if (!valid_ascii(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||
  1995. !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||
  1996. !valid_hex(ntime)) {
  1997. /* Annoying but we must not leak memory */
  1998. free(job_id);
  1999. free(coinbase1);
  2000. free(coinbase2);
  2001. goto out;
  2002. }
  2003. cg_wlock(&pool->data_lock);
  2004. free(pool->swork.job_id);
  2005. pool->swork.job_id = job_id;
  2006. if (memcmp(pool->prev_hash, prev_hash, 64)) {
  2007. pool->swork.clean = true;
  2008. } else {
  2009. pool->swork.clean = clean;
  2010. }
  2011. snprintf(pool->prev_hash, 65, "%s", prev_hash);
  2012. cb1_len = strlen(coinbase1) / 2;
  2013. cb2_len = strlen(coinbase2) / 2;
  2014. snprintf(pool->bbversion, 9, "%s", bbversion);
  2015. snprintf(pool->nbit, 9, "%s", nbit);
  2016. snprintf(pool->ntime, 9, "%s", ntime);
  2017. if (pool->next_diff > 0) {
  2018. pool->sdiff = pool->next_diff;
  2019. pool->next_diff = pool->diff_after;
  2020. pool->diff_after = 0;
  2021. }
  2022. alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  2023. pool->nonce2_offset = cb1_len + pool->n1_len;
  2024. for (i = 0; i < pool->merkles; i++)
  2025. free(pool->swork.merkle_bin[i]);
  2026. if (merkles) {
  2027. pool->swork.merkle_bin = cgrealloc(pool->swork.merkle_bin,
  2028. sizeof(char *) * merkles + 1);
  2029. for (i = 0; i < merkles; i++) {
  2030. char *merkle = json_array_string(arr, i);
  2031. pool->swork.merkle_bin[i] = cgmalloc(32);
  2032. if (opt_protocol)
  2033. applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
  2034. ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  2035. free(merkle);
  2036. if (unlikely(!ret)) {
  2037. applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
  2038. goto out_unlock;
  2039. }
  2040. }
  2041. }
  2042. pool->merkles = merkles;
  2043. if (pool->merkles < 2)
  2044. pool->bad_work++;
  2045. if (clean)
  2046. pool->nonce2 = 0;
  2047. #if 0
  2048. header_len = strlen(pool->bbversion) +
  2049. strlen(pool->prev_hash);
  2050. /* merkle_hash */ 32 +
  2051. strlen(pool->ntime) +
  2052. strlen(pool->nbit) +
  2053. /* nonce */ 8 +
  2054. /* workpadding */ 96;
  2055. #endif
  2056. snprintf(header, 257,
  2057. "%s%s%s%s%s%s%s",
  2058. pool->bbversion,
  2059. pool->prev_hash,
  2060. blank_merkle,
  2061. pool->ntime,
  2062. pool->nbit,
  2063. "00000000", /* nonce */
  2064. workpadding);
  2065. ret = hex2bin(pool->header_bin, header, 128);
  2066. if (unlikely(!ret)) {
  2067. applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
  2068. goto out_unlock;
  2069. }
  2070. cb1 = alloca(cb1_len);
  2071. ret = hex2bin(cb1, coinbase1, cb1_len);
  2072. if (unlikely(!ret)) {
  2073. applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
  2074. goto out_unlock;
  2075. }
  2076. cb2 = alloca(cb2_len);
  2077. ret = hex2bin(cb2, coinbase2, cb2_len);
  2078. if (unlikely(!ret)) {
  2079. applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
  2080. goto out_unlock;
  2081. }
  2082. free(pool->coinbase);
  2083. pool->coinbase = cgcalloc(alloc_len, 1);
  2084. cg_memcpy(pool->coinbase, cb1, cb1_len);
  2085. if (pool->n1_len)
  2086. cg_memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  2087. cg_memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  2088. if (opt_debug || opt_decode) {
  2089. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  2090. if (opt_decode)
  2091. decode_exit(pool, cb);
  2092. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  2093. free(cb);
  2094. }
  2095. out_unlock:
  2096. cg_wunlock(&pool->data_lock);
  2097. if (opt_protocol) {
  2098. applog(LOG_DEBUG, "job_id: %s", job_id);
  2099. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  2100. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  2101. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  2102. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  2103. applog(LOG_DEBUG, "nbit: %s", nbit);
  2104. applog(LOG_DEBUG, "ntime: %s", ntime);
  2105. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  2106. }
  2107. free(coinbase1);
  2108. free(coinbase2);
  2109. /* A notify message is the closest stratum gets to a getwork */
  2110. pool->getwork_requested++;
  2111. total_getworks++;
  2112. if (pool == current_pool())
  2113. opt_work_update = true;
  2114. out:
  2115. return ret;
  2116. }
  2117. static bool parse_diff(struct pool *pool, json_t *val)
  2118. {
  2119. double old_diff, diff;
  2120. diff = json_number_value(json_array_get(val, 0));
  2121. if (diff <= 0)
  2122. return false;
  2123. /* We can only change one diff per notify so assume diffs are being
  2124. * stacked for successive notifies. */
  2125. cg_wlock(&pool->data_lock);
  2126. if (pool->next_diff)
  2127. pool->diff_after = diff;
  2128. else
  2129. pool->next_diff = diff;
  2130. old_diff = pool->sdiff;
  2131. cg_wunlock(&pool->data_lock);
  2132. if (old_diff != diff) {
  2133. int idiff = diff;
  2134. if ((double)idiff == diff)
  2135. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  2136. pool->pool_no, idiff);
  2137. else
  2138. applog(LOG_NOTICE, "Pool %d difficulty changed to %.1f",
  2139. pool->pool_no, diff);
  2140. } else
  2141. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  2142. diff);
  2143. return true;
  2144. }
  2145. static bool parse_extranonce(struct pool *pool, json_t *val)
  2146. {
  2147. char s[RBUFSIZE], *nonce1;
  2148. int n2size;
  2149. nonce1 = json_array_string(val, 0);
  2150. if (!valid_hex(nonce1)) {
  2151. applog(LOG_INFO, "Failed to get valid nonce1 in parse_extranonce");
  2152. return false;
  2153. }
  2154. n2size = json_integer_value(json_array_get(val, 1));
  2155. if (!n2size) {
  2156. applog(LOG_INFO, "Failed to get valid n2size in parse_extranonce");
  2157. free(nonce1);
  2158. return false;
  2159. }
  2160. cg_wlock(&pool->data_lock);
  2161. free(pool->nonce1);
  2162. pool->nonce1 = nonce1;
  2163. pool->n1_len = strlen(nonce1) / 2;
  2164. free(pool->nonce1bin);
  2165. pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
  2166. if (unlikely(!pool->nonce1bin))
  2167. quithere(1, "Failed to calloc pool->nonce1bin");
  2168. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2169. pool->n2size = n2size;
  2170. cg_wunlock(&pool->data_lock);
  2171. applog(LOG_NOTICE, "Pool %d extranonce change requested", pool->pool_no);
  2172. return true;
  2173. }
  2174. static void __suspend_stratum(struct pool *pool)
  2175. {
  2176. clear_sockbuf(pool);
  2177. pool->stratum_active = pool->stratum_notify = false;
  2178. if (pool->sock)
  2179. CLOSESOCKET(pool->sock);
  2180. pool->sock = 0;
  2181. }
  2182. static bool parse_reconnect(struct pool *pool, json_t *val)
  2183. {
  2184. char *sockaddr_url, *stratum_port, *tmp;
  2185. char *url, *port, address[256];
  2186. int port_no;
  2187. memset(address, 0, 255);
  2188. url = (char *)json_string_value(json_array_get(val, 0));
  2189. if (!url)
  2190. url = pool->sockaddr_url;
  2191. else {
  2192. char *dot_pool, *dot_reconnect;
  2193. dot_pool = strchr(pool->sockaddr_url, '.');
  2194. if (!dot_pool) {
  2195. applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
  2196. pool->sockaddr_url);
  2197. return false;
  2198. }
  2199. dot_reconnect = strchr(url, '.');
  2200. if (!dot_reconnect) {
  2201. applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
  2202. url);
  2203. return false;
  2204. }
  2205. if (strcmp(dot_pool, dot_reconnect)) {
  2206. applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
  2207. pool->sockaddr_url);
  2208. return false;
  2209. }
  2210. }
  2211. port_no = json_integer_value(json_array_get(val, 1));
  2212. if (port_no) {
  2213. port = alloca(256);
  2214. sprintf(port, "%d", port_no);
  2215. } else {
  2216. port = (char *)json_string_value(json_array_get(val, 1));
  2217. if (!port)
  2218. port = pool->stratum_port;
  2219. }
  2220. snprintf(address, 254, "%s:%s", url, port);
  2221. if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
  2222. return false;
  2223. applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
  2224. clear_pool_work(pool);
  2225. mutex_lock(&pool->stratum_lock);
  2226. __suspend_stratum(pool);
  2227. tmp = pool->sockaddr_url;
  2228. pool->sockaddr_url = sockaddr_url;
  2229. pool->stratum_url = pool->sockaddr_url;
  2230. free(tmp);
  2231. tmp = pool->stratum_port;
  2232. pool->stratum_port = stratum_port;
  2233. free(tmp);
  2234. mutex_unlock(&pool->stratum_lock);
  2235. return restart_stratum(pool);
  2236. }
  2237. static bool send_version(struct pool *pool, json_t *val)
  2238. {
  2239. json_t *id_val = json_object_get(val, "id");
  2240. char s[RBUFSIZE];
  2241. int id;
  2242. if (!id_val)
  2243. return false;
  2244. id = json_integer_value(json_object_get(val, "id"));
  2245. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\", \"error\": null}", id);
  2246. if (!stratum_send(pool, s, strlen(s)))
  2247. return false;
  2248. return true;
  2249. }
  2250. static bool send_pong(struct pool *pool, json_t *val)
  2251. {
  2252. json_t *id_val = json_object_get(val, "id");
  2253. char s[RBUFSIZE];
  2254. int id;
  2255. if (!id_val)
  2256. return false;
  2257. id = json_integer_value(json_object_get(val, "id"));
  2258. sprintf(s, "{\"id\": %d, \"result\": \"pong\", \"error\": null}", id);
  2259. if (!stratum_send(pool, s, strlen(s)))
  2260. return false;
  2261. return true;
  2262. }
  2263. static bool show_message(struct pool *pool, json_t *val)
  2264. {
  2265. char *msg;
  2266. if (!json_is_array(val))
  2267. return false;
  2268. msg = (char *)json_string_value(json_array_get(val, 0));
  2269. if (!msg)
  2270. return false;
  2271. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  2272. return true;
  2273. }
  2274. static bool parse_vmask(struct pool *pool, json_t *params)
  2275. {
  2276. bool ret = false;
  2277. if (!params) {
  2278. applog(LOG_INFO, "No params with parse_vmask given for pool %d",
  2279. pool->pool_no);
  2280. goto out;
  2281. }
  2282. if (json_is_array(params))
  2283. params = json_array_get(params, 0);
  2284. //if (!json_is_string(params) || !json_string_length(params)) { //wait cgliner fix this error
  2285. if (!json_is_string(params)) {
  2286. applog(LOG_INFO, "Params invalid string for parse_vmask for pool %d",
  2287. pool->pool_no);
  2288. goto out;
  2289. }
  2290. pool->vmask = set_vmask(pool, params);
  2291. ret = true;
  2292. out:
  2293. return ret;
  2294. }
  2295. bool parse_method(struct pool *pool, char *s)
  2296. {
  2297. json_t *val = NULL, *method, *err_val, *params;
  2298. json_error_t err;
  2299. bool ret = false;
  2300. char *buf;
  2301. if (!s)
  2302. goto out;
  2303. val = JSON_LOADS(s, &err);
  2304. if (!val) {
  2305. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2306. goto out;
  2307. }
  2308. method = json_object_get(val, "method");
  2309. if (!method)
  2310. goto out_decref;
  2311. err_val = json_object_get(val, "error");
  2312. params = json_object_get(val, "params");
  2313. if (err_val && !json_is_null(err_val)) {
  2314. char *ss;
  2315. if (err_val)
  2316. ss = json_dumps(err_val, JSON_INDENT(3));
  2317. else
  2318. ss = strdup("(unknown reason)");
  2319. applog(LOG_INFO, "JSON-RPC method decode of %s failed: %s", s, ss);
  2320. free(ss);
  2321. goto out_decref;
  2322. }
  2323. buf = (char *)json_string_value(method);
  2324. if (!buf)
  2325. goto out_decref;
  2326. if (!strncasecmp(buf, "mining.notify", 13)) {
  2327. if (parse_notify(pool, params))
  2328. pool->stratum_notify = ret = true;
  2329. else
  2330. pool->stratum_notify = ret = false;
  2331. goto out_decref;
  2332. }
  2333. if (!strncasecmp(buf, "mining.set_difficulty", 21)) {
  2334. ret = parse_diff(pool, params);
  2335. goto out_decref;
  2336. }
  2337. if (!strncasecmp(buf, "mining.set_extranonce", 21)) {
  2338. ret = parse_extranonce(pool, params);
  2339. goto out_decref;
  2340. }
  2341. if (!strncasecmp(buf, "client.reconnect", 16)) {
  2342. ret = parse_reconnect(pool, params);
  2343. goto out_decref;
  2344. }
  2345. if (!strncasecmp(buf, "client.get_version", 18)) {
  2346. ret = send_version(pool, val);
  2347. goto out_decref;
  2348. }
  2349. if (!strncasecmp(buf, "client.show_message", 19)) {
  2350. ret = show_message(pool, params);
  2351. goto out_decref;
  2352. }
  2353. if (!strncasecmp(buf, "mining.ping", 11)) {
  2354. applog(LOG_INFO, "Pool %d ping", pool->pool_no);
  2355. ret = send_pong(pool, val);
  2356. goto out_decref;
  2357. }
  2358. if (!strncasecmp(buf, "mining.set_version_mask", 23)) {
  2359. ret = parse_vmask(pool, params);
  2360. goto out_decref;
  2361. }
  2362. applog(LOG_INFO, "Unknown JSON-RPC from pool %d: %s", pool->pool_no, s);
  2363. out_decref:
  2364. json_decref(val);
  2365. out:
  2366. return ret;
  2367. }
  2368. bool subscribe_extranonce(struct pool *pool)
  2369. {
  2370. json_t *val = NULL, *res_val, *err_val;
  2371. char s[RBUFSIZE], *sret = NULL;
  2372. json_error_t err;
  2373. bool ret = false;
  2374. sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}",
  2375. swork_id++);
  2376. if (!stratum_send(pool, s, strlen(s)))
  2377. return ret;
  2378. /* Parse all data in the queue and anything left should be the response */
  2379. while (42) {
  2380. if (!socket_full(pool, DEFAULT_SOCKWAIT / 30)) {
  2381. applog(LOG_DEBUG, "Timed out waiting for response extranonce.subscribe");
  2382. /* some pool doesnt send anything, so this is normal */
  2383. ret = true;
  2384. goto out;
  2385. }
  2386. sret = recv_line(pool);
  2387. if (!sret)
  2388. return ret;
  2389. if (parse_method(pool, sret))
  2390. free(sret);
  2391. else
  2392. break;
  2393. }
  2394. val = JSON_LOADS(sret, &err);
  2395. free(sret);
  2396. res_val = json_object_get(val, "result");
  2397. err_val = json_object_get(val, "error");
  2398. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2399. char *ss;
  2400. if (err_val) {
  2401. ss = __json_array_string(err_val, 1);
  2402. if (!ss)
  2403. ss = (char *)json_string_value(err_val);
  2404. if (ss && (strcmp(ss, "Method 'subscribe' not found for service 'mining.extranonce'") == 0)) {
  2405. applog(LOG_INFO, "Cannot subscribe to mining.extranonce for pool %d", pool->pool_no);
  2406. ret = true;
  2407. goto out;
  2408. }
  2409. if (ss && (strcmp(ss, "Unrecognized request provided") == 0)) {
  2410. applog(LOG_INFO, "Cannot subscribe to mining.extranonce for pool %d", pool->pool_no);
  2411. ret = true;
  2412. goto out;
  2413. }
  2414. ss = json_dumps(err_val, JSON_INDENT(3));
  2415. }
  2416. else
  2417. ss = strdup("(unknown reason)");
  2418. applog(LOG_INFO, "Pool %d JSON extranonce subscribe failed: %s", pool->pool_no, ss);
  2419. free(ss);
  2420. goto out;
  2421. }
  2422. ret = true;
  2423. applog(LOG_INFO, "Stratum extranonce subscribe for pool %d", pool->pool_no);
  2424. out:
  2425. json_decref(val);
  2426. return ret;
  2427. }
  2428. bool auth_stratum(struct pool *pool)
  2429. {
  2430. json_t *val = NULL, *res_val, *err_val;
  2431. char s[RBUFSIZE], *sret = NULL;
  2432. json_error_t err;
  2433. bool ret = false;
  2434. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  2435. swork_id++, pool->rpc_user, pool->rpc_pass);
  2436. if (!stratum_send(pool, s, strlen(s)))
  2437. return ret;
  2438. /* Parse all data in the queue and anything left should be auth */
  2439. while (42) {
  2440. sret = recv_line(pool);
  2441. if (!sret)
  2442. return ret;
  2443. if (parse_method(pool, sret))
  2444. free(sret);
  2445. else
  2446. break;
  2447. }
  2448. val = JSON_LOADS(sret, &err);
  2449. free(sret);
  2450. res_val = json_object_get(val, "result");
  2451. err_val = json_object_get(val, "error");
  2452. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2453. char *ss;
  2454. if (err_val)
  2455. ss = json_dumps(err_val, JSON_INDENT(3));
  2456. else
  2457. ss = strdup("(unknown reason)");
  2458. applog(LOG_INFO, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  2459. free(ss);
  2460. suspend_stratum(pool);
  2461. goto out;
  2462. }
  2463. ret = true;
  2464. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  2465. pool->probed = true;
  2466. successful_connect = true;
  2467. if (opt_suggest_diff) {
  2468. sprintf(s, "{\"id\": %d, \"method\": \"mining.suggest_difficulty\", \"params\": [%d]}",
  2469. swork_id++, opt_suggest_diff);
  2470. stratum_send(pool, s, strlen(s));
  2471. }
  2472. out:
  2473. json_decref(val);
  2474. return ret;
  2475. }
  2476. static int recv_byte(int sockd)
  2477. {
  2478. char c;
  2479. if (recv(sockd, &c, 1, 0) != -1)
  2480. return c;
  2481. return -1;
  2482. }
  2483. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  2484. {
  2485. char buf[1024];
  2486. int i, len;
  2487. if (http0) {
  2488. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  2489. pool->sockaddr_url, pool->stratum_port);
  2490. } else {
  2491. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  2492. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  2493. pool->stratum_port);
  2494. }
  2495. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  2496. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2497. send(sockd, buf, strlen(buf), 0);
  2498. len = recv(sockd, buf, 12, 0);
  2499. if (len <= 0) {
  2500. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  2501. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2502. return false;
  2503. }
  2504. buf[len] = '\0';
  2505. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  2506. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2507. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  2508. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  2509. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2510. return false;
  2511. }
  2512. /* Ignore unwanted headers till we get desired response */
  2513. for (i = 0; i < 4; i++) {
  2514. buf[i] = recv_byte(sockd);
  2515. if (buf[i] == (char)-1) {
  2516. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2517. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2518. return false;
  2519. }
  2520. }
  2521. while (strncmp(buf, "\r\n\r\n", 4)) {
  2522. for (i = 0; i < 3; i++)
  2523. buf[i] = buf[i + 1];
  2524. buf[3] = recv_byte(sockd);
  2525. if (buf[3] == (char)-1) {
  2526. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2527. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2528. return false;
  2529. }
  2530. }
  2531. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  2532. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2533. return true;
  2534. }
  2535. static bool socks5_negotiate(struct pool *pool, int sockd)
  2536. {
  2537. unsigned char atyp, uclen;
  2538. unsigned short port;
  2539. char buf[515];
  2540. int i, len;
  2541. buf[0] = 0x05;
  2542. buf[1] = 0x01;
  2543. buf[2] = 0x00;
  2544. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  2545. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2546. send(sockd, buf, 3, 0);
  2547. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  2548. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2549. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2550. return false;
  2551. }
  2552. buf[0] = 0x05;
  2553. buf[1] = 0x01;
  2554. buf[2] = 0x00;
  2555. buf[3] = 0x03;
  2556. len = (strlen(pool->sockaddr_url));
  2557. if (len > 255)
  2558. len = 255;
  2559. uclen = len;
  2560. buf[4] = (uclen & 0xff);
  2561. cg_memcpy(buf + 5, pool->sockaddr_url, len);
  2562. port = atoi(pool->stratum_port);
  2563. buf[5 + len] = (port >> 8);
  2564. buf[6 + len] = (port & 0xff);
  2565. send(sockd, buf, (7 + len), 0);
  2566. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  2567. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2568. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2569. return false;
  2570. }
  2571. recv_byte(sockd);
  2572. atyp = recv_byte(sockd);
  2573. if (atyp == 0x01) {
  2574. for (i = 0; i < 4; i++)
  2575. recv_byte(sockd);
  2576. } else if (atyp == 0x03) {
  2577. len = recv_byte(sockd);
  2578. for (i = 0; i < len; i++)
  2579. recv_byte(sockd);
  2580. } else {
  2581. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2582. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2583. return false;
  2584. }
  2585. for (i = 0; i < 2; i++)
  2586. recv_byte(sockd);
  2587. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  2588. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2589. return true;
  2590. }
  2591. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  2592. {
  2593. unsigned short port;
  2594. in_addr_t inp;
  2595. char buf[515];
  2596. int i, len;
  2597. buf[0] = 0x04;
  2598. buf[1] = 0x01;
  2599. port = atoi(pool->stratum_port);
  2600. buf[2] = port >> 8;
  2601. buf[3] = port & 0xff;
  2602. sprintf(&buf[8], "CGMINER");
  2603. /* See if we've been given an IP address directly to avoid needing to
  2604. * resolve it. */
  2605. inp = inet_addr(pool->sockaddr_url);
  2606. inp = ntohl(inp);
  2607. if ((int)inp != -1)
  2608. socks4a = false;
  2609. else {
  2610. /* Try to extract the IP address ourselves first */
  2611. struct addrinfo servinfobase, *servinfo, hints;
  2612. servinfo = &servinfobase;
  2613. memset(&hints, 0, sizeof(struct addrinfo));
  2614. hints.ai_family = AF_INET; /* IPV4 only */
  2615. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  2616. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  2617. inp = ntohl(saddr_in->sin_addr.s_addr);
  2618. socks4a = false;
  2619. freeaddrinfo(servinfo);
  2620. }
  2621. }
  2622. if (!socks4a) {
  2623. if ((int)inp == -1) {
  2624. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  2625. pool->sockaddr_url);
  2626. return false;
  2627. }
  2628. buf[4] = (inp >> 24) & 0xFF;
  2629. buf[5] = (inp >> 16) & 0xFF;
  2630. buf[6] = (inp >> 8) & 0xFF;
  2631. buf[7] = (inp >> 0) & 0xFF;
  2632. send(sockd, buf, 16, 0);
  2633. } else {
  2634. /* This appears to not be working but hopefully most will be
  2635. * able to resolve IP addresses themselves. */
  2636. buf[4] = 0;
  2637. buf[5] = 0;
  2638. buf[6] = 0;
  2639. buf[7] = 1;
  2640. len = strlen(pool->sockaddr_url);
  2641. if (len > 255)
  2642. len = 255;
  2643. cg_memcpy(&buf[16], pool->sockaddr_url, len);
  2644. len += 16;
  2645. buf[len++] = '\0';
  2646. send(sockd, buf, len, 0);
  2647. }
  2648. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  2649. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  2650. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2651. return false;
  2652. }
  2653. for (i = 0; i < 6; i++)
  2654. recv_byte(sockd);
  2655. return true;
  2656. }
  2657. static void noblock_socket(SOCKETTYPE fd)
  2658. {
  2659. #ifndef WIN32
  2660. int flags = fcntl(fd, F_GETFL, 0);
  2661. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  2662. #else
  2663. u_long flags = 1;
  2664. ioctlsocket(fd, FIONBIO, &flags);
  2665. #endif
  2666. }
  2667. static void block_socket(SOCKETTYPE fd)
  2668. {
  2669. #ifndef WIN32
  2670. int flags = fcntl(fd, F_GETFL, 0);
  2671. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  2672. #else
  2673. u_long flags = 0;
  2674. ioctlsocket(fd, FIONBIO, &flags);
  2675. #endif
  2676. }
  2677. static bool sock_connecting(void)
  2678. {
  2679. #ifndef WIN32
  2680. return errno == EINPROGRESS;
  2681. #else
  2682. return WSAGetLastError() == WSAEWOULDBLOCK;
  2683. #endif
  2684. }
  2685. static bool setup_stratum_socket(struct pool *pool)
  2686. {
  2687. struct addrinfo *servinfo, hints, *p;
  2688. char *sockaddr_url, *sockaddr_port;
  2689. int sockd;
  2690. mutex_lock(&pool->stratum_lock);
  2691. pool->stratum_active = false;
  2692. if (pool->sock)
  2693. CLOSESOCKET(pool->sock);
  2694. pool->sock = 0;
  2695. mutex_unlock(&pool->stratum_lock);
  2696. memset(&hints, 0, sizeof(struct addrinfo));
  2697. hints.ai_family = AF_UNSPEC;
  2698. hints.ai_socktype = SOCK_STREAM;
  2699. if (!pool->rpc_proxy && opt_socks_proxy) {
  2700. pool->rpc_proxy = opt_socks_proxy;
  2701. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  2702. pool->rpc_proxytype = PROXY_SOCKS5;
  2703. }
  2704. if (pool->rpc_proxy) {
  2705. sockaddr_url = pool->sockaddr_proxy_url;
  2706. sockaddr_port = pool->sockaddr_proxy_port;
  2707. } else {
  2708. sockaddr_url = pool->sockaddr_url;
  2709. sockaddr_port = pool->stratum_port;
  2710. }
  2711. if (getaddrinfo(sockaddr_url, sockaddr_port, &hints, &servinfo) != 0) {
  2712. if (!pool->probed) {
  2713. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  2714. sockaddr_url, sockaddr_port);
  2715. pool->probed = true;
  2716. } else {
  2717. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  2718. sockaddr_url, sockaddr_port);
  2719. }
  2720. return false;
  2721. }
  2722. for (p = servinfo; p != NULL; p = p->ai_next) {
  2723. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  2724. if (sockd == -1) {
  2725. applog(LOG_DEBUG, "Failed socket");
  2726. continue;
  2727. }
  2728. /* Iterate non blocking over entries returned by getaddrinfo
  2729. * to cope with round robin DNS entries, finding the first one
  2730. * we can connect to quickly. */
  2731. noblock_socket(sockd);
  2732. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  2733. struct timeval tv_timeout = {1, 0};
  2734. int selret;
  2735. fd_set rw;
  2736. if (!sock_connecting()) {
  2737. CLOSESOCKET(sockd);
  2738. applog(LOG_DEBUG, "Failed sock connect");
  2739. continue;
  2740. }
  2741. retry:
  2742. FD_ZERO(&rw);
  2743. FD_SET(sockd, &rw);
  2744. selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
  2745. if (selret > 0 && FD_ISSET(sockd, &rw)) {
  2746. socklen_t len;
  2747. int err, n;
  2748. len = sizeof(err);
  2749. n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);
  2750. if (!n && !err) {
  2751. applog(LOG_DEBUG, "Succeeded delayed connect");
  2752. block_socket(sockd);
  2753. break;
  2754. }
  2755. }
  2756. if (selret < 0 && interrupted())
  2757. goto retry;
  2758. CLOSESOCKET(sockd);
  2759. applog(LOG_DEBUG, "Select timeout/failed connect");
  2760. continue;
  2761. }
  2762. applog(LOG_WARNING, "Succeeded immediate connect");
  2763. block_socket(sockd);
  2764. break;
  2765. }
  2766. if (p == NULL) {
  2767. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  2768. sockaddr_url, sockaddr_port);
  2769. freeaddrinfo(servinfo);
  2770. return false;
  2771. }
  2772. freeaddrinfo(servinfo);
  2773. if (pool->rpc_proxy) {
  2774. switch (pool->rpc_proxytype) {
  2775. case PROXY_HTTP_1_0:
  2776. if (!http_negotiate(pool, sockd, true))
  2777. return false;
  2778. break;
  2779. case PROXY_HTTP:
  2780. if (!http_negotiate(pool, sockd, false))
  2781. return false;
  2782. break;
  2783. case PROXY_SOCKS5:
  2784. case PROXY_SOCKS5H:
  2785. if (!socks5_negotiate(pool, sockd))
  2786. return false;
  2787. break;
  2788. case PROXY_SOCKS4:
  2789. if (!socks4_negotiate(pool, sockd, false))
  2790. return false;
  2791. break;
  2792. case PROXY_SOCKS4A:
  2793. if (!socks4_negotiate(pool, sockd, true))
  2794. return false;
  2795. break;
  2796. default:
  2797. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  2798. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2799. return false;
  2800. break;
  2801. }
  2802. }
  2803. if (!pool->sockbuf) {
  2804. pool->sockbuf = cgcalloc(RBUFSIZE, 1);
  2805. pool->sockbuf_size = RBUFSIZE;
  2806. }
  2807. pool->sock = sockd;
  2808. keep_sockalive(sockd);
  2809. return true;
  2810. }
  2811. static char *get_sessionid(json_t *val)
  2812. {
  2813. char *ret = NULL;
  2814. json_t *arr_val;
  2815. int arrsize, i;
  2816. arr_val = json_array_get(val, 0);
  2817. if (!arr_val || !json_is_array(arr_val))
  2818. goto out;
  2819. arrsize = json_array_size(arr_val);
  2820. for (i = 0; i < arrsize; i++) {
  2821. json_t *arr = json_array_get(arr_val, i);
  2822. char *notify;
  2823. if (!arr | !json_is_array(arr))
  2824. break;
  2825. notify = __json_array_string(arr, 0);
  2826. if (!notify)
  2827. continue;
  2828. if (!strncasecmp(notify, "mining.notify", 13)) {
  2829. ret = json_array_string(arr, 1);
  2830. break;
  2831. }
  2832. }
  2833. out:
  2834. return ret;
  2835. }
  2836. void suspend_stratum(struct pool *pool)
  2837. {
  2838. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2839. mutex_lock(&pool->stratum_lock);
  2840. __suspend_stratum(pool);
  2841. mutex_unlock(&pool->stratum_lock);
  2842. }
  2843. bool initiate_stratum(struct pool *pool)
  2844. {
  2845. bool ret = false, recvd = false, noresume = false, sockd = false;
  2846. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid, *tmp;
  2847. json_t *val = NULL, *res_val, *err_val;
  2848. json_error_t err;
  2849. int n2size;
  2850. resend:
  2851. if (!setup_stratum_socket(pool)) {
  2852. sockd = false;
  2853. goto out;
  2854. }
  2855. sockd = true;
  2856. if (recvd) {
  2857. /* Get rid of any crap lying around if we're resending */
  2858. clear_sock(pool);
  2859. }
  2860. /* Attempt to configure stratum protocol feature set first. */
  2861. if (!configure_stratum_mining(pool))
  2862. goto out;
  2863. if (recvd) {
  2864. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2865. } else {
  2866. if (pool->sessionid)
  2867. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\", \"%s\"]}", swork_id++, pool->sessionid);
  2868. else
  2869. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\"]}", swork_id++);
  2870. }
  2871. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  2872. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2873. goto out;
  2874. }
  2875. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2876. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2877. goto out;
  2878. }
  2879. rereceive:
  2880. sret = recv_line(pool);
  2881. if (!sret)
  2882. goto out;
  2883. recvd = true;
  2884. val = JSON_LOADS(sret, &err);
  2885. if (!val) {
  2886. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2887. goto out;
  2888. }
  2889. res_val = json_object_get(val, "result");
  2890. err_val = json_object_get(val, "error");
  2891. if (!res_val) {
  2892. /* Check for a method just in case */
  2893. json_t *method_val = json_object_get(val, "method");
  2894. if (method_val && parse_method(pool, sret)) {
  2895. free(sret);
  2896. sret = NULL;
  2897. goto rereceive;
  2898. }
  2899. }
  2900. if (!res_val || json_is_null(res_val) ||
  2901. (err_val && !json_is_null(err_val))) {
  2902. char *ss;
  2903. if (err_val)
  2904. ss = json_dumps(err_val, JSON_INDENT(3));
  2905. else
  2906. ss = strdup("(unknown reason)");
  2907. applog(LOG_INFO, "JSON-RPC decode of message %s failed: %s", sret, ss);
  2908. free(ss);
  2909. goto out;
  2910. }
  2911. sessionid = get_sessionid(res_val);
  2912. if (!sessionid)
  2913. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2914. nonce1 = json_array_string(res_val, 1);
  2915. if (!valid_hex(nonce1)) {
  2916. applog(LOG_INFO, "Failed to get valid nonce1 in initiate_stratum");
  2917. free(sessionid);
  2918. free(nonce1);
  2919. goto out;
  2920. }
  2921. n2size = json_integer_value(json_array_get(res_val, 2));
  2922. if (n2size < 2 || n2size > 16) {
  2923. applog(LOG_INFO, "Failed to get valid n2size in initiate_stratum");
  2924. free(sessionid);
  2925. free(nonce1);
  2926. goto out;
  2927. }
  2928. if (sessionid && pool->sessionid && !strcmp(sessionid, pool->sessionid)) {
  2929. applog(LOG_NOTICE, "Pool %d successfully negotiated resume with the same session ID",
  2930. pool->pool_no);
  2931. }
  2932. cg_wlock(&pool->data_lock);
  2933. tmp = pool->sessionid;
  2934. pool->sessionid = sessionid;
  2935. free(tmp);
  2936. tmp = pool->nonce1;
  2937. pool->nonce1 = nonce1;
  2938. free(tmp);
  2939. pool->n1_len = strlen(nonce1) / 2;
  2940. free(pool->nonce1bin);
  2941. pool->nonce1bin = cgcalloc(pool->n1_len, 1);
  2942. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2943. pool->n2size = n2size;
  2944. cg_wunlock(&pool->data_lock);
  2945. if (sessionid)
  2946. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2947. ret = true;
  2948. out:
  2949. if (ret) {
  2950. if (!pool->stratum_url)
  2951. pool->stratum_url = pool->sockaddr_url;
  2952. pool->stratum_active = true;
  2953. pool->next_diff = pool->diff_after = 0;
  2954. pool->sdiff = 1;
  2955. if (opt_protocol) {
  2956. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2957. pool->pool_no, pool->nonce1, pool->n2size);
  2958. }
  2959. } else {
  2960. if (recvd && !noresume) {
  2961. /* Reset the sessionid used for stratum resuming in case the pool
  2962. * does not support it, or does not know how to respond to the
  2963. * presence of the sessionid parameter. */
  2964. cg_wlock(&pool->data_lock);
  2965. free(pool->sessionid);
  2966. free(pool->nonce1);
  2967. pool->sessionid = pool->nonce1 = NULL;
  2968. cg_wunlock(&pool->data_lock);
  2969. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2970. noresume = true;
  2971. json_decref(val);
  2972. goto resend;
  2973. }
  2974. applog(LOG_DEBUG, "Initiate stratum failed");
  2975. if (sockd)
  2976. suspend_stratum(pool);
  2977. }
  2978. json_decref(val);
  2979. free(sret);
  2980. return ret;
  2981. }
  2982. bool restart_stratum(struct pool *pool)
  2983. {
  2984. bool ret = false;
  2985. if (pool->stratum_active)
  2986. suspend_stratum(pool);
  2987. if (!initiate_stratum(pool))
  2988. goto out;
  2989. if (pool->extranonce_subscribe && !subscribe_extranonce(pool))
  2990. goto out;
  2991. if (!auth_stratum(pool))
  2992. goto out;
  2993. ret = true;
  2994. out:
  2995. if (!ret)
  2996. pool_died(pool);
  2997. else
  2998. stratum_resumed(pool);
  2999. return ret;
  3000. }
  3001. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  3002. {
  3003. dev->device_last_not_well = time(NULL);
  3004. dev->device_not_well_reason = reason;
  3005. switch (reason) {
  3006. case REASON_THREAD_FAIL_INIT:
  3007. dev->thread_fail_init_count++;
  3008. break;
  3009. case REASON_THREAD_ZERO_HASH:
  3010. dev->thread_zero_hash_count++;
  3011. break;
  3012. case REASON_THREAD_FAIL_QUEUE:
  3013. dev->thread_fail_queue_count++;
  3014. break;
  3015. case REASON_DEV_SICK_IDLE_60:
  3016. dev->dev_sick_idle_60_count++;
  3017. break;
  3018. case REASON_DEV_DEAD_IDLE_600:
  3019. dev->dev_dead_idle_600_count++;
  3020. break;
  3021. case REASON_DEV_NOSTART:
  3022. dev->dev_nostart_count++;
  3023. break;
  3024. case REASON_DEV_OVER_HEAT:
  3025. dev->dev_over_heat_count++;
  3026. break;
  3027. case REASON_DEV_THERMAL_CUTOFF:
  3028. dev->dev_thermal_cutoff_count++;
  3029. break;
  3030. case REASON_DEV_COMMS_ERROR:
  3031. dev->dev_comms_error_count++;
  3032. break;
  3033. case REASON_DEV_THROTTLE:
  3034. dev->dev_throttle_count++;
  3035. break;
  3036. }
  3037. }
  3038. /* Realloc an existing string to fit an extra string s, appending s to it. */
  3039. void *realloc_strcat(char *ptr, char *s)
  3040. {
  3041. size_t old = 0, len = strlen(s);
  3042. char *ret;
  3043. if (!len)
  3044. return ptr;
  3045. if (ptr)
  3046. old = strlen(ptr);
  3047. len += old + 1;
  3048. ret = cgmalloc(len);
  3049. if (ptr) {
  3050. sprintf(ret, "%s%s", ptr, s);
  3051. free(ptr);
  3052. } else
  3053. sprintf(ret, "%s", s);
  3054. return ret;
  3055. }
  3056. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  3057. * Including 0x00 at the end
  3058. * You must free the result yourself */
  3059. void *str_text(char *ptr)
  3060. {
  3061. unsigned char *uptr;
  3062. char *ret, *txt;
  3063. if (ptr == NULL) {
  3064. ret = strdup("(null)");
  3065. if (unlikely(!ret))
  3066. quithere(1, "Failed to malloc null");
  3067. }
  3068. uptr = (unsigned char *)ptr;
  3069. ret = txt = cgmalloc(strlen(ptr) * 4 + 5); // Guaranteed >= needed
  3070. do {
  3071. if (*uptr < ' ' || *uptr > '~') {
  3072. sprintf(txt, "0x%02x", *uptr);
  3073. txt += 4;
  3074. } else
  3075. *(txt++) = *uptr;
  3076. } while (*(uptr++));
  3077. *txt = '\0';
  3078. return ret;
  3079. }
  3080. void RenameThread(const char* name)
  3081. {
  3082. char buf[16];
  3083. snprintf(buf, sizeof(buf), "cg@%s", name);
  3084. #if defined(PR_SET_NAME)
  3085. // Only the first 15 characters are used (16 - NUL terminator)
  3086. prctl(PR_SET_NAME, buf, 0, 0, 0);
  3087. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  3088. pthread_set_name_np(pthread_self(), buf);
  3089. #elif defined(MAC_OSX)
  3090. pthread_setname_np(buf);
  3091. #else
  3092. // Prevent warnings
  3093. (void)buf;
  3094. #endif
  3095. }
  3096. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  3097. * that support them and for apple which does not. We use a single byte across
  3098. * a pipe to emulate semaphore behaviour there. */
  3099. #ifdef __APPLE__
  3100. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3101. {
  3102. int flags, fd, i;
  3103. if (pipe(cgsem->pipefd) == -1)
  3104. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  3105. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  3106. * execv on restart. */
  3107. for (i = 0; i < 2; i++) {
  3108. fd = cgsem->pipefd[i];
  3109. flags = fcntl(fd, F_GETFD, 0);
  3110. flags |= FD_CLOEXEC;
  3111. if (fcntl(fd, F_SETFD, flags) == -1)
  3112. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  3113. }
  3114. }
  3115. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3116. {
  3117. const char buf = 1;
  3118. int ret;
  3119. retry:
  3120. ret = write(cgsem->pipefd[1], &buf, 1);
  3121. if (unlikely(ret == 0))
  3122. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  3123. else if (unlikely(ret < 0 && interrupted))
  3124. goto retry;
  3125. }
  3126. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3127. {
  3128. char buf;
  3129. int ret;
  3130. retry:
  3131. ret = read(cgsem->pipefd[0], &buf, 1);
  3132. if (unlikely(ret == 0))
  3133. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  3134. else if (unlikely(ret < 0 && interrupted))
  3135. goto retry;
  3136. }
  3137. void cgsem_destroy(cgsem_t *cgsem)
  3138. {
  3139. close(cgsem->pipefd[1]);
  3140. close(cgsem->pipefd[0]);
  3141. }
  3142. /* This is similar to sem_timedwait but takes a millisecond value */
  3143. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  3144. {
  3145. struct timeval timeout;
  3146. int ret, fd;
  3147. fd_set rd;
  3148. char buf;
  3149. retry:
  3150. fd = cgsem->pipefd[0];
  3151. FD_ZERO(&rd);
  3152. FD_SET(fd, &rd);
  3153. ms_to_timeval(&timeout, ms);
  3154. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  3155. if (ret > 0) {
  3156. ret = read(fd, &buf, 1);
  3157. return 0;
  3158. }
  3159. if (likely(!ret))
  3160. return ETIMEDOUT;
  3161. if (interrupted())
  3162. goto retry;
  3163. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  3164. /* We don't reach here */
  3165. return 0;
  3166. }
  3167. /* Reset semaphore count back to zero */
  3168. void cgsem_reset(cgsem_t *cgsem)
  3169. {
  3170. int ret, fd;
  3171. fd_set rd;
  3172. char buf;
  3173. fd = cgsem->pipefd[0];
  3174. FD_ZERO(&rd);
  3175. FD_SET(fd, &rd);
  3176. do {
  3177. struct timeval timeout = {0, 0};
  3178. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  3179. if (ret > 0)
  3180. ret = read(fd, &buf, 1);
  3181. else if (unlikely(ret < 0 && interrupted()))
  3182. ret = 1;
  3183. } while (ret > 0);
  3184. }
  3185. #else
  3186. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3187. {
  3188. int ret;
  3189. if ((ret = sem_init(cgsem, 0, 0)))
  3190. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  3191. }
  3192. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3193. {
  3194. if (unlikely(sem_post(cgsem)))
  3195. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  3196. }
  3197. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3198. {
  3199. retry:
  3200. if (unlikely(sem_wait(cgsem))) {
  3201. if (interrupted())
  3202. goto retry;
  3203. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  3204. }
  3205. }
  3206. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  3207. {
  3208. struct timespec abs_timeout, tdiff;
  3209. int ret;
  3210. cgcond_time(&abs_timeout);
  3211. ms_to_timespec(&tdiff, ms);
  3212. timeraddspec(&abs_timeout, &tdiff);
  3213. retry:
  3214. ret = sem_timedwait(cgsem, &abs_timeout);
  3215. if (ret) {
  3216. if (likely(sock_timeout()))
  3217. return ETIMEDOUT;
  3218. if (interrupted())
  3219. goto retry;
  3220. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  3221. }
  3222. return 0;
  3223. }
  3224. void cgsem_reset(cgsem_t *cgsem)
  3225. {
  3226. int ret;
  3227. do {
  3228. ret = sem_trywait(cgsem);
  3229. if (unlikely(ret < 0 && interrupted()))
  3230. ret = 0;
  3231. } while (!ret);
  3232. }
  3233. void cgsem_destroy(cgsem_t *cgsem)
  3234. {
  3235. sem_destroy(cgsem);
  3236. }
  3237. #endif
  3238. /* Provide a completion_timeout helper function for unreliable functions that
  3239. * may die due to driver issues etc that time out if the function fails and
  3240. * can then reliably return. */
  3241. struct cg_completion {
  3242. cgsem_t cgsem;
  3243. void (*fn)(void *fnarg);
  3244. void *fnarg;
  3245. };
  3246. void *completion_thread(void *arg)
  3247. {
  3248. struct cg_completion *cgc = (struct cg_completion *)arg;
  3249. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3250. cgc->fn(cgc->fnarg);
  3251. cgsem_post(&cgc->cgsem);
  3252. return NULL;
  3253. }
  3254. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  3255. {
  3256. struct cg_completion *cgc;
  3257. pthread_t pthread;
  3258. bool ret = false;
  3259. cgc = cgmalloc(sizeof(struct cg_completion));
  3260. cgsem_init(&cgc->cgsem);
  3261. cgc->fn = fn;
  3262. cgc->fnarg = fnarg;
  3263. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  3264. ret = cgsem_mswait(&cgc->cgsem, timeout);
  3265. if (!ret) {
  3266. pthread_join(pthread, NULL);
  3267. free(cgc);
  3268. } else
  3269. pthread_cancel(pthread);
  3270. return !ret;
  3271. }
  3272. void _cg_memcpy(void *dest, const void *src, unsigned int n, const char *file, const char *func, const int line)
  3273. {
  3274. if (unlikely(n < 1 || n > (1ul << 31))) {
  3275. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from %s %s():%d",
  3276. n, file, func, line);
  3277. return;
  3278. }
  3279. if (unlikely(!dest)) {
  3280. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes to NULL from %s %s():%d",
  3281. n, file, func, line);
  3282. return;
  3283. }
  3284. if (unlikely(!src)) {
  3285. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from NULL from %s %s():%d",
  3286. n, file, func, line);
  3287. return;
  3288. }
  3289. memcpy(dest, src, n);
  3290. }