util.c 49 KB

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