util.c 48 KB

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