util.c 28 KB

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