util.c 67 KB

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