util.c 12 KB

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