util.c 46 KB

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