util.c 46 KB

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