util.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  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 ||(err_val && !json_is_null(err_val))) {
  375. char *s;
  376. if (err_val)
  377. s = json_dumps(err_val, JSON_INDENT(3));
  378. else
  379. s = strdup("(unknown reason)");
  380. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  381. free(s);
  382. goto err_out;
  383. }
  384. if (hi.reason) {
  385. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  386. free(hi.reason);
  387. hi.reason = NULL;
  388. }
  389. successful_connect = true;
  390. databuf_free(&all_data);
  391. curl_slist_free_all(headers);
  392. curl_easy_reset(curl);
  393. return val;
  394. err_out:
  395. databuf_free(&all_data);
  396. curl_slist_free_all(headers);
  397. curl_easy_reset(curl);
  398. if (!successful_connect)
  399. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  400. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  401. return NULL;
  402. }
  403. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  404. static struct {
  405. const char *name;
  406. curl_proxytype proxytype;
  407. } proxynames[] = {
  408. { "http:", CURLPROXY_HTTP },
  409. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  410. { "http0:", CURLPROXY_HTTP_1_0 },
  411. #endif
  412. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  413. { "socks4:", CURLPROXY_SOCKS4 },
  414. #endif
  415. { "socks5:", CURLPROXY_SOCKS5 },
  416. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  417. { "socks4a:", CURLPROXY_SOCKS4A },
  418. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  419. #endif
  420. { NULL, 0 }
  421. };
  422. #endif
  423. const char *proxytype(curl_proxytype proxytype)
  424. {
  425. int i;
  426. for (i = 0; proxynames[i].name; i++)
  427. if (proxynames[i].proxytype == proxytype)
  428. return proxynames[i].name;
  429. return "invalid";
  430. }
  431. char *get_proxy(char *url, struct pool *pool)
  432. {
  433. pool->rpc_proxy = NULL;
  434. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  435. char *split;
  436. int plen, len, i;
  437. for (i = 0; proxynames[i].name; i++) {
  438. plen = strlen(proxynames[i].name);
  439. if (strncmp(url, proxynames[i].name, plen) == 0) {
  440. if (!(split = strchr(url, '|')))
  441. return url;
  442. *split = '\0';
  443. len = split - url;
  444. pool->rpc_proxy = malloc(1 + len - plen);
  445. if (!(pool->rpc_proxy))
  446. quit(1, "Failed to malloc rpc_proxy");
  447. strcpy(pool->rpc_proxy, url + plen);
  448. pool->rpc_proxytype = proxynames[i].proxytype;
  449. url = split + 1;
  450. break;
  451. }
  452. }
  453. #endif
  454. return url;
  455. }
  456. /* Returns a malloced array string of a binary value of arbitrary length. The
  457. * array is rounded up to a 4 byte size to appease architectures that need
  458. * aligned array sizes */
  459. char *bin2hex(const unsigned char *p, size_t len)
  460. {
  461. unsigned int i;
  462. ssize_t slen;
  463. char *s;
  464. slen = len * 2 + 1;
  465. if (slen % 4)
  466. slen += 4 - (slen % 4);
  467. s = calloc(slen, 1);
  468. if (unlikely(!s))
  469. quit(1, "Failed to calloc in bin2hex");
  470. for (i = 0; i < len; i++)
  471. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  472. return s;
  473. }
  474. /* Does the reverse of bin2hex but does not allocate any ram */
  475. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  476. {
  477. bool ret = false;
  478. while (*hexstr && len) {
  479. char hex_byte[4];
  480. unsigned int v;
  481. if (unlikely(!hexstr[1])) {
  482. applog(LOG_ERR, "hex2bin str truncated");
  483. return ret;
  484. }
  485. memset(hex_byte, 0, 4);
  486. hex_byte[0] = hexstr[0];
  487. hex_byte[1] = hexstr[1];
  488. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  489. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  490. return ret;
  491. }
  492. *p = (unsigned char) v;
  493. p++;
  494. hexstr += 2;
  495. len--;
  496. }
  497. if (likely(len == 0 && *hexstr == 0))
  498. ret = true;
  499. return ret;
  500. }
  501. bool fulltest(const unsigned char *hash, const unsigned char *target)
  502. {
  503. unsigned char hash_swap[32], target_swap[32];
  504. uint32_t *hash32 = (uint32_t *) hash_swap;
  505. uint32_t *target32 = (uint32_t *) target_swap;
  506. char *hash_str, *target_str;
  507. bool rc = true;
  508. int i;
  509. swap256(hash_swap, hash);
  510. swap256(target_swap, target);
  511. for (i = 0; i < 32/4; i++) {
  512. uint32_t h32tmp = swab32(hash32[i]);
  513. uint32_t t32tmp = target32[i];
  514. target32[i] = swab32(target32[i]); /* for printing */
  515. if (h32tmp > t32tmp) {
  516. rc = false;
  517. break;
  518. }
  519. if (h32tmp < t32tmp) {
  520. rc = true;
  521. break;
  522. }
  523. }
  524. if (opt_debug) {
  525. hash_str = bin2hex(hash_swap, 32);
  526. target_str = bin2hex(target_swap, 32);
  527. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  528. hash_str,
  529. target_str,
  530. rc ? "YES (hash < target)" :
  531. "no (false positive; hash > target)");
  532. free(hash_str);
  533. free(target_str);
  534. }
  535. return rc;
  536. }
  537. struct thread_q *tq_new(void)
  538. {
  539. struct thread_q *tq;
  540. tq = calloc(1, sizeof(*tq));
  541. if (!tq)
  542. return NULL;
  543. INIT_LIST_HEAD(&tq->q);
  544. pthread_mutex_init(&tq->mutex, NULL);
  545. pthread_cond_init(&tq->cond, NULL);
  546. return tq;
  547. }
  548. void tq_free(struct thread_q *tq)
  549. {
  550. struct tq_ent *ent, *iter;
  551. if (!tq)
  552. return;
  553. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  554. list_del(&ent->q_node);
  555. free(ent);
  556. }
  557. pthread_cond_destroy(&tq->cond);
  558. pthread_mutex_destroy(&tq->mutex);
  559. memset(tq, 0, sizeof(*tq)); /* poison */
  560. free(tq);
  561. }
  562. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  563. {
  564. mutex_lock(&tq->mutex);
  565. tq->frozen = frozen;
  566. pthread_cond_signal(&tq->cond);
  567. mutex_unlock(&tq->mutex);
  568. }
  569. void tq_freeze(struct thread_q *tq)
  570. {
  571. tq_freezethaw(tq, true);
  572. }
  573. void tq_thaw(struct thread_q *tq)
  574. {
  575. tq_freezethaw(tq, false);
  576. }
  577. bool tq_push(struct thread_q *tq, void *data)
  578. {
  579. struct tq_ent *ent;
  580. bool rc = true;
  581. ent = calloc(1, sizeof(*ent));
  582. if (!ent)
  583. return false;
  584. ent->data = data;
  585. INIT_LIST_HEAD(&ent->q_node);
  586. mutex_lock(&tq->mutex);
  587. if (!tq->frozen) {
  588. list_add_tail(&ent->q_node, &tq->q);
  589. } else {
  590. free(ent);
  591. rc = false;
  592. }
  593. pthread_cond_signal(&tq->cond);
  594. mutex_unlock(&tq->mutex);
  595. return rc;
  596. }
  597. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  598. {
  599. struct tq_ent *ent;
  600. void *rval = NULL;
  601. int rc;
  602. mutex_lock(&tq->mutex);
  603. if (!list_empty(&tq->q))
  604. goto pop;
  605. if (abstime)
  606. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  607. else
  608. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  609. if (rc)
  610. goto out;
  611. if (list_empty(&tq->q))
  612. goto out;
  613. pop:
  614. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  615. rval = ent->data;
  616. list_del(&ent->q_node);
  617. free(ent);
  618. out:
  619. mutex_unlock(&tq->mutex);
  620. return rval;
  621. }
  622. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  623. {
  624. return pthread_create(&thr->pth, attr, start, arg);
  625. }
  626. void thr_info_freeze(struct thr_info *thr)
  627. {
  628. struct tq_ent *ent, *iter;
  629. struct thread_q *tq;
  630. if (!thr)
  631. return;
  632. tq = thr->q;
  633. if (!tq)
  634. return;
  635. mutex_lock(&tq->mutex);
  636. tq->frozen = true;
  637. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  638. list_del(&ent->q_node);
  639. free(ent);
  640. }
  641. mutex_unlock(&tq->mutex);
  642. }
  643. void thr_info_cancel(struct thr_info *thr)
  644. {
  645. if (!thr)
  646. return;
  647. if (PTH(thr) != 0L) {
  648. pthread_cancel(thr->pth);
  649. PTH(thr) = 0L;
  650. }
  651. }
  652. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  653. * on SMP machines */
  654. void nmsleep(unsigned int msecs)
  655. {
  656. struct timespec twait, tleft;
  657. int ret;
  658. ldiv_t d;
  659. d = ldiv(msecs, 1000);
  660. tleft.tv_sec = d.quot;
  661. tleft.tv_nsec = d.rem * 1000000;
  662. do {
  663. twait.tv_sec = tleft.tv_sec;
  664. twait.tv_nsec = tleft.tv_nsec;
  665. ret = nanosleep(&twait, &tleft);
  666. } while (ret == -1 && errno == EINTR);
  667. }
  668. /* Returns the microseconds difference between end and start times as a double */
  669. double us_tdiff(struct timeval *end, struct timeval *start)
  670. {
  671. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  672. }
  673. /* Returns the seconds difference between end and start times as a double */
  674. double tdiff(struct timeval *end, struct timeval *start)
  675. {
  676. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  677. }
  678. bool extract_sockaddr(struct pool *pool, char *url)
  679. {
  680. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  681. char url_address[256], port[6];
  682. int url_len, port_len = 0;
  683. pool->sockaddr_url = url;
  684. url_begin = strstr(url, "//");
  685. if (!url_begin)
  686. url_begin = url;
  687. else
  688. url_begin += 2;
  689. /* Look for numeric ipv6 entries */
  690. ipv6_begin = strstr(url_begin, "[");
  691. ipv6_end = strstr(url_begin, "]");
  692. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  693. url_end = strstr(ipv6_end, ":");
  694. else
  695. url_end = strstr(url_begin, ":");
  696. if (url_end) {
  697. url_len = url_end - url_begin;
  698. port_len = strlen(url_begin) - url_len - 1;
  699. if (port_len < 1)
  700. return false;
  701. port_start = url_end + 1;
  702. } else
  703. url_len = strlen(url_begin);
  704. if (url_len < 1)
  705. return false;
  706. sprintf(url_address, "%.*s", url_len, url_begin);
  707. if (port_len)
  708. snprintf(port, 6, "%.*s", port_len, port_start);
  709. else
  710. strcpy(port, "80");
  711. pool->stratum_port = strdup(port);
  712. pool->sockaddr_url = strdup(url_address);
  713. return true;
  714. }
  715. /* Send a single command across a socket, appending \n to it. This should all
  716. * be done under stratum lock except when first establishing the socket */
  717. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  718. {
  719. SOCKETTYPE sock = pool->sock;
  720. ssize_t ssent = 0;
  721. if (opt_protocol)
  722. applog(LOG_DEBUG, "SEND: %s", s);
  723. strcat(s, "\n");
  724. len++;
  725. while (len > 0 ) {
  726. struct timeval timeout = {0, 0};
  727. size_t sent = 0;
  728. CURLcode rc;
  729. fd_set wd;
  730. FD_ZERO(&wd);
  731. FD_SET(sock, &wd);
  732. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  733. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  734. return false;
  735. }
  736. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  737. if (rc != CURLE_OK) {
  738. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  739. return false;
  740. }
  741. ssent += sent;
  742. len -= ssent;
  743. }
  744. return true;
  745. }
  746. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  747. {
  748. bool ret = false;
  749. mutex_lock(&pool->stratum_lock);
  750. if (pool->stratum_active)
  751. ret = __stratum_send(pool, s, len);
  752. else
  753. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  754. mutex_unlock(&pool->stratum_lock);
  755. return ret;
  756. }
  757. static void clear_sock(struct pool *pool)
  758. {
  759. size_t n = 0;
  760. mutex_lock(&pool->stratum_lock);
  761. /* Ignore return code of curl_easy_recv since we're just clearing
  762. * anything in the socket if it's still alive */
  763. curl_easy_recv(pool->stratum_curl, pool->sockbuf, RECVSIZE, &n);
  764. mutex_unlock(&pool->stratum_lock);
  765. strcpy(pool->sockbuf, "");
  766. }
  767. /* Check to see if Santa's been good to you */
  768. static bool sock_full(struct pool *pool, bool wait)
  769. {
  770. SOCKETTYPE sock = pool->sock;
  771. struct timeval timeout;
  772. fd_set rd;
  773. if (strlen(pool->sockbuf))
  774. return true;
  775. FD_ZERO(&rd);
  776. FD_SET(sock, &rd);
  777. timeout.tv_usec = 0;
  778. if (wait)
  779. timeout.tv_sec = 60;
  780. else
  781. timeout.tv_sec = 0;
  782. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  783. return true;
  784. return false;
  785. }
  786. /* Peeks at a socket to find the first end of line and then reads just that
  787. * from the socket and returns that as a malloced char */
  788. char *recv_line(struct pool *pool)
  789. {
  790. ssize_t len, buflen;
  791. char *tok, *sret = NULL;
  792. size_t n = 0;
  793. if (!strstr(pool->sockbuf, "\n")) {
  794. char s[RBUFSIZE];
  795. size_t sspace;
  796. CURLcode rc;
  797. if (!sock_full(pool, true)) {
  798. applog(LOG_DEBUG, "Timed out waiting for data on sock_full");
  799. goto out;
  800. }
  801. memset(s, 0, RBUFSIZE);
  802. mutex_lock(&pool->stratum_lock);
  803. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  804. mutex_unlock(&pool->stratum_lock);
  805. if (rc != CURLE_OK) {
  806. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  807. goto out;
  808. }
  809. /* Prevent buffer overflows, but if 8k is still not enough,
  810. * likely we have had some comms issues and the data is all
  811. * useless anyway */
  812. sspace = RECVSIZE - strlen(pool->sockbuf);
  813. strncat(pool->sockbuf, s, sspace);
  814. }
  815. buflen = strlen(pool->sockbuf);
  816. tok = strtok(pool->sockbuf, "\n");
  817. if (!tok) {
  818. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  819. goto out;
  820. }
  821. sret = strdup(tok);
  822. len = strlen(sret);
  823. /* Copy what's left in the buffer after the \n, including the
  824. * terminating \0 */
  825. if (buflen > len + 1)
  826. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  827. else
  828. strcpy(pool->sockbuf, "");
  829. out:
  830. if (!sret)
  831. clear_sock(pool);
  832. else if (opt_protocol)
  833. applog(LOG_DEBUG, "RECVD: %s", sret);
  834. return sret;
  835. }
  836. /* Extracts a string value from a json array with error checking. To be used
  837. * when the value of the string returned is only examined and not to be stored.
  838. * See json_array_string below */
  839. static char *__json_array_string(json_t *val, unsigned int entry)
  840. {
  841. json_t *arr_entry;
  842. if (json_is_null(val))
  843. return NULL;
  844. if (!json_is_array(val))
  845. return NULL;
  846. if (entry > json_array_size(val))
  847. return NULL;
  848. arr_entry = json_array_get(val, entry);
  849. if (!json_is_string(arr_entry))
  850. return NULL;
  851. return (char *)json_string_value(arr_entry);
  852. }
  853. /* Creates a freshly malloced dup of __json_array_string */
  854. static char *json_array_string(json_t *val, unsigned int entry)
  855. {
  856. char *buf = __json_array_string(val, entry);
  857. if (buf)
  858. return strdup(buf);
  859. return NULL;
  860. }
  861. static bool parse_notify(struct pool *pool, json_t *val)
  862. {
  863. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  864. int merkles, i;
  865. json_t *arr;
  866. bool clean;
  867. arr = json_array_get(val, 4);
  868. if (!arr || !json_is_array(arr))
  869. return false;
  870. merkles = json_array_size(arr);
  871. job_id = json_array_string(val, 0);
  872. prev_hash = json_array_string(val, 1);
  873. coinbase1 = json_array_string(val, 2);
  874. coinbase2 = json_array_string(val, 3);
  875. bbversion = json_array_string(val, 5);
  876. nbit = json_array_string(val, 6);
  877. ntime = json_array_string(val, 7);
  878. clean = json_is_true(json_array_get(val, 8));
  879. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  880. /* Annoying but we must not leak memory */
  881. if (job_id)
  882. free(job_id);
  883. if (prev_hash)
  884. free(prev_hash);
  885. if (coinbase1)
  886. free(coinbase1);
  887. if (coinbase2)
  888. free(coinbase2);
  889. if (bbversion)
  890. free(bbversion);
  891. if (nbit)
  892. free(nbit);
  893. if (ntime)
  894. free(ntime);
  895. return false;
  896. }
  897. mutex_lock(&pool->pool_lock);
  898. free(pool->swork.job_id);
  899. free(pool->swork.prev_hash);
  900. free(pool->swork.coinbase1);
  901. free(pool->swork.coinbase2);
  902. free(pool->swork.bbversion);
  903. free(pool->swork.nbit);
  904. free(pool->swork.ntime);
  905. pool->swork.job_id = job_id;
  906. pool->swork.prev_hash = prev_hash;
  907. pool->swork.coinbase1 = coinbase1;
  908. pool->swork.coinbase2 = coinbase2;
  909. pool->swork.bbversion = bbversion;
  910. pool->swork.nbit = nbit;
  911. pool->swork.ntime = ntime;
  912. pool->swork.clean = clean;
  913. for (i = 0; i < pool->swork.merkles; i++)
  914. free(pool->swork.merkle[i]);
  915. if (merkles) {
  916. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  917. for (i = 0; i < merkles; i++)
  918. pool->swork.merkle[i] = json_array_string(arr, i);
  919. }
  920. pool->swork.merkles = merkles;
  921. if (clean)
  922. pool->nonce2 = 0;
  923. mutex_unlock(&pool->pool_lock);
  924. if (opt_protocol) {
  925. applog(LOG_DEBUG, "job_id: %s", job_id);
  926. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  927. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  928. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  929. for (i = 0; i < merkles; i++)
  930. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  931. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  932. applog(LOG_DEBUG, "nbit: %s", nbit);
  933. applog(LOG_DEBUG, "ntime: %s", ntime);
  934. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  935. }
  936. /* A notify message is the closest stratum gets to a getwork */
  937. pool->getwork_requested++;
  938. total_getworks++;
  939. return true;
  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) && parse_notify(pool, params)) {
  1015. ret = true;
  1016. goto out;
  1017. }
  1018. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1019. ret = true;
  1020. goto out;
  1021. }
  1022. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1023. ret = true;
  1024. goto out;
  1025. }
  1026. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1027. ret = true;
  1028. goto out;
  1029. }
  1030. out:
  1031. if (val)
  1032. json_decref(val);
  1033. return ret;
  1034. }
  1035. bool auth_stratum(struct pool *pool)
  1036. {
  1037. json_t *val = NULL, *res_val, *err_val;
  1038. char s[RBUFSIZE], *sret = NULL;
  1039. json_error_t err;
  1040. bool ret = false;
  1041. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1042. swork_id++, pool->rpc_user, pool->rpc_pass);
  1043. if (!stratum_send(pool, s, strlen(s)))
  1044. goto out;
  1045. /* Parse all data in the queue and anything left should be auth */
  1046. while (42) {
  1047. sret = recv_line(pool);
  1048. if (!sret)
  1049. goto out;
  1050. if (parse_method(pool, sret))
  1051. free(sret);
  1052. else
  1053. break;
  1054. }
  1055. val = JSON_LOADS(sret, &err);
  1056. free(sret);
  1057. res_val = json_object_get(val, "result");
  1058. err_val = json_object_get(val, "error");
  1059. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1060. char *ss;
  1061. if (err_val)
  1062. ss = json_dumps(err_val, JSON_INDENT(3));
  1063. else
  1064. ss = strdup("(unknown reason)");
  1065. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1066. free(ss);
  1067. goto out;
  1068. }
  1069. ret = true;
  1070. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1071. out:
  1072. if (val)
  1073. json_decref(val);
  1074. return ret;
  1075. }
  1076. bool initiate_stratum(struct pool *pool)
  1077. {
  1078. json_t *val = NULL, *res_val, *err_val;
  1079. char curl_err_str[CURL_ERROR_SIZE];
  1080. char s[RBUFSIZE], *sret = NULL;
  1081. CURL *curl = NULL;
  1082. json_error_t err;
  1083. bool ret = false;
  1084. mutex_lock(&pool->stratum_lock);
  1085. pool->stratum_active = false;
  1086. if (!pool->stratum_curl) {
  1087. pool->stratum_curl = curl_easy_init();
  1088. if (unlikely(!pool->stratum_curl))
  1089. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1090. }
  1091. mutex_unlock(&pool->stratum_lock);
  1092. curl = pool->stratum_curl;
  1093. /* Create a http url for use with curl */
  1094. memset(s, 0, RBUFSIZE);
  1095. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1096. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1097. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1098. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1099. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1100. curl_easy_setopt(curl, CURLOPT_URL, s);
  1101. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1102. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1103. if (pool->rpc_proxy) {
  1104. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1105. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  1106. } else if (opt_socks_proxy) {
  1107. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1108. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1109. }
  1110. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1111. if (curl_easy_perform(curl)) {
  1112. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1113. goto out;
  1114. }
  1115. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1116. keep_sockalive(pool->sock);
  1117. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1118. if (!__stratum_send(pool, s, strlen(s))) {
  1119. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1120. goto out;
  1121. }
  1122. if (!sock_full(pool, true)) {
  1123. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1124. goto out;
  1125. }
  1126. sret = recv_line(pool);
  1127. if (!sret)
  1128. goto out;
  1129. val = JSON_LOADS(sret, &err);
  1130. free(sret);
  1131. if (!val) {
  1132. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1133. goto out;
  1134. }
  1135. res_val = json_object_get(val, "result");
  1136. err_val = json_object_get(val, "error");
  1137. if (!res_val || json_is_null(res_val) ||
  1138. (err_val && !json_is_null(err_val))) {
  1139. char *ss;
  1140. if (err_val)
  1141. ss = json_dumps(err_val, JSON_INDENT(3));
  1142. else
  1143. ss = strdup("(unknown reason)");
  1144. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1145. free(ss);
  1146. goto out;
  1147. }
  1148. pool->nonce1 = json_array_string(res_val, 1);
  1149. if (!pool->nonce1) {
  1150. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1151. goto out;
  1152. }
  1153. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1154. if (!pool->n2size) {
  1155. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1156. goto out;
  1157. }
  1158. ret = true;
  1159. out:
  1160. if (val)
  1161. json_decref(val);
  1162. if (ret) {
  1163. if (!pool->stratum_url)
  1164. pool->stratum_url = pool->sockaddr_url;
  1165. pool->stratum_active = true;
  1166. pool->swork.diff = 1;
  1167. if (opt_protocol) {
  1168. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1169. pool->pool_no, pool->nonce1, pool->n2size);
  1170. }
  1171. } else
  1172. applog(LOG_DEBUG, "Initiate stratum failed");
  1173. return ret;
  1174. }
  1175. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1176. {
  1177. dev->device_last_not_well = time(NULL);
  1178. dev->device_not_well_reason = reason;
  1179. switch (reason)
  1180. {
  1181. case REASON_THREAD_FAIL_INIT:
  1182. dev->thread_fail_init_count++;
  1183. break;
  1184. case REASON_THREAD_ZERO_HASH:
  1185. dev->thread_zero_hash_count++;
  1186. break;
  1187. case REASON_THREAD_FAIL_QUEUE:
  1188. dev->thread_fail_queue_count++;
  1189. break;
  1190. case REASON_DEV_SICK_IDLE_60:
  1191. dev->dev_sick_idle_60_count++;
  1192. break;
  1193. case REASON_DEV_DEAD_IDLE_600:
  1194. dev->dev_dead_idle_600_count++;
  1195. break;
  1196. case REASON_DEV_NOSTART:
  1197. dev->dev_nostart_count++;
  1198. break;
  1199. case REASON_DEV_OVER_HEAT:
  1200. dev->dev_over_heat_count++;
  1201. break;
  1202. case REASON_DEV_THERMAL_CUTOFF:
  1203. dev->dev_thermal_cutoff_count++;
  1204. break;
  1205. case REASON_DEV_COMMS_ERROR:
  1206. dev->dev_comms_error_count++;
  1207. break;
  1208. case REASON_DEV_THROTTLE:
  1209. dev->dev_throttle_count++;
  1210. break;
  1211. }
  1212. }