util.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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. #ifdef WIN32
  15. #define FD_SETSIZE 4096
  16. #endif
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <ctype.h>
  20. #include <stdarg.h>
  21. #include <string.h>
  22. #include <pthread.h>
  23. #include <jansson.h>
  24. #include <curl/curl.h>
  25. #include <time.h>
  26. #include <errno.h>
  27. #include <unistd.h>
  28. #include <sys/types.h>
  29. #ifdef HAVE_SYS_PRCTL_H
  30. # include <sys/prctl.h>
  31. #endif
  32. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  33. # include <pthread_np.h>
  34. #endif
  35. #ifndef WIN32
  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 <winsock2.h>
  45. # include <mstcpip.h>
  46. # include <ws2tcpip.h>
  47. #endif
  48. #include "miner.h"
  49. #include "elist.h"
  50. #include "compat.h"
  51. #include "util.h"
  52. #define DEFAULT_SOCKWAIT 60
  53. bool successful_connect = false;
  54. struct timeval nettime;
  55. struct data_buffer {
  56. void *buf;
  57. size_t len;
  58. curl_socket_t *idlemarker;
  59. };
  60. struct upload_buffer {
  61. const void *buf;
  62. size_t len;
  63. };
  64. struct header_info {
  65. char *lp_path;
  66. int rolltime;
  67. char *reason;
  68. char *stratum_url;
  69. bool hadrolltime;
  70. bool canroll;
  71. bool hadexpire;
  72. };
  73. struct tq_ent {
  74. void *data;
  75. struct list_head q_node;
  76. };
  77. static void databuf_free(struct data_buffer *db)
  78. {
  79. if (!db)
  80. return;
  81. free(db->buf);
  82. #ifdef DEBUG_DATABUF
  83. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  84. #endif
  85. memset(db, 0, sizeof(*db));
  86. }
  87. // aka data_buffer_write
  88. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  89. void *user_data)
  90. {
  91. struct data_buffer *db = user_data;
  92. size_t oldlen, newlen;
  93. oldlen = db->len;
  94. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  95. return 0;
  96. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  97. nmemb = (SIZE_MAX - oldlen) / size;
  98. size_t len = size * nmemb;
  99. void *newmem;
  100. static const unsigned char zero = 0;
  101. if (db->idlemarker) {
  102. const unsigned char *cptr = ptr;
  103. for (size_t i = 0; i < len; ++i)
  104. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  105. *db->idlemarker = CURL_SOCKET_BAD;
  106. db->idlemarker = NULL;
  107. break;
  108. }
  109. }
  110. newlen = oldlen + len;
  111. newmem = realloc(db->buf, newlen + 1);
  112. #ifdef DEBUG_DATABUF
  113. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  114. #endif
  115. if (!newmem)
  116. return 0;
  117. db->buf = newmem;
  118. db->len = newlen;
  119. memcpy(db->buf + oldlen, ptr, len);
  120. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  121. return nmemb;
  122. }
  123. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  124. void *user_data)
  125. {
  126. struct upload_buffer *ub = user_data;
  127. unsigned int len = size * nmemb;
  128. if (len > ub->len)
  129. len = ub->len;
  130. if (len) {
  131. memcpy(ptr, ub->buf, len);
  132. ub->buf += len;
  133. ub->len -= len;
  134. }
  135. return len;
  136. }
  137. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  138. {
  139. struct header_info *hi = user_data;
  140. size_t remlen, slen, ptrlen = size * nmemb;
  141. char *rem, *val = NULL, *key = NULL;
  142. void *tmp;
  143. val = calloc(1, ptrlen);
  144. key = calloc(1, ptrlen);
  145. if (!key || !val)
  146. goto out;
  147. tmp = memchr(ptr, ':', ptrlen);
  148. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  149. goto out;
  150. slen = tmp - ptr;
  151. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  152. goto out;
  153. memcpy(key, ptr, slen); /* store & nul term key */
  154. key[slen] = 0;
  155. rem = ptr + slen + 1; /* trim value's leading whitespace */
  156. remlen = ptrlen - slen - 1;
  157. while ((remlen > 0) && (isspace(*rem))) {
  158. remlen--;
  159. rem++;
  160. }
  161. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  162. val[remlen] = 0;
  163. while ((*val) && (isspace(val[strlen(val) - 1])))
  164. val[strlen(val) - 1] = 0;
  165. if (!*val) /* skip blank value */
  166. goto out;
  167. if (opt_protocol)
  168. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  169. if (!strcasecmp("X-Roll-Ntime", key)) {
  170. hi->hadrolltime = true;
  171. if (!strncasecmp("N", val, 1))
  172. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  173. else {
  174. hi->canroll = true;
  175. /* Check to see if expire= is supported and if not, set
  176. * the rolltime to the default scantime */
  177. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  178. sscanf(val + 7, "%d", &hi->rolltime);
  179. hi->hadexpire = true;
  180. } else
  181. hi->rolltime = opt_scantime;
  182. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  183. }
  184. }
  185. if (!strcasecmp("X-Long-Polling", key)) {
  186. hi->lp_path = val; /* steal memory reference */
  187. val = NULL;
  188. }
  189. if (!strcasecmp("X-Reject-Reason", key)) {
  190. hi->reason = val; /* steal memory reference */
  191. val = NULL;
  192. }
  193. if (!strcasecmp("X-Stratum", key)) {
  194. hi->stratum_url = val;
  195. val = NULL;
  196. }
  197. out:
  198. free(key);
  199. free(val);
  200. return ptrlen;
  201. }
  202. static int keep_sockalive(SOCKETTYPE fd)
  203. {
  204. const int tcp_keepidle = 60;
  205. const int tcp_keepintvl = 60;
  206. const int keepalive = 1;
  207. int ret = 0;
  208. #ifndef WIN32
  209. const int tcp_keepcnt = 5;
  210. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  211. ret = 1;
  212. # ifdef __linux
  213. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  214. ret = 1;
  215. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  216. ret = 1;
  217. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  218. ret = 1;
  219. # endif /* __linux */
  220. # ifdef __APPLE_CC__
  221. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  222. ret = 1;
  223. # endif /* __APPLE_CC__ */
  224. #else /* WIN32 */
  225. const int zero = 0;
  226. struct tcp_keepalive vals;
  227. vals.onoff = 1;
  228. vals.keepalivetime = tcp_keepidle * 1000;
  229. vals.keepaliveinterval = tcp_keepintvl * 1000;
  230. DWORD outputBytes;
  231. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&keepalive, sizeof(keepalive))))
  232. ret = 1;
  233. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  234. ret = 1;
  235. /* Windows happily submits indefinitely to the send buffer blissfully
  236. * unaware nothing is getting there without gracefully failing unless
  237. * we disable the send buffer */
  238. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  239. ret = 1;
  240. #endif /* WIN32 */
  241. return ret;
  242. }
  243. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  244. curlsocktype __maybe_unused purpose)
  245. {
  246. return keep_sockalive(fd);
  247. }
  248. static void last_nettime(struct timeval *last)
  249. {
  250. rd_lock(&netacc_lock);
  251. last->tv_sec = nettime.tv_sec;
  252. last->tv_usec = nettime.tv_usec;
  253. rd_unlock(&netacc_lock);
  254. }
  255. static void set_nettime(void)
  256. {
  257. wr_lock(&netacc_lock);
  258. gettimeofday(&nettime, NULL);
  259. wr_unlock(&netacc_lock);
  260. }
  261. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  262. char *data, size_t size,
  263. void *userdata)
  264. {
  265. struct pool *pool = (struct pool *)userdata;
  266. switch(type) {
  267. case CURLINFO_HEADER_IN:
  268. case CURLINFO_DATA_IN:
  269. case CURLINFO_SSL_DATA_IN:
  270. pool->cgminer_pool_stats.bytes_received += size;
  271. total_bytes_xfer += size;
  272. pool->cgminer_pool_stats.net_bytes_received += size;
  273. break;
  274. case CURLINFO_HEADER_OUT:
  275. case CURLINFO_DATA_OUT:
  276. case CURLINFO_SSL_DATA_OUT:
  277. pool->cgminer_pool_stats.bytes_sent += size;
  278. total_bytes_xfer += size;
  279. pool->cgminer_pool_stats.net_bytes_sent += size;
  280. break;
  281. case CURLINFO_TEXT:
  282. {
  283. if (!opt_protocol)
  284. break;
  285. // data is not null-terminated, so we need to copy and terminate it for applog
  286. char datacp[size + 1];
  287. memcpy(datacp, data, size);
  288. while (likely(size) && unlikely(isspace(datacp[size-1])))
  289. --size;
  290. if (unlikely(!size))
  291. break;
  292. datacp[size] = '\0';
  293. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  294. break;
  295. }
  296. default:
  297. break;
  298. }
  299. return 0;
  300. }
  301. struct json_rpc_call_state {
  302. struct data_buffer all_data;
  303. struct header_info hi;
  304. void *priv;
  305. char curl_err_str[CURL_ERROR_SIZE];
  306. struct curl_slist *headers;
  307. struct upload_buffer upload_data;
  308. struct pool *pool;
  309. };
  310. void json_rpc_call_async(CURL *curl, const char *url,
  311. const char *userpass, const char *rpc_req,
  312. bool longpoll,
  313. struct pool *pool, bool share,
  314. void *priv)
  315. {
  316. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  317. *state = (struct json_rpc_call_state){
  318. .priv = priv,
  319. .pool = pool,
  320. };
  321. long timeout = longpoll ? (60 * 60) : 60;
  322. char len_hdr[64], user_agent_hdr[128];
  323. struct curl_slist *headers = NULL;
  324. if (longpoll)
  325. state->all_data.idlemarker = &pool->lp_socket;
  326. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  327. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  328. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  329. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  330. * to enable it */
  331. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  332. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  333. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  334. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  335. curl_easy_setopt(curl, CURLOPT_URL, url);
  336. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  337. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  338. /* Shares are staggered already and delays in submission can be costly
  339. * so do not delay them */
  340. if (!opt_delaynet || share)
  341. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  342. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  343. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  344. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  345. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  346. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  347. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  348. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  349. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  350. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  351. if (pool->rpc_proxy) {
  352. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  353. } else if (opt_socks_proxy) {
  354. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  355. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  356. }
  357. if (userpass) {
  358. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  359. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  360. }
  361. if (longpoll)
  362. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  363. curl_easy_setopt(curl, CURLOPT_POST, 1);
  364. if (opt_protocol)
  365. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  366. state->upload_data.buf = rpc_req;
  367. state->upload_data.len = strlen(rpc_req);
  368. sprintf(len_hdr, "Content-Length: %lu",
  369. (unsigned long) state->upload_data.len);
  370. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  371. headers = curl_slist_append(headers,
  372. "Content-type: application/json");
  373. headers = curl_slist_append(headers,
  374. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  375. if (longpoll)
  376. headers = curl_slist_append(headers,
  377. "X-Minimum-Wait: 0");
  378. if (likely(global_hashrate)) {
  379. char ghashrate[255];
  380. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  381. headers = curl_slist_append(headers, ghashrate);
  382. }
  383. headers = curl_slist_append(headers, len_hdr);
  384. headers = curl_slist_append(headers, user_agent_hdr);
  385. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  386. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  387. state->headers = headers;
  388. if (opt_delaynet) {
  389. /* Don't delay share submission, but still track the nettime */
  390. if (!share) {
  391. long long now_msecs, last_msecs;
  392. struct timeval now, last;
  393. gettimeofday(&now, NULL);
  394. last_nettime(&last);
  395. now_msecs = (long long)now.tv_sec * 1000;
  396. now_msecs += now.tv_usec / 1000;
  397. last_msecs = (long long)last.tv_sec * 1000;
  398. last_msecs += last.tv_usec / 1000;
  399. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  400. struct timespec rgtp;
  401. rgtp.tv_sec = 0;
  402. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  403. nanosleep(&rgtp, NULL);
  404. }
  405. }
  406. set_nettime();
  407. }
  408. }
  409. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  410. {
  411. struct json_rpc_call_state *state;
  412. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
  413. applog(LOG_ERR, "Failed to get private curl data");
  414. if (out_priv)
  415. *(void**)out_priv = NULL;
  416. goto err_out;
  417. }
  418. if (out_priv)
  419. *(void**)out_priv = state->priv;
  420. json_t *val, *err_val, *res_val;
  421. json_error_t err;
  422. struct pool *pool = state->pool;
  423. bool probing = probe && !pool->probed;
  424. if (rc) {
  425. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  426. goto err_out;
  427. }
  428. if (!state->all_data.buf) {
  429. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  430. goto err_out;
  431. }
  432. pool->cgminer_pool_stats.times_sent++;
  433. pool->cgminer_pool_stats.times_received++;
  434. if (probing) {
  435. pool->probed = true;
  436. /* If X-Long-Polling was found, activate long polling */
  437. if (state->hi.lp_path) {
  438. if (pool->hdr_path != NULL)
  439. free(pool->hdr_path);
  440. pool->hdr_path = state->hi.lp_path;
  441. } else
  442. pool->hdr_path = NULL;
  443. if (state->hi.stratum_url) {
  444. pool->stratum_url = state->hi.stratum_url;
  445. state->hi.stratum_url = NULL;
  446. }
  447. } else {
  448. if (state->hi.lp_path) {
  449. free(state->hi.lp_path);
  450. state->hi.lp_path = NULL;
  451. }
  452. if (state->hi.stratum_url) {
  453. free(state->hi.stratum_url);
  454. state->hi.stratum_url = NULL;
  455. }
  456. }
  457. if (rolltime)
  458. *rolltime = state->hi.rolltime;
  459. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  460. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  461. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  462. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  463. val = JSON_LOADS(state->all_data.buf, &err);
  464. if (!val) {
  465. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  466. if (opt_protocol)
  467. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  468. goto err_out;
  469. }
  470. if (opt_protocol) {
  471. char *s = json_dumps(val, JSON_INDENT(3));
  472. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  473. free(s);
  474. }
  475. /* JSON-RPC valid response returns a non-null 'result',
  476. * and a null 'error'.
  477. */
  478. res_val = json_object_get(val, "result");
  479. err_val = json_object_get(val, "error");
  480. if (!res_val ||(err_val && !json_is_null(err_val))) {
  481. char *s;
  482. if (err_val)
  483. s = json_dumps(err_val, JSON_INDENT(3));
  484. else
  485. s = strdup("(unknown reason)");
  486. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  487. free(s);
  488. json_decref(val);
  489. goto err_out;
  490. }
  491. if (state->hi.reason) {
  492. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  493. free(state->hi.reason);
  494. state->hi.reason = NULL;
  495. }
  496. successful_connect = true;
  497. databuf_free(&state->all_data);
  498. curl_slist_free_all(state->headers);
  499. curl_easy_reset(curl);
  500. free(state);
  501. return val;
  502. err_out:
  503. databuf_free(&state->all_data);
  504. curl_slist_free_all(state->headers);
  505. curl_easy_reset(curl);
  506. if (!successful_connect)
  507. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  508. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  509. free(state);
  510. return NULL;
  511. }
  512. json_t *json_rpc_call(CURL *curl, const char *url,
  513. const char *userpass, const char *rpc_req,
  514. bool probe, bool longpoll, int *rolltime,
  515. struct pool *pool, bool share)
  516. {
  517. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  518. int rc = curl_easy_perform(curl);
  519. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  520. }
  521. bool our_curl_supports_proxy_uris()
  522. {
  523. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  524. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  525. }
  526. /* Returns a malloced array string of a binary value of arbitrary length. The
  527. * array is rounded up to a 4 byte size to appease architectures that need
  528. * aligned array sizes */
  529. char *bin2hex(const unsigned char *p, size_t len)
  530. {
  531. unsigned int i;
  532. ssize_t slen;
  533. char *s;
  534. slen = len * 2 + 1;
  535. if (slen % 4)
  536. slen += 4 - (slen % 4);
  537. s = calloc(slen, 1);
  538. if (unlikely(!s))
  539. quit(1, "Failed to calloc in bin2hex");
  540. for (i = 0; i < len; i++)
  541. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  542. return s;
  543. }
  544. /* Does the reverse of bin2hex but does not allocate any ram */
  545. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  546. {
  547. bool ret = false;
  548. while (*hexstr && len) {
  549. char hex_byte[4];
  550. unsigned int v;
  551. if (unlikely(!hexstr[1])) {
  552. applog(LOG_ERR, "hex2bin str truncated");
  553. return ret;
  554. }
  555. memset(hex_byte, 0, 4);
  556. hex_byte[0] = hexstr[0];
  557. hex_byte[1] = hexstr[1];
  558. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  559. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  560. return ret;
  561. }
  562. *p = (unsigned char) v;
  563. p++;
  564. hexstr += 2;
  565. len--;
  566. }
  567. if (likely(len == 0 && *hexstr == 0))
  568. ret = true;
  569. return ret;
  570. }
  571. void hash_data(unsigned char *out_hash, const unsigned char *data)
  572. {
  573. unsigned char blkheader[80];
  574. // 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
  575. swap32yes(blkheader, data, 80 / 4);
  576. // double-SHA256 to get the block hash
  577. gen_hash(blkheader, out_hash, 80);
  578. }
  579. void real_block_target(unsigned char *target, const unsigned char *data)
  580. {
  581. uint8_t targetshift;
  582. if (unlikely(data[72] < 3 || data[72] > 0x20))
  583. {
  584. // Invalid (out of bounds) target
  585. memset(target, 0xff, 32);
  586. return;
  587. }
  588. targetshift = data[72] - 3;
  589. memset(target, 0, targetshift);
  590. target[targetshift++] = data[75];
  591. target[targetshift++] = data[74];
  592. target[targetshift++] = data[73];
  593. memset(&target[targetshift], 0, 0x20 - targetshift);
  594. }
  595. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  596. {
  597. const uint32_t *h32 = (uint32_t*)&hash[0];
  598. const uint32_t *t32 = (uint32_t*)&target[0];
  599. for (int i = 7; i >= 0; --i) {
  600. uint32_t h32i = le32toh(h32[i]);
  601. uint32_t t32i = le32toh(t32[i]);
  602. if (h32i > t32i)
  603. return false;
  604. if (h32i < t32i)
  605. return true;
  606. }
  607. return true;
  608. }
  609. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  610. {
  611. bool rc;
  612. rc = hash_target_check(hash, target);
  613. if (opt_debug) {
  614. unsigned char hash_swap[32], target_swap[32];
  615. char *hash_str, *target_str;
  616. for (int i = 0; i < 32; ++i) {
  617. hash_swap[i] = hash[31-i];
  618. target_swap[i] = target[31-i];
  619. }
  620. hash_str = bin2hex(hash_swap, 32);
  621. target_str = bin2hex(target_swap, 32);
  622. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  623. hash_str,
  624. target_str,
  625. rc ? "YES (hash <= target)" :
  626. "no (false positive; hash > target)");
  627. free(hash_str);
  628. free(target_str);
  629. }
  630. return rc;
  631. }
  632. // This operates on a native-endian SHA256 state
  633. // In other words, on little endian platforms, every 4 bytes are in reverse order
  634. bool fulltest(const unsigned char *hash, const unsigned char *target)
  635. {
  636. unsigned char hash2[32];
  637. swap32tobe(hash2, hash, 32 / 4);
  638. return hash_target_check_v(hash2, target);
  639. }
  640. struct thread_q *tq_new(void)
  641. {
  642. struct thread_q *tq;
  643. tq = calloc(1, sizeof(*tq));
  644. if (!tq)
  645. return NULL;
  646. INIT_LIST_HEAD(&tq->q);
  647. pthread_mutex_init(&tq->mutex, NULL);
  648. pthread_cond_init(&tq->cond, NULL);
  649. return tq;
  650. }
  651. void tq_free(struct thread_q *tq)
  652. {
  653. struct tq_ent *ent, *iter;
  654. if (!tq)
  655. return;
  656. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  657. list_del(&ent->q_node);
  658. free(ent);
  659. }
  660. pthread_cond_destroy(&tq->cond);
  661. pthread_mutex_destroy(&tq->mutex);
  662. memset(tq, 0, sizeof(*tq)); /* poison */
  663. free(tq);
  664. }
  665. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  666. {
  667. mutex_lock(&tq->mutex);
  668. tq->frozen = frozen;
  669. pthread_cond_signal(&tq->cond);
  670. mutex_unlock(&tq->mutex);
  671. }
  672. void tq_freeze(struct thread_q *tq)
  673. {
  674. tq_freezethaw(tq, true);
  675. }
  676. void tq_thaw(struct thread_q *tq)
  677. {
  678. tq_freezethaw(tq, false);
  679. }
  680. bool tq_push(struct thread_q *tq, void *data)
  681. {
  682. struct tq_ent *ent;
  683. bool rc = true;
  684. ent = calloc(1, sizeof(*ent));
  685. if (!ent)
  686. return false;
  687. ent->data = data;
  688. INIT_LIST_HEAD(&ent->q_node);
  689. mutex_lock(&tq->mutex);
  690. if (!tq->frozen) {
  691. list_add_tail(&ent->q_node, &tq->q);
  692. } else {
  693. free(ent);
  694. rc = false;
  695. }
  696. pthread_cond_signal(&tq->cond);
  697. mutex_unlock(&tq->mutex);
  698. return rc;
  699. }
  700. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  701. {
  702. struct tq_ent *ent;
  703. void *rval = NULL;
  704. int rc;
  705. mutex_lock(&tq->mutex);
  706. if (!list_empty(&tq->q))
  707. goto pop;
  708. if (abstime)
  709. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  710. else
  711. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  712. if (rc)
  713. goto out;
  714. if (list_empty(&tq->q))
  715. goto out;
  716. pop:
  717. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  718. rval = ent->data;
  719. list_del(&ent->q_node);
  720. free(ent);
  721. out:
  722. mutex_unlock(&tq->mutex);
  723. return rval;
  724. }
  725. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  726. {
  727. return pthread_create(&thr->pth, attr, start, arg);
  728. }
  729. void thr_info_freeze(struct thr_info *thr)
  730. {
  731. struct tq_ent *ent, *iter;
  732. struct thread_q *tq;
  733. if (!thr)
  734. return;
  735. tq = thr->q;
  736. if (!tq)
  737. return;
  738. mutex_lock(&tq->mutex);
  739. tq->frozen = true;
  740. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  741. list_del(&ent->q_node);
  742. free(ent);
  743. }
  744. mutex_unlock(&tq->mutex);
  745. }
  746. void thr_info_cancel(struct thr_info *thr)
  747. {
  748. if (!thr)
  749. return;
  750. if (PTH(thr) != 0L) {
  751. pthread_cancel(thr->pth);
  752. PTH(thr) = 0L;
  753. }
  754. }
  755. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  756. * on SMP machines */
  757. void nmsleep(unsigned int msecs)
  758. {
  759. struct timespec twait, tleft;
  760. int ret;
  761. ldiv_t d;
  762. d = ldiv(msecs, 1000);
  763. tleft.tv_sec = d.quot;
  764. tleft.tv_nsec = d.rem * 1000000;
  765. do {
  766. twait.tv_sec = tleft.tv_sec;
  767. twait.tv_nsec = tleft.tv_nsec;
  768. ret = nanosleep(&twait, &tleft);
  769. } while (ret == -1 && errno == EINTR);
  770. }
  771. /* Returns the microseconds difference between end and start times as a double */
  772. double us_tdiff(struct timeval *end, struct timeval *start)
  773. {
  774. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  775. }
  776. /* Returns the seconds difference between end and start times as a double */
  777. double tdiff(struct timeval *end, struct timeval *start)
  778. {
  779. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  780. }
  781. bool extract_sockaddr(struct pool *pool, char *url)
  782. {
  783. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  784. char url_address[256], port[6];
  785. int url_len, port_len = 0;
  786. url_begin = strstr(url, "//");
  787. if (!url_begin)
  788. url_begin = url;
  789. else
  790. url_begin += 2;
  791. /* Look for numeric ipv6 entries */
  792. ipv6_begin = strstr(url_begin, "[");
  793. ipv6_end = strstr(url_begin, "]");
  794. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  795. url_end = strstr(ipv6_end, ":");
  796. else
  797. url_end = strstr(url_begin, ":");
  798. if (url_end) {
  799. url_len = url_end - url_begin;
  800. port_len = strlen(url_begin) - url_len - 1;
  801. if (port_len < 1)
  802. return false;
  803. port_start = url_end + 1;
  804. } else
  805. url_len = strlen(url_begin);
  806. if (url_len < 1)
  807. return false;
  808. sprintf(url_address, "%.*s", url_len, url_begin);
  809. if (port_len)
  810. snprintf(port, 6, "%.*s", port_len, port_start);
  811. else
  812. strcpy(port, "80");
  813. free(pool->stratum_port);
  814. pool->stratum_port = strdup(port);
  815. free(pool->sockaddr_url);
  816. pool->sockaddr_url = strdup(url_address);
  817. return true;
  818. }
  819. enum send_ret {
  820. SEND_OK,
  821. SEND_SELECTFAIL,
  822. SEND_SENDFAIL,
  823. SEND_INACTIVE
  824. };
  825. /* Send a single command across a socket, appending \n to it. This should all
  826. * be done under stratum lock except when first establishing the socket */
  827. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  828. {
  829. SOCKETTYPE sock = pool->sock;
  830. ssize_t ssent = 0;
  831. strcat(s, "\n");
  832. len++;
  833. while (len > 0 ) {
  834. struct timeval timeout = {0, 0};
  835. ssize_t sent;
  836. fd_set wd;
  837. FD_ZERO(&wd);
  838. FD_SET(sock, &wd);
  839. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  840. return SEND_SELECTFAIL;
  841. sent = send(pool->sock, s + ssent, len, 0);
  842. if (sent < 0) {
  843. if (!sock_blocks())
  844. return SEND_SENDFAIL;
  845. sent = 0;
  846. }
  847. ssent += sent;
  848. len -= sent;
  849. }
  850. pool->cgminer_pool_stats.times_sent++;
  851. pool->cgminer_pool_stats.bytes_sent += ssent;
  852. total_bytes_xfer += ssent;
  853. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  854. return SEND_OK;
  855. }
  856. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  857. {
  858. enum send_ret ret = SEND_INACTIVE;
  859. if (opt_protocol)
  860. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  861. mutex_lock(&pool->stratum_lock);
  862. if (pool->stratum_active || force)
  863. ret = __stratum_send(pool, s, len);
  864. mutex_unlock(&pool->stratum_lock);
  865. /* This is to avoid doing applog under stratum_lock */
  866. switch (ret) {
  867. default:
  868. case SEND_OK:
  869. break;
  870. case SEND_SELECTFAIL:
  871. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  872. break;
  873. case SEND_SENDFAIL:
  874. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  875. break;
  876. case SEND_INACTIVE:
  877. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  878. break;
  879. }
  880. return (ret == SEND_OK);
  881. }
  882. static bool socket_full(struct pool *pool, int wait)
  883. {
  884. SOCKETTYPE sock = pool->sock;
  885. struct timeval timeout;
  886. fd_set rd;
  887. if (sock == INVSOCK)
  888. return true;
  889. if (unlikely(wait < 0))
  890. wait = 0;
  891. FD_ZERO(&rd);
  892. FD_SET(sock, &rd);
  893. timeout.tv_usec = 0;
  894. timeout.tv_sec = wait;
  895. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  896. return true;
  897. return false;
  898. }
  899. /* Check to see if Santa's been good to you */
  900. bool sock_full(struct pool *pool)
  901. {
  902. if (strlen(pool->sockbuf))
  903. return true;
  904. return (socket_full(pool, 0));
  905. }
  906. static void clear_sock(struct pool *pool)
  907. {
  908. ssize_t n;
  909. mutex_lock(&pool->stratum_lock);
  910. do
  911. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  912. while (n > 0);
  913. mutex_unlock(&pool->stratum_lock);
  914. strcpy(pool->sockbuf, "");
  915. }
  916. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  917. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  918. * and zeroing the new memory */
  919. static void recalloc_sock(struct pool *pool, size_t len)
  920. {
  921. size_t old, new;
  922. old = strlen(pool->sockbuf);
  923. new = old + len + 1;
  924. if (new < pool->sockbuf_size)
  925. return;
  926. new = new + (RBUFSIZE - (new % RBUFSIZE));
  927. applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  928. pool->sockbuf = realloc(pool->sockbuf, new);
  929. if (!pool->sockbuf)
  930. quit(1, "Failed to realloc pool sockbuf in recalloc_sock");
  931. memset(pool->sockbuf + old, 0, new - old);
  932. pool->sockbuf_size = new;
  933. }
  934. enum recv_ret {
  935. RECV_OK,
  936. RECV_CLOSED,
  937. RECV_RECVFAIL
  938. };
  939. /* Peeks at a socket to find the first end of line and then reads just that
  940. * from the socket and returns that as a malloced char */
  941. char *recv_line(struct pool *pool)
  942. {
  943. char *tok, *sret = NULL;
  944. ssize_t len, buflen;
  945. int waited = 0;
  946. if (!strstr(pool->sockbuf, "\n")) {
  947. enum recv_ret ret = RECV_OK;
  948. struct timeval rstart, now;
  949. int socket_recv_errno;
  950. gettimeofday(&rstart, NULL);
  951. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  952. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  953. goto out;
  954. }
  955. mutex_lock(&pool->stratum_lock);
  956. do {
  957. char s[RBUFSIZE];
  958. size_t slen;
  959. ssize_t n;
  960. memset(s, 0, RBUFSIZE);
  961. n = recv(pool->sock, s, RECVSIZE, 0);
  962. if (!n) {
  963. ret = RECV_CLOSED;
  964. break;
  965. }
  966. gettimeofday(&now, NULL);
  967. waited = tdiff(&now, &rstart);
  968. if (n < 0) {
  969. socket_recv_errno = errno;
  970. if (!sock_blocks()) {
  971. ret = RECV_RECVFAIL;
  972. break;
  973. }
  974. } else {
  975. slen = strlen(s);
  976. recalloc_sock(pool, slen);
  977. strcat(pool->sockbuf, s);
  978. }
  979. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  980. mutex_unlock(&pool->stratum_lock);
  981. switch (ret) {
  982. default:
  983. case RECV_OK:
  984. break;
  985. case RECV_CLOSED:
  986. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  987. goto out;
  988. case RECV_RECVFAIL:
  989. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %d", socket_recv_errno);
  990. goto out;
  991. }
  992. }
  993. buflen = strlen(pool->sockbuf);
  994. tok = strtok(pool->sockbuf, "\n");
  995. if (!tok) {
  996. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  997. goto out;
  998. }
  999. sret = strdup(tok);
  1000. len = strlen(sret);
  1001. /* Copy what's left in the buffer after the \n, including the
  1002. * terminating \0 */
  1003. if (buflen > len + 1)
  1004. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1005. else
  1006. strcpy(pool->sockbuf, "");
  1007. pool->cgminer_pool_stats.times_received++;
  1008. pool->cgminer_pool_stats.bytes_received += len;
  1009. total_bytes_xfer += len;
  1010. pool->cgminer_pool_stats.net_bytes_received += len;
  1011. out:
  1012. if (!sret)
  1013. clear_sock(pool);
  1014. else if (opt_protocol)
  1015. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1016. return sret;
  1017. }
  1018. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1019. * flag, but this is compatible with 2.0. */
  1020. char *json_dumps_ANY(json_t *json, size_t flags)
  1021. {
  1022. switch (json_typeof(json))
  1023. {
  1024. case JSON_ARRAY:
  1025. case JSON_OBJECT:
  1026. return json_dumps(json, flags);
  1027. default:
  1028. break;
  1029. }
  1030. char *rv;
  1031. #ifdef JSON_ENCODE_ANY
  1032. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1033. if (rv)
  1034. return rv;
  1035. #endif
  1036. json_t *tmp = json_array();
  1037. char *s;
  1038. int i;
  1039. size_t len;
  1040. if (!tmp)
  1041. quit(1, "json_dumps_ANY failed to allocate json array");
  1042. if (json_array_append(tmp, json))
  1043. quit(1, "json_dumps_ANY failed to append temporary array");
  1044. s = json_dumps(tmp, flags);
  1045. if (!s)
  1046. return NULL;
  1047. for (i = 0; s[i] != '['; ++i)
  1048. if (unlikely(!(s[i] && isspace(s[i]))))
  1049. quit(1, "json_dumps_ANY failed to find opening bracket in array dump");
  1050. len = strlen(&s[++i]) - 1;
  1051. if (unlikely(s[i+len] != ']'))
  1052. quit(1, "json_dumps_ANY failed to find closing bracket in array dump");
  1053. rv = malloc(len + 1);
  1054. memcpy(rv, &s[i], len);
  1055. rv[len] = '\0';
  1056. free(s);
  1057. json_decref(tmp);
  1058. return rv;
  1059. }
  1060. /* Extracts a string value from a json array with error checking. To be used
  1061. * when the value of the string returned is only examined and not to be stored.
  1062. * See json_array_string below */
  1063. static char *__json_array_string(json_t *val, unsigned int entry)
  1064. {
  1065. json_t *arr_entry;
  1066. if (json_is_null(val))
  1067. return NULL;
  1068. if (!json_is_array(val))
  1069. return NULL;
  1070. if (entry > json_array_size(val))
  1071. return NULL;
  1072. arr_entry = json_array_get(val, entry);
  1073. if (!json_is_string(arr_entry))
  1074. return NULL;
  1075. return (char *)json_string_value(arr_entry);
  1076. }
  1077. /* Creates a freshly malloced dup of __json_array_string */
  1078. static char *json_array_string(json_t *val, unsigned int entry)
  1079. {
  1080. char *buf = __json_array_string(val, entry);
  1081. if (buf)
  1082. return strdup(buf);
  1083. return NULL;
  1084. }
  1085. void stratum_probe_transparency(struct pool *pool)
  1086. {
  1087. // Request transaction data to discourage pools from doing anything shady
  1088. char s[1024];
  1089. int sLen;
  1090. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1091. pool->swork.job_id,
  1092. pool->swork.job_id);
  1093. stratum_send(pool, s, sLen);
  1094. if ((!pool->swork.opaque) && pool->swork.transparency_time == (time_t)-1)
  1095. pool->swork.transparency_time = time(NULL);
  1096. pool->swork.transparency_probed = true;
  1097. }
  1098. static bool parse_notify(struct pool *pool, json_t *val)
  1099. {
  1100. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1101. bool clean, ret = false;
  1102. int merkles, i;
  1103. json_t *arr;
  1104. arr = json_array_get(val, 4);
  1105. if (!arr || !json_is_array(arr))
  1106. goto out;
  1107. merkles = json_array_size(arr);
  1108. job_id = json_array_string(val, 0);
  1109. prev_hash = json_array_string(val, 1);
  1110. coinbase1 = json_array_string(val, 2);
  1111. coinbase2 = json_array_string(val, 3);
  1112. bbversion = json_array_string(val, 5);
  1113. nbit = json_array_string(val, 6);
  1114. ntime = json_array_string(val, 7);
  1115. clean = json_is_true(json_array_get(val, 8));
  1116. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1117. /* Annoying but we must not leak memory */
  1118. if (job_id)
  1119. free(job_id);
  1120. if (prev_hash)
  1121. free(prev_hash);
  1122. if (coinbase1)
  1123. free(coinbase1);
  1124. if (coinbase2)
  1125. free(coinbase2);
  1126. if (bbversion)
  1127. free(bbversion);
  1128. if (nbit)
  1129. free(nbit);
  1130. if (ntime)
  1131. free(ntime);
  1132. goto out;
  1133. }
  1134. mutex_lock(&pool->pool_lock);
  1135. free(pool->swork.job_id);
  1136. free(pool->swork.prev_hash);
  1137. free(pool->swork.coinbase1);
  1138. free(pool->swork.coinbase2);
  1139. free(pool->swork.bbversion);
  1140. free(pool->swork.nbit);
  1141. free(pool->swork.ntime);
  1142. pool->swork.job_id = job_id;
  1143. pool->swork.prev_hash = prev_hash;
  1144. pool->swork.coinbase1 = coinbase1;
  1145. pool->swork.cb1_len = strlen(coinbase1) / 2;
  1146. pool->swork.coinbase2 = coinbase2;
  1147. pool->swork.cb2_len = strlen(coinbase2) / 2;
  1148. pool->swork.bbversion = bbversion;
  1149. pool->swork.nbit = nbit;
  1150. pool->swork.ntime = ntime;
  1151. pool->submit_old = !clean;
  1152. pool->swork.clean = true;
  1153. pool->swork.cb_len = pool->swork.cb1_len + pool->n1_len + pool->n2size + pool->swork.cb2_len;
  1154. for (i = 0; i < pool->swork.merkles; i++)
  1155. free(pool->swork.merkle[i]);
  1156. if (merkles) {
  1157. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  1158. for (i = 0; i < merkles; i++)
  1159. pool->swork.merkle[i] = json_array_string(arr, i);
  1160. }
  1161. pool->swork.merkles = merkles;
  1162. if (clean)
  1163. pool->nonce2 = 0;
  1164. pool->swork.header_len = strlen(pool->swork.bbversion) +
  1165. strlen(pool->swork.prev_hash) +
  1166. strlen(pool->swork.ntime) +
  1167. strlen(pool->swork.nbit) +
  1168. /* merkle_hash */ 32 +
  1169. /* nonce */ 8 +
  1170. /* workpadding */ 96;
  1171. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1172. align_len(&pool->swork.header_len);
  1173. mutex_unlock(&pool->pool_lock);
  1174. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1175. pool->pool_no, job_id);
  1176. if (opt_protocol) {
  1177. applog(LOG_DEBUG, "job_id: %s", job_id);
  1178. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1179. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1180. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1181. for (i = 0; i < merkles; i++)
  1182. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  1183. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1184. applog(LOG_DEBUG, "nbit: %s", nbit);
  1185. applog(LOG_DEBUG, "ntime: %s", ntime);
  1186. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1187. }
  1188. /* A notify message is the closest stratum gets to a getwork */
  1189. pool->getwork_requested++;
  1190. total_getworks++;
  1191. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || pool->swork.transparency_time != (time_t)-1)
  1192. if (pool->stratum_auth)
  1193. stratum_probe_transparency(pool);
  1194. ret = true;
  1195. out:
  1196. return ret;
  1197. }
  1198. static bool parse_diff(struct pool *pool, json_t *val)
  1199. {
  1200. double diff;
  1201. diff = json_number_value(json_array_get(val, 0));
  1202. if (diff == 0)
  1203. return false;
  1204. mutex_lock(&pool->pool_lock);
  1205. pool->swork.diff = diff;
  1206. mutex_unlock(&pool->pool_lock);
  1207. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no, diff);
  1208. return true;
  1209. }
  1210. static bool parse_reconnect(struct pool *pool, json_t *val)
  1211. {
  1212. char *url, *port, address[256];
  1213. memset(address, 0, 255);
  1214. url = (char *)json_string_value(json_array_get(val, 0));
  1215. if (!url)
  1216. url = pool->sockaddr_url;
  1217. port = (char *)json_string_value(json_array_get(val, 1));
  1218. if (!port)
  1219. port = pool->stratum_port;
  1220. sprintf(address, "%s:%s", url, port);
  1221. if (!extract_sockaddr(pool, address))
  1222. return false;
  1223. pool->stratum_url = pool->sockaddr_url;
  1224. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1225. if (!initiate_stratum(pool) || !auth_stratum(pool))
  1226. return false;
  1227. return true;
  1228. }
  1229. static bool send_version(struct pool *pool, json_t *val)
  1230. {
  1231. char s[RBUFSIZE], *idstr;
  1232. json_t *id = json_object_get(val, "id");
  1233. if (!(id && !json_is_null(id)))
  1234. return false;
  1235. idstr = json_dumps_ANY(id, 0);
  1236. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1237. free(idstr);
  1238. if (!stratum_send(pool, s, strlen(s)))
  1239. return false;
  1240. return true;
  1241. }
  1242. bool parse_method(struct pool *pool, char *s)
  1243. {
  1244. json_t *val = NULL, *method, *err_val, *params;
  1245. json_error_t err;
  1246. bool ret = false;
  1247. char *buf;
  1248. if (!s)
  1249. goto out;
  1250. val = JSON_LOADS(s, &err);
  1251. if (!val) {
  1252. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1253. goto out;
  1254. }
  1255. method = json_object_get(val, "method");
  1256. if (!method)
  1257. goto out;
  1258. err_val = json_object_get(val, "error");
  1259. params = json_object_get(val, "params");
  1260. if (err_val && !json_is_null(err_val)) {
  1261. char *ss;
  1262. if (err_val)
  1263. ss = json_dumps(err_val, JSON_INDENT(3));
  1264. else
  1265. ss = strdup("(unknown reason)");
  1266. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1267. free(ss);
  1268. goto out;
  1269. }
  1270. buf = (char *)json_string_value(method);
  1271. if (!buf)
  1272. goto out;
  1273. if (!strncasecmp(buf, "mining.notify", 13)) {
  1274. if (parse_notify(pool, params))
  1275. pool->stratum_notify = ret = true;
  1276. else
  1277. pool->stratum_notify = ret = false;
  1278. goto out;
  1279. }
  1280. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1281. ret = true;
  1282. goto out;
  1283. }
  1284. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1285. ret = true;
  1286. goto out;
  1287. }
  1288. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1289. ret = true;
  1290. goto out;
  1291. }
  1292. out:
  1293. if (val)
  1294. json_decref(val);
  1295. return ret;
  1296. }
  1297. extern bool parse_stratum_response(struct pool *, char *s);
  1298. bool auth_stratum(struct pool *pool)
  1299. {
  1300. json_t *val = NULL, *res_val, *err_val;
  1301. char s[RBUFSIZE], *sret = NULL;
  1302. json_error_t err;
  1303. bool ret = false;
  1304. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1305. pool->rpc_user, pool->rpc_pass);
  1306. if (!stratum_send(pool, s, strlen(s)))
  1307. goto out;
  1308. /* Parse all data in the queue and anything left should be auth */
  1309. while (42) {
  1310. sret = recv_line(pool);
  1311. if (!sret)
  1312. goto out;
  1313. if (parse_method(pool, sret))
  1314. free(sret);
  1315. else
  1316. break;
  1317. }
  1318. val = JSON_LOADS(sret, &err);
  1319. free(sret);
  1320. res_val = json_object_get(val, "result");
  1321. err_val = json_object_get(val, "error");
  1322. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1323. char *ss;
  1324. if (err_val)
  1325. ss = json_dumps(err_val, JSON_INDENT(3));
  1326. else
  1327. ss = strdup("(unknown reason)");
  1328. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1329. free(ss);
  1330. goto out;
  1331. }
  1332. ret = true;
  1333. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1334. pool->probed = true;
  1335. pool->stratum_auth = true;
  1336. successful_connect = true;
  1337. out:
  1338. if (val)
  1339. json_decref(val);
  1340. if (pool->stratum_notify)
  1341. stratum_probe_transparency(pool);
  1342. return ret;
  1343. }
  1344. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1345. {
  1346. struct pool *pool = clientp;
  1347. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1348. pool->sock = sck;
  1349. return sck;
  1350. }
  1351. bool initiate_stratum(struct pool *pool)
  1352. {
  1353. json_t *val = NULL, *res_val, *err_val;
  1354. char curl_err_str[CURL_ERROR_SIZE];
  1355. char s[RBUFSIZE], *sret = NULL;
  1356. CURL *curl = NULL;
  1357. json_error_t err;
  1358. bool ret = false;
  1359. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1360. mutex_lock(&pool->stratum_lock);
  1361. pool->swork.transparency_time = (time_t)-1;
  1362. pool->stratum_active = false;
  1363. pool->stratum_auth = false;
  1364. pool->stratum_notify = false;
  1365. pool->swork.transparency_probed = false;
  1366. if (!pool->stratum_curl) {
  1367. pool->stratum_curl = curl_easy_init();
  1368. if (unlikely(!pool->stratum_curl))
  1369. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1370. }
  1371. if (pool->sockbuf)
  1372. pool->sockbuf[0] = '\0';
  1373. curl = pool->stratum_curl;
  1374. if (!pool->sockbuf) {
  1375. pool->sockbuf = calloc(RBUFSIZE, 1);
  1376. if (!pool->sockbuf)
  1377. quit(1, "Failed to calloc pool sockbuf in initiate_stratum");
  1378. pool->sockbuf_size = RBUFSIZE;
  1379. }
  1380. /* Create a http url for use with curl */
  1381. memset(s, 0, RBUFSIZE);
  1382. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1383. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1384. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1385. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1386. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1387. curl_easy_setopt(curl, CURLOPT_URL, s);
  1388. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1389. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1390. * to enable it */
  1391. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  1392. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  1393. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1394. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  1395. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  1396. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  1397. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1398. if (pool->rpc_proxy) {
  1399. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1400. } else if (opt_socks_proxy) {
  1401. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1402. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1403. }
  1404. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1405. pool->sock = INVSOCK;
  1406. if (curl_easy_perform(curl)) {
  1407. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1408. mutex_unlock(&pool->stratum_lock);
  1409. goto out;
  1410. }
  1411. if (pool->sock == INVSOCK)
  1412. {
  1413. pool->stratum_curl = NULL;
  1414. curl_easy_cleanup(curl);
  1415. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  1416. mutex_unlock(&pool->stratum_lock);
  1417. goto out;
  1418. }
  1419. keep_sockalive(pool->sock);
  1420. pool->cgminer_pool_stats.times_sent++;
  1421. pool->cgminer_pool_stats.times_received++;
  1422. mutex_unlock(&pool->stratum_lock);
  1423. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1424. if (!_stratum_send(pool, s, strlen(s), true)) {
  1425. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1426. goto out;
  1427. }
  1428. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1429. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1430. goto out;
  1431. }
  1432. sret = recv_line(pool);
  1433. if (!sret)
  1434. goto out;
  1435. val = JSON_LOADS(sret, &err);
  1436. free(sret);
  1437. if (!val) {
  1438. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1439. goto out;
  1440. }
  1441. res_val = json_object_get(val, "result");
  1442. err_val = json_object_get(val, "error");
  1443. if (!res_val || json_is_null(res_val) ||
  1444. (err_val && !json_is_null(err_val))) {
  1445. char *ss;
  1446. if (err_val)
  1447. ss = json_dumps(err_val, JSON_INDENT(3));
  1448. else
  1449. ss = strdup("(unknown reason)");
  1450. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1451. free(ss);
  1452. goto out;
  1453. }
  1454. free(pool->nonce1);
  1455. pool->nonce1 = json_array_string(res_val, 1);
  1456. if (!pool->nonce1) {
  1457. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1458. goto out;
  1459. }
  1460. pool->n1_len = strlen(pool->nonce1) / 2;
  1461. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1462. if (!pool->n2size) {
  1463. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1464. goto out;
  1465. }
  1466. ret = true;
  1467. out:
  1468. if (val)
  1469. json_decref(val);
  1470. if (ret) {
  1471. if (!pool->stratum_url)
  1472. pool->stratum_url = pool->sockaddr_url;
  1473. pool->stratum_active = true;
  1474. pool->swork.diff = 1;
  1475. if (opt_protocol) {
  1476. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1477. pool->pool_no, pool->nonce1, pool->n2size);
  1478. }
  1479. } else
  1480. {
  1481. applog(LOG_DEBUG, "Initiate stratum failed");
  1482. if (pool->sock != INVSOCK) {
  1483. shutdown(pool->sock, SHUT_RDWR);
  1484. pool->sock = INVSOCK;
  1485. }
  1486. }
  1487. return ret;
  1488. }
  1489. void suspend_stratum(struct pool *pool)
  1490. {
  1491. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1492. mutex_lock(&pool->stratum_lock);
  1493. pool->stratum_active = false;
  1494. pool->stratum_auth = false;
  1495. curl_easy_cleanup(pool->stratum_curl);
  1496. pool->stratum_curl = NULL;
  1497. pool->sock = INVSOCK;
  1498. mutex_unlock(&pool->stratum_lock);
  1499. }
  1500. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1501. {
  1502. dev->device_last_not_well = time(NULL);
  1503. dev->device_not_well_reason = reason;
  1504. switch (reason) {
  1505. case REASON_THREAD_FAIL_INIT:
  1506. dev->thread_fail_init_count++;
  1507. break;
  1508. case REASON_THREAD_ZERO_HASH:
  1509. dev->thread_zero_hash_count++;
  1510. break;
  1511. case REASON_THREAD_FAIL_QUEUE:
  1512. dev->thread_fail_queue_count++;
  1513. break;
  1514. case REASON_DEV_SICK_IDLE_60:
  1515. dev->dev_sick_idle_60_count++;
  1516. break;
  1517. case REASON_DEV_DEAD_IDLE_600:
  1518. dev->dev_dead_idle_600_count++;
  1519. break;
  1520. case REASON_DEV_NOSTART:
  1521. dev->dev_nostart_count++;
  1522. break;
  1523. case REASON_DEV_OVER_HEAT:
  1524. dev->dev_over_heat_count++;
  1525. break;
  1526. case REASON_DEV_THERMAL_CUTOFF:
  1527. dev->dev_thermal_cutoff_count++;
  1528. break;
  1529. case REASON_DEV_COMMS_ERROR:
  1530. dev->dev_comms_error_count++;
  1531. break;
  1532. case REASON_DEV_THROTTLE:
  1533. dev->dev_throttle_count++;
  1534. break;
  1535. }
  1536. }
  1537. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1538. void *realloc_strcat(char *ptr, char *s)
  1539. {
  1540. size_t old = strlen(ptr), len = strlen(s);
  1541. char *ret;
  1542. if (!len)
  1543. return ptr;
  1544. len += old + 1;
  1545. align_len(&len);
  1546. ret = malloc(len);
  1547. if (unlikely(!ret))
  1548. quit(1, "Failed to malloc in realloc_strcat");
  1549. sprintf(ret, "%s%s", ptr, s);
  1550. free(ptr);
  1551. return ret;
  1552. }
  1553. static
  1554. bool sanechars[] = {
  1555. false, false, false, false, false, false, false, false,
  1556. false, false, false, false, false, false, false, false,
  1557. false, false, false, false, false, false, false, false,
  1558. false, false, false, false, false, false, false, false,
  1559. false, false, false, false, false, false, false, false,
  1560. false, false, false, false, false, false, false, false,
  1561. true , true , true , true , true , true , true , true ,
  1562. true , true , false, false, false, false, false, false,
  1563. false, true , true , true , true , true , true , true ,
  1564. true , true , true , true , true , true , true , true ,
  1565. true , true , true , true , true , true , true , true ,
  1566. true , true , true , false, false, false, false, false,
  1567. false, true , true , true , true , true , true , true ,
  1568. true , true , true , true , true , true , true , true ,
  1569. true , true , true , true , true , true , true , true ,
  1570. true , true , true , false, false, false, false, false,
  1571. };
  1572. char *sanestr(char *o, char *s)
  1573. {
  1574. char *rv = o;
  1575. bool br = false;
  1576. for ( ; s[0]; ++s)
  1577. {
  1578. if (sanechars[s[0] & 0x7f])
  1579. {
  1580. if (br)
  1581. {
  1582. br = false;
  1583. if (s[0] >= '0' && s[0] <= '9')
  1584. (o++)[0] = '_';
  1585. }
  1586. (o++)[0] = s[0];
  1587. }
  1588. else
  1589. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  1590. br = true;
  1591. }
  1592. o[0] = '\0';
  1593. return rv;
  1594. }
  1595. void RenameThread(const char* name)
  1596. {
  1597. #if defined(PR_SET_NAME)
  1598. // Only the first 15 characters are used (16 - NUL terminator)
  1599. prctl(PR_SET_NAME, name, 0, 0, 0);
  1600. #elif defined(__APPLE__)
  1601. pthread_setname_np(name);
  1602. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1603. pthread_set_name_np(pthread_self(), name);
  1604. #else
  1605. // Prevent warnings for unused parameters...
  1606. (void)name;
  1607. #endif
  1608. }
  1609. #ifdef WIN32
  1610. static const char *WindowsErrorStr(DWORD dwMessageId)
  1611. {
  1612. static LPSTR msg = NULL;
  1613. if (msg)
  1614. LocalFree(msg);
  1615. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, dwMessageId, 0, (LPSTR)&msg, 0, 0))
  1616. return msg;
  1617. static const char fmt[] = "Error #%ld";
  1618. signed long ldMsgId = dwMessageId;
  1619. int sz = snprintf((char*)&sz, 0, fmt, ldMsgId) + 1;
  1620. msg = (LPTSTR)LocalAlloc(LMEM_FIXED, sz);
  1621. sprintf((char*)msg, fmt, ldMsgId);
  1622. return msg;
  1623. }
  1624. #endif
  1625. void notifier_init(notifier_t pipefd)
  1626. {
  1627. #ifdef WIN32
  1628. SOCKET listener, connecter, acceptor;
  1629. listener = socket(AF_INET, SOCK_STREAM, 0);
  1630. if (listener == INVALID_SOCKET)
  1631. quit(1, "Failed to create listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1632. connecter = socket(AF_INET, SOCK_STREAM, 0);
  1633. if (connecter == INVALID_SOCKET)
  1634. quit(1, "Failed to create connect socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1635. struct sockaddr_in inaddr = {
  1636. .sin_family = AF_INET,
  1637. .sin_addr = {
  1638. .s_addr = htonl(INADDR_LOOPBACK),
  1639. },
  1640. .sin_port = 0,
  1641. };
  1642. {
  1643. static const int reuse = 1;
  1644. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
  1645. }
  1646. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  1647. quit(1, "Failed to bind listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1648. socklen_t inaddr_sz = sizeof(inaddr);
  1649. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  1650. quit(1, "Failed to getsockname in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1651. if (listen(listener, 1) == SOCKET_ERROR)
  1652. quit(1, "Failed to listen in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1653. inaddr.sin_family = AF_INET;
  1654. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1655. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  1656. quit(1, "Failed to connect in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1657. acceptor = accept(listener, NULL, NULL);
  1658. if (acceptor == INVALID_SOCKET)
  1659. quit(1, "Failed to accept in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1660. closesocket(listener);
  1661. pipefd[0] = connecter;
  1662. pipefd[1] = acceptor;
  1663. #else
  1664. if (pipe(pipefd))
  1665. quit(1, "Failed to create pipe in create_notifier");
  1666. #endif
  1667. }
  1668. void notifier_wake(notifier_t fd)
  1669. {
  1670. #ifdef WIN32
  1671. (void)send(fd[1], "\0", 1, 0);
  1672. #else
  1673. (void)write(fd[1], "\0", 1);
  1674. #endif
  1675. }
  1676. void notifier_read(notifier_t fd)
  1677. {
  1678. char buf[0x10];
  1679. #ifdef WIN32
  1680. (void)recv(fd[0], buf, sizeof(buf), 0);
  1681. #else
  1682. (void)read(fd[0], buf, sizeof(buf));
  1683. #endif
  1684. }