util.c 43 KB

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