util.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <ctype.h>
  14. #include <stdarg.h>
  15. #include <string.h>
  16. #include <jansson.h>
  17. #include <curl/curl.h>
  18. #include <time.h>
  19. #include <errno.h>
  20. #include <unistd.h>
  21. #include <sys/types.h>
  22. #ifndef WIN32
  23. #include <fcntl.h>
  24. # ifdef __linux
  25. # include <sys/prctl.h>
  26. # endif
  27. # include <sys/socket.h>
  28. # include <netinet/in.h>
  29. # include <netinet/tcp.h>
  30. # include <netdb.h>
  31. #else
  32. # include <windows.h>
  33. # include <winsock2.h>
  34. # include <ws2tcpip.h>
  35. # include <mmsystem.h>
  36. #endif
  37. #include "miner.h"
  38. #include "elist.h"
  39. #include "compat.h"
  40. #include "util.h"
  41. #define DEFAULT_SOCKWAIT 60
  42. bool successful_connect = false;
  43. struct timeval nettime;
  44. struct data_buffer {
  45. void *buf;
  46. size_t len;
  47. };
  48. struct upload_buffer {
  49. const void *buf;
  50. size_t len;
  51. };
  52. struct header_info {
  53. char *lp_path;
  54. int rolltime;
  55. char *reason;
  56. char *stratum_url;
  57. bool hadrolltime;
  58. bool canroll;
  59. bool hadexpire;
  60. };
  61. struct tq_ent {
  62. void *data;
  63. struct list_head q_node;
  64. };
  65. static void databuf_free(struct data_buffer *db)
  66. {
  67. if (!db)
  68. return;
  69. free(db->buf);
  70. memset(db, 0, sizeof(*db));
  71. }
  72. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  73. void *user_data)
  74. {
  75. struct data_buffer *db = user_data;
  76. size_t len = size * nmemb;
  77. size_t oldlen, newlen;
  78. void *newmem;
  79. static const unsigned char zero = 0;
  80. oldlen = db->len;
  81. newlen = oldlen + len;
  82. newmem = realloc(db->buf, newlen + 1);
  83. if (!newmem)
  84. return 0;
  85. db->buf = newmem;
  86. db->len = newlen;
  87. memcpy(db->buf + oldlen, ptr, len);
  88. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  89. return len;
  90. }
  91. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  92. void *user_data)
  93. {
  94. struct upload_buffer *ub = user_data;
  95. unsigned int len = size * nmemb;
  96. if (len > ub->len)
  97. len = ub->len;
  98. if (len) {
  99. memcpy(ptr, ub->buf, len);
  100. ub->buf += len;
  101. ub->len -= len;
  102. }
  103. return len;
  104. }
  105. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  106. {
  107. struct header_info *hi = user_data;
  108. size_t remlen, slen, ptrlen = size * nmemb;
  109. char *rem, *val = NULL, *key = NULL;
  110. void *tmp;
  111. val = calloc(1, ptrlen);
  112. key = calloc(1, ptrlen);
  113. if (!key || !val)
  114. goto out;
  115. tmp = memchr(ptr, ':', ptrlen);
  116. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  117. goto out;
  118. slen = tmp - ptr;
  119. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  120. goto out;
  121. memcpy(key, ptr, slen); /* store & nul term key */
  122. key[slen] = 0;
  123. rem = ptr + slen + 1; /* trim value's leading whitespace */
  124. remlen = ptrlen - slen - 1;
  125. while ((remlen > 0) && (isspace(*rem))) {
  126. remlen--;
  127. rem++;
  128. }
  129. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  130. val[remlen] = 0;
  131. while ((*val) && (isspace(val[strlen(val) - 1])))
  132. val[strlen(val) - 1] = 0;
  133. if (!*val) /* skip blank value */
  134. goto out;
  135. if (opt_protocol)
  136. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  137. if (!strcasecmp("X-Roll-Ntime", key)) {
  138. hi->hadrolltime = true;
  139. if (!strncasecmp("N", val, 1))
  140. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  141. else {
  142. hi->canroll = true;
  143. /* Check to see if expire= is supported and if not, set
  144. * the rolltime to the default scantime */
  145. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  146. sscanf(val + 7, "%d", &hi->rolltime);
  147. hi->hadexpire = true;
  148. } else
  149. hi->rolltime = opt_scantime;
  150. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  151. }
  152. }
  153. if (!strcasecmp("X-Long-Polling", key)) {
  154. hi->lp_path = val; /* steal memory reference */
  155. val = NULL;
  156. }
  157. if (!strcasecmp("X-Reject-Reason", key)) {
  158. hi->reason = val; /* steal memory reference */
  159. val = NULL;
  160. }
  161. if (!strcasecmp("X-Stratum", key)) {
  162. hi->stratum_url = val;
  163. val = NULL;
  164. }
  165. out:
  166. free(key);
  167. free(val);
  168. return ptrlen;
  169. }
  170. static void keep_sockalive(SOCKETTYPE fd)
  171. {
  172. const int tcp_one = 1;
  173. #ifndef WIN32
  174. const int tcp_keepidle = 45;
  175. const int tcp_keepintvl = 30;
  176. int flags = fcntl(fd, F_GETFL, 0);
  177. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  178. #else
  179. u_long flags = 1;
  180. ioctlsocket(fd, FIONBIO, &flags);
  181. #endif
  182. setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const void *)&tcp_one, sizeof(tcp_one));
  183. if (!opt_delaynet)
  184. #ifndef __linux
  185. setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  186. #else /* __linux */
  187. setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  188. setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one));
  189. setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
  190. setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
  191. #endif /* __linux */
  192. #ifdef __APPLE_CC__
  193. setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
  194. #endif /* __APPLE_CC__ */
  195. }
  196. #if CURL_HAS_KEEPALIVE
  197. static void keep_curlalive(CURL *curl)
  198. {
  199. const int tcp_keepidle = 45;
  200. const int tcp_keepintvl = 30;
  201. const long int keepalive = 1;
  202. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
  203. curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, tcp_keepidle);
  204. curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, tcp_keepintvl);
  205. }
  206. #else
  207. static void keep_curlalive(CURL *curl)
  208. {
  209. SOCKETTYPE sock;
  210. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
  211. keep_sockalive(sock);
  212. }
  213. #endif
  214. static void last_nettime(struct timeval *last)
  215. {
  216. rd_lock(&netacc_lock);
  217. last->tv_sec = nettime.tv_sec;
  218. last->tv_usec = nettime.tv_usec;
  219. rd_unlock(&netacc_lock);
  220. }
  221. static void set_nettime(void)
  222. {
  223. wr_lock(&netacc_lock);
  224. cgtime(&nettime);
  225. wr_unlock(&netacc_lock);
  226. }
  227. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  228. __maybe_unused char *data, size_t size, void *userdata)
  229. {
  230. struct pool *pool = (struct pool *)userdata;
  231. switch(type) {
  232. case CURLINFO_HEADER_IN:
  233. case CURLINFO_DATA_IN:
  234. case CURLINFO_SSL_DATA_IN:
  235. pool->cgminer_pool_stats.net_bytes_received += size;
  236. break;
  237. case CURLINFO_HEADER_OUT:
  238. case CURLINFO_DATA_OUT:
  239. case CURLINFO_SSL_DATA_OUT:
  240. pool->cgminer_pool_stats.net_bytes_sent += size;
  241. break;
  242. case CURLINFO_TEXT:
  243. default:
  244. break;
  245. }
  246. return 0;
  247. }
  248. json_t *json_rpc_call(CURL *curl, const char *url,
  249. const char *userpass, const char *rpc_req,
  250. bool probe, bool longpoll, int *rolltime,
  251. struct pool *pool, bool share)
  252. {
  253. long timeout = longpoll ? (60 * 60) : 60;
  254. struct data_buffer all_data = {NULL, 0};
  255. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  256. char len_hdr[64], user_agent_hdr[128];
  257. char curl_err_str[CURL_ERROR_SIZE];
  258. struct curl_slist *headers = NULL;
  259. struct upload_buffer upload_data;
  260. json_t *val, *err_val, *res_val;
  261. bool probing = false;
  262. double byte_count;
  263. json_error_t err;
  264. int rc;
  265. memset(&err, 0, sizeof(err));
  266. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  267. if (probe)
  268. probing = !pool->probed;
  269. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  270. // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
  271. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  272. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  273. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  274. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  275. curl_easy_setopt(curl, CURLOPT_URL, url);
  276. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  277. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  278. /* Shares are staggered already and delays in submission can be costly
  279. * so do not delay them */
  280. if (!opt_delaynet || share)
  281. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  282. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  283. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  284. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  285. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  286. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  287. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  288. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  289. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  290. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  291. if (pool->rpc_proxy) {
  292. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  293. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  294. } else if (opt_socks_proxy) {
  295. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  296. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  297. }
  298. if (userpass) {
  299. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  300. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  301. }
  302. if (longpoll)
  303. keep_curlalive(curl);
  304. curl_easy_setopt(curl, CURLOPT_POST, 1);
  305. if (opt_protocol)
  306. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  307. upload_data.buf = rpc_req;
  308. upload_data.len = strlen(rpc_req);
  309. sprintf(len_hdr, "Content-Length: %lu",
  310. (unsigned long) upload_data.len);
  311. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  312. headers = curl_slist_append(headers,
  313. "Content-type: application/json");
  314. headers = curl_slist_append(headers,
  315. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  316. if (likely(global_hashrate)) {
  317. char ghashrate[255];
  318. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  319. headers = curl_slist_append(headers, ghashrate);
  320. }
  321. headers = curl_slist_append(headers, len_hdr);
  322. headers = curl_slist_append(headers, user_agent_hdr);
  323. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  324. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  325. if (opt_delaynet) {
  326. /* Don't delay share submission, but still track the nettime */
  327. if (!share) {
  328. long long now_msecs, last_msecs;
  329. struct timeval now, last;
  330. cgtime(&now);
  331. last_nettime(&last);
  332. now_msecs = (long long)now.tv_sec * 1000;
  333. now_msecs += now.tv_usec / 1000;
  334. last_msecs = (long long)last.tv_sec * 1000;
  335. last_msecs += last.tv_usec / 1000;
  336. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  337. struct timespec rgtp;
  338. rgtp.tv_sec = 0;
  339. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  340. nanosleep(&rgtp, NULL);
  341. }
  342. }
  343. set_nettime();
  344. }
  345. rc = curl_easy_perform(curl);
  346. if (rc) {
  347. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  348. goto err_out;
  349. }
  350. if (!all_data.buf) {
  351. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  352. goto err_out;
  353. }
  354. pool->cgminer_pool_stats.times_sent++;
  355. if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
  356. pool->cgminer_pool_stats.bytes_sent += byte_count;
  357. pool->cgminer_pool_stats.times_received++;
  358. if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
  359. pool->cgminer_pool_stats.bytes_received += byte_count;
  360. if (probing) {
  361. pool->probed = true;
  362. /* If X-Long-Polling was found, activate long polling */
  363. if (hi.lp_path) {
  364. if (pool->hdr_path != NULL)
  365. free(pool->hdr_path);
  366. pool->hdr_path = hi.lp_path;
  367. } else
  368. pool->hdr_path = NULL;
  369. if (hi.stratum_url) {
  370. pool->stratum_url = hi.stratum_url;
  371. hi.stratum_url = NULL;
  372. }
  373. } else {
  374. if (hi.lp_path) {
  375. free(hi.lp_path);
  376. hi.lp_path = NULL;
  377. }
  378. if (hi.stratum_url) {
  379. free(hi.stratum_url);
  380. hi.stratum_url = NULL;
  381. }
  382. }
  383. *rolltime = hi.rolltime;
  384. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  385. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  386. pool->cgminer_pool_stats.canroll = hi.canroll;
  387. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  388. val = JSON_LOADS(all_data.buf, &err);
  389. if (!val) {
  390. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  391. if (opt_protocol)
  392. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
  393. goto err_out;
  394. }
  395. if (opt_protocol) {
  396. char *s = json_dumps(val, JSON_INDENT(3));
  397. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  398. free(s);
  399. }
  400. /* JSON-RPC valid response returns a non-null 'result',
  401. * and a null 'error'.
  402. */
  403. res_val = json_object_get(val, "result");
  404. err_val = json_object_get(val, "error");
  405. if (!res_val ||(err_val && !json_is_null(err_val))) {
  406. char *s;
  407. if (err_val)
  408. s = json_dumps(err_val, JSON_INDENT(3));
  409. else
  410. s = strdup("(unknown reason)");
  411. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  412. free(s);
  413. goto err_out;
  414. }
  415. if (hi.reason) {
  416. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  417. free(hi.reason);
  418. hi.reason = NULL;
  419. }
  420. successful_connect = true;
  421. databuf_free(&all_data);
  422. curl_slist_free_all(headers);
  423. curl_easy_reset(curl);
  424. return val;
  425. err_out:
  426. databuf_free(&all_data);
  427. curl_slist_free_all(headers);
  428. curl_easy_reset(curl);
  429. if (!successful_connect)
  430. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  431. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  432. return NULL;
  433. }
  434. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  435. static struct {
  436. const char *name;
  437. curl_proxytype proxytype;
  438. } proxynames[] = {
  439. { "http:", CURLPROXY_HTTP },
  440. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  441. { "http0:", CURLPROXY_HTTP_1_0 },
  442. #endif
  443. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  444. { "socks4:", CURLPROXY_SOCKS4 },
  445. #endif
  446. { "socks5:", CURLPROXY_SOCKS5 },
  447. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  448. { "socks4a:", CURLPROXY_SOCKS4A },
  449. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  450. #endif
  451. { NULL, 0 }
  452. };
  453. #endif
  454. const char *proxytype(curl_proxytype proxytype)
  455. {
  456. int i;
  457. for (i = 0; proxynames[i].name; i++)
  458. if (proxynames[i].proxytype == proxytype)
  459. return proxynames[i].name;
  460. return "invalid";
  461. }
  462. char *get_proxy(char *url, struct pool *pool)
  463. {
  464. pool->rpc_proxy = NULL;
  465. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  466. char *split;
  467. int plen, len, i;
  468. for (i = 0; proxynames[i].name; i++) {
  469. plen = strlen(proxynames[i].name);
  470. if (strncmp(url, proxynames[i].name, plen) == 0) {
  471. if (!(split = strchr(url, '|')))
  472. return url;
  473. *split = '\0';
  474. len = split - url;
  475. pool->rpc_proxy = malloc(1 + len - plen);
  476. if (!(pool->rpc_proxy))
  477. quithere(1, "Failed to malloc rpc_proxy");
  478. strcpy(pool->rpc_proxy, url + plen);
  479. pool->rpc_proxytype = proxynames[i].proxytype;
  480. url = split + 1;
  481. break;
  482. }
  483. }
  484. #endif
  485. return url;
  486. }
  487. /* Returns a malloced array string of a binary value of arbitrary length. The
  488. * array is rounded up to a 4 byte size to appease architectures that need
  489. * aligned array sizes */
  490. char *bin2hex(const unsigned char *p, size_t len)
  491. {
  492. ssize_t slen;
  493. char *s;
  494. int i;
  495. slen = len * 2 + 1;
  496. if (slen % 4)
  497. slen += 4 - (slen % 4);
  498. s = calloc(slen, 1);
  499. if (unlikely(!s))
  500. quithere(1, "Failed to calloc");
  501. for (i = 0; i < (int)len; i++)
  502. sprintf(s + (i * 2), "%02x", (unsigned int)p[i]);
  503. return s;
  504. }
  505. /* Does the reverse of bin2hex but does not allocate any ram */
  506. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  507. {
  508. bool ret = false;
  509. while (*hexstr && len) {
  510. char hex_byte[4];
  511. unsigned int v;
  512. if (unlikely(!hexstr[1])) {
  513. applog(LOG_ERR, "hex2bin str truncated");
  514. return ret;
  515. }
  516. memset(hex_byte, 0, 4);
  517. hex_byte[0] = hexstr[0];
  518. hex_byte[1] = hexstr[1];
  519. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  520. applog(LOG_INFO, "hex2bin sscanf '%s' failed", hex_byte);
  521. return ret;
  522. }
  523. *p = (unsigned char) v;
  524. p++;
  525. hexstr += 2;
  526. len--;
  527. }
  528. if (likely(len == 0 && *hexstr == 0))
  529. ret = true;
  530. return ret;
  531. }
  532. bool fulltest(const unsigned char *hash, const unsigned char *target)
  533. {
  534. unsigned char hash_swap[32], target_swap[32];
  535. uint32_t *hash32 = (uint32_t *) hash_swap;
  536. uint32_t *target32 = (uint32_t *) target_swap;
  537. char *hash_str, *target_str;
  538. bool rc = true;
  539. int i;
  540. swap256(hash_swap, hash);
  541. swap256(target_swap, target);
  542. for (i = 0; i < 32/4; i++) {
  543. uint32_t h32tmp = htobe32(hash32[i]);
  544. uint32_t t32tmp = htole32(target32[i]);
  545. target32[i] = swab32(target32[i]); /* for printing */
  546. if (h32tmp > t32tmp) {
  547. rc = false;
  548. break;
  549. }
  550. if (h32tmp < t32tmp) {
  551. rc = true;
  552. break;
  553. }
  554. }
  555. if (opt_debug) {
  556. hash_str = bin2hex(hash_swap, 32);
  557. target_str = bin2hex(target_swap, 32);
  558. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  559. hash_str,
  560. target_str,
  561. rc ? "YES (hash <= target)" :
  562. "no (false positive; hash > target)");
  563. free(hash_str);
  564. free(target_str);
  565. }
  566. return rc;
  567. }
  568. struct thread_q *tq_new(void)
  569. {
  570. struct thread_q *tq;
  571. tq = calloc(1, sizeof(*tq));
  572. if (!tq)
  573. return NULL;
  574. INIT_LIST_HEAD(&tq->q);
  575. pthread_mutex_init(&tq->mutex, NULL);
  576. pthread_cond_init(&tq->cond, NULL);
  577. return tq;
  578. }
  579. void tq_free(struct thread_q *tq)
  580. {
  581. struct tq_ent *ent, *iter;
  582. if (!tq)
  583. return;
  584. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  585. list_del(&ent->q_node);
  586. free(ent);
  587. }
  588. pthread_cond_destroy(&tq->cond);
  589. pthread_mutex_destroy(&tq->mutex);
  590. memset(tq, 0, sizeof(*tq)); /* poison */
  591. free(tq);
  592. }
  593. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  594. {
  595. mutex_lock(&tq->mutex);
  596. tq->frozen = frozen;
  597. pthread_cond_signal(&tq->cond);
  598. mutex_unlock(&tq->mutex);
  599. }
  600. void tq_freeze(struct thread_q *tq)
  601. {
  602. tq_freezethaw(tq, true);
  603. }
  604. void tq_thaw(struct thread_q *tq)
  605. {
  606. tq_freezethaw(tq, false);
  607. }
  608. bool tq_push(struct thread_q *tq, void *data)
  609. {
  610. struct tq_ent *ent;
  611. bool rc = true;
  612. ent = calloc(1, sizeof(*ent));
  613. if (!ent)
  614. return false;
  615. ent->data = data;
  616. INIT_LIST_HEAD(&ent->q_node);
  617. mutex_lock(&tq->mutex);
  618. if (!tq->frozen) {
  619. list_add_tail(&ent->q_node, &tq->q);
  620. } else {
  621. free(ent);
  622. rc = false;
  623. }
  624. pthread_cond_signal(&tq->cond);
  625. mutex_unlock(&tq->mutex);
  626. return rc;
  627. }
  628. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  629. {
  630. struct tq_ent *ent;
  631. void *rval = NULL;
  632. int rc;
  633. mutex_lock(&tq->mutex);
  634. if (!list_empty(&tq->q))
  635. goto pop;
  636. if (abstime)
  637. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  638. else
  639. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  640. if (rc)
  641. goto out;
  642. if (list_empty(&tq->q))
  643. goto out;
  644. pop:
  645. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  646. rval = ent->data;
  647. list_del(&ent->q_node);
  648. free(ent);
  649. out:
  650. mutex_unlock(&tq->mutex);
  651. return rval;
  652. }
  653. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  654. {
  655. cgsem_init(&thr->sem);
  656. return pthread_create(&thr->pth, attr, start, arg);
  657. }
  658. void thr_info_cancel(struct thr_info *thr)
  659. {
  660. if (!thr)
  661. return;
  662. if (PTH(thr) != 0L) {
  663. pthread_cancel(thr->pth);
  664. PTH(thr) = 0L;
  665. }
  666. cgsem_destroy(&thr->sem);
  667. }
  668. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  669. * with tz set to NULL, and windows' default resolution is only 15ms, this
  670. * gives us higher resolution times on windows. */
  671. #ifndef WIN32
  672. void cgtime(struct timeval *tv)
  673. {
  674. gettimeofday(tv, NULL);
  675. }
  676. #else
  677. static void __cgtime(struct timeval *tv)
  678. {
  679. gettimeofday(tv, NULL);
  680. }
  681. void cgtime(struct timeval *tv)
  682. {
  683. timeBeginPeriod(1);
  684. __cgtime(tv);
  685. timeEndPeriod(1);
  686. }
  687. #endif
  688. void subtime(struct timeval *a, struct timeval *b)
  689. {
  690. timersub(a, b, b);
  691. }
  692. void addtime(struct timeval *a, struct timeval *b)
  693. {
  694. timeradd(a, b, b);
  695. }
  696. bool time_more(struct timeval *a, struct timeval *b)
  697. {
  698. return timercmp(a, b, >);
  699. }
  700. bool time_less(struct timeval *a, struct timeval *b)
  701. {
  702. return timercmp(a, b, <);
  703. }
  704. void copy_time(struct timeval *dest, const struct timeval *src)
  705. {
  706. memcpy(dest, src, sizeof(struct timeval));
  707. }
  708. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  709. {
  710. val->tv_sec = spec->tv_sec;
  711. val->tv_usec = spec->tv_nsec / 1000;
  712. }
  713. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  714. {
  715. spec->tv_sec = val->tv_sec;
  716. spec->tv_nsec = val->tv_usec * 1000;
  717. }
  718. void us_to_timeval(struct timeval *val, int64_t us)
  719. {
  720. lldiv_t tvdiv = lldiv(us, 1000000);
  721. val->tv_sec = tvdiv.quot;
  722. val->tv_usec = tvdiv.rem;
  723. }
  724. void us_to_timespec(struct timespec *spec, int64_t us)
  725. {
  726. lldiv_t tvdiv = lldiv(us, 1000000);
  727. spec->tv_sec = tvdiv.quot;
  728. spec->tv_nsec = tvdiv.rem * 1000;
  729. }
  730. void ms_to_timespec(struct timespec *spec, int64_t ms)
  731. {
  732. lldiv_t tvdiv = lldiv(ms, 1000);
  733. spec->tv_sec = tvdiv.quot;
  734. spec->tv_nsec = tvdiv.rem * 1000000;
  735. }
  736. void timeraddspec(struct timespec *a, const struct timespec *b)
  737. {
  738. a->tv_sec += b->tv_sec;
  739. a->tv_nsec += b->tv_nsec;
  740. if (a->tv_nsec >= 1000000000) {
  741. a->tv_nsec -= 1000000000;
  742. a->tv_sec++;
  743. }
  744. }
  745. /* These are cgminer specific sleep functions that use an absolute nanosecond
  746. * resolution timer to avoid poor usleep accuracy and overruns. */
  747. #ifndef WIN32
  748. void cgsleep_prepare_r(cgtimer_t *ts_start)
  749. {
  750. clock_gettime(CLOCK_MONOTONIC, ts_start);
  751. }
  752. static void nanosleep_abstime(struct timespec *ts_end)
  753. {
  754. int ret;
  755. do {
  756. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  757. } while (ret == EINTR);
  758. }
  759. /* Reentrant version of cgsleep functions allow start time to be set separately
  760. * from the beginning of the actual sleep, allowing scheduling delays to be
  761. * counted in the sleep. */
  762. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  763. {
  764. struct timespec ts_end;
  765. ms_to_timespec(&ts_end, ms);
  766. timeraddspec(&ts_end, ts_start);
  767. nanosleep_abstime(&ts_end);
  768. }
  769. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  770. {
  771. struct timespec ts_end;
  772. us_to_timespec(&ts_end, us);
  773. timeraddspec(&ts_end, ts_start);
  774. nanosleep_abstime(&ts_end);
  775. }
  776. #else
  777. void cgsleep_prepare_r(cgtimer_t *ts_start)
  778. {
  779. timeBeginPeriod(1);
  780. __cgtime(ts_start);
  781. }
  782. static void ms_to_timeval(struct timeval *val, int ms)
  783. {
  784. ldiv_t tvdiv = ldiv(ms, 1000);
  785. val->tv_sec = tvdiv.quot;
  786. val->tv_usec = tvdiv.rem * 1000;
  787. }
  788. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  789. {
  790. struct timeval now, tv_end, tv_diff;
  791. struct timespec ts_diff;
  792. ms_to_timeval(&tv_diff, ms);
  793. timeradd(ts_start, &tv_diff, &tv_end);
  794. __cgtime(&now);
  795. if (unlikely(time_more(&now, &tv_end)))
  796. goto out;
  797. timersub(&tv_end, &now, &tv_diff);
  798. timeval_to_spec(&ts_diff, &tv_diff);
  799. nanosleep(&ts_diff, NULL);
  800. out:
  801. timeEndPeriod(1);
  802. }
  803. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  804. {
  805. int ms = us / 1000;
  806. cgsleep_ms_r(ts_start, ms);
  807. }
  808. #endif
  809. void cgsleep_ms(int ms)
  810. {
  811. cgtimer_t ts_start;
  812. cgsleep_prepare_r(&ts_start);
  813. cgsleep_ms_r(&ts_start, ms);
  814. }
  815. void cgsleep_us(int64_t us)
  816. {
  817. cgtimer_t ts_start;
  818. cgsleep_prepare_r(&ts_start);
  819. cgsleep_us_r(&ts_start, us);
  820. }
  821. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  822. * on SMP machines */
  823. void nmsleep(unsigned int msecs)
  824. {
  825. cgsleep_ms((int)msecs);
  826. }
  827. /* Same for usecs */
  828. void nusleep(unsigned int usecs)
  829. {
  830. cgsleep_us((int64_t)usecs);
  831. }
  832. /* Returns the microseconds difference between end and start times as a double */
  833. double us_tdiff(struct timeval *end, struct timeval *start)
  834. {
  835. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  836. }
  837. /* Returns the seconds difference between end and start times as a double */
  838. double tdiff(struct timeval *end, struct timeval *start)
  839. {
  840. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  841. }
  842. bool extract_sockaddr(struct pool *pool, char *url)
  843. {
  844. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  845. char url_address[256], port[6];
  846. int url_len, port_len = 0;
  847. pool->sockaddr_url = url;
  848. url_begin = strstr(url, "//");
  849. if (!url_begin)
  850. url_begin = url;
  851. else
  852. url_begin += 2;
  853. /* Look for numeric ipv6 entries */
  854. ipv6_begin = strstr(url_begin, "[");
  855. ipv6_end = strstr(url_begin, "]");
  856. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  857. url_end = strstr(ipv6_end, ":");
  858. else
  859. url_end = strstr(url_begin, ":");
  860. if (url_end) {
  861. url_len = url_end - url_begin;
  862. port_len = strlen(url_begin) - url_len - 1;
  863. if (port_len < 1)
  864. return false;
  865. port_start = url_end + 1;
  866. } else
  867. url_len = strlen(url_begin);
  868. if (url_len < 1)
  869. return false;
  870. sprintf(url_address, "%.*s", url_len, url_begin);
  871. if (port_len)
  872. snprintf(port, 6, "%.*s", port_len, port_start);
  873. else
  874. strcpy(port, "80");
  875. pool->stratum_port = strdup(port);
  876. pool->sockaddr_url = strdup(url_address);
  877. return true;
  878. }
  879. enum send_ret {
  880. SEND_OK,
  881. SEND_SELECTFAIL,
  882. SEND_SENDFAIL,
  883. SEND_INACTIVE
  884. };
  885. /* Send a single command across a socket, appending \n to it. This should all
  886. * be done under stratum lock except when first establishing the socket */
  887. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  888. {
  889. SOCKETTYPE sock = pool->sock;
  890. ssize_t ssent = 0;
  891. strcat(s, "\n");
  892. len++;
  893. while (len > 0 ) {
  894. struct timeval timeout = {1, 0};
  895. ssize_t sent;
  896. fd_set wd;
  897. FD_ZERO(&wd);
  898. FD_SET(sock, &wd);
  899. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  900. return SEND_SELECTFAIL;
  901. #ifdef __APPLE__
  902. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  903. #elif WIN32
  904. sent = send(pool->sock, s + ssent, len, 0);
  905. #else
  906. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  907. #endif
  908. if (sent < 0) {
  909. if (!sock_blocks())
  910. return SEND_SENDFAIL;
  911. sent = 0;
  912. }
  913. ssent += sent;
  914. len -= sent;
  915. }
  916. pool->cgminer_pool_stats.times_sent++;
  917. pool->cgminer_pool_stats.bytes_sent += ssent;
  918. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  919. return SEND_OK;
  920. }
  921. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  922. {
  923. enum send_ret ret = SEND_INACTIVE;
  924. if (opt_protocol)
  925. applog(LOG_DEBUG, "SEND: %s", s);
  926. mutex_lock(&pool->stratum_lock);
  927. if (pool->stratum_active)
  928. ret = __stratum_send(pool, s, len);
  929. mutex_unlock(&pool->stratum_lock);
  930. /* This is to avoid doing applog under stratum_lock */
  931. switch (ret) {
  932. default:
  933. case SEND_OK:
  934. break;
  935. case SEND_SELECTFAIL:
  936. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  937. suspend_stratum(pool);
  938. break;
  939. case SEND_SENDFAIL:
  940. applog(LOG_DEBUG, "Failed to send in stratum_send");
  941. suspend_stratum(pool);
  942. break;
  943. case SEND_INACTIVE:
  944. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  945. break;
  946. }
  947. return (ret == SEND_OK);
  948. }
  949. static bool socket_full(struct pool *pool, int wait)
  950. {
  951. SOCKETTYPE sock = pool->sock;
  952. struct timeval timeout;
  953. fd_set rd;
  954. if (unlikely(wait < 0))
  955. wait = 0;
  956. FD_ZERO(&rd);
  957. FD_SET(sock, &rd);
  958. timeout.tv_usec = 0;
  959. timeout.tv_sec = wait;
  960. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  961. return true;
  962. return false;
  963. }
  964. /* Check to see if Santa's been good to you */
  965. bool sock_full(struct pool *pool)
  966. {
  967. if (strlen(pool->sockbuf))
  968. return true;
  969. return (socket_full(pool, 0));
  970. }
  971. static void clear_sockbuf(struct pool *pool)
  972. {
  973. strcpy(pool->sockbuf, "");
  974. }
  975. static void clear_sock(struct pool *pool)
  976. {
  977. ssize_t n;
  978. mutex_lock(&pool->stratum_lock);
  979. do {
  980. if (pool->sock)
  981. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  982. else
  983. n = 0;
  984. } while (n > 0);
  985. mutex_unlock(&pool->stratum_lock);
  986. clear_sockbuf(pool);
  987. }
  988. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  989. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  990. * and zeroing the new memory */
  991. static void recalloc_sock(struct pool *pool, size_t len)
  992. {
  993. size_t old, new;
  994. old = strlen(pool->sockbuf);
  995. new = old + len + 1;
  996. if (new < pool->sockbuf_size)
  997. return;
  998. new = new + (RBUFSIZE - (new % RBUFSIZE));
  999. // Avoid potentially recursive locking
  1000. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1001. pool->sockbuf = realloc(pool->sockbuf, new);
  1002. if (!pool->sockbuf)
  1003. quithere(1, "Failed to realloc pool sockbuf");
  1004. memset(pool->sockbuf + old, 0, new - old);
  1005. pool->sockbuf_size = new;
  1006. }
  1007. /* Peeks at a socket to find the first end of line and then reads just that
  1008. * from the socket and returns that as a malloced char */
  1009. char *recv_line(struct pool *pool)
  1010. {
  1011. char *tok, *sret = NULL;
  1012. ssize_t len, buflen;
  1013. int waited = 0;
  1014. if (!strstr(pool->sockbuf, "\n")) {
  1015. struct timeval rstart, now;
  1016. cgtime(&rstart);
  1017. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1018. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1019. goto out;
  1020. }
  1021. do {
  1022. char s[RBUFSIZE];
  1023. size_t slen;
  1024. ssize_t n;
  1025. memset(s, 0, RBUFSIZE);
  1026. n = recv(pool->sock, s, RECVSIZE, 0);
  1027. if (!n) {
  1028. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1029. suspend_stratum(pool);
  1030. break;
  1031. }
  1032. cgtime(&now);
  1033. waited = tdiff(&now, &rstart);
  1034. if (n < 0) {
  1035. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1036. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1037. suspend_stratum(pool);
  1038. break;
  1039. }
  1040. } else {
  1041. slen = strlen(s);
  1042. recalloc_sock(pool, slen);
  1043. strcat(pool->sockbuf, s);
  1044. }
  1045. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1046. }
  1047. buflen = strlen(pool->sockbuf);
  1048. tok = strtok(pool->sockbuf, "\n");
  1049. if (!tok) {
  1050. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1051. goto out;
  1052. }
  1053. sret = strdup(tok);
  1054. len = strlen(sret);
  1055. /* Copy what's left in the buffer after the \n, including the
  1056. * terminating \0 */
  1057. if (buflen > len + 1)
  1058. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1059. else
  1060. strcpy(pool->sockbuf, "");
  1061. pool->cgminer_pool_stats.times_received++;
  1062. pool->cgminer_pool_stats.bytes_received += len;
  1063. pool->cgminer_pool_stats.net_bytes_received += len;
  1064. out:
  1065. if (!sret)
  1066. clear_sock(pool);
  1067. else if (opt_protocol)
  1068. applog(LOG_DEBUG, "RECVD: %s", sret);
  1069. return sret;
  1070. }
  1071. /* Extracts a string value from a json array with error checking. To be used
  1072. * when the value of the string returned is only examined and not to be stored.
  1073. * See json_array_string below */
  1074. static char *__json_array_string(json_t *val, unsigned int entry)
  1075. {
  1076. json_t *arr_entry;
  1077. if (json_is_null(val))
  1078. return NULL;
  1079. if (!json_is_array(val))
  1080. return NULL;
  1081. if (entry > json_array_size(val))
  1082. return NULL;
  1083. arr_entry = json_array_get(val, entry);
  1084. if (!json_is_string(arr_entry))
  1085. return NULL;
  1086. return (char *)json_string_value(arr_entry);
  1087. }
  1088. /* Creates a freshly malloced dup of __json_array_string */
  1089. static char *json_array_string(json_t *val, unsigned int entry)
  1090. {
  1091. char *buf = __json_array_string(val, entry);
  1092. if (buf)
  1093. return strdup(buf);
  1094. return NULL;
  1095. }
  1096. static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
  1097. static bool parse_notify(struct pool *pool, json_t *val)
  1098. {
  1099. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1100. *ntime, *header;
  1101. size_t cb1_len, cb2_len, alloc_len;
  1102. unsigned char *cb1, *cb2;
  1103. bool clean, ret = false;
  1104. int merkles, i;
  1105. json_t *arr;
  1106. arr = json_array_get(val, 4);
  1107. if (!arr || !json_is_array(arr))
  1108. goto out;
  1109. merkles = json_array_size(arr);
  1110. job_id = json_array_string(val, 0);
  1111. prev_hash = json_array_string(val, 1);
  1112. coinbase1 = json_array_string(val, 2);
  1113. coinbase2 = json_array_string(val, 3);
  1114. bbversion = json_array_string(val, 5);
  1115. nbit = json_array_string(val, 6);
  1116. ntime = json_array_string(val, 7);
  1117. clean = json_is_true(json_array_get(val, 8));
  1118. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1119. /* Annoying but we must not leak memory */
  1120. if (job_id)
  1121. free(job_id);
  1122. if (prev_hash)
  1123. free(prev_hash);
  1124. if (coinbase1)
  1125. free(coinbase1);
  1126. if (coinbase2)
  1127. free(coinbase2);
  1128. if (bbversion)
  1129. free(bbversion);
  1130. if (nbit)
  1131. free(nbit);
  1132. if (ntime)
  1133. free(ntime);
  1134. goto out;
  1135. }
  1136. cg_wlock(&pool->data_lock);
  1137. free(pool->swork.job_id);
  1138. free(pool->swork.prev_hash);
  1139. free(pool->swork.bbversion);
  1140. free(pool->swork.nbit);
  1141. free(pool->swork.ntime);
  1142. pool->swork.job_id = job_id;
  1143. pool->swork.prev_hash = prev_hash;
  1144. cb1_len = strlen(coinbase1) / 2;
  1145. cb2_len = strlen(coinbase2) / 2;
  1146. pool->swork.bbversion = bbversion;
  1147. pool->swork.nbit = nbit;
  1148. pool->swork.ntime = ntime;
  1149. pool->swork.clean = clean;
  1150. alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  1151. pool->nonce2_offset = cb1_len + pool->n1_len;
  1152. for (i = 0; i < pool->swork.merkles; i++)
  1153. free(pool->swork.merkle_bin[i]);
  1154. if (merkles) {
  1155. pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
  1156. sizeof(char *) * merkles + 1);
  1157. for (i = 0; i < merkles; i++) {
  1158. char *merkle = json_array_string(arr, i);
  1159. pool->swork.merkle_bin[i] = malloc(32);
  1160. if (unlikely(!pool->swork.merkle_bin[i]))
  1161. quit(1, "Failed to malloc pool swork merkle_bin");
  1162. hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  1163. free(merkle);
  1164. }
  1165. }
  1166. pool->swork.merkles = merkles;
  1167. if (clean)
  1168. pool->nonce2 = 0;
  1169. pool->merkle_offset = strlen(pool->swork.bbversion) +
  1170. strlen(pool->swork.prev_hash);
  1171. pool->swork.header_len = pool->merkle_offset +
  1172. /* merkle_hash */ 32 +
  1173. strlen(pool->swork.ntime) +
  1174. strlen(pool->swork.nbit) +
  1175. /* nonce */ 8 +
  1176. /* workpadding */ 96;
  1177. pool->merkle_offset /= 2;
  1178. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1179. align_len(&pool->swork.header_len);
  1180. header = alloca(pool->swork.header_len);
  1181. snprintf(header, pool->swork.header_len,
  1182. "%s%s%s%s%s%s%s",
  1183. pool->swork.bbversion,
  1184. pool->swork.prev_hash,
  1185. blank_merkel,
  1186. pool->swork.ntime,
  1187. pool->swork.nbit,
  1188. "00000000", /* nonce */
  1189. workpadding);
  1190. if (unlikely(!hex2bin(pool->header_bin, header, 128)))
  1191. quit(1, "Failed to convert header to header_bin in parse_notify");
  1192. cb1 = calloc(cb1_len, 1);
  1193. if (unlikely(!cb1))
  1194. quithere(1, "Failed to calloc cb1 in parse_notify");
  1195. hex2bin(cb1, coinbase1, cb1_len);
  1196. cb2 = calloc(cb2_len, 1);
  1197. if (unlikely(!cb2))
  1198. quithere(1, "Failed to calloc cb2 in parse_notify");
  1199. hex2bin(cb2, coinbase2, cb2_len);
  1200. free(pool->coinbase);
  1201. align_len(&alloc_len);
  1202. pool->coinbase = calloc(alloc_len, 1);
  1203. if (unlikely(!pool->coinbase))
  1204. quit(1, "Failed to calloc pool coinbase in parse_notify");
  1205. memcpy(pool->coinbase, cb1, cb1_len);
  1206. memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  1207. memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  1208. cg_wunlock(&pool->data_lock);
  1209. if (opt_protocol) {
  1210. applog(LOG_DEBUG, "job_id: %s", job_id);
  1211. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1212. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1213. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1214. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1215. applog(LOG_DEBUG, "nbit: %s", nbit);
  1216. applog(LOG_DEBUG, "ntime: %s", ntime);
  1217. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1218. }
  1219. free(coinbase1);
  1220. free(coinbase2);
  1221. free(cb1);
  1222. free(cb2);
  1223. /* A notify message is the closest stratum gets to a getwork */
  1224. pool->getwork_requested++;
  1225. total_getworks++;
  1226. ret = true;
  1227. out:
  1228. return ret;
  1229. }
  1230. static bool parse_diff(struct pool *pool, json_t *val)
  1231. {
  1232. double old_diff, diff;
  1233. diff = json_number_value(json_array_get(val, 0));
  1234. if (diff == 0)
  1235. return false;
  1236. cg_wlock(&pool->data_lock);
  1237. old_diff = pool->swork.diff;
  1238. pool->swork.diff = diff;
  1239. cg_wunlock(&pool->data_lock);
  1240. if (old_diff != diff) {
  1241. int idiff = diff;
  1242. if ((double)idiff == diff)
  1243. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  1244. pool->pool_no, idiff);
  1245. else
  1246. applog(LOG_NOTICE, "Pool %d difficulty changed to %f",
  1247. pool->pool_no, diff);
  1248. } else
  1249. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  1250. diff);
  1251. return true;
  1252. }
  1253. static bool parse_reconnect(struct pool *pool, json_t *val)
  1254. {
  1255. char *url, *port, address[256];
  1256. memset(address, 0, 255);
  1257. url = (char *)json_string_value(json_array_get(val, 0));
  1258. if (!url)
  1259. url = pool->sockaddr_url;
  1260. port = (char *)json_string_value(json_array_get(val, 1));
  1261. if (!port)
  1262. port = pool->stratum_port;
  1263. sprintf(address, "%s:%s", url, port);
  1264. if (!extract_sockaddr(pool, address))
  1265. return false;
  1266. pool->stratum_url = pool->sockaddr_url;
  1267. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1268. if (!restart_stratum(pool))
  1269. return false;
  1270. return true;
  1271. }
  1272. static bool send_version(struct pool *pool, json_t *val)
  1273. {
  1274. char s[RBUFSIZE];
  1275. int id = json_integer_value(json_object_get(val, "id"));
  1276. if (!id)
  1277. return false;
  1278. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1279. if (!stratum_send(pool, s, strlen(s)))
  1280. return false;
  1281. return true;
  1282. }
  1283. static bool show_message(struct pool *pool, json_t *val)
  1284. {
  1285. char *msg;
  1286. if (!json_is_array(val))
  1287. return false;
  1288. msg = (char *)json_string_value(json_array_get(val, 0));
  1289. if (!msg)
  1290. return false;
  1291. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  1292. return true;
  1293. }
  1294. bool parse_method(struct pool *pool, char *s)
  1295. {
  1296. json_t *val = NULL, *method, *err_val, *params;
  1297. json_error_t err;
  1298. bool ret = false;
  1299. char *buf;
  1300. if (!s)
  1301. goto out;
  1302. val = JSON_LOADS(s, &err);
  1303. if (!val) {
  1304. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1305. goto out;
  1306. }
  1307. method = json_object_get(val, "method");
  1308. if (!method)
  1309. goto out;
  1310. err_val = json_object_get(val, "error");
  1311. params = json_object_get(val, "params");
  1312. if (err_val && !json_is_null(err_val)) {
  1313. char *ss;
  1314. if (err_val)
  1315. ss = json_dumps(err_val, JSON_INDENT(3));
  1316. else
  1317. ss = strdup("(unknown reason)");
  1318. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1319. free(ss);
  1320. goto out;
  1321. }
  1322. buf = (char *)json_string_value(method);
  1323. if (!buf)
  1324. goto out;
  1325. if (!strncasecmp(buf, "mining.notify", 13)) {
  1326. if (parse_notify(pool, params))
  1327. pool->stratum_notify = ret = true;
  1328. else
  1329. pool->stratum_notify = ret = false;
  1330. goto out;
  1331. }
  1332. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1333. ret = true;
  1334. goto out;
  1335. }
  1336. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1337. ret = true;
  1338. goto out;
  1339. }
  1340. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1341. ret = true;
  1342. goto out;
  1343. }
  1344. if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
  1345. ret = true;
  1346. goto out;
  1347. }
  1348. out:
  1349. if (val)
  1350. json_decref(val);
  1351. return ret;
  1352. }
  1353. bool auth_stratum(struct pool *pool)
  1354. {
  1355. json_t *val = NULL, *res_val, *err_val;
  1356. char s[RBUFSIZE], *sret = NULL;
  1357. json_error_t err;
  1358. bool ret = false;
  1359. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1360. swork_id++, pool->rpc_user, pool->rpc_pass);
  1361. if (!stratum_send(pool, s, strlen(s)))
  1362. goto out;
  1363. /* Parse all data in the queue and anything left should be auth */
  1364. while (42) {
  1365. sret = recv_line(pool);
  1366. if (!sret)
  1367. goto out;
  1368. if (parse_method(pool, sret))
  1369. free(sret);
  1370. else
  1371. break;
  1372. }
  1373. val = JSON_LOADS(sret, &err);
  1374. free(sret);
  1375. res_val = json_object_get(val, "result");
  1376. err_val = json_object_get(val, "error");
  1377. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1378. char *ss;
  1379. if (err_val)
  1380. ss = json_dumps(err_val, JSON_INDENT(3));
  1381. else
  1382. ss = strdup("(unknown reason)");
  1383. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1384. free(ss);
  1385. goto out;
  1386. }
  1387. ret = true;
  1388. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1389. pool->probed = true;
  1390. successful_connect = true;
  1391. out:
  1392. if (val)
  1393. json_decref(val);
  1394. return ret;
  1395. }
  1396. static bool setup_stratum_socket(struct pool *pool)
  1397. {
  1398. struct addrinfo *servinfo, *hints, *p;
  1399. int sockd;
  1400. mutex_lock(&pool->stratum_lock);
  1401. pool->stratum_active = false;
  1402. if (pool->sock)
  1403. CLOSESOCKET(pool->sock);
  1404. pool->sock = 0;
  1405. mutex_unlock(&pool->stratum_lock);
  1406. hints = &pool->stratum_hints;
  1407. memset(hints, 0, sizeof(struct addrinfo));
  1408. hints->ai_family = AF_UNSPEC;
  1409. hints->ai_socktype = SOCK_STREAM;
  1410. if (getaddrinfo(pool->sockaddr_url, pool->stratum_port, hints, &servinfo) != 0) {
  1411. if (!pool->probed) {
  1412. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  1413. pool->sockaddr_url, pool->stratum_port);
  1414. pool->probed = true;
  1415. } else {
  1416. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  1417. pool->sockaddr_url, pool->stratum_port);
  1418. }
  1419. return false;
  1420. }
  1421. for (p = servinfo; p != NULL; p = p->ai_next) {
  1422. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  1423. if (sockd == -1) {
  1424. applog(LOG_DEBUG, "Failed socket");
  1425. continue;
  1426. }
  1427. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  1428. CLOSESOCKET(sockd);
  1429. applog(LOG_DEBUG, "Failed connect");
  1430. continue;
  1431. }
  1432. break;
  1433. }
  1434. if (p == NULL) {
  1435. applog(LOG_INFO, "Failed to find a stratum servinfo on %s:%s",
  1436. pool->sockaddr_url, pool->stratum_port);
  1437. freeaddrinfo(servinfo);
  1438. return false;
  1439. }
  1440. freeaddrinfo(servinfo);
  1441. if (!pool->sockbuf) {
  1442. pool->sockbuf = calloc(RBUFSIZE, 1);
  1443. if (!pool->sockbuf)
  1444. quithere(1, "Failed to calloc pool sockbuf");
  1445. pool->sockbuf_size = RBUFSIZE;
  1446. }
  1447. pool->sock = sockd;
  1448. keep_sockalive(sockd);
  1449. return true;
  1450. }
  1451. static char *get_sessionid(json_t *val)
  1452. {
  1453. char *ret = NULL;
  1454. json_t *arr_val;
  1455. int arrsize, i;
  1456. arr_val = json_array_get(val, 0);
  1457. if (!arr_val || !json_is_array(arr_val))
  1458. goto out;
  1459. arrsize = json_array_size(arr_val);
  1460. for (i = 0; i < arrsize; i++) {
  1461. json_t *arr = json_array_get(arr_val, i);
  1462. char *notify;
  1463. if (!arr | !json_is_array(arr))
  1464. break;
  1465. notify = __json_array_string(arr, 0);
  1466. if (!notify)
  1467. continue;
  1468. if (!strncasecmp(notify, "mining.notify", 13)) {
  1469. ret = json_array_string(arr, 1);
  1470. break;
  1471. }
  1472. }
  1473. out:
  1474. return ret;
  1475. }
  1476. void suspend_stratum(struct pool *pool)
  1477. {
  1478. clear_sockbuf(pool);
  1479. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1480. mutex_lock(&pool->stratum_lock);
  1481. pool->stratum_active = pool->stratum_notify = false;
  1482. if (pool->sock)
  1483. CLOSESOCKET(pool->sock);
  1484. pool->sock = 0;
  1485. mutex_unlock(&pool->stratum_lock);
  1486. }
  1487. bool initiate_stratum(struct pool *pool)
  1488. {
  1489. bool ret = false, recvd = false, noresume = false, sockd = false;
  1490. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1491. json_t *val = NULL, *res_val, *err_val;
  1492. json_error_t err;
  1493. int n2size;
  1494. resend:
  1495. if (!setup_stratum_socket(pool)) {
  1496. sockd = false;
  1497. goto out;
  1498. }
  1499. sockd = true;
  1500. if (recvd) {
  1501. /* Get rid of any crap lying around if we're resending */
  1502. clear_sock(pool);
  1503. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1504. } else {
  1505. if (pool->sessionid)
  1506. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1507. else
  1508. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1509. }
  1510. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1511. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1512. goto out;
  1513. }
  1514. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1515. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1516. goto out;
  1517. }
  1518. sret = recv_line(pool);
  1519. if (!sret)
  1520. goto out;
  1521. recvd = true;
  1522. val = JSON_LOADS(sret, &err);
  1523. free(sret);
  1524. if (!val) {
  1525. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1526. goto out;
  1527. }
  1528. res_val = json_object_get(val, "result");
  1529. err_val = json_object_get(val, "error");
  1530. if (!res_val || json_is_null(res_val) ||
  1531. (err_val && !json_is_null(err_val))) {
  1532. char *ss;
  1533. if (err_val)
  1534. ss = json_dumps(err_val, JSON_INDENT(3));
  1535. else
  1536. ss = strdup("(unknown reason)");
  1537. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1538. free(ss);
  1539. goto out;
  1540. }
  1541. sessionid = get_sessionid(res_val);
  1542. if (!sessionid)
  1543. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1544. nonce1 = json_array_string(res_val, 1);
  1545. if (!nonce1) {
  1546. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1547. free(sessionid);
  1548. goto out;
  1549. }
  1550. n2size = json_integer_value(json_array_get(res_val, 2));
  1551. if (!n2size) {
  1552. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1553. free(sessionid);
  1554. free(nonce1);
  1555. goto out;
  1556. }
  1557. cg_wlock(&pool->data_lock);
  1558. pool->sessionid = sessionid;
  1559. pool->nonce1 = nonce1;
  1560. pool->n1_len = strlen(nonce1) / 2;
  1561. free(pool->nonce1bin);
  1562. pool->nonce1bin = calloc(pool->n1_len, 1);
  1563. if (unlikely(!pool->nonce1bin))
  1564. quithere(1, "Failed to calloc pool->nonce1bin");
  1565. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  1566. pool->n2size = n2size;
  1567. cg_wunlock(&pool->data_lock);
  1568. if (sessionid)
  1569. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1570. ret = true;
  1571. out:
  1572. if (val)
  1573. json_decref(val);
  1574. if (ret) {
  1575. if (!pool->stratum_url)
  1576. pool->stratum_url = pool->sockaddr_url;
  1577. pool->stratum_active = true;
  1578. pool->swork.diff = 1;
  1579. if (opt_protocol) {
  1580. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1581. pool->pool_no, pool->nonce1, pool->n2size);
  1582. }
  1583. } else {
  1584. if (recvd && !noresume) {
  1585. /* Reset the sessionid used for stratum resuming in case the pool
  1586. * does not support it, or does not know how to respond to the
  1587. * presence of the sessionid parameter. */
  1588. cg_wlock(&pool->data_lock);
  1589. free(pool->sessionid);
  1590. free(pool->nonce1);
  1591. pool->sessionid = pool->nonce1 = NULL;
  1592. cg_wunlock(&pool->data_lock);
  1593. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1594. noresume = true;
  1595. goto resend;
  1596. }
  1597. applog(LOG_DEBUG, "Initiate stratum failed");
  1598. if (sockd)
  1599. suspend_stratum(pool);
  1600. }
  1601. return ret;
  1602. }
  1603. bool restart_stratum(struct pool *pool)
  1604. {
  1605. if (pool->stratum_active)
  1606. suspend_stratum(pool);
  1607. if (!initiate_stratum(pool))
  1608. return false;
  1609. if (!auth_stratum(pool))
  1610. return false;
  1611. return true;
  1612. }
  1613. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1614. {
  1615. dev->device_last_not_well = time(NULL);
  1616. dev->device_not_well_reason = reason;
  1617. switch (reason) {
  1618. case REASON_THREAD_FAIL_INIT:
  1619. dev->thread_fail_init_count++;
  1620. break;
  1621. case REASON_THREAD_ZERO_HASH:
  1622. dev->thread_zero_hash_count++;
  1623. break;
  1624. case REASON_THREAD_FAIL_QUEUE:
  1625. dev->thread_fail_queue_count++;
  1626. break;
  1627. case REASON_DEV_SICK_IDLE_60:
  1628. dev->dev_sick_idle_60_count++;
  1629. break;
  1630. case REASON_DEV_DEAD_IDLE_600:
  1631. dev->dev_dead_idle_600_count++;
  1632. break;
  1633. case REASON_DEV_NOSTART:
  1634. dev->dev_nostart_count++;
  1635. break;
  1636. case REASON_DEV_OVER_HEAT:
  1637. dev->dev_over_heat_count++;
  1638. break;
  1639. case REASON_DEV_THERMAL_CUTOFF:
  1640. dev->dev_thermal_cutoff_count++;
  1641. break;
  1642. case REASON_DEV_COMMS_ERROR:
  1643. dev->dev_comms_error_count++;
  1644. break;
  1645. case REASON_DEV_THROTTLE:
  1646. dev->dev_throttle_count++;
  1647. break;
  1648. }
  1649. }
  1650. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1651. void *realloc_strcat(char *ptr, char *s)
  1652. {
  1653. size_t old = strlen(ptr), len = strlen(s);
  1654. char *ret;
  1655. if (!len)
  1656. return ptr;
  1657. len += old + 1;
  1658. align_len(&len);
  1659. ret = malloc(len);
  1660. if (unlikely(!ret))
  1661. quithere(1, "Failed to malloc");
  1662. sprintf(ret, "%s%s", ptr, s);
  1663. free(ptr);
  1664. return ret;
  1665. }
  1666. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  1667. * Including 0x00 at the end
  1668. * You must free the result yourself */
  1669. void *str_text(char *ptr)
  1670. {
  1671. unsigned char *uptr;
  1672. char *ret, *txt;
  1673. if (ptr == NULL) {
  1674. ret = strdup("(null)");
  1675. if (unlikely(!ret))
  1676. quithere(1, "Failed to malloc null");
  1677. }
  1678. uptr = (unsigned char *)ptr;
  1679. ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed
  1680. if (unlikely(!txt))
  1681. quithere(1, "Failed to malloc txt");
  1682. do {
  1683. if (*uptr < ' ' || *uptr > '~') {
  1684. sprintf(txt, "0x%02x", *uptr);
  1685. txt += 4;
  1686. } else
  1687. *(txt++) = *uptr;
  1688. } while (*(uptr++));
  1689. *txt = '\0';
  1690. return ret;
  1691. }
  1692. void RenameThread(const char* name)
  1693. {
  1694. #if defined(PR_SET_NAME)
  1695. // Only the first 15 characters are used (16 - NUL terminator)
  1696. prctl(PR_SET_NAME, name, 0, 0, 0);
  1697. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1698. pthread_set_name_np(pthread_self(), name);
  1699. #elif defined(MAC_OSX)
  1700. pthread_setname_np(name);
  1701. #else
  1702. // Prevent warnings for unused parameters...
  1703. (void)name;
  1704. #endif
  1705. }
  1706. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  1707. * that support them and for apple which does not. We use a single byte across
  1708. * a pipe to emulate semaphore behaviour there. */
  1709. #ifdef __APPLE__
  1710. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1711. {
  1712. int flags, fd, i;
  1713. if (pipe(cgsem->pipefd) == -1)
  1714. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  1715. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  1716. * execv on restart. */
  1717. for (i = 0; i < 2; i++) {
  1718. fd = cgsem->pipefd[i];
  1719. flags = fcntl(fd, F_GETFD, 0);
  1720. flags |= FD_CLOEXEC;
  1721. if (fcntl(fd, F_SETFD, flags) == -1)
  1722. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  1723. }
  1724. }
  1725. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1726. {
  1727. const char buf = 1;
  1728. int ret;
  1729. ret = write(cgsem->pipefd[1], &buf, 1);
  1730. if (unlikely(ret == 0))
  1731. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  1732. }
  1733. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1734. {
  1735. char buf;
  1736. int ret;
  1737. ret = read(cgsem->pipefd[0], &buf, 1);
  1738. if (unlikely(ret == 0))
  1739. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  1740. }
  1741. void _cgsem_destroy(cgsem_t *cgsem)
  1742. {
  1743. close(cgsem->pipefd[1]);
  1744. close(cgsem->pipefd[0]);
  1745. }
  1746. #else
  1747. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1748. {
  1749. int ret;
  1750. if ((ret = sem_init(cgsem, 0, 0)))
  1751. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  1752. }
  1753. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1754. {
  1755. if (unlikely(sem_post(cgsem)))
  1756. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  1757. }
  1758. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1759. {
  1760. if (unlikely(sem_wait(cgsem)))
  1761. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  1762. }
  1763. void _cgsem_destroy(cgsem_t *cgsem)
  1764. {
  1765. sem_destroy(cgsem);
  1766. }
  1767. #endif