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