util.c 33 KB

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