util.c 43 KB

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