util.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #define _GNU_SOURCE
  11. #include "config.h"
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <ctype.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include <jansson.h>
  18. #include <curl/curl.h>
  19. #include <time.h>
  20. #include <errno.h>
  21. #include <unistd.h>
  22. #include <sys/types.h>
  23. #ifndef WIN32
  24. # include <sys/socket.h>
  25. # include <netinet/in.h>
  26. # include <netinet/tcp.h>
  27. #else
  28. # include <winsock2.h>
  29. # include <mstcpip.h>
  30. #endif
  31. #include <netdb.h>
  32. #include "miner.h"
  33. #include "elist.h"
  34. #include "compat.h"
  35. #include "util.h"
  36. bool successful_connect = false;
  37. struct timeval nettime;
  38. struct data_buffer {
  39. void *buf;
  40. size_t len;
  41. };
  42. struct upload_buffer {
  43. const void *buf;
  44. size_t len;
  45. };
  46. struct header_info {
  47. char *lp_path;
  48. int rolltime;
  49. char *reason;
  50. char *stratum_url;
  51. bool hadrolltime;
  52. bool canroll;
  53. bool hadexpire;
  54. };
  55. struct tq_ent {
  56. void *data;
  57. struct list_head q_node;
  58. };
  59. static void databuf_free(struct data_buffer *db)
  60. {
  61. if (!db)
  62. return;
  63. free(db->buf);
  64. memset(db, 0, sizeof(*db));
  65. }
  66. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  67. void *user_data)
  68. {
  69. struct data_buffer *db = user_data;
  70. size_t len = size * nmemb;
  71. size_t oldlen, newlen;
  72. void *newmem;
  73. static const unsigned char zero = 0;
  74. oldlen = db->len;
  75. newlen = oldlen + len;
  76. newmem = realloc(db->buf, newlen + 1);
  77. if (!newmem)
  78. return 0;
  79. db->buf = newmem;
  80. db->len = newlen;
  81. memcpy(db->buf + oldlen, ptr, len);
  82. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  83. return len;
  84. }
  85. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  86. void *user_data)
  87. {
  88. struct upload_buffer *ub = user_data;
  89. unsigned int len = size * nmemb;
  90. if (len > ub->len)
  91. len = ub->len;
  92. if (len) {
  93. memcpy(ptr, ub->buf, len);
  94. ub->buf += len;
  95. ub->len -= len;
  96. }
  97. return len;
  98. }
  99. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  100. {
  101. struct header_info *hi = user_data;
  102. size_t remlen, slen, ptrlen = size * nmemb;
  103. char *rem, *val = NULL, *key = NULL;
  104. void *tmp;
  105. val = calloc(1, ptrlen);
  106. key = calloc(1, ptrlen);
  107. if (!key || !val)
  108. goto out;
  109. tmp = memchr(ptr, ':', ptrlen);
  110. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  111. goto out;
  112. slen = tmp - ptr;
  113. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  114. goto out;
  115. memcpy(key, ptr, slen); /* store & nul term key */
  116. key[slen] = 0;
  117. rem = ptr + slen + 1; /* trim value's leading whitespace */
  118. remlen = ptrlen - slen - 1;
  119. while ((remlen > 0) && (isspace(*rem))) {
  120. remlen--;
  121. rem++;
  122. }
  123. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  124. val[remlen] = 0;
  125. while ((*val) && (isspace(val[strlen(val) - 1])))
  126. val[strlen(val) - 1] = 0;
  127. if (!*val) /* skip blank value */
  128. goto out;
  129. if (opt_protocol)
  130. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  131. if (!strcasecmp("X-Roll-Ntime", key)) {
  132. hi->hadrolltime = true;
  133. if (!strncasecmp("N", val, 1))
  134. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  135. else {
  136. hi->canroll = true;
  137. /* Check to see if expire= is supported and if not, set
  138. * the rolltime to the default scantime */
  139. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  140. sscanf(val + 7, "%d", &hi->rolltime);
  141. hi->hadexpire = true;
  142. } else
  143. hi->rolltime = opt_scantime;
  144. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  145. }
  146. }
  147. if (!strcasecmp("X-Long-Polling", key)) {
  148. hi->lp_path = val; /* steal memory reference */
  149. val = NULL;
  150. }
  151. if (!strcasecmp("X-Reject-Reason", key)) {
  152. hi->reason = val; /* steal memory reference */
  153. val = NULL;
  154. }
  155. if (!strcasecmp("X-Stratum", key)) {
  156. hi->stratum_url = val;
  157. val = NULL;
  158. }
  159. out:
  160. free(key);
  161. free(val);
  162. return ptrlen;
  163. }
  164. #ifdef CURL_HAS_SOCKOPT
  165. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  166. curlsocktype __maybe_unused purpose)
  167. {
  168. int tcp_keepidle = 120;
  169. int tcp_keepintvl = 120;
  170. #ifndef WIN32
  171. int keepalive = 1;
  172. int tcp_keepcnt = 5;
  173. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  174. return 1;
  175. # ifdef __linux
  176. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  177. return 1;
  178. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  179. return 1;
  180. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  181. return 1;
  182. # endif /* __linux */
  183. # ifdef __APPLE_CC__
  184. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  185. return 1;
  186. # endif /* __APPLE_CC__ */
  187. #else /* WIN32 */
  188. struct tcp_keepalive vals;
  189. vals.onoff = 1;
  190. vals.keepalivetime = tcp_keepidle * 1000;
  191. vals.keepaliveinterval = tcp_keepintvl * 1000;
  192. DWORD outputBytes;
  193. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  194. return 1;
  195. #endif /* WIN32 */
  196. return 0;
  197. }
  198. #endif
  199. static void last_nettime(struct timeval *last)
  200. {
  201. rd_lock(&netacc_lock);
  202. last->tv_sec = nettime.tv_sec;
  203. last->tv_usec = nettime.tv_usec;
  204. rd_unlock(&netacc_lock);
  205. }
  206. static void set_nettime(void)
  207. {
  208. wr_lock(&netacc_lock);
  209. gettimeofday(&nettime, NULL);
  210. wr_unlock(&netacc_lock);
  211. }
  212. json_t *json_rpc_call(CURL *curl, const char *url,
  213. const char *userpass, const char *rpc_req,
  214. bool probe, bool longpoll, int *rolltime,
  215. struct pool *pool, bool share)
  216. {
  217. long timeout = longpoll ? (60 * 60) : 60;
  218. struct data_buffer all_data = {NULL, 0};
  219. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  220. char len_hdr[64], user_agent_hdr[128];
  221. char curl_err_str[CURL_ERROR_SIZE];
  222. struct curl_slist *headers = NULL;
  223. struct upload_buffer upload_data;
  224. json_t *val, *err_val, *res_val;
  225. bool probing = false;
  226. json_error_t err;
  227. int rc;
  228. memset(&err, 0, sizeof(err));
  229. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  230. if (probe)
  231. probing = !pool->probed;
  232. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  233. #if 0 /* Disable curl debugging since it spews to stderr */
  234. if (opt_protocol)
  235. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  236. #endif
  237. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  238. curl_easy_setopt(curl, CURLOPT_URL, url);
  239. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  240. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  241. /* Shares are staggered already and delays in submission can be costly
  242. * so do not delay them */
  243. if (!opt_delaynet || share)
  244. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  245. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  246. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  247. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  248. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  249. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  250. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  251. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  252. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  253. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  254. if (pool->rpc_proxy) {
  255. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  256. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  257. } else if (opt_socks_proxy) {
  258. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  259. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  260. }
  261. if (userpass) {
  262. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  263. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  264. }
  265. #ifdef CURL_HAS_SOCKOPT
  266. if (longpoll)
  267. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  268. #endif
  269. curl_easy_setopt(curl, CURLOPT_POST, 1);
  270. if (opt_protocol)
  271. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  272. upload_data.buf = rpc_req;
  273. upload_data.len = strlen(rpc_req);
  274. sprintf(len_hdr, "Content-Length: %lu",
  275. (unsigned long) upload_data.len);
  276. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  277. headers = curl_slist_append(headers,
  278. "Content-type: application/json");
  279. headers = curl_slist_append(headers,
  280. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  281. if (likely(global_hashrate)) {
  282. char ghashrate[255];
  283. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  284. headers = curl_slist_append(headers, ghashrate);
  285. }
  286. headers = curl_slist_append(headers, len_hdr);
  287. headers = curl_slist_append(headers, user_agent_hdr);
  288. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  289. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  290. if (opt_delaynet) {
  291. /* Don't delay share submission, but still track the nettime */
  292. if (!share) {
  293. long long now_msecs, last_msecs;
  294. struct timeval now, last;
  295. gettimeofday(&now, NULL);
  296. last_nettime(&last);
  297. now_msecs = (long long)now.tv_sec * 1000;
  298. now_msecs += now.tv_usec / 1000;
  299. last_msecs = (long long)last.tv_sec * 1000;
  300. last_msecs += last.tv_usec / 1000;
  301. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  302. struct timespec rgtp;
  303. rgtp.tv_sec = 0;
  304. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  305. nanosleep(&rgtp, NULL);
  306. }
  307. }
  308. set_nettime();
  309. }
  310. rc = curl_easy_perform(curl);
  311. if (rc) {
  312. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  313. goto err_out;
  314. }
  315. if (!all_data.buf) {
  316. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  317. goto err_out;
  318. }
  319. if (probing) {
  320. pool->probed = true;
  321. /* If X-Long-Polling was found, activate long polling */
  322. if (hi.lp_path) {
  323. if (pool->hdr_path != NULL)
  324. free(pool->hdr_path);
  325. pool->hdr_path = hi.lp_path;
  326. } else
  327. pool->hdr_path = NULL;
  328. if (hi.stratum_url) {
  329. pool->stratum_url = hi.stratum_url;
  330. hi.stratum_url = NULL;
  331. }
  332. } else {
  333. if (hi.lp_path) {
  334. free(hi.lp_path);
  335. hi.lp_path = NULL;
  336. }
  337. if (hi.stratum_url) {
  338. free(hi.stratum_url);
  339. hi.stratum_url = NULL;
  340. }
  341. }
  342. *rolltime = hi.rolltime;
  343. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  344. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  345. pool->cgminer_pool_stats.canroll = hi.canroll;
  346. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  347. val = JSON_LOADS(all_data.buf, &err);
  348. if (!val) {
  349. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  350. if (opt_protocol)
  351. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  352. goto err_out;
  353. }
  354. if (opt_protocol) {
  355. char *s = json_dumps(val, JSON_INDENT(3));
  356. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  357. free(s);
  358. }
  359. /* JSON-RPC valid response returns a non-null 'result',
  360. * and a null 'error'.
  361. */
  362. res_val = json_object_get(val, "result");
  363. err_val = json_object_get(val, "error");
  364. if (!res_val || json_is_null(res_val) ||
  365. (err_val && !json_is_null(err_val))) {
  366. char *s;
  367. if (err_val)
  368. s = json_dumps(err_val, JSON_INDENT(3));
  369. else
  370. s = strdup("(unknown reason)");
  371. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  372. free(s);
  373. goto err_out;
  374. }
  375. if (hi.reason) {
  376. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  377. free(hi.reason);
  378. hi.reason = NULL;
  379. }
  380. successful_connect = true;
  381. databuf_free(&all_data);
  382. curl_slist_free_all(headers);
  383. curl_easy_reset(curl);
  384. return val;
  385. err_out:
  386. databuf_free(&all_data);
  387. curl_slist_free_all(headers);
  388. curl_easy_reset(curl);
  389. if (!successful_connect)
  390. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  391. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  392. return NULL;
  393. }
  394. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  395. static struct {
  396. const char *name;
  397. curl_proxytype proxytype;
  398. } proxynames[] = {
  399. { "http:", CURLPROXY_HTTP },
  400. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  401. { "http0:", CURLPROXY_HTTP_1_0 },
  402. #endif
  403. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  404. { "socks4:", CURLPROXY_SOCKS4 },
  405. #endif
  406. { "socks5:", CURLPROXY_SOCKS5 },
  407. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  408. { "socks4a:", CURLPROXY_SOCKS4A },
  409. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  410. #endif
  411. { NULL, 0 }
  412. };
  413. #endif
  414. const char *proxytype(curl_proxytype proxytype)
  415. {
  416. int i;
  417. for (i = 0; proxynames[i].name; i++)
  418. if (proxynames[i].proxytype == proxytype)
  419. return proxynames[i].name;
  420. return "invalid";
  421. }
  422. char *get_proxy(char *url, struct pool *pool)
  423. {
  424. pool->rpc_proxy = NULL;
  425. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  426. char *split;
  427. int plen, len, i;
  428. for (i = 0; proxynames[i].name; i++) {
  429. plen = strlen(proxynames[i].name);
  430. if (strncmp(url, proxynames[i].name, plen) == 0) {
  431. if (!(split = strchr(url, '|')))
  432. return url;
  433. *split = '\0';
  434. len = split - url;
  435. pool->rpc_proxy = malloc(1 + len - plen);
  436. if (!(pool->rpc_proxy))
  437. quit(1, "Failed to malloc rpc_proxy");
  438. strcpy(pool->rpc_proxy, url + plen);
  439. pool->rpc_proxytype = proxynames[i].proxytype;
  440. url = split + 1;
  441. break;
  442. }
  443. }
  444. #endif
  445. return url;
  446. }
  447. char *bin2hex(const unsigned char *p, size_t len)
  448. {
  449. char *s = malloc((len * 2) + 1);
  450. unsigned int i;
  451. if (!s)
  452. return NULL;
  453. for (i = 0; i < len; i++)
  454. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  455. return s;
  456. }
  457. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  458. {
  459. while (*hexstr && len) {
  460. char hex_byte[3];
  461. unsigned int v;
  462. if (!hexstr[1]) {
  463. applog(LOG_ERR, "hex2bin str truncated");
  464. return false;
  465. }
  466. hex_byte[0] = hexstr[0];
  467. hex_byte[1] = hexstr[1];
  468. hex_byte[2] = 0;
  469. if (sscanf(hex_byte, "%x", &v) != 1) {
  470. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  471. return false;
  472. }
  473. *p = (unsigned char) v;
  474. p++;
  475. hexstr += 2;
  476. len--;
  477. }
  478. return (len == 0 && *hexstr == 0) ? true : false;
  479. }
  480. bool fulltest(const unsigned char *hash, const unsigned char *target)
  481. {
  482. unsigned char hash_swap[32], target_swap[32];
  483. uint32_t *hash32 = (uint32_t *) hash_swap;
  484. uint32_t *target32 = (uint32_t *) target_swap;
  485. char *hash_str, *target_str;
  486. bool rc = true;
  487. int i;
  488. swap256(hash_swap, hash);
  489. swap256(target_swap, target);
  490. for (i = 0; i < 32/4; i++) {
  491. uint32_t h32tmp = swab32(hash32[i]);
  492. uint32_t t32tmp = target32[i];
  493. target32[i] = swab32(target32[i]); /* for printing */
  494. if (h32tmp > t32tmp) {
  495. rc = false;
  496. break;
  497. }
  498. if (h32tmp < t32tmp) {
  499. rc = true;
  500. break;
  501. }
  502. }
  503. if (opt_debug) {
  504. hash_str = bin2hex(hash_swap, 32);
  505. target_str = bin2hex(target_swap, 32);
  506. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  507. hash_str,
  508. target_str,
  509. rc ? "YES (hash < target)" :
  510. "no (false positive; hash > target)");
  511. free(hash_str);
  512. free(target_str);
  513. }
  514. return rc;
  515. }
  516. struct thread_q *tq_new(void)
  517. {
  518. struct thread_q *tq;
  519. tq = calloc(1, sizeof(*tq));
  520. if (!tq)
  521. return NULL;
  522. INIT_LIST_HEAD(&tq->q);
  523. pthread_mutex_init(&tq->mutex, NULL);
  524. pthread_cond_init(&tq->cond, NULL);
  525. return tq;
  526. }
  527. void tq_free(struct thread_q *tq)
  528. {
  529. struct tq_ent *ent, *iter;
  530. if (!tq)
  531. return;
  532. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  533. list_del(&ent->q_node);
  534. free(ent);
  535. }
  536. pthread_cond_destroy(&tq->cond);
  537. pthread_mutex_destroy(&tq->mutex);
  538. memset(tq, 0, sizeof(*tq)); /* poison */
  539. free(tq);
  540. }
  541. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  542. {
  543. mutex_lock(&tq->mutex);
  544. tq->frozen = frozen;
  545. pthread_cond_signal(&tq->cond);
  546. mutex_unlock(&tq->mutex);
  547. }
  548. void tq_freeze(struct thread_q *tq)
  549. {
  550. tq_freezethaw(tq, true);
  551. }
  552. void tq_thaw(struct thread_q *tq)
  553. {
  554. tq_freezethaw(tq, false);
  555. }
  556. bool tq_push(struct thread_q *tq, void *data)
  557. {
  558. struct tq_ent *ent;
  559. bool rc = true;
  560. ent = calloc(1, sizeof(*ent));
  561. if (!ent)
  562. return false;
  563. ent->data = data;
  564. INIT_LIST_HEAD(&ent->q_node);
  565. mutex_lock(&tq->mutex);
  566. if (!tq->frozen) {
  567. list_add_tail(&ent->q_node, &tq->q);
  568. } else {
  569. free(ent);
  570. rc = false;
  571. }
  572. pthread_cond_signal(&tq->cond);
  573. mutex_unlock(&tq->mutex);
  574. return rc;
  575. }
  576. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  577. {
  578. struct tq_ent *ent;
  579. void *rval = NULL;
  580. int rc;
  581. mutex_lock(&tq->mutex);
  582. if (!list_empty(&tq->q))
  583. goto pop;
  584. if (abstime)
  585. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  586. else
  587. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  588. if (rc)
  589. goto out;
  590. if (list_empty(&tq->q))
  591. goto out;
  592. pop:
  593. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  594. rval = ent->data;
  595. list_del(&ent->q_node);
  596. free(ent);
  597. out:
  598. mutex_unlock(&tq->mutex);
  599. return rval;
  600. }
  601. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  602. {
  603. return pthread_create(&thr->pth, attr, start, arg);
  604. }
  605. void thr_info_freeze(struct thr_info *thr)
  606. {
  607. struct tq_ent *ent, *iter;
  608. struct thread_q *tq;
  609. if (!thr)
  610. return;
  611. tq = thr->q;
  612. if (!tq)
  613. return;
  614. mutex_lock(&tq->mutex);
  615. tq->frozen = true;
  616. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  617. list_del(&ent->q_node);
  618. free(ent);
  619. }
  620. mutex_unlock(&tq->mutex);
  621. }
  622. void thr_info_cancel(struct thr_info *thr)
  623. {
  624. if (!thr)
  625. return;
  626. if (PTH(thr) != 0L) {
  627. pthread_cancel(thr->pth);
  628. PTH(thr) = 0L;
  629. }
  630. }
  631. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  632. * on SMP machines */
  633. void nmsleep(unsigned int msecs)
  634. {
  635. struct timespec twait, tleft;
  636. int ret;
  637. ldiv_t d;
  638. d = ldiv(msecs, 1000);
  639. tleft.tv_sec = d.quot;
  640. tleft.tv_nsec = d.rem * 1000000;
  641. do {
  642. twait.tv_sec = tleft.tv_sec;
  643. twait.tv_nsec = tleft.tv_nsec;
  644. ret = nanosleep(&twait, &tleft);
  645. } while (ret == -1 && errno == EINTR);
  646. }
  647. /* Returns the microseconds difference between end and start times as a double */
  648. double us_tdiff(struct timeval *end, struct timeval *start)
  649. {
  650. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  651. }
  652. /* Returns the seconds difference between end and start times as a double */
  653. double tdiff(struct timeval *end, struct timeval *start)
  654. {
  655. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  656. }
  657. bool extract_sockaddr(struct pool *pool, char *url)
  658. {
  659. char *url_begin, *url_end, *port_start;
  660. char *url_address, *port;
  661. struct addrinfo hints, *res;
  662. int url_len, port_len = 0;
  663. url_begin = strstr(url, "//");
  664. if (!url_begin)
  665. url_begin = url;
  666. else
  667. url_begin += 2;
  668. url_end = strstr(url_begin, ":");
  669. if (url_end) {
  670. url_len = url_end - url_begin;
  671. port_len = strlen(url_begin) - url_len - 1;
  672. if (port_len < 1)
  673. return false;
  674. port_start = url_end + 1;
  675. } else
  676. url_len = strlen(url_begin);
  677. if (url_len < 1)
  678. return false;
  679. url_address = alloca(url_len + 1);
  680. sprintf(url_address, "%.*s", url_len, url_begin);
  681. if (port_len) {
  682. port = alloca(port_len + 1);
  683. sprintf(port, "%.*s", port_len, port_start);
  684. } else {
  685. port = alloca(4);
  686. strcpy(port, "80");
  687. }
  688. memset(&hints, 0, sizeof(struct addrinfo));
  689. hints.ai_family = AF_UNSPEC;
  690. hints.ai_socktype = SOCK_STREAM;
  691. hints.ai_protocol = IPPROTO_TCP;
  692. if (getaddrinfo(url_address, port, &hints, &res)) {
  693. applog(LOG_DEBUG, "Failed to extract sock addr");
  694. return false;
  695. }
  696. pool->server = (struct sockaddr_in *)res->ai_addr;
  697. pool->stratum_url = strdup(url_address);
  698. return true;
  699. }
  700. /* Send a single command across a socket, appending \n to it */
  701. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  702. {
  703. SOCKETTYPE sock = pool->sock;
  704. ssize_t sent = 0;
  705. bool ret = false;
  706. if (opt_protocol)
  707. applog(LOG_DEBUG, "SEND: %s", s);
  708. strcat(s, "\n");
  709. len++;
  710. mutex_lock(&pool->pool_lock);
  711. while (len > 0 ) {
  712. sent = send(sock, s + sent, len, 0);
  713. if (SOCKETFAIL(sent)) {
  714. ret = false;
  715. goto out_unlock;
  716. }
  717. len -= sent;
  718. }
  719. ret = true;
  720. fsync(sock);
  721. out_unlock:
  722. mutex_unlock(&pool->pool_lock);
  723. return ret;;
  724. }
  725. #define RECVSIZE 8192
  726. static void clear_sock(SOCKETTYPE sock)
  727. {
  728. char *s = alloca(RECVSIZE);
  729. recv(sock, s, RECVSIZE, MSG_DONTWAIT);
  730. }
  731. /* Check to see if Santa's been good to you */
  732. static bool sock_full(SOCKETTYPE sock, bool wait)
  733. {
  734. struct timeval timeout;
  735. fd_set rd;
  736. FD_ZERO(&rd);
  737. FD_SET(sock, &rd);
  738. timeout.tv_usec = 0;
  739. if (wait)
  740. timeout.tv_sec = 60;
  741. else
  742. timeout.tv_sec = 0;
  743. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  744. return true;
  745. return false;
  746. }
  747. /* Peeks at a socket to find the first end of line and then reads just that
  748. * from the socket and returns that as a malloced char */
  749. char *recv_line(SOCKETTYPE sock)
  750. {
  751. char *sret = NULL, *s, c;
  752. ssize_t offset = 0;
  753. s = alloca(RECVSIZE);
  754. if (SOCKETFAIL(recv(sock, s, RECVSIZE, MSG_PEEK))) {
  755. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  756. goto out;
  757. }
  758. sret = strtok(s, "\n");
  759. if (!sret) {
  760. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  761. goto out;
  762. }
  763. do {
  764. read(sock, &c, 1);
  765. memcpy(s + offset++, &c, 1);
  766. } while (strncmp(&c, "\n", 1));
  767. sret = strdup(s);
  768. strcpy(sret + offset - 1, "\0");
  769. out:
  770. if (!sret)
  771. clear_sock(sock);
  772. else if (opt_protocol)
  773. applog(LOG_DEBUG, "RECVD: %s", sret);
  774. return sret;
  775. }
  776. /* Extracts a string value from a json array with error checking. To be used
  777. * when the value of the string returned is only examined and not to be stored.
  778. * See json_array_string below */
  779. static char *__json_array_string(json_t *val, unsigned int entry)
  780. {
  781. json_t *arr_entry;
  782. if (json_is_null(val))
  783. return NULL;
  784. if (!json_is_array(val))
  785. return NULL;
  786. if (entry > json_array_size(val))
  787. return NULL;
  788. arr_entry = json_array_get(val, entry);
  789. if (!json_is_string(arr_entry))
  790. return NULL;
  791. return (char *)json_string_value(arr_entry);
  792. }
  793. /* Creates a freshly malloced dup of __json_array_string */
  794. static char *json_array_string(json_t *val, unsigned int entry)
  795. {
  796. char *buf = __json_array_string(val, entry);
  797. if (buf)
  798. return strdup(buf);
  799. return NULL;
  800. }
  801. static bool parse_notify(struct pool *pool, json_t *val)
  802. {
  803. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  804. int merkles, i;
  805. json_t *arr;
  806. bool clean;
  807. arr = json_array_get(val, 4);
  808. if (!arr || !json_is_array(arr))
  809. return false;
  810. merkles = json_array_size(arr);
  811. job_id = json_array_string(val, 0);
  812. prev_hash = json_array_string(val, 1);
  813. coinbase1 = json_array_string(val, 2);
  814. coinbase2 = json_array_string(val, 3);
  815. bbversion = json_array_string(val, 5);
  816. nbit = json_array_string(val, 6);
  817. ntime = json_array_string(val, 7);
  818. clean = json_is_true(json_array_get(val, 8));
  819. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  820. /* Annoying but we must not leak memory */
  821. if (job_id)
  822. free(job_id);
  823. if (prev_hash)
  824. free(prev_hash);
  825. if (coinbase1)
  826. free(coinbase1);
  827. if (coinbase2)
  828. free(coinbase2);
  829. if (bbversion)
  830. free(bbversion);
  831. if (nbit)
  832. free(nbit);
  833. if (ntime)
  834. free(ntime);
  835. return false;
  836. }
  837. mutex_lock(&pool->pool_lock);
  838. pool->swork.job_id = job_id;
  839. pool->swork.prev_hash = prev_hash;
  840. pool->swork.coinbase1 = coinbase1;
  841. pool->swork.coinbase2 = coinbase2;
  842. pool->swork.bbversion = bbversion;
  843. pool->swork.nbit = nbit;
  844. pool->swork.ntime = ntime;
  845. pool->swork.clean = clean;
  846. for (i = 0; i < pool->swork.merkles; i++)
  847. free(pool->swork.merkle[i]);
  848. if (merkles) {
  849. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  850. for (i = 0; i < merkles; i++)
  851. pool->swork.merkle[i] = json_array_string(arr, i);
  852. }
  853. pool->swork.merkles = merkles;
  854. if (clean)
  855. pool->nonce2 = 0;
  856. mutex_unlock(&pool->pool_lock);
  857. if (opt_protocol) {
  858. applog(LOG_DEBUG, "job_id: %s", job_id);
  859. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  860. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  861. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  862. for (i = 0; i < merkles; i++)
  863. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  864. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  865. applog(LOG_DEBUG, "nbit: %s", nbit);
  866. applog(LOG_DEBUG, "ntime: %s", ntime);
  867. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  868. }
  869. /* A notify message is the closest stratum gets to a getwork */
  870. pool->getwork_requested++;
  871. total_getworks++;
  872. return true;
  873. }
  874. static bool parse_diff(struct pool *pool, json_t *val)
  875. {
  876. int diff;
  877. diff = json_integer_value(json_array_get(val, 0));
  878. if (diff < 1)
  879. return false;
  880. mutex_lock(&pool->pool_lock);
  881. pool->swork.diff = diff;
  882. mutex_unlock(&pool->pool_lock);
  883. applog(LOG_DEBUG, "Pool %d difficulty set to %d", pool->pool_no, diff);
  884. return true;
  885. }
  886. bool parse_method(struct pool *pool, char *s)
  887. {
  888. json_t *val = NULL, *method, *err_val, *params;
  889. json_error_t err;
  890. bool ret = false;
  891. char *buf;
  892. val = JSON_LOADS(s, &err);
  893. if (!val) {
  894. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  895. goto out;
  896. }
  897. method = json_object_get(val, "method");
  898. if (!method)
  899. goto out;
  900. err_val = json_object_get(val, "error");
  901. params = json_object_get(val, "params");
  902. if (err_val && !json_is_null(err_val)) {
  903. char *ss;
  904. if (err_val)
  905. ss = json_dumps(err_val, JSON_INDENT(3));
  906. else
  907. ss = strdup("(unknown reason)");
  908. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  909. free(ss);
  910. goto out;
  911. }
  912. buf = (char *)json_string_value(method);
  913. if (!buf)
  914. goto out;
  915. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  916. ret = true;
  917. goto out;
  918. }
  919. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  920. ret = true;
  921. goto out;
  922. }
  923. out:
  924. if (val)
  925. json_decref(val);
  926. return ret;
  927. }
  928. bool auth_stratum(struct pool *pool)
  929. {
  930. json_t *val = NULL, *res_val, *err_val;
  931. char *s, *sret = NULL;
  932. json_error_t err;
  933. bool ret = false;
  934. s = alloca(RECVSIZE);
  935. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  936. swork_id++, pool->rpc_user, pool->rpc_pass);
  937. /* Parse all data prior sending auth request */
  938. while (sock_full(pool->sock, false)) {
  939. sret = recv_line(pool->sock);
  940. if (!parse_method(pool, sret)) {
  941. clear_sock(pool->sock);
  942. applog(LOG_WARNING, "Failed to parse stratum buffer");
  943. free(sret);
  944. return ret;
  945. }
  946. free(sret);
  947. }
  948. if (!stratum_send(pool, s, strlen(s)))
  949. goto out;
  950. sret = recv_line(pool->sock);
  951. if (!sret)
  952. goto out;
  953. val = JSON_LOADS(sret, &err);
  954. free(sret);
  955. res_val = json_object_get(val, "result");
  956. err_val = json_object_get(val, "error");
  957. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  958. char *ss;
  959. if (err_val)
  960. ss = json_dumps(err_val, JSON_INDENT(3));
  961. else
  962. ss = strdup("(unknown reason)");
  963. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  964. free(ss);
  965. goto out;
  966. }
  967. ret = true;
  968. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  969. out:
  970. if (val)
  971. json_decref(val);
  972. pool->stratum_auth = ret;
  973. return ret;
  974. }
  975. bool initiate_stratum(struct pool *pool)
  976. {
  977. json_t *val, *res_val, *err_val, *notify_val;
  978. char *s, *buf, *sret = NULL;
  979. json_error_t err;
  980. bool ret = false;
  981. if (pool->stratum_active)
  982. return true;
  983. s = alloca(RECVSIZE);
  984. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  985. pool->sock = socket(AF_INET, SOCK_STREAM, 0);
  986. if (pool->sock == INVSOCK)
  987. quit(1, "Failed to create pool socket in initiate_stratum");
  988. if (SOCKETFAIL(connect(pool->sock, (struct sockaddr *)pool->server, sizeof(struct sockaddr)))) {
  989. applog(LOG_DEBUG, "Failed to connect socket to pool");
  990. goto out;
  991. }
  992. if (!stratum_send(pool, s, strlen(s))) {
  993. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  994. goto out;
  995. }
  996. if (!sock_full(pool->sock, true)) {
  997. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  998. goto out;
  999. }
  1000. sret = recv_line(pool->sock);
  1001. if (!sret)
  1002. goto out;
  1003. val = JSON_LOADS(sret, &err);
  1004. free(sret);
  1005. if (!val) {
  1006. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1007. goto out;
  1008. }
  1009. res_val = json_object_get(val, "result");
  1010. err_val = json_object_get(val, "error");
  1011. if (!res_val || json_is_null(res_val) ||
  1012. (err_val && !json_is_null(err_val))) {
  1013. char *ss;
  1014. if (err_val)
  1015. ss = json_dumps(err_val, JSON_INDENT(3));
  1016. else
  1017. ss = strdup("(unknown reason)");
  1018. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1019. free(ss);
  1020. goto out;
  1021. }
  1022. notify_val = json_array_get(res_val, 0);
  1023. if (!notify_val || json_is_null(notify_val)) {
  1024. applog(LOG_WARNING, "Failed to parse notify_val in initiate_stratum");
  1025. goto out;
  1026. }
  1027. buf = __json_array_string(notify_val, 0);
  1028. if (!buf || strcasecmp(buf, "mining.notify")) {
  1029. applog(LOG_WARNING, "Failed to get mining notify in initiate_stratum");
  1030. goto out;
  1031. }
  1032. pool->subscription = json_array_string(notify_val, 1);
  1033. if (!pool->subscription) {
  1034. applog(LOG_WARNING, "Failed to get a subscription in initiate_stratum");
  1035. goto out;
  1036. }
  1037. pool->nonce1 = json_array_string(res_val, 1);
  1038. if (!pool->nonce1) {
  1039. applog(LOG_WARNING, "Failed to get nonce1 in initiate_stratum");
  1040. goto out;
  1041. }
  1042. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1043. if (!pool->n2size) {
  1044. applog(LOG_WARNING, "Failed to get n2size in initiate_stratum");
  1045. goto out;
  1046. }
  1047. ret = true;
  1048. out:
  1049. if (val)
  1050. json_decref(val);
  1051. if (ret) {
  1052. pool->stratum_active = true;
  1053. pool->swork.diff = 1;
  1054. if (opt_protocol) {
  1055. applog(LOG_DEBUG, "Pool %d confirmed mining.notify with subscription %s extranonce1 %s extran2size %d",
  1056. pool->pool_no, pool->subscription, pool->nonce1, pool->n2size);
  1057. }
  1058. } else
  1059. CLOSESOCKET(pool->sock);
  1060. return ret;
  1061. }