util.c 44 KB

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