util.c 29 KB

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