util.c 87 KB

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