util.c 64 KB

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