util.c.orig 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758
  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. void check_extranonce_option(struct pool *pool, char * url)
  1419. {
  1420. int i;
  1421. for (i = 0; url[i]; i++) url[i] = tolower(url[i]);
  1422. if (strstr(url, ".nicehash.com") || strstr(url, "#xnsub"))
  1423. {
  1424. pool->extranonce_subscribe = true;
  1425. applog(LOG_DEBUG, "Pool %d extranonce subscribe enabled.", pool->pool_no);
  1426. }
  1427. }
  1428. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1429. {
  1430. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1431. char url_address[256], port[6];
  1432. int url_len, port_len = 0;
  1433. *sockaddr_url = url;
  1434. url_begin = strstr(url, "//");
  1435. if (!url_begin)
  1436. url_begin = url;
  1437. else
  1438. url_begin += 2;
  1439. /* Look for numeric ipv6 entries */
  1440. ipv6_begin = strstr(url_begin, "[");
  1441. ipv6_end = strstr(url_begin, "]");
  1442. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1443. url_end = strstr(ipv6_end, ":");
  1444. else
  1445. url_end = strstr(url_begin, ":");
  1446. if (url_end) {
  1447. url_len = url_end - url_begin;
  1448. port_len = strlen(url_begin) - url_len - 1;
  1449. if (port_len < 1)
  1450. return false;
  1451. port_start = url_end + 1;
  1452. } else
  1453. url_len = strlen(url_begin);
  1454. if (url_len < 1)
  1455. return false;
  1456. /* Get rid of the [] */
  1457. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) {
  1458. url_len -= 2;
  1459. url_begin++;
  1460. }
  1461. snprintf(url_address, 254, "%.*s", url_len, url_begin);
  1462. if (port_len) {
  1463. char *slash;
  1464. snprintf(port, 6, "%.*s", port_len, port_start);
  1465. slash = strchr(port, '/');
  1466. if (slash)
  1467. *slash = '\0';
  1468. } else
  1469. strcpy(port, "80");
  1470. *sockaddr_port = strdup(port);
  1471. *sockaddr_url = strdup(url_address);
  1472. return true;
  1473. }
  1474. enum send_ret {
  1475. SEND_OK,
  1476. SEND_SELECTFAIL,
  1477. SEND_SENDFAIL,
  1478. SEND_INACTIVE
  1479. };
  1480. /* Send a single command across a socket, appending \n to it. This should all
  1481. * be done under stratum lock except when first establishing the socket */
  1482. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1483. {
  1484. SOCKETTYPE sock = pool->sock;
  1485. ssize_t ssent = 0;
  1486. strcat(s, "\n");
  1487. len++;
  1488. while (len > 0 ) {
  1489. struct timeval timeout = {1, 0};
  1490. ssize_t sent;
  1491. fd_set wd;
  1492. retry:
  1493. FD_ZERO(&wd);
  1494. FD_SET(sock, &wd);
  1495. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1496. if (interrupted())
  1497. goto retry;
  1498. return SEND_SELECTFAIL;
  1499. }
  1500. #ifdef __APPLE__
  1501. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1502. #elif WIN32
  1503. sent = send(pool->sock, s + ssent, len, 0);
  1504. #else
  1505. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1506. #endif
  1507. if (sent < 0) {
  1508. if (!sock_blocks())
  1509. return SEND_SENDFAIL;
  1510. sent = 0;
  1511. }
  1512. ssent += sent;
  1513. len -= sent;
  1514. }
  1515. pool->cgminer_pool_stats.times_sent++;
  1516. pool->cgminer_pool_stats.bytes_sent += ssent;
  1517. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1518. return SEND_OK;
  1519. }
  1520. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1521. {
  1522. enum send_ret ret = SEND_INACTIVE;
  1523. if (opt_protocol)
  1524. applog(LOG_DEBUG, "SEND: %s", s);
  1525. mutex_lock(&pool->stratum_lock);
  1526. if (pool->stratum_active)
  1527. ret = __stratum_send(pool, s, len);
  1528. mutex_unlock(&pool->stratum_lock);
  1529. /* This is to avoid doing applog under stratum_lock */
  1530. switch (ret) {
  1531. default:
  1532. case SEND_OK:
  1533. break;
  1534. case SEND_SELECTFAIL:
  1535. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1536. suspend_stratum(pool);
  1537. break;
  1538. case SEND_SENDFAIL:
  1539. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1540. suspend_stratum(pool);
  1541. break;
  1542. case SEND_INACTIVE:
  1543. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1544. break;
  1545. }
  1546. return (ret == SEND_OK);
  1547. }
  1548. static bool socket_full(struct pool *pool, int wait)
  1549. {
  1550. SOCKETTYPE sock = pool->sock;
  1551. struct timeval timeout;
  1552. fd_set rd;
  1553. if (unlikely(wait < 0))
  1554. wait = 0;
  1555. FD_ZERO(&rd);
  1556. FD_SET(sock, &rd);
  1557. timeout.tv_usec = 0;
  1558. timeout.tv_sec = wait;
  1559. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1560. return true;
  1561. return false;
  1562. }
  1563. /* Check to see if Santa's been good to you */
  1564. bool sock_full(struct pool *pool)
  1565. {
  1566. if (strlen(pool->sockbuf))
  1567. return true;
  1568. return (socket_full(pool, 0));
  1569. }
  1570. static void clear_sockbuf(struct pool *pool)
  1571. {
  1572. if (likely(pool->sockbuf))
  1573. strcpy(pool->sockbuf, "");
  1574. }
  1575. static void clear_sock(struct pool *pool)
  1576. {
  1577. ssize_t n;
  1578. mutex_lock(&pool->stratum_lock);
  1579. do {
  1580. if (pool->sock)
  1581. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1582. else
  1583. n = 0;
  1584. } while (n > 0);
  1585. mutex_unlock(&pool->stratum_lock);
  1586. clear_sockbuf(pool);
  1587. }
  1588. /* Realloc memory to new size and zero any extra memory added */
  1589. void _recalloc(void **ptr, size_t old, size_t new, const char *file, const char *func, const int line)
  1590. {
  1591. if (new == old)
  1592. return;
  1593. *ptr = realloc(*ptr, new);
  1594. if (unlikely(!*ptr))
  1595. quitfrom(1, file, func, line, "Failed to realloc");
  1596. if (new > old)
  1597. memset(*ptr + old, 0, new - old);
  1598. }
  1599. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1600. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1601. * and zeroing the new memory */
  1602. static void recalloc_sock(struct pool *pool, size_t len)
  1603. {
  1604. size_t old, new;
  1605. old = strlen(pool->sockbuf);
  1606. new = old + len + 1;
  1607. if (new < pool->sockbuf_size)
  1608. return;
  1609. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1610. // Avoid potentially recursive locking
  1611. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1612. pool->sockbuf = realloc(pool->sockbuf, new);
  1613. if (!pool->sockbuf)
  1614. quithere(1, "Failed to realloc pool sockbuf");
  1615. memset(pool->sockbuf + old, 0, new - old);
  1616. pool->sockbuf_size = new;
  1617. }
  1618. /* Peeks at a socket to find the first end of line and then reads just that
  1619. * from the socket and returns that as a malloced char */
  1620. char *recv_line(struct pool *pool)
  1621. {
  1622. char *tok, *sret = NULL;
  1623. ssize_t len, buflen;
  1624. int waited = 0;
  1625. if (!strstr(pool->sockbuf, "\n")) {
  1626. struct timeval rstart, now;
  1627. cgtime(&rstart);
  1628. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1629. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1630. goto out;
  1631. }
  1632. do {
  1633. char s[RBUFSIZE];
  1634. size_t slen;
  1635. ssize_t n;
  1636. memset(s, 0, RBUFSIZE);
  1637. n = recv(pool->sock, s, RECVSIZE, 0);
  1638. if (!n) {
  1639. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1640. suspend_stratum(pool);
  1641. break;
  1642. }
  1643. cgtime(&now);
  1644. waited = tdiff(&now, &rstart);
  1645. if (n < 0) {
  1646. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1647. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1648. suspend_stratum(pool);
  1649. break;
  1650. }
  1651. } else {
  1652. slen = strlen(s);
  1653. recalloc_sock(pool, slen);
  1654. strcat(pool->sockbuf, s);
  1655. }
  1656. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1657. }
  1658. buflen = strlen(pool->sockbuf);
  1659. tok = strtok(pool->sockbuf, "\n");
  1660. if (!tok) {
  1661. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1662. goto out;
  1663. }
  1664. sret = strdup(tok);
  1665. len = strlen(sret);
  1666. /* Copy what's left in the buffer after the \n, including the
  1667. * terminating \0 */
  1668. if (buflen > len + 1)
  1669. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1670. else
  1671. strcpy(pool->sockbuf, "");
  1672. pool->cgminer_pool_stats.times_received++;
  1673. pool->cgminer_pool_stats.bytes_received += len;
  1674. pool->cgminer_pool_stats.net_bytes_received += len;
  1675. out:
  1676. if (!sret)
  1677. clear_sock(pool);
  1678. else if (opt_protocol)
  1679. applog(LOG_DEBUG, "RECVD: %s", sret);
  1680. return sret;
  1681. }
  1682. /* Extracts a string value from a json array with error checking. To be used
  1683. * when the value of the string returned is only examined and not to be stored.
  1684. * See json_array_string below */
  1685. static char *__json_array_string(json_t *val, unsigned int entry)
  1686. {
  1687. json_t *arr_entry;
  1688. if (json_is_null(val))
  1689. return NULL;
  1690. if (!json_is_array(val))
  1691. return NULL;
  1692. if (entry > json_array_size(val))
  1693. return NULL;
  1694. arr_entry = json_array_get(val, entry);
  1695. if (!json_is_string(arr_entry))
  1696. return NULL;
  1697. return (char *)json_string_value(arr_entry);
  1698. }
  1699. /* Creates a freshly malloced dup of __json_array_string */
  1700. static char *json_array_string(json_t *val, unsigned int entry)
  1701. {
  1702. char *buf = __json_array_string(val, entry);
  1703. if (buf)
  1704. return strdup(buf);
  1705. return NULL;
  1706. }
  1707. static char *blank_merkle = "0000000000000000000000000000000000000000000000000000000000000000";
  1708. static bool parse_notify(struct pool *pool, json_t *val)
  1709. {
  1710. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1711. *ntime, header[228];
  1712. unsigned char *cb1 = NULL, *cb2 = NULL;
  1713. size_t cb1_len, cb2_len, alloc_len;
  1714. bool clean, ret = false;
  1715. int merkles, i;
  1716. json_t *arr;
  1717. arr = json_array_get(val, 4);
  1718. if (!arr || !json_is_array(arr))
  1719. goto out;
  1720. merkles = json_array_size(arr);
  1721. job_id = json_array_string(val, 0);
  1722. prev_hash = __json_array_string(val, 1);
  1723. coinbase1 = json_array_string(val, 2);
  1724. coinbase2 = json_array_string(val, 3);
  1725. bbversion = __json_array_string(val, 5);
  1726. nbit = __json_array_string(val, 6);
  1727. ntime = __json_array_string(val, 7);
  1728. clean = json_is_true(json_array_get(val, 8));
  1729. if (!valid_ascii(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||
  1730. !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||
  1731. !valid_hex(ntime)) {
  1732. /* Annoying but we must not leak memory */
  1733. free(job_id);
  1734. free(coinbase1);
  1735. free(coinbase2);
  1736. goto out;
  1737. }
  1738. cg_wlock(&pool->data_lock);
  1739. free(pool->swork.job_id);
  1740. pool->swork.job_id = job_id;
  1741. snprintf(pool->prev_hash, 65, "%s", prev_hash);
  1742. cb1_len = strlen(coinbase1) / 2;
  1743. cb2_len = strlen(coinbase2) / 2;
  1744. snprintf(pool->bbversion, 9, "%s", bbversion);
  1745. snprintf(pool->nbit, 9, "%s", nbit);
  1746. snprintf(pool->ntime, 9, "%s", ntime);
  1747. pool->swork.clean = clean;
  1748. if (pool->next_diff > 0) {
  1749. pool->sdiff = pool->next_diff;
  1750. }
  1751. alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  1752. pool->nonce2_offset = cb1_len + pool->n1_len;
  1753. for (i = 0; i < pool->merkles; i++)
  1754. free(pool->swork.merkle_bin[i]);
  1755. if (merkles) {
  1756. pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
  1757. sizeof(char *) * merkles + 1);
  1758. for (i = 0; i < merkles; i++) {
  1759. char *merkle = json_array_string(arr, i);
  1760. pool->swork.merkle_bin[i] = malloc(32);
  1761. if (unlikely(!pool->swork.merkle_bin[i]))
  1762. quit(1, "Failed to malloc pool swork merkle_bin");
  1763. if (opt_protocol)
  1764. applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
  1765. ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  1766. free(merkle);
  1767. if (unlikely(!ret)) {
  1768. applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
  1769. goto out_unlock;
  1770. }
  1771. }
  1772. }
  1773. pool->merkles = merkles;
  1774. if (clean)
  1775. pool->nonce2 = 0;
  1776. #if 0
  1777. header_len = strlen(pool->bbversion) +
  1778. strlen(pool->prev_hash);
  1779. /* merkle_hash */ 32 +
  1780. strlen(pool->ntime) +
  1781. strlen(pool->nbit) +
  1782. /* nonce */ 8 +
  1783. /* workpadding */ 96;
  1784. #endif
  1785. snprintf(header, 225,
  1786. "%s%s%s%s%s%s%s",
  1787. pool->bbversion,
  1788. pool->prev_hash,
  1789. blank_merkle,
  1790. pool->ntime,
  1791. pool->nbit,
  1792. "00000000", /* nonce */
  1793. workpadding);
  1794. ret = hex2bin(pool->header_bin, header, 112);
  1795. if (unlikely(!ret)) {
  1796. applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
  1797. goto out_unlock;
  1798. }
  1799. cb1 = alloca(cb1_len);
  1800. ret = hex2bin(cb1, coinbase1, cb1_len);
  1801. if (unlikely(!ret)) {
  1802. applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
  1803. goto out_unlock;
  1804. }
  1805. cb2 = alloca(cb2_len);
  1806. ret = hex2bin(cb2, coinbase2, cb2_len);
  1807. if (unlikely(!ret)) {
  1808. applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
  1809. goto out_unlock;
  1810. }
  1811. free(pool->coinbase);
  1812. align_len(&alloc_len);
  1813. pool->coinbase = calloc(alloc_len, 1);
  1814. if (unlikely(!pool->coinbase))
  1815. quit(1, "Failed to calloc pool coinbase in parse_notify");
  1816. memcpy(pool->coinbase, cb1, cb1_len);
  1817. memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  1818. memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  1819. if (opt_debug) {
  1820. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  1821. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  1822. free(cb);
  1823. }
  1824. out_unlock:
  1825. cg_wunlock(&pool->data_lock);
  1826. if (opt_protocol) {
  1827. applog(LOG_DEBUG, "job_id: %s", job_id);
  1828. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1829. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1830. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1831. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1832. applog(LOG_DEBUG, "nbit: %s", nbit);
  1833. applog(LOG_DEBUG, "ntime: %s", ntime);
  1834. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1835. }
  1836. free(coinbase1);
  1837. free(coinbase2);
  1838. /* A notify message is the closest stratum gets to a getwork */
  1839. pool->getwork_requested++;
  1840. total_getworks++;
  1841. if (pool == current_pool())
  1842. opt_work_update = true;
  1843. out:
  1844. return ret;
  1845. }
  1846. static bool parse_diff(struct pool *pool, json_t *val)
  1847. {
  1848. double old_diff, diff;
  1849. diff = json_number_value(json_array_get(val, 0));
  1850. if (diff == 0)
  1851. return false;
  1852. cg_wlock(&pool->data_lock);
  1853. if (pool->next_diff > 0) {
  1854. old_diff = pool->next_diff;
  1855. pool->next_diff = diff;
  1856. } else {
  1857. old_diff = pool->sdiff;
  1858. pool->next_diff = pool->sdiff = diff;
  1859. }
  1860. cg_wunlock(&pool->data_lock);
  1861. if (old_diff != diff) {
  1862. int idiff = diff;
  1863. if ((double)idiff == diff)
  1864. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  1865. pool->pool_no, idiff);
  1866. else
  1867. applog(LOG_NOTICE, "Pool %d difficulty changed to %.1f",
  1868. pool->pool_no, diff);
  1869. } else
  1870. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  1871. diff);
  1872. return true;
  1873. }
  1874. static bool parse_extranonce(struct pool *pool, json_t *val)
  1875. {
  1876. int n2size;
  1877. char* nonce1;
  1878. nonce1 = json_array_string(val, 0);
  1879. if (!valid_hex(nonce1)) {
  1880. applog(LOG_INFO, "Failed to get valid nonce1 in parse_extranonce");
  1881. goto out;
  1882. }
  1883. n2size = json_integer_value(json_array_get(val, 1));
  1884. if (n2size < 2 || n2size > 16) {
  1885. applog(LOG_INFO, "Failed to get valid n2size in parse_extranonce");
  1886. free(nonce1);
  1887. goto out;
  1888. }
  1889. cg_wlock(&pool->data_lock);
  1890. pool->nonce1 = nonce1;
  1891. pool->n1_len = strlen(nonce1) / 2;
  1892. free(pool->nonce1bin);
  1893. pool->nonce1bin = calloc(pool->n1_len, 1);
  1894. if (unlikely(!pool->nonce1bin))
  1895. quithere(1, "Failed to calloc pool->nonce1bin");
  1896. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  1897. pool->n2size = n2size;
  1898. applog(LOG_NOTICE, "Pool %d confirmed mining.extranonce.subscribe with extranonce1 %s extran2size %d",
  1899. pool->pool_no, pool->nonce1, pool->n2size);
  1900. cg_wunlock(&pool->data_lock);
  1901. return true;
  1902. out:
  1903. return false;
  1904. }
  1905. static bool parse_extranonce(struct pool *pool, json_t *val)
  1906. {
  1907. int n2size;
  1908. char* nonce1;
  1909. nonce1 = json_array_string(val, 0);
  1910. if (!valid_hex(nonce1)) {
  1911. applog(LOG_INFO, "Failed to get valid nonce1 in parse_extranonce");
  1912. goto out;
  1913. }
  1914. n2size = json_integer_value(json_array_get(val, 1));
  1915. if (n2size < 2 || n2size > 16) {
  1916. applog(LOG_INFO, "Failed to get valid n2size in parse_extranonce");
  1917. free(nonce1);
  1918. goto out;
  1919. }
  1920. cg_wlock(&pool->data_lock);
  1921. pool->nonce1 = nonce1;
  1922. pool->n1_len = strlen(nonce1) / 2;
  1923. free(pool->nonce1bin);
  1924. pool->nonce1bin = calloc(pool->n1_len, 1);
  1925. if (unlikely(!pool->nonce1bin))
  1926. quithere(1, "Failed to calloc pool->nonce1bin");
  1927. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  1928. pool->n2size = n2size;
  1929. applog(LOG_NOTICE, "Pool %d confirmed mining.extranonce.subscribe with extranonce1 %s extran2size %d",
  1930. pool->pool_no, pool->nonce1, pool->n2size);
  1931. cg_wunlock(&pool->data_lock);
  1932. return true;
  1933. out:
  1934. return false;
  1935. }
  1936. static void __suspend_stratum(struct pool *pool)
  1937. {
  1938. clear_sockbuf(pool);
  1939. pool->stratum_active = pool->stratum_notify = false;
  1940. if (pool->sock)
  1941. CLOSESOCKET(pool->sock);
  1942. pool->sock = 0;
  1943. }
  1944. static bool parse_reconnect(struct pool *pool, json_t *val)
  1945. {
  1946. char *sockaddr_url, *stratum_port, *tmp;
  1947. char *url, *port, address[256];
  1948. memset(address, 0, 255);
  1949. url = (char *)json_string_value(json_array_get(val, 0));
  1950. if (!url)
  1951. url = pool->sockaddr_url;
  1952. else {
  1953. char *dot_pool, *dot_reconnect;
  1954. dot_pool = strchr(pool->sockaddr_url, '.');
  1955. if (!dot_pool) {
  1956. applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
  1957. pool->sockaddr_url);
  1958. return false;
  1959. }
  1960. dot_reconnect = strchr(url, '.');
  1961. if (!dot_reconnect) {
  1962. applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
  1963. url);
  1964. return false;
  1965. }
  1966. if (strcmp(dot_pool, dot_reconnect)) {
  1967. applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
  1968. pool->sockaddr_url);
  1969. return false;
  1970. }
  1971. }
  1972. port = (char *)json_string_value(json_array_get(val, 1));
  1973. if (!port)
  1974. port = pool->stratum_port;
  1975. snprintf(address, 254, "%s:%s", url, port);
  1976. if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
  1977. return false;
  1978. applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
  1979. clear_pool_work(pool);
  1980. mutex_lock(&pool->stratum_lock);
  1981. __suspend_stratum(pool);
  1982. tmp = pool->sockaddr_url;
  1983. pool->sockaddr_url = sockaddr_url;
  1984. pool->stratum_url = pool->sockaddr_url;
  1985. free(tmp);
  1986. tmp = pool->stratum_port;
  1987. pool->stratum_port = stratum_port;
  1988. free(tmp);
  1989. mutex_unlock(&pool->stratum_lock);
  1990. return restart_stratum(pool);
  1991. }
  1992. static bool send_version(struct pool *pool, json_t *val)
  1993. {
  1994. json_t *id_val = json_object_get(val, "id");
  1995. char s[RBUFSIZE];
  1996. int id;
  1997. if (!id_val)
  1998. return false;
  1999. id = json_integer_value(json_object_get(val, "id"));
  2000. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  2001. if (!stratum_send(pool, s, strlen(s)))
  2002. return false;
  2003. return true;
  2004. }
  2005. static bool send_pong(struct pool *pool, json_t *val)
  2006. {
  2007. json_t *id_val = json_object_get(val, "id");
  2008. char s[RBUFSIZE];
  2009. int id;
  2010. if (!id_val)
  2011. return false;
  2012. id = json_integer_value(json_object_get(val, "id"));
  2013. sprintf(s, "{\"id\": %d, \"result\": \"pong\", \"error\": null}", id);
  2014. if (!stratum_send(pool, s, strlen(s)))
  2015. return false;
  2016. return true;
  2017. }
  2018. static bool show_message(struct pool *pool, json_t *val)
  2019. {
  2020. char *msg;
  2021. if (!json_is_array(val))
  2022. return false;
  2023. msg = (char *)json_string_value(json_array_get(val, 0));
  2024. if (!msg)
  2025. return false;
  2026. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  2027. return true;
  2028. }
  2029. bool parse_method(struct pool *pool, char *s)
  2030. {
  2031. json_t *val = NULL, *method, *err_val, *params;
  2032. json_error_t err;
  2033. bool ret = false;
  2034. char *buf;
  2035. if (!s)
  2036. goto out;
  2037. val = JSON_LOADS(s, &err);
  2038. if (!val) {
  2039. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2040. goto out;
  2041. }
  2042. method = json_object_get(val, "method");
  2043. if (!method)
  2044. goto out_decref;
  2045. err_val = json_object_get(val, "error");
  2046. params = json_object_get(val, "params");
  2047. if (err_val && !json_is_null(err_val)) {
  2048. char *ss;
  2049. if (err_val)
  2050. ss = json_dumps(err_val, JSON_INDENT(3));
  2051. else
  2052. ss = strdup("(unknown reason)");
  2053. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  2054. free(ss);
  2055. goto out_decref;
  2056. }
  2057. buf = (char *)json_string_value(method);
  2058. if (!buf)
  2059. goto out_decref;
  2060. if (!strncasecmp(buf, "mining.notify", 13)) {
  2061. if (parse_notify(pool, params))
  2062. pool->stratum_notify = ret = true;
  2063. else
  2064. pool->stratum_notify = ret = false;
  2065. goto out_decref;
  2066. }
  2067. if(!strncasecmp(buf, "mining.set_extranonce", 21)) {
  2068. ret = parse_extranonce(pool, params);
  2069. goto out_decref;
  2070. }
  2071. if (!strncasecmp(buf, "mining.set_difficulty", 21)) {
  2072. ret = parse_diff(pool, params);
  2073. goto out_decref;
  2074. }
  2075. if(!strncasecmp(buf, "mining.set_extranonce", 21)) {
  2076. ret = parse_extranonce(pool, params);
  2077. goto out_decref;
  2078. }
  2079. if (!strncasecmp(buf, "client.reconnect", 16)) {
  2080. ret = parse_reconnect(pool, params);
  2081. goto out_decref;
  2082. }
  2083. if (!strncasecmp(buf, "client.get_version", 18)) {
  2084. ret = send_version(pool, val);
  2085. goto out_decref;
  2086. }
  2087. if (!strncasecmp(buf, "client.show_message", 19)) {
  2088. ret = show_message(pool, params);
  2089. goto out_decref;
  2090. }
  2091. if (!strncasecmp(buf, "mining.ping", 11)) {
  2092. applog(LOG_INFO, "Pool %d ping", pool->pool_no);
  2093. ret = send_pong(pool, val);
  2094. goto out_decref;
  2095. }
  2096. out_decref:
  2097. json_decref(val);
  2098. out:
  2099. return ret;
  2100. }
  2101. bool auth_stratum(struct pool *pool)
  2102. {
  2103. json_t *val = NULL, *res_val, *err_val;
  2104. char s[RBUFSIZE], *sret = NULL;
  2105. json_error_t err;
  2106. bool ret = false;
  2107. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  2108. swork_id++, pool->rpc_user, pool->rpc_pass);
  2109. if (!stratum_send(pool, s, strlen(s)))
  2110. return ret;
  2111. /* Parse all data in the queue and anything left should be auth */
  2112. while (42) {
  2113. sret = recv_line(pool);
  2114. if (!sret)
  2115. return ret;
  2116. if (parse_method(pool, sret))
  2117. free(sret);
  2118. else
  2119. break;
  2120. }
  2121. val = JSON_LOADS(sret, &err);
  2122. free(sret);
  2123. res_val = json_object_get(val, "result");
  2124. err_val = json_object_get(val, "error");
  2125. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  2126. char *ss;
  2127. if (err_val)
  2128. ss = json_dumps(err_val, JSON_INDENT(3));
  2129. else
  2130. ss = strdup("(unknown reason)");
  2131. applog(LOG_INFO, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  2132. free(ss);
  2133. suspend_stratum(pool);
  2134. goto out;
  2135. }
  2136. ret = true;
  2137. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  2138. pool->probed = true;
  2139. successful_connect = true;
  2140. if (opt_suggest_diff) {
  2141. sprintf(s, "{\"id\": %d, \"method\": \"mining.suggest_difficulty\", \"params\": [%d]}",
  2142. swork_id++, opt_suggest_diff);
  2143. stratum_send(pool, s, strlen(s));
  2144. }
  2145. out:
  2146. json_decref(val);
  2147. return ret;
  2148. }
  2149. static int recv_byte(int sockd)
  2150. {
  2151. char c;
  2152. if (recv(sockd, &c, 1, 0) != -1)
  2153. return c;
  2154. return -1;
  2155. }
  2156. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  2157. {
  2158. char buf[1024];
  2159. int i, len;
  2160. if (http0) {
  2161. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  2162. pool->sockaddr_url, pool->stratum_port);
  2163. } else {
  2164. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  2165. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  2166. pool->stratum_port);
  2167. }
  2168. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  2169. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2170. send(sockd, buf, strlen(buf), 0);
  2171. len = recv(sockd, buf, 12, 0);
  2172. if (len <= 0) {
  2173. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  2174. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2175. return false;
  2176. }
  2177. buf[len] = '\0';
  2178. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  2179. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2180. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  2181. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  2182. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  2183. return false;
  2184. }
  2185. /* Ignore unwanted headers till we get desired response */
  2186. for (i = 0; i < 4; i++) {
  2187. buf[i] = recv_byte(sockd);
  2188. if (buf[i] == (char)-1) {
  2189. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2190. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2191. return false;
  2192. }
  2193. }
  2194. while (strncmp(buf, "\r\n\r\n", 4)) {
  2195. for (i = 0; i < 3; i++)
  2196. buf[i] = buf[i + 1];
  2197. buf[3] = recv_byte(sockd);
  2198. if (buf[3] == (char)-1) {
  2199. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  2200. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2201. return false;
  2202. }
  2203. }
  2204. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  2205. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2206. return true;
  2207. }
  2208. static bool socks5_negotiate(struct pool *pool, int sockd)
  2209. {
  2210. unsigned char atyp, uclen;
  2211. unsigned short port;
  2212. char buf[515];
  2213. int i, len;
  2214. buf[0] = 0x05;
  2215. buf[1] = 0x01;
  2216. buf[2] = 0x00;
  2217. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  2218. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2219. send(sockd, buf, 3, 0);
  2220. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  2221. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2222. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2223. return false;
  2224. }
  2225. buf[0] = 0x05;
  2226. buf[1] = 0x01;
  2227. buf[2] = 0x00;
  2228. buf[3] = 0x03;
  2229. len = (strlen(pool->sockaddr_url));
  2230. if (len > 255)
  2231. len = 255;
  2232. uclen = len;
  2233. buf[4] = (uclen & 0xff);
  2234. memcpy(buf + 5, pool->sockaddr_url, len);
  2235. port = atoi(pool->stratum_port);
  2236. buf[5 + len] = (port >> 8);
  2237. buf[6 + len] = (port & 0xff);
  2238. send(sockd, buf, (7 + len), 0);
  2239. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  2240. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2241. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2242. return false;
  2243. }
  2244. recv_byte(sockd);
  2245. atyp = recv_byte(sockd);
  2246. if (atyp == 0x01) {
  2247. for (i = 0; i < 4; i++)
  2248. recv_byte(sockd);
  2249. } else if (atyp == 0x03) {
  2250. len = recv_byte(sockd);
  2251. for (i = 0; i < len; i++)
  2252. recv_byte(sockd);
  2253. } else {
  2254. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  2255. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  2256. return false;
  2257. }
  2258. for (i = 0; i < 2; i++)
  2259. recv_byte(sockd);
  2260. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  2261. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2262. return true;
  2263. }
  2264. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  2265. {
  2266. unsigned short port;
  2267. in_addr_t inp;
  2268. char buf[515];
  2269. int i, len;
  2270. buf[0] = 0x04;
  2271. buf[1] = 0x01;
  2272. port = atoi(pool->stratum_port);
  2273. buf[2] = port >> 8;
  2274. buf[3] = port & 0xff;
  2275. sprintf(&buf[8], "CGMINER");
  2276. /* See if we've been given an IP address directly to avoid needing to
  2277. * resolve it. */
  2278. inp = inet_addr(pool->sockaddr_url);
  2279. inp = ntohl(inp);
  2280. if ((int)inp != -1)
  2281. socks4a = false;
  2282. else {
  2283. /* Try to extract the IP address ourselves first */
  2284. struct addrinfo servinfobase, *servinfo, hints;
  2285. servinfo = &servinfobase;
  2286. memset(&hints, 0, sizeof(struct addrinfo));
  2287. hints.ai_family = AF_INET; /* IPV4 only */
  2288. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  2289. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  2290. inp = ntohl(saddr_in->sin_addr.s_addr);
  2291. socks4a = false;
  2292. freeaddrinfo(servinfo);
  2293. }
  2294. }
  2295. if (!socks4a) {
  2296. if ((int)inp == -1) {
  2297. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  2298. pool->sockaddr_url);
  2299. return false;
  2300. }
  2301. buf[4] = (inp >> 24) & 0xFF;
  2302. buf[5] = (inp >> 16) & 0xFF;
  2303. buf[6] = (inp >> 8) & 0xFF;
  2304. buf[7] = (inp >> 0) & 0xFF;
  2305. send(sockd, buf, 16, 0);
  2306. } else {
  2307. /* This appears to not be working but hopefully most will be
  2308. * able to resolve IP addresses themselves. */
  2309. buf[4] = 0;
  2310. buf[5] = 0;
  2311. buf[6] = 0;
  2312. buf[7] = 1;
  2313. len = strlen(pool->sockaddr_url);
  2314. if (len > 255)
  2315. len = 255;
  2316. memcpy(&buf[16], pool->sockaddr_url, len);
  2317. len += 16;
  2318. buf[len++] = '\0';
  2319. send(sockd, buf, len, 0);
  2320. }
  2321. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  2322. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  2323. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2324. return false;
  2325. }
  2326. for (i = 0; i < 6; i++)
  2327. recv_byte(sockd);
  2328. return true;
  2329. }
  2330. static void noblock_socket(SOCKETTYPE fd)
  2331. {
  2332. #ifndef WIN32
  2333. int flags = fcntl(fd, F_GETFL, 0);
  2334. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  2335. #else
  2336. u_long flags = 1;
  2337. ioctlsocket(fd, FIONBIO, &flags);
  2338. #endif
  2339. }
  2340. static void block_socket(SOCKETTYPE fd)
  2341. {
  2342. #ifndef WIN32
  2343. int flags = fcntl(fd, F_GETFL, 0);
  2344. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  2345. #else
  2346. u_long flags = 0;
  2347. ioctlsocket(fd, FIONBIO, &flags);
  2348. #endif
  2349. }
  2350. static bool sock_connecting(void)
  2351. {
  2352. #ifndef WIN32
  2353. return errno == EINPROGRESS;
  2354. #else
  2355. return WSAGetLastError() == WSAEWOULDBLOCK;
  2356. #endif
  2357. }
  2358. static bool setup_stratum_socket(struct pool *pool)
  2359. {
  2360. struct addrinfo *servinfo, hints, *p;
  2361. char *sockaddr_url, *sockaddr_port;
  2362. int sockd;
  2363. mutex_lock(&pool->stratum_lock);
  2364. pool->stratum_active = false;
  2365. if (pool->sock)
  2366. CLOSESOCKET(pool->sock);
  2367. pool->sock = 0;
  2368. mutex_unlock(&pool->stratum_lock);
  2369. memset(&hints, 0, sizeof(struct addrinfo));
  2370. hints.ai_family = AF_UNSPEC;
  2371. hints.ai_socktype = SOCK_STREAM;
  2372. if (!pool->rpc_proxy && opt_socks_proxy) {
  2373. pool->rpc_proxy = opt_socks_proxy;
  2374. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  2375. pool->rpc_proxytype = PROXY_SOCKS5;
  2376. }
  2377. if (pool->rpc_proxy) {
  2378. sockaddr_url = pool->sockaddr_proxy_url;
  2379. sockaddr_port = pool->sockaddr_proxy_port;
  2380. } else {
  2381. sockaddr_url = pool->sockaddr_url;
  2382. sockaddr_port = pool->stratum_port;
  2383. }
  2384. if (getaddrinfo(sockaddr_url, sockaddr_port, &hints, &servinfo) != 0) {
  2385. if (!pool->probed) {
  2386. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  2387. sockaddr_url, sockaddr_port);
  2388. pool->probed = true;
  2389. } else {
  2390. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  2391. sockaddr_url, sockaddr_port);
  2392. }
  2393. return false;
  2394. }
  2395. for (p = servinfo; p != NULL; p = p->ai_next) {
  2396. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  2397. if (sockd == -1) {
  2398. applog(LOG_DEBUG, "Failed socket");
  2399. continue;
  2400. }
  2401. /* Iterate non blocking over entries returned by getaddrinfo
  2402. * to cope with round robin DNS entries, finding the first one
  2403. * we can connect to quickly. */
  2404. noblock_socket(sockd);
  2405. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  2406. struct timeval tv_timeout = {1, 0};
  2407. int selret;
  2408. fd_set rw;
  2409. if (!sock_connecting()) {
  2410. CLOSESOCKET(sockd);
  2411. applog(LOG_DEBUG, "Failed sock connect");
  2412. continue;
  2413. }
  2414. retry:
  2415. FD_ZERO(&rw);
  2416. FD_SET(sockd, &rw);
  2417. selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
  2418. if (selret > 0 && FD_ISSET(sockd, &rw)) {
  2419. socklen_t len;
  2420. int err, n;
  2421. len = sizeof(err);
  2422. n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);
  2423. if (!n && !err) {
  2424. applog(LOG_DEBUG, "Succeeded delayed connect");
  2425. block_socket(sockd);
  2426. break;
  2427. }
  2428. }
  2429. if (selret < 0 && interrupted())
  2430. goto retry;
  2431. CLOSESOCKET(sockd);
  2432. applog(LOG_DEBUG, "Select timeout/failed connect");
  2433. continue;
  2434. }
  2435. applog(LOG_WARNING, "Succeeded immediate connect");
  2436. block_socket(sockd);
  2437. break;
  2438. }
  2439. if (p == NULL) {
  2440. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  2441. sockaddr_url, sockaddr_port);
  2442. freeaddrinfo(servinfo);
  2443. return false;
  2444. }
  2445. freeaddrinfo(servinfo);
  2446. if (pool->rpc_proxy) {
  2447. switch (pool->rpc_proxytype) {
  2448. case PROXY_HTTP_1_0:
  2449. if (!http_negotiate(pool, sockd, true))
  2450. return false;
  2451. break;
  2452. case PROXY_HTTP:
  2453. if (!http_negotiate(pool, sockd, false))
  2454. return false;
  2455. break;
  2456. case PROXY_SOCKS5:
  2457. case PROXY_SOCKS5H:
  2458. if (!socks5_negotiate(pool, sockd))
  2459. return false;
  2460. break;
  2461. case PROXY_SOCKS4:
  2462. if (!socks4_negotiate(pool, sockd, false))
  2463. return false;
  2464. break;
  2465. case PROXY_SOCKS4A:
  2466. if (!socks4_negotiate(pool, sockd, true))
  2467. return false;
  2468. break;
  2469. default:
  2470. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  2471. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2472. return false;
  2473. break;
  2474. }
  2475. }
  2476. if (!pool->sockbuf) {
  2477. pool->sockbuf = calloc(RBUFSIZE, 1);
  2478. if (!pool->sockbuf)
  2479. quithere(1, "Failed to calloc pool sockbuf");
  2480. pool->sockbuf_size = RBUFSIZE;
  2481. }
  2482. pool->sock = sockd;
  2483. keep_sockalive(sockd);
  2484. return true;
  2485. }
  2486. static char *get_sessionid(json_t *val)
  2487. {
  2488. char *ret = NULL;
  2489. json_t *arr_val;
  2490. int arrsize, i;
  2491. arr_val = json_array_get(val, 0);
  2492. if (!arr_val || !json_is_array(arr_val))
  2493. goto out;
  2494. arrsize = json_array_size(arr_val);
  2495. for (i = 0; i < arrsize; i++) {
  2496. json_t *arr = json_array_get(arr_val, i);
  2497. char *notify;
  2498. if (!arr | !json_is_array(arr))
  2499. break;
  2500. notify = __json_array_string(arr, 0);
  2501. if (!notify)
  2502. continue;
  2503. if (!strncasecmp(notify, "mining.notify", 13)) {
  2504. ret = json_array_string(arr, 1);
  2505. break;
  2506. }
  2507. }
  2508. out:
  2509. return ret;
  2510. }
  2511. void suspend_stratum(struct pool *pool)
  2512. {
  2513. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2514. mutex_lock(&pool->stratum_lock);
  2515. __suspend_stratum(pool);
  2516. mutex_unlock(&pool->stratum_lock);
  2517. }
  2518. /*void extranonce_subscribe_stratum(struct pool *pool)
  2519. {
  2520. if(pool->extranonce_subscribe)
  2521. {
  2522. char s[RBUFSIZE];
  2523. sprintf(s,"{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}", swork_id++);
  2524. applog(LOG_INFO, "Send extranonce.subscribe for stratum pool %d", pool->pool_no);
  2525. stratum_send(pool, s, strlen(s));
  2526. }
  2527. }
  2528. void extranonce_subscribe_stratum(struct pool *pool)
  2529. {
  2530. char s[RBUFSIZE];
  2531. if(pool->extranonce_subscribe)
  2532. {
  2533. sprintf(s,"{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}", swork_id++);
  2534. applog(LOG_INFO, "Send extranonce.subscribe for stratum pool %d", pool->pool_no);
  2535. stratum_send(pool, s, strlen(s));
  2536. }
  2537. }*/
  2538. bool initiate_stratum(struct pool *pool)
  2539. {
  2540. bool ret = false, recvd = false, noresume = false, sockd = false;
  2541. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  2542. json_t *val = NULL, *res_val, *err_val;
  2543. json_error_t err;
  2544. int n2size;
  2545. resend:
  2546. if (!setup_stratum_socket(pool)) {
  2547. sockd = false;
  2548. goto out;
  2549. }
  2550. sockd = true;
  2551. if (recvd) {
  2552. /* Get rid of any crap lying around if we're resending */
  2553. clear_sock(pool);
  2554. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2555. } else {
  2556. if (pool->sessionid)
  2557. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2558. else
  2559. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  2560. }
  2561. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  2562. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2563. goto out;
  2564. }
  2565. if (pool->extranonce_subscribe)
  2566. {
  2567. sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}", swork_id++);
  2568. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  2569. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2570. goto out;
  2571. }
  2572. }
  2573. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2574. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2575. goto out;
  2576. }
  2577. sret = recv_line(pool);
  2578. if (!sret)
  2579. goto out;
  2580. recvd = true;
  2581. val = JSON_LOADS(sret, &err);
  2582. free(sret);
  2583. if (!val) {
  2584. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2585. goto out;
  2586. }
  2587. res_val = json_object_get(val, "result");
  2588. err_val = json_object_get(val, "error");
  2589. if (!res_val || json_is_null(res_val) ||
  2590. (err_val && !json_is_null(err_val))) {
  2591. char *ss;
  2592. if (err_val)
  2593. ss = json_dumps(err_val, JSON_INDENT(3));
  2594. else
  2595. ss = strdup("(unknown reason)");
  2596. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2597. free(ss);
  2598. goto out;
  2599. }
  2600. sessionid = get_sessionid(res_val);
  2601. if (!sessionid)
  2602. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2603. nonce1 = json_array_string(res_val, 1);
  2604. if (!valid_hex(nonce1)) {
  2605. applog(LOG_INFO, "Failed to get valid nonce1 in initiate_stratum");
  2606. free(sessionid);
  2607. goto out;
  2608. }
  2609. n2size = json_integer_value(json_array_get(res_val, 2));
  2610. if (n2size < 2 || n2size > 16) {
  2611. applog(LOG_INFO, "Failed to get valid n2size in initiate_stratum");
  2612. free(sessionid);
  2613. free(nonce1);
  2614. goto out;
  2615. }
  2616. cg_wlock(&pool->data_lock);
  2617. pool->sessionid = sessionid;
  2618. pool->nonce1 = nonce1;
  2619. pool->n1_len = strlen(nonce1) / 2;
  2620. free(pool->nonce1bin);
  2621. pool->nonce1bin = calloc(pool->n1_len, 1);
  2622. if (unlikely(!pool->nonce1bin))
  2623. quithere(1, "Failed to calloc pool->nonce1bin");
  2624. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2625. pool->n2size = n2size;
  2626. cg_wunlock(&pool->data_lock);
  2627. if (sessionid)
  2628. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2629. ret = true;
  2630. out:
  2631. if (ret) {
  2632. if (!pool->stratum_url)
  2633. pool->stratum_url = pool->sockaddr_url;
  2634. pool->stratum_active = true;
  2635. pool->next_diff = 0;
  2636. pool->sdiff = 1;
  2637. if (opt_protocol) {
  2638. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2639. pool->pool_no, pool->nonce1, pool->n2size);
  2640. }
  2641. if(pool->extranonce_subscribe)
  2642. {
  2643. sprintf(s,"{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}", swork_id++);
  2644. stratum_send(pool, s, strlen(s));
  2645. }
  2646. } else {
  2647. if (recvd && !noresume) {
  2648. /* Reset the sessionid used for stratum resuming in case the pool
  2649. * does not support it, or does not know how to respond to the
  2650. * presence of the sessionid parameter. */
  2651. cg_wlock(&pool->data_lock);
  2652. free(pool->sessionid);
  2653. free(pool->nonce1);
  2654. pool->sessionid = pool->nonce1 = NULL;
  2655. cg_wunlock(&pool->data_lock);
  2656. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2657. noresume = true;
  2658. json_decref(val);
  2659. goto resend;
  2660. }
  2661. applog(LOG_DEBUG, "Initiate stratum failed");
  2662. if (sockd)
  2663. suspend_stratum(pool);
  2664. }
  2665. json_decref(val);
  2666. return ret;
  2667. }
  2668. bool restart_stratum(struct pool *pool)
  2669. {
  2670. bool ret = false;
  2671. if (pool->stratum_active)
  2672. suspend_stratum(pool);
  2673. if (!initiate_stratum(pool))
  2674. goto out;
  2675. if (!auth_stratum(pool))
  2676. goto out;
  2677. //extranonce_subscribe_stratum(pool);
  2678. ret = true;
  2679. out:
  2680. if (!ret)
  2681. pool_died(pool);
  2682. else
  2683. stratum_resumed(pool);
  2684. return ret;
  2685. }
  2686. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2687. {
  2688. dev->device_last_not_well = time(NULL);
  2689. dev->device_not_well_reason = reason;
  2690. switch (reason) {
  2691. case REASON_THREAD_FAIL_INIT:
  2692. dev->thread_fail_init_count++;
  2693. break;
  2694. case REASON_THREAD_ZERO_HASH:
  2695. dev->thread_zero_hash_count++;
  2696. break;
  2697. case REASON_THREAD_FAIL_QUEUE:
  2698. dev->thread_fail_queue_count++;
  2699. break;
  2700. case REASON_DEV_SICK_IDLE_60:
  2701. dev->dev_sick_idle_60_count++;
  2702. break;
  2703. case REASON_DEV_DEAD_IDLE_600:
  2704. dev->dev_dead_idle_600_count++;
  2705. break;
  2706. case REASON_DEV_NOSTART:
  2707. dev->dev_nostart_count++;
  2708. break;
  2709. case REASON_DEV_OVER_HEAT:
  2710. dev->dev_over_heat_count++;
  2711. break;
  2712. case REASON_DEV_THERMAL_CUTOFF:
  2713. dev->dev_thermal_cutoff_count++;
  2714. break;
  2715. case REASON_DEV_COMMS_ERROR:
  2716. dev->dev_comms_error_count++;
  2717. break;
  2718. case REASON_DEV_THROTTLE:
  2719. dev->dev_throttle_count++;
  2720. break;
  2721. }
  2722. }
  2723. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2724. void *realloc_strcat(char *ptr, char *s)
  2725. {
  2726. size_t old = 0, len = strlen(s);
  2727. char *ret;
  2728. if (!len)
  2729. return ptr;
  2730. if (ptr)
  2731. old = strlen(ptr);
  2732. len += old + 1;
  2733. align_len(&len);
  2734. ret = malloc(len);
  2735. if (unlikely(!ret))
  2736. quithere(1, "Failed to malloc");
  2737. if (ptr) {
  2738. sprintf(ret, "%s%s", ptr, s);
  2739. free(ptr);
  2740. } else
  2741. sprintf(ret, "%s", s);
  2742. return ret;
  2743. }
  2744. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  2745. * Including 0x00 at the end
  2746. * You must free the result yourself */
  2747. void *str_text(char *ptr)
  2748. {
  2749. unsigned char *uptr;
  2750. char *ret, *txt;
  2751. if (ptr == NULL) {
  2752. ret = strdup("(null)");
  2753. if (unlikely(!ret))
  2754. quithere(1, "Failed to malloc null");
  2755. }
  2756. uptr = (unsigned char *)ptr;
  2757. ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed
  2758. if (unlikely(!txt))
  2759. quithere(1, "Failed to malloc txt");
  2760. do {
  2761. if (*uptr < ' ' || *uptr > '~') {
  2762. sprintf(txt, "0x%02x", *uptr);
  2763. txt += 4;
  2764. } else
  2765. *(txt++) = *uptr;
  2766. } while (*(uptr++));
  2767. *txt = '\0';
  2768. return ret;
  2769. }
  2770. void RenameThread(const char* name)
  2771. {
  2772. char buf[16];
  2773. snprintf(buf, sizeof(buf), "cg@%s", name);
  2774. #if defined(PR_SET_NAME)
  2775. // Only the first 15 characters are used (16 - NUL terminator)
  2776. prctl(PR_SET_NAME, buf, 0, 0, 0);
  2777. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2778. pthread_set_name_np(pthread_self(), buf);
  2779. #elif defined(MAC_OSX)
  2780. pthread_setname_np(buf);
  2781. #else
  2782. // Prevent warnings
  2783. (void)buf;
  2784. #endif
  2785. }
  2786. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  2787. * that support them and for apple which does not. We use a single byte across
  2788. * a pipe to emulate semaphore behaviour there. */
  2789. #ifdef __APPLE__
  2790. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2791. {
  2792. int flags, fd, i;
  2793. if (pipe(cgsem->pipefd) == -1)
  2794. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  2795. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  2796. * execv on restart. */
  2797. for (i = 0; i < 2; i++) {
  2798. fd = cgsem->pipefd[i];
  2799. flags = fcntl(fd, F_GETFD, 0);
  2800. flags |= FD_CLOEXEC;
  2801. if (fcntl(fd, F_SETFD, flags) == -1)
  2802. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  2803. }
  2804. }
  2805. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2806. {
  2807. const char buf = 1;
  2808. int ret;
  2809. retry:
  2810. ret = write(cgsem->pipefd[1], &buf, 1);
  2811. if (unlikely(ret == 0))
  2812. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  2813. else if (unlikely(ret < 0 && interrupted))
  2814. goto retry;
  2815. }
  2816. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2817. {
  2818. char buf;
  2819. int ret;
  2820. retry:
  2821. ret = read(cgsem->pipefd[0], &buf, 1);
  2822. if (unlikely(ret == 0))
  2823. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  2824. else if (unlikely(ret < 0 && interrupted))
  2825. goto retry;
  2826. }
  2827. void cgsem_destroy(cgsem_t *cgsem)
  2828. {
  2829. close(cgsem->pipefd[1]);
  2830. close(cgsem->pipefd[0]);
  2831. }
  2832. /* This is similar to sem_timedwait but takes a millisecond value */
  2833. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2834. {
  2835. struct timeval timeout;
  2836. int ret, fd;
  2837. fd_set rd;
  2838. char buf;
  2839. retry:
  2840. fd = cgsem->pipefd[0];
  2841. FD_ZERO(&rd);
  2842. FD_SET(fd, &rd);
  2843. ms_to_timeval(&timeout, ms);
  2844. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  2845. if (ret > 0) {
  2846. ret = read(fd, &buf, 1);
  2847. return 0;
  2848. }
  2849. if (likely(!ret))
  2850. return ETIMEDOUT;
  2851. if (interrupted())
  2852. goto retry;
  2853. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2854. /* We don't reach here */
  2855. return 0;
  2856. }
  2857. /* Reset semaphore count back to zero */
  2858. void cgsem_reset(cgsem_t *cgsem)
  2859. {
  2860. int ret, fd;
  2861. fd_set rd;
  2862. char buf;
  2863. fd = cgsem->pipefd[0];
  2864. FD_ZERO(&rd);
  2865. FD_SET(fd, &rd);
  2866. do {
  2867. struct timeval timeout = {0, 0};
  2868. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  2869. if (ret > 0)
  2870. ret = read(fd, &buf, 1);
  2871. else if (unlikely(ret < 0 && interrupted()))
  2872. ret = 1;
  2873. } while (ret > 0);
  2874. }
  2875. #else
  2876. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2877. {
  2878. int ret;
  2879. if ((ret = sem_init(cgsem, 0, 0)))
  2880. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  2881. }
  2882. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2883. {
  2884. if (unlikely(sem_post(cgsem)))
  2885. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  2886. }
  2887. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2888. {
  2889. retry:
  2890. if (unlikely(sem_wait(cgsem))) {
  2891. if (interrupted())
  2892. goto retry;
  2893. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  2894. }
  2895. }
  2896. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2897. {
  2898. struct timespec abs_timeout, ts_now;
  2899. struct timeval tv_now;
  2900. int ret;
  2901. cgtime(&tv_now);
  2902. timeval_to_spec(&ts_now, &tv_now);
  2903. ms_to_timespec(&abs_timeout, ms);
  2904. retry:
  2905. timeraddspec(&abs_timeout, &ts_now);
  2906. ret = sem_timedwait(cgsem, &abs_timeout);
  2907. if (ret) {
  2908. if (likely(sock_timeout()))
  2909. return ETIMEDOUT;
  2910. if (interrupted())
  2911. goto retry;
  2912. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2913. }
  2914. return 0;
  2915. }
  2916. void cgsem_reset(cgsem_t *cgsem)
  2917. {
  2918. int ret;
  2919. do {
  2920. ret = sem_trywait(cgsem);
  2921. if (unlikely(ret < 0 && interrupted()))
  2922. ret = 0;
  2923. } while (!ret);
  2924. }
  2925. void cgsem_destroy(cgsem_t *cgsem)
  2926. {
  2927. sem_destroy(cgsem);
  2928. }
  2929. #endif
  2930. /* Provide a completion_timeout helper function for unreliable functions that
  2931. * may die due to driver issues etc that time out if the function fails and
  2932. * can then reliably return. */
  2933. struct cg_completion {
  2934. cgsem_t cgsem;
  2935. void (*fn)(void *fnarg);
  2936. void *fnarg;
  2937. };
  2938. void *completion_thread(void *arg)
  2939. {
  2940. struct cg_completion *cgc = (struct cg_completion *)arg;
  2941. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2942. cgc->fn(cgc->fnarg);
  2943. cgsem_post(&cgc->cgsem);
  2944. return NULL;
  2945. }
  2946. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  2947. {
  2948. struct cg_completion *cgc;
  2949. pthread_t pthread;
  2950. bool ret = false;
  2951. cgc = malloc(sizeof(struct cg_completion));
  2952. if (unlikely(!cgc))
  2953. return ret;
  2954. cgsem_init(&cgc->cgsem);
  2955. cgc->fn = fn;
  2956. cgc->fnarg = fnarg;
  2957. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  2958. ret = cgsem_mswait(&cgc->cgsem, timeout);
  2959. if (!ret) {
  2960. pthread_join(pthread, NULL);
  2961. free(cgc);
  2962. } else
  2963. pthread_cancel(pthread);
  2964. return !ret;
  2965. }
  2966. void _cg_memcpy(void *dest, const void *src, unsigned int n, const char *file, const char *func, const int line)
  2967. {
  2968. if (unlikely(n < 1 || n > (1ul << 31))) {
  2969. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from %s %s():%d",
  2970. n, file, func, line);
  2971. return;
  2972. }
  2973. memcpy(dest, src, n);
  2974. }
  2975. int cg_timeval_subtract(struct timeval* result, struct timeval* x, struct timeval* y)
  2976. {
  2977. int nsec = 0;
  2978. if(x->tv_sec > y->tv_sec)
  2979. return -1;
  2980. if((x->tv_sec == y->tv_sec) && (x->tv_usec > y->tv_usec))
  2981. return -1;
  2982. result->tv_sec = (y->tv_sec - x->tv_sec);
  2983. result->tv_usec = (y->tv_usec - x->tv_usec);
  2984. if(result->tv_usec < 0)
  2985. {
  2986. result->tv_sec--;
  2987. result->tv_usec += 1000000;
  2988. }
  2989. return 0;
  2990. }
  2991. void rev(unsigned char *s, size_t l)
  2992. {
  2993. size_t i, j;
  2994. unsigned char t;
  2995. for (i = 0, j = l - 1; i < j; i++, j--) {
  2996. t = s[i];
  2997. s[i] = s[j];
  2998. s[j] = t;
  2999. }
  3000. }
  3001. int check_asicnum(int asic_num, unsigned char nonce)
  3002. {
  3003. switch(asic_num)
  3004. {
  3005. case 1:
  3006. return 1;
  3007. case 2:
  3008. switch(nonce & 0x80)
  3009. {
  3010. case 0x80: return 2;
  3011. default: return 1;
  3012. }
  3013. case 4:
  3014. switch(nonce & 0xC0)
  3015. {
  3016. case 0xC0: return 4;
  3017. case 0x80: return 3;
  3018. case 0x40: return 2;
  3019. default: return 1;
  3020. }
  3021. case 8:
  3022. switch(nonce & 0xE0)
  3023. {
  3024. case 0xE0: return 8;
  3025. case 0xC0: return 7;
  3026. case 0xA0: return 6;
  3027. case 0x80: return 5;
  3028. case 0x60: return 4;
  3029. case 0x40: return 3;
  3030. case 0x20: return 2;
  3031. default : return 1;
  3032. }
  3033. case 16:
  3034. switch(nonce & 0xF0)
  3035. {
  3036. case 0xF0: return 16;
  3037. case 0xE0: return 15;
  3038. case 0xD0: return 14;
  3039. case 0xC0: return 13;
  3040. case 0xB0: return 12;
  3041. case 0xA0: return 11;
  3042. case 0x90: return 10;
  3043. case 0x80: return 9;
  3044. case 0x70: return 8;
  3045. case 0x60: return 7;
  3046. case 0x50: return 6;
  3047. case 0x40: return 5;
  3048. case 0x30: return 4;
  3049. case 0x20: return 3;
  3050. case 0x10: return 2;
  3051. default : return 1;
  3052. }
  3053. case 32:
  3054. switch(nonce & 0xF8)
  3055. {
  3056. case 0xF8: return 32;
  3057. case 0xF0: return 31;
  3058. case 0xE8: return 30;
  3059. case 0xE0: return 29;
  3060. case 0xD8: return 28;
  3061. case 0xD0: return 27;
  3062. case 0xC8: return 26;
  3063. case 0xC0: return 25;
  3064. case 0xB8: return 24;
  3065. case 0xB0: return 23;
  3066. case 0xA8: return 22;
  3067. case 0xA0: return 21;
  3068. case 0x98: return 20;
  3069. case 0x90: return 19;
  3070. case 0x88: return 18;
  3071. case 0x80: return 17;
  3072. case 0x78: return 16;
  3073. case 0x70: return 15;
  3074. case 0x68: return 14;
  3075. case 0x60: return 13;
  3076. case 0x58: return 12;
  3077. case 0x50: return 11;
  3078. case 0x48: return 10;
  3079. case 0x40: return 9;
  3080. case 0x38: return 8;
  3081. case 0x30: return 7;
  3082. case 0x28: return 6;
  3083. case 0x20: return 5;
  3084. case 0x18: return 4;
  3085. case 0x10: return 3;
  3086. case 0x08: return 2;
  3087. default : return 1;
  3088. }
  3089. case 64:
  3090. switch(nonce & 0xFC)
  3091. {
  3092. case 0xFC: return 64;
  3093. case 0xF8: return 63;
  3094. case 0xF4: return 62;
  3095. case 0xF0: return 61;
  3096. case 0xEC: return 60;
  3097. case 0xE8: return 59;
  3098. case 0xE4: return 58;
  3099. case 0xE0: return 57;
  3100. case 0xDC: return 56;
  3101. case 0xD8: return 55;
  3102. case 0xD4: return 54;
  3103. case 0xD0: return 53;
  3104. case 0xCC: return 52;
  3105. case 0xC8: return 51;
  3106. case 0xC4: return 50;
  3107. case 0xC0: return 49;
  3108. case 0xBC: return 48;
  3109. case 0xB8: return 47;
  3110. case 0xB4: return 46;
  3111. case 0xB0: return 45;
  3112. case 0xAC: return 44;
  3113. case 0xA8: return 43;
  3114. case 0xA4: return 42;
  3115. case 0xA0: return 41;
  3116. case 0x9C: return 40;
  3117. case 0x98: return 39;
  3118. case 0x94: return 38;
  3119. case 0x90: return 37;
  3120. case 0x8C: return 36;
  3121. case 0x88: return 35;
  3122. case 0x84: return 34;
  3123. case 0x80: return 33;
  3124. case 0x7C: return 32;
  3125. case 0x78: return 31;
  3126. case 0x74: return 30;
  3127. case 0x70: return 29;
  3128. case 0x6C: return 28;
  3129. case 0x68: return 27;
  3130. case 0x64: return 26;
  3131. case 0x60: return 25;
  3132. case 0x5C: return 24;
  3133. case 0x58: return 23;
  3134. case 0x54: return 22;
  3135. case 0x50: return 21;
  3136. case 0x4C: return 20;
  3137. case 0x48: return 19;
  3138. case 0x44: return 18;
  3139. case 0x40: return 17;
  3140. case 0x3C: return 16;
  3141. case 0x38: return 15;
  3142. case 0x34: return 14;
  3143. case 0x30: return 13;
  3144. case 0x2C: return 12;
  3145. case 0x28: return 11;
  3146. case 0x24: return 10;
  3147. case 0x20: return 9;
  3148. case 0x1C: return 8;
  3149. case 0x18: return 7;
  3150. case 0x14: return 6;
  3151. case 0x10: return 5;
  3152. case 0x0C: return 4;
  3153. case 0x08: return 3;
  3154. case 0x04: return 2;
  3155. default : return 1;
  3156. }
  3157. default:
  3158. return 0;
  3159. }
  3160. }
  3161. void cg_logwork(struct work *work, unsigned char *nonce_bin, bool ok)
  3162. {
  3163. if(opt_logwork_path) {
  3164. char szmsg[1024] = {0};
  3165. unsigned char midstate_tmp[32] = {0};
  3166. unsigned char data_tmp[32] = {0};
  3167. unsigned char hash_tmp[32] = {0};
  3168. char * szworkdata = NULL;
  3169. char * szmidstate = NULL;
  3170. char * szdata = NULL;
  3171. char * sznonce4 = NULL;
  3172. char * sznonce5 = NULL;
  3173. char * szhash = NULL;
  3174. int asicnum = 0;
  3175. uint64_t worksharediff = 0;
  3176. memcpy(midstate_tmp, work->midstate, 32);
  3177. memcpy(data_tmp, work->data+64, 12);
  3178. memcpy(hash_tmp, work->hash, 32);
  3179. rev((void *)midstate_tmp, 32);
  3180. rev((void *)data_tmp, 12);
  3181. rev((void *)hash_tmp, 32);
  3182. szworkdata = bin2hex((void *)work->data, 128);
  3183. szmidstate = bin2hex((void *)midstate_tmp, 32);
  3184. szdata = bin2hex((void *)data_tmp, 12);
  3185. sznonce4 = bin2hex((void *)nonce_bin, 4);
  3186. sznonce5 = bin2hex((void *)nonce_bin, 5);
  3187. szhash = bin2hex((void *)hash_tmp, 32);
  3188. worksharediff = share_ndiff(work);
  3189. sprintf(szmsg, "%s %08x midstate %s data %s nonce %s hash %s diff %I64d", ok?"o":"x", work->id, szmidstate, szdata, sznonce5, szhash, worksharediff);
  3190. if(strcmp(opt_logwork_path, "screen") == 0) {
  3191. applog(LOG_ERR, szmsg);
  3192. } else {
  3193. applog(LOG_ERR, szmsg);
  3194. if(g_logwork_file) {
  3195. 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);
  3196. fwrite(szmsg, strlen(szmsg), 1, g_logwork_file);
  3197. fwrite("\n", 1, 1, g_logwork_file);
  3198. fflush(g_logwork_file);
  3199. if(ok) {
  3200. if(g_logwork_asicnum == 1) {
  3201. sprintf(szmsg, "midstate %s data %s nonce %s hash %s", szmidstate, szdata, sznonce4, szhash);
  3202. fwrite(szmsg, strlen(szmsg), 1, g_logwork_files[0]);
  3203. fwrite("\n", 1, 1, g_logwork_files[0]);
  3204. fflush(g_logwork_files[0]);
  3205. } else if(g_logwork_asicnum == 32 || g_logwork_asicnum == 64) {
  3206. sprintf(szmsg, "midstate %s data %s nonce %s hash %s", szmidstate, szdata, sznonce4, szhash);
  3207. asicnum = check_asicnum(g_logwork_asicnum, nonce_bin[0]);
  3208. fwrite(szmsg, strlen(szmsg), 1, g_logwork_files[asicnum]);
  3209. fwrite("\n", 1, 1, g_logwork_files[asicnum]);
  3210. fflush(g_logwork_files[asicnum]);
  3211. }
  3212. if(opt_logwork_diff) {
  3213. int diffnum = 0;
  3214. uint64_t difftmp = worksharediff;
  3215. while(1) {
  3216. difftmp = difftmp >> 1;
  3217. if(difftmp > 0) {
  3218. diffnum++;
  3219. if(diffnum >= 64) {
  3220. break;
  3221. }
  3222. } else {
  3223. break;
  3224. }
  3225. }
  3226. applog(LOG_DEBUG, "work diff %I64d diffnum %d", worksharediff, diffnum);
  3227. sprintf(szmsg, "midstate %s data %s nonce %s hash %s", szmidstate, szdata, sznonce4, szhash);
  3228. fwrite(szmsg, strlen(szmsg), 1, g_logwork_diffs[diffnum]);
  3229. fwrite("\n", 1, 1, g_logwork_diffs[diffnum]);
  3230. fflush(g_logwork_diffs[diffnum]);
  3231. }
  3232. }
  3233. }
  3234. }
  3235. if(szworkdata) free(szworkdata);
  3236. if(szmidstate) free(szmidstate);
  3237. if(szdata) free(szdata);
  3238. if(sznonce4) free(sznonce4);
  3239. if(sznonce5) free(sznonce5);
  3240. if(szhash) free(szhash);
  3241. }
  3242. }
  3243. void cg_logwork_uint32(struct work *work, uint32_t nonce, bool ok)
  3244. {
  3245. if(opt_logwork_path) {
  3246. unsigned char nonce_bin[5] = {0};
  3247. memcpy(nonce_bin, &nonce, 4);
  3248. cg_logwork(work, nonce_bin, ok);
  3249. }
  3250. }