util.c 37 KB

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