util.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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. #else
  37. # include <winsock2.h>
  38. # include <mstcpip.h>
  39. #endif
  40. #include <netdb.h>
  41. #include "miner.h"
  42. #include "elist.h"
  43. #include "compat.h"
  44. #include "util.h"
  45. bool successful_connect = false;
  46. struct timeval nettime;
  47. struct data_buffer {
  48. void *buf;
  49. size_t len;
  50. curl_socket_t *idlemarker;
  51. };
  52. struct upload_buffer {
  53. const void *buf;
  54. size_t len;
  55. };
  56. struct header_info {
  57. char *lp_path;
  58. int rolltime;
  59. char *reason;
  60. char *stratum_url;
  61. bool hadrolltime;
  62. bool canroll;
  63. bool hadexpire;
  64. };
  65. struct tq_ent {
  66. void *data;
  67. struct list_head q_node;
  68. };
  69. static void databuf_free(struct data_buffer *db)
  70. {
  71. if (!db)
  72. return;
  73. free(db->buf);
  74. memset(db, 0, sizeof(*db));
  75. }
  76. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  77. void *user_data)
  78. {
  79. struct data_buffer *db = user_data;
  80. size_t len = size * nmemb;
  81. size_t oldlen, newlen;
  82. void *newmem;
  83. static const unsigned char zero = 0;
  84. if (db->idlemarker) {
  85. const unsigned char *cptr = ptr;
  86. for (size_t i = 0; i < len; ++i)
  87. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  88. *db->idlemarker = CURL_SOCKET_BAD;
  89. db->idlemarker = NULL;
  90. break;
  91. }
  92. }
  93. oldlen = db->len;
  94. newlen = oldlen + len;
  95. newmem = realloc(db->buf, newlen + 1);
  96. if (!newmem)
  97. return 0;
  98. db->buf = newmem;
  99. db->len = newlen;
  100. memcpy(db->buf + oldlen, ptr, len);
  101. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  102. return len;
  103. }
  104. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  105. void *user_data)
  106. {
  107. struct upload_buffer *ub = user_data;
  108. unsigned int len = size * nmemb;
  109. if (len > ub->len)
  110. len = ub->len;
  111. if (len) {
  112. memcpy(ptr, ub->buf, len);
  113. ub->buf += len;
  114. ub->len -= len;
  115. }
  116. return len;
  117. }
  118. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  119. {
  120. struct header_info *hi = user_data;
  121. size_t remlen, slen, ptrlen = size * nmemb;
  122. char *rem, *val = NULL, *key = NULL;
  123. void *tmp;
  124. val = calloc(1, ptrlen);
  125. key = calloc(1, ptrlen);
  126. if (!key || !val)
  127. goto out;
  128. tmp = memchr(ptr, ':', ptrlen);
  129. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  130. goto out;
  131. slen = tmp - ptr;
  132. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  133. goto out;
  134. memcpy(key, ptr, slen); /* store & nul term key */
  135. key[slen] = 0;
  136. rem = ptr + slen + 1; /* trim value's leading whitespace */
  137. remlen = ptrlen - slen - 1;
  138. while ((remlen > 0) && (isspace(*rem))) {
  139. remlen--;
  140. rem++;
  141. }
  142. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  143. val[remlen] = 0;
  144. while ((*val) && (isspace(val[strlen(val) - 1])))
  145. val[strlen(val) - 1] = 0;
  146. if (!*val) /* skip blank value */
  147. goto out;
  148. if (opt_protocol)
  149. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  150. if (!strcasecmp("X-Roll-Ntime", key)) {
  151. hi->hadrolltime = true;
  152. if (!strncasecmp("N", val, 1))
  153. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  154. else {
  155. hi->canroll = true;
  156. /* Check to see if expire= is supported and if not, set
  157. * the rolltime to the default scantime */
  158. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  159. sscanf(val + 7, "%d", &hi->rolltime);
  160. hi->hadexpire = true;
  161. } else
  162. hi->rolltime = opt_scantime;
  163. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  164. }
  165. }
  166. if (!strcasecmp("X-Long-Polling", key)) {
  167. hi->lp_path = val; /* steal memory reference */
  168. val = NULL;
  169. }
  170. if (!strcasecmp("X-Reject-Reason", key)) {
  171. hi->reason = val; /* steal memory reference */
  172. val = NULL;
  173. }
  174. if (!strcasecmp("X-Stratum", key)) {
  175. hi->stratum_url = val;
  176. val = NULL;
  177. }
  178. out:
  179. free(key);
  180. free(val);
  181. return ptrlen;
  182. }
  183. #ifdef CURL_HAS_SOCKOPT
  184. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  185. curlsocktype __maybe_unused purpose)
  186. {
  187. int tcp_keepidle = 120;
  188. int tcp_keepintvl = 120;
  189. #ifndef WIN32
  190. int keepalive = 1;
  191. int tcp_keepcnt = 5;
  192. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  193. return 1;
  194. # ifdef __linux
  195. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  196. return 1;
  197. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  198. return 1;
  199. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  200. return 1;
  201. # endif /* __linux */
  202. # ifdef __APPLE_CC__
  203. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  204. return 1;
  205. # endif /* __APPLE_CC__ */
  206. #else /* WIN32 */
  207. struct tcp_keepalive vals;
  208. vals.onoff = 1;
  209. vals.keepalivetime = tcp_keepidle * 1000;
  210. vals.keepaliveinterval = tcp_keepintvl * 1000;
  211. DWORD outputBytes;
  212. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  213. return 1;
  214. #endif /* WIN32 */
  215. return 0;
  216. }
  217. #endif
  218. static void last_nettime(struct timeval *last)
  219. {
  220. rd_lock(&netacc_lock);
  221. last->tv_sec = nettime.tv_sec;
  222. last->tv_usec = nettime.tv_usec;
  223. rd_unlock(&netacc_lock);
  224. }
  225. static void set_nettime(void)
  226. {
  227. wr_lock(&netacc_lock);
  228. gettimeofday(&nettime, NULL);
  229. wr_unlock(&netacc_lock);
  230. }
  231. json_t *json_rpc_call(CURL *curl, const char *url,
  232. const char *userpass, const char *rpc_req,
  233. bool probe, bool longpoll, int *rolltime,
  234. struct pool *pool, bool share)
  235. {
  236. long timeout = longpoll ? (60 * 60) : 60;
  237. struct data_buffer all_data = {NULL, 0, NULL};
  238. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  239. char len_hdr[64], user_agent_hdr[128];
  240. char curl_err_str[CURL_ERROR_SIZE];
  241. struct curl_slist *headers = NULL;
  242. struct upload_buffer upload_data;
  243. json_t *val, *err_val, *res_val;
  244. bool probing = false;
  245. json_error_t err;
  246. int rc;
  247. memset(&err, 0, sizeof(err));
  248. if (longpoll)
  249. all_data.idlemarker = &pool->lp_socket;
  250. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  251. if (probe)
  252. probing = !pool->probed;
  253. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  254. #if 0 /* Disable curl debugging since it spews to stderr */
  255. if (opt_protocol)
  256. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  257. #endif
  258. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  259. curl_easy_setopt(curl, CURLOPT_URL, url);
  260. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  261. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  262. /* Shares are staggered already and delays in submission can be costly
  263. * so do not delay them */
  264. if (!opt_delaynet || share)
  265. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  266. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  267. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  268. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  269. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  270. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  271. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  272. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  273. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  274. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  275. if (pool->rpc_proxy) {
  276. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  277. } else if (opt_socks_proxy) {
  278. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  279. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  280. }
  281. if (userpass) {
  282. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  283. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  284. }
  285. #ifdef CURL_HAS_SOCKOPT
  286. if (longpoll)
  287. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  288. #endif
  289. curl_easy_setopt(curl, CURLOPT_POST, 1);
  290. if (opt_protocol)
  291. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  292. upload_data.buf = rpc_req;
  293. upload_data.len = strlen(rpc_req);
  294. sprintf(len_hdr, "Content-Length: %lu",
  295. (unsigned long) upload_data.len);
  296. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  297. headers = curl_slist_append(headers,
  298. "Content-type: application/json");
  299. headers = curl_slist_append(headers,
  300. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  301. if (longpoll)
  302. headers = curl_slist_append(headers,
  303. "X-Minimum-Wait: 0");
  304. if (likely(global_hashrate)) {
  305. char ghashrate[255];
  306. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  307. headers = curl_slist_append(headers, ghashrate);
  308. }
  309. headers = curl_slist_append(headers, len_hdr);
  310. headers = curl_slist_append(headers, user_agent_hdr);
  311. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  312. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  313. if (opt_delaynet) {
  314. /* Don't delay share submission, but still track the nettime */
  315. if (!share) {
  316. long long now_msecs, last_msecs;
  317. struct timeval now, last;
  318. gettimeofday(&now, NULL);
  319. last_nettime(&last);
  320. now_msecs = (long long)now.tv_sec * 1000;
  321. now_msecs += now.tv_usec / 1000;
  322. last_msecs = (long long)last.tv_sec * 1000;
  323. last_msecs += last.tv_usec / 1000;
  324. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  325. struct timespec rgtp;
  326. rgtp.tv_sec = 0;
  327. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  328. nanosleep(&rgtp, NULL);
  329. }
  330. }
  331. set_nettime();
  332. }
  333. rc = curl_easy_perform(curl);
  334. if (rc) {
  335. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  336. goto err_out;
  337. }
  338. if (!all_data.buf) {
  339. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  340. goto err_out;
  341. }
  342. if (probing) {
  343. pool->probed = true;
  344. /* If X-Long-Polling was found, activate long polling */
  345. if (hi.lp_path) {
  346. if (pool->hdr_path != NULL)
  347. free(pool->hdr_path);
  348. pool->hdr_path = hi.lp_path;
  349. } else
  350. pool->hdr_path = NULL;
  351. if (hi.stratum_url) {
  352. pool->stratum_url = hi.stratum_url;
  353. hi.stratum_url = NULL;
  354. }
  355. } else {
  356. if (hi.lp_path) {
  357. free(hi.lp_path);
  358. hi.lp_path = NULL;
  359. }
  360. if (hi.stratum_url) {
  361. free(hi.stratum_url);
  362. hi.stratum_url = NULL;
  363. }
  364. }
  365. *rolltime = hi.rolltime;
  366. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  367. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  368. pool->cgminer_pool_stats.canroll = hi.canroll;
  369. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  370. val = JSON_LOADS(all_data.buf, &err);
  371. if (!val) {
  372. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  373. if (opt_protocol)
  374. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  375. goto err_out;
  376. }
  377. if (opt_protocol) {
  378. char *s = json_dumps(val, JSON_INDENT(3));
  379. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  380. free(s);
  381. }
  382. /* JSON-RPC valid response returns a non-null 'result',
  383. * and a null 'error'.
  384. */
  385. res_val = json_object_get(val, "result");
  386. err_val = json_object_get(val, "error");
  387. if (!res_val ||
  388. (err_val && !json_is_null(err_val))) {
  389. char *s;
  390. if (err_val)
  391. s = json_dumps(err_val, JSON_INDENT(3));
  392. else
  393. s = strdup("(unknown reason)");
  394. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  395. free(s);
  396. goto err_out;
  397. }
  398. if (hi.reason) {
  399. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  400. free(hi.reason);
  401. hi.reason = NULL;
  402. }
  403. successful_connect = true;
  404. databuf_free(&all_data);
  405. curl_slist_free_all(headers);
  406. curl_easy_reset(curl);
  407. return val;
  408. err_out:
  409. databuf_free(&all_data);
  410. curl_slist_free_all(headers);
  411. curl_easy_reset(curl);
  412. if (!successful_connect)
  413. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  414. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  415. return NULL;
  416. }
  417. bool our_curl_supports_proxy_uris()
  418. {
  419. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  420. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  421. }
  422. char *bin2hex(const unsigned char *p, size_t len)
  423. {
  424. char *s = malloc((len * 2) + 1);
  425. unsigned int i;
  426. if (!s)
  427. return NULL;
  428. for (i = 0; i < len; i++)
  429. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  430. return s;
  431. }
  432. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  433. {
  434. while (*hexstr && len) {
  435. char hex_byte[3];
  436. unsigned int v;
  437. if (!hexstr[1]) {
  438. applog(LOG_ERR, "hex2bin str truncated");
  439. return false;
  440. }
  441. hex_byte[0] = hexstr[0];
  442. hex_byte[1] = hexstr[1];
  443. hex_byte[2] = 0;
  444. if (sscanf(hex_byte, "%x", &v) != 1) {
  445. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  446. return false;
  447. }
  448. *p = (unsigned char) v;
  449. p++;
  450. hexstr += 2;
  451. len--;
  452. }
  453. return (len == 0 && *hexstr == 0) ? true : false;
  454. }
  455. bool fulltest(const unsigned char *hash, const unsigned char *target)
  456. {
  457. unsigned char hash_swap[32], target_swap[32];
  458. uint32_t *hash32 = (uint32_t *) hash_swap;
  459. uint32_t *target32 = (uint32_t *) target_swap;
  460. char *hash_str, *target_str;
  461. bool rc = true;
  462. int i;
  463. swap256(hash_swap, hash);
  464. swap256(target_swap, target);
  465. for (i = 0; i < 32/4; i++) {
  466. uint32_t h32tmp = swab32(hash32[i]);
  467. uint32_t t32tmp = target32[i];
  468. target32[i] = swab32(target32[i]); /* for printing */
  469. if (h32tmp > t32tmp) {
  470. rc = false;
  471. break;
  472. }
  473. if (h32tmp < t32tmp) {
  474. rc = true;
  475. break;
  476. }
  477. }
  478. if (opt_debug) {
  479. hash_str = bin2hex(hash_swap, 32);
  480. target_str = bin2hex(target_swap, 32);
  481. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  482. hash_str,
  483. target_str,
  484. rc ? "YES (hash < target)" :
  485. "no (false positive; hash > target)");
  486. free(hash_str);
  487. free(target_str);
  488. }
  489. return rc;
  490. }
  491. struct thread_q *tq_new(void)
  492. {
  493. struct thread_q *tq;
  494. tq = calloc(1, sizeof(*tq));
  495. if (!tq)
  496. return NULL;
  497. INIT_LIST_HEAD(&tq->q);
  498. pthread_mutex_init(&tq->mutex, NULL);
  499. pthread_cond_init(&tq->cond, NULL);
  500. return tq;
  501. }
  502. void tq_free(struct thread_q *tq)
  503. {
  504. struct tq_ent *ent, *iter;
  505. if (!tq)
  506. return;
  507. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  508. list_del(&ent->q_node);
  509. free(ent);
  510. }
  511. pthread_cond_destroy(&tq->cond);
  512. pthread_mutex_destroy(&tq->mutex);
  513. memset(tq, 0, sizeof(*tq)); /* poison */
  514. free(tq);
  515. }
  516. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  517. {
  518. mutex_lock(&tq->mutex);
  519. tq->frozen = frozen;
  520. pthread_cond_signal(&tq->cond);
  521. mutex_unlock(&tq->mutex);
  522. }
  523. void tq_freeze(struct thread_q *tq)
  524. {
  525. tq_freezethaw(tq, true);
  526. }
  527. void tq_thaw(struct thread_q *tq)
  528. {
  529. tq_freezethaw(tq, false);
  530. }
  531. bool tq_push(struct thread_q *tq, void *data)
  532. {
  533. struct tq_ent *ent;
  534. bool rc = true;
  535. ent = calloc(1, sizeof(*ent));
  536. if (!ent)
  537. return false;
  538. ent->data = data;
  539. INIT_LIST_HEAD(&ent->q_node);
  540. mutex_lock(&tq->mutex);
  541. if (!tq->frozen) {
  542. list_add_tail(&ent->q_node, &tq->q);
  543. } else {
  544. free(ent);
  545. rc = false;
  546. }
  547. pthread_cond_signal(&tq->cond);
  548. mutex_unlock(&tq->mutex);
  549. return rc;
  550. }
  551. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  552. {
  553. struct tq_ent *ent;
  554. void *rval = NULL;
  555. int rc;
  556. mutex_lock(&tq->mutex);
  557. if (!list_empty(&tq->q))
  558. goto pop;
  559. if (abstime)
  560. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  561. else
  562. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  563. if (rc)
  564. goto out;
  565. if (list_empty(&tq->q))
  566. goto out;
  567. pop:
  568. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  569. rval = ent->data;
  570. list_del(&ent->q_node);
  571. free(ent);
  572. out:
  573. mutex_unlock(&tq->mutex);
  574. return rval;
  575. }
  576. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  577. {
  578. return pthread_create(&thr->pth, attr, start, arg);
  579. }
  580. void thr_info_freeze(struct thr_info *thr)
  581. {
  582. struct tq_ent *ent, *iter;
  583. struct thread_q *tq;
  584. if (!thr)
  585. return;
  586. tq = thr->q;
  587. if (!tq)
  588. return;
  589. mutex_lock(&tq->mutex);
  590. tq->frozen = true;
  591. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  592. list_del(&ent->q_node);
  593. free(ent);
  594. }
  595. mutex_unlock(&tq->mutex);
  596. }
  597. void thr_info_cancel(struct thr_info *thr)
  598. {
  599. if (!thr)
  600. return;
  601. if (PTH(thr) != 0L) {
  602. pthread_cancel(thr->pth);
  603. PTH(thr) = 0L;
  604. }
  605. }
  606. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  607. * on SMP machines */
  608. void nmsleep(unsigned int msecs)
  609. {
  610. struct timespec twait, tleft;
  611. int ret;
  612. ldiv_t d;
  613. d = ldiv(msecs, 1000);
  614. tleft.tv_sec = d.quot;
  615. tleft.tv_nsec = d.rem * 1000000;
  616. do {
  617. twait.tv_sec = tleft.tv_sec;
  618. twait.tv_nsec = tleft.tv_nsec;
  619. ret = nanosleep(&twait, &tleft);
  620. } while (ret == -1 && errno == EINTR);
  621. }
  622. void rename_thr(const char* name) {
  623. #if defined(PR_SET_NAME)
  624. // Only the first 15 characters are used (16 - NUL terminator)
  625. prctl(PR_SET_NAME, name, 0, 0, 0);
  626. #elif defined(__APPLE__)
  627. pthread_setname_np(name);
  628. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  629. pthread_set_name_np(pthread_self(), name);
  630. #else
  631. // Prevent warnings for unused parameters...
  632. (void)name;
  633. #endif
  634. }
  635. /* Returns the seconds difference between end and start times as a double */
  636. double tdiff(struct timeval *end, struct timeval *start)
  637. {
  638. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  639. }
  640. bool extract_sockaddr(struct pool *pool, char *url)
  641. {
  642. char *url_begin, *url_end, *port_start = NULL;
  643. char *url_address, *port;
  644. struct addrinfo hints, *res;
  645. int url_len, port_len = 0;
  646. url_begin = strstr(url, "//");
  647. if (!url_begin)
  648. url_begin = url;
  649. else
  650. url_begin += 2;
  651. url_end = strstr(url_begin, ":");
  652. if (url_end) {
  653. url_len = url_end - url_begin;
  654. port_len = strlen(url_begin) - url_len - 1;
  655. if (port_len < 1)
  656. return false;
  657. port_start = url_end + 1;
  658. } else
  659. url_len = strlen(url_begin);
  660. if (url_len < 1)
  661. return false;
  662. url_address = alloca(url_len + 1);
  663. sprintf(url_address, "%.*s", url_len, url_begin);
  664. if (port_len) {
  665. port = alloca(port_len + 1);
  666. sprintf(port, "%.*s", port_len, port_start);
  667. } else {
  668. port = alloca(4);
  669. strcpy(port, "80");
  670. }
  671. memset(&hints, 0, sizeof(struct addrinfo));
  672. hints.ai_family = AF_UNSPEC;
  673. hints.ai_socktype = SOCK_STREAM;
  674. hints.ai_protocol = IPPROTO_TCP;
  675. if (getaddrinfo(url_address, port, &hints, &res)) {
  676. applog(LOG_DEBUG, "Failed to extract sock addr");
  677. return false;
  678. }
  679. pool->server = (struct sockaddr_in *)res->ai_addr;
  680. pool->sockaddr_url = strdup(url_address);
  681. return true;
  682. }
  683. /* Send a single command across a socket, appending \n to it */
  684. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  685. {
  686. SOCKETTYPE sock = pool->sock;
  687. ssize_t sent = 0;
  688. bool ret = false;
  689. if (opt_protocol)
  690. applog(LOG_DEBUG, "SEND: %s", s);
  691. strcat(s, "\n");
  692. len++;
  693. mutex_lock(&pool->pool_lock);
  694. while (len > 0 ) {
  695. sent = send(sock, s + sent, len, 0);
  696. if (SOCKETFAIL(sent)) {
  697. ret = false;
  698. goto out_unlock;
  699. }
  700. len -= sent;
  701. }
  702. ret = true;
  703. fsync(sock);
  704. out_unlock:
  705. mutex_unlock(&pool->pool_lock);
  706. return ret;;
  707. }
  708. #define RECVSIZE 8191
  709. static void clear_sock(SOCKETTYPE sock)
  710. {
  711. char *s = alloca(RECVSIZE);
  712. recv(sock, s, RECVSIZE, MSG_DONTWAIT);
  713. }
  714. /* Check to see if Santa's been good to you */
  715. static bool sock_full(SOCKETTYPE sock, bool wait)
  716. {
  717. struct timeval timeout;
  718. fd_set rd;
  719. FD_ZERO(&rd);
  720. FD_SET(sock, &rd);
  721. timeout.tv_usec = 0;
  722. if (wait)
  723. timeout.tv_sec = 60;
  724. else
  725. timeout.tv_sec = 0;
  726. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  727. return true;
  728. return false;
  729. }
  730. /* Peeks at a socket to find the first end of line and then reads just that
  731. * from the socket and returns that as a malloced char */
  732. char *recv_line(SOCKETTYPE sock)
  733. {
  734. char *sret = NULL, *s, c;
  735. ssize_t offset = 0;
  736. s = alloca(RECVSIZE + 1);
  737. if (SOCKETFAIL(recv(sock, s, RECVSIZE, MSG_PEEK))) {
  738. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  739. goto out;
  740. }
  741. sret = strtok(s, "\n");
  742. if (!sret) {
  743. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  744. goto out;
  745. }
  746. do {
  747. read(sock, &c, 1);
  748. memcpy(s + offset++, &c, 1);
  749. } while (strncmp(&c, "\n", 1));
  750. sret = strdup(s);
  751. strcpy(sret + offset - 1, "\0");
  752. out:
  753. if (!sret)
  754. clear_sock(sock);
  755. else if (opt_protocol)
  756. applog(LOG_DEBUG, "RECVD: %s", sret);
  757. return sret;
  758. }
  759. /* Extracts a string value from a json array with error checking. To be used
  760. * when the value of the string returned is only examined and not to be stored.
  761. * See json_array_string below */
  762. static char *__json_array_string(json_t *val, unsigned int entry)
  763. {
  764. json_t *arr_entry;
  765. if (json_is_null(val))
  766. return NULL;
  767. if (!json_is_array(val))
  768. return NULL;
  769. if (entry > json_array_size(val))
  770. return NULL;
  771. arr_entry = json_array_get(val, entry);
  772. if (!json_is_string(arr_entry))
  773. return NULL;
  774. return (char *)json_string_value(arr_entry);
  775. }
  776. /* Creates a freshly malloced dup of __json_array_string */
  777. static char *json_array_string(json_t *val, unsigned int entry)
  778. {
  779. char *buf = __json_array_string(val, entry);
  780. if (buf)
  781. return strdup(buf);
  782. return NULL;
  783. }
  784. static bool parse_notify(struct pool *pool, json_t *val)
  785. {
  786. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  787. int merkles, i;
  788. json_t *arr;
  789. bool clean;
  790. arr = json_array_get(val, 4);
  791. if (!arr || !json_is_array(arr))
  792. return false;
  793. merkles = json_array_size(arr);
  794. job_id = json_array_string(val, 0);
  795. prev_hash = json_array_string(val, 1);
  796. coinbase1 = json_array_string(val, 2);
  797. coinbase2 = json_array_string(val, 3);
  798. bbversion = json_array_string(val, 5);
  799. nbit = json_array_string(val, 6);
  800. ntime = json_array_string(val, 7);
  801. clean = json_is_true(json_array_get(val, 8));
  802. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  803. /* Annoying but we must not leak memory */
  804. if (job_id)
  805. free(job_id);
  806. if (prev_hash)
  807. free(prev_hash);
  808. if (coinbase1)
  809. free(coinbase1);
  810. if (coinbase2)
  811. free(coinbase2);
  812. if (bbversion)
  813. free(bbversion);
  814. if (nbit)
  815. free(nbit);
  816. if (ntime)
  817. free(ntime);
  818. return false;
  819. }
  820. mutex_lock(&pool->pool_lock);
  821. pool->swork.job_id = job_id;
  822. pool->swork.prev_hash = prev_hash;
  823. pool->swork.coinbase1 = coinbase1;
  824. pool->swork.coinbase2 = coinbase2;
  825. pool->swork.bbversion = bbversion;
  826. pool->swork.nbit = nbit;
  827. pool->swork.ntime = ntime;
  828. pool->swork.clean = clean;
  829. for (i = 0; i < pool->swork.merkles; i++)
  830. free(pool->swork.merkle[i]);
  831. if (merkles) {
  832. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  833. for (i = 0; i < merkles; i++)
  834. pool->swork.merkle[i] = json_array_string(arr, i);
  835. }
  836. pool->swork.merkles = merkles;
  837. if (clean)
  838. pool->nonce2 = 0;
  839. mutex_unlock(&pool->pool_lock);
  840. if (opt_protocol) {
  841. applog(LOG_DEBUG, "job_id: %s", job_id);
  842. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  843. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  844. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  845. for (i = 0; i < merkles; i++)
  846. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  847. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  848. applog(LOG_DEBUG, "nbit: %s", nbit);
  849. applog(LOG_DEBUG, "ntime: %s", ntime);
  850. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  851. }
  852. /* A notify message is the closest stratum gets to a getwork */
  853. pool->getwork_requested++;
  854. total_getworks++;
  855. return true;
  856. }
  857. static bool parse_diff(struct pool *pool, json_t *val)
  858. {
  859. int diff;
  860. diff = json_integer_value(json_array_get(val, 0));
  861. if (diff < 1)
  862. return false;
  863. mutex_lock(&pool->pool_lock);
  864. pool->swork.diff = diff;
  865. mutex_unlock(&pool->pool_lock);
  866. applog(LOG_DEBUG, "Pool %d difficulty set to %d", pool->pool_no, diff);
  867. return true;
  868. }
  869. bool parse_method(struct pool *pool, char *s)
  870. {
  871. json_t *val = NULL, *method, *err_val, *params;
  872. json_error_t err;
  873. bool ret = false;
  874. char *buf;
  875. val = JSON_LOADS(s, &err);
  876. if (!val) {
  877. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  878. goto out;
  879. }
  880. method = json_object_get(val, "method");
  881. if (!method)
  882. goto out;
  883. err_val = json_object_get(val, "error");
  884. params = json_object_get(val, "params");
  885. if (err_val && !json_is_null(err_val)) {
  886. char *ss;
  887. if (err_val)
  888. ss = json_dumps(err_val, JSON_INDENT(3));
  889. else
  890. ss = strdup("(unknown reason)");
  891. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  892. free(ss);
  893. goto out;
  894. }
  895. buf = (char *)json_string_value(method);
  896. if (!buf)
  897. goto out;
  898. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  899. ret = true;
  900. goto out;
  901. }
  902. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  903. ret = true;
  904. goto out;
  905. }
  906. out:
  907. if (val)
  908. json_decref(val);
  909. return ret;
  910. }
  911. bool auth_stratum(struct pool *pool)
  912. {
  913. json_t *val = NULL, *res_val, *err_val;
  914. char *s, *sret = NULL;
  915. json_error_t err;
  916. bool ret = false;
  917. s = alloca(RECVSIZE + 1);
  918. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  919. swork_id++, pool->rpc_user, pool->rpc_pass);
  920. /* Parse all data prior sending auth request */
  921. while (sock_full(pool->sock, false)) {
  922. sret = recv_line(pool->sock);
  923. if (!parse_method(pool, sret)) {
  924. clear_sock(pool->sock);
  925. applog(LOG_WARNING, "Failed to parse stratum buffer");
  926. free(sret);
  927. return ret;
  928. }
  929. free(sret);
  930. }
  931. if (!stratum_send(pool, s, strlen(s)))
  932. goto out;
  933. sret = recv_line(pool->sock);
  934. if (!sret)
  935. goto out;
  936. val = JSON_LOADS(sret, &err);
  937. free(sret);
  938. res_val = json_object_get(val, "result");
  939. err_val = json_object_get(val, "error");
  940. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  941. char *ss;
  942. if (err_val)
  943. ss = json_dumps(err_val, JSON_INDENT(3));
  944. else
  945. ss = strdup("(unknown reason)");
  946. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  947. free(ss);
  948. goto out;
  949. }
  950. ret = true;
  951. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  952. out:
  953. if (val)
  954. json_decref(val);
  955. pool->stratum_auth = ret;
  956. return ret;
  957. }
  958. bool initiate_stratum(struct pool *pool)
  959. {
  960. json_t *val = NULL, *res_val, *err_val;
  961. char *s, *sret = NULL;
  962. json_error_t err;
  963. bool ret = false;
  964. if (pool->stratum_active)
  965. return true;
  966. s = alloca(RECVSIZE + 1);
  967. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  968. pool->sock = socket(AF_INET, SOCK_STREAM, 0);
  969. if (pool->sock == INVSOCK)
  970. quit(1, "Failed to create pool socket in initiate_stratum");
  971. if (SOCKETFAIL(connect(pool->sock, (struct sockaddr *)pool->server, sizeof(struct sockaddr)))) {
  972. applog(LOG_DEBUG, "Failed to connect socket to pool");
  973. goto out;
  974. }
  975. if (!stratum_send(pool, s, strlen(s))) {
  976. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  977. goto out;
  978. }
  979. if (!sock_full(pool->sock, true)) {
  980. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  981. goto out;
  982. }
  983. sret = recv_line(pool->sock);
  984. if (!sret)
  985. goto out;
  986. val = JSON_LOADS(sret, &err);
  987. free(sret);
  988. if (!val) {
  989. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  990. goto out;
  991. }
  992. res_val = json_object_get(val, "result");
  993. err_val = json_object_get(val, "error");
  994. if (!res_val || json_is_null(res_val) ||
  995. (err_val && !json_is_null(err_val))) {
  996. char *ss;
  997. if (err_val)
  998. ss = json_dumps(err_val, JSON_INDENT(3));
  999. else
  1000. ss = strdup("(unknown reason)");
  1001. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1002. free(ss);
  1003. goto out;
  1004. }
  1005. pool->nonce1 = json_array_string(res_val, 1);
  1006. if (!pool->nonce1) {
  1007. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1008. goto out;
  1009. }
  1010. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1011. if (!pool->n2size) {
  1012. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1013. goto out;
  1014. }
  1015. ret = true;
  1016. out:
  1017. if (val)
  1018. json_decref(val);
  1019. if (ret) {
  1020. pool->stratum_url = pool->sockaddr_url;
  1021. pool->stratum_active = true;
  1022. pool->swork.diff = 1;
  1023. if (opt_protocol) {
  1024. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1025. pool->pool_no, pool->nonce1, pool->n2size);
  1026. }
  1027. } else
  1028. CLOSESOCKET(pool->sock);
  1029. return ret;
  1030. }