util.c 42 KB

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