]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/journal-remote/journal-remote.c
Merge pull request #7096 from keszybz/logind-session-killing
[thirdparty/systemd.git] / src / journal-remote / journal-remote.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2012 Zbigniew Jędrzejewski-Szmek
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <getopt.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/prctl.h>
27 #include <sys/socket.h>
28 #include <unistd.h>
29 #include <stdint.h>
30
31 #include "sd-daemon.h"
32
33 #include "alloc-util.h"
34 #include "conf-parser.h"
35 #include "def.h"
36 #include "escape.h"
37 #include "fd-util.h"
38 #include "fileio.h"
39 #include "journal-file.h"
40 #include "journal-remote-write.h"
41 #include "journal-remote.h"
42 #include "journald-native.h"
43 #include "macro.h"
44 #include "parse-util.h"
45 #include "signal-util.h"
46 #include "socket-util.h"
47 #include "stat-util.h"
48 #include "stdio-util.h"
49 #include "string-table.h"
50 #include "string-util.h"
51 #include "strv.h"
52
53 #define REMOTE_JOURNAL_PATH "/var/log/journal/remote"
54
55 #define PRIV_KEY_FILE CERTIFICATE_ROOT "/private/journal-remote.pem"
56 #define CERT_FILE CERTIFICATE_ROOT "/certs/journal-remote.pem"
57 #define TRUST_FILE CERTIFICATE_ROOT "/ca/trusted.pem"
58
59 static char* arg_url = NULL;
60 static char* arg_getter = NULL;
61 static char* arg_listen_raw = NULL;
62 static char* arg_listen_http = NULL;
63 static char* arg_listen_https = NULL;
64 static char** arg_files = NULL;
65 static int arg_compress = true;
66 static int arg_seal = false;
67 static int http_socket = -1, https_socket = -1;
68 static char** arg_gnutls_log = NULL;
69
70 static JournalWriteSplitMode arg_split_mode = _JOURNAL_WRITE_SPLIT_INVALID;
71 static char* arg_output = NULL;
72
73 static char *arg_key = NULL;
74 static char *arg_cert = NULL;
75 static char *arg_trust = NULL;
76 static bool arg_trust_all = false;
77
78 /**********************************************************************
79 **********************************************************************
80 **********************************************************************/
81
82 static int spawn_child(const char* child, char** argv) {
83 int fd[2];
84 pid_t parent_pid, child_pid;
85 int r;
86
87 if (pipe(fd) < 0)
88 return log_error_errno(errno, "Failed to create pager pipe: %m");
89
90 parent_pid = getpid_cached();
91
92 child_pid = fork();
93 if (child_pid < 0) {
94 r = log_error_errno(errno, "Failed to fork: %m");
95 safe_close_pair(fd);
96 return r;
97 }
98
99 /* In the child */
100 if (child_pid == 0) {
101
102 (void) reset_all_signal_handlers();
103 (void) reset_signal_mask();
104
105 r = dup2(fd[1], STDOUT_FILENO);
106 if (r < 0) {
107 log_error_errno(errno, "Failed to dup pipe to stdout: %m");
108 _exit(EXIT_FAILURE);
109 }
110
111 safe_close_pair(fd);
112
113 /* Make sure the child goes away when the parent dies */
114 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
115 _exit(EXIT_FAILURE);
116
117 /* Check whether our parent died before we were able
118 * to set the death signal */
119 if (getppid() != parent_pid)
120 _exit(EXIT_SUCCESS);
121
122 execvp(child, argv);
123 log_error_errno(errno, "Failed to exec child %s: %m", child);
124 _exit(EXIT_FAILURE);
125 }
126
127 r = close(fd[1]);
128 if (r < 0)
129 log_warning_errno(errno, "Failed to close write end of pipe: %m");
130
131 r = fd_nonblock(fd[0], true);
132 if (r < 0)
133 log_warning_errno(errno, "Failed to set child pipe to non-blocking: %m");
134
135 return fd[0];
136 }
137
138 static int spawn_curl(const char* url) {
139 char **argv = STRV_MAKE("curl",
140 "-HAccept: application/vnd.fdo.journal",
141 "--silent",
142 "--show-error",
143 url);
144 int r;
145
146 r = spawn_child("curl", argv);
147 if (r < 0)
148 log_error_errno(r, "Failed to spawn curl: %m");
149 return r;
150 }
151
152 static int spawn_getter(const char *getter) {
153 int r;
154 _cleanup_strv_free_ char **words = NULL;
155
156 assert(getter);
157 r = strv_split_extract(&words, getter, WHITESPACE, EXTRACT_QUOTES);
158 if (r < 0)
159 return log_error_errno(r, "Failed to split getter option: %m");
160
161 r = spawn_child(words[0], words);
162 if (r < 0)
163 log_error_errno(r, "Failed to spawn getter %s: %m", getter);
164
165 return r;
166 }
167
168 #define filename_escape(s) xescape((s), "/ ")
169
170 static int open_output(Writer *w, const char* host) {
171 _cleanup_free_ char *_output = NULL;
172 const char *output;
173 int r;
174
175 switch (arg_split_mode) {
176 case JOURNAL_WRITE_SPLIT_NONE:
177 output = arg_output ?: REMOTE_JOURNAL_PATH "/remote.journal";
178 break;
179
180 case JOURNAL_WRITE_SPLIT_HOST: {
181 _cleanup_free_ char *name;
182
183 assert(host);
184
185 name = filename_escape(host);
186 if (!name)
187 return log_oom();
188
189 r = asprintf(&_output, "%s/remote-%s.journal",
190 arg_output ?: REMOTE_JOURNAL_PATH,
191 name);
192 if (r < 0)
193 return log_oom();
194
195 output = _output;
196 break;
197 }
198
199 default:
200 assert_not_reached("what?");
201 }
202
203 r = journal_file_open_reliably(output,
204 O_RDWR|O_CREAT, 0640,
205 arg_compress, arg_seal,
206 &w->metrics,
207 w->mmap, NULL,
208 NULL, &w->journal);
209 if (r < 0)
210 log_error_errno(r, "Failed to open output journal %s: %m",
211 output);
212 else
213 log_debug("Opened output file %s", w->journal->path);
214 return r;
215 }
216
217 /**********************************************************************
218 **********************************************************************
219 **********************************************************************/
220
221 static int init_writer_hashmap(RemoteServer *s) {
222 static const struct hash_ops *hash_ops[] = {
223 [JOURNAL_WRITE_SPLIT_NONE] = NULL,
224 [JOURNAL_WRITE_SPLIT_HOST] = &string_hash_ops,
225 };
226
227 assert(arg_split_mode >= 0 && arg_split_mode < (int) ELEMENTSOF(hash_ops));
228
229 s->writers = hashmap_new(hash_ops[arg_split_mode]);
230 if (!s->writers)
231 return log_oom();
232
233 return 0;
234 }
235
236 static int get_writer(RemoteServer *s, const char *host,
237 Writer **writer) {
238 const void *key;
239 _cleanup_writer_unref_ Writer *w = NULL;
240 int r;
241
242 switch(arg_split_mode) {
243 case JOURNAL_WRITE_SPLIT_NONE:
244 key = "one and only";
245 break;
246
247 case JOURNAL_WRITE_SPLIT_HOST:
248 assert(host);
249 key = host;
250 break;
251
252 default:
253 assert_not_reached("what split mode?");
254 }
255
256 w = hashmap_get(s->writers, key);
257 if (w)
258 writer_ref(w);
259 else {
260 w = writer_new(s);
261 if (!w)
262 return log_oom();
263
264 if (arg_split_mode == JOURNAL_WRITE_SPLIT_HOST) {
265 w->hashmap_key = strdup(key);
266 if (!w->hashmap_key)
267 return log_oom();
268 }
269
270 r = open_output(w, host);
271 if (r < 0)
272 return r;
273
274 r = hashmap_put(s->writers, w->hashmap_key ?: key, w);
275 if (r < 0)
276 return r;
277 }
278
279 *writer = w;
280 w = NULL;
281 return 0;
282 }
283
284 /**********************************************************************
285 **********************************************************************
286 **********************************************************************/
287
288 /* This should go away as soon as µhttpd allows state to be passed around. */
289 static RemoteServer *server;
290
291 static int dispatch_raw_source_event(sd_event_source *event,
292 int fd,
293 uint32_t revents,
294 void *userdata);
295 static int dispatch_raw_source_until_block(sd_event_source *event,
296 void *userdata);
297 static int dispatch_blocking_source_event(sd_event_source *event,
298 void *userdata);
299 static int dispatch_raw_connection_event(sd_event_source *event,
300 int fd,
301 uint32_t revents,
302 void *userdata);
303 static int null_timer_event_handler(sd_event_source *s,
304 uint64_t usec,
305 void *userdata);
306 static int dispatch_http_event(sd_event_source *event,
307 int fd,
308 uint32_t revents,
309 void *userdata);
310
311 static int get_source_for_fd(RemoteServer *s,
312 int fd, char *name, RemoteSource **source) {
313 Writer *writer;
314 int r;
315
316 /* This takes ownership of name, but only on success. */
317
318 assert(fd >= 0);
319 assert(source);
320
321 if (!GREEDY_REALLOC0(s->sources, s->sources_size, fd + 1))
322 return log_oom();
323
324 r = get_writer(s, name, &writer);
325 if (r < 0)
326 return log_warning_errno(r, "Failed to get writer for source %s: %m",
327 name);
328
329 if (s->sources[fd] == NULL) {
330 s->sources[fd] = source_new(fd, false, name, writer);
331 if (!s->sources[fd]) {
332 writer_unref(writer);
333 return log_oom();
334 }
335
336 s->active++;
337 }
338
339 *source = s->sources[fd];
340 return 0;
341 }
342
343 static int remove_source(RemoteServer *s, int fd) {
344 RemoteSource *source;
345
346 assert(s);
347 assert(fd >= 0 && fd < (ssize_t) s->sources_size);
348
349 source = s->sources[fd];
350 if (source) {
351 /* this closes fd too */
352 source_free(source);
353 s->sources[fd] = NULL;
354 s->active--;
355 }
356
357 return 0;
358 }
359
360 static int add_source(RemoteServer *s, int fd, char* name, bool own_name) {
361
362 RemoteSource *source = NULL;
363 int r;
364
365 /* This takes ownership of name, even on failure, if own_name is true. */
366
367 assert(s);
368 assert(fd >= 0);
369 assert(name);
370
371 if (!own_name) {
372 name = strdup(name);
373 if (!name)
374 return log_oom();
375 }
376
377 r = get_source_for_fd(s, fd, name, &source);
378 if (r < 0) {
379 log_error_errno(r, "Failed to create source for fd:%d (%s): %m",
380 fd, name);
381 free(name);
382 return r;
383 }
384
385 r = sd_event_add_io(s->events, &source->event,
386 fd, EPOLLIN|EPOLLRDHUP|EPOLLPRI,
387 dispatch_raw_source_event, source);
388 if (r == 0) {
389 /* Add additional source for buffer processing. It will be
390 * enabled later. */
391 r = sd_event_add_defer(s->events, &source->buffer_event,
392 dispatch_raw_source_until_block, source);
393 if (r == 0)
394 sd_event_source_set_enabled(source->buffer_event, SD_EVENT_OFF);
395 } else if (r == -EPERM) {
396 log_debug("Falling back to sd_event_add_defer for fd:%d (%s)", fd, name);
397 r = sd_event_add_defer(s->events, &source->event,
398 dispatch_blocking_source_event, source);
399 if (r == 0)
400 sd_event_source_set_enabled(source->event, SD_EVENT_ON);
401 }
402 if (r < 0) {
403 log_error_errno(r, "Failed to register event source for fd:%d: %m",
404 fd);
405 goto error;
406 }
407
408 r = sd_event_source_set_description(source->event, name);
409 if (r < 0) {
410 log_error_errno(r, "Failed to set source name for fd:%d: %m", fd);
411 goto error;
412 }
413
414 return 1; /* work to do */
415
416 error:
417 remove_source(s, fd);
418 return r;
419 }
420
421 static int add_raw_socket(RemoteServer *s, int fd) {
422 int r;
423 _cleanup_close_ int fd_ = fd;
424 char name[sizeof("raw-socket-")-1 + DECIMAL_STR_MAX(int) + 1];
425
426 assert(fd >= 0);
427
428 r = sd_event_add_io(s->events, &s->listen_event,
429 fd, EPOLLIN,
430 dispatch_raw_connection_event, s);
431 if (r < 0)
432 return r;
433
434 xsprintf(name, "raw-socket-%d", fd);
435
436 r = sd_event_source_set_description(s->listen_event, name);
437 if (r < 0)
438 return r;
439
440 fd_ = -1;
441 s->active++;
442 return 0;
443 }
444
445 static int setup_raw_socket(RemoteServer *s, const char *address) {
446 int fd;
447
448 fd = make_socket_fd(LOG_INFO, address, SOCK_STREAM, SOCK_CLOEXEC);
449 if (fd < 0)
450 return fd;
451
452 return add_raw_socket(s, fd);
453 }
454
455 /**********************************************************************
456 **********************************************************************
457 **********************************************************************/
458
459 static int request_meta(void **connection_cls, int fd, char *hostname) {
460 RemoteSource *source;
461 Writer *writer;
462 int r;
463
464 assert(connection_cls);
465 if (*connection_cls)
466 return 0;
467
468 r = get_writer(server, hostname, &writer);
469 if (r < 0)
470 return log_warning_errno(r, "Failed to get writer for source %s: %m",
471 hostname);
472
473 source = source_new(fd, true, hostname, writer);
474 if (!source) {
475 writer_unref(writer);
476 return log_oom();
477 }
478
479 log_debug("Added RemoteSource as connection metadata %p", source);
480
481 *connection_cls = source;
482 return 0;
483 }
484
485 static void request_meta_free(void *cls,
486 struct MHD_Connection *connection,
487 void **connection_cls,
488 enum MHD_RequestTerminationCode toe) {
489 RemoteSource *s;
490
491 assert(connection_cls);
492 s = *connection_cls;
493
494 if (s) {
495 log_debug("Cleaning up connection metadata %p", s);
496 source_free(s);
497 *connection_cls = NULL;
498 }
499 }
500
501 static int process_http_upload(
502 struct MHD_Connection *connection,
503 const char *upload_data,
504 size_t *upload_data_size,
505 RemoteSource *source) {
506
507 bool finished = false;
508 size_t remaining;
509 int r;
510
511 assert(source);
512
513 log_trace("%s: connection %p, %zu bytes",
514 __func__, connection, *upload_data_size);
515
516 if (*upload_data_size) {
517 log_trace("Received %zu bytes", *upload_data_size);
518
519 r = journal_importer_push_data(&source->importer,
520 upload_data, *upload_data_size);
521 if (r < 0)
522 return mhd_respond_oom(connection);
523
524 *upload_data_size = 0;
525 } else
526 finished = true;
527
528 for (;;) {
529 r = process_source(source, arg_compress, arg_seal);
530 if (r == -EAGAIN)
531 break;
532 else if (r < 0) {
533 log_warning("Failed to process data for connection %p", connection);
534 if (r == -E2BIG)
535 return mhd_respondf(connection,
536 r, MHD_HTTP_PAYLOAD_TOO_LARGE,
537 "Entry is too large, maximum is " STRINGIFY(DATA_SIZE_MAX) " bytes.");
538 else
539 return mhd_respondf(connection,
540 r, MHD_HTTP_UNPROCESSABLE_ENTITY,
541 "Processing failed: %m.");
542 }
543 }
544
545 if (!finished)
546 return MHD_YES;
547
548 /* The upload is finished */
549
550 remaining = journal_importer_bytes_remaining(&source->importer);
551 if (remaining > 0) {
552 log_warning("Premature EOF byte. %zu bytes lost.", remaining);
553 return mhd_respondf(connection,
554 0, MHD_HTTP_EXPECTATION_FAILED,
555 "Premature EOF. %zu bytes of trailing data not processed.",
556 remaining);
557 }
558
559 return mhd_respond(connection, MHD_HTTP_ACCEPTED, "OK.");
560 };
561
562 static int request_handler(
563 void *cls,
564 struct MHD_Connection *connection,
565 const char *url,
566 const char *method,
567 const char *version,
568 const char *upload_data,
569 size_t *upload_data_size,
570 void **connection_cls) {
571
572 const char *header;
573 int r, code, fd;
574 _cleanup_free_ char *hostname = NULL;
575
576 assert(connection);
577 assert(connection_cls);
578 assert(url);
579 assert(method);
580
581 log_trace("Handling a connection %s %s %s", method, url, version);
582
583 if (*connection_cls)
584 return process_http_upload(connection,
585 upload_data, upload_data_size,
586 *connection_cls);
587
588 if (!streq(method, "POST"))
589 return mhd_respond(connection, MHD_HTTP_NOT_ACCEPTABLE, "Unsupported method.");
590
591 if (!streq(url, "/upload"))
592 return mhd_respond(connection, MHD_HTTP_NOT_FOUND, "Not found.");
593
594 header = MHD_lookup_connection_value(connection,
595 MHD_HEADER_KIND, "Content-Type");
596 if (!header || !streq(header, "application/vnd.fdo.journal"))
597 return mhd_respond(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE,
598 "Content-Type: application/vnd.fdo.journal is required.");
599
600 {
601 const union MHD_ConnectionInfo *ci;
602
603 ci = MHD_get_connection_info(connection,
604 MHD_CONNECTION_INFO_CONNECTION_FD);
605 if (!ci) {
606 log_error("MHD_get_connection_info failed: cannot get remote fd");
607 return mhd_respond(connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
608 "Cannot check remote address.");
609 }
610
611 fd = ci->connect_fd;
612 assert(fd >= 0);
613 }
614
615 if (server->check_trust) {
616 r = check_permissions(connection, &code, &hostname);
617 if (r < 0)
618 return code;
619 } else {
620 r = getpeername_pretty(fd, false, &hostname);
621 if (r < 0)
622 return mhd_respond(connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
623 "Cannot check remote hostname.");
624 }
625
626 assert(hostname);
627
628 r = request_meta(connection_cls, fd, hostname);
629 if (r == -ENOMEM)
630 return respond_oom(connection);
631 else if (r < 0)
632 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "%m");
633
634 hostname = NULL;
635 return MHD_YES;
636 }
637
638 static int setup_microhttpd_server(RemoteServer *s,
639 int fd,
640 const char *key,
641 const char *cert,
642 const char *trust) {
643 struct MHD_OptionItem opts[] = {
644 { MHD_OPTION_NOTIFY_COMPLETED, (intptr_t) request_meta_free},
645 { MHD_OPTION_EXTERNAL_LOGGER, (intptr_t) microhttpd_logger},
646 { MHD_OPTION_LISTEN_SOCKET, fd},
647 { MHD_OPTION_CONNECTION_MEMORY_LIMIT, 128*1024},
648 { MHD_OPTION_END},
649 { MHD_OPTION_END},
650 { MHD_OPTION_END},
651 { MHD_OPTION_END},
652 { MHD_OPTION_END}};
653 int opts_pos = 4;
654 int flags =
655 MHD_USE_DEBUG |
656 MHD_USE_DUAL_STACK |
657 MHD_USE_EPOLL |
658 MHD_USE_ITC;
659
660 const union MHD_DaemonInfo *info;
661 int r, epoll_fd;
662 MHDDaemonWrapper *d;
663
664 assert(fd >= 0);
665
666 r = fd_nonblock(fd, true);
667 if (r < 0)
668 return log_error_errno(r, "Failed to make fd:%d nonblocking: %m", fd);
669
670 /* MHD_OPTION_STRICT_FOR_CLIENT is introduced in microhttpd 0.9.54,
671 * and MHD_USE_PEDANTIC_CHECKS will be deprecated in future.
672 * If MHD_USE_PEDANTIC_CHECKS is '#define'd, then it is deprecated
673 * and we should use MHD_OPTION_STRICT_FOR_CLIENT. On the other hand,
674 * if MHD_USE_PEDANTIC_CHECKS is not '#define'd, then it is not
675 * deprecated yet and there exists an enum element with the same name.
676 * So we can safely use it. */
677 #ifdef MHD_USE_PEDANTIC_CHECKS
678 opts[opts_pos++] = (struct MHD_OptionItem)
679 {MHD_OPTION_STRICT_FOR_CLIENT, 1};
680 #else
681 flags |= MHD_USE_PEDANTIC_CHECKS;
682 #endif
683
684 if (key) {
685 assert(cert);
686
687 opts[opts_pos++] = (struct MHD_OptionItem)
688 {MHD_OPTION_HTTPS_MEM_KEY, 0, (char*) key};
689 opts[opts_pos++] = (struct MHD_OptionItem)
690 {MHD_OPTION_HTTPS_MEM_CERT, 0, (char*) cert};
691
692 flags |= MHD_USE_TLS;
693
694 if (trust)
695 opts[opts_pos++] = (struct MHD_OptionItem)
696 {MHD_OPTION_HTTPS_MEM_TRUST, 0, (char*) trust};
697 }
698
699 d = new(MHDDaemonWrapper, 1);
700 if (!d)
701 return log_oom();
702
703 d->fd = (uint64_t) fd;
704
705 d->daemon = MHD_start_daemon(flags, 0,
706 NULL, NULL,
707 request_handler, NULL,
708 MHD_OPTION_ARRAY, opts,
709 MHD_OPTION_END);
710 if (!d->daemon) {
711 log_error("Failed to start µhttp daemon");
712 r = -EINVAL;
713 goto error;
714 }
715
716 log_debug("Started MHD %s daemon on fd:%d (wrapper @ %p)",
717 key ? "HTTPS" : "HTTP", fd, d);
718
719
720 info = MHD_get_daemon_info(d->daemon, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
721 if (!info) {
722 log_error("µhttp returned NULL daemon info");
723 r = -EOPNOTSUPP;
724 goto error;
725 }
726
727 epoll_fd = info->listen_fd;
728 if (epoll_fd < 0) {
729 log_error("µhttp epoll fd is invalid");
730 r = -EUCLEAN;
731 goto error;
732 }
733
734 r = sd_event_add_io(s->events, &d->io_event,
735 epoll_fd, EPOLLIN,
736 dispatch_http_event, d);
737 if (r < 0) {
738 log_error_errno(r, "Failed to add event callback: %m");
739 goto error;
740 }
741
742 r = sd_event_source_set_description(d->io_event, "io_event");
743 if (r < 0) {
744 log_error_errno(r, "Failed to set source name: %m");
745 goto error;
746 }
747
748 r = sd_event_add_time(s->events, &d->timer_event,
749 CLOCK_MONOTONIC, UINT64_MAX, 0,
750 null_timer_event_handler, d);
751 if (r < 0) {
752 log_error_errno(r, "Failed to add timer_event: %m");
753 goto error;
754 }
755
756 r = sd_event_source_set_description(d->timer_event, "timer_event");
757 if (r < 0) {
758 log_error_errno(r, "Failed to set source name: %m");
759 goto error;
760 }
761
762 r = hashmap_ensure_allocated(&s->daemons, &uint64_hash_ops);
763 if (r < 0) {
764 log_oom();
765 goto error;
766 }
767
768 r = hashmap_put(s->daemons, &d->fd, d);
769 if (r < 0) {
770 log_error_errno(r, "Failed to add daemon to hashmap: %m");
771 goto error;
772 }
773
774 s->active++;
775 return 0;
776
777 error:
778 MHD_stop_daemon(d->daemon);
779 free(d->daemon);
780 free(d);
781 return r;
782 }
783
784 static int setup_microhttpd_socket(RemoteServer *s,
785 const char *address,
786 const char *key,
787 const char *cert,
788 const char *trust) {
789 int fd;
790
791 fd = make_socket_fd(LOG_DEBUG, address, SOCK_STREAM, SOCK_CLOEXEC);
792 if (fd < 0)
793 return fd;
794
795 return setup_microhttpd_server(s, fd, key, cert, trust);
796 }
797
798 static int null_timer_event_handler(sd_event_source *timer_event,
799 uint64_t usec,
800 void *userdata) {
801 return dispatch_http_event(timer_event, 0, 0, userdata);
802 }
803
804 static int dispatch_http_event(sd_event_source *event,
805 int fd,
806 uint32_t revents,
807 void *userdata) {
808 MHDDaemonWrapper *d = userdata;
809 int r;
810 MHD_UNSIGNED_LONG_LONG timeout = ULONG_LONG_MAX;
811
812 assert(d);
813
814 r = MHD_run(d->daemon);
815 if (r == MHD_NO) {
816 log_error("MHD_run failed!");
817 // XXX: unregister daemon
818 return -EINVAL;
819 }
820 if (MHD_get_timeout(d->daemon, &timeout) == MHD_NO)
821 timeout = ULONG_LONG_MAX;
822
823 r = sd_event_source_set_time(d->timer_event, timeout);
824 if (r < 0) {
825 log_warning_errno(r, "Unable to set event loop timeout: %m, this may result in indefinite blocking!");
826 return 1;
827 }
828
829 r = sd_event_source_set_enabled(d->timer_event, SD_EVENT_ON);
830 if (r < 0)
831 log_warning_errno(r, "Unable to enable timer_event: %m, this may result in indefinite blocking!");
832
833 return 1; /* work to do */
834 }
835
836 /**********************************************************************
837 **********************************************************************
838 **********************************************************************/
839
840 static int setup_signals(RemoteServer *s) {
841 int r;
842
843 assert(s);
844
845 assert_se(sigprocmask_many(SIG_SETMASK, NULL, SIGINT, SIGTERM, -1) >= 0);
846
847 r = sd_event_add_signal(s->events, &s->sigterm_event, SIGTERM, NULL, s);
848 if (r < 0)
849 return r;
850
851 r = sd_event_add_signal(s->events, &s->sigint_event, SIGINT, NULL, s);
852 if (r < 0)
853 return r;
854
855 return 0;
856 }
857
858 static int negative_fd(const char *spec) {
859 /* Return a non-positive number as its inverse, -EINVAL otherwise. */
860
861 int fd, r;
862
863 r = safe_atoi(spec, &fd);
864 if (r < 0)
865 return r;
866
867 if (fd > 0)
868 return -EINVAL;
869 else
870 return -fd;
871 }
872
873 static int remoteserver_init(RemoteServer *s,
874 const char* key,
875 const char* cert,
876 const char* trust) {
877 int r, n, fd;
878 char **file;
879
880 assert(s);
881
882 if ((arg_listen_raw || arg_listen_http) && trust) {
883 log_error("Option --trust makes all non-HTTPS connections untrusted.");
884 return -EINVAL;
885 }
886
887 r = sd_event_default(&s->events);
888 if (r < 0)
889 return log_error_errno(r, "Failed to allocate event loop: %m");
890
891 setup_signals(s);
892
893 assert(server == NULL);
894 server = s;
895
896 r = init_writer_hashmap(s);
897 if (r < 0)
898 return r;
899
900 n = sd_listen_fds(true);
901 if (n < 0)
902 return log_error_errno(n, "Failed to read listening file descriptors from environment: %m");
903 else
904 log_debug("Received %d descriptors", n);
905
906 if (MAX(http_socket, https_socket) >= SD_LISTEN_FDS_START + n) {
907 log_error("Received fewer sockets than expected");
908 return -EBADFD;
909 }
910
911 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
912 if (sd_is_socket(fd, AF_UNSPEC, 0, true)) {
913 log_debug("Received a listening socket (fd:%d)", fd);
914
915 if (fd == http_socket)
916 r = setup_microhttpd_server(s, fd, NULL, NULL, NULL);
917 else if (fd == https_socket)
918 r = setup_microhttpd_server(s, fd, key, cert, trust);
919 else
920 r = add_raw_socket(s, fd);
921 } else if (sd_is_socket(fd, AF_UNSPEC, 0, false)) {
922 char *hostname;
923
924 r = getpeername_pretty(fd, false, &hostname);
925 if (r < 0)
926 return log_error_errno(r, "Failed to retrieve remote name: %m");
927
928 log_debug("Received a connection socket (fd:%d) from %s", fd, hostname);
929
930 r = add_source(s, fd, hostname, true);
931 } else {
932 log_error("Unknown socket passed on fd:%d", fd);
933
934 return -EINVAL;
935 }
936
937 if (r < 0)
938 return log_error_errno(r, "Failed to register socket (fd:%d): %m",
939 fd);
940 }
941
942 if (arg_getter) {
943 log_info("Spawning getter %s...", arg_getter);
944 fd = spawn_getter(arg_getter);
945 if (fd < 0)
946 return fd;
947
948 r = add_source(s, fd, (char*) arg_output, false);
949 if (r < 0)
950 return r;
951 }
952
953 if (arg_url) {
954 const char *url;
955 char *hostname, *p;
956
957 if (!strstr(arg_url, "/entries")) {
958 if (endswith(arg_url, "/"))
959 url = strjoina(arg_url, "entries");
960 else
961 url = strjoina(arg_url, "/entries");
962 }
963 else
964 url = strdupa(arg_url);
965
966 log_info("Spawning curl %s...", url);
967 fd = spawn_curl(url);
968 if (fd < 0)
969 return fd;
970
971 hostname =
972 startswith(arg_url, "https://") ?:
973 startswith(arg_url, "http://") ?:
974 arg_url;
975
976 hostname = strdupa(hostname);
977 if ((p = strchr(hostname, '/')))
978 *p = '\0';
979 if ((p = strchr(hostname, ':')))
980 *p = '\0';
981
982 r = add_source(s, fd, hostname, false);
983 if (r < 0)
984 return r;
985 }
986
987 if (arg_listen_raw) {
988 log_debug("Listening on a socket...");
989 r = setup_raw_socket(s, arg_listen_raw);
990 if (r < 0)
991 return r;
992 }
993
994 if (arg_listen_http) {
995 r = setup_microhttpd_socket(s, arg_listen_http, NULL, NULL, NULL);
996 if (r < 0)
997 return r;
998 }
999
1000 if (arg_listen_https) {
1001 r = setup_microhttpd_socket(s, arg_listen_https, key, cert, trust);
1002 if (r < 0)
1003 return r;
1004 }
1005
1006 STRV_FOREACH(file, arg_files) {
1007 const char *output_name;
1008
1009 if (streq(*file, "-")) {
1010 log_debug("Using standard input as source.");
1011
1012 fd = STDIN_FILENO;
1013 output_name = "stdin";
1014 } else {
1015 log_debug("Reading file %s...", *file);
1016
1017 fd = open(*file, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
1018 if (fd < 0)
1019 return log_error_errno(errno, "Failed to open %s: %m", *file);
1020 output_name = *file;
1021 }
1022
1023 r = add_source(s, fd, (char*) output_name, false);
1024 if (r < 0)
1025 return r;
1026 }
1027
1028 if (s->active == 0) {
1029 log_error("Zero sources specified");
1030 return -EINVAL;
1031 }
1032
1033 if (arg_split_mode == JOURNAL_WRITE_SPLIT_NONE) {
1034 /* In this case we know what the writer will be
1035 called, so we can create it and verify that we can
1036 create output as expected. */
1037 r = get_writer(s, NULL, &s->_single_writer);
1038 if (r < 0)
1039 return r;
1040 }
1041
1042 return 0;
1043 }
1044
1045 static void server_destroy(RemoteServer *s) {
1046 size_t i;
1047 MHDDaemonWrapper *d;
1048
1049 while ((d = hashmap_steal_first(s->daemons))) {
1050 MHD_stop_daemon(d->daemon);
1051 sd_event_source_unref(d->io_event);
1052 sd_event_source_unref(d->timer_event);
1053 free(d);
1054 }
1055
1056 hashmap_free(s->daemons);
1057
1058 assert(s->sources_size == 0 || s->sources);
1059 for (i = 0; i < s->sources_size; i++)
1060 remove_source(s, i);
1061 free(s->sources);
1062
1063 writer_unref(s->_single_writer);
1064 hashmap_free(s->writers);
1065
1066 sd_event_source_unref(s->sigterm_event);
1067 sd_event_source_unref(s->sigint_event);
1068 sd_event_source_unref(s->listen_event);
1069 sd_event_unref(s->events);
1070
1071 /* fds that we're listening on remain open... */
1072 }
1073
1074 /**********************************************************************
1075 **********************************************************************
1076 **********************************************************************/
1077
1078 static int handle_raw_source(sd_event_source *event,
1079 int fd,
1080 uint32_t revents,
1081 RemoteServer *s) {
1082
1083 RemoteSource *source;
1084 int r;
1085
1086 /* Returns 1 if there might be more data pending,
1087 * 0 if data is currently exhausted, negative on error.
1088 */
1089
1090 assert(fd >= 0 && fd < (ssize_t) s->sources_size);
1091 source = s->sources[fd];
1092 assert(source->importer.fd == fd);
1093
1094 r = process_source(source, arg_compress, arg_seal);
1095 if (journal_importer_eof(&source->importer)) {
1096 size_t remaining;
1097
1098 log_debug("EOF reached with source %s (fd=%d)",
1099 source->importer.name, source->importer.fd);
1100
1101 remaining = journal_importer_bytes_remaining(&source->importer);
1102 if (remaining > 0)
1103 log_notice("Premature EOF. %zu bytes lost.", remaining);
1104 remove_source(s, source->importer.fd);
1105 log_debug("%zu active sources remaining", s->active);
1106 return 0;
1107 } else if (r == -E2BIG) {
1108 log_notice_errno(E2BIG, "Entry too big, skipped");
1109 return 1;
1110 } else if (r == -EAGAIN) {
1111 return 0;
1112 } else if (r < 0) {
1113 log_debug_errno(r, "Closing connection: %m");
1114 remove_source(server, fd);
1115 return 0;
1116 } else
1117 return 1;
1118 }
1119
1120 static int dispatch_raw_source_until_block(sd_event_source *event,
1121 void *userdata) {
1122 RemoteSource *source = userdata;
1123 int r;
1124
1125 /* Make sure event stays around even if source is destroyed */
1126 sd_event_source_ref(event);
1127
1128 r = handle_raw_source(event, source->importer.fd, EPOLLIN, server);
1129 if (r != 1)
1130 /* No more data for now */
1131 sd_event_source_set_enabled(event, SD_EVENT_OFF);
1132
1133 sd_event_source_unref(event);
1134
1135 return r;
1136 }
1137
1138 static int dispatch_raw_source_event(sd_event_source *event,
1139 int fd,
1140 uint32_t revents,
1141 void *userdata) {
1142 RemoteSource *source = userdata;
1143 int r;
1144
1145 assert(source->event);
1146 assert(source->buffer_event);
1147
1148 r = handle_raw_source(event, fd, EPOLLIN, server);
1149 if (r == 1)
1150 /* Might have more data. We need to rerun the handler
1151 * until we are sure the buffer is exhausted. */
1152 sd_event_source_set_enabled(source->buffer_event, SD_EVENT_ON);
1153
1154 return r;
1155 }
1156
1157 static int dispatch_blocking_source_event(sd_event_source *event,
1158 void *userdata) {
1159 RemoteSource *source = userdata;
1160
1161 return handle_raw_source(event, source->importer.fd, EPOLLIN, server);
1162 }
1163
1164 static int accept_connection(const char* type, int fd,
1165 SocketAddress *addr, char **hostname) {
1166 int fd2, r;
1167
1168 log_debug("Accepting new %s connection on fd:%d", type, fd);
1169 fd2 = accept4(fd, &addr->sockaddr.sa, &addr->size, SOCK_NONBLOCK|SOCK_CLOEXEC);
1170 if (fd2 < 0)
1171 return log_error_errno(errno, "accept() on fd:%d failed: %m", fd);
1172
1173 switch(socket_address_family(addr)) {
1174 case AF_INET:
1175 case AF_INET6: {
1176 _cleanup_free_ char *a = NULL;
1177 char *b;
1178
1179 r = socket_address_print(addr, &a);
1180 if (r < 0) {
1181 log_error_errno(r, "socket_address_print(): %m");
1182 close(fd2);
1183 return r;
1184 }
1185
1186 r = socknameinfo_pretty(&addr->sockaddr, addr->size, &b);
1187 if (r < 0) {
1188 log_error_errno(r, "Resolving hostname failed: %m");
1189 close(fd2);
1190 return r;
1191 }
1192
1193 log_debug("Accepted %s %s connection from %s",
1194 type,
1195 socket_address_family(addr) == AF_INET ? "IP" : "IPv6",
1196 a);
1197
1198 *hostname = b;
1199
1200 return fd2;
1201 };
1202 default:
1203 log_error("Rejected %s connection with unsupported family %d",
1204 type, socket_address_family(addr));
1205 close(fd2);
1206
1207 return -EINVAL;
1208 }
1209 }
1210
1211 static int dispatch_raw_connection_event(sd_event_source *event,
1212 int fd,
1213 uint32_t revents,
1214 void *userdata) {
1215 RemoteServer *s = userdata;
1216 int fd2;
1217 SocketAddress addr = {
1218 .size = sizeof(union sockaddr_union),
1219 .type = SOCK_STREAM,
1220 };
1221 char *hostname = NULL;
1222
1223 fd2 = accept_connection("raw", fd, &addr, &hostname);
1224 if (fd2 < 0)
1225 return fd2;
1226
1227 return add_source(s, fd2, hostname, true);
1228 }
1229
1230 /**********************************************************************
1231 **********************************************************************
1232 **********************************************************************/
1233
1234 static const char* const journal_write_split_mode_table[_JOURNAL_WRITE_SPLIT_MAX] = {
1235 [JOURNAL_WRITE_SPLIT_NONE] = "none",
1236 [JOURNAL_WRITE_SPLIT_HOST] = "host",
1237 };
1238
1239 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(journal_write_split_mode, JournalWriteSplitMode);
1240 static DEFINE_CONFIG_PARSE_ENUM(config_parse_write_split_mode,
1241 journal_write_split_mode,
1242 JournalWriteSplitMode,
1243 "Failed to parse split mode setting");
1244
1245 static int parse_config(void) {
1246 const ConfigTableItem items[] = {
1247 { "Remote", "Seal", config_parse_bool, 0, &arg_seal },
1248 { "Remote", "SplitMode", config_parse_write_split_mode, 0, &arg_split_mode },
1249 { "Remote", "ServerKeyFile", config_parse_path, 0, &arg_key },
1250 { "Remote", "ServerCertificateFile", config_parse_path, 0, &arg_cert },
1251 { "Remote", "TrustedCertificateFile", config_parse_path, 0, &arg_trust },
1252 {}};
1253
1254 return config_parse_many_nulstr(PKGSYSCONFDIR "/journal-remote.conf",
1255 CONF_PATHS_NULSTR("systemd/journal-remote.conf.d"),
1256 "Remote\0", config_item_table_lookup, items,
1257 false, NULL);
1258 }
1259
1260 static void help(void) {
1261 printf("%s [OPTIONS...] {FILE|-}...\n\n"
1262 "Write external journal events to journal file(s).\n\n"
1263 " -h --help Show this help\n"
1264 " --version Show package version\n"
1265 " --url=URL Read events from systemd-journal-gatewayd at URL\n"
1266 " --getter=COMMAND Read events from the output of COMMAND\n"
1267 " --listen-raw=ADDR Listen for connections at ADDR\n"
1268 " --listen-http=ADDR Listen for HTTP connections at ADDR\n"
1269 " --listen-https=ADDR Listen for HTTPS connections at ADDR\n"
1270 " -o --output=FILE|DIR Write output to FILE or DIR/external-*.journal\n"
1271 " --compress[=BOOL] XZ-compress the output journal (default: yes)\n"
1272 " --seal[=BOOL] Use event sealing (default: no)\n"
1273 " --key=FILENAME SSL key in PEM format (default:\n"
1274 " \"" PRIV_KEY_FILE "\")\n"
1275 " --cert=FILENAME SSL certificate in PEM format (default:\n"
1276 " \"" CERT_FILE "\")\n"
1277 " --trust=FILENAME|all SSL CA certificate or disable checking (default:\n"
1278 " \"" TRUST_FILE "\")\n"
1279 " --gnutls-log=CATEGORY...\n"
1280 " Specify a list of gnutls logging categories\n"
1281 " --split-mode=none|host How many output files to create\n"
1282 "\n"
1283 "Note: file descriptors from sd_listen_fds() will be consumed, too.\n"
1284 , program_invocation_short_name);
1285 }
1286
1287 static int parse_argv(int argc, char *argv[]) {
1288 enum {
1289 ARG_VERSION = 0x100,
1290 ARG_URL,
1291 ARG_LISTEN_RAW,
1292 ARG_LISTEN_HTTP,
1293 ARG_LISTEN_HTTPS,
1294 ARG_GETTER,
1295 ARG_SPLIT_MODE,
1296 ARG_COMPRESS,
1297 ARG_SEAL,
1298 ARG_KEY,
1299 ARG_CERT,
1300 ARG_TRUST,
1301 ARG_GNUTLS_LOG,
1302 };
1303
1304 static const struct option options[] = {
1305 { "help", no_argument, NULL, 'h' },
1306 { "version", no_argument, NULL, ARG_VERSION },
1307 { "url", required_argument, NULL, ARG_URL },
1308 { "getter", required_argument, NULL, ARG_GETTER },
1309 { "listen-raw", required_argument, NULL, ARG_LISTEN_RAW },
1310 { "listen-http", required_argument, NULL, ARG_LISTEN_HTTP },
1311 { "listen-https", required_argument, NULL, ARG_LISTEN_HTTPS },
1312 { "output", required_argument, NULL, 'o' },
1313 { "split-mode", required_argument, NULL, ARG_SPLIT_MODE },
1314 { "compress", optional_argument, NULL, ARG_COMPRESS },
1315 { "seal", optional_argument, NULL, ARG_SEAL },
1316 { "key", required_argument, NULL, ARG_KEY },
1317 { "cert", required_argument, NULL, ARG_CERT },
1318 { "trust", required_argument, NULL, ARG_TRUST },
1319 { "gnutls-log", required_argument, NULL, ARG_GNUTLS_LOG },
1320 {}
1321 };
1322
1323 int c, r;
1324 bool type_a, type_b;
1325
1326 assert(argc >= 0);
1327 assert(argv);
1328
1329 while ((c = getopt_long(argc, argv, "ho:", options, NULL)) >= 0)
1330 switch(c) {
1331 case 'h':
1332 help();
1333 return 0 /* done */;
1334
1335 case ARG_VERSION:
1336 return version();
1337
1338 case ARG_URL:
1339 if (arg_url) {
1340 log_error("cannot currently set more than one --url");
1341 return -EINVAL;
1342 }
1343
1344 arg_url = optarg;
1345 break;
1346
1347 case ARG_GETTER:
1348 if (arg_getter) {
1349 log_error("cannot currently use --getter more than once");
1350 return -EINVAL;
1351 }
1352
1353 arg_getter = optarg;
1354 break;
1355
1356 case ARG_LISTEN_RAW:
1357 if (arg_listen_raw) {
1358 log_error("cannot currently use --listen-raw more than once");
1359 return -EINVAL;
1360 }
1361
1362 arg_listen_raw = optarg;
1363 break;
1364
1365 case ARG_LISTEN_HTTP:
1366 if (arg_listen_http || http_socket >= 0) {
1367 log_error("cannot currently use --listen-http more than once");
1368 return -EINVAL;
1369 }
1370
1371 r = negative_fd(optarg);
1372 if (r >= 0)
1373 http_socket = r;
1374 else
1375 arg_listen_http = optarg;
1376 break;
1377
1378 case ARG_LISTEN_HTTPS:
1379 if (arg_listen_https || https_socket >= 0) {
1380 log_error("cannot currently use --listen-https more than once");
1381 return -EINVAL;
1382 }
1383
1384 r = negative_fd(optarg);
1385 if (r >= 0)
1386 https_socket = r;
1387 else
1388 arg_listen_https = optarg;
1389
1390 break;
1391
1392 case ARG_KEY:
1393 if (arg_key) {
1394 log_error("Key file specified twice");
1395 return -EINVAL;
1396 }
1397
1398 arg_key = strdup(optarg);
1399 if (!arg_key)
1400 return log_oom();
1401
1402 break;
1403
1404 case ARG_CERT:
1405 if (arg_cert) {
1406 log_error("Certificate file specified twice");
1407 return -EINVAL;
1408 }
1409
1410 arg_cert = strdup(optarg);
1411 if (!arg_cert)
1412 return log_oom();
1413
1414 break;
1415
1416 case ARG_TRUST:
1417 if (arg_trust || arg_trust_all) {
1418 log_error("Confusing trusted CA configuration");
1419 return -EINVAL;
1420 }
1421
1422 if (streq(optarg, "all"))
1423 arg_trust_all = true;
1424 else {
1425 #if HAVE_GNUTLS
1426 arg_trust = strdup(optarg);
1427 if (!arg_trust)
1428 return log_oom();
1429 #else
1430 log_error("Option --trust is not available.");
1431 return -EINVAL;
1432 #endif
1433 }
1434
1435 break;
1436
1437 case 'o':
1438 if (arg_output) {
1439 log_error("cannot use --output/-o more than once");
1440 return -EINVAL;
1441 }
1442
1443 arg_output = optarg;
1444 break;
1445
1446 case ARG_SPLIT_MODE:
1447 arg_split_mode = journal_write_split_mode_from_string(optarg);
1448 if (arg_split_mode == _JOURNAL_WRITE_SPLIT_INVALID) {
1449 log_error("Invalid split mode: %s", optarg);
1450 return -EINVAL;
1451 }
1452 break;
1453
1454 case ARG_COMPRESS:
1455 if (optarg) {
1456 r = parse_boolean(optarg);
1457 if (r < 0) {
1458 log_error("Failed to parse --compress= parameter.");
1459 return -EINVAL;
1460 }
1461
1462 arg_compress = !!r;
1463 } else
1464 arg_compress = true;
1465
1466 break;
1467
1468 case ARG_SEAL:
1469 if (optarg) {
1470 r = parse_boolean(optarg);
1471 if (r < 0) {
1472 log_error("Failed to parse --seal= parameter.");
1473 return -EINVAL;
1474 }
1475
1476 arg_seal = !!r;
1477 } else
1478 arg_seal = true;
1479
1480 break;
1481
1482 case ARG_GNUTLS_LOG: {
1483 #if HAVE_GNUTLS
1484 const char* p = optarg;
1485 for (;;) {
1486 _cleanup_free_ char *word = NULL;
1487
1488 r = extract_first_word(&p, &word, ",", 0);
1489 if (r < 0)
1490 return log_error_errno(r, "Failed to parse --gnutls-log= argument: %m");
1491
1492 if (r == 0)
1493 break;
1494
1495 if (strv_push(&arg_gnutls_log, word) < 0)
1496 return log_oom();
1497
1498 word = NULL;
1499 }
1500 break;
1501 #else
1502 log_error("Option --gnutls-log is not available.");
1503 return -EINVAL;
1504 #endif
1505 }
1506
1507 case '?':
1508 return -EINVAL;
1509
1510 default:
1511 assert_not_reached("Unknown option code.");
1512 }
1513
1514 if (optind < argc)
1515 arg_files = argv + optind;
1516
1517 type_a = arg_getter || !strv_isempty(arg_files);
1518 type_b = arg_url
1519 || arg_listen_raw
1520 || arg_listen_http || arg_listen_https
1521 || sd_listen_fds(false) > 0;
1522 if (type_a && type_b) {
1523 log_error("Cannot use file input or --getter with "
1524 "--arg-listen-... or socket activation.");
1525 return -EINVAL;
1526 }
1527 if (type_a) {
1528 if (!arg_output) {
1529 log_error("Option --output must be specified with file input or --getter.");
1530 return -EINVAL;
1531 }
1532
1533 if (!IN_SET(arg_split_mode, JOURNAL_WRITE_SPLIT_NONE, _JOURNAL_WRITE_SPLIT_INVALID)) {
1534 log_error("For active sources, only --split-mode=none is allowed.");
1535 return -EINVAL;
1536 }
1537
1538 arg_split_mode = JOURNAL_WRITE_SPLIT_NONE;
1539 }
1540
1541 if (arg_split_mode == _JOURNAL_WRITE_SPLIT_INVALID)
1542 arg_split_mode = JOURNAL_WRITE_SPLIT_HOST;
1543
1544 if (arg_split_mode == JOURNAL_WRITE_SPLIT_NONE && arg_output) {
1545 if (is_dir(arg_output, true) > 0) {
1546 log_error("For SplitMode=none, output must be a file.");
1547 return -EINVAL;
1548 }
1549 if (!endswith(arg_output, ".journal")) {
1550 log_error("For SplitMode=none, output file name must end with .journal.");
1551 return -EINVAL;
1552 }
1553 }
1554
1555 if (arg_split_mode == JOURNAL_WRITE_SPLIT_HOST
1556 && arg_output && is_dir(arg_output, true) <= 0) {
1557 log_error("For SplitMode=host, output must be a directory.");
1558 return -EINVAL;
1559 }
1560
1561 log_debug("Full config: SplitMode=%s Key=%s Cert=%s Trust=%s",
1562 journal_write_split_mode_to_string(arg_split_mode),
1563 strna(arg_key),
1564 strna(arg_cert),
1565 strna(arg_trust));
1566
1567 return 1 /* work to do */;
1568 }
1569
1570 static int load_certificates(char **key, char **cert, char **trust) {
1571 int r;
1572
1573 r = read_full_file(arg_key ?: PRIV_KEY_FILE, key, NULL);
1574 if (r < 0)
1575 return log_error_errno(r, "Failed to read key from file '%s': %m",
1576 arg_key ?: PRIV_KEY_FILE);
1577
1578 r = read_full_file(arg_cert ?: CERT_FILE, cert, NULL);
1579 if (r < 0)
1580 return log_error_errno(r, "Failed to read certificate from file '%s': %m",
1581 arg_cert ?: CERT_FILE);
1582
1583 if (arg_trust_all)
1584 log_info("Certificate checking disabled.");
1585 else {
1586 r = read_full_file(arg_trust ?: TRUST_FILE, trust, NULL);
1587 if (r < 0)
1588 return log_error_errno(r, "Failed to read CA certificate file '%s': %m",
1589 arg_trust ?: TRUST_FILE);
1590 }
1591
1592 return 0;
1593 }
1594
1595 int main(int argc, char **argv) {
1596 RemoteServer s = {};
1597 int r;
1598 _cleanup_free_ char *key = NULL, *cert = NULL, *trust = NULL;
1599
1600 log_show_color(true);
1601 log_parse_environment();
1602
1603 r = parse_config();
1604 if (r < 0)
1605 return EXIT_FAILURE;
1606
1607 r = parse_argv(argc, argv);
1608 if (r <= 0)
1609 return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1610
1611
1612 if (arg_listen_http || arg_listen_https) {
1613 r = setup_gnutls_logger(arg_gnutls_log);
1614 if (r < 0)
1615 return EXIT_FAILURE;
1616 }
1617
1618 if (arg_listen_https || https_socket >= 0)
1619 if (load_certificates(&key, &cert, &trust) < 0)
1620 return EXIT_FAILURE;
1621
1622 if (remoteserver_init(&s, key, cert, trust) < 0)
1623 return EXIT_FAILURE;
1624
1625 r = sd_event_set_watchdog(s.events, true);
1626 if (r < 0)
1627 log_error_errno(r, "Failed to enable watchdog: %m");
1628 else
1629 log_debug("Watchdog is %sd.", enable_disable(r > 0));
1630
1631 log_debug("%s running as pid "PID_FMT,
1632 program_invocation_short_name, getpid_cached());
1633 sd_notify(false,
1634 "READY=1\n"
1635 "STATUS=Processing requests...");
1636
1637 while (s.active) {
1638 r = sd_event_get_state(s.events);
1639 if (r < 0)
1640 break;
1641 if (r == SD_EVENT_FINISHED)
1642 break;
1643
1644 r = sd_event_run(s.events, -1);
1645 if (r < 0) {
1646 log_error_errno(r, "Failed to run event loop: %m");
1647 break;
1648 }
1649 }
1650
1651 sd_notifyf(false,
1652 "STOPPING=1\n"
1653 "STATUS=Shutting down after writing %" PRIu64 " entries...", s.event_count);
1654 log_info("Finishing after writing %" PRIu64 " entries", s.event_count);
1655
1656 server_destroy(&s);
1657
1658 free(arg_key);
1659 free(arg_cert);
1660 free(arg_trust);
1661
1662 return r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1663 }