util.c 12 KB

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