util.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610
  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. static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  500. for (i = 0; i < (int)len; i++) {
  501. *s++ = hex[p[i] >> 4];
  502. *s++ = hex[p[i] & 0xF];
  503. }
  504. *s++ = '\0';
  505. }
  506. /* Returns a malloced array string of a binary value of arbitrary length. The
  507. * array is rounded up to a 4 byte size to appease architectures that need
  508. * aligned array sizes */
  509. char *bin2hex(const unsigned char *p, size_t len)
  510. {
  511. ssize_t slen;
  512. char *s;
  513. slen = len * 2 + 1;
  514. if (slen % 4)
  515. slen += 4 - (slen % 4);
  516. s = calloc(slen, 1);
  517. if (unlikely(!s))
  518. quithere(1, "Failed to calloc");
  519. __bin2hex(s, p, len);
  520. return s;
  521. }
  522. /* Does the reverse of bin2hex but does not allocate any ram */
  523. static const int hex2bin_tbl[256] = {
  524. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  525. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  526. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  527. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  528. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  529. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  530. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  531. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  532. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  533. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  534. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  535. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  536. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  537. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  538. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  539. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  540. };
  541. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  542. {
  543. int nibble1, nibble2;
  544. unsigned char idx;
  545. bool ret = false;
  546. while (*hexstr && len) {
  547. if (unlikely(!hexstr[1])) {
  548. applog(LOG_ERR, "hex2bin str truncated");
  549. return ret;
  550. }
  551. idx = *hexstr++;
  552. nibble1 = hex2bin_tbl[idx];
  553. idx = *hexstr++;
  554. nibble2 = hex2bin_tbl[idx];
  555. if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
  556. applog(LOG_ERR, "hex2bin scan failed");
  557. return ret;
  558. }
  559. *p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
  560. --len;
  561. }
  562. if (likely(len == 0 && *hexstr == 0))
  563. ret = true;
  564. return ret;
  565. }
  566. bool fulltest(const unsigned char *hash, const unsigned char *target)
  567. {
  568. unsigned char hash_swap[32], target_swap[32];
  569. uint32_t *hash32 = (uint32_t *) hash_swap;
  570. uint32_t *target32 = (uint32_t *) target_swap;
  571. char *hash_str, *target_str;
  572. bool rc = true;
  573. int i;
  574. swap256(hash_swap, hash);
  575. swap256(target_swap, target);
  576. for (i = 0; i < 32/4; i++) {
  577. uint32_t h32tmp = htobe32(hash32[i]);
  578. uint32_t t32tmp = htole32(target32[i]);
  579. target32[i] = swab32(target32[i]); /* for printing */
  580. if (h32tmp > t32tmp) {
  581. rc = false;
  582. break;
  583. }
  584. if (h32tmp < t32tmp) {
  585. rc = true;
  586. break;
  587. }
  588. }
  589. if (opt_debug) {
  590. hash_str = bin2hex(hash_swap, 32);
  591. target_str = bin2hex(target_swap, 32);
  592. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  593. hash_str,
  594. target_str,
  595. rc ? "YES (hash <= target)" :
  596. "no (false positive; hash > target)");
  597. free(hash_str);
  598. free(target_str);
  599. }
  600. return rc;
  601. }
  602. struct thread_q *tq_new(void)
  603. {
  604. struct thread_q *tq;
  605. tq = calloc(1, sizeof(*tq));
  606. if (!tq)
  607. return NULL;
  608. INIT_LIST_HEAD(&tq->q);
  609. pthread_mutex_init(&tq->mutex, NULL);
  610. pthread_cond_init(&tq->cond, NULL);
  611. return tq;
  612. }
  613. void tq_free(struct thread_q *tq)
  614. {
  615. struct tq_ent *ent, *iter;
  616. if (!tq)
  617. return;
  618. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  619. list_del(&ent->q_node);
  620. free(ent);
  621. }
  622. pthread_cond_destroy(&tq->cond);
  623. pthread_mutex_destroy(&tq->mutex);
  624. memset(tq, 0, sizeof(*tq)); /* poison */
  625. free(tq);
  626. }
  627. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  628. {
  629. mutex_lock(&tq->mutex);
  630. tq->frozen = frozen;
  631. pthread_cond_signal(&tq->cond);
  632. mutex_unlock(&tq->mutex);
  633. }
  634. void tq_freeze(struct thread_q *tq)
  635. {
  636. tq_freezethaw(tq, true);
  637. }
  638. void tq_thaw(struct thread_q *tq)
  639. {
  640. tq_freezethaw(tq, false);
  641. }
  642. bool tq_push(struct thread_q *tq, void *data)
  643. {
  644. struct tq_ent *ent;
  645. bool rc = true;
  646. ent = calloc(1, sizeof(*ent));
  647. if (!ent)
  648. return false;
  649. ent->data = data;
  650. INIT_LIST_HEAD(&ent->q_node);
  651. mutex_lock(&tq->mutex);
  652. if (!tq->frozen) {
  653. list_add_tail(&ent->q_node, &tq->q);
  654. } else {
  655. free(ent);
  656. rc = false;
  657. }
  658. pthread_cond_signal(&tq->cond);
  659. mutex_unlock(&tq->mutex);
  660. return rc;
  661. }
  662. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  663. {
  664. struct tq_ent *ent;
  665. void *rval = NULL;
  666. int rc;
  667. mutex_lock(&tq->mutex);
  668. if (!list_empty(&tq->q))
  669. goto pop;
  670. if (abstime)
  671. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  672. else
  673. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  674. if (rc)
  675. goto out;
  676. if (list_empty(&tq->q))
  677. goto out;
  678. pop:
  679. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  680. rval = ent->data;
  681. list_del(&ent->q_node);
  682. free(ent);
  683. out:
  684. mutex_unlock(&tq->mutex);
  685. return rval;
  686. }
  687. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  688. {
  689. cgsem_init(&thr->sem);
  690. return pthread_create(&thr->pth, attr, start, arg);
  691. }
  692. void thr_info_cancel(struct thr_info *thr)
  693. {
  694. if (!thr)
  695. return;
  696. if (PTH(thr) != 0L) {
  697. pthread_cancel(thr->pth);
  698. PTH(thr) = 0L;
  699. }
  700. cgsem_destroy(&thr->sem);
  701. }
  702. void subtime(struct timeval *a, struct timeval *b)
  703. {
  704. timersub(a, b, b);
  705. }
  706. void addtime(struct timeval *a, struct timeval *b)
  707. {
  708. timeradd(a, b, b);
  709. }
  710. bool time_more(struct timeval *a, struct timeval *b)
  711. {
  712. return timercmp(a, b, >);
  713. }
  714. bool time_less(struct timeval *a, struct timeval *b)
  715. {
  716. return timercmp(a, b, <);
  717. }
  718. void copy_time(struct timeval *dest, const struct timeval *src)
  719. {
  720. memcpy(dest, src, sizeof(struct timeval));
  721. }
  722. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  723. {
  724. val->tv_sec = spec->tv_sec;
  725. val->tv_usec = spec->tv_nsec / 1000;
  726. }
  727. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  728. {
  729. spec->tv_sec = val->tv_sec;
  730. spec->tv_nsec = val->tv_usec * 1000;
  731. }
  732. void us_to_timeval(struct timeval *val, int64_t us)
  733. {
  734. lldiv_t tvdiv = lldiv(us, 1000000);
  735. val->tv_sec = tvdiv.quot;
  736. val->tv_usec = tvdiv.rem;
  737. }
  738. void us_to_timespec(struct timespec *spec, int64_t us)
  739. {
  740. lldiv_t tvdiv = lldiv(us, 1000000);
  741. spec->tv_sec = tvdiv.quot;
  742. spec->tv_nsec = tvdiv.rem * 1000;
  743. }
  744. void ms_to_timespec(struct timespec *spec, int64_t ms)
  745. {
  746. lldiv_t tvdiv = lldiv(ms, 1000);
  747. spec->tv_sec = tvdiv.quot;
  748. spec->tv_nsec = tvdiv.rem * 1000000;
  749. }
  750. void ms_to_timeval(struct timeval *val, int64_t ms)
  751. {
  752. lldiv_t tvdiv = lldiv(ms, 1000);
  753. val->tv_sec = tvdiv.quot;
  754. val->tv_usec = tvdiv.rem * 1000;
  755. }
  756. void timeraddspec(struct timespec *a, const struct timespec *b)
  757. {
  758. a->tv_sec += b->tv_sec;
  759. a->tv_nsec += b->tv_nsec;
  760. if (a->tv_nsec >= 1000000000) {
  761. a->tv_nsec -= 1000000000;
  762. a->tv_sec++;
  763. }
  764. }
  765. static int __maybe_unused timespec_to_ms(struct timespec *ts)
  766. {
  767. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  768. }
  769. /* Subtract b from a */
  770. static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
  771. {
  772. a->tv_sec -= b->tv_sec;
  773. a->tv_nsec -= b->tv_nsec;
  774. if (a->tv_nsec < 0) {
  775. a->tv_nsec += 1000000000;
  776. a->tv_sec--;
  777. }
  778. }
  779. /* These are cgminer specific sleep functions that use an absolute nanosecond
  780. * resolution timer to avoid poor usleep accuracy and overruns. */
  781. #ifdef WIN32
  782. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  783. #define EPOCHFILETIME (116444736000000000LL)
  784. /* Return the system time as an lldiv_t in decimicroseconds. */
  785. static void decius_time(lldiv_t *lidiv)
  786. {
  787. FILETIME ft;
  788. LARGE_INTEGER li;
  789. GetSystemTimeAsFileTime(&ft);
  790. li.LowPart = ft.dwLowDateTime;
  791. li.HighPart = ft.dwHighDateTime;
  792. li.QuadPart -= EPOCHFILETIME;
  793. /* SystemTime is in decimicroseconds so divide by an unusual number */
  794. *lidiv = lldiv(li.QuadPart, 10000000);
  795. }
  796. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  797. * with tz set to NULL, and windows' default resolution is only 15ms, this
  798. * gives us higher resolution times on windows. */
  799. void cgtime(struct timeval *tv)
  800. {
  801. lldiv_t lidiv;
  802. decius_time(&lidiv);
  803. tv->tv_sec = lidiv.quot;
  804. tv->tv_usec = lidiv.rem / 10;
  805. }
  806. #else /* WIN32 */
  807. void cgtime(struct timeval *tv)
  808. {
  809. gettimeofday(tv, NULL);
  810. }
  811. int cgtimer_to_ms(cgtimer_t *cgt)
  812. {
  813. return timespec_to_ms(cgt);
  814. }
  815. /* Subtracts b from a and stores it in res. */
  816. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  817. {
  818. res->tv_sec = a->tv_sec - b->tv_sec;
  819. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  820. if (res->tv_nsec < 0) {
  821. res->tv_nsec += 1000000000;
  822. res->tv_sec--;
  823. }
  824. }
  825. #endif /* WIN32 */
  826. #ifdef CLOCK_MONOTONIC /* Essentially just linux */
  827. void cgtimer_time(cgtimer_t *ts_start)
  828. {
  829. clock_gettime(CLOCK_MONOTONIC, ts_start);
  830. }
  831. static void nanosleep_abstime(struct timespec *ts_end)
  832. {
  833. int ret;
  834. do {
  835. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  836. } while (ret == EINTR);
  837. }
  838. /* Reentrant version of cgsleep functions allow start time to be set separately
  839. * from the beginning of the actual sleep, allowing scheduling delays to be
  840. * counted in the sleep. */
  841. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  842. {
  843. struct timespec ts_end;
  844. ms_to_timespec(&ts_end, ms);
  845. timeraddspec(&ts_end, ts_start);
  846. nanosleep_abstime(&ts_end);
  847. }
  848. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  849. {
  850. struct timespec ts_end;
  851. us_to_timespec(&ts_end, us);
  852. timeraddspec(&ts_end, ts_start);
  853. nanosleep_abstime(&ts_end);
  854. }
  855. #else /* CLOCK_MONOTONIC */
  856. #ifdef __MACH__
  857. #include <mach/clock.h>
  858. #include <mach/mach.h>
  859. void cgtimer_time(cgtimer_t *ts_start)
  860. {
  861. clock_serv_t cclock;
  862. mach_timespec_t mts;
  863. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  864. clock_get_time(cclock, &mts);
  865. mach_port_deallocate(mach_task_self(), cclock);
  866. ts_start->tv_sec = mts.tv_sec;
  867. ts_start->tv_nsec = mts.tv_nsec;
  868. }
  869. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  870. void cgtimer_time(cgtimer_t *ts_start)
  871. {
  872. struct timeval tv;
  873. cgtime(&tv);
  874. ts_start->tv_sec = tv->tv_sec;
  875. ts_start->tv_nsec = tv->tv_usec * 1000;
  876. }
  877. #endif /* __MACH__ */
  878. #ifdef WIN32
  879. /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
  880. * typedef, allowing us to have sub-microsecond resolution for times, do simple
  881. * arithmetic for timer calculations, and use windows' own hTimers to get
  882. * accurate absolute timeouts. */
  883. int cgtimer_to_ms(cgtimer_t *cgt)
  884. {
  885. return (int)(cgt->QuadPart / 10000LL);
  886. }
  887. /* Subtracts b from a and stores it in res. */
  888. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  889. {
  890. res->QuadPart = a->QuadPart - b->QuadPart;
  891. }
  892. /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
  893. * timeouts with hTimers. */
  894. void cgtimer_time(cgtimer_t *ts_start)
  895. {
  896. FILETIME ft;
  897. GetSystemTimeAsFileTime(&ft);
  898. ts_start->LowPart = ft.dwLowDateTime;
  899. ts_start->HighPart = ft.dwHighDateTime;
  900. }
  901. static void liSleep(LARGE_INTEGER *li, int timeout)
  902. {
  903. HANDLE hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  904. DWORD ret;
  905. if (unlikely(!hTimer))
  906. quit(1, "Failed to create hTimer in liSleep");
  907. ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
  908. if (unlikely(!ret))
  909. quit(1, "Failed to SetWaitableTimer in liSleep");
  910. /* We still use a timeout as a sanity check in case the system time
  911. * is changed while we're running */
  912. ret = WaitForSingleObject(hTimer, timeout);
  913. if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
  914. quit(1, "Failed to WaitForSingleObject in liSleep");
  915. CloseHandle(hTimer);
  916. }
  917. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  918. {
  919. LARGE_INTEGER li;
  920. li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
  921. liSleep(&li, ms);
  922. }
  923. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  924. {
  925. LARGE_INTEGER li;
  926. int ms;
  927. li.QuadPart = ts_start->QuadPart + us * 10LL;
  928. ms = us / 1000;
  929. if (!ms)
  930. ms = 1;
  931. liSleep(&li, ms);
  932. }
  933. #else /* WIN32 */
  934. static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  935. {
  936. struct timespec now;
  937. timeraddspec(ts_diff, ts_start);
  938. cgtimer_time(&now);
  939. timersubspec(ts_diff, &now);
  940. if (unlikely(ts_diff->tv_sec < 0))
  941. return;
  942. nanosleep(ts_diff, NULL);
  943. }
  944. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  945. {
  946. struct timespec ts_diff;
  947. ms_to_timespec(&ts_diff, ms);
  948. cgsleep_spec(&ts_diff, ts_start);
  949. }
  950. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  951. {
  952. struct timespec ts_diff;
  953. us_to_timespec(&ts_diff, us);
  954. cgsleep_spec(&ts_diff, ts_start);
  955. }
  956. #endif /* WIN32 */
  957. #endif /* CLOCK_MONOTONIC */
  958. void cgsleep_ms(int ms)
  959. {
  960. cgtimer_t ts_start;
  961. cgsleep_prepare_r(&ts_start);
  962. cgsleep_ms_r(&ts_start, ms);
  963. }
  964. void cgsleep_us(int64_t us)
  965. {
  966. cgtimer_t ts_start;
  967. cgsleep_prepare_r(&ts_start);
  968. cgsleep_us_r(&ts_start, us);
  969. }
  970. /* Returns the microseconds difference between end and start times as a double */
  971. double us_tdiff(struct timeval *end, struct timeval *start)
  972. {
  973. /* Sanity check. We should only be using this for small differences so
  974. * limit the max to 60 seconds. */
  975. if (unlikely(end->tv_sec - start->tv_sec > 60))
  976. return 60000000;
  977. return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
  978. }
  979. /* Returns the milliseconds difference between end and start times */
  980. int ms_tdiff(struct timeval *end, struct timeval *start)
  981. {
  982. /* Like us_tdiff, limit to 1 hour. */
  983. if (unlikely(end->tv_sec - start->tv_sec > 3600))
  984. return 3600000;
  985. return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
  986. }
  987. /* Returns the seconds difference between end and start times as a double */
  988. double tdiff(struct timeval *end, struct timeval *start)
  989. {
  990. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  991. }
  992. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  993. {
  994. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  995. char url_address[256], port[6];
  996. int url_len, port_len = 0;
  997. *sockaddr_url = url;
  998. url_begin = strstr(url, "//");
  999. if (!url_begin)
  1000. url_begin = url;
  1001. else
  1002. url_begin += 2;
  1003. /* Look for numeric ipv6 entries */
  1004. ipv6_begin = strstr(url_begin, "[");
  1005. ipv6_end = strstr(url_begin, "]");
  1006. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1007. url_end = strstr(ipv6_end, ":");
  1008. else
  1009. url_end = strstr(url_begin, ":");
  1010. if (url_end) {
  1011. url_len = url_end - url_begin;
  1012. port_len = strlen(url_begin) - url_len - 1;
  1013. if (port_len < 1)
  1014. return false;
  1015. port_start = url_end + 1;
  1016. } else
  1017. url_len = strlen(url_begin);
  1018. if (url_len < 1)
  1019. return false;
  1020. sprintf(url_address, "%.*s", url_len, url_begin);
  1021. if (port_len) {
  1022. char *slash;
  1023. snprintf(port, 6, "%.*s", port_len, port_start);
  1024. slash = strchr(port, '/');
  1025. if (slash)
  1026. *slash = '\0';
  1027. } else
  1028. strcpy(port, "80");
  1029. *sockaddr_port = strdup(port);
  1030. *sockaddr_url = strdup(url_address);
  1031. return true;
  1032. }
  1033. enum send_ret {
  1034. SEND_OK,
  1035. SEND_SELECTFAIL,
  1036. SEND_SENDFAIL,
  1037. SEND_INACTIVE
  1038. };
  1039. /* Send a single command across a socket, appending \n to it. This should all
  1040. * be done under stratum lock except when first establishing the socket */
  1041. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1042. {
  1043. SOCKETTYPE sock = pool->sock;
  1044. ssize_t ssent = 0;
  1045. strcat(s, "\n");
  1046. len++;
  1047. while (len > 0 ) {
  1048. struct timeval timeout = {1, 0};
  1049. ssize_t sent;
  1050. fd_set wd;
  1051. FD_ZERO(&wd);
  1052. FD_SET(sock, &wd);
  1053. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  1054. return SEND_SELECTFAIL;
  1055. #ifdef __APPLE__
  1056. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1057. #elif WIN32
  1058. sent = send(pool->sock, s + ssent, len, 0);
  1059. #else
  1060. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1061. #endif
  1062. if (sent < 0) {
  1063. if (!sock_blocks())
  1064. return SEND_SENDFAIL;
  1065. sent = 0;
  1066. }
  1067. ssent += sent;
  1068. len -= sent;
  1069. }
  1070. pool->cgminer_pool_stats.times_sent++;
  1071. pool->cgminer_pool_stats.bytes_sent += ssent;
  1072. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1073. return SEND_OK;
  1074. }
  1075. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1076. {
  1077. enum send_ret ret = SEND_INACTIVE;
  1078. if (opt_protocol)
  1079. applog(LOG_DEBUG, "SEND: %s", s);
  1080. mutex_lock(&pool->stratum_lock);
  1081. if (pool->stratum_active)
  1082. ret = __stratum_send(pool, s, len);
  1083. mutex_unlock(&pool->stratum_lock);
  1084. /* This is to avoid doing applog under stratum_lock */
  1085. switch (ret) {
  1086. default:
  1087. case SEND_OK:
  1088. break;
  1089. case SEND_SELECTFAIL:
  1090. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1091. suspend_stratum(pool);
  1092. break;
  1093. case SEND_SENDFAIL:
  1094. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1095. suspend_stratum(pool);
  1096. break;
  1097. case SEND_INACTIVE:
  1098. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1099. break;
  1100. }
  1101. return (ret == SEND_OK);
  1102. }
  1103. static bool socket_full(struct pool *pool, int wait)
  1104. {
  1105. SOCKETTYPE sock = pool->sock;
  1106. struct timeval timeout;
  1107. fd_set rd;
  1108. if (unlikely(wait < 0))
  1109. wait = 0;
  1110. FD_ZERO(&rd);
  1111. FD_SET(sock, &rd);
  1112. timeout.tv_usec = 0;
  1113. timeout.tv_sec = wait;
  1114. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1115. return true;
  1116. return false;
  1117. }
  1118. /* Check to see if Santa's been good to you */
  1119. bool sock_full(struct pool *pool)
  1120. {
  1121. if (strlen(pool->sockbuf))
  1122. return true;
  1123. return (socket_full(pool, 0));
  1124. }
  1125. static void clear_sockbuf(struct pool *pool)
  1126. {
  1127. strcpy(pool->sockbuf, "");
  1128. }
  1129. static void clear_sock(struct pool *pool)
  1130. {
  1131. ssize_t n;
  1132. mutex_lock(&pool->stratum_lock);
  1133. do {
  1134. if (pool->sock)
  1135. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1136. else
  1137. n = 0;
  1138. } while (n > 0);
  1139. mutex_unlock(&pool->stratum_lock);
  1140. clear_sockbuf(pool);
  1141. }
  1142. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1143. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1144. * and zeroing the new memory */
  1145. static void recalloc_sock(struct pool *pool, size_t len)
  1146. {
  1147. size_t old, new;
  1148. old = strlen(pool->sockbuf);
  1149. new = old + len + 1;
  1150. if (new < pool->sockbuf_size)
  1151. return;
  1152. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1153. // Avoid potentially recursive locking
  1154. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1155. pool->sockbuf = realloc(pool->sockbuf, new);
  1156. if (!pool->sockbuf)
  1157. quithere(1, "Failed to realloc pool sockbuf");
  1158. memset(pool->sockbuf + old, 0, new - old);
  1159. pool->sockbuf_size = new;
  1160. }
  1161. /* Peeks at a socket to find the first end of line and then reads just that
  1162. * from the socket and returns that as a malloced char */
  1163. char *recv_line(struct pool *pool)
  1164. {
  1165. char *tok, *sret = NULL;
  1166. ssize_t len, buflen;
  1167. int waited = 0;
  1168. if (!strstr(pool->sockbuf, "\n")) {
  1169. struct timeval rstart, now;
  1170. cgtime(&rstart);
  1171. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1172. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1173. goto out;
  1174. }
  1175. do {
  1176. char s[RBUFSIZE];
  1177. size_t slen;
  1178. ssize_t n;
  1179. memset(s, 0, RBUFSIZE);
  1180. n = recv(pool->sock, s, RECVSIZE, 0);
  1181. if (!n) {
  1182. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1183. suspend_stratum(pool);
  1184. break;
  1185. }
  1186. cgtime(&now);
  1187. waited = tdiff(&now, &rstart);
  1188. if (n < 0) {
  1189. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1190. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1191. suspend_stratum(pool);
  1192. break;
  1193. }
  1194. } else {
  1195. slen = strlen(s);
  1196. recalloc_sock(pool, slen);
  1197. strcat(pool->sockbuf, s);
  1198. }
  1199. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1200. }
  1201. buflen = strlen(pool->sockbuf);
  1202. tok = strtok(pool->sockbuf, "\n");
  1203. if (!tok) {
  1204. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1205. goto out;
  1206. }
  1207. sret = strdup(tok);
  1208. len = strlen(sret);
  1209. /* Copy what's left in the buffer after the \n, including the
  1210. * terminating \0 */
  1211. if (buflen > len + 1)
  1212. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1213. else
  1214. strcpy(pool->sockbuf, "");
  1215. pool->cgminer_pool_stats.times_received++;
  1216. pool->cgminer_pool_stats.bytes_received += len;
  1217. pool->cgminer_pool_stats.net_bytes_received += len;
  1218. out:
  1219. if (!sret)
  1220. clear_sock(pool);
  1221. else if (opt_protocol)
  1222. applog(LOG_DEBUG, "RECVD: %s", sret);
  1223. return sret;
  1224. }
  1225. /* Extracts a string value from a json array with error checking. To be used
  1226. * when the value of the string returned is only examined and not to be stored.
  1227. * See json_array_string below */
  1228. static char *__json_array_string(json_t *val, unsigned int entry)
  1229. {
  1230. json_t *arr_entry;
  1231. if (json_is_null(val))
  1232. return NULL;
  1233. if (!json_is_array(val))
  1234. return NULL;
  1235. if (entry > json_array_size(val))
  1236. return NULL;
  1237. arr_entry = json_array_get(val, entry);
  1238. if (!json_is_string(arr_entry))
  1239. return NULL;
  1240. return (char *)json_string_value(arr_entry);
  1241. }
  1242. /* Creates a freshly malloced dup of __json_array_string */
  1243. static char *json_array_string(json_t *val, unsigned int entry)
  1244. {
  1245. char *buf = __json_array_string(val, entry);
  1246. if (buf)
  1247. return strdup(buf);
  1248. return NULL;
  1249. }
  1250. static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
  1251. static bool parse_notify(struct pool *pool, json_t *val)
  1252. {
  1253. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1254. *ntime, *header;
  1255. size_t cb1_len, cb2_len, alloc_len;
  1256. unsigned char *cb1, *cb2;
  1257. bool clean, ret = false;
  1258. int merkles, i;
  1259. json_t *arr;
  1260. arr = json_array_get(val, 4);
  1261. if (!arr || !json_is_array(arr))
  1262. goto out;
  1263. merkles = json_array_size(arr);
  1264. job_id = json_array_string(val, 0);
  1265. prev_hash = json_array_string(val, 1);
  1266. coinbase1 = json_array_string(val, 2);
  1267. coinbase2 = json_array_string(val, 3);
  1268. bbversion = json_array_string(val, 5);
  1269. nbit = json_array_string(val, 6);
  1270. ntime = json_array_string(val, 7);
  1271. clean = json_is_true(json_array_get(val, 8));
  1272. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1273. /* Annoying but we must not leak memory */
  1274. if (job_id)
  1275. free(job_id);
  1276. if (prev_hash)
  1277. free(prev_hash);
  1278. if (coinbase1)
  1279. free(coinbase1);
  1280. if (coinbase2)
  1281. free(coinbase2);
  1282. if (bbversion)
  1283. free(bbversion);
  1284. if (nbit)
  1285. free(nbit);
  1286. if (ntime)
  1287. free(ntime);
  1288. goto out;
  1289. }
  1290. cg_wlock(&pool->data_lock);
  1291. free(pool->swork.job_id);
  1292. free(pool->swork.prev_hash);
  1293. free(pool->swork.bbversion);
  1294. free(pool->swork.nbit);
  1295. free(pool->swork.ntime);
  1296. pool->swork.job_id = job_id;
  1297. pool->swork.prev_hash = prev_hash;
  1298. cb1_len = strlen(coinbase1) / 2;
  1299. cb2_len = strlen(coinbase2) / 2;
  1300. pool->swork.bbversion = bbversion;
  1301. pool->swork.nbit = nbit;
  1302. pool->swork.ntime = ntime;
  1303. pool->swork.clean = clean;
  1304. alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  1305. pool->nonce2_offset = cb1_len + pool->n1_len;
  1306. for (i = 0; i < pool->swork.merkles; i++)
  1307. free(pool->swork.merkle_bin[i]);
  1308. if (merkles) {
  1309. pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
  1310. sizeof(char *) * merkles + 1);
  1311. for (i = 0; i < merkles; i++) {
  1312. char *merkle = json_array_string(arr, i);
  1313. pool->swork.merkle_bin[i] = malloc(32);
  1314. if (unlikely(!pool->swork.merkle_bin[i]))
  1315. quit(1, "Failed to malloc pool swork merkle_bin");
  1316. hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  1317. free(merkle);
  1318. }
  1319. }
  1320. pool->swork.merkles = merkles;
  1321. if (clean)
  1322. pool->nonce2 = 0;
  1323. pool->merkle_offset = strlen(pool->swork.bbversion) +
  1324. strlen(pool->swork.prev_hash);
  1325. pool->swork.header_len = pool->merkle_offset +
  1326. /* merkle_hash */ 32 +
  1327. strlen(pool->swork.ntime) +
  1328. strlen(pool->swork.nbit) +
  1329. /* nonce */ 8 +
  1330. /* workpadding */ 96;
  1331. pool->merkle_offset /= 2;
  1332. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1333. align_len(&pool->swork.header_len);
  1334. header = alloca(pool->swork.header_len);
  1335. snprintf(header, pool->swork.header_len,
  1336. "%s%s%s%s%s%s%s",
  1337. pool->swork.bbversion,
  1338. pool->swork.prev_hash,
  1339. blank_merkel,
  1340. pool->swork.ntime,
  1341. pool->swork.nbit,
  1342. "00000000", /* nonce */
  1343. workpadding);
  1344. if (unlikely(!hex2bin(pool->header_bin, header, 128)))
  1345. quit(1, "Failed to convert header to header_bin in parse_notify");
  1346. cb1 = calloc(cb1_len, 1);
  1347. if (unlikely(!cb1))
  1348. quithere(1, "Failed to calloc cb1 in parse_notify");
  1349. hex2bin(cb1, coinbase1, cb1_len);
  1350. cb2 = calloc(cb2_len, 1);
  1351. if (unlikely(!cb2))
  1352. quithere(1, "Failed to calloc cb2 in parse_notify");
  1353. hex2bin(cb2, coinbase2, cb2_len);
  1354. free(pool->coinbase);
  1355. align_len(&alloc_len);
  1356. pool->coinbase = calloc(alloc_len, 1);
  1357. if (unlikely(!pool->coinbase))
  1358. quit(1, "Failed to calloc pool coinbase in parse_notify");
  1359. memcpy(pool->coinbase, cb1, cb1_len);
  1360. memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  1361. memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  1362. cg_wunlock(&pool->data_lock);
  1363. if (opt_protocol) {
  1364. applog(LOG_DEBUG, "job_id: %s", job_id);
  1365. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1366. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1367. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1368. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1369. applog(LOG_DEBUG, "nbit: %s", nbit);
  1370. applog(LOG_DEBUG, "ntime: %s", ntime);
  1371. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1372. }
  1373. free(coinbase1);
  1374. free(coinbase2);
  1375. free(cb1);
  1376. free(cb2);
  1377. /* A notify message is the closest stratum gets to a getwork */
  1378. pool->getwork_requested++;
  1379. total_getworks++;
  1380. ret = true;
  1381. if (pool == current_pool())
  1382. opt_work_update = true;
  1383. out:
  1384. return ret;
  1385. }
  1386. static bool parse_diff(struct pool *pool, json_t *val)
  1387. {
  1388. double old_diff, diff;
  1389. diff = json_number_value(json_array_get(val, 0));
  1390. if (diff == 0)
  1391. return false;
  1392. cg_wlock(&pool->data_lock);
  1393. old_diff = pool->swork.diff;
  1394. pool->swork.diff = diff;
  1395. cg_wunlock(&pool->data_lock);
  1396. if (old_diff != diff) {
  1397. int idiff = diff;
  1398. if ((double)idiff == diff)
  1399. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  1400. pool->pool_no, idiff);
  1401. else
  1402. applog(LOG_NOTICE, "Pool %d difficulty changed to %f",
  1403. pool->pool_no, diff);
  1404. } else
  1405. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  1406. diff);
  1407. return true;
  1408. }
  1409. static bool parse_reconnect(struct pool *pool, json_t *val)
  1410. {
  1411. char *url, *port, address[256];
  1412. memset(address, 0, 255);
  1413. url = (char *)json_string_value(json_array_get(val, 0));
  1414. if (!url)
  1415. url = pool->sockaddr_url;
  1416. port = (char *)json_string_value(json_array_get(val, 1));
  1417. if (!port)
  1418. port = pool->stratum_port;
  1419. sprintf(address, "%s:%s", url, port);
  1420. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  1421. return false;
  1422. pool->stratum_url = pool->sockaddr_url;
  1423. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1424. if (!restart_stratum(pool))
  1425. return false;
  1426. return true;
  1427. }
  1428. static bool send_version(struct pool *pool, json_t *val)
  1429. {
  1430. char s[RBUFSIZE];
  1431. int id = json_integer_value(json_object_get(val, "id"));
  1432. if (!id)
  1433. return false;
  1434. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1435. if (!stratum_send(pool, s, strlen(s)))
  1436. return false;
  1437. return true;
  1438. }
  1439. static bool show_message(struct pool *pool, json_t *val)
  1440. {
  1441. char *msg;
  1442. if (!json_is_array(val))
  1443. return false;
  1444. msg = (char *)json_string_value(json_array_get(val, 0));
  1445. if (!msg)
  1446. return false;
  1447. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  1448. return true;
  1449. }
  1450. bool parse_method(struct pool *pool, char *s)
  1451. {
  1452. json_t *val = NULL, *method, *err_val, *params;
  1453. json_error_t err;
  1454. bool ret = false;
  1455. char *buf;
  1456. if (!s)
  1457. return ret;
  1458. val = JSON_LOADS(s, &err);
  1459. if (!val) {
  1460. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1461. return ret;
  1462. }
  1463. method = json_object_get(val, "method");
  1464. if (!method)
  1465. return ret;
  1466. err_val = json_object_get(val, "error");
  1467. params = json_object_get(val, "params");
  1468. if (err_val && !json_is_null(err_val)) {
  1469. char *ss;
  1470. if (err_val)
  1471. ss = json_dumps(err_val, JSON_INDENT(3));
  1472. else
  1473. ss = strdup("(unknown reason)");
  1474. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1475. free(ss);
  1476. return ret;
  1477. }
  1478. buf = (char *)json_string_value(method);
  1479. if (!buf)
  1480. return ret;
  1481. if (!strncasecmp(buf, "mining.notify", 13)) {
  1482. if (parse_notify(pool, params))
  1483. pool->stratum_notify = ret = true;
  1484. else
  1485. pool->stratum_notify = ret = false;
  1486. return ret;
  1487. }
  1488. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1489. ret = true;
  1490. return ret;
  1491. }
  1492. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1493. ret = true;
  1494. return ret;
  1495. }
  1496. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1497. ret = true;
  1498. return ret;
  1499. }
  1500. if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
  1501. ret = true;
  1502. return ret;
  1503. }
  1504. return ret;
  1505. }
  1506. bool auth_stratum(struct pool *pool)
  1507. {
  1508. json_t *val = NULL, *res_val, *err_val;
  1509. char s[RBUFSIZE], *sret = NULL;
  1510. json_error_t err;
  1511. bool ret = false;
  1512. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1513. swork_id++, pool->rpc_user, pool->rpc_pass);
  1514. if (!stratum_send(pool, s, strlen(s)))
  1515. return ret;
  1516. /* Parse all data in the queue and anything left should be auth */
  1517. while (42) {
  1518. sret = recv_line(pool);
  1519. if (!sret)
  1520. return ret;
  1521. if (parse_method(pool, sret))
  1522. free(sret);
  1523. else
  1524. break;
  1525. }
  1526. val = JSON_LOADS(sret, &err);
  1527. free(sret);
  1528. res_val = json_object_get(val, "result");
  1529. err_val = json_object_get(val, "error");
  1530. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1531. char *ss;
  1532. if (err_val)
  1533. ss = json_dumps(err_val, JSON_INDENT(3));
  1534. else
  1535. ss = strdup("(unknown reason)");
  1536. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1537. free(ss);
  1538. return ret;
  1539. }
  1540. ret = true;
  1541. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1542. pool->probed = true;
  1543. successful_connect = true;
  1544. return ret;
  1545. }
  1546. static int recv_byte(int sockd)
  1547. {
  1548. char c;
  1549. if (recv(sockd, &c, 1, 0) != -1)
  1550. return c;
  1551. return -1;
  1552. }
  1553. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  1554. {
  1555. char buf[1024];
  1556. int i, len;
  1557. if (http0) {
  1558. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  1559. pool->sockaddr_url, pool->stratum_port);
  1560. } else {
  1561. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  1562. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  1563. pool->stratum_port);
  1564. }
  1565. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  1566. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1567. send(sockd, buf, strlen(buf), 0);
  1568. len = recv(sockd, buf, 12, 0);
  1569. if (len <= 0) {
  1570. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  1571. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1572. return false;
  1573. }
  1574. buf[len] = '\0';
  1575. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  1576. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1577. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  1578. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  1579. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1580. return false;
  1581. }
  1582. /* Ignore unwanted headers till we get desired response */
  1583. for (i = 0; i < 4; i++) {
  1584. buf[i] = recv_byte(sockd);
  1585. if (buf[i] == (char)-1) {
  1586. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  1587. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1588. return false;
  1589. }
  1590. }
  1591. while (strncmp(buf, "\r\n\r\n", 4)) {
  1592. for (i = 0; i < 3; i++)
  1593. buf[i] = buf[i + 1];
  1594. buf[3] = recv_byte(sockd);
  1595. if (buf[3] == (char)-1) {
  1596. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  1597. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1598. return false;
  1599. }
  1600. }
  1601. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  1602. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1603. return true;
  1604. }
  1605. static bool socks5_negotiate(struct pool *pool, int sockd)
  1606. {
  1607. unsigned char atyp, uclen;
  1608. unsigned short port;
  1609. char buf[515];
  1610. int i, len;
  1611. buf[0] = 0x05;
  1612. buf[1] = 0x01;
  1613. buf[2] = 0x00;
  1614. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  1615. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1616. send(sockd, buf, 3, 0);
  1617. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  1618. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1619. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1620. return false;
  1621. }
  1622. buf[0] = 0x05;
  1623. buf[1] = 0x01;
  1624. buf[2] = 0x00;
  1625. buf[3] = 0x03;
  1626. len = (strlen(pool->sockaddr_url));
  1627. if (len > 255)
  1628. len = 255;
  1629. uclen = len;
  1630. buf[4] = (uclen & 0xff);
  1631. memcpy(buf + 5, pool->sockaddr_url, len);
  1632. port = atoi(pool->stratum_port);
  1633. buf[5 + len] = (port >> 8);
  1634. buf[6 + len] = (port & 0xff);
  1635. send(sockd, buf, (7 + len), 0);
  1636. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  1637. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1638. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1639. return false;
  1640. }
  1641. recv_byte(sockd);
  1642. atyp = recv_byte(sockd);
  1643. if (atyp == 0x01) {
  1644. for (i = 0; i < 4; i++)
  1645. recv_byte(sockd);
  1646. } else if (atyp == 0x03) {
  1647. len = recv_byte(sockd);
  1648. for (i = 0; i < len; i++)
  1649. recv_byte(sockd);
  1650. } else {
  1651. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1652. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1653. return false;
  1654. }
  1655. for (i = 0; i < 2; i++)
  1656. recv_byte(sockd);
  1657. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  1658. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1659. return true;
  1660. }
  1661. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  1662. {
  1663. unsigned short port;
  1664. in_addr_t inp;
  1665. char buf[515];
  1666. int i, len;
  1667. buf[0] = 0x04;
  1668. buf[1] = 0x01;
  1669. port = atoi(pool->stratum_port);
  1670. buf[2] = port >> 8;
  1671. buf[3] = port & 0xff;
  1672. sprintf(&buf[8], "CGMINER");
  1673. /* See if we've been given an IP address directly to avoid needing to
  1674. * resolve it. */
  1675. inp = inet_addr(pool->sockaddr_url);
  1676. inp = ntohl(inp);
  1677. if ((int)inp != -1)
  1678. socks4a = false;
  1679. else {
  1680. /* Try to extract the IP address ourselves first */
  1681. struct addrinfo servinfobase, *servinfo, hints;
  1682. servinfo = &servinfobase;
  1683. memset(&hints, 0, sizeof(struct addrinfo));
  1684. hints.ai_family = AF_INET; /* IPV4 only */
  1685. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  1686. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  1687. inp = ntohl(saddr_in->sin_addr.s_addr);
  1688. socks4a = false;
  1689. freeaddrinfo(servinfo);
  1690. }
  1691. }
  1692. if (!socks4a) {
  1693. if ((int)inp == -1) {
  1694. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  1695. pool->sockaddr_url);
  1696. return false;
  1697. }
  1698. buf[4] = (inp >> 24) & 0xFF;
  1699. buf[5] = (inp >> 16) & 0xFF;
  1700. buf[6] = (inp >> 8) & 0xFF;
  1701. buf[7] = (inp >> 0) & 0xFF;
  1702. send(sockd, buf, 16, 0);
  1703. } else {
  1704. /* This appears to not be working but hopefully most will be
  1705. * able to resolve IP addresses themselves. */
  1706. buf[4] = 0;
  1707. buf[5] = 0;
  1708. buf[6] = 0;
  1709. buf[7] = 1;
  1710. len = strlen(pool->sockaddr_url);
  1711. if (len > 255)
  1712. len = 255;
  1713. memcpy(&buf[16], pool->sockaddr_url, len);
  1714. len += 16;
  1715. buf[len++] = '\0';
  1716. send(sockd, buf, len, 0);
  1717. }
  1718. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  1719. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  1720. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1721. return false;
  1722. }
  1723. for (i = 0; i < 6; i++)
  1724. recv_byte(sockd);
  1725. return true;
  1726. }
  1727. static bool setup_stratum_socket(struct pool *pool)
  1728. {
  1729. struct addrinfo servinfobase, *servinfo, *hints, *p;
  1730. char *sockaddr_url, *sockaddr_port;
  1731. int sockd;
  1732. mutex_lock(&pool->stratum_lock);
  1733. pool->stratum_active = false;
  1734. if (pool->sock)
  1735. CLOSESOCKET(pool->sock);
  1736. pool->sock = 0;
  1737. mutex_unlock(&pool->stratum_lock);
  1738. hints = &pool->stratum_hints;
  1739. memset(hints, 0, sizeof(struct addrinfo));
  1740. hints->ai_family = AF_UNSPEC;
  1741. hints->ai_socktype = SOCK_STREAM;
  1742. servinfo = &servinfobase;
  1743. if (!pool->rpc_proxy && opt_socks_proxy) {
  1744. pool->rpc_proxy = opt_socks_proxy;
  1745. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  1746. pool->rpc_proxytype = PROXY_SOCKS5;
  1747. }
  1748. if (pool->rpc_proxy) {
  1749. sockaddr_url = pool->sockaddr_proxy_url;
  1750. sockaddr_port = pool->sockaddr_proxy_port;
  1751. } else {
  1752. sockaddr_url = pool->sockaddr_url;
  1753. sockaddr_port = pool->stratum_port;
  1754. }
  1755. if (getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo) != 0) {
  1756. if (!pool->probed) {
  1757. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  1758. sockaddr_url, sockaddr_port);
  1759. pool->probed = true;
  1760. } else {
  1761. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  1762. sockaddr_url, sockaddr_port);
  1763. }
  1764. return false;
  1765. }
  1766. for (p = servinfo; p != NULL; p = p->ai_next) {
  1767. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  1768. if (sockd == -1) {
  1769. applog(LOG_DEBUG, "Failed socket");
  1770. continue;
  1771. }
  1772. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  1773. CLOSESOCKET(sockd);
  1774. applog(LOG_DEBUG, "Failed connect");
  1775. continue;
  1776. }
  1777. break;
  1778. }
  1779. if (p == NULL) {
  1780. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  1781. sockaddr_url, sockaddr_port);
  1782. freeaddrinfo(servinfo);
  1783. return false;
  1784. }
  1785. freeaddrinfo(servinfo);
  1786. if (pool->rpc_proxy) {
  1787. switch (pool->rpc_proxytype) {
  1788. case PROXY_HTTP_1_0:
  1789. if (!http_negotiate(pool, sockd, true))
  1790. return false;
  1791. break;
  1792. case PROXY_HTTP:
  1793. if (!http_negotiate(pool, sockd, false))
  1794. return false;
  1795. break;
  1796. case PROXY_SOCKS5:
  1797. case PROXY_SOCKS5H:
  1798. if (!socks5_negotiate(pool, sockd))
  1799. return false;
  1800. break;
  1801. case PROXY_SOCKS4:
  1802. if (!socks4_negotiate(pool, sockd, false))
  1803. return false;
  1804. break;
  1805. case PROXY_SOCKS4A:
  1806. if (!socks4_negotiate(pool, sockd, true))
  1807. return false;
  1808. break;
  1809. default:
  1810. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  1811. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1812. return false;
  1813. break;
  1814. }
  1815. }
  1816. if (!pool->sockbuf) {
  1817. pool->sockbuf = calloc(RBUFSIZE, 1);
  1818. if (!pool->sockbuf)
  1819. quithere(1, "Failed to calloc pool sockbuf");
  1820. pool->sockbuf_size = RBUFSIZE;
  1821. }
  1822. pool->sock = sockd;
  1823. keep_sockalive(sockd);
  1824. return true;
  1825. }
  1826. static char *get_sessionid(json_t *val)
  1827. {
  1828. char *ret = NULL;
  1829. json_t *arr_val;
  1830. int arrsize, i;
  1831. arr_val = json_array_get(val, 0);
  1832. if (!arr_val || !json_is_array(arr_val))
  1833. goto out;
  1834. arrsize = json_array_size(arr_val);
  1835. for (i = 0; i < arrsize; i++) {
  1836. json_t *arr = json_array_get(arr_val, i);
  1837. char *notify;
  1838. if (!arr | !json_is_array(arr))
  1839. break;
  1840. notify = __json_array_string(arr, 0);
  1841. if (!notify)
  1842. continue;
  1843. if (!strncasecmp(notify, "mining.notify", 13)) {
  1844. ret = json_array_string(arr, 1);
  1845. break;
  1846. }
  1847. }
  1848. out:
  1849. return ret;
  1850. }
  1851. void suspend_stratum(struct pool *pool)
  1852. {
  1853. clear_sockbuf(pool);
  1854. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1855. mutex_lock(&pool->stratum_lock);
  1856. pool->stratum_active = pool->stratum_notify = false;
  1857. if (pool->sock)
  1858. CLOSESOCKET(pool->sock);
  1859. pool->sock = 0;
  1860. mutex_unlock(&pool->stratum_lock);
  1861. }
  1862. bool initiate_stratum(struct pool *pool)
  1863. {
  1864. bool ret = false, recvd = false, noresume = false, sockd = false;
  1865. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1866. json_t *val = NULL, *res_val, *err_val;
  1867. json_error_t err;
  1868. int n2size;
  1869. resend:
  1870. if (!setup_stratum_socket(pool)) {
  1871. sockd = false;
  1872. goto out;
  1873. }
  1874. sockd = true;
  1875. if (recvd) {
  1876. /* Get rid of any crap lying around if we're resending */
  1877. clear_sock(pool);
  1878. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1879. } else {
  1880. if (pool->sessionid)
  1881. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1882. else
  1883. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1884. }
  1885. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1886. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1887. goto out;
  1888. }
  1889. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1890. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1891. goto out;
  1892. }
  1893. sret = recv_line(pool);
  1894. if (!sret)
  1895. goto out;
  1896. recvd = true;
  1897. val = JSON_LOADS(sret, &err);
  1898. free(sret);
  1899. if (!val) {
  1900. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1901. goto out;
  1902. }
  1903. res_val = json_object_get(val, "result");
  1904. err_val = json_object_get(val, "error");
  1905. if (!res_val || json_is_null(res_val) ||
  1906. (err_val && !json_is_null(err_val))) {
  1907. char *ss;
  1908. if (err_val)
  1909. ss = json_dumps(err_val, JSON_INDENT(3));
  1910. else
  1911. ss = strdup("(unknown reason)");
  1912. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1913. free(ss);
  1914. goto out;
  1915. }
  1916. sessionid = get_sessionid(res_val);
  1917. if (!sessionid)
  1918. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1919. nonce1 = json_array_string(res_val, 1);
  1920. if (!nonce1) {
  1921. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1922. free(sessionid);
  1923. goto out;
  1924. }
  1925. n2size = json_integer_value(json_array_get(res_val, 2));
  1926. if (!n2size) {
  1927. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1928. free(sessionid);
  1929. free(nonce1);
  1930. goto out;
  1931. }
  1932. cg_wlock(&pool->data_lock);
  1933. pool->sessionid = sessionid;
  1934. pool->nonce1 = nonce1;
  1935. pool->n1_len = strlen(nonce1) / 2;
  1936. free(pool->nonce1bin);
  1937. pool->nonce1bin = calloc(pool->n1_len, 1);
  1938. if (unlikely(!pool->nonce1bin))
  1939. quithere(1, "Failed to calloc pool->nonce1bin");
  1940. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  1941. pool->n2size = n2size;
  1942. cg_wunlock(&pool->data_lock);
  1943. if (sessionid)
  1944. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1945. ret = true;
  1946. out:
  1947. if (ret) {
  1948. if (!pool->stratum_url)
  1949. pool->stratum_url = pool->sockaddr_url;
  1950. pool->stratum_active = true;
  1951. pool->swork.diff = 1;
  1952. if (opt_protocol) {
  1953. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1954. pool->pool_no, pool->nonce1, pool->n2size);
  1955. }
  1956. } else {
  1957. if (recvd && !noresume) {
  1958. /* Reset the sessionid used for stratum resuming in case the pool
  1959. * does not support it, or does not know how to respond to the
  1960. * presence of the sessionid parameter. */
  1961. cg_wlock(&pool->data_lock);
  1962. free(pool->sessionid);
  1963. free(pool->nonce1);
  1964. pool->sessionid = pool->nonce1 = NULL;
  1965. cg_wunlock(&pool->data_lock);
  1966. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1967. noresume = true;
  1968. goto resend;
  1969. }
  1970. applog(LOG_DEBUG, "Initiate stratum failed");
  1971. if (sockd)
  1972. suspend_stratum(pool);
  1973. }
  1974. return ret;
  1975. }
  1976. bool restart_stratum(struct pool *pool)
  1977. {
  1978. if (pool->stratum_active)
  1979. suspend_stratum(pool);
  1980. if (!initiate_stratum(pool))
  1981. return false;
  1982. if (!auth_stratum(pool))
  1983. return false;
  1984. return true;
  1985. }
  1986. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1987. {
  1988. dev->device_last_not_well = time(NULL);
  1989. dev->device_not_well_reason = reason;
  1990. switch (reason) {
  1991. case REASON_THREAD_FAIL_INIT:
  1992. dev->thread_fail_init_count++;
  1993. break;
  1994. case REASON_THREAD_ZERO_HASH:
  1995. dev->thread_zero_hash_count++;
  1996. break;
  1997. case REASON_THREAD_FAIL_QUEUE:
  1998. dev->thread_fail_queue_count++;
  1999. break;
  2000. case REASON_DEV_SICK_IDLE_60:
  2001. dev->dev_sick_idle_60_count++;
  2002. break;
  2003. case REASON_DEV_DEAD_IDLE_600:
  2004. dev->dev_dead_idle_600_count++;
  2005. break;
  2006. case REASON_DEV_NOSTART:
  2007. dev->dev_nostart_count++;
  2008. break;
  2009. case REASON_DEV_OVER_HEAT:
  2010. dev->dev_over_heat_count++;
  2011. break;
  2012. case REASON_DEV_THERMAL_CUTOFF:
  2013. dev->dev_thermal_cutoff_count++;
  2014. break;
  2015. case REASON_DEV_COMMS_ERROR:
  2016. dev->dev_comms_error_count++;
  2017. break;
  2018. case REASON_DEV_THROTTLE:
  2019. dev->dev_throttle_count++;
  2020. break;
  2021. }
  2022. }
  2023. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2024. void *realloc_strcat(char *ptr, char *s)
  2025. {
  2026. size_t old = strlen(ptr), len = strlen(s);
  2027. char *ret;
  2028. if (!len)
  2029. return ptr;
  2030. len += old + 1;
  2031. align_len(&len);
  2032. ret = malloc(len);
  2033. if (unlikely(!ret))
  2034. quithere(1, "Failed to malloc");
  2035. sprintf(ret, "%s%s", ptr, s);
  2036. free(ptr);
  2037. return ret;
  2038. }
  2039. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  2040. * Including 0x00 at the end
  2041. * You must free the result yourself */
  2042. void *str_text(char *ptr)
  2043. {
  2044. unsigned char *uptr;
  2045. char *ret, *txt;
  2046. if (ptr == NULL) {
  2047. ret = strdup("(null)");
  2048. if (unlikely(!ret))
  2049. quithere(1, "Failed to malloc null");
  2050. }
  2051. uptr = (unsigned char *)ptr;
  2052. ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed
  2053. if (unlikely(!txt))
  2054. quithere(1, "Failed to malloc txt");
  2055. do {
  2056. if (*uptr < ' ' || *uptr > '~') {
  2057. sprintf(txt, "0x%02x", *uptr);
  2058. txt += 4;
  2059. } else
  2060. *(txt++) = *uptr;
  2061. } while (*(uptr++));
  2062. *txt = '\0';
  2063. return ret;
  2064. }
  2065. void RenameThread(const char* name)
  2066. {
  2067. #if defined(PR_SET_NAME)
  2068. // Only the first 15 characters are used (16 - NUL terminator)
  2069. prctl(PR_SET_NAME, name, 0, 0, 0);
  2070. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2071. pthread_set_name_np(pthread_self(), name);
  2072. #elif defined(MAC_OSX)
  2073. pthread_setname_np(name);
  2074. #else
  2075. // Prevent warnings for unused parameters...
  2076. (void)name;
  2077. #endif
  2078. }
  2079. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  2080. * that support them and for apple which does not. We use a single byte across
  2081. * a pipe to emulate semaphore behaviour there. */
  2082. #ifdef __APPLE__
  2083. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2084. {
  2085. int flags, fd, i;
  2086. if (pipe(cgsem->pipefd) == -1)
  2087. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  2088. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  2089. * execv on restart. */
  2090. for (i = 0; i < 2; i++) {
  2091. fd = cgsem->pipefd[i];
  2092. flags = fcntl(fd, F_GETFD, 0);
  2093. flags |= FD_CLOEXEC;
  2094. if (fcntl(fd, F_SETFD, flags) == -1)
  2095. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  2096. }
  2097. }
  2098. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2099. {
  2100. const char buf = 1;
  2101. int ret;
  2102. ret = write(cgsem->pipefd[1], &buf, 1);
  2103. if (unlikely(ret == 0))
  2104. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  2105. }
  2106. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2107. {
  2108. char buf;
  2109. int ret;
  2110. ret = read(cgsem->pipefd[0], &buf, 1);
  2111. if (unlikely(ret == 0))
  2112. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  2113. }
  2114. void cgsem_destroy(cgsem_t *cgsem)
  2115. {
  2116. close(cgsem->pipefd[1]);
  2117. close(cgsem->pipefd[0]);
  2118. }
  2119. /* This is similar to sem_timedwait but takes a millisecond value */
  2120. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2121. {
  2122. struct timeval timeout;
  2123. int ret, fd;
  2124. fd_set rd;
  2125. char buf;
  2126. fd = cgsem->pipefd[0];
  2127. FD_ZERO(&rd);
  2128. FD_SET(fd, &rd);
  2129. ms_to_timeval(&timeout, ms);
  2130. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  2131. if (ret > 0) {
  2132. ret = read(fd, &buf, 1);
  2133. return 0;
  2134. }
  2135. if (likely(!ret))
  2136. return ETIMEDOUT;
  2137. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2138. /* We don't reach here */
  2139. return 0;
  2140. }
  2141. #else
  2142. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2143. {
  2144. int ret;
  2145. if ((ret = sem_init(cgsem, 0, 0)))
  2146. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  2147. }
  2148. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2149. {
  2150. if (unlikely(sem_post(cgsem)))
  2151. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  2152. }
  2153. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2154. {
  2155. if (unlikely(sem_wait(cgsem)))
  2156. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  2157. }
  2158. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2159. {
  2160. struct timespec abs_timeout, ts_now;
  2161. struct timeval tv_now;
  2162. int ret;
  2163. cgtime(&tv_now);
  2164. timeval_to_spec(&ts_now, &tv_now);
  2165. ms_to_timespec(&abs_timeout, ms);
  2166. timeraddspec(&abs_timeout, &ts_now);
  2167. ret = sem_timedwait(cgsem, &abs_timeout);
  2168. if (ret) {
  2169. if (likely(sock_timeout()))
  2170. return ETIMEDOUT;
  2171. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2172. }
  2173. return 0;
  2174. }
  2175. void cgsem_destroy(cgsem_t *cgsem)
  2176. {
  2177. sem_destroy(cgsem);
  2178. }
  2179. #endif
  2180. /* Provide a completion_timeout helper function for unreliable functions that
  2181. * may die due to driver issues etc that time out if the function fails and
  2182. * can then reliably return. */
  2183. struct cg_completion {
  2184. cgsem_t cgsem;
  2185. void (*fn)(void *fnarg);
  2186. void *fnarg;
  2187. };
  2188. void *completion_thread(void *arg)
  2189. {
  2190. struct cg_completion *cgc = (struct cg_completion *)arg;
  2191. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2192. cgc->fn(cgc->fnarg);
  2193. cgsem_post(&cgc->cgsem);
  2194. return NULL;
  2195. }
  2196. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  2197. {
  2198. struct cg_completion *cgc;
  2199. pthread_t pthread;
  2200. bool ret = false;
  2201. cgc = malloc(sizeof(struct cg_completion));
  2202. if (unlikely(!cgc))
  2203. return ret;
  2204. cgsem_init(&cgc->cgsem);
  2205. cgc->fn = fn;
  2206. cgc->fnarg = fnarg;
  2207. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  2208. ret = cgsem_mswait(&cgc->cgsem, timeout);
  2209. if (!ret) {
  2210. pthread_join(pthread, NULL);
  2211. free(cgc);
  2212. } else
  2213. pthread_cancel(pthread);
  2214. return !ret;
  2215. }