util.c 33 KB

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