util.c 33 KB

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