1 /*
2  * Copyright 2010 Jeff Garzik
3  * Copyright 2012 Luke Dashjr
4  * Copyright 2012-2017 pooler
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the Free
8  * Software Foundation; either version 2 of the License, or (at your option)
9  * any later version.  See COPYING for more details.
10  */
11 
12 #define _GNU_SOURCE
13 #include "cpuminer-config.h"
14 
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <ctype.h>
18 #include <stdarg.h>
19 #include <string.h>
20 #include <stdbool.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <jansson.h>
26 #include <curl/curl.h>
27 #include <time.h>
28 #if defined(WIN32)
29 #include <winsock2.h>
30 #include <mstcpip.h>
31 #else
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netinet/tcp.h>
35 #endif
36 #include "compat.h"
37 #include "miner.h"
38 #include "elist.h"
39 
40 struct data_buffer {
41 	void		*buf;
42 	size_t		len;
43 };
44 
45 struct upload_buffer {
46 	const void	*buf;
47 	size_t		len;
48 	size_t		pos;
49 };
50 
51 struct header_info {
52 	char		*lp_path;
53 	char		*reason;
54 	char		*stratum_url;
55 };
56 
57 struct tq_ent {
58 	void			*data;
59 	struct list_head	q_node;
60 };
61 
62 struct thread_q {
63 	struct list_head	q;
64 
65 	bool frozen;
66 
67 	pthread_mutex_t		mutex;
68 	pthread_cond_t		cond;
69 };
70 
applog(int prio,const char * fmt,...)71 void applog(int prio, const char *fmt, ...)
72 {
73 	va_list ap;
74 
75 	va_start(ap, fmt);
76 
77 #ifdef HAVE_SYSLOG_H
78 	if (use_syslog) {
79 		va_list ap2;
80 		char *buf;
81 		int len;
82 
83 		va_copy(ap2, ap);
84 		len = vsnprintf(NULL, 0, fmt, ap2) + 1;
85 		va_end(ap2);
86 		buf = alloca(len);
87 		if (vsnprintf(buf, len, fmt, ap) >= 0)
88 			syslog(prio, "%s", buf);
89 	}
90 #else
91 	if (0) {}
92 #endif
93 	else {
94 		char *f;
95 		int len;
96 		time_t now;
97 		struct tm tm, *tm_p;
98 
99 		time(&now);
100 
101 		pthread_mutex_lock(&applog_lock);
102 		tm_p = localtime(&now);
103 		memcpy(&tm, tm_p, sizeof(tm));
104 		pthread_mutex_unlock(&applog_lock);
105 
106 		len = 40 + strlen(fmt) + 2;
107 		f = alloca(len);
108 		sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d] %s\n",
109 			tm.tm_year + 1900,
110 			tm.tm_mon + 1,
111 			tm.tm_mday,
112 			tm.tm_hour,
113 			tm.tm_min,
114 			tm.tm_sec,
115 			fmt);
116 		pthread_mutex_lock(&applog_lock);
117 		vfprintf(stderr, f, ap);	/* atomic write to stderr */
118 		fflush(stderr);
119 		pthread_mutex_unlock(&applog_lock);
120 	}
121 	va_end(ap);
122 }
123 
124 /* Modify the representation of integer numbers which would cause an overflow
125  * so that they are treated as floating-point numbers.
126  * This is a hack to overcome the limitations of some versions of Jansson. */
hack_json_numbers(const char * in)127 static char *hack_json_numbers(const char *in)
128 {
129 	char *out;
130 	int i, off, intoff;
131 	bool in_str, in_int;
132 
133 	out = calloc(2 * strlen(in) + 1, 1);
134 	if (!out)
135 		return NULL;
136 	off = intoff = 0;
137 	in_str = in_int = false;
138 	for (i = 0; in[i]; i++) {
139 		char c = in[i];
140 		if (c == '"') {
141 			in_str = !in_str;
142 		} else if (c == '\\') {
143 			out[off++] = c;
144 			if (!in[++i])
145 				break;
146 		} else if (!in_str && !in_int && isdigit(c)) {
147 			intoff = off;
148 			in_int = true;
149 		} else if (in_int && !isdigit(c)) {
150 			if (c != '.' && c != 'e' && c != 'E' && c != '+' && c != '-') {
151 				in_int = false;
152 				if (off - intoff > 4) {
153 					char *end;
154 #if JSON_INTEGER_IS_LONG_LONG
155 					errno = 0;
156 					strtoll(out + intoff, &end, 10);
157 					if (!*end && errno == ERANGE) {
158 #else
159 					long l;
160 					errno = 0;
161 					l = strtol(out + intoff, &end, 10);
162 					if (!*end && (errno == ERANGE || l > INT_MAX)) {
163 #endif
164 						out[off++] = '.';
165 						out[off++] = '0';
166 					}
167 				}
168 			}
169 		}
170 		out[off++] = in[i];
171 	}
172 	return out;
173 }
174 
175 static void databuf_free(struct data_buffer *db)
176 {
177 	if (!db)
178 		return;
179 
180 	free(db->buf);
181 
182 	memset(db, 0, sizeof(*db));
183 }
184 
185 static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
186 			  void *user_data)
187 {
188 	struct data_buffer *db = user_data;
189 	size_t len = size * nmemb;
190 	size_t oldlen, newlen;
191 	void *newmem;
192 	static const unsigned char zero = 0;
193 
194 	oldlen = db->len;
195 	newlen = oldlen + len;
196 
197 	newmem = realloc(db->buf, newlen + 1);
198 	if (!newmem)
199 		return 0;
200 
201 	db->buf = newmem;
202 	db->len = newlen;
203 	memcpy(db->buf + oldlen, ptr, len);
204 	memcpy(db->buf + newlen, &zero, 1);	/* null terminate */
205 
206 	return len;
207 }
208 
209 static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
210 			     void *user_data)
211 {
212 	struct upload_buffer *ub = user_data;
213 	int len = size * nmemb;
214 
215 	if (len > ub->len - ub->pos)
216 		len = ub->len - ub->pos;
217 
218 	if (len) {
219 		memcpy(ptr, ub->buf + ub->pos, len);
220 		ub->pos += len;
221 	}
222 
223 	return len;
224 }
225 
226 #if LIBCURL_VERSION_NUM >= 0x071200
227 static int seek_data_cb(void *user_data, curl_off_t offset, int origin)
228 {
229 	struct upload_buffer *ub = user_data;
230 
231 	switch (origin) {
232 	case SEEK_SET:
233 		ub->pos = offset;
234 		break;
235 	case SEEK_CUR:
236 		ub->pos += offset;
237 		break;
238 	case SEEK_END:
239 		ub->pos = ub->len + offset;
240 		break;
241 	default:
242 		return 1; /* CURL_SEEKFUNC_FAIL */
243 	}
244 
245 	return 0; /* CURL_SEEKFUNC_OK */
246 }
247 #endif
248 
249 static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
250 {
251 	struct header_info *hi = user_data;
252 	size_t remlen, slen, ptrlen = size * nmemb;
253 	char *rem, *val = NULL, *key = NULL;
254 	void *tmp;
255 
256 	val = calloc(1, ptrlen);
257 	key = calloc(1, ptrlen);
258 	if (!key || !val)
259 		goto out;
260 
261 	tmp = memchr(ptr, ':', ptrlen);
262 	if (!tmp || (tmp == ptr))	/* skip empty keys / blanks */
263 		goto out;
264 	slen = tmp - ptr;
265 	if ((slen + 1) == ptrlen)	/* skip key w/ no value */
266 		goto out;
267 	memcpy(key, ptr, slen);		/* store & nul term key */
268 	key[slen] = 0;
269 
270 	rem = ptr + slen + 1;		/* trim value's leading whitespace */
271 	remlen = ptrlen - slen - 1;
272 	while ((remlen > 0) && (isspace(*rem))) {
273 		remlen--;
274 		rem++;
275 	}
276 
277 	memcpy(val, rem, remlen);	/* store value, trim trailing ws */
278 	val[remlen] = 0;
279 	while ((*val) && (isspace(val[strlen(val) - 1]))) {
280 		val[strlen(val) - 1] = 0;
281 	}
282 	if (!*val)			/* skip blank value */
283 		goto out;
284 
285 	if (!strcasecmp("X-Long-Polling", key)) {
286 		hi->lp_path = val;	/* steal memory reference */
287 		val = NULL;
288 	}
289 
290 	if (!strcasecmp("X-Reject-Reason", key)) {
291 		hi->reason = val;	/* steal memory reference */
292 		val = NULL;
293 	}
294 
295 	if (!strcasecmp("X-Stratum", key)) {
296 		hi->stratum_url = val;	/* steal memory reference */
297 		val = NULL;
298 	}
299 
300 out:
301 	free(key);
302 	free(val);
303 	return ptrlen;
304 }
305 
306 #if LIBCURL_VERSION_NUM >= 0x070f06
307 static int sockopt_keepalive_cb(void *userdata, curl_socket_t fd,
308 	curlsocktype purpose)
309 {
310 	int keepalive = 1;
311 	int tcp_keepcnt = 3;
312 	int tcp_keepidle = 50;
313 	int tcp_keepintvl = 50;
314 
315 #ifndef WIN32
316 	if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive,
317 		sizeof(keepalive))))
318 		return 1;
319 #ifdef __linux
320 	if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT,
321 		&tcp_keepcnt, sizeof(tcp_keepcnt))))
322 		return 1;
323 	if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE,
324 		&tcp_keepidle, sizeof(tcp_keepidle))))
325 		return 1;
326 	if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL,
327 		&tcp_keepintvl, sizeof(tcp_keepintvl))))
328 		return 1;
329 #endif /* __linux */
330 #ifdef __APPLE_CC__
331 	if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE,
332 		&tcp_keepintvl, sizeof(tcp_keepintvl))))
333 		return 1;
334 #endif /* __APPLE_CC__ */
335 #else /* WIN32 */
336 	struct tcp_keepalive vals;
337 	vals.onoff = 1;
338 	vals.keepalivetime = tcp_keepidle * 1000;
339 	vals.keepaliveinterval = tcp_keepintvl * 1000;
340 	DWORD outputBytes;
341 	if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals),
342 		NULL, 0, &outputBytes, NULL, NULL)))
343 		return 1;
344 #endif /* WIN32 */
345 
346 	return 0;
347 }
348 #endif
349 
350 json_t *json_rpc_call(CURL *curl, const char *url,
351 		      const char *userpass, const char *rpc_req,
352 		      int *curl_err, int flags)
353 {
354 	json_t *val, *err_val, *res_val;
355 	int rc;
356 	long http_rc;
357 	struct data_buffer all_data = {0};
358 	struct upload_buffer upload_data;
359 	char *json_buf;
360 	json_error_t err;
361 	struct curl_slist *headers = NULL;
362 	char len_hdr[64];
363 	char curl_err_str[CURL_ERROR_SIZE];
364 	long timeout = (flags & JSON_RPC_LONGPOLL) ? opt_timeout : 30;
365 	struct header_info hi = {0};
366 
367 	/* it is assumed that 'curl' is freshly [re]initialized at this pt */
368 
369 	if (opt_protocol)
370 		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
371 	curl_easy_setopt(curl, CURLOPT_URL, url);
372 	if (opt_cert)
373 		curl_easy_setopt(curl, CURLOPT_CAINFO, opt_cert);
374 	curl_easy_setopt(curl, CURLOPT_ENCODING, "");
375 	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
376 	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
377 	curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
378 	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
379 	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
380 	curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
381 	curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
382 #if LIBCURL_VERSION_NUM >= 0x071200
383 	curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, &seek_data_cb);
384 	curl_easy_setopt(curl, CURLOPT_SEEKDATA, &upload_data);
385 #endif
386 	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
387 	if (opt_redirect)
388 		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
389 	curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
390 	curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
391 	curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
392 	if (opt_proxy) {
393 		curl_easy_setopt(curl, CURLOPT_PROXY, opt_proxy);
394 		curl_easy_setopt(curl, CURLOPT_PROXYTYPE, opt_proxy_type);
395 	}
396 	if (userpass) {
397 		curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
398 		curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
399 	}
400 #if LIBCURL_VERSION_NUM >= 0x070f06
401 	if (flags & JSON_RPC_LONGPOLL)
402 		curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_keepalive_cb);
403 #endif
404 	curl_easy_setopt(curl, CURLOPT_POST, 1);
405 
406 	if (opt_protocol)
407 		applog(LOG_DEBUG, "JSON protocol request:\n%s\n", rpc_req);
408 
409 	upload_data.buf = rpc_req;
410 	upload_data.len = strlen(rpc_req);
411 	upload_data.pos = 0;
412 	sprintf(len_hdr, "Content-Length: %lu",
413 		(unsigned long) upload_data.len);
414 
415 	headers = curl_slist_append(headers, "Content-Type: application/json");
416 	headers = curl_slist_append(headers, len_hdr);
417 	headers = curl_slist_append(headers, "User-Agent: " USER_AGENT);
418 	headers = curl_slist_append(headers, "X-Mining-Extensions: midstate");
419 	headers = curl_slist_append(headers, "Accept:"); /* disable Accept hdr*/
420 	headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
421 
422 	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
423 
424 	rc = curl_easy_perform(curl);
425 	if (curl_err != NULL)
426 		*curl_err = rc;
427 	if (rc) {
428 		curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_rc);
429 		if (!((flags & JSON_RPC_LONGPOLL) && rc == CURLE_OPERATION_TIMEDOUT) &&
430 		    !((flags & JSON_RPC_QUIET_404) && http_rc == 404))
431 			applog(LOG_ERR, "HTTP request failed: %s", curl_err_str);
432 		if (curl_err && (flags & JSON_RPC_QUIET_404) && http_rc == 404)
433 			*curl_err = CURLE_OK;
434 		goto err_out;
435 	}
436 
437 	/* If X-Stratum was found, activate Stratum */
438 	if (want_stratum && hi.stratum_url &&
439 	    !strncasecmp(hi.stratum_url, "stratum+tcp://", 14)) {
440 		have_stratum = true;
441 		tq_push(thr_info[stratum_thr_id].q, hi.stratum_url);
442 		hi.stratum_url = NULL;
443 	}
444 
445 	/* If X-Long-Polling was found, activate long polling */
446 	if (!have_longpoll && want_longpoll && hi.lp_path && !have_gbt &&
447 	    allow_getwork && !have_stratum) {
448 		have_longpoll = true;
449 		tq_push(thr_info[longpoll_thr_id].q, hi.lp_path);
450 		hi.lp_path = NULL;
451 	}
452 
453 	if (!all_data.buf) {
454 		applog(LOG_ERR, "Empty data received in json_rpc_call.");
455 		goto err_out;
456 	}
457 
458 	json_buf = hack_json_numbers(all_data.buf);
459 	errno = 0; /* needed for Jansson < 2.1 */
460 	val = JSON_LOADS(json_buf, &err);
461 	free(json_buf);
462 	if (!val) {
463 		applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
464 		goto err_out;
465 	}
466 
467 	if (opt_protocol) {
468 		char *s = json_dumps(val, JSON_INDENT(3));
469 		applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
470 		free(s);
471 	}
472 
473 	/* JSON-RPC valid response returns a 'result' and a null 'error'. */
474 	res_val = json_object_get(val, "result");
475 	err_val = json_object_get(val, "error");
476 
477 	if (!res_val || (err_val && !json_is_null(err_val))) {
478 		char *s;
479 
480 		if (err_val)
481 			s = json_dumps(err_val, JSON_INDENT(3));
482 		else
483 			s = strdup("(unknown reason)");
484 
485 		applog(LOG_ERR, "JSON-RPC call failed: %s", s);
486 
487 		free(s);
488 
489 		goto err_out;
490 	}
491 
492 	if (hi.reason)
493 		json_object_set_new(val, "reject-reason", json_string(hi.reason));
494 
495 	databuf_free(&all_data);
496 	curl_slist_free_all(headers);
497 	curl_easy_reset(curl);
498 	return val;
499 
500 err_out:
501 	free(hi.lp_path);
502 	free(hi.reason);
503 	free(hi.stratum_url);
504 	databuf_free(&all_data);
505 	curl_slist_free_all(headers);
506 	curl_easy_reset(curl);
507 	return NULL;
508 }
509 
510 void memrev(unsigned char *p, size_t len)
511 {
512 	unsigned char c, *q;
513 	for (q = p + len - 1; p < q; p++, q--) {
514 		c = *p;
515 		*p = *q;
516 		*q = c;
517 	}
518 }
519 
520 void bin2hex(char *s, const unsigned char *p, size_t len)
521 {
522 	int i;
523 	for (i = 0; i < len; i++)
524 		sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
525 }
526 
527 char *abin2hex(const unsigned char *p, size_t len)
528 {
529 	char *s = malloc((len * 2) + 1);
530 	if (!s)
531 		return NULL;
532 	bin2hex(s, p, len);
533 	return s;
534 }
535 
536 bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
537 {
538 	char hex_byte[3];
539 	char *ep;
540 
541 	hex_byte[2] = '\0';
542 
543 	while (*hexstr && len) {
544 		if (!hexstr[1]) {
545 			applog(LOG_ERR, "hex2bin str truncated");
546 			return false;
547 		}
548 		hex_byte[0] = hexstr[0];
549 		hex_byte[1] = hexstr[1];
550 		*p = (unsigned char) strtol(hex_byte, &ep, 16);
551 		if (*ep) {
552 			applog(LOG_ERR, "hex2bin failed on '%s'", hex_byte);
553 			return false;
554 		}
555 		p++;
556 		hexstr += 2;
557 		len--;
558 	}
559 
560 	return (len == 0 && *hexstr == 0) ? true : false;
561 }
562 
563 int varint_encode(unsigned char *p, uint64_t n)
564 {
565 	int i;
566 	if (n < 0xfd) {
567 		p[0] = n;
568 		return 1;
569 	}
570 	if (n <= 0xffff) {
571 		p[0] = 0xfd;
572 		p[1] = n & 0xff;
573 		p[2] = n >> 8;
574 		return 3;
575 	}
576 	if (n <= 0xffffffff) {
577 		p[0] = 0xfe;
578 		for (i = 1; i < 5; i++) {
579 			p[i] = n & 0xff;
580 			n >>= 8;
581 		}
582 		return 5;
583 	}
584 	p[0] = 0xff;
585 	for (i = 1; i < 9; i++) {
586 		p[i] = n & 0xff;
587 		n >>= 8;
588 	}
589 	return 9;
590 }
591 
592 static const char b58digits[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
593 
594 static bool b58dec(unsigned char *bin, size_t binsz, const char *b58)
595 {
596 	size_t i, j;
597 	uint64_t t;
598 	uint32_t c;
599 	uint32_t *outi;
600 	size_t outisz = (binsz + 3) / 4;
601 	int rem = binsz % 4;
602 	uint32_t remmask = 0xffffffff << (8 * rem);
603 	size_t b58sz = strlen(b58);
604 	bool rc = false;
605 
606 	outi = calloc(outisz, sizeof(*outi));
607 
608 	for (i = 0; i < b58sz; ++i) {
609 		for (c = 0; b58digits[c] != b58[i]; c++)
610 			if (!b58digits[c])
611 				goto out;
612 		for (j = outisz; j--; ) {
613 			t = (uint64_t)outi[j] * 58 + c;
614 			c = t >> 32;
615 			outi[j] = t & 0xffffffff;
616 		}
617 		if (c || outi[0] & remmask)
618 			goto out;
619 	}
620 
621 	j = 0;
622 	switch (rem) {
623 		case 3:
624 			*(bin++) = (outi[0] >> 16) & 0xff;
625 		case 2:
626 			*(bin++) = (outi[0] >> 8) & 0xff;
627 		case 1:
628 			*(bin++) = outi[0] & 0xff;
629 			++j;
630 		default:
631 			break;
632 	}
633 	for (; j < outisz; ++j) {
634 		be32enc((uint32_t *)bin, outi[j]);
635 		bin += sizeof(uint32_t);
636 	}
637 
638 	rc = true;
639 out:
640 	free(outi);
641 	return rc;
642 }
643 
644 static int b58check(unsigned char *bin, size_t binsz, const char *b58)
645 {
646 	unsigned char buf[32];
647 	int i;
648 
649 	sha256d(buf, bin, binsz - 4);
650 	if (memcmp(&bin[binsz - 4], buf, 4))
651 		return -1;
652 
653 	/* Check number of zeros is correct AFTER verifying checksum
654 	 * (to avoid possibility of accessing the string beyond the end) */
655 	for (i = 0; bin[i] == '\0' && b58[i] == '1'; ++i);
656 	if (bin[i] == '\0' || b58[i] == '1')
657 		return -3;
658 
659 	return bin[0];
660 }
661 
662 size_t address_to_script(unsigned char *out, size_t outsz, const char *addr)
663 {
664 	unsigned char addrbin[25];
665 	int addrver;
666 	size_t rv;
667 
668 	if (!b58dec(addrbin, sizeof(addrbin), addr))
669 		return 0;
670 	addrver = b58check(addrbin, sizeof(addrbin), addr);
671 	if (addrver < 0)
672 		return 0;
673 	switch (addrver) {
674 		case 5:    /* Bitcoin script hash */
675 		case 196:  /* Testnet script hash */
676 			if (outsz < (rv = 23))
677 				return rv;
678 			out[ 0] = 0xa9;  /* OP_HASH160 */
679 			out[ 1] = 0x14;  /* push 20 bytes */
680 			memcpy(&out[2], &addrbin[1], 20);
681 			out[22] = 0x87;  /* OP_EQUAL */
682 			return rv;
683 		default:
684 			if (outsz < (rv = 25))
685 				return rv;
686 			out[ 0] = 0x76;  /* OP_DUP */
687 			out[ 1] = 0xa9;  /* OP_HASH160 */
688 			out[ 2] = 0x14;  /* push 20 bytes */
689 			memcpy(&out[3], &addrbin[1], 20);
690 			out[23] = 0x88;  /* OP_EQUALVERIFY */
691 			out[24] = 0xac;  /* OP_CHECKSIG */
692 			return rv;
693 	}
694 }
695 
696 /* Subtract the `struct timeval' values X and Y,
697    storing the result in RESULT.
698    Return 1 if the difference is negative, otherwise 0.  */
699 int timeval_subtract(struct timeval *result, struct timeval *x,
700 	struct timeval *y)
701 {
702 	/* Perform the carry for the later subtraction by updating Y. */
703 	if (x->tv_usec < y->tv_usec) {
704 		int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
705 		y->tv_usec -= 1000000 * nsec;
706 		y->tv_sec += nsec;
707 	}
708 	if (x->tv_usec - y->tv_usec > 1000000) {
709 		int nsec = (x->tv_usec - y->tv_usec) / 1000000;
710 		y->tv_usec += 1000000 * nsec;
711 		y->tv_sec -= nsec;
712 	}
713 
714 	/* Compute the time remaining to wait.
715 	 * `tv_usec' is certainly positive. */
716 	result->tv_sec = x->tv_sec - y->tv_sec;
717 	result->tv_usec = x->tv_usec - y->tv_usec;
718 
719 	/* Return 1 if result is negative. */
720 	return x->tv_sec < y->tv_sec;
721 }
722 
723 bool fulltest(const uint32_t *hash, const uint32_t *target)
724 {
725 	int i;
726 	bool rc = true;
727 
728 	for (i = 7; i >= 0; i--) {
729 		if (hash[i] > target[i]) {
730 			rc = false;
731 			break;
732 		}
733 		if (hash[i] < target[i]) {
734 			rc = true;
735 			break;
736 		}
737 	}
738 
739 	if (opt_debug) {
740 		uint32_t hash_be[8], target_be[8];
741 		char hash_str[65], target_str[65];
742 
743 		for (i = 0; i < 8; i++) {
744 			be32enc(hash_be + i, hash[7 - i]);
745 			be32enc(target_be + i, target[7 - i]);
746 		}
747 		bin2hex(hash_str, (unsigned char *)hash_be, 32);
748 		bin2hex(target_str, (unsigned char *)target_be, 32);
749 
750 		applog(LOG_DEBUG, "DEBUG: %s\nHash:   %s\nTarget: %s",
751 			rc ? "hash <= target"
752 			   : "hash > target (false positive)",
753 			hash_str,
754 			target_str);
755 	}
756 
757 	return rc;
758 }
759 
760 void diff_to_target(uint32_t *target, double diff)
761 {
762 	uint64_t m;
763 	int k;
764 
765 	for (k = 6; k > 0 && diff > 1.0; k--)
766 		diff /= 4294967296.0;
767 	m = 4294901760.0 / diff;
768 	if (m == 0 && k == 6)
769 		memset(target, 0xff, 32);
770 	else {
771 		memset(target, 0, 32);
772 		target[k] = (uint32_t)m;
773 		target[k + 1] = (uint32_t)(m >> 32);
774 	}
775 }
776 
777 #ifdef WIN32
778 #define socket_blocks() (WSAGetLastError() == WSAEWOULDBLOCK)
779 #else
780 #define socket_blocks() (errno == EAGAIN || errno == EWOULDBLOCK)
781 #endif
782 
783 static bool send_line(struct stratum_ctx *sctx, char *s)
784 {
785 	ssize_t len, sent = 0;
786 
787 	len = strlen(s);
788 	s[len++] = '\n';
789 
790 	while (len > 0) {
791 		struct timeval timeout = {0, 0};
792 		ssize_t n;
793 		fd_set wd;
794 
795 		FD_ZERO(&wd);
796 		FD_SET(sctx->sock, &wd);
797 		if (select(sctx->sock + 1, NULL, &wd, NULL, &timeout) < 1)
798 			return false;
799 #if LIBCURL_VERSION_NUM >= 0x071202
800 		CURLcode rc = curl_easy_send(sctx->curl, s + sent, len, (size_t *)&n);
801 		if (rc != CURLE_OK) {
802 			if (rc != CURLE_AGAIN)
803 #else
804 		n = send(sctx->sock, s + sent, len, 0);
805 		if (n < 0) {
806 			if (!socket_blocks())
807 #endif
808 				return false;
809 			n = 0;
810 		}
811 		sent += n;
812 		len -= n;
813 	}
814 
815 	return true;
816 }
817 
818 bool stratum_send_line(struct stratum_ctx *sctx, char *s)
819 {
820 	bool ret = false;
821 
822 	if (opt_protocol)
823 		applog(LOG_DEBUG, "> %s", s);
824 
825 	pthread_mutex_lock(&sctx->sock_lock);
826 	ret = send_line(sctx, s);
827 	pthread_mutex_unlock(&sctx->sock_lock);
828 
829 	return ret;
830 }
831 
832 static bool socket_full(curl_socket_t sock, int timeout)
833 {
834 	struct timeval tv;
835 	fd_set rd;
836 
837 	FD_ZERO(&rd);
838 	FD_SET(sock, &rd);
839 	tv.tv_sec = timeout;
840 	tv.tv_usec = 0;
841 	if (select(sock + 1, &rd, NULL, NULL, &tv) > 0)
842 		return true;
843 	return false;
844 }
845 
846 bool stratum_socket_full(struct stratum_ctx *sctx, int timeout)
847 {
848 	return strlen(sctx->sockbuf) || socket_full(sctx->sock, timeout);
849 }
850 
851 #define RBUFSIZE 2048
852 #define RECVSIZE (RBUFSIZE - 4)
853 
854 static void stratum_buffer_append(struct stratum_ctx *sctx, const char *s)
855 {
856 	size_t old, new;
857 
858 	old = strlen(sctx->sockbuf);
859 	new = old + strlen(s) + 1;
860 	if (new >= sctx->sockbuf_size) {
861 		sctx->sockbuf_size = new + (RBUFSIZE - (new % RBUFSIZE));
862 		sctx->sockbuf = realloc(sctx->sockbuf, sctx->sockbuf_size);
863 	}
864 	strcpy(sctx->sockbuf + old, s);
865 }
866 
867 char *stratum_recv_line(struct stratum_ctx *sctx)
868 {
869 	ssize_t len, buflen;
870 	char *tok, *sret = NULL;
871 
872 	if (!strstr(sctx->sockbuf, "\n")) {
873 		bool ret = true;
874 		time_t rstart;
875 
876 		time(&rstart);
877 		if (!socket_full(sctx->sock, 60)) {
878 			applog(LOG_ERR, "stratum_recv_line timed out");
879 			goto out;
880 		}
881 		do {
882 			char s[RBUFSIZE];
883 			ssize_t n;
884 
885 			memset(s, 0, RBUFSIZE);
886 #if LIBCURL_VERSION_NUM >= 0x071202
887 			CURLcode rc = curl_easy_recv(sctx->curl, s, RECVSIZE, (size_t *)&n);
888 			if (rc == CURLE_OK && !n) {
889 				ret = false;
890 				break;
891 			}
892 			if (rc != CURLE_OK) {
893 				if (rc != CURLE_AGAIN || !socket_full(sctx->sock, 1)) {
894 #else
895 			n = recv(sctx->sock, s, RECVSIZE, 0);
896 			if (!n) {
897 				ret = false;
898 				break;
899 			}
900 			if (n < 0) {
901 				if (!socket_blocks() || !socket_full(sctx->sock, 1)) {
902 #endif
903 					ret = false;
904 					break;
905 				}
906 			} else
907 				stratum_buffer_append(sctx, s);
908 		} while (time(NULL) - rstart < 60 && !strstr(sctx->sockbuf, "\n"));
909 
910 		if (!ret) {
911 			applog(LOG_ERR, "stratum_recv_line failed");
912 			goto out;
913 		}
914 	}
915 
916 	buflen = strlen(sctx->sockbuf);
917 	tok = strtok(sctx->sockbuf, "\n");
918 	if (!tok) {
919 		applog(LOG_ERR, "stratum_recv_line failed to parse a newline-terminated string");
920 		goto out;
921 	}
922 	sret = strdup(tok);
923 	len = strlen(sret);
924 
925 	if (buflen > len + 1)
926 		memmove(sctx->sockbuf, sctx->sockbuf + len + 1, buflen - len + 1);
927 	else
928 		sctx->sockbuf[0] = '\0';
929 
930 out:
931 	if (sret && opt_protocol)
932 		applog(LOG_DEBUG, "< %s", sret);
933 	return sret;
934 }
935 
936 #if LIBCURL_VERSION_NUM >= 0x071101
937 static curl_socket_t opensocket_grab_cb(void *clientp, curlsocktype purpose,
938 	struct curl_sockaddr *addr)
939 {
940 	curl_socket_t *sock = clientp;
941 	*sock = socket(addr->family, addr->socktype, addr->protocol);
942 	return *sock;
943 }
944 #endif
945 
946 bool stratum_connect(struct stratum_ctx *sctx, const char *url)
947 {
948 	CURL *curl;
949 	int rc;
950 
951 	pthread_mutex_lock(&sctx->sock_lock);
952 	if (sctx->curl)
953 		curl_easy_cleanup(sctx->curl);
954 	sctx->curl = curl_easy_init();
955 	if (!sctx->curl) {
956 		applog(LOG_ERR, "CURL initialization failed");
957 		pthread_mutex_unlock(&sctx->sock_lock);
958 		return false;
959 	}
960 	curl = sctx->curl;
961 	if (!sctx->sockbuf) {
962 		sctx->sockbuf = calloc(RBUFSIZE, 1);
963 		sctx->sockbuf_size = RBUFSIZE;
964 	}
965 	sctx->sockbuf[0] = '\0';
966 	pthread_mutex_unlock(&sctx->sock_lock);
967 
968 	if (url != sctx->url) {
969 		free(sctx->url);
970 		sctx->url = strdup(url);
971 	}
972 	free(sctx->curl_url);
973 	sctx->curl_url = malloc(strlen(url));
974 	sprintf(sctx->curl_url, "http%s", url + 11);
975 
976 	if (opt_protocol)
977 		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
978 	curl_easy_setopt(curl, CURLOPT_URL, sctx->curl_url);
979 	if (opt_cert)
980 		curl_easy_setopt(curl, CURLOPT_CAINFO, opt_cert);
981 	curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
982 	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
983 	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, sctx->curl_err_str);
984 	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
985 	curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
986 	if (opt_proxy) {
987 		curl_easy_setopt(curl, CURLOPT_PROXY, opt_proxy);
988 		curl_easy_setopt(curl, CURLOPT_PROXYTYPE, opt_proxy_type);
989 	}
990 	curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
991 #if LIBCURL_VERSION_NUM >= 0x070f06
992 	curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_keepalive_cb);
993 #endif
994 #if LIBCURL_VERSION_NUM >= 0x071101
995 	curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_grab_cb);
996 	curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &sctx->sock);
997 #endif
998 	curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
999 
1000 	rc = curl_easy_perform(curl);
1001 	if (rc) {
1002 		applog(LOG_ERR, "Stratum connection failed: %s", sctx->curl_err_str);
1003 		curl_easy_cleanup(curl);
1004 		sctx->curl = NULL;
1005 		return false;
1006 	}
1007 
1008 #if LIBCURL_VERSION_NUM < 0x071101
1009 	/* CURLINFO_LASTSOCKET is broken on Win64; only use it as a last resort */
1010 	curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sctx->sock);
1011 #endif
1012 
1013 	return true;
1014 }
1015 
1016 void stratum_disconnect(struct stratum_ctx *sctx)
1017 {
1018 	pthread_mutex_lock(&sctx->sock_lock);
1019 	if (sctx->curl) {
1020 		curl_easy_cleanup(sctx->curl);
1021 		sctx->curl = NULL;
1022 		sctx->sockbuf[0] = '\0';
1023 	}
1024 	pthread_mutex_unlock(&sctx->sock_lock);
1025 }
1026 
1027 static const char *get_stratum_session_id(json_t *val)
1028 {
1029 	json_t *arr_val;
1030 	int i, n;
1031 
1032 	arr_val = json_array_get(val, 0);
1033 	if (!arr_val || !json_is_array(arr_val))
1034 		return NULL;
1035 	n = json_array_size(arr_val);
1036 	for (i = 0; i < n; i++) {
1037 		const char *notify;
1038 		json_t *arr = json_array_get(arr_val, i);
1039 
1040 		if (!arr || !json_is_array(arr))
1041 			break;
1042 		notify = json_string_value(json_array_get(arr, 0));
1043 		if (!notify)
1044 			continue;
1045 		if (!strcasecmp(notify, "mining.notify"))
1046 			return json_string_value(json_array_get(arr, 1));
1047 	}
1048 	return NULL;
1049 }
1050 
1051 bool stratum_subscribe(struct stratum_ctx *sctx)
1052 {
1053 	char *s, *sret = NULL;
1054 	const char *sid, *xnonce1;
1055 	int xn2_size;
1056 	json_t *val = NULL, *res_val, *err_val;
1057 	json_error_t err;
1058 	bool ret = false, retry = false;
1059 
1060 start:
1061 	s = malloc(128 + (sctx->session_id ? strlen(sctx->session_id) : 0));
1062 	if (retry)
1063 		sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}");
1064 	else if (sctx->session_id)
1065 		sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": [\"" USER_AGENT "\", \"%s\"]}", sctx->session_id);
1066 	else
1067 		sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": [\"" USER_AGENT "\"]}");
1068 
1069 	if (!stratum_send_line(sctx, s)) {
1070 		applog(LOG_ERR, "stratum_subscribe send failed");
1071 		goto out;
1072 	}
1073 
1074 	if (!socket_full(sctx->sock, 30)) {
1075 		applog(LOG_ERR, "stratum_subscribe timed out");
1076 		goto out;
1077 	}
1078 
1079 	sret = stratum_recv_line(sctx);
1080 	if (!sret)
1081 		goto out;
1082 
1083 	val = JSON_LOADS(sret, &err);
1084 	free(sret);
1085 	if (!val) {
1086 		applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
1087 		goto out;
1088 	}
1089 
1090 	res_val = json_object_get(val, "result");
1091 	err_val = json_object_get(val, "error");
1092 
1093 	if (!res_val || json_is_null(res_val) ||
1094 	    (err_val && !json_is_null(err_val))) {
1095 		if (opt_debug || retry) {
1096 			free(s);
1097 			if (err_val)
1098 				s = json_dumps(err_val, JSON_INDENT(3));
1099 			else
1100 				s = strdup("(unknown reason)");
1101 			applog(LOG_ERR, "JSON-RPC call failed: %s", s);
1102 		}
1103 		goto out;
1104 	}
1105 
1106 	sid = get_stratum_session_id(res_val);
1107 	if (opt_debug && !sid)
1108 		applog(LOG_DEBUG, "Failed to get Stratum session id");
1109 	xnonce1 = json_string_value(json_array_get(res_val, 1));
1110 	if (!xnonce1) {
1111 		applog(LOG_ERR, "Failed to get extranonce1");
1112 		goto out;
1113 	}
1114 	xn2_size = json_integer_value(json_array_get(res_val, 2));
1115 	if (!xn2_size) {
1116 		applog(LOG_ERR, "Failed to get extranonce2_size");
1117 		goto out;
1118 	}
1119 	if (xn2_size < 0 || xn2_size > 100) {
1120 		applog(LOG_ERR, "Invalid value of extranonce2_size");
1121 		goto out;
1122 	}
1123 
1124 	pthread_mutex_lock(&sctx->work_lock);
1125 	free(sctx->session_id);
1126 	free(sctx->xnonce1);
1127 	sctx->session_id = sid ? strdup(sid) : NULL;
1128 	sctx->xnonce1_size = strlen(xnonce1) / 2;
1129 	sctx->xnonce1 = malloc(sctx->xnonce1_size);
1130 	hex2bin(sctx->xnonce1, xnonce1, sctx->xnonce1_size);
1131 	sctx->xnonce2_size = xn2_size;
1132 	sctx->next_diff = 1.0;
1133 	pthread_mutex_unlock(&sctx->work_lock);
1134 
1135 	if (opt_debug && sid)
1136 		applog(LOG_DEBUG, "Stratum session id: %s", sctx->session_id);
1137 
1138 	ret = true;
1139 
1140 out:
1141 	free(s);
1142 	if (val)
1143 		json_decref(val);
1144 
1145 	if (!ret) {
1146 		if (sret && !retry) {
1147 			retry = true;
1148 			goto start;
1149 		}
1150 	}
1151 
1152 	return ret;
1153 }
1154 
1155 bool stratum_authorize(struct stratum_ctx *sctx, const char *user, const char *pass)
1156 {
1157 	json_t *val = NULL, *res_val, *err_val;
1158 	char *s, *sret;
1159 	json_error_t err;
1160 	bool ret = false;
1161 
1162 	s = malloc(80 + strlen(user) + strlen(pass));
1163 	sprintf(s, "{\"id\": 2, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
1164 	        user, pass);
1165 
1166 	if (!stratum_send_line(sctx, s))
1167 		goto out;
1168 
1169 	while (1) {
1170 		sret = stratum_recv_line(sctx);
1171 		if (!sret)
1172 			goto out;
1173 		if (!stratum_handle_method(sctx, sret))
1174 			break;
1175 		free(sret);
1176 	}
1177 
1178 	val = JSON_LOADS(sret, &err);
1179 	free(sret);
1180 	if (!val) {
1181 		applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
1182 		goto out;
1183 	}
1184 
1185 	res_val = json_object_get(val, "result");
1186 	err_val = json_object_get(val, "error");
1187 
1188 	if (!res_val || json_is_false(res_val) ||
1189 	    (err_val && !json_is_null(err_val)))  {
1190 		applog(LOG_ERR, "Stratum authentication failed");
1191 		goto out;
1192 	}
1193 
1194 	ret = true;
1195 
1196 out:
1197 	free(s);
1198 	if (val)
1199 		json_decref(val);
1200 
1201 	return ret;
1202 }
1203 
1204 static bool stratum_notify(struct stratum_ctx *sctx, json_t *params)
1205 {
1206 	const char *job_id, *prevhash, *coinb1, *coinb2, *version, *nbits, *ntime;
1207 	size_t coinb1_size, coinb2_size;
1208 	bool clean, ret = false;
1209 	int merkle_count, i;
1210 	json_t *merkle_arr;
1211 	unsigned char **merkle;
1212 
1213 	job_id = json_string_value(json_array_get(params, 0));
1214 	prevhash = json_string_value(json_array_get(params, 1));
1215 	coinb1 = json_string_value(json_array_get(params, 2));
1216 	coinb2 = json_string_value(json_array_get(params, 3));
1217 	merkle_arr = json_array_get(params, 4);
1218 	if (!merkle_arr || !json_is_array(merkle_arr))
1219 		goto out;
1220 	merkle_count = json_array_size(merkle_arr);
1221 	version = json_string_value(json_array_get(params, 5));
1222 	nbits = json_string_value(json_array_get(params, 6));
1223 	ntime = json_string_value(json_array_get(params, 7));
1224 	clean = json_is_true(json_array_get(params, 8));
1225 
1226 	if (!job_id || !prevhash || !coinb1 || !coinb2 || !version || !nbits || !ntime ||
1227 	    strlen(prevhash) != 64 || strlen(version) != 8 ||
1228 	    strlen(nbits) != 8 || strlen(ntime) != 8) {
1229 		applog(LOG_ERR, "Stratum notify: invalid parameters");
1230 		goto out;
1231 	}
1232 	merkle = malloc(merkle_count * sizeof(char *));
1233 	for (i = 0; i < merkle_count; i++) {
1234 		const char *s = json_string_value(json_array_get(merkle_arr, i));
1235 		if (!s || strlen(s) != 64) {
1236 			while (i--)
1237 				free(merkle[i]);
1238 			free(merkle);
1239 			applog(LOG_ERR, "Stratum notify: invalid Merkle branch");
1240 			goto out;
1241 		}
1242 		merkle[i] = malloc(32);
1243 		hex2bin(merkle[i], s, 32);
1244 	}
1245 
1246 	pthread_mutex_lock(&sctx->work_lock);
1247 
1248 	coinb1_size = strlen(coinb1) / 2;
1249 	coinb2_size = strlen(coinb2) / 2;
1250 	sctx->job.coinbase_size = coinb1_size + sctx->xnonce1_size +
1251 	                          sctx->xnonce2_size + coinb2_size;
1252 	sctx->job.coinbase = realloc(sctx->job.coinbase, sctx->job.coinbase_size);
1253 	sctx->job.xnonce2 = sctx->job.coinbase + coinb1_size + sctx->xnonce1_size;
1254 	hex2bin(sctx->job.coinbase, coinb1, coinb1_size);
1255 	memcpy(sctx->job.coinbase + coinb1_size, sctx->xnonce1, sctx->xnonce1_size);
1256 	if (!sctx->job.job_id || strcmp(sctx->job.job_id, job_id))
1257 		memset(sctx->job.xnonce2, 0, sctx->xnonce2_size);
1258 	hex2bin(sctx->job.xnonce2 + sctx->xnonce2_size, coinb2, coinb2_size);
1259 
1260 	free(sctx->job.job_id);
1261 	sctx->job.job_id = strdup(job_id);
1262 	hex2bin(sctx->job.prevhash, prevhash, 32);
1263 
1264 	for (i = 0; i < sctx->job.merkle_count; i++)
1265 		free(sctx->job.merkle[i]);
1266 	free(sctx->job.merkle);
1267 	sctx->job.merkle = merkle;
1268 	sctx->job.merkle_count = merkle_count;
1269 
1270 	hex2bin(sctx->job.version, version, 4);
1271 	hex2bin(sctx->job.nbits, nbits, 4);
1272 	hex2bin(sctx->job.ntime, ntime, 4);
1273 	sctx->job.clean = clean;
1274 
1275 	sctx->job.diff = sctx->next_diff;
1276 
1277 	pthread_mutex_unlock(&sctx->work_lock);
1278 
1279 	ret = true;
1280 
1281 out:
1282 	return ret;
1283 }
1284 
1285 static bool stratum_set_difficulty(struct stratum_ctx *sctx, json_t *params)
1286 {
1287 	double diff;
1288 
1289 	diff = json_number_value(json_array_get(params, 0));
1290 	if (diff == 0)
1291 		return false;
1292 
1293 	pthread_mutex_lock(&sctx->work_lock);
1294 	sctx->next_diff = diff;
1295 	pthread_mutex_unlock(&sctx->work_lock);
1296 
1297 	if (opt_debug)
1298 		applog(LOG_DEBUG, "Stratum difficulty set to %g", diff);
1299 
1300 	return true;
1301 }
1302 
1303 static bool stratum_reconnect(struct stratum_ctx *sctx, json_t *params)
1304 {
1305 	json_t *port_val;
1306 	char *url;
1307 	const char *host;
1308 	int port;
1309 
1310 	host = json_string_value(json_array_get(params, 0));
1311 	port_val = json_array_get(params, 1);
1312 	if (json_is_string(port_val))
1313 		port = atoi(json_string_value(port_val));
1314 	else
1315 		port = json_integer_value(port_val);
1316 	if (!host || !port)
1317 		return false;
1318 
1319 	url = malloc(32 + strlen(host));
1320 	strncpy(url, sctx->url, 15);
1321 	sprintf(strstr(url, "://") + 3, "%s:%d", host, port);
1322 
1323 	if (!opt_redirect) {
1324 		applog(LOG_INFO, "Ignoring request to reconnect to %s", url);
1325 		free(url);
1326 		return true;
1327 	}
1328 
1329 	applog(LOG_NOTICE, "Server requested reconnection to %s", url);
1330 
1331 	free(sctx->url);
1332 	sctx->url = url;
1333 	stratum_disconnect(sctx);
1334 
1335 	return true;
1336 }
1337 
1338 static bool stratum_get_version(struct stratum_ctx *sctx, json_t *id)
1339 {
1340 	char *s;
1341 	json_t *val;
1342 	bool ret;
1343 
1344 	if (!id || json_is_null(id))
1345 		return false;
1346 
1347 	val = json_object();
1348 	json_object_set(val, "id", id);
1349 	json_object_set_new(val, "error", json_null());
1350 	json_object_set_new(val, "result", json_string(USER_AGENT));
1351 	s = json_dumps(val, 0);
1352 	ret = stratum_send_line(sctx, s);
1353 	json_decref(val);
1354 	free(s);
1355 
1356 	return ret;
1357 }
1358 
1359 static bool stratum_show_message(struct stratum_ctx *sctx, json_t *id, json_t *params)
1360 {
1361 	char *s;
1362 	json_t *val;
1363 	bool ret;
1364 
1365 	val = json_array_get(params, 0);
1366 	if (val)
1367 		applog(LOG_NOTICE, "MESSAGE FROM SERVER: %s", json_string_value(val));
1368 
1369 	if (!id || json_is_null(id))
1370 		return true;
1371 
1372 	val = json_object();
1373 	json_object_set(val, "id", id);
1374 	json_object_set_new(val, "error", json_null());
1375 	json_object_set_new(val, "result", json_true());
1376 	s = json_dumps(val, 0);
1377 	ret = stratum_send_line(sctx, s);
1378 	json_decref(val);
1379 	free(s);
1380 
1381 	return ret;
1382 }
1383 
1384 bool stratum_handle_method(struct stratum_ctx *sctx, const char *s)
1385 {
1386 	json_t *val, *id, *params;
1387 	json_error_t err;
1388 	const char *method;
1389 	bool ret = false;
1390 
1391 	val = JSON_LOADS(s, &err);
1392 	if (!val) {
1393 		applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
1394 		goto out;
1395 	}
1396 
1397 	method = json_string_value(json_object_get(val, "method"));
1398 	if (!method)
1399 		goto out;
1400 	id = json_object_get(val, "id");
1401 	params = json_object_get(val, "params");
1402 
1403 	if (!strcasecmp(method, "mining.notify")) {
1404 		ret = stratum_notify(sctx, params);
1405 		goto out;
1406 	}
1407 	if (!strcasecmp(method, "mining.set_difficulty")) {
1408 		ret = stratum_set_difficulty(sctx, params);
1409 		goto out;
1410 	}
1411 	if (!strcasecmp(method, "client.reconnect")) {
1412 		ret = stratum_reconnect(sctx, params);
1413 		goto out;
1414 	}
1415 	if (!strcasecmp(method, "client.get_version")) {
1416 		ret = stratum_get_version(sctx, id);
1417 		goto out;
1418 	}
1419 	if (!strcasecmp(method, "client.show_message")) {
1420 		ret = stratum_show_message(sctx, id, params);
1421 		goto out;
1422 	}
1423 
1424 out:
1425 	if (val)
1426 		json_decref(val);
1427 
1428 	return ret;
1429 }
1430 
1431 struct thread_q *tq_new(void)
1432 {
1433 	struct thread_q *tq;
1434 
1435 	tq = calloc(1, sizeof(*tq));
1436 	if (!tq)
1437 		return NULL;
1438 
1439 	INIT_LIST_HEAD(&tq->q);
1440 	pthread_mutex_init(&tq->mutex, NULL);
1441 	pthread_cond_init(&tq->cond, NULL);
1442 
1443 	return tq;
1444 }
1445 
1446 void tq_free(struct thread_q *tq)
1447 {
1448 	struct tq_ent *ent, *iter;
1449 
1450 	if (!tq)
1451 		return;
1452 
1453 	list_for_each_entry_safe(ent, iter, &tq->q, q_node, struct tq_ent) {
1454 		list_del(&ent->q_node);
1455 		free(ent);
1456 	}
1457 
1458 	pthread_cond_destroy(&tq->cond);
1459 	pthread_mutex_destroy(&tq->mutex);
1460 
1461 	memset(tq, 0, sizeof(*tq));	/* poison */
1462 	free(tq);
1463 }
1464 
1465 static void tq_freezethaw(struct thread_q *tq, bool frozen)
1466 {
1467 	pthread_mutex_lock(&tq->mutex);
1468 
1469 	tq->frozen = frozen;
1470 
1471 	pthread_cond_signal(&tq->cond);
1472 	pthread_mutex_unlock(&tq->mutex);
1473 }
1474 
1475 void tq_freeze(struct thread_q *tq)
1476 {
1477 	tq_freezethaw(tq, true);
1478 }
1479 
1480 void tq_thaw(struct thread_q *tq)
1481 {
1482 	tq_freezethaw(tq, false);
1483 }
1484 
1485 bool tq_push(struct thread_q *tq, void *data)
1486 {
1487 	struct tq_ent *ent;
1488 	bool rc = true;
1489 
1490 	ent = calloc(1, sizeof(*ent));
1491 	if (!ent)
1492 		return false;
1493 
1494 	ent->data = data;
1495 	INIT_LIST_HEAD(&ent->q_node);
1496 
1497 	pthread_mutex_lock(&tq->mutex);
1498 
1499 	if (!tq->frozen) {
1500 		list_add_tail(&ent->q_node, &tq->q);
1501 	} else {
1502 		free(ent);
1503 		rc = false;
1504 	}
1505 
1506 	pthread_cond_signal(&tq->cond);
1507 	pthread_mutex_unlock(&tq->mutex);
1508 
1509 	return rc;
1510 }
1511 
1512 void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
1513 {
1514 	struct tq_ent *ent;
1515 	void *rval = NULL;
1516 	int rc;
1517 
1518 	pthread_mutex_lock(&tq->mutex);
1519 
1520 	if (!list_empty(&tq->q))
1521 		goto pop;
1522 
1523 	if (abstime)
1524 		rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
1525 	else
1526 		rc = pthread_cond_wait(&tq->cond, &tq->mutex);
1527 	if (rc)
1528 		goto out;
1529 	if (list_empty(&tq->q))
1530 		goto out;
1531 
1532 pop:
1533 	ent = list_entry(tq->q.next, struct tq_ent, q_node);
1534 	rval = ent->data;
1535 
1536 	list_del(&ent->q_node);
1537 	free(ent);
1538 
1539 out:
1540 	pthread_mutex_unlock(&tq->mutex);
1541 	return rval;
1542 }
1543