From 1e4e7b71e1938daa9b2b9718a9f54c69017a9ef5 Mon Sep 17 00:00:00 2001 From: Zbigniew Jędrzejewski-Szmek Date: Tue, 25 Mar 2014 22:30:24 -0400 Subject: Move network-related journal programs to src/journal-remote/ Directory src/journal has become one of the largest directories, and since systemd-journal-gatewayd, systemd-journal-remote, and forthcoming systemd-journal-upload are all closely related, create a separate directory for them. --- src/journal-remote/Makefile | 1 + src/journal-remote/browse.html | 544 ++++++++++++ src/journal-remote/journal-gatewayd.c | 1054 ++++++++++++++++++++++++ src/journal-remote/journal-remote-parse.c | 439 ++++++++++ src/journal-remote/journal-remote-parse.h | 61 ++ src/journal-remote/journal-remote-write.c | 124 +++ src/journal-remote/journal-remote-write.h | 51 ++ src/journal-remote/journal-remote.c | 1283 +++++++++++++++++++++++++++++ src/journal-remote/microhttpd-util.c | 298 +++++++ src/journal-remote/microhttpd-util.h | 55 ++ src/journal/browse.html | 544 ------------ src/journal/journal-gatewayd.c | 1054 ------------------------ src/journal/journal-remote-parse.c | 439 ---------- src/journal/journal-remote-parse.h | 61 -- src/journal/journal-remote-write.c | 124 --- src/journal/journal-remote-write.h | 51 -- src/journal/journal-remote.c | 1283 ----------------------------- src/journal/microhttpd-util.c | 298 ------- src/journal/microhttpd-util.h | 55 -- 19 files changed, 3910 insertions(+), 3909 deletions(-) create mode 120000 src/journal-remote/Makefile create mode 100644 src/journal-remote/browse.html create mode 100644 src/journal-remote/journal-gatewayd.c create mode 100644 src/journal-remote/journal-remote-parse.c create mode 100644 src/journal-remote/journal-remote-parse.h create mode 100644 src/journal-remote/journal-remote-write.c create mode 100644 src/journal-remote/journal-remote-write.h create mode 100644 src/journal-remote/journal-remote.c create mode 100644 src/journal-remote/microhttpd-util.c create mode 100644 src/journal-remote/microhttpd-util.h delete mode 100644 src/journal/browse.html delete mode 100644 src/journal/journal-gatewayd.c delete mode 100644 src/journal/journal-remote-parse.c delete mode 100644 src/journal/journal-remote-parse.h delete mode 100644 src/journal/journal-remote-write.c delete mode 100644 src/journal/journal-remote-write.h delete mode 100644 src/journal/journal-remote.c delete mode 100644 src/journal/microhttpd-util.c delete mode 100644 src/journal/microhttpd-util.h (limited to 'src') diff --git a/src/journal-remote/Makefile b/src/journal-remote/Makefile new file mode 120000 index 0000000000..d0b0e8e008 --- /dev/null +++ b/src/journal-remote/Makefile @@ -0,0 +1 @@ +../Makefile \ No newline at end of file diff --git a/src/journal-remote/browse.html b/src/journal-remote/browse.html new file mode 100644 index 0000000000..3594f70c87 --- /dev/null +++ b/src/journal-remote/browse.html @@ -0,0 +1,544 @@ + + + + Journal + + + + + + + +

+ +
+
+
+
+
+
+ +
+ +      + Only current boot +
+ +
+ +
+ +
+ + + + +      + + +
+ +
+ g: First Page      + ←, k, BACKSPACE: Previous Page      + →, j, SPACE: Next Page      + G: Last Page      + +: More entries      + -: Fewer entries +
+ + + + diff --git a/src/journal-remote/journal-gatewayd.c b/src/journal-remote/journal-gatewayd.c new file mode 100644 index 0000000000..db07700111 --- /dev/null +++ b/src/journal-remote/journal-gatewayd.c @@ -0,0 +1,1054 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2012 Lennart Poettering + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#include +#include +#include +#include +#include + +#include + +#ifdef HAVE_GNUTLS +#include +#endif + +#include "log.h" +#include "util.h" +#include "sd-journal.h" +#include "sd-daemon.h" +#include "sd-bus.h" +#include "bus-util.h" +#include "logs-show.h" +#include "microhttpd-util.h" +#include "build.h" +#include "fileio.h" + +static char *key_pem = NULL; +static char *cert_pem = NULL; +static char *trust_pem = NULL; + +typedef struct RequestMeta { + sd_journal *journal; + + OutputMode mode; + + char *cursor; + int64_t n_skip; + uint64_t n_entries; + bool n_entries_set; + + FILE *tmp; + uint64_t delta, size; + + int argument_parse_error; + + bool follow; + bool discrete; + + uint64_t n_fields; + bool n_fields_set; +} RequestMeta; + +static const char* const mime_types[_OUTPUT_MODE_MAX] = { + [OUTPUT_SHORT] = "text/plain", + [OUTPUT_JSON] = "application/json", + [OUTPUT_JSON_SSE] = "text/event-stream", + [OUTPUT_EXPORT] = "application/vnd.fdo.journal", +}; + +static RequestMeta *request_meta(void **connection_cls) { + RequestMeta *m; + + assert(connection_cls); + if (*connection_cls) + return *connection_cls; + + m = new0(RequestMeta, 1); + if (!m) + return NULL; + + *connection_cls = m; + return m; +} + +static void request_meta_free( + void *cls, + struct MHD_Connection *connection, + void **connection_cls, + enum MHD_RequestTerminationCode toe) { + + RequestMeta *m = *connection_cls; + + if (!m) + return; + + if (m->journal) + sd_journal_close(m->journal); + + if (m->tmp) + fclose(m->tmp); + + free(m->cursor); + free(m); +} + +static int open_journal(RequestMeta *m) { + assert(m); + + if (m->journal) + return 0; + + return sd_journal_open(&m->journal, SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_SYSTEM); +} + +static ssize_t request_reader_entries( + void *cls, + uint64_t pos, + char *buf, + size_t max) { + + RequestMeta *m = cls; + int r; + size_t n, k; + + assert(m); + assert(buf); + assert(max > 0); + assert(pos >= m->delta); + + pos -= m->delta; + + while (pos >= m->size) { + off_t sz; + + /* End of this entry, so let's serialize the next + * one */ + + if (m->n_entries_set && + m->n_entries <= 0) + return MHD_CONTENT_READER_END_OF_STREAM; + + if (m->n_skip < 0) + r = sd_journal_previous_skip(m->journal, (uint64_t) -m->n_skip + 1); + else if (m->n_skip > 0) + r = sd_journal_next_skip(m->journal, (uint64_t) m->n_skip + 1); + else + r = sd_journal_next(m->journal); + + if (r < 0) { + log_error("Failed to advance journal pointer: %s", strerror(-r)); + return MHD_CONTENT_READER_END_WITH_ERROR; + } else if (r == 0) { + + if (m->follow) { + r = sd_journal_wait(m->journal, (uint64_t) -1); + if (r < 0) { + log_error("Couldn't wait for journal event: %s", strerror(-r)); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + continue; + } + + return MHD_CONTENT_READER_END_OF_STREAM; + } + + if (m->discrete) { + assert(m->cursor); + + r = sd_journal_test_cursor(m->journal, m->cursor); + if (r < 0) { + log_error("Failed to test cursor: %s", strerror(-r)); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + if (r == 0) + return MHD_CONTENT_READER_END_OF_STREAM; + } + + pos -= m->size; + m->delta += m->size; + + if (m->n_entries_set) + m->n_entries -= 1; + + m->n_skip = 0; + + if (m->tmp) + rewind(m->tmp); + else { + m->tmp = tmpfile(); + if (!m->tmp) { + log_error("Failed to create temporary file: %m"); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + } + + r = output_journal(m->tmp, m->journal, m->mode, 0, OUTPUT_FULL_WIDTH, NULL); + if (r < 0) { + log_error("Failed to serialize item: %s", strerror(-r)); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + sz = ftello(m->tmp); + if (sz == (off_t) -1) { + log_error("Failed to retrieve file position: %m"); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + m->size = (uint64_t) sz; + } + + if (fseeko(m->tmp, pos, SEEK_SET) < 0) { + log_error("Failed to seek to position: %m"); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + n = m->size - pos; + if (n > max) + n = max; + + errno = 0; + k = fread(buf, 1, n, m->tmp); + if (k != n) { + log_error("Failed to read from file: %s", errno ? strerror(errno) : "Premature EOF"); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + return (ssize_t) k; +} + +static int request_parse_accept( + RequestMeta *m, + struct MHD_Connection *connection) { + + const char *header; + + assert(m); + assert(connection); + + header = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Accept"); + if (!header) + return 0; + + if (streq(header, mime_types[OUTPUT_JSON])) + m->mode = OUTPUT_JSON; + else if (streq(header, mime_types[OUTPUT_JSON_SSE])) + m->mode = OUTPUT_JSON_SSE; + else if (streq(header, mime_types[OUTPUT_EXPORT])) + m->mode = OUTPUT_EXPORT; + else + m->mode = OUTPUT_SHORT; + + return 0; +} + +static int request_parse_range( + RequestMeta *m, + struct MHD_Connection *connection) { + + const char *range, *colon, *colon2; + int r; + + assert(m); + assert(connection); + + range = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Range"); + if (!range) + return 0; + + if (!startswith(range, "entries=")) + return 0; + + range += 8; + range += strspn(range, WHITESPACE); + + colon = strchr(range, ':'); + if (!colon) + m->cursor = strdup(range); + else { + const char *p; + + colon2 = strchr(colon + 1, ':'); + if (colon2) { + _cleanup_free_ char *t; + + t = strndup(colon + 1, colon2 - colon - 1); + if (!t) + return -ENOMEM; + + r = safe_atoi64(t, &m->n_skip); + if (r < 0) + return r; + } + + p = (colon2 ? colon2 : colon) + 1; + if (*p) { + r = safe_atou64(p, &m->n_entries); + if (r < 0) + return r; + + if (m->n_entries <= 0) + return -EINVAL; + + m->n_entries_set = true; + } + + m->cursor = strndup(range, colon - range); + } + + if (!m->cursor) + return -ENOMEM; + + m->cursor[strcspn(m->cursor, WHITESPACE)] = 0; + if (isempty(m->cursor)) { + free(m->cursor); + m->cursor = NULL; + } + + return 0; +} + +static int request_parse_arguments_iterator( + void *cls, + enum MHD_ValueKind kind, + const char *key, + const char *value) { + + RequestMeta *m = cls; + _cleanup_free_ char *p = NULL; + int r; + + assert(m); + + if (isempty(key)) { + m->argument_parse_error = -EINVAL; + return MHD_NO; + } + + if (streq(key, "follow")) { + if (isempty(value)) { + m->follow = true; + return MHD_YES; + } + + r = parse_boolean(value); + if (r < 0) { + m->argument_parse_error = r; + return MHD_NO; + } + + m->follow = r; + return MHD_YES; + } + + if (streq(key, "discrete")) { + if (isempty(value)) { + m->discrete = true; + return MHD_YES; + } + + r = parse_boolean(value); + if (r < 0) { + m->argument_parse_error = r; + return MHD_NO; + } + + m->discrete = r; + return MHD_YES; + } + + if (streq(key, "boot")) { + if (isempty(value)) + r = true; + else { + r = parse_boolean(value); + if (r < 0) { + m->argument_parse_error = r; + return MHD_NO; + } + } + + if (r) { + char match[9 + 32 + 1] = "_BOOT_ID="; + sd_id128_t bid; + + r = sd_id128_get_boot(&bid); + if (r < 0) { + log_error("Failed to get boot ID: %s", strerror(-r)); + return MHD_NO; + } + + sd_id128_to_string(bid, match + 9); + r = sd_journal_add_match(m->journal, match, sizeof(match)-1); + if (r < 0) { + m->argument_parse_error = r; + return MHD_NO; + } + } + + return MHD_YES; + } + + p = strjoin(key, "=", strempty(value), NULL); + if (!p) { + m->argument_parse_error = log_oom(); + return MHD_NO; + } + + r = sd_journal_add_match(m->journal, p, 0); + if (r < 0) { + m->argument_parse_error = r; + return MHD_NO; + } + + return MHD_YES; +} + +static int request_parse_arguments( + RequestMeta *m, + struct MHD_Connection *connection) { + + assert(m); + assert(connection); + + m->argument_parse_error = 0; + MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND, request_parse_arguments_iterator, m); + + return m->argument_parse_error; +} + +static int request_handler_entries( + struct MHD_Connection *connection, + void *connection_cls) { + + struct MHD_Response *response; + RequestMeta *m = connection_cls; + int r; + + assert(connection); + assert(m); + + r = open_journal(m); + if (r < 0) + return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r)); + + if (request_parse_accept(m, connection) < 0) + return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Accept header.\n"); + + if (request_parse_range(m, connection) < 0) + return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Range header.\n"); + + if (request_parse_arguments(m, connection) < 0) + return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse URL arguments.\n"); + + if (m->discrete) { + if (!m->cursor) + return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Discrete seeks require a cursor specification.\n"); + + m->n_entries = 1; + m->n_entries_set = true; + } + + if (m->cursor) + r = sd_journal_seek_cursor(m->journal, m->cursor); + else if (m->n_skip >= 0) + r = sd_journal_seek_head(m->journal); + else if (m->n_skip < 0) + r = sd_journal_seek_tail(m->journal); + if (r < 0) + return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to seek in journal.\n"); + + response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 4*1024, request_reader_entries, m, NULL); + if (!response) + return respond_oom(connection); + + MHD_add_response_header(response, "Content-Type", mime_types[m->mode]); + + r = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); + + return r; +} + +static int output_field(FILE *f, OutputMode m, const char *d, size_t l) { + const char *eq; + size_t j; + + eq = memchr(d, '=', l); + if (!eq) + return -EINVAL; + + j = l - (eq - d + 1); + + if (m == OUTPUT_JSON) { + fprintf(f, "{ \"%.*s\" : ", (int) (eq - d), d); + json_escape(f, eq+1, j, OUTPUT_FULL_WIDTH); + fputs(" }\n", f); + } else { + fwrite(eq+1, 1, j, f); + fputc('\n', f); + } + + return 0; +} + +static ssize_t request_reader_fields( + void *cls, + uint64_t pos, + char *buf, + size_t max) { + + RequestMeta *m = cls; + int r; + size_t n, k; + + assert(m); + assert(buf); + assert(max > 0); + assert(pos >= m->delta); + + pos -= m->delta; + + while (pos >= m->size) { + off_t sz; + const void *d; + size_t l; + + /* End of this field, so let's serialize the next + * one */ + + if (m->n_fields_set && + m->n_fields <= 0) + return MHD_CONTENT_READER_END_OF_STREAM; + + r = sd_journal_enumerate_unique(m->journal, &d, &l); + if (r < 0) { + log_error("Failed to advance field index: %s", strerror(-r)); + return MHD_CONTENT_READER_END_WITH_ERROR; + } else if (r == 0) + return MHD_CONTENT_READER_END_OF_STREAM; + + pos -= m->size; + m->delta += m->size; + + if (m->n_fields_set) + m->n_fields -= 1; + + if (m->tmp) + rewind(m->tmp); + else { + m->tmp = tmpfile(); + if (!m->tmp) { + log_error("Failed to create temporary file: %m"); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + } + + r = output_field(m->tmp, m->mode, d, l); + if (r < 0) { + log_error("Failed to serialize item: %s", strerror(-r)); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + sz = ftello(m->tmp); + if (sz == (off_t) -1) { + log_error("Failed to retrieve file position: %m"); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + m->size = (uint64_t) sz; + } + + if (fseeko(m->tmp, pos, SEEK_SET) < 0) { + log_error("Failed to seek to position: %m"); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + n = m->size - pos; + if (n > max) + n = max; + + errno = 0; + k = fread(buf, 1, n, m->tmp); + if (k != n) { + log_error("Failed to read from file: %s", errno ? strerror(errno) : "Premature EOF"); + return MHD_CONTENT_READER_END_WITH_ERROR; + } + + return (ssize_t) k; +} + +static int request_handler_fields( + struct MHD_Connection *connection, + const char *field, + void *connection_cls) { + + struct MHD_Response *response; + RequestMeta *m = connection_cls; + int r; + + assert(connection); + assert(m); + + r = open_journal(m); + if (r < 0) + return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r)); + + if (request_parse_accept(m, connection) < 0) + return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Accept header.\n"); + + r = sd_journal_query_unique(m->journal, field); + if (r < 0) + return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to query unique fields.\n"); + + response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 4*1024, request_reader_fields, m, NULL); + if (!response) + return respond_oom(connection); + + MHD_add_response_header(response, "Content-Type", mime_types[m->mode == OUTPUT_JSON ? OUTPUT_JSON : OUTPUT_SHORT]); + + r = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); + + return r; +} + +static int request_handler_redirect( + struct MHD_Connection *connection, + const char *target) { + + char *page; + struct MHD_Response *response; + int ret; + + assert(connection); + assert(target); + + if (asprintf(&page, "Please continue to the journal browser.", target) < 0) + return respond_oom(connection); + + response = MHD_create_response_from_buffer(strlen(page), page, MHD_RESPMEM_MUST_FREE); + if (!response) { + free(page); + return respond_oom(connection); + } + + MHD_add_response_header(response, "Content-Type", "text/html"); + MHD_add_response_header(response, "Location", target); + + ret = MHD_queue_response(connection, MHD_HTTP_MOVED_PERMANENTLY, response); + MHD_destroy_response(response); + + return ret; +} + +static int request_handler_file( + struct MHD_Connection *connection, + const char *path, + const char *mime_type) { + + struct MHD_Response *response; + int ret; + _cleanup_close_ int fd = -1; + struct stat st; + + assert(connection); + assert(path); + assert(mime_type); + + fd = open(path, O_RDONLY|O_CLOEXEC); + if (fd < 0) + return mhd_respondf(connection, MHD_HTTP_NOT_FOUND, "Failed to open file %s: %m\n", path); + + if (fstat(fd, &st) < 0) + return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to stat file: %m\n"); + + response = MHD_create_response_from_fd_at_offset(st.st_size, fd, 0); + if (!response) + return respond_oom(connection); + + fd = -1; + + MHD_add_response_header(response, "Content-Type", mime_type); + + ret = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); + + return ret; +} + +static int get_virtualization(char **v) { + _cleanup_bus_unref_ sd_bus *bus = NULL; + char *b = NULL; + int r; + + r = sd_bus_default_system(&bus); + if (r < 0) + return r; + + r = sd_bus_get_property_string( + bus, + "org.freedesktop.systemd1", + "/org/freedesktop/systemd1", + "org.freedesktop.systemd1.Manager", + "Virtualization", + NULL, + &b); + if (r < 0) + return r; + + if (isempty(b)) { + free(b); + *v = NULL; + return 0; + } + + *v = b; + return 1; +} + +static int request_handler_machine( + struct MHD_Connection *connection, + void *connection_cls) { + + struct MHD_Response *response; + RequestMeta *m = connection_cls; + int r; + _cleanup_free_ char* hostname = NULL, *os_name = NULL; + uint64_t cutoff_from = 0, cutoff_to = 0, usage; + char *json; + sd_id128_t mid, bid; + _cleanup_free_ char *v = NULL; + + assert(connection); + assert(m); + + r = open_journal(m); + if (r < 0) + return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r)); + + r = sd_id128_get_machine(&mid); + if (r < 0) + return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine machine ID: %s\n", strerror(-r)); + + r = sd_id128_get_boot(&bid); + if (r < 0) + return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine boot ID: %s\n", strerror(-r)); + + hostname = gethostname_malloc(); + if (!hostname) + return respond_oom(connection); + + r = sd_journal_get_usage(m->journal, &usage); + if (r < 0) + return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine disk usage: %s\n", strerror(-r)); + + r = sd_journal_get_cutoff_realtime_usec(m->journal, &cutoff_from, &cutoff_to); + if (r < 0) + return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine disk usage: %s\n", strerror(-r)); + + if (parse_env_file("/etc/os-release", NEWLINE, "PRETTY_NAME", &os_name, NULL) == -ENOENT) + parse_env_file("/usr/lib/os-release", NEWLINE, "PRETTY_NAME", &os_name, NULL); + + get_virtualization(&v); + + r = asprintf(&json, + "{ \"machine_id\" : \"" SD_ID128_FORMAT_STR "\"," + "\"boot_id\" : \"" SD_ID128_FORMAT_STR "\"," + "\"hostname\" : \"%s\"," + "\"os_pretty_name\" : \"%s\"," + "\"virtualization\" : \"%s\"," + "\"usage\" : \"%"PRIu64"\"," + "\"cutoff_from_realtime\" : \"%"PRIu64"\"," + "\"cutoff_to_realtime\" : \"%"PRIu64"\" }\n", + SD_ID128_FORMAT_VAL(mid), + SD_ID128_FORMAT_VAL(bid), + hostname_cleanup(hostname, false), + os_name ? os_name : "Linux", + v ? v : "bare", + usage, + cutoff_from, + cutoff_to); + + if (r < 0) + return respond_oom(connection); + + response = MHD_create_response_from_buffer(strlen(json), json, MHD_RESPMEM_MUST_FREE); + if (!response) { + free(json); + return respond_oom(connection); + } + + MHD_add_response_header(response, "Content-Type", "application/json"); + r = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); + + return r; +} + +static int request_handler( + void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, + size_t *upload_data_size, + void **connection_cls) { + int r, code; + + assert(connection); + assert(connection_cls); + assert(url); + assert(method); + + if (!streq(method, "GET")) + return mhd_respond(connection, MHD_HTTP_METHOD_NOT_ACCEPTABLE, + "Unsupported method.\n"); + + + if (!*connection_cls) { + if (!request_meta(connection_cls)) + return respond_oom(connection); + return MHD_YES; + } + + if (trust_pem) { + r = check_permissions(connection, &code); + if (r < 0) + return code; + } + + if (streq(url, "/")) + return request_handler_redirect(connection, "/browse"); + + if (streq(url, "/entries")) + return request_handler_entries(connection, *connection_cls); + + if (startswith(url, "/fields/")) + return request_handler_fields(connection, url + 8, *connection_cls); + + if (streq(url, "/browse")) + return request_handler_file(connection, DOCUMENT_ROOT "/browse.html", "text/html"); + + if (streq(url, "/machine")) + return request_handler_machine(connection, *connection_cls); + + return mhd_respond(connection, MHD_HTTP_NOT_FOUND, "Not found.\n"); +} + +static int help(void) { + + printf("%s [OPTIONS...] ...\n\n" + "HTTP server for journal events.\n\n" + " -h --help Show this help\n" + " --version Show package version\n" + " --cert=CERT.PEM Server certificate in PEM format\n" + " --key=KEY.PEM Server key in PEM format\n" + " --trust=CERT.PEM Certificat authority certificate in PEM format\n", + program_invocation_short_name); + + return 0; +} + +static int parse_argv(int argc, char *argv[]) { + enum { + ARG_VERSION = 0x100, + ARG_KEY, + ARG_CERT, + ARG_TRUST, + }; + + int r, c; + + static const struct option options[] = { + { "help", no_argument, NULL, 'h' }, + { "version", no_argument, NULL, ARG_VERSION }, + { "key", required_argument, NULL, ARG_KEY }, + { "cert", required_argument, NULL, ARG_CERT }, + { "trust", required_argument, NULL, ARG_TRUST }, + {} + }; + + assert(argc >= 0); + assert(argv); + + while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) + + switch(c) { + + case 'h': + return help(); + + case ARG_VERSION: + puts(PACKAGE_STRING); + puts(SYSTEMD_FEATURES); + return 0; + + case ARG_KEY: + if (key_pem) { + log_error("Key file specified twice"); + return -EINVAL; + } + r = read_full_file(optarg, &key_pem, NULL); + if (r < 0) { + log_error("Failed to read key file: %s", strerror(-r)); + return r; + } + assert(key_pem); + break; + + case ARG_CERT: + if (cert_pem) { + log_error("Certificate file specified twice"); + return -EINVAL; + } + r = read_full_file(optarg, &cert_pem, NULL); + if (r < 0) { + log_error("Failed to read certificate file: %s", strerror(-r)); + return r; + } + assert(cert_pem); + break; + + case ARG_TRUST: +#ifdef HAVE_GNUTLS + if (trust_pem) { + log_error("CA certificate file specified twice"); + return -EINVAL; + } + r = read_full_file(optarg, &trust_pem, NULL); + if (r < 0) { + log_error("Failed to read CA certificate file: %s", strerror(-r)); + return r; + } + assert(trust_pem); + break; +#else + log_error("Option --trust is not available."); +#endif + + case '?': + return -EINVAL; + + default: + assert_not_reached("Unhandled option"); + } + + if (optind < argc) { + log_error("This program does not take arguments."); + return -EINVAL; + } + + if (!!key_pem != !!cert_pem) { + log_error("Certificate and key files must be specified together"); + return -EINVAL; + } + + if (trust_pem && !key_pem) { + log_error("CA certificate can only be used with certificate file"); + return -EINVAL; + } + + return 1; +} + +int main(int argc, char *argv[]) { + struct MHD_Daemon *d = NULL; + int r, n; + + log_set_target(LOG_TARGET_AUTO); + log_parse_environment(); + log_open(); + + r = parse_argv(argc, argv); + if (r < 0) + return EXIT_FAILURE; + if (r == 0) + return EXIT_SUCCESS; + +#ifdef HAVE_GNUTLS + gnutls_global_set_log_function(log_func_gnutls); + log_reset_gnutls_level(); +#endif + + n = sd_listen_fds(1); + if (n < 0) { + log_error("Failed to determine passed sockets: %s", strerror(-n)); + goto finish; + } else if (n > 1) { + log_error("Can't listen on more than one socket."); + goto finish; + } else { + struct MHD_OptionItem opts[] = { + { MHD_OPTION_NOTIFY_COMPLETED, + (intptr_t) request_meta_free, NULL }, + { MHD_OPTION_EXTERNAL_LOGGER, + (intptr_t) microhttpd_logger, NULL }, + { MHD_OPTION_END, 0, NULL }, + { MHD_OPTION_END, 0, NULL }, + { MHD_OPTION_END, 0, NULL }, + { MHD_OPTION_END, 0, NULL }, + { MHD_OPTION_END, 0, NULL }}; + int opts_pos = 2; + int flags = MHD_USE_THREAD_PER_CONNECTION|MHD_USE_POLL|MHD_USE_DEBUG; + + if (n > 0) + opts[opts_pos++] = (struct MHD_OptionItem) + {MHD_OPTION_LISTEN_SOCKET, SD_LISTEN_FDS_START}; + if (key_pem) { + assert(cert_pem); + opts[opts_pos++] = (struct MHD_OptionItem) + {MHD_OPTION_HTTPS_MEM_KEY, 0, key_pem}; + opts[opts_pos++] = (struct MHD_OptionItem) + {MHD_OPTION_HTTPS_MEM_CERT, 0, cert_pem}; + flags |= MHD_USE_SSL; + } + if (trust_pem) { + assert(flags & MHD_USE_SSL); + opts[opts_pos++] = (struct MHD_OptionItem) + {MHD_OPTION_HTTPS_MEM_TRUST, 0, trust_pem}; + } + + d = MHD_start_daemon(flags, 19531, + NULL, NULL, + request_handler, NULL, + MHD_OPTION_ARRAY, opts, + MHD_OPTION_END); + } + + if (!d) { + log_error("Failed to start daemon!"); + goto finish; + } + + pause(); + + r = EXIT_SUCCESS; + +finish: + if (d) + MHD_stop_daemon(d); + + return r; +} diff --git a/src/journal-remote/journal-remote-parse.c b/src/journal-remote/journal-remote-parse.c new file mode 100644 index 0000000000..dbdf02aa3c --- /dev/null +++ b/src/journal-remote/journal-remote-parse.c @@ -0,0 +1,439 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2014 Zbigniew Jędrzejewski-Szmek + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#include "journal-remote-parse.h" +#include "journald-native.h" + +#define LINE_CHUNK 1024u + +void source_free(RemoteSource *source) { + if (!source) + return; + + if (source->fd >= 0) { + log_debug("Closing fd:%d (%s)", source->fd, source->name); + close(source->fd); + } + free(source->name); + free(source->buf); + iovw_free_contents(&source->iovw); + free(source); +} + +static int get_line(RemoteSource *source, char **line, size_t *size) { + ssize_t n, remain; + char *c = NULL; + char *newbuf = NULL; + size_t newsize = 0; + + assert(source); + assert(source->state == STATE_LINE); + assert(source->filled <= source->size); + assert(source->buf == NULL || source->size > 0); + + if (source->buf) + c = memchr(source->buf, '\n', source->filled); + + if (c != NULL) + goto docopy; + + resize: + if (source->fd < 0) + /* we have to wait for some data to come to us */ + return -EWOULDBLOCK; + + if (source->size - source->filled < LINE_CHUNK) { + // XXX: add check for maximum line length + + if (!GREEDY_REALLOC(source->buf, source->size, + source->filled + LINE_CHUNK)) + return log_oom(); + } + assert(source->size - source->filled >= LINE_CHUNK); + + n = read(source->fd, source->buf + source->filled, + source->size - source->filled); + if (n < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) + log_error("read(%d, ..., %zd): %m", source->fd, + source->size - source->filled); + return -errno; + } else if (n == 0) + return 0; + + c = memchr(source->buf + source->filled, '\n', n); + source->filled += n; + + if (c == NULL) + goto resize; + + docopy: + *line = source->buf; + *size = c + 1 - source->buf; + + /* Check if something remains */ + remain = source->buf + source->filled - c - 1; + assert(remain >= 0); + if (remain) { + newsize = MAX(remain, LINE_CHUNK); + newbuf = malloc(newsize); + if (!newbuf) + return log_oom(); + memcpy(newbuf, c + 1, remain); + } + source->buf = newbuf; + source->size = newsize; + source->filled = remain; + + return 1; +} + +int push_data(RemoteSource *source, const char *data, size_t size) { + assert(source); + assert(source->state != STATE_EOF); + + if (!GREEDY_REALLOC(source->buf, source->size, + source->filled + size)) + return log_oom(); + + memcpy(source->buf + source->filled, data, size); + source->filled += size; + + return 0; +} + +static int fill_fixed_size(RemoteSource *source, void **data, size_t size) { + int n; + char *newbuf = NULL; + size_t newsize = 0, remain; + + assert(source); + assert(source->state == STATE_DATA_START || + source->state == STATE_DATA || + source->state == STATE_DATA_FINISH); + assert(size <= DATA_SIZE_MAX); + assert(source->filled <= source->size); + assert(source->buf != NULL || source->size == 0); + assert(source->buf == NULL || source->size > 0); + assert(data); + + while(source->filled < size) { + if (source->fd < 0) + /* we have to wait for some data to come to us */ + return -EWOULDBLOCK; + + if (!GREEDY_REALLOC(source->buf, source->size, size)) + return log_oom(); + + n = read(source->fd, source->buf + source->filled, + source->size - source->filled); + if (n < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) + log_error("read(%d, ..., %zd): %m", source->fd, + source->size - source->filled); + return -errno; + } else if (n == 0) + return 0; + + source->filled += n; + } + + *data = source->buf; + + /* Check if something remains */ + assert(size <= source->filled); + remain = source->filled - size; + if (remain) { + newsize = MAX(remain, LINE_CHUNK); + newbuf = malloc(newsize); + if (!newbuf) + return log_oom(); + memcpy(newbuf, source->buf + size, remain); + } + source->buf = newbuf; + source->size = newsize; + source->filled = remain; + + return 1; +} + +static int get_data_size(RemoteSource *source) { + int r; + _cleanup_free_ void *data = NULL; + + assert(source); + assert(source->state == STATE_DATA_START); + assert(source->data_size == 0); + + r = fill_fixed_size(source, &data, sizeof(uint64_t)); + if (r <= 0) + return r; + + source->data_size = le64toh( *(uint64_t *) data ); + if (source->data_size > DATA_SIZE_MAX) { + log_error("Stream declares field with size %zu > %u == DATA_SIZE_MAX", + source->data_size, DATA_SIZE_MAX); + return -EINVAL; + } + if (source->data_size == 0) + log_warning("Binary field with zero length"); + + return 1; +} + +static int get_data_data(RemoteSource *source, void **data) { + int r; + + assert(source); + assert(data); + assert(source->state == STATE_DATA); + + r = fill_fixed_size(source, data, source->data_size); + if (r <= 0) + return r; + + return 1; +} + +static int get_data_newline(RemoteSource *source) { + int r; + _cleanup_free_ char *data = NULL; + + assert(source); + assert(source->state == STATE_DATA_FINISH); + + r = fill_fixed_size(source, (void**) &data, 1); + if (r <= 0) + return r; + + assert(data); + if (*data != '\n') { + log_error("expected newline, got '%c'", *data); + return -EINVAL; + } + + return 1; +} + +static int process_dunder(RemoteSource *source, char *line, size_t n) { + const char *timestamp; + int r; + + assert(line); + assert(n > 0); + assert(line[n-1] == '\n'); + + /* XXX: is it worth to support timestamps in extended format? + * We don't produce them, but who knows... */ + + timestamp = startswith(line, "__CURSOR="); + if (timestamp) + /* ignore __CURSOR */ + return 1; + + timestamp = startswith(line, "__REALTIME_TIMESTAMP="); + if (timestamp) { + long long unsigned x; + line[n-1] = '\0'; + r = safe_atollu(timestamp, &x); + if (r < 0) + log_warning("Failed to parse __REALTIME_TIMESTAMP: '%s'", timestamp); + else + source->ts.realtime = x; + return r < 0 ? r : 1; + } + + timestamp = startswith(line, "__MONOTONIC_TIMESTAMP="); + if (timestamp) { + long long unsigned x; + line[n-1] = '\0'; + r = safe_atollu(timestamp, &x); + if (r < 0) + log_warning("Failed to parse __MONOTONIC_TIMESTAMP: '%s'", timestamp); + else + source->ts.monotonic = x; + return r < 0 ? r : 1; + } + + timestamp = startswith(line, "__"); + if (timestamp) { + log_notice("Unknown dunder line %s", line); + return 1; + } + + /* no dunder */ + return 0; +} + +int process_data(RemoteSource *source) { + int r; + + switch(source->state) { + case STATE_LINE: { + char *line, *sep; + size_t n; + + assert(source->data_size == 0); + + r = get_line(source, &line, &n); + if (r < 0) + return r; + if (r == 0) { + source->state = STATE_EOF; + return r; + } + assert(n > 0); + assert(line[n-1] == '\n'); + + if (n == 1) { + log_debug("Received empty line, event is ready"); + free(line); + return 1; + } + + r = process_dunder(source, line, n); + if (r != 0) { + free(line); + return r < 0 ? r : 0; + } + + /* MESSAGE=xxx\n + or + COREDUMP\n + LLLLLLLL0011223344...\n + */ + sep = memchr(line, '=', n); + if (sep) + /* chomp newline */ + n--; + else + /* replace \n with = */ + line[n-1] = '='; + log_debug("Received: %.*s", (int) n, line); + + r = iovw_put(&source->iovw, line, n); + if (r < 0) { + log_error("Failed to put line in iovect"); + free(line); + return r; + } + + if (!sep) + source->state = STATE_DATA_START; + return 0; /* continue */ + } + + case STATE_DATA_START: + assert(source->data_size == 0); + + r = get_data_size(source); + log_debug("get_data_size() -> %d", r); + if (r < 0) + return r; + if (r == 0) { + source->state = STATE_EOF; + return 0; + } + + source->state = source->data_size > 0 ? + STATE_DATA : STATE_DATA_FINISH; + + return 0; /* continue */ + + case STATE_DATA: { + void *data; + + assert(source->data_size > 0); + + r = get_data_data(source, &data); + log_debug("get_data_data() -> %d", r); + if (r < 0) + return r; + if (r == 0) { + source->state = STATE_EOF; + return 0; + } + + assert(data); + + r = iovw_put(&source->iovw, data, source->data_size); + if (r < 0) { + log_error("failed to put binary buffer in iovect"); + return r; + } + + source->state = STATE_DATA_FINISH; + + return 0; /* continue */ + } + + case STATE_DATA_FINISH: + r = get_data_newline(source); + log_debug("get_data_newline() -> %d", r); + if (r < 0) + return r; + if (r == 0) { + source->state = STATE_EOF; + return 0; + } + + source->data_size = 0; + source->state = STATE_LINE; + + return 0; /* continue */ + default: + assert_not_reached("wtf?"); + } +} + +int process_source(RemoteSource *source, Writer *writer, bool compress, bool seal) { + int r; + + assert(source); + assert(writer); + + r = process_data(source); + if (r <= 0) + return r; + + /* We have a full event */ + log_info("Received a full event from source@%p fd:%d (%s)", + source, source->fd, source->name); + + if (!source->iovw.count) { + log_warning("Entry with no payload, skipping"); + goto freeing; + } + + assert(source->iovw.iovec); + assert(source->iovw.count); + + r = writer_write(writer, &source->iovw, &source->ts, compress, seal); + if (r < 0) + log_error("Failed to write entry of %zu bytes: %s", + iovw_size(&source->iovw), strerror(-r)); + else + r = 1; + + freeing: + iovw_free_contents(&source->iovw); + return r; +} diff --git a/src/journal-remote/journal-remote-parse.h b/src/journal-remote/journal-remote-parse.h new file mode 100644 index 0000000000..c1506d118d --- /dev/null +++ b/src/journal-remote/journal-remote-parse.h @@ -0,0 +1,61 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2014 Zbigniew Jędrzejewski-Szmek + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#pragma once + +#include "sd-event.h" +#include "journal-remote-write.h" + +typedef enum { + STATE_LINE = 0, /* waiting to read, or reading line */ + STATE_DATA_START, /* reading binary data header */ + STATE_DATA, /* reading binary data */ + STATE_DATA_FINISH, /* expecting newline */ + STATE_EOF, /* done */ +} source_state; + +typedef struct RemoteSource { + char* name; + int fd; + + char *buf; + size_t size; + size_t filled; + size_t data_size; + + struct iovec_wrapper iovw; + + source_state state; + dual_timestamp ts; + + sd_event_source *event; +} RemoteSource; + +static inline int source_non_empty(RemoteSource *source) { + assert(source); + + return source->filled > 0; +} + +void source_free(RemoteSource *source); +int process_data(RemoteSource *source); +int push_data(RemoteSource *source, const char *data, size_t size); +int process_source(RemoteSource *source, Writer *writer, bool compress, bool seal); diff --git a/src/journal-remote/journal-remote-write.c b/src/journal-remote/journal-remote-write.c new file mode 100644 index 0000000000..4d142bdc97 --- /dev/null +++ b/src/journal-remote/journal-remote-write.c @@ -0,0 +1,124 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2012 Zbigniew Jędrzejewski-Szmek + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#include "journal-remote-write.h" + +int iovw_put(struct iovec_wrapper *iovw, void* data, size_t len) { + if (!GREEDY_REALLOC(iovw->iovec, iovw->size_bytes, iovw->count + 1)) + return log_oom(); + + iovw->iovec[iovw->count++] = (struct iovec) {data, len}; + return 0; +} + +void iovw_free_contents(struct iovec_wrapper *iovw) { + for (size_t j = 0; j < iovw->count; j++) + free(iovw->iovec[j].iov_base); + free(iovw->iovec); + iovw->iovec = NULL; + iovw->size_bytes = iovw->count = 0; +} + +size_t iovw_size(struct iovec_wrapper *iovw) { + size_t n = 0, i; + + for(i = 0; i < iovw->count; i++) + n += iovw->iovec[i].iov_len; + + return n; +} + +/********************************************************************** + ********************************************************************** + **********************************************************************/ + +static int do_rotate(JournalFile **f, bool compress, bool seal) { + int r = journal_file_rotate(f, compress, seal); + if (r < 0) { + if (*f) + log_error("Failed to rotate %s: %s", (*f)->path, + strerror(-r)); + else + log_error("Failed to create rotated journal: %s", + strerror(-r)); + } + + return r; +} + +int writer_init(Writer *s) { + assert(s); + + s->journal = NULL; + + memset(&s->metrics, 0xFF, sizeof(s->metrics)); + + s->mmap = mmap_cache_new(); + if (!s->mmap) + return log_oom(); + + s->seqnum = 0; + + return 0; +} + +int writer_close(Writer *s) { + if (s->journal) + journal_file_close(s->journal); + if (s->mmap) + mmap_cache_unref(s->mmap); + return 0; +} + +int writer_write(Writer *s, + struct iovec_wrapper *iovw, + dual_timestamp *ts, + bool compress, + bool seal) { + int r; + + assert(s); + assert(iovw); + assert(iovw->count > 0); + + if (journal_file_rotate_suggested(s->journal, 0)) { + log_info("%s: Journal header limits reached or header out-of-date, rotating", + s->journal->path); + r = do_rotate(&s->journal, compress, seal); + if (r < 0) + return r; + } + + r = journal_file_append_entry(s->journal, ts, iovw->iovec, iovw->count, + &s->seqnum, NULL, NULL); + if (r >= 0) + return 1; + + log_info("%s: Write failed, rotating", s->journal->path); + r = do_rotate(&s->journal, compress, seal); + if (r < 0) + return r; + + log_debug("Retrying write."); + r = journal_file_append_entry(s->journal, ts, iovw->iovec, iovw->count, + &s->seqnum, NULL, NULL); + return r < 0 ? r : 1; +} diff --git a/src/journal-remote/journal-remote-write.h b/src/journal-remote/journal-remote-write.h new file mode 100644 index 0000000000..8798216415 --- /dev/null +++ b/src/journal-remote/journal-remote-write.h @@ -0,0 +1,51 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2014 Zbigniew Jędrzejewski-Szmek + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#pragma once + +#include + +#include "journal-file.h" + +struct iovec_wrapper { + struct iovec *iovec; + size_t size_bytes; + size_t count; +}; + +int iovw_put(struct iovec_wrapper *iovw, void* data, size_t len); +void iovw_free_contents(struct iovec_wrapper *iovw); +size_t iovw_size(struct iovec_wrapper *iovw); + +typedef struct Writer { + JournalFile *journal; + JournalMetrics metrics; + MMapCache *mmap; + uint64_t seqnum; +} Writer; + +int writer_init(Writer *s); +int writer_close(Writer *s); +int writer_write(Writer *s, + struct iovec_wrapper *iovw, + dual_timestamp *ts, + bool compress, + bool seal); diff --git a/src/journal-remote/journal-remote.c b/src/journal-remote/journal-remote.c new file mode 100644 index 0000000000..9db4692a28 --- /dev/null +++ b/src/journal-remote/journal-remote.c @@ -0,0 +1,1283 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2012 Zbigniew Jędrzejewski-Szmek + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sd-daemon.h" +#include "sd-event.h" +#include "journal-file.h" +#include "journald-native.h" +#include "socket-util.h" +#include "mkdir.h" +#include "build.h" +#include "macro.h" +#include "strv.h" +#include "fileio.h" +#include "microhttpd-util.h" + +#ifdef HAVE_GNUTLS +#include +#endif + +#include "journal-remote-parse.h" +#include "journal-remote-write.h" + +#define REMOTE_JOURNAL_PATH "/var/log/journal/" SD_ID128_FORMAT_STR "/remote-%s.journal" + +static char* arg_output = NULL; +static char* arg_url = NULL; +static char* arg_getter = NULL; +static char* arg_listen_raw = NULL; +static char* arg_listen_http = NULL; +static char* arg_listen_https = NULL; +static char** arg_files = NULL; +static int arg_compress = true; +static int arg_seal = false; +static int http_socket = -1, https_socket = -1; +static char** arg_gnutls_log = NULL; + +static char *key_pem = NULL; +static char *cert_pem = NULL; +static char *trust_pem = NULL; + +/********************************************************************** + ********************************************************************** + **********************************************************************/ + +static int spawn_child(const char* child, char** argv) { + int fd[2]; + pid_t parent_pid, child_pid; + int r; + + if (pipe(fd) < 0) { + log_error("Failed to create pager pipe: %m"); + return -errno; + } + + parent_pid = getpid(); + + child_pid = fork(); + if (child_pid < 0) { + r = -errno; + log_error("Failed to fork: %m"); + safe_close_pair(fd); + return r; + } + + /* In the child */ + if (child_pid == 0) { + r = dup2(fd[1], STDOUT_FILENO); + if (r < 0) { + log_error("Failed to dup pipe to stdout: %m"); + _exit(EXIT_FAILURE); + } + + safe_close_pair(fd); + + /* Make sure the child goes away when the parent dies */ + if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) + _exit(EXIT_FAILURE); + + /* Check whether our parent died before we were able + * to set the death signal */ + if (getppid() != parent_pid) + _exit(EXIT_SUCCESS); + + execvp(child, argv); + log_error("Failed to exec child %s: %m", child); + _exit(EXIT_FAILURE); + } + + r = close(fd[1]); + if (r < 0) + log_warning("Failed to close write end of pipe: %m"); + + return fd[0]; +} + +static int spawn_curl(char* url) { + char **argv = STRV_MAKE("curl", + "-HAccept: application/vnd.fdo.journal", + "--silent", + "--show-error", + url); + int r; + + r = spawn_child("curl", argv); + if (r < 0) + log_error("Failed to spawn curl: %m"); + return r; +} + +static int spawn_getter(char *getter, char *url) { + int r; + _cleanup_strv_free_ char **words = NULL; + + assert(getter); + words = strv_split_quoted(getter); + if (!words) + return log_oom(); + + r = spawn_child(words[0], words); + if (r < 0) + log_error("Failed to spawn getter %s: %m", getter); + + return r; +} + +static int open_output(Writer *s, const char* url) { + _cleanup_free_ char *name, *output = NULL; + char *c; + int r; + + assert(url); + name = strdup(url); + if (!name) + return log_oom(); + + for(c = name; *c; c++) { + if (*c == '/' || *c == ':' || *c == ' ') + *c = '~'; + else if (*c == '?') { + *c = '\0'; + break; + } + } + + if (!arg_output) { + sd_id128_t machine; + r = sd_id128_get_machine(&machine); + if (r < 0) { + log_error("failed to determine machine ID128: %s", strerror(-r)); + return r; + } + + r = asprintf(&output, REMOTE_JOURNAL_PATH, + SD_ID128_FORMAT_VAL(machine), name); + if (r < 0) + return log_oom(); + } else { + r = is_dir(arg_output, true); + if (r > 0) { + r = asprintf(&output, + "%s/remote-%s.journal", arg_output, name); + if (r < 0) + return log_oom(); + } else { + output = strdup(arg_output); + if (!output) + return log_oom(); + } + } + + r = journal_file_open_reliably(output, + O_RDWR|O_CREAT, 0640, + arg_compress, arg_seal, + &s->metrics, + s->mmap, + NULL, &s->journal); + if (r < 0) + log_error("Failed to open output journal %s: %s", + arg_output, strerror(-r)); + else + log_info("Opened output file %s", s->journal->path); + return r; +} + +/********************************************************************** + ********************************************************************** + **********************************************************************/ + +typedef struct MHDDaemonWrapper { + uint64_t fd; + struct MHD_Daemon *daemon; + + sd_event_source *event; +} MHDDaemonWrapper; + +typedef struct RemoteServer { + RemoteSource **sources; + size_t sources_size; + size_t active; + + sd_event *events; + sd_event_source *sigterm_event, *sigint_event, *listen_event; + + Writer writer; + + Hashmap *daemons; +} RemoteServer; + +/* This should go away as soon as µhttpd allows state to be passed around. */ +static RemoteServer *server; + +static int dispatch_raw_source_event(sd_event_source *event, + int fd, + uint32_t revents, + void *userdata); +static int dispatch_raw_connection_event(sd_event_source *event, + int fd, + uint32_t revents, + void *userdata); +static int dispatch_http_event(sd_event_source *event, + int fd, + uint32_t revents, + void *userdata); + +static int get_source_for_fd(RemoteServer *s, int fd, RemoteSource **source) { + assert(fd >= 0); + assert(source); + + if (!GREEDY_REALLOC0(s->sources, s->sources_size, fd + 1)) + return log_oom(); + + if (s->sources[fd] == NULL) { + s->sources[fd] = new0(RemoteSource, 1); + if (!s->sources[fd]) + return log_oom(); + s->sources[fd]->fd = -1; + s->active++; + } + + *source = s->sources[fd]; + return 0; +} + +static int remove_source(RemoteServer *s, int fd) { + RemoteSource *source; + + assert(s); + assert(fd >= 0 && fd < (ssize_t) s->sources_size); + + source = s->sources[fd]; + if (source) { + source_free(source); + s->sources[fd] = NULL; + s->active--; + } + + close(fd); + + return 0; +} + +static int add_source(RemoteServer *s, int fd, const char* name) { + RemoteSource *source = NULL; + _cleanup_free_ char *realname = NULL; + int r; + + assert(s); + assert(fd >= 0); + + if (name) { + realname = strdup(name); + if (!realname) + return log_oom(); + } else { + r = asprintf(&realname, "fd:%d", fd); + if (r < 0) + return log_oom(); + } + + log_debug("Creating source for fd:%d (%s)", fd, realname); + + r = get_source_for_fd(s, fd, &source); + if (r < 0) { + log_error("Failed to create source for fd:%d (%s)", fd, realname); + return r; + } + assert(source); + assert(source->fd < 0); + source->fd = fd; + + r = sd_event_add_io(s->events, &source->event, + fd, EPOLLIN, dispatch_raw_source_event, s); + if (r < 0) { + log_error("Failed to register event source for fd:%d: %s", + fd, strerror(-r)); + goto error; + } + + return 1; /* work to do */ + + error: + remove_source(s, fd); + return r; +} + +static int add_raw_socket(RemoteServer *s, int fd) { + int r; + + r = sd_event_add_io(s->events, &s->listen_event, fd, EPOLLIN, + dispatch_raw_connection_event, s); + if (r < 0) { + close(fd); + return r; + } + + s->active ++; + return 0; +} + +static int setup_raw_socket(RemoteServer *s, const char *address) { + int fd; + + fd = make_socket_fd(LOG_INFO, address, SOCK_STREAM | SOCK_CLOEXEC); + if (fd < 0) + return fd; + + return add_raw_socket(s, fd); +} + +/********************************************************************** + ********************************************************************** + **********************************************************************/ + +static RemoteSource *request_meta(void **connection_cls) { + RemoteSource *source; + + assert(connection_cls); + if (*connection_cls) + return *connection_cls; + + source = new0(RemoteSource, 1); + if (!source) + return NULL; + source->fd = -1; + + log_debug("Added RemoteSource as connection metadata %p", source); + + *connection_cls = source; + return source; +} + +static void request_meta_free(void *cls, + struct MHD_Connection *connection, + void **connection_cls, + enum MHD_RequestTerminationCode toe) { + RemoteSource *s; + + assert(connection_cls); + s = *connection_cls; + + log_debug("Cleaning up connection metadata %p", s); + source_free(s); + *connection_cls = NULL; +} + +static int process_http_upload( + struct MHD_Connection *connection, + const char *upload_data, + size_t *upload_data_size, + RemoteSource *source) { + + bool finished = false; + int r; + + assert(source); + + log_debug("request_handler_upload: connection %p, %zu bytes", + connection, *upload_data_size); + + if (*upload_data_size) { + log_info("Received %zu bytes", *upload_data_size); + + r = push_data(source, upload_data, *upload_data_size); + if (r < 0) { + log_error("Failed to store received data of size %zu: %s", + *upload_data_size, strerror(-r)); + return mhd_respond_oom(connection); + } + *upload_data_size = 0; + } else + finished = true; + + while (true) { + r = process_source(source, &server->writer, arg_compress, arg_seal); + if (r == -E2BIG) + log_warning("Entry too big, skipped"); + else if (r == -EAGAIN || r == -EWOULDBLOCK) + break; + else if (r < 0) { + log_warning("Failed to process data for connection %p", connection); + return mhd_respondf(connection, MHD_HTTP_UNPROCESSABLE_ENTITY, + "Processing failed: %s", strerror(-r)); + } + } + + if (!finished) + return MHD_YES; + + /* The upload is finished */ + + if (source_non_empty(source)) { + log_warning("EOF reached with incomplete data"); + return mhd_respond(connection, MHD_HTTP_EXPECTATION_FAILED, + "Trailing data not processed."); + } + + return mhd_respond(connection, MHD_HTTP_ACCEPTED, "OK.\n"); +}; + +static int request_handler( + void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, + size_t *upload_data_size, + void **connection_cls) { + + const char *header; + int r ,code; + + assert(connection); + assert(connection_cls); + assert(url); + assert(method); + + log_debug("Handling a connection %s %s %s", method, url, version); + + if (*connection_cls) + return process_http_upload(connection, + upload_data, upload_data_size, + *connection_cls); + + if (!streq(method, "POST")) + return mhd_respond(connection, MHD_HTTP_METHOD_NOT_ACCEPTABLE, + "Unsupported method.\n"); + + if (!streq(url, "/upload")) + return mhd_respond(connection, MHD_HTTP_NOT_FOUND, + "Not found.\n"); + + header = MHD_lookup_connection_value(connection, + MHD_HEADER_KIND, "Content-Type"); + if (!header || !streq(header, "application/vnd.fdo.journal")) + return mhd_respond(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE, + "Content-Type: application/vnd.fdo.journal" + " is required.\n"); + + if (trust_pem) { + r = check_permissions(connection, &code); + if (r < 0) + return code; + } + + if (!request_meta(connection_cls)) + return respond_oom(connection); + return MHD_YES; +} + +static int setup_microhttpd_server(RemoteServer *s, int fd, bool https) { + struct MHD_OptionItem opts[] = { + { MHD_OPTION_NOTIFY_COMPLETED, (intptr_t) request_meta_free}, + { MHD_OPTION_EXTERNAL_LOGGER, (intptr_t) microhttpd_logger}, + { MHD_OPTION_LISTEN_SOCKET, fd}, + { MHD_OPTION_END}, + { MHD_OPTION_END}, + { MHD_OPTION_END}, + { MHD_OPTION_END}}; + int opts_pos = 3; + int flags = + MHD_USE_DEBUG | + MHD_USE_PEDANTIC_CHECKS | + MHD_USE_EPOLL_LINUX_ONLY | + MHD_USE_DUAL_STACK; + + const union MHD_DaemonInfo *info; + int r, epoll_fd; + MHDDaemonWrapper *d; + + assert(fd >= 0); + + r = fd_nonblock(fd, true); + if (r < 0) { + log_error("Failed to make fd:%d nonblocking: %s", fd, strerror(-r)); + return r; + } + + if (https) { + opts[opts_pos++] = (struct MHD_OptionItem) + {MHD_OPTION_HTTPS_MEM_KEY, 0, key_pem}; + opts[opts_pos++] = (struct MHD_OptionItem) + {MHD_OPTION_HTTPS_MEM_CERT, 0, cert_pem}; + + flags |= MHD_USE_SSL; + + if (trust_pem) + opts[opts_pos++] = (struct MHD_OptionItem) + {MHD_OPTION_HTTPS_MEM_TRUST, 0, trust_pem}; + } + + d = new(MHDDaemonWrapper, 1); + if (!d) + return log_oom(); + + d->fd = (uint64_t) fd; + + d->daemon = MHD_start_daemon(flags, 0, + NULL, NULL, + request_handler, NULL, + MHD_OPTION_ARRAY, opts, + MHD_OPTION_END); + if (!d->daemon) { + log_error("Failed to start µhttp daemon"); + r = -EINVAL; + goto error; + } + + log_debug("Started MHD %s daemon on fd:%d (wrapper @ %p)", + https ? "HTTPS" : "HTTP", fd, d); + + + info = MHD_get_daemon_info(d->daemon, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY); + if (!info) { + log_error("µhttp returned NULL daemon info"); + r = -ENOTSUP; + goto error; + } + + epoll_fd = info->listen_fd; + if (epoll_fd < 0) { + log_error("µhttp epoll fd is invalid"); + r = -EUCLEAN; + goto error; + } + + r = sd_event_add_io(s->events, &d->event, + epoll_fd, EPOLLIN, dispatch_http_event, d); + if (r < 0) { + log_error("Failed to add event callback: %s", strerror(-r)); + goto error; + } + + r = hashmap_ensure_allocated(&s->daemons, uint64_hash_func, uint64_compare_func); + if (r < 0) { + log_oom(); + goto error; + } + + r = hashmap_put(s->daemons, &d->fd, d); + if (r < 0) { + log_error("Failed to add daemon to hashmap: %s", strerror(-r)); + goto error; + } + + s->active ++; + return 0; + +error: + MHD_stop_daemon(d->daemon); + free(d->daemon); + free(d); + return r; +} + +static int setup_microhttpd_socket(RemoteServer *s, + const char *address, + bool https) { + int fd; + + fd = make_socket_fd(LOG_INFO, address, SOCK_STREAM | SOCK_CLOEXEC); + if (fd < 0) + return fd; + + return setup_microhttpd_server(s, fd, https); +} + +static int dispatch_http_event(sd_event_source *event, + int fd, + uint32_t revents, + void *userdata) { + MHDDaemonWrapper *d = userdata; + int r; + + assert(d); + + log_info("%s", __func__); + + r = MHD_run(d->daemon); + if (r == MHD_NO) { + log_error("MHD_run failed!"); + // XXX: unregister daemon + return -EINVAL; + } + + return 1; /* work to do */ +} + +/********************************************************************** + ********************************************************************** + **********************************************************************/ + +static int dispatch_sigterm(sd_event_source *event, + const struct signalfd_siginfo *si, + void *userdata) { + RemoteServer *s = userdata; + + assert(s); + + log_received_signal(LOG_INFO, si); + + sd_event_exit(s->events, 0); + return 0; +} + +static int setup_signals(RemoteServer *s) { + sigset_t mask; + int r; + + assert(s); + + assert_se(sigemptyset(&mask) == 0); + sigset_add_many(&mask, SIGINT, SIGTERM, -1); + assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0); + + r = sd_event_add_signal(s->events, &s->sigterm_event, SIGTERM, dispatch_sigterm, s); + if (r < 0) + return r; + + r = sd_event_add_signal(s->events, &s->sigint_event, SIGINT, dispatch_sigterm, s); + if (r < 0) + return r; + + return 0; +} + +static int fd_fd(const char *spec) { + int fd, r; + + r = safe_atoi(spec, &fd); + if (r < 0) + return r; + + if (fd >= 0) + return -ENOENT; + + return -fd; +} + + +static int remoteserver_init(RemoteServer *s) { + int r, n, fd; + const char *output_name = NULL; + char **file; + + assert(s); + + sd_event_default(&s->events); + + setup_signals(s); + + assert(server == NULL); + server = s; + + n = sd_listen_fds(true); + if (n < 0) { + log_error("Failed to read listening file descriptors from environment: %s", + strerror(-n)); + return n; + } else + log_info("Received %d descriptors", n); + + if (MAX(http_socket, https_socket) >= SD_LISTEN_FDS_START + n) { + log_error("Received fewer sockets than expected"); + return -EBADFD; + } + + for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) { + if (sd_is_socket(fd, AF_UNSPEC, 0, false)) { + log_info("Received a listening socket (fd:%d)", fd); + + if (fd == http_socket) + r = setup_microhttpd_server(s, fd, false); + else if (fd == https_socket) + r = setup_microhttpd_server(s, fd, true); + else + r = add_raw_socket(s, fd); + } else if (sd_is_socket(fd, AF_UNSPEC, 0, true)) { + log_info("Received a connection socket (fd:%d)", fd); + + r = add_source(s, fd, NULL); + } else { + log_error("Unknown socket passed on fd:%d", fd); + + return -EINVAL; + } + + if(r < 0) { + log_error("Failed to register socket (fd:%d): %s", + fd, strerror(-r)); + return r; + } + + output_name = "socket"; + } + + if (arg_url) { + _cleanup_free_ char *url = NULL; + _cleanup_strv_free_ char **urlv = strv_new(arg_url, "/entries", NULL); + if (!urlv) + return log_oom(); + url = strv_join(urlv, ""); + if (!url) + return log_oom(); + + if (arg_getter) { + log_info("Spawning getter %s...", url); + fd = spawn_getter(arg_getter, url); + } else { + log_info("Spawning curl %s...", url); + fd = spawn_curl(url); + } + if (fd < 0) + return fd; + + r = add_source(s, fd, arg_url); + if (r < 0) + return r; + + output_name = arg_url; + } + + if (arg_listen_raw) { + log_info("Listening on a socket..."); + r = setup_raw_socket(s, arg_listen_raw); + if (r < 0) + return r; + + output_name = arg_listen_raw; + } + + if (arg_listen_http) { + r = setup_microhttpd_socket(s, arg_listen_http, false); + if (r < 0) + return r; + + output_name = arg_listen_http; + } + + if (arg_listen_https) { + r = setup_microhttpd_socket(s, arg_listen_https, true); + if (r < 0) + return r; + + output_name = arg_listen_https; + } + + STRV_FOREACH(file, arg_files) { + if (streq(*file, "-")) { + log_info("Reading standard input..."); + + fd = STDIN_FILENO; + output_name = "stdin"; + } else { + log_info("Reading file %s...", *file); + + fd = open(*file, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK); + if (fd < 0) { + log_error("Failed to open %s: %m", *file); + return -errno; + } + output_name = *file; + } + + r = add_source(s, fd, output_name); + if (r < 0) + return r; + } + + if (s->active == 0) { + log_error("Zarro sources specified"); + return -EINVAL; + } + + if (!!n + !!arg_url + !!arg_listen_raw + !!arg_files) + output_name = "multiple"; + + r = writer_init(&s->writer); + if (r < 0) + return r; + + r = open_output(&s->writer, output_name); + return r; +} + +static int server_destroy(RemoteServer *s) { + int r; + size_t i; + MHDDaemonWrapper *d; + + r = writer_close(&s->writer); + + while ((d = hashmap_steal_first(s->daemons))) { + MHD_stop_daemon(d->daemon); + sd_event_source_unref(d->event); + free(d); + } + + hashmap_free(s->daemons); + + assert(s->sources_size == 0 || s->sources); + for (i = 0; i < s->sources_size; i++) + remove_source(s, i); + + free(s->sources); + + sd_event_source_unref(s->sigterm_event); + sd_event_source_unref(s->sigint_event); + sd_event_source_unref(s->listen_event); + sd_event_unref(s->events); + + /* fds that we're listening on remain open... */ + + return r; +} + +/********************************************************************** + ********************************************************************** + **********************************************************************/ + +static int dispatch_raw_source_event(sd_event_source *event, + int fd, + uint32_t revents, + void *userdata) { + + RemoteServer *s = userdata; + RemoteSource *source; + int r; + + assert(fd >= 0 && fd < (ssize_t) s->sources_size); + source = s->sources[fd]; + assert(source->fd == fd); + + r = process_source(source, &s->writer, arg_compress, arg_seal); + if (source->state == STATE_EOF) { + log_info("EOF reached with source fd:%d (%s)", + source->fd, source->name); + if (source_non_empty(source)) + log_warning("EOF reached with incomplete data"); + remove_source(s, source->fd); + log_info("%zd active source remaining", s->active); + } else if (r == -E2BIG) { + log_error("Entry too big, skipped"); + r = 1; + } + + return r; +} + +static int accept_connection(const char* type, int fd, SocketAddress *addr) { + int fd2, r; + + log_debug("Accepting new %s connection on fd:%d", type, fd); + fd2 = accept4(fd, &addr->sockaddr.sa, &addr->size, SOCK_NONBLOCK|SOCK_CLOEXEC); + if (fd2 < 0) { + log_error("accept() on fd:%d failed: %m", fd); + return -errno; + } + + switch(socket_address_family(addr)) { + case AF_INET: + case AF_INET6: { + char* _cleanup_free_ a = NULL; + + r = socket_address_print(addr, &a); + if (r < 0) { + log_error("socket_address_print(): %s", strerror(-r)); + close(fd2); + return r; + } + + log_info("Accepted %s %s connection from %s", + type, + socket_address_family(addr) == AF_INET ? "IP" : "IPv6", + a); + + return fd2; + }; + default: + log_error("Rejected %s connection with unsupported family %d", + type, socket_address_family(addr)); + close(fd2); + + return -EINVAL; + } +} + +static int dispatch_raw_connection_event(sd_event_source *event, + int fd, + uint32_t revents, + void *userdata) { + RemoteServer *s = userdata; + int fd2; + SocketAddress addr = { + .size = sizeof(union sockaddr_union), + .type = SOCK_STREAM, + }; + + fd2 = accept_connection("raw", fd, &addr); + if (fd2 < 0) + return fd2; + + return add_source(s, fd2, NULL); +} + +/********************************************************************** + ********************************************************************** + **********************************************************************/ + +static int help(void) { + printf("%s [OPTIONS...] {FILE|-}...\n\n" + "Write external journal events to a journal file.\n\n" + "Options:\n" + " --url=URL Read events from systemd-journal-gatewayd at URL\n" + " --getter=COMMAND Read events from the output of COMMAND\n" + " --listen-raw=ADDR Listen for connections at ADDR\n" + " --listen-http=ADDR Listen for HTTP connections at ADDR\n" + " --listen-https=ADDR Listen for HTTPS connections at ADDR\n" + " -o --output=FILE|DIR Write output to FILE or DIR/external-*.journal\n" + " --[no-]compress Use XZ-compression in the output journal (default: yes)\n" + " --[no-]seal Use Event sealing in the output journal (default: no)\n" + " --key=FILENAME Specify key in PEM format\n" + " --cert=FILENAME Specify certificate in PEM format\n" + " --trust=FILENAME Specify CA certificate in PEM format\n" + " --gnutls-log=CATEGORY...\n" + " Specify a list of gnutls logging categories\n" + " -h --help Show this help and exit\n" + " --version Print version string and exit\n" + "\n" + "Note: file descriptors from sd_listen_fds() will be consumed, too.\n" + , program_invocation_short_name); + + return 0; +} + +static int parse_argv(int argc, char *argv[]) { + enum { + ARG_VERSION = 0x100, + ARG_URL, + ARG_LISTEN_RAW, + ARG_LISTEN_HTTP, + ARG_LISTEN_HTTPS, + ARG_GETTER, + ARG_COMPRESS, + ARG_NO_COMPRESS, + ARG_SEAL, + ARG_NO_SEAL, + ARG_KEY, + ARG_CERT, + ARG_TRUST, + ARG_GNUTLS_LOG, + }; + + static const struct option options[] = { + { "help", no_argument, NULL, 'h' }, + { "version", no_argument, NULL, ARG_VERSION }, + { "url", required_argument, NULL, ARG_URL }, + { "getter", required_argument, NULL, ARG_GETTER }, + { "listen-raw", required_argument, NULL, ARG_LISTEN_RAW }, + { "listen-http", required_argument, NULL, ARG_LISTEN_HTTP }, + { "listen-https", required_argument, NULL, ARG_LISTEN_HTTPS }, + { "output", required_argument, NULL, 'o' }, + { "compress", no_argument, NULL, ARG_COMPRESS }, + { "no-compress", no_argument, NULL, ARG_NO_COMPRESS }, + { "seal", no_argument, NULL, ARG_SEAL }, + { "no-seal", no_argument, NULL, ARG_NO_SEAL }, + { "key", required_argument, NULL, ARG_KEY }, + { "cert", required_argument, NULL, ARG_CERT }, + { "trust", required_argument, NULL, ARG_TRUST }, + { "gnutls-log", required_argument, NULL, ARG_GNUTLS_LOG }, + {} + }; + + int c, r; + + assert(argc >= 0); + assert(argv); + + while ((c = getopt_long(argc, argv, "ho:", options, NULL)) >= 0) + switch(c) { + case 'h': + help(); + return 0 /* done */; + + case ARG_VERSION: + puts(PACKAGE_STRING); + puts(SYSTEMD_FEATURES); + return 0 /* done */; + + case ARG_URL: + if (arg_url) { + log_error("cannot currently set more than one --url"); + return -EINVAL; + } + + arg_url = optarg; + break; + + case ARG_GETTER: + if (arg_getter) { + log_error("cannot currently use --getter more than once"); + return -EINVAL; + } + + arg_getter = optarg; + break; + + case ARG_LISTEN_RAW: + if (arg_listen_raw) { + log_error("cannot currently use --listen-raw more than once"); + return -EINVAL; + } + + arg_listen_raw = optarg; + break; + + case ARG_LISTEN_HTTP: + if (arg_listen_http || http_socket >= 0) { + log_error("cannot currently use --listen-http more than once"); + return -EINVAL; + } + + r = fd_fd(optarg); + if (r >= 0) + http_socket = r; + else if (r == -ENOENT) + arg_listen_http = optarg; + else { + log_error("Invalid port/fd specification %s: %s", + optarg, strerror(-r)); + return -EINVAL; + } + + break; + + case ARG_LISTEN_HTTPS: + if (arg_listen_https || https_socket >= 0) { + log_error("cannot currently use --listen-https more than once"); + return -EINVAL; + } + + r = fd_fd(optarg); + if (r >= 0) + https_socket = r; + else if (r == -ENOENT) + arg_listen_https = optarg; + else { + log_error("Invalid port/fd specification %s: %s", + optarg, strerror(-r)); + return -EINVAL; + } + + break; + + case ARG_KEY: + if (key_pem) { + log_error("Key file specified twice"); + return -EINVAL; + } + r = read_full_file(optarg, &key_pem, NULL); + if (r < 0) { + log_error("Failed to read key file: %s", strerror(-r)); + return r; + } + assert(key_pem); + break; + + case ARG_CERT: + if (cert_pem) { + log_error("Certificate file specified twice"); + return -EINVAL; + } + r = read_full_file(optarg, &cert_pem, NULL); + if (r < 0) { + log_error("Failed to read certificate file: %s", strerror(-r)); + return r; + } + assert(cert_pem); + break; + + case ARG_TRUST: +#ifdef HAVE_GNUTLS + if (trust_pem) { + log_error("CA certificate file specified twice"); + return -EINVAL; + } + r = read_full_file(optarg, &trust_pem, NULL); + if (r < 0) { + log_error("Failed to read CA certificate file: %s", strerror(-r)); + return r; + } + assert(trust_pem); + break; +#else + log_error("Option --trust is not available."); + return -EINVAL; +#endif + + case 'o': + if (arg_output) { + log_error("cannot use --output/-o more than once"); + return -EINVAL; + } + + arg_output = optarg; + break; + + case ARG_COMPRESS: + arg_compress = true; + break; + case ARG_NO_COMPRESS: + arg_compress = false; + break; + case ARG_SEAL: + arg_seal = true; + break; + case ARG_NO_SEAL: + arg_seal = false; + break; + + case ARG_GNUTLS_LOG: { +#ifdef HAVE_GNUTLS + char *word, *state; + size_t size; + + FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) { + char *cat; + + cat = strndup(word, size); + if (!cat) + return log_oom(); + + if (strv_consume(&arg_gnutls_log, cat) < 0) + return log_oom(); + } + break; +#else + log_error("Option --gnutls-log is not available."); + return -EINVAL; +#endif + } + + case '?': + return -EINVAL; + + default: + log_error("Unknown option code %c", c); + return -EINVAL; + } + + if (arg_listen_https && !(key_pem && cert_pem)) { + log_error("Options --key and --cert must be used when https sources are specified"); + return -EINVAL; + } + + if (optind < argc) + arg_files = argv + optind; + + return 1 /* work to do */; +} + +static int setup_gnutls_logger(char **categories) { + if (!arg_listen_http && !arg_listen_https) + return 0; + +#ifdef HAVE_GNUTLS + { + char **cat; + int r; + + gnutls_global_set_log_function(log_func_gnutls); + + if (categories) + STRV_FOREACH(cat, categories) { + r = log_enable_gnutls_category(*cat); + if (r < 0) + return r; + } + else + log_reset_gnutls_level(); + } +#endif + + return 0; +} + +int main(int argc, char **argv) { + RemoteServer s = {}; + int r, r2; + + log_set_max_level(LOG_DEBUG); + log_show_color(true); + log_parse_environment(); + + r = parse_argv(argc, argv); + if (r <= 0) + return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE; + + r = setup_gnutls_logger(arg_gnutls_log); + if (r < 0) + return EXIT_FAILURE; + + if (remoteserver_init(&s) < 0) + return EXIT_FAILURE; + + log_debug("%s running as pid "PID_FMT, + program_invocation_short_name, getpid()); + sd_notify(false, + "READY=1\n" + "STATUS=Processing requests..."); + + while (s.active) { + r = sd_event_get_state(s.events); + if (r < 0) + break; + if (r == SD_EVENT_FINISHED) + break; + + r = sd_event_run(s.events, -1); + if (r < 0) { + log_error("Failed to run event loop: %s", strerror(-r)); + break; + } + } + + log_info("Finishing after writing %" PRIu64 " entries", s.writer.seqnum); + r2 = server_destroy(&s); + + sd_notify(false, "STATUS=Shutting down..."); + + return r >= 0 && r2 >= 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/src/journal-remote/microhttpd-util.c b/src/journal-remote/microhttpd-util.c new file mode 100644 index 0000000000..d0466867b7 --- /dev/null +++ b/src/journal-remote/microhttpd-util.c @@ -0,0 +1,298 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2012 Lennart Poettering + Copyright 2012 Zbigniew Jędrzejewski-Szmek + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#include +#include +#include + +#include "microhttpd-util.h" +#include "log.h" +#include "macro.h" +#include "util.h" +#include "strv.h" + +#ifdef HAVE_GNUTLS +#include +#include +#endif + +void microhttpd_logger(void *arg, const char *fmt, va_list ap) { + char *f; + + f = strappenda("microhttpd: ", fmt); + + DISABLE_WARNING_FORMAT_NONLITERAL; + log_metav(LOG_INFO, NULL, 0, NULL, f, ap); + REENABLE_WARNING; +} + + +static int mhd_respond_internal(struct MHD_Connection *connection, + enum MHD_RequestTerminationCode code, + char *buffer, + size_t size, + enum MHD_ResponseMemoryMode mode) { + struct MHD_Response *response; + int r; + + assert(connection); + + response = MHD_create_response_from_buffer(size, buffer, mode); + if (!response) + return MHD_NO; + + log_debug("Queing response %u: %s", code, buffer); + MHD_add_response_header(response, "Content-Type", "text/plain"); + r = MHD_queue_response(connection, code, response); + MHD_destroy_response(response); + + return r; +} + +int mhd_respond(struct MHD_Connection *connection, + enum MHD_RequestTerminationCode code, + const char *message) { + + return mhd_respond_internal(connection, code, + (char*) message, strlen(message), + MHD_RESPMEM_PERSISTENT); +} + +int mhd_respond_oom(struct MHD_Connection *connection) { + return mhd_respond(connection, MHD_HTTP_SERVICE_UNAVAILABLE, "Out of memory.\n"); +} + +int mhd_respondf(struct MHD_Connection *connection, + enum MHD_RequestTerminationCode code, + const char *format, ...) { + + char *m; + int r; + va_list ap; + + assert(connection); + assert(format); + + va_start(ap, format); + r = vasprintf(&m, format, ap); + va_end(ap); + + if (r < 0) + return respond_oom(connection); + + return mhd_respond_internal(connection, code, m, r, MHD_RESPMEM_MUST_FREE); +} + +#ifdef HAVE_GNUTLS + +static struct { + const char *const names[4]; + int level; + bool enabled; +} gnutls_log_map[] = { + { {"0"}, LOG_DEBUG }, + { {"1", "audit"}, LOG_WARNING, true}, /* gnutls session audit */ + { {"2", "assert"}, LOG_DEBUG }, /* gnutls assert log */ + { {"3", "hsk", "ext"}, LOG_DEBUG }, /* gnutls handshake log */ + { {"4", "rec"}, LOG_DEBUG }, /* gnutls record log */ + { {"5", "dtls"}, LOG_DEBUG }, /* gnutls DTLS log */ + { {"6", "buf"}, LOG_DEBUG }, + { {"7", "write", "read"}, LOG_DEBUG }, + { {"8"}, LOG_DEBUG }, + { {"9", "enc", "int"}, LOG_DEBUG }, +}; + +void log_func_gnutls(int level, const char *message) { + assert_se(message); + + if (0 <= level && level < (int) ELEMENTSOF(gnutls_log_map)) { + if (gnutls_log_map[level].enabled) + log_meta(gnutls_log_map[level].level, NULL, 0, NULL, + "gnutls %d/%s: %s", level, gnutls_log_map[level].names[1], message); + } else { + log_debug("Received GNUTLS message with unknown level %d.", level); + log_meta(LOG_DEBUG, NULL, 0, NULL, "gnutls: %s", message); + } +} + +int log_enable_gnutls_category(const char *cat) { + unsigned i; + + if (streq(cat, "all")) { + for (i = 0; i < ELEMENTSOF(gnutls_log_map); i++) + gnutls_log_map[i].enabled = true; + log_reset_gnutls_level(); + return 0; + } else + for (i = 0; i < ELEMENTSOF(gnutls_log_map); i++) + if (strv_contains((char**)gnutls_log_map[i].names, cat)) { + gnutls_log_map[i].enabled = true; + log_reset_gnutls_level(); + return 0; + } + log_error("No such log category: %s", cat); + return -EINVAL; +} + +void log_reset_gnutls_level(void) { + int i; + + for (i = ELEMENTSOF(gnutls_log_map) - 1; i >= 0; i--) + if (gnutls_log_map[i].enabled) { + log_debug("Setting gnutls log level to %d", i); + gnutls_global_set_log_level(i); + break; + } +} + +static int verify_cert_authorized(gnutls_session_t session) { + unsigned status; + gnutls_certificate_type_t type; + gnutls_datum_t out; + int r; + + r = gnutls_certificate_verify_peers2(session, &status); + if (r < 0) { + log_error("gnutls_certificate_verify_peers2 failed: %s", strerror(-r)); + return r; + } + + type = gnutls_certificate_type_get(session); + r = gnutls_certificate_verification_status_print(status, type, &out, 0); + if (r < 0) { + log_error("gnutls_certificate_verification_status_print failed: %s", strerror(-r)); + return r; + } + + log_info("Certificate status: %s", out.data); + + return status == 0 ? 0 : -EPERM; +} + +static int get_client_cert(gnutls_session_t session, gnutls_x509_crt_t *client_cert) { + const gnutls_datum_t *pcert; + unsigned listsize; + gnutls_x509_crt_t cert; + int r; + + assert(session); + assert(client_cert); + + pcert = gnutls_certificate_get_peers(session, &listsize); + if (!pcert || !listsize) { + log_error("Failed to retrieve certificate chain"); + return -EINVAL; + } + + r = gnutls_x509_crt_init(&cert); + if (r < 0) { + log_error("Failed to initialize client certificate"); + return r; + } + + /* Note that by passing values between 0 and listsize here, you + can get access to the CA's certs */ + r = gnutls_x509_crt_import(cert, &pcert[0], GNUTLS_X509_FMT_DER); + if (r < 0) { + log_error("Failed to import client certificate"); + gnutls_x509_crt_deinit(cert); + return r; + } + + *client_cert = cert; + return 0; +} + +static int get_auth_dn(gnutls_x509_crt_t client_cert, char **buf) { + size_t len = 0; + int r; + + assert(buf); + assert(*buf == NULL); + + r = gnutls_x509_crt_get_dn(client_cert, NULL, &len); + if (r != GNUTLS_E_SHORT_MEMORY_BUFFER) { + log_error("gnutls_x509_crt_get_dn failed"); + return r; + } + + *buf = malloc(len); + if (!*buf) + return log_oom(); + + gnutls_x509_crt_get_dn(client_cert, *buf, &len); + return 0; +} + +int check_permissions(struct MHD_Connection *connection, int *code) { + const union MHD_ConnectionInfo *ci; + gnutls_session_t session; + gnutls_x509_crt_t client_cert; + _cleanup_free_ char *buf = NULL; + int r; + + assert(connection); + assert(code); + + *code = 0; + + ci = MHD_get_connection_info(connection, + MHD_CONNECTION_INFO_GNUTLS_SESSION); + if (!ci) { + log_error("MHD_get_connection_info failed: session is unencrypted"); + *code = mhd_respond(connection, MHD_HTTP_FORBIDDEN, + "Encrypted connection is required"); + return -EPERM; + } + session = ci->tls_session; + assert(session); + + r = get_client_cert(session, &client_cert); + if (r < 0) { + *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED, + "Authorization through certificate is required"); + return -EPERM; + } + + r = get_auth_dn(client_cert, &buf); + if (r < 0) { + *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED, + "Failed to determine distinguished name from certificate"); + return -EPERM; + } + + log_info("Connection from %s", buf); + + r = verify_cert_authorized(session); + if (r < 0) { + log_warning("Client is not authorized"); + *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED, + "Client certificate not signed by recognized authority"); + } + return r; +} + +#else +int check_permissions(struct MHD_Connection *connection, int *code) { + return -EPERM; +} +#endif diff --git a/src/journal-remote/microhttpd-util.h b/src/journal-remote/microhttpd-util.h new file mode 100644 index 0000000000..4186da888e --- /dev/null +++ b/src/journal-remote/microhttpd-util.h @@ -0,0 +1,55 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2012 Zbigniew Jędrzejewski-Szmek + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#pragma once + +#include +#include + +#include "macro.h" + +void microhttpd_logger(void *arg, const char *fmt, va_list ap) _printf_(2, 0); + +/* respond_oom() must be usable with return, hence this form. */ +#define respond_oom(connection) log_oom(), mhd_respond_oom(connection) + +int mhd_respondf(struct MHD_Connection *connection, + unsigned code, + const char *format, ...) _printf_(3,4); + +int mhd_respond(struct MHD_Connection *connection, + unsigned code, + const char *message); + +int mhd_respond_oom(struct MHD_Connection *connection); + +int check_permissions(struct MHD_Connection *connection, int *code); + +#ifdef HAVE_GNUTLS +void log_func_gnutls(int level, const char *message); +int log_enable_gnutls_category(const char *cat); +void log_reset_gnutls_level(void); + +/* This is additionally filtered by our internal log level, so it + * should be set fairly high to capture all potentially interesting + * events without overwhelming detail. + */ +#endif diff --git a/src/journal/browse.html b/src/journal/browse.html deleted file mode 100644 index 3594f70c87..0000000000 --- a/src/journal/browse.html +++ /dev/null @@ -1,544 +0,0 @@ - - - - Journal - - - - - - - -

- -
-
-
-
-
-
- -
- -      - Only current boot -
- -
- -
- -
- - - - -      - - -
- -
- g: First Page      - ←, k, BACKSPACE: Previous Page      - →, j, SPACE: Next Page      - G: Last Page      - +: More entries      - -: Fewer entries -
- - - - diff --git a/src/journal/journal-gatewayd.c b/src/journal/journal-gatewayd.c deleted file mode 100644 index db07700111..0000000000 --- a/src/journal/journal-gatewayd.c +++ /dev/null @@ -1,1054 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2012 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include -#include - -#include - -#ifdef HAVE_GNUTLS -#include -#endif - -#include "log.h" -#include "util.h" -#include "sd-journal.h" -#include "sd-daemon.h" -#include "sd-bus.h" -#include "bus-util.h" -#include "logs-show.h" -#include "microhttpd-util.h" -#include "build.h" -#include "fileio.h" - -static char *key_pem = NULL; -static char *cert_pem = NULL; -static char *trust_pem = NULL; - -typedef struct RequestMeta { - sd_journal *journal; - - OutputMode mode; - - char *cursor; - int64_t n_skip; - uint64_t n_entries; - bool n_entries_set; - - FILE *tmp; - uint64_t delta, size; - - int argument_parse_error; - - bool follow; - bool discrete; - - uint64_t n_fields; - bool n_fields_set; -} RequestMeta; - -static const char* const mime_types[_OUTPUT_MODE_MAX] = { - [OUTPUT_SHORT] = "text/plain", - [OUTPUT_JSON] = "application/json", - [OUTPUT_JSON_SSE] = "text/event-stream", - [OUTPUT_EXPORT] = "application/vnd.fdo.journal", -}; - -static RequestMeta *request_meta(void **connection_cls) { - RequestMeta *m; - - assert(connection_cls); - if (*connection_cls) - return *connection_cls; - - m = new0(RequestMeta, 1); - if (!m) - return NULL; - - *connection_cls = m; - return m; -} - -static void request_meta_free( - void *cls, - struct MHD_Connection *connection, - void **connection_cls, - enum MHD_RequestTerminationCode toe) { - - RequestMeta *m = *connection_cls; - - if (!m) - return; - - if (m->journal) - sd_journal_close(m->journal); - - if (m->tmp) - fclose(m->tmp); - - free(m->cursor); - free(m); -} - -static int open_journal(RequestMeta *m) { - assert(m); - - if (m->journal) - return 0; - - return sd_journal_open(&m->journal, SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_SYSTEM); -} - -static ssize_t request_reader_entries( - void *cls, - uint64_t pos, - char *buf, - size_t max) { - - RequestMeta *m = cls; - int r; - size_t n, k; - - assert(m); - assert(buf); - assert(max > 0); - assert(pos >= m->delta); - - pos -= m->delta; - - while (pos >= m->size) { - off_t sz; - - /* End of this entry, so let's serialize the next - * one */ - - if (m->n_entries_set && - m->n_entries <= 0) - return MHD_CONTENT_READER_END_OF_STREAM; - - if (m->n_skip < 0) - r = sd_journal_previous_skip(m->journal, (uint64_t) -m->n_skip + 1); - else if (m->n_skip > 0) - r = sd_journal_next_skip(m->journal, (uint64_t) m->n_skip + 1); - else - r = sd_journal_next(m->journal); - - if (r < 0) { - log_error("Failed to advance journal pointer: %s", strerror(-r)); - return MHD_CONTENT_READER_END_WITH_ERROR; - } else if (r == 0) { - - if (m->follow) { - r = sd_journal_wait(m->journal, (uint64_t) -1); - if (r < 0) { - log_error("Couldn't wait for journal event: %s", strerror(-r)); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - continue; - } - - return MHD_CONTENT_READER_END_OF_STREAM; - } - - if (m->discrete) { - assert(m->cursor); - - r = sd_journal_test_cursor(m->journal, m->cursor); - if (r < 0) { - log_error("Failed to test cursor: %s", strerror(-r)); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - if (r == 0) - return MHD_CONTENT_READER_END_OF_STREAM; - } - - pos -= m->size; - m->delta += m->size; - - if (m->n_entries_set) - m->n_entries -= 1; - - m->n_skip = 0; - - if (m->tmp) - rewind(m->tmp); - else { - m->tmp = tmpfile(); - if (!m->tmp) { - log_error("Failed to create temporary file: %m"); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - } - - r = output_journal(m->tmp, m->journal, m->mode, 0, OUTPUT_FULL_WIDTH, NULL); - if (r < 0) { - log_error("Failed to serialize item: %s", strerror(-r)); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - sz = ftello(m->tmp); - if (sz == (off_t) -1) { - log_error("Failed to retrieve file position: %m"); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - m->size = (uint64_t) sz; - } - - if (fseeko(m->tmp, pos, SEEK_SET) < 0) { - log_error("Failed to seek to position: %m"); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - n = m->size - pos; - if (n > max) - n = max; - - errno = 0; - k = fread(buf, 1, n, m->tmp); - if (k != n) { - log_error("Failed to read from file: %s", errno ? strerror(errno) : "Premature EOF"); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - return (ssize_t) k; -} - -static int request_parse_accept( - RequestMeta *m, - struct MHD_Connection *connection) { - - const char *header; - - assert(m); - assert(connection); - - header = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Accept"); - if (!header) - return 0; - - if (streq(header, mime_types[OUTPUT_JSON])) - m->mode = OUTPUT_JSON; - else if (streq(header, mime_types[OUTPUT_JSON_SSE])) - m->mode = OUTPUT_JSON_SSE; - else if (streq(header, mime_types[OUTPUT_EXPORT])) - m->mode = OUTPUT_EXPORT; - else - m->mode = OUTPUT_SHORT; - - return 0; -} - -static int request_parse_range( - RequestMeta *m, - struct MHD_Connection *connection) { - - const char *range, *colon, *colon2; - int r; - - assert(m); - assert(connection); - - range = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Range"); - if (!range) - return 0; - - if (!startswith(range, "entries=")) - return 0; - - range += 8; - range += strspn(range, WHITESPACE); - - colon = strchr(range, ':'); - if (!colon) - m->cursor = strdup(range); - else { - const char *p; - - colon2 = strchr(colon + 1, ':'); - if (colon2) { - _cleanup_free_ char *t; - - t = strndup(colon + 1, colon2 - colon - 1); - if (!t) - return -ENOMEM; - - r = safe_atoi64(t, &m->n_skip); - if (r < 0) - return r; - } - - p = (colon2 ? colon2 : colon) + 1; - if (*p) { - r = safe_atou64(p, &m->n_entries); - if (r < 0) - return r; - - if (m->n_entries <= 0) - return -EINVAL; - - m->n_entries_set = true; - } - - m->cursor = strndup(range, colon - range); - } - - if (!m->cursor) - return -ENOMEM; - - m->cursor[strcspn(m->cursor, WHITESPACE)] = 0; - if (isempty(m->cursor)) { - free(m->cursor); - m->cursor = NULL; - } - - return 0; -} - -static int request_parse_arguments_iterator( - void *cls, - enum MHD_ValueKind kind, - const char *key, - const char *value) { - - RequestMeta *m = cls; - _cleanup_free_ char *p = NULL; - int r; - - assert(m); - - if (isempty(key)) { - m->argument_parse_error = -EINVAL; - return MHD_NO; - } - - if (streq(key, "follow")) { - if (isempty(value)) { - m->follow = true; - return MHD_YES; - } - - r = parse_boolean(value); - if (r < 0) { - m->argument_parse_error = r; - return MHD_NO; - } - - m->follow = r; - return MHD_YES; - } - - if (streq(key, "discrete")) { - if (isempty(value)) { - m->discrete = true; - return MHD_YES; - } - - r = parse_boolean(value); - if (r < 0) { - m->argument_parse_error = r; - return MHD_NO; - } - - m->discrete = r; - return MHD_YES; - } - - if (streq(key, "boot")) { - if (isempty(value)) - r = true; - else { - r = parse_boolean(value); - if (r < 0) { - m->argument_parse_error = r; - return MHD_NO; - } - } - - if (r) { - char match[9 + 32 + 1] = "_BOOT_ID="; - sd_id128_t bid; - - r = sd_id128_get_boot(&bid); - if (r < 0) { - log_error("Failed to get boot ID: %s", strerror(-r)); - return MHD_NO; - } - - sd_id128_to_string(bid, match + 9); - r = sd_journal_add_match(m->journal, match, sizeof(match)-1); - if (r < 0) { - m->argument_parse_error = r; - return MHD_NO; - } - } - - return MHD_YES; - } - - p = strjoin(key, "=", strempty(value), NULL); - if (!p) { - m->argument_parse_error = log_oom(); - return MHD_NO; - } - - r = sd_journal_add_match(m->journal, p, 0); - if (r < 0) { - m->argument_parse_error = r; - return MHD_NO; - } - - return MHD_YES; -} - -static int request_parse_arguments( - RequestMeta *m, - struct MHD_Connection *connection) { - - assert(m); - assert(connection); - - m->argument_parse_error = 0; - MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND, request_parse_arguments_iterator, m); - - return m->argument_parse_error; -} - -static int request_handler_entries( - struct MHD_Connection *connection, - void *connection_cls) { - - struct MHD_Response *response; - RequestMeta *m = connection_cls; - int r; - - assert(connection); - assert(m); - - r = open_journal(m); - if (r < 0) - return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r)); - - if (request_parse_accept(m, connection) < 0) - return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Accept header.\n"); - - if (request_parse_range(m, connection) < 0) - return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Range header.\n"); - - if (request_parse_arguments(m, connection) < 0) - return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse URL arguments.\n"); - - if (m->discrete) { - if (!m->cursor) - return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Discrete seeks require a cursor specification.\n"); - - m->n_entries = 1; - m->n_entries_set = true; - } - - if (m->cursor) - r = sd_journal_seek_cursor(m->journal, m->cursor); - else if (m->n_skip >= 0) - r = sd_journal_seek_head(m->journal); - else if (m->n_skip < 0) - r = sd_journal_seek_tail(m->journal); - if (r < 0) - return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to seek in journal.\n"); - - response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 4*1024, request_reader_entries, m, NULL); - if (!response) - return respond_oom(connection); - - MHD_add_response_header(response, "Content-Type", mime_types[m->mode]); - - r = MHD_queue_response(connection, MHD_HTTP_OK, response); - MHD_destroy_response(response); - - return r; -} - -static int output_field(FILE *f, OutputMode m, const char *d, size_t l) { - const char *eq; - size_t j; - - eq = memchr(d, '=', l); - if (!eq) - return -EINVAL; - - j = l - (eq - d + 1); - - if (m == OUTPUT_JSON) { - fprintf(f, "{ \"%.*s\" : ", (int) (eq - d), d); - json_escape(f, eq+1, j, OUTPUT_FULL_WIDTH); - fputs(" }\n", f); - } else { - fwrite(eq+1, 1, j, f); - fputc('\n', f); - } - - return 0; -} - -static ssize_t request_reader_fields( - void *cls, - uint64_t pos, - char *buf, - size_t max) { - - RequestMeta *m = cls; - int r; - size_t n, k; - - assert(m); - assert(buf); - assert(max > 0); - assert(pos >= m->delta); - - pos -= m->delta; - - while (pos >= m->size) { - off_t sz; - const void *d; - size_t l; - - /* End of this field, so let's serialize the next - * one */ - - if (m->n_fields_set && - m->n_fields <= 0) - return MHD_CONTENT_READER_END_OF_STREAM; - - r = sd_journal_enumerate_unique(m->journal, &d, &l); - if (r < 0) { - log_error("Failed to advance field index: %s", strerror(-r)); - return MHD_CONTENT_READER_END_WITH_ERROR; - } else if (r == 0) - return MHD_CONTENT_READER_END_OF_STREAM; - - pos -= m->size; - m->delta += m->size; - - if (m->n_fields_set) - m->n_fields -= 1; - - if (m->tmp) - rewind(m->tmp); - else { - m->tmp = tmpfile(); - if (!m->tmp) { - log_error("Failed to create temporary file: %m"); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - } - - r = output_field(m->tmp, m->mode, d, l); - if (r < 0) { - log_error("Failed to serialize item: %s", strerror(-r)); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - sz = ftello(m->tmp); - if (sz == (off_t) -1) { - log_error("Failed to retrieve file position: %m"); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - m->size = (uint64_t) sz; - } - - if (fseeko(m->tmp, pos, SEEK_SET) < 0) { - log_error("Failed to seek to position: %m"); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - n = m->size - pos; - if (n > max) - n = max; - - errno = 0; - k = fread(buf, 1, n, m->tmp); - if (k != n) { - log_error("Failed to read from file: %s", errno ? strerror(errno) : "Premature EOF"); - return MHD_CONTENT_READER_END_WITH_ERROR; - } - - return (ssize_t) k; -} - -static int request_handler_fields( - struct MHD_Connection *connection, - const char *field, - void *connection_cls) { - - struct MHD_Response *response; - RequestMeta *m = connection_cls; - int r; - - assert(connection); - assert(m); - - r = open_journal(m); - if (r < 0) - return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r)); - - if (request_parse_accept(m, connection) < 0) - return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Accept header.\n"); - - r = sd_journal_query_unique(m->journal, field); - if (r < 0) - return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to query unique fields.\n"); - - response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 4*1024, request_reader_fields, m, NULL); - if (!response) - return respond_oom(connection); - - MHD_add_response_header(response, "Content-Type", mime_types[m->mode == OUTPUT_JSON ? OUTPUT_JSON : OUTPUT_SHORT]); - - r = MHD_queue_response(connection, MHD_HTTP_OK, response); - MHD_destroy_response(response); - - return r; -} - -static int request_handler_redirect( - struct MHD_Connection *connection, - const char *target) { - - char *page; - struct MHD_Response *response; - int ret; - - assert(connection); - assert(target); - - if (asprintf(&page, "Please continue to the journal browser.", target) < 0) - return respond_oom(connection); - - response = MHD_create_response_from_buffer(strlen(page), page, MHD_RESPMEM_MUST_FREE); - if (!response) { - free(page); - return respond_oom(connection); - } - - MHD_add_response_header(response, "Content-Type", "text/html"); - MHD_add_response_header(response, "Location", target); - - ret = MHD_queue_response(connection, MHD_HTTP_MOVED_PERMANENTLY, response); - MHD_destroy_response(response); - - return ret; -} - -static int request_handler_file( - struct MHD_Connection *connection, - const char *path, - const char *mime_type) { - - struct MHD_Response *response; - int ret; - _cleanup_close_ int fd = -1; - struct stat st; - - assert(connection); - assert(path); - assert(mime_type); - - fd = open(path, O_RDONLY|O_CLOEXEC); - if (fd < 0) - return mhd_respondf(connection, MHD_HTTP_NOT_FOUND, "Failed to open file %s: %m\n", path); - - if (fstat(fd, &st) < 0) - return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to stat file: %m\n"); - - response = MHD_create_response_from_fd_at_offset(st.st_size, fd, 0); - if (!response) - return respond_oom(connection); - - fd = -1; - - MHD_add_response_header(response, "Content-Type", mime_type); - - ret = MHD_queue_response(connection, MHD_HTTP_OK, response); - MHD_destroy_response(response); - - return ret; -} - -static int get_virtualization(char **v) { - _cleanup_bus_unref_ sd_bus *bus = NULL; - char *b = NULL; - int r; - - r = sd_bus_default_system(&bus); - if (r < 0) - return r; - - r = sd_bus_get_property_string( - bus, - "org.freedesktop.systemd1", - "/org/freedesktop/systemd1", - "org.freedesktop.systemd1.Manager", - "Virtualization", - NULL, - &b); - if (r < 0) - return r; - - if (isempty(b)) { - free(b); - *v = NULL; - return 0; - } - - *v = b; - return 1; -} - -static int request_handler_machine( - struct MHD_Connection *connection, - void *connection_cls) { - - struct MHD_Response *response; - RequestMeta *m = connection_cls; - int r; - _cleanup_free_ char* hostname = NULL, *os_name = NULL; - uint64_t cutoff_from = 0, cutoff_to = 0, usage; - char *json; - sd_id128_t mid, bid; - _cleanup_free_ char *v = NULL; - - assert(connection); - assert(m); - - r = open_journal(m); - if (r < 0) - return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r)); - - r = sd_id128_get_machine(&mid); - if (r < 0) - return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine machine ID: %s\n", strerror(-r)); - - r = sd_id128_get_boot(&bid); - if (r < 0) - return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine boot ID: %s\n", strerror(-r)); - - hostname = gethostname_malloc(); - if (!hostname) - return respond_oom(connection); - - r = sd_journal_get_usage(m->journal, &usage); - if (r < 0) - return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine disk usage: %s\n", strerror(-r)); - - r = sd_journal_get_cutoff_realtime_usec(m->journal, &cutoff_from, &cutoff_to); - if (r < 0) - return mhd_respondf(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine disk usage: %s\n", strerror(-r)); - - if (parse_env_file("/etc/os-release", NEWLINE, "PRETTY_NAME", &os_name, NULL) == -ENOENT) - parse_env_file("/usr/lib/os-release", NEWLINE, "PRETTY_NAME", &os_name, NULL); - - get_virtualization(&v); - - r = asprintf(&json, - "{ \"machine_id\" : \"" SD_ID128_FORMAT_STR "\"," - "\"boot_id\" : \"" SD_ID128_FORMAT_STR "\"," - "\"hostname\" : \"%s\"," - "\"os_pretty_name\" : \"%s\"," - "\"virtualization\" : \"%s\"," - "\"usage\" : \"%"PRIu64"\"," - "\"cutoff_from_realtime\" : \"%"PRIu64"\"," - "\"cutoff_to_realtime\" : \"%"PRIu64"\" }\n", - SD_ID128_FORMAT_VAL(mid), - SD_ID128_FORMAT_VAL(bid), - hostname_cleanup(hostname, false), - os_name ? os_name : "Linux", - v ? v : "bare", - usage, - cutoff_from, - cutoff_to); - - if (r < 0) - return respond_oom(connection); - - response = MHD_create_response_from_buffer(strlen(json), json, MHD_RESPMEM_MUST_FREE); - if (!response) { - free(json); - return respond_oom(connection); - } - - MHD_add_response_header(response, "Content-Type", "application/json"); - r = MHD_queue_response(connection, MHD_HTTP_OK, response); - MHD_destroy_response(response); - - return r; -} - -static int request_handler( - void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, - size_t *upload_data_size, - void **connection_cls) { - int r, code; - - assert(connection); - assert(connection_cls); - assert(url); - assert(method); - - if (!streq(method, "GET")) - return mhd_respond(connection, MHD_HTTP_METHOD_NOT_ACCEPTABLE, - "Unsupported method.\n"); - - - if (!*connection_cls) { - if (!request_meta(connection_cls)) - return respond_oom(connection); - return MHD_YES; - } - - if (trust_pem) { - r = check_permissions(connection, &code); - if (r < 0) - return code; - } - - if (streq(url, "/")) - return request_handler_redirect(connection, "/browse"); - - if (streq(url, "/entries")) - return request_handler_entries(connection, *connection_cls); - - if (startswith(url, "/fields/")) - return request_handler_fields(connection, url + 8, *connection_cls); - - if (streq(url, "/browse")) - return request_handler_file(connection, DOCUMENT_ROOT "/browse.html", "text/html"); - - if (streq(url, "/machine")) - return request_handler_machine(connection, *connection_cls); - - return mhd_respond(connection, MHD_HTTP_NOT_FOUND, "Not found.\n"); -} - -static int help(void) { - - printf("%s [OPTIONS...] ...\n\n" - "HTTP server for journal events.\n\n" - " -h --help Show this help\n" - " --version Show package version\n" - " --cert=CERT.PEM Server certificate in PEM format\n" - " --key=KEY.PEM Server key in PEM format\n" - " --trust=CERT.PEM Certificat authority certificate in PEM format\n", - program_invocation_short_name); - - return 0; -} - -static int parse_argv(int argc, char *argv[]) { - enum { - ARG_VERSION = 0x100, - ARG_KEY, - ARG_CERT, - ARG_TRUST, - }; - - int r, c; - - static const struct option options[] = { - { "help", no_argument, NULL, 'h' }, - { "version", no_argument, NULL, ARG_VERSION }, - { "key", required_argument, NULL, ARG_KEY }, - { "cert", required_argument, NULL, ARG_CERT }, - { "trust", required_argument, NULL, ARG_TRUST }, - {} - }; - - assert(argc >= 0); - assert(argv); - - while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) - - switch(c) { - - case 'h': - return help(); - - case ARG_VERSION: - puts(PACKAGE_STRING); - puts(SYSTEMD_FEATURES); - return 0; - - case ARG_KEY: - if (key_pem) { - log_error("Key file specified twice"); - return -EINVAL; - } - r = read_full_file(optarg, &key_pem, NULL); - if (r < 0) { - log_error("Failed to read key file: %s", strerror(-r)); - return r; - } - assert(key_pem); - break; - - case ARG_CERT: - if (cert_pem) { - log_error("Certificate file specified twice"); - return -EINVAL; - } - r = read_full_file(optarg, &cert_pem, NULL); - if (r < 0) { - log_error("Failed to read certificate file: %s", strerror(-r)); - return r; - } - assert(cert_pem); - break; - - case ARG_TRUST: -#ifdef HAVE_GNUTLS - if (trust_pem) { - log_error("CA certificate file specified twice"); - return -EINVAL; - } - r = read_full_file(optarg, &trust_pem, NULL); - if (r < 0) { - log_error("Failed to read CA certificate file: %s", strerror(-r)); - return r; - } - assert(trust_pem); - break; -#else - log_error("Option --trust is not available."); -#endif - - case '?': - return -EINVAL; - - default: - assert_not_reached("Unhandled option"); - } - - if (optind < argc) { - log_error("This program does not take arguments."); - return -EINVAL; - } - - if (!!key_pem != !!cert_pem) { - log_error("Certificate and key files must be specified together"); - return -EINVAL; - } - - if (trust_pem && !key_pem) { - log_error("CA certificate can only be used with certificate file"); - return -EINVAL; - } - - return 1; -} - -int main(int argc, char *argv[]) { - struct MHD_Daemon *d = NULL; - int r, n; - - log_set_target(LOG_TARGET_AUTO); - log_parse_environment(); - log_open(); - - r = parse_argv(argc, argv); - if (r < 0) - return EXIT_FAILURE; - if (r == 0) - return EXIT_SUCCESS; - -#ifdef HAVE_GNUTLS - gnutls_global_set_log_function(log_func_gnutls); - log_reset_gnutls_level(); -#endif - - n = sd_listen_fds(1); - if (n < 0) { - log_error("Failed to determine passed sockets: %s", strerror(-n)); - goto finish; - } else if (n > 1) { - log_error("Can't listen on more than one socket."); - goto finish; - } else { - struct MHD_OptionItem opts[] = { - { MHD_OPTION_NOTIFY_COMPLETED, - (intptr_t) request_meta_free, NULL }, - { MHD_OPTION_EXTERNAL_LOGGER, - (intptr_t) microhttpd_logger, NULL }, - { MHD_OPTION_END, 0, NULL }, - { MHD_OPTION_END, 0, NULL }, - { MHD_OPTION_END, 0, NULL }, - { MHD_OPTION_END, 0, NULL }, - { MHD_OPTION_END, 0, NULL }}; - int opts_pos = 2; - int flags = MHD_USE_THREAD_PER_CONNECTION|MHD_USE_POLL|MHD_USE_DEBUG; - - if (n > 0) - opts[opts_pos++] = (struct MHD_OptionItem) - {MHD_OPTION_LISTEN_SOCKET, SD_LISTEN_FDS_START}; - if (key_pem) { - assert(cert_pem); - opts[opts_pos++] = (struct MHD_OptionItem) - {MHD_OPTION_HTTPS_MEM_KEY, 0, key_pem}; - opts[opts_pos++] = (struct MHD_OptionItem) - {MHD_OPTION_HTTPS_MEM_CERT, 0, cert_pem}; - flags |= MHD_USE_SSL; - } - if (trust_pem) { - assert(flags & MHD_USE_SSL); - opts[opts_pos++] = (struct MHD_OptionItem) - {MHD_OPTION_HTTPS_MEM_TRUST, 0, trust_pem}; - } - - d = MHD_start_daemon(flags, 19531, - NULL, NULL, - request_handler, NULL, - MHD_OPTION_ARRAY, opts, - MHD_OPTION_END); - } - - if (!d) { - log_error("Failed to start daemon!"); - goto finish; - } - - pause(); - - r = EXIT_SUCCESS; - -finish: - if (d) - MHD_stop_daemon(d); - - return r; -} diff --git a/src/journal/journal-remote-parse.c b/src/journal/journal-remote-parse.c deleted file mode 100644 index dbdf02aa3c..0000000000 --- a/src/journal/journal-remote-parse.c +++ /dev/null @@ -1,439 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "journal-remote-parse.h" -#include "journald-native.h" - -#define LINE_CHUNK 1024u - -void source_free(RemoteSource *source) { - if (!source) - return; - - if (source->fd >= 0) { - log_debug("Closing fd:%d (%s)", source->fd, source->name); - close(source->fd); - } - free(source->name); - free(source->buf); - iovw_free_contents(&source->iovw); - free(source); -} - -static int get_line(RemoteSource *source, char **line, size_t *size) { - ssize_t n, remain; - char *c = NULL; - char *newbuf = NULL; - size_t newsize = 0; - - assert(source); - assert(source->state == STATE_LINE); - assert(source->filled <= source->size); - assert(source->buf == NULL || source->size > 0); - - if (source->buf) - c = memchr(source->buf, '\n', source->filled); - - if (c != NULL) - goto docopy; - - resize: - if (source->fd < 0) - /* we have to wait for some data to come to us */ - return -EWOULDBLOCK; - - if (source->size - source->filled < LINE_CHUNK) { - // XXX: add check for maximum line length - - if (!GREEDY_REALLOC(source->buf, source->size, - source->filled + LINE_CHUNK)) - return log_oom(); - } - assert(source->size - source->filled >= LINE_CHUNK); - - n = read(source->fd, source->buf + source->filled, - source->size - source->filled); - if (n < 0) { - if (errno != EAGAIN && errno != EWOULDBLOCK) - log_error("read(%d, ..., %zd): %m", source->fd, - source->size - source->filled); - return -errno; - } else if (n == 0) - return 0; - - c = memchr(source->buf + source->filled, '\n', n); - source->filled += n; - - if (c == NULL) - goto resize; - - docopy: - *line = source->buf; - *size = c + 1 - source->buf; - - /* Check if something remains */ - remain = source->buf + source->filled - c - 1; - assert(remain >= 0); - if (remain) { - newsize = MAX(remain, LINE_CHUNK); - newbuf = malloc(newsize); - if (!newbuf) - return log_oom(); - memcpy(newbuf, c + 1, remain); - } - source->buf = newbuf; - source->size = newsize; - source->filled = remain; - - return 1; -} - -int push_data(RemoteSource *source, const char *data, size_t size) { - assert(source); - assert(source->state != STATE_EOF); - - if (!GREEDY_REALLOC(source->buf, source->size, - source->filled + size)) - return log_oom(); - - memcpy(source->buf + source->filled, data, size); - source->filled += size; - - return 0; -} - -static int fill_fixed_size(RemoteSource *source, void **data, size_t size) { - int n; - char *newbuf = NULL; - size_t newsize = 0, remain; - - assert(source); - assert(source->state == STATE_DATA_START || - source->state == STATE_DATA || - source->state == STATE_DATA_FINISH); - assert(size <= DATA_SIZE_MAX); - assert(source->filled <= source->size); - assert(source->buf != NULL || source->size == 0); - assert(source->buf == NULL || source->size > 0); - assert(data); - - while(source->filled < size) { - if (source->fd < 0) - /* we have to wait for some data to come to us */ - return -EWOULDBLOCK; - - if (!GREEDY_REALLOC(source->buf, source->size, size)) - return log_oom(); - - n = read(source->fd, source->buf + source->filled, - source->size - source->filled); - if (n < 0) { - if (errno != EAGAIN && errno != EWOULDBLOCK) - log_error("read(%d, ..., %zd): %m", source->fd, - source->size - source->filled); - return -errno; - } else if (n == 0) - return 0; - - source->filled += n; - } - - *data = source->buf; - - /* Check if something remains */ - assert(size <= source->filled); - remain = source->filled - size; - if (remain) { - newsize = MAX(remain, LINE_CHUNK); - newbuf = malloc(newsize); - if (!newbuf) - return log_oom(); - memcpy(newbuf, source->buf + size, remain); - } - source->buf = newbuf; - source->size = newsize; - source->filled = remain; - - return 1; -} - -static int get_data_size(RemoteSource *source) { - int r; - _cleanup_free_ void *data = NULL; - - assert(source); - assert(source->state == STATE_DATA_START); - assert(source->data_size == 0); - - r = fill_fixed_size(source, &data, sizeof(uint64_t)); - if (r <= 0) - return r; - - source->data_size = le64toh( *(uint64_t *) data ); - if (source->data_size > DATA_SIZE_MAX) { - log_error("Stream declares field with size %zu > %u == DATA_SIZE_MAX", - source->data_size, DATA_SIZE_MAX); - return -EINVAL; - } - if (source->data_size == 0) - log_warning("Binary field with zero length"); - - return 1; -} - -static int get_data_data(RemoteSource *source, void **data) { - int r; - - assert(source); - assert(data); - assert(source->state == STATE_DATA); - - r = fill_fixed_size(source, data, source->data_size); - if (r <= 0) - return r; - - return 1; -} - -static int get_data_newline(RemoteSource *source) { - int r; - _cleanup_free_ char *data = NULL; - - assert(source); - assert(source->state == STATE_DATA_FINISH); - - r = fill_fixed_size(source, (void**) &data, 1); - if (r <= 0) - return r; - - assert(data); - if (*data != '\n') { - log_error("expected newline, got '%c'", *data); - return -EINVAL; - } - - return 1; -} - -static int process_dunder(RemoteSource *source, char *line, size_t n) { - const char *timestamp; - int r; - - assert(line); - assert(n > 0); - assert(line[n-1] == '\n'); - - /* XXX: is it worth to support timestamps in extended format? - * We don't produce them, but who knows... */ - - timestamp = startswith(line, "__CURSOR="); - if (timestamp) - /* ignore __CURSOR */ - return 1; - - timestamp = startswith(line, "__REALTIME_TIMESTAMP="); - if (timestamp) { - long long unsigned x; - line[n-1] = '\0'; - r = safe_atollu(timestamp, &x); - if (r < 0) - log_warning("Failed to parse __REALTIME_TIMESTAMP: '%s'", timestamp); - else - source->ts.realtime = x; - return r < 0 ? r : 1; - } - - timestamp = startswith(line, "__MONOTONIC_TIMESTAMP="); - if (timestamp) { - long long unsigned x; - line[n-1] = '\0'; - r = safe_atollu(timestamp, &x); - if (r < 0) - log_warning("Failed to parse __MONOTONIC_TIMESTAMP: '%s'", timestamp); - else - source->ts.monotonic = x; - return r < 0 ? r : 1; - } - - timestamp = startswith(line, "__"); - if (timestamp) { - log_notice("Unknown dunder line %s", line); - return 1; - } - - /* no dunder */ - return 0; -} - -int process_data(RemoteSource *source) { - int r; - - switch(source->state) { - case STATE_LINE: { - char *line, *sep; - size_t n; - - assert(source->data_size == 0); - - r = get_line(source, &line, &n); - if (r < 0) - return r; - if (r == 0) { - source->state = STATE_EOF; - return r; - } - assert(n > 0); - assert(line[n-1] == '\n'); - - if (n == 1) { - log_debug("Received empty line, event is ready"); - free(line); - return 1; - } - - r = process_dunder(source, line, n); - if (r != 0) { - free(line); - return r < 0 ? r : 0; - } - - /* MESSAGE=xxx\n - or - COREDUMP\n - LLLLLLLL0011223344...\n - */ - sep = memchr(line, '=', n); - if (sep) - /* chomp newline */ - n--; - else - /* replace \n with = */ - line[n-1] = '='; - log_debug("Received: %.*s", (int) n, line); - - r = iovw_put(&source->iovw, line, n); - if (r < 0) { - log_error("Failed to put line in iovect"); - free(line); - return r; - } - - if (!sep) - source->state = STATE_DATA_START; - return 0; /* continue */ - } - - case STATE_DATA_START: - assert(source->data_size == 0); - - r = get_data_size(source); - log_debug("get_data_size() -> %d", r); - if (r < 0) - return r; - if (r == 0) { - source->state = STATE_EOF; - return 0; - } - - source->state = source->data_size > 0 ? - STATE_DATA : STATE_DATA_FINISH; - - return 0; /* continue */ - - case STATE_DATA: { - void *data; - - assert(source->data_size > 0); - - r = get_data_data(source, &data); - log_debug("get_data_data() -> %d", r); - if (r < 0) - return r; - if (r == 0) { - source->state = STATE_EOF; - return 0; - } - - assert(data); - - r = iovw_put(&source->iovw, data, source->data_size); - if (r < 0) { - log_error("failed to put binary buffer in iovect"); - return r; - } - - source->state = STATE_DATA_FINISH; - - return 0; /* continue */ - } - - case STATE_DATA_FINISH: - r = get_data_newline(source); - log_debug("get_data_newline() -> %d", r); - if (r < 0) - return r; - if (r == 0) { - source->state = STATE_EOF; - return 0; - } - - source->data_size = 0; - source->state = STATE_LINE; - - return 0; /* continue */ - default: - assert_not_reached("wtf?"); - } -} - -int process_source(RemoteSource *source, Writer *writer, bool compress, bool seal) { - int r; - - assert(source); - assert(writer); - - r = process_data(source); - if (r <= 0) - return r; - - /* We have a full event */ - log_info("Received a full event from source@%p fd:%d (%s)", - source, source->fd, source->name); - - if (!source->iovw.count) { - log_warning("Entry with no payload, skipping"); - goto freeing; - } - - assert(source->iovw.iovec); - assert(source->iovw.count); - - r = writer_write(writer, &source->iovw, &source->ts, compress, seal); - if (r < 0) - log_error("Failed to write entry of %zu bytes: %s", - iovw_size(&source->iovw), strerror(-r)); - else - r = 1; - - freeing: - iovw_free_contents(&source->iovw); - return r; -} diff --git a/src/journal/journal-remote-parse.h b/src/journal/journal-remote-parse.h deleted file mode 100644 index c1506d118d..0000000000 --- a/src/journal/journal-remote-parse.h +++ /dev/null @@ -1,61 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#pragma once - -#include "sd-event.h" -#include "journal-remote-write.h" - -typedef enum { - STATE_LINE = 0, /* waiting to read, or reading line */ - STATE_DATA_START, /* reading binary data header */ - STATE_DATA, /* reading binary data */ - STATE_DATA_FINISH, /* expecting newline */ - STATE_EOF, /* done */ -} source_state; - -typedef struct RemoteSource { - char* name; - int fd; - - char *buf; - size_t size; - size_t filled; - size_t data_size; - - struct iovec_wrapper iovw; - - source_state state; - dual_timestamp ts; - - sd_event_source *event; -} RemoteSource; - -static inline int source_non_empty(RemoteSource *source) { - assert(source); - - return source->filled > 0; -} - -void source_free(RemoteSource *source); -int process_data(RemoteSource *source); -int push_data(RemoteSource *source, const char *data, size_t size); -int process_source(RemoteSource *source, Writer *writer, bool compress, bool seal); diff --git a/src/journal/journal-remote-write.c b/src/journal/journal-remote-write.c deleted file mode 100644 index 4d142bdc97..0000000000 --- a/src/journal/journal-remote-write.c +++ /dev/null @@ -1,124 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2012 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "journal-remote-write.h" - -int iovw_put(struct iovec_wrapper *iovw, void* data, size_t len) { - if (!GREEDY_REALLOC(iovw->iovec, iovw->size_bytes, iovw->count + 1)) - return log_oom(); - - iovw->iovec[iovw->count++] = (struct iovec) {data, len}; - return 0; -} - -void iovw_free_contents(struct iovec_wrapper *iovw) { - for (size_t j = 0; j < iovw->count; j++) - free(iovw->iovec[j].iov_base); - free(iovw->iovec); - iovw->iovec = NULL; - iovw->size_bytes = iovw->count = 0; -} - -size_t iovw_size(struct iovec_wrapper *iovw) { - size_t n = 0, i; - - for(i = 0; i < iovw->count; i++) - n += iovw->iovec[i].iov_len; - - return n; -} - -/********************************************************************** - ********************************************************************** - **********************************************************************/ - -static int do_rotate(JournalFile **f, bool compress, bool seal) { - int r = journal_file_rotate(f, compress, seal); - if (r < 0) { - if (*f) - log_error("Failed to rotate %s: %s", (*f)->path, - strerror(-r)); - else - log_error("Failed to create rotated journal: %s", - strerror(-r)); - } - - return r; -} - -int writer_init(Writer *s) { - assert(s); - - s->journal = NULL; - - memset(&s->metrics, 0xFF, sizeof(s->metrics)); - - s->mmap = mmap_cache_new(); - if (!s->mmap) - return log_oom(); - - s->seqnum = 0; - - return 0; -} - -int writer_close(Writer *s) { - if (s->journal) - journal_file_close(s->journal); - if (s->mmap) - mmap_cache_unref(s->mmap); - return 0; -} - -int writer_write(Writer *s, - struct iovec_wrapper *iovw, - dual_timestamp *ts, - bool compress, - bool seal) { - int r; - - assert(s); - assert(iovw); - assert(iovw->count > 0); - - if (journal_file_rotate_suggested(s->journal, 0)) { - log_info("%s: Journal header limits reached or header out-of-date, rotating", - s->journal->path); - r = do_rotate(&s->journal, compress, seal); - if (r < 0) - return r; - } - - r = journal_file_append_entry(s->journal, ts, iovw->iovec, iovw->count, - &s->seqnum, NULL, NULL); - if (r >= 0) - return 1; - - log_info("%s: Write failed, rotating", s->journal->path); - r = do_rotate(&s->journal, compress, seal); - if (r < 0) - return r; - - log_debug("Retrying write."); - r = journal_file_append_entry(s->journal, ts, iovw->iovec, iovw->count, - &s->seqnum, NULL, NULL); - return r < 0 ? r : 1; -} diff --git a/src/journal/journal-remote-write.h b/src/journal/journal-remote-write.h deleted file mode 100644 index 8798216415..0000000000 --- a/src/journal/journal-remote-write.h +++ /dev/null @@ -1,51 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#pragma once - -#include - -#include "journal-file.h" - -struct iovec_wrapper { - struct iovec *iovec; - size_t size_bytes; - size_t count; -}; - -int iovw_put(struct iovec_wrapper *iovw, void* data, size_t len); -void iovw_free_contents(struct iovec_wrapper *iovw); -size_t iovw_size(struct iovec_wrapper *iovw); - -typedef struct Writer { - JournalFile *journal; - JournalMetrics metrics; - MMapCache *mmap; - uint64_t seqnum; -} Writer; - -int writer_init(Writer *s); -int writer_close(Writer *s); -int writer_write(Writer *s, - struct iovec_wrapper *iovw, - dual_timestamp *ts, - bool compress, - bool seal); diff --git a/src/journal/journal-remote.c b/src/journal/journal-remote.c deleted file mode 100644 index 9db4692a28..0000000000 --- a/src/journal/journal-remote.c +++ /dev/null @@ -1,1283 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2012 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "sd-daemon.h" -#include "sd-event.h" -#include "journal-file.h" -#include "journald-native.h" -#include "socket-util.h" -#include "mkdir.h" -#include "build.h" -#include "macro.h" -#include "strv.h" -#include "fileio.h" -#include "microhttpd-util.h" - -#ifdef HAVE_GNUTLS -#include -#endif - -#include "journal-remote-parse.h" -#include "journal-remote-write.h" - -#define REMOTE_JOURNAL_PATH "/var/log/journal/" SD_ID128_FORMAT_STR "/remote-%s.journal" - -static char* arg_output = NULL; -static char* arg_url = NULL; -static char* arg_getter = NULL; -static char* arg_listen_raw = NULL; -static char* arg_listen_http = NULL; -static char* arg_listen_https = NULL; -static char** arg_files = NULL; -static int arg_compress = true; -static int arg_seal = false; -static int http_socket = -1, https_socket = -1; -static char** arg_gnutls_log = NULL; - -static char *key_pem = NULL; -static char *cert_pem = NULL; -static char *trust_pem = NULL; - -/********************************************************************** - ********************************************************************** - **********************************************************************/ - -static int spawn_child(const char* child, char** argv) { - int fd[2]; - pid_t parent_pid, child_pid; - int r; - - if (pipe(fd) < 0) { - log_error("Failed to create pager pipe: %m"); - return -errno; - } - - parent_pid = getpid(); - - child_pid = fork(); - if (child_pid < 0) { - r = -errno; - log_error("Failed to fork: %m"); - safe_close_pair(fd); - return r; - } - - /* In the child */ - if (child_pid == 0) { - r = dup2(fd[1], STDOUT_FILENO); - if (r < 0) { - log_error("Failed to dup pipe to stdout: %m"); - _exit(EXIT_FAILURE); - } - - safe_close_pair(fd); - - /* Make sure the child goes away when the parent dies */ - if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) - _exit(EXIT_FAILURE); - - /* Check whether our parent died before we were able - * to set the death signal */ - if (getppid() != parent_pid) - _exit(EXIT_SUCCESS); - - execvp(child, argv); - log_error("Failed to exec child %s: %m", child); - _exit(EXIT_FAILURE); - } - - r = close(fd[1]); - if (r < 0) - log_warning("Failed to close write end of pipe: %m"); - - return fd[0]; -} - -static int spawn_curl(char* url) { - char **argv = STRV_MAKE("curl", - "-HAccept: application/vnd.fdo.journal", - "--silent", - "--show-error", - url); - int r; - - r = spawn_child("curl", argv); - if (r < 0) - log_error("Failed to spawn curl: %m"); - return r; -} - -static int spawn_getter(char *getter, char *url) { - int r; - _cleanup_strv_free_ char **words = NULL; - - assert(getter); - words = strv_split_quoted(getter); - if (!words) - return log_oom(); - - r = spawn_child(words[0], words); - if (r < 0) - log_error("Failed to spawn getter %s: %m", getter); - - return r; -} - -static int open_output(Writer *s, const char* url) { - _cleanup_free_ char *name, *output = NULL; - char *c; - int r; - - assert(url); - name = strdup(url); - if (!name) - return log_oom(); - - for(c = name; *c; c++) { - if (*c == '/' || *c == ':' || *c == ' ') - *c = '~'; - else if (*c == '?') { - *c = '\0'; - break; - } - } - - if (!arg_output) { - sd_id128_t machine; - r = sd_id128_get_machine(&machine); - if (r < 0) { - log_error("failed to determine machine ID128: %s", strerror(-r)); - return r; - } - - r = asprintf(&output, REMOTE_JOURNAL_PATH, - SD_ID128_FORMAT_VAL(machine), name); - if (r < 0) - return log_oom(); - } else { - r = is_dir(arg_output, true); - if (r > 0) { - r = asprintf(&output, - "%s/remote-%s.journal", arg_output, name); - if (r < 0) - return log_oom(); - } else { - output = strdup(arg_output); - if (!output) - return log_oom(); - } - } - - r = journal_file_open_reliably(output, - O_RDWR|O_CREAT, 0640, - arg_compress, arg_seal, - &s->metrics, - s->mmap, - NULL, &s->journal); - if (r < 0) - log_error("Failed to open output journal %s: %s", - arg_output, strerror(-r)); - else - log_info("Opened output file %s", s->journal->path); - return r; -} - -/********************************************************************** - ********************************************************************** - **********************************************************************/ - -typedef struct MHDDaemonWrapper { - uint64_t fd; - struct MHD_Daemon *daemon; - - sd_event_source *event; -} MHDDaemonWrapper; - -typedef struct RemoteServer { - RemoteSource **sources; - size_t sources_size; - size_t active; - - sd_event *events; - sd_event_source *sigterm_event, *sigint_event, *listen_event; - - Writer writer; - - Hashmap *daemons; -} RemoteServer; - -/* This should go away as soon as µhttpd allows state to be passed around. */ -static RemoteServer *server; - -static int dispatch_raw_source_event(sd_event_source *event, - int fd, - uint32_t revents, - void *userdata); -static int dispatch_raw_connection_event(sd_event_source *event, - int fd, - uint32_t revents, - void *userdata); -static int dispatch_http_event(sd_event_source *event, - int fd, - uint32_t revents, - void *userdata); - -static int get_source_for_fd(RemoteServer *s, int fd, RemoteSource **source) { - assert(fd >= 0); - assert(source); - - if (!GREEDY_REALLOC0(s->sources, s->sources_size, fd + 1)) - return log_oom(); - - if (s->sources[fd] == NULL) { - s->sources[fd] = new0(RemoteSource, 1); - if (!s->sources[fd]) - return log_oom(); - s->sources[fd]->fd = -1; - s->active++; - } - - *source = s->sources[fd]; - return 0; -} - -static int remove_source(RemoteServer *s, int fd) { - RemoteSource *source; - - assert(s); - assert(fd >= 0 && fd < (ssize_t) s->sources_size); - - source = s->sources[fd]; - if (source) { - source_free(source); - s->sources[fd] = NULL; - s->active--; - } - - close(fd); - - return 0; -} - -static int add_source(RemoteServer *s, int fd, const char* name) { - RemoteSource *source = NULL; - _cleanup_free_ char *realname = NULL; - int r; - - assert(s); - assert(fd >= 0); - - if (name) { - realname = strdup(name); - if (!realname) - return log_oom(); - } else { - r = asprintf(&realname, "fd:%d", fd); - if (r < 0) - return log_oom(); - } - - log_debug("Creating source for fd:%d (%s)", fd, realname); - - r = get_source_for_fd(s, fd, &source); - if (r < 0) { - log_error("Failed to create source for fd:%d (%s)", fd, realname); - return r; - } - assert(source); - assert(source->fd < 0); - source->fd = fd; - - r = sd_event_add_io(s->events, &source->event, - fd, EPOLLIN, dispatch_raw_source_event, s); - if (r < 0) { - log_error("Failed to register event source for fd:%d: %s", - fd, strerror(-r)); - goto error; - } - - return 1; /* work to do */ - - error: - remove_source(s, fd); - return r; -} - -static int add_raw_socket(RemoteServer *s, int fd) { - int r; - - r = sd_event_add_io(s->events, &s->listen_event, fd, EPOLLIN, - dispatch_raw_connection_event, s); - if (r < 0) { - close(fd); - return r; - } - - s->active ++; - return 0; -} - -static int setup_raw_socket(RemoteServer *s, const char *address) { - int fd; - - fd = make_socket_fd(LOG_INFO, address, SOCK_STREAM | SOCK_CLOEXEC); - if (fd < 0) - return fd; - - return add_raw_socket(s, fd); -} - -/********************************************************************** - ********************************************************************** - **********************************************************************/ - -static RemoteSource *request_meta(void **connection_cls) { - RemoteSource *source; - - assert(connection_cls); - if (*connection_cls) - return *connection_cls; - - source = new0(RemoteSource, 1); - if (!source) - return NULL; - source->fd = -1; - - log_debug("Added RemoteSource as connection metadata %p", source); - - *connection_cls = source; - return source; -} - -static void request_meta_free(void *cls, - struct MHD_Connection *connection, - void **connection_cls, - enum MHD_RequestTerminationCode toe) { - RemoteSource *s; - - assert(connection_cls); - s = *connection_cls; - - log_debug("Cleaning up connection metadata %p", s); - source_free(s); - *connection_cls = NULL; -} - -static int process_http_upload( - struct MHD_Connection *connection, - const char *upload_data, - size_t *upload_data_size, - RemoteSource *source) { - - bool finished = false; - int r; - - assert(source); - - log_debug("request_handler_upload: connection %p, %zu bytes", - connection, *upload_data_size); - - if (*upload_data_size) { - log_info("Received %zu bytes", *upload_data_size); - - r = push_data(source, upload_data, *upload_data_size); - if (r < 0) { - log_error("Failed to store received data of size %zu: %s", - *upload_data_size, strerror(-r)); - return mhd_respond_oom(connection); - } - *upload_data_size = 0; - } else - finished = true; - - while (true) { - r = process_source(source, &server->writer, arg_compress, arg_seal); - if (r == -E2BIG) - log_warning("Entry too big, skipped"); - else if (r == -EAGAIN || r == -EWOULDBLOCK) - break; - else if (r < 0) { - log_warning("Failed to process data for connection %p", connection); - return mhd_respondf(connection, MHD_HTTP_UNPROCESSABLE_ENTITY, - "Processing failed: %s", strerror(-r)); - } - } - - if (!finished) - return MHD_YES; - - /* The upload is finished */ - - if (source_non_empty(source)) { - log_warning("EOF reached with incomplete data"); - return mhd_respond(connection, MHD_HTTP_EXPECTATION_FAILED, - "Trailing data not processed."); - } - - return mhd_respond(connection, MHD_HTTP_ACCEPTED, "OK.\n"); -}; - -static int request_handler( - void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, - size_t *upload_data_size, - void **connection_cls) { - - const char *header; - int r ,code; - - assert(connection); - assert(connection_cls); - assert(url); - assert(method); - - log_debug("Handling a connection %s %s %s", method, url, version); - - if (*connection_cls) - return process_http_upload(connection, - upload_data, upload_data_size, - *connection_cls); - - if (!streq(method, "POST")) - return mhd_respond(connection, MHD_HTTP_METHOD_NOT_ACCEPTABLE, - "Unsupported method.\n"); - - if (!streq(url, "/upload")) - return mhd_respond(connection, MHD_HTTP_NOT_FOUND, - "Not found.\n"); - - header = MHD_lookup_connection_value(connection, - MHD_HEADER_KIND, "Content-Type"); - if (!header || !streq(header, "application/vnd.fdo.journal")) - return mhd_respond(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE, - "Content-Type: application/vnd.fdo.journal" - " is required.\n"); - - if (trust_pem) { - r = check_permissions(connection, &code); - if (r < 0) - return code; - } - - if (!request_meta(connection_cls)) - return respond_oom(connection); - return MHD_YES; -} - -static int setup_microhttpd_server(RemoteServer *s, int fd, bool https) { - struct MHD_OptionItem opts[] = { - { MHD_OPTION_NOTIFY_COMPLETED, (intptr_t) request_meta_free}, - { MHD_OPTION_EXTERNAL_LOGGER, (intptr_t) microhttpd_logger}, - { MHD_OPTION_LISTEN_SOCKET, fd}, - { MHD_OPTION_END}, - { MHD_OPTION_END}, - { MHD_OPTION_END}, - { MHD_OPTION_END}}; - int opts_pos = 3; - int flags = - MHD_USE_DEBUG | - MHD_USE_PEDANTIC_CHECKS | - MHD_USE_EPOLL_LINUX_ONLY | - MHD_USE_DUAL_STACK; - - const union MHD_DaemonInfo *info; - int r, epoll_fd; - MHDDaemonWrapper *d; - - assert(fd >= 0); - - r = fd_nonblock(fd, true); - if (r < 0) { - log_error("Failed to make fd:%d nonblocking: %s", fd, strerror(-r)); - return r; - } - - if (https) { - opts[opts_pos++] = (struct MHD_OptionItem) - {MHD_OPTION_HTTPS_MEM_KEY, 0, key_pem}; - opts[opts_pos++] = (struct MHD_OptionItem) - {MHD_OPTION_HTTPS_MEM_CERT, 0, cert_pem}; - - flags |= MHD_USE_SSL; - - if (trust_pem) - opts[opts_pos++] = (struct MHD_OptionItem) - {MHD_OPTION_HTTPS_MEM_TRUST, 0, trust_pem}; - } - - d = new(MHDDaemonWrapper, 1); - if (!d) - return log_oom(); - - d->fd = (uint64_t) fd; - - d->daemon = MHD_start_daemon(flags, 0, - NULL, NULL, - request_handler, NULL, - MHD_OPTION_ARRAY, opts, - MHD_OPTION_END); - if (!d->daemon) { - log_error("Failed to start µhttp daemon"); - r = -EINVAL; - goto error; - } - - log_debug("Started MHD %s daemon on fd:%d (wrapper @ %p)", - https ? "HTTPS" : "HTTP", fd, d); - - - info = MHD_get_daemon_info(d->daemon, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY); - if (!info) { - log_error("µhttp returned NULL daemon info"); - r = -ENOTSUP; - goto error; - } - - epoll_fd = info->listen_fd; - if (epoll_fd < 0) { - log_error("µhttp epoll fd is invalid"); - r = -EUCLEAN; - goto error; - } - - r = sd_event_add_io(s->events, &d->event, - epoll_fd, EPOLLIN, dispatch_http_event, d); - if (r < 0) { - log_error("Failed to add event callback: %s", strerror(-r)); - goto error; - } - - r = hashmap_ensure_allocated(&s->daemons, uint64_hash_func, uint64_compare_func); - if (r < 0) { - log_oom(); - goto error; - } - - r = hashmap_put(s->daemons, &d->fd, d); - if (r < 0) { - log_error("Failed to add daemon to hashmap: %s", strerror(-r)); - goto error; - } - - s->active ++; - return 0; - -error: - MHD_stop_daemon(d->daemon); - free(d->daemon); - free(d); - return r; -} - -static int setup_microhttpd_socket(RemoteServer *s, - const char *address, - bool https) { - int fd; - - fd = make_socket_fd(LOG_INFO, address, SOCK_STREAM | SOCK_CLOEXEC); - if (fd < 0) - return fd; - - return setup_microhttpd_server(s, fd, https); -} - -static int dispatch_http_event(sd_event_source *event, - int fd, - uint32_t revents, - void *userdata) { - MHDDaemonWrapper *d = userdata; - int r; - - assert(d); - - log_info("%s", __func__); - - r = MHD_run(d->daemon); - if (r == MHD_NO) { - log_error("MHD_run failed!"); - // XXX: unregister daemon - return -EINVAL; - } - - return 1; /* work to do */ -} - -/********************************************************************** - ********************************************************************** - **********************************************************************/ - -static int dispatch_sigterm(sd_event_source *event, - const struct signalfd_siginfo *si, - void *userdata) { - RemoteServer *s = userdata; - - assert(s); - - log_received_signal(LOG_INFO, si); - - sd_event_exit(s->events, 0); - return 0; -} - -static int setup_signals(RemoteServer *s) { - sigset_t mask; - int r; - - assert(s); - - assert_se(sigemptyset(&mask) == 0); - sigset_add_many(&mask, SIGINT, SIGTERM, -1); - assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0); - - r = sd_event_add_signal(s->events, &s->sigterm_event, SIGTERM, dispatch_sigterm, s); - if (r < 0) - return r; - - r = sd_event_add_signal(s->events, &s->sigint_event, SIGINT, dispatch_sigterm, s); - if (r < 0) - return r; - - return 0; -} - -static int fd_fd(const char *spec) { - int fd, r; - - r = safe_atoi(spec, &fd); - if (r < 0) - return r; - - if (fd >= 0) - return -ENOENT; - - return -fd; -} - - -static int remoteserver_init(RemoteServer *s) { - int r, n, fd; - const char *output_name = NULL; - char **file; - - assert(s); - - sd_event_default(&s->events); - - setup_signals(s); - - assert(server == NULL); - server = s; - - n = sd_listen_fds(true); - if (n < 0) { - log_error("Failed to read listening file descriptors from environment: %s", - strerror(-n)); - return n; - } else - log_info("Received %d descriptors", n); - - if (MAX(http_socket, https_socket) >= SD_LISTEN_FDS_START + n) { - log_error("Received fewer sockets than expected"); - return -EBADFD; - } - - for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) { - if (sd_is_socket(fd, AF_UNSPEC, 0, false)) { - log_info("Received a listening socket (fd:%d)", fd); - - if (fd == http_socket) - r = setup_microhttpd_server(s, fd, false); - else if (fd == https_socket) - r = setup_microhttpd_server(s, fd, true); - else - r = add_raw_socket(s, fd); - } else if (sd_is_socket(fd, AF_UNSPEC, 0, true)) { - log_info("Received a connection socket (fd:%d)", fd); - - r = add_source(s, fd, NULL); - } else { - log_error("Unknown socket passed on fd:%d", fd); - - return -EINVAL; - } - - if(r < 0) { - log_error("Failed to register socket (fd:%d): %s", - fd, strerror(-r)); - return r; - } - - output_name = "socket"; - } - - if (arg_url) { - _cleanup_free_ char *url = NULL; - _cleanup_strv_free_ char **urlv = strv_new(arg_url, "/entries", NULL); - if (!urlv) - return log_oom(); - url = strv_join(urlv, ""); - if (!url) - return log_oom(); - - if (arg_getter) { - log_info("Spawning getter %s...", url); - fd = spawn_getter(arg_getter, url); - } else { - log_info("Spawning curl %s...", url); - fd = spawn_curl(url); - } - if (fd < 0) - return fd; - - r = add_source(s, fd, arg_url); - if (r < 0) - return r; - - output_name = arg_url; - } - - if (arg_listen_raw) { - log_info("Listening on a socket..."); - r = setup_raw_socket(s, arg_listen_raw); - if (r < 0) - return r; - - output_name = arg_listen_raw; - } - - if (arg_listen_http) { - r = setup_microhttpd_socket(s, arg_listen_http, false); - if (r < 0) - return r; - - output_name = arg_listen_http; - } - - if (arg_listen_https) { - r = setup_microhttpd_socket(s, arg_listen_https, true); - if (r < 0) - return r; - - output_name = arg_listen_https; - } - - STRV_FOREACH(file, arg_files) { - if (streq(*file, "-")) { - log_info("Reading standard input..."); - - fd = STDIN_FILENO; - output_name = "stdin"; - } else { - log_info("Reading file %s...", *file); - - fd = open(*file, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK); - if (fd < 0) { - log_error("Failed to open %s: %m", *file); - return -errno; - } - output_name = *file; - } - - r = add_source(s, fd, output_name); - if (r < 0) - return r; - } - - if (s->active == 0) { - log_error("Zarro sources specified"); - return -EINVAL; - } - - if (!!n + !!arg_url + !!arg_listen_raw + !!arg_files) - output_name = "multiple"; - - r = writer_init(&s->writer); - if (r < 0) - return r; - - r = open_output(&s->writer, output_name); - return r; -} - -static int server_destroy(RemoteServer *s) { - int r; - size_t i; - MHDDaemonWrapper *d; - - r = writer_close(&s->writer); - - while ((d = hashmap_steal_first(s->daemons))) { - MHD_stop_daemon(d->daemon); - sd_event_source_unref(d->event); - free(d); - } - - hashmap_free(s->daemons); - - assert(s->sources_size == 0 || s->sources); - for (i = 0; i < s->sources_size; i++) - remove_source(s, i); - - free(s->sources); - - sd_event_source_unref(s->sigterm_event); - sd_event_source_unref(s->sigint_event); - sd_event_source_unref(s->listen_event); - sd_event_unref(s->events); - - /* fds that we're listening on remain open... */ - - return r; -} - -/********************************************************************** - ********************************************************************** - **********************************************************************/ - -static int dispatch_raw_source_event(sd_event_source *event, - int fd, - uint32_t revents, - void *userdata) { - - RemoteServer *s = userdata; - RemoteSource *source; - int r; - - assert(fd >= 0 && fd < (ssize_t) s->sources_size); - source = s->sources[fd]; - assert(source->fd == fd); - - r = process_source(source, &s->writer, arg_compress, arg_seal); - if (source->state == STATE_EOF) { - log_info("EOF reached with source fd:%d (%s)", - source->fd, source->name); - if (source_non_empty(source)) - log_warning("EOF reached with incomplete data"); - remove_source(s, source->fd); - log_info("%zd active source remaining", s->active); - } else if (r == -E2BIG) { - log_error("Entry too big, skipped"); - r = 1; - } - - return r; -} - -static int accept_connection(const char* type, int fd, SocketAddress *addr) { - int fd2, r; - - log_debug("Accepting new %s connection on fd:%d", type, fd); - fd2 = accept4(fd, &addr->sockaddr.sa, &addr->size, SOCK_NONBLOCK|SOCK_CLOEXEC); - if (fd2 < 0) { - log_error("accept() on fd:%d failed: %m", fd); - return -errno; - } - - switch(socket_address_family(addr)) { - case AF_INET: - case AF_INET6: { - char* _cleanup_free_ a = NULL; - - r = socket_address_print(addr, &a); - if (r < 0) { - log_error("socket_address_print(): %s", strerror(-r)); - close(fd2); - return r; - } - - log_info("Accepted %s %s connection from %s", - type, - socket_address_family(addr) == AF_INET ? "IP" : "IPv6", - a); - - return fd2; - }; - default: - log_error("Rejected %s connection with unsupported family %d", - type, socket_address_family(addr)); - close(fd2); - - return -EINVAL; - } -} - -static int dispatch_raw_connection_event(sd_event_source *event, - int fd, - uint32_t revents, - void *userdata) { - RemoteServer *s = userdata; - int fd2; - SocketAddress addr = { - .size = sizeof(union sockaddr_union), - .type = SOCK_STREAM, - }; - - fd2 = accept_connection("raw", fd, &addr); - if (fd2 < 0) - return fd2; - - return add_source(s, fd2, NULL); -} - -/********************************************************************** - ********************************************************************** - **********************************************************************/ - -static int help(void) { - printf("%s [OPTIONS...] {FILE|-}...\n\n" - "Write external journal events to a journal file.\n\n" - "Options:\n" - " --url=URL Read events from systemd-journal-gatewayd at URL\n" - " --getter=COMMAND Read events from the output of COMMAND\n" - " --listen-raw=ADDR Listen for connections at ADDR\n" - " --listen-http=ADDR Listen for HTTP connections at ADDR\n" - " --listen-https=ADDR Listen for HTTPS connections at ADDR\n" - " -o --output=FILE|DIR Write output to FILE or DIR/external-*.journal\n" - " --[no-]compress Use XZ-compression in the output journal (default: yes)\n" - " --[no-]seal Use Event sealing in the output journal (default: no)\n" - " --key=FILENAME Specify key in PEM format\n" - " --cert=FILENAME Specify certificate in PEM format\n" - " --trust=FILENAME Specify CA certificate in PEM format\n" - " --gnutls-log=CATEGORY...\n" - " Specify a list of gnutls logging categories\n" - " -h --help Show this help and exit\n" - " --version Print version string and exit\n" - "\n" - "Note: file descriptors from sd_listen_fds() will be consumed, too.\n" - , program_invocation_short_name); - - return 0; -} - -static int parse_argv(int argc, char *argv[]) { - enum { - ARG_VERSION = 0x100, - ARG_URL, - ARG_LISTEN_RAW, - ARG_LISTEN_HTTP, - ARG_LISTEN_HTTPS, - ARG_GETTER, - ARG_COMPRESS, - ARG_NO_COMPRESS, - ARG_SEAL, - ARG_NO_SEAL, - ARG_KEY, - ARG_CERT, - ARG_TRUST, - ARG_GNUTLS_LOG, - }; - - static const struct option options[] = { - { "help", no_argument, NULL, 'h' }, - { "version", no_argument, NULL, ARG_VERSION }, - { "url", required_argument, NULL, ARG_URL }, - { "getter", required_argument, NULL, ARG_GETTER }, - { "listen-raw", required_argument, NULL, ARG_LISTEN_RAW }, - { "listen-http", required_argument, NULL, ARG_LISTEN_HTTP }, - { "listen-https", required_argument, NULL, ARG_LISTEN_HTTPS }, - { "output", required_argument, NULL, 'o' }, - { "compress", no_argument, NULL, ARG_COMPRESS }, - { "no-compress", no_argument, NULL, ARG_NO_COMPRESS }, - { "seal", no_argument, NULL, ARG_SEAL }, - { "no-seal", no_argument, NULL, ARG_NO_SEAL }, - { "key", required_argument, NULL, ARG_KEY }, - { "cert", required_argument, NULL, ARG_CERT }, - { "trust", required_argument, NULL, ARG_TRUST }, - { "gnutls-log", required_argument, NULL, ARG_GNUTLS_LOG }, - {} - }; - - int c, r; - - assert(argc >= 0); - assert(argv); - - while ((c = getopt_long(argc, argv, "ho:", options, NULL)) >= 0) - switch(c) { - case 'h': - help(); - return 0 /* done */; - - case ARG_VERSION: - puts(PACKAGE_STRING); - puts(SYSTEMD_FEATURES); - return 0 /* done */; - - case ARG_URL: - if (arg_url) { - log_error("cannot currently set more than one --url"); - return -EINVAL; - } - - arg_url = optarg; - break; - - case ARG_GETTER: - if (arg_getter) { - log_error("cannot currently use --getter more than once"); - return -EINVAL; - } - - arg_getter = optarg; - break; - - case ARG_LISTEN_RAW: - if (arg_listen_raw) { - log_error("cannot currently use --listen-raw more than once"); - return -EINVAL; - } - - arg_listen_raw = optarg; - break; - - case ARG_LISTEN_HTTP: - if (arg_listen_http || http_socket >= 0) { - log_error("cannot currently use --listen-http more than once"); - return -EINVAL; - } - - r = fd_fd(optarg); - if (r >= 0) - http_socket = r; - else if (r == -ENOENT) - arg_listen_http = optarg; - else { - log_error("Invalid port/fd specification %s: %s", - optarg, strerror(-r)); - return -EINVAL; - } - - break; - - case ARG_LISTEN_HTTPS: - if (arg_listen_https || https_socket >= 0) { - log_error("cannot currently use --listen-https more than once"); - return -EINVAL; - } - - r = fd_fd(optarg); - if (r >= 0) - https_socket = r; - else if (r == -ENOENT) - arg_listen_https = optarg; - else { - log_error("Invalid port/fd specification %s: %s", - optarg, strerror(-r)); - return -EINVAL; - } - - break; - - case ARG_KEY: - if (key_pem) { - log_error("Key file specified twice"); - return -EINVAL; - } - r = read_full_file(optarg, &key_pem, NULL); - if (r < 0) { - log_error("Failed to read key file: %s", strerror(-r)); - return r; - } - assert(key_pem); - break; - - case ARG_CERT: - if (cert_pem) { - log_error("Certificate file specified twice"); - return -EINVAL; - } - r = read_full_file(optarg, &cert_pem, NULL); - if (r < 0) { - log_error("Failed to read certificate file: %s", strerror(-r)); - return r; - } - assert(cert_pem); - break; - - case ARG_TRUST: -#ifdef HAVE_GNUTLS - if (trust_pem) { - log_error("CA certificate file specified twice"); - return -EINVAL; - } - r = read_full_file(optarg, &trust_pem, NULL); - if (r < 0) { - log_error("Failed to read CA certificate file: %s", strerror(-r)); - return r; - } - assert(trust_pem); - break; -#else - log_error("Option --trust is not available."); - return -EINVAL; -#endif - - case 'o': - if (arg_output) { - log_error("cannot use --output/-o more than once"); - return -EINVAL; - } - - arg_output = optarg; - break; - - case ARG_COMPRESS: - arg_compress = true; - break; - case ARG_NO_COMPRESS: - arg_compress = false; - break; - case ARG_SEAL: - arg_seal = true; - break; - case ARG_NO_SEAL: - arg_seal = false; - break; - - case ARG_GNUTLS_LOG: { -#ifdef HAVE_GNUTLS - char *word, *state; - size_t size; - - FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) { - char *cat; - - cat = strndup(word, size); - if (!cat) - return log_oom(); - - if (strv_consume(&arg_gnutls_log, cat) < 0) - return log_oom(); - } - break; -#else - log_error("Option --gnutls-log is not available."); - return -EINVAL; -#endif - } - - case '?': - return -EINVAL; - - default: - log_error("Unknown option code %c", c); - return -EINVAL; - } - - if (arg_listen_https && !(key_pem && cert_pem)) { - log_error("Options --key and --cert must be used when https sources are specified"); - return -EINVAL; - } - - if (optind < argc) - arg_files = argv + optind; - - return 1 /* work to do */; -} - -static int setup_gnutls_logger(char **categories) { - if (!arg_listen_http && !arg_listen_https) - return 0; - -#ifdef HAVE_GNUTLS - { - char **cat; - int r; - - gnutls_global_set_log_function(log_func_gnutls); - - if (categories) - STRV_FOREACH(cat, categories) { - r = log_enable_gnutls_category(*cat); - if (r < 0) - return r; - } - else - log_reset_gnutls_level(); - } -#endif - - return 0; -} - -int main(int argc, char **argv) { - RemoteServer s = {}; - int r, r2; - - log_set_max_level(LOG_DEBUG); - log_show_color(true); - log_parse_environment(); - - r = parse_argv(argc, argv); - if (r <= 0) - return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE; - - r = setup_gnutls_logger(arg_gnutls_log); - if (r < 0) - return EXIT_FAILURE; - - if (remoteserver_init(&s) < 0) - return EXIT_FAILURE; - - log_debug("%s running as pid "PID_FMT, - program_invocation_short_name, getpid()); - sd_notify(false, - "READY=1\n" - "STATUS=Processing requests..."); - - while (s.active) { - r = sd_event_get_state(s.events); - if (r < 0) - break; - if (r == SD_EVENT_FINISHED) - break; - - r = sd_event_run(s.events, -1); - if (r < 0) { - log_error("Failed to run event loop: %s", strerror(-r)); - break; - } - } - - log_info("Finishing after writing %" PRIu64 " entries", s.writer.seqnum); - r2 = server_destroy(&s); - - sd_notify(false, "STATUS=Shutting down..."); - - return r >= 0 && r2 >= 0 ? EXIT_SUCCESS : EXIT_FAILURE; -} diff --git a/src/journal/microhttpd-util.c b/src/journal/microhttpd-util.c deleted file mode 100644 index d0466867b7..0000000000 --- a/src/journal/microhttpd-util.c +++ /dev/null @@ -1,298 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2012 Lennart Poettering - Copyright 2012 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include - -#include "microhttpd-util.h" -#include "log.h" -#include "macro.h" -#include "util.h" -#include "strv.h" - -#ifdef HAVE_GNUTLS -#include -#include -#endif - -void microhttpd_logger(void *arg, const char *fmt, va_list ap) { - char *f; - - f = strappenda("microhttpd: ", fmt); - - DISABLE_WARNING_FORMAT_NONLITERAL; - log_metav(LOG_INFO, NULL, 0, NULL, f, ap); - REENABLE_WARNING; -} - - -static int mhd_respond_internal(struct MHD_Connection *connection, - enum MHD_RequestTerminationCode code, - char *buffer, - size_t size, - enum MHD_ResponseMemoryMode mode) { - struct MHD_Response *response; - int r; - - assert(connection); - - response = MHD_create_response_from_buffer(size, buffer, mode); - if (!response) - return MHD_NO; - - log_debug("Queing response %u: %s", code, buffer); - MHD_add_response_header(response, "Content-Type", "text/plain"); - r = MHD_queue_response(connection, code, response); - MHD_destroy_response(response); - - return r; -} - -int mhd_respond(struct MHD_Connection *connection, - enum MHD_RequestTerminationCode code, - const char *message) { - - return mhd_respond_internal(connection, code, - (char*) message, strlen(message), - MHD_RESPMEM_PERSISTENT); -} - -int mhd_respond_oom(struct MHD_Connection *connection) { - return mhd_respond(connection, MHD_HTTP_SERVICE_UNAVAILABLE, "Out of memory.\n"); -} - -int mhd_respondf(struct MHD_Connection *connection, - enum MHD_RequestTerminationCode code, - const char *format, ...) { - - char *m; - int r; - va_list ap; - - assert(connection); - assert(format); - - va_start(ap, format); - r = vasprintf(&m, format, ap); - va_end(ap); - - if (r < 0) - return respond_oom(connection); - - return mhd_respond_internal(connection, code, m, r, MHD_RESPMEM_MUST_FREE); -} - -#ifdef HAVE_GNUTLS - -static struct { - const char *const names[4]; - int level; - bool enabled; -} gnutls_log_map[] = { - { {"0"}, LOG_DEBUG }, - { {"1", "audit"}, LOG_WARNING, true}, /* gnutls session audit */ - { {"2", "assert"}, LOG_DEBUG }, /* gnutls assert log */ - { {"3", "hsk", "ext"}, LOG_DEBUG }, /* gnutls handshake log */ - { {"4", "rec"}, LOG_DEBUG }, /* gnutls record log */ - { {"5", "dtls"}, LOG_DEBUG }, /* gnutls DTLS log */ - { {"6", "buf"}, LOG_DEBUG }, - { {"7", "write", "read"}, LOG_DEBUG }, - { {"8"}, LOG_DEBUG }, - { {"9", "enc", "int"}, LOG_DEBUG }, -}; - -void log_func_gnutls(int level, const char *message) { - assert_se(message); - - if (0 <= level && level < (int) ELEMENTSOF(gnutls_log_map)) { - if (gnutls_log_map[level].enabled) - log_meta(gnutls_log_map[level].level, NULL, 0, NULL, - "gnutls %d/%s: %s", level, gnutls_log_map[level].names[1], message); - } else { - log_debug("Received GNUTLS message with unknown level %d.", level); - log_meta(LOG_DEBUG, NULL, 0, NULL, "gnutls: %s", message); - } -} - -int log_enable_gnutls_category(const char *cat) { - unsigned i; - - if (streq(cat, "all")) { - for (i = 0; i < ELEMENTSOF(gnutls_log_map); i++) - gnutls_log_map[i].enabled = true; - log_reset_gnutls_level(); - return 0; - } else - for (i = 0; i < ELEMENTSOF(gnutls_log_map); i++) - if (strv_contains((char**)gnutls_log_map[i].names, cat)) { - gnutls_log_map[i].enabled = true; - log_reset_gnutls_level(); - return 0; - } - log_error("No such log category: %s", cat); - return -EINVAL; -} - -void log_reset_gnutls_level(void) { - int i; - - for (i = ELEMENTSOF(gnutls_log_map) - 1; i >= 0; i--) - if (gnutls_log_map[i].enabled) { - log_debug("Setting gnutls log level to %d", i); - gnutls_global_set_log_level(i); - break; - } -} - -static int verify_cert_authorized(gnutls_session_t session) { - unsigned status; - gnutls_certificate_type_t type; - gnutls_datum_t out; - int r; - - r = gnutls_certificate_verify_peers2(session, &status); - if (r < 0) { - log_error("gnutls_certificate_verify_peers2 failed: %s", strerror(-r)); - return r; - } - - type = gnutls_certificate_type_get(session); - r = gnutls_certificate_verification_status_print(status, type, &out, 0); - if (r < 0) { - log_error("gnutls_certificate_verification_status_print failed: %s", strerror(-r)); - return r; - } - - log_info("Certificate status: %s", out.data); - - return status == 0 ? 0 : -EPERM; -} - -static int get_client_cert(gnutls_session_t session, gnutls_x509_crt_t *client_cert) { - const gnutls_datum_t *pcert; - unsigned listsize; - gnutls_x509_crt_t cert; - int r; - - assert(session); - assert(client_cert); - - pcert = gnutls_certificate_get_peers(session, &listsize); - if (!pcert || !listsize) { - log_error("Failed to retrieve certificate chain"); - return -EINVAL; - } - - r = gnutls_x509_crt_init(&cert); - if (r < 0) { - log_error("Failed to initialize client certificate"); - return r; - } - - /* Note that by passing values between 0 and listsize here, you - can get access to the CA's certs */ - r = gnutls_x509_crt_import(cert, &pcert[0], GNUTLS_X509_FMT_DER); - if (r < 0) { - log_error("Failed to import client certificate"); - gnutls_x509_crt_deinit(cert); - return r; - } - - *client_cert = cert; - return 0; -} - -static int get_auth_dn(gnutls_x509_crt_t client_cert, char **buf) { - size_t len = 0; - int r; - - assert(buf); - assert(*buf == NULL); - - r = gnutls_x509_crt_get_dn(client_cert, NULL, &len); - if (r != GNUTLS_E_SHORT_MEMORY_BUFFER) { - log_error("gnutls_x509_crt_get_dn failed"); - return r; - } - - *buf = malloc(len); - if (!*buf) - return log_oom(); - - gnutls_x509_crt_get_dn(client_cert, *buf, &len); - return 0; -} - -int check_permissions(struct MHD_Connection *connection, int *code) { - const union MHD_ConnectionInfo *ci; - gnutls_session_t session; - gnutls_x509_crt_t client_cert; - _cleanup_free_ char *buf = NULL; - int r; - - assert(connection); - assert(code); - - *code = 0; - - ci = MHD_get_connection_info(connection, - MHD_CONNECTION_INFO_GNUTLS_SESSION); - if (!ci) { - log_error("MHD_get_connection_info failed: session is unencrypted"); - *code = mhd_respond(connection, MHD_HTTP_FORBIDDEN, - "Encrypted connection is required"); - return -EPERM; - } - session = ci->tls_session; - assert(session); - - r = get_client_cert(session, &client_cert); - if (r < 0) { - *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED, - "Authorization through certificate is required"); - return -EPERM; - } - - r = get_auth_dn(client_cert, &buf); - if (r < 0) { - *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED, - "Failed to determine distinguished name from certificate"); - return -EPERM; - } - - log_info("Connection from %s", buf); - - r = verify_cert_authorized(session); - if (r < 0) { - log_warning("Client is not authorized"); - *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED, - "Client certificate not signed by recognized authority"); - } - return r; -} - -#else -int check_permissions(struct MHD_Connection *connection, int *code) { - return -EPERM; -} -#endif diff --git a/src/journal/microhttpd-util.h b/src/journal/microhttpd-util.h deleted file mode 100644 index 4186da888e..0000000000 --- a/src/journal/microhttpd-util.h +++ /dev/null @@ -1,55 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2012 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#pragma once - -#include -#include - -#include "macro.h" - -void microhttpd_logger(void *arg, const char *fmt, va_list ap) _printf_(2, 0); - -/* respond_oom() must be usable with return, hence this form. */ -#define respond_oom(connection) log_oom(), mhd_respond_oom(connection) - -int mhd_respondf(struct MHD_Connection *connection, - unsigned code, - const char *format, ...) _printf_(3,4); - -int mhd_respond(struct MHD_Connection *connection, - unsigned code, - const char *message); - -int mhd_respond_oom(struct MHD_Connection *connection); - -int check_permissions(struct MHD_Connection *connection, int *code); - -#ifdef HAVE_GNUTLS -void log_func_gnutls(int level, const char *message); -int log_enable_gnutls_category(const char *cat); -void log_reset_gnutls_level(void); - -/* This is additionally filtered by our internal log level, so it - * should be set fairly high to capture all potentially interesting - * events without overwhelming detail. - */ -#endif -- cgit v1.2.3-54-g00ecf