util.c 30 KB

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