util.c 12 KB

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