util.c 46 KB

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