util.c 67 KB

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