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;
157 r = readdir_r(d, &buf, &de);
164 if (!endswith(de->d_name, ".journal") &&
165 !endswith(de->d_name, ".journal~"))
168 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
171 if (!S_ISREG(st.st_mode))
174 sum += (uint64_t) st.st_blocks * 512UL;
177 avail = sum >= m->max_use ? 0 : m->max_use - sum;
179 ss_avail = ss.f_bsize * ss.f_bavail;
181 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
183 if (ss_avail < avail)
186 s->cached_available_space = avail;
187 s->cached_available_space_timestamp = ts;
195 static void server_read_file_gid(Server *s) {
196 const char *adm = "adm";
201 if (s->file_gid_valid)
204 r = get_group_creds(&adm, &s->file_gid);
206 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
208 /* if we couldn't read the gid, then it will be 0, but that's
209 * fine and we shouldn't try to resolve the group again, so
210 * let's just pretend it worked right-away. */
211 s->file_gid_valid = true;
214 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
219 acl_permset_t permset;
224 server_read_file_gid(s);
226 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
228 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
234 acl = acl_get_fd(f->fd);
236 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
240 r = acl_find_uid(acl, uid, &entry);
243 if (acl_create_entry(&acl, &entry) < 0 ||
244 acl_set_tag_type(entry, ACL_USER) < 0 ||
245 acl_set_qualifier(entry, &uid) < 0) {
246 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
251 if (acl_get_permset(entry, &permset) < 0 ||
252 acl_add_perm(permset, ACL_READ) < 0 ||
253 acl_calc_mask(&acl) < 0) {
254 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
258 if (acl_set_fd(f->fd, acl) < 0)
259 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
266 static JournalFile* find_journal(Server *s, uid_t uid) {
275 /* We split up user logs only on /var, not on /run. If the
276 * runtime file is open, we write to it exclusively, in order
277 * to guarantee proper order as soon as we flush /run to
278 * /var and close the runtime file. */
280 if (s->runtime_journal)
281 return s->runtime_journal;
284 return s->system_journal;
286 r = sd_id128_get_machine(&machine);
288 return s->system_journal;
290 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
294 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
295 return s->system_journal;
297 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
298 /* Too many open? Then let's close one */
299 f = hashmap_steal_first(s->user_journals);
301 journal_file_close(f);
304 r = journal_file_open_reliably(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
308 return s->system_journal;
310 server_fix_perms(s, f, uid);
312 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
314 journal_file_close(f);
315 return s->system_journal;
321 static void server_rotate(Server *s) {
327 log_info("Rotating...");
329 if (s->runtime_journal) {
330 r = journal_file_rotate(&s->runtime_journal);
332 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
334 server_fix_perms(s, s->runtime_journal, 0);
337 if (s->system_journal) {
338 r = journal_file_rotate(&s->system_journal);
340 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
342 server_fix_perms(s, s->system_journal, 0);
345 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
346 r = journal_file_rotate(&f);
348 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
350 hashmap_replace(s->user_journals, k, f);
351 server_fix_perms(s, s->system_journal, PTR_TO_UINT32(k));
356 static void server_vacuum(Server *s) {
362 log_info("Vacuuming...");
364 r = sd_id128_get_machine(&machine);
366 log_error("Failed to get machine ID: %s", strerror(-r));
370 sd_id128_to_string(machine, ids);
372 if (s->system_journal) {
373 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
374 log_error("Out of memory.");
378 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
379 if (r < 0 && r != -ENOENT)
380 log_error("Failed to vacuum %s: %s", p, strerror(-r));
385 if (s->runtime_journal) {
386 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
387 log_error("Out of memory.");
391 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
392 if (r < 0 && r != -ENOENT)
393 log_error("Failed to vacuum %s: %s", p, strerror(-r));
397 s->cached_available_space_timestamp = 0;
400 static char *shortened_cgroup_path(pid_t pid) {
402 char *process_path, *init_path, *path;
406 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
410 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
416 if (endswith(init_path, "/system"))
417 init_path[strlen(init_path) - 7] = 0;
418 else if (streq(init_path, "/"))
421 if (startswith(process_path, init_path)) {
424 p = strdup(process_path + strlen(init_path));
442 static void dispatch_message_real(
444 struct iovec *iovec, unsigned n, unsigned m,
447 const char *label, size_t label_len) {
449 char *pid = NULL, *uid = NULL, *gid = NULL,
450 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
451 *comm = NULL, *cmdline = NULL, *hostname = NULL,
452 *audit_session = NULL, *audit_loginuid = NULL,
453 *exe = NULL, *cgroup = NULL, *session = NULL,
454 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
460 uid_t loginuid = 0, realuid = 0;
462 bool vacuumed = false;
467 assert(n + N_IOVEC_META_FIELDS <= m);
473 realuid = ucred->uid;
475 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
476 IOVEC_SET_STRING(iovec[n++], pid);
478 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
479 IOVEC_SET_STRING(iovec[n++], uid);
481 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
482 IOVEC_SET_STRING(iovec[n++], gid);
484 r = get_process_comm(ucred->pid, &t);
486 comm = strappend("_COMM=", t);
490 IOVEC_SET_STRING(iovec[n++], comm);
493 r = get_process_exe(ucred->pid, &t);
495 exe = strappend("_EXE=", t);
499 IOVEC_SET_STRING(iovec[n++], exe);
502 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
504 cmdline = strappend("_CMDLINE=", t);
508 IOVEC_SET_STRING(iovec[n++], cmdline);
511 r = audit_session_from_pid(ucred->pid, &audit);
513 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
514 IOVEC_SET_STRING(iovec[n++], audit_session);
516 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
518 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
519 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
521 t = shortened_cgroup_path(ucred->pid);
523 cgroup = strappend("_SYSTEMD_CGROUP=", t);
527 IOVEC_SET_STRING(iovec[n++], cgroup);
530 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
531 session = strappend("_SYSTEMD_SESSION=", t);
535 IOVEC_SET_STRING(iovec[n++], session);
538 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
539 unit = strappend("_SYSTEMD_UNIT=", t);
543 IOVEC_SET_STRING(iovec[n++], unit);
546 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
547 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
548 IOVEC_SET_STRING(iovec[n++], owner_uid);
552 selinux_context = malloc(sizeof("_SELINUX_CONTEXT=") + label_len);
553 if (selinux_context) {
554 memcpy(selinux_context, "_SELINUX_CONTEXT=", sizeof("_SELINUX_CONTEXT=")-1);
555 memcpy(selinux_context+sizeof("_SELINUX_CONTEXT=")-1, label, label_len);
556 selinux_context[sizeof("_SELINUX_CONTEXT=")-1+label_len] = 0;
557 IOVEC_SET_STRING(iovec[n++], selinux_context);
560 security_context_t con;
562 if (getpidcon(ucred->pid, &con) >= 0) {
563 selinux_context = strappend("_SELINUX_CONTEXT=", con);
565 IOVEC_SET_STRING(iovec[n++], selinux_context);
574 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
575 (unsigned long long) timeval_load(tv)) >= 0)
576 IOVEC_SET_STRING(iovec[n++], source_time);
579 /* Note that strictly speaking storing the boot id here is
580 * redundant since the entry includes this in-line
581 * anyway. However, we need this indexed, too. */
582 r = sd_id128_get_boot(&id);
584 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
585 IOVEC_SET_STRING(iovec[n++], boot_id);
587 r = sd_id128_get_machine(&id);
589 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
590 IOVEC_SET_STRING(iovec[n++], machine_id);
592 t = gethostname_malloc();
594 hostname = strappend("_HOSTNAME=", t);
597 IOVEC_SET_STRING(iovec[n++], hostname);
602 server_flush_to_var(s);
605 f = find_journal(s, realuid == 0 ? 0 : loginuid);
607 log_warning("Dropping message, as we can't find a place to store the data.");
609 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
611 if ((r == -E2BIG || /* hit limit */
612 r == -EFBIG || /* hit fs limit */
613 r == -EDQUOT || /* quota hit */
614 r == -ENOSPC || /* disk full */
615 r == -EBADMSG || /* corrupted */
616 r == -ENODATA || /* truncated */
617 r == -EHOSTDOWN || /* other machine */
618 r == -EPROTONOSUPPORT) && /* unsupported feature */
622 log_info("Allocation limit reached, rotating.");
624 log_warning("Journal file corrupted, rotating.");
630 log_info("Retrying write.");
635 log_error("Failed to write entry, ignoring: %s", strerror(-r));
649 free(audit_loginuid);
654 free(selinux_context);
657 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
658 char mid[11 + 32 + 1];
659 char buffer[16 + LINE_MAX + 1];
660 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
668 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
669 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
671 memcpy(buffer, "MESSAGE=", 8);
672 va_start(ap, format);
673 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
675 char_array_0(buffer);
676 IOVEC_SET_STRING(iovec[n++], buffer);
678 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
680 IOVEC_SET_STRING(iovec[n++], mid);
683 ucred.pid = getpid();
684 ucred.uid = getuid();
685 ucred.gid = getgid();
687 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0);
690 static void dispatch_message(Server *s,
691 struct iovec *iovec, unsigned n, unsigned m,
694 const char *label, size_t label_len,
697 char *path = NULL, *c;
700 assert(iovec || n == 0);
708 path = shortened_cgroup_path(ucred->pid);
712 /* example: /user/lennart/3/foobar
713 * /system/dbus.service/foobar
715 * So let's cut of everything past the third /, since that is
716 * wher user directories start */
718 c = strchr(path, '/');
720 c = strchr(c+1, '/');
722 c = strchr(c+1, '/');
728 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
735 /* Write a suppression message if we suppressed something */
737 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
742 dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len);
745 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
746 struct msghdr msghdr;
747 struct cmsghdr *cmsg;
749 struct cmsghdr cmsghdr;
750 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
752 union sockaddr_union sa;
759 msghdr.msg_iov = (struct iovec*) iovec;
760 msghdr.msg_iovlen = n_iovec;
763 sa.un.sun_family = AF_UNIX;
764 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
765 msghdr.msg_name = &sa;
766 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
770 msghdr.msg_control = &control;
771 msghdr.msg_controllen = sizeof(control);
773 cmsg = CMSG_FIRSTHDR(&msghdr);
774 cmsg->cmsg_level = SOL_SOCKET;
775 cmsg->cmsg_type = SCM_CREDENTIALS;
776 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
777 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
778 msghdr.msg_controllen = cmsg->cmsg_len;
781 /* Forward the syslog message we received via /dev/log to
782 * /run/systemd/syslog. Unfortunately we currently can't set
783 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
785 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
788 /* The socket is full? I guess the syslog implementation is
789 * too slow, and we shouldn't wait for that... */
793 if (ucred && errno == ESRCH) {
796 /* Hmm, presumably the sender process vanished
797 * by now, so let's fix it as good as we
802 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
804 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
811 log_debug("Failed to forward syslog message: %m");
814 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
820 IOVEC_SET_STRING(iovec, buffer);
821 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
824 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
825 struct iovec iovec[5];
826 char header_priority[6], header_time[64], header_pid[16];
830 char *ident_buf = NULL;
833 assert(priority >= 0);
834 assert(priority <= 999);
837 /* First: priority field */
838 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
839 char_array_0(header_priority);
840 IOVEC_SET_STRING(iovec[n++], header_priority);
842 /* Second: timestamp */
843 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
847 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
849 IOVEC_SET_STRING(iovec[n++], header_time);
851 /* Third: identifier and PID */
854 get_process_comm(ucred->pid, &ident_buf);
855 identifier = ident_buf;
858 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
859 char_array_0(header_pid);
862 IOVEC_SET_STRING(iovec[n++], identifier);
864 IOVEC_SET_STRING(iovec[n++], header_pid);
865 } else if (identifier) {
866 IOVEC_SET_STRING(iovec[n++], identifier);
867 IOVEC_SET_STRING(iovec[n++], ": ");
870 /* Fourth: message */
871 IOVEC_SET_STRING(iovec[n++], message);
873 forward_syslog_iovec(s, iovec, n, ucred, tv);
878 static int fixup_priority(int priority) {
880 if ((priority & LOG_FACMASK) == 0)
881 return (priority & LOG_PRIMASK) | LOG_USER;
886 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
887 struct iovec iovec[5];
888 char header_priority[6], header_pid[16];
890 char *ident_buf = NULL;
894 assert(priority >= 0);
895 assert(priority <= 999);
898 /* Never allow messages with kernel facility to be written to
899 * kmsg, regardless where the data comes from. */
900 priority = fixup_priority(priority);
902 /* First: priority field */
903 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
904 char_array_0(header_priority);
905 IOVEC_SET_STRING(iovec[n++], header_priority);
907 /* Second: identifier and PID */
910 get_process_comm(ucred->pid, &ident_buf);
911 identifier = ident_buf;
914 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
915 char_array_0(header_pid);
918 IOVEC_SET_STRING(iovec[n++], identifier);
920 IOVEC_SET_STRING(iovec[n++], header_pid);
921 } else if (identifier) {
922 IOVEC_SET_STRING(iovec[n++], identifier);
923 IOVEC_SET_STRING(iovec[n++], ": ");
926 /* Fourth: message */
927 IOVEC_SET_STRING(iovec[n++], message);
928 IOVEC_SET_STRING(iovec[n++], "\n");
930 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
932 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
936 if (writev(fd, iovec, n) < 0)
937 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
939 close_nointr_nofail(fd);
945 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
946 struct iovec iovec[4];
949 char *ident_buf = NULL;
954 /* First: identifier and PID */
957 get_process_comm(ucred->pid, &ident_buf);
958 identifier = ident_buf;
961 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
962 char_array_0(header_pid);
965 IOVEC_SET_STRING(iovec[n++], identifier);
967 IOVEC_SET_STRING(iovec[n++], header_pid);
968 } else if (identifier) {
969 IOVEC_SET_STRING(iovec[n++], identifier);
970 IOVEC_SET_STRING(iovec[n++], ": ");
974 IOVEC_SET_STRING(iovec[n++], message);
975 IOVEC_SET_STRING(iovec[n++], "\n");
977 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
979 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
983 if (writev(fd, iovec, n) < 0)
984 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
986 close_nointr_nofail(fd);
992 static void read_identifier(const char **buf, char **identifier, char **pid) {
1003 p += strspn(p, WHITESPACE);
1004 l = strcspn(p, WHITESPACE);
1013 if (p[l-1] == ']') {
1019 t = strndup(p+k+1, l-k-2);
1039 *buf += strspn(*buf, WHITESPACE);
1042 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) {
1043 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1044 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1046 int priority = LOG_USER | LOG_INFO;
1047 char *identifier = NULL, *pid = NULL;
1052 if (s->forward_to_syslog)
1053 forward_syslog_raw(s, buf, ucred, tv);
1055 parse_syslog_priority((char**) &buf, &priority);
1056 skip_syslog_date((char**) &buf);
1057 read_identifier(&buf, &identifier, &pid);
1059 if (s->forward_to_kmsg)
1060 forward_kmsg(s, priority, identifier, buf, ucred);
1062 if (s->forward_to_console)
1063 forward_console(s, identifier, buf, ucred);
1065 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1067 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1068 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1070 if (priority & LOG_FACMASK)
1071 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1072 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1075 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1076 if (syslog_identifier)
1077 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1081 syslog_pid = strappend("SYSLOG_PID=", pid);
1083 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1086 message = strappend("MESSAGE=", buf);
1088 IOVEC_SET_STRING(iovec[n++], message);
1090 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, label, label_len, priority);
1095 free(syslog_priority);
1096 free(syslog_facility);
1097 free(syslog_identifier);
1100 static bool valid_user_field(const char *p, size_t l) {
1103 /* We kinda enforce POSIX syntax recommendations for
1104 environment variables here, but make a couple of additional
1107 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1109 /* No empty field names */
1113 /* Don't allow names longer than 64 chars */
1117 /* Variables starting with an underscore are protected */
1121 /* Don't allow digits as first character */
1122 if (p[0] >= '0' && p[0] <= '9')
1125 /* Only allow A-Z0-9 and '_' */
1126 for (a = p; a < p + l; a++)
1127 if (!((*a >= 'A' && *a <= 'Z') ||
1128 (*a >= '0' && *a <= '9') ||
1135 static void process_native_message(
1137 const void *buffer, size_t buffer_size,
1138 struct ucred *ucred,
1140 const char *label, size_t label_len) {
1142 struct iovec *iovec = NULL;
1143 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1146 int priority = LOG_INFO;
1147 char *identifier = NULL, *message = NULL;
1150 assert(buffer || n == 0);
1153 remaining = buffer_size;
1155 while (remaining > 0) {
1158 e = memchr(p, '\n', remaining);
1161 /* Trailing noise, let's ignore it, and flush what we collected */
1162 log_debug("Received message with trailing noise, ignoring.");
1167 /* Entry separator */
1168 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1170 priority = LOG_INFO;
1177 if (*p == '.' || *p == '#') {
1178 /* Ignore control commands for now, and
1180 remaining -= (e - p) + 1;
1185 /* A property follows */
1187 if (n+N_IOVEC_META_FIELDS >= m) {
1191 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1192 c = realloc(iovec, u * sizeof(struct iovec));
1194 log_error("Out of memory");
1202 q = memchr(p, '=', e - p);
1204 if (valid_user_field(p, q - p)) {
1209 /* If the field name starts with an
1210 * underscore, skip the variable,
1211 * since that indidates a trusted
1213 iovec[n].iov_base = (char*) p;
1214 iovec[n].iov_len = l;
1217 /* We need to determine the priority
1218 * of this entry for the rate limiting
1221 memcmp(p, "PRIORITY=", 9) == 0 &&
1222 p[9] >= '0' && p[9] <= '9')
1223 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1226 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1227 p[16] >= '0' && p[16] <= '9')
1228 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1231 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1232 p[16] >= '0' && p[16] <= '9' &&
1233 p[17] >= '0' && p[17] <= '9')
1234 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1237 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1240 t = strndup(p + 11, l - 11);
1245 } else if (l >= 8 &&
1246 memcmp(p, "MESSAGE=", 8) == 0) {
1249 t = strndup(p + 8, l - 8);
1257 remaining -= (e - p) + 1;
1264 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1265 log_debug("Failed to parse message, ignoring.");
1269 memcpy(&l, e + 1, sizeof(uint64_t));
1272 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1273 e[1+sizeof(uint64_t)+l] != '\n') {
1274 log_debug("Failed to parse message, ignoring.");
1278 k = malloc((e - p) + 1 + l);
1280 log_error("Out of memory");
1284 memcpy(k, p, e - p);
1286 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1288 if (valid_user_field(p, e - p)) {
1289 iovec[n].iov_base = k;
1290 iovec[n].iov_len = (e - p) + 1 + l;
1295 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1296 p = e + 1 + sizeof(uint64_t) + l + 1;
1304 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1307 if (s->forward_to_syslog)
1308 forward_syslog(s, priority, identifier, message, ucred, tv);
1310 if (s->forward_to_kmsg)
1311 forward_kmsg(s, priority, identifier, message, ucred);
1313 if (s->forward_to_console)
1314 forward_console(s, identifier, message, ucred);
1317 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1320 for (j = 0; j < n; j++) {
1324 if (iovec[j].iov_base < buffer ||
1325 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1326 free(iovec[j].iov_base);
1334 static void process_native_file(
1337 struct ucred *ucred,
1339 const char *label, size_t label_len) {
1348 /* Data is in the passed file, since it didn't fit in a
1349 * datagram. We can't map the file here, since clients might
1350 * then truncate it and trigger a SIGBUS for us. So let's
1351 * stupidly read it */
1353 if (fstat(fd, &st) < 0) {
1354 log_error("Failed to stat passed file, ignoring: %m");
1358 if (!S_ISREG(st.st_mode)) {
1359 log_error("File passed is not regular. Ignoring.");
1363 if (st.st_size <= 0)
1366 if (st.st_size > ENTRY_SIZE_MAX) {
1367 log_error("File passed too large. Ignoring.");
1371 p = malloc(st.st_size);
1373 log_error("Out of memory");
1377 n = pread(fd, p, st.st_size, 0);
1379 log_error("Failed to read file, ignoring: %s", strerror(-n));
1381 process_native_message(s, p, n, ucred, tv, label, label_len);
1386 static int stdout_stream_log(StdoutStream *s, const char *p) {
1387 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1388 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1392 size_t label_len = 0;
1400 priority = s->priority;
1402 if (s->level_prefix)
1403 parse_syslog_priority((char**) &p, &priority);
1405 if (s->forward_to_syslog || s->server->forward_to_syslog)
1406 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1408 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1409 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1411 if (s->forward_to_console || s->server->forward_to_console)
1412 forward_console(s->server, s->identifier, p, &s->ucred);
1414 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1416 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1417 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1419 if (priority & LOG_FACMASK)
1420 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1421 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1423 if (s->identifier) {
1424 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1425 if (syslog_identifier)
1426 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1429 message = strappend("MESSAGE=", p);
1431 IOVEC_SET_STRING(iovec[n++], message);
1434 if (s->security_context) {
1435 label = (char*) s->security_context;
1436 label_len = strlen((char*) s->security_context);
1440 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, priority);
1443 free(syslog_priority);
1444 free(syslog_facility);
1445 free(syslog_identifier);
1450 static int stdout_stream_line(StdoutStream *s, char *p) {
1460 case STDOUT_STREAM_IDENTIFIER:
1462 s->identifier = NULL;
1464 s->identifier = strdup(p);
1465 if (!s->identifier) {
1466 log_error("Out of memory");
1471 s->state = STDOUT_STREAM_PRIORITY;
1474 case STDOUT_STREAM_PRIORITY:
1475 r = safe_atoi(p, &s->priority);
1476 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1477 log_warning("Failed to parse log priority line.");
1481 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1484 case STDOUT_STREAM_LEVEL_PREFIX:
1485 r = parse_boolean(p);
1487 log_warning("Failed to parse level prefix line.");
1491 s->level_prefix = !!r;
1492 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1495 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1496 r = parse_boolean(p);
1498 log_warning("Failed to parse forward to syslog line.");
1502 s->forward_to_syslog = !!r;
1503 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1506 case STDOUT_STREAM_FORWARD_TO_KMSG:
1507 r = parse_boolean(p);
1509 log_warning("Failed to parse copy to kmsg line.");
1513 s->forward_to_kmsg = !!r;
1514 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1517 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1518 r = parse_boolean(p);
1520 log_warning("Failed to parse copy to console line.");
1524 s->forward_to_console = !!r;
1525 s->state = STDOUT_STREAM_RUNNING;
1528 case STDOUT_STREAM_RUNNING:
1529 return stdout_stream_log(s, p);
1532 assert_not_reached("Unknown stream state");
1535 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1543 remaining = s->length;
1548 end = memchr(p, '\n', remaining);
1551 else if (remaining >= sizeof(s->buffer) - 1) {
1552 end = p + sizeof(s->buffer) - 1;
1559 r = stdout_stream_line(s, p);
1567 if (force_flush && remaining > 0) {
1569 r = stdout_stream_line(s, p);
1577 if (p > s->buffer) {
1578 memmove(s->buffer, p, remaining);
1579 s->length = remaining;
1585 static int stdout_stream_process(StdoutStream *s) {
1591 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1594 if (errno == EAGAIN)
1597 log_warning("Failed to read from stream: %m");
1602 r = stdout_stream_scan(s, true);
1610 r = stdout_stream_scan(s, false);
1618 static void stdout_stream_free(StdoutStream *s) {
1622 assert(s->server->n_stdout_streams > 0);
1623 s->server->n_stdout_streams --;
1624 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1629 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1631 close_nointr_nofail(s->fd);
1635 if (s->security_context)
1636 freecon(s->security_context);
1639 free(s->identifier);
1643 static int stdout_stream_new(Server *s) {
1644 StdoutStream *stream;
1647 struct epoll_event ev;
1651 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1653 if (errno == EAGAIN)
1656 log_error("Failed to accept stdout connection: %m");
1660 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1661 log_warning("Too many stdout streams, refusing connection.");
1662 close_nointr_nofail(fd);
1666 stream = new0(StdoutStream, 1);
1668 log_error("Out of memory.");
1669 close_nointr_nofail(fd);
1675 len = sizeof(stream->ucred);
1676 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1677 log_error("Failed to determine peer credentials: %m");
1683 if (getpeercon(fd, &stream->security_context) < 0)
1684 log_error("Failed to determine peer security context.");
1687 if (shutdown(fd, SHUT_WR) < 0) {
1688 log_error("Failed to shutdown writing side of socket: %m");
1694 ev.data.ptr = stream;
1695 ev.events = EPOLLIN;
1696 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1697 log_error("Failed to add stream to event loop: %m");
1703 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1704 s->n_stdout_streams ++;
1709 stdout_stream_free(stream);
1713 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1724 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1729 for (i = 1; i <= 5; i++) {
1735 k = undecchar(p[i]);
1742 for (i = 7; i <= 12; i++) {
1745 k = undecchar(p[i]);
1754 *_p += strspn(*_p, WHITESPACE);
1759 static void proc_kmsg_line(Server *s, const char *p) {
1760 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1761 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1762 int priority = LOG_KERN | LOG_INFO;
1765 char *identifier = NULL, *pid = NULL;
1773 parse_syslog_priority((char **) &p, &priority);
1775 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1778 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1779 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1780 (unsigned long long) usec) >= 0)
1781 IOVEC_SET_STRING(iovec[n++], source_time);
1784 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1786 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1787 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1789 if ((priority & LOG_FACMASK) == LOG_KERN) {
1791 if (s->forward_to_syslog)
1792 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1794 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1796 read_identifier(&p, &identifier, &pid);
1798 if (s->forward_to_syslog)
1799 forward_syslog(s, priority, identifier, p, NULL, NULL);
1802 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1803 if (syslog_identifier)
1804 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1808 syslog_pid = strappend("SYSLOG_PID=", pid);
1810 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1813 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1814 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1817 message = strappend("MESSAGE=", p);
1819 IOVEC_SET_STRING(iovec[n++], message);
1821 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, priority);
1824 free(syslog_priority);
1825 free(syslog_identifier);
1827 free(syslog_facility);
1833 static void proc_kmsg_scan(Server *s) {
1839 p = s->proc_kmsg_buffer;
1840 remaining = s->proc_kmsg_length;
1845 end = memchr(p, '\n', remaining);
1848 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1849 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1856 proc_kmsg_line(s, p);
1862 if (p > s->proc_kmsg_buffer) {
1863 memmove(s->proc_kmsg_buffer, p, remaining);
1864 s->proc_kmsg_length = remaining;
1868 static int system_journal_open(Server *s) {
1874 r = sd_id128_get_machine(&machine);
1878 sd_id128_to_string(machine, ids);
1880 if (!s->system_journal) {
1882 /* First try to create the machine path, but not the prefix */
1883 fn = strappend("/var/log/journal/", ids);
1886 (void) mkdir(fn, 0755);
1889 /* The create the system journal file */
1890 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1894 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1898 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1900 s->system_journal->metrics = s->system_metrics;
1901 s->system_journal->compress = s->compress;
1903 server_fix_perms(s, s->system_journal, 0);
1906 if (r != -ENOENT && r != -EROFS)
1907 log_warning("Failed to open system journal: %s", strerror(-r));
1913 if (!s->runtime_journal) {
1915 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1919 if (s->system_journal) {
1921 /* Try to open the runtime journal, but only
1922 * if it already exists, so that we can flush
1923 * it into the system journal */
1925 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1930 log_warning("Failed to open runtime journal: %s", strerror(-r));
1937 /* OK, we really need the runtime journal, so create
1938 * it if necessary. */
1940 (void) mkdir_parents(fn, 0755);
1941 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1945 log_error("Failed to open runtime journal: %s", strerror(-r));
1950 if (s->runtime_journal) {
1951 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1953 s->runtime_journal->metrics = s->runtime_metrics;
1954 s->runtime_journal->compress = s->compress;
1956 server_fix_perms(s, s->runtime_journal, 0);
1963 static int server_flush_to_var(Server *s) {
1964 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1973 if (!s->runtime_journal)
1976 ts = now(CLOCK_MONOTONIC);
1977 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1980 s->var_available_timestamp = ts;
1982 system_journal_open(s);
1984 if (!s->system_journal)
1987 log_info("Flushing to /var...");
1989 r = sd_id128_get_machine(&machine);
1991 log_error("Failed to get machine id: %s", strerror(-r));
1995 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1997 log_error("Failed to read runtime journal: %s", strerror(-r));
2001 SD_JOURNAL_FOREACH(j) {
2004 f = j->current_file;
2005 assert(f && f->current_offset > 0);
2007 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2009 log_error("Can't read entry: %s", strerror(-r));
2013 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2015 log_info("Allocation limit reached.");
2017 journal_file_post_change(s->system_journal);
2021 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2025 log_error("Can't write entry: %s", strerror(-r));
2031 journal_file_post_change(s->system_journal);
2033 journal_file_close(s->runtime_journal);
2034 s->runtime_journal = NULL;
2037 sd_id128_to_string(machine, path + 17);
2038 rm_rf(path, false, true, false);
2044 static int server_read_proc_kmsg(Server *s) {
2047 assert(s->proc_kmsg_fd >= 0);
2049 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
2052 if (errno == EAGAIN || errno == EINTR)
2055 log_error("Failed to read from kernel: %m");
2059 s->proc_kmsg_length += l;
2065 static int server_flush_proc_kmsg(Server *s) {
2070 if (s->proc_kmsg_fd < 0)
2073 log_info("Flushing /proc/kmsg...");
2076 r = server_read_proc_kmsg(s);
2087 static int process_event(Server *s, struct epoll_event *ev) {
2090 if (ev->data.fd == s->signal_fd) {
2091 struct signalfd_siginfo sfsi;
2094 if (ev->events != EPOLLIN) {
2095 log_info("Got invalid event from epoll.");
2099 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2100 if (n != sizeof(sfsi)) {
2105 if (errno == EINTR || errno == EAGAIN)
2111 if (sfsi.ssi_signo == SIGUSR1) {
2112 server_flush_to_var(s);
2116 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2119 } else if (ev->data.fd == s->proc_kmsg_fd) {
2122 if (ev->events != EPOLLIN) {
2123 log_info("Got invalid event from epoll.");
2127 r = server_read_proc_kmsg(s);
2133 } else if (ev->data.fd == s->native_fd ||
2134 ev->data.fd == s->syslog_fd) {
2136 if (ev->events != EPOLLIN) {
2137 log_info("Got invalid event from epoll.");
2142 struct msghdr msghdr;
2144 struct ucred *ucred = NULL;
2145 struct timeval *tv = NULL;
2146 struct cmsghdr *cmsg;
2148 size_t label_len = 0;
2150 struct cmsghdr cmsghdr;
2152 /* We use NAME_MAX space for the
2153 * SELinux label here. The kernel
2154 * currently enforces no limit, but
2155 * according to suggestions from the
2156 * SELinux people this will change and
2157 * it will probably be identical to
2158 * NAME_MAX. For now we use that, but
2159 * this should be updated one day when
2160 * the final limit is known.*/
2161 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2162 CMSG_SPACE(sizeof(struct timeval)) +
2163 CMSG_SPACE(sizeof(int)) + /* fd */
2164 CMSG_SPACE(NAME_MAX)]; /* selinux label */
2171 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2172 log_error("SIOCINQ failed: %m");
2176 if (s->buffer_size < (size_t) v) {
2180 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2181 b = realloc(s->buffer, l+1);
2184 log_error("Couldn't increase buffer.");
2193 iovec.iov_base = s->buffer;
2194 iovec.iov_len = s->buffer_size;
2198 msghdr.msg_iov = &iovec;
2199 msghdr.msg_iovlen = 1;
2200 msghdr.msg_control = &control;
2201 msghdr.msg_controllen = sizeof(control);
2203 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2206 if (errno == EINTR || errno == EAGAIN)
2209 log_error("recvmsg() failed: %m");
2213 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2215 if (cmsg->cmsg_level == SOL_SOCKET &&
2216 cmsg->cmsg_type == SCM_CREDENTIALS &&
2217 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2218 ucred = (struct ucred*) CMSG_DATA(cmsg);
2219 else if (cmsg->cmsg_level == SOL_SOCKET &&
2220 cmsg->cmsg_type == SCM_SECURITY) {
2221 label = (char*) CMSG_DATA(cmsg);
2222 label_len = cmsg->cmsg_len - CMSG_LEN(0);
2223 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2224 cmsg->cmsg_type == SO_TIMESTAMP &&
2225 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2226 tv = (struct timeval*) CMSG_DATA(cmsg);
2227 else if (cmsg->cmsg_level == SOL_SOCKET &&
2228 cmsg->cmsg_type == SCM_RIGHTS) {
2229 fds = (int*) CMSG_DATA(cmsg);
2230 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2234 if (ev->data.fd == s->syslog_fd) {
2237 if (n > 0 && n_fds == 0) {
2238 e = memchr(s->buffer, '\n', n);
2244 process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
2245 } else if (n_fds > 0)
2246 log_warning("Got file descriptors via syslog socket. Ignoring.");
2249 if (n > 0 && n_fds == 0)
2250 process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
2251 else if (n == 0 && n_fds == 1)
2252 process_native_file(s, fds[0], ucred, tv, label, label_len);
2254 log_warning("Got too many file descriptors via native socket. Ignoring.");
2257 close_many(fds, n_fds);
2262 } else if (ev->data.fd == s->stdout_fd) {
2264 if (ev->events != EPOLLIN) {
2265 log_info("Got invalid event from epoll.");
2269 stdout_stream_new(s);
2273 StdoutStream *stream;
2275 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2276 log_info("Got invalid event from epoll.");
2280 /* If it is none of the well-known fds, it must be an
2281 * stdout stream fd. Note that this is a bit ugly here
2282 * (since we rely that none of the well-known fds
2283 * could be interpreted as pointer), but nonetheless
2284 * safe, since the well-known fds would never get an
2285 * fd > 4096, i.e. beyond the first memory page */
2287 stream = ev->data.ptr;
2289 if (stdout_stream_process(stream) <= 0)
2290 stdout_stream_free(stream);
2295 log_error("Unknown event.");
2299 static int open_syslog_socket(Server *s) {
2300 union sockaddr_union sa;
2302 struct epoll_event ev;
2306 if (s->syslog_fd < 0) {
2308 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2309 if (s->syslog_fd < 0) {
2310 log_error("socket() failed: %m");
2315 sa.un.sun_family = AF_UNIX;
2316 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2318 unlink(sa.un.sun_path);
2320 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2322 log_error("bind() failed: %m");
2326 chmod(sa.un.sun_path, 0666);
2328 fd_nonblock(s->syslog_fd, 1);
2331 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2333 log_error("SO_PASSCRED failed: %m");
2339 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2341 log_warning("SO_PASSSEC failed: %m");
2345 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2347 log_error("SO_TIMESTAMP failed: %m");
2352 ev.events = EPOLLIN;
2353 ev.data.fd = s->syslog_fd;
2354 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2355 log_error("Failed to add syslog server fd to epoll object: %m");
2362 static int open_native_socket(Server*s) {
2363 union sockaddr_union sa;
2365 struct epoll_event ev;
2369 if (s->native_fd < 0) {
2371 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2372 if (s->native_fd < 0) {
2373 log_error("socket() failed: %m");
2378 sa.un.sun_family = AF_UNIX;
2379 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2381 unlink(sa.un.sun_path);
2383 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2385 log_error("bind() failed: %m");
2389 chmod(sa.un.sun_path, 0666);
2391 fd_nonblock(s->native_fd, 1);
2394 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2396 log_error("SO_PASSCRED failed: %m");
2402 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2404 log_warning("SO_PASSSEC failed: %m");
2408 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2410 log_error("SO_TIMESTAMP failed: %m");
2415 ev.events = EPOLLIN;
2416 ev.data.fd = s->native_fd;
2417 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2418 log_error("Failed to add native server fd to epoll object: %m");
2425 static int open_stdout_socket(Server *s) {
2426 union sockaddr_union sa;
2428 struct epoll_event ev;
2432 if (s->stdout_fd < 0) {
2434 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2435 if (s->stdout_fd < 0) {
2436 log_error("socket() failed: %m");
2441 sa.un.sun_family = AF_UNIX;
2442 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2444 unlink(sa.un.sun_path);
2446 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2448 log_error("bind() failed: %m");
2452 chmod(sa.un.sun_path, 0666);
2454 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2455 log_error("liste() failed: %m");
2459 fd_nonblock(s->stdout_fd, 1);
2462 ev.events = EPOLLIN;
2463 ev.data.fd = s->stdout_fd;
2464 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2465 log_error("Failed to add stdout server fd to epoll object: %m");
2472 static int open_proc_kmsg(Server *s) {
2473 struct epoll_event ev;
2477 if (!s->import_proc_kmsg)
2481 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2482 if (s->proc_kmsg_fd < 0) {
2483 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2488 ev.events = EPOLLIN;
2489 ev.data.fd = s->proc_kmsg_fd;
2490 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2491 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2498 static int open_signalfd(Server *s) {
2500 struct epoll_event ev;
2504 assert_se(sigemptyset(&mask) == 0);
2505 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2506 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2508 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2509 if (s->signal_fd < 0) {
2510 log_error("signalfd(): %m");
2515 ev.events = EPOLLIN;
2516 ev.data.fd = s->signal_fd;
2518 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2519 log_error("epoll_ctl(): %m");
2526 static int server_parse_proc_cmdline(Server *s) {
2527 char *line, *w, *state;
2531 if (detect_container(NULL) > 0)
2534 r = read_one_line_file("/proc/cmdline", &line);
2536 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2540 FOREACH_WORD_QUOTED(w, l, line, state) {
2543 word = strndup(w, l);
2549 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2550 r = parse_boolean(word + 35);
2552 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2554 s->forward_to_syslog = r;
2555 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2556 r = parse_boolean(word + 33);
2558 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2560 s->forward_to_kmsg = r;
2561 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2562 r = parse_boolean(word + 36);
2564 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2566 s->forward_to_console = r;
2579 static int server_parse_config_file(Server *s) {
2586 fn = "/etc/systemd/systemd-journald.conf";
2587 f = fopen(fn, "re");
2589 if (errno == ENOENT)
2592 log_warning("Failed to open configuration file %s: %m", fn);
2596 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2598 log_warning("Failed to parse configuration file: %s", strerror(-r));
2605 static int server_init(Server *s) {
2611 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2614 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2615 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2617 s->forward_to_syslog = true;
2618 s->import_proc_kmsg = true;
2620 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2621 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2623 server_parse_config_file(s);
2624 server_parse_proc_cmdline(s);
2626 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2627 if (!s->user_journals) {
2628 log_error("Out of memory.");
2632 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2633 if (s->epoll_fd < 0) {
2634 log_error("Failed to create epoll object: %m");
2638 n = sd_listen_fds(true);
2640 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2644 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2646 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2648 if (s->native_fd >= 0) {
2649 log_error("Too many native sockets passed.");
2655 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2657 if (s->stdout_fd >= 0) {
2658 log_error("Too many stdout sockets passed.");
2664 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2666 if (s->syslog_fd >= 0) {
2667 log_error("Too many /dev/log sockets passed.");
2674 log_error("Unknown socket passed.");
2679 r = open_syslog_socket(s);
2683 r = open_native_socket(s);
2687 r = open_stdout_socket(s);
2691 r = open_proc_kmsg(s);
2695 r = open_signalfd(s);
2699 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2703 r = system_journal_open(s);
2710 static void server_done(Server *s) {
2714 while (s->stdout_streams)
2715 stdout_stream_free(s->stdout_streams);
2717 if (s->system_journal)
2718 journal_file_close(s->system_journal);
2720 if (s->runtime_journal)
2721 journal_file_close(s->runtime_journal);
2723 while ((f = hashmap_steal_first(s->user_journals)))
2724 journal_file_close(f);
2726 hashmap_free(s->user_journals);
2728 if (s->epoll_fd >= 0)
2729 close_nointr_nofail(s->epoll_fd);
2731 if (s->signal_fd >= 0)
2732 close_nointr_nofail(s->signal_fd);
2734 if (s->syslog_fd >= 0)
2735 close_nointr_nofail(s->syslog_fd);
2737 if (s->native_fd >= 0)
2738 close_nointr_nofail(s->native_fd);
2740 if (s->stdout_fd >= 0)
2741 close_nointr_nofail(s->stdout_fd);
2743 if (s->proc_kmsg_fd >= 0)
2744 close_nointr_nofail(s->proc_kmsg_fd);
2747 journal_rate_limit_free(s->rate_limit);
2752 int main(int argc, char *argv[]) {
2756 /* if (getppid() != 1) { */
2757 /* log_error("This program should be invoked by init only."); */
2758 /* return EXIT_FAILURE; */
2762 log_error("This program does not take arguments.");
2763 return EXIT_FAILURE;
2766 log_set_target(LOG_TARGET_CONSOLE);
2767 log_parse_environment();
2772 r = server_init(&server);
2776 server_vacuum(&server);
2777 server_flush_to_var(&server);
2778 server_flush_proc_kmsg(&server);
2780 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2781 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2785 "STATUS=Processing requests...");
2788 struct epoll_event event;
2790 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2796 log_error("epoll_wait() failed: %m");
2802 r = process_event(&server, &event);
2809 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2810 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2814 "STATUS=Shutting down...");
2816 server_done(&server);
2818 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;