1 /* SPDX-License-Identifier: LGPL-2.1+ */
7 #include <selinux/selinux.h>
10 #include "sd-daemon.h"
13 #include "alloc-util.h"
14 #include "dirent-util.h"
16 #include "errno-util.h"
21 #include "journald-console.h"
22 #include "journald-context.h"
23 #include "journald-kmsg.h"
24 #include "journald-server.h"
25 #include "journald-stream.h"
26 #include "journald-syslog.h"
27 #include "journald-wall.h"
29 #include "parse-util.h"
30 #include "process-util.h"
31 #include "selinux-util.h"
32 #include "socket-util.h"
33 #include "stdio-util.h"
34 #include "string-util.h"
35 #include "syslog-util.h"
36 #include "tmpfile-util.h"
37 #include "unit-name.h"
39 #define STDOUT_STREAMS_MAX 4096
41 typedef enum StdoutStreamState
{
42 STDOUT_STREAM_IDENTIFIER
,
43 STDOUT_STREAM_UNIT_ID
,
44 STDOUT_STREAM_PRIORITY
,
45 STDOUT_STREAM_LEVEL_PREFIX
,
46 STDOUT_STREAM_FORWARD_TO_SYSLOG
,
47 STDOUT_STREAM_FORWARD_TO_KMSG
,
48 STDOUT_STREAM_FORWARD_TO_CONSOLE
,
52 /* The different types of log record terminators: a real \n was read, a NUL character was read, the maximum line length
53 * was reached, or the end of the stream was reached */
55 typedef enum LineBreak
{
64 StdoutStreamState state
;
74 bool forward_to_syslog
:1;
75 bool forward_to_kmsg
:1;
76 bool forward_to_console
:1;
79 bool in_notify_queue
:1;
85 sd_event_source
*event_source
;
89 ClientContext
*context
;
91 LIST_FIELDS(StdoutStream
, stdout_stream
);
92 LIST_FIELDS(StdoutStream
, stdout_stream_notify_queue
);
94 char id_field
[STRLEN("_STREAM_ID=") + SD_ID128_STRING_MAX
];
97 void stdout_stream_free(StdoutStream
*s
) {
104 client_context_release(s
->server
, s
->context
);
106 assert(s
->server
->n_stdout_streams
> 0);
107 s
->server
->n_stdout_streams
--;
108 LIST_REMOVE(stdout_stream
, s
->server
->stdout_streams
, s
);
110 if (s
->in_notify_queue
)
111 LIST_REMOVE(stdout_stream_notify_queue
, s
->server
->stdout_streams_notify_queue
, s
);
114 if (s
->event_source
) {
115 sd_event_source_set_enabled(s
->event_source
, SD_EVENT_OFF
);
116 s
->event_source
= sd_event_source_unref(s
->event_source
);
129 DEFINE_TRIVIAL_CLEANUP_FUNC(StdoutStream
*, stdout_stream_free
);
131 void stdout_stream_destroy(StdoutStream
*s
) {
136 (void) unlink(s
->state_file
);
138 stdout_stream_free(s
);
141 static int stdout_stream_save(StdoutStream
*s
) {
142 _cleanup_free_
char *temp_path
= NULL
;
143 _cleanup_fclose_
FILE *f
= NULL
;
148 if (s
->state
!= STDOUT_STREAM_RUNNING
)
151 if (!s
->state_file
) {
154 r
= fstat(s
->fd
, &st
);
156 return log_warning_errno(errno
, "Failed to stat connected stream: %m");
158 /* We use device and inode numbers as identifier for the stream */
159 if (asprintf(&s
->state_file
, "/run/systemd/journal/streams/%lu:%lu", (unsigned long) st
.st_dev
, (unsigned long) st
.st_ino
) < 0)
163 (void) mkdir_p("/run/systemd/journal/streams", 0755);
165 r
= fopen_temporary(s
->state_file
, &f
, &temp_path
);
170 "# This is private data. Do not parse\n"
173 "FORWARD_TO_SYSLOG=%i\n"
174 "FORWARD_TO_KMSG=%i\n"
175 "FORWARD_TO_CONSOLE=%i\n"
179 s
->forward_to_syslog
,
181 s
->forward_to_console
,
182 s
->id_field
+ STRLEN("_STREAM_ID="));
184 if (!isempty(s
->identifier
)) {
185 _cleanup_free_
char *escaped
;
187 escaped
= cescape(s
->identifier
);
193 fprintf(f
, "IDENTIFIER=%s\n", escaped
);
196 if (!isempty(s
->unit_id
)) {
197 _cleanup_free_
char *escaped
;
199 escaped
= cescape(s
->unit_id
);
205 fprintf(f
, "UNIT=%s\n", escaped
);
208 r
= fflush_and_check(f
);
212 if (rename(temp_path
, s
->state_file
) < 0) {
217 if (!s
->fdstore
&& !s
->in_notify_queue
) {
218 LIST_PREPEND(stdout_stream_notify_queue
, s
->server
->stdout_streams_notify_queue
, s
);
219 s
->in_notify_queue
= true;
221 if (s
->server
->notify_event_source
) {
222 r
= sd_event_source_set_enabled(s
->server
->notify_event_source
, SD_EVENT_ON
);
224 log_warning_errno(r
, "Failed to enable notify event source: %m");
231 (void) unlink(s
->state_file
);
234 (void) unlink(temp_path
);
236 return log_error_errno(r
, "Failed to save stream data %s: %m", s
->state_file
);
239 static int stdout_stream_log(StdoutStream
*s
, const char *p
, LineBreak line_break
) {
242 char syslog_priority
[] = "PRIORITY=\0";
243 char syslog_facility
[STRLEN("SYSLOG_FACILITY=") + DECIMAL_STR_MAX(int) + 1];
244 _cleanup_free_
char *message
= NULL
, *syslog_identifier
= NULL
;
252 (void) client_context_maybe_refresh(s
->server
, s
->context
, NULL
, NULL
, 0, NULL
, USEC_INFINITY
);
253 else if (pid_is_valid(s
->ucred
.pid
)) {
254 r
= client_context_acquire(s
->server
, s
->ucred
.pid
, &s
->ucred
, s
->label
, strlen_ptr(s
->label
), s
->unit_id
, &s
->context
);
256 log_warning_errno(r
, "Failed to acquire client context, ignoring: %m");
259 priority
= s
->priority
;
262 syslog_parse_priority(&p
, &priority
, false);
264 if (!client_context_test_priority(s
->context
, priority
))
270 if (s
->forward_to_syslog
|| s
->server
->forward_to_syslog
)
271 server_forward_syslog(s
->server
, syslog_fixup_facility(priority
), s
->identifier
, p
, &s
->ucred
, NULL
);
273 if (s
->forward_to_kmsg
|| s
->server
->forward_to_kmsg
)
274 server_forward_kmsg(s
->server
, priority
, s
->identifier
, p
, &s
->ucred
);
276 if (s
->forward_to_console
|| s
->server
->forward_to_console
)
277 server_forward_console(s
->server
, priority
, s
->identifier
, p
, &s
->ucred
);
279 if (s
->server
->forward_to_wall
)
280 server_forward_wall(s
->server
, priority
, s
->identifier
, p
, &s
->ucred
);
282 m
= N_IOVEC_META_FIELDS
+ 7 + client_context_extra_fields_n_iovec(s
->context
);
283 iovec
= newa(struct iovec
, m
);
285 iovec
[n
++] = IOVEC_MAKE_STRING("_TRANSPORT=stdout");
286 iovec
[n
++] = IOVEC_MAKE_STRING(s
->id_field
);
288 syslog_priority
[STRLEN("PRIORITY=")] = '0' + LOG_PRI(priority
);
289 iovec
[n
++] = IOVEC_MAKE_STRING(syslog_priority
);
291 if (priority
& LOG_FACMASK
) {
292 xsprintf(syslog_facility
, "SYSLOG_FACILITY=%i", LOG_FAC(priority
));
293 iovec
[n
++] = IOVEC_MAKE_STRING(syslog_facility
);
297 syslog_identifier
= strappend("SYSLOG_IDENTIFIER=", s
->identifier
);
298 if (syslog_identifier
)
299 iovec
[n
++] = IOVEC_MAKE_STRING(syslog_identifier
);
302 if (line_break
!= LINE_BREAK_NEWLINE
) {
305 /* If this log message was generated due to an uncommon line break then mention this in the log
308 c
= line_break
== LINE_BREAK_NUL
? "_LINE_BREAK=nul" :
309 line_break
== LINE_BREAK_LINE_MAX
? "_LINE_BREAK=line-max" :
311 iovec
[n
++] = IOVEC_MAKE_STRING(c
);
314 message
= strappend("MESSAGE=", p
);
316 iovec
[n
++] = IOVEC_MAKE_STRING(message
);
318 server_dispatch_message(s
->server
, iovec
, n
, m
, s
->context
, NULL
, priority
, 0);
322 static int stdout_stream_line(StdoutStream
*s
, char *p
, LineBreak line_break
) {
332 /* line breaks by NUL, line max length or EOF are not permissible during the negotiation part of the protocol */
333 if (line_break
!= LINE_BREAK_NEWLINE
&& s
->state
!= STDOUT_STREAM_RUNNING
) {
334 log_warning("Control protocol line not properly terminated.");
340 case STDOUT_STREAM_IDENTIFIER
:
342 s
->identifier
= strdup(p
);
347 s
->state
= STDOUT_STREAM_UNIT_ID
;
350 case STDOUT_STREAM_UNIT_ID
:
351 if (s
->ucred
.uid
== 0 &&
352 unit_name_is_valid(p
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
354 s
->unit_id
= strdup(p
);
359 s
->state
= STDOUT_STREAM_PRIORITY
;
362 case STDOUT_STREAM_PRIORITY
:
363 r
= safe_atoi(p
, &s
->priority
);
364 if (r
< 0 || s
->priority
< 0 || s
->priority
> 999) {
365 log_warning("Failed to parse log priority line.");
369 s
->state
= STDOUT_STREAM_LEVEL_PREFIX
;
372 case STDOUT_STREAM_LEVEL_PREFIX
:
373 r
= parse_boolean(p
);
375 log_warning("Failed to parse level prefix line.");
380 s
->state
= STDOUT_STREAM_FORWARD_TO_SYSLOG
;
383 case STDOUT_STREAM_FORWARD_TO_SYSLOG
:
384 r
= parse_boolean(p
);
386 log_warning("Failed to parse forward to syslog line.");
390 s
->forward_to_syslog
= r
;
391 s
->state
= STDOUT_STREAM_FORWARD_TO_KMSG
;
394 case STDOUT_STREAM_FORWARD_TO_KMSG
:
395 r
= parse_boolean(p
);
397 log_warning("Failed to parse copy to kmsg line.");
401 s
->forward_to_kmsg
= r
;
402 s
->state
= STDOUT_STREAM_FORWARD_TO_CONSOLE
;
405 case STDOUT_STREAM_FORWARD_TO_CONSOLE
:
406 r
= parse_boolean(p
);
408 log_warning("Failed to parse copy to console line.");
412 s
->forward_to_console
= r
;
413 s
->state
= STDOUT_STREAM_RUNNING
;
415 /* Try to save the stream, so that journald can be restarted and we can recover */
416 (void) stdout_stream_save(s
);
419 case STDOUT_STREAM_RUNNING
:
420 return stdout_stream_log(s
, orig
, line_break
);
423 assert_not_reached("Unknown stream state");
426 static int stdout_stream_scan(StdoutStream
*s
, bool force_flush
) {
434 remaining
= s
->length
;
436 /* XXX: This function does nothing if (s->length == 0) */
439 LineBreak line_break
;
443 end1
= memchr(p
, '\n', remaining
);
444 end2
= memchr(p
, 0, end1
? (size_t) (end1
- p
) : remaining
);
447 /* We found a NUL terminator */
449 line_break
= LINE_BREAK_NUL
;
451 /* We found a \n terminator */
454 line_break
= LINE_BREAK_NEWLINE
;
455 } else if (remaining
>= s
->server
->line_max
) {
456 /* Force a line break after the maximum line length */
457 *(p
+ s
->server
->line_max
) = 0;
459 line_break
= LINE_BREAK_LINE_MAX
;
463 r
= stdout_stream_line(s
, p
, line_break
);
471 if (force_flush
&& remaining
> 0) {
473 r
= stdout_stream_line(s
, p
, LINE_BREAK_EOF
);
482 memmove(s
->buffer
, p
, remaining
);
483 s
->length
= remaining
;
489 static int stdout_stream_process(sd_event_source
*es
, int fd
, uint32_t revents
, void *userdata
) {
490 StdoutStream
*s
= userdata
;
497 if ((revents
|EPOLLIN
|EPOLLHUP
) != (EPOLLIN
|EPOLLHUP
)) {
498 log_error("Got invalid event from epoll for stdout stream: %"PRIx32
, revents
);
502 /* If the buffer is full already (discounting the extra NUL we need), add room for another 1K */
503 if (s
->length
+ 1 >= s
->allocated
) {
504 if (!GREEDY_REALLOC(s
->buffer
, s
->allocated
, s
->length
+ 1 + 1024)) {
510 /* Try to make use of the allocated buffer in full, but never read more than the configured line size. Also,
511 * always leave room for a terminating NUL we might need to add. */
512 limit
= MIN(s
->allocated
- 1, s
->server
->line_max
);
514 l
= read(s
->fd
, s
->buffer
+ s
->length
, limit
- s
->length
);
519 log_warning_errno(errno
, "Failed to read from stream: %m");
524 stdout_stream_scan(s
, true);
529 r
= stdout_stream_scan(s
, false);
536 stdout_stream_destroy(s
);
540 int stdout_stream_install(Server
*s
, int fd
, StdoutStream
**ret
) {
541 _cleanup_(stdout_stream_freep
) StdoutStream
*stream
= NULL
;
548 r
= sd_id128_randomize(&id
);
550 return log_error_errno(r
, "Failed to generate stream ID: %m");
552 stream
= new0(StdoutStream
, 1);
557 stream
->priority
= LOG_INFO
;
559 xsprintf(stream
->id_field
, "_STREAM_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(id
));
561 r
= getpeercred(fd
, &stream
->ucred
);
563 return log_error_errno(r
, "Failed to determine peer credentials: %m");
565 if (mac_selinux_use()) {
566 r
= getpeersec(fd
, &stream
->label
);
567 if (r
< 0 && r
!= -EOPNOTSUPP
)
568 (void) log_warning_errno(r
, "Failed to determine peer security context: %m");
571 (void) shutdown(fd
, SHUT_WR
);
573 r
= sd_event_add_io(s
->event
, &stream
->event_source
, fd
, EPOLLIN
, stdout_stream_process
, stream
);
575 return log_error_errno(r
, "Failed to add stream to event loop: %m");
577 r
= sd_event_source_set_priority(stream
->event_source
, SD_EVENT_PRIORITY_NORMAL
+5);
579 return log_error_errno(r
, "Failed to adjust stdout event source priority: %m");
584 LIST_PREPEND(stdout_stream
, s
->stdout_streams
, stream
);
585 s
->n_stdout_streams
++;
595 static int stdout_stream_new(sd_event_source
*es
, int listen_fd
, uint32_t revents
, void *userdata
) {
596 _cleanup_close_
int fd
= -1;
597 Server
*s
= userdata
;
602 if (revents
!= EPOLLIN
)
603 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
604 "Got invalid event from epoll for stdout server fd: %" PRIx32
,
607 fd
= accept4(s
->stdout_fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
609 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
612 return log_error_errno(errno
, "Failed to accept stdout connection: %m");
615 if (s
->n_stdout_streams
>= STDOUT_STREAMS_MAX
) {
618 r
= getpeercred(fd
, &u
);
620 /* By closing fd here we make sure that the client won't wait too long for journald to
621 * gather all the data it adds to the error message to find out that the connection has
626 server_driver_message(s
, r
< 0 ? 0 : u
.pid
, NULL
, LOG_MESSAGE("Too many stdout streams, refusing connection."), NULL
);
630 r
= stdout_stream_install(s
, fd
, NULL
);
638 static int stdout_stream_load(StdoutStream
*stream
, const char *fname
) {
641 *level_prefix
= NULL
,
642 *forward_to_syslog
= NULL
,
643 *forward_to_kmsg
= NULL
,
644 *forward_to_console
= NULL
,
651 if (!stream
->state_file
) {
652 stream
->state_file
= strappend("/run/systemd/journal/streams/", fname
);
653 if (!stream
->state_file
)
657 r
= parse_env_file(NULL
, stream
->state_file
,
658 "PRIORITY", &priority
,
659 "LEVEL_PREFIX", &level_prefix
,
660 "FORWARD_TO_SYSLOG", &forward_to_syslog
,
661 "FORWARD_TO_KMSG", &forward_to_kmsg
,
662 "FORWARD_TO_CONSOLE", &forward_to_console
,
663 "IDENTIFIER", &stream
->identifier
,
664 "UNIT", &stream
->unit_id
,
665 "STREAM_ID", &stream_id
);
667 return log_error_errno(r
, "Failed to read: %s", stream
->state_file
);
672 p
= log_level_from_string(priority
);
674 stream
->priority
= p
;
678 r
= parse_boolean(level_prefix
);
680 stream
->level_prefix
= r
;
683 if (forward_to_syslog
) {
684 r
= parse_boolean(forward_to_syslog
);
686 stream
->forward_to_syslog
= r
;
689 if (forward_to_kmsg
) {
690 r
= parse_boolean(forward_to_kmsg
);
692 stream
->forward_to_kmsg
= r
;
695 if (forward_to_console
) {
696 r
= parse_boolean(forward_to_console
);
698 stream
->forward_to_console
= r
;
704 r
= sd_id128_from_string(stream_id
, &id
);
706 xsprintf(stream
->id_field
, "_STREAM_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(id
));
712 static int stdout_stream_restore(Server
*s
, const char *fname
, int fd
) {
713 StdoutStream
*stream
;
720 if (s
->n_stdout_streams
>= STDOUT_STREAMS_MAX
) {
721 log_warning("Too many stdout streams, refusing restoring of stream.");
725 r
= stdout_stream_install(s
, fd
, &stream
);
729 stream
->state
= STDOUT_STREAM_RUNNING
;
730 stream
->fdstore
= true;
732 /* Ignore all parsing errors */
733 (void) stdout_stream_load(stream
, fname
);
738 int server_restore_streams(Server
*s
, FDSet
*fds
) {
739 _cleanup_closedir_
DIR *d
= NULL
;
743 d
= opendir("/run/systemd/journal/streams");
748 return log_warning_errno(errno
, "Failed to enumerate /run/systemd/journal/streams: %m");
751 FOREACH_DIRENT(de
, d
, goto fail
) {
752 unsigned long st_dev
, st_ino
;
757 if (sscanf(de
->d_name
, "%lu:%lu", &st_dev
, &st_ino
) != 2)
760 FDSET_FOREACH(fd
, fds
, i
) {
763 if (fstat(fd
, &st
) < 0)
764 return log_error_errno(errno
, "Failed to stat %s: %m", de
->d_name
);
766 if (S_ISSOCK(st
.st_mode
) && st
.st_dev
== st_dev
&& st
.st_ino
== st_ino
) {
773 /* No file descriptor? Then let's delete the state file */
774 log_debug("Cannot restore stream file %s", de
->d_name
);
775 if (unlinkat(dirfd(d
), de
->d_name
, 0) < 0)
776 log_warning_errno(errno
, "Failed to remove /run/systemd/journal/streams/%s: %m",
781 fdset_remove(fds
, fd
);
783 r
= stdout_stream_restore(s
, de
->d_name
, fd
);
791 return log_error_errno(errno
, "Failed to read streams directory: %m");
794 int server_open_stdout_socket(Server
*s
) {
795 static const union sockaddr_union sa
= {
796 .un
.sun_family
= AF_UNIX
,
797 .un
.sun_path
= "/run/systemd/journal/stdout",
803 if (s
->stdout_fd
< 0) {
804 s
->stdout_fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
805 if (s
->stdout_fd
< 0)
806 return log_error_errno(errno
, "socket() failed: %m");
808 (void) sockaddr_un_unlink(&sa
.un
);
810 r
= bind(s
->stdout_fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
812 return log_error_errno(errno
, "bind(%s) failed: %m", sa
.un
.sun_path
);
814 (void) chmod(sa
.un
.sun_path
, 0666);
816 if (listen(s
->stdout_fd
, SOMAXCONN
) < 0)
817 return log_error_errno(errno
, "listen(%s) failed: %m", sa
.un
.sun_path
);
819 (void) fd_nonblock(s
->stdout_fd
, true);
821 r
= sd_event_add_io(s
->event
, &s
->stdout_event_source
, s
->stdout_fd
, EPOLLIN
, stdout_stream_new
, s
);
823 return log_error_errno(r
, "Failed to add stdout server fd to event source: %m");
825 r
= sd_event_source_set_priority(s
->stdout_event_source
, SD_EVENT_PRIORITY_NORMAL
+5);
827 return log_error_errno(r
, "Failed to adjust priority of stdout server event source: %m");
832 void stdout_stream_send_notify(StdoutStream
*s
) {
833 struct iovec iovec
= {
834 .iov_base
= (char*) "FDSTORE=1",
835 .iov_len
= STRLEN("FDSTORE=1"),
837 struct msghdr msghdr
= {
841 struct cmsghdr
*cmsg
;
846 assert(s
->in_notify_queue
);
848 assert(s
->server
->notify_fd
>= 0);
850 /* Store the connection fd in PID 1, so that we get it passed
851 * in again on next start */
853 msghdr
.msg_controllen
= CMSG_SPACE(sizeof(int));
854 msghdr
.msg_control
= alloca0(msghdr
.msg_controllen
);
856 cmsg
= CMSG_FIRSTHDR(&msghdr
);
857 cmsg
->cmsg_level
= SOL_SOCKET
;
858 cmsg
->cmsg_type
= SCM_RIGHTS
;
859 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
861 memcpy(CMSG_DATA(cmsg
), &s
->fd
, sizeof(int));
863 l
= sendmsg(s
->server
->notify_fd
, &msghdr
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
868 log_error_errno(errno
, "Failed to send stream file descriptor to service manager: %m");
870 log_debug("Successfully sent stream file descriptor to service manager.");
874 LIST_REMOVE(stdout_stream_notify_queue
, s
->server
->stdout_streams_notify_queue
, s
);
875 s
->in_notify_queue
= false;