util.c 42 KB

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