util.c 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841
  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. return NULL;
  1175. ofs = ret - lowhay;
  1176. return haystack + ofs;
  1177. }
  1178. char *Strsep(char **stringp, const char *delim)
  1179. {
  1180. char *ret = *stringp;
  1181. char *p;
  1182. p = (ret != NULL) ? strpbrk(ret, delim) : NULL;
  1183. if (p == NULL)
  1184. *stringp = NULL;
  1185. else {
  1186. *p = '\0';
  1187. *stringp = p + 1;
  1188. }
  1189. return ret;
  1190. }
  1191. /* Get timespec specifically for use by cond_timedwait functions which use
  1192. * CLOCK_REALTIME for expiry */
  1193. void cgcond_time(struct timespec *abstime)
  1194. {
  1195. clock_gettime(CLOCK_REALTIME, abstime);
  1196. }
  1197. #ifdef USE_GEKKO
  1198. /* Get CLOCK_REALTIME for display purposes */
  1199. void cgtime_real(struct timeval *tv)
  1200. {
  1201. struct timespec tp;
  1202. clock_gettime(CLOCK_REALTIME, &tp);
  1203. tv->tv_sec = tp.tv_sec;
  1204. tv->tv_usec = tp.tv_nsec / 1000;
  1205. }
  1206. #endif
  1207. #ifdef WIN32
  1208. /* Mingw32 has no strsep so create our own custom one */
  1209. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  1210. #define EPOCHFILETIME (116444736000000000LL)
  1211. /* These are cgminer specific sleep functions that use an absolute nanosecond
  1212. * resolution timer to avoid poor usleep accuracy and overruns. */
  1213. /* Return the system time as an lldiv_t in decimicroseconds. */
  1214. static void decius_time(lldiv_t *lidiv)
  1215. {
  1216. FILETIME ft;
  1217. LARGE_INTEGER li;
  1218. GetSystemTimeAsFileTime(&ft);
  1219. li.LowPart = ft.dwLowDateTime;
  1220. li.HighPart = ft.dwHighDateTime;
  1221. li.QuadPart -= EPOCHFILETIME;
  1222. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1223. *lidiv = lldiv(li.QuadPart, 10000000);
  1224. }
  1225. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  1226. * with tz set to NULL, and windows' default resolution is only 15ms, this
  1227. * gives us higher resolution times on windows. */
  1228. void cgtime(struct timeval *tv)
  1229. {
  1230. lldiv_t lidiv;
  1231. decius_time(&lidiv);
  1232. tv->tv_sec = lidiv.quot;
  1233. tv->tv_usec = lidiv.rem / 10;
  1234. }
  1235. #else /* WIN32 */
  1236. void cgtime(struct timeval *tv)
  1237. {
  1238. cgtimer_t cgt;
  1239. cgtimer_time(&cgt);
  1240. timespec_to_val(tv, &cgt);
  1241. }
  1242. int cgtimer_to_ms(cgtimer_t *cgt)
  1243. {
  1244. return timespec_to_ms(cgt);
  1245. }
  1246. /* Subtracts b from a and stores it in res. */
  1247. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1248. {
  1249. res->tv_sec = a->tv_sec - b->tv_sec;
  1250. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  1251. if (res->tv_nsec < 0) {
  1252. res->tv_nsec += 1000000000;
  1253. res->tv_sec--;
  1254. }
  1255. }
  1256. #endif /* WIN32 */
  1257. #if defined(CLOCK_MONOTONIC) && !defined(__FreeBSD__) && !defined(__APPLE__) && !defined(WIN32) /* Essentially just linux */
  1258. //#ifdef CLOCK_MONOTONIC /* Essentially just linux */
  1259. void cgtimer_time(cgtimer_t *ts_start)
  1260. {
  1261. clock_gettime(CLOCK_MONOTONIC, ts_start);
  1262. }
  1263. static void nanosleep_abstime(struct timespec *ts_end)
  1264. {
  1265. int ret;
  1266. do {
  1267. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  1268. } while (ret == EINTR);
  1269. }
  1270. /* Reentrant version of cgsleep functions allow start time to be set separately
  1271. * from the beginning of the actual sleep, allowing scheduling delays to be
  1272. * counted in the sleep. */
  1273. #ifdef USE_BITMAIN_SOC
  1274. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1275. {
  1276. struct timespec ts_end;
  1277. ms_to_timespec(&ts_end, ms);
  1278. timeraddspec(&ts_end, ts_start);
  1279. nanosleep_abstime(&ts_end);
  1280. }
  1281. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1282. {
  1283. struct timespec ts_end;
  1284. us_to_timespec(&ts_end, us);
  1285. timeraddspec(&ts_end, ts_start);
  1286. nanosleep_abstime(&ts_end);
  1287. }
  1288. #else /* USE_BITMAIN_SOC */
  1289. int cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1290. {
  1291. struct timespec ts_end, ts_diff;
  1292. int msdiff;
  1293. ms_to_timespec(&ts_end, ms);
  1294. timeraddspec(&ts_end, ts_start);
  1295. cgtimer_time(&ts_diff);
  1296. /* Should be a negative value if we still have to sleep */
  1297. timersubspec(&ts_diff, &ts_end);
  1298. msdiff = -timespec_to_ms(&ts_diff);
  1299. if (msdiff <= 0)
  1300. return 0;
  1301. nanosleep_abstime(&ts_end);
  1302. return msdiff;
  1303. }
  1304. int64_t cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1305. {
  1306. struct timespec ts_end, ts_diff;
  1307. int64_t usdiff;
  1308. us_to_timespec(&ts_end, us);
  1309. timeraddspec(&ts_end, ts_start);
  1310. cgtimer_time(&ts_diff);
  1311. usdiff = -timespec_to_us(&ts_diff);
  1312. if (usdiff <= 0)
  1313. return 0;
  1314. nanosleep_abstime(&ts_end);
  1315. return usdiff;
  1316. }
  1317. #endif /* USE_BITMAIN_SOC */
  1318. #else /* CLOCK_MONOTONIC */
  1319. #ifdef __MACH__
  1320. #include <mach/clock.h>
  1321. #include <mach/mach.h>
  1322. void cgtimer_time(cgtimer_t *ts_start)
  1323. {
  1324. clock_serv_t cclock;
  1325. mach_timespec_t mts;
  1326. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  1327. clock_get_time(cclock, &mts);
  1328. mach_port_deallocate(mach_task_self(), cclock);
  1329. ts_start->tv_sec = mts.tv_sec;
  1330. ts_start->tv_nsec = mts.tv_nsec;
  1331. }
  1332. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  1333. void cgtimer_time(cgtimer_t *ts_start)
  1334. {
  1335. struct timeval tv;
  1336. cgtime(&tv);
  1337. ts_start->tv_sec = tv.tv_sec;
  1338. ts_start->tv_nsec = tv.tv_usec * 1000;
  1339. }
  1340. #endif /* __MACH__ */
  1341. #ifdef WIN32
  1342. /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
  1343. * typedef, allowing us to have sub-microsecond resolution for times, do simple
  1344. * arithmetic for timer calculations, and use windows' own hTimers to get
  1345. * accurate absolute timeouts. */
  1346. int cgtimer_to_ms(cgtimer_t *cgt)
  1347. {
  1348. return (int)(cgt->QuadPart / 10000LL);
  1349. }
  1350. /* Subtracts b from a and stores it in res. */
  1351. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1352. {
  1353. res->QuadPart = a->QuadPart - b->QuadPart;
  1354. }
  1355. /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
  1356. * timeouts with hTimers. */
  1357. void cgtimer_time(cgtimer_t *ts_start)
  1358. {
  1359. FILETIME ft;
  1360. GetSystemTimeAsFileTime(&ft);
  1361. ts_start->LowPart = ft.dwLowDateTime;
  1362. ts_start->HighPart = ft.dwHighDateTime;
  1363. }
  1364. static void liSleep(LARGE_INTEGER *li, int timeout)
  1365. {
  1366. HANDLE hTimer;
  1367. DWORD ret;
  1368. if (unlikely(timeout <= 0))
  1369. return;
  1370. hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  1371. if (unlikely(!hTimer))
  1372. quit(1, "Failed to create hTimer in liSleep");
  1373. ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
  1374. if (unlikely(!ret))
  1375. quit(1, "Failed to SetWaitableTimer in liSleep");
  1376. /* We still use a timeout as a sanity check in case the system time
  1377. * is changed while we're running */
  1378. ret = WaitForSingleObject(hTimer, timeout);
  1379. if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
  1380. quit(1, "Failed to WaitForSingleObject in liSleep");
  1381. CloseHandle(hTimer);
  1382. }
  1383. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1384. {
  1385. LARGE_INTEGER li;
  1386. li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
  1387. liSleep(&li, ms);
  1388. }
  1389. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1390. {
  1391. LARGE_INTEGER li;
  1392. int ms;
  1393. li.QuadPart = ts_start->QuadPart + us * 10LL;
  1394. ms = us / 1000;
  1395. if (!ms)
  1396. ms = 1;
  1397. liSleep(&li, ms);
  1398. }
  1399. #else /* WIN32 */
  1400. static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  1401. {
  1402. struct timespec now;
  1403. timeraddspec(ts_diff, ts_start);
  1404. cgtimer_time(&now);
  1405. timersubspec(ts_diff, &now);
  1406. if (unlikely(ts_diff->tv_sec < 0))
  1407. return;
  1408. nanosleep(ts_diff, NULL);
  1409. }
  1410. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1411. {
  1412. struct timespec ts_diff;
  1413. ms_to_timespec(&ts_diff, ms);
  1414. cgsleep_spec(&ts_diff, ts_start);
  1415. }
  1416. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1417. {
  1418. struct timespec ts_diff;
  1419. us_to_timespec(&ts_diff, us);
  1420. cgsleep_spec(&ts_diff, ts_start);
  1421. }
  1422. #endif /* WIN32 */
  1423. #endif /* CLOCK_MONOTONIC */
  1424. void cgsleep_ms(int ms)
  1425. {
  1426. cgtimer_t ts_start;
  1427. cgsleep_prepare_r(&ts_start);
  1428. cgsleep_ms_r(&ts_start, ms);
  1429. }
  1430. static void busywait_us(int64_t us)
  1431. {
  1432. struct timeval diff, end, now;
  1433. cgtime(&end);
  1434. us_to_timeval(&diff, us);
  1435. addtime(&diff, &end);
  1436. do {
  1437. sched_yield();
  1438. cgtime(&now);
  1439. } while (time_less(&now, &end));
  1440. }
  1441. void cgsleep_us(int64_t us)
  1442. {
  1443. cgtimer_t ts_start;
  1444. /* Most timer resolution is unlikely to be able to sleep accurately
  1445. * for less than 1ms so busywait instead. */
  1446. if (us < 1000)
  1447. return busywait_us(us);
  1448. cgsleep_prepare_r(&ts_start);
  1449. cgsleep_us_r(&ts_start, us);
  1450. }
  1451. /* Returns the microseconds difference between end and start times as a double */
  1452. double us_tdiff(struct timeval *end, struct timeval *start)
  1453. {
  1454. /* Sanity check. We should only be using this for small differences so
  1455. * limit the max to 60 seconds. */
  1456. if (unlikely(end->tv_sec - start->tv_sec > 60))
  1457. return 60000000;
  1458. return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
  1459. }
  1460. /* Returns the milliseconds difference between end and start times */
  1461. int ms_tdiff(struct timeval *end, struct timeval *start)
  1462. {
  1463. /* Like us_tdiff, limit to 1 hour. */
  1464. if (unlikely(end->tv_sec - start->tv_sec > 3600))
  1465. return 3600000;
  1466. return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
  1467. }
  1468. /* Returns the seconds difference between end and start times as a double */
  1469. double tdiff(struct timeval *end, struct timeval *start)
  1470. {
  1471. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1472. }
  1473. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1474. {
  1475. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1476. char url_address[256], port[6];
  1477. int url_len, port_len = 0;
  1478. *sockaddr_url = url;
  1479. url_begin = strstr(url, "//");
  1480. if (!url_begin)
  1481. url_begin = url;
  1482. else
  1483. url_begin += 2;
  1484. /* Look for numeric ipv6 entries */
  1485. ipv6_begin = strstr(url_begin, "[");
  1486. ipv6_end = strstr(url_begin, "]");
  1487. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1488. url_end = strstr(ipv6_end, ":");
  1489. else
  1490. url_end = strstr(url_begin, ":");
  1491. if (url_end) {
  1492. url_len = url_end - url_begin;
  1493. port_len = strlen(url_begin) - url_len - 1;
  1494. if (port_len < 1)
  1495. return false;
  1496. port_start = url_end + 1;
  1497. } else
  1498. url_len = strlen(url_begin);
  1499. if (url_len < 1)
  1500. return false;
  1501. /* Get rid of the [] */
  1502. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) {
  1503. url_len -= 2;
  1504. url_begin++;
  1505. }
  1506. snprintf(url_address, 254, "%.*s", url_len, url_begin);
  1507. if (port_len) {
  1508. char *slash;
  1509. snprintf(port, 6, "%.*s", port_len, port_start);
  1510. slash = strpbrk(port, "/#");
  1511. if (slash)
  1512. *slash = '\0';
  1513. } else
  1514. strcpy(port, "80");
  1515. *sockaddr_port = strdup(port);
  1516. *sockaddr_url = strdup(url_address);
  1517. return true;
  1518. }
  1519. enum send_ret {
  1520. SEND_OK,
  1521. SEND_SELECTFAIL,
  1522. SEND_SENDFAIL,
  1523. SEND_INACTIVE
  1524. };
  1525. /* Send a single command across a socket, appending \n to it. This should all
  1526. * be done under stratum lock except when first establishing the socket */
  1527. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1528. {
  1529. SOCKETTYPE sock = pool->sock;
  1530. ssize_t ssent = 0;
  1531. strcat(s, "\n");
  1532. len++;
  1533. while (len > 0 ) {
  1534. struct timeval timeout = {1, 0};
  1535. ssize_t sent;
  1536. fd_set wd;
  1537. retry:
  1538. FD_ZERO(&wd);
  1539. FD_SET(sock, &wd);
  1540. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1541. if (interrupted())
  1542. goto retry;
  1543. return SEND_SELECTFAIL;
  1544. }
  1545. #ifdef __APPLE__
  1546. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1547. #elif WIN32
  1548. sent = send(pool->sock, s + ssent, len, 0);
  1549. #else
  1550. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1551. #endif
  1552. if (sent < 0) {
  1553. if (!sock_blocks())
  1554. return SEND_SENDFAIL;
  1555. sent = 0;
  1556. }
  1557. ssent += sent;
  1558. len -= sent;
  1559. }
  1560. pool->cgminer_pool_stats.times_sent++;
  1561. pool->cgminer_pool_stats.bytes_sent += ssent;
  1562. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1563. return SEND_OK;
  1564. }
  1565. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1566. {
  1567. enum send_ret ret = SEND_INACTIVE;
  1568. if (opt_protocol)
  1569. applog(LOG_DEBUG, "SEND: %s", s);
  1570. mutex_lock(&pool->stratum_lock);
  1571. if (pool->stratum_active)
  1572. ret = __stratum_send(pool, s, len);
  1573. mutex_unlock(&pool->stratum_lock);
  1574. /* This is to avoid doing applog under stratum_lock */
  1575. switch (ret) {
  1576. default:
  1577. case SEND_OK:
  1578. break;
  1579. case SEND_SELECTFAIL:
  1580. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1581. suspend_stratum(pool);
  1582. break;
  1583. case SEND_SENDFAIL:
  1584. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1585. suspend_stratum(pool);
  1586. break;
  1587. case SEND_INACTIVE:
  1588. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1589. break;
  1590. }
  1591. return (ret == SEND_OK);
  1592. }
  1593. static bool socket_full(struct pool *pool, int wait)
  1594. {
  1595. SOCKETTYPE sock = pool->sock;
  1596. struct timeval timeout;
  1597. fd_set rd;
  1598. if (unlikely(wait < 0))
  1599. wait = 0;
  1600. FD_ZERO(&rd);
  1601. FD_SET(sock, &rd);
  1602. timeout.tv_usec = 0;
  1603. timeout.tv_sec = wait;
  1604. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1605. return true;
  1606. return false;
  1607. }
  1608. /* Check to see if Santa's been good to you */
  1609. bool sock_full(struct pool *pool)
  1610. {
  1611. if (strlen(pool->sockbuf))
  1612. return true;
  1613. return (socket_full(pool, 0));
  1614. }
  1615. static void clear_sockbuf(struct pool *pool)
  1616. {
  1617. if (likely(pool->sockbuf))
  1618. strcpy(pool->sockbuf, "");
  1619. }
  1620. static void clear_sock(struct pool *pool)
  1621. {
  1622. ssize_t n;
  1623. mutex_lock(&pool->stratum_lock);
  1624. do {
  1625. if (pool->sock)
  1626. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1627. else
  1628. n = 0;
  1629. } while (n > 0);
  1630. mutex_unlock(&pool->stratum_lock);
  1631. clear_sockbuf(pool);
  1632. }
  1633. /* Realloc memory to new size and zero any extra memory added */
  1634. void ckrecalloc(void **ptr, size_t old, size_t new, const char *file, const char *func, const int line)
  1635. {
  1636. if (new == old)
  1637. return;
  1638. *ptr = _cgrealloc(*ptr, new, file, func, line);
  1639. if (new > old)
  1640. memset(*ptr + old, 0, new - old);
  1641. }
  1642. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1643. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1644. * and zeroing the new memory */
  1645. static void recalloc_sock(struct pool *pool, size_t len)
  1646. {
  1647. size_t old, new;
  1648. old = strlen(pool->sockbuf);
  1649. new = old + len + 1;
  1650. if (new < pool->sockbuf_size)
  1651. return;
  1652. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1653. // Avoid potentially recursive locking
  1654. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1655. pool->sockbuf = cgrealloc(pool->sockbuf, new);
  1656. memset(pool->sockbuf + old, 0, new - old);
  1657. pool->sockbuf_size = new;
  1658. }
  1659. /* Peeks at a socket to find the first end of line and then reads just that
  1660. * from the socket and returns that as a malloced char */
  1661. char *recv_line(struct pool *pool)
  1662. {
  1663. char *tok, *sret = NULL;
  1664. ssize_t len, buflen;
  1665. int waited = 0;
  1666. if (!strstr(pool->sockbuf, "\n")) {
  1667. struct timeval rstart, now;
  1668. cgtime(&rstart);
  1669. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1670. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1671. goto out;
  1672. }
  1673. do {
  1674. char s[RBUFSIZE];
  1675. size_t slen;
  1676. ssize_t n;
  1677. memset(s, 0, RBUFSIZE);
  1678. n = recv(pool->sock, s, RECVSIZE, 0);
  1679. if (!n) {
  1680. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1681. suspend_stratum(pool);
  1682. break;
  1683. }
  1684. cgtime(&now);
  1685. waited = tdiff(&now, &rstart);
  1686. if (n < 0) {
  1687. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1688. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1689. suspend_stratum(pool);
  1690. break;
  1691. }
  1692. } else {
  1693. slen = strlen(s);
  1694. recalloc_sock(pool, slen);
  1695. strcat(pool->sockbuf, s);
  1696. }
  1697. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1698. }
  1699. buflen = strlen(pool->sockbuf);
  1700. tok = strtok(pool->sockbuf, "\n");
  1701. if (!tok) {
  1702. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1703. goto out;
  1704. }
  1705. sret = strdup(tok);
  1706. len = strlen(sret);
  1707. /* Copy what's left in the buffer after the \n, including the
  1708. * terminating \0 */
  1709. if (buflen > len + 1)
  1710. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1711. else
  1712. strcpy(pool->sockbuf, "");
  1713. pool->cgminer_pool_stats.times_received++;
  1714. pool->cgminer_pool_stats.bytes_received += len;
  1715. pool->cgminer_pool_stats.net_bytes_received += len;
  1716. out:
  1717. if (!sret)
  1718. clear_sock(pool);
  1719. else if (opt_protocol)
  1720. applog(LOG_DEBUG, "RECVD: %s", sret);
  1721. return sret;
  1722. }
  1723. /* Extracts a string value from a json array with error checking. To be used
  1724. * when the value of the string returned is only examined and not to be stored.
  1725. * See json_array_string below */
  1726. static char *__json_array_string(json_t *val, unsigned int entry)
  1727. {
  1728. json_t *arr_entry;
  1729. if (json_is_null(val))
  1730. return NULL;
  1731. if (!json_is_array(val))
  1732. return NULL;
  1733. if (entry > json_array_size(val))
  1734. return NULL;
  1735. arr_entry = json_array_get(val, entry);
  1736. if (!json_is_string(arr_entry))
  1737. return NULL;
  1738. return (char *)json_string_value(arr_entry);
  1739. }
  1740. /* Creates a freshly malloced dup of __json_array_string */
  1741. static char *json_array_string(json_t *val, unsigned int entry)
  1742. {
  1743. char *buf = __json_array_string(val, entry);
  1744. if (buf)
  1745. return strdup(buf);
  1746. return NULL;
  1747. }
  1748. static char *blank_merkle = "0000000000000000000000000000000000000000000000000000000000000000";
  1749. #ifdef HAVE_LIBCURL
  1750. static void decode_exit(struct pool *pool, char *cb)
  1751. {
  1752. CURL *curl = curl_easy_init();
  1753. char *decreq, *s;
  1754. json_t *val;
  1755. int dummy;
  1756. if (!opt_btcd && !sleep(3) && !opt_btcd) {
  1757. applog(LOG_ERR, "No bitcoind specified, unable to decode coinbase.");
  1758. exit(1);
  1759. }
  1760. decreq = cgmalloc(strlen(cb) + 256);
  1761. sprintf(decreq, "{\"id\": 0, \"method\": \"decoderawtransaction\", \"params\": [\"%s\"]}\n",
  1762. cb);
  1763. val = json_rpc_call(curl, opt_btcd->rpc_url, opt_btcd->rpc_userpass, decreq,
  1764. false, false, &dummy, opt_btcd, false);
  1765. free(decreq);
  1766. if (!val) {
  1767. applog(LOG_ERR, "Failed json_rpc_call to btcd %s", opt_btcd->rpc_url);
  1768. exit(1);
  1769. }
  1770. s = json_dumps(val, JSON_INDENT(4));
  1771. printf("Pool %s:\n%s\n", pool->rpc_url, s);
  1772. free(s);
  1773. exit(0);
  1774. }
  1775. #else
  1776. static void decode_exit(struct pool __maybe_unused *pool, char __maybe_unused *b)
  1777. {
  1778. }
  1779. #endif
  1780. static int calculate_num_bits(int num)
  1781. {
  1782. int ret=0;
  1783. while(num != 0)
  1784. {
  1785. ret++;
  1786. num /= 16;
  1787. }
  1788. return ret;
  1789. }
  1790. static void get_vmask(struct pool *pool, char *bbversion)
  1791. {
  1792. char defaultStr[9]= "00000000";
  1793. int bversion, num_bits, i, j;
  1794. uint8_t buffer[4] = {};
  1795. uint32_t uiMagicNum;
  1796. char *tmpstr;
  1797. uint32_t *p1;
  1798. p1 = (uint32_t *)buffer;
  1799. bversion = strtol(bbversion, NULL, 16);
  1800. for (i = 0; i < 4; i++) {
  1801. uiMagicNum = bversion | pool->vmask_003[i];
  1802. //printf("[ccx]uiMagicNum:0x%x. \n", uiMagicNum);
  1803. *p1 = bswap_32(uiMagicNum);
  1804. //printf("[ccx]*p1:0x%x. \n", *p1);
  1805. switch(i) {
  1806. case 0:
  1807. pool->vmask_001[8] = *p1;
  1808. break;
  1809. case 1:
  1810. pool->vmask_001[4] = *p1;
  1811. break;
  1812. case 2:
  1813. pool->vmask_001[2] = *p1;
  1814. break;
  1815. case 3:
  1816. pool->vmask_001[0] = *p1;
  1817. break;
  1818. default:
  1819. break;
  1820. }
  1821. }
  1822. for (i = 0; i < 16; i++) {
  1823. if ((i!= 2) && (i!=4) && (i!=8))
  1824. pool->vmask_001[i] = pool->vmask_001[0];
  1825. }
  1826. for (i = 0; i < 16; i++)
  1827. memcpy(pool->vmask_002[i], defaultStr, 9);
  1828. for (i = 0; i < 3; i++) {
  1829. char cMask[12];
  1830. tmpstr = (char *)cgcalloc(9, 1);
  1831. num_bits = calculate_num_bits(pool->vmask_003[i]);
  1832. for (j = 0; j < (8-num_bits); j++)
  1833. tmpstr[j] = '0';
  1834. snprintf(cMask, 9, "%x", pool->vmask_003[i]);
  1835. memcpy(tmpstr + 8 - num_bits, cMask, num_bits);
  1836. tmpstr[8] = '\0';
  1837. //printf("[ccx]tmpstr:%s. \n", tmpstr);
  1838. switch(i) {
  1839. case 0:
  1840. memcpy(pool->vmask_002[8], tmpstr, 9);
  1841. break;
  1842. case 1:
  1843. memcpy(pool->vmask_002[4], tmpstr, 9);
  1844. break;
  1845. case 2:
  1846. memcpy(pool->vmask_002[2], tmpstr, 9);
  1847. break;
  1848. default:
  1849. break;
  1850. }
  1851. free(tmpstr);
  1852. }
  1853. }
  1854. static bool set_vmask(struct pool *pool, json_t *val)
  1855. {
  1856. int mask, tmpMask = 0, cnt = 0, i, rem;
  1857. const char *version_mask;
  1858. version_mask = json_string_value(val);
  1859. applog(LOG_INFO, "Pool %d version_mask:%s.", pool->pool_no, version_mask);
  1860. mask = strtol(version_mask, NULL, 16);
  1861. if (!mask)
  1862. return false;
  1863. pool->vmask_003[0] = mask;
  1864. while (mask % 16 == 0) {
  1865. cnt++;
  1866. mask /= 16;
  1867. }
  1868. if ((rem = mask % 16))
  1869. tmpMask = rem;
  1870. else if ((rem = mask % 8))
  1871. tmpMask = rem;
  1872. else if ((rem = mask % 4))
  1873. tmpMask = rem;
  1874. else if ((rem = mask % 2))
  1875. tmpMask = rem;
  1876. for (i = 0; i < cnt; i++)
  1877. tmpMask *= 16;
  1878. pool->vmask_003[2] = tmpMask;
  1879. pool->vmask_003[1] = pool->vmask_003[0] - tmpMask;
  1880. return true;
  1881. }
  1882. #ifdef USE_VMASK
  1883. #define STRATUM_VERSION_ROLLING "version-rolling"
  1884. #define STRATUM_VERSION_ROLLING_LEN (sizeof(STRATUM_VERSION_ROLLING) - 1)
  1885. /**
  1886. * Configures stratum mining based on connected hardware capabilities
  1887. * (version rolling etc.)
  1888. *
  1889. * Sample communication
  1890. * Request:
  1891. * {"id": 1, "method": "mining.configure", "params": [ ["version-rolling"], "version-rolling.mask": "ffffffff" }]}\n
  1892. * Response:
  1893. * {"id": 1, "result": { "version-rolling": True, "version-rolling.mask": "00003000" }, "error": null}\n
  1894. *
  1895. * @param pool
  1896. *
  1897. *
  1898. * @return
  1899. */
  1900. static bool configure_stratum_mining(struct pool *pool)
  1901. {
  1902. char s[RBUFSIZE];
  1903. char *response_str = NULL;
  1904. bool config_status = false;
  1905. bool version_rolling_status = false;
  1906. bool version_mask_valid = false;
  1907. const char *key;
  1908. json_t *response, *value, *res_val, *err_val;
  1909. json_error_t err;
  1910. #ifdef USE_GEKKO
  1911. if (!opt_gekko_boost)
  1912. return true;
  1913. #endif
  1914. snprintf(s, RBUFSIZE,
  1915. "{\"id\": %d, \"method\": \"mining.configure\", \"params\": "
  1916. "[[\""STRATUM_VERSION_ROLLING"\"], "
  1917. "{\""STRATUM_VERSION_ROLLING".mask\": \"%x\""
  1918. "}]}",
  1919. swork_id++, 0xffffffff);
  1920. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1921. applog(LOG_DEBUG, "Failed to send mining.configure");
  1922. goto out;
  1923. }
  1924. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1925. applog(LOG_DEBUG, "Timed out waiting for response in %s", __FUNCTION__);
  1926. goto out;
  1927. }
  1928. response_str = recv_line(pool);
  1929. if (!response_str)
  1930. goto out;
  1931. response = JSON_LOADS(response_str, &err);
  1932. free(response_str);
  1933. res_val = json_object_get(response, "result");
  1934. err_val = json_object_get(response, "error");
  1935. if (!res_val || json_is_null(res_val) ||
  1936. (err_val && !json_is_null(err_val))) {
  1937. char *ss;
  1938. if (err_val)
  1939. ss = json_dumps(err_val, JSON_INDENT(3));
  1940. else
  1941. ss = strdup("(unknown reason)");
  1942. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1943. free(ss);
  1944. goto json_response_error;
  1945. }
  1946. json_object_foreach(res_val, key, value) {
  1947. if (!strcasecmp(key, STRATUM_VERSION_ROLLING) &&
  1948. strlen(key) == STRATUM_VERSION_ROLLING_LEN)
  1949. version_rolling_status = json_boolean_value(value);
  1950. else if (!strcasecmp(key, STRATUM_VERSION_ROLLING ".mask"))
  1951. pool->vmask = version_mask_valid = set_vmask(pool, value);
  1952. else
  1953. applog(LOG_ERR, "JSON-RPC unexpected mining.configure value: %s", key);
  1954. }
  1955. /* Valid configuration for now only requires enabled version rolling and valid bit mask */
  1956. config_status = version_rolling_status && version_mask_valid;
  1957. json_response_error:
  1958. json_decref(response);
  1959. out:
  1960. return config_status;
  1961. }
  1962. #else
  1963. static inline bool configure_stratum_mining(struct pool __maybe_unused *pool)
  1964. {
  1965. return true;
  1966. }
  1967. #endif
  1968. static bool parse_notify(struct pool *pool, json_t *val)
  1969. {
  1970. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1971. *ntime, header[260];
  1972. unsigned char *cb1 = NULL, *cb2 = NULL;
  1973. size_t cb1_len, cb2_len, alloc_len;
  1974. bool clean, ret = false;
  1975. int merkles, i;
  1976. json_t *arr;
  1977. arr = json_array_get(val, 4);
  1978. if (!arr || !json_is_array(arr))
  1979. goto out;
  1980. merkles = json_array_size(arr);
  1981. job_id = json_array_string(val, 0);
  1982. prev_hash = __json_array_string(val, 1);
  1983. coinbase1 = json_array_string(val, 2);
  1984. coinbase2 = json_array_string(val, 3);
  1985. bbversion = __json_array_string(val, 5);
  1986. nbit = __json_array_string(val, 6);
  1987. ntime = __json_array_string(val, 7);
  1988. clean = json_is_true(json_array_get(val, 8));
  1989. get_vmask(pool, bbversion);
  1990. if (!valid_ascii(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||
  1991. !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||
  1992. !valid_hex(ntime)) {
  1993. /* Annoying but we must not leak memory */
  1994. free(job_id);
  1995. free(coinbase1);
  1996. free(coinbase2);
  1997. goto out;
  1998. }
  1999. cg_wlock(&pool->data_lock);
  2000. free(pool->swork.job_id);
  2001. pool->swork.job_id = job_id;
  2002. if (memcmp(pool->prev_hash, prev_hash, 64)) {
  2003. pool->swork.clean = true;
  2004. } else {
  2005. pool->swork.clean = clean;
  2006. }
  2007. snprintf(pool->prev_hash, 65, "%s", prev_hash);
  2008. cb1_len = strlen(coinbase1) / 2;
  2009. cb2_len = strlen(coinbase2) / 2;
  2010. snprintf(pool->bbversion, 9, "%s", bbversion);
  2011. snprintf(pool->nbit, 9, "%s", nbit);
  2012. snprintf(pool->ntime, 9, "%s", ntime);
  2013. if (pool->next_diff > 0) {
  2014. pool->sdiff = pool->next_diff;
  2015. pool->next_diff = pool->diff_after;
  2016. pool->diff_after = 0;
  2017. }
  2018. alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  2019. pool->nonce2_offset = cb1_len + pool->n1_len;
  2020. for (i = 0; i < pool->merkles; i++)
  2021. free(pool->swork.merkle_bin[i]);
  2022. if (merkles) {
  2023. pool->swork.merkle_bin = cgrealloc(pool->swork.merkle_bin,
  2024. sizeof(char *) * merkles + 1);
  2025. for (i = 0; i < merkles; i++) {
  2026. char *merkle = json_array_string(arr, i);
  2027. pool->swork.merkle_bin[i] = cgmalloc(32);
  2028. if (opt_protocol)
  2029. applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
  2030. ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  2031. free(merkle);
  2032. if (unlikely(!ret)) {
  2033. applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
  2034. goto out_unlock;
  2035. }
  2036. }
  2037. }
  2038. pool->merkles = merkles;
  2039. if (pool->merkles < 2)
  2040. pool->bad_work++;
  2041. if (clean)
  2042. pool->nonce2 = 0;
  2043. #if 0
  2044. header_len = strlen(pool->bbversion) +
  2045. strlen(pool->prev_hash);
  2046. /* merkle_hash */ 32 +
  2047. strlen(pool->ntime) +
  2048. strlen(pool->nbit) +
  2049. /* nonce */ 8 +
  2050. /* workpadding */ 96;
  2051. #endif
  2052. snprintf(header, 257,
  2053. "%s%s%s%s%s%s%s",
  2054. pool->bbversion,
  2055. pool->prev_hash,
  2056. blank_merkle,
  2057. pool->ntime,
  2058. pool->nbit,
  2059. "00000000", /* nonce */
  2060. workpadding);
  2061. ret = hex2bin(pool->header_bin, header, 128);
  2062. if (unlikely(!ret)) {
  2063. applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
  2064. goto out_unlock;
  2065. }
  2066. cb1 = alloca(cb1_len);
  2067. ret = hex2bin(cb1, coinbase1, cb1_len);
  2068. if (unlikely(!ret)) {
  2069. applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
  2070. goto out_unlock;
  2071. }
  2072. cb2 = alloca(cb2_len);
  2073. ret = hex2bin(cb2, coinbase2, cb2_len);
  2074. if (unlikely(!ret)) {
  2075. applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
  2076. goto out_unlock;
  2077. }
  2078. free(pool->coinbase);
  2079. pool->coinbase = cgcalloc(alloc_len, 1);
  2080. cg_memcpy(pool->coinbase, cb1, cb1_len);
  2081. if (pool->n1_len)
  2082. cg_memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  2083. cg_memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  2084. if (opt_debug || opt_decode) {
  2085. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  2086. if (opt_decode)
  2087. decode_exit(pool, cb);
  2088. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  2089. free(cb);
  2090. }
  2091. out_unlock:
  2092. cg_wunlock(&pool->data_lock);
  2093. if (opt_protocol) {
  2094. applog(LOG_DEBUG, "job_id: %s", job_id);
  2095. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  2096. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  2097. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  2098. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  2099. applog(LOG_DEBUG, "nbit: %s", nbit);
  2100. applog(LOG_DEBUG, "ntime: %s", ntime);
  2101. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  2102. }
  2103. free(coinbase1);
  2104. free(coinbase2);
  2105. /* A notify message is the closest stratum gets to a getwork */
  2106. pool->getwork_requested++;
  2107. total_getworks++;
  2108. if (pool == current_pool())
  2109. opt_work_update = true;
  2110. out:
  2111. return ret;
  2112. }
  2113. static bool parse_diff(struct pool *pool, json_t *val)
  2114. {
  2115. double old_diff, diff;
  2116. diff = json_number_value(json_array_get(val, 0));
  2117. if (diff <= 0)
  2118. return false;
  2119. /* We can only change one diff per notify so assume diffs are being
  2120. * stacked for successive notifies. */
  2121. cg_wlock(&pool->data_lock);
  2122. if (pool->next_diff)
  2123. pool->diff_after = diff;
  2124. else
  2125. pool->next_diff = diff;
  2126. old_diff = pool->sdiff;
  2127. cg_wunlock(&pool->data_lock);
  2128. if (old_diff != diff) {
  2129. int idiff = diff;
  2130. if ((double)idiff == diff)
  2131. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  2132. pool->pool_no, idiff);
  2133. else
  2134. applog(LOG_NOTICE, "Pool %d difficulty changed to %.1f",
  2135. pool->pool_no, diff);
  2136. } else
  2137. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  2138. diff);
  2139. return true;
  2140. }
  2141. static bool parse_extranonce(struct pool *pool, json_t *val)
  2142. {
  2143. char s[RBUFSIZE], *nonce1;
  2144. int n2size;
  2145. nonce1 = json_array_string(val, 0);
  2146. if (!valid_hex(nonce1)) {
  2147. applog(LOG_INFO, "Failed to get valid nonce1 in parse_extranonce");
  2148. return false;
  2149. }
  2150. n2size = json_integer_value(json_array_get(val, 1));
  2151. if (!n2size) {
  2152. applog(LOG_INFO, "Failed to get valid n2size in parse_extranonce");
  2153. free(nonce1);
  2154. return false;
  2155. }
  2156. cg_wlock(&pool->data_lock);
  2157. free(pool->nonce1);
  2158. pool->nonce1 = nonce1;
  2159. pool->n1_len = strlen(nonce1) / 2;
  2160. free(pool->nonce1bin);
  2161. pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
  2162. if (unlikely(!pool->nonce1bin))
  2163. quithere(1, "Failed to calloc pool->nonce1bin");
  2164. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2165. pool->n2size = n2size;
  2166. cg_wunlock(&pool->data_lock);
  2167. applog(LOG_NOTICE, "Pool %d extranonce change requested", pool->pool_no);
  2168. return true;
  2169. }
  2170. static void __suspend_stratum(struct pool *pool)
  2171. {
  2172. clear_sockbuf(pool);
  2173. pool->stratum_active = pool->stratum_notify = false;
  2174. if (pool->sock)
  2175. CLOSESOCKET(pool->sock);
  2176. pool->sock = 0;
  2177. }
  2178. static bool parse_reconnect(struct pool *pool, json_t *val)
  2179. {
  2180. char *sockaddr_url, *stratum_port, *tmp;
  2181. char *url, *port, address[256];
  2182. int port_no;
  2183. memset(address, 0, 255);
  2184. url = (char *)json_string_value(json_array_get(val, 0));
  2185. if (!url)
  2186. url = pool->sockaddr_url;
  2187. else {
  2188. char *dot_pool, *dot_reconnect;
  2189. dot_pool = strchr(pool->sockaddr_url, '.');
  2190. if (!dot_pool) {
  2191. applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
  2192. pool->sockaddr_url);
  2193. return false;
  2194. }
  2195. dot_reconnect = strchr(url, '.');
  2196. if (!dot_reconnect) {
  2197. applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
  2198. url);
  2199. return false;
  2200. }
  2201. if (strcmp(dot_pool, dot_reconnect)) {
  2202. applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
  2203. pool->sockaddr_url);
  2204. return false;
  2205. }
  2206. }
  2207. port_no = json_integer_value(json_array_get(val, 1));
  2208. if (port_no) {
  2209. port = alloca(256);
  2210. sprintf(port, "%d", port_no);
  2211. } else {
  2212. port = (char *)json_string_value(json_array_get(val, 1));
  2213. if (!port)
  2214. port = pool->stratum_port;
  2215. }
  2216. snprintf(address, 254, "%s:%s", url, port);
  2217. if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
  2218. return false;
  2219. applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
  2220. clear_pool_work(pool);
  2221. mutex_lock(&pool->stratum_lock);
  2222. __suspend_stratum(pool);
  2223. tmp = pool->sockaddr_url;
  2224. pool->sockaddr_url = sockaddr_url;
  2225. pool->stratum_url = pool->sockaddr_url;
  2226. free(tmp);
  2227. tmp = pool->stratum_port;
  2228. pool->stratum_port = stratum_port;
  2229. free(tmp);
  2230. mutex_unlock(&pool->stratum_lock);
  2231. return restart_stratum(pool);
  2232. }
  2233. static bool send_version(struct pool *pool, json_t *val)
  2234. {
  2235. json_t *id_val = json_object_get(val, "id");
  2236. char s[RBUFSIZE];
  2237. int id;
  2238. if (!id_val)
  2239. return false;
  2240. id = json_integer_value(json_object_get(val, "id"));
  2241. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\", \"error\": null}", id);
  2242. if (!stratum_send(pool, s, strlen(s)))
  2243. return false;
  2244. return true;
  2245. }
  2246. static bool send_pong(struct pool *pool, json_t *val)
  2247. {
  2248. json_t *id_val = json_object_get(val, "id");
  2249. char s[RBUFSIZE];
  2250. int id;
  2251. if (!id_val)
  2252. return false;
  2253. id = json_integer_value(json_object_get(val, "id"));
  2254. sprintf(s, "{\"id\": %d, \"result\": \"pong\", \"error\": null}", id);
  2255. if (!stratum_send(pool, s, strlen(s)))
  2256. return false;
  2257. return true;
  2258. }
  2259. static bool show_message(struct pool *pool, json_t *val)
  2260. {
  2261. char *msg;
  2262. if (!json_is_array(val))
  2263. return false;
  2264. msg = (char *)json_string_value(json_array_get(val, 0));
  2265. if (!msg)
  2266. return false;
  2267. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  2268. return true;
  2269. }
  2270. static bool parse_vmask(struct pool *pool, json_t *params)
  2271. {
  2272. bool ret = false;
  2273. if (!params) {
  2274. applog(LOG_INFO, "No params with parse_vmask given for pool %d",
  2275. pool->pool_no);
  2276. goto out;
  2277. }
  2278. if (json_is_array(params))
  2279. params = json_array_get(params, 0);
  2280. //if (!json_is_string(params) || !json_string_length(params)) { //wait cgliner fix this error
  2281. if (!json_is_string(params)) {
  2282. applog(LOG_INFO, "Params invalid string for parse_vmask for pool %d",
  2283. pool->pool_no);
  2284. goto out;
  2285. }
  2286. pool->vmask = set_vmask(pool, params);
  2287. ret = true;
  2288. out:
  2289. return ret;
  2290. }
  2291. bool parse_method(struct pool *pool, char *s)
  2292. {
  2293. json_t *val = NULL, *method, *err_val, *params;
  2294. json_error_t err;
  2295. bool ret = false;
  2296. char *buf;
  2297. if (!s)
  2298. goto out;
  2299. val = JSON_LOADS(s, &err);
  2300. if (!val) {
  2301. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2302. goto out;
  2303. }
  2304. method = json_object_get(val, "method");
  2305. if (!method)
  2306. goto out_decref;
  2307. err_val = json_object_get(val, "error");
  2308. params = json_object_get(val, "params");
  2309. if (err_val && !json_is_null(err_val)) {
  2310. char *ss;
  2311. if (err_val)
  2312. ss = json_dumps(err_val, JSON_INDENT(3));
  2313. else
  2314. ss = strdup("(unknown reason)");
  2315. applog(LOG_INFO, "JSON-RPC method decode of %s failed: %s", s, ss);
  2316. free(ss);
  2317. goto out_decref;
  2318. }
  2319. buf = (char *)json_string_value(method);
  2320. if (!buf)
  2321. goto out_decref;
  2322. if (!strncasecmp(buf, "mining.notify", 13)) {
  2323. if (parse_notify(pool, params))
  2324. pool->stratum_notify = ret = true;
  2325. else
  2326. pool->stratum_notify = ret = false;
  2327. goto out_decref;
  2328. }
  2329. if (!strncasecmp(buf, "mining.set_difficulty", 21)) {
  2330. ret = parse_diff(pool, params);
  2331. goto out_decref;
  2332. }
  2333. if (!strncasecmp(buf, "mining.set_extranonce", 21)) {
  2334. ret = parse_extranonce(pool, params);
  2335. goto out_decref;
  2336. }
  2337. if (!strncasecmp(buf, "client.reconnect", 16)) {
  2338. ret = parse_reconnect(pool, params);
  2339. goto out_decref;
  2340. }
  2341. if (!strncasecmp(buf, "client.get_version", 18)) {
  2342. ret = send_version(pool, val);
  2343. goto out_decref;
  2344. }
  2345. if (!strncasecmp(buf, "client.show_message", 19)) {
  2346. ret = show_message(pool, params);
  2347. goto out_decref;
  2348. }
  2349. if (!strncasecmp(buf, "mining.ping", 11)) {
  2350. applog(LOG_INFO, "Pool %d ping", pool->pool_no);
  2351. ret = send_pong(pool, val);
  2352. goto out_decref;
  2353. }
  2354. if (!strncasecmp(buf, "mining.set_version_mask", 23)) {
  2355. ret = parse_vmask(pool, params);
  2356. goto out_decref;
  2357. }
  2358. applog(LOG_INFO, "Unknown JSON-RPC from pool %d: %s", pool->pool_no, s);
  2359. out_decref:
  2360. json_decref(val);
  2361. out:
  2362. return ret;
  2363. }
  2364. bool subscribe_extranonce(struct pool *pool)
  2365. {
  2366. json_t *val = NULL, *res_val, *err_val;
  2367. char s[RBUFSIZE], *sret = NULL;
  2368. json_error_t err;
  2369. bool ret = false;
  2370. sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}",
  2371. swork_id++);
  2372. if (!stratum_send(pool, s, strlen(s)))
  2373. return ret;
  2374. /* Parse all data in the queue and anything left should be the response */
  2375. while (42) {
  2376. if (!socket_full(pool, DEFAULT_SOCKWAIT / 30)) {
  2377. applog(LOG_DEBUG, "Timed out waiting for response extranonce.subscribe");
  2378. /* some pool doesnt send anything, so this is normal */
  2379. ret = true;
  2380. goto out;
  2381. }
  2382. sret = recv_line(pool);
  2383. if (!sret)
  2384. return ret;
  2385. if (parse_method(pool, sret))
  2386. free(sret);
  2387. else
  2388. break;
  2389. }
  2390. val = JSON_LOADS(sret, &err);
  2391. free(sret);
  2392. res_val = json_object_get(val, "result");
  2393. err_val = json_object_get(val, "error");
  2394. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2395. char *ss;
  2396. if (err_val) {
  2397. ss = __json_array_string(err_val, 1);
  2398. if (!ss)
  2399. ss = (char *)json_string_value(err_val);
  2400. if (ss && (strcmp(ss, "Method 'subscribe' not found for service 'mining.extranonce'") == 0)) {
  2401. applog(LOG_INFO, "Cannot subscribe to mining.extranonce for pool %d", pool->pool_no);
  2402. ret = true;
  2403. goto out;
  2404. }
  2405. if (ss && (strcmp(ss, "Unrecognized request provided") == 0)) {
  2406. applog(LOG_INFO, "Cannot subscribe to mining.extranonce for pool %d", pool->pool_no);
  2407. ret = true;
  2408. goto out;
  2409. }
  2410. ss = json_dumps(err_val, JSON_INDENT(3));
  2411. }
  2412. else
  2413. ss = strdup("(unknown reason)");
  2414. applog(LOG_INFO, "Pool %d JSON extranonce subscribe failed: %s", pool->pool_no, ss);
  2415. free(ss);
  2416. goto out;
  2417. }
  2418. ret = true;
  2419. applog(LOG_INFO, "Stratum extranonce subscribe for pool %d", pool->pool_no);
  2420. out:
  2421. json_decref(val);
  2422. return ret;
  2423. }
  2424. bool auth_stratum(struct pool *pool)
  2425. {
  2426. json_t *val = NULL, *res_val, *err_val;
  2427. char s[RBUFSIZE], *sret = NULL;
  2428. json_error_t err;
  2429. bool ret = false;
  2430. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  2431. swork_id++, pool->rpc_user, pool->rpc_pass);
  2432. if (!stratum_send(pool, s, strlen(s)))
  2433. return ret;
  2434. /* Parse all data in the queue and anything left should be auth */
  2435. while (42) {
  2436. sret = recv_line(pool);
  2437. if (!sret)
  2438. return ret;
  2439. if (parse_method(pool, sret))
  2440. free(sret);
  2441. else
  2442. break;
  2443. }
  2444. val = JSON_LOADS(sret, &err);
  2445. free(sret);
  2446. res_val = json_object_get(val, "result");
  2447. err_val = json_object_get(val, "error");
  2448. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2449. char *ss;
  2450. if (err_val)
  2451. ss = json_dumps(err_val, JSON_INDENT(3));
  2452. else
  2453. ss = strdup("(unknown reason)");
  2454. applog(LOG_INFO, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  2455. free(ss);
  2456. suspend_stratum(pool);
  2457. goto out;
  2458. }
  2459. ret = true;
  2460. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  2461. pool->probed = true;
  2462. successful_connect = true;
  2463. if (opt_suggest_diff) {
  2464. sprintf(s, "{\"id\": %d, \"method\": \"mining.suggest_difficulty\", \"params\": [%d]}",
  2465. swork_id++, opt_suggest_diff);
  2466. stratum_send(pool, s, strlen(s));
  2467. }
  2468. out:
  2469. json_decref(val);
  2470. return ret;
  2471. }
  2472. static int recv_byte(int sockd)
  2473. {
  2474. char c;
  2475. if (recv(sockd, &c, 1, 0) != -1)
  2476. return c;
  2477. return -1;
  2478. }
  2479. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  2480. {
  2481. char buf[1024];
  2482. int i, len;
  2483. if (http0) {
  2484. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  2485. pool->sockaddr_url, pool->stratum_port);
  2486. } else {
  2487. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  2488. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  2489. pool->stratum_port);
  2490. }
  2491. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  2492. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2493. send(sockd, buf, strlen(buf), 0);
  2494. len = recv(sockd, buf, 12, 0);
  2495. if (len <= 0) {
  2496. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  2497. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2498. return false;
  2499. }
  2500. buf[len] = '\0';
  2501. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  2502. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2503. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  2504. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  2505. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2506. return false;
  2507. }
  2508. /* Ignore unwanted headers till we get desired response */
  2509. for (i = 0; i < 4; i++) {
  2510. buf[i] = recv_byte(sockd);
  2511. if (buf[i] == (char)-1) {
  2512. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2513. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2514. return false;
  2515. }
  2516. }
  2517. while (strncmp(buf, "\r\n\r\n", 4)) {
  2518. for (i = 0; i < 3; i++)
  2519. buf[i] = buf[i + 1];
  2520. buf[3] = recv_byte(sockd);
  2521. if (buf[3] == (char)-1) {
  2522. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2523. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2524. return false;
  2525. }
  2526. }
  2527. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  2528. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2529. return true;
  2530. }
  2531. static bool socks5_negotiate(struct pool *pool, int sockd)
  2532. {
  2533. unsigned char atyp, uclen;
  2534. unsigned short port;
  2535. char buf[515];
  2536. int i, len;
  2537. buf[0] = 0x05;
  2538. buf[1] = 0x01;
  2539. buf[2] = 0x00;
  2540. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  2541. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2542. send(sockd, buf, 3, 0);
  2543. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  2544. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2545. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2546. return false;
  2547. }
  2548. buf[0] = 0x05;
  2549. buf[1] = 0x01;
  2550. buf[2] = 0x00;
  2551. buf[3] = 0x03;
  2552. len = (strlen(pool->sockaddr_url));
  2553. if (len > 255)
  2554. len = 255;
  2555. uclen = len;
  2556. buf[4] = (uclen & 0xff);
  2557. cg_memcpy(buf + 5, pool->sockaddr_url, len);
  2558. port = atoi(pool->stratum_port);
  2559. buf[5 + len] = (port >> 8);
  2560. buf[6 + len] = (port & 0xff);
  2561. send(sockd, buf, (7 + len), 0);
  2562. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  2563. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2564. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2565. return false;
  2566. }
  2567. recv_byte(sockd);
  2568. atyp = recv_byte(sockd);
  2569. if (atyp == 0x01) {
  2570. for (i = 0; i < 4; i++)
  2571. recv_byte(sockd);
  2572. } else if (atyp == 0x03) {
  2573. len = recv_byte(sockd);
  2574. for (i = 0; i < len; i++)
  2575. recv_byte(sockd);
  2576. } else {
  2577. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2578. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2579. return false;
  2580. }
  2581. for (i = 0; i < 2; i++)
  2582. recv_byte(sockd);
  2583. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  2584. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2585. return true;
  2586. }
  2587. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  2588. {
  2589. unsigned short port;
  2590. in_addr_t inp;
  2591. char buf[515];
  2592. int i, len;
  2593. buf[0] = 0x04;
  2594. buf[1] = 0x01;
  2595. port = atoi(pool->stratum_port);
  2596. buf[2] = port >> 8;
  2597. buf[3] = port & 0xff;
  2598. sprintf(&buf[8], "CGMINER");
  2599. /* See if we've been given an IP address directly to avoid needing to
  2600. * resolve it. */
  2601. inp = inet_addr(pool->sockaddr_url);
  2602. inp = ntohl(inp);
  2603. if ((int)inp != -1)
  2604. socks4a = false;
  2605. else {
  2606. /* Try to extract the IP address ourselves first */
  2607. struct addrinfo servinfobase, *servinfo, hints;
  2608. servinfo = &servinfobase;
  2609. memset(&hints, 0, sizeof(struct addrinfo));
  2610. hints.ai_family = AF_INET; /* IPV4 only */
  2611. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  2612. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  2613. inp = ntohl(saddr_in->sin_addr.s_addr);
  2614. socks4a = false;
  2615. freeaddrinfo(servinfo);
  2616. }
  2617. }
  2618. if (!socks4a) {
  2619. if ((int)inp == -1) {
  2620. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  2621. pool->sockaddr_url);
  2622. return false;
  2623. }
  2624. buf[4] = (inp >> 24) & 0xFF;
  2625. buf[5] = (inp >> 16) & 0xFF;
  2626. buf[6] = (inp >> 8) & 0xFF;
  2627. buf[7] = (inp >> 0) & 0xFF;
  2628. send(sockd, buf, 16, 0);
  2629. } else {
  2630. /* This appears to not be working but hopefully most will be
  2631. * able to resolve IP addresses themselves. */
  2632. buf[4] = 0;
  2633. buf[5] = 0;
  2634. buf[6] = 0;
  2635. buf[7] = 1;
  2636. len = strlen(pool->sockaddr_url);
  2637. if (len > 255)
  2638. len = 255;
  2639. cg_memcpy(&buf[16], pool->sockaddr_url, len);
  2640. len += 16;
  2641. buf[len++] = '\0';
  2642. send(sockd, buf, len, 0);
  2643. }
  2644. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  2645. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  2646. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2647. return false;
  2648. }
  2649. for (i = 0; i < 6; i++)
  2650. recv_byte(sockd);
  2651. return true;
  2652. }
  2653. static void noblock_socket(SOCKETTYPE fd)
  2654. {
  2655. #ifndef WIN32
  2656. int flags = fcntl(fd, F_GETFL, 0);
  2657. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  2658. #else
  2659. u_long flags = 1;
  2660. ioctlsocket(fd, FIONBIO, &flags);
  2661. #endif
  2662. }
  2663. static void block_socket(SOCKETTYPE fd)
  2664. {
  2665. #ifndef WIN32
  2666. int flags = fcntl(fd, F_GETFL, 0);
  2667. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  2668. #else
  2669. u_long flags = 0;
  2670. ioctlsocket(fd, FIONBIO, &flags);
  2671. #endif
  2672. }
  2673. static bool sock_connecting(void)
  2674. {
  2675. #ifndef WIN32
  2676. return errno == EINPROGRESS;
  2677. #else
  2678. return WSAGetLastError() == WSAEWOULDBLOCK;
  2679. #endif
  2680. }
  2681. static bool setup_stratum_socket(struct pool *pool)
  2682. {
  2683. struct addrinfo *servinfo, hints, *p;
  2684. char *sockaddr_url, *sockaddr_port;
  2685. int sockd;
  2686. mutex_lock(&pool->stratum_lock);
  2687. pool->stratum_active = false;
  2688. if (pool->sock)
  2689. CLOSESOCKET(pool->sock);
  2690. pool->sock = 0;
  2691. mutex_unlock(&pool->stratum_lock);
  2692. memset(&hints, 0, sizeof(struct addrinfo));
  2693. hints.ai_family = AF_UNSPEC;
  2694. hints.ai_socktype = SOCK_STREAM;
  2695. if (!pool->rpc_proxy && opt_socks_proxy) {
  2696. pool->rpc_proxy = opt_socks_proxy;
  2697. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  2698. pool->rpc_proxytype = PROXY_SOCKS5;
  2699. }
  2700. if (pool->rpc_proxy) {
  2701. sockaddr_url = pool->sockaddr_proxy_url;
  2702. sockaddr_port = pool->sockaddr_proxy_port;
  2703. } else {
  2704. sockaddr_url = pool->sockaddr_url;
  2705. sockaddr_port = pool->stratum_port;
  2706. }
  2707. if (getaddrinfo(sockaddr_url, sockaddr_port, &hints, &servinfo) != 0) {
  2708. if (!pool->probed) {
  2709. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  2710. sockaddr_url, sockaddr_port);
  2711. pool->probed = true;
  2712. } else {
  2713. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  2714. sockaddr_url, sockaddr_port);
  2715. }
  2716. return false;
  2717. }
  2718. for (p = servinfo; p != NULL; p = p->ai_next) {
  2719. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  2720. if (sockd == -1) {
  2721. applog(LOG_DEBUG, "Failed socket");
  2722. continue;
  2723. }
  2724. /* Iterate non blocking over entries returned by getaddrinfo
  2725. * to cope with round robin DNS entries, finding the first one
  2726. * we can connect to quickly. */
  2727. noblock_socket(sockd);
  2728. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  2729. struct timeval tv_timeout = {1, 0};
  2730. int selret;
  2731. fd_set rw;
  2732. if (!sock_connecting()) {
  2733. CLOSESOCKET(sockd);
  2734. applog(LOG_DEBUG, "Failed sock connect");
  2735. continue;
  2736. }
  2737. retry:
  2738. FD_ZERO(&rw);
  2739. FD_SET(sockd, &rw);
  2740. selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
  2741. if (selret > 0 && FD_ISSET(sockd, &rw)) {
  2742. socklen_t len;
  2743. int err, n;
  2744. len = sizeof(err);
  2745. n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);
  2746. if (!n && !err) {
  2747. applog(LOG_DEBUG, "Succeeded delayed connect");
  2748. block_socket(sockd);
  2749. break;
  2750. }
  2751. }
  2752. if (selret < 0 && interrupted())
  2753. goto retry;
  2754. CLOSESOCKET(sockd);
  2755. applog(LOG_DEBUG, "Select timeout/failed connect");
  2756. continue;
  2757. }
  2758. applog(LOG_WARNING, "Succeeded immediate connect");
  2759. block_socket(sockd);
  2760. break;
  2761. }
  2762. if (p == NULL) {
  2763. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  2764. sockaddr_url, sockaddr_port);
  2765. freeaddrinfo(servinfo);
  2766. return false;
  2767. }
  2768. freeaddrinfo(servinfo);
  2769. if (pool->rpc_proxy) {
  2770. switch (pool->rpc_proxytype) {
  2771. case PROXY_HTTP_1_0:
  2772. if (!http_negotiate(pool, sockd, true))
  2773. return false;
  2774. break;
  2775. case PROXY_HTTP:
  2776. if (!http_negotiate(pool, sockd, false))
  2777. return false;
  2778. break;
  2779. case PROXY_SOCKS5:
  2780. case PROXY_SOCKS5H:
  2781. if (!socks5_negotiate(pool, sockd))
  2782. return false;
  2783. break;
  2784. case PROXY_SOCKS4:
  2785. if (!socks4_negotiate(pool, sockd, false))
  2786. return false;
  2787. break;
  2788. case PROXY_SOCKS4A:
  2789. if (!socks4_negotiate(pool, sockd, true))
  2790. return false;
  2791. break;
  2792. default:
  2793. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  2794. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2795. return false;
  2796. break;
  2797. }
  2798. }
  2799. if (!pool->sockbuf) {
  2800. pool->sockbuf = cgcalloc(RBUFSIZE, 1);
  2801. pool->sockbuf_size = RBUFSIZE;
  2802. }
  2803. pool->sock = sockd;
  2804. keep_sockalive(sockd);
  2805. return true;
  2806. }
  2807. static char *get_sessionid(json_t *val)
  2808. {
  2809. char *ret = NULL;
  2810. json_t *arr_val;
  2811. int arrsize, i;
  2812. arr_val = json_array_get(val, 0);
  2813. if (!arr_val || !json_is_array(arr_val))
  2814. goto out;
  2815. arrsize = json_array_size(arr_val);
  2816. for (i = 0; i < arrsize; i++) {
  2817. json_t *arr = json_array_get(arr_val, i);
  2818. char *notify;
  2819. if (!arr | !json_is_array(arr))
  2820. break;
  2821. notify = __json_array_string(arr, 0);
  2822. if (!notify)
  2823. continue;
  2824. if (!strncasecmp(notify, "mining.notify", 13)) {
  2825. ret = json_array_string(arr, 1);
  2826. break;
  2827. }
  2828. }
  2829. out:
  2830. return ret;
  2831. }
  2832. void suspend_stratum(struct pool *pool)
  2833. {
  2834. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2835. mutex_lock(&pool->stratum_lock);
  2836. __suspend_stratum(pool);
  2837. mutex_unlock(&pool->stratum_lock);
  2838. }
  2839. bool initiate_stratum(struct pool *pool)
  2840. {
  2841. bool ret = false, recvd = false, noresume = false, sockd = false;
  2842. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid, *tmp;
  2843. json_t *val = NULL, *res_val, *err_val;
  2844. json_error_t err;
  2845. int n2size;
  2846. resend:
  2847. if (!setup_stratum_socket(pool)) {
  2848. sockd = false;
  2849. goto out;
  2850. }
  2851. sockd = true;
  2852. if (recvd) {
  2853. /* Get rid of any crap lying around if we're resending */
  2854. clear_sock(pool);
  2855. }
  2856. /* Attempt to configure stratum protocol feature set first. */
  2857. if (!configure_stratum_mining(pool))
  2858. goto out;
  2859. if (recvd) {
  2860. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2861. } else {
  2862. if (pool->sessionid)
  2863. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\", \"%s\"]}", swork_id++, pool->sessionid);
  2864. else
  2865. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION""STRATUM_USER_AGENT"\"]}", swork_id++);
  2866. }
  2867. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  2868. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2869. goto out;
  2870. }
  2871. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2872. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2873. goto out;
  2874. }
  2875. rereceive:
  2876. sret = recv_line(pool);
  2877. if (!sret)
  2878. goto out;
  2879. recvd = true;
  2880. val = JSON_LOADS(sret, &err);
  2881. if (!val) {
  2882. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2883. goto out;
  2884. }
  2885. res_val = json_object_get(val, "result");
  2886. err_val = json_object_get(val, "error");
  2887. if (!res_val) {
  2888. /* Check for a method just in case */
  2889. json_t *method_val = json_object_get(val, "method");
  2890. if (method_val && parse_method(pool, sret)) {
  2891. free(sret);
  2892. sret = NULL;
  2893. goto rereceive;
  2894. }
  2895. }
  2896. if (!res_val || json_is_null(res_val) ||
  2897. (err_val && !json_is_null(err_val))) {
  2898. char *ss;
  2899. if (err_val)
  2900. ss = json_dumps(err_val, JSON_INDENT(3));
  2901. else
  2902. ss = strdup("(unknown reason)");
  2903. applog(LOG_INFO, "JSON-RPC decode of message %s failed: %s", sret, ss);
  2904. free(ss);
  2905. goto out;
  2906. }
  2907. sessionid = get_sessionid(res_val);
  2908. if (!sessionid)
  2909. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2910. nonce1 = json_array_string(res_val, 1);
  2911. if (!valid_hex(nonce1)) {
  2912. applog(LOG_INFO, "Failed to get valid nonce1 in initiate_stratum");
  2913. free(sessionid);
  2914. free(nonce1);
  2915. goto out;
  2916. }
  2917. n2size = json_integer_value(json_array_get(res_val, 2));
  2918. if (n2size < 2 || n2size > 16) {
  2919. applog(LOG_INFO, "Failed to get valid n2size in initiate_stratum");
  2920. free(sessionid);
  2921. free(nonce1);
  2922. goto out;
  2923. }
  2924. if (sessionid && pool->sessionid && !strcmp(sessionid, pool->sessionid)) {
  2925. applog(LOG_NOTICE, "Pool %d successfully negotiated resume with the same session ID",
  2926. pool->pool_no);
  2927. }
  2928. cg_wlock(&pool->data_lock);
  2929. tmp = pool->sessionid;
  2930. pool->sessionid = sessionid;
  2931. free(tmp);
  2932. tmp = pool->nonce1;
  2933. pool->nonce1 = nonce1;
  2934. free(tmp);
  2935. pool->n1_len = strlen(nonce1) / 2;
  2936. free(pool->nonce1bin);
  2937. pool->nonce1bin = cgcalloc(pool->n1_len, 1);
  2938. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2939. pool->n2size = n2size;
  2940. cg_wunlock(&pool->data_lock);
  2941. if (sessionid)
  2942. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2943. ret = true;
  2944. out:
  2945. if (ret) {
  2946. if (!pool->stratum_url)
  2947. pool->stratum_url = pool->sockaddr_url;
  2948. pool->stratum_active = true;
  2949. pool->next_diff = pool->diff_after = 0;
  2950. pool->sdiff = 1;
  2951. if (opt_protocol) {
  2952. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2953. pool->pool_no, pool->nonce1, pool->n2size);
  2954. }
  2955. } else {
  2956. if (recvd && !noresume) {
  2957. /* Reset the sessionid used for stratum resuming in case the pool
  2958. * does not support it, or does not know how to respond to the
  2959. * presence of the sessionid parameter. */
  2960. cg_wlock(&pool->data_lock);
  2961. free(pool->sessionid);
  2962. free(pool->nonce1);
  2963. pool->sessionid = pool->nonce1 = NULL;
  2964. cg_wunlock(&pool->data_lock);
  2965. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2966. noresume = true;
  2967. json_decref(val);
  2968. goto resend;
  2969. }
  2970. applog(LOG_DEBUG, "Initiate stratum failed");
  2971. if (sockd)
  2972. suspend_stratum(pool);
  2973. }
  2974. json_decref(val);
  2975. free(sret);
  2976. return ret;
  2977. }
  2978. bool restart_stratum(struct pool *pool)
  2979. {
  2980. bool ret = false;
  2981. if (pool->stratum_active)
  2982. suspend_stratum(pool);
  2983. if (!initiate_stratum(pool))
  2984. goto out;
  2985. if (pool->extranonce_subscribe && !subscribe_extranonce(pool))
  2986. goto out;
  2987. if (!auth_stratum(pool))
  2988. goto out;
  2989. ret = true;
  2990. out:
  2991. if (!ret)
  2992. pool_died(pool);
  2993. else
  2994. stratum_resumed(pool);
  2995. return ret;
  2996. }
  2997. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2998. {
  2999. dev->device_last_not_well = time(NULL);
  3000. dev->device_not_well_reason = reason;
  3001. switch (reason) {
  3002. case REASON_THREAD_FAIL_INIT:
  3003. dev->thread_fail_init_count++;
  3004. break;
  3005. case REASON_THREAD_ZERO_HASH:
  3006. dev->thread_zero_hash_count++;
  3007. break;
  3008. case REASON_THREAD_FAIL_QUEUE:
  3009. dev->thread_fail_queue_count++;
  3010. break;
  3011. case REASON_DEV_SICK_IDLE_60:
  3012. dev->dev_sick_idle_60_count++;
  3013. break;
  3014. case REASON_DEV_DEAD_IDLE_600:
  3015. dev->dev_dead_idle_600_count++;
  3016. break;
  3017. case REASON_DEV_NOSTART:
  3018. dev->dev_nostart_count++;
  3019. break;
  3020. case REASON_DEV_OVER_HEAT:
  3021. dev->dev_over_heat_count++;
  3022. break;
  3023. case REASON_DEV_THERMAL_CUTOFF:
  3024. dev->dev_thermal_cutoff_count++;
  3025. break;
  3026. case REASON_DEV_COMMS_ERROR:
  3027. dev->dev_comms_error_count++;
  3028. break;
  3029. case REASON_DEV_THROTTLE:
  3030. dev->dev_throttle_count++;
  3031. break;
  3032. }
  3033. }
  3034. /* Realloc an existing string to fit an extra string s, appending s to it. */
  3035. void *realloc_strcat(char *ptr, char *s)
  3036. {
  3037. size_t old = 0, len = strlen(s);
  3038. char *ret;
  3039. if (!len)
  3040. return ptr;
  3041. if (ptr)
  3042. old = strlen(ptr);
  3043. len += old + 1;
  3044. ret = cgmalloc(len);
  3045. if (ptr) {
  3046. sprintf(ret, "%s%s", ptr, s);
  3047. free(ptr);
  3048. } else
  3049. sprintf(ret, "%s", s);
  3050. return ret;
  3051. }
  3052. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  3053. * Including 0x00 at the end
  3054. * You must free the result yourself */
  3055. void *str_text(char *ptr)
  3056. {
  3057. unsigned char *uptr;
  3058. char *ret, *txt;
  3059. if (ptr == NULL) {
  3060. ret = strdup("(null)");
  3061. if (unlikely(!ret))
  3062. quithere(1, "Failed to malloc null");
  3063. }
  3064. uptr = (unsigned char *)ptr;
  3065. ret = txt = cgmalloc(strlen(ptr) * 4 + 5); // Guaranteed >= needed
  3066. do {
  3067. if (*uptr < ' ' || *uptr > '~') {
  3068. sprintf(txt, "0x%02x", *uptr);
  3069. txt += 4;
  3070. } else
  3071. *(txt++) = *uptr;
  3072. } while (*(uptr++));
  3073. *txt = '\0';
  3074. return ret;
  3075. }
  3076. void RenameThread(const char* name)
  3077. {
  3078. char buf[16];
  3079. snprintf(buf, sizeof(buf), "cg@%s", name);
  3080. #if defined(PR_SET_NAME)
  3081. // Only the first 15 characters are used (16 - NUL terminator)
  3082. prctl(PR_SET_NAME, buf, 0, 0, 0);
  3083. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  3084. pthread_set_name_np(pthread_self(), buf);
  3085. #elif defined(MAC_OSX)
  3086. pthread_setname_np(buf);
  3087. #else
  3088. // Prevent warnings
  3089. (void)buf;
  3090. #endif
  3091. }
  3092. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  3093. * that support them and for apple which does not. We use a single byte across
  3094. * a pipe to emulate semaphore behaviour there. */
  3095. #ifdef __APPLE__
  3096. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3097. {
  3098. int flags, fd, i;
  3099. if (pipe(cgsem->pipefd) == -1)
  3100. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  3101. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  3102. * execv on restart. */
  3103. for (i = 0; i < 2; i++) {
  3104. fd = cgsem->pipefd[i];
  3105. flags = fcntl(fd, F_GETFD, 0);
  3106. flags |= FD_CLOEXEC;
  3107. if (fcntl(fd, F_SETFD, flags) == -1)
  3108. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  3109. }
  3110. }
  3111. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3112. {
  3113. const char buf = 1;
  3114. int ret;
  3115. retry:
  3116. ret = write(cgsem->pipefd[1], &buf, 1);
  3117. if (unlikely(ret == 0))
  3118. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  3119. else if (unlikely(ret < 0 && interrupted()))
  3120. goto retry;
  3121. }
  3122. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3123. {
  3124. char buf;
  3125. int ret;
  3126. retry:
  3127. ret = read(cgsem->pipefd[0], &buf, 1);
  3128. if (unlikely(ret == 0))
  3129. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  3130. else if (unlikely(ret < 0 && interrupted())
  3131. goto retry;
  3132. }
  3133. void cgsem_destroy(cgsem_t *cgsem)
  3134. {
  3135. close(cgsem->pipefd[1]);
  3136. close(cgsem->pipefd[0]);
  3137. }
  3138. /* This is similar to sem_timedwait but takes a millisecond value */
  3139. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  3140. {
  3141. struct timeval timeout;
  3142. int ret, fd;
  3143. fd_set rd;
  3144. char buf;
  3145. retry:
  3146. fd = cgsem->pipefd[0];
  3147. FD_ZERO(&rd);
  3148. FD_SET(fd, &rd);
  3149. ms_to_timeval(&timeout, ms);
  3150. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  3151. if (ret > 0) {
  3152. ret = read(fd, &buf, 1);
  3153. return 0;
  3154. }
  3155. if (likely(!ret))
  3156. return ETIMEDOUT;
  3157. if (interrupted())
  3158. goto retry;
  3159. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  3160. /* We don't reach here */
  3161. return 0;
  3162. }
  3163. /* Reset semaphore count back to zero */
  3164. void cgsem_reset(cgsem_t *cgsem)
  3165. {
  3166. int ret, fd;
  3167. fd_set rd;
  3168. char buf;
  3169. fd = cgsem->pipefd[0];
  3170. FD_ZERO(&rd);
  3171. FD_SET(fd, &rd);
  3172. do {
  3173. struct timeval timeout = {0, 0};
  3174. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  3175. if (ret > 0)
  3176. ret = read(fd, &buf, 1);
  3177. else if (unlikely(ret < 0 && interrupted()))
  3178. ret = 1;
  3179. } while (ret > 0);
  3180. }
  3181. #else
  3182. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3183. {
  3184. int ret;
  3185. if ((ret = sem_init(cgsem, 0, 0)))
  3186. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  3187. }
  3188. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3189. {
  3190. if (unlikely(sem_post(cgsem)))
  3191. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  3192. }
  3193. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  3194. {
  3195. retry:
  3196. if (unlikely(sem_wait(cgsem))) {
  3197. if (interrupted())
  3198. goto retry;
  3199. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  3200. }
  3201. }
  3202. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  3203. {
  3204. struct timespec abs_timeout, tdiff;
  3205. int ret;
  3206. cgcond_time(&abs_timeout);
  3207. ms_to_timespec(&tdiff, ms);
  3208. timeraddspec(&abs_timeout, &tdiff);
  3209. retry:
  3210. ret = sem_timedwait(cgsem, &abs_timeout);
  3211. if (ret) {
  3212. if (likely(sock_timeout()))
  3213. return ETIMEDOUT;
  3214. if (interrupted())
  3215. goto retry;
  3216. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  3217. }
  3218. return 0;
  3219. }
  3220. void cgsem_reset(cgsem_t *cgsem)
  3221. {
  3222. int ret;
  3223. do {
  3224. ret = sem_trywait(cgsem);
  3225. if (unlikely(ret < 0 && interrupted()))
  3226. ret = 0;
  3227. } while (!ret);
  3228. }
  3229. void cgsem_destroy(cgsem_t *cgsem)
  3230. {
  3231. sem_destroy(cgsem);
  3232. }
  3233. #endif
  3234. /* Provide a completion_timeout helper function for unreliable functions that
  3235. * may die due to driver issues etc that time out if the function fails and
  3236. * can then reliably return. */
  3237. struct cg_completion {
  3238. cgsem_t cgsem;
  3239. void (*fn)(void *fnarg);
  3240. void *fnarg;
  3241. };
  3242. void *completion_thread(void *arg)
  3243. {
  3244. struct cg_completion *cgc = (struct cg_completion *)arg;
  3245. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3246. cgc->fn(cgc->fnarg);
  3247. cgsem_post(&cgc->cgsem);
  3248. return NULL;
  3249. }
  3250. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  3251. {
  3252. struct cg_completion *cgc;
  3253. pthread_t pthread;
  3254. bool ret = false;
  3255. cgc = cgmalloc(sizeof(struct cg_completion));
  3256. cgsem_init(&cgc->cgsem);
  3257. cgc->fn = fn;
  3258. cgc->fnarg = fnarg;
  3259. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  3260. ret = cgsem_mswait(&cgc->cgsem, timeout);
  3261. if (!ret) {
  3262. pthread_join(pthread, NULL);
  3263. free(cgc);
  3264. } else
  3265. pthread_cancel(pthread);
  3266. return !ret;
  3267. }
  3268. void _cg_memcpy(void *dest, const void *src, unsigned int n, const char *file, const char *func, const int line)
  3269. {
  3270. if (unlikely(n < 1 || n > (1ul << 31))) {
  3271. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from %s %s():%d",
  3272. n, file, func, line);
  3273. return;
  3274. }
  3275. if (unlikely(!dest)) {
  3276. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes to NULL from %s %s():%d",
  3277. n, file, func, line);
  3278. return;
  3279. }
  3280. if (unlikely(!src)) {
  3281. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from NULL from %s %s():%d",
  3282. n, file, func, line);
  3283. return;
  3284. }
  3285. memcpy(dest, src, n);
  3286. }