util.c 40 KB

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