util.c 28 KB

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