util.c 29 KB

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