util.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581
  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. #include <fcntl.h>
  34. # ifdef __linux
  35. # include <sys/prctl.h>
  36. # endif
  37. # include <sys/socket.h>
  38. # include <netinet/in.h>
  39. # include <netinet/tcp.h>
  40. # include <netdb.h>
  41. #else
  42. # include <windows.h>
  43. # include <winsock2.h>
  44. # include <mstcpip.h>
  45. # include <ws2tcpip.h>
  46. # include <mmsystem.h>
  47. #endif
  48. #include <utlist.h>
  49. #include "miner.h"
  50. #include "compat.h"
  51. #include "util.h"
  52. bool successful_connect = false;
  53. struct timeval nettime;
  54. struct data_buffer {
  55. void *buf;
  56. size_t len;
  57. curl_socket_t *idlemarker;
  58. };
  59. struct upload_buffer {
  60. const void *buf;
  61. size_t len;
  62. };
  63. struct header_info {
  64. char *lp_path;
  65. int rolltime;
  66. char *reason;
  67. char *stratum_url;
  68. bool hadrolltime;
  69. bool canroll;
  70. bool hadexpire;
  71. };
  72. struct tq_ent {
  73. void *data;
  74. struct tq_ent *prev;
  75. struct tq_ent *next;
  76. };
  77. static void databuf_free(struct data_buffer *db)
  78. {
  79. if (!db)
  80. return;
  81. free(db->buf);
  82. #ifdef DEBUG_DATABUF
  83. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  84. #endif
  85. memset(db, 0, sizeof(*db));
  86. }
  87. // aka data_buffer_write
  88. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  89. void *user_data)
  90. {
  91. struct data_buffer *db = user_data;
  92. size_t oldlen, newlen;
  93. oldlen = db->len;
  94. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  95. return 0;
  96. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  97. nmemb = (SIZE_MAX - oldlen) / size;
  98. size_t len = size * nmemb;
  99. void *newmem;
  100. static const unsigned char zero = 0;
  101. if (db->idlemarker) {
  102. const unsigned char *cptr = ptr;
  103. for (size_t i = 0; i < len; ++i)
  104. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  105. *db->idlemarker = CURL_SOCKET_BAD;
  106. db->idlemarker = NULL;
  107. break;
  108. }
  109. }
  110. newlen = oldlen + len;
  111. newmem = realloc(db->buf, newlen + 1);
  112. #ifdef DEBUG_DATABUF
  113. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  114. #endif
  115. if (!newmem)
  116. return 0;
  117. db->buf = newmem;
  118. db->len = newlen;
  119. memcpy(db->buf + oldlen, ptr, len);
  120. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  121. return nmemb;
  122. }
  123. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  124. void *user_data)
  125. {
  126. struct upload_buffer *ub = user_data;
  127. unsigned int len = size * nmemb;
  128. if (len > ub->len)
  129. len = ub->len;
  130. if (len) {
  131. memcpy(ptr, ub->buf, len);
  132. ub->buf += len;
  133. ub->len -= len;
  134. }
  135. return len;
  136. }
  137. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  138. {
  139. struct header_info *hi = user_data;
  140. size_t remlen, slen, ptrlen = size * nmemb;
  141. char *rem, *val = NULL, *key = NULL;
  142. void *tmp;
  143. val = calloc(1, ptrlen);
  144. key = calloc(1, ptrlen);
  145. if (!key || !val)
  146. goto out;
  147. tmp = memchr(ptr, ':', ptrlen);
  148. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  149. goto out;
  150. slen = tmp - ptr;
  151. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  152. goto out;
  153. memcpy(key, ptr, slen); /* store & nul term key */
  154. key[slen] = 0;
  155. rem = ptr + slen + 1; /* trim value's leading whitespace */
  156. remlen = ptrlen - slen - 1;
  157. while ((remlen > 0) && (isspace(*rem))) {
  158. remlen--;
  159. rem++;
  160. }
  161. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  162. val[remlen] = 0;
  163. while ((*val) && (isspace(val[strlen(val) - 1])))
  164. val[strlen(val) - 1] = 0;
  165. if (!*val) /* skip blank value */
  166. goto out;
  167. if (opt_protocol)
  168. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  169. if (!strcasecmp("X-Roll-Ntime", key)) {
  170. hi->hadrolltime = true;
  171. if (!strncasecmp("N", val, 1))
  172. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  173. else {
  174. hi->canroll = true;
  175. /* Check to see if expire= is supported and if not, set
  176. * the rolltime to the default scantime */
  177. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  178. sscanf(val + 7, "%d", &hi->rolltime);
  179. hi->hadexpire = true;
  180. } else
  181. hi->rolltime = opt_scantime;
  182. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  183. }
  184. }
  185. if (!strcasecmp("X-Long-Polling", key)) {
  186. hi->lp_path = val; /* steal memory reference */
  187. val = NULL;
  188. }
  189. if (!strcasecmp("X-Reject-Reason", key)) {
  190. hi->reason = val; /* steal memory reference */
  191. val = NULL;
  192. }
  193. if (!strcasecmp("X-Stratum", key)) {
  194. hi->stratum_url = val;
  195. val = NULL;
  196. }
  197. out:
  198. free(key);
  199. free(val);
  200. return ptrlen;
  201. }
  202. static int keep_sockalive(SOCKETTYPE fd)
  203. {
  204. const int tcp_one = 1;
  205. const int tcp_keepidle = 45;
  206. const int tcp_keepintvl = 30;
  207. int ret = 0;
  208. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one))))
  209. ret = 1;
  210. #ifndef WIN32
  211. int flags = fcntl(fd, F_GETFL, 0);
  212. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  213. #else
  214. u_long flags = 1;
  215. ioctlsocket(fd, FIONBIO, &flags);
  216. #endif
  217. if (!opt_delaynet)
  218. #ifndef __linux
  219. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  220. #else /* __linux */
  221. if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  222. #endif /* __linux */
  223. ret = 1;
  224. #ifdef __linux
  225. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one))))
  226. ret = 1;
  227. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  228. ret = 1;
  229. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  230. ret = 1;
  231. #endif /* __linux */
  232. #ifdef __APPLE_CC__
  233. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  234. ret = 1;
  235. #endif /* __APPLE_CC__ */
  236. #ifdef WIN32
  237. const int zero = 0;
  238. struct tcp_keepalive vals;
  239. vals.onoff = 1;
  240. vals.keepalivetime = tcp_keepidle * 1000;
  241. vals.keepaliveinterval = tcp_keepintvl * 1000;
  242. DWORD outputBytes;
  243. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  244. ret = 1;
  245. /* Windows happily submits indefinitely to the send buffer blissfully
  246. * unaware nothing is getting there without gracefully failing unless
  247. * we disable the send buffer */
  248. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  249. ret = 1;
  250. #endif /* WIN32 */
  251. return ret;
  252. }
  253. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  254. curlsocktype __maybe_unused purpose)
  255. {
  256. return keep_sockalive(fd);
  257. }
  258. static void last_nettime(struct timeval *last)
  259. {
  260. rd_lock(&netacc_lock);
  261. last->tv_sec = nettime.tv_sec;
  262. last->tv_usec = nettime.tv_usec;
  263. rd_unlock(&netacc_lock);
  264. }
  265. static void set_nettime(void)
  266. {
  267. wr_lock(&netacc_lock);
  268. cgtime(&nettime);
  269. wr_unlock(&netacc_lock);
  270. }
  271. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  272. char *data, size_t size,
  273. void *userdata)
  274. {
  275. struct pool *pool = (struct pool *)userdata;
  276. switch(type) {
  277. case CURLINFO_HEADER_IN:
  278. case CURLINFO_DATA_IN:
  279. case CURLINFO_SSL_DATA_IN:
  280. pool->cgminer_pool_stats.bytes_received += size;
  281. total_bytes_xfer += size;
  282. pool->cgminer_pool_stats.net_bytes_received += size;
  283. break;
  284. case CURLINFO_HEADER_OUT:
  285. case CURLINFO_DATA_OUT:
  286. case CURLINFO_SSL_DATA_OUT:
  287. pool->cgminer_pool_stats.bytes_sent += size;
  288. total_bytes_xfer += size;
  289. pool->cgminer_pool_stats.net_bytes_sent += size;
  290. break;
  291. case CURLINFO_TEXT:
  292. {
  293. if (!opt_protocol)
  294. break;
  295. // data is not null-terminated, so we need to copy and terminate it for applog
  296. char datacp[size + 1];
  297. memcpy(datacp, data, size);
  298. while (likely(size) && unlikely(isspace(datacp[size-1])))
  299. --size;
  300. if (unlikely(!size))
  301. break;
  302. datacp[size] = '\0';
  303. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  304. break;
  305. }
  306. default:
  307. break;
  308. }
  309. return 0;
  310. }
  311. struct json_rpc_call_state {
  312. struct data_buffer all_data;
  313. struct header_info hi;
  314. void *priv;
  315. char curl_err_str[CURL_ERROR_SIZE];
  316. struct curl_slist *headers;
  317. struct upload_buffer upload_data;
  318. struct pool *pool;
  319. };
  320. void json_rpc_call_async(CURL *curl, const char *url,
  321. const char *userpass, const char *rpc_req,
  322. bool longpoll,
  323. struct pool *pool, bool share,
  324. void *priv)
  325. {
  326. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  327. *state = (struct json_rpc_call_state){
  328. .priv = priv,
  329. .pool = pool,
  330. };
  331. long timeout = longpoll ? (60 * 60) : 60;
  332. char len_hdr[64], user_agent_hdr[128];
  333. struct curl_slist *headers = NULL;
  334. if (longpoll)
  335. state->all_data.idlemarker = &pool->lp_socket;
  336. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  337. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  338. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  339. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  340. * to enable it */
  341. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  342. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  343. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  344. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  345. curl_easy_setopt(curl, CURLOPT_URL, url);
  346. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  347. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  348. /* Shares are staggered already and delays in submission can be costly
  349. * so do not delay them */
  350. if (!opt_delaynet || share)
  351. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  352. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  353. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  354. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  355. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  356. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  357. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  358. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  359. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  360. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  361. if (pool->rpc_proxy) {
  362. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  363. } else if (opt_socks_proxy) {
  364. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  365. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  366. }
  367. if (userpass) {
  368. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  369. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  370. }
  371. if (longpoll)
  372. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  373. curl_easy_setopt(curl, CURLOPT_POST, 1);
  374. if (opt_protocol)
  375. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  376. state->upload_data.buf = rpc_req;
  377. state->upload_data.len = strlen(rpc_req);
  378. sprintf(len_hdr, "Content-Length: %lu",
  379. (unsigned long) state->upload_data.len);
  380. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  381. headers = curl_slist_append(headers,
  382. "Content-type: application/json");
  383. headers = curl_slist_append(headers,
  384. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  385. if (longpoll)
  386. headers = curl_slist_append(headers,
  387. "X-Minimum-Wait: 0");
  388. if (likely(global_hashrate)) {
  389. char ghashrate[255];
  390. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  391. headers = curl_slist_append(headers, ghashrate);
  392. }
  393. headers = curl_slist_append(headers, len_hdr);
  394. headers = curl_slist_append(headers, user_agent_hdr);
  395. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  396. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  397. state->headers = headers;
  398. if (opt_delaynet) {
  399. /* Don't delay share submission, but still track the nettime */
  400. if (!share) {
  401. long long now_msecs, last_msecs;
  402. struct timeval now, last;
  403. cgtime(&now);
  404. last_nettime(&last);
  405. now_msecs = (long long)now.tv_sec * 1000;
  406. now_msecs += now.tv_usec / 1000;
  407. last_msecs = (long long)last.tv_sec * 1000;
  408. last_msecs += last.tv_usec / 1000;
  409. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  410. struct timespec rgtp;
  411. rgtp.tv_sec = 0;
  412. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  413. nanosleep(&rgtp, NULL);
  414. }
  415. }
  416. set_nettime();
  417. }
  418. }
  419. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  420. {
  421. struct json_rpc_call_state *state;
  422. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
  423. applog(LOG_ERR, "Failed to get private curl data");
  424. if (out_priv)
  425. *(void**)out_priv = NULL;
  426. goto err_out;
  427. }
  428. if (out_priv)
  429. *(void**)out_priv = state->priv;
  430. json_t *val, *err_val, *res_val;
  431. json_error_t err;
  432. struct pool *pool = state->pool;
  433. bool probing = probe && !pool->probed;
  434. if (rc) {
  435. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  436. goto err_out;
  437. }
  438. if (!state->all_data.buf) {
  439. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  440. goto err_out;
  441. }
  442. pool->cgminer_pool_stats.times_sent++;
  443. pool->cgminer_pool_stats.times_received++;
  444. if (probing) {
  445. pool->probed = true;
  446. /* If X-Long-Polling was found, activate long polling */
  447. if (state->hi.lp_path) {
  448. if (pool->hdr_path != NULL)
  449. free(pool->hdr_path);
  450. pool->hdr_path = state->hi.lp_path;
  451. } else
  452. pool->hdr_path = NULL;
  453. if (state->hi.stratum_url) {
  454. pool->stratum_url = state->hi.stratum_url;
  455. state->hi.stratum_url = NULL;
  456. }
  457. } else {
  458. if (state->hi.lp_path) {
  459. free(state->hi.lp_path);
  460. state->hi.lp_path = NULL;
  461. }
  462. if (state->hi.stratum_url) {
  463. free(state->hi.stratum_url);
  464. state->hi.stratum_url = NULL;
  465. }
  466. }
  467. if (pool->force_rollntime)
  468. {
  469. state->hi.canroll = true;
  470. state->hi.hadexpire = true;
  471. state->hi.rolltime = pool->force_rollntime;
  472. }
  473. if (rolltime)
  474. *rolltime = state->hi.rolltime;
  475. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  476. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  477. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  478. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  479. val = JSON_LOADS(state->all_data.buf, &err);
  480. if (!val) {
  481. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  482. if (opt_protocol)
  483. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  484. goto err_out;
  485. }
  486. if (opt_protocol) {
  487. char *s = json_dumps(val, JSON_INDENT(3));
  488. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  489. free(s);
  490. }
  491. /* JSON-RPC valid response returns a non-null 'result',
  492. * and a null 'error'.
  493. */
  494. res_val = json_object_get(val, "result");
  495. err_val = json_object_get(val, "error");
  496. if (!res_val ||(err_val && !json_is_null(err_val))) {
  497. char *s;
  498. if (err_val)
  499. s = json_dumps(err_val, JSON_INDENT(3));
  500. else
  501. s = strdup("(unknown reason)");
  502. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  503. free(s);
  504. json_decref(val);
  505. goto err_out;
  506. }
  507. if (state->hi.reason) {
  508. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  509. free(state->hi.reason);
  510. state->hi.reason = NULL;
  511. }
  512. successful_connect = true;
  513. databuf_free(&state->all_data);
  514. curl_slist_free_all(state->headers);
  515. curl_easy_reset(curl);
  516. free(state);
  517. return val;
  518. err_out:
  519. databuf_free(&state->all_data);
  520. curl_slist_free_all(state->headers);
  521. curl_easy_reset(curl);
  522. if (!successful_connect)
  523. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  524. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  525. free(state);
  526. return NULL;
  527. }
  528. json_t *json_rpc_call(CURL *curl, const char *url,
  529. const char *userpass, const char *rpc_req,
  530. bool probe, bool longpoll, int *rolltime,
  531. struct pool *pool, bool share)
  532. {
  533. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  534. int rc = curl_easy_perform(curl);
  535. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  536. }
  537. bool our_curl_supports_proxy_uris()
  538. {
  539. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  540. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  541. }
  542. // NOTE: This assumes reference URI is a root
  543. char *absolute_uri(char *uri, const char *ref)
  544. {
  545. if (strstr(uri, "://"))
  546. return strdup(uri);
  547. char *copy_start, *abs;
  548. bool need_slash = false;
  549. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  550. if (ref[strlen(ref) - 1] != '/')
  551. need_slash = true;
  552. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  553. if (!abs) {
  554. applog(LOG_ERR, "Malloc failure in absolute_uri");
  555. return NULL;
  556. }
  557. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  558. return abs;
  559. }
  560. static const char _hexchars[0x10] = "0123456789abcdef";
  561. void bin2hex(char *out, const void *in, size_t len)
  562. {
  563. const unsigned char *p = in;
  564. while (len--)
  565. {
  566. (out++)[0] = _hexchars[p[0] >> 4];
  567. (out++)[0] = _hexchars[p[0] & 0xf];
  568. ++p;
  569. }
  570. out[0] = '\0';
  571. }
  572. static inline
  573. int _hex2bin_char(const char c)
  574. {
  575. if (c >= '0' && c <= '9')
  576. return c - '0';
  577. if (c >= 'a' && c <= 'f')
  578. return (c - 'a') + 10;
  579. if (c >= 'A' && c <= 'F')
  580. return (c - 'A') + 10;
  581. return -1;
  582. }
  583. /* Does the reverse of bin2hex but does not allocate any ram */
  584. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  585. {
  586. int n, o;
  587. while (len--)
  588. {
  589. n = _hex2bin_char((hexstr++)[0]);
  590. if (unlikely(n == -1))
  591. {
  592. badchar:
  593. if (!hexstr[-1])
  594. applog(LOG_ERR, "hex2bin: str truncated");
  595. else
  596. applog(LOG_ERR, "hex2bin: invalid character 0x%02x", (int)hexstr[-1]);
  597. return false;
  598. }
  599. o = _hex2bin_char((hexstr++)[0]);
  600. if (unlikely(o == -1))
  601. goto badchar;
  602. (p++)[0] = (n << 4) | o;
  603. }
  604. return likely(!hexstr[0]);
  605. }
  606. void hash_data(unsigned char *out_hash, const unsigned char *data)
  607. {
  608. unsigned char blkheader[80];
  609. // 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
  610. swap32yes(blkheader, data, 80 / 4);
  611. // double-SHA256 to get the block hash
  612. gen_hash(blkheader, out_hash, 80);
  613. }
  614. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  615. void real_block_target(unsigned char *target, const unsigned char *data)
  616. {
  617. uint8_t targetshift;
  618. if (unlikely(data[72] < 3 || data[72] > 0x20))
  619. {
  620. // Invalid (out of bounds) target
  621. memset(target, 0xff, 32);
  622. return;
  623. }
  624. targetshift = data[72] - 3;
  625. memset(target, 0, targetshift);
  626. target[targetshift++] = data[75];
  627. target[targetshift++] = data[74];
  628. target[targetshift++] = data[73];
  629. memset(&target[targetshift], 0, 0x20 - targetshift);
  630. }
  631. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  632. {
  633. const uint32_t *h32 = (uint32_t*)&hash[0];
  634. const uint32_t *t32 = (uint32_t*)&target[0];
  635. for (int i = 7; i >= 0; --i) {
  636. uint32_t h32i = le32toh(h32[i]);
  637. uint32_t t32i = le32toh(t32[i]);
  638. if (h32i > t32i)
  639. return false;
  640. if (h32i < t32i)
  641. return true;
  642. }
  643. return true;
  644. }
  645. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  646. {
  647. bool rc;
  648. rc = hash_target_check(hash, target);
  649. if (opt_debug) {
  650. unsigned char hash_swap[32], target_swap[32];
  651. char hash_str[65];
  652. char target_str[65];
  653. for (int i = 0; i < 32; ++i) {
  654. hash_swap[i] = hash[31-i];
  655. target_swap[i] = target[31-i];
  656. }
  657. bin2hex(hash_str, hash_swap, 32);
  658. bin2hex(target_str, target_swap, 32);
  659. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  660. hash_str,
  661. target_str,
  662. rc ? "YES (hash <= target)" :
  663. "no (false positive; hash > target)");
  664. }
  665. return rc;
  666. }
  667. // This operates on a native-endian SHA256 state
  668. // In other words, on little endian platforms, every 4 bytes are in reverse order
  669. bool fulltest(const unsigned char *hash, const unsigned char *target)
  670. {
  671. unsigned char hash2[32];
  672. swap32tobe(hash2, hash, 32 / 4);
  673. return hash_target_check_v(hash2, target);
  674. }
  675. struct thread_q *tq_new(void)
  676. {
  677. struct thread_q *tq;
  678. tq = calloc(1, sizeof(*tq));
  679. if (!tq)
  680. return NULL;
  681. pthread_mutex_init(&tq->mutex, NULL);
  682. pthread_cond_init(&tq->cond, NULL);
  683. return tq;
  684. }
  685. void tq_free(struct thread_q *tq)
  686. {
  687. struct tq_ent *ent, *iter;
  688. if (!tq)
  689. return;
  690. DL_FOREACH_SAFE(tq->q, ent, iter) {
  691. DL_DELETE(tq->q, ent);
  692. free(ent);
  693. }
  694. pthread_cond_destroy(&tq->cond);
  695. pthread_mutex_destroy(&tq->mutex);
  696. memset(tq, 0, sizeof(*tq)); /* poison */
  697. free(tq);
  698. }
  699. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  700. {
  701. mutex_lock(&tq->mutex);
  702. tq->frozen = frozen;
  703. pthread_cond_signal(&tq->cond);
  704. mutex_unlock(&tq->mutex);
  705. }
  706. void tq_freeze(struct thread_q *tq)
  707. {
  708. tq_freezethaw(tq, true);
  709. }
  710. void tq_thaw(struct thread_q *tq)
  711. {
  712. tq_freezethaw(tq, false);
  713. }
  714. bool tq_push(struct thread_q *tq, void *data)
  715. {
  716. struct tq_ent *ent;
  717. bool rc = true;
  718. ent = calloc(1, sizeof(*ent));
  719. if (!ent)
  720. return false;
  721. ent->data = data;
  722. mutex_lock(&tq->mutex);
  723. if (!tq->frozen) {
  724. DL_APPEND(tq->q, ent);
  725. } else {
  726. free(ent);
  727. rc = false;
  728. }
  729. pthread_cond_signal(&tq->cond);
  730. mutex_unlock(&tq->mutex);
  731. return rc;
  732. }
  733. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  734. {
  735. struct tq_ent *ent;
  736. void *rval = NULL;
  737. int rc;
  738. mutex_lock(&tq->mutex);
  739. if (tq->q)
  740. goto pop;
  741. if (abstime)
  742. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  743. else
  744. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  745. if (rc)
  746. goto out;
  747. if (!tq->q)
  748. goto out;
  749. pop:
  750. ent = tq->q;
  751. rval = ent->data;
  752. DL_DELETE(tq->q, ent);
  753. free(ent);
  754. out:
  755. mutex_unlock(&tq->mutex);
  756. return rval;
  757. }
  758. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  759. {
  760. int rv = pthread_create(&thr->pth, attr, start, arg);
  761. if (likely(!rv))
  762. thr->has_pth = true;
  763. return rv;
  764. }
  765. void thr_info_freeze(struct thr_info *thr)
  766. {
  767. struct tq_ent *ent, *iter;
  768. struct thread_q *tq;
  769. if (!thr)
  770. return;
  771. tq = thr->q;
  772. if (!tq)
  773. return;
  774. mutex_lock(&tq->mutex);
  775. tq->frozen = true;
  776. DL_FOREACH_SAFE(tq->q, ent, iter) {
  777. DL_DELETE(tq->q, ent);
  778. free(ent);
  779. }
  780. mutex_unlock(&tq->mutex);
  781. }
  782. void thr_info_cancel(struct thr_info *thr)
  783. {
  784. if (!thr)
  785. return;
  786. if (thr->has_pth) {
  787. pthread_cancel(thr->pth);
  788. thr->has_pth = false;
  789. }
  790. }
  791. #ifndef HAVE_PTHREAD_CANCEL
  792. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  793. enum pthread_cancel_workaround_mode {
  794. PCWM_DEFAULT = 0,
  795. PCWM_TERMINATE = 1,
  796. PCWM_ASYNC = 2,
  797. PCWM_DISABLED = 4,
  798. PCWM_CANCELLED = 8,
  799. };
  800. static pthread_key_t key_pcwm;
  801. struct sigaction pcwm_orig_term_handler;
  802. static
  803. void do_pthread_cancel_exit(int flags)
  804. {
  805. if (!(flags & PCWM_ASYNC))
  806. // NOTE: Logging disables cancel while mutex held, so this is safe
  807. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  808. pthread_exit(PTHREAD_CANCELED);
  809. }
  810. static
  811. void sighandler_pthread_cancel(int sig)
  812. {
  813. int flags = (int)pthread_getspecific(key_pcwm);
  814. if (flags & PCWM_TERMINATE) // Main thread
  815. {
  816. // Restore original handler and call it
  817. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  818. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  819. raise(SIGTERM);
  820. quit(1, "pthread_cancel workaround: Original handler returned");
  821. }
  822. if (flags & PCWM_CANCELLED) // Already pending cancel
  823. return;
  824. if (flags & PCWM_DISABLED)
  825. {
  826. flags |= PCWM_CANCELLED;
  827. if (pthread_setspecific(key_pcwm, (void*)flags))
  828. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  829. return;
  830. }
  831. do_pthread_cancel_exit(flags);
  832. }
  833. void pthread_testcancel(void)
  834. {
  835. int flags = (int)pthread_getspecific(key_pcwm);
  836. if (flags & PCWM_CANCELLED && !(flags & PCWM_DISABLED))
  837. do_pthread_cancel_exit(flags);
  838. }
  839. int pthread_setcancelstate(int state, int *oldstate)
  840. {
  841. int flags = (int)pthread_getspecific(key_pcwm);
  842. if (oldstate)
  843. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  844. if (state == PTHREAD_CANCEL_DISABLE)
  845. flags |= PCWM_DISABLED;
  846. else
  847. {
  848. if (flags & PCWM_CANCELLED)
  849. do_pthread_cancel_exit(flags);
  850. flags &= ~PCWM_DISABLED;
  851. }
  852. if (pthread_setspecific(key_pcwm, (void*)flags))
  853. return -1;
  854. return 0;
  855. }
  856. int pthread_setcanceltype(int type, int *oldtype)
  857. {
  858. int flags = (int)pthread_getspecific(key_pcwm);
  859. if (oldtype)
  860. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  861. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  862. flags |= PCWM_ASYNC;
  863. else
  864. flags &= ~PCWM_ASYNC;
  865. if (pthread_setspecific(key_pcwm, (void*)flags))
  866. return -1;
  867. return 0;
  868. }
  869. void setup_pthread_cancel_workaround()
  870. {
  871. if (pthread_key_create(&key_pcwm, NULL))
  872. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  873. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  874. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  875. struct sigaction new_sigact = {
  876. .sa_handler = sighandler_pthread_cancel,
  877. };
  878. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  879. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  880. }
  881. #endif
  882. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  883. * on SMP machines */
  884. void nmsleep(unsigned int msecs)
  885. {
  886. struct timespec twait, tleft;
  887. int ret;
  888. ldiv_t d;
  889. #ifdef WIN32
  890. timeBeginPeriod(1);
  891. #endif
  892. d = ldiv(msecs, 1000);
  893. tleft.tv_sec = d.quot;
  894. tleft.tv_nsec = d.rem * 1000000;
  895. do {
  896. twait.tv_sec = tleft.tv_sec;
  897. twait.tv_nsec = tleft.tv_nsec;
  898. ret = nanosleep(&twait, &tleft);
  899. } while (ret == -1 && errno == EINTR);
  900. #ifdef WIN32
  901. timeEndPeriod(1);
  902. #endif
  903. }
  904. /* Same for usecs */
  905. void nusleep(unsigned int usecs)
  906. {
  907. struct timespec twait, tleft;
  908. int ret;
  909. ldiv_t d;
  910. #ifdef WIN32
  911. timeBeginPeriod(1);
  912. #endif
  913. d = ldiv(usecs, 1000000);
  914. tleft.tv_sec = d.quot;
  915. tleft.tv_nsec = d.rem * 1000;
  916. do {
  917. twait.tv_sec = tleft.tv_sec;
  918. twait.tv_nsec = tleft.tv_nsec;
  919. ret = nanosleep(&twait, &tleft);
  920. } while (ret == -1 && errno == EINTR);
  921. #ifdef WIN32
  922. timeEndPeriod(1);
  923. #endif
  924. }
  925. static
  926. void _now_gettimeofday(struct timeval *tv)
  927. {
  928. #ifdef WIN32
  929. // Windows' default resolution is only 15ms. This requests 1ms.
  930. timeBeginPeriod(1);
  931. #endif
  932. gettimeofday(tv, NULL);
  933. #ifdef WIN32
  934. timeEndPeriod(1);
  935. #endif
  936. }
  937. #ifdef HAVE_POOR_GETTIMEOFDAY
  938. static struct timeval tv_timeofday_offset;
  939. static struct timeval _tv_timeofday_lastchecked;
  940. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  941. static
  942. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  943. {
  944. struct timeval actual, delta;
  945. timeradd(expected, &tv_timeofday_offset, expected);
  946. _now_gettimeofday(&actual);
  947. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  948. // Within reason - no change necessary
  949. return;
  950. timersub(&actual, expected, &delta);
  951. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  952. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  953. *expected = actual;
  954. }
  955. void bfg_gettimeofday(struct timeval *out)
  956. {
  957. char buf[64] = "";
  958. timer_set_now(out);
  959. mutex_lock(&_tv_timeofday_mutex);
  960. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  961. bfg_calibrate_timeofday(out, buf);
  962. else
  963. timeradd(out, &tv_timeofday_offset, out);
  964. mutex_unlock(&_tv_timeofday_mutex);
  965. if (unlikely(buf[0]))
  966. applog(LOG_WARNING, "%s", buf);
  967. }
  968. #endif
  969. #ifdef WIN32
  970. static LARGE_INTEGER _perffreq;
  971. static
  972. void _now_queryperformancecounter(struct timeval *tv)
  973. {
  974. LARGE_INTEGER now;
  975. if (unlikely(!QueryPerformanceCounter(&now)))
  976. quit(1, "QueryPerformanceCounter failed");
  977. *tv = (struct timeval){
  978. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  979. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  980. };
  981. }
  982. #endif
  983. static void bfg_init_time();
  984. static
  985. void _now_is_not_set(__maybe_unused struct timeval *tv)
  986. {
  987. bfg_init_time();
  988. timer_set_now(tv);
  989. }
  990. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  991. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  992. static clockid_t bfg_timer_clk;
  993. static
  994. void _now_clock_gettime(struct timeval *tv)
  995. {
  996. struct timespec ts;
  997. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  998. quit(1, "clock_gettime failed");
  999. *tv = (struct timeval){
  1000. .tv_sec = ts.tv_sec,
  1001. .tv_usec = ts.tv_nsec / 1000,
  1002. };
  1003. }
  1004. static
  1005. bool _bfg_try_clock_gettime(clockid_t clk)
  1006. {
  1007. struct timespec ts;
  1008. if (clock_gettime(clk, &ts))
  1009. return false;
  1010. bfg_timer_clk = clk;
  1011. timer_set_now = _now_clock_gettime;
  1012. return true;
  1013. }
  1014. #endif
  1015. static
  1016. void bfg_init_time()
  1017. {
  1018. if (timer_set_now != _now_is_not_set)
  1019. return;
  1020. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1021. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1022. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1023. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1024. else
  1025. #endif
  1026. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1027. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1028. else
  1029. #endif
  1030. #ifdef WIN32
  1031. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1032. {
  1033. timer_set_now = _now_queryperformancecounter;
  1034. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1035. }
  1036. else
  1037. #endif
  1038. {
  1039. timer_set_now = _now_gettimeofday;
  1040. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1041. }
  1042. #ifdef HAVE_POOR_GETTIMEOFDAY
  1043. char buf[64] = "";
  1044. struct timeval tv;
  1045. timer_set_now(&tv);
  1046. bfg_calibrate_timeofday(&tv, buf);
  1047. applog(LOG_DEBUG, "%s", buf);
  1048. #endif
  1049. }
  1050. void subtime(struct timeval *a, struct timeval *b)
  1051. {
  1052. timersub(a, b, b);
  1053. }
  1054. void addtime(struct timeval *a, struct timeval *b)
  1055. {
  1056. timeradd(a, b, b);
  1057. }
  1058. bool time_more(struct timeval *a, struct timeval *b)
  1059. {
  1060. return timercmp(a, b, >);
  1061. }
  1062. bool time_less(struct timeval *a, struct timeval *b)
  1063. {
  1064. return timercmp(a, b, <);
  1065. }
  1066. void copy_time(struct timeval *dest, const struct timeval *src)
  1067. {
  1068. memcpy(dest, src, sizeof(struct timeval));
  1069. }
  1070. /* Returns the microseconds difference between end and start times as a double */
  1071. double us_tdiff(struct timeval *end, struct timeval *start)
  1072. {
  1073. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1074. }
  1075. /* Returns the seconds difference between end and start times as a double */
  1076. double tdiff(struct timeval *end, struct timeval *start)
  1077. {
  1078. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1079. }
  1080. bool extract_sockaddr(struct pool *pool, char *url)
  1081. {
  1082. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1083. char url_address[256], port[6];
  1084. int url_len, port_len = 0;
  1085. url_begin = strstr(url, "//");
  1086. if (!url_begin)
  1087. url_begin = url;
  1088. else
  1089. url_begin += 2;
  1090. /* Look for numeric ipv6 entries */
  1091. ipv6_begin = strstr(url_begin, "[");
  1092. ipv6_end = strstr(url_begin, "]");
  1093. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1094. url_end = strstr(ipv6_end, ":");
  1095. else
  1096. url_end = strstr(url_begin, ":");
  1097. if (url_end) {
  1098. url_len = url_end - url_begin;
  1099. port_len = strlen(url_begin) - url_len - 1;
  1100. if (port_len < 1)
  1101. return false;
  1102. port_start = url_end + 1;
  1103. } else
  1104. url_len = strlen(url_begin);
  1105. if (url_len < 1)
  1106. return false;
  1107. sprintf(url_address, "%.*s", url_len, url_begin);
  1108. if (port_len)
  1109. snprintf(port, 6, "%.*s", port_len, port_start);
  1110. else
  1111. strcpy(port, "80");
  1112. free(pool->stratum_port);
  1113. pool->stratum_port = strdup(port);
  1114. free(pool->sockaddr_url);
  1115. pool->sockaddr_url = strdup(url_address);
  1116. return true;
  1117. }
  1118. enum send_ret {
  1119. SEND_OK,
  1120. SEND_SELECTFAIL,
  1121. SEND_SENDFAIL,
  1122. SEND_INACTIVE
  1123. };
  1124. /* Send a single command across a socket, appending \n to it. This should all
  1125. * be done under stratum lock except when first establishing the socket */
  1126. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1127. {
  1128. SOCKETTYPE sock = pool->sock;
  1129. ssize_t ssent = 0;
  1130. strcat(s, "\n");
  1131. len++;
  1132. while (len > 0 ) {
  1133. struct timeval timeout = {1, 0};
  1134. ssize_t sent;
  1135. fd_set wd;
  1136. FD_ZERO(&wd);
  1137. FD_SET(sock, &wd);
  1138. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  1139. return SEND_SELECTFAIL;
  1140. #ifdef __APPLE__
  1141. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1142. #elif WIN32
  1143. sent = send(pool->sock, s + ssent, len, 0);
  1144. #else
  1145. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1146. #endif
  1147. if (sent < 0) {
  1148. if (!sock_blocks())
  1149. return SEND_SENDFAIL;
  1150. sent = 0;
  1151. }
  1152. ssent += sent;
  1153. len -= sent;
  1154. }
  1155. pool->cgminer_pool_stats.times_sent++;
  1156. pool->cgminer_pool_stats.bytes_sent += ssent;
  1157. total_bytes_xfer += ssent;
  1158. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1159. return SEND_OK;
  1160. }
  1161. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1162. {
  1163. enum send_ret ret = SEND_INACTIVE;
  1164. if (opt_protocol)
  1165. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1166. mutex_lock(&pool->stratum_lock);
  1167. if (pool->stratum_active)
  1168. ret = __stratum_send(pool, s, len);
  1169. mutex_unlock(&pool->stratum_lock);
  1170. /* This is to avoid doing applog under stratum_lock */
  1171. switch (ret) {
  1172. default:
  1173. case SEND_OK:
  1174. break;
  1175. case SEND_SELECTFAIL:
  1176. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1177. suspend_stratum(pool);
  1178. break;
  1179. case SEND_SENDFAIL:
  1180. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1181. suspend_stratum(pool);
  1182. break;
  1183. case SEND_INACTIVE:
  1184. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1185. break;
  1186. }
  1187. return (ret == SEND_OK);
  1188. }
  1189. static bool socket_full(struct pool *pool, bool wait)
  1190. {
  1191. SOCKETTYPE sock = pool->sock;
  1192. struct timeval timeout;
  1193. fd_set rd;
  1194. FD_ZERO(&rd);
  1195. FD_SET(sock, &rd);
  1196. timeout.tv_usec = 0;
  1197. if (wait)
  1198. timeout.tv_sec = 60;
  1199. else
  1200. timeout.tv_sec = 1;
  1201. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1202. return true;
  1203. return false;
  1204. }
  1205. /* Check to see if Santa's been good to you */
  1206. bool sock_full(struct pool *pool)
  1207. {
  1208. if (strlen(pool->sockbuf))
  1209. return true;
  1210. return (socket_full(pool, false));
  1211. }
  1212. static void clear_sockbuf(struct pool *pool)
  1213. {
  1214. strcpy(pool->sockbuf, "");
  1215. }
  1216. static void clear_sock(struct pool *pool)
  1217. {
  1218. ssize_t n;
  1219. mutex_lock(&pool->stratum_lock);
  1220. do {
  1221. if (pool->sock)
  1222. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1223. else
  1224. n = 0;
  1225. } while (n > 0);
  1226. mutex_unlock(&pool->stratum_lock);
  1227. clear_sockbuf(pool);
  1228. }
  1229. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1230. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1231. * and zeroing the new memory */
  1232. static void recalloc_sock(struct pool *pool, size_t len)
  1233. {
  1234. size_t old, new;
  1235. old = strlen(pool->sockbuf);
  1236. new = old + len + 1;
  1237. if (new < pool->sockbuf_size)
  1238. return;
  1239. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1240. // Avoid potentially recursive locking
  1241. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1242. pool->sockbuf = realloc(pool->sockbuf, new);
  1243. if (!pool->sockbuf)
  1244. quit(1, "Failed to realloc pool sockbuf in recalloc_sock");
  1245. memset(pool->sockbuf + old, 0, new - old);
  1246. pool->sockbuf_size = new;
  1247. }
  1248. /* Peeks at a socket to find the first end of line and then reads just that
  1249. * from the socket and returns that as a malloced char */
  1250. char *recv_line(struct pool *pool)
  1251. {
  1252. ssize_t len, buflen;
  1253. char *tok, *sret = NULL;
  1254. if (!strstr(pool->sockbuf, "\n")) {
  1255. struct timeval rstart, now;
  1256. cgtime(&rstart);
  1257. if (!socket_full(pool, true)) {
  1258. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1259. goto out;
  1260. }
  1261. do {
  1262. char s[RBUFSIZE];
  1263. size_t slen;
  1264. ssize_t n;
  1265. memset(s, 0, RBUFSIZE);
  1266. n = recv(pool->sock, s, RECVSIZE, 0);
  1267. if (!n) {
  1268. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1269. suspend_stratum(pool);
  1270. break;
  1271. }
  1272. if (n < 0) {
  1273. //Save errno from being overweitten bei socket_ commands
  1274. int socket_recv_errno;
  1275. socket_recv_errno = SOCKERR;
  1276. if (!sock_blocks() || !socket_full(pool, true)) {
  1277. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %s", bfg_strerror(socket_recv_errno, BST_SOCKET));
  1278. suspend_stratum(pool);
  1279. break;
  1280. }
  1281. } else {
  1282. slen = strlen(s);
  1283. recalloc_sock(pool, slen);
  1284. strcat(pool->sockbuf, s);
  1285. }
  1286. cgtime(&now);
  1287. } while (tdiff(&now, &rstart) < 60 && !strstr(pool->sockbuf, "\n"));
  1288. }
  1289. buflen = strlen(pool->sockbuf);
  1290. tok = strtok(pool->sockbuf, "\n");
  1291. if (!tok) {
  1292. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1293. goto out;
  1294. }
  1295. sret = strdup(tok);
  1296. len = strlen(sret);
  1297. /* Copy what's left in the buffer after the \n, including the
  1298. * terminating \0 */
  1299. if (buflen > len + 1)
  1300. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1301. else
  1302. strcpy(pool->sockbuf, "");
  1303. pool->cgminer_pool_stats.times_received++;
  1304. pool->cgminer_pool_stats.bytes_received += len;
  1305. total_bytes_xfer += len;
  1306. pool->cgminer_pool_stats.net_bytes_received += len;
  1307. out:
  1308. if (!sret)
  1309. clear_sock(pool);
  1310. else if (opt_protocol)
  1311. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1312. return sret;
  1313. }
  1314. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1315. * flag, but this is compatible with 2.0. */
  1316. char *json_dumps_ANY(json_t *json, size_t flags)
  1317. {
  1318. switch (json_typeof(json))
  1319. {
  1320. case JSON_ARRAY:
  1321. case JSON_OBJECT:
  1322. return json_dumps(json, flags);
  1323. default:
  1324. break;
  1325. }
  1326. char *rv;
  1327. #ifdef JSON_ENCODE_ANY
  1328. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1329. if (rv)
  1330. return rv;
  1331. #endif
  1332. json_t *tmp = json_array();
  1333. char *s;
  1334. int i;
  1335. size_t len;
  1336. if (!tmp)
  1337. quit(1, "json_dumps_ANY failed to allocate json array");
  1338. if (json_array_append(tmp, json))
  1339. quit(1, "json_dumps_ANY failed to append temporary array");
  1340. s = json_dumps(tmp, flags);
  1341. if (!s)
  1342. return NULL;
  1343. for (i = 0; s[i] != '['; ++i)
  1344. if (unlikely(!(s[i] && isspace(s[i]))))
  1345. quit(1, "json_dumps_ANY failed to find opening bracket in array dump");
  1346. len = strlen(&s[++i]) - 1;
  1347. if (unlikely(s[i+len] != ']'))
  1348. quit(1, "json_dumps_ANY failed to find closing bracket in array dump");
  1349. rv = malloc(len + 1);
  1350. memcpy(rv, &s[i], len);
  1351. rv[len] = '\0';
  1352. free(s);
  1353. json_decref(tmp);
  1354. return rv;
  1355. }
  1356. /* Extracts a string value from a json array with error checking. To be used
  1357. * when the value of the string returned is only examined and not to be stored.
  1358. * See json_array_string below */
  1359. static char *__json_array_string(json_t *val, unsigned int entry)
  1360. {
  1361. json_t *arr_entry;
  1362. if (json_is_null(val))
  1363. return NULL;
  1364. if (!json_is_array(val))
  1365. return NULL;
  1366. if (entry > json_array_size(val))
  1367. return NULL;
  1368. arr_entry = json_array_get(val, entry);
  1369. if (!json_is_string(arr_entry))
  1370. return NULL;
  1371. return (char *)json_string_value(arr_entry);
  1372. }
  1373. /* Creates a freshly malloced dup of __json_array_string */
  1374. static char *json_array_string(json_t *val, unsigned int entry)
  1375. {
  1376. char *buf = __json_array_string(val, entry);
  1377. if (buf)
  1378. return strdup(buf);
  1379. return NULL;
  1380. }
  1381. void stratum_probe_transparency(struct pool *pool)
  1382. {
  1383. // Request transaction data to discourage pools from doing anything shady
  1384. char s[1024];
  1385. int sLen;
  1386. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1387. pool->swork.job_id,
  1388. pool->swork.job_id);
  1389. stratum_send(pool, s, sLen);
  1390. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  1391. cgtime(&pool->swork.tv_transparency);
  1392. pool->swork.transparency_probed = true;
  1393. }
  1394. static bool parse_notify(struct pool *pool, json_t *val)
  1395. {
  1396. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1397. bool clean, ret = false;
  1398. int merkles, i;
  1399. size_t cb1_len, cb2_len;
  1400. json_t *arr;
  1401. arr = json_array_get(val, 4);
  1402. if (!arr || !json_is_array(arr))
  1403. goto out;
  1404. merkles = json_array_size(arr);
  1405. for (i = 0; i < merkles; i++)
  1406. if (!json_is_string(json_array_get(arr, i)))
  1407. goto out;
  1408. prev_hash = __json_array_string(val, 1);
  1409. coinbase1 = __json_array_string(val, 2);
  1410. coinbase2 = __json_array_string(val, 3);
  1411. bbversion = __json_array_string(val, 5);
  1412. nbit = __json_array_string(val, 6);
  1413. ntime = __json_array_string(val, 7);
  1414. clean = json_is_true(json_array_get(val, 8));
  1415. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  1416. goto out;
  1417. job_id = json_array_string(val, 0);
  1418. if (!job_id)
  1419. goto out;
  1420. cg_wlock(&pool->data_lock);
  1421. free(pool->swork.job_id);
  1422. pool->swork.job_id = job_id;
  1423. pool->submit_old = !clean;
  1424. pool->swork.clean = true;
  1425. hex2bin(&pool->swork.header1[0], bbversion, 4);
  1426. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  1427. hex2bin(&pool->swork.ntime[0], ntime, 4);
  1428. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  1429. cb1_len = strlen(coinbase1) / 2;
  1430. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  1431. cb2_len = strlen(coinbase2) / 2;
  1432. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->n2size + cb2_len);
  1433. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  1434. hex2bin(coinbase, coinbase1, cb1_len);
  1435. hex2bin(&coinbase[cb1_len], pool->nonce1, pool->n1_len);
  1436. // NOTE: gap for nonce2, filled at work generation time
  1437. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->n2size], coinbase2, cb2_len);
  1438. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  1439. for (i = 0; i < merkles; i++)
  1440. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  1441. pool->swork.merkles = merkles;
  1442. if (clean)
  1443. pool->nonce2 = 0;
  1444. cg_wunlock(&pool->data_lock);
  1445. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1446. pool->pool_no, job_id);
  1447. if (opt_debug && opt_protocol)
  1448. {
  1449. applog(LOG_DEBUG, "job_id: %s", job_id);
  1450. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1451. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1452. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1453. for (i = 0; i < merkles; i++)
  1454. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  1455. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1456. applog(LOG_DEBUG, "nbit: %s", nbit);
  1457. applog(LOG_DEBUG, "ntime: %s", ntime);
  1458. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1459. }
  1460. /* A notify message is the closest stratum gets to a getwork */
  1461. pool->getwork_requested++;
  1462. total_getworks++;
  1463. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  1464. if (pool->stratum_init)
  1465. stratum_probe_transparency(pool);
  1466. ret = true;
  1467. out:
  1468. return ret;
  1469. }
  1470. static bool parse_diff(struct pool *pool, json_t *val)
  1471. {
  1472. double diff;
  1473. diff = json_number_value(json_array_get(val, 0));
  1474. if (diff == 0)
  1475. return false;
  1476. cg_wlock(&pool->data_lock);
  1477. pool->swork.diff = diff;
  1478. cg_wunlock(&pool->data_lock);
  1479. applog(LOG_DEBUG, "Pool %d stratum bdifficulty set to %f", pool->pool_no, diff);
  1480. return true;
  1481. }
  1482. static bool parse_reconnect(struct pool *pool, json_t *val)
  1483. {
  1484. char *url, *port, address[256];
  1485. memset(address, 0, 255);
  1486. url = (char *)json_string_value(json_array_get(val, 0));
  1487. if (!url)
  1488. url = pool->sockaddr_url;
  1489. port = (char *)json_string_value(json_array_get(val, 1));
  1490. if (!port)
  1491. port = pool->stratum_port;
  1492. sprintf(address, "%s:%s", url, port);
  1493. if (!extract_sockaddr(pool, address))
  1494. return false;
  1495. pool->stratum_url = pool->sockaddr_url;
  1496. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1497. if (!restart_stratum(pool))
  1498. return false;
  1499. return true;
  1500. }
  1501. static bool send_version(struct pool *pool, json_t *val)
  1502. {
  1503. char s[RBUFSIZE], *idstr;
  1504. json_t *id = json_object_get(val, "id");
  1505. if (!(id && !json_is_null(id)))
  1506. return false;
  1507. idstr = json_dumps_ANY(id, 0);
  1508. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1509. free(idstr);
  1510. if (!stratum_send(pool, s, strlen(s)))
  1511. return false;
  1512. return true;
  1513. }
  1514. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  1515. {
  1516. char *msg;
  1517. char s[RBUFSIZE], *idstr;
  1518. json_t *id = json_object_get(val, "id");
  1519. msg = json_array_string(params, 0);
  1520. if (likely(msg))
  1521. {
  1522. free(pool->admin_msg);
  1523. pool->admin_msg = msg;
  1524. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  1525. }
  1526. if (!(id && !json_is_null(id)))
  1527. return true;
  1528. idstr = json_dumps_ANY(id, 0);
  1529. if (likely(msg))
  1530. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  1531. else
  1532. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  1533. free(idstr);
  1534. if (!stratum_send(pool, s, strlen(s)))
  1535. return false;
  1536. return true;
  1537. }
  1538. bool parse_method(struct pool *pool, char *s)
  1539. {
  1540. json_t *val = NULL, *method, *err_val, *params;
  1541. json_error_t err;
  1542. bool ret = false;
  1543. char *buf;
  1544. if (!s)
  1545. goto out;
  1546. val = JSON_LOADS(s, &err);
  1547. if (!val) {
  1548. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1549. goto out;
  1550. }
  1551. method = json_object_get(val, "method");
  1552. if (!method)
  1553. goto out;
  1554. err_val = json_object_get(val, "error");
  1555. params = json_object_get(val, "params");
  1556. if (err_val && !json_is_null(err_val)) {
  1557. char *ss;
  1558. if (err_val)
  1559. ss = json_dumps(err_val, JSON_INDENT(3));
  1560. else
  1561. ss = strdup("(unknown reason)");
  1562. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1563. free(ss);
  1564. goto out;
  1565. }
  1566. buf = (char *)json_string_value(method);
  1567. if (!buf)
  1568. goto out;
  1569. if (!strncasecmp(buf, "mining.notify", 13)) {
  1570. if (parse_notify(pool, params))
  1571. pool->stratum_notify = ret = true;
  1572. else
  1573. pool->stratum_notify = ret = false;
  1574. goto out;
  1575. }
  1576. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1577. ret = true;
  1578. goto out;
  1579. }
  1580. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1581. ret = true;
  1582. goto out;
  1583. }
  1584. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1585. ret = true;
  1586. goto out;
  1587. }
  1588. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  1589. ret = true;
  1590. goto out;
  1591. }
  1592. out:
  1593. if (val)
  1594. json_decref(val);
  1595. return ret;
  1596. }
  1597. extern bool parse_stratum_response(struct pool *, char *s);
  1598. bool auth_stratum(struct pool *pool)
  1599. {
  1600. json_t *val = NULL, *res_val, *err_val;
  1601. char s[RBUFSIZE], *sret = NULL;
  1602. json_error_t err;
  1603. bool ret = false;
  1604. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1605. pool->rpc_user, pool->rpc_pass);
  1606. if (!stratum_send(pool, s, strlen(s)))
  1607. goto out;
  1608. /* Parse all data in the queue and anything left should be auth */
  1609. while (42) {
  1610. sret = recv_line(pool);
  1611. if (!sret)
  1612. goto out;
  1613. if (parse_method(pool, sret))
  1614. free(sret);
  1615. else
  1616. break;
  1617. }
  1618. val = JSON_LOADS(sret, &err);
  1619. free(sret);
  1620. res_val = json_object_get(val, "result");
  1621. err_val = json_object_get(val, "error");
  1622. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1623. char *ss;
  1624. if (err_val)
  1625. ss = json_dumps(err_val, JSON_INDENT(3));
  1626. else
  1627. ss = strdup("(unknown reason)");
  1628. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1629. free(ss);
  1630. goto out;
  1631. }
  1632. ret = true;
  1633. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1634. pool->probed = true;
  1635. successful_connect = true;
  1636. out:
  1637. if (val)
  1638. json_decref(val);
  1639. if (pool->stratum_notify)
  1640. stratum_probe_transparency(pool);
  1641. return ret;
  1642. }
  1643. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1644. {
  1645. struct pool *pool = clientp;
  1646. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1647. pool->sock = sck;
  1648. return sck;
  1649. }
  1650. static bool setup_stratum_curl(struct pool *pool)
  1651. {
  1652. char curl_err_str[CURL_ERROR_SIZE];
  1653. CURL *curl = NULL;
  1654. char s[RBUFSIZE];
  1655. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1656. mutex_lock(&pool->stratum_lock);
  1657. timer_unset(&pool->swork.tv_transparency);
  1658. pool->stratum_active = false;
  1659. pool->stratum_notify = false;
  1660. pool->swork.transparency_probed = false;
  1661. if (pool->stratum_curl)
  1662. curl_easy_cleanup(pool->stratum_curl);
  1663. pool->stratum_curl = curl_easy_init();
  1664. if (unlikely(!pool->stratum_curl))
  1665. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1666. if (pool->sockbuf)
  1667. pool->sockbuf[0] = '\0';
  1668. mutex_unlock(&pool->stratum_lock);
  1669. curl = pool->stratum_curl;
  1670. if (!pool->sockbuf) {
  1671. pool->sockbuf = calloc(RBUFSIZE, 1);
  1672. if (!pool->sockbuf)
  1673. quit(1, "Failed to calloc pool sockbuf in initiate_stratum");
  1674. pool->sockbuf_size = RBUFSIZE;
  1675. }
  1676. /* Create a http url for use with curl */
  1677. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1678. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1679. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1680. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1681. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1682. curl_easy_setopt(curl, CURLOPT_URL, s);
  1683. if (!opt_delaynet)
  1684. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1685. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1686. * to enable it */
  1687. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  1688. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  1689. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1690. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  1691. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  1692. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  1693. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1694. if (pool->rpc_proxy) {
  1695. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1696. } else if (opt_socks_proxy) {
  1697. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1698. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1699. }
  1700. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1701. pool->sock = INVSOCK;
  1702. if (curl_easy_perform(curl)) {
  1703. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1704. curl_easy_cleanup(curl);
  1705. pool->stratum_curl = NULL;
  1706. return false;
  1707. }
  1708. if (pool->sock == INVSOCK)
  1709. {
  1710. pool->stratum_curl = NULL;
  1711. curl_easy_cleanup(curl);
  1712. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  1713. return false;
  1714. }
  1715. keep_sockalive(pool->sock);
  1716. pool->cgminer_pool_stats.times_sent++;
  1717. pool->cgminer_pool_stats.times_received++;
  1718. return true;
  1719. }
  1720. static char *get_sessionid(json_t *val)
  1721. {
  1722. char *ret = NULL;
  1723. json_t *arr_val;
  1724. int arrsize, i;
  1725. arr_val = json_array_get(val, 0);
  1726. if (!arr_val || !json_is_array(arr_val))
  1727. goto out;
  1728. arrsize = json_array_size(arr_val);
  1729. for (i = 0; i < arrsize; i++) {
  1730. json_t *arr = json_array_get(arr_val, i);
  1731. char *notify;
  1732. if (!arr | !json_is_array(arr))
  1733. break;
  1734. notify = __json_array_string(arr, 0);
  1735. if (!notify)
  1736. continue;
  1737. if (!strncasecmp(notify, "mining.notify", 13)) {
  1738. ret = json_array_string(arr, 1);
  1739. break;
  1740. }
  1741. }
  1742. out:
  1743. return ret;
  1744. }
  1745. void suspend_stratum(struct pool *pool)
  1746. {
  1747. clear_sockbuf(pool);
  1748. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1749. mutex_lock(&pool->stratum_lock);
  1750. pool->stratum_active = pool->stratum_notify = false;
  1751. if (pool->stratum_curl) {
  1752. curl_easy_cleanup(pool->stratum_curl);
  1753. }
  1754. pool->stratum_curl = NULL;
  1755. pool->sock = INVSOCK;
  1756. mutex_unlock(&pool->stratum_lock);
  1757. }
  1758. bool initiate_stratum(struct pool *pool)
  1759. {
  1760. bool ret = false, recvd = false, noresume = false, sockd = false;
  1761. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1762. json_t *val = NULL, *res_val, *err_val;
  1763. json_error_t err;
  1764. int n2size;
  1765. resend:
  1766. if (!setup_stratum_curl(pool)) {
  1767. sockd = false;
  1768. goto out;
  1769. }
  1770. sockd = true;
  1771. if (noresume) {
  1772. /* Get rid of any crap lying around if we're resending */
  1773. clear_sock(pool);
  1774. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1775. } else {
  1776. if (pool->sessionid)
  1777. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1778. else
  1779. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1780. }
  1781. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1782. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1783. goto out;
  1784. }
  1785. if (!socket_full(pool, true)) {
  1786. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1787. goto out;
  1788. }
  1789. sret = recv_line(pool);
  1790. if (!sret)
  1791. goto out;
  1792. recvd = true;
  1793. val = JSON_LOADS(sret, &err);
  1794. free(sret);
  1795. if (!val) {
  1796. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1797. goto out;
  1798. }
  1799. res_val = json_object_get(val, "result");
  1800. err_val = json_object_get(val, "error");
  1801. if (!res_val || json_is_null(res_val) ||
  1802. (err_val && !json_is_null(err_val))) {
  1803. char *ss;
  1804. if (err_val)
  1805. ss = json_dumps(err_val, JSON_INDENT(3));
  1806. else
  1807. ss = strdup("(unknown reason)");
  1808. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1809. free(ss);
  1810. goto out;
  1811. }
  1812. sessionid = get_sessionid(res_val);
  1813. if (!sessionid)
  1814. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1815. nonce1 = json_array_string(res_val, 1);
  1816. if (!nonce1) {
  1817. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1818. free(sessionid);
  1819. goto out;
  1820. }
  1821. n2size = json_integer_value(json_array_get(res_val, 2));
  1822. if (!n2size) {
  1823. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1824. free(sessionid);
  1825. free(nonce1);
  1826. goto out;
  1827. }
  1828. cg_wlock(&pool->data_lock);
  1829. free(pool->sessionid);
  1830. pool->sessionid = sessionid;
  1831. free(pool->nonce1);
  1832. pool->nonce1 = nonce1;
  1833. pool->n1_len = strlen(nonce1) / 2;
  1834. pool->n2size = n2size;
  1835. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  1836. #ifdef WORDS_BIGENDIAN
  1837. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  1838. #endif
  1839. cg_wunlock(&pool->data_lock);
  1840. if (sessionid)
  1841. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1842. ret = true;
  1843. out:
  1844. if (val)
  1845. json_decref(val);
  1846. if (ret) {
  1847. if (!pool->stratum_url)
  1848. pool->stratum_url = pool->sockaddr_url;
  1849. pool->stratum_active = true;
  1850. pool->swork.diff = 1;
  1851. if (opt_protocol) {
  1852. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1853. pool->pool_no, pool->nonce1, pool->n2size);
  1854. }
  1855. } else {
  1856. if (recvd && !noresume) {
  1857. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1858. noresume = true;
  1859. goto resend;
  1860. }
  1861. applog(LOG_DEBUG, "Initiate stratum failed");
  1862. if (sockd)
  1863. suspend_stratum(pool);
  1864. }
  1865. return ret;
  1866. }
  1867. bool restart_stratum(struct pool *pool)
  1868. {
  1869. if (pool->stratum_active)
  1870. suspend_stratum(pool);
  1871. if (!initiate_stratum(pool))
  1872. return false;
  1873. if (!auth_stratum(pool))
  1874. return false;
  1875. return true;
  1876. }
  1877. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1878. {
  1879. dev->device_last_not_well = time(NULL);
  1880. cgtime(&dev->tv_device_last_not_well);
  1881. dev->device_not_well_reason = reason;
  1882. switch (reason) {
  1883. case REASON_THREAD_FAIL_INIT:
  1884. dev->thread_fail_init_count++;
  1885. break;
  1886. case REASON_THREAD_ZERO_HASH:
  1887. dev->thread_zero_hash_count++;
  1888. break;
  1889. case REASON_THREAD_FAIL_QUEUE:
  1890. dev->thread_fail_queue_count++;
  1891. break;
  1892. case REASON_DEV_SICK_IDLE_60:
  1893. dev->dev_sick_idle_60_count++;
  1894. break;
  1895. case REASON_DEV_DEAD_IDLE_600:
  1896. dev->dev_dead_idle_600_count++;
  1897. break;
  1898. case REASON_DEV_NOSTART:
  1899. dev->dev_nostart_count++;
  1900. break;
  1901. case REASON_DEV_OVER_HEAT:
  1902. dev->dev_over_heat_count++;
  1903. break;
  1904. case REASON_DEV_THERMAL_CUTOFF:
  1905. dev->dev_thermal_cutoff_count++;
  1906. break;
  1907. case REASON_DEV_COMMS_ERROR:
  1908. dev->dev_comms_error_count++;
  1909. break;
  1910. case REASON_DEV_THROTTLE:
  1911. dev->dev_throttle_count++;
  1912. break;
  1913. }
  1914. }
  1915. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1916. void *realloc_strcat(char *ptr, char *s)
  1917. {
  1918. size_t old = strlen(ptr), len = strlen(s);
  1919. char *ret;
  1920. if (!len)
  1921. return ptr;
  1922. len += old + 1;
  1923. align_len(&len);
  1924. ret = malloc(len);
  1925. if (unlikely(!ret))
  1926. quit(1, "Failed to malloc in realloc_strcat");
  1927. sprintf(ret, "%s%s", ptr, s);
  1928. free(ptr);
  1929. return ret;
  1930. }
  1931. static
  1932. bool sanechars[] = {
  1933. false, false, false, false, false, false, false, false,
  1934. false, false, false, false, false, false, false, false,
  1935. false, false, false, false, false, false, false, false,
  1936. false, false, false, false, false, false, false, false,
  1937. false, false, false, false, false, false, false, false,
  1938. false, false, false, false, false, false, false, false,
  1939. true , true , true , true , true , true , true , true ,
  1940. true , true , false, false, false, false, false, false,
  1941. false, true , true , true , true , true , true , true ,
  1942. true , true , true , true , true , true , true , true ,
  1943. true , true , true , true , true , true , true , true ,
  1944. true , true , true , false, false, false, false, false,
  1945. false, true , true , true , true , true , true , true ,
  1946. true , true , true , true , true , true , true , true ,
  1947. true , true , true , true , true , true , true , true ,
  1948. true , true , true , false, false, false, false, false,
  1949. };
  1950. char *sanestr(char *o, char *s)
  1951. {
  1952. char *rv = o;
  1953. bool br = false;
  1954. for ( ; s[0]; ++s)
  1955. {
  1956. if (sanechars[s[0] & 0x7f])
  1957. {
  1958. if (br)
  1959. {
  1960. br = false;
  1961. if (s[0] >= '0' && s[0] <= '9')
  1962. (o++)[0] = '_';
  1963. }
  1964. (o++)[0] = s[0];
  1965. }
  1966. else
  1967. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  1968. br = true;
  1969. }
  1970. o[0] = '\0';
  1971. return rv;
  1972. }
  1973. void RenameThread(const char* name)
  1974. {
  1975. #if defined(PR_SET_NAME)
  1976. // Only the first 15 characters are used (16 - NUL terminator)
  1977. prctl(PR_SET_NAME, name, 0, 0, 0);
  1978. #elif defined(__APPLE__)
  1979. pthread_setname_np(name);
  1980. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1981. pthread_set_name_np(pthread_self(), name);
  1982. #else
  1983. // Prevent warnings for unused parameters...
  1984. (void)name;
  1985. #endif
  1986. }
  1987. static pthread_key_t key_bfgtls;
  1988. struct bfgtls_data {
  1989. char *bfg_strerror_result;
  1990. size_t bfg_strerror_resultsz;
  1991. #ifdef WIN32
  1992. LPSTR bfg_strerror_socketresult;
  1993. #endif
  1994. };
  1995. static
  1996. struct bfgtls_data *get_bfgtls()
  1997. {
  1998. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  1999. if (bfgtls)
  2000. return bfgtls;
  2001. void *p;
  2002. bfgtls = malloc(sizeof(*bfgtls));
  2003. if (!bfgtls)
  2004. quit(1, "malloc bfgtls failed");
  2005. p = malloc(64);
  2006. if (!p)
  2007. quit(1, "malloc bfg_strerror_result failed");
  2008. *bfgtls = (struct bfgtls_data){
  2009. .bfg_strerror_resultsz = 64,
  2010. .bfg_strerror_result = p,
  2011. };
  2012. if (pthread_setspecific(key_bfgtls, bfgtls))
  2013. quit(1, "pthread_setspecific failed");
  2014. return bfgtls;
  2015. }
  2016. void bfg_init_threadlocal()
  2017. {
  2018. if (pthread_key_create(&key_bfgtls, NULL))
  2019. quit(1, "pthread_key_create failed");
  2020. }
  2021. static
  2022. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  2023. {
  2024. if (minimum <= *bufszp)
  2025. return false;
  2026. while (minimum > *bufszp)
  2027. *bufszp = 2;
  2028. *bufp = realloc(*bufp, *bufszp);
  2029. if (unlikely(!*bufp))
  2030. quit(1, "realloc failed in bfg_grow_buffer");
  2031. return true;
  2032. }
  2033. static
  2034. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  2035. {
  2036. if (!src)
  2037. return NULL;
  2038. const size_t srcsz = strlen(src) + 1;
  2039. bfg_grow_buffer(bufp, bufszp, srcsz);
  2040. memcpy(*bufp, src, srcsz);
  2041. return *bufp;
  2042. }
  2043. // Guaranteed to always return some string (or quit)
  2044. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  2045. {
  2046. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2047. struct bfgtls_data *bfgtls = get_bfgtls();
  2048. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  2049. char ** const bufp = &bfgtls->bfg_strerror_result;
  2050. const char *have = NULL;
  2051. switch (type) {
  2052. case BST_LIBUSB:
  2053. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  2054. #ifdef HAVE_LIBUSB
  2055. # if HAVE_DECL_LIBUSB_ERROR_NAME
  2056. // libusb makes no guarantees for thread-safety or persistence
  2057. mutex_lock(&mutex);
  2058. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  2059. mutex_unlock(&mutex);
  2060. # endif
  2061. #endif
  2062. break;
  2063. case BST_SOCKET:
  2064. {
  2065. #ifdef WIN32
  2066. // Windows has a different namespace for socket errors
  2067. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  2068. if (*msg)
  2069. LocalFree(*msg);
  2070. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  2071. return *msg;
  2072. *msg = NULL;
  2073. break;
  2074. #endif
  2075. }
  2076. // Fallthru on non-WIN32
  2077. case BST_ERRNO:
  2078. {
  2079. #ifdef __STRERROR_S_WORKS
  2080. // FIXME: Not sure how to get this on MingW64
  2081. retry:
  2082. if (likely(!strerror_s(*bufp, *bufszp, e)))
  2083. {
  2084. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  2085. goto retry;
  2086. return *bufp;
  2087. }
  2088. // TODO: XSI strerror_r
  2089. // TODO: GNU strerror_r
  2090. #else
  2091. mutex_lock(&mutex);
  2092. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  2093. mutex_unlock(&mutex);
  2094. #endif
  2095. }
  2096. }
  2097. if (have)
  2098. return *bufp;
  2099. // Failback: Stringify the number
  2100. static const char fmt[] = "%s error #%d", *typestr;
  2101. switch (type) {
  2102. case BST_ERRNO:
  2103. typestr = "System";
  2104. break;
  2105. case BST_SOCKET:
  2106. typestr = "Socket";
  2107. break;
  2108. case BST_LIBUSB:
  2109. typestr = "libusb";
  2110. break;
  2111. default:
  2112. typestr = "Unexpected";
  2113. }
  2114. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  2115. bfg_grow_buffer(bufp, bufszp, sz);
  2116. sprintf(*bufp, fmt, typestr, e);
  2117. return *bufp;
  2118. }
  2119. void notifier_init(notifier_t pipefd)
  2120. {
  2121. #ifdef WIN32
  2122. #define WindowsErrorStr(e) bfg_strerror(e, true)
  2123. SOCKET listener, connecter, acceptor;
  2124. listener = socket(AF_INET, SOCK_STREAM, 0);
  2125. if (listener == INVALID_SOCKET)
  2126. quit(1, "Failed to create listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2127. connecter = socket(AF_INET, SOCK_STREAM, 0);
  2128. if (connecter == INVALID_SOCKET)
  2129. quit(1, "Failed to create connect socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2130. struct sockaddr_in inaddr = {
  2131. .sin_family = AF_INET,
  2132. .sin_addr = {
  2133. .s_addr = htonl(INADDR_LOOPBACK),
  2134. },
  2135. .sin_port = 0,
  2136. };
  2137. {
  2138. char reuse = 1;
  2139. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  2140. }
  2141. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  2142. quit(1, "Failed to bind listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2143. socklen_t inaddr_sz = sizeof(inaddr);
  2144. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  2145. quit(1, "Failed to getsockname in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2146. if (listen(listener, 1) == SOCKET_ERROR)
  2147. quit(1, "Failed to listen in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2148. inaddr.sin_family = AF_INET;
  2149. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2150. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  2151. quit(1, "Failed to connect in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2152. acceptor = accept(listener, NULL, NULL);
  2153. if (acceptor == INVALID_SOCKET)
  2154. quit(1, "Failed to accept in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  2155. closesocket(listener);
  2156. pipefd[0] = connecter;
  2157. pipefd[1] = acceptor;
  2158. #else
  2159. if (pipe(pipefd))
  2160. quit(1, "Failed to create pipe in create_notifier");
  2161. #endif
  2162. }
  2163. void notifier_wake(notifier_t fd)
  2164. {
  2165. if (fd[1] == INVSOCK)
  2166. return;
  2167. #ifdef WIN32
  2168. (void)send(fd[1], "\0", 1, 0);
  2169. #else
  2170. (void)write(fd[1], "\0", 1);
  2171. #endif
  2172. }
  2173. void notifier_read(notifier_t fd)
  2174. {
  2175. char buf[0x10];
  2176. #ifdef WIN32
  2177. (void)recv(fd[0], buf, sizeof(buf), 0);
  2178. #else
  2179. (void)read(fd[0], buf, sizeof(buf));
  2180. #endif
  2181. }
  2182. void notifier_destroy(notifier_t fd)
  2183. {
  2184. #ifdef WIN32
  2185. closesocket(fd[0]);
  2186. closesocket(fd[1]);
  2187. #else
  2188. close(fd[0]);
  2189. close(fd[1]);
  2190. #endif
  2191. fd[0] = fd[1] = INVSOCK;
  2192. }
  2193. void _bytes_alloc_failure(size_t sz)
  2194. {
  2195. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  2196. }