util.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #define _GNU_SOURCE
  11. #include "config.h"
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <ctype.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include <jansson.h>
  18. #include <curl/curl.h>
  19. #include <time.h>
  20. #include <curses.h>
  21. #include <errno.h>
  22. #include <unistd.h>
  23. #include "miner.h"
  24. #include "elist.h"
  25. #if JANSSON_MAJOR_VERSION >= 2
  26. #define JSON_LOADS(str, err_ptr) json_loads((str), 0, (err_ptr))
  27. #else
  28. #define JSON_LOADS(str, err_ptr) json_loads((str), (err_ptr))
  29. #endif
  30. bool successful_connect = false;
  31. bool test_and_set(bool *var)
  32. {
  33. bool ret;
  34. pthread_mutex_lock(&control_lock);
  35. ret = *var;
  36. *var = true;
  37. pthread_mutex_unlock(&control_lock);
  38. return ret;
  39. }
  40. bool test_and_clear(bool *var)
  41. {
  42. bool ret;
  43. pthread_mutex_lock(&control_lock);
  44. ret = *var;
  45. *var = false;
  46. pthread_mutex_unlock(&control_lock);
  47. return ret;
  48. }
  49. struct data_buffer {
  50. void *buf;
  51. size_t len;
  52. };
  53. struct upload_buffer {
  54. const void *buf;
  55. size_t len;
  56. };
  57. struct header_info {
  58. char *lp_path;
  59. bool has_rolltime;
  60. };
  61. struct tq_ent {
  62. void *data;
  63. struct list_head q_node;
  64. };
  65. struct thread_q {
  66. struct list_head q;
  67. bool frozen;
  68. pthread_mutex_t mutex;
  69. pthread_cond_t cond;
  70. };
  71. void vapplog(int prio, const char *fmt, va_list ap)
  72. {
  73. #ifdef HAVE_SYSLOG_H
  74. if (use_syslog) {
  75. vsyslog(prio, fmt, ap);
  76. }
  77. #else
  78. if (0) {}
  79. #endif
  80. else if (opt_log_output || prio == LOG_WARNING || prio == LOG_ERR) {
  81. char *f;
  82. int len;
  83. struct timeval tv = { };
  84. struct tm tm;
  85. gettimeofday(&tv, NULL);
  86. localtime_r(&tv.tv_sec, &tm);
  87. len = 40 + strlen(fmt) + 22;
  88. f = alloca(len);
  89. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d] %s \n",
  90. tm.tm_year + 1900,
  91. tm.tm_mon + 1,
  92. tm.tm_mday,
  93. tm.tm_hour,
  94. tm.tm_min,
  95. tm.tm_sec,
  96. fmt);
  97. /* Only output to stderr if it's not going to the screen as well */
  98. if (opt_log_output && !isatty(fileno((FILE *)stderr))) {
  99. va_list apc;
  100. va_copy(apc, ap);
  101. vfprintf(stderr, f, apc); /* atomic write to stderr */
  102. fflush(stderr);
  103. }
  104. log_curses(f, ap);
  105. }
  106. }
  107. void applog(int prio, const char *fmt, ...)
  108. {
  109. va_list ap;
  110. va_start(ap, fmt);
  111. vapplog(prio, fmt, ap);
  112. va_end(ap);
  113. }
  114. static void databuf_free(struct data_buffer *db)
  115. {
  116. if (!db)
  117. return;
  118. free(db->buf);
  119. memset(db, 0, sizeof(*db));
  120. }
  121. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  122. void *user_data)
  123. {
  124. struct data_buffer *db = user_data;
  125. size_t len = size * nmemb;
  126. size_t oldlen, newlen;
  127. void *newmem;
  128. static const unsigned char zero = 0;
  129. oldlen = db->len;
  130. newlen = oldlen + len;
  131. newmem = realloc(db->buf, newlen + 1);
  132. if (!newmem)
  133. return 0;
  134. db->buf = newmem;
  135. db->len = newlen;
  136. memcpy(db->buf + oldlen, ptr, len);
  137. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  138. return len;
  139. }
  140. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  141. void *user_data)
  142. {
  143. struct upload_buffer *ub = user_data;
  144. int len = size * nmemb;
  145. if (len > ub->len)
  146. len = ub->len;
  147. if (len) {
  148. memcpy(ptr, ub->buf, len);
  149. ub->buf += len;
  150. ub->len -= len;
  151. }
  152. return len;
  153. }
  154. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  155. {
  156. struct header_info *hi = user_data;
  157. size_t remlen, slen, ptrlen = size * nmemb;
  158. char *rem, *val = NULL, *key = NULL;
  159. void *tmp;
  160. val = calloc(1, ptrlen);
  161. key = calloc(1, ptrlen);
  162. if (!key || !val)
  163. goto out;
  164. tmp = memchr(ptr, ':', ptrlen);
  165. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  166. goto out;
  167. slen = tmp - ptr;
  168. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  169. goto out;
  170. memcpy(key, ptr, slen); /* store & nul term key */
  171. key[slen] = 0;
  172. rem = ptr + slen + 1; /* trim value's leading whitespace */
  173. remlen = ptrlen - slen - 1;
  174. while ((remlen > 0) && (isspace(*rem))) {
  175. remlen--;
  176. rem++;
  177. }
  178. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  179. val[remlen] = 0;
  180. while ((*val) && (isspace(val[strlen(val) - 1]))) {
  181. val[strlen(val) - 1] = 0;
  182. }
  183. if (!*val) /* skip blank value */
  184. goto out;
  185. if (opt_protocol)
  186. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  187. if (!strcasecmp("X-Roll-Ntime", key)) {
  188. applog(LOG_INFO, "X-Roll-Ntime found");
  189. hi->has_rolltime = true;
  190. }
  191. if (!strcasecmp("X-Long-Polling", key)) {
  192. hi->lp_path = val; /* steal memory reference */
  193. val = NULL;
  194. }
  195. out:
  196. free(key);
  197. free(val);
  198. return ptrlen;
  199. }
  200. static bool comms_error = false;
  201. json_t *json_rpc_call(CURL *curl, const char *url,
  202. const char *userpass, const char *rpc_req,
  203. bool probe, bool longpoll,
  204. struct pool *pool)
  205. {
  206. json_t *val, *err_val, *res_val;
  207. int rc;
  208. struct data_buffer all_data = { };
  209. struct upload_buffer upload_data;
  210. json_error_t err = { };
  211. struct curl_slist *headers = NULL;
  212. char len_hdr[64], user_agent_hdr[128];
  213. char curl_err_str[CURL_ERROR_SIZE];
  214. struct header_info hi = { };
  215. bool probing = false;
  216. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  217. if (probe)
  218. probing = ((want_longpoll && !have_longpoll) || !pool->probed);
  219. if (opt_protocol)
  220. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  221. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  222. curl_easy_setopt(curl, CURLOPT_URL, url);
  223. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  224. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  225. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  226. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  227. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  228. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  229. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  230. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  231. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  232. if (probing) {
  233. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  234. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  235. }
  236. if (userpass) {
  237. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  238. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  239. }
  240. if (longpoll)
  241. curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
  242. else
  243. curl_easy_setopt(curl, CURLOPT_POST, 1);
  244. if (opt_protocol)
  245. applog(LOG_DEBUG, "JSON protocol request:\n%s\n", rpc_req);
  246. upload_data.buf = rpc_req;
  247. upload_data.len = strlen(rpc_req);
  248. sprintf(len_hdr, "Content-Length: %lu",
  249. (unsigned long) upload_data.len);
  250. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  251. headers = curl_slist_append(headers,
  252. "Content-type: application/json");
  253. headers = curl_slist_append(headers, len_hdr);
  254. headers = curl_slist_append(headers, user_agent_hdr);
  255. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  256. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  257. rc = curl_easy_perform(curl);
  258. if (rc) {
  259. if (!comms_error)
  260. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  261. comms_error = true;
  262. goto err_out;
  263. }
  264. if (!all_data.buf) {
  265. if (opt_debug)
  266. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  267. goto err_out;
  268. }
  269. if (!have_longpoll) {
  270. /* If X-Long-Polling was found, activate long polling */
  271. if (hi.lp_path) {
  272. have_longpoll = true;
  273. tq_push(thr_info[longpoll_thr_id].q, hi.lp_path);
  274. } else
  275. free(hi.lp_path);
  276. }
  277. if (probing) {
  278. pool->probed = true;
  279. pool->has_rolltime = hi.has_rolltime;
  280. }
  281. hi.lp_path = NULL;
  282. val = JSON_LOADS(all_data.buf, &err);
  283. if (!val) {
  284. if (!comms_error)
  285. applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
  286. comms_error = true;
  287. if (opt_protocol)
  288. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  289. goto err_out;
  290. }
  291. if (opt_protocol) {
  292. char *s = json_dumps(val, JSON_INDENT(3));
  293. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  294. free(s);
  295. }
  296. /* JSON-RPC valid response returns a non-null 'result',
  297. * and a null 'error'.
  298. */
  299. res_val = json_object_get(val, "result");
  300. err_val = json_object_get(val, "error");
  301. if (!res_val || json_is_null(res_val) ||
  302. (err_val && !json_is_null(err_val))) {
  303. char *s;
  304. if (err_val)
  305. s = json_dumps(err_val, JSON_INDENT(3));
  306. else
  307. s = strdup("(unknown reason)");
  308. if (!comms_error)
  309. applog(LOG_ERR, "JSON-RPC call failed: %s", s);
  310. comms_error = true;
  311. free(s);
  312. goto err_out;
  313. }
  314. successful_connect = true;
  315. comms_error = false;
  316. databuf_free(&all_data);
  317. curl_slist_free_all(headers);
  318. curl_easy_reset(curl);
  319. return val;
  320. err_out:
  321. databuf_free(&all_data);
  322. curl_slist_free_all(headers);
  323. curl_easy_reset(curl);
  324. if (!successful_connect) {
  325. kill_work();
  326. applog(LOG_ERR, "Failed to connect - wrong URL or login details?");
  327. }
  328. return NULL;
  329. }
  330. char *bin2hex(const unsigned char *p, size_t len)
  331. {
  332. int i;
  333. char *s = malloc((len * 2) + 1);
  334. if (!s)
  335. return NULL;
  336. for (i = 0; i < len; i++)
  337. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  338. return s;
  339. }
  340. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  341. {
  342. while (*hexstr && len) {
  343. char hex_byte[3];
  344. unsigned int v;
  345. if (!hexstr[1]) {
  346. applog(LOG_ERR, "hex2bin str truncated");
  347. return false;
  348. }
  349. hex_byte[0] = hexstr[0];
  350. hex_byte[1] = hexstr[1];
  351. hex_byte[2] = 0;
  352. if (sscanf(hex_byte, "%x", &v) != 1) {
  353. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  354. return false;
  355. }
  356. *p = (unsigned char) v;
  357. p++;
  358. hexstr += 2;
  359. len--;
  360. }
  361. return (len == 0 && *hexstr == 0) ? true : false;
  362. }
  363. /* Subtract the `struct timeval' values X and Y,
  364. storing the result in RESULT.
  365. Return 1 if the difference is negative, otherwise 0. */
  366. int
  367. timeval_subtract (
  368. struct timeval *result, struct timeval *x, struct timeval *y)
  369. {
  370. /* Perform the carry for the later subtraction by updating Y. */
  371. if (x->tv_usec < y->tv_usec) {
  372. int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
  373. y->tv_usec -= 1000000 * nsec;
  374. y->tv_sec += nsec;
  375. }
  376. if (x->tv_usec - y->tv_usec > 1000000) {
  377. int nsec = (x->tv_usec - y->tv_usec) / 1000000;
  378. y->tv_usec += 1000000 * nsec;
  379. y->tv_sec -= nsec;
  380. }
  381. /* Compute the time remaining to wait.
  382. `tv_usec' is certainly positive. */
  383. result->tv_sec = x->tv_sec - y->tv_sec;
  384. result->tv_usec = x->tv_usec - y->tv_usec;
  385. /* Return 1 if result is negative. */
  386. return x->tv_sec < y->tv_sec;
  387. }
  388. bool fulltest(const unsigned char *hash, const unsigned char *target)
  389. {
  390. unsigned char hash_swap[32], target_swap[32];
  391. uint32_t *hash32 = (uint32_t *) hash_swap;
  392. uint32_t *target32 = (uint32_t *) target_swap;
  393. int i;
  394. bool rc = true;
  395. char *hash_str, *target_str;
  396. swap256(hash_swap, hash);
  397. swap256(target_swap, target);
  398. for (i = 0; i < 32/4; i++) {
  399. uint32_t h32tmp = swab32(hash32[i]);
  400. uint32_t t32tmp = target32[i];
  401. target32[i] = swab32(target32[i]); /* for printing */
  402. if (h32tmp > t32tmp) {
  403. rc = false;
  404. break;
  405. }
  406. if (h32tmp < t32tmp) {
  407. rc = true;
  408. break;
  409. }
  410. }
  411. if (opt_debug) {
  412. hash_str = bin2hex(hash_swap, 32);
  413. target_str = bin2hex(target_swap, 32);
  414. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  415. hash_str,
  416. target_str,
  417. rc ? "YES (hash < target)" :
  418. "no (false positive; hash > target)");
  419. free(hash_str);
  420. free(target_str);
  421. }
  422. return true; /* FIXME: return rc; */
  423. }
  424. struct thread_q *tq_new(void)
  425. {
  426. struct thread_q *tq;
  427. tq = calloc(1, sizeof(*tq));
  428. if (!tq)
  429. return NULL;
  430. INIT_LIST_HEAD(&tq->q);
  431. pthread_mutex_init(&tq->mutex, NULL);
  432. pthread_cond_init(&tq->cond, NULL);
  433. return tq;
  434. }
  435. void tq_free(struct thread_q *tq)
  436. {
  437. struct tq_ent *ent, *iter;
  438. if (!tq)
  439. return;
  440. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  441. list_del(&ent->q_node);
  442. free(ent);
  443. }
  444. pthread_cond_destroy(&tq->cond);
  445. pthread_mutex_destroy(&tq->mutex);
  446. memset(tq, 0, sizeof(*tq)); /* poison */
  447. free(tq);
  448. }
  449. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  450. {
  451. pthread_mutex_lock(&tq->mutex);
  452. tq->frozen = frozen;
  453. pthread_cond_signal(&tq->cond);
  454. pthread_mutex_unlock(&tq->mutex);
  455. }
  456. void tq_freeze(struct thread_q *tq)
  457. {
  458. tq_freezethaw(tq, true);
  459. }
  460. void tq_thaw(struct thread_q *tq)
  461. {
  462. tq_freezethaw(tq, false);
  463. }
  464. bool tq_push(struct thread_q *tq, void *data)
  465. {
  466. struct tq_ent *ent;
  467. bool rc = true;
  468. ent = calloc(1, sizeof(*ent));
  469. if (!ent)
  470. return false;
  471. ent->data = data;
  472. INIT_LIST_HEAD(&ent->q_node);
  473. pthread_mutex_lock(&tq->mutex);
  474. if (!tq->frozen) {
  475. list_add_tail(&ent->q_node, &tq->q);
  476. } else {
  477. free(ent);
  478. rc = false;
  479. }
  480. pthread_cond_signal(&tq->cond);
  481. pthread_mutex_unlock(&tq->mutex);
  482. return rc;
  483. }
  484. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  485. {
  486. struct tq_ent *ent;
  487. void *rval = NULL;
  488. int rc;
  489. pthread_mutex_lock(&tq->mutex);
  490. if (!list_empty(&tq->q))
  491. goto pop;
  492. if (abstime)
  493. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  494. else
  495. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  496. if (rc)
  497. goto out;
  498. if (list_empty(&tq->q))
  499. goto out;
  500. pop:
  501. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  502. rval = ent->data;
  503. list_del(&ent->q_node);
  504. free(ent);
  505. out:
  506. pthread_mutex_unlock(&tq->mutex);
  507. return rval;
  508. }