util.c 29 KB

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