util.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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 = NULL;
  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->sockaddr_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 8191
  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 + 1);
  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 + 1);
  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 = NULL, *res_val, *err_val;
  978. char *s, *sret = NULL;
  979. json_error_t err;
  980. bool ret = false;
  981. if (pool->stratum_active)
  982. return true;
  983. s = alloca(RECVSIZE + 1);
  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. pool->nonce1 = json_array_string(res_val, 1);
  1023. if (!pool->nonce1) {
  1024. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1025. goto out;
  1026. }
  1027. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1028. if (!pool->n2size) {
  1029. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1030. goto out;
  1031. }
  1032. ret = true;
  1033. out:
  1034. if (val)
  1035. json_decref(val);
  1036. if (ret) {
  1037. pool->stratum_url = pool->sockaddr_url;
  1038. pool->stratum_active = true;
  1039. pool->swork.diff = 1;
  1040. if (opt_protocol) {
  1041. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1042. pool->pool_no, pool->nonce1, pool->n2size);
  1043. }
  1044. } else
  1045. CLOSESOCKET(pool->sock);
  1046. return ret;
  1047. }