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;
1265 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1266 log_debug("Failed to parse message, ignoring.");
1270 memcpy(&l_le, e + 1, sizeof(uint64_t));
1273 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1274 e[1+sizeof(uint64_t)+l] != '\n') {
1275 log_debug("Failed to parse message, ignoring.");
1279 k = malloc((e - p) + 1 + l);
1281 log_error("Out of memory");
1285 memcpy(k, p, e - p);
1287 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1289 if (valid_user_field(p, e - p)) {
1290 iovec[n].iov_base = k;
1291 iovec[n].iov_len = (e - p) + 1 + l;
1296 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1297 p = e + 1 + sizeof(uint64_t) + l + 1;
1305 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1308 if (s->forward_to_syslog)
1309 forward_syslog(s, priority, identifier, message, ucred, tv);
1311 if (s->forward_to_kmsg)
1312 forward_kmsg(s, priority, identifier, message, ucred);
1314 if (s->forward_to_console)
1315 forward_console(s, identifier, message, ucred);
1318 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1321 for (j = 0; j < n; j++) {
1325 if (iovec[j].iov_base < buffer ||
1326 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1327 free(iovec[j].iov_base);
1335 static void process_native_file(
1338 struct ucred *ucred,
1340 const char *label, size_t label_len) {
1349 /* Data is in the passed file, since it didn't fit in a
1350 * datagram. We can't map the file here, since clients might
1351 * then truncate it and trigger a SIGBUS for us. So let's
1352 * stupidly read it */
1354 if (fstat(fd, &st) < 0) {
1355 log_error("Failed to stat passed file, ignoring: %m");
1359 if (!S_ISREG(st.st_mode)) {
1360 log_error("File passed is not regular. Ignoring.");
1364 if (st.st_size <= 0)
1367 if (st.st_size > ENTRY_SIZE_MAX) {
1368 log_error("File passed too large. Ignoring.");
1372 p = malloc(st.st_size);
1374 log_error("Out of memory");
1378 n = pread(fd, p, st.st_size, 0);
1380 log_error("Failed to read file, ignoring: %s", strerror(-n));
1382 process_native_message(s, p, n, ucred, tv, label, label_len);
1387 static int stdout_stream_log(StdoutStream *s, const char *p) {
1388 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1389 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1393 size_t label_len = 0;
1401 priority = s->priority;
1403 if (s->level_prefix)
1404 parse_syslog_priority((char**) &p, &priority);
1406 if (s->forward_to_syslog || s->server->forward_to_syslog)
1407 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1409 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1410 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1412 if (s->forward_to_console || s->server->forward_to_console)
1413 forward_console(s->server, s->identifier, p, &s->ucred);
1415 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1417 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1418 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1420 if (priority & LOG_FACMASK)
1421 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1422 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1424 if (s->identifier) {
1425 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1426 if (syslog_identifier)
1427 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1430 message = strappend("MESSAGE=", p);
1432 IOVEC_SET_STRING(iovec[n++], message);
1435 if (s->security_context) {
1436 label = (char*) s->security_context;
1437 label_len = strlen((char*) s->security_context);
1441 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, priority);
1444 free(syslog_priority);
1445 free(syslog_facility);
1446 free(syslog_identifier);
1451 static int stdout_stream_line(StdoutStream *s, char *p) {
1461 case STDOUT_STREAM_IDENTIFIER:
1463 s->identifier = NULL;
1465 s->identifier = strdup(p);
1466 if (!s->identifier) {
1467 log_error("Out of memory");
1472 s->state = STDOUT_STREAM_PRIORITY;
1475 case STDOUT_STREAM_PRIORITY:
1476 r = safe_atoi(p, &s->priority);
1477 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1478 log_warning("Failed to parse log priority line.");
1482 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1485 case STDOUT_STREAM_LEVEL_PREFIX:
1486 r = parse_boolean(p);
1488 log_warning("Failed to parse level prefix line.");
1492 s->level_prefix = !!r;
1493 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1496 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1497 r = parse_boolean(p);
1499 log_warning("Failed to parse forward to syslog line.");
1503 s->forward_to_syslog = !!r;
1504 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1507 case STDOUT_STREAM_FORWARD_TO_KMSG:
1508 r = parse_boolean(p);
1510 log_warning("Failed to parse copy to kmsg line.");
1514 s->forward_to_kmsg = !!r;
1515 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1518 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1519 r = parse_boolean(p);
1521 log_warning("Failed to parse copy to console line.");
1525 s->forward_to_console = !!r;
1526 s->state = STDOUT_STREAM_RUNNING;
1529 case STDOUT_STREAM_RUNNING:
1530 return stdout_stream_log(s, p);
1533 assert_not_reached("Unknown stream state");
1536 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1544 remaining = s->length;
1549 end = memchr(p, '\n', remaining);
1552 else if (remaining >= sizeof(s->buffer) - 1) {
1553 end = p + sizeof(s->buffer) - 1;
1560 r = stdout_stream_line(s, p);
1568 if (force_flush && remaining > 0) {
1570 r = stdout_stream_line(s, p);
1578 if (p > s->buffer) {
1579 memmove(s->buffer, p, remaining);
1580 s->length = remaining;
1586 static int stdout_stream_process(StdoutStream *s) {
1592 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1595 if (errno == EAGAIN)
1598 log_warning("Failed to read from stream: %m");
1603 r = stdout_stream_scan(s, true);
1611 r = stdout_stream_scan(s, false);
1619 static void stdout_stream_free(StdoutStream *s) {
1623 assert(s->server->n_stdout_streams > 0);
1624 s->server->n_stdout_streams --;
1625 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1630 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1632 close_nointr_nofail(s->fd);
1636 if (s->security_context)
1637 freecon(s->security_context);
1640 free(s->identifier);
1644 static int stdout_stream_new(Server *s) {
1645 StdoutStream *stream;
1648 struct epoll_event ev;
1652 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1654 if (errno == EAGAIN)
1657 log_error("Failed to accept stdout connection: %m");
1661 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1662 log_warning("Too many stdout streams, refusing connection.");
1663 close_nointr_nofail(fd);
1667 stream = new0(StdoutStream, 1);
1669 log_error("Out of memory.");
1670 close_nointr_nofail(fd);
1676 len = sizeof(stream->ucred);
1677 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1678 log_error("Failed to determine peer credentials: %m");
1684 if (getpeercon(fd, &stream->security_context) < 0)
1685 log_error("Failed to determine peer security context.");
1688 if (shutdown(fd, SHUT_WR) < 0) {
1689 log_error("Failed to shutdown writing side of socket: %m");
1695 ev.data.ptr = stream;
1696 ev.events = EPOLLIN;
1697 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1698 log_error("Failed to add stream to event loop: %m");
1704 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1705 s->n_stdout_streams ++;
1710 stdout_stream_free(stream);
1714 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1725 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1730 for (i = 1; i <= 5; i++) {
1736 k = undecchar(p[i]);
1743 for (i = 7; i <= 12; i++) {
1746 k = undecchar(p[i]);
1755 *_p += strspn(*_p, WHITESPACE);
1760 static void proc_kmsg_line(Server *s, const char *p) {
1761 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1762 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1763 int priority = LOG_KERN | LOG_INFO;
1766 char *identifier = NULL, *pid = NULL;
1774 parse_syslog_priority((char **) &p, &priority);
1776 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1779 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1780 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1781 (unsigned long long) usec) >= 0)
1782 IOVEC_SET_STRING(iovec[n++], source_time);
1785 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1787 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1788 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1790 if ((priority & LOG_FACMASK) == LOG_KERN) {
1792 if (s->forward_to_syslog)
1793 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1795 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1797 read_identifier(&p, &identifier, &pid);
1799 if (s->forward_to_syslog)
1800 forward_syslog(s, priority, identifier, p, NULL, NULL);
1803 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1804 if (syslog_identifier)
1805 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1809 syslog_pid = strappend("SYSLOG_PID=", pid);
1811 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1814 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1815 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1818 message = strappend("MESSAGE=", p);
1820 IOVEC_SET_STRING(iovec[n++], message);
1822 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, priority);
1825 free(syslog_priority);
1826 free(syslog_identifier);
1828 free(syslog_facility);
1834 static void proc_kmsg_scan(Server *s) {
1840 p = s->proc_kmsg_buffer;
1841 remaining = s->proc_kmsg_length;
1846 end = memchr(p, '\n', remaining);
1849 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1850 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1857 proc_kmsg_line(s, p);
1863 if (p > s->proc_kmsg_buffer) {
1864 memmove(s->proc_kmsg_buffer, p, remaining);
1865 s->proc_kmsg_length = remaining;
1869 static int system_journal_open(Server *s) {
1875 r = sd_id128_get_machine(&machine);
1879 sd_id128_to_string(machine, ids);
1881 if (!s->system_journal) {
1883 /* First try to create the machine path, but not the prefix */
1884 fn = strappend("/var/log/journal/", ids);
1887 (void) mkdir(fn, 0755);
1890 /* The create the system journal file */
1891 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1895 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1899 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1901 s->system_journal->metrics = s->system_metrics;
1902 s->system_journal->compress = s->compress;
1904 server_fix_perms(s, s->system_journal, 0);
1907 if (r != -ENOENT && r != -EROFS)
1908 log_warning("Failed to open system journal: %s", strerror(-r));
1914 if (!s->runtime_journal) {
1916 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1920 if (s->system_journal) {
1922 /* Try to open the runtime journal, but only
1923 * if it already exists, so that we can flush
1924 * it into the system journal */
1926 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1931 log_warning("Failed to open runtime journal: %s", strerror(-r));
1938 /* OK, we really need the runtime journal, so create
1939 * it if necessary. */
1941 (void) mkdir_parents(fn, 0755);
1942 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1946 log_error("Failed to open runtime journal: %s", strerror(-r));
1951 if (s->runtime_journal) {
1952 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1954 s->runtime_journal->metrics = s->runtime_metrics;
1955 s->runtime_journal->compress = s->compress;
1957 server_fix_perms(s, s->runtime_journal, 0);
1964 static int server_flush_to_var(Server *s) {
1965 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1974 if (!s->runtime_journal)
1977 ts = now(CLOCK_MONOTONIC);
1978 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1981 s->var_available_timestamp = ts;
1983 system_journal_open(s);
1985 if (!s->system_journal)
1988 log_info("Flushing to /var...");
1990 r = sd_id128_get_machine(&machine);
1992 log_error("Failed to get machine id: %s", strerror(-r));
1996 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1998 log_error("Failed to read runtime journal: %s", strerror(-r));
2002 SD_JOURNAL_FOREACH(j) {
2005 f = j->current_file;
2006 assert(f && f->current_offset > 0);
2008 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2010 log_error("Can't read entry: %s", strerror(-r));
2014 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2016 log_info("Allocation limit reached.");
2018 journal_file_post_change(s->system_journal);
2022 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2026 log_error("Can't write entry: %s", strerror(-r));
2032 journal_file_post_change(s->system_journal);
2034 journal_file_close(s->runtime_journal);
2035 s->runtime_journal = NULL;
2038 sd_id128_to_string(machine, path + 17);
2039 rm_rf(path, false, true, false);
2045 static int server_read_proc_kmsg(Server *s) {
2048 assert(s->proc_kmsg_fd >= 0);
2050 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
2053 if (errno == EAGAIN || errno == EINTR)
2056 log_error("Failed to read from kernel: %m");
2060 s->proc_kmsg_length += l;
2066 static int server_flush_proc_kmsg(Server *s) {
2071 if (s->proc_kmsg_fd < 0)
2074 log_info("Flushing /proc/kmsg...");
2077 r = server_read_proc_kmsg(s);
2088 static int process_event(Server *s, struct epoll_event *ev) {
2091 if (ev->data.fd == s->signal_fd) {
2092 struct signalfd_siginfo sfsi;
2095 if (ev->events != EPOLLIN) {
2096 log_info("Got invalid event from epoll.");
2100 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2101 if (n != sizeof(sfsi)) {
2106 if (errno == EINTR || errno == EAGAIN)
2112 if (sfsi.ssi_signo == SIGUSR1) {
2113 server_flush_to_var(s);
2117 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2120 } else if (ev->data.fd == s->proc_kmsg_fd) {
2123 if (ev->events != EPOLLIN) {
2124 log_info("Got invalid event from epoll.");
2128 r = server_read_proc_kmsg(s);
2134 } else if (ev->data.fd == s->native_fd ||
2135 ev->data.fd == s->syslog_fd) {
2137 if (ev->events != EPOLLIN) {
2138 log_info("Got invalid event from epoll.");
2143 struct msghdr msghdr;
2145 struct ucred *ucred = NULL;
2146 struct timeval *tv = NULL;
2147 struct cmsghdr *cmsg;
2149 size_t label_len = 0;
2151 struct cmsghdr cmsghdr;
2153 /* We use NAME_MAX space for the
2154 * SELinux label here. The kernel
2155 * currently enforces no limit, but
2156 * according to suggestions from the
2157 * SELinux people this will change and
2158 * it will probably be identical to
2159 * NAME_MAX. For now we use that, but
2160 * this should be updated one day when
2161 * the final limit is known.*/
2162 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2163 CMSG_SPACE(sizeof(struct timeval)) +
2164 CMSG_SPACE(sizeof(int)) + /* fd */
2165 CMSG_SPACE(NAME_MAX)]; /* selinux label */
2172 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2173 log_error("SIOCINQ failed: %m");
2177 if (s->buffer_size < (size_t) v) {
2181 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2182 b = realloc(s->buffer, l+1);
2185 log_error("Couldn't increase buffer.");
2194 iovec.iov_base = s->buffer;
2195 iovec.iov_len = s->buffer_size;
2199 msghdr.msg_iov = &iovec;
2200 msghdr.msg_iovlen = 1;
2201 msghdr.msg_control = &control;
2202 msghdr.msg_controllen = sizeof(control);
2204 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2207 if (errno == EINTR || errno == EAGAIN)
2210 log_error("recvmsg() failed: %m");
2214 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2216 if (cmsg->cmsg_level == SOL_SOCKET &&
2217 cmsg->cmsg_type == SCM_CREDENTIALS &&
2218 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2219 ucred = (struct ucred*) CMSG_DATA(cmsg);
2220 else if (cmsg->cmsg_level == SOL_SOCKET &&
2221 cmsg->cmsg_type == SCM_SECURITY) {
2222 label = (char*) CMSG_DATA(cmsg);
2223 label_len = cmsg->cmsg_len - CMSG_LEN(0);
2224 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2225 cmsg->cmsg_type == SO_TIMESTAMP &&
2226 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2227 tv = (struct timeval*) CMSG_DATA(cmsg);
2228 else if (cmsg->cmsg_level == SOL_SOCKET &&
2229 cmsg->cmsg_type == SCM_RIGHTS) {
2230 fds = (int*) CMSG_DATA(cmsg);
2231 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2235 if (ev->data.fd == s->syslog_fd) {
2238 if (n > 0 && n_fds == 0) {
2239 e = memchr(s->buffer, '\n', n);
2245 process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
2246 } else if (n_fds > 0)
2247 log_warning("Got file descriptors via syslog socket. Ignoring.");
2250 if (n > 0 && n_fds == 0)
2251 process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
2252 else if (n == 0 && n_fds == 1)
2253 process_native_file(s, fds[0], ucred, tv, label, label_len);
2255 log_warning("Got too many file descriptors via native socket. Ignoring.");
2258 close_many(fds, n_fds);
2263 } else if (ev->data.fd == s->stdout_fd) {
2265 if (ev->events != EPOLLIN) {
2266 log_info("Got invalid event from epoll.");
2270 stdout_stream_new(s);
2274 StdoutStream *stream;
2276 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2277 log_info("Got invalid event from epoll.");
2281 /* If it is none of the well-known fds, it must be an
2282 * stdout stream fd. Note that this is a bit ugly here
2283 * (since we rely that none of the well-known fds
2284 * could be interpreted as pointer), but nonetheless
2285 * safe, since the well-known fds would never get an
2286 * fd > 4096, i.e. beyond the first memory page */
2288 stream = ev->data.ptr;
2290 if (stdout_stream_process(stream) <= 0)
2291 stdout_stream_free(stream);
2296 log_error("Unknown event.");
2300 static int open_syslog_socket(Server *s) {
2301 union sockaddr_union sa;
2303 struct epoll_event ev;
2307 if (s->syslog_fd < 0) {
2309 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2310 if (s->syslog_fd < 0) {
2311 log_error("socket() failed: %m");
2316 sa.un.sun_family = AF_UNIX;
2317 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2319 unlink(sa.un.sun_path);
2321 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2323 log_error("bind() failed: %m");
2327 chmod(sa.un.sun_path, 0666);
2329 fd_nonblock(s->syslog_fd, 1);
2332 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2334 log_error("SO_PASSCRED failed: %m");
2340 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2342 log_warning("SO_PASSSEC failed: %m");
2346 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2348 log_error("SO_TIMESTAMP failed: %m");
2353 ev.events = EPOLLIN;
2354 ev.data.fd = s->syslog_fd;
2355 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2356 log_error("Failed to add syslog server fd to epoll object: %m");
2363 static int open_native_socket(Server*s) {
2364 union sockaddr_union sa;
2366 struct epoll_event ev;
2370 if (s->native_fd < 0) {
2372 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2373 if (s->native_fd < 0) {
2374 log_error("socket() failed: %m");
2379 sa.un.sun_family = AF_UNIX;
2380 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2382 unlink(sa.un.sun_path);
2384 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2386 log_error("bind() failed: %m");
2390 chmod(sa.un.sun_path, 0666);
2392 fd_nonblock(s->native_fd, 1);
2395 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2397 log_error("SO_PASSCRED failed: %m");
2403 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2405 log_warning("SO_PASSSEC failed: %m");
2409 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2411 log_error("SO_TIMESTAMP failed: %m");
2416 ev.events = EPOLLIN;
2417 ev.data.fd = s->native_fd;
2418 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2419 log_error("Failed to add native server fd to epoll object: %m");
2426 static int open_stdout_socket(Server *s) {
2427 union sockaddr_union sa;
2429 struct epoll_event ev;
2433 if (s->stdout_fd < 0) {
2435 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2436 if (s->stdout_fd < 0) {
2437 log_error("socket() failed: %m");
2442 sa.un.sun_family = AF_UNIX;
2443 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2445 unlink(sa.un.sun_path);
2447 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2449 log_error("bind() failed: %m");
2453 chmod(sa.un.sun_path, 0666);
2455 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2456 log_error("liste() failed: %m");
2460 fd_nonblock(s->stdout_fd, 1);
2463 ev.events = EPOLLIN;
2464 ev.data.fd = s->stdout_fd;
2465 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2466 log_error("Failed to add stdout server fd to epoll object: %m");
2473 static int open_proc_kmsg(Server *s) {
2474 struct epoll_event ev;
2478 if (!s->import_proc_kmsg)
2482 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2483 if (s->proc_kmsg_fd < 0) {
2484 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2489 ev.events = EPOLLIN;
2490 ev.data.fd = s->proc_kmsg_fd;
2491 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2492 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2499 static int open_signalfd(Server *s) {
2501 struct epoll_event ev;
2505 assert_se(sigemptyset(&mask) == 0);
2506 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2507 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2509 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2510 if (s->signal_fd < 0) {
2511 log_error("signalfd(): %m");
2516 ev.events = EPOLLIN;
2517 ev.data.fd = s->signal_fd;
2519 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2520 log_error("epoll_ctl(): %m");
2527 static int server_parse_proc_cmdline(Server *s) {
2528 char *line, *w, *state;
2532 if (detect_container(NULL) > 0)
2535 r = read_one_line_file("/proc/cmdline", &line);
2537 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2541 FOREACH_WORD_QUOTED(w, l, line, state) {
2544 word = strndup(w, l);
2550 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2551 r = parse_boolean(word + 35);
2553 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2555 s->forward_to_syslog = r;
2556 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2557 r = parse_boolean(word + 33);
2559 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2561 s->forward_to_kmsg = r;
2562 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2563 r = parse_boolean(word + 36);
2565 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2567 s->forward_to_console = r;
2580 static int server_parse_config_file(Server *s) {
2587 fn = "/etc/systemd/journald.conf";
2588 f = fopen(fn, "re");
2590 if (errno == ENOENT)
2593 log_warning("Failed to open configuration file %s: %m", fn);
2597 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2599 log_warning("Failed to parse configuration file: %s", strerror(-r));
2606 static int server_init(Server *s) {
2612 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2615 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2616 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2618 s->forward_to_syslog = true;
2619 s->import_proc_kmsg = true;
2621 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2622 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2624 server_parse_config_file(s);
2625 server_parse_proc_cmdline(s);
2627 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2628 if (!s->user_journals) {
2629 log_error("Out of memory.");
2633 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2634 if (s->epoll_fd < 0) {
2635 log_error("Failed to create epoll object: %m");
2639 n = sd_listen_fds(true);
2641 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2645 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2647 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2649 if (s->native_fd >= 0) {
2650 log_error("Too many native sockets passed.");
2656 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2658 if (s->stdout_fd >= 0) {
2659 log_error("Too many stdout sockets passed.");
2665 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2667 if (s->syslog_fd >= 0) {
2668 log_error("Too many /dev/log sockets passed.");
2675 log_error("Unknown socket passed.");
2680 r = open_syslog_socket(s);
2684 r = open_native_socket(s);
2688 r = open_stdout_socket(s);
2692 r = open_proc_kmsg(s);
2696 r = open_signalfd(s);
2700 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2704 r = system_journal_open(s);
2711 static void server_done(Server *s) {
2715 while (s->stdout_streams)
2716 stdout_stream_free(s->stdout_streams);
2718 if (s->system_journal)
2719 journal_file_close(s->system_journal);
2721 if (s->runtime_journal)
2722 journal_file_close(s->runtime_journal);
2724 while ((f = hashmap_steal_first(s->user_journals)))
2725 journal_file_close(f);
2727 hashmap_free(s->user_journals);
2729 if (s->epoll_fd >= 0)
2730 close_nointr_nofail(s->epoll_fd);
2732 if (s->signal_fd >= 0)
2733 close_nointr_nofail(s->signal_fd);
2735 if (s->syslog_fd >= 0)
2736 close_nointr_nofail(s->syslog_fd);
2738 if (s->native_fd >= 0)
2739 close_nointr_nofail(s->native_fd);
2741 if (s->stdout_fd >= 0)
2742 close_nointr_nofail(s->stdout_fd);
2744 if (s->proc_kmsg_fd >= 0)
2745 close_nointr_nofail(s->proc_kmsg_fd);
2748 journal_rate_limit_free(s->rate_limit);
2753 int main(int argc, char *argv[]) {
2757 /* if (getppid() != 1) { */
2758 /* log_error("This program should be invoked by init only."); */
2759 /* return EXIT_FAILURE; */
2763 log_error("This program does not take arguments.");
2764 return EXIT_FAILURE;
2767 log_set_target(LOG_TARGET_CONSOLE);
2768 log_set_facility(LOG_SYSLOG);
2769 log_parse_environment();
2774 r = server_init(&server);
2778 server_vacuum(&server);
2779 server_flush_to_var(&server);
2780 server_flush_proc_kmsg(&server);
2782 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2783 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2787 "STATUS=Processing requests...");
2790 struct epoll_event event;
2792 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2798 log_error("epoll_wait() failed: %m");
2804 r = process_event(&server, &event);
2811 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2812 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2816 "STATUS=Shutting down...");
2818 server_done(&server);
2820 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;