util.c 32 KB

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