util.c 44 KB

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