util.c 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. * Copyright 2012 Giel van Schijndel
  6. * Copyright 2012 Gavin Andresen
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <ctype.h>
  19. #include <stdarg.h>
  20. #include <string.h>
  21. #include <pthread.h>
  22. #include <jansson.h>
  23. #include <curl/curl.h>
  24. #include <time.h>
  25. #include <errno.h>
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #ifdef HAVE_SYS_PRCTL_H
  29. # include <sys/prctl.h>
  30. #endif
  31. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  32. # include <pthread_np.h>
  33. #endif
  34. #ifndef WIN32
  35. #include <fcntl.h>
  36. # ifdef __linux
  37. # include <sys/prctl.h>
  38. # endif
  39. # include <sys/socket.h>
  40. # include <netinet/in.h>
  41. # include <netinet/tcp.h>
  42. # include <netdb.h>
  43. #else
  44. # include <windows.h>
  45. # include <winsock2.h>
  46. # include <mstcpip.h>
  47. # include <ws2tcpip.h>
  48. # include <mmsystem.h>
  49. #endif
  50. #include <utlist.h>
  51. #ifdef NEED_BFG_LOWL_VCOM
  52. #include "lowl-vcom.h"
  53. #endif
  54. #include "miner.h"
  55. #include "compat.h"
  56. #include "util.h"
  57. #define DEFAULT_SOCKWAIT 60
  58. bool successful_connect = false;
  59. struct timeval nettime;
  60. struct data_buffer {
  61. void *buf;
  62. size_t len;
  63. curl_socket_t *idlemarker;
  64. };
  65. struct upload_buffer {
  66. const void *buf;
  67. size_t len;
  68. };
  69. struct header_info {
  70. char *lp_path;
  71. int rolltime;
  72. char *reason;
  73. char *stratum_url;
  74. bool hadrolltime;
  75. bool canroll;
  76. bool hadexpire;
  77. };
  78. struct tq_ent {
  79. void *data;
  80. struct tq_ent *prev;
  81. struct tq_ent *next;
  82. };
  83. static void databuf_free(struct data_buffer *db)
  84. {
  85. if (!db)
  86. return;
  87. free(db->buf);
  88. #ifdef DEBUG_DATABUF
  89. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  90. #endif
  91. memset(db, 0, sizeof(*db));
  92. }
  93. // aka data_buffer_write
  94. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  95. void *user_data)
  96. {
  97. struct data_buffer *db = user_data;
  98. size_t oldlen, newlen;
  99. oldlen = db->len;
  100. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  101. return 0;
  102. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  103. nmemb = (SIZE_MAX - oldlen) / size;
  104. size_t len = size * nmemb;
  105. void *newmem;
  106. static const unsigned char zero = 0;
  107. if (db->idlemarker) {
  108. const unsigned char *cptr = ptr;
  109. for (size_t i = 0; i < len; ++i)
  110. if (!(isCspace(cptr[i]) || cptr[i] == '{')) {
  111. *db->idlemarker = CURL_SOCKET_BAD;
  112. db->idlemarker = NULL;
  113. break;
  114. }
  115. }
  116. newlen = oldlen + len;
  117. newmem = realloc(db->buf, newlen + 1);
  118. #ifdef DEBUG_DATABUF
  119. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  120. #endif
  121. if (!newmem)
  122. return 0;
  123. db->buf = newmem;
  124. db->len = newlen;
  125. memcpy(db->buf + oldlen, ptr, len);
  126. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  127. return nmemb;
  128. }
  129. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  130. void *user_data)
  131. {
  132. struct upload_buffer *ub = user_data;
  133. unsigned int len = size * nmemb;
  134. if (len > ub->len)
  135. len = ub->len;
  136. if (len) {
  137. memcpy(ptr, ub->buf, len);
  138. ub->buf += len;
  139. ub->len -= len;
  140. }
  141. return len;
  142. }
  143. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  144. {
  145. struct header_info *hi = user_data;
  146. size_t remlen, slen, ptrlen = size * nmemb;
  147. char *rem, *val = NULL, *key = NULL;
  148. void *tmp;
  149. val = calloc(1, ptrlen);
  150. key = calloc(1, ptrlen);
  151. if (!key || !val)
  152. goto out;
  153. tmp = memchr(ptr, ':', ptrlen);
  154. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  155. goto out;
  156. slen = tmp - ptr;
  157. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  158. goto out;
  159. memcpy(key, ptr, slen); /* store & nul term key */
  160. key[slen] = 0;
  161. rem = ptr + slen + 1; /* trim value's leading whitespace */
  162. remlen = ptrlen - slen - 1;
  163. while ((remlen > 0) && (isCspace(*rem))) {
  164. remlen--;
  165. rem++;
  166. }
  167. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  168. val[remlen] = 0;
  169. while ((*val) && (isCspace(val[strlen(val) - 1])))
  170. val[strlen(val) - 1] = 0;
  171. if (!*val) /* skip blank value */
  172. goto out;
  173. if (opt_protocol)
  174. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  175. if (!strcasecmp("X-Roll-Ntime", key)) {
  176. hi->hadrolltime = true;
  177. if (!strncasecmp("N", val, 1))
  178. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  179. else {
  180. hi->canroll = true;
  181. /* Check to see if expire= is supported and if not, set
  182. * the rolltime to the default scantime */
  183. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  184. sscanf(val + 7, "%d", &hi->rolltime);
  185. hi->hadexpire = true;
  186. } else
  187. hi->rolltime = opt_scantime;
  188. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  189. }
  190. }
  191. if (!strcasecmp("X-Long-Polling", key)) {
  192. hi->lp_path = val; /* steal memory reference */
  193. val = NULL;
  194. }
  195. if (!strcasecmp("X-Reject-Reason", key)) {
  196. hi->reason = val; /* steal memory reference */
  197. val = NULL;
  198. }
  199. if (!strcasecmp("X-Stratum", key)) {
  200. hi->stratum_url = val;
  201. val = NULL;
  202. }
  203. out:
  204. free(key);
  205. free(val);
  206. return ptrlen;
  207. }
  208. static int keep_sockalive(SOCKETTYPE fd)
  209. {
  210. const int tcp_one = 1;
  211. const int tcp_keepidle = 45;
  212. const int tcp_keepintvl = 30;
  213. int ret = 0;
  214. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one))))
  215. ret = 1;
  216. #ifndef WIN32
  217. int flags = fcntl(fd, F_GETFL, 0);
  218. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  219. #else
  220. u_long flags = 1;
  221. ioctlsocket(fd, FIONBIO, &flags);
  222. #endif
  223. if (!opt_delaynet)
  224. #ifndef __linux
  225. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  226. #else /* __linux */
  227. if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  228. #endif /* __linux */
  229. ret = 1;
  230. #ifdef __linux
  231. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one))))
  232. ret = 1;
  233. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  234. ret = 1;
  235. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  236. ret = 1;
  237. #endif /* __linux */
  238. #ifdef __APPLE_CC__
  239. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  240. ret = 1;
  241. #endif /* __APPLE_CC__ */
  242. #ifdef WIN32
  243. const int zero = 0;
  244. struct tcp_keepalive vals;
  245. vals.onoff = 1;
  246. vals.keepalivetime = tcp_keepidle * 1000;
  247. vals.keepaliveinterval = tcp_keepintvl * 1000;
  248. DWORD outputBytes;
  249. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  250. ret = 1;
  251. /* Windows happily submits indefinitely to the send buffer blissfully
  252. * unaware nothing is getting there without gracefully failing unless
  253. * we disable the send buffer */
  254. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  255. ret = 1;
  256. #endif /* WIN32 */
  257. return ret;
  258. }
  259. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  260. curlsocktype __maybe_unused purpose)
  261. {
  262. return keep_sockalive(fd);
  263. }
  264. static void last_nettime(struct timeval *last)
  265. {
  266. rd_lock(&netacc_lock);
  267. last->tv_sec = nettime.tv_sec;
  268. last->tv_usec = nettime.tv_usec;
  269. rd_unlock(&netacc_lock);
  270. }
  271. static void set_nettime(void)
  272. {
  273. wr_lock(&netacc_lock);
  274. cgtime(&nettime);
  275. wr_unlock(&netacc_lock);
  276. }
  277. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  278. char *data, size_t size,
  279. void *userdata)
  280. {
  281. struct pool *pool = (struct pool *)userdata;
  282. switch(type) {
  283. case CURLINFO_HEADER_IN:
  284. case CURLINFO_DATA_IN:
  285. case CURLINFO_SSL_DATA_IN:
  286. pool->cgminer_pool_stats.bytes_received += size;
  287. total_bytes_rcvd += size;
  288. pool->cgminer_pool_stats.net_bytes_received += size;
  289. break;
  290. case CURLINFO_HEADER_OUT:
  291. case CURLINFO_DATA_OUT:
  292. case CURLINFO_SSL_DATA_OUT:
  293. pool->cgminer_pool_stats.bytes_sent += size;
  294. total_bytes_sent += size;
  295. pool->cgminer_pool_stats.net_bytes_sent += size;
  296. break;
  297. case CURLINFO_TEXT:
  298. {
  299. if (!opt_protocol)
  300. break;
  301. // data is not null-terminated, so we need to copy and terminate it for applog
  302. char datacp[size + 1];
  303. memcpy(datacp, data, size);
  304. while (likely(size) && unlikely(isCspace(datacp[size-1])))
  305. --size;
  306. if (unlikely(!size))
  307. break;
  308. datacp[size] = '\0';
  309. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  310. break;
  311. }
  312. default:
  313. break;
  314. }
  315. return 0;
  316. }
  317. struct json_rpc_call_state {
  318. struct data_buffer all_data;
  319. struct header_info hi;
  320. void *priv;
  321. char curl_err_str[CURL_ERROR_SIZE];
  322. struct curl_slist *headers;
  323. struct upload_buffer upload_data;
  324. struct pool *pool;
  325. };
  326. void json_rpc_call_async(CURL *curl, const char *url,
  327. const char *userpass, const char *rpc_req,
  328. bool longpoll,
  329. struct pool *pool, bool share,
  330. void *priv)
  331. {
  332. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  333. *state = (struct json_rpc_call_state){
  334. .priv = priv,
  335. .pool = pool,
  336. };
  337. long timeout = longpoll ? (60 * 60) : 60;
  338. char len_hdr[64], user_agent_hdr[128];
  339. struct curl_slist *headers = NULL;
  340. if (longpoll)
  341. state->all_data.idlemarker = &pool->lp_socket;
  342. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  343. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  344. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  345. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  346. * to enable it */
  347. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  348. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  349. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  350. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  351. curl_easy_setopt(curl, CURLOPT_URL, url);
  352. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  353. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  354. /* Shares are staggered already and delays in submission can be costly
  355. * so do not delay them */
  356. if (!opt_delaynet || share)
  357. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  358. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  359. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  360. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  361. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  362. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  363. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  364. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  365. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  366. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  367. if (pool->rpc_proxy) {
  368. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  369. } else if (opt_socks_proxy) {
  370. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  371. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  372. }
  373. if (userpass) {
  374. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  375. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  376. }
  377. if (longpoll)
  378. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  379. curl_easy_setopt(curl, CURLOPT_POST, 1);
  380. if (opt_protocol)
  381. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  382. state->upload_data.buf = rpc_req;
  383. state->upload_data.len = strlen(rpc_req);
  384. sprintf(len_hdr, "Content-Length: %lu",
  385. (unsigned long) state->upload_data.len);
  386. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  387. headers = curl_slist_append(headers,
  388. "Content-type: application/json");
  389. headers = curl_slist_append(headers,
  390. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  391. if (longpoll)
  392. headers = curl_slist_append(headers,
  393. "X-Minimum-Wait: 0");
  394. if (likely(global_hashrate)) {
  395. char ghashrate[255];
  396. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  397. headers = curl_slist_append(headers, ghashrate);
  398. }
  399. headers = curl_slist_append(headers, len_hdr);
  400. headers = curl_slist_append(headers, user_agent_hdr);
  401. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  402. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  403. state->headers = headers;
  404. if (opt_delaynet) {
  405. /* Don't delay share submission, but still track the nettime */
  406. if (!share) {
  407. long long now_msecs, last_msecs;
  408. struct timeval now, last;
  409. cgtime(&now);
  410. last_nettime(&last);
  411. now_msecs = (long long)now.tv_sec * 1000;
  412. now_msecs += now.tv_usec / 1000;
  413. last_msecs = (long long)last.tv_sec * 1000;
  414. last_msecs += last.tv_usec / 1000;
  415. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  416. struct timespec rgtp;
  417. rgtp.tv_sec = 0;
  418. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  419. nanosleep(&rgtp, NULL);
  420. }
  421. }
  422. set_nettime();
  423. }
  424. }
  425. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  426. {
  427. struct json_rpc_call_state *state;
  428. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, (void*)&state) != CURLE_OK) {
  429. applog(LOG_ERR, "Failed to get private curl data");
  430. if (out_priv)
  431. *(void**)out_priv = NULL;
  432. goto err_out;
  433. }
  434. if (out_priv)
  435. *(void**)out_priv = state->priv;
  436. json_t *val, *err_val, *res_val;
  437. json_error_t err;
  438. struct pool *pool = state->pool;
  439. bool probing = probe && !pool->probed;
  440. if (rc) {
  441. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  442. goto err_out;
  443. }
  444. if (!state->all_data.buf) {
  445. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  446. goto err_out;
  447. }
  448. pool->cgminer_pool_stats.times_sent++;
  449. pool->cgminer_pool_stats.times_received++;
  450. if (probing) {
  451. pool->probed = true;
  452. /* If X-Long-Polling was found, activate long polling */
  453. if (state->hi.lp_path) {
  454. if (pool->hdr_path != NULL)
  455. free(pool->hdr_path);
  456. pool->hdr_path = state->hi.lp_path;
  457. } else
  458. pool->hdr_path = NULL;
  459. if (state->hi.stratum_url) {
  460. pool->stratum_url = state->hi.stratum_url;
  461. state->hi.stratum_url = NULL;
  462. }
  463. } else {
  464. if (state->hi.lp_path) {
  465. free(state->hi.lp_path);
  466. state->hi.lp_path = NULL;
  467. }
  468. if (state->hi.stratum_url) {
  469. free(state->hi.stratum_url);
  470. state->hi.stratum_url = NULL;
  471. }
  472. }
  473. if (pool->force_rollntime)
  474. {
  475. state->hi.canroll = true;
  476. state->hi.hadexpire = true;
  477. state->hi.rolltime = pool->force_rollntime;
  478. }
  479. if (rolltime)
  480. *rolltime = state->hi.rolltime;
  481. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  482. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  483. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  484. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  485. val = JSON_LOADS(state->all_data.buf, &err);
  486. if (!val) {
  487. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  488. if (opt_protocol)
  489. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  490. goto err_out;
  491. }
  492. if (opt_protocol) {
  493. char *s = json_dumps(val, JSON_INDENT(3));
  494. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  495. free(s);
  496. }
  497. /* JSON-RPC valid response returns a non-null 'result',
  498. * and a null 'error'.
  499. */
  500. res_val = json_object_get(val, "result");
  501. err_val = json_object_get(val, "error");
  502. if (!res_val ||(err_val && !json_is_null(err_val))) {
  503. char *s;
  504. if (err_val)
  505. s = json_dumps(err_val, JSON_INDENT(3));
  506. else
  507. s = strdup("(unknown reason)");
  508. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  509. free(s);
  510. json_decref(val);
  511. goto err_out;
  512. }
  513. if (state->hi.reason) {
  514. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  515. free(state->hi.reason);
  516. state->hi.reason = NULL;
  517. }
  518. successful_connect = true;
  519. databuf_free(&state->all_data);
  520. curl_slist_free_all(state->headers);
  521. curl_easy_reset(curl);
  522. free(state);
  523. return val;
  524. err_out:
  525. databuf_free(&state->all_data);
  526. curl_slist_free_all(state->headers);
  527. curl_easy_reset(curl);
  528. if (!successful_connect)
  529. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  530. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  531. free(state);
  532. return NULL;
  533. }
  534. json_t *json_rpc_call(CURL *curl, const char *url,
  535. const char *userpass, const char *rpc_req,
  536. bool probe, bool longpoll, int *rolltime,
  537. struct pool *pool, bool share)
  538. {
  539. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  540. int rc = curl_easy_perform(curl);
  541. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  542. }
  543. bool our_curl_supports_proxy_uris()
  544. {
  545. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  546. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  547. }
  548. // NOTE: This assumes reference URI is a root
  549. char *absolute_uri(char *uri, const char *ref)
  550. {
  551. if (strstr(uri, "://"))
  552. return strdup(uri);
  553. char *copy_start, *abs;
  554. bool need_slash = false;
  555. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  556. if (ref[strlen(ref) - 1] != '/')
  557. need_slash = true;
  558. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  559. if (!abs) {
  560. applog(LOG_ERR, "Malloc failure in absolute_uri");
  561. return NULL;
  562. }
  563. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  564. return abs;
  565. }
  566. static const char _hexchars[0x10] = "0123456789abcdef";
  567. void bin2hex(char *out, const void *in, size_t len)
  568. {
  569. const unsigned char *p = in;
  570. while (len--)
  571. {
  572. (out++)[0] = _hexchars[p[0] >> 4];
  573. (out++)[0] = _hexchars[p[0] & 0xf];
  574. ++p;
  575. }
  576. out[0] = '\0';
  577. }
  578. static inline
  579. int _hex2bin_char(const char c)
  580. {
  581. if (c >= '0' && c <= '9')
  582. return c - '0';
  583. if (c >= 'a' && c <= 'f')
  584. return (c - 'a') + 10;
  585. if (c >= 'A' && c <= 'F')
  586. return (c - 'A') + 10;
  587. return -1;
  588. }
  589. /* Does the reverse of bin2hex but does not allocate any ram */
  590. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  591. {
  592. int n, o;
  593. while (len--)
  594. {
  595. n = _hex2bin_char((hexstr++)[0]);
  596. if (unlikely(n == -1))
  597. {
  598. badchar:
  599. if (!hexstr[-1])
  600. applog(LOG_ERR, "hex2bin: str truncated");
  601. else
  602. applog(LOG_ERR, "hex2bin: invalid character 0x%02x", (int)hexstr[-1]);
  603. return false;
  604. }
  605. o = _hex2bin_char((hexstr++)[0]);
  606. if (unlikely(o == -1))
  607. goto badchar;
  608. (p++)[0] = (n << 4) | o;
  609. }
  610. return likely(!hexstr[0]);
  611. }
  612. size_t ucs2_to_utf8(char * const out, const uint16_t * const in, const size_t sz)
  613. {
  614. uint8_t *p = (void*)out;
  615. for (int i = 0; i < sz; ++i)
  616. {
  617. const uint16_t c = in[i];
  618. if (c < 0x80)
  619. p++[0] = c;
  620. else
  621. {
  622. if (c < 0x800)
  623. p++[0] = 0xc0 | (c >> 6);
  624. else
  625. {
  626. p++[0] = 0xe0 | (c >> 12);
  627. p++[0] = 0x80 | ((c >> 6) & 0x3f);
  628. }
  629. p++[0] = 0x80 | (c & 0x3f);
  630. }
  631. }
  632. return p - (uint8_t*)(void*)out;
  633. }
  634. char *ucs2_to_utf8_dup(uint16_t * const in, size_t sz)
  635. {
  636. char * const out = malloc((sz * 4) + 1);
  637. sz = ucs2_to_utf8(out, in, sz);
  638. out[sz] = '\0';
  639. return out;
  640. }
  641. void hash_data(unsigned char *out_hash, const unsigned char *data)
  642. {
  643. unsigned char blkheader[80];
  644. // data is past the first SHA256 step (padding and interpreting as big endian on a little endian platform), so we need to flip each 32-bit chunk around to get the original input block header
  645. swap32yes(blkheader, data, 80 / 4);
  646. // double-SHA256 to get the block hash
  647. gen_hash(blkheader, out_hash, 80);
  648. }
  649. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  650. void real_block_target(unsigned char *target, const unsigned char *data)
  651. {
  652. uint8_t targetshift;
  653. if (unlikely(data[72] < 3 || data[72] > 0x20))
  654. {
  655. // Invalid (out of bounds) target
  656. memset(target, 0xff, 32);
  657. return;
  658. }
  659. targetshift = data[72] - 3;
  660. memset(target, 0, targetshift);
  661. target[targetshift++] = data[75];
  662. target[targetshift++] = data[74];
  663. target[targetshift++] = data[73];
  664. memset(&target[targetshift], 0, 0x20 - targetshift);
  665. }
  666. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  667. {
  668. const uint32_t *h32 = (uint32_t*)&hash[0];
  669. const uint32_t *t32 = (uint32_t*)&target[0];
  670. for (int i = 7; i >= 0; --i) {
  671. uint32_t h32i = le32toh(h32[i]);
  672. uint32_t t32i = le32toh(t32[i]);
  673. if (h32i > t32i)
  674. return false;
  675. if (h32i < t32i)
  676. return true;
  677. }
  678. return true;
  679. }
  680. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  681. {
  682. bool rc;
  683. rc = hash_target_check(hash, target);
  684. if (opt_debug) {
  685. unsigned char hash_swap[32], target_swap[32];
  686. char hash_str[65];
  687. char target_str[65];
  688. for (int i = 0; i < 32; ++i) {
  689. hash_swap[i] = hash[31-i];
  690. target_swap[i] = target[31-i];
  691. }
  692. bin2hex(hash_str, hash_swap, 32);
  693. bin2hex(target_str, target_swap, 32);
  694. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  695. hash_str,
  696. target_str,
  697. rc ? "YES (hash <= target)" :
  698. "no (false positive; hash > target)");
  699. }
  700. return rc;
  701. }
  702. // This operates on a native-endian SHA256 state
  703. // In other words, on little endian platforms, every 4 bytes are in reverse order
  704. bool fulltest(const unsigned char *hash, const unsigned char *target)
  705. {
  706. unsigned char hash2[32];
  707. swap32tobe(hash2, hash, 32 / 4);
  708. return hash_target_check_v(hash2, target);
  709. }
  710. struct thread_q *tq_new(void)
  711. {
  712. struct thread_q *tq;
  713. tq = calloc(1, sizeof(*tq));
  714. if (!tq)
  715. return NULL;
  716. pthread_mutex_init(&tq->mutex, NULL);
  717. pthread_cond_init(&tq->cond, NULL);
  718. return tq;
  719. }
  720. void tq_free(struct thread_q *tq)
  721. {
  722. struct tq_ent *ent, *iter;
  723. if (!tq)
  724. return;
  725. DL_FOREACH_SAFE(tq->q, ent, iter) {
  726. DL_DELETE(tq->q, ent);
  727. free(ent);
  728. }
  729. pthread_cond_destroy(&tq->cond);
  730. pthread_mutex_destroy(&tq->mutex);
  731. memset(tq, 0, sizeof(*tq)); /* poison */
  732. free(tq);
  733. }
  734. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  735. {
  736. mutex_lock(&tq->mutex);
  737. tq->frozen = frozen;
  738. pthread_cond_signal(&tq->cond);
  739. mutex_unlock(&tq->mutex);
  740. }
  741. void tq_freeze(struct thread_q *tq)
  742. {
  743. tq_freezethaw(tq, true);
  744. }
  745. void tq_thaw(struct thread_q *tq)
  746. {
  747. tq_freezethaw(tq, false);
  748. }
  749. bool tq_push(struct thread_q *tq, void *data)
  750. {
  751. struct tq_ent *ent;
  752. bool rc = true;
  753. ent = calloc(1, sizeof(*ent));
  754. if (!ent)
  755. return false;
  756. ent->data = data;
  757. mutex_lock(&tq->mutex);
  758. if (!tq->frozen) {
  759. DL_APPEND(tq->q, ent);
  760. } else {
  761. free(ent);
  762. rc = false;
  763. }
  764. pthread_cond_signal(&tq->cond);
  765. mutex_unlock(&tq->mutex);
  766. return rc;
  767. }
  768. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  769. {
  770. struct tq_ent *ent;
  771. void *rval = NULL;
  772. int rc;
  773. mutex_lock(&tq->mutex);
  774. if (tq->q)
  775. goto pop;
  776. if (abstime)
  777. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  778. else
  779. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  780. if (rc)
  781. goto out;
  782. if (!tq->q)
  783. goto out;
  784. pop:
  785. ent = tq->q;
  786. rval = ent->data;
  787. DL_DELETE(tq->q, ent);
  788. free(ent);
  789. out:
  790. mutex_unlock(&tq->mutex);
  791. return rval;
  792. }
  793. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  794. {
  795. int rv = pthread_create(&thr->pth, attr, start, arg);
  796. if (likely(!rv))
  797. thr->has_pth = true;
  798. return rv;
  799. }
  800. void thr_info_freeze(struct thr_info *thr)
  801. {
  802. struct tq_ent *ent, *iter;
  803. struct thread_q *tq;
  804. if (!thr)
  805. return;
  806. tq = thr->q;
  807. if (!tq)
  808. return;
  809. mutex_lock(&tq->mutex);
  810. tq->frozen = true;
  811. DL_FOREACH_SAFE(tq->q, ent, iter) {
  812. DL_DELETE(tq->q, ent);
  813. free(ent);
  814. }
  815. mutex_unlock(&tq->mutex);
  816. }
  817. void thr_info_cancel(struct thr_info *thr)
  818. {
  819. if (!thr)
  820. return;
  821. if (thr->has_pth) {
  822. pthread_cancel(thr->pth);
  823. thr->has_pth = false;
  824. }
  825. }
  826. #ifndef HAVE_PTHREAD_CANCEL
  827. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  828. enum pthread_cancel_workaround_mode {
  829. PCWM_DEFAULT = 0,
  830. PCWM_TERMINATE = 1,
  831. PCWM_ASYNC = 2,
  832. PCWM_DISABLED = 4,
  833. PCWM_CANCELLED = 8,
  834. };
  835. static pthread_key_t key_pcwm;
  836. struct sigaction pcwm_orig_term_handler;
  837. static
  838. void do_pthread_cancel_exit(int flags)
  839. {
  840. if (!(flags & PCWM_ASYNC))
  841. // NOTE: Logging disables cancel while mutex held, so this is safe
  842. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  843. pthread_exit(PTHREAD_CANCELED);
  844. }
  845. static
  846. void sighandler_pthread_cancel(int sig)
  847. {
  848. int flags = (int)pthread_getspecific(key_pcwm);
  849. if (flags & PCWM_TERMINATE) // Main thread
  850. {
  851. // Restore original handler and call it
  852. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  853. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  854. raise(SIGTERM);
  855. quit(1, "pthread_cancel workaround: Original handler returned");
  856. }
  857. if (flags & PCWM_CANCELLED) // Already pending cancel
  858. return;
  859. if (flags & PCWM_DISABLED)
  860. {
  861. flags |= PCWM_CANCELLED;
  862. if (pthread_setspecific(key_pcwm, (void*)flags))
  863. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  864. return;
  865. }
  866. do_pthread_cancel_exit(flags);
  867. }
  868. void pthread_testcancel(void)
  869. {
  870. int flags = (int)pthread_getspecific(key_pcwm);
  871. if (flags & PCWM_CANCELLED && !(flags & PCWM_DISABLED))
  872. do_pthread_cancel_exit(flags);
  873. }
  874. int pthread_setcancelstate(int state, int *oldstate)
  875. {
  876. int flags = (int)pthread_getspecific(key_pcwm);
  877. if (oldstate)
  878. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  879. if (state == PTHREAD_CANCEL_DISABLE)
  880. flags |= PCWM_DISABLED;
  881. else
  882. {
  883. if (flags & PCWM_CANCELLED)
  884. do_pthread_cancel_exit(flags);
  885. flags &= ~PCWM_DISABLED;
  886. }
  887. if (pthread_setspecific(key_pcwm, (void*)flags))
  888. return -1;
  889. return 0;
  890. }
  891. int pthread_setcanceltype(int type, int *oldtype)
  892. {
  893. int flags = (int)pthread_getspecific(key_pcwm);
  894. if (oldtype)
  895. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  896. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  897. flags |= PCWM_ASYNC;
  898. else
  899. flags &= ~PCWM_ASYNC;
  900. if (pthread_setspecific(key_pcwm, (void*)flags))
  901. return -1;
  902. return 0;
  903. }
  904. void setup_pthread_cancel_workaround()
  905. {
  906. if (pthread_key_create(&key_pcwm, NULL))
  907. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  908. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  909. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  910. struct sigaction new_sigact = {
  911. .sa_handler = sighandler_pthread_cancel,
  912. };
  913. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  914. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  915. }
  916. #endif
  917. static void _now_gettimeofday(struct timeval *);
  918. static void _cgsleep_us_r_nanosleep(cgtimer_t *, int64_t);
  919. #ifdef HAVE_POOR_GETTIMEOFDAY
  920. static struct timeval tv_timeofday_offset;
  921. static struct timeval _tv_timeofday_lastchecked;
  922. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  923. static
  924. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  925. {
  926. struct timeval actual, delta;
  927. timeradd(expected, &tv_timeofday_offset, expected);
  928. _now_gettimeofday(&actual);
  929. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  930. // Within reason - no change necessary
  931. return;
  932. timersub(&actual, expected, &delta);
  933. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  934. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  935. *expected = actual;
  936. }
  937. void bfg_gettimeofday(struct timeval *out)
  938. {
  939. char buf[64] = "";
  940. timer_set_now(out);
  941. mutex_lock(&_tv_timeofday_mutex);
  942. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  943. bfg_calibrate_timeofday(out, buf);
  944. else
  945. timeradd(out, &tv_timeofday_offset, out);
  946. mutex_unlock(&_tv_timeofday_mutex);
  947. if (unlikely(buf[0]))
  948. applog(LOG_WARNING, "%s", buf);
  949. }
  950. #endif
  951. #ifdef WIN32
  952. static LARGE_INTEGER _perffreq;
  953. static
  954. void _now_queryperformancecounter(struct timeval *tv)
  955. {
  956. LARGE_INTEGER now;
  957. if (unlikely(!QueryPerformanceCounter(&now)))
  958. quit(1, "QueryPerformanceCounter failed");
  959. *tv = (struct timeval){
  960. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  961. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  962. };
  963. }
  964. #endif
  965. static void bfg_init_time();
  966. static
  967. void _now_is_not_set(__maybe_unused struct timeval *tv)
  968. {
  969. bfg_init_time();
  970. timer_set_now(tv);
  971. }
  972. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  973. void (*cgsleep_us_r)(cgtimer_t *, int64_t) = _cgsleep_us_r_nanosleep;
  974. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  975. static clockid_t bfg_timer_clk;
  976. static
  977. void _now_clock_gettime(struct timeval *tv)
  978. {
  979. struct timespec ts;
  980. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  981. quit(1, "clock_gettime failed");
  982. *tv = (struct timeval){
  983. .tv_sec = ts.tv_sec,
  984. .tv_usec = ts.tv_nsec / 1000,
  985. };
  986. }
  987. #ifdef HAVE_CLOCK_NANOSLEEP
  988. static
  989. void _cgsleep_us_r_monotonic(cgtimer_t *tv_start, int64_t us)
  990. {
  991. struct timeval tv_end[1];
  992. struct timespec ts_end[1];
  993. int ret;
  994. timer_set_delay(tv_end, tv_start, us);
  995. timeval_to_spec(ts_end, tv_end);
  996. do {
  997. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  998. } while (ret == EINTR);
  999. }
  1000. #endif
  1001. static
  1002. bool _bfg_try_clock_gettime(clockid_t clk)
  1003. {
  1004. struct timespec ts;
  1005. if (clock_gettime(clk, &ts))
  1006. return false;
  1007. bfg_timer_clk = clk;
  1008. timer_set_now = _now_clock_gettime;
  1009. return true;
  1010. }
  1011. #endif
  1012. static
  1013. void bfg_init_time()
  1014. {
  1015. if (timer_set_now != _now_is_not_set)
  1016. return;
  1017. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1018. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1019. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1020. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1021. else
  1022. #endif
  1023. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1024. {
  1025. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1026. #ifdef HAVE_CLOCK_NANOSLEEP
  1027. cgsleep_us_r = _cgsleep_us_r_monotonic;
  1028. #endif
  1029. }
  1030. else
  1031. #endif
  1032. #ifdef WIN32
  1033. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1034. {
  1035. timer_set_now = _now_queryperformancecounter;
  1036. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1037. }
  1038. else
  1039. #endif
  1040. {
  1041. timer_set_now = _now_gettimeofday;
  1042. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1043. }
  1044. #ifdef HAVE_POOR_GETTIMEOFDAY
  1045. char buf[64] = "";
  1046. struct timeval tv;
  1047. timer_set_now(&tv);
  1048. bfg_calibrate_timeofday(&tv, buf);
  1049. applog(LOG_DEBUG, "%s", buf);
  1050. #endif
  1051. }
  1052. void subtime(struct timeval *a, struct timeval *b)
  1053. {
  1054. timersub(a, b, b);
  1055. }
  1056. void addtime(struct timeval *a, struct timeval *b)
  1057. {
  1058. timeradd(a, b, b);
  1059. }
  1060. bool time_more(struct timeval *a, struct timeval *b)
  1061. {
  1062. return timercmp(a, b, >);
  1063. }
  1064. bool time_less(struct timeval *a, struct timeval *b)
  1065. {
  1066. return timercmp(a, b, <);
  1067. }
  1068. void copy_time(struct timeval *dest, const struct timeval *src)
  1069. {
  1070. memcpy(dest, src, sizeof(struct timeval));
  1071. }
  1072. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  1073. {
  1074. val->tv_sec = spec->tv_sec;
  1075. val->tv_usec = spec->tv_nsec / 1000;
  1076. }
  1077. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  1078. {
  1079. spec->tv_sec = val->tv_sec;
  1080. spec->tv_nsec = val->tv_usec * 1000;
  1081. }
  1082. void us_to_timeval(struct timeval *val, int64_t us)
  1083. {
  1084. lldiv_t tvdiv = lldiv(us, 1000000);
  1085. val->tv_sec = tvdiv.quot;
  1086. val->tv_usec = tvdiv.rem;
  1087. }
  1088. void us_to_timespec(struct timespec *spec, int64_t us)
  1089. {
  1090. lldiv_t tvdiv = lldiv(us, 1000000);
  1091. spec->tv_sec = tvdiv.quot;
  1092. spec->tv_nsec = tvdiv.rem * 1000;
  1093. }
  1094. void ms_to_timespec(struct timespec *spec, int64_t ms)
  1095. {
  1096. lldiv_t tvdiv = lldiv(ms, 1000);
  1097. spec->tv_sec = tvdiv.quot;
  1098. spec->tv_nsec = tvdiv.rem * 1000000;
  1099. }
  1100. void timeraddspec(struct timespec *a, const struct timespec *b)
  1101. {
  1102. a->tv_sec += b->tv_sec;
  1103. a->tv_nsec += b->tv_nsec;
  1104. if (a->tv_nsec >= 1000000000) {
  1105. a->tv_nsec -= 1000000000;
  1106. a->tv_sec++;
  1107. }
  1108. }
  1109. #ifndef WIN32
  1110. static
  1111. void _now_gettimeofday(struct timeval *tv)
  1112. {
  1113. gettimeofday(tv, NULL);
  1114. }
  1115. #else
  1116. /* Windows start time is since 1601 lol so convert it to unix epoch 1970. */
  1117. #define EPOCHFILETIME (116444736000000000LL)
  1118. /* Return the system time as an lldiv_t in decimicroseconds. */
  1119. static void decius_time(lldiv_t *lidiv)
  1120. {
  1121. FILETIME ft;
  1122. LARGE_INTEGER li;
  1123. GetSystemTimeAsFileTime(&ft);
  1124. li.LowPart = ft.dwLowDateTime;
  1125. li.HighPart = ft.dwHighDateTime;
  1126. li.QuadPart -= EPOCHFILETIME;
  1127. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1128. *lidiv = lldiv(li.QuadPart, 10000000);
  1129. }
  1130. void _now_gettimeofday(struct timeval *tv)
  1131. {
  1132. lldiv_t lidiv;
  1133. decius_time(&lidiv);
  1134. tv->tv_sec = lidiv.quot;
  1135. tv->tv_usec = lidiv.rem / 10;
  1136. }
  1137. #endif
  1138. void cgsleep_ms_r(cgtimer_t *tv_start, int ms)
  1139. {
  1140. cgsleep_us_r(tv_start, ((int64_t)ms) * 1000);
  1141. }
  1142. static
  1143. void _cgsleep_us_r_nanosleep(cgtimer_t *tv_start, int64_t us)
  1144. {
  1145. struct timeval tv_timer[1], tv[1];
  1146. struct timespec ts[1];
  1147. timer_set_delay(tv_timer, tv_start, us);
  1148. while (true)
  1149. {
  1150. timer_set_now(tv);
  1151. if (!timercmp(tv_timer, tv, >))
  1152. return;
  1153. timersub(tv_timer, tv, tv);
  1154. timeval_to_spec(ts, tv);
  1155. nanosleep(ts, NULL);
  1156. }
  1157. }
  1158. void cgsleep_ms(int ms)
  1159. {
  1160. cgtimer_t ts_start;
  1161. cgsleep_prepare_r(&ts_start);
  1162. cgsleep_ms_r(&ts_start, ms);
  1163. }
  1164. void cgsleep_us(int64_t us)
  1165. {
  1166. cgtimer_t ts_start;
  1167. cgsleep_prepare_r(&ts_start);
  1168. cgsleep_us_r(&ts_start, us);
  1169. }
  1170. /* Returns the microseconds difference between end and start times as a double */
  1171. double us_tdiff(struct timeval *end, struct timeval *start)
  1172. {
  1173. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1174. }
  1175. /* Returns the seconds difference between end and start times as a double */
  1176. double tdiff(struct timeval *end, struct timeval *start)
  1177. {
  1178. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1179. }
  1180. int32_t utf8_decode(const void *b, int *out_len)
  1181. {
  1182. int32_t w;
  1183. const unsigned char *s = b;
  1184. if (!(s[0] & 0x80))
  1185. {
  1186. // ASCII
  1187. *out_len = 1;
  1188. return s[0];
  1189. }
  1190. #ifdef STRICT_UTF8
  1191. if (unlikely(!(s[0] & 0x40)))
  1192. goto invalid;
  1193. #endif
  1194. if (!(s[0] & 0x20))
  1195. *out_len = 2;
  1196. else
  1197. if (!(s[0] & 0x10))
  1198. *out_len = 3;
  1199. else
  1200. if (likely(!(s[0] & 8)))
  1201. *out_len = 4;
  1202. else
  1203. goto invalid;
  1204. w = s[0] & ((2 << (6 - *out_len)) - 1);
  1205. for (int i = 1; i < *out_len; ++i)
  1206. {
  1207. #ifdef STRICT_UTF8
  1208. if (unlikely((s[i] & 0xc0) != 0x80))
  1209. goto invalid;
  1210. #endif
  1211. w = (w << 6) | (s[i] & 0x3f);
  1212. }
  1213. #if defined(STRICT_UTF8)
  1214. if (unlikely(w > 0x10FFFF))
  1215. goto invalid;
  1216. // FIXME: UTF-8 requires smallest possible encoding; check it
  1217. #endif
  1218. return w;
  1219. invalid:
  1220. *out_len = 1;
  1221. return REPLACEMENT_CHAR;
  1222. }
  1223. static
  1224. void _utf8_test(const char *s, const wchar_t expected, int expectedlen)
  1225. {
  1226. int len;
  1227. wchar_t r;
  1228. r = utf8_decode(s, &len);
  1229. if (unlikely(r != expected || expectedlen != len))
  1230. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got U+%06lX (len %d)", (unsigned long)expected, expectedlen, (unsigned long)r, len);
  1231. }
  1232. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1233. void utf8_test()
  1234. {
  1235. _utf8_test("", 0, 1);
  1236. _utf8_test("\1", 1, 1);
  1237. _utf8_test("\x7f", 0x7f, 1);
  1238. #if WCHAR_MAX >= 0x80
  1239. _utf8_test("\xc2\x80", 0x80, 2);
  1240. #if WCHAR_MAX >= 0xff
  1241. _utf8_test("\xc3\xbf", 0xff, 2);
  1242. #if WCHAR_MAX >= 0x7ff
  1243. _utf8_test("\xdf\xbf", 0x7ff, 2);
  1244. #if WCHAR_MAX >= 0x800
  1245. _utf8_test("\xe0\xa0\x80", 0x800, 3);
  1246. #if WCHAR_MAX >= 0xffff
  1247. _utf8_test("\xef\xbf\xbf", 0xffff, 3);
  1248. #if WCHAR_MAX >= 0x10000
  1249. _utf8_test("\xf0\x90\x80\x80", 0x10000, 4);
  1250. #if WCHAR_MAX >= 0x10ffff
  1251. _utf8_test("\xf4\x8f\xbf\xbf", 0x10ffff, 4);
  1252. #endif
  1253. #endif
  1254. #endif
  1255. #endif
  1256. #endif
  1257. #endif
  1258. #endif
  1259. #ifdef STRICT_UTF8
  1260. _utf8_test("\x80", REPLACEMENT_CHAR, 1);
  1261. _utf8_test("\xbf", REPLACEMENT_CHAR, 1);
  1262. _utf8_test("\xfe", REPLACEMENT_CHAR, 1);
  1263. _utf8_test("\xff", REPLACEMENT_CHAR, 1);
  1264. #endif
  1265. }
  1266. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1267. {
  1268. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1269. char url_address[256], port[6];
  1270. int url_len, port_len = 0;
  1271. url_begin = strstr(url, "//");
  1272. if (!url_begin)
  1273. url_begin = url;
  1274. else
  1275. url_begin += 2;
  1276. /* Look for numeric ipv6 entries */
  1277. ipv6_begin = strstr(url_begin, "[");
  1278. ipv6_end = strstr(url_begin, "]");
  1279. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1280. url_end = strstr(ipv6_end, ":");
  1281. else
  1282. url_end = strstr(url_begin, ":");
  1283. if (url_end) {
  1284. url_len = url_end - url_begin;
  1285. port_len = strlen(url_begin) - url_len - 1;
  1286. if (port_len < 1)
  1287. return false;
  1288. port_start = url_end + 1;
  1289. } else
  1290. url_len = strlen(url_begin);
  1291. if (url_len < 1)
  1292. return false;
  1293. sprintf(url_address, "%.*s", url_len, url_begin);
  1294. if (port_len) {
  1295. char *slash;
  1296. snprintf(port, 6, "%.*s", port_len, port_start);
  1297. slash = strchr(port, '/');
  1298. if (slash)
  1299. *slash = '\0';
  1300. } else
  1301. strcpy(port, "80");
  1302. free(*sockaddr_port);
  1303. *sockaddr_port = strdup(port);
  1304. free(*sockaddr_url);
  1305. *sockaddr_url = strdup(url_address);
  1306. return true;
  1307. }
  1308. enum send_ret {
  1309. SEND_OK,
  1310. SEND_SELECTFAIL,
  1311. SEND_SENDFAIL,
  1312. SEND_INACTIVE
  1313. };
  1314. /* Send a single command across a socket, appending \n to it. This should all
  1315. * be done under stratum lock except when first establishing the socket */
  1316. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1317. {
  1318. SOCKETTYPE sock = pool->sock;
  1319. ssize_t ssent = 0;
  1320. strcat(s, "\n");
  1321. len++;
  1322. while (len > 0 ) {
  1323. struct timeval timeout = {1, 0};
  1324. ssize_t sent;
  1325. fd_set wd;
  1326. FD_ZERO(&wd);
  1327. FD_SET(sock, &wd);
  1328. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  1329. return SEND_SELECTFAIL;
  1330. #ifdef __APPLE__
  1331. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1332. #elif WIN32
  1333. sent = send(pool->sock, s + ssent, len, 0);
  1334. #else
  1335. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1336. #endif
  1337. if (sent < 0) {
  1338. if (!sock_blocks())
  1339. return SEND_SENDFAIL;
  1340. sent = 0;
  1341. }
  1342. ssent += sent;
  1343. len -= sent;
  1344. }
  1345. pool->cgminer_pool_stats.times_sent++;
  1346. pool->cgminer_pool_stats.bytes_sent += ssent;
  1347. total_bytes_sent += ssent;
  1348. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1349. return SEND_OK;
  1350. }
  1351. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1352. {
  1353. enum send_ret ret = SEND_INACTIVE;
  1354. if (opt_protocol)
  1355. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1356. mutex_lock(&pool->stratum_lock);
  1357. if (pool->stratum_active || force)
  1358. ret = __stratum_send(pool, s, len);
  1359. mutex_unlock(&pool->stratum_lock);
  1360. /* This is to avoid doing applog under stratum_lock */
  1361. switch (ret) {
  1362. default:
  1363. case SEND_OK:
  1364. break;
  1365. case SEND_SELECTFAIL:
  1366. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1367. suspend_stratum(pool);
  1368. break;
  1369. case SEND_SENDFAIL:
  1370. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1371. suspend_stratum(pool);
  1372. break;
  1373. case SEND_INACTIVE:
  1374. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1375. break;
  1376. }
  1377. return (ret == SEND_OK);
  1378. }
  1379. static bool socket_full(struct pool *pool, int wait)
  1380. {
  1381. SOCKETTYPE sock = pool->sock;
  1382. struct timeval timeout;
  1383. fd_set rd;
  1384. if (sock == INVSOCK)
  1385. return true;
  1386. if (unlikely(wait < 0))
  1387. wait = 0;
  1388. FD_ZERO(&rd);
  1389. FD_SET(sock, &rd);
  1390. timeout.tv_usec = 0;
  1391. timeout.tv_sec = wait;
  1392. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1393. return true;
  1394. return false;
  1395. }
  1396. /* Check to see if Santa's been good to you */
  1397. bool sock_full(struct pool *pool)
  1398. {
  1399. if (strlen(pool->sockbuf))
  1400. return true;
  1401. return (socket_full(pool, 0));
  1402. }
  1403. static void clear_sockbuf(struct pool *pool)
  1404. {
  1405. strcpy(pool->sockbuf, "");
  1406. }
  1407. static void clear_sock(struct pool *pool)
  1408. {
  1409. ssize_t n;
  1410. mutex_lock(&pool->stratum_lock);
  1411. do {
  1412. if (pool->sock)
  1413. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1414. else
  1415. n = 0;
  1416. } while (n > 0);
  1417. mutex_unlock(&pool->stratum_lock);
  1418. clear_sockbuf(pool);
  1419. }
  1420. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1421. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1422. * and zeroing the new memory */
  1423. static void recalloc_sock(struct pool *pool, size_t len)
  1424. {
  1425. size_t old, new;
  1426. old = strlen(pool->sockbuf);
  1427. new = old + len + 1;
  1428. if (new < pool->sockbuf_size)
  1429. return;
  1430. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1431. // Avoid potentially recursive locking
  1432. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1433. pool->sockbuf = realloc(pool->sockbuf, new);
  1434. if (!pool->sockbuf)
  1435. quithere(1, "Failed to realloc pool sockbuf");
  1436. memset(pool->sockbuf + old, 0, new - old);
  1437. pool->sockbuf_size = new;
  1438. }
  1439. /* Peeks at a socket to find the first end of line and then reads just that
  1440. * from the socket and returns that as a malloced char */
  1441. char *recv_line(struct pool *pool)
  1442. {
  1443. char *tok, *sret = NULL;
  1444. ssize_t len, buflen;
  1445. int waited = 0;
  1446. if (!strstr(pool->sockbuf, "\n")) {
  1447. struct timeval rstart, now;
  1448. cgtime(&rstart);
  1449. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1450. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1451. goto out;
  1452. }
  1453. do {
  1454. char s[RBUFSIZE];
  1455. size_t slen;
  1456. ssize_t n;
  1457. memset(s, 0, RBUFSIZE);
  1458. n = recv(pool->sock, s, RECVSIZE, 0);
  1459. if (!n) {
  1460. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1461. suspend_stratum(pool);
  1462. break;
  1463. }
  1464. cgtime(&now);
  1465. waited = tdiff(&now, &rstart);
  1466. if (n < 0) {
  1467. //Save errno from being overweitten bei socket_ commands
  1468. int socket_recv_errno;
  1469. socket_recv_errno = SOCKERR;
  1470. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1471. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %s", bfg_strerror(socket_recv_errno, BST_SOCKET));
  1472. suspend_stratum(pool);
  1473. break;
  1474. }
  1475. } else {
  1476. slen = strlen(s);
  1477. recalloc_sock(pool, slen);
  1478. strcat(pool->sockbuf, s);
  1479. }
  1480. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1481. }
  1482. buflen = strlen(pool->sockbuf);
  1483. tok = strtok(pool->sockbuf, "\n");
  1484. if (!tok) {
  1485. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1486. goto out;
  1487. }
  1488. sret = strdup(tok);
  1489. len = strlen(sret);
  1490. /* Copy what's left in the buffer after the \n, including the
  1491. * terminating \0 */
  1492. if (buflen > len + 1)
  1493. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1494. else
  1495. strcpy(pool->sockbuf, "");
  1496. pool->cgminer_pool_stats.times_received++;
  1497. pool->cgminer_pool_stats.bytes_received += len;
  1498. total_bytes_rcvd += len;
  1499. pool->cgminer_pool_stats.net_bytes_received += len;
  1500. out:
  1501. if (!sret)
  1502. clear_sock(pool);
  1503. else if (opt_protocol)
  1504. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1505. return sret;
  1506. }
  1507. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1508. * flag, but this is compatible with 2.0. */
  1509. char *json_dumps_ANY(json_t *json, size_t flags)
  1510. {
  1511. switch (json_typeof(json))
  1512. {
  1513. case JSON_ARRAY:
  1514. case JSON_OBJECT:
  1515. return json_dumps(json, flags);
  1516. default:
  1517. break;
  1518. }
  1519. char *rv;
  1520. #ifdef JSON_ENCODE_ANY
  1521. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1522. if (rv)
  1523. return rv;
  1524. #endif
  1525. json_t *tmp = json_array();
  1526. char *s;
  1527. int i;
  1528. size_t len;
  1529. if (!tmp)
  1530. quithere(1, "Failed to allocate json array");
  1531. if (json_array_append(tmp, json))
  1532. quithere(1, "Failed to append temporary array");
  1533. s = json_dumps(tmp, flags);
  1534. if (!s)
  1535. return NULL;
  1536. for (i = 0; s[i] != '['; ++i)
  1537. if (unlikely(!(s[i] && isCspace(s[i]))))
  1538. quithere(1, "Failed to find opening bracket in array dump");
  1539. len = strlen(&s[++i]) - 1;
  1540. if (unlikely(s[i+len] != ']'))
  1541. quithere(1, "Failed to find closing bracket in array dump");
  1542. rv = malloc(len + 1);
  1543. memcpy(rv, &s[i], len);
  1544. rv[len] = '\0';
  1545. free(s);
  1546. json_decref(tmp);
  1547. return rv;
  1548. }
  1549. /* Extracts a string value from a json array with error checking. To be used
  1550. * when the value of the string returned is only examined and not to be stored.
  1551. * See json_array_string below */
  1552. const char *__json_array_string(json_t *val, unsigned int entry)
  1553. {
  1554. json_t *arr_entry;
  1555. if (json_is_null(val))
  1556. return NULL;
  1557. if (!json_is_array(val))
  1558. return NULL;
  1559. if (entry > json_array_size(val))
  1560. return NULL;
  1561. arr_entry = json_array_get(val, entry);
  1562. if (!json_is_string(arr_entry))
  1563. return NULL;
  1564. return json_string_value(arr_entry);
  1565. }
  1566. /* Creates a freshly malloced dup of __json_array_string */
  1567. static char *json_array_string(json_t *val, unsigned int entry)
  1568. {
  1569. const char *buf = __json_array_string(val, entry);
  1570. if (buf)
  1571. return strdup(buf);
  1572. return NULL;
  1573. }
  1574. void stratum_probe_transparency(struct pool *pool)
  1575. {
  1576. // Request transaction data to discourage pools from doing anything shady
  1577. char s[1024];
  1578. int sLen;
  1579. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1580. pool->swork.job_id,
  1581. pool->swork.job_id);
  1582. stratum_send(pool, s, sLen);
  1583. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  1584. cgtime(&pool->swork.tv_transparency);
  1585. pool->swork.transparency_probed = true;
  1586. }
  1587. static bool parse_notify(struct pool *pool, json_t *val)
  1588. {
  1589. const char *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1590. char *job_id;
  1591. bool clean, ret = false;
  1592. int merkles, i;
  1593. size_t cb1_len, cb2_len;
  1594. json_t *arr;
  1595. arr = json_array_get(val, 4);
  1596. if (!arr || !json_is_array(arr))
  1597. goto out;
  1598. merkles = json_array_size(arr);
  1599. for (i = 0; i < merkles; i++)
  1600. if (!json_is_string(json_array_get(arr, i)))
  1601. goto out;
  1602. prev_hash = __json_array_string(val, 1);
  1603. coinbase1 = __json_array_string(val, 2);
  1604. coinbase2 = __json_array_string(val, 3);
  1605. bbversion = __json_array_string(val, 5);
  1606. nbit = __json_array_string(val, 6);
  1607. ntime = __json_array_string(val, 7);
  1608. clean = json_is_true(json_array_get(val, 8));
  1609. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  1610. goto out;
  1611. job_id = json_array_string(val, 0);
  1612. if (!job_id)
  1613. goto out;
  1614. cg_wlock(&pool->data_lock);
  1615. cgtime(&pool->swork.tv_received);
  1616. free(pool->swork.job_id);
  1617. pool->swork.job_id = job_id;
  1618. pool->submit_old = !clean;
  1619. pool->swork.clean = true;
  1620. hex2bin(&pool->swork.header1[0], bbversion, 4);
  1621. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  1622. hex2bin((void*)&pool->swork.ntime, ntime, 4);
  1623. pool->swork.ntime = be32toh(pool->swork.ntime);
  1624. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  1625. cb1_len = strlen(coinbase1) / 2;
  1626. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  1627. cb2_len = strlen(coinbase2) / 2;
  1628. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->n2size + cb2_len);
  1629. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  1630. hex2bin(coinbase, coinbase1, cb1_len);
  1631. hex2bin(&coinbase[cb1_len], pool->nonce1, pool->n1_len);
  1632. // NOTE: gap for nonce2, filled at work generation time
  1633. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->n2size], coinbase2, cb2_len);
  1634. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  1635. for (i = 0; i < merkles; i++)
  1636. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  1637. pool->swork.merkles = merkles;
  1638. pool->nonce2 = 0;
  1639. cg_wunlock(&pool->data_lock);
  1640. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1641. pool->pool_no, job_id);
  1642. if (opt_debug && opt_protocol)
  1643. {
  1644. applog(LOG_DEBUG, "job_id: %s", job_id);
  1645. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1646. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1647. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1648. for (i = 0; i < merkles; i++)
  1649. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  1650. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1651. applog(LOG_DEBUG, "nbit: %s", nbit);
  1652. applog(LOG_DEBUG, "ntime: %s", ntime);
  1653. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1654. }
  1655. /* A notify message is the closest stratum gets to a getwork */
  1656. pool->getwork_requested++;
  1657. total_getworks++;
  1658. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  1659. if (pool->probed)
  1660. stratum_probe_transparency(pool);
  1661. ret = true;
  1662. out:
  1663. return ret;
  1664. }
  1665. static bool parse_diff(struct pool *pool, json_t *val)
  1666. {
  1667. double diff;
  1668. diff = json_number_value(json_array_get(val, 0));
  1669. if (diff == 0)
  1670. return false;
  1671. cg_wlock(&pool->data_lock);
  1672. pool->swork.diff = diff;
  1673. cg_wunlock(&pool->data_lock);
  1674. applog(LOG_DEBUG, "Pool %d stratum bdifficulty set to %f", pool->pool_no, diff);
  1675. return true;
  1676. }
  1677. static bool parse_reconnect(struct pool *pool, json_t *val)
  1678. {
  1679. const char *url, *port;
  1680. char address[256];
  1681. url = __json_array_string(val, 0);
  1682. if (!url)
  1683. url = pool->sockaddr_url;
  1684. port = __json_array_string(val, 1);
  1685. if (!port)
  1686. port = pool->stratum_port;
  1687. snprintf(address, sizeof(address), "%s:%s", url, port);
  1688. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  1689. return false;
  1690. pool->stratum_url = pool->sockaddr_url;
  1691. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1692. if (!restart_stratum(pool))
  1693. return false;
  1694. return true;
  1695. }
  1696. static bool send_version(struct pool *pool, json_t *val)
  1697. {
  1698. char s[RBUFSIZE], *idstr;
  1699. json_t *id = json_object_get(val, "id");
  1700. if (!(id && !json_is_null(id)))
  1701. return false;
  1702. idstr = json_dumps_ANY(id, 0);
  1703. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1704. free(idstr);
  1705. if (!stratum_send(pool, s, strlen(s)))
  1706. return false;
  1707. return true;
  1708. }
  1709. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  1710. {
  1711. char *msg;
  1712. char s[RBUFSIZE], *idstr;
  1713. json_t *id = json_object_get(val, "id");
  1714. msg = json_array_string(params, 0);
  1715. if (likely(msg))
  1716. {
  1717. free(pool->admin_msg);
  1718. pool->admin_msg = msg;
  1719. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  1720. }
  1721. if (!(id && !json_is_null(id)))
  1722. return true;
  1723. idstr = json_dumps_ANY(id, 0);
  1724. if (likely(msg))
  1725. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  1726. else
  1727. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  1728. free(idstr);
  1729. if (!stratum_send(pool, s, strlen(s)))
  1730. return false;
  1731. return true;
  1732. }
  1733. bool parse_method(struct pool *pool, char *s)
  1734. {
  1735. json_t *val = NULL, *method, *err_val, *params;
  1736. json_error_t err;
  1737. bool ret = false;
  1738. const char *buf;
  1739. if (!s)
  1740. goto out;
  1741. val = JSON_LOADS(s, &err);
  1742. if (!val) {
  1743. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1744. goto out;
  1745. }
  1746. method = json_object_get(val, "method");
  1747. if (!method)
  1748. goto out;
  1749. err_val = json_object_get(val, "error");
  1750. params = json_object_get(val, "params");
  1751. if (err_val && !json_is_null(err_val)) {
  1752. char *ss;
  1753. if (err_val)
  1754. ss = json_dumps(err_val, JSON_INDENT(3));
  1755. else
  1756. ss = strdup("(unknown reason)");
  1757. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1758. free(ss);
  1759. goto out;
  1760. }
  1761. buf = json_string_value(method);
  1762. if (!buf)
  1763. goto out;
  1764. if (!strncasecmp(buf, "mining.notify", 13)) {
  1765. if (parse_notify(pool, params))
  1766. pool->stratum_notify = ret = true;
  1767. else
  1768. pool->stratum_notify = ret = false;
  1769. goto out;
  1770. }
  1771. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1772. ret = true;
  1773. goto out;
  1774. }
  1775. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1776. ret = true;
  1777. goto out;
  1778. }
  1779. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1780. ret = true;
  1781. goto out;
  1782. }
  1783. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  1784. ret = true;
  1785. goto out;
  1786. }
  1787. out:
  1788. if (val)
  1789. json_decref(val);
  1790. return ret;
  1791. }
  1792. extern bool parse_stratum_response(struct pool *, char *s);
  1793. bool auth_stratum(struct pool *pool)
  1794. {
  1795. json_t *val = NULL, *res_val, *err_val;
  1796. char s[RBUFSIZE], *sret = NULL;
  1797. json_error_t err;
  1798. bool ret = false;
  1799. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1800. pool->rpc_user, pool->rpc_pass);
  1801. if (!stratum_send(pool, s, strlen(s)))
  1802. goto out;
  1803. /* Parse all data in the queue and anything left should be auth */
  1804. while (42) {
  1805. sret = recv_line(pool);
  1806. if (!sret)
  1807. goto out;
  1808. if (parse_method(pool, sret))
  1809. free(sret);
  1810. else
  1811. break;
  1812. }
  1813. val = JSON_LOADS(sret, &err);
  1814. free(sret);
  1815. res_val = json_object_get(val, "result");
  1816. err_val = json_object_get(val, "error");
  1817. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1818. char *ss;
  1819. if (err_val)
  1820. ss = json_dumps(err_val, JSON_INDENT(3));
  1821. else
  1822. ss = strdup("(unknown reason)");
  1823. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1824. free(ss);
  1825. goto out;
  1826. }
  1827. ret = true;
  1828. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1829. pool->probed = true;
  1830. successful_connect = true;
  1831. out:
  1832. if (val)
  1833. json_decref(val);
  1834. if (pool->stratum_notify)
  1835. stratum_probe_transparency(pool);
  1836. return ret;
  1837. }
  1838. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1839. {
  1840. struct pool *pool = clientp;
  1841. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1842. pool->sock = sck;
  1843. return sck;
  1844. }
  1845. static bool setup_stratum_curl(struct pool *pool)
  1846. {
  1847. char curl_err_str[CURL_ERROR_SIZE];
  1848. CURL *curl = NULL;
  1849. char s[RBUFSIZE];
  1850. bool ret = false;
  1851. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1852. mutex_lock(&pool->stratum_lock);
  1853. timer_unset(&pool->swork.tv_transparency);
  1854. pool->stratum_active = false;
  1855. pool->stratum_notify = false;
  1856. pool->swork.transparency_probed = false;
  1857. if (pool->stratum_curl)
  1858. curl_easy_cleanup(pool->stratum_curl);
  1859. pool->stratum_curl = curl_easy_init();
  1860. if (unlikely(!pool->stratum_curl))
  1861. quithere(1, "Failed to curl_easy_init");
  1862. if (pool->sockbuf)
  1863. pool->sockbuf[0] = '\0';
  1864. curl = pool->stratum_curl;
  1865. if (!pool->sockbuf) {
  1866. pool->sockbuf = calloc(RBUFSIZE, 1);
  1867. if (!pool->sockbuf)
  1868. quithere(1, "Failed to calloc pool sockbuf");
  1869. pool->sockbuf_size = RBUFSIZE;
  1870. }
  1871. /* Create a http url for use with curl */
  1872. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1873. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1874. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1875. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1876. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1877. curl_easy_setopt(curl, CURLOPT_URL, s);
  1878. if (!opt_delaynet)
  1879. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1880. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1881. * to enable it */
  1882. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  1883. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  1884. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1885. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  1886. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  1887. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  1888. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1889. if (pool->rpc_proxy) {
  1890. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  1891. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1892. } else if (opt_socks_proxy) {
  1893. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  1894. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1895. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  1896. }
  1897. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1898. pool->sock = INVSOCK;
  1899. if (curl_easy_perform(curl)) {
  1900. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1901. errout:
  1902. curl_easy_cleanup(curl);
  1903. pool->stratum_curl = NULL;
  1904. goto out;
  1905. }
  1906. if (pool->sock == INVSOCK)
  1907. {
  1908. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  1909. goto errout;
  1910. }
  1911. keep_sockalive(pool->sock);
  1912. pool->cgminer_pool_stats.times_sent++;
  1913. pool->cgminer_pool_stats.times_received++;
  1914. ret = true;
  1915. out:
  1916. mutex_unlock(&pool->stratum_lock);
  1917. return ret;
  1918. }
  1919. static char *get_sessionid(json_t *val)
  1920. {
  1921. char *ret = NULL;
  1922. json_t *arr_val;
  1923. int arrsize, i;
  1924. arr_val = json_array_get(val, 0);
  1925. if (!arr_val || !json_is_array(arr_val))
  1926. goto out;
  1927. arrsize = json_array_size(arr_val);
  1928. for (i = 0; i < arrsize; i++) {
  1929. json_t *arr = json_array_get(arr_val, i);
  1930. const char *notify;
  1931. if (!arr | !json_is_array(arr))
  1932. break;
  1933. notify = __json_array_string(arr, 0);
  1934. if (!notify)
  1935. continue;
  1936. if (!strncasecmp(notify, "mining.notify", 13)) {
  1937. ret = json_array_string(arr, 1);
  1938. break;
  1939. }
  1940. }
  1941. out:
  1942. return ret;
  1943. }
  1944. void suspend_stratum(struct pool *pool)
  1945. {
  1946. clear_sockbuf(pool);
  1947. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1948. mutex_lock(&pool->stratum_lock);
  1949. pool->stratum_active = pool->stratum_notify = false;
  1950. if (pool->stratum_curl) {
  1951. curl_easy_cleanup(pool->stratum_curl);
  1952. }
  1953. pool->stratum_curl = NULL;
  1954. pool->sock = INVSOCK;
  1955. mutex_unlock(&pool->stratum_lock);
  1956. }
  1957. bool initiate_stratum(struct pool *pool)
  1958. {
  1959. bool ret = false, recvd = false, noresume = false, sockd = false;
  1960. bool trysuggest = request_target_str;
  1961. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1962. json_t *val = NULL, *res_val, *err_val;
  1963. json_error_t err;
  1964. int n2size;
  1965. resend:
  1966. if (!setup_stratum_curl(pool)) {
  1967. sockd = false;
  1968. goto out;
  1969. }
  1970. sockd = true;
  1971. clear_sock(pool);
  1972. if (trysuggest)
  1973. {
  1974. int sz = sprintf(s, "{\"id\": null, \"method\": \"mining.suggest_target\", \"params\": [\"%s\"]}", request_target_str);
  1975. if (!_stratum_send(pool, s, sz, true))
  1976. {
  1977. applog(LOG_DEBUG, "Pool %u: Failed to send suggest_target in initiate_stratum", pool->pool_no);
  1978. goto out;
  1979. }
  1980. recvd = true;
  1981. }
  1982. if (noresume) {
  1983. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1984. } else {
  1985. if (pool->sessionid)
  1986. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1987. else
  1988. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1989. }
  1990. if (!_stratum_send(pool, s, strlen(s), true)) {
  1991. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1992. goto out;
  1993. }
  1994. recvd = true;
  1995. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1996. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1997. goto out;
  1998. }
  1999. sret = recv_line(pool);
  2000. if (!sret)
  2001. goto out;
  2002. val = JSON_LOADS(sret, &err);
  2003. free(sret);
  2004. if (!val) {
  2005. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2006. goto out;
  2007. }
  2008. res_val = json_object_get(val, "result");
  2009. err_val = json_object_get(val, "error");
  2010. if (!res_val || json_is_null(res_val) ||
  2011. (err_val && !json_is_null(err_val))) {
  2012. char *ss;
  2013. if (err_val)
  2014. ss = json_dumps(err_val, JSON_INDENT(3));
  2015. else
  2016. ss = strdup("(unknown reason)");
  2017. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2018. free(ss);
  2019. goto out;
  2020. }
  2021. sessionid = get_sessionid(res_val);
  2022. if (!sessionid)
  2023. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2024. nonce1 = json_array_string(res_val, 1);
  2025. if (!nonce1) {
  2026. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  2027. free(sessionid);
  2028. goto out;
  2029. }
  2030. n2size = json_integer_value(json_array_get(res_val, 2));
  2031. if (!n2size) {
  2032. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  2033. free(sessionid);
  2034. free(nonce1);
  2035. goto out;
  2036. }
  2037. cg_wlock(&pool->data_lock);
  2038. free(pool->sessionid);
  2039. pool->sessionid = sessionid;
  2040. free(pool->nonce1);
  2041. pool->nonce1 = nonce1;
  2042. pool->n1_len = strlen(nonce1) / 2;
  2043. pool->n2size = n2size;
  2044. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  2045. #ifdef WORDS_BIGENDIAN
  2046. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  2047. #endif
  2048. cg_wunlock(&pool->data_lock);
  2049. if (sessionid)
  2050. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2051. ret = true;
  2052. out:
  2053. if (val)
  2054. {
  2055. json_decref(val);
  2056. val = NULL;
  2057. }
  2058. if (ret) {
  2059. if (!pool->stratum_url)
  2060. pool->stratum_url = pool->sockaddr_url;
  2061. pool->stratum_active = true;
  2062. pool->swork.diff = 1;
  2063. if (opt_protocol) {
  2064. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2065. pool->pool_no, pool->nonce1, pool->n2size);
  2066. }
  2067. } else {
  2068. if (recvd)
  2069. {
  2070. if (trysuggest)
  2071. {
  2072. applog(LOG_DEBUG, "Pool %u: Failed to connect stratum with mining.suggest_target, retrying without", pool->pool_no);
  2073. trysuggest = false;
  2074. goto resend;
  2075. }
  2076. if (!noresume)
  2077. {
  2078. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2079. noresume = true;
  2080. goto resend;
  2081. }
  2082. }
  2083. applog(LOG_DEBUG, "Initiate stratum failed");
  2084. if (sockd)
  2085. suspend_stratum(pool);
  2086. }
  2087. return ret;
  2088. }
  2089. bool restart_stratum(struct pool *pool)
  2090. {
  2091. if (pool->stratum_active)
  2092. suspend_stratum(pool);
  2093. if (!initiate_stratum(pool))
  2094. return false;
  2095. if (!auth_stratum(pool))
  2096. return false;
  2097. return true;
  2098. }
  2099. void dev_error_update(struct cgpu_info *dev, enum dev_reason reason)
  2100. {
  2101. dev->device_last_not_well = time(NULL);
  2102. cgtime(&dev->tv_device_last_not_well);
  2103. dev->device_not_well_reason = reason;
  2104. }
  2105. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2106. {
  2107. dev_error_update(dev, reason);
  2108. switch (reason) {
  2109. case REASON_THREAD_FAIL_INIT:
  2110. dev->thread_fail_init_count++;
  2111. break;
  2112. case REASON_THREAD_ZERO_HASH:
  2113. dev->thread_zero_hash_count++;
  2114. break;
  2115. case REASON_THREAD_FAIL_QUEUE:
  2116. dev->thread_fail_queue_count++;
  2117. break;
  2118. case REASON_DEV_SICK_IDLE_60:
  2119. dev->dev_sick_idle_60_count++;
  2120. break;
  2121. case REASON_DEV_DEAD_IDLE_600:
  2122. dev->dev_dead_idle_600_count++;
  2123. break;
  2124. case REASON_DEV_NOSTART:
  2125. dev->dev_nostart_count++;
  2126. break;
  2127. case REASON_DEV_OVER_HEAT:
  2128. dev->dev_over_heat_count++;
  2129. break;
  2130. case REASON_DEV_THERMAL_CUTOFF:
  2131. dev->dev_thermal_cutoff_count++;
  2132. break;
  2133. case REASON_DEV_COMMS_ERROR:
  2134. dev->dev_comms_error_count++;
  2135. break;
  2136. case REASON_DEV_THROTTLE:
  2137. dev->dev_throttle_count++;
  2138. break;
  2139. }
  2140. }
  2141. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2142. void *realloc_strcat(char *ptr, char *s)
  2143. {
  2144. size_t old = strlen(ptr), len = strlen(s);
  2145. char *ret;
  2146. if (!len)
  2147. return ptr;
  2148. len += old + 1;
  2149. align_len(&len);
  2150. ret = malloc(len);
  2151. if (unlikely(!ret))
  2152. quithere(1, "Failed to malloc");
  2153. sprintf(ret, "%s%s", ptr, s);
  2154. free(ptr);
  2155. return ret;
  2156. }
  2157. static
  2158. bool sanechars[] = {
  2159. false, false, false, false, false, false, false, false,
  2160. false, false, false, false, false, false, false, false,
  2161. false, false, false, false, false, false, false, false,
  2162. false, false, false, false, false, false, false, false,
  2163. false, false, false, false, false, false, false, false,
  2164. false, false, false, false, false, false, false, false,
  2165. true , true , true , true , true , true , true , true ,
  2166. true , true , false, false, false, false, false, false,
  2167. false, true , true , true , true , true , true , true ,
  2168. true , true , true , true , true , true , true , true ,
  2169. true , true , true , true , true , true , true , true ,
  2170. true , true , true , false, false, false, false, false,
  2171. false, true , true , true , true , true , true , true ,
  2172. true , true , true , true , true , true , true , true ,
  2173. true , true , true , true , true , true , true , true ,
  2174. true , true , true , false, false, false, false, false,
  2175. };
  2176. char *sanestr(char *o, char *s)
  2177. {
  2178. char *rv = o;
  2179. bool br = false;
  2180. for ( ; s[0]; ++s)
  2181. {
  2182. if (sanechars[s[0] & 0x7f])
  2183. {
  2184. if (br)
  2185. {
  2186. br = false;
  2187. if (s[0] >= '0' && s[0] <= '9')
  2188. (o++)[0] = '_';
  2189. }
  2190. (o++)[0] = s[0];
  2191. }
  2192. else
  2193. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  2194. br = true;
  2195. }
  2196. o[0] = '\0';
  2197. return rv;
  2198. }
  2199. void RenameThread(const char* name)
  2200. {
  2201. #if defined(PR_SET_NAME)
  2202. // Only the first 15 characters are used (16 - NUL terminator)
  2203. prctl(PR_SET_NAME, name, 0, 0, 0);
  2204. #elif defined(__APPLE__)
  2205. pthread_setname_np(name);
  2206. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2207. pthread_set_name_np(pthread_self(), name);
  2208. #else
  2209. // Prevent warnings for unused parameters...
  2210. (void)name;
  2211. #endif
  2212. }
  2213. static pthread_key_t key_bfgtls;
  2214. struct bfgtls_data {
  2215. char *bfg_strerror_result;
  2216. size_t bfg_strerror_resultsz;
  2217. #ifdef WIN32
  2218. LPSTR bfg_strerror_socketresult;
  2219. #endif
  2220. #ifdef NEED_BFG_LOWL_VCOM
  2221. struct detectone_meta_info_t __detectone_meta_info;
  2222. #endif
  2223. };
  2224. static
  2225. struct bfgtls_data *get_bfgtls()
  2226. {
  2227. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  2228. if (bfgtls)
  2229. return bfgtls;
  2230. void *p;
  2231. bfgtls = malloc(sizeof(*bfgtls));
  2232. if (!bfgtls)
  2233. quithere(1, "malloc bfgtls failed");
  2234. p = malloc(64);
  2235. if (!p)
  2236. quithere(1, "malloc bfg_strerror_result failed");
  2237. *bfgtls = (struct bfgtls_data){
  2238. .bfg_strerror_resultsz = 64,
  2239. .bfg_strerror_result = p,
  2240. };
  2241. if (pthread_setspecific(key_bfgtls, bfgtls))
  2242. quithere(1, "pthread_setspecific failed");
  2243. return bfgtls;
  2244. }
  2245. static
  2246. void bfgtls_free(void * const p)
  2247. {
  2248. struct bfgtls_data * const bfgtls = p;
  2249. free(bfgtls->bfg_strerror_result);
  2250. #ifdef WIN32
  2251. if (bfgtls->bfg_strerror_socketresult)
  2252. LocalFree(bfgtls->bfg_strerror_socketresult);
  2253. #endif
  2254. free(bfgtls);
  2255. }
  2256. #ifdef NEED_BFG_LOWL_VCOM
  2257. struct detectone_meta_info_t *_detectone_meta_info()
  2258. {
  2259. return &get_bfgtls()->__detectone_meta_info;
  2260. }
  2261. #endif
  2262. void bfg_init_threadlocal()
  2263. {
  2264. if (pthread_key_create(&key_bfgtls, bfgtls_free))
  2265. quithere(1, "pthread_key_create failed");
  2266. }
  2267. static
  2268. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  2269. {
  2270. if (minimum <= *bufszp)
  2271. return false;
  2272. while (minimum > *bufszp)
  2273. *bufszp = 2;
  2274. *bufp = realloc(*bufp, *bufszp);
  2275. if (unlikely(!*bufp))
  2276. quithere(1, "realloc failed");
  2277. return true;
  2278. }
  2279. static
  2280. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  2281. {
  2282. if (!src)
  2283. return NULL;
  2284. const size_t srcsz = strlen(src) + 1;
  2285. bfg_grow_buffer(bufp, bufszp, srcsz);
  2286. memcpy(*bufp, src, srcsz);
  2287. return *bufp;
  2288. }
  2289. // Guaranteed to always return some string (or quit)
  2290. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  2291. {
  2292. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2293. struct bfgtls_data *bfgtls = get_bfgtls();
  2294. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  2295. char ** const bufp = &bfgtls->bfg_strerror_result;
  2296. const char *have = NULL;
  2297. switch (type) {
  2298. case BST_LIBUSB:
  2299. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  2300. #ifdef HAVE_LIBUSB
  2301. # if HAVE_DECL_LIBUSB_ERROR_NAME
  2302. // libusb makes no guarantees for thread-safety or persistence
  2303. mutex_lock(&mutex);
  2304. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  2305. mutex_unlock(&mutex);
  2306. # endif
  2307. #endif
  2308. break;
  2309. case BST_SOCKET:
  2310. case BST_SYSTEM:
  2311. {
  2312. #ifdef WIN32
  2313. // Windows has a different namespace for system and socket errors
  2314. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  2315. if (*msg)
  2316. LocalFree(*msg);
  2317. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  2318. {
  2319. LPSTR msgp = *msg;
  2320. size_t n = strlen(msgp);
  2321. while (isCspace(msgp[--n]))
  2322. msgp[n] = '\0';
  2323. return *msg;
  2324. }
  2325. *msg = NULL;
  2326. break;
  2327. #endif
  2328. }
  2329. // Fallthru on non-WIN32
  2330. case BST_ERRNO:
  2331. {
  2332. #ifdef __STRERROR_S_WORKS
  2333. // FIXME: Not sure how to get this on MingW64
  2334. retry:
  2335. if (likely(!strerror_s(*bufp, *bufszp, e)))
  2336. {
  2337. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  2338. goto retry;
  2339. return *bufp;
  2340. }
  2341. // TODO: XSI strerror_r
  2342. // TODO: GNU strerror_r
  2343. #else
  2344. mutex_lock(&mutex);
  2345. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  2346. mutex_unlock(&mutex);
  2347. #endif
  2348. }
  2349. }
  2350. if (have)
  2351. return *bufp;
  2352. // Failback: Stringify the number
  2353. static const char fmt[] = "%s error #%d", *typestr;
  2354. switch (type) {
  2355. case BST_ERRNO:
  2356. typestr = "System";
  2357. break;
  2358. case BST_SOCKET:
  2359. typestr = "Socket";
  2360. break;
  2361. case BST_LIBUSB:
  2362. typestr = "libusb";
  2363. break;
  2364. default:
  2365. typestr = "Unexpected";
  2366. }
  2367. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  2368. bfg_grow_buffer(bufp, bufszp, sz);
  2369. sprintf(*bufp, fmt, typestr, e);
  2370. return *bufp;
  2371. }
  2372. void notifier_init(notifier_t pipefd)
  2373. {
  2374. #ifdef WIN32
  2375. #define WindowsErrorStr(e) bfg_strerror(e, BST_SOCKET)
  2376. SOCKET listener, connecter, acceptor;
  2377. listener = socket(AF_INET, SOCK_STREAM, 0);
  2378. if (listener == INVALID_SOCKET)
  2379. quit(1, "Failed to create listener socket"IN_FMT_FFL": %s",
  2380. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2381. connecter = socket(AF_INET, SOCK_STREAM, 0);
  2382. if (connecter == INVALID_SOCKET)
  2383. quit(1, "Failed to create connect socket"IN_FMT_FFL": %s",
  2384. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2385. struct sockaddr_in inaddr = {
  2386. .sin_family = AF_INET,
  2387. .sin_addr = {
  2388. .s_addr = htonl(INADDR_LOOPBACK),
  2389. },
  2390. .sin_port = 0,
  2391. };
  2392. {
  2393. static const int reuse = 1;
  2394. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
  2395. }
  2396. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  2397. quit(1, "Failed to bind listener socket"IN_FMT_FFL": %s",
  2398. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2399. socklen_t inaddr_sz = sizeof(inaddr);
  2400. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  2401. quit(1, "Failed to getsockname"IN_FMT_FFL": %s",
  2402. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2403. if (listen(listener, 1) == SOCKET_ERROR)
  2404. quit(1, "Failed to listen"IN_FMT_FFL": %s",
  2405. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2406. inaddr.sin_family = AF_INET;
  2407. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2408. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  2409. quit(1, "Failed to connect"IN_FMT_FFL": %s",
  2410. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2411. acceptor = accept(listener, NULL, NULL);
  2412. if (acceptor == INVALID_SOCKET)
  2413. quit(1, "Failed to accept"IN_FMT_FFL": %s",
  2414. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2415. closesocket(listener);
  2416. pipefd[0] = connecter;
  2417. pipefd[1] = acceptor;
  2418. #else
  2419. if (pipe(pipefd))
  2420. quithere(1, "Failed to create pipe");
  2421. #endif
  2422. }
  2423. void notifier_wake(notifier_t fd)
  2424. {
  2425. if (fd[1] == INVSOCK)
  2426. return;
  2427. if (1 !=
  2428. #ifdef WIN32
  2429. send(fd[1], "\0", 1, 0)
  2430. #else
  2431. write(fd[1], "\0", 1)
  2432. #endif
  2433. )
  2434. applog(LOG_WARNING, "Error trying to wake notifier");
  2435. }
  2436. void notifier_read(notifier_t fd)
  2437. {
  2438. char buf[0x10];
  2439. #ifdef WIN32
  2440. IGNORE_RETURN_VALUE(recv(fd[0], buf, sizeof(buf), 0));
  2441. #else
  2442. IGNORE_RETURN_VALUE(read(fd[0], buf, sizeof(buf)));
  2443. #endif
  2444. }
  2445. void notifier_init_invalid(notifier_t fd)
  2446. {
  2447. fd[0] = fd[1] = INVSOCK;
  2448. }
  2449. void notifier_destroy(notifier_t fd)
  2450. {
  2451. #ifdef WIN32
  2452. closesocket(fd[0]);
  2453. closesocket(fd[1]);
  2454. #else
  2455. close(fd[0]);
  2456. close(fd[1]);
  2457. #endif
  2458. fd[0] = fd[1] = INVSOCK;
  2459. }
  2460. void _bytes_alloc_failure(size_t sz)
  2461. {
  2462. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  2463. }
  2464. void *cmd_thread(void *cmdp)
  2465. {
  2466. const char *cmd = cmdp;
  2467. applog(LOG_DEBUG, "Executing command: %s", cmd);
  2468. int rc = system(cmd);
  2469. if (rc)
  2470. applog(LOG_WARNING, "Command returned %d exit code: %s", rc, cmd);
  2471. return NULL;
  2472. }
  2473. void run_cmd(const char *cmd)
  2474. {
  2475. if (!cmd)
  2476. return;
  2477. pthread_t pth;
  2478. pthread_create(&pth, NULL, cmd_thread, (void*)cmd);
  2479. }
  2480. static uint8_t _crc8ccitt_table[0x100];
  2481. void bfg_init_checksums(void)
  2482. {
  2483. for (int i = 0; i < 0x100; ++i)
  2484. {
  2485. uint8_t crc = i;
  2486. for (int j = 0; j < 8; ++j)
  2487. crc = (crc << 1) ^ ((crc & 0x80) ? 7 : 0);
  2488. _crc8ccitt_table[i] = crc & 0xff;
  2489. }
  2490. }
  2491. uint8_t crc8ccitt(const void * const buf, const size_t buflen)
  2492. {
  2493. const uint8_t *p = buf;
  2494. uint8_t crc = 0xff;
  2495. for (int i = 0; i < buflen; ++i)
  2496. crc = _crc8ccitt_table[crc ^ *p++];
  2497. return crc;
  2498. }