util.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592
  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. #ifdef HAVE_LIBCURL
  18. #include <curl/curl.h>
  19. #endif
  20. #include <time.h>
  21. #include <errno.h>
  22. #include <unistd.h>
  23. #include <sys/types.h>
  24. #ifndef WIN32
  25. #include <fcntl.h>
  26. # ifdef __linux
  27. # include <sys/prctl.h>
  28. # endif
  29. # include <sys/socket.h>
  30. # include <netinet/in.h>
  31. # include <netinet/tcp.h>
  32. # include <netdb.h>
  33. #else
  34. # include <windows.h>
  35. # include <winsock2.h>
  36. # include <ws2tcpip.h>
  37. # include <mmsystem.h>
  38. #endif
  39. #include "miner.h"
  40. #include "elist.h"
  41. #include "compat.h"
  42. #include "util.h"
  43. #define DEFAULT_SOCKWAIT 60
  44. bool successful_connect = false;
  45. static void keep_sockalive(SOCKETTYPE fd)
  46. {
  47. const int tcp_one = 1;
  48. #ifndef WIN32
  49. const int tcp_keepidle = 45;
  50. const int tcp_keepintvl = 30;
  51. int flags = fcntl(fd, F_GETFL, 0);
  52. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  53. #else
  54. u_long flags = 1;
  55. ioctlsocket(fd, FIONBIO, &flags);
  56. #endif
  57. setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const void *)&tcp_one, sizeof(tcp_one));
  58. if (!opt_delaynet)
  59. #ifndef __linux
  60. setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  61. #else /* __linux */
  62. setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  63. setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one));
  64. setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
  65. setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
  66. #endif /* __linux */
  67. #ifdef __APPLE_CC__
  68. setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
  69. #endif /* __APPLE_CC__ */
  70. }
  71. struct tq_ent {
  72. void *data;
  73. struct list_head q_node;
  74. };
  75. #ifdef HAVE_LIBCURL
  76. struct timeval nettime;
  77. struct data_buffer {
  78. void *buf;
  79. size_t len;
  80. };
  81. struct upload_buffer {
  82. const void *buf;
  83. size_t len;
  84. };
  85. struct header_info {
  86. char *lp_path;
  87. int rolltime;
  88. char *reason;
  89. char *stratum_url;
  90. bool hadrolltime;
  91. bool canroll;
  92. bool hadexpire;
  93. };
  94. static void databuf_free(struct data_buffer *db)
  95. {
  96. if (!db)
  97. return;
  98. free(db->buf);
  99. memset(db, 0, sizeof(*db));
  100. }
  101. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  102. void *user_data)
  103. {
  104. struct data_buffer *db = user_data;
  105. size_t len = size * nmemb;
  106. size_t oldlen, newlen;
  107. void *newmem;
  108. static const unsigned char zero = 0;
  109. oldlen = db->len;
  110. newlen = oldlen + len;
  111. newmem = realloc(db->buf, newlen + 1);
  112. if (!newmem)
  113. return 0;
  114. db->buf = newmem;
  115. db->len = newlen;
  116. memcpy(db->buf + oldlen, ptr, len);
  117. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  118. return len;
  119. }
  120. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  121. void *user_data)
  122. {
  123. struct upload_buffer *ub = user_data;
  124. unsigned int len = size * nmemb;
  125. if (len > ub->len)
  126. len = ub->len;
  127. if (len) {
  128. memcpy(ptr, ub->buf, len);
  129. ub->buf += len;
  130. ub->len -= len;
  131. }
  132. return len;
  133. }
  134. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  135. {
  136. struct header_info *hi = user_data;
  137. size_t remlen, slen, ptrlen = size * nmemb;
  138. char *rem, *val = NULL, *key = NULL;
  139. void *tmp;
  140. val = calloc(1, ptrlen);
  141. key = calloc(1, ptrlen);
  142. if (!key || !val)
  143. goto out;
  144. tmp = memchr(ptr, ':', ptrlen);
  145. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  146. goto out;
  147. slen = tmp - ptr;
  148. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  149. goto out;
  150. memcpy(key, ptr, slen); /* store & nul term key */
  151. key[slen] = 0;
  152. rem = ptr + slen + 1; /* trim value's leading whitespace */
  153. remlen = ptrlen - slen - 1;
  154. while ((remlen > 0) && (isspace(*rem))) {
  155. remlen--;
  156. rem++;
  157. }
  158. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  159. val[remlen] = 0;
  160. while ((*val) && (isspace(val[strlen(val) - 1])))
  161. val[strlen(val) - 1] = 0;
  162. if (!*val) /* skip blank value */
  163. goto out;
  164. if (opt_protocol)
  165. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  166. if (!strcasecmp("X-Roll-Ntime", key)) {
  167. hi->hadrolltime = true;
  168. if (!strncasecmp("N", val, 1))
  169. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  170. else {
  171. hi->canroll = true;
  172. /* Check to see if expire= is supported and if not, set
  173. * the rolltime to the default scantime */
  174. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  175. sscanf(val + 7, "%d", &hi->rolltime);
  176. hi->hadexpire = true;
  177. } else
  178. hi->rolltime = opt_scantime;
  179. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  180. }
  181. }
  182. if (!strcasecmp("X-Long-Polling", key)) {
  183. hi->lp_path = val; /* steal memory reference */
  184. val = NULL;
  185. }
  186. if (!strcasecmp("X-Reject-Reason", key)) {
  187. hi->reason = val; /* steal memory reference */
  188. val = NULL;
  189. }
  190. if (!strcasecmp("X-Stratum", key)) {
  191. hi->stratum_url = val;
  192. val = NULL;
  193. }
  194. out:
  195. free(key);
  196. free(val);
  197. return ptrlen;
  198. }
  199. static void last_nettime(struct timeval *last)
  200. {
  201. rd_lock(&netacc_lock);
  202. last->tv_sec = nettime.tv_sec;
  203. last->tv_usec = nettime.tv_usec;
  204. rd_unlock(&netacc_lock);
  205. }
  206. static void set_nettime(void)
  207. {
  208. wr_lock(&netacc_lock);
  209. cgtime(&nettime);
  210. wr_unlock(&netacc_lock);
  211. }
  212. #if CURL_HAS_KEEPALIVE
  213. static void keep_curlalive(CURL *curl)
  214. {
  215. const int tcp_keepidle = 45;
  216. const int tcp_keepintvl = 30;
  217. const long int keepalive = 1;
  218. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
  219. curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, tcp_keepidle);
  220. curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, tcp_keepintvl);
  221. }
  222. #else
  223. static void keep_curlalive(CURL *curl)
  224. {
  225. SOCKETTYPE sock;
  226. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
  227. keep_sockalive(sock);
  228. }
  229. #endif
  230. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  231. __maybe_unused char *data, size_t size, void *userdata)
  232. {
  233. struct pool *pool = (struct pool *)userdata;
  234. switch(type) {
  235. case CURLINFO_HEADER_IN:
  236. case CURLINFO_DATA_IN:
  237. case CURLINFO_SSL_DATA_IN:
  238. pool->cgminer_pool_stats.net_bytes_received += size;
  239. break;
  240. case CURLINFO_HEADER_OUT:
  241. case CURLINFO_DATA_OUT:
  242. case CURLINFO_SSL_DATA_OUT:
  243. pool->cgminer_pool_stats.net_bytes_sent += size;
  244. break;
  245. case CURLINFO_TEXT:
  246. default:
  247. break;
  248. }
  249. return 0;
  250. }
  251. json_t *json_rpc_call(CURL *curl, const char *url,
  252. const char *userpass, const char *rpc_req,
  253. bool probe, bool longpoll, int *rolltime,
  254. struct pool *pool, bool share)
  255. {
  256. long timeout = longpoll ? (60 * 60) : 60;
  257. struct data_buffer all_data = {NULL, 0};
  258. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  259. char len_hdr[64], user_agent_hdr[128];
  260. char curl_err_str[CURL_ERROR_SIZE];
  261. struct curl_slist *headers = NULL;
  262. struct upload_buffer upload_data;
  263. json_t *val, *err_val, *res_val;
  264. bool probing = false;
  265. double byte_count;
  266. json_error_t err;
  267. int rc;
  268. memset(&err, 0, sizeof(err));
  269. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  270. if (probe)
  271. probing = !pool->probed;
  272. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  273. // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
  274. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  275. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  276. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  277. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  278. curl_easy_setopt(curl, CURLOPT_URL, url);
  279. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  280. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  281. /* Shares are staggered already and delays in submission can be costly
  282. * so do not delay them */
  283. if (!opt_delaynet || share)
  284. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  285. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  286. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  287. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  288. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  289. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  290. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  291. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  292. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  293. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  294. if (pool->rpc_proxy) {
  295. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  296. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  297. } else if (opt_socks_proxy) {
  298. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  299. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  300. }
  301. if (userpass) {
  302. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  303. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  304. }
  305. if (longpoll)
  306. keep_curlalive(curl);
  307. curl_easy_setopt(curl, CURLOPT_POST, 1);
  308. if (opt_protocol)
  309. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  310. upload_data.buf = rpc_req;
  311. upload_data.len = strlen(rpc_req);
  312. sprintf(len_hdr, "Content-Length: %lu",
  313. (unsigned long) upload_data.len);
  314. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  315. headers = curl_slist_append(headers,
  316. "Content-type: application/json");
  317. headers = curl_slist_append(headers,
  318. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  319. if (likely(global_hashrate)) {
  320. char ghashrate[255];
  321. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  322. headers = curl_slist_append(headers, ghashrate);
  323. }
  324. headers = curl_slist_append(headers, len_hdr);
  325. headers = curl_slist_append(headers, user_agent_hdr);
  326. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  327. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  328. if (opt_delaynet) {
  329. /* Don't delay share submission, but still track the nettime */
  330. if (!share) {
  331. long long now_msecs, last_msecs;
  332. struct timeval now, last;
  333. cgtime(&now);
  334. last_nettime(&last);
  335. now_msecs = (long long)now.tv_sec * 1000;
  336. now_msecs += now.tv_usec / 1000;
  337. last_msecs = (long long)last.tv_sec * 1000;
  338. last_msecs += last.tv_usec / 1000;
  339. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  340. struct timespec rgtp;
  341. rgtp.tv_sec = 0;
  342. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  343. nanosleep(&rgtp, NULL);
  344. }
  345. }
  346. set_nettime();
  347. }
  348. rc = curl_easy_perform(curl);
  349. if (rc) {
  350. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  351. goto err_out;
  352. }
  353. if (!all_data.buf) {
  354. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  355. goto err_out;
  356. }
  357. pool->cgminer_pool_stats.times_sent++;
  358. if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
  359. pool->cgminer_pool_stats.bytes_sent += byte_count;
  360. pool->cgminer_pool_stats.times_received++;
  361. if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
  362. pool->cgminer_pool_stats.bytes_received += byte_count;
  363. if (probing) {
  364. pool->probed = true;
  365. /* If X-Long-Polling was found, activate long polling */
  366. if (hi.lp_path) {
  367. if (pool->hdr_path != NULL)
  368. free(pool->hdr_path);
  369. pool->hdr_path = hi.lp_path;
  370. } else
  371. pool->hdr_path = NULL;
  372. if (hi.stratum_url) {
  373. pool->stratum_url = hi.stratum_url;
  374. hi.stratum_url = NULL;
  375. }
  376. } else {
  377. if (hi.lp_path) {
  378. free(hi.lp_path);
  379. hi.lp_path = NULL;
  380. }
  381. if (hi.stratum_url) {
  382. free(hi.stratum_url);
  383. hi.stratum_url = NULL;
  384. }
  385. }
  386. *rolltime = hi.rolltime;
  387. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  388. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  389. pool->cgminer_pool_stats.canroll = hi.canroll;
  390. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  391. val = JSON_LOADS(all_data.buf, &err);
  392. if (!val) {
  393. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  394. if (opt_protocol)
  395. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
  396. goto err_out;
  397. }
  398. if (opt_protocol) {
  399. char *s = json_dumps(val, JSON_INDENT(3));
  400. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  401. free(s);
  402. }
  403. /* JSON-RPC valid response returns a non-null 'result',
  404. * and a null 'error'.
  405. */
  406. res_val = json_object_get(val, "result");
  407. err_val = json_object_get(val, "error");
  408. if (!res_val ||(err_val && !json_is_null(err_val))) {
  409. char *s;
  410. if (err_val)
  411. s = json_dumps(err_val, JSON_INDENT(3));
  412. else
  413. s = strdup("(unknown reason)");
  414. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  415. free(s);
  416. goto err_out;
  417. }
  418. if (hi.reason) {
  419. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  420. free(hi.reason);
  421. hi.reason = NULL;
  422. }
  423. successful_connect = true;
  424. databuf_free(&all_data);
  425. curl_slist_free_all(headers);
  426. curl_easy_reset(curl);
  427. return val;
  428. err_out:
  429. databuf_free(&all_data);
  430. curl_slist_free_all(headers);
  431. curl_easy_reset(curl);
  432. if (!successful_connect)
  433. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  434. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  435. return NULL;
  436. }
  437. #define PROXY_HTTP CURLPROXY_HTTP
  438. #define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0
  439. #define PROXY_SOCKS4 CURLPROXY_SOCKS4
  440. #define PROXY_SOCKS5 CURLPROXY_SOCKS5
  441. #define PROXY_SOCKS4A CURLPROXY_SOCKS4A
  442. #define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME
  443. #else /* HAVE_LIBCURL */
  444. #define PROXY_HTTP 0
  445. #define PROXY_HTTP_1_0 1
  446. #define PROXY_SOCKS4 2
  447. #define PROXY_SOCKS5 3
  448. #define PROXY_SOCKS4A 4
  449. #define PROXY_SOCKS5H 5
  450. #endif /* HAVE_LIBCURL */
  451. static struct {
  452. const char *name;
  453. proxytypes_t proxytype;
  454. } proxynames[] = {
  455. { "http:", PROXY_HTTP },
  456. { "http0:", PROXY_HTTP_1_0 },
  457. { "socks4:", PROXY_SOCKS4 },
  458. { "socks5:", PROXY_SOCKS5 },
  459. { "socks4a:", PROXY_SOCKS4A },
  460. { "socks5h:", PROXY_SOCKS5H },
  461. { NULL, 0 }
  462. };
  463. const char *proxytype(proxytypes_t proxytype)
  464. {
  465. int i;
  466. for (i = 0; proxynames[i].name; i++)
  467. if (proxynames[i].proxytype == proxytype)
  468. return proxynames[i].name;
  469. return "invalid";
  470. }
  471. char *get_proxy(char *url, struct pool *pool)
  472. {
  473. pool->rpc_proxy = NULL;
  474. char *split;
  475. int plen, len, i;
  476. for (i = 0; proxynames[i].name; i++) {
  477. plen = strlen(proxynames[i].name);
  478. if (strncmp(url, proxynames[i].name, plen) == 0) {
  479. if (!(split = strchr(url, '|')))
  480. return url;
  481. *split = '\0';
  482. len = split - url;
  483. pool->rpc_proxy = malloc(1 + len - plen);
  484. if (!(pool->rpc_proxy))
  485. quithere(1, "Failed to malloc rpc_proxy");
  486. strcpy(pool->rpc_proxy, url + plen);
  487. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  488. pool->rpc_proxytype = proxynames[i].proxytype;
  489. url = split + 1;
  490. break;
  491. }
  492. }
  493. return url;
  494. }
  495. /* Adequate size s==len*2 + 1 must be alloced to use this variant */
  496. void __bin2hex(char *s, const unsigned char *p, size_t len)
  497. {
  498. int i;
  499. for (i = 0; i < (int)len; i++)
  500. sprintf(s + (i * 2), "%02x", (unsigned int)p[i]);
  501. }
  502. /* Returns a malloced array string of a binary value of arbitrary length. The
  503. * array is rounded up to a 4 byte size to appease architectures that need
  504. * aligned array sizes */
  505. char *bin2hex(const unsigned char *p, size_t len)
  506. {
  507. ssize_t slen;
  508. char *s;
  509. slen = len * 2 + 1;
  510. if (slen % 4)
  511. slen += 4 - (slen % 4);
  512. s = calloc(slen, 1);
  513. if (unlikely(!s))
  514. quithere(1, "Failed to calloc");
  515. __bin2hex(s, p, len);
  516. return s;
  517. }
  518. /* Does the reverse of bin2hex but does not allocate any ram */
  519. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  520. {
  521. bool ret = false;
  522. while (*hexstr && len) {
  523. char hex_byte[4];
  524. unsigned int v;
  525. if (unlikely(!hexstr[1])) {
  526. applog(LOG_ERR, "hex2bin str truncated");
  527. return ret;
  528. }
  529. memset(hex_byte, 0, 4);
  530. hex_byte[0] = hexstr[0];
  531. hex_byte[1] = hexstr[1];
  532. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  533. applog(LOG_INFO, "hex2bin sscanf '%s' failed", hex_byte);
  534. return ret;
  535. }
  536. *p = (unsigned char) v;
  537. p++;
  538. hexstr += 2;
  539. len--;
  540. }
  541. if (likely(len == 0 && *hexstr == 0))
  542. ret = true;
  543. return ret;
  544. }
  545. bool fulltest(const unsigned char *hash, const unsigned char *target)
  546. {
  547. unsigned char hash_swap[32], target_swap[32];
  548. uint32_t *hash32 = (uint32_t *) hash_swap;
  549. uint32_t *target32 = (uint32_t *) target_swap;
  550. char *hash_str, *target_str;
  551. bool rc = true;
  552. int i;
  553. swap256(hash_swap, hash);
  554. swap256(target_swap, target);
  555. for (i = 0; i < 32/4; i++) {
  556. uint32_t h32tmp = htobe32(hash32[i]);
  557. uint32_t t32tmp = htole32(target32[i]);
  558. target32[i] = swab32(target32[i]); /* for printing */
  559. if (h32tmp > t32tmp) {
  560. rc = false;
  561. break;
  562. }
  563. if (h32tmp < t32tmp) {
  564. rc = true;
  565. break;
  566. }
  567. }
  568. if (opt_debug) {
  569. hash_str = bin2hex(hash_swap, 32);
  570. target_str = bin2hex(target_swap, 32);
  571. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  572. hash_str,
  573. target_str,
  574. rc ? "YES (hash <= target)" :
  575. "no (false positive; hash > target)");
  576. free(hash_str);
  577. free(target_str);
  578. }
  579. return rc;
  580. }
  581. struct thread_q *tq_new(void)
  582. {
  583. struct thread_q *tq;
  584. tq = calloc(1, sizeof(*tq));
  585. if (!tq)
  586. return NULL;
  587. INIT_LIST_HEAD(&tq->q);
  588. pthread_mutex_init(&tq->mutex, NULL);
  589. pthread_cond_init(&tq->cond, NULL);
  590. return tq;
  591. }
  592. void tq_free(struct thread_q *tq)
  593. {
  594. struct tq_ent *ent, *iter;
  595. if (!tq)
  596. return;
  597. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  598. list_del(&ent->q_node);
  599. free(ent);
  600. }
  601. pthread_cond_destroy(&tq->cond);
  602. pthread_mutex_destroy(&tq->mutex);
  603. memset(tq, 0, sizeof(*tq)); /* poison */
  604. free(tq);
  605. }
  606. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  607. {
  608. mutex_lock(&tq->mutex);
  609. tq->frozen = frozen;
  610. pthread_cond_signal(&tq->cond);
  611. mutex_unlock(&tq->mutex);
  612. }
  613. void tq_freeze(struct thread_q *tq)
  614. {
  615. tq_freezethaw(tq, true);
  616. }
  617. void tq_thaw(struct thread_q *tq)
  618. {
  619. tq_freezethaw(tq, false);
  620. }
  621. bool tq_push(struct thread_q *tq, void *data)
  622. {
  623. struct tq_ent *ent;
  624. bool rc = true;
  625. ent = calloc(1, sizeof(*ent));
  626. if (!ent)
  627. return false;
  628. ent->data = data;
  629. INIT_LIST_HEAD(&ent->q_node);
  630. mutex_lock(&tq->mutex);
  631. if (!tq->frozen) {
  632. list_add_tail(&ent->q_node, &tq->q);
  633. } else {
  634. free(ent);
  635. rc = false;
  636. }
  637. pthread_cond_signal(&tq->cond);
  638. mutex_unlock(&tq->mutex);
  639. return rc;
  640. }
  641. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  642. {
  643. struct tq_ent *ent;
  644. void *rval = NULL;
  645. int rc;
  646. mutex_lock(&tq->mutex);
  647. if (!list_empty(&tq->q))
  648. goto pop;
  649. if (abstime)
  650. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  651. else
  652. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  653. if (rc)
  654. goto out;
  655. if (list_empty(&tq->q))
  656. goto out;
  657. pop:
  658. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  659. rval = ent->data;
  660. list_del(&ent->q_node);
  661. free(ent);
  662. out:
  663. mutex_unlock(&tq->mutex);
  664. return rval;
  665. }
  666. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  667. {
  668. cgsem_init(&thr->sem);
  669. return pthread_create(&thr->pth, attr, start, arg);
  670. }
  671. void thr_info_cancel(struct thr_info *thr)
  672. {
  673. if (!thr)
  674. return;
  675. if (PTH(thr) != 0L) {
  676. pthread_cancel(thr->pth);
  677. PTH(thr) = 0L;
  678. }
  679. cgsem_destroy(&thr->sem);
  680. }
  681. void subtime(struct timeval *a, struct timeval *b)
  682. {
  683. timersub(a, b, b);
  684. }
  685. void addtime(struct timeval *a, struct timeval *b)
  686. {
  687. timeradd(a, b, b);
  688. }
  689. bool time_more(struct timeval *a, struct timeval *b)
  690. {
  691. return timercmp(a, b, >);
  692. }
  693. bool time_less(struct timeval *a, struct timeval *b)
  694. {
  695. return timercmp(a, b, <);
  696. }
  697. void copy_time(struct timeval *dest, const struct timeval *src)
  698. {
  699. memcpy(dest, src, sizeof(struct timeval));
  700. }
  701. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  702. {
  703. val->tv_sec = spec->tv_sec;
  704. val->tv_usec = spec->tv_nsec / 1000;
  705. }
  706. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  707. {
  708. spec->tv_sec = val->tv_sec;
  709. spec->tv_nsec = val->tv_usec * 1000;
  710. }
  711. void us_to_timeval(struct timeval *val, int64_t us)
  712. {
  713. lldiv_t tvdiv = lldiv(us, 1000000);
  714. val->tv_sec = tvdiv.quot;
  715. val->tv_usec = tvdiv.rem;
  716. }
  717. void us_to_timespec(struct timespec *spec, int64_t us)
  718. {
  719. lldiv_t tvdiv = lldiv(us, 1000000);
  720. spec->tv_sec = tvdiv.quot;
  721. spec->tv_nsec = tvdiv.rem * 1000;
  722. }
  723. void ms_to_timespec(struct timespec *spec, int64_t ms)
  724. {
  725. lldiv_t tvdiv = lldiv(ms, 1000);
  726. spec->tv_sec = tvdiv.quot;
  727. spec->tv_nsec = tvdiv.rem * 1000000;
  728. }
  729. void ms_to_timeval(struct timeval *val, int64_t ms)
  730. {
  731. lldiv_t tvdiv = lldiv(ms, 1000);
  732. val->tv_sec = tvdiv.quot;
  733. val->tv_usec = tvdiv.rem * 1000;
  734. }
  735. void timeraddspec(struct timespec *a, const struct timespec *b)
  736. {
  737. a->tv_sec += b->tv_sec;
  738. a->tv_nsec += b->tv_nsec;
  739. if (a->tv_nsec >= 1000000000) {
  740. a->tv_nsec -= 1000000000;
  741. a->tv_sec++;
  742. }
  743. }
  744. static int __maybe_unused timespec_to_ms(struct timespec *ts)
  745. {
  746. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  747. }
  748. /* Subtract b from a */
  749. static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
  750. {
  751. a->tv_sec -= b->tv_sec;
  752. a->tv_nsec -= b->tv_nsec;
  753. if (a->tv_nsec < 0) {
  754. a->tv_nsec += 1000000000;
  755. a->tv_sec--;
  756. }
  757. }
  758. /* These are cgminer specific sleep functions that use an absolute nanosecond
  759. * resolution timer to avoid poor usleep accuracy and overruns. */
  760. #ifdef WIN32
  761. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  762. #define EPOCHFILETIME (116444736000000000LL)
  763. /* Return the system time as an lldiv_t in decimicroseconds. */
  764. static void decius_time(lldiv_t *lidiv)
  765. {
  766. FILETIME ft;
  767. LARGE_INTEGER li;
  768. GetSystemTimeAsFileTime(&ft);
  769. li.LowPart = ft.dwLowDateTime;
  770. li.HighPart = ft.dwHighDateTime;
  771. li.QuadPart -= EPOCHFILETIME;
  772. /* SystemTime is in decimicroseconds so divide by an unusual number */
  773. *lidiv = lldiv(li.QuadPart, 10000000);
  774. }
  775. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  776. * with tz set to NULL, and windows' default resolution is only 15ms, this
  777. * gives us higher resolution times on windows. */
  778. void cgtime(struct timeval *tv)
  779. {
  780. lldiv_t lidiv;
  781. decius_time(&lidiv);
  782. tv->tv_sec = lidiv.quot;
  783. tv->tv_usec = lidiv.rem / 10;
  784. }
  785. #else /* WIN32 */
  786. void cgtime(struct timeval *tv)
  787. {
  788. gettimeofday(tv, NULL);
  789. }
  790. int cgtimer_to_ms(cgtimer_t *cgt)
  791. {
  792. return timespec_to_ms(cgt);
  793. }
  794. /* Subtracts b from a and stores it in res. */
  795. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  796. {
  797. res->tv_sec = a->tv_sec - b->tv_sec;
  798. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  799. if (res->tv_nsec < 0) {
  800. res->tv_nsec += 1000000000;
  801. res->tv_sec--;
  802. }
  803. }
  804. #endif /* WIN32 */
  805. #ifdef CLOCK_MONOTONIC /* Essentially just linux */
  806. void cgtimer_time(cgtimer_t *ts_start)
  807. {
  808. clock_gettime(CLOCK_MONOTONIC, ts_start);
  809. }
  810. static void nanosleep_abstime(struct timespec *ts_end)
  811. {
  812. int ret;
  813. do {
  814. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  815. } while (ret == EINTR);
  816. }
  817. /* Reentrant version of cgsleep functions allow start time to be set separately
  818. * from the beginning of the actual sleep, allowing scheduling delays to be
  819. * counted in the sleep. */
  820. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  821. {
  822. struct timespec ts_end;
  823. ms_to_timespec(&ts_end, ms);
  824. timeraddspec(&ts_end, ts_start);
  825. nanosleep_abstime(&ts_end);
  826. }
  827. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  828. {
  829. struct timespec ts_end;
  830. us_to_timespec(&ts_end, us);
  831. timeraddspec(&ts_end, ts_start);
  832. nanosleep_abstime(&ts_end);
  833. }
  834. #else /* CLOCK_MONOTONIC */
  835. #ifdef __MACH__
  836. #include <mach/clock.h>
  837. #include <mach/mach.h>
  838. void cgtimer_time(cgtimer_t *ts_start)
  839. {
  840. clock_serv_t cclock;
  841. mach_timespec_t mts;
  842. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  843. clock_get_time(cclock, &mts);
  844. mach_port_deallocate(mach_task_self(), cclock);
  845. ts_start->tv_sec = mts.tv_sec;
  846. ts_start->tv_nsec = mts.tv_nsec;
  847. }
  848. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  849. void cgtimer_time(cgtimer_t *ts_start)
  850. {
  851. struct timeval tv;
  852. cgtime(&tv);
  853. ts_start->tv_sec = tv->tv_sec;
  854. ts_start->tv_nsec = tv->tv_usec * 1000;
  855. }
  856. #endif /* __MACH__ */
  857. #ifdef WIN32
  858. /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
  859. * typedef, allowing us to have sub-microsecond resolution for times, do simple
  860. * arithmetic for timer calculations, and use windows' own hTimers to get
  861. * accurate absolute timeouts. */
  862. int cgtimer_to_ms(cgtimer_t *cgt)
  863. {
  864. return (int)(cgt->QuadPart / 10000LL);
  865. }
  866. /* Subtracts b from a and stores it in res. */
  867. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  868. {
  869. res->QuadPart = a->QuadPart - b->QuadPart;
  870. }
  871. /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
  872. * timeouts with hTimers. */
  873. void cgtimer_time(cgtimer_t *ts_start)
  874. {
  875. FILETIME ft;
  876. GetSystemTimeAsFileTime(&ft);
  877. ts_start->LowPart = ft.dwLowDateTime;
  878. ts_start->HighPart = ft.dwHighDateTime;
  879. }
  880. static void liSleep(LARGE_INTEGER *li, int timeout)
  881. {
  882. HANDLE hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  883. DWORD ret;
  884. if (unlikely(!hTimer))
  885. quit(1, "Failed to create hTimer in liSleep");
  886. ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
  887. if (unlikely(!ret))
  888. quit(1, "Failed to SetWaitableTimer in liSleep");
  889. /* We still use a timeout as a sanity check in case the system time
  890. * is changed while we're running */
  891. ret = WaitForSingleObject(hTimer, timeout);
  892. if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
  893. quit(1, "Failed to WaitForSingleObject in liSleep");
  894. CloseHandle(hTimer);
  895. }
  896. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  897. {
  898. LARGE_INTEGER li;
  899. li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
  900. liSleep(&li, ms);
  901. }
  902. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  903. {
  904. LARGE_INTEGER li;
  905. int ms;
  906. li.QuadPart = ts_start->QuadPart + us * 10LL;
  907. ms = us / 1000;
  908. if (!ms)
  909. ms = 1;
  910. liSleep(&li, ms);
  911. }
  912. #else /* WIN32 */
  913. static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  914. {
  915. struct timespec now;
  916. timeraddspec(ts_diff, ts_start);
  917. cgtimer_time(&now);
  918. timersubspec(ts_diff, &now);
  919. if (unlikely(ts_diff->tv_sec < 0))
  920. return;
  921. nanosleep(ts_diff, NULL);
  922. }
  923. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  924. {
  925. struct timespec ts_diff;
  926. ms_to_timespec(&ts_diff, ms);
  927. cgsleep_spec(&ts_diff, ts_start);
  928. }
  929. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  930. {
  931. struct timespec ts_diff;
  932. us_to_timespec(&ts_diff, us);
  933. cgsleep_spec(&ts_diff, ts_start);
  934. }
  935. #endif /* WIN32 */
  936. #endif /* CLOCK_MONOTONIC */
  937. void cgsleep_ms(int ms)
  938. {
  939. cgtimer_t ts_start;
  940. cgsleep_prepare_r(&ts_start);
  941. cgsleep_ms_r(&ts_start, ms);
  942. }
  943. void cgsleep_us(int64_t us)
  944. {
  945. cgtimer_t ts_start;
  946. cgsleep_prepare_r(&ts_start);
  947. cgsleep_us_r(&ts_start, us);
  948. }
  949. /* Returns the microseconds difference between end and start times as a double */
  950. double us_tdiff(struct timeval *end, struct timeval *start)
  951. {
  952. /* Sanity check. We should only be using this for small differences so
  953. * limit the max to 60 seconds. */
  954. if (unlikely(end->tv_sec - start->tv_sec > 60))
  955. return 60000000;
  956. return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
  957. }
  958. /* Returns the milliseconds difference between end and start times */
  959. int ms_tdiff(struct timeval *end, struct timeval *start)
  960. {
  961. /* Like us_tdiff, limit to 1 hour. */
  962. if (unlikely(end->tv_sec - start->tv_sec > 3600))
  963. return 3600000;
  964. return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
  965. }
  966. /* Returns the seconds difference between end and start times as a double */
  967. double tdiff(struct timeval *end, struct timeval *start)
  968. {
  969. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  970. }
  971. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  972. {
  973. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  974. char url_address[256], port[6];
  975. int url_len, port_len = 0;
  976. *sockaddr_url = url;
  977. url_begin = strstr(url, "//");
  978. if (!url_begin)
  979. url_begin = url;
  980. else
  981. url_begin += 2;
  982. /* Look for numeric ipv6 entries */
  983. ipv6_begin = strstr(url_begin, "[");
  984. ipv6_end = strstr(url_begin, "]");
  985. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  986. url_end = strstr(ipv6_end, ":");
  987. else
  988. url_end = strstr(url_begin, ":");
  989. if (url_end) {
  990. url_len = url_end - url_begin;
  991. port_len = strlen(url_begin) - url_len - 1;
  992. if (port_len < 1)
  993. return false;
  994. port_start = url_end + 1;
  995. } else
  996. url_len = strlen(url_begin);
  997. if (url_len < 1)
  998. return false;
  999. sprintf(url_address, "%.*s", url_len, url_begin);
  1000. if (port_len) {
  1001. char *slash;
  1002. snprintf(port, 6, "%.*s", port_len, port_start);
  1003. slash = strchr(port, '/');
  1004. if (slash)
  1005. *slash = '\0';
  1006. } else
  1007. strcpy(port, "80");
  1008. *sockaddr_port = strdup(port);
  1009. *sockaddr_url = strdup(url_address);
  1010. return true;
  1011. }
  1012. enum send_ret {
  1013. SEND_OK,
  1014. SEND_SELECTFAIL,
  1015. SEND_SENDFAIL,
  1016. SEND_INACTIVE
  1017. };
  1018. /* Send a single command across a socket, appending \n to it. This should all
  1019. * be done under stratum lock except when first establishing the socket */
  1020. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1021. {
  1022. SOCKETTYPE sock = pool->sock;
  1023. ssize_t ssent = 0;
  1024. strcat(s, "\n");
  1025. len++;
  1026. while (len > 0 ) {
  1027. struct timeval timeout = {1, 0};
  1028. ssize_t sent;
  1029. fd_set wd;
  1030. FD_ZERO(&wd);
  1031. FD_SET(sock, &wd);
  1032. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  1033. return SEND_SELECTFAIL;
  1034. #ifdef __APPLE__
  1035. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1036. #elif WIN32
  1037. sent = send(pool->sock, s + ssent, len, 0);
  1038. #else
  1039. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1040. #endif
  1041. if (sent < 0) {
  1042. if (!sock_blocks())
  1043. return SEND_SENDFAIL;
  1044. sent = 0;
  1045. }
  1046. ssent += sent;
  1047. len -= sent;
  1048. }
  1049. pool->cgminer_pool_stats.times_sent++;
  1050. pool->cgminer_pool_stats.bytes_sent += ssent;
  1051. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1052. return SEND_OK;
  1053. }
  1054. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1055. {
  1056. enum send_ret ret = SEND_INACTIVE;
  1057. if (opt_protocol)
  1058. applog(LOG_DEBUG, "SEND: %s", s);
  1059. mutex_lock(&pool->stratum_lock);
  1060. if (pool->stratum_active)
  1061. ret = __stratum_send(pool, s, len);
  1062. mutex_unlock(&pool->stratum_lock);
  1063. /* This is to avoid doing applog under stratum_lock */
  1064. switch (ret) {
  1065. default:
  1066. case SEND_OK:
  1067. break;
  1068. case SEND_SELECTFAIL:
  1069. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1070. suspend_stratum(pool);
  1071. break;
  1072. case SEND_SENDFAIL:
  1073. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1074. suspend_stratum(pool);
  1075. break;
  1076. case SEND_INACTIVE:
  1077. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1078. break;
  1079. }
  1080. return (ret == SEND_OK);
  1081. }
  1082. static bool socket_full(struct pool *pool, int wait)
  1083. {
  1084. SOCKETTYPE sock = pool->sock;
  1085. struct timeval timeout;
  1086. fd_set rd;
  1087. if (unlikely(wait < 0))
  1088. wait = 0;
  1089. FD_ZERO(&rd);
  1090. FD_SET(sock, &rd);
  1091. timeout.tv_usec = 0;
  1092. timeout.tv_sec = wait;
  1093. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1094. return true;
  1095. return false;
  1096. }
  1097. /* Check to see if Santa's been good to you */
  1098. bool sock_full(struct pool *pool)
  1099. {
  1100. if (strlen(pool->sockbuf))
  1101. return true;
  1102. return (socket_full(pool, 0));
  1103. }
  1104. static void clear_sockbuf(struct pool *pool)
  1105. {
  1106. strcpy(pool->sockbuf, "");
  1107. }
  1108. static void clear_sock(struct pool *pool)
  1109. {
  1110. ssize_t n;
  1111. mutex_lock(&pool->stratum_lock);
  1112. do {
  1113. if (pool->sock)
  1114. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1115. else
  1116. n = 0;
  1117. } while (n > 0);
  1118. mutex_unlock(&pool->stratum_lock);
  1119. clear_sockbuf(pool);
  1120. }
  1121. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1122. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1123. * and zeroing the new memory */
  1124. static void recalloc_sock(struct pool *pool, size_t len)
  1125. {
  1126. size_t old, new;
  1127. old = strlen(pool->sockbuf);
  1128. new = old + len + 1;
  1129. if (new < pool->sockbuf_size)
  1130. return;
  1131. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1132. // Avoid potentially recursive locking
  1133. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1134. pool->sockbuf = realloc(pool->sockbuf, new);
  1135. if (!pool->sockbuf)
  1136. quithere(1, "Failed to realloc pool sockbuf");
  1137. memset(pool->sockbuf + old, 0, new - old);
  1138. pool->sockbuf_size = new;
  1139. }
  1140. /* Peeks at a socket to find the first end of line and then reads just that
  1141. * from the socket and returns that as a malloced char */
  1142. char *recv_line(struct pool *pool)
  1143. {
  1144. char *tok, *sret = NULL;
  1145. ssize_t len, buflen;
  1146. int waited = 0;
  1147. if (!strstr(pool->sockbuf, "\n")) {
  1148. struct timeval rstart, now;
  1149. cgtime(&rstart);
  1150. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1151. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1152. goto out;
  1153. }
  1154. do {
  1155. char s[RBUFSIZE];
  1156. size_t slen;
  1157. ssize_t n;
  1158. memset(s, 0, RBUFSIZE);
  1159. n = recv(pool->sock, s, RECVSIZE, 0);
  1160. if (!n) {
  1161. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1162. suspend_stratum(pool);
  1163. break;
  1164. }
  1165. cgtime(&now);
  1166. waited = tdiff(&now, &rstart);
  1167. if (n < 0) {
  1168. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1169. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1170. suspend_stratum(pool);
  1171. break;
  1172. }
  1173. } else {
  1174. slen = strlen(s);
  1175. recalloc_sock(pool, slen);
  1176. strcat(pool->sockbuf, s);
  1177. }
  1178. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1179. }
  1180. buflen = strlen(pool->sockbuf);
  1181. tok = strtok(pool->sockbuf, "\n");
  1182. if (!tok) {
  1183. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1184. goto out;
  1185. }
  1186. sret = strdup(tok);
  1187. len = strlen(sret);
  1188. /* Copy what's left in the buffer after the \n, including the
  1189. * terminating \0 */
  1190. if (buflen > len + 1)
  1191. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1192. else
  1193. strcpy(pool->sockbuf, "");
  1194. pool->cgminer_pool_stats.times_received++;
  1195. pool->cgminer_pool_stats.bytes_received += len;
  1196. pool->cgminer_pool_stats.net_bytes_received += len;
  1197. out:
  1198. if (!sret)
  1199. clear_sock(pool);
  1200. else if (opt_protocol)
  1201. applog(LOG_DEBUG, "RECVD: %s", sret);
  1202. return sret;
  1203. }
  1204. /* Extracts a string value from a json array with error checking. To be used
  1205. * when the value of the string returned is only examined and not to be stored.
  1206. * See json_array_string below */
  1207. static char *__json_array_string(json_t *val, unsigned int entry)
  1208. {
  1209. json_t *arr_entry;
  1210. if (json_is_null(val))
  1211. return NULL;
  1212. if (!json_is_array(val))
  1213. return NULL;
  1214. if (entry > json_array_size(val))
  1215. return NULL;
  1216. arr_entry = json_array_get(val, entry);
  1217. if (!json_is_string(arr_entry))
  1218. return NULL;
  1219. return (char *)json_string_value(arr_entry);
  1220. }
  1221. /* Creates a freshly malloced dup of __json_array_string */
  1222. static char *json_array_string(json_t *val, unsigned int entry)
  1223. {
  1224. char *buf = __json_array_string(val, entry);
  1225. if (buf)
  1226. return strdup(buf);
  1227. return NULL;
  1228. }
  1229. static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
  1230. static bool parse_notify(struct pool *pool, json_t *val)
  1231. {
  1232. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1233. *ntime, *header;
  1234. size_t cb1_len, cb2_len, alloc_len;
  1235. unsigned char *cb1, *cb2;
  1236. bool clean, ret = false;
  1237. int merkles, i;
  1238. json_t *arr;
  1239. arr = json_array_get(val, 4);
  1240. if (!arr || !json_is_array(arr))
  1241. goto out;
  1242. merkles = json_array_size(arr);
  1243. job_id = json_array_string(val, 0);
  1244. prev_hash = json_array_string(val, 1);
  1245. coinbase1 = json_array_string(val, 2);
  1246. coinbase2 = json_array_string(val, 3);
  1247. bbversion = json_array_string(val, 5);
  1248. nbit = json_array_string(val, 6);
  1249. ntime = json_array_string(val, 7);
  1250. clean = json_is_true(json_array_get(val, 8));
  1251. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1252. /* Annoying but we must not leak memory */
  1253. if (job_id)
  1254. free(job_id);
  1255. if (prev_hash)
  1256. free(prev_hash);
  1257. if (coinbase1)
  1258. free(coinbase1);
  1259. if (coinbase2)
  1260. free(coinbase2);
  1261. if (bbversion)
  1262. free(bbversion);
  1263. if (nbit)
  1264. free(nbit);
  1265. if (ntime)
  1266. free(ntime);
  1267. goto out;
  1268. }
  1269. cg_wlock(&pool->data_lock);
  1270. free(pool->swork.job_id);
  1271. free(pool->swork.prev_hash);
  1272. free(pool->swork.bbversion);
  1273. free(pool->swork.nbit);
  1274. free(pool->swork.ntime);
  1275. pool->swork.job_id = job_id;
  1276. pool->swork.prev_hash = prev_hash;
  1277. cb1_len = strlen(coinbase1) / 2;
  1278. cb2_len = strlen(coinbase2) / 2;
  1279. pool->swork.bbversion = bbversion;
  1280. pool->swork.nbit = nbit;
  1281. pool->swork.ntime = ntime;
  1282. pool->swork.clean = clean;
  1283. alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  1284. pool->nonce2_offset = cb1_len + pool->n1_len;
  1285. for (i = 0; i < pool->swork.merkles; i++)
  1286. free(pool->swork.merkle_bin[i]);
  1287. if (merkles) {
  1288. pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
  1289. sizeof(char *) * merkles + 1);
  1290. for (i = 0; i < merkles; i++) {
  1291. char *merkle = json_array_string(arr, i);
  1292. pool->swork.merkle_bin[i] = malloc(32);
  1293. if (unlikely(!pool->swork.merkle_bin[i]))
  1294. quit(1, "Failed to malloc pool swork merkle_bin");
  1295. hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  1296. free(merkle);
  1297. }
  1298. }
  1299. pool->swork.merkles = merkles;
  1300. if (clean)
  1301. pool->nonce2 = 0;
  1302. pool->merkle_offset = strlen(pool->swork.bbversion) +
  1303. strlen(pool->swork.prev_hash);
  1304. pool->swork.header_len = pool->merkle_offset +
  1305. /* merkle_hash */ 32 +
  1306. strlen(pool->swork.ntime) +
  1307. strlen(pool->swork.nbit) +
  1308. /* nonce */ 8 +
  1309. /* workpadding */ 96;
  1310. pool->merkle_offset /= 2;
  1311. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1312. align_len(&pool->swork.header_len);
  1313. header = alloca(pool->swork.header_len);
  1314. snprintf(header, pool->swork.header_len,
  1315. "%s%s%s%s%s%s%s",
  1316. pool->swork.bbversion,
  1317. pool->swork.prev_hash,
  1318. blank_merkel,
  1319. pool->swork.ntime,
  1320. pool->swork.nbit,
  1321. "00000000", /* nonce */
  1322. workpadding);
  1323. if (unlikely(!hex2bin(pool->header_bin, header, 128)))
  1324. quit(1, "Failed to convert header to header_bin in parse_notify");
  1325. cb1 = calloc(cb1_len, 1);
  1326. if (unlikely(!cb1))
  1327. quithere(1, "Failed to calloc cb1 in parse_notify");
  1328. hex2bin(cb1, coinbase1, cb1_len);
  1329. cb2 = calloc(cb2_len, 1);
  1330. if (unlikely(!cb2))
  1331. quithere(1, "Failed to calloc cb2 in parse_notify");
  1332. hex2bin(cb2, coinbase2, cb2_len);
  1333. free(pool->coinbase);
  1334. align_len(&alloc_len);
  1335. pool->coinbase = calloc(alloc_len, 1);
  1336. if (unlikely(!pool->coinbase))
  1337. quit(1, "Failed to calloc pool coinbase in parse_notify");
  1338. memcpy(pool->coinbase, cb1, cb1_len);
  1339. memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  1340. memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  1341. cg_wunlock(&pool->data_lock);
  1342. if (opt_protocol) {
  1343. applog(LOG_DEBUG, "job_id: %s", job_id);
  1344. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1345. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1346. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1347. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1348. applog(LOG_DEBUG, "nbit: %s", nbit);
  1349. applog(LOG_DEBUG, "ntime: %s", ntime);
  1350. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1351. }
  1352. free(coinbase1);
  1353. free(coinbase2);
  1354. free(cb1);
  1355. free(cb2);
  1356. /* A notify message is the closest stratum gets to a getwork */
  1357. pool->getwork_requested++;
  1358. total_getworks++;
  1359. ret = true;
  1360. if (pool == current_pool())
  1361. opt_work_update = true;
  1362. out:
  1363. return ret;
  1364. }
  1365. static bool parse_diff(struct pool *pool, json_t *val)
  1366. {
  1367. double old_diff, diff;
  1368. diff = json_number_value(json_array_get(val, 0));
  1369. if (diff == 0)
  1370. return false;
  1371. cg_wlock(&pool->data_lock);
  1372. old_diff = pool->swork.diff;
  1373. pool->swork.diff = diff;
  1374. cg_wunlock(&pool->data_lock);
  1375. if (old_diff != diff) {
  1376. int idiff = diff;
  1377. if ((double)idiff == diff)
  1378. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  1379. pool->pool_no, idiff);
  1380. else
  1381. applog(LOG_NOTICE, "Pool %d difficulty changed to %f",
  1382. pool->pool_no, diff);
  1383. } else
  1384. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  1385. diff);
  1386. return true;
  1387. }
  1388. static bool parse_reconnect(struct pool *pool, json_t *val)
  1389. {
  1390. char *url, *port, address[256];
  1391. memset(address, 0, 255);
  1392. url = (char *)json_string_value(json_array_get(val, 0));
  1393. if (!url)
  1394. url = pool->sockaddr_url;
  1395. port = (char *)json_string_value(json_array_get(val, 1));
  1396. if (!port)
  1397. port = pool->stratum_port;
  1398. sprintf(address, "%s:%s", url, port);
  1399. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  1400. return false;
  1401. pool->stratum_url = pool->sockaddr_url;
  1402. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1403. if (!restart_stratum(pool))
  1404. return false;
  1405. return true;
  1406. }
  1407. static bool send_version(struct pool *pool, json_t *val)
  1408. {
  1409. char s[RBUFSIZE];
  1410. int id = json_integer_value(json_object_get(val, "id"));
  1411. if (!id)
  1412. return false;
  1413. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1414. if (!stratum_send(pool, s, strlen(s)))
  1415. return false;
  1416. return true;
  1417. }
  1418. static bool show_message(struct pool *pool, json_t *val)
  1419. {
  1420. char *msg;
  1421. if (!json_is_array(val))
  1422. return false;
  1423. msg = (char *)json_string_value(json_array_get(val, 0));
  1424. if (!msg)
  1425. return false;
  1426. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  1427. return true;
  1428. }
  1429. bool parse_method(struct pool *pool, char *s)
  1430. {
  1431. json_t *val = NULL, *method, *err_val, *params;
  1432. json_error_t err;
  1433. bool ret = false;
  1434. char *buf;
  1435. if (!s)
  1436. return ret;
  1437. val = JSON_LOADS(s, &err);
  1438. if (!val) {
  1439. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1440. return ret;
  1441. }
  1442. method = json_object_get(val, "method");
  1443. if (!method)
  1444. return ret;
  1445. err_val = json_object_get(val, "error");
  1446. params = json_object_get(val, "params");
  1447. if (err_val && !json_is_null(err_val)) {
  1448. char *ss;
  1449. if (err_val)
  1450. ss = json_dumps(err_val, JSON_INDENT(3));
  1451. else
  1452. ss = strdup("(unknown reason)");
  1453. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1454. free(ss);
  1455. return ret;
  1456. }
  1457. buf = (char *)json_string_value(method);
  1458. if (!buf)
  1459. return ret;
  1460. if (!strncasecmp(buf, "mining.notify", 13)) {
  1461. if (parse_notify(pool, params))
  1462. pool->stratum_notify = ret = true;
  1463. else
  1464. pool->stratum_notify = ret = false;
  1465. return ret;
  1466. }
  1467. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1468. ret = true;
  1469. return ret;
  1470. }
  1471. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1472. ret = true;
  1473. return ret;
  1474. }
  1475. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1476. ret = true;
  1477. return ret;
  1478. }
  1479. if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
  1480. ret = true;
  1481. return ret;
  1482. }
  1483. return ret;
  1484. }
  1485. bool auth_stratum(struct pool *pool)
  1486. {
  1487. json_t *val = NULL, *res_val, *err_val;
  1488. char s[RBUFSIZE], *sret = NULL;
  1489. json_error_t err;
  1490. bool ret = false;
  1491. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1492. swork_id++, pool->rpc_user, pool->rpc_pass);
  1493. if (!stratum_send(pool, s, strlen(s)))
  1494. return ret;
  1495. /* Parse all data in the queue and anything left should be auth */
  1496. while (42) {
  1497. sret = recv_line(pool);
  1498. if (!sret)
  1499. return ret;
  1500. if (parse_method(pool, sret))
  1501. free(sret);
  1502. else
  1503. break;
  1504. }
  1505. val = JSON_LOADS(sret, &err);
  1506. free(sret);
  1507. res_val = json_object_get(val, "result");
  1508. err_val = json_object_get(val, "error");
  1509. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1510. char *ss;
  1511. if (err_val)
  1512. ss = json_dumps(err_val, JSON_INDENT(3));
  1513. else
  1514. ss = strdup("(unknown reason)");
  1515. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1516. free(ss);
  1517. return ret;
  1518. }
  1519. ret = true;
  1520. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1521. pool->probed = true;
  1522. successful_connect = true;
  1523. return ret;
  1524. }
  1525. static int recv_byte(int sockd)
  1526. {
  1527. char c;
  1528. if (recv(sockd, &c, 1, 0) != -1)
  1529. return c;
  1530. return -1;
  1531. }
  1532. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  1533. {
  1534. char buf[1024];
  1535. int i, len;
  1536. if (http0) {
  1537. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  1538. pool->sockaddr_url, pool->stratum_port);
  1539. } else {
  1540. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  1541. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  1542. pool->stratum_port);
  1543. }
  1544. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  1545. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1546. send(sockd, buf, strlen(buf), 0);
  1547. len = recv(sockd, buf, 12, 0);
  1548. if (len <= 0) {
  1549. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  1550. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1551. return false;
  1552. }
  1553. buf[len] = '\0';
  1554. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  1555. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1556. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  1557. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  1558. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1559. return false;
  1560. }
  1561. /* Ignore unwanted headers till we get desired response */
  1562. for (i = 0; i < 4; i++) {
  1563. buf[i] = recv_byte(sockd);
  1564. if (buf[i] == (char)-1) {
  1565. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  1566. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1567. return false;
  1568. }
  1569. }
  1570. while (strncmp(buf, "\r\n\r\n", 4)) {
  1571. for (i = 0; i < 3; i++)
  1572. buf[i] = buf[i + 1];
  1573. buf[3] = recv_byte(sockd);
  1574. if (buf[3] == (char)-1) {
  1575. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  1576. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1577. return false;
  1578. }
  1579. }
  1580. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  1581. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1582. return true;
  1583. }
  1584. static bool socks5_negotiate(struct pool *pool, int sockd)
  1585. {
  1586. unsigned char atyp, uclen;
  1587. unsigned short port;
  1588. char buf[515];
  1589. int i, len;
  1590. buf[0] = 0x05;
  1591. buf[1] = 0x01;
  1592. buf[2] = 0x00;
  1593. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  1594. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1595. send(sockd, buf, 3, 0);
  1596. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  1597. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1598. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1599. return false;
  1600. }
  1601. buf[0] = 0x05;
  1602. buf[1] = 0x01;
  1603. buf[2] = 0x00;
  1604. buf[3] = 0x03;
  1605. len = (strlen(pool->sockaddr_url));
  1606. if (len > 255)
  1607. len = 255;
  1608. uclen = len;
  1609. buf[4] = (uclen & 0xff);
  1610. memcpy(buf + 5, pool->sockaddr_url, len);
  1611. port = atoi(pool->stratum_port);
  1612. buf[5 + len] = (port >> 8);
  1613. buf[6 + len] = (port & 0xff);
  1614. send(sockd, buf, (7 + len), 0);
  1615. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  1616. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1617. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1618. return false;
  1619. }
  1620. recv_byte(sockd);
  1621. atyp = recv_byte(sockd);
  1622. if (atyp == 0x01) {
  1623. for (i = 0; i < 4; i++)
  1624. recv_byte(sockd);
  1625. } else if (atyp == 0x03) {
  1626. len = recv_byte(sockd);
  1627. for (i = 0; i < len; i++)
  1628. recv_byte(sockd);
  1629. } else {
  1630. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1631. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1632. return false;
  1633. }
  1634. for (i = 0; i < 2; i++)
  1635. recv_byte(sockd);
  1636. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  1637. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1638. return true;
  1639. }
  1640. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  1641. {
  1642. unsigned short port;
  1643. in_addr_t inp;
  1644. char buf[515];
  1645. int i, len;
  1646. buf[0] = 0x04;
  1647. buf[1] = 0x01;
  1648. port = atoi(pool->stratum_port);
  1649. buf[2] = port >> 8;
  1650. buf[3] = port & 0xff;
  1651. sprintf(&buf[8], "CGMINER");
  1652. /* See if we've been given an IP address directly to avoid needing to
  1653. * resolve it. */
  1654. inp = inet_addr(pool->sockaddr_url);
  1655. inp = ntohl(inp);
  1656. if ((int)inp != -1)
  1657. socks4a = false;
  1658. else {
  1659. /* Try to extract the IP address ourselves first */
  1660. struct addrinfo servinfobase, *servinfo, hints;
  1661. servinfo = &servinfobase;
  1662. memset(&hints, 0, sizeof(struct addrinfo));
  1663. hints.ai_family = AF_INET; /* IPV4 only */
  1664. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  1665. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  1666. inp = ntohl(saddr_in->sin_addr.s_addr);
  1667. socks4a = false;
  1668. freeaddrinfo(servinfo);
  1669. }
  1670. }
  1671. if (!socks4a) {
  1672. if ((int)inp == -1) {
  1673. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  1674. pool->sockaddr_url);
  1675. return false;
  1676. }
  1677. buf[4] = (inp >> 24) & 0xFF;
  1678. buf[5] = (inp >> 16) & 0xFF;
  1679. buf[6] = (inp >> 8) & 0xFF;
  1680. buf[7] = (inp >> 0) & 0xFF;
  1681. send(sockd, buf, 16, 0);
  1682. } else {
  1683. /* This appears to not be working but hopefully most will be
  1684. * able to resolve IP addresses themselves. */
  1685. buf[4] = 0;
  1686. buf[5] = 0;
  1687. buf[6] = 0;
  1688. buf[7] = 1;
  1689. len = strlen(pool->sockaddr_url);
  1690. if (len > 255)
  1691. len = 255;
  1692. memcpy(&buf[16], pool->sockaddr_url, len);
  1693. len += 16;
  1694. buf[len++] = '\0';
  1695. send(sockd, buf, len, 0);
  1696. }
  1697. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  1698. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  1699. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1700. return false;
  1701. }
  1702. for (i = 0; i < 6; i++)
  1703. recv_byte(sockd);
  1704. return true;
  1705. }
  1706. static bool setup_stratum_socket(struct pool *pool)
  1707. {
  1708. struct addrinfo servinfobase, *servinfo, *hints, *p;
  1709. char *sockaddr_url, *sockaddr_port;
  1710. int sockd;
  1711. mutex_lock(&pool->stratum_lock);
  1712. pool->stratum_active = false;
  1713. if (pool->sock)
  1714. CLOSESOCKET(pool->sock);
  1715. pool->sock = 0;
  1716. mutex_unlock(&pool->stratum_lock);
  1717. hints = &pool->stratum_hints;
  1718. memset(hints, 0, sizeof(struct addrinfo));
  1719. hints->ai_family = AF_UNSPEC;
  1720. hints->ai_socktype = SOCK_STREAM;
  1721. servinfo = &servinfobase;
  1722. if (!pool->rpc_proxy && opt_socks_proxy) {
  1723. pool->rpc_proxy = opt_socks_proxy;
  1724. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  1725. pool->rpc_proxytype = PROXY_SOCKS5;
  1726. }
  1727. if (pool->rpc_proxy) {
  1728. sockaddr_url = pool->sockaddr_proxy_url;
  1729. sockaddr_port = pool->sockaddr_proxy_port;
  1730. } else {
  1731. sockaddr_url = pool->sockaddr_url;
  1732. sockaddr_port = pool->stratum_port;
  1733. }
  1734. if (getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo) != 0) {
  1735. if (!pool->probed) {
  1736. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  1737. sockaddr_url, sockaddr_port);
  1738. pool->probed = true;
  1739. } else {
  1740. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  1741. sockaddr_url, sockaddr_port);
  1742. }
  1743. return false;
  1744. }
  1745. for (p = servinfo; p != NULL; p = p->ai_next) {
  1746. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  1747. if (sockd == -1) {
  1748. applog(LOG_DEBUG, "Failed socket");
  1749. continue;
  1750. }
  1751. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  1752. CLOSESOCKET(sockd);
  1753. applog(LOG_DEBUG, "Failed connect");
  1754. continue;
  1755. }
  1756. break;
  1757. }
  1758. if (p == NULL) {
  1759. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  1760. sockaddr_url, sockaddr_port);
  1761. freeaddrinfo(servinfo);
  1762. return false;
  1763. }
  1764. freeaddrinfo(servinfo);
  1765. if (pool->rpc_proxy) {
  1766. switch (pool->rpc_proxytype) {
  1767. case PROXY_HTTP_1_0:
  1768. if (!http_negotiate(pool, sockd, true))
  1769. return false;
  1770. break;
  1771. case PROXY_HTTP:
  1772. if (!http_negotiate(pool, sockd, false))
  1773. return false;
  1774. break;
  1775. case PROXY_SOCKS5:
  1776. case PROXY_SOCKS5H:
  1777. if (!socks5_negotiate(pool, sockd))
  1778. return false;
  1779. break;
  1780. case PROXY_SOCKS4:
  1781. if (!socks4_negotiate(pool, sockd, false))
  1782. return false;
  1783. break;
  1784. case PROXY_SOCKS4A:
  1785. if (!socks4_negotiate(pool, sockd, true))
  1786. return false;
  1787. break;
  1788. default:
  1789. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  1790. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1791. return false;
  1792. break;
  1793. }
  1794. }
  1795. if (!pool->sockbuf) {
  1796. pool->sockbuf = calloc(RBUFSIZE, 1);
  1797. if (!pool->sockbuf)
  1798. quithere(1, "Failed to calloc pool sockbuf");
  1799. pool->sockbuf_size = RBUFSIZE;
  1800. }
  1801. pool->sock = sockd;
  1802. keep_sockalive(sockd);
  1803. return true;
  1804. }
  1805. static char *get_sessionid(json_t *val)
  1806. {
  1807. char *ret = NULL;
  1808. json_t *arr_val;
  1809. int arrsize, i;
  1810. arr_val = json_array_get(val, 0);
  1811. if (!arr_val || !json_is_array(arr_val))
  1812. goto out;
  1813. arrsize = json_array_size(arr_val);
  1814. for (i = 0; i < arrsize; i++) {
  1815. json_t *arr = json_array_get(arr_val, i);
  1816. char *notify;
  1817. if (!arr | !json_is_array(arr))
  1818. break;
  1819. notify = __json_array_string(arr, 0);
  1820. if (!notify)
  1821. continue;
  1822. if (!strncasecmp(notify, "mining.notify", 13)) {
  1823. ret = json_array_string(arr, 1);
  1824. break;
  1825. }
  1826. }
  1827. out:
  1828. return ret;
  1829. }
  1830. void suspend_stratum(struct pool *pool)
  1831. {
  1832. clear_sockbuf(pool);
  1833. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1834. mutex_lock(&pool->stratum_lock);
  1835. pool->stratum_active = pool->stratum_notify = false;
  1836. if (pool->sock)
  1837. CLOSESOCKET(pool->sock);
  1838. pool->sock = 0;
  1839. mutex_unlock(&pool->stratum_lock);
  1840. }
  1841. bool initiate_stratum(struct pool *pool)
  1842. {
  1843. bool ret = false, recvd = false, noresume = false, sockd = false;
  1844. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1845. json_t *val = NULL, *res_val, *err_val;
  1846. json_error_t err;
  1847. int n2size;
  1848. resend:
  1849. if (!setup_stratum_socket(pool)) {
  1850. sockd = false;
  1851. goto out;
  1852. }
  1853. sockd = true;
  1854. if (recvd) {
  1855. /* Get rid of any crap lying around if we're resending */
  1856. clear_sock(pool);
  1857. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1858. } else {
  1859. if (pool->sessionid)
  1860. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1861. else
  1862. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1863. }
  1864. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1865. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1866. goto out;
  1867. }
  1868. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1869. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1870. goto out;
  1871. }
  1872. sret = recv_line(pool);
  1873. if (!sret)
  1874. goto out;
  1875. recvd = true;
  1876. val = JSON_LOADS(sret, &err);
  1877. free(sret);
  1878. if (!val) {
  1879. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1880. goto out;
  1881. }
  1882. res_val = json_object_get(val, "result");
  1883. err_val = json_object_get(val, "error");
  1884. if (!res_val || json_is_null(res_val) ||
  1885. (err_val && !json_is_null(err_val))) {
  1886. char *ss;
  1887. if (err_val)
  1888. ss = json_dumps(err_val, JSON_INDENT(3));
  1889. else
  1890. ss = strdup("(unknown reason)");
  1891. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1892. free(ss);
  1893. goto out;
  1894. }
  1895. sessionid = get_sessionid(res_val);
  1896. if (!sessionid)
  1897. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1898. nonce1 = json_array_string(res_val, 1);
  1899. if (!nonce1) {
  1900. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1901. free(sessionid);
  1902. goto out;
  1903. }
  1904. n2size = json_integer_value(json_array_get(res_val, 2));
  1905. if (!n2size) {
  1906. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1907. free(sessionid);
  1908. free(nonce1);
  1909. goto out;
  1910. }
  1911. cg_wlock(&pool->data_lock);
  1912. pool->sessionid = sessionid;
  1913. pool->nonce1 = nonce1;
  1914. pool->n1_len = strlen(nonce1) / 2;
  1915. free(pool->nonce1bin);
  1916. pool->nonce1bin = calloc(pool->n1_len, 1);
  1917. if (unlikely(!pool->nonce1bin))
  1918. quithere(1, "Failed to calloc pool->nonce1bin");
  1919. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  1920. pool->n2size = n2size;
  1921. cg_wunlock(&pool->data_lock);
  1922. if (sessionid)
  1923. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1924. ret = true;
  1925. out:
  1926. if (ret) {
  1927. if (!pool->stratum_url)
  1928. pool->stratum_url = pool->sockaddr_url;
  1929. pool->stratum_active = true;
  1930. pool->swork.diff = 1;
  1931. if (opt_protocol) {
  1932. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1933. pool->pool_no, pool->nonce1, pool->n2size);
  1934. }
  1935. } else {
  1936. if (recvd && !noresume) {
  1937. /* Reset the sessionid used for stratum resuming in case the pool
  1938. * does not support it, or does not know how to respond to the
  1939. * presence of the sessionid parameter. */
  1940. cg_wlock(&pool->data_lock);
  1941. free(pool->sessionid);
  1942. free(pool->nonce1);
  1943. pool->sessionid = pool->nonce1 = NULL;
  1944. cg_wunlock(&pool->data_lock);
  1945. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1946. noresume = true;
  1947. goto resend;
  1948. }
  1949. applog(LOG_DEBUG, "Initiate stratum failed");
  1950. if (sockd)
  1951. suspend_stratum(pool);
  1952. }
  1953. return ret;
  1954. }
  1955. bool restart_stratum(struct pool *pool)
  1956. {
  1957. if (pool->stratum_active)
  1958. suspend_stratum(pool);
  1959. if (!initiate_stratum(pool))
  1960. return false;
  1961. if (!auth_stratum(pool))
  1962. return false;
  1963. return true;
  1964. }
  1965. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1966. {
  1967. dev->device_last_not_well = time(NULL);
  1968. dev->device_not_well_reason = reason;
  1969. switch (reason) {
  1970. case REASON_THREAD_FAIL_INIT:
  1971. dev->thread_fail_init_count++;
  1972. break;
  1973. case REASON_THREAD_ZERO_HASH:
  1974. dev->thread_zero_hash_count++;
  1975. break;
  1976. case REASON_THREAD_FAIL_QUEUE:
  1977. dev->thread_fail_queue_count++;
  1978. break;
  1979. case REASON_DEV_SICK_IDLE_60:
  1980. dev->dev_sick_idle_60_count++;
  1981. break;
  1982. case REASON_DEV_DEAD_IDLE_600:
  1983. dev->dev_dead_idle_600_count++;
  1984. break;
  1985. case REASON_DEV_NOSTART:
  1986. dev->dev_nostart_count++;
  1987. break;
  1988. case REASON_DEV_OVER_HEAT:
  1989. dev->dev_over_heat_count++;
  1990. break;
  1991. case REASON_DEV_THERMAL_CUTOFF:
  1992. dev->dev_thermal_cutoff_count++;
  1993. break;
  1994. case REASON_DEV_COMMS_ERROR:
  1995. dev->dev_comms_error_count++;
  1996. break;
  1997. case REASON_DEV_THROTTLE:
  1998. dev->dev_throttle_count++;
  1999. break;
  2000. }
  2001. }
  2002. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2003. void *realloc_strcat(char *ptr, char *s)
  2004. {
  2005. size_t old = strlen(ptr), len = strlen(s);
  2006. char *ret;
  2007. if (!len)
  2008. return ptr;
  2009. len += old + 1;
  2010. align_len(&len);
  2011. ret = malloc(len);
  2012. if (unlikely(!ret))
  2013. quithere(1, "Failed to malloc");
  2014. sprintf(ret, "%s%s", ptr, s);
  2015. free(ptr);
  2016. return ret;
  2017. }
  2018. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  2019. * Including 0x00 at the end
  2020. * You must free the result yourself */
  2021. void *str_text(char *ptr)
  2022. {
  2023. unsigned char *uptr;
  2024. char *ret, *txt;
  2025. if (ptr == NULL) {
  2026. ret = strdup("(null)");
  2027. if (unlikely(!ret))
  2028. quithere(1, "Failed to malloc null");
  2029. }
  2030. uptr = (unsigned char *)ptr;
  2031. ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed
  2032. if (unlikely(!txt))
  2033. quithere(1, "Failed to malloc txt");
  2034. do {
  2035. if (*uptr < ' ' || *uptr > '~') {
  2036. sprintf(txt, "0x%02x", *uptr);
  2037. txt += 4;
  2038. } else
  2039. *(txt++) = *uptr;
  2040. } while (*(uptr++));
  2041. *txt = '\0';
  2042. return ret;
  2043. }
  2044. void RenameThread(const char* name)
  2045. {
  2046. #if defined(PR_SET_NAME)
  2047. // Only the first 15 characters are used (16 - NUL terminator)
  2048. prctl(PR_SET_NAME, name, 0, 0, 0);
  2049. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2050. pthread_set_name_np(pthread_self(), name);
  2051. #elif defined(MAC_OSX)
  2052. pthread_setname_np(name);
  2053. #else
  2054. // Prevent warnings for unused parameters...
  2055. (void)name;
  2056. #endif
  2057. }
  2058. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  2059. * that support them and for apple which does not. We use a single byte across
  2060. * a pipe to emulate semaphore behaviour there. */
  2061. #ifdef __APPLE__
  2062. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2063. {
  2064. int flags, fd, i;
  2065. if (pipe(cgsem->pipefd) == -1)
  2066. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  2067. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  2068. * execv on restart. */
  2069. for (i = 0; i < 2; i++) {
  2070. fd = cgsem->pipefd[i];
  2071. flags = fcntl(fd, F_GETFD, 0);
  2072. flags |= FD_CLOEXEC;
  2073. if (fcntl(fd, F_SETFD, flags) == -1)
  2074. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  2075. }
  2076. }
  2077. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2078. {
  2079. const char buf = 1;
  2080. int ret;
  2081. ret = write(cgsem->pipefd[1], &buf, 1);
  2082. if (unlikely(ret == 0))
  2083. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  2084. }
  2085. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2086. {
  2087. char buf;
  2088. int ret;
  2089. ret = read(cgsem->pipefd[0], &buf, 1);
  2090. if (unlikely(ret == 0))
  2091. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  2092. }
  2093. void cgsem_destroy(cgsem_t *cgsem)
  2094. {
  2095. close(cgsem->pipefd[1]);
  2096. close(cgsem->pipefd[0]);
  2097. }
  2098. /* This is similar to sem_timedwait but takes a millisecond value */
  2099. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2100. {
  2101. struct timeval timeout;
  2102. int ret, fd;
  2103. fd_set rd;
  2104. char buf;
  2105. fd = cgsem->pipefd[0];
  2106. FD_ZERO(&rd);
  2107. FD_SET(fd, &rd);
  2108. ms_to_timeval(&timeout, ms);
  2109. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  2110. if (ret > 0) {
  2111. ret = read(fd, &buf, 1);
  2112. return 0;
  2113. }
  2114. if (likely(!ret))
  2115. return ETIMEDOUT;
  2116. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2117. /* We don't reach here */
  2118. return 0;
  2119. }
  2120. #else
  2121. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2122. {
  2123. int ret;
  2124. if ((ret = sem_init(cgsem, 0, 0)))
  2125. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  2126. }
  2127. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2128. {
  2129. if (unlikely(sem_post(cgsem)))
  2130. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  2131. }
  2132. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2133. {
  2134. if (unlikely(sem_wait(cgsem)))
  2135. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  2136. }
  2137. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2138. {
  2139. struct timespec abs_timeout, ts_now;
  2140. struct timeval tv_now;
  2141. int ret;
  2142. cgtime(&tv_now);
  2143. timeval_to_spec(&ts_now, &tv_now);
  2144. ms_to_timespec(&abs_timeout, ms);
  2145. timeraddspec(&abs_timeout, &ts_now);
  2146. ret = sem_timedwait(cgsem, &abs_timeout);
  2147. if (ret) {
  2148. if (likely(sock_timeout()))
  2149. return ETIMEDOUT;
  2150. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2151. }
  2152. return 0;
  2153. }
  2154. void cgsem_destroy(cgsem_t *cgsem)
  2155. {
  2156. sem_destroy(cgsem);
  2157. }
  2158. #endif
  2159. /* Provide a completion_timeout helper function for unreliable functions that
  2160. * may die due to driver issues etc that time out if the function fails and
  2161. * can then reliably return. */
  2162. struct cg_completion {
  2163. cgsem_t cgsem;
  2164. void (*fn)(void *fnarg);
  2165. void *fnarg;
  2166. };
  2167. void *completion_thread(void *arg)
  2168. {
  2169. struct cg_completion *cgc = (struct cg_completion *)arg;
  2170. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2171. cgc->fn(cgc->fnarg);
  2172. cgsem_post(&cgc->cgsem);
  2173. return NULL;
  2174. }
  2175. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  2176. {
  2177. struct cg_completion *cgc;
  2178. pthread_t pthread;
  2179. bool ret = false;
  2180. cgc = malloc(sizeof(struct cg_completion));
  2181. if (unlikely(!cgc))
  2182. return ret;
  2183. cgsem_init(&cgc->cgsem);
  2184. cgc->fn = fn;
  2185. cgc->fnarg = fnarg;
  2186. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  2187. ret = cgsem_mswait(&cgc->cgsem, timeout);
  2188. if (!ret) {
  2189. pthread_join(pthread, NULL);
  2190. free(cgc);
  2191. } else
  2192. pthread_cancel(pthread);
  2193. return !ret;
  2194. }