util.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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, c;
  729. ssize_t offset = 0;
  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. do {
  741. read(sock, &c, 1);
  742. memcpy(s + offset++, &c, 1);
  743. } while (strncmp(&c, "\n", 1));
  744. sret = strdup(s);
  745. strcpy(sret + offset - 1, "\0");
  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. if (!method)
  876. goto out;
  877. err_val = json_object_get(val, "error");
  878. params = json_object_get(val, "params");
  879. if (err_val && !json_is_null(err_val)) {
  880. char *ss;
  881. if (err_val)
  882. ss = json_dumps(err_val, JSON_INDENT(3));
  883. else
  884. ss = strdup("(unknown reason)");
  885. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  886. free(ss);
  887. goto out;
  888. }
  889. buf = (char *)json_string_value(method);
  890. if (!buf)
  891. goto out;
  892. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  893. ret = true;
  894. goto out;
  895. }
  896. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  897. ret = true;
  898. goto out;
  899. }
  900. out:
  901. if (val)
  902. json_decref(val);
  903. return ret;
  904. }
  905. bool auth_stratum(struct pool *pool)
  906. {
  907. json_t *val = NULL, *res_val, *err_val;
  908. char *s, *sret = NULL;
  909. json_error_t err;
  910. bool ret = false;
  911. s = alloca(RECVSIZE);
  912. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  913. swork_id++, pool->rpc_user, pool->rpc_pass);
  914. /* Parse all data prior sending auth request */
  915. while (sock_full(pool->sock, false)) {
  916. sret = recv_line(pool->sock);
  917. if (!parse_method(pool, sret)) {
  918. clear_sock(pool->sock);
  919. applog(LOG_WARNING, "Failed to parse stratum buffer");
  920. free(sret);
  921. return ret;
  922. }
  923. free(sret);
  924. }
  925. if (!sock_send(pool->sock, s, strlen(s)))
  926. goto out;
  927. sret = recv_line(pool->sock);
  928. if (!sret)
  929. goto out;
  930. val = JSON_LOADS(sret, &err);
  931. free(sret);
  932. res_val = json_object_get(val, "result");
  933. err_val = json_object_get(val, "error");
  934. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  935. char *ss;
  936. if (err_val)
  937. ss = json_dumps(err_val, JSON_INDENT(3));
  938. else
  939. ss = strdup("(unknown reason)");
  940. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  941. free(ss);
  942. goto out;
  943. }
  944. ret = true;
  945. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  946. out:
  947. if (val)
  948. json_decref(val);
  949. pool->stratum_auth = ret;
  950. return ret;
  951. }
  952. bool initiate_stratum(struct pool *pool)
  953. {
  954. json_t *val, *res_val, *err_val, *notify_val;
  955. char *s, *buf, *sret = NULL;
  956. json_error_t err;
  957. bool ret = false;
  958. if (pool->stratum_active)
  959. return true;
  960. s = alloca(RECVSIZE);
  961. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  962. pool->sock = socket(AF_INET, SOCK_STREAM, 0);
  963. if (pool->sock == INVSOCK)
  964. quit(1, "Failed to create pool socket in initiate_stratum");
  965. if (SOCKETFAIL(connect(pool->sock, (struct sockaddr *)pool->server, sizeof(struct sockaddr)))) {
  966. applog(LOG_DEBUG, "Failed to connect socket to pool");
  967. goto out;
  968. }
  969. if (!sock_send(pool->sock, s, strlen(s))) {
  970. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  971. goto out;
  972. }
  973. if (!sock_full(pool->sock, true)) {
  974. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  975. goto out;
  976. }
  977. sret = recv_line(pool->sock);
  978. if (!sret)
  979. goto out;
  980. val = JSON_LOADS(sret, &err);
  981. free(sret);
  982. if (!val) {
  983. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  984. goto out;
  985. }
  986. res_val = json_object_get(val, "result");
  987. err_val = json_object_get(val, "error");
  988. if (!res_val || json_is_null(res_val) ||
  989. (err_val && !json_is_null(err_val))) {
  990. char *ss;
  991. if (err_val)
  992. ss = json_dumps(err_val, JSON_INDENT(3));
  993. else
  994. ss = strdup("(unknown reason)");
  995. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  996. free(ss);
  997. goto out;
  998. }
  999. notify_val = json_array_get(res_val, 0);
  1000. if (!notify_val || json_is_null(notify_val)) {
  1001. applog(LOG_WARNING, "Failed to parse notify_val in initiate_stratum");
  1002. goto out;
  1003. }
  1004. buf = __json_array_string(notify_val, 0);
  1005. if (!buf || strcasecmp(buf, "mining.notify")) {
  1006. applog(LOG_WARNING, "Failed to get mining notify in initiate_stratum");
  1007. goto out;
  1008. }
  1009. pool->subscription = json_array_string(notify_val, 1);
  1010. if (!pool->subscription) {
  1011. applog(LOG_WARNING, "Failed to get a subscription in initiate_stratum");
  1012. goto out;
  1013. }
  1014. pool->nonce1 = json_array_string(res_val, 1);
  1015. if (!pool->nonce1) {
  1016. applog(LOG_WARNING, "Failed to get nonce1 in initiate_stratum");
  1017. goto out;
  1018. }
  1019. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1020. if (!pool->n2size) {
  1021. applog(LOG_WARNING, "Failed to get n2size in initiate_stratum");
  1022. goto out;
  1023. }
  1024. ret = true;
  1025. out:
  1026. if (val)
  1027. json_decref(val);
  1028. if (ret) {
  1029. pool->stratum_active = true;
  1030. pool->swork.diff = 1;
  1031. if (opt_protocol) {
  1032. applog(LOG_DEBUG, "Pool %d confirmed mining.notify with subscription %s extranonce1 %s extran2size %d",
  1033. pool->pool_no, pool->subscription, pool->nonce1, pool->n2size);
  1034. }
  1035. } else
  1036. CLOSESOCKET(pool->sock);
  1037. return ret;
  1038. }