util.c 29 KB

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