util.c 38 KB

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