util.c 32 KB

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