2 This file is part of systemd.
4 Copyright 2011 Lennart Poettering
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.
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.
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/>.
24 #include <selinux/selinux.h>
27 #include "sd-daemon.h"
30 #include "alloc-util.h"
31 #include "dirent-util.h"
36 #include "journald-console.h"
37 #include "journald-context.h"
38 #include "journald-kmsg.h"
39 #include "journald-server.h"
40 #include "journald-stream.h"
41 #include "journald-syslog.h"
42 #include "journald-wall.h"
44 #include "parse-util.h"
45 #include "process-util.h"
46 #include "selinux-util.h"
47 #include "socket-util.h"
48 #include "stdio-util.h"
49 #include "string-util.h"
50 #include "syslog-util.h"
51 #include "unit-name.h"
53 #define STDOUT_STREAMS_MAX 4096
55 typedef enum StdoutStreamState
{
56 STDOUT_STREAM_IDENTIFIER
,
57 STDOUT_STREAM_UNIT_ID
,
58 STDOUT_STREAM_PRIORITY
,
59 STDOUT_STREAM_LEVEL_PREFIX
,
60 STDOUT_STREAM_FORWARD_TO_SYSLOG
,
61 STDOUT_STREAM_FORWARD_TO_KMSG
,
62 STDOUT_STREAM_FORWARD_TO_CONSOLE
,
66 /* The different types of log record terminators: a real \n was read, a NUL character was read, the maximum line length
67 * was reached, or the end of the stream was reached */
69 typedef enum LineBreak
{
78 StdoutStreamState state
;
88 bool forward_to_syslog
:1;
89 bool forward_to_kmsg
:1;
90 bool forward_to_console
:1;
93 bool in_notify_queue
:1;
99 sd_event_source
*event_source
;
103 ClientContext
*context
;
105 LIST_FIELDS(StdoutStream
, stdout_stream
);
106 LIST_FIELDS(StdoutStream
, stdout_stream_notify_queue
);
108 char id_field
[sizeof("_STREAM_ID=")-1 + SD_ID128_STRING_MAX
];
111 void stdout_stream_free(StdoutStream
*s
) {
118 client_context_release(s
->server
, s
->context
);
120 assert(s
->server
->n_stdout_streams
> 0);
121 s
->server
->n_stdout_streams
--;
122 LIST_REMOVE(stdout_stream
, s
->server
->stdout_streams
, s
);
124 if (s
->in_notify_queue
)
125 LIST_REMOVE(stdout_stream_notify_queue
, s
->server
->stdout_streams_notify_queue
, s
);
128 if (s
->event_source
) {
129 sd_event_source_set_enabled(s
->event_source
, SD_EVENT_OFF
);
130 s
->event_source
= sd_event_source_unref(s
->event_source
);
143 DEFINE_TRIVIAL_CLEANUP_FUNC(StdoutStream
*, stdout_stream_free
);
145 static void stdout_stream_destroy(StdoutStream
*s
) {
150 (void) unlink(s
->state_file
);
152 stdout_stream_free(s
);
155 static int stdout_stream_save(StdoutStream
*s
) {
156 _cleanup_free_
char *temp_path
= NULL
;
157 _cleanup_fclose_
FILE *f
= NULL
;
162 if (s
->state
!= STDOUT_STREAM_RUNNING
)
165 if (!s
->state_file
) {
168 r
= fstat(s
->fd
, &st
);
170 return log_warning_errno(errno
, "Failed to stat connected stream: %m");
172 /* We use device and inode numbers as identifier for the stream */
173 if (asprintf(&s
->state_file
, "/run/systemd/journal/streams/%lu:%lu", (unsigned long) st
.st_dev
, (unsigned long) st
.st_ino
) < 0)
177 mkdir_p("/run/systemd/journal/streams", 0755);
179 r
= fopen_temporary(s
->state_file
, &f
, &temp_path
);
184 "# This is private data. Do not parse\n"
187 "FORWARD_TO_SYSLOG=%i\n"
188 "FORWARD_TO_KMSG=%i\n"
189 "FORWARD_TO_CONSOLE=%i\n"
193 s
->forward_to_syslog
,
195 s
->forward_to_console
,
196 s
->id_field
+ strlen("_STREAM_ID="));
198 if (!isempty(s
->identifier
)) {
199 _cleanup_free_
char *escaped
;
201 escaped
= cescape(s
->identifier
);
207 fprintf(f
, "IDENTIFIER=%s\n", escaped
);
210 if (!isempty(s
->unit_id
)) {
211 _cleanup_free_
char *escaped
;
213 escaped
= cescape(s
->unit_id
);
219 fprintf(f
, "UNIT=%s\n", escaped
);
222 r
= fflush_and_check(f
);
226 if (rename(temp_path
, s
->state_file
) < 0) {
231 if (!s
->fdstore
&& !s
->in_notify_queue
) {
232 LIST_PREPEND(stdout_stream_notify_queue
, s
->server
->stdout_streams_notify_queue
, s
);
233 s
->in_notify_queue
= true;
235 if (s
->server
->notify_event_source
) {
236 r
= sd_event_source_set_enabled(s
->server
->notify_event_source
, SD_EVENT_ON
);
238 log_warning_errno(r
, "Failed to enable notify event source: %m");
245 (void) unlink(s
->state_file
);
248 (void) unlink(temp_path
);
250 return log_error_errno(r
, "Failed to save stream data %s: %m", s
->state_file
);
253 static int stdout_stream_log(StdoutStream
*s
, const char *p
, LineBreak line_break
) {
254 struct iovec iovec
[N_IOVEC_META_FIELDS
+ 7];
256 char syslog_priority
[] = "PRIORITY=\0";
257 char syslog_facility
[sizeof("SYSLOG_FACILITY=")-1 + DECIMAL_STR_MAX(int) + 1];
258 _cleanup_free_
char *message
= NULL
, *syslog_identifier
= NULL
;
265 priority
= s
->priority
;
268 syslog_parse_priority(&p
, &priority
, false);
273 if (s
->forward_to_syslog
|| s
->server
->forward_to_syslog
)
274 server_forward_syslog(s
->server
, syslog_fixup_facility(priority
), s
->identifier
, p
, &s
->ucred
, NULL
);
276 if (s
->forward_to_kmsg
|| s
->server
->forward_to_kmsg
)
277 server_forward_kmsg(s
->server
, priority
, s
->identifier
, p
, &s
->ucred
);
279 if (s
->forward_to_console
|| s
->server
->forward_to_console
)
280 server_forward_console(s
->server
, priority
, s
->identifier
, p
, &s
->ucred
);
282 if (s
->server
->forward_to_wall
)
283 server_forward_wall(s
->server
, priority
, s
->identifier
, p
, &s
->ucred
);
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
);
319 (void) client_context_maybe_refresh(s
->server
, s
->context
, NULL
, NULL
, 0, NULL
, USEC_INFINITY
);
320 else if (pid_is_valid(s
->ucred
.pid
)) {
321 r
= client_context_acquire(s
->server
, s
->ucred
.pid
, &s
->ucred
, s
->label
, strlen_ptr(s
->label
), s
->unit_id
, &s
->context
);
323 log_warning_errno(r
, "Failed to acquire client context, ignoring: %m");
326 server_dispatch_message(s
->server
, iovec
, n
, ELEMENTSOF(iovec
), s
->context
, NULL
, priority
, 0);
330 static int stdout_stream_line(StdoutStream
*s
, char *p
, LineBreak line_break
) {
340 /* line breaks by NUL, line max length or EOF are not permissible during the negotiation part of the protocol */
341 if (line_break
!= LINE_BREAK_NEWLINE
&& s
->state
!= STDOUT_STREAM_RUNNING
) {
342 log_warning("Control protocol line not properly terminated.");
348 case STDOUT_STREAM_IDENTIFIER
:
350 s
->identifier
= strdup(p
);
355 s
->state
= STDOUT_STREAM_UNIT_ID
;
358 case STDOUT_STREAM_UNIT_ID
:
359 if (s
->ucred
.uid
== 0 &&
360 unit_name_is_valid(p
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
362 s
->unit_id
= strdup(p
);
367 s
->state
= STDOUT_STREAM_PRIORITY
;
370 case STDOUT_STREAM_PRIORITY
:
371 r
= safe_atoi(p
, &s
->priority
);
372 if (r
< 0 || s
->priority
< 0 || s
->priority
> 999) {
373 log_warning("Failed to parse log priority line.");
377 s
->state
= STDOUT_STREAM_LEVEL_PREFIX
;
380 case STDOUT_STREAM_LEVEL_PREFIX
:
381 r
= parse_boolean(p
);
383 log_warning("Failed to parse level prefix line.");
387 s
->level_prefix
= !!r
;
388 s
->state
= STDOUT_STREAM_FORWARD_TO_SYSLOG
;
391 case STDOUT_STREAM_FORWARD_TO_SYSLOG
:
392 r
= parse_boolean(p
);
394 log_warning("Failed to parse forward to syslog line.");
398 s
->forward_to_syslog
= !!r
;
399 s
->state
= STDOUT_STREAM_FORWARD_TO_KMSG
;
402 case STDOUT_STREAM_FORWARD_TO_KMSG
:
403 r
= parse_boolean(p
);
405 log_warning("Failed to parse copy to kmsg line.");
409 s
->forward_to_kmsg
= !!r
;
410 s
->state
= STDOUT_STREAM_FORWARD_TO_CONSOLE
;
413 case STDOUT_STREAM_FORWARD_TO_CONSOLE
:
414 r
= parse_boolean(p
);
416 log_warning("Failed to parse copy to console line.");
420 s
->forward_to_console
= !!r
;
421 s
->state
= STDOUT_STREAM_RUNNING
;
423 /* Try to save the stream, so that journald can be restarted and we can recover */
424 (void) stdout_stream_save(s
);
427 case STDOUT_STREAM_RUNNING
:
428 return stdout_stream_log(s
, orig
, line_break
);
431 assert_not_reached("Unknown stream state");
434 static int stdout_stream_scan(StdoutStream
*s
, bool force_flush
) {
442 remaining
= s
->length
;
444 /* XXX: This function does nothing if (s->length == 0) */
447 LineBreak line_break
;
451 end1
= memchr(p
, '\n', remaining
);
452 end2
= memchr(p
, 0, end1
? (size_t) (end1
- p
) : remaining
);
455 /* We found a NUL terminator */
457 line_break
= LINE_BREAK_NUL
;
459 /* We found a \n terminator */
462 line_break
= LINE_BREAK_NEWLINE
;
463 } else if (remaining
>= s
->server
->line_max
) {
464 /* Force a line break after the maximum line length */
465 *(p
+ s
->server
->line_max
) = 0;
467 line_break
= LINE_BREAK_LINE_MAX
;
471 r
= stdout_stream_line(s
, p
, line_break
);
479 if (force_flush
&& remaining
> 0) {
481 r
= stdout_stream_line(s
, p
, LINE_BREAK_EOF
);
490 memmove(s
->buffer
, p
, remaining
);
491 s
->length
= remaining
;
497 static int stdout_stream_process(sd_event_source
*es
, int fd
, uint32_t revents
, void *userdata
) {
498 StdoutStream
*s
= userdata
;
505 if ((revents
|EPOLLIN
|EPOLLHUP
) != (EPOLLIN
|EPOLLHUP
)) {
506 log_error("Got invalid event from epoll for stdout stream: %"PRIx32
, revents
);
510 /* If the buffer is full already (discounting the extra NUL we need), add room for another 1K */
511 if (s
->length
+ 1 >= s
->allocated
) {
512 if (!GREEDY_REALLOC(s
->buffer
, s
->allocated
, s
->length
+ 1 + 1024)) {
518 /* Try to make use of the allocated buffer in full, but never read more than the configured line size. Also,
519 * always leave room for a terminating NUL we might need to add. */
520 limit
= MIN(s
->allocated
- 1, s
->server
->line_max
);
522 l
= read(s
->fd
, s
->buffer
+ s
->length
, limit
- s
->length
);
527 log_warning_errno(errno
, "Failed to read from stream: %m");
532 stdout_stream_scan(s
, true);
537 r
= stdout_stream_scan(s
, false);
544 stdout_stream_destroy(s
);
548 static int stdout_stream_install(Server
*s
, int fd
, StdoutStream
**ret
) {
549 _cleanup_(stdout_stream_freep
) StdoutStream
*stream
= NULL
;
556 r
= sd_id128_randomize(&id
);
558 return log_error_errno(r
, "Failed to generate stream ID: %m");
560 stream
= new0(StdoutStream
, 1);
565 stream
->priority
= LOG_INFO
;
567 xsprintf(stream
->id_field
, "_STREAM_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(id
));
569 r
= getpeercred(fd
, &stream
->ucred
);
571 return log_error_errno(r
, "Failed to determine peer credentials: %m");
573 if (mac_selinux_use()) {
574 r
= getpeersec(fd
, &stream
->label
);
575 if (r
< 0 && r
!= -EOPNOTSUPP
)
576 (void) log_warning_errno(r
, "Failed to determine peer security context: %m");
579 (void) shutdown(fd
, SHUT_WR
);
581 r
= sd_event_add_io(s
->event
, &stream
->event_source
, fd
, EPOLLIN
, stdout_stream_process
, stream
);
583 return log_error_errno(r
, "Failed to add stream to event loop: %m");
585 r
= sd_event_source_set_priority(stream
->event_source
, SD_EVENT_PRIORITY_NORMAL
+5);
587 return log_error_errno(r
, "Failed to adjust stdout event source priority: %m");
592 LIST_PREPEND(stdout_stream
, s
->stdout_streams
, stream
);
593 s
->n_stdout_streams
++;
603 static int stdout_stream_new(sd_event_source
*es
, int listen_fd
, uint32_t revents
, void *userdata
) {
604 _cleanup_close_
int fd
= -1;
605 Server
*s
= userdata
;
610 if (revents
!= EPOLLIN
) {
611 log_error("Got invalid event from epoll for stdout server fd: %"PRIx32
, revents
);
615 fd
= accept4(s
->stdout_fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
620 return log_error_errno(errno
, "Failed to accept stdout connection: %m");
623 if (s
->n_stdout_streams
>= STDOUT_STREAMS_MAX
) {
624 log_warning("Too many stdout streams, refusing connection.");
628 r
= stdout_stream_install(s
, fd
, NULL
);
636 static int stdout_stream_load(StdoutStream
*stream
, const char *fname
) {
639 *level_prefix
= NULL
,
640 *forward_to_syslog
= NULL
,
641 *forward_to_kmsg
= NULL
,
642 *forward_to_console
= NULL
,
649 if (!stream
->state_file
) {
650 stream
->state_file
= strappend("/run/systemd/journal/streams/", fname
);
651 if (!stream
->state_file
)
655 r
= parse_env_file(stream
->state_file
, NEWLINE
,
656 "PRIORITY", &priority
,
657 "LEVEL_PREFIX", &level_prefix
,
658 "FORWARD_TO_SYSLOG", &forward_to_syslog
,
659 "FORWARD_TO_KMSG", &forward_to_kmsg
,
660 "FORWARD_TO_CONSOLE", &forward_to_console
,
661 "IDENTIFIER", &stream
->identifier
,
662 "UNIT", &stream
->unit_id
,
663 "STREAM_ID", &stream_id
,
666 return log_error_errno(r
, "Failed to read: %s", stream
->state_file
);
671 p
= log_level_from_string(priority
);
673 stream
->priority
= p
;
677 r
= parse_boolean(level_prefix
);
679 stream
->level_prefix
= r
;
682 if (forward_to_syslog
) {
683 r
= parse_boolean(forward_to_syslog
);
685 stream
->forward_to_syslog
= r
;
688 if (forward_to_kmsg
) {
689 r
= parse_boolean(forward_to_kmsg
);
691 stream
->forward_to_kmsg
= r
;
694 if (forward_to_console
) {
695 r
= parse_boolean(forward_to_console
);
697 stream
->forward_to_console
= r
;
703 r
= sd_id128_from_string(stream_id
, &id
);
705 xsprintf(stream
->id_field
, "_STREAM_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(id
));
711 static int stdout_stream_restore(Server
*s
, const char *fname
, int fd
) {
712 StdoutStream
*stream
;
719 if (s
->n_stdout_streams
>= STDOUT_STREAMS_MAX
) {
720 log_warning("Too many stdout streams, refusing restoring of stream.");
724 r
= stdout_stream_install(s
, fd
, &stream
);
728 stream
->state
= STDOUT_STREAM_RUNNING
;
729 stream
->fdstore
= true;
731 /* Ignore all parsing errors */
732 (void) stdout_stream_load(stream
, fname
);
737 int server_restore_streams(Server
*s
, FDSet
*fds
) {
738 _cleanup_closedir_
DIR *d
= NULL
;
742 d
= opendir("/run/systemd/journal/streams");
747 return log_warning_errno(errno
, "Failed to enumerate /run/systemd/journal/streams: %m");
750 FOREACH_DIRENT(de
, d
, goto fail
) {
751 unsigned long st_dev
, st_ino
;
756 if (sscanf(de
->d_name
, "%lu:%lu", &st_dev
, &st_ino
) != 2)
759 FDSET_FOREACH(fd
, fds
, i
) {
762 if (fstat(fd
, &st
) < 0)
763 return log_error_errno(errno
, "Failed to stat %s: %m", de
->d_name
);
765 if (S_ISSOCK(st
.st_mode
) && st
.st_dev
== st_dev
&& st
.st_ino
== st_ino
) {
772 /* No file descriptor? Then let's delete the state file */
773 log_debug("Cannot restore stream file %s", de
->d_name
);
774 unlinkat(dirfd(d
), de
->d_name
, 0);
778 fdset_remove(fds
, fd
);
780 r
= stdout_stream_restore(s
, de
->d_name
, fd
);
788 return log_error_errno(errno
, "Failed to read streams directory: %m");
791 int server_open_stdout_socket(Server
*s
) {
792 static const union sockaddr_union sa
= {
793 .un
.sun_family
= AF_UNIX
,
794 .un
.sun_path
= "/run/systemd/journal/stdout",
800 if (s
->stdout_fd
< 0) {
801 s
->stdout_fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
802 if (s
->stdout_fd
< 0)
803 return log_error_errno(errno
, "socket() failed: %m");
805 (void) unlink(sa
.un
.sun_path
);
807 r
= bind(s
->stdout_fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
809 return log_error_errno(errno
, "bind(%s) failed: %m", sa
.un
.sun_path
);
811 (void) chmod(sa
.un
.sun_path
, 0666);
813 if (listen(s
->stdout_fd
, SOMAXCONN
) < 0)
814 return log_error_errno(errno
, "listen(%s) failed: %m", sa
.un
.sun_path
);
816 fd_nonblock(s
->stdout_fd
, 1);
818 r
= sd_event_add_io(s
->event
, &s
->stdout_event_source
, s
->stdout_fd
, EPOLLIN
, stdout_stream_new
, s
);
820 return log_error_errno(r
, "Failed to add stdout server fd to event source: %m");
822 r
= sd_event_source_set_priority(s
->stdout_event_source
, SD_EVENT_PRIORITY_NORMAL
+5);
824 return log_error_errno(r
, "Failed to adjust priority of stdout server event source: %m");
829 void stdout_stream_send_notify(StdoutStream
*s
) {
830 struct iovec iovec
= {
831 .iov_base
= (char*) "FDSTORE=1",
832 .iov_len
= strlen("FDSTORE=1"),
834 struct msghdr msghdr
= {
838 struct cmsghdr
*cmsg
;
843 assert(s
->in_notify_queue
);
845 assert(s
->server
->notify_fd
>= 0);
847 /* Store the connection fd in PID 1, so that we get it passed
848 * in again on next start */
850 msghdr
.msg_controllen
= CMSG_SPACE(sizeof(int));
851 msghdr
.msg_control
= alloca0(msghdr
.msg_controllen
);
853 cmsg
= CMSG_FIRSTHDR(&msghdr
);
854 cmsg
->cmsg_level
= SOL_SOCKET
;
855 cmsg
->cmsg_type
= SCM_RIGHTS
;
856 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
858 memcpy(CMSG_DATA(cmsg
), &s
->fd
, sizeof(int));
860 l
= sendmsg(s
->server
->notify_fd
, &msghdr
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
865 log_error_errno(errno
, "Failed to send stream file descriptor to service manager: %m");
867 log_debug("Successfully sent stream file descriptor to service manager.");
871 LIST_REMOVE(stdout_stream_notify_queue
, s
->server
->stdout_streams_notify_queue
, s
);
872 s
->in_notify_queue
= false;