]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/journal-remote/journal-remote-main.c
tree-wide: invoke rlimit_nofile_safe() before various exec{v,ve,l}() invocations
[thirdparty/systemd.git] / src / journal-remote / journal-remote-main.c
CommitLineData
c064d8db
ZJS
1/* SPDX-License-Identifier: LGPL-2.1+ */
2
3#include <getopt.h>
4#include <unistd.h>
5
6#include "sd-daemon.h"
7
8#include "conf-parser.h"
9#include "def.h"
10#include "fd-util.h"
11#include "fileio.h"
12#include "journal-remote-write.h"
13#include "journal-remote.h"
294bf0c3 14#include "pretty-print.h"
c064d8db 15#include "process-util.h"
1abaf488 16#include "rlimit-util.h"
c064d8db
ZJS
17#include "signal-util.h"
18#include "socket-util.h"
19#include "stat-util.h"
20#include "string-table.h"
21#include "strv.h"
22
23#define PRIV_KEY_FILE CERTIFICATE_ROOT "/private/journal-remote.pem"
24#define CERT_FILE CERTIFICATE_ROOT "/certs/journal-remote.pem"
25#define TRUST_FILE CERTIFICATE_ROOT "/ca/trusted.pem"
26
27static char* arg_url = NULL;
28static char* arg_getter = NULL;
29static char* arg_listen_raw = NULL;
30static char* arg_listen_http = NULL;
31static char* arg_listen_https = NULL;
32static char** arg_files = NULL;
33static int arg_compress = true;
34static int arg_seal = false;
35static int http_socket = -1, https_socket = -1;
36static char** arg_gnutls_log = NULL;
37
38static JournalWriteSplitMode arg_split_mode = _JOURNAL_WRITE_SPLIT_INVALID;
39static char* arg_output = NULL;
40
41static char *arg_key = NULL;
42static char *arg_cert = NULL;
43static char *arg_trust = NULL;
44static bool arg_trust_all = false;
45
46static const char* const journal_write_split_mode_table[_JOURNAL_WRITE_SPLIT_MAX] = {
47 [JOURNAL_WRITE_SPLIT_NONE] = "none",
48 [JOURNAL_WRITE_SPLIT_HOST] = "host",
49};
50
51DEFINE_PRIVATE_STRING_TABLE_LOOKUP(journal_write_split_mode, JournalWriteSplitMode);
52static DEFINE_CONFIG_PARSE_ENUM(config_parse_write_split_mode,
53 journal_write_split_mode,
54 JournalWriteSplitMode,
55 "Failed to parse split mode setting");
56
57/**********************************************************************
58 **********************************************************************
59 **********************************************************************/
60
61static int spawn_child(const char* child, char** argv) {
62 pid_t child_pid;
63 int fd[2], r;
64
65 if (pipe(fd) < 0)
66 return log_error_errno(errno, "Failed to create pager pipe: %m");
67
68 r = safe_fork("(remote)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &child_pid);
69 if (r < 0) {
70 safe_close_pair(fd);
71 return r;
72 }
73
74 /* In the child */
75 if (r == 0) {
76 safe_close(fd[0]);
77
78 r = rearrange_stdio(STDIN_FILENO, fd[1], STDERR_FILENO);
79 if (r < 0) {
80 log_error_errno(r, "Failed to dup pipe to stdout: %m");
81 _exit(EXIT_FAILURE);
82 }
83
595225af
LP
84 (void) rlimit_nofile_safe();
85
c064d8db
ZJS
86 execvp(child, argv);
87 log_error_errno(errno, "Failed to exec child %s: %m", child);
88 _exit(EXIT_FAILURE);
89 }
90
91 safe_close(fd[1]);
92
93 r = fd_nonblock(fd[0], true);
94 if (r < 0)
95 log_warning_errno(errno, "Failed to set child pipe to non-blocking: %m");
96
97 return fd[0];
98}
99
100static int spawn_curl(const char* url) {
101 char **argv = STRV_MAKE("curl",
102 "-HAccept: application/vnd.fdo.journal",
103 "--silent",
104 "--show-error",
105 url);
106 int r;
107
108 r = spawn_child("curl", argv);
109 if (r < 0)
110 log_error_errno(r, "Failed to spawn curl: %m");
111 return r;
112}
113
114static int spawn_getter(const char *getter) {
115 int r;
116 _cleanup_strv_free_ char **words = NULL;
117
118 assert(getter);
119 r = strv_split_extract(&words, getter, WHITESPACE, EXTRACT_QUOTES);
120 if (r < 0)
121 return log_error_errno(r, "Failed to split getter option: %m");
122
123 r = spawn_child(words[0], words);
124 if (r < 0)
125 log_error_errno(r, "Failed to spawn getter %s: %m", getter);
126
127 return r;
128}
129
130/**********************************************************************
131 **********************************************************************
132 **********************************************************************/
133
134static int null_timer_event_handler(sd_event_source *s,
135 uint64_t usec,
136 void *userdata);
137static int dispatch_http_event(sd_event_source *event,
138 int fd,
139 uint32_t revents,
140 void *userdata);
141
142static int request_meta(void **connection_cls, int fd, char *hostname) {
143 RemoteSource *source;
144 Writer *writer;
145 int r;
146
147 assert(connection_cls);
148 if (*connection_cls)
149 return 0;
150
151 r = journal_remote_get_writer(journal_remote_server_global, hostname, &writer);
152 if (r < 0)
153 return log_warning_errno(r, "Failed to get writer for source %s: %m",
154 hostname);
155
156 source = source_new(fd, true, hostname, writer);
157 if (!source) {
158 writer_unref(writer);
159 return log_oom();
160 }
161
162 log_debug("Added RemoteSource as connection metadata %p", source);
163
164 *connection_cls = source;
165 return 0;
166}
167
168static void request_meta_free(void *cls,
169 struct MHD_Connection *connection,
170 void **connection_cls,
171 enum MHD_RequestTerminationCode toe) {
172 RemoteSource *s;
173
174 assert(connection_cls);
175 s = *connection_cls;
176
177 if (s) {
178 log_debug("Cleaning up connection metadata %p", s);
179 source_free(s);
180 *connection_cls = NULL;
181 }
182}
183
184static int process_http_upload(
185 struct MHD_Connection *connection,
186 const char *upload_data,
187 size_t *upload_data_size,
188 RemoteSource *source) {
189
190 bool finished = false;
191 size_t remaining;
192 int r;
193
194 assert(source);
195
196 log_trace("%s: connection %p, %zu bytes",
197 __func__, connection, *upload_data_size);
198
199 if (*upload_data_size) {
200 log_trace("Received %zu bytes", *upload_data_size);
201
202 r = journal_importer_push_data(&source->importer,
203 upload_data, *upload_data_size);
204 if (r < 0)
205 return mhd_respond_oom(connection);
206
207 *upload_data_size = 0;
208 } else
209 finished = true;
210
211 for (;;) {
212 r = process_source(source,
213 journal_remote_server_global->compress,
214 journal_remote_server_global->seal);
215 if (r == -EAGAIN)
216 break;
217 else if (r < 0) {
218 log_warning("Failed to process data for connection %p", connection);
219 if (r == -E2BIG)
220 return mhd_respondf(connection,
221 r, MHD_HTTP_PAYLOAD_TOO_LARGE,
222 "Entry is too large, maximum is " STRINGIFY(DATA_SIZE_MAX) " bytes.");
223 else
224 return mhd_respondf(connection,
225 r, MHD_HTTP_UNPROCESSABLE_ENTITY,
226 "Processing failed: %m.");
227 }
228 }
229
230 if (!finished)
231 return MHD_YES;
232
233 /* The upload is finished */
234
235 remaining = journal_importer_bytes_remaining(&source->importer);
236 if (remaining > 0) {
237 log_warning("Premature EOF byte. %zu bytes lost.", remaining);
238 return mhd_respondf(connection,
239 0, MHD_HTTP_EXPECTATION_FAILED,
240 "Premature EOF. %zu bytes of trailing data not processed.",
241 remaining);
242 }
243
244 return mhd_respond(connection, MHD_HTTP_ACCEPTED, "OK.");
245};
246
247static int request_handler(
248 void *cls,
249 struct MHD_Connection *connection,
250 const char *url,
251 const char *method,
252 const char *version,
253 const char *upload_data,
254 size_t *upload_data_size,
255 void **connection_cls) {
256
257 const char *header;
258 int r, code, fd;
259 _cleanup_free_ char *hostname = NULL;
260
261 assert(connection);
262 assert(connection_cls);
263 assert(url);
264 assert(method);
265
266 log_trace("Handling a connection %s %s %s", method, url, version);
267
268 if (*connection_cls)
269 return process_http_upload(connection,
270 upload_data, upload_data_size,
271 *connection_cls);
272
273 if (!streq(method, "POST"))
274 return mhd_respond(connection, MHD_HTTP_NOT_ACCEPTABLE, "Unsupported method.");
275
276 if (!streq(url, "/upload"))
277 return mhd_respond(connection, MHD_HTTP_NOT_FOUND, "Not found.");
278
279 header = MHD_lookup_connection_value(connection,
280 MHD_HEADER_KIND, "Content-Type");
281 if (!header || !streq(header, "application/vnd.fdo.journal"))
282 return mhd_respond(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE,
283 "Content-Type: application/vnd.fdo.journal is required.");
284
285 {
286 const union MHD_ConnectionInfo *ci;
287
288 ci = MHD_get_connection_info(connection,
289 MHD_CONNECTION_INFO_CONNECTION_FD);
290 if (!ci) {
291 log_error("MHD_get_connection_info failed: cannot get remote fd");
292 return mhd_respond(connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
293 "Cannot check remote address.");
294 }
295
296 fd = ci->connect_fd;
297 assert(fd >= 0);
298 }
299
300 if (journal_remote_server_global->check_trust) {
301 r = check_permissions(connection, &code, &hostname);
302 if (r < 0)
303 return code;
304 } else {
305 r = getpeername_pretty(fd, false, &hostname);
306 if (r < 0)
307 return mhd_respond(connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
308 "Cannot check remote hostname.");
309 }
310
311 assert(hostname);
312
313 r = request_meta(connection_cls, fd, hostname);
314 if (r == -ENOMEM)
315 return respond_oom(connection);
316 else if (r < 0)
317 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "%m");
318
319 hostname = NULL;
320 return MHD_YES;
321}
322
323static int setup_microhttpd_server(RemoteServer *s,
324 int fd,
325 const char *key,
326 const char *cert,
327 const char *trust) {
328 struct MHD_OptionItem opts[] = {
329 { MHD_OPTION_NOTIFY_COMPLETED, (intptr_t) request_meta_free},
330 { MHD_OPTION_EXTERNAL_LOGGER, (intptr_t) microhttpd_logger},
331 { MHD_OPTION_LISTEN_SOCKET, fd},
332 { MHD_OPTION_CONNECTION_MEMORY_LIMIT, 128*1024},
333 { MHD_OPTION_END},
334 { MHD_OPTION_END},
335 { MHD_OPTION_END},
336 { MHD_OPTION_END},
337 { MHD_OPTION_END}};
338 int opts_pos = 4;
339 int flags =
340 MHD_USE_DEBUG |
341 MHD_USE_DUAL_STACK |
342 MHD_USE_EPOLL |
343 MHD_USE_ITC;
344
345 const union MHD_DaemonInfo *info;
346 int r, epoll_fd;
347 MHDDaemonWrapper *d;
348
349 assert(fd >= 0);
350
351 r = fd_nonblock(fd, true);
352 if (r < 0)
353 return log_error_errno(r, "Failed to make fd:%d nonblocking: %m", fd);
354
355/* MHD_OPTION_STRICT_FOR_CLIENT is introduced in microhttpd 0.9.54,
356 * and MHD_USE_PEDANTIC_CHECKS will be deprecated in future.
357 * If MHD_USE_PEDANTIC_CHECKS is '#define'd, then it is deprecated
358 * and we should use MHD_OPTION_STRICT_FOR_CLIENT. On the other hand,
359 * if MHD_USE_PEDANTIC_CHECKS is not '#define'd, then it is not
360 * deprecated yet and there exists an enum element with the same name.
361 * So we can safely use it. */
362#ifdef MHD_USE_PEDANTIC_CHECKS
363 opts[opts_pos++] = (struct MHD_OptionItem)
364 {MHD_OPTION_STRICT_FOR_CLIENT, 1};
365#else
366 flags |= MHD_USE_PEDANTIC_CHECKS;
367#endif
368
369 if (key) {
370 assert(cert);
371
372 opts[opts_pos++] = (struct MHD_OptionItem)
373 {MHD_OPTION_HTTPS_MEM_KEY, 0, (char*) key};
374 opts[opts_pos++] = (struct MHD_OptionItem)
375 {MHD_OPTION_HTTPS_MEM_CERT, 0, (char*) cert};
376
377 flags |= MHD_USE_TLS;
378
379 if (trust)
380 opts[opts_pos++] = (struct MHD_OptionItem)
381 {MHD_OPTION_HTTPS_MEM_TRUST, 0, (char*) trust};
382 }
383
384 d = new(MHDDaemonWrapper, 1);
385 if (!d)
386 return log_oom();
387
388 d->fd = (uint64_t) fd;
389
390 d->daemon = MHD_start_daemon(flags, 0,
391 NULL, NULL,
392 request_handler, NULL,
393 MHD_OPTION_ARRAY, opts,
394 MHD_OPTION_END);
395 if (!d->daemon) {
396 log_error("Failed to start µhttp daemon");
397 r = -EINVAL;
398 goto error;
399 }
400
401 log_debug("Started MHD %s daemon on fd:%d (wrapper @ %p)",
402 key ? "HTTPS" : "HTTP", fd, d);
403
404 info = MHD_get_daemon_info(d->daemon, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
405 if (!info) {
406 log_error("µhttp returned NULL daemon info");
407 r = -EOPNOTSUPP;
408 goto error;
409 }
410
411 epoll_fd = info->listen_fd;
412 if (epoll_fd < 0) {
413 log_error("µhttp epoll fd is invalid");
414 r = -EUCLEAN;
415 goto error;
416 }
417
418 r = sd_event_add_io(s->events, &d->io_event,
419 epoll_fd, EPOLLIN,
420 dispatch_http_event, d);
421 if (r < 0) {
422 log_error_errno(r, "Failed to add event callback: %m");
423 goto error;
424 }
425
426 r = sd_event_source_set_description(d->io_event, "io_event");
427 if (r < 0) {
428 log_error_errno(r, "Failed to set source name: %m");
429 goto error;
430 }
431
432 r = sd_event_add_time(s->events, &d->timer_event,
433 CLOCK_MONOTONIC, (uint64_t) -1, 0,
434 null_timer_event_handler, d);
435 if (r < 0) {
436 log_error_errno(r, "Failed to add timer_event: %m");
437 goto error;
438 }
439
440 r = sd_event_source_set_description(d->timer_event, "timer_event");
441 if (r < 0) {
442 log_error_errno(r, "Failed to set source name: %m");
443 goto error;
444 }
445
446 r = hashmap_ensure_allocated(&s->daemons, &uint64_hash_ops);
447 if (r < 0) {
448 log_oom();
449 goto error;
450 }
451
452 r = hashmap_put(s->daemons, &d->fd, d);
453 if (r < 0) {
454 log_error_errno(r, "Failed to add daemon to hashmap: %m");
455 goto error;
456 }
457
458 s->active++;
459 return 0;
460
461error:
462 MHD_stop_daemon(d->daemon);
463 free(d->daemon);
464 free(d);
465 return r;
466}
467
468static int setup_microhttpd_socket(RemoteServer *s,
469 const char *address,
470 const char *key,
471 const char *cert,
472 const char *trust) {
473 int fd;
474
475 fd = make_socket_fd(LOG_DEBUG, address, SOCK_STREAM, SOCK_CLOEXEC);
476 if (fd < 0)
477 return fd;
478
479 return setup_microhttpd_server(s, fd, key, cert, trust);
480}
481
482static int null_timer_event_handler(sd_event_source *timer_event,
483 uint64_t usec,
484 void *userdata) {
485 return dispatch_http_event(timer_event, 0, 0, userdata);
486}
487
488static int dispatch_http_event(sd_event_source *event,
489 int fd,
490 uint32_t revents,
491 void *userdata) {
492 MHDDaemonWrapper *d = userdata;
493 int r;
494 MHD_UNSIGNED_LONG_LONG timeout = ULONG_LONG_MAX;
495
496 assert(d);
497
498 r = MHD_run(d->daemon);
baaa35ad
ZJS
499 if (r == MHD_NO)
500 // FIXME: unregister daemon
501 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
502 "MHD_run failed!");
c064d8db
ZJS
503 if (MHD_get_timeout(d->daemon, &timeout) == MHD_NO)
504 timeout = ULONG_LONG_MAX;
505
506 r = sd_event_source_set_time(d->timer_event, timeout);
507 if (r < 0) {
508 log_warning_errno(r, "Unable to set event loop timeout: %m, this may result in indefinite blocking!");
509 return 1;
510 }
511
512 r = sd_event_source_set_enabled(d->timer_event, SD_EVENT_ON);
513 if (r < 0)
514 log_warning_errno(r, "Unable to enable timer_event: %m, this may result in indefinite blocking!");
515
516 return 1; /* work to do */
517}
518
519/**********************************************************************
520 **********************************************************************
521 **********************************************************************/
522
523static int setup_signals(RemoteServer *s) {
524 int r;
525
526 assert(s);
527
528 assert_se(sigprocmask_many(SIG_SETMASK, NULL, SIGINT, SIGTERM, -1) >= 0);
529
530 r = sd_event_add_signal(s->events, &s->sigterm_event, SIGTERM, NULL, s);
531 if (r < 0)
532 return r;
533
534 r = sd_event_add_signal(s->events, &s->sigint_event, SIGINT, NULL, s);
535 if (r < 0)
536 return r;
537
538 return 0;
539}
540
541static int setup_raw_socket(RemoteServer *s, const char *address) {
542 int fd;
543
544 fd = make_socket_fd(LOG_INFO, address, SOCK_STREAM, SOCK_CLOEXEC);
545 if (fd < 0)
546 return fd;
547
548 return journal_remote_add_raw_socket(s, fd);
549}
550
551static int create_remoteserver(
552 RemoteServer *s,
553 const char* key,
554 const char* cert,
555 const char* trust) {
556
557 int r, n, fd;
558 char **file;
559
560 r = journal_remote_server_init(s, arg_output, arg_split_mode, arg_compress, arg_seal);
561 if (r < 0)
562 return r;
563
83a43339
LP
564 r = setup_signals(s);
565 if (r < 0)
566 return log_error_errno(r, "Failed to set up signals: %m");
c064d8db
ZJS
567
568 n = sd_listen_fds(true);
569 if (n < 0)
570 return log_error_errno(n, "Failed to read listening file descriptors from environment: %m");
571 else
572 log_debug("Received %d descriptors", n);
573
baaa35ad
ZJS
574 if (MAX(http_socket, https_socket) >= SD_LISTEN_FDS_START + n)
575 return log_error_errno(SYNTHETIC_ERRNO(EBADFD),
576 "Received fewer sockets than expected");
c064d8db
ZJS
577
578 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
579 if (sd_is_socket(fd, AF_UNSPEC, 0, true)) {
580 log_debug("Received a listening socket (fd:%d)", fd);
581
582 if (fd == http_socket)
583 r = setup_microhttpd_server(s, fd, NULL, NULL, NULL);
584 else if (fd == https_socket)
585 r = setup_microhttpd_server(s, fd, key, cert, trust);
586 else
587 r = journal_remote_add_raw_socket(s, fd);
588 } else if (sd_is_socket(fd, AF_UNSPEC, 0, false)) {
589 char *hostname;
590
591 r = getpeername_pretty(fd, false, &hostname);
592 if (r < 0)
593 return log_error_errno(r, "Failed to retrieve remote name: %m");
594
595 log_debug("Received a connection socket (fd:%d) from %s", fd, hostname);
596
597 r = journal_remote_add_source(s, fd, hostname, true);
baaa35ad
ZJS
598 } else
599 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
600 "Unknown socket passed on fd:%d", fd);
c064d8db
ZJS
601
602 if (r < 0)
baaa35ad 603 return log_error_errno(r, "Failed to register socket (fd:%d): %m", fd);
c064d8db
ZJS
604 }
605
606 if (arg_getter) {
607 log_info("Spawning getter %s...", arg_getter);
608 fd = spawn_getter(arg_getter);
609 if (fd < 0)
610 return fd;
611
612 r = journal_remote_add_source(s, fd, (char*) arg_output, false);
613 if (r < 0)
614 return r;
615 }
616
617 if (arg_url) {
618 const char *url;
15d121b0 619 char *hostname;
c064d8db
ZJS
620
621 if (!strstr(arg_url, "/entries")) {
622 if (endswith(arg_url, "/"))
623 url = strjoina(arg_url, "entries");
624 else
625 url = strjoina(arg_url, "/entries");
15d121b0 626 } else
c064d8db
ZJS
627 url = strdupa(arg_url);
628
629 log_info("Spawning curl %s...", url);
630 fd = spawn_curl(url);
631 if (fd < 0)
632 return fd;
633
49fe5c09
LP
634 hostname = STARTSWITH_SET(arg_url, "https://", "http://");
635 if (!hostname)
636 hostname = arg_url;
c064d8db 637
15d121b0 638 hostname = strndupa(hostname, strcspn(hostname, "/:"));
c064d8db
ZJS
639
640 r = journal_remote_add_source(s, fd, hostname, false);
641 if (r < 0)
642 return r;
643 }
644
645 if (arg_listen_raw) {
646 log_debug("Listening on a socket...");
647 r = setup_raw_socket(s, arg_listen_raw);
648 if (r < 0)
649 return r;
650 }
651
652 if (arg_listen_http) {
653 r = setup_microhttpd_socket(s, arg_listen_http, NULL, NULL, NULL);
654 if (r < 0)
655 return r;
656 }
657
658 if (arg_listen_https) {
659 r = setup_microhttpd_socket(s, arg_listen_https, key, cert, trust);
660 if (r < 0)
661 return r;
662 }
663
664 STRV_FOREACH(file, arg_files) {
665 const char *output_name;
666
667 if (streq(*file, "-")) {
668 log_debug("Using standard input as source.");
669
670 fd = STDIN_FILENO;
671 output_name = "stdin";
672 } else {
673 log_debug("Reading file %s...", *file);
674
675 fd = open(*file, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
676 if (fd < 0)
677 return log_error_errno(errno, "Failed to open %s: %m", *file);
678 output_name = *file;
679 }
680
681 r = journal_remote_add_source(s, fd, (char*) output_name, false);
682 if (r < 0)
683 return r;
684 }
685
baaa35ad
ZJS
686 if (s->active == 0)
687 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
688 "Zero sources specified");
c064d8db
ZJS
689
690 if (arg_split_mode == JOURNAL_WRITE_SPLIT_NONE) {
691 /* In this case we know what the writer will be
692 called, so we can create it and verify that we can
693 create output as expected. */
694 r = journal_remote_get_writer(s, NULL, &s->_single_writer);
695 if (r < 0)
696 return r;
697 }
698
699 return 0;
700}
701
702static int negative_fd(const char *spec) {
703 /* Return a non-positive number as its inverse, -EINVAL otherwise. */
704
705 int fd, r;
706
707 r = safe_atoi(spec, &fd);
708 if (r < 0)
709 return r;
710
711 if (fd > 0)
712 return -EINVAL;
713 else
714 return -fd;
715}
716
717static int parse_config(void) {
718 const ConfigTableItem items[] = {
719 { "Remote", "Seal", config_parse_bool, 0, &arg_seal },
720 { "Remote", "SplitMode", config_parse_write_split_mode, 0, &arg_split_mode },
721 { "Remote", "ServerKeyFile", config_parse_path, 0, &arg_key },
722 { "Remote", "ServerCertificateFile", config_parse_path, 0, &arg_cert },
723 { "Remote", "TrustedCertificateFile", config_parse_path, 0, &arg_trust },
37ec0fdd
LP
724 {}
725 };
c064d8db
ZJS
726
727 return config_parse_many_nulstr(PKGSYSCONFDIR "/journal-remote.conf",
728 CONF_PATHS_NULSTR("systemd/journal-remote.conf.d"),
729 "Remote\0", config_item_table_lookup, items,
730 CONFIG_PARSE_WARN, NULL);
731}
732
37ec0fdd
LP
733static int help(void) {
734 _cleanup_free_ char *link = NULL;
735 int r;
736
737 r = terminal_urlify_man("systemd-journal-remote.service", "8", &link);
738 if (r < 0)
739 return log_oom();
740
c064d8db
ZJS
741 printf("%s [OPTIONS...] {FILE|-}...\n\n"
742 "Write external journal events to journal file(s).\n\n"
743 " -h --help Show this help\n"
744 " --version Show package version\n"
745 " --url=URL Read events from systemd-journal-gatewayd at URL\n"
746 " --getter=COMMAND Read events from the output of COMMAND\n"
747 " --listen-raw=ADDR Listen for connections at ADDR\n"
748 " --listen-http=ADDR Listen for HTTP connections at ADDR\n"
749 " --listen-https=ADDR Listen for HTTPS connections at ADDR\n"
750 " -o --output=FILE|DIR Write output to FILE or DIR/external-*.journal\n"
751 " --compress[=BOOL] XZ-compress the output journal (default: yes)\n"
752 " --seal[=BOOL] Use event sealing (default: no)\n"
753 " --key=FILENAME SSL key in PEM format (default:\n"
754 " \"" PRIV_KEY_FILE "\")\n"
755 " --cert=FILENAME SSL certificate in PEM format (default:\n"
756 " \"" CERT_FILE "\")\n"
757 " --trust=FILENAME|all SSL CA certificate or disable checking (default:\n"
758 " \"" TRUST_FILE "\")\n"
759 " --gnutls-log=CATEGORY...\n"
760 " Specify a list of gnutls logging categories\n"
761 " --split-mode=none|host How many output files to create\n"
37ec0fdd
LP
762 "\nNote: file descriptors from sd_listen_fds() will be consumed, too.\n"
763 "\nSee the %s for details.\n"
764 , program_invocation_short_name
765 , link
766 );
767
768 return 0;
c064d8db
ZJS
769}
770
771static int parse_argv(int argc, char *argv[]) {
772 enum {
773 ARG_VERSION = 0x100,
774 ARG_URL,
775 ARG_LISTEN_RAW,
776 ARG_LISTEN_HTTP,
777 ARG_LISTEN_HTTPS,
778 ARG_GETTER,
779 ARG_SPLIT_MODE,
780 ARG_COMPRESS,
781 ARG_SEAL,
782 ARG_KEY,
783 ARG_CERT,
784 ARG_TRUST,
785 ARG_GNUTLS_LOG,
786 };
787
788 static const struct option options[] = {
789 { "help", no_argument, NULL, 'h' },
790 { "version", no_argument, NULL, ARG_VERSION },
791 { "url", required_argument, NULL, ARG_URL },
792 { "getter", required_argument, NULL, ARG_GETTER },
793 { "listen-raw", required_argument, NULL, ARG_LISTEN_RAW },
794 { "listen-http", required_argument, NULL, ARG_LISTEN_HTTP },
795 { "listen-https", required_argument, NULL, ARG_LISTEN_HTTPS },
796 { "output", required_argument, NULL, 'o' },
797 { "split-mode", required_argument, NULL, ARG_SPLIT_MODE },
798 { "compress", optional_argument, NULL, ARG_COMPRESS },
799 { "seal", optional_argument, NULL, ARG_SEAL },
800 { "key", required_argument, NULL, ARG_KEY },
801 { "cert", required_argument, NULL, ARG_CERT },
802 { "trust", required_argument, NULL, ARG_TRUST },
803 { "gnutls-log", required_argument, NULL, ARG_GNUTLS_LOG },
804 {}
805 };
806
807 int c, r;
808 bool type_a, type_b;
809
810 assert(argc >= 0);
811 assert(argv);
812
813 while ((c = getopt_long(argc, argv, "ho:", options, NULL)) >= 0)
814 switch(c) {
37ec0fdd 815
c064d8db 816 case 'h':
37ec0fdd 817 return help();
c064d8db
ZJS
818
819 case ARG_VERSION:
820 return version();
821
822 case ARG_URL:
baaa35ad
ZJS
823 if (arg_url)
824 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
825 "cannot currently set more than one --url");
c064d8db
ZJS
826
827 arg_url = optarg;
828 break;
829
830 case ARG_GETTER:
baaa35ad
ZJS
831 if (arg_getter)
832 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
833 "cannot currently use --getter more than once");
c064d8db
ZJS
834
835 arg_getter = optarg;
836 break;
837
838 case ARG_LISTEN_RAW:
baaa35ad
ZJS
839 if (arg_listen_raw)
840 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
841 "cannot currently use --listen-raw more than once");
c064d8db
ZJS
842
843 arg_listen_raw = optarg;
844 break;
845
846 case ARG_LISTEN_HTTP:
baaa35ad
ZJS
847 if (arg_listen_http || http_socket >= 0)
848 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
849 "cannot currently use --listen-http more than once");
c064d8db
ZJS
850
851 r = negative_fd(optarg);
852 if (r >= 0)
853 http_socket = r;
854 else
855 arg_listen_http = optarg;
856 break;
857
858 case ARG_LISTEN_HTTPS:
baaa35ad
ZJS
859 if (arg_listen_https || https_socket >= 0)
860 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
861 "cannot currently use --listen-https more than once");
c064d8db
ZJS
862
863 r = negative_fd(optarg);
864 if (r >= 0)
865 https_socket = r;
866 else
867 arg_listen_https = optarg;
868
869 break;
870
871 case ARG_KEY:
baaa35ad
ZJS
872 if (arg_key)
873 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
874 "Key file specified twice");
c064d8db
ZJS
875
876 arg_key = strdup(optarg);
877 if (!arg_key)
878 return log_oom();
879
880 break;
881
882 case ARG_CERT:
baaa35ad
ZJS
883 if (arg_cert)
884 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
885 "Certificate file specified twice");
c064d8db
ZJS
886
887 arg_cert = strdup(optarg);
888 if (!arg_cert)
889 return log_oom();
890
891 break;
892
893 case ARG_TRUST:
baaa35ad
ZJS
894 if (arg_trust || arg_trust_all)
895 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
896 "Confusing trusted CA configuration");
c064d8db
ZJS
897
898 if (streq(optarg, "all"))
899 arg_trust_all = true;
900 else {
901#if HAVE_GNUTLS
902 arg_trust = strdup(optarg);
903 if (!arg_trust)
904 return log_oom();
905#else
baaa35ad
ZJS
906 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
907 "Option --trust is not available.");
c064d8db
ZJS
908#endif
909 }
910
911 break;
912
913 case 'o':
baaa35ad
ZJS
914 if (arg_output)
915 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
916 "cannot use --output/-o more than once");
c064d8db
ZJS
917
918 arg_output = optarg;
919 break;
920
921 case ARG_SPLIT_MODE:
922 arg_split_mode = journal_write_split_mode_from_string(optarg);
baaa35ad
ZJS
923 if (arg_split_mode == _JOURNAL_WRITE_SPLIT_INVALID)
924 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
925 "Invalid split mode: %s", optarg);
c064d8db
ZJS
926 break;
927
928 case ARG_COMPRESS:
929 if (optarg) {
930 r = parse_boolean(optarg);
baaa35ad
ZJS
931 if (r < 0)
932 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
933 "Failed to parse --compress= parameter.");
c064d8db
ZJS
934
935 arg_compress = !!r;
936 } else
937 arg_compress = true;
938
939 break;
940
941 case ARG_SEAL:
942 if (optarg) {
943 r = parse_boolean(optarg);
baaa35ad
ZJS
944 if (r < 0)
945 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
946 "Failed to parse --seal= parameter.");
c064d8db
ZJS
947
948 arg_seal = !!r;
949 } else
950 arg_seal = true;
951
952 break;
953
954 case ARG_GNUTLS_LOG: {
955#if HAVE_GNUTLS
956 const char* p = optarg;
957 for (;;) {
958 _cleanup_free_ char *word = NULL;
959
960 r = extract_first_word(&p, &word, ",", 0);
961 if (r < 0)
962 return log_error_errno(r, "Failed to parse --gnutls-log= argument: %m");
c064d8db
ZJS
963 if (r == 0)
964 break;
965
966 if (strv_push(&arg_gnutls_log, word) < 0)
967 return log_oom();
968
969 word = NULL;
970 }
971 break;
972#else
baaa35ad
ZJS
973 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
974 "Option --gnutls-log is not available.");
c064d8db
ZJS
975#endif
976 }
977
978 case '?':
979 return -EINVAL;
980
981 default:
982 assert_not_reached("Unknown option code.");
983 }
984
985 if (optind < argc)
986 arg_files = argv + optind;
987
988 type_a = arg_getter || !strv_isempty(arg_files);
989 type_b = arg_url
990 || arg_listen_raw
991 || arg_listen_http || arg_listen_https
992 || sd_listen_fds(false) > 0;
baaa35ad
ZJS
993 if (type_a && type_b)
994 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
995 "Cannot use file input or --getter with "
996 "--arg-listen-... or socket activation.");
c064d8db 997 if (type_a) {
baaa35ad
ZJS
998 if (!arg_output)
999 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1000 "Option --output must be specified with file input or --getter.");
c064d8db 1001
baaa35ad
ZJS
1002 if (!IN_SET(arg_split_mode, JOURNAL_WRITE_SPLIT_NONE, _JOURNAL_WRITE_SPLIT_INVALID))
1003 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1004 "For active sources, only --split-mode=none is allowed.");
c064d8db
ZJS
1005
1006 arg_split_mode = JOURNAL_WRITE_SPLIT_NONE;
1007 }
1008
1009 if (arg_split_mode == _JOURNAL_WRITE_SPLIT_INVALID)
1010 arg_split_mode = JOURNAL_WRITE_SPLIT_HOST;
1011
1012 if (arg_split_mode == JOURNAL_WRITE_SPLIT_NONE && arg_output) {
baaa35ad
ZJS
1013 if (is_dir(arg_output, true) > 0)
1014 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1015 "For SplitMode=none, output must be a file.");
1016 if (!endswith(arg_output, ".journal"))
1017 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1018 "For SplitMode=none, output file name must end with .journal.");
c064d8db
ZJS
1019 }
1020
1021 if (arg_split_mode == JOURNAL_WRITE_SPLIT_HOST
baaa35ad
ZJS
1022 && arg_output && is_dir(arg_output, true) <= 0)
1023 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1024 "For SplitMode=host, output must be a directory.");
c064d8db
ZJS
1025
1026 log_debug("Full config: SplitMode=%s Key=%s Cert=%s Trust=%s",
1027 journal_write_split_mode_to_string(arg_split_mode),
1028 strna(arg_key),
1029 strna(arg_cert),
1030 strna(arg_trust));
1031
1032 return 1 /* work to do */;
1033}
1034
1035static int load_certificates(char **key, char **cert, char **trust) {
1036 int r;
1037
1038 r = read_full_file(arg_key ?: PRIV_KEY_FILE, key, NULL);
1039 if (r < 0)
1040 return log_error_errno(r, "Failed to read key from file '%s': %m",
1041 arg_key ?: PRIV_KEY_FILE);
1042
1043 r = read_full_file(arg_cert ?: CERT_FILE, cert, NULL);
1044 if (r < 0)
1045 return log_error_errno(r, "Failed to read certificate from file '%s': %m",
1046 arg_cert ?: CERT_FILE);
1047
1048 if (arg_trust_all)
1049 log_info("Certificate checking disabled.");
1050 else {
1051 r = read_full_file(arg_trust ?: TRUST_FILE, trust, NULL);
1052 if (r < 0)
1053 return log_error_errno(r, "Failed to read CA certificate file '%s': %m",
1054 arg_trust ?: TRUST_FILE);
1055 }
1056
baaa35ad
ZJS
1057 if ((arg_listen_raw || arg_listen_http) && *trust)
1058 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1059 "Option --trust makes all non-HTTPS connections untrusted.");
c064d8db
ZJS
1060
1061 return 0;
1062}
1063
1064int main(int argc, char **argv) {
1065 RemoteServer s = {};
1066 int r;
1067 _cleanup_free_ char *key = NULL, *cert = NULL, *trust = NULL;
1068
1069 log_show_color(true);
1070 log_parse_environment();
1071
1abaf488
LP
1072 /* The journal merging logic potentially needs a lot of fds. */
1073 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
1074
c064d8db
ZJS
1075 r = parse_config();
1076 if (r < 0)
1077 return EXIT_FAILURE;
1078
1079 r = parse_argv(argc, argv);
1080 if (r <= 0)
1081 return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1082
1083 if (arg_listen_http || arg_listen_https) {
1084 r = setup_gnutls_logger(arg_gnutls_log);
1085 if (r < 0)
1086 return EXIT_FAILURE;
1087 }
1088
d7ef030b 1089 if (arg_listen_https || https_socket >= 0) {
c064d8db
ZJS
1090 if (load_certificates(&key, &cert, &trust) < 0)
1091 return EXIT_FAILURE;
d7ef030b
MG
1092 s.check_trust = !arg_trust_all;
1093 }
c064d8db
ZJS
1094
1095 if (create_remoteserver(&s, key, cert, trust) < 0)
1096 return EXIT_FAILURE;
1097
1098 r = sd_event_set_watchdog(s.events, true);
1099 if (r < 0)
1100 log_error_errno(r, "Failed to enable watchdog: %m");
1101 else
1102 log_debug("Watchdog is %sd.", enable_disable(r > 0));
1103
1104 log_debug("%s running as pid "PID_FMT,
1105 program_invocation_short_name, getpid_cached());
1106 sd_notify(false,
1107 "READY=1\n"
1108 "STATUS=Processing requests...");
1109
1110 while (s.active) {
1111 r = sd_event_get_state(s.events);
1112 if (r < 0)
1113 break;
1114 if (r == SD_EVENT_FINISHED)
1115 break;
1116
1117 r = sd_event_run(s.events, -1);
1118 if (r < 0) {
1119 log_error_errno(r, "Failed to run event loop: %m");
1120 break;
1121 }
1122 }
1123
1124 sd_notifyf(false,
1125 "STOPPING=1\n"
1126 "STATUS=Shutting down after writing %" PRIu64 " entries...", s.event_count);
1127 log_info("Finishing after writing %" PRIu64 " entries", s.event_count);
1128
1129 journal_remote_server_destroy(&s);
1130
1131 free(arg_key);
1132 free(arg_cert);
1133 free(arg_trust);
1134
1135 return r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1136}