util.c 41 KB

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