1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2011 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/epoll.h>
23 #include <sys/socket.h>
25 #include <sys/signalfd.h>
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <sys/statvfs.h>
34 #include <systemd/sd-journal.h>
35 #include <systemd/sd-login.h>
36 #include <systemd/sd-messages.h>
37 #include <systemd/sd-daemon.h>
40 #include "journal-file.h"
41 #include "socket-util.h"
42 #include "cgroup-util.h"
44 #include "journal-rate-limit.h"
45 #include "journal-internal.h"
46 #include "conf-parser.h"
53 #include <acl/libacl.h>
58 #include <selinux/selinux.h>
61 #define USER_JOURNALS_MAX 1024
62 #define STDOUT_STREAMS_MAX 4096
64 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
65 #define DEFAULT_RATE_LIMIT_BURST 200
67 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
69 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
71 #define N_IOVEC_META_FIELDS 17
73 #define ENTRY_SIZE_MAX (1024*1024*32)
75 typedef enum StdoutStreamState
{
76 STDOUT_STREAM_IDENTIFIER
,
77 STDOUT_STREAM_PRIORITY
,
78 STDOUT_STREAM_LEVEL_PREFIX
,
79 STDOUT_STREAM_FORWARD_TO_SYSLOG
,
80 STDOUT_STREAM_FORWARD_TO_KMSG
,
81 STDOUT_STREAM_FORWARD_TO_CONSOLE
,
87 StdoutStreamState state
;
93 security_context_t security_context
;
99 bool forward_to_syslog
:1;
100 bool forward_to_kmsg
:1;
101 bool forward_to_console
:1;
103 char buffer
[LINE_MAX
+1];
106 LIST_FIELDS(StdoutStream
, stdout_stream
);
109 static int server_flush_to_var(Server
*s
);
111 static uint64_t available_space(Server
*s
) {
116 uint64_t sum
= 0, avail
= 0, ss_avail
= 0;
122 ts
= now(CLOCK_MONOTONIC
);
124 if (s
->cached_available_space_timestamp
+ RECHECK_AVAILABLE_SPACE_USEC
> ts
)
125 return s
->cached_available_space
;
127 r
= sd_id128_get_machine(&machine
);
131 if (s
->system_journal
) {
132 f
= "/var/log/journal/";
133 m
= &s
->system_metrics
;
135 f
= "/run/log/journal/";
136 m
= &s
->runtime_metrics
;
141 p
= strappend(f
, sd_id128_to_string(machine
, ids
));
151 if (fstatvfs(dirfd(d
), &ss
) < 0)
156 struct dirent buf
, *de
;
159 k
= readdir_r(d
, &buf
, &de
);
168 if (!dirent_is_file_with_suffix(de
, ".journal"))
171 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
174 if (!S_ISREG(st
.st_mode
))
177 sum
+= (uint64_t) st
.st_blocks
* 512UL;
180 avail
= sum
>= m
->max_use
? 0 : m
->max_use
- sum
;
182 ss_avail
= ss
.f_bsize
* ss
.f_bavail
;
184 ss_avail
= ss_avail
< m
->keep_free
? 0 : ss_avail
- m
->keep_free
;
186 if (ss_avail
< avail
)
189 s
->cached_available_space
= avail
;
190 s
->cached_available_space_timestamp
= ts
;
198 static void server_read_file_gid(Server
*s
) {
199 const char *adm
= "adm";
204 if (s
->file_gid_valid
)
207 r
= get_group_creds(&adm
, &s
->file_gid
);
209 log_warning("Failed to resolve 'adm' group: %s", strerror(-r
));
211 /* if we couldn't read the gid, then it will be 0, but that's
212 * fine and we shouldn't try to resolve the group again, so
213 * let's just pretend it worked right-away. */
214 s
->file_gid_valid
= true;
217 static void server_fix_perms(Server
*s
, JournalFile
*f
, uid_t uid
) {
222 acl_permset_t permset
;
227 server_read_file_gid(s
);
229 r
= fchmod_and_fchown(f
->fd
, 0640, 0, s
->file_gid
);
231 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f
->path
, strerror(-r
));
237 acl
= acl_get_fd(f
->fd
);
239 log_warning("Failed to read ACL on %s, ignoring: %m", f
->path
);
243 r
= acl_find_uid(acl
, uid
, &entry
);
246 if (acl_create_entry(&acl
, &entry
) < 0 ||
247 acl_set_tag_type(entry
, ACL_USER
) < 0 ||
248 acl_set_qualifier(entry
, &uid
) < 0) {
249 log_warning("Failed to patch ACL on %s, ignoring: %m", f
->path
);
254 if (acl_get_permset(entry
, &permset
) < 0 ||
255 acl_add_perm(permset
, ACL_READ
) < 0 ||
256 acl_calc_mask(&acl
) < 0) {
257 log_warning("Failed to patch ACL on %s, ignoring: %m", f
->path
);
261 if (acl_set_fd(f
->fd
, acl
) < 0)
262 log_warning("Failed to set ACL on %s, ignoring: %m", f
->path
);
269 static JournalFile
* find_journal(Server
*s
, uid_t uid
) {
278 /* We split up user logs only on /var, not on /run. If the
279 * runtime file is open, we write to it exclusively, in order
280 * to guarantee proper order as soon as we flush /run to
281 * /var and close the runtime file. */
283 if (s
->runtime_journal
)
284 return s
->runtime_journal
;
287 return s
->system_journal
;
289 r
= sd_id128_get_machine(&machine
);
291 return s
->system_journal
;
293 f
= hashmap_get(s
->user_journals
, UINT32_TO_PTR(uid
));
297 if (asprintf(&p
, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine
, ids
), (unsigned long) uid
) < 0)
298 return s
->system_journal
;
300 while (hashmap_size(s
->user_journals
) >= USER_JOURNALS_MAX
) {
301 /* Too many open? Then let's close one */
302 f
= hashmap_steal_first(s
->user_journals
);
304 journal_file_close(f
);
307 r
= journal_file_open_reliably(p
, O_RDWR
|O_CREAT
, 0640, s
->system_journal
, &f
);
311 return s
->system_journal
;
313 server_fix_perms(s
, f
, uid
);
315 r
= hashmap_put(s
->user_journals
, UINT32_TO_PTR(uid
), f
);
317 journal_file_close(f
);
318 return s
->system_journal
;
324 static void server_rotate(Server
*s
) {
330 log_info("Rotating...");
332 if (s
->runtime_journal
) {
333 r
= journal_file_rotate(&s
->runtime_journal
);
335 log_error("Failed to rotate %s: %s", s
->runtime_journal
->path
, strerror(-r
));
338 if (s
->system_journal
) {
339 r
= journal_file_rotate(&s
->system_journal
);
341 log_error("Failed to rotate %s: %s", s
->system_journal
->path
, strerror(-r
));
344 HASHMAP_FOREACH_KEY(f
, k
, s
->user_journals
, i
) {
345 r
= journal_file_rotate(&f
);
347 log_error("Failed to rotate %s: %s", f
->path
, strerror(-r
));
349 hashmap_replace(s
->user_journals
, k
, f
);
353 static void server_vacuum(Server
*s
) {
359 log_info("Vacuuming...");
361 r
= sd_id128_get_machine(&machine
);
363 log_error("Failed to get machine ID: %s", strerror(-r
));
367 sd_id128_to_string(machine
, ids
);
369 if (s
->system_journal
) {
370 if (asprintf(&p
, "/var/log/journal/%s", ids
) < 0) {
371 log_error("Out of memory.");
375 r
= journal_directory_vacuum(p
, s
->system_metrics
.max_use
, s
->system_metrics
.keep_free
);
376 if (r
< 0 && r
!= -ENOENT
)
377 log_error("Failed to vacuum %s: %s", p
, strerror(-r
));
382 if (s
->runtime_journal
) {
383 if (asprintf(&p
, "/run/log/journal/%s", ids
) < 0) {
384 log_error("Out of memory.");
388 r
= journal_directory_vacuum(p
, s
->runtime_metrics
.max_use
, s
->runtime_metrics
.keep_free
);
389 if (r
< 0 && r
!= -ENOENT
)
390 log_error("Failed to vacuum %s: %s", p
, strerror(-r
));
394 s
->cached_available_space_timestamp
= 0;
397 static char *shortened_cgroup_path(pid_t pid
) {
399 char *process_path
, *init_path
, *path
;
403 r
= cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER
, pid
, &process_path
);
407 r
= cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER
, 1, &init_path
);
413 if (endswith(init_path
, "/system"))
414 init_path
[strlen(init_path
) - 7] = 0;
415 else if (streq(init_path
, "/"))
418 if (startswith(process_path
, init_path
)) {
421 p
= strdup(process_path
+ strlen(init_path
));
439 static void dispatch_message_real(
441 struct iovec
*iovec
, unsigned n
, unsigned m
,
444 const char *label
, size_t label_len
) {
446 char *pid
= NULL
, *uid
= NULL
, *gid
= NULL
,
447 *source_time
= NULL
, *boot_id
= NULL
, *machine_id
= NULL
,
448 *comm
= NULL
, *cmdline
= NULL
, *hostname
= NULL
,
449 *audit_session
= NULL
, *audit_loginuid
= NULL
,
450 *exe
= NULL
, *cgroup
= NULL
, *session
= NULL
,
451 *owner_uid
= NULL
, *unit
= NULL
, *selinux_context
= NULL
;
457 uid_t loginuid
= 0, realuid
= 0;
459 bool vacuumed
= false;
464 assert(n
+ N_IOVEC_META_FIELDS
<= m
);
470 realuid
= ucred
->uid
;
472 if (asprintf(&pid
, "_PID=%lu", (unsigned long) ucred
->pid
) >= 0)
473 IOVEC_SET_STRING(iovec
[n
++], pid
);
475 if (asprintf(&uid
, "_UID=%lu", (unsigned long) ucred
->uid
) >= 0)
476 IOVEC_SET_STRING(iovec
[n
++], uid
);
478 if (asprintf(&gid
, "_GID=%lu", (unsigned long) ucred
->gid
) >= 0)
479 IOVEC_SET_STRING(iovec
[n
++], gid
);
481 r
= get_process_comm(ucred
->pid
, &t
);
483 comm
= strappend("_COMM=", t
);
487 IOVEC_SET_STRING(iovec
[n
++], comm
);
490 r
= get_process_exe(ucred
->pid
, &t
);
492 exe
= strappend("_EXE=", t
);
496 IOVEC_SET_STRING(iovec
[n
++], exe
);
499 r
= get_process_cmdline(ucred
->pid
, LINE_MAX
, false, &t
);
501 cmdline
= strappend("_CMDLINE=", t
);
505 IOVEC_SET_STRING(iovec
[n
++], cmdline
);
508 r
= audit_session_from_pid(ucred
->pid
, &audit
);
510 if (asprintf(&audit_session
, "_AUDIT_SESSION=%lu", (unsigned long) audit
) >= 0)
511 IOVEC_SET_STRING(iovec
[n
++], audit_session
);
513 r
= audit_loginuid_from_pid(ucred
->pid
, &loginuid
);
515 if (asprintf(&audit_loginuid
, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid
) >= 0)
516 IOVEC_SET_STRING(iovec
[n
++], audit_loginuid
);
518 t
= shortened_cgroup_path(ucred
->pid
);
520 cgroup
= strappend("_SYSTEMD_CGROUP=", t
);
524 IOVEC_SET_STRING(iovec
[n
++], cgroup
);
527 if (sd_pid_get_session(ucred
->pid
, &t
) >= 0) {
528 session
= strappend("_SYSTEMD_SESSION=", t
);
532 IOVEC_SET_STRING(iovec
[n
++], session
);
535 if (sd_pid_get_unit(ucred
->pid
, &t
) >= 0) {
536 unit
= strappend("_SYSTEMD_UNIT=", t
);
540 IOVEC_SET_STRING(iovec
[n
++], unit
);
543 if (sd_pid_get_owner_uid(ucred
->uid
, &owner
) >= 0)
544 if (asprintf(&owner_uid
, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner
) >= 0)
545 IOVEC_SET_STRING(iovec
[n
++], owner_uid
);
549 selinux_context
= malloc(sizeof("_SELINUX_CONTEXT=") + label_len
);
550 if (selinux_context
) {
551 memcpy(selinux_context
, "_SELINUX_CONTEXT=", sizeof("_SELINUX_CONTEXT=")-1);
552 memcpy(selinux_context
+sizeof("_SELINUX_CONTEXT=")-1, label
, label_len
);
553 selinux_context
[sizeof("_SELINUX_CONTEXT=")-1+label_len
] = 0;
554 IOVEC_SET_STRING(iovec
[n
++], selinux_context
);
557 security_context_t con
;
559 if (getpidcon(ucred
->pid
, &con
) >= 0) {
560 selinux_context
= strappend("_SELINUX_CONTEXT=", con
);
562 IOVEC_SET_STRING(iovec
[n
++], selinux_context
);
571 if (asprintf(&source_time
, "_SOURCE_REALTIME_TIMESTAMP=%llu",
572 (unsigned long long) timeval_load(tv
)) >= 0)
573 IOVEC_SET_STRING(iovec
[n
++], source_time
);
576 /* Note that strictly speaking storing the boot id here is
577 * redundant since the entry includes this in-line
578 * anyway. However, we need this indexed, too. */
579 r
= sd_id128_get_boot(&id
);
581 if (asprintf(&boot_id
, "_BOOT_ID=%s", sd_id128_to_string(id
, idbuf
)) >= 0)
582 IOVEC_SET_STRING(iovec
[n
++], boot_id
);
584 r
= sd_id128_get_machine(&id
);
586 if (asprintf(&machine_id
, "_MACHINE_ID=%s", sd_id128_to_string(id
, idbuf
)) >= 0)
587 IOVEC_SET_STRING(iovec
[n
++], machine_id
);
589 t
= gethostname_malloc();
591 hostname
= strappend("_HOSTNAME=", t
);
594 IOVEC_SET_STRING(iovec
[n
++], hostname
);
599 server_flush_to_var(s
);
602 f
= find_journal(s
, realuid
== 0 ? 0 : loginuid
);
604 log_warning("Dropping message, as we can't find a place to store the data.");
606 r
= journal_file_append_entry(f
, NULL
, iovec
, n
, &s
->seqnum
, NULL
, NULL
);
608 if ((r
== -EBADMSG
|| r
== -E2BIG
) && !vacuumed
) {
611 log_info("Allocation limit reached, rotating.");
613 log_warning("Journal file corrupted, rotating.");
619 log_info("Retrying write.");
624 log_error("Failed to write entry, ignoring: %s", strerror(-r
));
638 free(audit_loginuid
);
643 free(selinux_context
);
646 static void driver_message(Server
*s
, sd_id128_t message_id
, const char *format
, ...) {
647 char mid
[11 + 32 + 1];
648 char buffer
[16 + LINE_MAX
+ 1];
649 struct iovec iovec
[N_IOVEC_META_FIELDS
+ 4];
657 IOVEC_SET_STRING(iovec
[n
++], "PRIORITY=5");
658 IOVEC_SET_STRING(iovec
[n
++], "_TRANSPORT=driver");
660 memcpy(buffer
, "MESSAGE=", 8);
661 va_start(ap
, format
);
662 vsnprintf(buffer
+ 8, sizeof(buffer
) - 8, format
, ap
);
664 char_array_0(buffer
);
665 IOVEC_SET_STRING(iovec
[n
++], buffer
);
667 snprintf(mid
, sizeof(mid
), "MESSAGE_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(message_id
));
669 IOVEC_SET_STRING(iovec
[n
++], mid
);
672 ucred
.pid
= getpid();
673 ucred
.uid
= getuid();
674 ucred
.gid
= getgid();
676 dispatch_message_real(s
, iovec
, n
, ELEMENTSOF(iovec
), &ucred
, NULL
, NULL
, 0);
679 static void dispatch_message(Server
*s
,
680 struct iovec
*iovec
, unsigned n
, unsigned m
,
683 const char *label
, size_t label_len
,
686 char *path
= NULL
, *c
;
689 assert(iovec
|| n
== 0);
697 path
= shortened_cgroup_path(ucred
->pid
);
701 /* example: /user/lennart/3/foobar
702 * /system/dbus.service/foobar
704 * So let's cut of everything past the third /, since that is
705 * wher user directories start */
707 c
= strchr(path
, '/');
709 c
= strchr(c
+1, '/');
711 c
= strchr(c
+1, '/');
717 rl
= journal_rate_limit_test(s
->rate_limit
, path
, priority
& LOG_PRIMASK
, available_space(s
));
724 /* Write a suppression message if we suppressed something */
726 driver_message(s
, SD_MESSAGE_JOURNAL_DROPPED
, "Suppressed %u messages from %s", rl
- 1, path
);
731 dispatch_message_real(s
, iovec
, n
, m
, ucred
, tv
, label
, label_len
);
734 static void forward_syslog_iovec(Server
*s
, const struct iovec
*iovec
, unsigned n_iovec
, struct ucred
*ucred
, struct timeval
*tv
) {
735 struct msghdr msghdr
;
736 struct cmsghdr
*cmsg
;
738 struct cmsghdr cmsghdr
;
739 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
))];
741 union sockaddr_union sa
;
748 msghdr
.msg_iov
= (struct iovec
*) iovec
;
749 msghdr
.msg_iovlen
= n_iovec
;
752 sa
.un
.sun_family
= AF_UNIX
;
753 strncpy(sa
.un
.sun_path
, "/run/systemd/journal/syslog", sizeof(sa
.un
.sun_path
));
754 msghdr
.msg_name
= &sa
;
755 msghdr
.msg_namelen
= offsetof(union sockaddr_union
, un
.sun_path
) + strlen(sa
.un
.sun_path
);
759 msghdr
.msg_control
= &control
;
760 msghdr
.msg_controllen
= sizeof(control
);
762 cmsg
= CMSG_FIRSTHDR(&msghdr
);
763 cmsg
->cmsg_level
= SOL_SOCKET
;
764 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
765 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
766 memcpy(CMSG_DATA(cmsg
), ucred
, sizeof(struct ucred
));
767 msghdr
.msg_controllen
= cmsg
->cmsg_len
;
770 /* Forward the syslog message we received via /dev/log to
771 * /run/systemd/syslog. Unfortunately we currently can't set
772 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
774 if (sendmsg(s
->syslog_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
777 /* The socket is full? I guess the syslog implementation is
778 * too slow, and we shouldn't wait for that... */
782 if (ucred
&& errno
== ESRCH
) {
785 /* Hmm, presumably the sender process vanished
786 * by now, so let's fix it as good as we
791 memcpy(CMSG_DATA(cmsg
), &u
, sizeof(struct ucred
));
793 if (sendmsg(s
->syslog_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
800 log_debug("Failed to forward syslog message: %m");
803 static void forward_syslog_raw(Server
*s
, const char *buffer
, struct ucred
*ucred
, struct timeval
*tv
) {
809 IOVEC_SET_STRING(iovec
, buffer
);
810 forward_syslog_iovec(s
, &iovec
, 1, ucred
, tv
);
813 static void forward_syslog(Server
*s
, int priority
, const char *identifier
, const char *message
, struct ucred
*ucred
, struct timeval
*tv
) {
814 struct iovec iovec
[5];
815 char header_priority
[6], header_time
[64], header_pid
[16];
819 char *ident_buf
= NULL
;
822 assert(priority
>= 0);
823 assert(priority
<= 999);
826 /* First: priority field */
827 snprintf(header_priority
, sizeof(header_priority
), "<%i>", priority
);
828 char_array_0(header_priority
);
829 IOVEC_SET_STRING(iovec
[n
++], header_priority
);
831 /* Second: timestamp */
832 t
= tv
? tv
->tv_sec
: ((time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
));
836 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", tm
) <= 0)
838 IOVEC_SET_STRING(iovec
[n
++], header_time
);
840 /* Third: identifier and PID */
843 get_process_comm(ucred
->pid
, &ident_buf
);
844 identifier
= ident_buf
;
847 snprintf(header_pid
, sizeof(header_pid
), "[%lu]: ", (unsigned long) ucred
->pid
);
848 char_array_0(header_pid
);
851 IOVEC_SET_STRING(iovec
[n
++], identifier
);
853 IOVEC_SET_STRING(iovec
[n
++], header_pid
);
854 } else if (identifier
) {
855 IOVEC_SET_STRING(iovec
[n
++], identifier
);
856 IOVEC_SET_STRING(iovec
[n
++], ": ");
859 /* Fourth: message */
860 IOVEC_SET_STRING(iovec
[n
++], message
);
862 forward_syslog_iovec(s
, iovec
, n
, ucred
, tv
);
867 static int fixup_priority(int priority
) {
869 if ((priority
& LOG_FACMASK
) == 0)
870 return (priority
& LOG_PRIMASK
) | LOG_USER
;
875 static void forward_kmsg(Server
*s
, int priority
, const char *identifier
, const char *message
, struct ucred
*ucred
) {
876 struct iovec iovec
[5];
877 char header_priority
[6], header_pid
[16];
879 char *ident_buf
= NULL
;
883 assert(priority
>= 0);
884 assert(priority
<= 999);
887 /* Never allow messages with kernel facility to be written to
888 * kmsg, regardless where the data comes from. */
889 priority
= fixup_priority(priority
);
891 /* First: priority field */
892 snprintf(header_priority
, sizeof(header_priority
), "<%i>", priority
);
893 char_array_0(header_priority
);
894 IOVEC_SET_STRING(iovec
[n
++], header_priority
);
896 /* Second: identifier and PID */
899 get_process_comm(ucred
->pid
, &ident_buf
);
900 identifier
= ident_buf
;
903 snprintf(header_pid
, sizeof(header_pid
), "[%lu]: ", (unsigned long) ucred
->pid
);
904 char_array_0(header_pid
);
907 IOVEC_SET_STRING(iovec
[n
++], identifier
);
909 IOVEC_SET_STRING(iovec
[n
++], header_pid
);
910 } else if (identifier
) {
911 IOVEC_SET_STRING(iovec
[n
++], identifier
);
912 IOVEC_SET_STRING(iovec
[n
++], ": ");
915 /* Fourth: message */
916 IOVEC_SET_STRING(iovec
[n
++], message
);
917 IOVEC_SET_STRING(iovec
[n
++], "\n");
919 fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
921 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno
));
925 if (writev(fd
, iovec
, n
) < 0)
926 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno
));
928 close_nointr_nofail(fd
);
934 static void forward_console(Server
*s
, const char *identifier
, const char *message
, struct ucred
*ucred
) {
935 struct iovec iovec
[4];
938 char *ident_buf
= NULL
;
943 /* First: identifier and PID */
946 get_process_comm(ucred
->pid
, &ident_buf
);
947 identifier
= ident_buf
;
950 snprintf(header_pid
, sizeof(header_pid
), "[%lu]: ", (unsigned long) ucred
->pid
);
951 char_array_0(header_pid
);
954 IOVEC_SET_STRING(iovec
[n
++], identifier
);
956 IOVEC_SET_STRING(iovec
[n
++], header_pid
);
957 } else if (identifier
) {
958 IOVEC_SET_STRING(iovec
[n
++], identifier
);
959 IOVEC_SET_STRING(iovec
[n
++], ": ");
963 IOVEC_SET_STRING(iovec
[n
++], message
);
964 IOVEC_SET_STRING(iovec
[n
++], "\n");
966 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
968 log_debug("Failed to open /dev/console for logging: %s", strerror(errno
));
972 if (writev(fd
, iovec
, n
) < 0)
973 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno
));
975 close_nointr_nofail(fd
);
981 static void read_identifier(const char **buf
, char **identifier
, char **pid
) {
992 p
+= strspn(p
, WHITESPACE
);
993 l
= strcspn(p
, WHITESPACE
);
1002 if (p
[l
-1] == ']') {
1008 t
= strndup(p
+k
+1, l
-k
-2);
1028 *buf
+= strspn(*buf
, WHITESPACE
);
1031 static void process_syslog_message(Server
*s
, const char *buf
, struct ucred
*ucred
, struct timeval
*tv
, const char *label
, size_t label_len
) {
1032 char *message
= NULL
, *syslog_priority
= NULL
, *syslog_facility
= NULL
, *syslog_identifier
= NULL
, *syslog_pid
= NULL
;
1033 struct iovec iovec
[N_IOVEC_META_FIELDS
+ 6];
1035 int priority
= LOG_USER
| LOG_INFO
;
1036 char *identifier
= NULL
, *pid
= NULL
;
1041 if (s
->forward_to_syslog
)
1042 forward_syslog_raw(s
, buf
, ucred
, tv
);
1044 parse_syslog_priority((char**) &buf
, &priority
);
1045 skip_syslog_date((char**) &buf
);
1046 read_identifier(&buf
, &identifier
, &pid
);
1048 if (s
->forward_to_kmsg
)
1049 forward_kmsg(s
, priority
, identifier
, buf
, ucred
);
1051 if (s
->forward_to_console
)
1052 forward_console(s
, identifier
, buf
, ucred
);
1054 IOVEC_SET_STRING(iovec
[n
++], "_TRANSPORT=syslog");
1056 if (asprintf(&syslog_priority
, "PRIORITY=%i", priority
& LOG_PRIMASK
) >= 0)
1057 IOVEC_SET_STRING(iovec
[n
++], syslog_priority
);
1059 if (priority
& LOG_FACMASK
)
1060 if (asprintf(&syslog_facility
, "SYSLOG_FACILITY=%i", LOG_FAC(priority
)) >= 0)
1061 IOVEC_SET_STRING(iovec
[n
++], syslog_facility
);
1064 syslog_identifier
= strappend("SYSLOG_IDENTIFIER=", identifier
);
1065 if (syslog_identifier
)
1066 IOVEC_SET_STRING(iovec
[n
++], syslog_identifier
);
1070 syslog_pid
= strappend("SYSLOG_PID=", pid
);
1072 IOVEC_SET_STRING(iovec
[n
++], syslog_pid
);
1075 message
= strappend("MESSAGE=", buf
);
1077 IOVEC_SET_STRING(iovec
[n
++], message
);
1079 dispatch_message(s
, iovec
, n
, ELEMENTSOF(iovec
), ucred
, tv
, label
, label_len
, priority
);
1084 free(syslog_priority
);
1085 free(syslog_facility
);
1086 free(syslog_identifier
);
1089 static bool valid_user_field(const char *p
, size_t l
) {
1092 /* We kinda enforce POSIX syntax recommendations for
1093 environment variables here, but make a couple of additional
1096 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1098 /* No empty field names */
1102 /* Don't allow names longer than 64 chars */
1106 /* Variables starting with an underscore are protected */
1110 /* Don't allow digits as first character */
1111 if (p
[0] >= '0' && p
[0] <= '9')
1114 /* Only allow A-Z0-9 and '_' */
1115 for (a
= p
; a
< p
+ l
; a
++)
1116 if (!((*a
>= 'A' && *a
<= 'Z') ||
1117 (*a
>= '0' && *a
<= '9') ||
1124 static void process_native_message(
1126 const void *buffer
, size_t buffer_size
,
1127 struct ucred
*ucred
,
1129 const char *label
, size_t label_len
) {
1131 struct iovec
*iovec
= NULL
;
1132 unsigned n
= 0, m
= 0, j
, tn
= (unsigned) -1;
1135 int priority
= LOG_INFO
;
1136 char *identifier
= NULL
, *message
= NULL
;
1139 assert(buffer
|| n
== 0);
1142 remaining
= buffer_size
;
1144 while (remaining
> 0) {
1147 e
= memchr(p
, '\n', remaining
);
1150 /* Trailing noise, let's ignore it, and flush what we collected */
1151 log_debug("Received message with trailing noise, ignoring.");
1156 /* Entry separator */
1157 dispatch_message(s
, iovec
, n
, m
, ucred
, tv
, label
, label_len
, priority
);
1159 priority
= LOG_INFO
;
1166 if (*p
== '.' || *p
== '#') {
1167 /* Ignore control commands for now, and
1169 remaining
-= (e
- p
) + 1;
1174 /* A property follows */
1176 if (n
+N_IOVEC_META_FIELDS
>= m
) {
1180 u
= MAX((n
+N_IOVEC_META_FIELDS
+1) * 2U, 4U);
1181 c
= realloc(iovec
, u
* sizeof(struct iovec
));
1183 log_error("Out of memory");
1191 q
= memchr(p
, '=', e
- p
);
1193 if (valid_user_field(p
, q
- p
)) {
1198 /* If the field name starts with an
1199 * underscore, skip the variable,
1200 * since that indidates a trusted
1202 iovec
[n
].iov_base
= (char*) p
;
1203 iovec
[n
].iov_len
= l
;
1206 /* We need to determine the priority
1207 * of this entry for the rate limiting
1210 memcmp(p
, "PRIORITY=", 9) == 0 &&
1211 p
[9] >= '0' && p
[9] <= '9')
1212 priority
= (priority
& LOG_FACMASK
) | (p
[9] - '0');
1215 memcmp(p
, "SYSLOG_FACILITY=", 16) == 0 &&
1216 p
[16] >= '0' && p
[16] <= '9')
1217 priority
= (priority
& LOG_PRIMASK
) | ((p
[16] - '0') << 3);
1220 memcmp(p
, "SYSLOG_FACILITY=", 16) == 0 &&
1221 p
[16] >= '0' && p
[16] <= '9' &&
1222 p
[17] >= '0' && p
[17] <= '9')
1223 priority
= (priority
& LOG_PRIMASK
) | (((p
[16] - '0')*10 + (p
[17] - '0')) << 3);
1226 memcmp(p
, "SYSLOG_IDENTIFIER=", 11) == 0) {
1229 t
= strndup(p
+ 11, l
- 11);
1234 } else if (l
>= 8 &&
1235 memcmp(p
, "MESSAGE=", 8) == 0) {
1238 t
= strndup(p
+ 8, l
- 8);
1246 remaining
-= (e
- p
) + 1;
1253 if (remaining
< e
- p
+ 1 + sizeof(uint64_t) + 1) {
1254 log_debug("Failed to parse message, ignoring.");
1258 memcpy(&l
, e
+ 1, sizeof(uint64_t));
1261 if (remaining
< e
- p
+ 1 + sizeof(uint64_t) + l
+ 1 ||
1262 e
[1+sizeof(uint64_t)+l
] != '\n') {
1263 log_debug("Failed to parse message, ignoring.");
1267 k
= malloc((e
- p
) + 1 + l
);
1269 log_error("Out of memory");
1273 memcpy(k
, p
, e
- p
);
1275 memcpy(k
+ (e
- p
) + 1, e
+ 1 + sizeof(uint64_t), l
);
1277 if (valid_user_field(p
, e
- p
)) {
1278 iovec
[n
].iov_base
= k
;
1279 iovec
[n
].iov_len
= (e
- p
) + 1 + l
;
1284 remaining
-= (e
- p
) + 1 + sizeof(uint64_t) + l
+ 1;
1285 p
= e
+ 1 + sizeof(uint64_t) + l
+ 1;
1293 IOVEC_SET_STRING(iovec
[tn
], "_TRANSPORT=journal");
1296 if (s
->forward_to_syslog
)
1297 forward_syslog(s
, priority
, identifier
, message
, ucred
, tv
);
1299 if (s
->forward_to_kmsg
)
1300 forward_kmsg(s
, priority
, identifier
, message
, ucred
);
1302 if (s
->forward_to_console
)
1303 forward_console(s
, identifier
, message
, ucred
);
1306 dispatch_message(s
, iovec
, n
, m
, ucred
, tv
, label
, label_len
, priority
);
1309 for (j
= 0; j
< n
; j
++) {
1313 if (iovec
[j
].iov_base
< buffer
||
1314 (const uint8_t*) iovec
[j
].iov_base
>= (const uint8_t*) buffer
+ buffer_size
)
1315 free(iovec
[j
].iov_base
);
1323 static void process_native_file(
1326 struct ucred
*ucred
,
1328 const char *label
, size_t label_len
) {
1337 /* Data is in the passed file, since it didn't fit in a
1338 * datagram. We can't map the file here, since clients might
1339 * then truncate it and trigger a SIGBUS for us. So let's
1340 * stupidly read it */
1342 if (fstat(fd
, &st
) < 0) {
1343 log_error("Failed to stat passed file, ignoring: %m");
1347 if (!S_ISREG(st
.st_mode
)) {
1348 log_error("File passed is not regular. Ignoring.");
1352 if (st
.st_size
<= 0)
1355 if (st
.st_size
> ENTRY_SIZE_MAX
) {
1356 log_error("File passed too large. Ignoring.");
1360 p
= malloc(st
.st_size
);
1362 log_error("Out of memory");
1366 n
= pread(fd
, p
, st
.st_size
, 0);
1368 log_error("Failed to read file, ignoring: %s", strerror(-n
));
1370 process_native_message(s
, p
, n
, ucred
, tv
, label
, label_len
);
1375 static int stdout_stream_log(StdoutStream
*s
, const char *p
) {
1376 struct iovec iovec
[N_IOVEC_META_FIELDS
+ 5];
1377 char *message
= NULL
, *syslog_priority
= NULL
, *syslog_facility
= NULL
, *syslog_identifier
= NULL
;
1381 size_t label_len
= 0;
1389 priority
= s
->priority
;
1391 if (s
->level_prefix
)
1392 parse_syslog_priority((char**) &p
, &priority
);
1394 if (s
->forward_to_syslog
|| s
->server
->forward_to_syslog
)
1395 forward_syslog(s
->server
, fixup_priority(priority
), s
->identifier
, p
, &s
->ucred
, NULL
);
1397 if (s
->forward_to_kmsg
|| s
->server
->forward_to_kmsg
)
1398 forward_kmsg(s
->server
, priority
, s
->identifier
, p
, &s
->ucred
);
1400 if (s
->forward_to_console
|| s
->server
->forward_to_console
)
1401 forward_console(s
->server
, s
->identifier
, p
, &s
->ucred
);
1403 IOVEC_SET_STRING(iovec
[n
++], "_TRANSPORT=stdout");
1405 if (asprintf(&syslog_priority
, "PRIORITY=%i", priority
& LOG_PRIMASK
) >= 0)
1406 IOVEC_SET_STRING(iovec
[n
++], syslog_priority
);
1408 if (priority
& LOG_FACMASK
)
1409 if (asprintf(&syslog_facility
, "SYSLOG_FACILITY=%i", LOG_FAC(priority
)) >= 0)
1410 IOVEC_SET_STRING(iovec
[n
++], syslog_facility
);
1412 if (s
->identifier
) {
1413 syslog_identifier
= strappend("SYSLOG_IDENTIFIER=", s
->identifier
);
1414 if (syslog_identifier
)
1415 IOVEC_SET_STRING(iovec
[n
++], syslog_identifier
);
1418 message
= strappend("MESSAGE=", p
);
1420 IOVEC_SET_STRING(iovec
[n
++], message
);
1423 if (s
->security_context
) {
1424 label
= (char*) s
->security_context
;
1425 label_len
= strlen((char*) s
->security_context
);
1429 dispatch_message(s
->server
, iovec
, n
, ELEMENTSOF(iovec
), &s
->ucred
, NULL
, label
, label_len
, priority
);
1432 free(syslog_priority
);
1433 free(syslog_facility
);
1434 free(syslog_identifier
);
1439 static int stdout_stream_line(StdoutStream
*s
, char *p
) {
1449 case STDOUT_STREAM_IDENTIFIER
:
1451 s
->identifier
= NULL
;
1453 s
->identifier
= strdup(p
);
1454 if (!s
->identifier
) {
1455 log_error("Out of memory");
1460 s
->state
= STDOUT_STREAM_PRIORITY
;
1463 case STDOUT_STREAM_PRIORITY
:
1464 r
= safe_atoi(p
, &s
->priority
);
1465 if (r
< 0 || s
->priority
<= 0 || s
->priority
>= 999) {
1466 log_warning("Failed to parse log priority line.");
1470 s
->state
= STDOUT_STREAM_LEVEL_PREFIX
;
1473 case STDOUT_STREAM_LEVEL_PREFIX
:
1474 r
= parse_boolean(p
);
1476 log_warning("Failed to parse level prefix line.");
1480 s
->level_prefix
= !!r
;
1481 s
->state
= STDOUT_STREAM_FORWARD_TO_SYSLOG
;
1484 case STDOUT_STREAM_FORWARD_TO_SYSLOG
:
1485 r
= parse_boolean(p
);
1487 log_warning("Failed to parse forward to syslog line.");
1491 s
->forward_to_syslog
= !!r
;
1492 s
->state
= STDOUT_STREAM_FORWARD_TO_KMSG
;
1495 case STDOUT_STREAM_FORWARD_TO_KMSG
:
1496 r
= parse_boolean(p
);
1498 log_warning("Failed to parse copy to kmsg line.");
1502 s
->forward_to_kmsg
= !!r
;
1503 s
->state
= STDOUT_STREAM_FORWARD_TO_CONSOLE
;
1506 case STDOUT_STREAM_FORWARD_TO_CONSOLE
:
1507 r
= parse_boolean(p
);
1509 log_warning("Failed to parse copy to console line.");
1513 s
->forward_to_console
= !!r
;
1514 s
->state
= STDOUT_STREAM_RUNNING
;
1517 case STDOUT_STREAM_RUNNING
:
1518 return stdout_stream_log(s
, p
);
1521 assert_not_reached("Unknown stream state");
1524 static int stdout_stream_scan(StdoutStream
*s
, bool force_flush
) {
1532 remaining
= s
->length
;
1537 end
= memchr(p
, '\n', remaining
);
1540 else if (remaining
>= sizeof(s
->buffer
) - 1) {
1541 end
= p
+ sizeof(s
->buffer
) - 1;
1548 r
= stdout_stream_line(s
, p
);
1556 if (force_flush
&& remaining
> 0) {
1558 r
= stdout_stream_line(s
, p
);
1566 if (p
> s
->buffer
) {
1567 memmove(s
->buffer
, p
, remaining
);
1568 s
->length
= remaining
;
1574 static int stdout_stream_process(StdoutStream
*s
) {
1580 l
= read(s
->fd
, s
->buffer
+s
->length
, sizeof(s
->buffer
)-1-s
->length
);
1583 if (errno
== EAGAIN
)
1586 log_warning("Failed to read from stream: %m");
1591 r
= stdout_stream_scan(s
, true);
1599 r
= stdout_stream_scan(s
, false);
1607 static void stdout_stream_free(StdoutStream
*s
) {
1611 assert(s
->server
->n_stdout_streams
> 0);
1612 s
->server
->n_stdout_streams
--;
1613 LIST_REMOVE(StdoutStream
, stdout_stream
, s
->server
->stdout_streams
, s
);
1618 epoll_ctl(s
->server
->epoll_fd
, EPOLL_CTL_DEL
, s
->fd
, NULL
);
1620 close_nointr_nofail(s
->fd
);
1624 if (s
->security_context
)
1625 freecon(s
->security_context
);
1628 free(s
->identifier
);
1632 static int stdout_stream_new(Server
*s
) {
1633 StdoutStream
*stream
;
1636 struct epoll_event ev
;
1640 fd
= accept4(s
->stdout_fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1642 if (errno
== EAGAIN
)
1645 log_error("Failed to accept stdout connection: %m");
1649 if (s
->n_stdout_streams
>= STDOUT_STREAMS_MAX
) {
1650 log_warning("Too many stdout streams, refusing connection.");
1651 close_nointr_nofail(fd
);
1655 stream
= new0(StdoutStream
, 1);
1657 log_error("Out of memory.");
1658 close_nointr_nofail(fd
);
1664 len
= sizeof(stream
->ucred
);
1665 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &stream
->ucred
, &len
) < 0) {
1666 log_error("Failed to determine peer credentials: %m");
1672 if (getpeercon(fd
, &stream
->security_context
) < 0)
1673 log_error("Failed to determine peer security context.");
1676 if (shutdown(fd
, SHUT_WR
) < 0) {
1677 log_error("Failed to shutdown writing side of socket: %m");
1683 ev
.data
.ptr
= stream
;
1684 ev
.events
= EPOLLIN
;
1685 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0) {
1686 log_error("Failed to add stream to event loop: %m");
1692 LIST_PREPEND(StdoutStream
, stdout_stream
, s
->stdout_streams
, stream
);
1693 s
->n_stdout_streams
++;
1698 stdout_stream_free(stream
);
1702 static int parse_kernel_timestamp(char **_p
, usec_t
*t
) {
1713 if (strlen(p
) < 14 || p
[0] != '[' || p
[13] != ']' || p
[6] != '.')
1718 for (i
= 1; i
<= 5; i
++) {
1724 k
= undecchar(p
[i
]);
1731 for (i
= 7; i
<= 12; i
++) {
1734 k
= undecchar(p
[i
]);
1743 *_p
+= strspn(*_p
, WHITESPACE
);
1748 static void proc_kmsg_line(Server
*s
, const char *p
) {
1749 struct iovec iovec
[N_IOVEC_META_FIELDS
+ 7];
1750 char *message
= NULL
, *syslog_priority
= NULL
, *syslog_pid
= NULL
, *syslog_facility
= NULL
, *syslog_identifier
= NULL
, *source_time
= NULL
;
1751 int priority
= LOG_KERN
| LOG_INFO
;
1754 char *identifier
= NULL
, *pid
= NULL
;
1762 parse_syslog_priority((char **) &p
, &priority
);
1764 if (s
->forward_to_kmsg
&& (priority
& LOG_FACMASK
) != LOG_KERN
)
1767 if (parse_kernel_timestamp((char **) &p
, &usec
) > 0) {
1768 if (asprintf(&source_time
, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1769 (unsigned long long) usec
) >= 0)
1770 IOVEC_SET_STRING(iovec
[n
++], source_time
);
1773 IOVEC_SET_STRING(iovec
[n
++], "_TRANSPORT=kernel");
1775 if (asprintf(&syslog_priority
, "PRIORITY=%i", priority
& LOG_PRIMASK
) >= 0)
1776 IOVEC_SET_STRING(iovec
[n
++], syslog_priority
);
1778 if ((priority
& LOG_FACMASK
) == LOG_KERN
) {
1780 if (s
->forward_to_syslog
)
1781 forward_syslog(s
, priority
, "kernel", p
, NULL
, NULL
);
1783 IOVEC_SET_STRING(iovec
[n
++], "SYSLOG_IDENTIFIER=kernel");
1785 read_identifier(&p
, &identifier
, &pid
);
1787 if (s
->forward_to_syslog
)
1788 forward_syslog(s
, priority
, identifier
, p
, NULL
, NULL
);
1791 syslog_identifier
= strappend("SYSLOG_IDENTIFIER=", identifier
);
1792 if (syslog_identifier
)
1793 IOVEC_SET_STRING(iovec
[n
++], syslog_identifier
);
1797 syslog_pid
= strappend("SYSLOG_PID=", pid
);
1799 IOVEC_SET_STRING(iovec
[n
++], syslog_pid
);
1802 if (asprintf(&syslog_facility
, "SYSLOG_FACILITY=%i", LOG_FAC(priority
)) >= 0)
1803 IOVEC_SET_STRING(iovec
[n
++], syslog_facility
);
1806 message
= strappend("MESSAGE=", p
);
1808 IOVEC_SET_STRING(iovec
[n
++], message
);
1810 dispatch_message(s
, iovec
, n
, ELEMENTSOF(iovec
), NULL
, NULL
, NULL
, 0, priority
);
1813 free(syslog_priority
);
1814 free(syslog_identifier
);
1816 free(syslog_facility
);
1822 static void proc_kmsg_scan(Server
*s
) {
1828 p
= s
->proc_kmsg_buffer
;
1829 remaining
= s
->proc_kmsg_length
;
1834 end
= memchr(p
, '\n', remaining
);
1837 else if (remaining
>= sizeof(s
->proc_kmsg_buffer
) - 1) {
1838 end
= p
+ sizeof(s
->proc_kmsg_buffer
) - 1;
1845 proc_kmsg_line(s
, p
);
1851 if (p
> s
->proc_kmsg_buffer
) {
1852 memmove(s
->proc_kmsg_buffer
, p
, remaining
);
1853 s
->proc_kmsg_length
= remaining
;
1857 static int system_journal_open(Server
*s
) {
1863 r
= sd_id128_get_machine(&machine
);
1867 sd_id128_to_string(machine
, ids
);
1869 if (!s
->system_journal
) {
1871 /* First try to create the machine path, but not the prefix */
1872 fn
= strappend("/var/log/journal/", ids
);
1875 (void) mkdir(fn
, 0755);
1878 /* The create the system journal file */
1879 fn
= join("/var/log/journal/", ids
, "/system.journal", NULL
);
1883 r
= journal_file_open_reliably(fn
, O_RDWR
|O_CREAT
, 0640, NULL
, &s
->system_journal
);
1887 journal_default_metrics(&s
->system_metrics
, s
->system_journal
->fd
);
1889 s
->system_journal
->metrics
= s
->system_metrics
;
1890 s
->system_journal
->compress
= s
->compress
;
1892 server_fix_perms(s
, s
->system_journal
, 0);
1895 if (r
!= -ENOENT
&& r
!= -EROFS
)
1896 log_warning("Failed to open system journal: %s", strerror(-r
));
1902 if (!s
->runtime_journal
) {
1904 fn
= join("/run/log/journal/", ids
, "/system.journal", NULL
);
1908 if (s
->system_journal
) {
1910 /* Try to open the runtime journal, but only
1911 * if it already exists, so that we can flush
1912 * it into the system journal */
1914 r
= journal_file_open_reliably(fn
, O_RDWR
, 0640, NULL
, &s
->runtime_journal
);
1919 log_warning("Failed to open runtime journal: %s", strerror(-r
));
1926 /* OK, we really need the runtime journal, so create
1927 * it if necessary. */
1929 (void) mkdir_parents(fn
, 0755);
1930 r
= journal_file_open_reliably(fn
, O_RDWR
|O_CREAT
, 0640, NULL
, &s
->runtime_journal
);
1934 log_error("Failed to open runtime journal: %s", strerror(-r
));
1939 if (s
->runtime_journal
) {
1940 journal_default_metrics(&s
->runtime_metrics
, s
->runtime_journal
->fd
);
1942 s
->runtime_journal
->metrics
= s
->runtime_metrics
;
1943 s
->runtime_journal
->compress
= s
->compress
;
1945 server_fix_perms(s
, s
->runtime_journal
, 0);
1952 static int server_flush_to_var(Server
*s
) {
1953 char path
[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1962 if (!s
->runtime_journal
)
1965 ts
= now(CLOCK_MONOTONIC
);
1966 if (s
->var_available_timestamp
+ RECHECK_VAR_AVAILABLE_USEC
> ts
)
1969 s
->var_available_timestamp
= ts
;
1971 system_journal_open(s
);
1973 if (!s
->system_journal
)
1976 log_info("Flushing to /var...");
1978 r
= sd_id128_get_machine(&machine
);
1980 log_error("Failed to get machine id: %s", strerror(-r
));
1984 r
= sd_journal_open(&j
, SD_JOURNAL_RUNTIME_ONLY
);
1986 log_error("Failed to read runtime journal: %s", strerror(-r
));
1990 SD_JOURNAL_FOREACH(j
) {
1993 f
= j
->current_file
;
1994 assert(f
&& f
->current_offset
> 0);
1996 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, f
->current_offset
, &o
);
1998 log_error("Can't read entry: %s", strerror(-r
));
2002 r
= journal_file_copy_entry(f
, s
->system_journal
, o
, f
->current_offset
, NULL
, NULL
, NULL
);
2004 log_info("Allocation limit reached.");
2006 journal_file_post_change(s
->system_journal
);
2010 r
= journal_file_copy_entry(f
, s
->system_journal
, o
, f
->current_offset
, NULL
, NULL
, NULL
);
2014 log_error("Can't write entry: %s", strerror(-r
));
2020 journal_file_post_change(s
->system_journal
);
2022 journal_file_close(s
->runtime_journal
);
2023 s
->runtime_journal
= NULL
;
2026 sd_id128_to_string(machine
, path
+ 17);
2027 rm_rf(path
, false, true, false);
2033 static int server_read_proc_kmsg(Server
*s
) {
2036 assert(s
->proc_kmsg_fd
>= 0);
2038 l
= read(s
->proc_kmsg_fd
, s
->proc_kmsg_buffer
+ s
->proc_kmsg_length
, sizeof(s
->proc_kmsg_buffer
) - 1 - s
->proc_kmsg_length
);
2041 if (errno
== EAGAIN
|| errno
== EINTR
)
2044 log_error("Failed to read from kernel: %m");
2048 s
->proc_kmsg_length
+= l
;
2054 static int server_flush_proc_kmsg(Server
*s
) {
2059 if (s
->proc_kmsg_fd
< 0)
2062 log_info("Flushing /proc/kmsg...");
2065 r
= server_read_proc_kmsg(s
);
2076 static int process_event(Server
*s
, struct epoll_event
*ev
) {
2079 if (ev
->data
.fd
== s
->signal_fd
) {
2080 struct signalfd_siginfo sfsi
;
2083 if (ev
->events
!= EPOLLIN
) {
2084 log_info("Got invalid event from epoll.");
2088 n
= read(s
->signal_fd
, &sfsi
, sizeof(sfsi
));
2089 if (n
!= sizeof(sfsi
)) {
2094 if (errno
== EINTR
|| errno
== EAGAIN
)
2100 if (sfsi
.ssi_signo
== SIGUSR1
) {
2101 server_flush_to_var(s
);
2105 log_debug("Received SIG%s", signal_to_string(sfsi
.ssi_signo
));
2108 } else if (ev
->data
.fd
== s
->proc_kmsg_fd
) {
2111 if (ev
->events
!= EPOLLIN
) {
2112 log_info("Got invalid event from epoll.");
2116 r
= server_read_proc_kmsg(s
);
2122 } else if (ev
->data
.fd
== s
->native_fd
||
2123 ev
->data
.fd
== s
->syslog_fd
) {
2125 if (ev
->events
!= EPOLLIN
) {
2126 log_info("Got invalid event from epoll.");
2131 struct msghdr msghdr
;
2133 struct ucred
*ucred
= NULL
;
2134 struct timeval
*tv
= NULL
;
2135 struct cmsghdr
*cmsg
;
2137 size_t label_len
= 0;
2139 struct cmsghdr cmsghdr
;
2140 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
)) +
2141 CMSG_SPACE(sizeof(struct timeval
)) +
2142 CMSG_SPACE(sizeof(int)) +
2143 CMSG_SPACE(PAGE_SIZE
)]; /* selinux label */
2150 if (ioctl(ev
->data
.fd
, SIOCINQ
, &v
) < 0) {
2151 log_error("SIOCINQ failed: %m");
2155 if (s
->buffer_size
< (size_t) v
) {
2159 l
= MAX(LINE_MAX
+ (size_t) v
, s
->buffer_size
* 2);
2160 b
= realloc(s
->buffer
, l
+1);
2163 log_error("Couldn't increase buffer.");
2172 iovec
.iov_base
= s
->buffer
;
2173 iovec
.iov_len
= s
->buffer_size
;
2177 msghdr
.msg_iov
= &iovec
;
2178 msghdr
.msg_iovlen
= 1;
2179 msghdr
.msg_control
= &control
;
2180 msghdr
.msg_controllen
= sizeof(control
);
2182 n
= recvmsg(ev
->data
.fd
, &msghdr
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
2185 if (errno
== EINTR
|| errno
== EAGAIN
)
2188 log_error("recvmsg() failed: %m");
2192 for (cmsg
= CMSG_FIRSTHDR(&msghdr
); cmsg
; cmsg
= CMSG_NXTHDR(&msghdr
, cmsg
)) {
2194 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
2195 cmsg
->cmsg_type
== SCM_CREDENTIALS
&&
2196 cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)))
2197 ucred
= (struct ucred
*) CMSG_DATA(cmsg
);
2198 else if (cmsg
->cmsg_level
== SOL_SOCKET
&&
2199 cmsg
->cmsg_type
== SCM_SECURITY
) {
2200 label
= (char*) CMSG_DATA(cmsg
);
2201 label_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
2202 } else if (cmsg
->cmsg_level
== SOL_SOCKET
&&
2203 cmsg
->cmsg_type
== SO_TIMESTAMP
&&
2204 cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct timeval
)))
2205 tv
= (struct timeval
*) CMSG_DATA(cmsg
);
2206 else if (cmsg
->cmsg_level
== SOL_SOCKET
&&
2207 cmsg
->cmsg_type
== SCM_RIGHTS
) {
2208 fds
= (int*) CMSG_DATA(cmsg
);
2209 n_fds
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
2213 if (ev
->data
.fd
== s
->syslog_fd
) {
2216 if (n
> 0 && n_fds
== 0) {
2217 e
= memchr(s
->buffer
, '\n', n
);
2223 process_syslog_message(s
, strstrip(s
->buffer
), ucred
, tv
, label
, label_len
);
2224 } else if (n_fds
> 0)
2225 log_warning("Got file descriptors via syslog socket. Ignoring.");
2228 if (n
> 0 && n_fds
== 0)
2229 process_native_message(s
, s
->buffer
, n
, ucred
, tv
, label
, label_len
);
2230 else if (n
== 0 && n_fds
== 1)
2231 process_native_file(s
, fds
[0], ucred
, tv
, label
, label_len
);
2233 log_warning("Got too many file descriptors via native socket. Ignoring.");
2236 close_many(fds
, n_fds
);
2241 } else if (ev
->data
.fd
== s
->stdout_fd
) {
2243 if (ev
->events
!= EPOLLIN
) {
2244 log_info("Got invalid event from epoll.");
2248 stdout_stream_new(s
);
2252 StdoutStream
*stream
;
2254 if ((ev
->events
|EPOLLIN
|EPOLLHUP
) != (EPOLLIN
|EPOLLHUP
)) {
2255 log_info("Got invalid event from epoll.");
2259 /* If it is none of the well-known fds, it must be an
2260 * stdout stream fd. Note that this is a bit ugly here
2261 * (since we rely that none of the well-known fds
2262 * could be interpreted as pointer), but nonetheless
2263 * safe, since the well-known fds would never get an
2264 * fd > 4096, i.e. beyond the first memory page */
2266 stream
= ev
->data
.ptr
;
2268 if (stdout_stream_process(stream
) <= 0)
2269 stdout_stream_free(stream
);
2274 log_error("Unknown event.");
2278 static int open_syslog_socket(Server
*s
) {
2279 union sockaddr_union sa
;
2281 struct epoll_event ev
;
2285 if (s
->syslog_fd
< 0) {
2287 s
->syslog_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
2288 if (s
->syslog_fd
< 0) {
2289 log_error("socket() failed: %m");
2294 sa
.un
.sun_family
= AF_UNIX
;
2295 strncpy(sa
.un
.sun_path
, "/dev/log", sizeof(sa
.un
.sun_path
));
2297 unlink(sa
.un
.sun_path
);
2299 r
= bind(s
->syslog_fd
, &sa
.sa
, offsetof(union sockaddr_union
, un
.sun_path
) + strlen(sa
.un
.sun_path
));
2301 log_error("bind() failed: %m");
2305 chmod(sa
.un
.sun_path
, 0666);
2307 fd_nonblock(s
->syslog_fd
, 1);
2310 r
= setsockopt(s
->syslog_fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
));
2312 log_error("SO_PASSCRED failed: %m");
2318 r
= setsockopt(s
->syslog_fd
, SOL_SOCKET
, SO_PASSSEC
, &one
, sizeof(one
));
2320 log_warning("SO_PASSSEC failed: %m");
2324 r
= setsockopt(s
->syslog_fd
, SOL_SOCKET
, SO_TIMESTAMP
, &one
, sizeof(one
));
2326 log_error("SO_TIMESTAMP failed: %m");
2331 ev
.events
= EPOLLIN
;
2332 ev
.data
.fd
= s
->syslog_fd
;
2333 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->syslog_fd
, &ev
) < 0) {
2334 log_error("Failed to add syslog server fd to epoll object: %m");
2341 static int open_native_socket(Server
*s
) {
2342 union sockaddr_union sa
;
2344 struct epoll_event ev
;
2348 if (s
->native_fd
< 0) {
2350 s
->native_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
2351 if (s
->native_fd
< 0) {
2352 log_error("socket() failed: %m");
2357 sa
.un
.sun_family
= AF_UNIX
;
2358 strncpy(sa
.un
.sun_path
, "/run/systemd/journal/socket", sizeof(sa
.un
.sun_path
));
2360 unlink(sa
.un
.sun_path
);
2362 r
= bind(s
->native_fd
, &sa
.sa
, offsetof(union sockaddr_union
, un
.sun_path
) + strlen(sa
.un
.sun_path
));
2364 log_error("bind() failed: %m");
2368 chmod(sa
.un
.sun_path
, 0666);
2370 fd_nonblock(s
->native_fd
, 1);
2373 r
= setsockopt(s
->native_fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
));
2375 log_error("SO_PASSCRED failed: %m");
2381 r
= setsockopt(s
->syslog_fd
, SOL_SOCKET
, SO_PASSSEC
, &one
, sizeof(one
));
2383 log_warning("SO_PASSSEC failed: %m");
2387 r
= setsockopt(s
->native_fd
, SOL_SOCKET
, SO_TIMESTAMP
, &one
, sizeof(one
));
2389 log_error("SO_TIMESTAMP failed: %m");
2394 ev
.events
= EPOLLIN
;
2395 ev
.data
.fd
= s
->native_fd
;
2396 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->native_fd
, &ev
) < 0) {
2397 log_error("Failed to add native server fd to epoll object: %m");
2404 static int open_stdout_socket(Server
*s
) {
2405 union sockaddr_union sa
;
2407 struct epoll_event ev
;
2411 if (s
->stdout_fd
< 0) {
2413 s
->stdout_fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
2414 if (s
->stdout_fd
< 0) {
2415 log_error("socket() failed: %m");
2420 sa
.un
.sun_family
= AF_UNIX
;
2421 strncpy(sa
.un
.sun_path
, "/run/systemd/journal/stdout", sizeof(sa
.un
.sun_path
));
2423 unlink(sa
.un
.sun_path
);
2425 r
= bind(s
->stdout_fd
, &sa
.sa
, offsetof(union sockaddr_union
, un
.sun_path
) + strlen(sa
.un
.sun_path
));
2427 log_error("bind() failed: %m");
2431 chmod(sa
.un
.sun_path
, 0666);
2433 if (listen(s
->stdout_fd
, SOMAXCONN
) < 0) {
2434 log_error("liste() failed: %m");
2438 fd_nonblock(s
->stdout_fd
, 1);
2441 ev
.events
= EPOLLIN
;
2442 ev
.data
.fd
= s
->stdout_fd
;
2443 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->stdout_fd
, &ev
) < 0) {
2444 log_error("Failed to add stdout server fd to epoll object: %m");
2451 static int open_proc_kmsg(Server
*s
) {
2452 struct epoll_event ev
;
2456 if (!s
->import_proc_kmsg
)
2460 s
->proc_kmsg_fd
= open("/proc/kmsg", O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
2461 if (s
->proc_kmsg_fd
< 0) {
2462 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2467 ev
.events
= EPOLLIN
;
2468 ev
.data
.fd
= s
->proc_kmsg_fd
;
2469 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->proc_kmsg_fd
, &ev
) < 0) {
2470 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2477 static int open_signalfd(Server
*s
) {
2479 struct epoll_event ev
;
2483 assert_se(sigemptyset(&mask
) == 0);
2484 sigset_add_many(&mask
, SIGINT
, SIGTERM
, SIGUSR1
, -1);
2485 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) == 0);
2487 s
->signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
2488 if (s
->signal_fd
< 0) {
2489 log_error("signalfd(): %m");
2494 ev
.events
= EPOLLIN
;
2495 ev
.data
.fd
= s
->signal_fd
;
2497 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->signal_fd
, &ev
) < 0) {
2498 log_error("epoll_ctl(): %m");
2505 static int server_parse_proc_cmdline(Server
*s
) {
2506 char *line
, *w
, *state
;
2510 if (detect_container(NULL
) > 0)
2513 r
= read_one_line_file("/proc/cmdline", &line
);
2515 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r
));
2519 FOREACH_WORD_QUOTED(w
, l
, line
, state
) {
2522 word
= strndup(w
, l
);
2528 if (startswith(word
, "systemd_journald.forward_to_syslog=")) {
2529 r
= parse_boolean(word
+ 35);
2531 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word
+ 35);
2533 s
->forward_to_syslog
= r
;
2534 } else if (startswith(word
, "systemd_journald.forward_to_kmsg=")) {
2535 r
= parse_boolean(word
+ 33);
2537 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word
+ 33);
2539 s
->forward_to_kmsg
= r
;
2540 } else if (startswith(word
, "systemd_journald.forward_to_console=")) {
2541 r
= parse_boolean(word
+ 36);
2543 log_warning("Failed to parse forward to console switch %s. Ignoring.", word
+ 36);
2545 s
->forward_to_console
= r
;
2558 static int server_parse_config_file(Server
*s
) {
2565 fn
= "/etc/systemd/systemd-journald.conf";
2566 f
= fopen(fn
, "re");
2568 if (errno
== ENOENT
)
2571 log_warning("Failed to open configuration file %s: %m", fn
);
2575 r
= config_parse(fn
, f
, "Journal\0", config_item_perf_lookup
, (void*) journald_gperf_lookup
, false, s
);
2577 log_warning("Failed to parse configuration file: %s", strerror(-r
));
2584 static int server_init(Server
*s
) {
2590 s
->syslog_fd
= s
->native_fd
= s
->stdout_fd
= s
->signal_fd
= s
->epoll_fd
= s
->proc_kmsg_fd
= -1;
2593 s
->rate_limit_interval
= DEFAULT_RATE_LIMIT_INTERVAL
;
2594 s
->rate_limit_burst
= DEFAULT_RATE_LIMIT_BURST
;
2596 s
->forward_to_syslog
= true;
2597 s
->import_proc_kmsg
= true;
2599 memset(&s
->system_metrics
, 0xFF, sizeof(s
->system_metrics
));
2600 memset(&s
->runtime_metrics
, 0xFF, sizeof(s
->runtime_metrics
));
2602 server_parse_config_file(s
);
2603 server_parse_proc_cmdline(s
);
2605 s
->user_journals
= hashmap_new(trivial_hash_func
, trivial_compare_func
);
2606 if (!s
->user_journals
) {
2607 log_error("Out of memory.");
2611 s
->epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
2612 if (s
->epoll_fd
< 0) {
2613 log_error("Failed to create epoll object: %m");
2617 n
= sd_listen_fds(true);
2619 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n
));
2623 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
2625 if (sd_is_socket_unix(fd
, SOCK_DGRAM
, -1, "/run/systemd/journal/socket", 0) > 0) {
2627 if (s
->native_fd
>= 0) {
2628 log_error("Too many native sockets passed.");
2634 } else if (sd_is_socket_unix(fd
, SOCK_STREAM
, 1, "/run/systemd/journal/stdout", 0) > 0) {
2636 if (s
->stdout_fd
>= 0) {
2637 log_error("Too many stdout sockets passed.");
2643 } else if (sd_is_socket_unix(fd
, SOCK_DGRAM
, -1, "/dev/log", 0) > 0) {
2645 if (s
->syslog_fd
>= 0) {
2646 log_error("Too many /dev/log sockets passed.");
2653 log_error("Unknown socket passed.");
2658 r
= open_syslog_socket(s
);
2662 r
= open_native_socket(s
);
2666 r
= open_stdout_socket(s
);
2670 r
= open_proc_kmsg(s
);
2674 r
= open_signalfd(s
);
2678 s
->rate_limit
= journal_rate_limit_new(s
->rate_limit_interval
, s
->rate_limit_burst
);
2682 r
= system_journal_open(s
);
2689 static void server_done(Server
*s
) {
2693 while (s
->stdout_streams
)
2694 stdout_stream_free(s
->stdout_streams
);
2696 if (s
->system_journal
)
2697 journal_file_close(s
->system_journal
);
2699 if (s
->runtime_journal
)
2700 journal_file_close(s
->runtime_journal
);
2702 while ((f
= hashmap_steal_first(s
->user_journals
)))
2703 journal_file_close(f
);
2705 hashmap_free(s
->user_journals
);
2707 if (s
->epoll_fd
>= 0)
2708 close_nointr_nofail(s
->epoll_fd
);
2710 if (s
->signal_fd
>= 0)
2711 close_nointr_nofail(s
->signal_fd
);
2713 if (s
->syslog_fd
>= 0)
2714 close_nointr_nofail(s
->syslog_fd
);
2716 if (s
->native_fd
>= 0)
2717 close_nointr_nofail(s
->native_fd
);
2719 if (s
->stdout_fd
>= 0)
2720 close_nointr_nofail(s
->stdout_fd
);
2722 if (s
->proc_kmsg_fd
>= 0)
2723 close_nointr_nofail(s
->proc_kmsg_fd
);
2726 journal_rate_limit_free(s
->rate_limit
);
2731 int main(int argc
, char *argv
[]) {
2735 /* if (getppid() != 1) { */
2736 /* log_error("This program should be invoked by init only."); */
2737 /* return EXIT_FAILURE; */
2741 log_error("This program does not take arguments.");
2742 return EXIT_FAILURE
;
2745 log_set_target(LOG_TARGET_CONSOLE
);
2746 log_parse_environment();
2751 r
= server_init(&server
);
2755 server_vacuum(&server
);
2756 server_flush_to_var(&server
);
2757 server_flush_proc_kmsg(&server
);
2759 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2760 driver_message(&server
, SD_MESSAGE_JOURNAL_START
, "Journal started");
2764 "STATUS=Processing requests...");
2767 struct epoll_event event
;
2769 r
= epoll_wait(server
.epoll_fd
, &event
, 1, -1);
2775 log_error("epoll_wait() failed: %m");
2781 r
= process_event(&server
, &event
);
2788 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2789 driver_message(&server
, SD_MESSAGE_JOURNAL_STOP
, "Journal stopped");
2793 "STATUS=Shutting down...");
2795 server_done(&server
);
2797 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;