util.c 48 KB

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