util.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. if (!longpoll)
  218. curl_easy_setopt(curl, CURLOPT_POST, 1);
  219. if (opt_protocol)
  220. applog(LOG_DEBUG, "JSON protocol request:\n%s\n", rpc_req);
  221. upload_data.buf = rpc_req;
  222. upload_data.len = strlen(rpc_req);
  223. sprintf(len_hdr, "Content-Length: %lu",
  224. (unsigned long) upload_data.len);
  225. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  226. headers = curl_slist_append(headers,
  227. "Content-type: application/json");
  228. headers = curl_slist_append(headers, len_hdr);
  229. headers = curl_slist_append(headers, user_agent_hdr);
  230. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  231. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  232. rc = curl_easy_perform(curl);
  233. if (rc) {
  234. if (!comms_error)
  235. applog(LOG_ERR, "HTTP request failed: %s", curl_err_str);
  236. comms_error = true;
  237. goto err_out;
  238. }
  239. /* If X-Long-Polling was found, activate long polling */
  240. if (hi.lp_path) {
  241. have_longpoll = true;
  242. tq_push(thr_info[longpoll_thr_id].q, hi.lp_path);
  243. } else
  244. free(hi.lp_path);
  245. hi.lp_path = NULL;
  246. val = JSON_LOADS(all_data.buf, &err);
  247. if (!val) {
  248. if (!comms_error)
  249. applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
  250. comms_error = true;
  251. if (opt_protocol)
  252. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  253. goto err_out;
  254. }
  255. if (opt_protocol) {
  256. char *s = json_dumps(val, JSON_INDENT(3));
  257. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  258. free(s);
  259. }
  260. /* JSON-RPC valid response returns a non-null 'result',
  261. * and a null 'error'.
  262. */
  263. res_val = json_object_get(val, "result");
  264. err_val = json_object_get(val, "error");
  265. if (!res_val || json_is_null(res_val) ||
  266. (err_val && !json_is_null(err_val))) {
  267. char *s;
  268. if (err_val)
  269. s = json_dumps(err_val, JSON_INDENT(3));
  270. else
  271. s = strdup("(unknown reason)");
  272. if (!comms_error)
  273. applog(LOG_ERR, "JSON-RPC call failed: %s", s);
  274. comms_error = true;
  275. free(s);
  276. goto err_out;
  277. }
  278. comms_error = false;
  279. databuf_free(&all_data);
  280. curl_slist_free_all(headers);
  281. curl_easy_reset(curl);
  282. return val;
  283. err_out:
  284. databuf_free(&all_data);
  285. curl_slist_free_all(headers);
  286. curl_easy_reset(curl);
  287. return NULL;
  288. }
  289. char *bin2hex(const unsigned char *p, size_t len)
  290. {
  291. int i;
  292. char *s = malloc((len * 2) + 1);
  293. if (!s)
  294. return NULL;
  295. for (i = 0; i < len; i++)
  296. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  297. return s;
  298. }
  299. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  300. {
  301. while (*hexstr && len) {
  302. char hex_byte[3];
  303. unsigned int v;
  304. if (!hexstr[1]) {
  305. applog(LOG_ERR, "hex2bin str truncated");
  306. return false;
  307. }
  308. hex_byte[0] = hexstr[0];
  309. hex_byte[1] = hexstr[1];
  310. hex_byte[2] = 0;
  311. if (sscanf(hex_byte, "%x", &v) != 1) {
  312. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  313. return false;
  314. }
  315. *p = (unsigned char) v;
  316. p++;
  317. hexstr += 2;
  318. len--;
  319. }
  320. return (len == 0 && *hexstr == 0) ? true : false;
  321. }
  322. /* Subtract the `struct timeval' values X and Y,
  323. storing the result in RESULT.
  324. Return 1 if the difference is negative, otherwise 0. */
  325. int
  326. timeval_subtract (
  327. struct timeval *result, struct timeval *x, struct timeval *y)
  328. {
  329. /* Perform the carry for the later subtraction by updating Y. */
  330. if (x->tv_usec < y->tv_usec) {
  331. int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
  332. y->tv_usec -= 1000000 * nsec;
  333. y->tv_sec += nsec;
  334. }
  335. if (x->tv_usec - y->tv_usec > 1000000) {
  336. int nsec = (x->tv_usec - y->tv_usec) / 1000000;
  337. y->tv_usec += 1000000 * nsec;
  338. y->tv_sec -= nsec;
  339. }
  340. /* Compute the time remaining to wait.
  341. `tv_usec' is certainly positive. */
  342. result->tv_sec = x->tv_sec - y->tv_sec;
  343. result->tv_usec = x->tv_usec - y->tv_usec;
  344. /* Return 1 if result is negative. */
  345. return x->tv_sec < y->tv_sec;
  346. }
  347. bool fulltest(const unsigned char *hash, const unsigned char *target)
  348. {
  349. unsigned char hash_swap[32], target_swap[32];
  350. uint32_t *hash32 = (uint32_t *) hash_swap;
  351. uint32_t *target32 = (uint32_t *) target_swap;
  352. int i;
  353. bool rc = true;
  354. char *hash_str, *target_str;
  355. swap256(hash_swap, hash);
  356. swap256(target_swap, target);
  357. for (i = 0; i < 32/4; i++) {
  358. uint32_t h32tmp = swab32(hash32[i]);
  359. uint32_t t32tmp = target32[i];
  360. target32[i] = swab32(target32[i]); /* for printing */
  361. if (h32tmp > t32tmp) {
  362. rc = false;
  363. break;
  364. }
  365. if (h32tmp < t32tmp) {
  366. rc = true;
  367. break;
  368. }
  369. }
  370. if (opt_debug) {
  371. hash_str = bin2hex(hash_swap, 32);
  372. target_str = bin2hex(target_swap, 32);
  373. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  374. hash_str,
  375. target_str,
  376. rc ? "YES (hash < target)" :
  377. "no (false positive; hash > target)");
  378. free(hash_str);
  379. free(target_str);
  380. }
  381. return true; /* FIXME: return rc; */
  382. }
  383. struct thread_q *tq_new(void)
  384. {
  385. struct thread_q *tq;
  386. tq = calloc(1, sizeof(*tq));
  387. if (!tq)
  388. return NULL;
  389. INIT_LIST_HEAD(&tq->q);
  390. pthread_mutex_init(&tq->mutex, NULL);
  391. pthread_cond_init(&tq->cond, NULL);
  392. return tq;
  393. }
  394. void tq_free(struct thread_q *tq)
  395. {
  396. struct tq_ent *ent, *iter;
  397. if (!tq)
  398. return;
  399. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  400. list_del(&ent->q_node);
  401. free(ent);
  402. }
  403. pthread_cond_destroy(&tq->cond);
  404. pthread_mutex_destroy(&tq->mutex);
  405. memset(tq, 0, sizeof(*tq)); /* poison */
  406. free(tq);
  407. }
  408. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  409. {
  410. pthread_mutex_lock(&tq->mutex);
  411. tq->frozen = frozen;
  412. pthread_cond_signal(&tq->cond);
  413. pthread_mutex_unlock(&tq->mutex);
  414. }
  415. void tq_freeze(struct thread_q *tq)
  416. {
  417. tq_freezethaw(tq, true);
  418. }
  419. void tq_thaw(struct thread_q *tq)
  420. {
  421. tq_freezethaw(tq, false);
  422. }
  423. bool tq_push(struct thread_q *tq, void *data)
  424. {
  425. struct tq_ent *ent;
  426. bool rc = true;
  427. ent = calloc(1, sizeof(*ent));
  428. if (!ent)
  429. return false;
  430. ent->data = data;
  431. INIT_LIST_HEAD(&ent->q_node);
  432. pthread_mutex_lock(&tq->mutex);
  433. if (!tq->frozen) {
  434. list_add_tail(&ent->q_node, &tq->q);
  435. } else {
  436. free(ent);
  437. rc = false;
  438. }
  439. pthread_cond_signal(&tq->cond);
  440. pthread_mutex_unlock(&tq->mutex);
  441. return rc;
  442. }
  443. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  444. {
  445. struct tq_ent *ent;
  446. void *rval = NULL;
  447. int rc;
  448. pthread_mutex_lock(&tq->mutex);
  449. if (!list_empty(&tq->q))
  450. goto pop;
  451. if (abstime)
  452. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  453. else
  454. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  455. if (unlikely(rc)) {
  456. if (rc == ETIMEDOUT)
  457. applog(LOG_WARNING, "Timed out waiting in tq_pop");
  458. goto out;
  459. }
  460. if (list_empty(&tq->q))
  461. goto out;
  462. pop:
  463. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  464. rval = ent->data;
  465. list_del(&ent->q_node);
  466. free(ent);
  467. out:
  468. pthread_mutex_unlock(&tq->mutex);
  469. return rval;
  470. }