util.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  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 <ws2tcpip.h>
  31. #endif
  32. #include "miner.h"
  33. #include "elist.h"
  34. #include "compat.h"
  35. #include "util.h"
  36. bool successful_connect = false;
  37. struct timeval nettime;
  38. struct data_buffer {
  39. void *buf;
  40. size_t len;
  41. };
  42. struct upload_buffer {
  43. const void *buf;
  44. size_t len;
  45. };
  46. struct header_info {
  47. char *lp_path;
  48. int rolltime;
  49. char *reason;
  50. char *stratum_url;
  51. bool hadrolltime;
  52. bool canroll;
  53. bool hadexpire;
  54. };
  55. struct tq_ent {
  56. void *data;
  57. struct list_head q_node;
  58. };
  59. static void databuf_free(struct data_buffer *db)
  60. {
  61. if (!db)
  62. return;
  63. free(db->buf);
  64. memset(db, 0, sizeof(*db));
  65. }
  66. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  67. void *user_data)
  68. {
  69. struct data_buffer *db = user_data;
  70. size_t len = size * nmemb;
  71. size_t oldlen, newlen;
  72. void *newmem;
  73. static const unsigned char zero = 0;
  74. oldlen = db->len;
  75. newlen = oldlen + len;
  76. newmem = realloc(db->buf, newlen + 1);
  77. if (!newmem)
  78. return 0;
  79. db->buf = newmem;
  80. db->len = newlen;
  81. memcpy(db->buf + oldlen, ptr, len);
  82. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  83. return len;
  84. }
  85. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  86. void *user_data)
  87. {
  88. struct upload_buffer *ub = user_data;
  89. unsigned int len = size * nmemb;
  90. if (len > ub->len)
  91. len = ub->len;
  92. if (len) {
  93. memcpy(ptr, ub->buf, len);
  94. ub->buf += len;
  95. ub->len -= len;
  96. }
  97. return len;
  98. }
  99. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  100. {
  101. struct header_info *hi = user_data;
  102. size_t remlen, slen, ptrlen = size * nmemb;
  103. char *rem, *val = NULL, *key = NULL;
  104. void *tmp;
  105. val = calloc(1, ptrlen);
  106. key = calloc(1, ptrlen);
  107. if (!key || !val)
  108. goto out;
  109. tmp = memchr(ptr, ':', ptrlen);
  110. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  111. goto out;
  112. slen = tmp - ptr;
  113. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  114. goto out;
  115. memcpy(key, ptr, slen); /* store & nul term key */
  116. key[slen] = 0;
  117. rem = ptr + slen + 1; /* trim value's leading whitespace */
  118. remlen = ptrlen - slen - 1;
  119. while ((remlen > 0) && (isspace(*rem))) {
  120. remlen--;
  121. rem++;
  122. }
  123. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  124. val[remlen] = 0;
  125. while ((*val) && (isspace(val[strlen(val) - 1])))
  126. val[strlen(val) - 1] = 0;
  127. if (!*val) /* skip blank value */
  128. goto out;
  129. if (opt_protocol)
  130. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  131. if (!strcasecmp("X-Roll-Ntime", key)) {
  132. hi->hadrolltime = true;
  133. if (!strncasecmp("N", val, 1))
  134. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  135. else {
  136. hi->canroll = true;
  137. /* Check to see if expire= is supported and if not, set
  138. * the rolltime to the default scantime */
  139. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  140. sscanf(val + 7, "%d", &hi->rolltime);
  141. hi->hadexpire = true;
  142. } else
  143. hi->rolltime = opt_scantime;
  144. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  145. }
  146. }
  147. if (!strcasecmp("X-Long-Polling", key)) {
  148. hi->lp_path = val; /* steal memory reference */
  149. val = NULL;
  150. }
  151. if (!strcasecmp("X-Reject-Reason", key)) {
  152. hi->reason = val; /* steal memory reference */
  153. val = NULL;
  154. }
  155. if (!strcasecmp("X-Stratum", key)) {
  156. hi->stratum_url = val;
  157. val = NULL;
  158. }
  159. out:
  160. free(key);
  161. free(val);
  162. return ptrlen;
  163. }
  164. #if CURL_HAS_KEEPALIVE
  165. static void keep_curlalive(CURL *curl)
  166. {
  167. const int tcp_keepidle = 60;
  168. const int tcp_keepintvl = 60;
  169. const long int keepalive = 1;
  170. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
  171. curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, tcp_keepidle);
  172. curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, tcp_keepintvl);
  173. }
  174. static void keep_alive(CURL *curl, __maybe_unused SOCKETTYPE fd)
  175. {
  176. keep_curlalive(curl);
  177. }
  178. #else
  179. static void keep_sockalive(SOCKETTYPE fd)
  180. {
  181. const int tcp_keepidle = 60;
  182. const int tcp_keepintvl = 60;
  183. const int keepalive = 1;
  184. const int tcp_keepcnt = 5;
  185. setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive));
  186. # ifdef __linux
  187. setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt));
  188. setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
  189. setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
  190. # endif /* __linux */
  191. # ifdef __APPLE_CC__
  192. setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
  193. # endif /* __APPLE_CC__ */
  194. }
  195. static void keep_curlalive(CURL *curl)
  196. {
  197. SOCKETTYPE sock;
  198. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
  199. keep_sockalive(sock);
  200. }
  201. static void keep_alive(CURL __maybe_unused *curl, SOCKETTYPE fd)
  202. {
  203. keep_sockalive(fd);
  204. }
  205. #endif
  206. static void last_nettime(struct timeval *last)
  207. {
  208. rd_lock(&netacc_lock);
  209. last->tv_sec = nettime.tv_sec;
  210. last->tv_usec = nettime.tv_usec;
  211. rd_unlock(&netacc_lock);
  212. }
  213. static void set_nettime(void)
  214. {
  215. wr_lock(&netacc_lock);
  216. gettimeofday(&nettime, NULL);
  217. wr_unlock(&netacc_lock);
  218. }
  219. json_t *json_rpc_call(CURL *curl, const char *url,
  220. const char *userpass, const char *rpc_req,
  221. bool probe, bool longpoll, int *rolltime,
  222. struct pool *pool, bool share)
  223. {
  224. long timeout = longpoll ? (60 * 60) : 60;
  225. struct data_buffer all_data = {NULL, 0};
  226. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  227. char len_hdr[64], user_agent_hdr[128];
  228. char curl_err_str[CURL_ERROR_SIZE];
  229. struct curl_slist *headers = NULL;
  230. struct upload_buffer upload_data;
  231. json_t *val, *err_val, *res_val;
  232. bool probing = false;
  233. json_error_t err;
  234. int rc;
  235. memset(&err, 0, sizeof(err));
  236. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  237. if (probe)
  238. probing = !pool->probed;
  239. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  240. #if 0 /* Disable curl debugging since it spews to stderr */
  241. if (opt_protocol)
  242. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  243. #endif
  244. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  245. curl_easy_setopt(curl, CURLOPT_URL, url);
  246. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  247. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  248. /* Shares are staggered already and delays in submission can be costly
  249. * so do not delay them */
  250. if (!opt_delaynet || share)
  251. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  252. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  253. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  254. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  255. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  256. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  257. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  258. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  259. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  260. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  261. if (pool->rpc_proxy) {
  262. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  263. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  264. } else if (opt_socks_proxy) {
  265. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  266. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  267. }
  268. if (userpass) {
  269. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  270. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  271. }
  272. if (longpoll)
  273. keep_curlalive(curl);
  274. curl_easy_setopt(curl, CURLOPT_POST, 1);
  275. if (opt_protocol)
  276. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  277. upload_data.buf = rpc_req;
  278. upload_data.len = strlen(rpc_req);
  279. sprintf(len_hdr, "Content-Length: %lu",
  280. (unsigned long) upload_data.len);
  281. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  282. headers = curl_slist_append(headers,
  283. "Content-type: application/json");
  284. headers = curl_slist_append(headers,
  285. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  286. if (likely(global_hashrate)) {
  287. char ghashrate[255];
  288. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  289. headers = curl_slist_append(headers, ghashrate);
  290. }
  291. headers = curl_slist_append(headers, len_hdr);
  292. headers = curl_slist_append(headers, user_agent_hdr);
  293. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  294. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  295. if (opt_delaynet) {
  296. /* Don't delay share submission, but still track the nettime */
  297. if (!share) {
  298. long long now_msecs, last_msecs;
  299. struct timeval now, last;
  300. gettimeofday(&now, NULL);
  301. last_nettime(&last);
  302. now_msecs = (long long)now.tv_sec * 1000;
  303. now_msecs += now.tv_usec / 1000;
  304. last_msecs = (long long)last.tv_sec * 1000;
  305. last_msecs += last.tv_usec / 1000;
  306. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  307. struct timespec rgtp;
  308. rgtp.tv_sec = 0;
  309. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  310. nanosleep(&rgtp, NULL);
  311. }
  312. }
  313. set_nettime();
  314. }
  315. rc = curl_easy_perform(curl);
  316. if (rc) {
  317. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  318. goto err_out;
  319. }
  320. if (!all_data.buf) {
  321. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  322. goto err_out;
  323. }
  324. if (probing) {
  325. pool->probed = true;
  326. /* If X-Long-Polling was found, activate long polling */
  327. if (hi.lp_path) {
  328. if (pool->hdr_path != NULL)
  329. free(pool->hdr_path);
  330. pool->hdr_path = hi.lp_path;
  331. } else
  332. pool->hdr_path = NULL;
  333. if (hi.stratum_url) {
  334. pool->stratum_url = hi.stratum_url;
  335. hi.stratum_url = NULL;
  336. }
  337. } else {
  338. if (hi.lp_path) {
  339. free(hi.lp_path);
  340. hi.lp_path = NULL;
  341. }
  342. if (hi.stratum_url) {
  343. free(hi.stratum_url);
  344. hi.stratum_url = NULL;
  345. }
  346. }
  347. *rolltime = hi.rolltime;
  348. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  349. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  350. pool->cgminer_pool_stats.canroll = hi.canroll;
  351. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  352. val = JSON_LOADS(all_data.buf, &err);
  353. if (!val) {
  354. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  355. if (opt_protocol)
  356. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  357. goto err_out;
  358. }
  359. if (opt_protocol) {
  360. char *s = json_dumps(val, JSON_INDENT(3));
  361. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  362. free(s);
  363. }
  364. /* JSON-RPC valid response returns a non-null 'result',
  365. * and a null 'error'.
  366. */
  367. res_val = json_object_get(val, "result");
  368. err_val = json_object_get(val, "error");
  369. if (!res_val ||(err_val && !json_is_null(err_val))) {
  370. char *s;
  371. if (err_val)
  372. s = json_dumps(err_val, JSON_INDENT(3));
  373. else
  374. s = strdup("(unknown reason)");
  375. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  376. free(s);
  377. goto err_out;
  378. }
  379. if (hi.reason) {
  380. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  381. free(hi.reason);
  382. hi.reason = NULL;
  383. }
  384. successful_connect = true;
  385. databuf_free(&all_data);
  386. curl_slist_free_all(headers);
  387. curl_easy_reset(curl);
  388. return val;
  389. err_out:
  390. databuf_free(&all_data);
  391. curl_slist_free_all(headers);
  392. curl_easy_reset(curl);
  393. if (!successful_connect)
  394. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  395. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  396. return NULL;
  397. }
  398. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  399. static struct {
  400. const char *name;
  401. curl_proxytype proxytype;
  402. } proxynames[] = {
  403. { "http:", CURLPROXY_HTTP },
  404. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  405. { "http0:", CURLPROXY_HTTP_1_0 },
  406. #endif
  407. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  408. { "socks4:", CURLPROXY_SOCKS4 },
  409. #endif
  410. { "socks5:", CURLPROXY_SOCKS5 },
  411. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  412. { "socks4a:", CURLPROXY_SOCKS4A },
  413. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  414. #endif
  415. { NULL, 0 }
  416. };
  417. #endif
  418. const char *proxytype(curl_proxytype proxytype)
  419. {
  420. int i;
  421. for (i = 0; proxynames[i].name; i++)
  422. if (proxynames[i].proxytype == proxytype)
  423. return proxynames[i].name;
  424. return "invalid";
  425. }
  426. char *get_proxy(char *url, struct pool *pool)
  427. {
  428. pool->rpc_proxy = NULL;
  429. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  430. char *split;
  431. int plen, len, i;
  432. for (i = 0; proxynames[i].name; i++) {
  433. plen = strlen(proxynames[i].name);
  434. if (strncmp(url, proxynames[i].name, plen) == 0) {
  435. if (!(split = strchr(url, '|')))
  436. return url;
  437. *split = '\0';
  438. len = split - url;
  439. pool->rpc_proxy = malloc(1 + len - plen);
  440. if (!(pool->rpc_proxy))
  441. quit(1, "Failed to malloc rpc_proxy");
  442. strcpy(pool->rpc_proxy, url + plen);
  443. pool->rpc_proxytype = proxynames[i].proxytype;
  444. url = split + 1;
  445. break;
  446. }
  447. }
  448. #endif
  449. return url;
  450. }
  451. /* Returns a malloced array string of a binary value of arbitrary length. The
  452. * array is rounded up to a 4 byte size to appease architectures that need
  453. * aligned array sizes */
  454. char *bin2hex(const unsigned char *p, size_t len)
  455. {
  456. unsigned int i;
  457. ssize_t slen;
  458. char *s;
  459. slen = len * 2 + 1;
  460. if (slen % 4)
  461. slen += 4 - (slen % 4);
  462. s = calloc(slen, 1);
  463. if (unlikely(!s))
  464. quit(1, "Failed to calloc in bin2hex");
  465. for (i = 0; i < len; i++)
  466. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  467. return s;
  468. }
  469. /* Does the reverse of bin2hex but does not allocate any ram */
  470. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  471. {
  472. bool ret = false;
  473. while (*hexstr && len) {
  474. char hex_byte[4];
  475. unsigned int v;
  476. if (unlikely(!hexstr[1])) {
  477. applog(LOG_ERR, "hex2bin str truncated");
  478. return ret;
  479. }
  480. memset(hex_byte, 0, 4);
  481. hex_byte[0] = hexstr[0];
  482. hex_byte[1] = hexstr[1];
  483. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  484. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  485. return ret;
  486. }
  487. *p = (unsigned char) v;
  488. p++;
  489. hexstr += 2;
  490. len--;
  491. }
  492. if (likely(len == 0 && *hexstr == 0))
  493. ret = true;
  494. return ret;
  495. }
  496. bool fulltest(const unsigned char *hash, const unsigned char *target)
  497. {
  498. unsigned char hash_swap[32], target_swap[32];
  499. uint32_t *hash32 = (uint32_t *) hash_swap;
  500. uint32_t *target32 = (uint32_t *) target_swap;
  501. char *hash_str, *target_str;
  502. bool rc = true;
  503. int i;
  504. swap256(hash_swap, hash);
  505. swap256(target_swap, target);
  506. for (i = 0; i < 32/4; i++) {
  507. #ifdef MIPSEB
  508. uint32_t h32tmp = hash32[i];
  509. uint32_t t32tmp = swab32(target32[i]);
  510. #else
  511. uint32_t h32tmp = swab32(hash32[i]);
  512. uint32_t t32tmp = target32[i];
  513. #endif
  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. pool->probed = true;
  1072. successful_connect = true;
  1073. out:
  1074. if (val)
  1075. json_decref(val);
  1076. return ret;
  1077. }
  1078. bool initiate_stratum(struct pool *pool)
  1079. {
  1080. json_t *val = NULL, *res_val, *err_val;
  1081. char curl_err_str[CURL_ERROR_SIZE];
  1082. char s[RBUFSIZE], *sret = NULL;
  1083. CURL *curl = NULL;
  1084. json_error_t err;
  1085. bool ret = false;
  1086. mutex_lock(&pool->stratum_lock);
  1087. pool->stratum_active = false;
  1088. if (!pool->stratum_curl) {
  1089. pool->stratum_curl = curl_easy_init();
  1090. if (unlikely(!pool->stratum_curl))
  1091. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1092. }
  1093. mutex_unlock(&pool->stratum_lock);
  1094. curl = pool->stratum_curl;
  1095. /* Create a http url for use with curl */
  1096. memset(s, 0, RBUFSIZE);
  1097. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1098. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1099. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1100. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1101. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1102. curl_easy_setopt(curl, CURLOPT_URL, s);
  1103. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1104. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1105. if (pool->rpc_proxy) {
  1106. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1107. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  1108. } else if (opt_socks_proxy) {
  1109. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1110. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1111. }
  1112. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1113. if (curl_easy_perform(curl)) {
  1114. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1115. goto out;
  1116. }
  1117. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1118. keep_alive(curl, pool->sock);
  1119. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1120. if (!__stratum_send(pool, s, strlen(s))) {
  1121. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1122. goto out;
  1123. }
  1124. if (!sock_full(pool, true)) {
  1125. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1126. goto out;
  1127. }
  1128. sret = recv_line(pool);
  1129. if (!sret)
  1130. goto out;
  1131. val = JSON_LOADS(sret, &err);
  1132. free(sret);
  1133. if (!val) {
  1134. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1135. goto out;
  1136. }
  1137. res_val = json_object_get(val, "result");
  1138. err_val = json_object_get(val, "error");
  1139. if (!res_val || json_is_null(res_val) ||
  1140. (err_val && !json_is_null(err_val))) {
  1141. char *ss;
  1142. if (err_val)
  1143. ss = json_dumps(err_val, JSON_INDENT(3));
  1144. else
  1145. ss = strdup("(unknown reason)");
  1146. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1147. free(ss);
  1148. goto out;
  1149. }
  1150. pool->nonce1 = json_array_string(res_val, 1);
  1151. if (!pool->nonce1) {
  1152. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1153. goto out;
  1154. }
  1155. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1156. if (!pool->n2size) {
  1157. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1158. goto out;
  1159. }
  1160. ret = true;
  1161. out:
  1162. if (val)
  1163. json_decref(val);
  1164. if (ret) {
  1165. if (!pool->stratum_url)
  1166. pool->stratum_url = pool->sockaddr_url;
  1167. pool->stratum_active = true;
  1168. pool->swork.diff = 1;
  1169. if (opt_protocol) {
  1170. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1171. pool->pool_no, pool->nonce1, pool->n2size);
  1172. }
  1173. } else
  1174. applog(LOG_DEBUG, "Initiate stratum failed");
  1175. return ret;
  1176. }
  1177. void suspend_stratum(struct pool *pool)
  1178. {
  1179. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1180. mutex_lock(&pool->stratum_lock);
  1181. pool->stratum_active = false;
  1182. mutex_unlock(&pool->stratum_lock);
  1183. CLOSESOCKET(pool->sock);
  1184. }
  1185. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1186. {
  1187. dev->device_last_not_well = time(NULL);
  1188. dev->device_not_well_reason = reason;
  1189. switch (reason) {
  1190. case REASON_THREAD_FAIL_INIT:
  1191. dev->thread_fail_init_count++;
  1192. break;
  1193. case REASON_THREAD_ZERO_HASH:
  1194. dev->thread_zero_hash_count++;
  1195. break;
  1196. case REASON_THREAD_FAIL_QUEUE:
  1197. dev->thread_fail_queue_count++;
  1198. break;
  1199. case REASON_DEV_SICK_IDLE_60:
  1200. dev->dev_sick_idle_60_count++;
  1201. break;
  1202. case REASON_DEV_DEAD_IDLE_600:
  1203. dev->dev_dead_idle_600_count++;
  1204. break;
  1205. case REASON_DEV_NOSTART:
  1206. dev->dev_nostart_count++;
  1207. break;
  1208. case REASON_DEV_OVER_HEAT:
  1209. dev->dev_over_heat_count++;
  1210. break;
  1211. case REASON_DEV_THERMAL_CUTOFF:
  1212. dev->dev_thermal_cutoff_count++;
  1213. break;
  1214. case REASON_DEV_COMMS_ERROR:
  1215. dev->dev_comms_error_count++;
  1216. break;
  1217. case REASON_DEV_THROTTLE:
  1218. dev->dev_throttle_count++;
  1219. break;
  1220. }
  1221. }
  1222. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1223. void *realloc_strcat(char *ptr, char *s)
  1224. {
  1225. size_t old = strlen(ptr), len = strlen(s);
  1226. char *ret;
  1227. if (!len)
  1228. return ptr;
  1229. len += old + 1;
  1230. if (len % 4)
  1231. len += 4 - (len % 4);
  1232. ret = malloc(len);
  1233. if (unlikely(!ret))
  1234. quit(1, "Failed to malloc in realloc_strcat");
  1235. sprintf(ret, "%s%s", ptr, s);
  1236. free(ptr);
  1237. return ret;
  1238. }
  1239. void RenameThread(const char* name)
  1240. {
  1241. #if defined(PR_SET_NAME)
  1242. // Only the first 15 characters are used (16 - NUL terminator)
  1243. prctl(PR_SET_NAME, name, 0, 0, 0);
  1244. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1245. pthread_set_name_np(pthread_self(), name);
  1246. #elif defined(MAC_OSX)
  1247. pthread_setname_np(name);
  1248. #else
  1249. // Prevent warnings for unused parameters...
  1250. (void)name;
  1251. #endif
  1252. }