util.c 47 KB

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