util.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. * Copyright 2012 Giel van Schijndel
  5. * Copyright 2012 Gavin Andresen
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #define _GNU_SOURCE
  13. #include "config.h"
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <ctype.h>
  17. #include <stdarg.h>
  18. #include <string.h>
  19. #include <pthread.h>
  20. #include <jansson.h>
  21. #include <curl/curl.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include <unistd.h>
  25. #include <sys/types.h>
  26. #ifdef HAVE_SYS_PRCTL_H
  27. # include <sys/prctl.h>
  28. #endif
  29. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  30. # include <pthread_np.h>
  31. #endif
  32. #ifndef WIN32
  33. # include <sys/socket.h>
  34. # include <netinet/in.h>
  35. # include <netinet/tcp.h>
  36. # include <netdb.h>
  37. #else
  38. # include <winsock2.h>
  39. # include <mstcpip.h>
  40. # include <ws2tcpip.h>
  41. #endif
  42. #include "miner.h"
  43. #include "elist.h"
  44. #include "compat.h"
  45. #include "util.h"
  46. bool successful_connect = false;
  47. struct timeval nettime;
  48. struct upload_buffer {
  49. const void *buf;
  50. size_t len;
  51. };
  52. struct header_info {
  53. char *lp_path;
  54. int rolltime;
  55. char *reason;
  56. char *stratum_url;
  57. bool hadrolltime;
  58. bool canroll;
  59. bool hadexpire;
  60. };
  61. struct tq_ent {
  62. void *data;
  63. struct list_head q_node;
  64. };
  65. static void databuf_free(struct data_buffer *db)
  66. {
  67. if (!db)
  68. return;
  69. free(db->buf);
  70. memset(db, 0, sizeof(*db));
  71. }
  72. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  73. void *user_data)
  74. {
  75. struct data_buffer *db = user_data;
  76. size_t len = size * nmemb;
  77. size_t oldlen, newlen;
  78. void *newmem;
  79. static const unsigned char zero = 0;
  80. if (db->idlemarker) {
  81. const unsigned char *cptr = ptr;
  82. for (size_t i = 0; i < len; ++i)
  83. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  84. *db->idlemarker = CURL_SOCKET_BAD;
  85. db->idlemarker = NULL;
  86. break;
  87. }
  88. }
  89. oldlen = db->len;
  90. newlen = oldlen + len;
  91. newmem = realloc(db->buf, newlen + 1);
  92. if (!newmem)
  93. return 0;
  94. db->buf = newmem;
  95. db->len = newlen;
  96. memcpy(db->buf + oldlen, ptr, len);
  97. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  98. return len;
  99. }
  100. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  101. void *user_data)
  102. {
  103. struct upload_buffer *ub = user_data;
  104. unsigned int len = size * nmemb;
  105. if (len > ub->len)
  106. len = ub->len;
  107. if (len) {
  108. memcpy(ptr, ub->buf, len);
  109. ub->buf += len;
  110. ub->len -= len;
  111. }
  112. return len;
  113. }
  114. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  115. {
  116. struct header_info *hi = user_data;
  117. size_t remlen, slen, ptrlen = size * nmemb;
  118. char *rem, *val = NULL, *key = NULL;
  119. void *tmp;
  120. val = calloc(1, ptrlen);
  121. key = calloc(1, ptrlen);
  122. if (!key || !val)
  123. goto out;
  124. tmp = memchr(ptr, ':', ptrlen);
  125. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  126. goto out;
  127. slen = tmp - ptr;
  128. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  129. goto out;
  130. memcpy(key, ptr, slen); /* store & nul term key */
  131. key[slen] = 0;
  132. rem = ptr + slen + 1; /* trim value's leading whitespace */
  133. remlen = ptrlen - slen - 1;
  134. while ((remlen > 0) && (isspace(*rem))) {
  135. remlen--;
  136. rem++;
  137. }
  138. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  139. val[remlen] = 0;
  140. while ((*val) && (isspace(val[strlen(val) - 1])))
  141. val[strlen(val) - 1] = 0;
  142. if (!*val) /* skip blank value */
  143. goto out;
  144. if (opt_protocol)
  145. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  146. if (!strcasecmp("X-Roll-Ntime", key)) {
  147. hi->hadrolltime = true;
  148. if (!strncasecmp("N", val, 1))
  149. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  150. else {
  151. hi->canroll = true;
  152. /* Check to see if expire= is supported and if not, set
  153. * the rolltime to the default scantime */
  154. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  155. sscanf(val + 7, "%d", &hi->rolltime);
  156. hi->hadexpire = true;
  157. } else
  158. hi->rolltime = opt_scantime;
  159. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  160. }
  161. }
  162. if (!strcasecmp("X-Long-Polling", key)) {
  163. hi->lp_path = val; /* steal memory reference */
  164. val = NULL;
  165. }
  166. if (!strcasecmp("X-Reject-Reason", key)) {
  167. hi->reason = val; /* steal memory reference */
  168. val = NULL;
  169. }
  170. if (!strcasecmp("X-Stratum", key)) {
  171. hi->stratum_url = val;
  172. val = NULL;
  173. }
  174. out:
  175. free(key);
  176. free(val);
  177. return ptrlen;
  178. }
  179. static int keep_sockalive(SOCKETTYPE fd)
  180. {
  181. const int tcp_keepidle = 60;
  182. const int tcp_keepintvl = 60;
  183. const int keepalive = 1;
  184. int ret = 0;
  185. #ifndef WIN32
  186. const int tcp_keepcnt = 5;
  187. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  188. ret = 1;
  189. # ifdef __linux
  190. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  191. ret = 1;
  192. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  193. ret = 1;
  194. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  195. ret = 1;
  196. # endif /* __linux */
  197. # ifdef __APPLE_CC__
  198. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  199. ret = 1;
  200. # endif /* __APPLE_CC__ */
  201. #else /* WIN32 */
  202. const int zero = 0;
  203. struct tcp_keepalive vals;
  204. vals.onoff = 1;
  205. vals.keepalivetime = tcp_keepidle * 1000;
  206. vals.keepaliveinterval = tcp_keepintvl * 1000;
  207. DWORD outputBytes;
  208. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&keepalive, sizeof(keepalive))))
  209. ret = 1;
  210. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  211. ret = 1;
  212. /* Windows happily submits indefinitely to the send buffer blissfully
  213. * unaware nothing is getting there without gracefully failing unless
  214. * we disable the send buffer */
  215. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  216. ret = 1;
  217. #endif /* WIN32 */
  218. return ret;
  219. }
  220. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  221. curlsocktype __maybe_unused purpose)
  222. {
  223. return keep_sockalive(fd);
  224. }
  225. static void last_nettime(struct timeval *last)
  226. {
  227. rd_lock(&netacc_lock);
  228. last->tv_sec = nettime.tv_sec;
  229. last->tv_usec = nettime.tv_usec;
  230. rd_unlock(&netacc_lock);
  231. }
  232. static void set_nettime(void)
  233. {
  234. wr_lock(&netacc_lock);
  235. gettimeofday(&nettime, NULL);
  236. wr_unlock(&netacc_lock);
  237. }
  238. struct json_rpc_call_state {
  239. struct data_buffer all_data;
  240. struct header_info hi;
  241. void *priv;
  242. char curl_err_str[CURL_ERROR_SIZE];
  243. struct curl_slist *headers;
  244. struct upload_buffer upload_data;
  245. struct pool *pool;
  246. };
  247. void json_rpc_call_async(CURL *curl, const char *url,
  248. const char *userpass, const char *rpc_req,
  249. bool longpoll,
  250. struct pool *pool, bool share,
  251. void *priv)
  252. {
  253. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  254. *state = (struct json_rpc_call_state){
  255. .priv = priv,
  256. .pool = pool,
  257. };
  258. long timeout = longpoll ? (60 * 60) : 60;
  259. char len_hdr[64], user_agent_hdr[128];
  260. struct curl_slist *headers = NULL;
  261. if (longpoll)
  262. state->all_data.idlemarker = &pool->lp_socket;
  263. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  264. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  265. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  266. #if 0 /* Disable curl debugging since it spews to stderr */
  267. if (opt_protocol)
  268. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  269. #endif
  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, &state->all_data);
  280. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  281. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  282. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  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, &state->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. } else if (opt_socks_proxy) {
  290. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  291. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  292. }
  293. if (userpass) {
  294. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  295. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  296. }
  297. if (longpoll)
  298. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  299. curl_easy_setopt(curl, CURLOPT_POST, 1);
  300. if (opt_protocol)
  301. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  302. state->upload_data.buf = rpc_req;
  303. state->upload_data.len = strlen(rpc_req);
  304. sprintf(len_hdr, "Content-Length: %lu",
  305. (unsigned long) state->upload_data.len);
  306. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  307. headers = curl_slist_append(headers,
  308. "Content-type: application/json");
  309. headers = curl_slist_append(headers,
  310. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  311. if (longpoll)
  312. headers = curl_slist_append(headers,
  313. "X-Minimum-Wait: 0");
  314. if (likely(global_hashrate)) {
  315. char ghashrate[255];
  316. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  317. headers = curl_slist_append(headers, ghashrate);
  318. }
  319. headers = curl_slist_append(headers, len_hdr);
  320. headers = curl_slist_append(headers, user_agent_hdr);
  321. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  322. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  323. state->headers = 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. gettimeofday(&now, NULL);
  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. }
  345. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  346. {
  347. struct json_rpc_call_state *state;
  348. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
  349. applog(LOG_ERR, "Failed to get private curl data");
  350. if (out_priv)
  351. *(void**)out_priv = NULL;
  352. goto err_out;
  353. }
  354. if (out_priv)
  355. *(void**)out_priv = state->priv;
  356. json_t *val, *err_val, *res_val;
  357. json_error_t err;
  358. struct pool *pool = state->pool;
  359. bool probing = probe && !pool->probed;
  360. if (rc) {
  361. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  362. goto err_out;
  363. }
  364. if (!state->all_data.buf) {
  365. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  366. goto err_out;
  367. }
  368. if (probing) {
  369. pool->probed = true;
  370. /* If X-Long-Polling was found, activate long polling */
  371. if (state->hi.lp_path) {
  372. if (pool->hdr_path != NULL)
  373. free(pool->hdr_path);
  374. pool->hdr_path = state->hi.lp_path;
  375. } else
  376. pool->hdr_path = NULL;
  377. if (state->hi.stratum_url) {
  378. pool->stratum_url = state->hi.stratum_url;
  379. state->hi.stratum_url = NULL;
  380. }
  381. } else {
  382. if (state->hi.lp_path) {
  383. free(state->hi.lp_path);
  384. state->hi.lp_path = NULL;
  385. }
  386. if (state->hi.stratum_url) {
  387. free(state->hi.stratum_url);
  388. state->hi.stratum_url = NULL;
  389. }
  390. }
  391. if (rolltime)
  392. *rolltime = state->hi.rolltime;
  393. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  394. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  395. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  396. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  397. val = JSON_LOADS(state->all_data.buf, &err);
  398. if (!val) {
  399. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  400. if (opt_protocol)
  401. applog(LOG_DEBUG, "JSON protocol response:\n%s", state->all_data.buf);
  402. goto err_out;
  403. }
  404. if (opt_protocol) {
  405. char *s = json_dumps(val, JSON_INDENT(3));
  406. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  407. free(s);
  408. }
  409. /* JSON-RPC valid response returns a non-null 'result',
  410. * and a null 'error'.
  411. */
  412. res_val = json_object_get(val, "result");
  413. err_val = json_object_get(val, "error");
  414. if (!res_val ||(err_val && !json_is_null(err_val))) {
  415. char *s;
  416. if (err_val)
  417. s = json_dumps(err_val, JSON_INDENT(3));
  418. else
  419. s = strdup("(unknown reason)");
  420. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  421. free(s);
  422. json_decref(val);
  423. goto err_out;
  424. }
  425. if (state->hi.reason) {
  426. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  427. free(state->hi.reason);
  428. state->hi.reason = NULL;
  429. }
  430. successful_connect = true;
  431. databuf_free(&state->all_data);
  432. curl_slist_free_all(state->headers);
  433. curl_easy_reset(curl);
  434. free(state);
  435. return val;
  436. err_out:
  437. databuf_free(&state->all_data);
  438. curl_slist_free_all(state->headers);
  439. curl_easy_reset(curl);
  440. if (!successful_connect)
  441. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  442. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  443. free(state);
  444. return NULL;
  445. }
  446. json_t *json_rpc_call(CURL *curl, const char *url,
  447. const char *userpass, const char *rpc_req,
  448. bool probe, bool longpoll, int *rolltime,
  449. struct pool *pool, bool share)
  450. {
  451. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  452. int rc = curl_easy_perform(curl);
  453. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  454. }
  455. bool our_curl_supports_proxy_uris()
  456. {
  457. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  458. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  459. }
  460. /* Returns a malloced array string of a binary value of arbitrary length. The
  461. * array is rounded up to a 4 byte size to appease architectures that need
  462. * aligned array sizes */
  463. char *bin2hex(const unsigned char *p, size_t len)
  464. {
  465. unsigned int i;
  466. ssize_t slen;
  467. char *s;
  468. slen = len * 2 + 1;
  469. if (slen % 4)
  470. slen += 4 - (slen % 4);
  471. s = calloc(slen, 1);
  472. if (unlikely(!s))
  473. quit(1, "Failed to calloc in bin2hex");
  474. for (i = 0; i < len; i++)
  475. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  476. return s;
  477. }
  478. /* Does the reverse of bin2hex but does not allocate any ram */
  479. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  480. {
  481. bool ret = false;
  482. while (*hexstr && len) {
  483. char hex_byte[4];
  484. unsigned int v;
  485. if (unlikely(!hexstr[1])) {
  486. applog(LOG_ERR, "hex2bin str truncated");
  487. return ret;
  488. }
  489. memset(hex_byte, 0, 4);
  490. hex_byte[0] = hexstr[0];
  491. hex_byte[1] = hexstr[1];
  492. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  493. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  494. return ret;
  495. }
  496. *p = (unsigned char) v;
  497. p++;
  498. hexstr += 2;
  499. len--;
  500. }
  501. if (likely(len == 0 && *hexstr == 0))
  502. ret = true;
  503. return ret;
  504. }
  505. bool fulltest(const unsigned char *hash, const unsigned char *target)
  506. {
  507. unsigned char hash_swap[32], target_swap[32];
  508. uint32_t *hash32 = (uint32_t *) hash_swap;
  509. uint32_t *target32 = (uint32_t *) target_swap;
  510. char *hash_str, *target_str;
  511. bool rc = true;
  512. int i;
  513. swap256(hash_swap, hash);
  514. swap256(target_swap, target);
  515. for (i = 0; i < 32/4; i++) {
  516. uint32_t h32tmp = htobe32(hash32[i]);
  517. uint32_t t32tmp = htole32(target32[i]);
  518. target32[i] = swab32(target32[i]); /* for printing */
  519. if (h32tmp > t32tmp) {
  520. rc = false;
  521. break;
  522. }
  523. if (h32tmp < t32tmp) {
  524. rc = true;
  525. break;
  526. }
  527. }
  528. if (opt_debug) {
  529. hash_str = bin2hex(hash_swap, 32);
  530. target_str = bin2hex(target_swap, 32);
  531. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  532. hash_str,
  533. target_str,
  534. rc ? "YES (hash < target)" :
  535. "no (false positive; hash > target)");
  536. free(hash_str);
  537. free(target_str);
  538. }
  539. return rc;
  540. }
  541. struct thread_q *tq_new(void)
  542. {
  543. struct thread_q *tq;
  544. tq = calloc(1, sizeof(*tq));
  545. if (!tq)
  546. return NULL;
  547. INIT_LIST_HEAD(&tq->q);
  548. pthread_mutex_init(&tq->mutex, NULL);
  549. pthread_cond_init(&tq->cond, NULL);
  550. return tq;
  551. }
  552. void tq_free(struct thread_q *tq)
  553. {
  554. struct tq_ent *ent, *iter;
  555. if (!tq)
  556. return;
  557. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  558. list_del(&ent->q_node);
  559. free(ent);
  560. }
  561. pthread_cond_destroy(&tq->cond);
  562. pthread_mutex_destroy(&tq->mutex);
  563. memset(tq, 0, sizeof(*tq)); /* poison */
  564. free(tq);
  565. }
  566. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  567. {
  568. mutex_lock(&tq->mutex);
  569. tq->frozen = frozen;
  570. pthread_cond_signal(&tq->cond);
  571. mutex_unlock(&tq->mutex);
  572. }
  573. void tq_freeze(struct thread_q *tq)
  574. {
  575. tq_freezethaw(tq, true);
  576. }
  577. void tq_thaw(struct thread_q *tq)
  578. {
  579. tq_freezethaw(tq, false);
  580. }
  581. bool tq_push(struct thread_q *tq, void *data)
  582. {
  583. struct tq_ent *ent;
  584. bool rc = true;
  585. ent = calloc(1, sizeof(*ent));
  586. if (!ent)
  587. return false;
  588. ent->data = data;
  589. INIT_LIST_HEAD(&ent->q_node);
  590. mutex_lock(&tq->mutex);
  591. if (!tq->frozen) {
  592. list_add_tail(&ent->q_node, &tq->q);
  593. } else {
  594. free(ent);
  595. rc = false;
  596. }
  597. pthread_cond_signal(&tq->cond);
  598. mutex_unlock(&tq->mutex);
  599. return rc;
  600. }
  601. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  602. {
  603. struct tq_ent *ent;
  604. void *rval = NULL;
  605. int rc;
  606. mutex_lock(&tq->mutex);
  607. if (!list_empty(&tq->q))
  608. goto pop;
  609. if (abstime)
  610. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  611. else
  612. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  613. if (rc)
  614. goto out;
  615. if (list_empty(&tq->q))
  616. goto out;
  617. pop:
  618. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  619. rval = ent->data;
  620. list_del(&ent->q_node);
  621. free(ent);
  622. out:
  623. mutex_unlock(&tq->mutex);
  624. return rval;
  625. }
  626. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  627. {
  628. return pthread_create(&thr->pth, attr, start, arg);
  629. }
  630. void thr_info_freeze(struct thr_info *thr)
  631. {
  632. struct tq_ent *ent, *iter;
  633. struct thread_q *tq;
  634. if (!thr)
  635. return;
  636. tq = thr->q;
  637. if (!tq)
  638. return;
  639. mutex_lock(&tq->mutex);
  640. tq->frozen = true;
  641. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  642. list_del(&ent->q_node);
  643. free(ent);
  644. }
  645. mutex_unlock(&tq->mutex);
  646. }
  647. void thr_info_cancel(struct thr_info *thr)
  648. {
  649. if (!thr)
  650. return;
  651. if (PTH(thr) != 0L) {
  652. pthread_cancel(thr->pth);
  653. PTH(thr) = 0L;
  654. }
  655. }
  656. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  657. * on SMP machines */
  658. void nmsleep(unsigned int msecs)
  659. {
  660. struct timespec twait, tleft;
  661. int ret;
  662. ldiv_t d;
  663. d = ldiv(msecs, 1000);
  664. tleft.tv_sec = d.quot;
  665. tleft.tv_nsec = d.rem * 1000000;
  666. do {
  667. twait.tv_sec = tleft.tv_sec;
  668. twait.tv_nsec = tleft.tv_nsec;
  669. ret = nanosleep(&twait, &tleft);
  670. } while (ret == -1 && errno == EINTR);
  671. }
  672. /* Returns the microseconds difference between end and start times as a double */
  673. double us_tdiff(struct timeval *end, struct timeval *start)
  674. {
  675. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  676. }
  677. /* Returns the seconds difference between end and start times as a double */
  678. double tdiff(struct timeval *end, struct timeval *start)
  679. {
  680. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  681. }
  682. bool extract_sockaddr(struct pool *pool, char *url)
  683. {
  684. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  685. char url_address[256], port[6];
  686. int url_len, port_len = 0;
  687. url_begin = strstr(url, "//");
  688. if (!url_begin)
  689. url_begin = url;
  690. else
  691. url_begin += 2;
  692. /* Look for numeric ipv6 entries */
  693. ipv6_begin = strstr(url_begin, "[");
  694. ipv6_end = strstr(url_begin, "]");
  695. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  696. url_end = strstr(ipv6_end, ":");
  697. else
  698. url_end = strstr(url_begin, ":");
  699. if (url_end) {
  700. url_len = url_end - url_begin;
  701. port_len = strlen(url_begin) - url_len - 1;
  702. if (port_len < 1)
  703. return false;
  704. port_start = url_end + 1;
  705. } else
  706. url_len = strlen(url_begin);
  707. if (url_len < 1)
  708. return false;
  709. sprintf(url_address, "%.*s", url_len, url_begin);
  710. if (port_len)
  711. snprintf(port, 6, "%.*s", port_len, port_start);
  712. else
  713. strcpy(port, "80");
  714. free(pool->stratum_port);
  715. pool->stratum_port = strdup(port);
  716. free(pool->sockaddr_url);
  717. pool->sockaddr_url = strdup(url_address);
  718. return true;
  719. }
  720. /* Send a single command across a socket, appending \n to it. This should all
  721. * be done under stratum lock except when first establishing the socket */
  722. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  723. {
  724. SOCKETTYPE sock = pool->sock;
  725. ssize_t ssent = 0;
  726. if (opt_protocol)
  727. applog(LOG_DEBUG, "SEND: %s", s);
  728. strcat(s, "\n");
  729. len++;
  730. while (len > 0 ) {
  731. struct timeval timeout = {0, 0};
  732. size_t sent = 0;
  733. CURLcode rc;
  734. fd_set wd;
  735. FD_ZERO(&wd);
  736. FD_SET(sock, &wd);
  737. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  738. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  739. return false;
  740. }
  741. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  742. if (rc != CURLE_OK) {
  743. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  744. return false;
  745. }
  746. ssent += sent;
  747. len -= ssent;
  748. }
  749. return true;
  750. }
  751. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  752. {
  753. bool ret = false;
  754. mutex_lock(&pool->stratum_lock);
  755. if (pool->stratum_active)
  756. ret = __stratum_send(pool, s, len);
  757. else
  758. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  759. mutex_unlock(&pool->stratum_lock);
  760. return ret;
  761. }
  762. static void clear_sock(struct pool *pool)
  763. {
  764. size_t n = 0;
  765. char buf[RECVSIZE];
  766. mutex_lock(&pool->stratum_lock);
  767. while (CURLE_OK == curl_easy_recv(pool->stratum_curl, buf, RECVSIZE, &n))
  768. {}
  769. mutex_unlock(&pool->stratum_lock);
  770. }
  771. /* Check to see if Santa's been good to you */
  772. static bool sock_full(struct pool *pool, bool wait)
  773. {
  774. SOCKETTYPE sock = pool->sock;
  775. struct timeval timeout;
  776. fd_set rd;
  777. if (pool->readbuf.buf && memchr(pool->readbuf.buf, '\n', pool->readbuf.len))
  778. return true;
  779. FD_ZERO(&rd);
  780. FD_SET(sock, &rd);
  781. timeout.tv_usec = 0;
  782. if (wait)
  783. timeout.tv_sec = 60;
  784. else
  785. timeout.tv_sec = 0;
  786. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  787. return true;
  788. return false;
  789. }
  790. /* Peeks at a socket to find the first end of line and then reads just that
  791. * from the socket and returns that as a malloced char */
  792. char *recv_line(struct pool *pool)
  793. {
  794. ssize_t len;
  795. char *tok, *sret = NULL;
  796. size_t n = 0;
  797. while (!(pool->readbuf.buf && memchr(pool->readbuf.buf, '\n', pool->readbuf.len))) {
  798. char s[RBUFSIZE];
  799. CURLcode rc;
  800. if (!sock_full(pool, true)) {
  801. applog(LOG_DEBUG, "Timed out waiting for data on sock_full");
  802. goto out;
  803. }
  804. memset(s, 0, RBUFSIZE);
  805. mutex_lock(&pool->stratum_lock);
  806. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  807. mutex_unlock(&pool->stratum_lock);
  808. if (rc != CURLE_OK) {
  809. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %d", rc);
  810. goto out;
  811. }
  812. len = all_data_cb(s, n, 1, &pool->readbuf);
  813. if (n != (size_t)len) {
  814. applog(LOG_DEBUG, "Error appending readbuf in recv_line");
  815. goto out;
  816. }
  817. }
  818. // Assuming the bulk of the data will be in the line, steal the buffer and return it
  819. tok = memchr(pool->readbuf.buf, '\n', pool->readbuf.len);
  820. *tok = '\0';
  821. len = tok - (char*)pool->readbuf.buf;
  822. pool->readbuf.len -= len + 1;
  823. tok = memcpy(malloc(pool->readbuf.len), tok + 1, pool->readbuf.len);
  824. sret = realloc(pool->readbuf.buf, len + 1);
  825. pool->readbuf.buf = tok;
  826. out:
  827. if (!sret)
  828. clear_sock(pool);
  829. else if (opt_protocol)
  830. applog(LOG_DEBUG, "RECVD: %s", sret);
  831. return sret;
  832. }
  833. /* Extracts a string value from a json array with error checking. To be used
  834. * when the value of the string returned is only examined and not to be stored.
  835. * See json_array_string below */
  836. static char *__json_array_string(json_t *val, unsigned int entry)
  837. {
  838. json_t *arr_entry;
  839. if (json_is_null(val))
  840. return NULL;
  841. if (!json_is_array(val))
  842. return NULL;
  843. if (entry > json_array_size(val))
  844. return NULL;
  845. arr_entry = json_array_get(val, entry);
  846. if (!json_is_string(arr_entry))
  847. return NULL;
  848. return (char *)json_string_value(arr_entry);
  849. }
  850. /* Creates a freshly malloced dup of __json_array_string */
  851. static char *json_array_string(json_t *val, unsigned int entry)
  852. {
  853. char *buf = __json_array_string(val, entry);
  854. if (buf)
  855. return strdup(buf);
  856. return NULL;
  857. }
  858. static bool parse_notify(struct pool *pool, json_t *val)
  859. {
  860. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  861. int merkles, i;
  862. json_t *arr;
  863. bool clean;
  864. arr = json_array_get(val, 4);
  865. if (!arr || !json_is_array(arr))
  866. return false;
  867. merkles = json_array_size(arr);
  868. job_id = json_array_string(val, 0);
  869. prev_hash = json_array_string(val, 1);
  870. coinbase1 = json_array_string(val, 2);
  871. coinbase2 = json_array_string(val, 3);
  872. bbversion = json_array_string(val, 5);
  873. nbit = json_array_string(val, 6);
  874. ntime = json_array_string(val, 7);
  875. clean = json_is_true(json_array_get(val, 8));
  876. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  877. /* Annoying but we must not leak memory */
  878. if (job_id)
  879. free(job_id);
  880. if (prev_hash)
  881. free(prev_hash);
  882. if (coinbase1)
  883. free(coinbase1);
  884. if (coinbase2)
  885. free(coinbase2);
  886. if (bbversion)
  887. free(bbversion);
  888. if (nbit)
  889. free(nbit);
  890. if (ntime)
  891. free(ntime);
  892. return false;
  893. }
  894. mutex_lock(&pool->pool_lock);
  895. free(pool->swork.job_id);
  896. free(pool->swork.prev_hash);
  897. free(pool->swork.coinbase1);
  898. free(pool->swork.coinbase2);
  899. free(pool->swork.bbversion);
  900. free(pool->swork.nbit);
  901. free(pool->swork.ntime);
  902. pool->swork.job_id = job_id;
  903. pool->swork.prev_hash = prev_hash;
  904. pool->swork.coinbase1 = coinbase1;
  905. pool->swork.coinbase2 = coinbase2;
  906. pool->swork.bbversion = bbversion;
  907. pool->swork.nbit = nbit;
  908. pool->swork.ntime = ntime;
  909. pool->submit_old = !clean;
  910. pool->swork.clean = true;
  911. for (i = 0; i < pool->swork.merkles; i++)
  912. free(pool->swork.merkle[i]);
  913. if (merkles) {
  914. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  915. for (i = 0; i < merkles; i++)
  916. pool->swork.merkle[i] = json_array_string(arr, i);
  917. }
  918. pool->swork.merkles = merkles;
  919. if (clean)
  920. pool->nonce2 = 0;
  921. mutex_unlock(&pool->pool_lock);
  922. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  923. pool->pool_no, job_id);
  924. if (opt_protocol) {
  925. applog(LOG_DEBUG, "job_id: %s", job_id);
  926. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  927. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  928. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  929. for (i = 0; i < merkles; i++)
  930. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  931. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  932. applog(LOG_DEBUG, "nbit: %s", nbit);
  933. applog(LOG_DEBUG, "ntime: %s", ntime);
  934. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  935. }
  936. /* A notify message is the closest stratum gets to a getwork */
  937. pool->getwork_requested++;
  938. total_getworks++;
  939. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || pool->swork.transparency_time != (time_t)-1)
  940. {
  941. // Request transaction data to discourage pools from doing anything shady
  942. char s[1024];
  943. int sLen;
  944. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  945. pool->swork.job_id,
  946. pool->swork.job_id);
  947. stratum_send(pool, s, sLen);
  948. if ((!pool->swork.opaque) && pool->swork.transparency_time == (time_t)-1)
  949. pool->swork.transparency_time = time(NULL);
  950. pool->swork.transparency_probed = true;
  951. }
  952. return true;
  953. }
  954. static bool parse_diff(struct pool *pool, json_t *val)
  955. {
  956. double diff;
  957. diff = json_number_value(json_array_get(val, 0));
  958. if (diff == 0)
  959. return false;
  960. mutex_lock(&pool->pool_lock);
  961. pool->swork.diff = diff;
  962. mutex_unlock(&pool->pool_lock);
  963. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no, diff);
  964. return true;
  965. }
  966. static bool parse_reconnect(struct pool *pool, json_t *val)
  967. {
  968. char *url, *port, address[256];
  969. memset(address, 0, 255);
  970. url = (char *)json_string_value(json_array_get(val, 0));
  971. if (!url)
  972. url = pool->sockaddr_url;
  973. port = (char *)json_string_value(json_array_get(val, 1));
  974. if (!port)
  975. port = pool->stratum_port;
  976. sprintf(address, "%s:%s", url, port);
  977. if (!extract_sockaddr(pool, address))
  978. return false;
  979. pool->stratum_url = pool->sockaddr_url;
  980. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  981. if (!initiate_stratum(pool) || !auth_stratum(pool))
  982. return false;
  983. return true;
  984. }
  985. static bool send_version(struct pool *pool, json_t *val)
  986. {
  987. char s[RBUFSIZE];
  988. int id = json_integer_value(json_object_get(val, "id"));
  989. if (!id)
  990. return false;
  991. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  992. if (!stratum_send(pool, s, strlen(s)))
  993. return false;
  994. return true;
  995. }
  996. bool parse_method(struct pool *pool, char *s)
  997. {
  998. json_t *val = NULL, *method, *err_val, *params;
  999. json_error_t err;
  1000. bool ret = false;
  1001. char *buf;
  1002. if (!s)
  1003. goto out;
  1004. val = JSON_LOADS(s, &err);
  1005. if (!val) {
  1006. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1007. goto out;
  1008. }
  1009. method = json_object_get(val, "method");
  1010. if (!method)
  1011. goto out;
  1012. err_val = json_object_get(val, "error");
  1013. params = json_object_get(val, "params");
  1014. if (err_val && !json_is_null(err_val)) {
  1015. char *ss;
  1016. if (err_val)
  1017. ss = json_dumps(err_val, JSON_INDENT(3));
  1018. else
  1019. ss = strdup("(unknown reason)");
  1020. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1021. free(ss);
  1022. goto out;
  1023. }
  1024. buf = (char *)json_string_value(method);
  1025. if (!buf)
  1026. goto out;
  1027. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  1028. ret = true;
  1029. goto out;
  1030. }
  1031. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1032. ret = true;
  1033. goto out;
  1034. }
  1035. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1036. ret = true;
  1037. goto out;
  1038. }
  1039. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1040. ret = true;
  1041. goto out;
  1042. }
  1043. out:
  1044. if (val)
  1045. json_decref(val);
  1046. return ret;
  1047. }
  1048. extern bool parse_stratum_response(struct pool *, char *s);
  1049. bool auth_stratum(struct pool *pool)
  1050. {
  1051. json_t *val = NULL, *res_val, *err_val;
  1052. char s[RBUFSIZE], *sret = NULL;
  1053. json_error_t err;
  1054. bool ret = false;
  1055. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1056. pool->rpc_user, pool->rpc_pass);
  1057. if (!stratum_send(pool, s, strlen(s)))
  1058. goto out;
  1059. /* Parse all data in the queue and anything left should be auth */
  1060. while (42) {
  1061. sret = recv_line(pool);
  1062. if (!sret)
  1063. goto out;
  1064. if (parse_method(pool, sret))
  1065. free(sret);
  1066. else
  1067. break;
  1068. }
  1069. val = JSON_LOADS(sret, &err);
  1070. free(sret);
  1071. res_val = json_object_get(val, "result");
  1072. err_val = json_object_get(val, "error");
  1073. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1074. char *ss;
  1075. if (err_val)
  1076. ss = json_dumps(err_val, JSON_INDENT(3));
  1077. else
  1078. ss = strdup("(unknown reason)");
  1079. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1080. free(ss);
  1081. goto out;
  1082. }
  1083. ret = true;
  1084. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1085. out:
  1086. if (val)
  1087. json_decref(val);
  1088. return ret;
  1089. }
  1090. bool initiate_stratum(struct pool *pool)
  1091. {
  1092. json_t *val = NULL, *res_val, *err_val;
  1093. char curl_err_str[CURL_ERROR_SIZE];
  1094. char s[RBUFSIZE], *sret = NULL;
  1095. CURL *curl = NULL;
  1096. json_error_t err;
  1097. bool ret = false;
  1098. mutex_lock(&pool->stratum_lock);
  1099. pool->stratum_active = false;
  1100. pool->swork.transparency_probed = false;
  1101. if (!pool->stratum_curl) {
  1102. pool->stratum_curl = curl_easy_init();
  1103. if (unlikely(!pool->stratum_curl))
  1104. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1105. }
  1106. mutex_unlock(&pool->stratum_lock);
  1107. curl = pool->stratum_curl;
  1108. /* Create a http url for use with curl */
  1109. memset(s, 0, RBUFSIZE);
  1110. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1111. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1112. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1113. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1114. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1115. curl_easy_setopt(curl, CURLOPT_URL, s);
  1116. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1117. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1118. if (pool->rpc_proxy) {
  1119. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1120. } else if (opt_socks_proxy) {
  1121. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1122. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1123. }
  1124. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1125. if (curl_easy_perform(curl)) {
  1126. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1127. goto out;
  1128. }
  1129. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1130. keep_sockalive(pool->sock);
  1131. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1132. if (!__stratum_send(pool, s, strlen(s))) {
  1133. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1134. goto out;
  1135. }
  1136. if (!sock_full(pool, true)) {
  1137. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1138. goto out;
  1139. }
  1140. sret = recv_line(pool);
  1141. if (!sret)
  1142. goto out;
  1143. val = JSON_LOADS(sret, &err);
  1144. free(sret);
  1145. if (!val) {
  1146. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1147. goto out;
  1148. }
  1149. res_val = json_object_get(val, "result");
  1150. err_val = json_object_get(val, "error");
  1151. if (!res_val || json_is_null(res_val) ||
  1152. (err_val && !json_is_null(err_val))) {
  1153. char *ss;
  1154. if (err_val)
  1155. ss = json_dumps(err_val, JSON_INDENT(3));
  1156. else
  1157. ss = strdup("(unknown reason)");
  1158. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1159. free(ss);
  1160. goto out;
  1161. }
  1162. free(pool->nonce1);
  1163. pool->nonce1 = json_array_string(res_val, 1);
  1164. if (!pool->nonce1) {
  1165. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1166. goto out;
  1167. }
  1168. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1169. if (!pool->n2size) {
  1170. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1171. goto out;
  1172. }
  1173. ret = true;
  1174. out:
  1175. if (val)
  1176. json_decref(val);
  1177. if (ret) {
  1178. if (!pool->stratum_url)
  1179. pool->stratum_url = pool->sockaddr_url;
  1180. pool->stratum_active = true;
  1181. pool->swork.diff = 1;
  1182. if (opt_protocol) {
  1183. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1184. pool->pool_no, pool->nonce1, pool->n2size);
  1185. }
  1186. } else
  1187. applog(LOG_DEBUG, "Initiate stratum failed");
  1188. return ret;
  1189. }
  1190. void suspend_stratum(struct pool *pool)
  1191. {
  1192. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1193. mutex_lock(&pool->stratum_lock);
  1194. pool->stratum_active = false;
  1195. mutex_unlock(&pool->stratum_lock);
  1196. CLOSESOCKET(pool->sock);
  1197. }
  1198. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1199. {
  1200. dev->device_last_not_well = time(NULL);
  1201. dev->device_not_well_reason = reason;
  1202. switch (reason) {
  1203. case REASON_THREAD_FAIL_INIT:
  1204. dev->thread_fail_init_count++;
  1205. break;
  1206. case REASON_THREAD_ZERO_HASH:
  1207. dev->thread_zero_hash_count++;
  1208. break;
  1209. case REASON_THREAD_FAIL_QUEUE:
  1210. dev->thread_fail_queue_count++;
  1211. break;
  1212. case REASON_DEV_SICK_IDLE_60:
  1213. dev->dev_sick_idle_60_count++;
  1214. break;
  1215. case REASON_DEV_DEAD_IDLE_600:
  1216. dev->dev_dead_idle_600_count++;
  1217. break;
  1218. case REASON_DEV_NOSTART:
  1219. dev->dev_nostart_count++;
  1220. break;
  1221. case REASON_DEV_OVER_HEAT:
  1222. dev->dev_over_heat_count++;
  1223. break;
  1224. case REASON_DEV_THERMAL_CUTOFF:
  1225. dev->dev_thermal_cutoff_count++;
  1226. break;
  1227. case REASON_DEV_COMMS_ERROR:
  1228. dev->dev_comms_error_count++;
  1229. break;
  1230. case REASON_DEV_THROTTLE:
  1231. dev->dev_throttle_count++;
  1232. break;
  1233. }
  1234. }
  1235. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1236. void *realloc_strcat(char *ptr, char *s)
  1237. {
  1238. size_t old = strlen(ptr), len = strlen(s);
  1239. char *ret;
  1240. if (!len)
  1241. return ptr;
  1242. len += old + 1;
  1243. if (len % 4)
  1244. len += 4 - (len % 4);
  1245. ret = malloc(len);
  1246. if (unlikely(!ret))
  1247. quit(1, "Failed to malloc in realloc_strcat");
  1248. sprintf(ret, "%s%s", ptr, s);
  1249. free(ptr);
  1250. return ret;
  1251. }
  1252. void RenameThread(const char* name)
  1253. {
  1254. #if defined(PR_SET_NAME)
  1255. // Only the first 15 characters are used (16 - NUL terminator)
  1256. prctl(PR_SET_NAME, name, 0, 0, 0);
  1257. #elif defined(__APPLE__)
  1258. pthread_setname_np(name);
  1259. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1260. pthread_set_name_np(pthread_self(), name);
  1261. #else
  1262. // Prevent warnings for unused parameters...
  1263. (void)name;
  1264. #endif
  1265. }