util.c 42 KB

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