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 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
177 avail = sum >= m->max_use ? 0 : m->max_use - sum;
179 ss_avail = ss.f_bsize * ss.f_bavail;
181 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
183 if (ss_avail < avail)
186 s->cached_available_space = avail;
187 s->cached_available_space_timestamp = ts;
195 static void server_read_file_gid(Server *s) {
196 const char *adm = "adm";
201 if (s->file_gid_valid)
204 r = get_group_creds(&adm, &s->file_gid);
206 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
208 /* if we couldn't read the gid, then it will be 0, but that's
209 * fine and we shouldn't try to resolve the group again, so
210 * let's just pretend it worked right-away. */
211 s->file_gid_valid = true;
214 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
219 acl_permset_t permset;
224 server_read_file_gid(s);
226 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
228 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
234 acl = acl_get_fd(f->fd);
236 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
240 r = acl_find_uid(acl, uid, &entry);
243 if (acl_create_entry(&acl, &entry) < 0 ||
244 acl_set_tag_type(entry, ACL_USER) < 0 ||
245 acl_set_qualifier(entry, &uid) < 0) {
246 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
251 if (acl_get_permset(entry, &permset) < 0 ||
252 acl_add_perm(permset, ACL_READ) < 0 ||
253 acl_calc_mask(&acl) < 0) {
254 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
258 if (acl_set_fd(f->fd, acl) < 0)
259 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
266 static JournalFile* find_journal(Server *s, uid_t uid) {
275 /* We split up user logs only on /var, not on /run. If the
276 * runtime file is open, we write to it exclusively, in order
277 * to guarantee proper order as soon as we flush /run to
278 * /var and close the runtime file. */
280 if (s->runtime_journal)
281 return s->runtime_journal;
284 return s->system_journal;
286 r = sd_id128_get_machine(&machine);
288 return s->system_journal;
290 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
294 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
295 return s->system_journal;
297 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
298 /* Too many open? Then let's close one */
299 f = hashmap_steal_first(s->user_journals);
301 journal_file_close(f);
304 r = journal_file_open_reliably(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
308 return s->system_journal;
310 server_fix_perms(s, f, uid);
312 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
314 journal_file_close(f);
315 return s->system_journal;
321 static void server_rotate(Server *s) {
327 log_info("Rotating...");
329 if (s->runtime_journal) {
330 r = journal_file_rotate(&s->runtime_journal);
332 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
335 if (s->system_journal) {
336 r = journal_file_rotate(&s->system_journal);
338 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
341 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
342 r = journal_file_rotate(&f);
344 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
346 hashmap_replace(s->user_journals, k, f);
350 static void server_vacuum(Server *s) {
356 log_info("Vacuuming...");
358 r = sd_id128_get_machine(&machine);
360 log_error("Failed to get machine ID: %s", strerror(-r));
364 sd_id128_to_string(machine, ids);
366 if (s->system_journal) {
367 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
368 log_error("Out of memory.");
372 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
373 if (r < 0 && r != -ENOENT)
374 log_error("Failed to vacuum %s: %s", p, strerror(-r));
379 if (s->runtime_journal) {
380 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
381 log_error("Out of memory.");
385 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
386 if (r < 0 && r != -ENOENT)
387 log_error("Failed to vacuum %s: %s", p, strerror(-r));
391 s->cached_available_space_timestamp = 0;
394 static char *shortened_cgroup_path(pid_t pid) {
396 char *process_path, *init_path, *path;
400 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
404 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
410 if (endswith(init_path, "/system"))
411 init_path[strlen(init_path) - 7] = 0;
412 else if (streq(init_path, "/"))
415 if (startswith(process_path, init_path)) {
418 p = strdup(process_path + strlen(init_path));
436 static void dispatch_message_real(
438 struct iovec *iovec, unsigned n, unsigned m,
441 const char *label, size_t label_len) {
443 char *pid = NULL, *uid = NULL, *gid = NULL,
444 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
445 *comm = NULL, *cmdline = NULL, *hostname = NULL,
446 *audit_session = NULL, *audit_loginuid = NULL,
447 *exe = NULL, *cgroup = NULL, *session = NULL,
448 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
454 uid_t loginuid = 0, realuid = 0;
456 bool vacuumed = false;
461 assert(n + N_IOVEC_META_FIELDS <= m);
467 realuid = ucred->uid;
469 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
470 IOVEC_SET_STRING(iovec[n++], pid);
472 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
473 IOVEC_SET_STRING(iovec[n++], uid);
475 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
476 IOVEC_SET_STRING(iovec[n++], gid);
478 r = get_process_comm(ucred->pid, &t);
480 comm = strappend("_COMM=", t);
484 IOVEC_SET_STRING(iovec[n++], comm);
487 r = get_process_exe(ucred->pid, &t);
489 exe = strappend("_EXE=", t);
493 IOVEC_SET_STRING(iovec[n++], exe);
496 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
498 cmdline = strappend("_CMDLINE=", t);
502 IOVEC_SET_STRING(iovec[n++], cmdline);
505 r = audit_session_from_pid(ucred->pid, &audit);
507 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
508 IOVEC_SET_STRING(iovec[n++], audit_session);
510 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
512 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
513 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
515 t = shortened_cgroup_path(ucred->pid);
517 cgroup = strappend("_SYSTEMD_CGROUP=", t);
521 IOVEC_SET_STRING(iovec[n++], cgroup);
524 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
525 session = strappend("_SYSTEMD_SESSION=", t);
529 IOVEC_SET_STRING(iovec[n++], session);
532 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
533 unit = strappend("_SYSTEMD_UNIT=", t);
537 IOVEC_SET_STRING(iovec[n++], unit);
540 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
541 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
542 IOVEC_SET_STRING(iovec[n++], owner_uid);
546 selinux_context = malloc(sizeof("_SELINUX_CONTEXT=") + label_len);
547 if (selinux_context) {
548 memcpy(selinux_context, "_SELINUX_CONTEXT=", sizeof("_SELINUX_CONTEXT=")-1);
549 memcpy(selinux_context+sizeof("_SELINUX_CONTEXT=")-1, label, label_len);
550 selinux_context[sizeof("_SELINUX_CONTEXT=")-1+label_len] = 0;
551 IOVEC_SET_STRING(iovec[n++], selinux_context);
554 security_context_t con;
556 if (getpidcon(ucred->pid, &con) >= 0) {
557 selinux_context = strappend("_SELINUX_CONTEXT=", con);
559 IOVEC_SET_STRING(iovec[n++], selinux_context);
568 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
569 (unsigned long long) timeval_load(tv)) >= 0)
570 IOVEC_SET_STRING(iovec[n++], source_time);
573 /* Note that strictly speaking storing the boot id here is
574 * redundant since the entry includes this in-line
575 * anyway. However, we need this indexed, too. */
576 r = sd_id128_get_boot(&id);
578 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
579 IOVEC_SET_STRING(iovec[n++], boot_id);
581 r = sd_id128_get_machine(&id);
583 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
584 IOVEC_SET_STRING(iovec[n++], machine_id);
586 t = gethostname_malloc();
588 hostname = strappend("_HOSTNAME=", t);
591 IOVEC_SET_STRING(iovec[n++], hostname);
596 server_flush_to_var(s);
599 f = find_journal(s, realuid == 0 ? 0 : loginuid);
601 log_warning("Dropping message, as we can't find a place to store the data.");
603 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
605 if ((r == -EBADMSG || r == -E2BIG) && !vacuumed) {
608 log_info("Allocation limit reached, rotating.");
610 log_warning("Journal file corrupted, rotating.");
616 log_info("Retrying write.");
621 log_error("Failed to write entry, ignoring: %s", strerror(-r));
635 free(audit_loginuid);
640 free(selinux_context);
643 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
644 char mid[11 + 32 + 1];
645 char buffer[16 + LINE_MAX + 1];
646 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
654 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
655 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
657 memcpy(buffer, "MESSAGE=", 8);
658 va_start(ap, format);
659 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
661 char_array_0(buffer);
662 IOVEC_SET_STRING(iovec[n++], buffer);
664 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
666 IOVEC_SET_STRING(iovec[n++], mid);
669 ucred.pid = getpid();
670 ucred.uid = getuid();
671 ucred.gid = getgid();
673 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0);
676 static void dispatch_message(Server *s,
677 struct iovec *iovec, unsigned n, unsigned m,
680 const char *label, size_t label_len,
683 char *path = NULL, *c;
686 assert(iovec || n == 0);
694 path = shortened_cgroup_path(ucred->pid);
698 /* example: /user/lennart/3/foobar
699 * /system/dbus.service/foobar
701 * So let's cut of everything past the third /, since that is
702 * wher user directories start */
704 c = strchr(path, '/');
706 c = strchr(c+1, '/');
708 c = strchr(c+1, '/');
714 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
721 /* Write a suppression message if we suppressed something */
723 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
728 dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len);
731 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
732 struct msghdr msghdr;
733 struct cmsghdr *cmsg;
735 struct cmsghdr cmsghdr;
736 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
738 union sockaddr_union sa;
745 msghdr.msg_iov = (struct iovec*) iovec;
746 msghdr.msg_iovlen = n_iovec;
749 sa.un.sun_family = AF_UNIX;
750 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
751 msghdr.msg_name = &sa;
752 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
756 msghdr.msg_control = &control;
757 msghdr.msg_controllen = sizeof(control);
759 cmsg = CMSG_FIRSTHDR(&msghdr);
760 cmsg->cmsg_level = SOL_SOCKET;
761 cmsg->cmsg_type = SCM_CREDENTIALS;
762 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
763 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
764 msghdr.msg_controllen = cmsg->cmsg_len;
767 /* Forward the syslog message we received via /dev/log to
768 * /run/systemd/syslog. Unfortunately we currently can't set
769 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
771 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
774 /* The socket is full? I guess the syslog implementation is
775 * too slow, and we shouldn't wait for that... */
779 if (ucred && errno == ESRCH) {
782 /* Hmm, presumably the sender process vanished
783 * by now, so let's fix it as good as we
788 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
790 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
797 log_debug("Failed to forward syslog message: %m");
800 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
806 IOVEC_SET_STRING(iovec, buffer);
807 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
810 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
811 struct iovec iovec[5];
812 char header_priority[6], header_time[64], header_pid[16];
816 char *ident_buf = NULL;
819 assert(priority >= 0);
820 assert(priority <= 999);
823 /* First: priority field */
824 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
825 char_array_0(header_priority);
826 IOVEC_SET_STRING(iovec[n++], header_priority);
828 /* Second: timestamp */
829 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
833 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
835 IOVEC_SET_STRING(iovec[n++], header_time);
837 /* Third: identifier and PID */
840 get_process_comm(ucred->pid, &ident_buf);
841 identifier = ident_buf;
844 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
845 char_array_0(header_pid);
848 IOVEC_SET_STRING(iovec[n++], identifier);
850 IOVEC_SET_STRING(iovec[n++], header_pid);
851 } else if (identifier) {
852 IOVEC_SET_STRING(iovec[n++], identifier);
853 IOVEC_SET_STRING(iovec[n++], ": ");
856 /* Fourth: message */
857 IOVEC_SET_STRING(iovec[n++], message);
859 forward_syslog_iovec(s, iovec, n, ucred, tv);
864 static int fixup_priority(int priority) {
866 if ((priority & LOG_FACMASK) == 0)
867 return (priority & LOG_PRIMASK) | LOG_USER;
872 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
873 struct iovec iovec[5];
874 char header_priority[6], header_pid[16];
876 char *ident_buf = NULL;
880 assert(priority >= 0);
881 assert(priority <= 999);
884 /* Never allow messages with kernel facility to be written to
885 * kmsg, regardless where the data comes from. */
886 priority = fixup_priority(priority);
888 /* First: priority field */
889 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
890 char_array_0(header_priority);
891 IOVEC_SET_STRING(iovec[n++], header_priority);
893 /* Second: identifier and PID */
896 get_process_comm(ucred->pid, &ident_buf);
897 identifier = ident_buf;
900 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
901 char_array_0(header_pid);
904 IOVEC_SET_STRING(iovec[n++], identifier);
906 IOVEC_SET_STRING(iovec[n++], header_pid);
907 } else if (identifier) {
908 IOVEC_SET_STRING(iovec[n++], identifier);
909 IOVEC_SET_STRING(iovec[n++], ": ");
912 /* Fourth: message */
913 IOVEC_SET_STRING(iovec[n++], message);
914 IOVEC_SET_STRING(iovec[n++], "\n");
916 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
918 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
922 if (writev(fd, iovec, n) < 0)
923 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
925 close_nointr_nofail(fd);
931 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
932 struct iovec iovec[4];
935 char *ident_buf = NULL;
940 /* First: identifier and PID */
943 get_process_comm(ucred->pid, &ident_buf);
944 identifier = ident_buf;
947 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
948 char_array_0(header_pid);
951 IOVEC_SET_STRING(iovec[n++], identifier);
953 IOVEC_SET_STRING(iovec[n++], header_pid);
954 } else if (identifier) {
955 IOVEC_SET_STRING(iovec[n++], identifier);
956 IOVEC_SET_STRING(iovec[n++], ": ");
960 IOVEC_SET_STRING(iovec[n++], message);
961 IOVEC_SET_STRING(iovec[n++], "\n");
963 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
965 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
969 if (writev(fd, iovec, n) < 0)
970 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
972 close_nointr_nofail(fd);
978 static void read_identifier(const char **buf, char **identifier, char **pid) {
989 p += strspn(p, WHITESPACE);
990 l = strcspn(p, WHITESPACE);
1005 t = strndup(p+k+1, l-k-2);
1025 *buf += strspn(*buf, WHITESPACE);
1028 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) {
1029 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1030 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1032 int priority = LOG_USER | LOG_INFO;
1033 char *identifier = NULL, *pid = NULL;
1038 if (s->forward_to_syslog)
1039 forward_syslog_raw(s, buf, ucred, tv);
1041 parse_syslog_priority((char**) &buf, &priority);
1042 skip_syslog_date((char**) &buf);
1043 read_identifier(&buf, &identifier, &pid);
1045 if (s->forward_to_kmsg)
1046 forward_kmsg(s, priority, identifier, buf, ucred);
1048 if (s->forward_to_console)
1049 forward_console(s, identifier, buf, ucred);
1051 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1053 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1054 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1056 if (priority & LOG_FACMASK)
1057 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1058 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1061 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1062 if (syslog_identifier)
1063 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1067 syslog_pid = strappend("SYSLOG_PID=", pid);
1069 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1072 message = strappend("MESSAGE=", buf);
1074 IOVEC_SET_STRING(iovec[n++], message);
1076 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, label, label_len, priority);
1081 free(syslog_priority);
1082 free(syslog_facility);
1083 free(syslog_identifier);
1086 static bool valid_user_field(const char *p, size_t l) {
1089 /* We kinda enforce POSIX syntax recommendations for
1090 environment variables here, but make a couple of additional
1093 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1095 /* No empty field names */
1099 /* Don't allow names longer than 64 chars */
1103 /* Variables starting with an underscore are protected */
1107 /* Don't allow digits as first character */
1108 if (p[0] >= '0' && p[0] <= '9')
1111 /* Only allow A-Z0-9 and '_' */
1112 for (a = p; a < p + l; a++)
1113 if (!((*a >= 'A' && *a <= 'Z') ||
1114 (*a >= '0' && *a <= '9') ||
1121 static void process_native_message(
1123 const void *buffer, size_t buffer_size,
1124 struct ucred *ucred,
1126 const char *label, size_t label_len) {
1128 struct iovec *iovec = NULL;
1129 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1132 int priority = LOG_INFO;
1133 char *identifier = NULL, *message = NULL;
1136 assert(buffer || n == 0);
1139 remaining = buffer_size;
1141 while (remaining > 0) {
1144 e = memchr(p, '\n', remaining);
1147 /* Trailing noise, let's ignore it, and flush what we collected */
1148 log_debug("Received message with trailing noise, ignoring.");
1153 /* Entry separator */
1154 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1156 priority = LOG_INFO;
1163 if (*p == '.' || *p == '#') {
1164 /* Ignore control commands for now, and
1166 remaining -= (e - p) + 1;
1171 /* A property follows */
1173 if (n+N_IOVEC_META_FIELDS >= m) {
1177 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1178 c = realloc(iovec, u * sizeof(struct iovec));
1180 log_error("Out of memory");
1188 q = memchr(p, '=', e - p);
1190 if (valid_user_field(p, q - p)) {
1195 /* If the field name starts with an
1196 * underscore, skip the variable,
1197 * since that indidates a trusted
1199 iovec[n].iov_base = (char*) p;
1200 iovec[n].iov_len = l;
1203 /* We need to determine the priority
1204 * of this entry for the rate limiting
1207 memcmp(p, "PRIORITY=", 9) == 0 &&
1208 p[9] >= '0' && p[9] <= '9')
1209 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1212 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1213 p[16] >= '0' && p[16] <= '9')
1214 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1217 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1218 p[16] >= '0' && p[16] <= '9' &&
1219 p[17] >= '0' && p[17] <= '9')
1220 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1223 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1226 t = strndup(p + 11, l - 11);
1231 } else if (l >= 8 &&
1232 memcmp(p, "MESSAGE=", 8) == 0) {
1235 t = strndup(p + 8, l - 8);
1243 remaining -= (e - p) + 1;
1250 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1251 log_debug("Failed to parse message, ignoring.");
1255 memcpy(&l, e + 1, sizeof(uint64_t));
1258 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1259 e[1+sizeof(uint64_t)+l] != '\n') {
1260 log_debug("Failed to parse message, ignoring.");
1264 k = malloc((e - p) + 1 + l);
1266 log_error("Out of memory");
1270 memcpy(k, p, e - p);
1272 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1274 if (valid_user_field(p, e - p)) {
1275 iovec[n].iov_base = k;
1276 iovec[n].iov_len = (e - p) + 1 + l;
1281 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1282 p = e + 1 + sizeof(uint64_t) + l + 1;
1290 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1293 if (s->forward_to_syslog)
1294 forward_syslog(s, priority, identifier, message, ucred, tv);
1296 if (s->forward_to_kmsg)
1297 forward_kmsg(s, priority, identifier, message, ucred);
1299 if (s->forward_to_console)
1300 forward_console(s, identifier, message, ucred);
1303 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1306 for (j = 0; j < n; j++) {
1310 if (iovec[j].iov_base < buffer ||
1311 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1312 free(iovec[j].iov_base);
1320 static void process_native_file(
1323 struct ucred *ucred,
1325 const char *label, size_t label_len) {
1334 /* Data is in the passed file, since it didn't fit in a
1335 * datagram. We can't map the file here, since clients might
1336 * then truncate it and trigger a SIGBUS for us. So let's
1337 * stupidly read it */
1339 if (fstat(fd, &st) < 0) {
1340 log_error("Failed to stat passed file, ignoring: %m");
1344 if (!S_ISREG(st.st_mode)) {
1345 log_error("File passed is not regular. Ignoring.");
1349 if (st.st_size <= 0)
1352 if (st.st_size > ENTRY_SIZE_MAX) {
1353 log_error("File passed too large. Ignoring.");
1357 p = malloc(st.st_size);
1359 log_error("Out of memory");
1363 n = pread(fd, p, st.st_size, 0);
1365 log_error("Failed to read file, ignoring: %s", strerror(-n));
1367 process_native_message(s, p, n, ucred, tv, label, label_len);
1372 static int stdout_stream_log(StdoutStream *s, const char *p) {
1373 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1374 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1378 size_t label_len = 0;
1386 priority = s->priority;
1388 if (s->level_prefix)
1389 parse_syslog_priority((char**) &p, &priority);
1391 if (s->forward_to_syslog || s->server->forward_to_syslog)
1392 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1394 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1395 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1397 if (s->forward_to_console || s->server->forward_to_console)
1398 forward_console(s->server, s->identifier, p, &s->ucred);
1400 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1402 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1403 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1405 if (priority & LOG_FACMASK)
1406 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1407 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1409 if (s->identifier) {
1410 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1411 if (syslog_identifier)
1412 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1415 message = strappend("MESSAGE=", p);
1417 IOVEC_SET_STRING(iovec[n++], message);
1420 if (s->security_context) {
1421 label = (char*) s->security_context;
1422 label_len = strlen((char*) s->security_context);
1426 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, priority);
1429 free(syslog_priority);
1430 free(syslog_facility);
1431 free(syslog_identifier);
1436 static int stdout_stream_line(StdoutStream *s, char *p) {
1446 case STDOUT_STREAM_IDENTIFIER:
1448 s->identifier = NULL;
1450 s->identifier = strdup(p);
1451 if (!s->identifier) {
1452 log_error("Out of memory");
1457 s->state = STDOUT_STREAM_PRIORITY;
1460 case STDOUT_STREAM_PRIORITY:
1461 r = safe_atoi(p, &s->priority);
1462 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1463 log_warning("Failed to parse log priority line.");
1467 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1470 case STDOUT_STREAM_LEVEL_PREFIX:
1471 r = parse_boolean(p);
1473 log_warning("Failed to parse level prefix line.");
1477 s->level_prefix = !!r;
1478 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1481 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1482 r = parse_boolean(p);
1484 log_warning("Failed to parse forward to syslog line.");
1488 s->forward_to_syslog = !!r;
1489 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1492 case STDOUT_STREAM_FORWARD_TO_KMSG:
1493 r = parse_boolean(p);
1495 log_warning("Failed to parse copy to kmsg line.");
1499 s->forward_to_kmsg = !!r;
1500 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1503 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1504 r = parse_boolean(p);
1506 log_warning("Failed to parse copy to console line.");
1510 s->forward_to_console = !!r;
1511 s->state = STDOUT_STREAM_RUNNING;
1514 case STDOUT_STREAM_RUNNING:
1515 return stdout_stream_log(s, p);
1518 assert_not_reached("Unknown stream state");
1521 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1529 remaining = s->length;
1534 end = memchr(p, '\n', remaining);
1537 else if (remaining >= sizeof(s->buffer) - 1) {
1538 end = p + sizeof(s->buffer) - 1;
1545 r = stdout_stream_line(s, p);
1553 if (force_flush && remaining > 0) {
1555 r = stdout_stream_line(s, p);
1563 if (p > s->buffer) {
1564 memmove(s->buffer, p, remaining);
1565 s->length = remaining;
1571 static int stdout_stream_process(StdoutStream *s) {
1577 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1580 if (errno == EAGAIN)
1583 log_warning("Failed to read from stream: %m");
1588 r = stdout_stream_scan(s, true);
1596 r = stdout_stream_scan(s, false);
1604 static void stdout_stream_free(StdoutStream *s) {
1608 assert(s->server->n_stdout_streams > 0);
1609 s->server->n_stdout_streams --;
1610 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1615 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1617 close_nointr_nofail(s->fd);
1621 if (s->security_context)
1622 freecon(s->security_context);
1625 free(s->identifier);
1629 static int stdout_stream_new(Server *s) {
1630 StdoutStream *stream;
1633 struct epoll_event ev;
1637 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1639 if (errno == EAGAIN)
1642 log_error("Failed to accept stdout connection: %m");
1646 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1647 log_warning("Too many stdout streams, refusing connection.");
1648 close_nointr_nofail(fd);
1652 stream = new0(StdoutStream, 1);
1654 log_error("Out of memory.");
1655 close_nointr_nofail(fd);
1661 len = sizeof(stream->ucred);
1662 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1663 log_error("Failed to determine peer credentials: %m");
1669 if (getpeercon(fd, &stream->security_context) < 0)
1670 log_error("Failed to determine peer security context.");
1673 if (shutdown(fd, SHUT_WR) < 0) {
1674 log_error("Failed to shutdown writing side of socket: %m");
1680 ev.data.ptr = stream;
1681 ev.events = EPOLLIN;
1682 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1683 log_error("Failed to add stream to event loop: %m");
1689 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1690 s->n_stdout_streams ++;
1695 stdout_stream_free(stream);
1699 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1710 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1715 for (i = 1; i <= 5; i++) {
1721 k = undecchar(p[i]);
1728 for (i = 7; i <= 12; i++) {
1731 k = undecchar(p[i]);
1740 *_p += strspn(*_p, WHITESPACE);
1745 static void proc_kmsg_line(Server *s, const char *p) {
1746 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1747 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1748 int priority = LOG_KERN | LOG_INFO;
1751 char *identifier = NULL, *pid = NULL;
1759 parse_syslog_priority((char **) &p, &priority);
1761 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1764 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1765 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1766 (unsigned long long) usec) >= 0)
1767 IOVEC_SET_STRING(iovec[n++], source_time);
1770 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1772 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1773 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1775 if ((priority & LOG_FACMASK) == LOG_KERN) {
1777 if (s->forward_to_syslog)
1778 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1780 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1782 read_identifier(&p, &identifier, &pid);
1784 if (s->forward_to_syslog)
1785 forward_syslog(s, priority, identifier, p, NULL, NULL);
1788 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1789 if (syslog_identifier)
1790 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1794 syslog_pid = strappend("SYSLOG_PID=", pid);
1796 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1799 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1800 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1803 message = strappend("MESSAGE=", p);
1805 IOVEC_SET_STRING(iovec[n++], message);
1807 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, priority);
1810 free(syslog_priority);
1811 free(syslog_identifier);
1813 free(syslog_facility);
1819 static void proc_kmsg_scan(Server *s) {
1825 p = s->proc_kmsg_buffer;
1826 remaining = s->proc_kmsg_length;
1831 end = memchr(p, '\n', remaining);
1834 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1835 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1842 proc_kmsg_line(s, p);
1848 if (p > s->proc_kmsg_buffer) {
1849 memmove(s->proc_kmsg_buffer, p, remaining);
1850 s->proc_kmsg_length = remaining;
1854 static int system_journal_open(Server *s) {
1860 r = sd_id128_get_machine(&machine);
1864 sd_id128_to_string(machine, ids);
1866 if (!s->system_journal) {
1868 /* First try to create the machine path, but not the prefix */
1869 fn = strappend("/var/log/journal/", ids);
1872 (void) mkdir(fn, 0755);
1875 /* The create the system journal file */
1876 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1880 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1884 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1886 s->system_journal->metrics = s->system_metrics;
1887 s->system_journal->compress = s->compress;
1889 server_fix_perms(s, s->system_journal, 0);
1892 if (r != -ENOENT && r != -EROFS)
1893 log_warning("Failed to open system journal: %s", strerror(-r));
1899 if (!s->runtime_journal) {
1901 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1905 if (s->system_journal) {
1907 /* Try to open the runtime journal, but only
1908 * if it already exists, so that we can flush
1909 * it into the system journal */
1911 r = journal_file_open_reliably(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1916 log_warning("Failed to open runtime journal: %s", strerror(-r));
1923 /* OK, we really need the runtime journal, so create
1924 * it if necessary. */
1926 (void) mkdir_parents(fn, 0755);
1927 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1931 log_error("Failed to open runtime journal: %s", strerror(-r));
1936 if (s->runtime_journal) {
1937 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1939 s->runtime_journal->metrics = s->runtime_metrics;
1940 s->runtime_journal->compress = s->compress;
1942 server_fix_perms(s, s->runtime_journal, 0);
1949 static int server_flush_to_var(Server *s) {
1950 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1959 if (!s->runtime_journal)
1962 ts = now(CLOCK_MONOTONIC);
1963 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1966 s->var_available_timestamp = ts;
1968 system_journal_open(s);
1970 if (!s->system_journal)
1973 log_info("Flushing to /var...");
1975 r = sd_id128_get_machine(&machine);
1977 log_error("Failed to get machine id: %s", strerror(-r));
1981 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1983 log_error("Failed to read runtime journal: %s", strerror(-r));
1987 SD_JOURNAL_FOREACH(j) {
1990 f = j->current_file;
1991 assert(f && f->current_offset > 0);
1993 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1995 log_error("Can't read entry: %s", strerror(-r));
1999 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2001 log_info("Allocation limit reached.");
2003 journal_file_post_change(s->system_journal);
2007 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2011 log_error("Can't write entry: %s", strerror(-r));
2017 journal_file_post_change(s->system_journal);
2019 journal_file_close(s->runtime_journal);
2020 s->runtime_journal = NULL;
2023 sd_id128_to_string(machine, path + 17);
2024 rm_rf(path, false, true, false);
2030 static int server_read_proc_kmsg(Server *s) {
2033 assert(s->proc_kmsg_fd >= 0);
2035 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
2038 if (errno == EAGAIN || errno == EINTR)
2041 log_error("Failed to read from kernel: %m");
2045 s->proc_kmsg_length += l;
2051 static int server_flush_proc_kmsg(Server *s) {
2056 if (s->proc_kmsg_fd < 0)
2059 log_info("Flushing /proc/kmsg...");
2062 r = server_read_proc_kmsg(s);
2073 static int process_event(Server *s, struct epoll_event *ev) {
2076 if (ev->data.fd == s->signal_fd) {
2077 struct signalfd_siginfo sfsi;
2080 if (ev->events != EPOLLIN) {
2081 log_info("Got invalid event from epoll.");
2085 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2086 if (n != sizeof(sfsi)) {
2091 if (errno == EINTR || errno == EAGAIN)
2097 if (sfsi.ssi_signo == SIGUSR1) {
2098 server_flush_to_var(s);
2102 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2105 } else if (ev->data.fd == s->proc_kmsg_fd) {
2108 if (ev->events != EPOLLIN) {
2109 log_info("Got invalid event from epoll.");
2113 r = server_read_proc_kmsg(s);
2119 } else if (ev->data.fd == s->native_fd ||
2120 ev->data.fd == s->syslog_fd) {
2122 if (ev->events != EPOLLIN) {
2123 log_info("Got invalid event from epoll.");
2128 struct msghdr msghdr;
2130 struct ucred *ucred = NULL;
2131 struct timeval *tv = NULL;
2132 struct cmsghdr *cmsg;
2134 size_t label_len = 0;
2136 struct cmsghdr cmsghdr;
2137 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2138 CMSG_SPACE(sizeof(struct timeval)) +
2139 CMSG_SPACE(sizeof(int)) +
2140 CMSG_SPACE(PAGE_SIZE)]; /* selinux label */
2147 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2148 log_error("SIOCINQ failed: %m");
2152 if (s->buffer_size < (size_t) v) {
2156 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2157 b = realloc(s->buffer, l+1);
2160 log_error("Couldn't increase buffer.");
2169 iovec.iov_base = s->buffer;
2170 iovec.iov_len = s->buffer_size;
2174 msghdr.msg_iov = &iovec;
2175 msghdr.msg_iovlen = 1;
2176 msghdr.msg_control = &control;
2177 msghdr.msg_controllen = sizeof(control);
2179 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2182 if (errno == EINTR || errno == EAGAIN)
2185 log_error("recvmsg() failed: %m");
2189 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2191 if (cmsg->cmsg_level == SOL_SOCKET &&
2192 cmsg->cmsg_type == SCM_CREDENTIALS &&
2193 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2194 ucred = (struct ucred*) CMSG_DATA(cmsg);
2195 else if (cmsg->cmsg_level == SOL_SOCKET &&
2196 cmsg->cmsg_type == SCM_SECURITY) {
2197 label = (char*) CMSG_DATA(cmsg);
2198 label_len = cmsg->cmsg_len - CMSG_LEN(0);
2199 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2200 cmsg->cmsg_type == SO_TIMESTAMP &&
2201 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2202 tv = (struct timeval*) CMSG_DATA(cmsg);
2203 else if (cmsg->cmsg_level == SOL_SOCKET &&
2204 cmsg->cmsg_type == SCM_RIGHTS) {
2205 fds = (int*) CMSG_DATA(cmsg);
2206 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2210 if (ev->data.fd == s->syslog_fd) {
2213 if (n > 0 && n_fds == 0) {
2214 e = memchr(s->buffer, '\n', n);
2220 process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
2221 } else if (n_fds > 0)
2222 log_warning("Got file descriptors via syslog socket. Ignoring.");
2225 if (n > 0 && n_fds == 0)
2226 process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
2227 else if (n == 0 && n_fds == 1)
2228 process_native_file(s, fds[0], ucred, tv, label, label_len);
2230 log_warning("Got too many file descriptors via native socket. Ignoring.");
2233 close_many(fds, n_fds);
2238 } else if (ev->data.fd == s->stdout_fd) {
2240 if (ev->events != EPOLLIN) {
2241 log_info("Got invalid event from epoll.");
2245 stdout_stream_new(s);
2249 StdoutStream *stream;
2251 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2252 log_info("Got invalid event from epoll.");
2256 /* If it is none of the well-known fds, it must be an
2257 * stdout stream fd. Note that this is a bit ugly here
2258 * (since we rely that none of the well-known fds
2259 * could be interpreted as pointer), but nonetheless
2260 * safe, since the well-known fds would never get an
2261 * fd > 4096, i.e. beyond the first memory page */
2263 stream = ev->data.ptr;
2265 if (stdout_stream_process(stream) <= 0)
2266 stdout_stream_free(stream);
2271 log_error("Unknown event.");
2275 static int open_syslog_socket(Server *s) {
2276 union sockaddr_union sa;
2278 struct epoll_event ev;
2282 if (s->syslog_fd < 0) {
2284 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2285 if (s->syslog_fd < 0) {
2286 log_error("socket() failed: %m");
2291 sa.un.sun_family = AF_UNIX;
2292 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2294 unlink(sa.un.sun_path);
2296 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2298 log_error("bind() failed: %m");
2302 chmod(sa.un.sun_path, 0666);
2304 fd_nonblock(s->syslog_fd, 1);
2307 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2309 log_error("SO_PASSCRED failed: %m");
2315 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2317 log_warning("SO_PASSSEC failed: %m");
2321 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2323 log_error("SO_TIMESTAMP failed: %m");
2328 ev.events = EPOLLIN;
2329 ev.data.fd = s->syslog_fd;
2330 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2331 log_error("Failed to add syslog server fd to epoll object: %m");
2338 static int open_native_socket(Server*s) {
2339 union sockaddr_union sa;
2341 struct epoll_event ev;
2345 if (s->native_fd < 0) {
2347 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2348 if (s->native_fd < 0) {
2349 log_error("socket() failed: %m");
2354 sa.un.sun_family = AF_UNIX;
2355 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2357 unlink(sa.un.sun_path);
2359 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2361 log_error("bind() failed: %m");
2365 chmod(sa.un.sun_path, 0666);
2367 fd_nonblock(s->native_fd, 1);
2370 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2372 log_error("SO_PASSCRED failed: %m");
2378 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2380 log_warning("SO_PASSSEC failed: %m");
2384 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2386 log_error("SO_TIMESTAMP failed: %m");
2391 ev.events = EPOLLIN;
2392 ev.data.fd = s->native_fd;
2393 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2394 log_error("Failed to add native server fd to epoll object: %m");
2401 static int open_stdout_socket(Server *s) {
2402 union sockaddr_union sa;
2404 struct epoll_event ev;
2408 if (s->stdout_fd < 0) {
2410 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2411 if (s->stdout_fd < 0) {
2412 log_error("socket() failed: %m");
2417 sa.un.sun_family = AF_UNIX;
2418 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2420 unlink(sa.un.sun_path);
2422 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2424 log_error("bind() failed: %m");
2428 chmod(sa.un.sun_path, 0666);
2430 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2431 log_error("liste() failed: %m");
2435 fd_nonblock(s->stdout_fd, 1);
2438 ev.events = EPOLLIN;
2439 ev.data.fd = s->stdout_fd;
2440 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2441 log_error("Failed to add stdout server fd to epoll object: %m");
2448 static int open_proc_kmsg(Server *s) {
2449 struct epoll_event ev;
2453 if (!s->import_proc_kmsg)
2457 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2458 if (s->proc_kmsg_fd < 0) {
2459 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2464 ev.events = EPOLLIN;
2465 ev.data.fd = s->proc_kmsg_fd;
2466 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2467 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2474 static int open_signalfd(Server *s) {
2476 struct epoll_event ev;
2480 assert_se(sigemptyset(&mask) == 0);
2481 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2482 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2484 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2485 if (s->signal_fd < 0) {
2486 log_error("signalfd(): %m");
2491 ev.events = EPOLLIN;
2492 ev.data.fd = s->signal_fd;
2494 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2495 log_error("epoll_ctl(): %m");
2502 static int server_parse_proc_cmdline(Server *s) {
2503 char *line, *w, *state;
2507 if (detect_container(NULL) > 0)
2510 r = read_one_line_file("/proc/cmdline", &line);
2512 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2516 FOREACH_WORD_QUOTED(w, l, line, state) {
2519 word = strndup(w, l);
2525 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2526 r = parse_boolean(word + 35);
2528 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2530 s->forward_to_syslog = r;
2531 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2532 r = parse_boolean(word + 33);
2534 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2536 s->forward_to_kmsg = r;
2537 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2538 r = parse_boolean(word + 36);
2540 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2542 s->forward_to_console = r;
2555 static int server_parse_config_file(Server *s) {
2562 fn = "/etc/systemd/systemd-journald.conf";
2563 f = fopen(fn, "re");
2565 if (errno == ENOENT)
2568 log_warning("Failed to open configuration file %s: %m", fn);
2572 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2574 log_warning("Failed to parse configuration file: %s", strerror(-r));
2581 static int server_init(Server *s) {
2587 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2590 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2591 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2593 s->forward_to_syslog = true;
2594 s->import_proc_kmsg = true;
2596 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2597 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2599 server_parse_config_file(s);
2600 server_parse_proc_cmdline(s);
2602 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2603 if (!s->user_journals) {
2604 log_error("Out of memory.");
2608 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2609 if (s->epoll_fd < 0) {
2610 log_error("Failed to create epoll object: %m");
2614 n = sd_listen_fds(true);
2616 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2620 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2622 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2624 if (s->native_fd >= 0) {
2625 log_error("Too many native sockets passed.");
2631 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2633 if (s->stdout_fd >= 0) {
2634 log_error("Too many stdout sockets passed.");
2640 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2642 if (s->syslog_fd >= 0) {
2643 log_error("Too many /dev/log sockets passed.");
2650 log_error("Unknown socket passed.");
2655 r = open_syslog_socket(s);
2659 r = open_native_socket(s);
2663 r = open_stdout_socket(s);
2667 r = open_proc_kmsg(s);
2671 r = open_signalfd(s);
2675 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2679 r = system_journal_open(s);
2686 static void server_done(Server *s) {
2690 while (s->stdout_streams)
2691 stdout_stream_free(s->stdout_streams);
2693 if (s->system_journal)
2694 journal_file_close(s->system_journal);
2696 if (s->runtime_journal)
2697 journal_file_close(s->runtime_journal);
2699 while ((f = hashmap_steal_first(s->user_journals)))
2700 journal_file_close(f);
2702 hashmap_free(s->user_journals);
2704 if (s->epoll_fd >= 0)
2705 close_nointr_nofail(s->epoll_fd);
2707 if (s->signal_fd >= 0)
2708 close_nointr_nofail(s->signal_fd);
2710 if (s->syslog_fd >= 0)
2711 close_nointr_nofail(s->syslog_fd);
2713 if (s->native_fd >= 0)
2714 close_nointr_nofail(s->native_fd);
2716 if (s->stdout_fd >= 0)
2717 close_nointr_nofail(s->stdout_fd);
2719 if (s->proc_kmsg_fd >= 0)
2720 close_nointr_nofail(s->proc_kmsg_fd);
2723 journal_rate_limit_free(s->rate_limit);
2728 int main(int argc, char *argv[]) {
2732 /* if (getppid() != 1) { */
2733 /* log_error("This program should be invoked by init only."); */
2734 /* return EXIT_FAILURE; */
2738 log_error("This program does not take arguments.");
2739 return EXIT_FAILURE;
2742 log_set_target(LOG_TARGET_CONSOLE);
2743 log_parse_environment();
2748 r = server_init(&server);
2752 server_vacuum(&server);
2753 server_flush_to_var(&server);
2754 server_flush_proc_kmsg(&server);
2756 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2757 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2761 "STATUS=Processing requests...");
2764 struct epoll_event event;
2766 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2772 log_error("epoll_wait() failed: %m");
2778 r = process_event(&server, &event);
2785 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2786 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2790 "STATUS=Shutting down...");
2792 server_done(&server);
2794 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;