util.c 39 KB

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