util.c 81 KB

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