util.c 45 KB

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