util.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  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. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  669. * on SMP machines */
  670. void nmsleep(unsigned int msecs)
  671. {
  672. struct timespec twait, tleft;
  673. int ret;
  674. ldiv_t d;
  675. #ifdef WIN32
  676. timeBeginPeriod(1);
  677. #endif
  678. d = ldiv(msecs, 1000);
  679. tleft.tv_sec = d.quot;
  680. tleft.tv_nsec = d.rem * 1000000;
  681. do {
  682. twait.tv_sec = tleft.tv_sec;
  683. twait.tv_nsec = tleft.tv_nsec;
  684. ret = nanosleep(&twait, &tleft);
  685. } while (ret == -1 && errno == EINTR);
  686. #ifdef WIN32
  687. timeEndPeriod(1);
  688. #endif
  689. }
  690. /* Same for usecs */
  691. void nusleep(unsigned int usecs)
  692. {
  693. struct timespec twait, tleft;
  694. int ret;
  695. ldiv_t d;
  696. #ifdef WIN32
  697. timeBeginPeriod(1);
  698. #endif
  699. d = ldiv(usecs, 1000000);
  700. tleft.tv_sec = d.quot;
  701. tleft.tv_nsec = d.rem * 1000;
  702. do {
  703. twait.tv_sec = tleft.tv_sec;
  704. twait.tv_nsec = tleft.tv_nsec;
  705. ret = nanosleep(&twait, &tleft);
  706. } while (ret == -1 && errno == EINTR);
  707. #ifdef WIN32
  708. timeEndPeriod(1);
  709. #endif
  710. }
  711. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  712. * with tz set to NULL, and windows' default resolution is only 15ms, this
  713. * gives us higher resolution times on windows. */
  714. void cgtime(struct timeval *tv)
  715. {
  716. #ifdef WIN32
  717. timeBeginPeriod(1);
  718. #endif
  719. gettimeofday(tv, NULL);
  720. #ifdef WIN32
  721. timeEndPeriod(1);
  722. #endif
  723. }
  724. void subtime(struct timeval *a, struct timeval *b)
  725. {
  726. timersub(a, b, b);
  727. }
  728. void addtime(struct timeval *a, struct timeval *b)
  729. {
  730. timeradd(a, b, b);
  731. }
  732. bool time_more(struct timeval *a, struct timeval *b)
  733. {
  734. return timercmp(a, b, >);
  735. }
  736. bool time_less(struct timeval *a, struct timeval *b)
  737. {
  738. return timercmp(a, b, <);
  739. }
  740. void copy_time(struct timeval *dest, const struct timeval *src)
  741. {
  742. memcpy(dest, src, sizeof(struct timeval));
  743. }
  744. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  745. {
  746. val->tv_sec = spec->tv_sec;
  747. val->tv_usec = spec->tv_nsec / 1000;
  748. }
  749. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  750. {
  751. spec->tv_sec = val->tv_sec;
  752. spec->tv_nsec = val->tv_usec * 1000;
  753. }
  754. void us_to_timeval(struct timeval *val, int64_t us)
  755. {
  756. val->tv_sec = us / 1000000;
  757. val->tv_usec = us - (val->tv_sec * 1000000);
  758. }
  759. void us_to_timespec(struct timespec *spec, int64_t us)
  760. {
  761. spec->tv_sec = us / 1000000;
  762. spec->tv_nsec = (us - (spec->tv_sec * 1000000)) * 1000;
  763. }
  764. void timeraddspec(struct timespec *a, const struct timespec *b)
  765. {
  766. a->tv_sec += b->tv_sec;
  767. a->tv_nsec += b->tv_nsec;
  768. if (a->tv_nsec >+ 1000000000) {
  769. a->tv_nsec -= 1000000000;
  770. a->tv_sec++;
  771. }
  772. }
  773. /* Returns the microseconds difference between end and start times as a double */
  774. double us_tdiff(struct timeval *end, struct timeval *start)
  775. {
  776. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  777. }
  778. /* Returns the seconds difference between end and start times as a double */
  779. double tdiff(struct timeval *end, struct timeval *start)
  780. {
  781. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  782. }
  783. bool extract_sockaddr(struct pool *pool, char *url)
  784. {
  785. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  786. char url_address[256], port[6];
  787. int url_len, port_len = 0;
  788. pool->sockaddr_url = url;
  789. url_begin = strstr(url, "//");
  790. if (!url_begin)
  791. url_begin = url;
  792. else
  793. url_begin += 2;
  794. /* Look for numeric ipv6 entries */
  795. ipv6_begin = strstr(url_begin, "[");
  796. ipv6_end = strstr(url_begin, "]");
  797. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  798. url_end = strstr(ipv6_end, ":");
  799. else
  800. url_end = strstr(url_begin, ":");
  801. if (url_end) {
  802. url_len = url_end - url_begin;
  803. port_len = strlen(url_begin) - url_len - 1;
  804. if (port_len < 1)
  805. return false;
  806. port_start = url_end + 1;
  807. } else
  808. url_len = strlen(url_begin);
  809. if (url_len < 1)
  810. return false;
  811. sprintf(url_address, "%.*s", url_len, url_begin);
  812. if (port_len)
  813. snprintf(port, 6, "%.*s", port_len, port_start);
  814. else
  815. strcpy(port, "80");
  816. pool->stratum_port = strdup(port);
  817. pool->sockaddr_url = strdup(url_address);
  818. return true;
  819. }
  820. enum send_ret {
  821. SEND_OK,
  822. SEND_SELECTFAIL,
  823. SEND_SENDFAIL,
  824. SEND_INACTIVE
  825. };
  826. /* Send a single command across a socket, appending \n to it. This should all
  827. * be done under stratum lock except when first establishing the socket */
  828. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  829. {
  830. SOCKETTYPE sock = pool->sock;
  831. ssize_t ssent = 0;
  832. strcat(s, "\n");
  833. len++;
  834. while (len > 0 ) {
  835. struct timeval timeout = {1, 0};
  836. ssize_t sent;
  837. fd_set wd;
  838. FD_ZERO(&wd);
  839. FD_SET(sock, &wd);
  840. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  841. return SEND_SELECTFAIL;
  842. #ifdef __APPLE__
  843. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  844. #elif WIN32
  845. sent = send(pool->sock, s + ssent, len, 0);
  846. #else
  847. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  848. #endif
  849. if (sent < 0) {
  850. if (!sock_blocks())
  851. return SEND_SENDFAIL;
  852. sent = 0;
  853. }
  854. ssent += sent;
  855. len -= sent;
  856. }
  857. pool->cgminer_pool_stats.times_sent++;
  858. pool->cgminer_pool_stats.bytes_sent += ssent;
  859. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  860. return SEND_OK;
  861. }
  862. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  863. {
  864. enum send_ret ret = SEND_INACTIVE;
  865. if (opt_protocol)
  866. applog(LOG_DEBUG, "SEND: %s", s);
  867. mutex_lock(&pool->stratum_lock);
  868. if (pool->stratum_active)
  869. ret = __stratum_send(pool, s, len);
  870. mutex_unlock(&pool->stratum_lock);
  871. /* This is to avoid doing applog under stratum_lock */
  872. switch (ret) {
  873. default:
  874. case SEND_OK:
  875. break;
  876. case SEND_SELECTFAIL:
  877. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  878. suspend_stratum(pool);
  879. break;
  880. case SEND_SENDFAIL:
  881. applog(LOG_DEBUG, "Failed to send in stratum_send");
  882. suspend_stratum(pool);
  883. break;
  884. case SEND_INACTIVE:
  885. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  886. break;
  887. }
  888. return (ret == SEND_OK);
  889. }
  890. static bool socket_full(struct pool *pool, int wait)
  891. {
  892. SOCKETTYPE sock = pool->sock;
  893. struct timeval timeout;
  894. fd_set rd;
  895. if (unlikely(wait < 0))
  896. wait = 0;
  897. FD_ZERO(&rd);
  898. FD_SET(sock, &rd);
  899. timeout.tv_usec = 0;
  900. timeout.tv_sec = wait;
  901. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  902. return true;
  903. return false;
  904. }
  905. /* Check to see if Santa's been good to you */
  906. bool sock_full(struct pool *pool)
  907. {
  908. if (strlen(pool->sockbuf))
  909. return true;
  910. return (socket_full(pool, 0));
  911. }
  912. static void clear_sockbuf(struct pool *pool)
  913. {
  914. strcpy(pool->sockbuf, "");
  915. }
  916. static void clear_sock(struct pool *pool)
  917. {
  918. ssize_t n;
  919. mutex_lock(&pool->stratum_lock);
  920. do {
  921. if (pool->sock)
  922. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  923. else
  924. n = 0;
  925. } while (n > 0);
  926. mutex_unlock(&pool->stratum_lock);
  927. clear_sockbuf(pool);
  928. }
  929. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  930. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  931. * and zeroing the new memory */
  932. static void recalloc_sock(struct pool *pool, size_t len)
  933. {
  934. size_t old, new;
  935. old = strlen(pool->sockbuf);
  936. new = old + len + 1;
  937. if (new < pool->sockbuf_size)
  938. return;
  939. new = new + (RBUFSIZE - (new % RBUFSIZE));
  940. // Avoid potentially recursive locking
  941. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  942. pool->sockbuf = realloc(pool->sockbuf, new);
  943. if (!pool->sockbuf)
  944. quithere(1, "Failed to realloc pool sockbuf");
  945. memset(pool->sockbuf + old, 0, new - old);
  946. pool->sockbuf_size = new;
  947. }
  948. /* Peeks at a socket to find the first end of line and then reads just that
  949. * from the socket and returns that as a malloced char */
  950. char *recv_line(struct pool *pool)
  951. {
  952. char *tok, *sret = NULL;
  953. ssize_t len, buflen;
  954. int waited = 0;
  955. if (!strstr(pool->sockbuf, "\n")) {
  956. struct timeval rstart, now;
  957. cgtime(&rstart);
  958. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  959. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  960. goto out;
  961. }
  962. do {
  963. char s[RBUFSIZE];
  964. size_t slen;
  965. ssize_t n;
  966. memset(s, 0, RBUFSIZE);
  967. n = recv(pool->sock, s, RECVSIZE, 0);
  968. if (!n) {
  969. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  970. suspend_stratum(pool);
  971. break;
  972. }
  973. cgtime(&now);
  974. waited = tdiff(&now, &rstart);
  975. if (n < 0) {
  976. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  977. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  978. suspend_stratum(pool);
  979. break;
  980. }
  981. } else {
  982. slen = strlen(s);
  983. recalloc_sock(pool, slen);
  984. strcat(pool->sockbuf, s);
  985. }
  986. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  987. }
  988. buflen = strlen(pool->sockbuf);
  989. tok = strtok(pool->sockbuf, "\n");
  990. if (!tok) {
  991. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  992. goto out;
  993. }
  994. sret = strdup(tok);
  995. len = strlen(sret);
  996. /* Copy what's left in the buffer after the \n, including the
  997. * terminating \0 */
  998. if (buflen > len + 1)
  999. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1000. else
  1001. strcpy(pool->sockbuf, "");
  1002. pool->cgminer_pool_stats.times_received++;
  1003. pool->cgminer_pool_stats.bytes_received += len;
  1004. pool->cgminer_pool_stats.net_bytes_received += len;
  1005. out:
  1006. if (!sret)
  1007. clear_sock(pool);
  1008. else if (opt_protocol)
  1009. applog(LOG_DEBUG, "RECVD: %s", sret);
  1010. return sret;
  1011. }
  1012. /* Extracts a string value from a json array with error checking. To be used
  1013. * when the value of the string returned is only examined and not to be stored.
  1014. * See json_array_string below */
  1015. static char *__json_array_string(json_t *val, unsigned int entry)
  1016. {
  1017. json_t *arr_entry;
  1018. if (json_is_null(val))
  1019. return NULL;
  1020. if (!json_is_array(val))
  1021. return NULL;
  1022. if (entry > json_array_size(val))
  1023. return NULL;
  1024. arr_entry = json_array_get(val, entry);
  1025. if (!json_is_string(arr_entry))
  1026. return NULL;
  1027. return (char *)json_string_value(arr_entry);
  1028. }
  1029. /* Creates a freshly malloced dup of __json_array_string */
  1030. static char *json_array_string(json_t *val, unsigned int entry)
  1031. {
  1032. char *buf = __json_array_string(val, entry);
  1033. if (buf)
  1034. return strdup(buf);
  1035. return NULL;
  1036. }
  1037. static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
  1038. static bool parse_notify(struct pool *pool, json_t *val)
  1039. {
  1040. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1041. *ntime, *header;
  1042. size_t cb1_len, cb2_len, alloc_len;
  1043. unsigned char *cb1, *cb2;
  1044. bool clean, ret = false;
  1045. int merkles, i;
  1046. json_t *arr;
  1047. arr = json_array_get(val, 4);
  1048. if (!arr || !json_is_array(arr))
  1049. goto out;
  1050. merkles = json_array_size(arr);
  1051. job_id = json_array_string(val, 0);
  1052. prev_hash = json_array_string(val, 1);
  1053. coinbase1 = json_array_string(val, 2);
  1054. coinbase2 = json_array_string(val, 3);
  1055. bbversion = json_array_string(val, 5);
  1056. nbit = json_array_string(val, 6);
  1057. ntime = json_array_string(val, 7);
  1058. clean = json_is_true(json_array_get(val, 8));
  1059. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1060. /* Annoying but we must not leak memory */
  1061. if (job_id)
  1062. free(job_id);
  1063. if (prev_hash)
  1064. free(prev_hash);
  1065. if (coinbase1)
  1066. free(coinbase1);
  1067. if (coinbase2)
  1068. free(coinbase2);
  1069. if (bbversion)
  1070. free(bbversion);
  1071. if (nbit)
  1072. free(nbit);
  1073. if (ntime)
  1074. free(ntime);
  1075. goto out;
  1076. }
  1077. cg_wlock(&pool->data_lock);
  1078. free(pool->swork.job_id);
  1079. free(pool->swork.prev_hash);
  1080. free(pool->swork.bbversion);
  1081. free(pool->swork.nbit);
  1082. free(pool->swork.ntime);
  1083. pool->swork.job_id = job_id;
  1084. pool->swork.prev_hash = prev_hash;
  1085. cb1_len = strlen(coinbase1) / 2;
  1086. cb2_len = strlen(coinbase2) / 2;
  1087. pool->swork.bbversion = bbversion;
  1088. pool->swork.nbit = nbit;
  1089. pool->swork.ntime = ntime;
  1090. pool->swork.clean = clean;
  1091. alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  1092. pool->nonce2_offset = cb1_len + pool->n1_len;
  1093. for (i = 0; i < pool->swork.merkles; i++)
  1094. free(pool->swork.merkle_bin[i]);
  1095. if (merkles) {
  1096. pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
  1097. sizeof(char *) * merkles + 1);
  1098. for (i = 0; i < merkles; i++) {
  1099. char *merkle = json_array_string(arr, i);
  1100. pool->swork.merkle_bin[i] = malloc(32);
  1101. if (unlikely(!pool->swork.merkle_bin[i]))
  1102. quit(1, "Failed to malloc pool swork merkle_bin");
  1103. hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  1104. free(merkle);
  1105. }
  1106. }
  1107. pool->swork.merkles = merkles;
  1108. if (clean)
  1109. pool->nonce2 = 0;
  1110. pool->merkle_offset = strlen(pool->swork.bbversion) +
  1111. strlen(pool->swork.prev_hash);
  1112. pool->swork.header_len = pool->merkle_offset +
  1113. /* merkle_hash */ 32 +
  1114. strlen(pool->swork.ntime) +
  1115. strlen(pool->swork.nbit) +
  1116. /* nonce */ 8 +
  1117. /* workpadding */ 96;
  1118. pool->merkle_offset /= 2;
  1119. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1120. align_len(&pool->swork.header_len);
  1121. header = alloca(pool->swork.header_len);
  1122. snprintf(header, pool->swork.header_len,
  1123. "%s%s%s%s%s%s%s",
  1124. pool->swork.bbversion,
  1125. pool->swork.prev_hash,
  1126. blank_merkel,
  1127. pool->swork.ntime,
  1128. pool->swork.nbit,
  1129. "00000000", /* nonce */
  1130. workpadding);
  1131. if (unlikely(!hex2bin(pool->header_bin, header, 128)))
  1132. quit(1, "Failed to convert header to header_bin in parse_notify");
  1133. cb1 = calloc(cb1_len, 1);
  1134. if (unlikely(!cb1))
  1135. quithere(1, "Failed to calloc cb1 in parse_notify");
  1136. hex2bin(cb1, coinbase1, cb1_len);
  1137. cb2 = calloc(cb2_len, 1);
  1138. if (unlikely(!cb2))
  1139. quithere(1, "Failed to calloc cb2 in parse_notify");
  1140. hex2bin(cb2, coinbase2, cb2_len);
  1141. free(pool->coinbase);
  1142. align_len(&alloc_len);
  1143. pool->coinbase = calloc(alloc_len, 1);
  1144. if (unlikely(!pool->coinbase))
  1145. quit(1, "Failed to calloc pool coinbase in parse_notify");
  1146. memcpy(pool->coinbase, cb1, cb1_len);
  1147. memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  1148. memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  1149. cg_wunlock(&pool->data_lock);
  1150. if (opt_protocol) {
  1151. applog(LOG_DEBUG, "job_id: %s", job_id);
  1152. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1153. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1154. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1155. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1156. applog(LOG_DEBUG, "nbit: %s", nbit);
  1157. applog(LOG_DEBUG, "ntime: %s", ntime);
  1158. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1159. }
  1160. free(coinbase1);
  1161. free(coinbase2);
  1162. free(cb1);
  1163. free(cb2);
  1164. /* A notify message is the closest stratum gets to a getwork */
  1165. pool->getwork_requested++;
  1166. total_getworks++;
  1167. ret = true;
  1168. out:
  1169. return ret;
  1170. }
  1171. static bool parse_diff(struct pool *pool, json_t *val)
  1172. {
  1173. double old_diff, diff;
  1174. diff = json_number_value(json_array_get(val, 0));
  1175. if (diff == 0)
  1176. return false;
  1177. cg_wlock(&pool->data_lock);
  1178. old_diff = pool->swork.diff;
  1179. pool->swork.diff = diff;
  1180. cg_wunlock(&pool->data_lock);
  1181. if (old_diff != diff) {
  1182. int idiff = diff;
  1183. if ((double)idiff == diff)
  1184. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  1185. pool->pool_no, idiff);
  1186. else
  1187. applog(LOG_NOTICE, "Pool %d difficulty changed to %f",
  1188. pool->pool_no, diff);
  1189. } else
  1190. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  1191. diff);
  1192. return true;
  1193. }
  1194. static bool parse_reconnect(struct pool *pool, json_t *val)
  1195. {
  1196. char *url, *port, address[256];
  1197. memset(address, 0, 255);
  1198. url = (char *)json_string_value(json_array_get(val, 0));
  1199. if (!url)
  1200. url = pool->sockaddr_url;
  1201. port = (char *)json_string_value(json_array_get(val, 1));
  1202. if (!port)
  1203. port = pool->stratum_port;
  1204. sprintf(address, "%s:%s", url, port);
  1205. if (!extract_sockaddr(pool, address))
  1206. return false;
  1207. pool->stratum_url = pool->sockaddr_url;
  1208. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1209. if (!restart_stratum(pool))
  1210. return false;
  1211. return true;
  1212. }
  1213. static bool send_version(struct pool *pool, json_t *val)
  1214. {
  1215. char s[RBUFSIZE];
  1216. int id = json_integer_value(json_object_get(val, "id"));
  1217. if (!id)
  1218. return false;
  1219. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1220. if (!stratum_send(pool, s, strlen(s)))
  1221. return false;
  1222. return true;
  1223. }
  1224. static bool show_message(struct pool *pool, json_t *val)
  1225. {
  1226. char *msg;
  1227. if (!json_is_array(val))
  1228. return false;
  1229. msg = (char *)json_string_value(json_array_get(val, 0));
  1230. if (!msg)
  1231. return false;
  1232. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  1233. return true;
  1234. }
  1235. bool parse_method(struct pool *pool, char *s)
  1236. {
  1237. json_t *val = NULL, *method, *err_val, *params;
  1238. json_error_t err;
  1239. bool ret = false;
  1240. char *buf;
  1241. if (!s)
  1242. goto out;
  1243. val = JSON_LOADS(s, &err);
  1244. if (!val) {
  1245. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1246. goto out;
  1247. }
  1248. method = json_object_get(val, "method");
  1249. if (!method)
  1250. goto out;
  1251. err_val = json_object_get(val, "error");
  1252. params = json_object_get(val, "params");
  1253. if (err_val && !json_is_null(err_val)) {
  1254. char *ss;
  1255. if (err_val)
  1256. ss = json_dumps(err_val, JSON_INDENT(3));
  1257. else
  1258. ss = strdup("(unknown reason)");
  1259. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1260. free(ss);
  1261. goto out;
  1262. }
  1263. buf = (char *)json_string_value(method);
  1264. if (!buf)
  1265. goto out;
  1266. if (!strncasecmp(buf, "mining.notify", 13)) {
  1267. if (parse_notify(pool, params))
  1268. pool->stratum_notify = ret = true;
  1269. else
  1270. pool->stratum_notify = ret = false;
  1271. goto out;
  1272. }
  1273. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1274. ret = true;
  1275. goto out;
  1276. }
  1277. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1278. ret = true;
  1279. goto out;
  1280. }
  1281. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1282. ret = true;
  1283. goto out;
  1284. }
  1285. if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
  1286. ret = true;
  1287. goto out;
  1288. }
  1289. out:
  1290. if (val)
  1291. json_decref(val);
  1292. return ret;
  1293. }
  1294. bool auth_stratum(struct pool *pool)
  1295. {
  1296. json_t *val = NULL, *res_val, *err_val;
  1297. char s[RBUFSIZE], *sret = NULL;
  1298. json_error_t err;
  1299. bool ret = false;
  1300. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1301. swork_id++, pool->rpc_user, pool->rpc_pass);
  1302. if (!stratum_send(pool, s, strlen(s)))
  1303. goto out;
  1304. /* Parse all data in the queue and anything left should be auth */
  1305. while (42) {
  1306. sret = recv_line(pool);
  1307. if (!sret)
  1308. goto out;
  1309. if (parse_method(pool, sret))
  1310. free(sret);
  1311. else
  1312. break;
  1313. }
  1314. val = JSON_LOADS(sret, &err);
  1315. free(sret);
  1316. res_val = json_object_get(val, "result");
  1317. err_val = json_object_get(val, "error");
  1318. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1319. char *ss;
  1320. if (err_val)
  1321. ss = json_dumps(err_val, JSON_INDENT(3));
  1322. else
  1323. ss = strdup("(unknown reason)");
  1324. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1325. free(ss);
  1326. goto out;
  1327. }
  1328. ret = true;
  1329. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1330. pool->probed = true;
  1331. successful_connect = true;
  1332. out:
  1333. if (val)
  1334. json_decref(val);
  1335. return ret;
  1336. }
  1337. static bool setup_stratum_socket(struct pool *pool)
  1338. {
  1339. struct addrinfo *servinfo, *hints, *p;
  1340. int sockd;
  1341. mutex_lock(&pool->stratum_lock);
  1342. pool->stratum_active = false;
  1343. if (pool->sock)
  1344. CLOSESOCKET(pool->sock);
  1345. pool->sock = 0;
  1346. mutex_unlock(&pool->stratum_lock);
  1347. hints = &pool->stratum_hints;
  1348. memset(hints, 0, sizeof(struct addrinfo));
  1349. hints->ai_family = AF_UNSPEC;
  1350. hints->ai_socktype = SOCK_STREAM;
  1351. if (getaddrinfo(pool->sockaddr_url, pool->stratum_port, hints, &servinfo) != 0) {
  1352. if (!pool->probed) {
  1353. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  1354. pool->sockaddr_url, pool->stratum_port);
  1355. pool->probed = true;
  1356. } else {
  1357. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  1358. pool->sockaddr_url, pool->stratum_port);
  1359. }
  1360. return false;
  1361. }
  1362. for (p = servinfo; p != NULL; p = p->ai_next) {
  1363. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  1364. if (sockd == -1) {
  1365. applog(LOG_DEBUG, "Failed socket");
  1366. continue;
  1367. }
  1368. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  1369. CLOSESOCKET(sockd);
  1370. applog(LOG_DEBUG, "Failed connect");
  1371. continue;
  1372. }
  1373. break;
  1374. }
  1375. if (p == NULL) {
  1376. applog(LOG_INFO, "Failed to find a stratum servinfo on %s:%s",
  1377. pool->sockaddr_url, pool->stratum_port);
  1378. freeaddrinfo(servinfo);
  1379. return false;
  1380. }
  1381. freeaddrinfo(servinfo);
  1382. if (!pool->sockbuf) {
  1383. pool->sockbuf = calloc(RBUFSIZE, 1);
  1384. if (!pool->sockbuf)
  1385. quithere(1, "Failed to calloc pool sockbuf");
  1386. pool->sockbuf_size = RBUFSIZE;
  1387. }
  1388. pool->sock = sockd;
  1389. keep_sockalive(sockd);
  1390. return true;
  1391. }
  1392. static char *get_sessionid(json_t *val)
  1393. {
  1394. char *ret = NULL;
  1395. json_t *arr_val;
  1396. int arrsize, i;
  1397. arr_val = json_array_get(val, 0);
  1398. if (!arr_val || !json_is_array(arr_val))
  1399. goto out;
  1400. arrsize = json_array_size(arr_val);
  1401. for (i = 0; i < arrsize; i++) {
  1402. json_t *arr = json_array_get(arr_val, i);
  1403. char *notify;
  1404. if (!arr | !json_is_array(arr))
  1405. break;
  1406. notify = __json_array_string(arr, 0);
  1407. if (!notify)
  1408. continue;
  1409. if (!strncasecmp(notify, "mining.notify", 13)) {
  1410. ret = json_array_string(arr, 1);
  1411. break;
  1412. }
  1413. }
  1414. out:
  1415. return ret;
  1416. }
  1417. void suspend_stratum(struct pool *pool)
  1418. {
  1419. clear_sockbuf(pool);
  1420. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1421. mutex_lock(&pool->stratum_lock);
  1422. pool->stratum_active = pool->stratum_notify = false;
  1423. if (pool->sock)
  1424. CLOSESOCKET(pool->sock);
  1425. pool->sock = 0;
  1426. mutex_unlock(&pool->stratum_lock);
  1427. }
  1428. bool initiate_stratum(struct pool *pool)
  1429. {
  1430. bool ret = false, recvd = false, noresume = false, sockd = false;
  1431. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1432. json_t *val = NULL, *res_val, *err_val;
  1433. json_error_t err;
  1434. int n2size;
  1435. resend:
  1436. if (!setup_stratum_socket(pool)) {
  1437. sockd = false;
  1438. goto out;
  1439. }
  1440. sockd = true;
  1441. if (recvd) {
  1442. /* Get rid of any crap lying around if we're resending */
  1443. clear_sock(pool);
  1444. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1445. } else {
  1446. if (pool->sessionid)
  1447. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1448. else
  1449. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1450. }
  1451. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1452. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1453. goto out;
  1454. }
  1455. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1456. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1457. goto out;
  1458. }
  1459. sret = recv_line(pool);
  1460. if (!sret)
  1461. goto out;
  1462. recvd = true;
  1463. val = JSON_LOADS(sret, &err);
  1464. free(sret);
  1465. if (!val) {
  1466. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1467. goto out;
  1468. }
  1469. res_val = json_object_get(val, "result");
  1470. err_val = json_object_get(val, "error");
  1471. if (!res_val || json_is_null(res_val) ||
  1472. (err_val && !json_is_null(err_val))) {
  1473. char *ss;
  1474. if (err_val)
  1475. ss = json_dumps(err_val, JSON_INDENT(3));
  1476. else
  1477. ss = strdup("(unknown reason)");
  1478. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1479. free(ss);
  1480. goto out;
  1481. }
  1482. sessionid = get_sessionid(res_val);
  1483. if (!sessionid)
  1484. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1485. nonce1 = json_array_string(res_val, 1);
  1486. if (!nonce1) {
  1487. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1488. free(sessionid);
  1489. goto out;
  1490. }
  1491. n2size = json_integer_value(json_array_get(res_val, 2));
  1492. if (!n2size) {
  1493. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1494. free(sessionid);
  1495. free(nonce1);
  1496. goto out;
  1497. }
  1498. cg_wlock(&pool->data_lock);
  1499. pool->sessionid = sessionid;
  1500. pool->nonce1 = nonce1;
  1501. pool->n1_len = strlen(nonce1) / 2;
  1502. free(pool->nonce1bin);
  1503. pool->nonce1bin = calloc(pool->n1_len, 1);
  1504. if (unlikely(!pool->nonce1bin))
  1505. quithere(1, "Failed to calloc pool->nonce1bin");
  1506. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  1507. pool->n2size = n2size;
  1508. cg_wunlock(&pool->data_lock);
  1509. if (sessionid)
  1510. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1511. ret = true;
  1512. out:
  1513. if (val)
  1514. json_decref(val);
  1515. if (ret) {
  1516. if (!pool->stratum_url)
  1517. pool->stratum_url = pool->sockaddr_url;
  1518. pool->stratum_active = true;
  1519. pool->swork.diff = 1;
  1520. if (opt_protocol) {
  1521. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1522. pool->pool_no, pool->nonce1, pool->n2size);
  1523. }
  1524. } else {
  1525. if (recvd && !noresume) {
  1526. /* Reset the sessionid used for stratum resuming in case the pool
  1527. * does not support it, or does not know how to respond to the
  1528. * presence of the sessionid parameter. */
  1529. cg_wlock(&pool->data_lock);
  1530. free(pool->sessionid);
  1531. free(pool->nonce1);
  1532. pool->sessionid = pool->nonce1 = NULL;
  1533. cg_wunlock(&pool->data_lock);
  1534. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1535. noresume = true;
  1536. goto resend;
  1537. }
  1538. applog(LOG_DEBUG, "Initiate stratum failed");
  1539. if (sockd)
  1540. suspend_stratum(pool);
  1541. }
  1542. return ret;
  1543. }
  1544. bool restart_stratum(struct pool *pool)
  1545. {
  1546. if (pool->stratum_active)
  1547. suspend_stratum(pool);
  1548. if (!initiate_stratum(pool))
  1549. return false;
  1550. if (!auth_stratum(pool))
  1551. return false;
  1552. return true;
  1553. }
  1554. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1555. {
  1556. dev->device_last_not_well = time(NULL);
  1557. dev->device_not_well_reason = reason;
  1558. switch (reason) {
  1559. case REASON_THREAD_FAIL_INIT:
  1560. dev->thread_fail_init_count++;
  1561. break;
  1562. case REASON_THREAD_ZERO_HASH:
  1563. dev->thread_zero_hash_count++;
  1564. break;
  1565. case REASON_THREAD_FAIL_QUEUE:
  1566. dev->thread_fail_queue_count++;
  1567. break;
  1568. case REASON_DEV_SICK_IDLE_60:
  1569. dev->dev_sick_idle_60_count++;
  1570. break;
  1571. case REASON_DEV_DEAD_IDLE_600:
  1572. dev->dev_dead_idle_600_count++;
  1573. break;
  1574. case REASON_DEV_NOSTART:
  1575. dev->dev_nostart_count++;
  1576. break;
  1577. case REASON_DEV_OVER_HEAT:
  1578. dev->dev_over_heat_count++;
  1579. break;
  1580. case REASON_DEV_THERMAL_CUTOFF:
  1581. dev->dev_thermal_cutoff_count++;
  1582. break;
  1583. case REASON_DEV_COMMS_ERROR:
  1584. dev->dev_comms_error_count++;
  1585. break;
  1586. case REASON_DEV_THROTTLE:
  1587. dev->dev_throttle_count++;
  1588. break;
  1589. }
  1590. }
  1591. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1592. void *realloc_strcat(char *ptr, char *s)
  1593. {
  1594. size_t old = strlen(ptr), len = strlen(s);
  1595. char *ret;
  1596. if (!len)
  1597. return ptr;
  1598. len += old + 1;
  1599. align_len(&len);
  1600. ret = malloc(len);
  1601. if (unlikely(!ret))
  1602. quithere(1, "Failed to malloc");
  1603. sprintf(ret, "%s%s", ptr, s);
  1604. free(ptr);
  1605. return ret;
  1606. }
  1607. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  1608. * Including 0x00 at the end
  1609. * You must free the result yourself */
  1610. void *str_text(char *ptr)
  1611. {
  1612. unsigned char *uptr;
  1613. char *ret, *txt;
  1614. if (ptr == NULL) {
  1615. ret = strdup("(null)");
  1616. if (unlikely(!ret))
  1617. quithere(1, "Failed to malloc null");
  1618. }
  1619. uptr = (unsigned char *)ptr;
  1620. ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed
  1621. if (unlikely(!txt))
  1622. quithere(1, "Failed to malloc txt");
  1623. do {
  1624. if (*uptr < ' ' || *uptr > '~') {
  1625. sprintf(txt, "0x%02x", *uptr);
  1626. txt += 4;
  1627. } else
  1628. *(txt++) = *uptr;
  1629. } while (*(uptr++));
  1630. *txt = '\0';
  1631. return ret;
  1632. }
  1633. void RenameThread(const char* name)
  1634. {
  1635. #if defined(PR_SET_NAME)
  1636. // Only the first 15 characters are used (16 - NUL terminator)
  1637. prctl(PR_SET_NAME, name, 0, 0, 0);
  1638. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1639. pthread_set_name_np(pthread_self(), name);
  1640. #elif defined(MAC_OSX)
  1641. pthread_setname_np(name);
  1642. #else
  1643. // Prevent warnings for unused parameters...
  1644. (void)name;
  1645. #endif
  1646. }
  1647. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  1648. * that support them and for apple which does not. We use a single byte across
  1649. * a pipe to emulate semaphore behaviour there. */
  1650. #ifdef __APPLE__
  1651. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1652. {
  1653. int flags, fd, i;
  1654. if (pipe(cgsem->pipefd) == -1)
  1655. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  1656. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  1657. * execv on restart. */
  1658. for (i = 0; i < 2; i++) {
  1659. fd = cgsem->pipefd[i];
  1660. flags = fcntl(fd, F_GETFD, 0);
  1661. flags |= FD_CLOEXEC;
  1662. if (fcntl(fd, F_SETFD, flags) == -1)
  1663. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  1664. }
  1665. }
  1666. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1667. {
  1668. const char buf = 1;
  1669. int ret;
  1670. ret = write(cgsem->pipefd[1], &buf, 1);
  1671. if (unlikely(ret == 0))
  1672. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  1673. }
  1674. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1675. {
  1676. char buf;
  1677. int ret;
  1678. ret = read(cgsem->pipefd[0], &buf, 1);
  1679. if (unlikely(ret == 0))
  1680. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  1681. }
  1682. void _cgsem_destroy(cgsem_t *cgsem)
  1683. {
  1684. close(cgsem->pipefd[1]);
  1685. close(cgsem->pipefd[0]);
  1686. }
  1687. #else
  1688. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1689. {
  1690. int ret;
  1691. if ((ret = sem_init(cgsem, 0, 0)))
  1692. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  1693. }
  1694. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1695. {
  1696. if (unlikely(sem_post(cgsem)))
  1697. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  1698. }
  1699. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1700. {
  1701. if (unlikely(sem_wait(cgsem)))
  1702. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  1703. }
  1704. void _cgsem_destroy(cgsem_t *cgsem)
  1705. {
  1706. sem_destroy(cgsem);
  1707. }
  1708. #endif