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>
33 #include <systemd/sd-journal.h>
34 #include <systemd/sd-login.h>
35 #include <systemd/sd-messages.h>
36 #include <systemd/sd-daemon.h>
39 #include "journal-file.h"
40 #include "socket-util.h"
41 #include "cgroup-util.h"
43 #include "journal-rate-limit.h"
44 #include "journal-internal.h"
45 #include "conf-parser.h"
52 #include <acl/libacl.h>
57 #include <selinux/selinux.h>
60 #define USER_JOURNALS_MAX 1024
61 #define STDOUT_STREAMS_MAX 4096
63 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
64 #define DEFAULT_RATE_LIMIT_BURST 200
66 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
68 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
70 #define N_IOVEC_META_FIELDS 17
72 #define ENTRY_SIZE_MAX (1024*1024*32)
74 typedef enum StdoutStreamState {
75 STDOUT_STREAM_IDENTIFIER,
76 STDOUT_STREAM_PRIORITY,
77 STDOUT_STREAM_LEVEL_PREFIX,
78 STDOUT_STREAM_FORWARD_TO_SYSLOG,
79 STDOUT_STREAM_FORWARD_TO_KMSG,
80 STDOUT_STREAM_FORWARD_TO_CONSOLE,
86 StdoutStreamState state;
92 security_context_t security_context;
98 bool forward_to_syslog:1;
99 bool forward_to_kmsg:1;
100 bool forward_to_console:1;
102 char buffer[LINE_MAX+1];
105 LIST_FIELDS(StdoutStream, stdout_stream);
108 static int server_flush_to_var(Server *s);
110 static uint64_t available_space(Server *s) {
115 uint64_t sum = 0, avail = 0, ss_avail = 0;
121 ts = now(CLOCK_MONOTONIC);
123 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
124 return s->cached_available_space;
126 r = sd_id128_get_machine(&machine);
130 if (s->system_journal) {
131 f = "/var/log/journal/";
132 m = &s->system_metrics;
134 f = "/run/log/journal/";
135 m = &s->runtime_metrics;
140 p = strappend(f, sd_id128_to_string(machine, ids));
150 if (fstatvfs(dirfd(d), &ss) < 0)
155 struct dirent buf, *de;
158 k = readdir_r(d, &buf, &de);
167 if (!dirent_is_file_with_suffix(de, ".journal"))
170 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
173 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
176 avail = sum >= m->max_use ? 0 : m->max_use - sum;
178 ss_avail = ss.f_bsize * ss.f_bavail;
180 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
182 if (ss_avail < avail)
185 s->cached_available_space = avail;
186 s->cached_available_space_timestamp = ts;
194 static void server_read_file_gid(Server *s) {
195 const char *adm = "adm";
200 if (s->file_gid_valid)
203 r = get_group_creds(&adm, &s->file_gid);
205 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
207 /* if we couldn't read the gid, then it will be 0, but that's
208 * fine and we shouldn't try to resolve the group again, so
209 * let's just pretend it worked right-away. */
210 s->file_gid_valid = true;
213 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
218 acl_permset_t permset;
223 server_read_file_gid(s);
225 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
227 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
233 acl = acl_get_fd(f->fd);
235 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
239 r = acl_find_uid(acl, uid, &entry);
242 if (acl_create_entry(&acl, &entry) < 0 ||
243 acl_set_tag_type(entry, ACL_USER) < 0 ||
244 acl_set_qualifier(entry, &uid) < 0) {
245 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
250 if (acl_get_permset(entry, &permset) < 0 ||
251 acl_add_perm(permset, ACL_READ) < 0 ||
252 acl_calc_mask(&acl) < 0) {
253 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
257 if (acl_set_fd(f->fd, acl) < 0)
258 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
265 static JournalFile* find_journal(Server *s, uid_t uid) {
274 /* We split up user logs only on /var, not on /run. If the
275 * runtime file is open, we write to it exclusively, in order
276 * to guarantee proper order as soon as we flush /run to
277 * /var and close the runtime file. */
279 if (s->runtime_journal)
280 return s->runtime_journal;
283 return s->system_journal;
285 r = sd_id128_get_machine(&machine);
287 return s->system_journal;
289 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
293 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
294 return s->system_journal;
296 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
297 /* Too many open? Then let's close one */
298 f = hashmap_steal_first(s->user_journals);
300 journal_file_close(f);
303 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
307 return s->system_journal;
309 server_fix_perms(s, f, uid);
310 f->metrics = s->system_metrics;
311 f->compress = s->compress;
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));
336 if (s->system_journal) {
337 r = journal_file_rotate(&s->system_journal);
339 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
342 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
343 r = journal_file_rotate(&f);
345 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
347 hashmap_replace(s->user_journals, k, f);
351 static void server_vacuum(Server *s) {
357 log_info("Vacuuming...");
359 r = sd_id128_get_machine(&machine);
361 log_error("Failed to get machine ID: %s", strerror(-r));
365 sd_id128_to_string(machine, ids);
367 if (s->system_journal) {
368 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
369 log_error("Out of memory.");
373 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
374 if (r < 0 && r != -ENOENT)
375 log_error("Failed to vacuum %s: %s", p, strerror(-r));
380 if (s->runtime_journal) {
381 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
382 log_error("Out of memory.");
386 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
387 if (r < 0 && r != -ENOENT)
388 log_error("Failed to vacuum %s: %s", p, strerror(-r));
392 s->cached_available_space_timestamp = 0;
395 static char *shortened_cgroup_path(pid_t pid) {
397 char *process_path, *init_path, *path;
401 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
405 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
411 if (endswith(init_path, "/system"))
412 init_path[strlen(init_path) - 7] = 0;
413 else if (streq(init_path, "/"))
416 if (startswith(process_path, init_path)) {
419 p = strdup(process_path + strlen(init_path));
437 static void dispatch_message_real(
439 struct iovec *iovec, unsigned n, unsigned m,
442 const char *label, size_t label_len) {
444 char *pid = NULL, *uid = NULL, *gid = NULL,
445 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
446 *comm = NULL, *cmdline = NULL, *hostname = NULL,
447 *audit_session = NULL, *audit_loginuid = NULL,
448 *exe = NULL, *cgroup = NULL, *session = NULL,
449 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
455 uid_t loginuid = 0, realuid = 0;
457 bool vacuumed = false;
462 assert(n + N_IOVEC_META_FIELDS <= m);
468 realuid = ucred->uid;
470 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
471 IOVEC_SET_STRING(iovec[n++], pid);
473 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
474 IOVEC_SET_STRING(iovec[n++], uid);
476 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
477 IOVEC_SET_STRING(iovec[n++], gid);
479 r = get_process_comm(ucred->pid, &t);
481 comm = strappend("_COMM=", t);
485 IOVEC_SET_STRING(iovec[n++], comm);
488 r = get_process_exe(ucred->pid, &t);
490 exe = strappend("_EXE=", t);
494 IOVEC_SET_STRING(iovec[n++], exe);
497 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
499 cmdline = strappend("_CMDLINE=", t);
503 IOVEC_SET_STRING(iovec[n++], cmdline);
506 r = audit_session_from_pid(ucred->pid, &audit);
508 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
509 IOVEC_SET_STRING(iovec[n++], audit_session);
511 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
513 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
514 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
516 t = shortened_cgroup_path(ucred->pid);
518 cgroup = strappend("_SYSTEMD_CGROUP=", t);
522 IOVEC_SET_STRING(iovec[n++], cgroup);
525 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
526 session = strappend("_SYSTEMD_SESSION=", t);
530 IOVEC_SET_STRING(iovec[n++], session);
533 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
534 unit = strappend("_SYSTEMD_UNIT=", t);
538 IOVEC_SET_STRING(iovec[n++], unit);
541 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
542 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
543 IOVEC_SET_STRING(iovec[n++], owner_uid);
547 selinux_context = malloc(sizeof("_SELINUX_CONTEXT=") + label_len);
548 if (selinux_context) {
549 memcpy(selinux_context, "_SELINUX_CONTEXT=", sizeof("_SELINUX_CONTEXT=")-1);
550 memcpy(selinux_context+sizeof("_SELINUX_CONTEXT=")-1, label, label_len);
551 selinux_context[sizeof("_SELINUX_CONTEXT=")-1+label_len] = 0;
552 IOVEC_SET_STRING(iovec[n++], selinux_context);
555 security_context_t con;
557 if (getpidcon(ucred->pid, &con) >= 0) {
558 selinux_context = strappend("_SELINUX_CONTEXT=", con);
560 IOVEC_SET_STRING(iovec[n++], selinux_context);
569 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
570 (unsigned long long) timeval_load(tv)) >= 0)
571 IOVEC_SET_STRING(iovec[n++], source_time);
574 /* Note that strictly speaking storing the boot id here is
575 * redundant since the entry includes this in-line
576 * anyway. However, we need this indexed, too. */
577 r = sd_id128_get_boot(&id);
579 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
580 IOVEC_SET_STRING(iovec[n++], boot_id);
582 r = sd_id128_get_machine(&id);
584 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
585 IOVEC_SET_STRING(iovec[n++], machine_id);
587 t = gethostname_malloc();
589 hostname = strappend("_HOSTNAME=", t);
592 IOVEC_SET_STRING(iovec[n++], hostname);
597 server_flush_to_var(s);
600 f = find_journal(s, realuid == 0 ? 0 : loginuid);
602 log_warning("Dropping message, as we can't find a place to store the data.");
604 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
606 if (r == -E2BIG && !vacuumed) {
607 log_info("Allocation limit reached.");
613 log_info("Retrying write.");
618 log_error("Failed to write entry, ignoring: %s", strerror(-r));
632 free(audit_loginuid);
637 free(selinux_context);
640 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
641 char mid[11 + 32 + 1];
642 char buffer[16 + LINE_MAX + 1];
643 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
651 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
652 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
654 memcpy(buffer, "MESSAGE=", 8);
655 va_start(ap, format);
656 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
658 char_array_0(buffer);
659 IOVEC_SET_STRING(iovec[n++], buffer);
661 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
663 IOVEC_SET_STRING(iovec[n++], mid);
666 ucred.pid = getpid();
667 ucred.uid = getuid();
668 ucred.gid = getgid();
670 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0);
673 static void dispatch_message(Server *s,
674 struct iovec *iovec, unsigned n, unsigned m,
677 const char *label, size_t label_len,
680 char *path = NULL, *c;
683 assert(iovec || n == 0);
691 path = shortened_cgroup_path(ucred->pid);
695 /* example: /user/lennart/3/foobar
696 * /system/dbus.service/foobar
698 * So let's cut of everything past the third /, since that is
699 * wher user directories start */
701 c = strchr(path, '/');
703 c = strchr(c+1, '/');
705 c = strchr(c+1, '/');
711 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
718 /* Write a suppression message if we suppressed something */
720 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
725 dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len);
728 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
729 struct msghdr msghdr;
730 struct cmsghdr *cmsg;
732 struct cmsghdr cmsghdr;
733 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
735 union sockaddr_union sa;
742 msghdr.msg_iov = (struct iovec*) iovec;
743 msghdr.msg_iovlen = n_iovec;
746 sa.un.sun_family = AF_UNIX;
747 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
748 msghdr.msg_name = &sa;
749 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
753 msghdr.msg_control = &control;
754 msghdr.msg_controllen = sizeof(control);
756 cmsg = CMSG_FIRSTHDR(&msghdr);
757 cmsg->cmsg_level = SOL_SOCKET;
758 cmsg->cmsg_type = SCM_CREDENTIALS;
759 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
760 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
761 msghdr.msg_controllen = cmsg->cmsg_len;
764 /* Forward the syslog message we received via /dev/log to
765 * /run/systemd/syslog. Unfortunately we currently can't set
766 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
768 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
771 /* The socket is full? I guess the syslog implementation is
772 * too slow, and we shouldn't wait for that... */
776 if (ucred && errno == ESRCH) {
779 /* Hmm, presumably the sender process vanished
780 * by now, so let's fix it as good as we
785 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
787 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
794 log_debug("Failed to forward syslog message: %m");
797 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
803 IOVEC_SET_STRING(iovec, buffer);
804 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
807 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
808 struct iovec iovec[5];
809 char header_priority[6], header_time[64], header_pid[16];
813 char *ident_buf = NULL;
816 assert(priority >= 0);
817 assert(priority <= 999);
820 /* First: priority field */
821 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
822 char_array_0(header_priority);
823 IOVEC_SET_STRING(iovec[n++], header_priority);
825 /* Second: timestamp */
826 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
830 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
832 IOVEC_SET_STRING(iovec[n++], header_time);
834 /* Third: identifier and PID */
837 get_process_comm(ucred->pid, &ident_buf);
838 identifier = ident_buf;
841 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
842 char_array_0(header_pid);
845 IOVEC_SET_STRING(iovec[n++], identifier);
847 IOVEC_SET_STRING(iovec[n++], header_pid);
848 } else if (identifier) {
849 IOVEC_SET_STRING(iovec[n++], identifier);
850 IOVEC_SET_STRING(iovec[n++], ": ");
853 /* Fourth: message */
854 IOVEC_SET_STRING(iovec[n++], message);
856 forward_syslog_iovec(s, iovec, n, ucred, tv);
861 static int fixup_priority(int priority) {
863 if ((priority & LOG_FACMASK) == 0)
864 return (priority & LOG_PRIMASK) | LOG_USER;
869 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
870 struct iovec iovec[5];
871 char header_priority[6], header_pid[16];
873 char *ident_buf = NULL;
877 assert(priority >= 0);
878 assert(priority <= 999);
881 /* Never allow messages with kernel facility to be written to
882 * kmsg, regardless where the data comes from. */
883 priority = fixup_priority(priority);
885 /* First: priority field */
886 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
887 char_array_0(header_priority);
888 IOVEC_SET_STRING(iovec[n++], header_priority);
890 /* Second: identifier and PID */
893 get_process_comm(ucred->pid, &ident_buf);
894 identifier = ident_buf;
897 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
898 char_array_0(header_pid);
901 IOVEC_SET_STRING(iovec[n++], identifier);
903 IOVEC_SET_STRING(iovec[n++], header_pid);
904 } else if (identifier) {
905 IOVEC_SET_STRING(iovec[n++], identifier);
906 IOVEC_SET_STRING(iovec[n++], ": ");
909 /* Fourth: message */
910 IOVEC_SET_STRING(iovec[n++], message);
911 IOVEC_SET_STRING(iovec[n++], "\n");
913 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
915 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
919 if (writev(fd, iovec, n) < 0)
920 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
922 close_nointr_nofail(fd);
928 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
929 struct iovec iovec[4];
932 char *ident_buf = NULL;
937 /* First: identifier and PID */
940 get_process_comm(ucred->pid, &ident_buf);
941 identifier = ident_buf;
944 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
945 char_array_0(header_pid);
948 IOVEC_SET_STRING(iovec[n++], identifier);
950 IOVEC_SET_STRING(iovec[n++], header_pid);
951 } else if (identifier) {
952 IOVEC_SET_STRING(iovec[n++], identifier);
953 IOVEC_SET_STRING(iovec[n++], ": ");
957 IOVEC_SET_STRING(iovec[n++], message);
958 IOVEC_SET_STRING(iovec[n++], "\n");
960 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
962 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
966 if (writev(fd, iovec, n) < 0)
967 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
969 close_nointr_nofail(fd);
975 static void read_identifier(const char **buf, char **identifier, char **pid) {
986 p += strspn(p, WHITESPACE);
987 l = strcspn(p, WHITESPACE);
1002 t = strndup(p+k+1, l-k-2);
1022 *buf += strspn(*buf, WHITESPACE);
1025 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) {
1026 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1027 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1029 int priority = LOG_USER | LOG_INFO;
1030 char *identifier = NULL, *pid = NULL;
1035 if (s->forward_to_syslog)
1036 forward_syslog_raw(s, buf, ucred, tv);
1038 parse_syslog_priority((char**) &buf, &priority);
1039 skip_syslog_date((char**) &buf);
1040 read_identifier(&buf, &identifier, &pid);
1042 if (s->forward_to_kmsg)
1043 forward_kmsg(s, priority, identifier, buf, ucred);
1045 if (s->forward_to_console)
1046 forward_console(s, identifier, buf, ucred);
1048 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1050 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1051 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1053 if (priority & LOG_FACMASK)
1054 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1055 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1058 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1059 if (syslog_identifier)
1060 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1064 syslog_pid = strappend("SYSLOG_PID=", pid);
1066 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1069 message = strappend("MESSAGE=", buf);
1071 IOVEC_SET_STRING(iovec[n++], message);
1073 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, label, label_len, priority);
1078 free(syslog_priority);
1079 free(syslog_facility);
1080 free(syslog_identifier);
1083 static bool valid_user_field(const char *p, size_t l) {
1086 /* We kinda enforce POSIX syntax recommendations for
1087 environment variables here, but make a couple of additional
1090 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1092 /* No empty field names */
1096 /* Don't allow names longer than 64 chars */
1100 /* Variables starting with an underscore are protected */
1104 /* Don't allow digits as first character */
1105 if (p[0] >= '0' && p[0] <= '9')
1108 /* Only allow A-Z0-9 and '_' */
1109 for (a = p; a < p + l; a++)
1110 if (!((*a >= 'A' && *a <= 'Z') ||
1111 (*a >= '0' && *a <= '9') ||
1118 static void process_native_message(
1120 const void *buffer, size_t buffer_size,
1121 struct ucred *ucred,
1123 const char *label, size_t label_len) {
1125 struct iovec *iovec = NULL;
1126 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1129 int priority = LOG_INFO;
1130 char *identifier = NULL, *message = NULL;
1133 assert(buffer || n == 0);
1136 remaining = buffer_size;
1138 while (remaining > 0) {
1141 e = memchr(p, '\n', remaining);
1144 /* Trailing noise, let's ignore it, and flush what we collected */
1145 log_debug("Received message with trailing noise, ignoring.");
1150 /* Entry separator */
1151 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1153 priority = LOG_INFO;
1160 if (*p == '.' || *p == '#') {
1161 /* Ignore control commands for now, and
1163 remaining -= (e - p) + 1;
1168 /* A property follows */
1170 if (n+N_IOVEC_META_FIELDS >= m) {
1174 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1175 c = realloc(iovec, u * sizeof(struct iovec));
1177 log_error("Out of memory");
1185 q = memchr(p, '=', e - p);
1187 if (valid_user_field(p, q - p)) {
1192 /* If the field name starts with an
1193 * underscore, skip the variable,
1194 * since that indidates a trusted
1196 iovec[n].iov_base = (char*) p;
1197 iovec[n].iov_len = l;
1200 /* We need to determine the priority
1201 * of this entry for the rate limiting
1204 memcmp(p, "PRIORITY=", 9) == 0 &&
1205 p[9] >= '0' && p[9] <= '9')
1206 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1209 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1210 p[16] >= '0' && p[16] <= '9')
1211 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1214 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1215 p[16] >= '0' && p[16] <= '9' &&
1216 p[17] >= '0' && p[17] <= '9')
1217 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1220 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1223 t = strndup(p + 11, l - 11);
1228 } else if (l >= 8 &&
1229 memcmp(p, "MESSAGE=", 8) == 0) {
1232 t = strndup(p + 8, l - 8);
1240 remaining -= (e - p) + 1;
1247 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1248 log_debug("Failed to parse message, ignoring.");
1252 memcpy(&l, e + 1, sizeof(uint64_t));
1255 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1256 e[1+sizeof(uint64_t)+l] != '\n') {
1257 log_debug("Failed to parse message, ignoring.");
1261 k = malloc((e - p) + 1 + l);
1263 log_error("Out of memory");
1267 memcpy(k, p, e - p);
1269 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1271 if (valid_user_field(p, e - p)) {
1272 iovec[n].iov_base = k;
1273 iovec[n].iov_len = (e - p) + 1 + l;
1278 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1279 p = e + 1 + sizeof(uint64_t) + l + 1;
1287 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1290 if (s->forward_to_syslog)
1291 forward_syslog(s, priority, identifier, message, ucred, tv);
1293 if (s->forward_to_kmsg)
1294 forward_kmsg(s, priority, identifier, message, ucred);
1296 if (s->forward_to_console)
1297 forward_console(s, identifier, message, ucred);
1300 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1303 for (j = 0; j < n; j++) {
1307 if (iovec[j].iov_base < buffer ||
1308 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1309 free(iovec[j].iov_base);
1316 static void process_native_file(
1319 struct ucred *ucred,
1321 const char *label, size_t label_len) {
1330 /* Data is in the passed file, since it didn't fit in a
1331 * datagram. We can't map the file here, since clients might
1332 * then truncate it and trigger a SIGBUS for us. So let's
1333 * stupidly read it */
1335 if (fstat(fd, &st) < 0) {
1336 log_error("Failed to stat passed file, ignoring: %m");
1340 if (!S_ISREG(st.st_mode)) {
1341 log_error("File passed is not regular. Ignoring.");
1345 if (st.st_size <= 0)
1348 if (st.st_size > ENTRY_SIZE_MAX) {
1349 log_error("File passed too large. Ignoring.");
1353 p = malloc(st.st_size);
1355 log_error("Out of memory");
1359 n = pread(fd, p, st.st_size, 0);
1361 log_error("Failed to read file, ignoring: %s", strerror(-n));
1363 process_native_message(s, p, n, ucred, tv, label, label_len);
1368 static int stdout_stream_log(StdoutStream *s, const char *p) {
1369 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1370 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1374 size_t label_len = 0;
1382 priority = s->priority;
1384 if (s->level_prefix)
1385 parse_syslog_priority((char**) &p, &priority);
1387 if (s->forward_to_syslog || s->server->forward_to_syslog)
1388 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1390 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1391 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1393 if (s->forward_to_console || s->server->forward_to_console)
1394 forward_console(s->server, s->identifier, p, &s->ucred);
1396 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1398 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1399 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1401 if (priority & LOG_FACMASK)
1402 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1403 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1405 if (s->identifier) {
1406 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1407 if (syslog_identifier)
1408 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1411 message = strappend("MESSAGE=", p);
1413 IOVEC_SET_STRING(iovec[n++], message);
1416 if (s->security_context) {
1417 label = (char*) s->security_context;
1418 label_len = strlen((char*) s->security_context);
1422 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, priority);
1425 free(syslog_priority);
1426 free(syslog_facility);
1427 free(syslog_identifier);
1432 static int stdout_stream_line(StdoutStream *s, char *p) {
1442 case STDOUT_STREAM_IDENTIFIER:
1444 s->identifier = NULL;
1446 s->identifier = strdup(p);
1447 if (!s->identifier) {
1448 log_error("Out of memory");
1453 s->state = STDOUT_STREAM_PRIORITY;
1456 case STDOUT_STREAM_PRIORITY:
1457 r = safe_atoi(p, &s->priority);
1458 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1459 log_warning("Failed to parse log priority line.");
1463 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1466 case STDOUT_STREAM_LEVEL_PREFIX:
1467 r = parse_boolean(p);
1469 log_warning("Failed to parse level prefix line.");
1473 s->level_prefix = !!r;
1474 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1477 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1478 r = parse_boolean(p);
1480 log_warning("Failed to parse forward to syslog line.");
1484 s->forward_to_syslog = !!r;
1485 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1488 case STDOUT_STREAM_FORWARD_TO_KMSG:
1489 r = parse_boolean(p);
1491 log_warning("Failed to parse copy to kmsg line.");
1495 s->forward_to_kmsg = !!r;
1496 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1499 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1500 r = parse_boolean(p);
1502 log_warning("Failed to parse copy to console line.");
1506 s->forward_to_console = !!r;
1507 s->state = STDOUT_STREAM_RUNNING;
1510 case STDOUT_STREAM_RUNNING:
1511 return stdout_stream_log(s, p);
1514 assert_not_reached("Unknown stream state");
1517 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1525 remaining = s->length;
1530 end = memchr(p, '\n', remaining);
1533 else if (remaining >= sizeof(s->buffer) - 1) {
1534 end = p + sizeof(s->buffer) - 1;
1541 r = stdout_stream_line(s, p);
1549 if (force_flush && remaining > 0) {
1551 r = stdout_stream_line(s, p);
1559 if (p > s->buffer) {
1560 memmove(s->buffer, p, remaining);
1561 s->length = remaining;
1567 static int stdout_stream_process(StdoutStream *s) {
1573 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1576 if (errno == EAGAIN)
1579 log_warning("Failed to read from stream: %m");
1584 r = stdout_stream_scan(s, true);
1592 r = stdout_stream_scan(s, false);
1600 static void stdout_stream_free(StdoutStream *s) {
1604 assert(s->server->n_stdout_streams > 0);
1605 s->server->n_stdout_streams --;
1606 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1611 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1613 close_nointr_nofail(s->fd);
1617 if (s->security_context)
1618 freecon(s->security_context);
1621 free(s->identifier);
1625 static int stdout_stream_new(Server *s) {
1626 StdoutStream *stream;
1629 struct epoll_event ev;
1633 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1635 if (errno == EAGAIN)
1638 log_error("Failed to accept stdout connection: %m");
1642 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1643 log_warning("Too many stdout streams, refusing connection.");
1644 close_nointr_nofail(fd);
1648 stream = new0(StdoutStream, 1);
1650 log_error("Out of memory.");
1651 close_nointr_nofail(fd);
1657 len = sizeof(stream->ucred);
1658 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1659 log_error("Failed to determine peer credentials: %m");
1665 if (getpeercon(fd, &stream->security_context) < 0)
1666 log_error("Failed to determine peer security context.");
1669 if (shutdown(fd, SHUT_WR) < 0) {
1670 log_error("Failed to shutdown writing side of socket: %m");
1676 ev.data.ptr = stream;
1677 ev.events = EPOLLIN;
1678 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1679 log_error("Failed to add stream to event loop: %m");
1685 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1686 s->n_stdout_streams ++;
1691 stdout_stream_free(stream);
1695 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1706 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1711 for (i = 1; i <= 5; i++) {
1717 k = undecchar(p[i]);
1724 for (i = 7; i <= 12; i++) {
1727 k = undecchar(p[i]);
1736 *_p += strspn(*_p, WHITESPACE);
1741 static void proc_kmsg_line(Server *s, const char *p) {
1742 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1743 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1744 int priority = LOG_KERN | LOG_INFO;
1747 char *identifier = NULL, *pid = NULL;
1755 parse_syslog_priority((char **) &p, &priority);
1757 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1760 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1761 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1762 (unsigned long long) usec) >= 0)
1763 IOVEC_SET_STRING(iovec[n++], source_time);
1766 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1768 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1769 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1771 if ((priority & LOG_FACMASK) == LOG_KERN) {
1773 if (s->forward_to_syslog)
1774 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1776 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1778 read_identifier(&p, &identifier, &pid);
1780 if (s->forward_to_syslog)
1781 forward_syslog(s, priority, identifier, p, NULL, NULL);
1784 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1785 if (syslog_identifier)
1786 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1790 syslog_pid = strappend("SYSLOG_PID=", pid);
1792 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1795 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1796 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1799 message = strappend("MESSAGE=", p);
1801 IOVEC_SET_STRING(iovec[n++], message);
1803 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, priority);
1806 free(syslog_priority);
1807 free(syslog_identifier);
1809 free(syslog_facility);
1815 static void proc_kmsg_scan(Server *s) {
1821 p = s->proc_kmsg_buffer;
1822 remaining = s->proc_kmsg_length;
1827 end = memchr(p, '\n', remaining);
1830 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1831 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1838 proc_kmsg_line(s, p);
1844 if (p > s->proc_kmsg_buffer) {
1845 memmove(s->proc_kmsg_buffer, p, remaining);
1846 s->proc_kmsg_length = remaining;
1850 static int system_journal_open(Server *s) {
1856 r = sd_id128_get_machine(&machine);
1860 sd_id128_to_string(machine, ids);
1862 if (!s->system_journal) {
1864 /* First try to create the machine path, but not the prefix */
1865 fn = strappend("/var/log/journal/", ids);
1868 (void) mkdir(fn, 0755);
1871 /* The create the system journal file */
1872 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1876 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1880 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1882 s->system_journal->metrics = s->system_metrics;
1883 s->system_journal->compress = s->compress;
1885 server_fix_perms(s, s->system_journal, 0);
1888 if (r != -ENOENT && r != -EROFS)
1889 log_warning("Failed to open system journal: %s", strerror(-r));
1895 if (!s->runtime_journal) {
1897 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1901 if (s->system_journal) {
1903 /* Try to open the runtime journal, but only
1904 * if it already exists, so that we can flush
1905 * it into the system journal */
1907 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1912 log_warning("Failed to open runtime journal: %s", strerror(-r));
1919 /* OK, we really need the runtime journal, so create
1920 * it if necessary. */
1922 (void) mkdir_parents(fn, 0755);
1923 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1927 log_error("Failed to open runtime journal: %s", strerror(-r));
1932 if (s->runtime_journal) {
1933 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1935 s->runtime_journal->metrics = s->runtime_metrics;
1936 s->runtime_journal->compress = s->compress;
1938 server_fix_perms(s, s->runtime_journal, 0);
1945 static int server_flush_to_var(Server *s) {
1946 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1955 if (!s->runtime_journal)
1958 ts = now(CLOCK_MONOTONIC);
1959 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1962 s->var_available_timestamp = ts;
1964 system_journal_open(s);
1966 if (!s->system_journal)
1969 log_info("Flushing to /var...");
1971 r = sd_id128_get_machine(&machine);
1973 log_error("Failed to get machine id: %s", strerror(-r));
1977 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1979 log_error("Failed to read runtime journal: %s", strerror(-r));
1983 SD_JOURNAL_FOREACH(j) {
1986 f = j->current_file;
1987 assert(f && f->current_offset > 0);
1989 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1991 log_error("Can't read entry: %s", strerror(-r));
1995 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1997 log_info("Allocation limit reached.");
1999 journal_file_post_change(s->system_journal);
2003 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2007 log_error("Can't write entry: %s", strerror(-r));
2013 journal_file_post_change(s->system_journal);
2015 journal_file_close(s->runtime_journal);
2016 s->runtime_journal = NULL;
2019 sd_id128_to_string(machine, path + 17);
2020 rm_rf(path, false, true, false);
2026 static int server_read_proc_kmsg(Server *s) {
2029 assert(s->proc_kmsg_fd >= 0);
2031 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
2034 if (errno == EAGAIN || errno == EINTR)
2037 log_error("Failed to read from kernel: %m");
2041 s->proc_kmsg_length += l;
2047 static int server_flush_proc_kmsg(Server *s) {
2052 if (s->proc_kmsg_fd < 0)
2055 log_info("Flushing /proc/kmsg...");
2058 r = server_read_proc_kmsg(s);
2069 static int process_event(Server *s, struct epoll_event *ev) {
2072 if (ev->data.fd == s->signal_fd) {
2073 struct signalfd_siginfo sfsi;
2076 if (ev->events != EPOLLIN) {
2077 log_info("Got invalid event from epoll.");
2081 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2082 if (n != sizeof(sfsi)) {
2087 if (errno == EINTR || errno == EAGAIN)
2093 if (sfsi.ssi_signo == SIGUSR1) {
2094 server_flush_to_var(s);
2098 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2101 } else if (ev->data.fd == s->proc_kmsg_fd) {
2104 if (ev->events != EPOLLIN) {
2105 log_info("Got invalid event from epoll.");
2109 r = server_read_proc_kmsg(s);
2115 } else if (ev->data.fd == s->native_fd ||
2116 ev->data.fd == s->syslog_fd) {
2118 if (ev->events != EPOLLIN) {
2119 log_info("Got invalid event from epoll.");
2124 struct msghdr msghdr;
2126 struct ucred *ucred = NULL;
2127 struct timeval *tv = NULL;
2128 struct cmsghdr *cmsg;
2130 size_t label_len = 0;
2132 struct cmsghdr cmsghdr;
2133 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2134 CMSG_SPACE(sizeof(struct timeval)) +
2135 CMSG_SPACE(sizeof(int)) +
2136 CMSG_SPACE(LINE_MAX)]; /* selinux label */
2143 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2144 log_error("SIOCINQ failed: %m");
2148 if (s->buffer_size < (size_t) v) {
2152 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2153 b = realloc(s->buffer, l+1);
2156 log_error("Couldn't increase buffer.");
2165 iovec.iov_base = s->buffer;
2166 iovec.iov_len = s->buffer_size;
2170 msghdr.msg_iov = &iovec;
2171 msghdr.msg_iovlen = 1;
2172 msghdr.msg_control = &control;
2173 msghdr.msg_controllen = sizeof(control);
2175 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2178 if (errno == EINTR || errno == EAGAIN)
2181 log_error("recvmsg() failed: %m");
2185 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2187 if (cmsg->cmsg_level == SOL_SOCKET &&
2188 cmsg->cmsg_type == SCM_CREDENTIALS &&
2189 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2190 ucred = (struct ucred*) CMSG_DATA(cmsg);
2191 else if (cmsg->cmsg_level == SOL_SOCKET &&
2192 cmsg->cmsg_type == SCM_SECURITY) {
2193 label = (char*) CMSG_DATA(cmsg);
2194 label_len = cmsg->cmsg_len - CMSG_LEN(0);
2195 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2196 cmsg->cmsg_type == SO_TIMESTAMP &&
2197 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2198 tv = (struct timeval*) CMSG_DATA(cmsg);
2199 else if (cmsg->cmsg_level == SOL_SOCKET &&
2200 cmsg->cmsg_type == SCM_RIGHTS) {
2201 fds = (int*) CMSG_DATA(cmsg);
2202 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2206 if (ev->data.fd == s->syslog_fd) {
2209 if (n > 0 && n_fds == 0) {
2210 e = memchr(s->buffer, '\n', n);
2216 process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
2217 } else if (n_fds > 0)
2218 log_warning("Got file descriptors via syslog socket. Ignoring.");
2221 if (n > 0 && n_fds == 0)
2222 process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
2223 else if (n == 0 && n_fds == 1)
2224 process_native_file(s, fds[0], ucred, tv, label, label_len);
2226 log_warning("Got too many file descriptors via native socket. Ignoring.");
2229 close_many(fds, n_fds);
2234 } else if (ev->data.fd == s->stdout_fd) {
2236 if (ev->events != EPOLLIN) {
2237 log_info("Got invalid event from epoll.");
2241 stdout_stream_new(s);
2245 StdoutStream *stream;
2247 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2248 log_info("Got invalid event from epoll.");
2252 /* If it is none of the well-known fds, it must be an
2253 * stdout stream fd. Note that this is a bit ugly here
2254 * (since we rely that none of the well-known fds
2255 * could be interpreted as pointer), but nonetheless
2256 * safe, since the well-known fds would never get an
2257 * fd > 4096, i.e. beyond the first memory page */
2259 stream = ev->data.ptr;
2261 if (stdout_stream_process(stream) <= 0)
2262 stdout_stream_free(stream);
2267 log_error("Unknown event.");
2271 static int open_syslog_socket(Server *s) {
2272 union sockaddr_union sa;
2274 struct epoll_event ev;
2278 if (s->syslog_fd < 0) {
2280 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2281 if (s->syslog_fd < 0) {
2282 log_error("socket() failed: %m");
2287 sa.un.sun_family = AF_UNIX;
2288 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2290 unlink(sa.un.sun_path);
2292 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2294 log_error("bind() failed: %m");
2298 chmod(sa.un.sun_path, 0666);
2300 fd_nonblock(s->syslog_fd, 1);
2303 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2305 log_error("SO_PASSCRED failed: %m");
2310 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2312 log_warning("SO_PASSSEC failed: %m");
2315 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2317 log_error("SO_TIMESTAMP failed: %m");
2322 ev.events = EPOLLIN;
2323 ev.data.fd = s->syslog_fd;
2324 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2325 log_error("Failed to add syslog server fd to epoll object: %m");
2332 static int open_native_socket(Server*s) {
2333 union sockaddr_union sa;
2335 struct epoll_event ev;
2339 if (s->native_fd < 0) {
2341 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2342 if (s->native_fd < 0) {
2343 log_error("socket() failed: %m");
2348 sa.un.sun_family = AF_UNIX;
2349 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2351 unlink(sa.un.sun_path);
2353 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2355 log_error("bind() failed: %m");
2359 chmod(sa.un.sun_path, 0666);
2361 fd_nonblock(s->native_fd, 1);
2364 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2366 log_error("SO_PASSCRED failed: %m");
2371 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2373 log_warning("SO_PASSSEC failed: %m");
2376 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2378 log_error("SO_TIMESTAMP failed: %m");
2383 ev.events = EPOLLIN;
2384 ev.data.fd = s->native_fd;
2385 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2386 log_error("Failed to add native server fd to epoll object: %m");
2393 static int open_stdout_socket(Server *s) {
2394 union sockaddr_union sa;
2396 struct epoll_event ev;
2400 if (s->stdout_fd < 0) {
2402 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2403 if (s->stdout_fd < 0) {
2404 log_error("socket() failed: %m");
2409 sa.un.sun_family = AF_UNIX;
2410 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2412 unlink(sa.un.sun_path);
2414 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2416 log_error("bind() failed: %m");
2420 chmod(sa.un.sun_path, 0666);
2422 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2423 log_error("liste() failed: %m");
2427 fd_nonblock(s->stdout_fd, 1);
2430 ev.events = EPOLLIN;
2431 ev.data.fd = s->stdout_fd;
2432 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2433 log_error("Failed to add stdout server fd to epoll object: %m");
2440 static int open_proc_kmsg(Server *s) {
2441 struct epoll_event ev;
2445 if (!s->import_proc_kmsg)
2449 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2450 if (s->proc_kmsg_fd < 0) {
2451 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2456 ev.events = EPOLLIN;
2457 ev.data.fd = s->proc_kmsg_fd;
2458 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2459 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2466 static int open_signalfd(Server *s) {
2468 struct epoll_event ev;
2472 assert_se(sigemptyset(&mask) == 0);
2473 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2474 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2476 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2477 if (s->signal_fd < 0) {
2478 log_error("signalfd(): %m");
2483 ev.events = EPOLLIN;
2484 ev.data.fd = s->signal_fd;
2486 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2487 log_error("epoll_ctl(): %m");
2494 static int server_parse_proc_cmdline(Server *s) {
2495 char *line, *w, *state;
2499 if (detect_container(NULL) > 0)
2502 r = read_one_line_file("/proc/cmdline", &line);
2504 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2508 FOREACH_WORD_QUOTED(w, l, line, state) {
2511 word = strndup(w, l);
2517 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2518 r = parse_boolean(word + 35);
2520 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2522 s->forward_to_syslog = r;
2523 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2524 r = parse_boolean(word + 33);
2526 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2528 s->forward_to_kmsg = r;
2529 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2530 r = parse_boolean(word + 36);
2532 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2534 s->forward_to_console = r;
2547 static int server_parse_config_file(Server *s) {
2554 fn = "/etc/systemd/systemd-journald.conf";
2555 f = fopen(fn, "re");
2557 if (errno == ENOENT)
2560 log_warning("Failed to open configuration file %s: %m", fn);
2564 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2566 log_warning("Failed to parse configuration file: %s", strerror(-r));
2573 static int server_init(Server *s) {
2579 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2582 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2583 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2585 s->forward_to_syslog = true;
2586 s->import_proc_kmsg = true;
2588 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2589 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2591 server_parse_config_file(s);
2592 server_parse_proc_cmdline(s);
2594 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2595 if (!s->user_journals) {
2596 log_error("Out of memory.");
2600 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2601 if (s->epoll_fd < 0) {
2602 log_error("Failed to create epoll object: %m");
2606 n = sd_listen_fds(true);
2608 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2612 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2614 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2616 if (s->native_fd >= 0) {
2617 log_error("Too many native sockets passed.");
2623 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2625 if (s->stdout_fd >= 0) {
2626 log_error("Too many stdout sockets passed.");
2632 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2634 if (s->syslog_fd >= 0) {
2635 log_error("Too many /dev/log sockets passed.");
2642 log_error("Unknown socket passed.");
2647 r = open_syslog_socket(s);
2651 r = open_native_socket(s);
2655 r = open_stdout_socket(s);
2659 r = open_proc_kmsg(s);
2663 r = system_journal_open(s);
2667 r = open_signalfd(s);
2671 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2678 static void server_done(Server *s) {
2682 while (s->stdout_streams)
2683 stdout_stream_free(s->stdout_streams);
2685 if (s->system_journal)
2686 journal_file_close(s->system_journal);
2688 if (s->runtime_journal)
2689 journal_file_close(s->runtime_journal);
2691 while ((f = hashmap_steal_first(s->user_journals)))
2692 journal_file_close(f);
2694 hashmap_free(s->user_journals);
2696 if (s->epoll_fd >= 0)
2697 close_nointr_nofail(s->epoll_fd);
2699 if (s->signal_fd >= 0)
2700 close_nointr_nofail(s->signal_fd);
2702 if (s->syslog_fd >= 0)
2703 close_nointr_nofail(s->syslog_fd);
2705 if (s->native_fd >= 0)
2706 close_nointr_nofail(s->native_fd);
2708 if (s->stdout_fd >= 0)
2709 close_nointr_nofail(s->stdout_fd);
2711 if (s->proc_kmsg_fd >= 0)
2712 close_nointr_nofail(s->proc_kmsg_fd);
2715 journal_rate_limit_free(s->rate_limit);
2720 int main(int argc, char *argv[]) {
2724 /* if (getppid() != 1) { */
2725 /* log_error("This program should be invoked by init only."); */
2726 /* return EXIT_FAILURE; */
2730 log_error("This program does not take arguments.");
2731 return EXIT_FAILURE;
2734 log_set_target(LOG_TARGET_CONSOLE);
2735 log_parse_environment();
2740 r = server_init(&server);
2744 server_vacuum(&server);
2745 server_flush_to_var(&server);
2746 server_flush_proc_kmsg(&server);
2748 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2749 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2753 "STATUS=Processing requests...");
2756 struct epoll_event event;
2758 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2764 log_error("epoll_wait() failed: %m");
2770 r = process_event(&server, &event);
2777 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2778 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2782 "STATUS=Shutting down...");
2784 server_done(&server);
2786 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;