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;
158 r = readdir_r(d, &buf, &de);
165 if (!endswith(de->d_name, ".journal") &&
166 !endswith(de->d_name, ".journal~"))
169 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
172 if (!S_ISREG(st.st_mode))
175 sum += (uint64_t) st.st_blocks * 512UL;
178 avail = sum >= m->max_use ? 0 : m->max_use - sum;
180 ss_avail = ss.f_bsize * ss.f_bavail;
182 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
184 if (ss_avail < avail)
187 s->cached_available_space = avail;
188 s->cached_available_space_timestamp = ts;
196 static void server_read_file_gid(Server *s) {
197 const char *adm = "adm";
202 if (s->file_gid_valid)
205 r = get_group_creds(&adm, &s->file_gid);
207 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
209 /* if we couldn't read the gid, then it will be 0, but that's
210 * fine and we shouldn't try to resolve the group again, so
211 * let's just pretend it worked right-away. */
212 s->file_gid_valid = true;
215 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
220 acl_permset_t permset;
225 server_read_file_gid(s);
227 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
229 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
235 acl = acl_get_fd(f->fd);
237 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
241 r = acl_find_uid(acl, uid, &entry);
244 if (acl_create_entry(&acl, &entry) < 0 ||
245 acl_set_tag_type(entry, ACL_USER) < 0 ||
246 acl_set_qualifier(entry, &uid) < 0) {
247 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
252 if (acl_get_permset(entry, &permset) < 0 ||
253 acl_add_perm(permset, ACL_READ) < 0 ||
254 acl_calc_mask(&acl) < 0) {
255 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
259 if (acl_set_fd(f->fd, acl) < 0)
260 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
267 static JournalFile* find_journal(Server *s, uid_t uid) {
276 /* We split up user logs only on /var, not on /run. If the
277 * runtime file is open, we write to it exclusively, in order
278 * to guarantee proper order as soon as we flush /run to
279 * /var and close the runtime file. */
281 if (s->runtime_journal)
282 return s->runtime_journal;
285 return s->system_journal;
287 r = sd_id128_get_machine(&machine);
289 return s->system_journal;
291 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
295 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
296 return s->system_journal;
298 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
299 /* Too many open? Then let's close one */
300 f = hashmap_steal_first(s->user_journals);
302 journal_file_close(f);
305 r = journal_file_open_reliably(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
309 return s->system_journal;
311 server_fix_perms(s, f, uid);
313 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
315 journal_file_close(f);
316 return s->system_journal;
322 static void server_rotate(Server *s) {
328 log_info("Rotating...");
330 if (s->runtime_journal) {
331 r = journal_file_rotate(&s->runtime_journal);
333 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
335 server_fix_perms(s, s->runtime_journal, 0);
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));
343 server_fix_perms(s, s->system_journal, 0);
346 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
347 r = journal_file_rotate(&f);
349 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
351 hashmap_replace(s->user_journals, k, f);
352 server_fix_perms(s, s->system_journal, PTR_TO_UINT32(k));
357 static void server_vacuum(Server *s) {
363 log_info("Vacuuming...");
365 r = sd_id128_get_machine(&machine);
367 log_error("Failed to get machine ID: %s", strerror(-r));
371 sd_id128_to_string(machine, ids);
373 if (s->system_journal) {
374 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
375 log_error("Out of memory.");
379 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
380 if (r < 0 && r != -ENOENT)
381 log_error("Failed to vacuum %s: %s", p, strerror(-r));
386 if (s->runtime_journal) {
387 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
388 log_error("Out of memory.");
392 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
393 if (r < 0 && r != -ENOENT)
394 log_error("Failed to vacuum %s: %s", p, strerror(-r));
398 s->cached_available_space_timestamp = 0;
401 static char *shortened_cgroup_path(pid_t pid) {
403 char *process_path, *init_path, *path;
407 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
411 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
417 if (endswith(init_path, "/system"))
418 init_path[strlen(init_path) - 7] = 0;
419 else if (streq(init_path, "/"))
422 if (startswith(process_path, init_path)) {
425 p = strdup(process_path + strlen(init_path));
443 static void dispatch_message_real(
445 struct iovec *iovec, unsigned n, unsigned m,
448 const char *label, size_t label_len) {
450 char *pid = NULL, *uid = NULL, *gid = NULL,
451 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
452 *comm = NULL, *cmdline = NULL, *hostname = NULL,
453 *audit_session = NULL, *audit_loginuid = NULL,
454 *exe = NULL, *cgroup = NULL, *session = NULL,
455 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
461 uid_t loginuid = 0, realuid = 0;
463 bool vacuumed = false;
468 assert(n + N_IOVEC_META_FIELDS <= m);
474 realuid = ucred->uid;
476 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
477 IOVEC_SET_STRING(iovec[n++], pid);
479 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
480 IOVEC_SET_STRING(iovec[n++], uid);
482 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
483 IOVEC_SET_STRING(iovec[n++], gid);
485 r = get_process_comm(ucred->pid, &t);
487 comm = strappend("_COMM=", t);
491 IOVEC_SET_STRING(iovec[n++], comm);
494 r = get_process_exe(ucred->pid, &t);
496 exe = strappend("_EXE=", t);
500 IOVEC_SET_STRING(iovec[n++], exe);
503 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
505 cmdline = strappend("_CMDLINE=", t);
509 IOVEC_SET_STRING(iovec[n++], cmdline);
512 r = audit_session_from_pid(ucred->pid, &audit);
514 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
515 IOVEC_SET_STRING(iovec[n++], audit_session);
517 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
519 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
520 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
522 t = shortened_cgroup_path(ucred->pid);
524 cgroup = strappend("_SYSTEMD_CGROUP=", t);
528 IOVEC_SET_STRING(iovec[n++], cgroup);
531 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
532 session = strappend("_SYSTEMD_SESSION=", t);
536 IOVEC_SET_STRING(iovec[n++], session);
539 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
540 unit = strappend("_SYSTEMD_UNIT=", t);
544 IOVEC_SET_STRING(iovec[n++], unit);
547 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
548 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
549 IOVEC_SET_STRING(iovec[n++], owner_uid);
553 selinux_context = malloc(sizeof("_SELINUX_CONTEXT=") + label_len);
554 if (selinux_context) {
555 memcpy(selinux_context, "_SELINUX_CONTEXT=", sizeof("_SELINUX_CONTEXT=")-1);
556 memcpy(selinux_context+sizeof("_SELINUX_CONTEXT=")-1, label, label_len);
557 selinux_context[sizeof("_SELINUX_CONTEXT=")-1+label_len] = 0;
558 IOVEC_SET_STRING(iovec[n++], selinux_context);
561 security_context_t con;
563 if (getpidcon(ucred->pid, &con) >= 0) {
564 selinux_context = strappend("_SELINUX_CONTEXT=", con);
566 IOVEC_SET_STRING(iovec[n++], selinux_context);
575 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
576 (unsigned long long) timeval_load(tv)) >= 0)
577 IOVEC_SET_STRING(iovec[n++], source_time);
580 /* Note that strictly speaking storing the boot id here is
581 * redundant since the entry includes this in-line
582 * anyway. However, we need this indexed, too. */
583 r = sd_id128_get_boot(&id);
585 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
586 IOVEC_SET_STRING(iovec[n++], boot_id);
588 r = sd_id128_get_machine(&id);
590 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
591 IOVEC_SET_STRING(iovec[n++], machine_id);
593 t = gethostname_malloc();
595 hostname = strappend("_HOSTNAME=", t);
598 IOVEC_SET_STRING(iovec[n++], hostname);
603 server_flush_to_var(s);
606 f = find_journal(s, realuid == 0 ? 0 : loginuid);
608 log_warning("Dropping message, as we can't find a place to store the data.");
610 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
612 if ((r == -E2BIG || /* hit limit */
613 r == -EFBIG || /* hit fs limit */
614 r == -EDQUOT || /* quota hit */
615 r == -ENOSPC || /* disk full */
616 r == -EBADMSG || /* corrupted */
617 r == -ENODATA || /* truncated */
618 r == -EHOSTDOWN || /* other machine */
619 r == -EPROTONOSUPPORT) && /* unsupported feature */
623 log_info("Allocation limit reached, rotating.");
625 log_warning("Journal file corrupted, rotating.");
631 log_info("Retrying write.");
636 log_error("Failed to write entry, ignoring: %s", strerror(-r));
650 free(audit_loginuid);
655 free(selinux_context);
658 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
659 char mid[11 + 32 + 1];
660 char buffer[16 + LINE_MAX + 1];
661 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
669 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
670 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
672 memcpy(buffer, "MESSAGE=", 8);
673 va_start(ap, format);
674 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
676 char_array_0(buffer);
677 IOVEC_SET_STRING(iovec[n++], buffer);
679 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
681 IOVEC_SET_STRING(iovec[n++], mid);
684 ucred.pid = getpid();
685 ucred.uid = getuid();
686 ucred.gid = getgid();
688 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0);
691 static void dispatch_message(Server *s,
692 struct iovec *iovec, unsigned n, unsigned m,
695 const char *label, size_t label_len,
698 char *path = NULL, *c;
701 assert(iovec || n == 0);
709 path = shortened_cgroup_path(ucred->pid);
713 /* example: /user/lennart/3/foobar
714 * /system/dbus.service/foobar
716 * So let's cut of everything past the third /, since that is
717 * wher user directories start */
719 c = strchr(path, '/');
721 c = strchr(c+1, '/');
723 c = strchr(c+1, '/');
729 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
736 /* Write a suppression message if we suppressed something */
738 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
743 dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len);
746 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
747 struct msghdr msghdr;
748 struct cmsghdr *cmsg;
750 struct cmsghdr cmsghdr;
751 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
753 union sockaddr_union sa;
760 msghdr.msg_iov = (struct iovec*) iovec;
761 msghdr.msg_iovlen = n_iovec;
764 sa.un.sun_family = AF_UNIX;
765 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
766 msghdr.msg_name = &sa;
767 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
771 msghdr.msg_control = &control;
772 msghdr.msg_controllen = sizeof(control);
774 cmsg = CMSG_FIRSTHDR(&msghdr);
775 cmsg->cmsg_level = SOL_SOCKET;
776 cmsg->cmsg_type = SCM_CREDENTIALS;
777 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
778 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
779 msghdr.msg_controllen = cmsg->cmsg_len;
782 /* Forward the syslog message we received via /dev/log to
783 * /run/systemd/syslog. Unfortunately we currently can't set
784 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
786 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
789 /* The socket is full? I guess the syslog implementation is
790 * too slow, and we shouldn't wait for that... */
794 if (ucred && errno == ESRCH) {
797 /* Hmm, presumably the sender process vanished
798 * by now, so let's fix it as good as we
803 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
805 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
812 log_debug("Failed to forward syslog message: %m");
815 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
821 IOVEC_SET_STRING(iovec, buffer);
822 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
825 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
826 struct iovec iovec[5];
827 char header_priority[6], header_time[64], header_pid[16];
831 char *ident_buf = NULL;
834 assert(priority >= 0);
835 assert(priority <= 999);
838 /* First: priority field */
839 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
840 char_array_0(header_priority);
841 IOVEC_SET_STRING(iovec[n++], header_priority);
843 /* Second: timestamp */
844 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
848 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
850 IOVEC_SET_STRING(iovec[n++], header_time);
852 /* Third: identifier and PID */
855 get_process_comm(ucred->pid, &ident_buf);
856 identifier = ident_buf;
859 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
860 char_array_0(header_pid);
863 IOVEC_SET_STRING(iovec[n++], identifier);
865 IOVEC_SET_STRING(iovec[n++], header_pid);
866 } else if (identifier) {
867 IOVEC_SET_STRING(iovec[n++], identifier);
868 IOVEC_SET_STRING(iovec[n++], ": ");
871 /* Fourth: message */
872 IOVEC_SET_STRING(iovec[n++], message);
874 forward_syslog_iovec(s, iovec, n, ucred, tv);
879 static int fixup_priority(int priority) {
881 if ((priority & LOG_FACMASK) == 0)
882 return (priority & LOG_PRIMASK) | LOG_USER;
887 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
888 struct iovec iovec[5];
889 char header_priority[6], header_pid[16];
891 char *ident_buf = NULL;
895 assert(priority >= 0);
896 assert(priority <= 999);
899 /* Never allow messages with kernel facility to be written to
900 * kmsg, regardless where the data comes from. */
901 priority = fixup_priority(priority);
903 /* First: priority field */
904 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
905 char_array_0(header_priority);
906 IOVEC_SET_STRING(iovec[n++], header_priority);
908 /* Second: identifier and PID */
911 get_process_comm(ucred->pid, &ident_buf);
912 identifier = ident_buf;
915 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
916 char_array_0(header_pid);
919 IOVEC_SET_STRING(iovec[n++], identifier);
921 IOVEC_SET_STRING(iovec[n++], header_pid);
922 } else if (identifier) {
923 IOVEC_SET_STRING(iovec[n++], identifier);
924 IOVEC_SET_STRING(iovec[n++], ": ");
927 /* Fourth: message */
928 IOVEC_SET_STRING(iovec[n++], message);
929 IOVEC_SET_STRING(iovec[n++], "\n");
931 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
933 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
937 if (writev(fd, iovec, n) < 0)
938 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
940 close_nointr_nofail(fd);
946 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
947 struct iovec iovec[4];
950 char *ident_buf = NULL;
955 /* First: identifier and PID */
958 get_process_comm(ucred->pid, &ident_buf);
959 identifier = ident_buf;
962 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
963 char_array_0(header_pid);
966 IOVEC_SET_STRING(iovec[n++], identifier);
968 IOVEC_SET_STRING(iovec[n++], header_pid);
969 } else if (identifier) {
970 IOVEC_SET_STRING(iovec[n++], identifier);
971 IOVEC_SET_STRING(iovec[n++], ": ");
975 IOVEC_SET_STRING(iovec[n++], message);
976 IOVEC_SET_STRING(iovec[n++], "\n");
978 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
980 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
984 if (writev(fd, iovec, n) < 0)
985 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
987 close_nointr_nofail(fd);
993 static void read_identifier(const char **buf, char **identifier, char **pid) {
1004 p += strspn(p, WHITESPACE);
1005 l = strcspn(p, WHITESPACE);
1014 if (p[l-1] == ']') {
1020 t = strndup(p+k+1, l-k-2);
1040 *buf += strspn(*buf, WHITESPACE);
1043 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) {
1044 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1045 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1047 int priority = LOG_USER | LOG_INFO;
1048 char *identifier = NULL, *pid = NULL;
1053 if (s->forward_to_syslog)
1054 forward_syslog_raw(s, buf, ucred, tv);
1056 parse_syslog_priority((char**) &buf, &priority);
1057 skip_syslog_date((char**) &buf);
1058 read_identifier(&buf, &identifier, &pid);
1060 if (s->forward_to_kmsg)
1061 forward_kmsg(s, priority, identifier, buf, ucred);
1063 if (s->forward_to_console)
1064 forward_console(s, identifier, buf, ucred);
1066 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1068 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1069 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1071 if (priority & LOG_FACMASK)
1072 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1073 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1076 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1077 if (syslog_identifier)
1078 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1082 syslog_pid = strappend("SYSLOG_PID=", pid);
1084 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1087 message = strappend("MESSAGE=", buf);
1089 IOVEC_SET_STRING(iovec[n++], message);
1091 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, label, label_len, priority);
1096 free(syslog_priority);
1097 free(syslog_facility);
1098 free(syslog_identifier);
1101 static bool valid_user_field(const char *p, size_t l) {
1104 /* We kinda enforce POSIX syntax recommendations for
1105 environment variables here, but make a couple of additional
1108 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1110 /* No empty field names */
1114 /* Don't allow names longer than 64 chars */
1118 /* Variables starting with an underscore are protected */
1122 /* Don't allow digits as first character */
1123 if (p[0] >= '0' && p[0] <= '9')
1126 /* Only allow A-Z0-9 and '_' */
1127 for (a = p; a < p + l; a++)
1128 if (!((*a >= 'A' && *a <= 'Z') ||
1129 (*a >= '0' && *a <= '9') ||
1136 static void process_native_message(
1138 const void *buffer, size_t buffer_size,
1139 struct ucred *ucred,
1141 const char *label, size_t label_len) {
1143 struct iovec *iovec = NULL;
1144 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1147 int priority = LOG_INFO;
1148 char *identifier = NULL, *message = NULL;
1151 assert(buffer || n == 0);
1154 remaining = buffer_size;
1156 while (remaining > 0) {
1159 e = memchr(p, '\n', remaining);
1162 /* Trailing noise, let's ignore it, and flush what we collected */
1163 log_debug("Received message with trailing noise, ignoring.");
1168 /* Entry separator */
1169 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1171 priority = LOG_INFO;
1178 if (*p == '.' || *p == '#') {
1179 /* Ignore control commands for now, and
1181 remaining -= (e - p) + 1;
1186 /* A property follows */
1188 if (n+N_IOVEC_META_FIELDS >= m) {
1192 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1193 c = realloc(iovec, u * sizeof(struct iovec));
1195 log_error("Out of memory");
1203 q = memchr(p, '=', e - p);
1205 if (valid_user_field(p, q - p)) {
1210 /* If the field name starts with an
1211 * underscore, skip the variable,
1212 * since that indidates a trusted
1214 iovec[n].iov_base = (char*) p;
1215 iovec[n].iov_len = l;
1218 /* We need to determine the priority
1219 * of this entry for the rate limiting
1222 memcmp(p, "PRIORITY=", 9) == 0 &&
1223 p[9] >= '0' && p[9] <= '9')
1224 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1227 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1228 p[16] >= '0' && p[16] <= '9')
1229 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1232 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1233 p[16] >= '0' && p[16] <= '9' &&
1234 p[17] >= '0' && p[17] <= '9')
1235 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1238 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1241 t = strndup(p + 11, l - 11);
1246 } else if (l >= 8 &&
1247 memcmp(p, "MESSAGE=", 8) == 0) {
1250 t = strndup(p + 8, l - 8);
1258 remaining -= (e - p) + 1;
1265 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1266 log_debug("Failed to parse message, ignoring.");
1270 memcpy(&l, e + 1, sizeof(uint64_t));
1273 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1274 e[1+sizeof(uint64_t)+l] != '\n') {
1275 log_debug("Failed to parse message, ignoring.");
1279 k = malloc((e - p) + 1 + l);
1281 log_error("Out of memory");
1285 memcpy(k, p, e - p);
1287 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1289 if (valid_user_field(p, e - p)) {
1290 iovec[n].iov_base = k;
1291 iovec[n].iov_len = (e - p) + 1 + l;
1296 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1297 p = e + 1 + sizeof(uint64_t) + l + 1;
1305 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1308 if (s->forward_to_syslog)
1309 forward_syslog(s, priority, identifier, message, ucred, tv);
1311 if (s->forward_to_kmsg)
1312 forward_kmsg(s, priority, identifier, message, ucred);
1314 if (s->forward_to_console)
1315 forward_console(s, identifier, message, ucred);
1318 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1321 for (j = 0; j < n; j++) {
1325 if (iovec[j].iov_base < buffer ||
1326 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1327 free(iovec[j].iov_base);
1335 static void process_native_file(
1338 struct ucred *ucred,
1340 const char *label, size_t label_len) {
1349 /* Data is in the passed file, since it didn't fit in a
1350 * datagram. We can't map the file here, since clients might
1351 * then truncate it and trigger a SIGBUS for us. So let's
1352 * stupidly read it */
1354 if (fstat(fd, &st) < 0) {
1355 log_error("Failed to stat passed file, ignoring: %m");
1359 if (!S_ISREG(st.st_mode)) {
1360 log_error("File passed is not regular. Ignoring.");
1364 if (st.st_size <= 0)
1367 if (st.st_size > ENTRY_SIZE_MAX) {
1368 log_error("File passed too large. Ignoring.");
1372 p = malloc(st.st_size);
1374 log_error("Out of memory");
1378 n = pread(fd, p, st.st_size, 0);
1380 log_error("Failed to read file, ignoring: %s", strerror(-n));
1382 process_native_message(s, p, n, ucred, tv, label, label_len);
1387 static int stdout_stream_log(StdoutStream *s, const char *p) {
1388 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1389 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1393 size_t label_len = 0;
1401 priority = s->priority;
1403 if (s->level_prefix)
1404 parse_syslog_priority((char**) &p, &priority);
1406 if (s->forward_to_syslog || s->server->forward_to_syslog)
1407 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1409 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1410 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1412 if (s->forward_to_console || s->server->forward_to_console)
1413 forward_console(s->server, s->identifier, p, &s->ucred);
1415 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1417 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1418 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1420 if (priority & LOG_FACMASK)
1421 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1422 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1424 if (s->identifier) {
1425 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1426 if (syslog_identifier)
1427 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1430 message = strappend("MESSAGE=", p);
1432 IOVEC_SET_STRING(iovec[n++], message);
1435 if (s->security_context) {
1436 label = (char*) s->security_context;
1437 label_len = strlen((char*) s->security_context);
1441 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, priority);
1444 free(syslog_priority);
1445 free(syslog_facility);
1446 free(syslog_identifier);
1451 static int stdout_stream_line(StdoutStream *s, char *p) {
1461 case STDOUT_STREAM_IDENTIFIER:
1463 s->identifier = NULL;
1465 s->identifier = strdup(p);
1466 if (!s->identifier) {
1467 log_error("Out of memory");
1472 s->state = STDOUT_STREAM_PRIORITY;
1475 case STDOUT_STREAM_PRIORITY:
1476 r = safe_atoi(p, &s->priority);
1477 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1478 log_warning("Failed to parse log priority line.");
1482 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1485 case STDOUT_STREAM_LEVEL_PREFIX:
1486 r = parse_boolean(p);
1488 log_warning("Failed to parse level prefix line.");
1492 s->level_prefix = !!r;
1493 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1496 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1497 r = parse_boolean(p);
1499 log_warning("Failed to parse forward to syslog line.");
1503 s->forward_to_syslog = !!r;
1504 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1507 case STDOUT_STREAM_FORWARD_TO_KMSG:
1508 r = parse_boolean(p);
1510 log_warning("Failed to parse copy to kmsg line.");
1514 s->forward_to_kmsg = !!r;
1515 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1518 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1519 r = parse_boolean(p);
1521 log_warning("Failed to parse copy to console line.");
1525 s->forward_to_console = !!r;
1526 s->state = STDOUT_STREAM_RUNNING;
1529 case STDOUT_STREAM_RUNNING:
1530 return stdout_stream_log(s, p);
1533 assert_not_reached("Unknown stream state");
1536 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1544 remaining = s->length;
1549 end = memchr(p, '\n', remaining);
1552 else if (remaining >= sizeof(s->buffer) - 1) {
1553 end = p + sizeof(s->buffer) - 1;
1560 r = stdout_stream_line(s, p);
1568 if (force_flush && remaining > 0) {
1570 r = stdout_stream_line(s, p);
1578 if (p > s->buffer) {
1579 memmove(s->buffer, p, remaining);
1580 s->length = remaining;
1586 static int stdout_stream_process(StdoutStream *s) {
1592 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1595 if (errno == EAGAIN)
1598 log_warning("Failed to read from stream: %m");
1603 r = stdout_stream_scan(s, true);
1611 r = stdout_stream_scan(s, false);
1619 static void stdout_stream_free(StdoutStream *s) {
1623 assert(s->server->n_stdout_streams > 0);
1624 s->server->n_stdout_streams --;
1625 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1630 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1632 close_nointr_nofail(s->fd);
1636 if (s->security_context)
1637 freecon(s->security_context);
1640 free(s->identifier);
1644 static int stdout_stream_new(Server *s) {
1645 StdoutStream *stream;
1648 struct epoll_event ev;
1652 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1654 if (errno == EAGAIN)
1657 log_error("Failed to accept stdout connection: %m");
1661 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1662 log_warning("Too many stdout streams, refusing connection.");
1663 close_nointr_nofail(fd);
1667 stream = new0(StdoutStream, 1);
1669 log_error("Out of memory.");
1670 close_nointr_nofail(fd);
1676 len = sizeof(stream->ucred);
1677 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1678 log_error("Failed to determine peer credentials: %m");
1684 if (getpeercon(fd, &stream->security_context) < 0)
1685 log_error("Failed to determine peer security context.");
1688 if (shutdown(fd, SHUT_WR) < 0) {
1689 log_error("Failed to shutdown writing side of socket: %m");
1695 ev.data.ptr = stream;
1696 ev.events = EPOLLIN;
1697 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1698 log_error("Failed to add stream to event loop: %m");
1704 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1705 s->n_stdout_streams ++;
1710 stdout_stream_free(stream);
1714 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1725 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1730 for (i = 1; i <= 5; i++) {
1736 k = undecchar(p[i]);
1743 for (i = 7; i <= 12; i++) {
1746 k = undecchar(p[i]);
1755 *_p += strspn(*_p, WHITESPACE);
1760 static void proc_kmsg_line(Server *s, const char *p) {
1761 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1762 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1763 int priority = LOG_KERN | LOG_INFO;
1766 char *identifier = NULL, *pid = NULL;
1774 parse_syslog_priority((char **) &p, &priority);
1776 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1779 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1780 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1781 (unsigned long long) usec) >= 0)
1782 IOVEC_SET_STRING(iovec[n++], source_time);
1785 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1787 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1788 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1790 if ((priority & LOG_FACMASK) == LOG_KERN) {
1792 if (s->forward_to_syslog)
1793 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1795 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1797 read_identifier(&p, &identifier, &pid);
1799 if (s->forward_to_syslog)
1800 forward_syslog(s, priority, identifier, p, NULL, NULL);
1803 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1804 if (syslog_identifier)
1805 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1809 syslog_pid = strappend("SYSLOG_PID=", pid);
1811 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1814 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1815 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1818 message = strappend("MESSAGE=", p);
1820 IOVEC_SET_STRING(iovec[n++], message);
1822 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, priority);
1825 free(syslog_priority);
1826 free(syslog_identifier);
1828 free(syslog_facility);
1834 static void proc_kmsg_scan(Server *s) {
1840 p = s->proc_kmsg_buffer;
1841 remaining = s->proc_kmsg_length;
1846 end = memchr(p, '\n', remaining);
1849 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1850 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1857 proc_kmsg_line(s, p);
1863 if (p > s->proc_kmsg_buffer) {
1864 memmove(s->proc_kmsg_buffer, p, remaining);
1865 s->proc_kmsg_length = remaining;
1869 static int system_journal_open(Server *s) {
1875 r = sd_id128_get_machine(&machine);
1879 sd_id128_to_string(machine, ids);
1881 if (!s->system_journal) {
1883 /* First try to create the machine path, but not the prefix */
1884 fn = strappend("/var/log/journal/", ids);
1887 (void) mkdir(fn, 0755);
1890 /* The create the system journal file */
1891 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1895 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1899 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1901 s->system_journal->metrics = s->system_metrics;
1902 s->system_journal->compress = s->compress;
1904 server_fix_perms(s, s->system_journal, 0);
1907 if (r != -ENOENT && r != -EROFS)
1908 log_warning("Failed to open system journal: %s", strerror(-r));
1914 if (!s->runtime_journal) {
1916 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1920 if (s->system_journal) {
1922 /* Try to open the runtime journal, but only
1923 * if it already exists, so that we can flush
1924 * it into the system journal */
1926 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1931 log_warning("Failed to open runtime journal: %s", strerror(-r));
1938 /* OK, we really need the runtime journal, so create
1939 * it if necessary. */
1941 (void) mkdir_parents(fn, 0755);
1942 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1946 log_error("Failed to open runtime journal: %s", strerror(-r));
1951 if (s->runtime_journal) {
1952 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1954 s->runtime_journal->metrics = s->runtime_metrics;
1955 s->runtime_journal->compress = s->compress;
1957 server_fix_perms(s, s->runtime_journal, 0);
1964 static int server_flush_to_var(Server *s) {
1965 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1974 if (!s->runtime_journal)
1977 ts = now(CLOCK_MONOTONIC);
1978 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1981 s->var_available_timestamp = ts;
1983 system_journal_open(s);
1985 if (!s->system_journal)
1988 log_info("Flushing to /var...");
1990 r = sd_id128_get_machine(&machine);
1992 log_error("Failed to get machine id: %s", strerror(-r));
1996 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1998 log_error("Failed to read runtime journal: %s", strerror(-r));
2002 SD_JOURNAL_FOREACH(j) {
2005 f = j->current_file;
2006 assert(f && f->current_offset > 0);
2008 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2010 log_error("Can't read entry: %s", strerror(-r));
2014 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2016 log_info("Allocation limit reached.");
2018 journal_file_post_change(s->system_journal);
2022 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2026 log_error("Can't write entry: %s", strerror(-r));
2032 journal_file_post_change(s->system_journal);
2034 journal_file_close(s->runtime_journal);
2035 s->runtime_journal = NULL;
2038 sd_id128_to_string(machine, path + 17);
2039 rm_rf(path, false, true, false);
2045 static int server_read_proc_kmsg(Server *s) {
2048 assert(s->proc_kmsg_fd >= 0);
2050 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
2053 if (errno == EAGAIN || errno == EINTR)
2056 log_error("Failed to read from kernel: %m");
2060 s->proc_kmsg_length += l;
2066 static int server_flush_proc_kmsg(Server *s) {
2071 if (s->proc_kmsg_fd < 0)
2074 log_info("Flushing /proc/kmsg...");
2077 r = server_read_proc_kmsg(s);
2088 static int process_event(Server *s, struct epoll_event *ev) {
2091 if (ev->data.fd == s->signal_fd) {
2092 struct signalfd_siginfo sfsi;
2095 if (ev->events != EPOLLIN) {
2096 log_info("Got invalid event from epoll.");
2100 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2101 if (n != sizeof(sfsi)) {
2106 if (errno == EINTR || errno == EAGAIN)
2112 if (sfsi.ssi_signo == SIGUSR1) {
2113 server_flush_to_var(s);
2117 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2120 } else if (ev->data.fd == s->proc_kmsg_fd) {
2123 if (ev->events != EPOLLIN) {
2124 log_info("Got invalid event from epoll.");
2128 r = server_read_proc_kmsg(s);
2134 } else if (ev->data.fd == s->native_fd ||
2135 ev->data.fd == s->syslog_fd) {
2137 if (ev->events != EPOLLIN) {
2138 log_info("Got invalid event from epoll.");
2143 struct msghdr msghdr;
2145 struct ucred *ucred = NULL;
2146 struct timeval *tv = NULL;
2147 struct cmsghdr *cmsg;
2149 size_t label_len = 0;
2151 struct cmsghdr cmsghdr;
2152 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2153 CMSG_SPACE(sizeof(struct timeval)) +
2154 CMSG_SPACE(sizeof(int)) +
2155 CMSG_SPACE(PAGE_SIZE)]; /* selinux label */
2162 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2163 log_error("SIOCINQ failed: %m");
2167 if (s->buffer_size < (size_t) v) {
2171 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2172 b = realloc(s->buffer, l+1);
2175 log_error("Couldn't increase buffer.");
2184 iovec.iov_base = s->buffer;
2185 iovec.iov_len = s->buffer_size;
2189 msghdr.msg_iov = &iovec;
2190 msghdr.msg_iovlen = 1;
2191 msghdr.msg_control = &control;
2192 msghdr.msg_controllen = sizeof(control);
2194 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2197 if (errno == EINTR || errno == EAGAIN)
2200 log_error("recvmsg() failed: %m");
2204 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2206 if (cmsg->cmsg_level == SOL_SOCKET &&
2207 cmsg->cmsg_type == SCM_CREDENTIALS &&
2208 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2209 ucred = (struct ucred*) CMSG_DATA(cmsg);
2210 else if (cmsg->cmsg_level == SOL_SOCKET &&
2211 cmsg->cmsg_type == SCM_SECURITY) {
2212 label = (char*) CMSG_DATA(cmsg);
2213 label_len = cmsg->cmsg_len - CMSG_LEN(0);
2214 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2215 cmsg->cmsg_type == SO_TIMESTAMP &&
2216 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2217 tv = (struct timeval*) CMSG_DATA(cmsg);
2218 else if (cmsg->cmsg_level == SOL_SOCKET &&
2219 cmsg->cmsg_type == SCM_RIGHTS) {
2220 fds = (int*) CMSG_DATA(cmsg);
2221 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2225 if (ev->data.fd == s->syslog_fd) {
2228 if (n > 0 && n_fds == 0) {
2229 e = memchr(s->buffer, '\n', n);
2235 process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
2236 } else if (n_fds > 0)
2237 log_warning("Got file descriptors via syslog socket. Ignoring.");
2240 if (n > 0 && n_fds == 0)
2241 process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
2242 else if (n == 0 && n_fds == 1)
2243 process_native_file(s, fds[0], ucred, tv, label, label_len);
2245 log_warning("Got too many file descriptors via native socket. Ignoring.");
2248 close_many(fds, n_fds);
2253 } else if (ev->data.fd == s->stdout_fd) {
2255 if (ev->events != EPOLLIN) {
2256 log_info("Got invalid event from epoll.");
2260 stdout_stream_new(s);
2264 StdoutStream *stream;
2266 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2267 log_info("Got invalid event from epoll.");
2271 /* If it is none of the well-known fds, it must be an
2272 * stdout stream fd. Note that this is a bit ugly here
2273 * (since we rely that none of the well-known fds
2274 * could be interpreted as pointer), but nonetheless
2275 * safe, since the well-known fds would never get an
2276 * fd > 4096, i.e. beyond the first memory page */
2278 stream = ev->data.ptr;
2280 if (stdout_stream_process(stream) <= 0)
2281 stdout_stream_free(stream);
2286 log_error("Unknown event.");
2290 static int open_syslog_socket(Server *s) {
2291 union sockaddr_union sa;
2293 struct epoll_event ev;
2297 if (s->syslog_fd < 0) {
2299 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2300 if (s->syslog_fd < 0) {
2301 log_error("socket() failed: %m");
2306 sa.un.sun_family = AF_UNIX;
2307 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2309 unlink(sa.un.sun_path);
2311 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2313 log_error("bind() failed: %m");
2317 chmod(sa.un.sun_path, 0666);
2319 fd_nonblock(s->syslog_fd, 1);
2322 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2324 log_error("SO_PASSCRED failed: %m");
2330 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2332 log_warning("SO_PASSSEC failed: %m");
2336 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2338 log_error("SO_TIMESTAMP failed: %m");
2343 ev.events = EPOLLIN;
2344 ev.data.fd = s->syslog_fd;
2345 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2346 log_error("Failed to add syslog server fd to epoll object: %m");
2353 static int open_native_socket(Server*s) {
2354 union sockaddr_union sa;
2356 struct epoll_event ev;
2360 if (s->native_fd < 0) {
2362 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2363 if (s->native_fd < 0) {
2364 log_error("socket() failed: %m");
2369 sa.un.sun_family = AF_UNIX;
2370 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2372 unlink(sa.un.sun_path);
2374 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2376 log_error("bind() failed: %m");
2380 chmod(sa.un.sun_path, 0666);
2382 fd_nonblock(s->native_fd, 1);
2385 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2387 log_error("SO_PASSCRED failed: %m");
2393 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2395 log_warning("SO_PASSSEC failed: %m");
2399 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2401 log_error("SO_TIMESTAMP failed: %m");
2406 ev.events = EPOLLIN;
2407 ev.data.fd = s->native_fd;
2408 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2409 log_error("Failed to add native server fd to epoll object: %m");
2416 static int open_stdout_socket(Server *s) {
2417 union sockaddr_union sa;
2419 struct epoll_event ev;
2423 if (s->stdout_fd < 0) {
2425 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2426 if (s->stdout_fd < 0) {
2427 log_error("socket() failed: %m");
2432 sa.un.sun_family = AF_UNIX;
2433 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2435 unlink(sa.un.sun_path);
2437 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2439 log_error("bind() failed: %m");
2443 chmod(sa.un.sun_path, 0666);
2445 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2446 log_error("liste() failed: %m");
2450 fd_nonblock(s->stdout_fd, 1);
2453 ev.events = EPOLLIN;
2454 ev.data.fd = s->stdout_fd;
2455 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2456 log_error("Failed to add stdout server fd to epoll object: %m");
2463 static int open_proc_kmsg(Server *s) {
2464 struct epoll_event ev;
2468 if (!s->import_proc_kmsg)
2472 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2473 if (s->proc_kmsg_fd < 0) {
2474 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2479 ev.events = EPOLLIN;
2480 ev.data.fd = s->proc_kmsg_fd;
2481 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2482 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2489 static int open_signalfd(Server *s) {
2491 struct epoll_event ev;
2495 assert_se(sigemptyset(&mask) == 0);
2496 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2497 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2499 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2500 if (s->signal_fd < 0) {
2501 log_error("signalfd(): %m");
2506 ev.events = EPOLLIN;
2507 ev.data.fd = s->signal_fd;
2509 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2510 log_error("epoll_ctl(): %m");
2517 static int server_parse_proc_cmdline(Server *s) {
2518 char *line, *w, *state;
2522 if (detect_container(NULL) > 0)
2525 r = read_one_line_file("/proc/cmdline", &line);
2527 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2531 FOREACH_WORD_QUOTED(w, l, line, state) {
2534 word = strndup(w, l);
2540 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2541 r = parse_boolean(word + 35);
2543 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2545 s->forward_to_syslog = r;
2546 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2547 r = parse_boolean(word + 33);
2549 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2551 s->forward_to_kmsg = r;
2552 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2553 r = parse_boolean(word + 36);
2555 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2557 s->forward_to_console = r;
2570 static int server_parse_config_file(Server *s) {
2577 fn = "/etc/systemd/systemd-journald.conf";
2578 f = fopen(fn, "re");
2580 if (errno == ENOENT)
2583 log_warning("Failed to open configuration file %s: %m", fn);
2587 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2589 log_warning("Failed to parse configuration file: %s", strerror(-r));
2596 static int server_init(Server *s) {
2602 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2605 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2606 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2608 s->forward_to_syslog = true;
2609 s->import_proc_kmsg = true;
2611 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2612 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2614 server_parse_config_file(s);
2615 server_parse_proc_cmdline(s);
2617 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2618 if (!s->user_journals) {
2619 log_error("Out of memory.");
2623 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2624 if (s->epoll_fd < 0) {
2625 log_error("Failed to create epoll object: %m");
2629 n = sd_listen_fds(true);
2631 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2635 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2637 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2639 if (s->native_fd >= 0) {
2640 log_error("Too many native sockets passed.");
2646 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2648 if (s->stdout_fd >= 0) {
2649 log_error("Too many stdout sockets passed.");
2655 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2657 if (s->syslog_fd >= 0) {
2658 log_error("Too many /dev/log sockets passed.");
2665 log_error("Unknown socket passed.");
2670 r = open_syslog_socket(s);
2674 r = open_native_socket(s);
2678 r = open_stdout_socket(s);
2682 r = open_proc_kmsg(s);
2686 r = open_signalfd(s);
2690 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2694 r = system_journal_open(s);
2701 static void server_done(Server *s) {
2705 while (s->stdout_streams)
2706 stdout_stream_free(s->stdout_streams);
2708 if (s->system_journal)
2709 journal_file_close(s->system_journal);
2711 if (s->runtime_journal)
2712 journal_file_close(s->runtime_journal);
2714 while ((f = hashmap_steal_first(s->user_journals)))
2715 journal_file_close(f);
2717 hashmap_free(s->user_journals);
2719 if (s->epoll_fd >= 0)
2720 close_nointr_nofail(s->epoll_fd);
2722 if (s->signal_fd >= 0)
2723 close_nointr_nofail(s->signal_fd);
2725 if (s->syslog_fd >= 0)
2726 close_nointr_nofail(s->syslog_fd);
2728 if (s->native_fd >= 0)
2729 close_nointr_nofail(s->native_fd);
2731 if (s->stdout_fd >= 0)
2732 close_nointr_nofail(s->stdout_fd);
2734 if (s->proc_kmsg_fd >= 0)
2735 close_nointr_nofail(s->proc_kmsg_fd);
2738 journal_rate_limit_free(s->rate_limit);
2743 int main(int argc, char *argv[]) {
2747 /* if (getppid() != 1) { */
2748 /* log_error("This program should be invoked by init only."); */
2749 /* return EXIT_FAILURE; */
2753 log_error("This program does not take arguments.");
2754 return EXIT_FAILURE;
2757 log_set_target(LOG_TARGET_CONSOLE);
2758 log_parse_environment();
2763 r = server_init(&server);
2767 server_vacuum(&server);
2768 server_flush_to_var(&server);
2769 server_flush_proc_kmsg(&server);
2771 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2772 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2776 "STATUS=Processing requests...");
2779 struct epoll_event event;
2781 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2787 log_error("epoll_wait() failed: %m");
2793 r = process_event(&server, &event);
2800 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2801 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2805 "STATUS=Shutting down...");
2807 server_done(&server);
2809 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;