util.c 65 KB

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