1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2011 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/epoll.h>
23 #include <sys/socket.h>
25 #include <sys/signalfd.h>
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <sys/statvfs.h>
34 #include <systemd/sd-journal.h>
35 #include <systemd/sd-login.h>
36 #include <systemd/sd-messages.h>
37 #include <systemd/sd-daemon.h>
40 #include "journal-file.h"
41 #include "socket-util.h"
42 #include "cgroup-util.h"
44 #include "journal-rate-limit.h"
45 #include "journal-internal.h"
46 #include "conf-parser.h"
53 #include <acl/libacl.h>
58 #include <selinux/selinux.h>
61 #define USER_JOURNALS_MAX 1024
62 #define STDOUT_STREAMS_MAX 4096
64 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
65 #define DEFAULT_RATE_LIMIT_BURST 200
67 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
69 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
71 #define N_IOVEC_META_FIELDS 17
73 #define ENTRY_SIZE_MAX (1024*1024*32)
75 typedef enum StdoutStreamState {
76 STDOUT_STREAM_IDENTIFIER,
77 STDOUT_STREAM_PRIORITY,
78 STDOUT_STREAM_LEVEL_PREFIX,
79 STDOUT_STREAM_FORWARD_TO_SYSLOG,
80 STDOUT_STREAM_FORWARD_TO_KMSG,
81 STDOUT_STREAM_FORWARD_TO_CONSOLE,
87 StdoutStreamState state;
93 security_context_t security_context;
99 bool forward_to_syslog:1;
100 bool forward_to_kmsg:1;
101 bool forward_to_console:1;
103 char buffer[LINE_MAX+1];
106 LIST_FIELDS(StdoutStream, stdout_stream);
109 static int server_flush_to_var(Server *s);
111 static uint64_t available_space(Server *s) {
116 uint64_t sum = 0, avail = 0, ss_avail = 0;
122 ts = now(CLOCK_MONOTONIC);
124 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
125 return s->cached_available_space;
127 r = sd_id128_get_machine(&machine);
131 if (s->system_journal) {
132 f = "/var/log/journal/";
133 m = &s->system_metrics;
135 f = "/run/log/journal/";
136 m = &s->runtime_metrics;
141 p = strappend(f, sd_id128_to_string(machine, ids));
151 if (fstatvfs(dirfd(d), &ss) < 0)
156 struct dirent buf, *de;
158 r = readdir_r(d, &buf, &de);
165 if (!endswith(de->d_name, ".journal") &&
166 !endswith(de->d_name, ".journal~"))
169 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
172 if (!S_ISREG(st.st_mode))
175 sum += (uint64_t) st.st_blocks * 512UL;
178 avail = sum >= m->max_use ? 0 : m->max_use - sum;
180 ss_avail = ss.f_bsize * ss.f_bavail;
182 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
184 if (ss_avail < avail)
187 s->cached_available_space = avail;
188 s->cached_available_space_timestamp = ts;
196 static void server_read_file_gid(Server *s) {
197 const char *adm = "adm";
202 if (s->file_gid_valid)
205 r = get_group_creds(&adm, &s->file_gid);
207 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
209 /* if we couldn't read the gid, then it will be 0, but that's
210 * fine and we shouldn't try to resolve the group again, so
211 * let's just pretend it worked right-away. */
212 s->file_gid_valid = true;
215 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
220 acl_permset_t permset;
225 server_read_file_gid(s);
227 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
229 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
235 acl = acl_get_fd(f->fd);
237 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
241 r = acl_find_uid(acl, uid, &entry);
244 if (acl_create_entry(&acl, &entry) < 0 ||
245 acl_set_tag_type(entry, ACL_USER) < 0 ||
246 acl_set_qualifier(entry, &uid) < 0) {
247 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
252 if (acl_get_permset(entry, &permset) < 0 ||
253 acl_add_perm(permset, ACL_READ) < 0 ||
254 acl_calc_mask(&acl) < 0) {
255 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
259 if (acl_set_fd(f->fd, acl) < 0)
260 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
267 static JournalFile* find_journal(Server *s, uid_t uid) {
276 /* We split up user logs only on /var, not on /run. If the
277 * runtime file is open, we write to it exclusively, in order
278 * to guarantee proper order as soon as we flush /run to
279 * /var and close the runtime file. */
281 if (s->runtime_journal)
282 return s->runtime_journal;
285 return s->system_journal;
287 r = sd_id128_get_machine(&machine);
289 return s->system_journal;
291 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
295 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
296 return s->system_journal;
298 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
299 /* Too many open? Then let's close one */
300 f = hashmap_steal_first(s->user_journals);
302 journal_file_close(f);
305 r = journal_file_open_reliably(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
309 return s->system_journal;
311 server_fix_perms(s, f, uid);
313 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
315 journal_file_close(f);
316 return s->system_journal;
322 static void server_rotate(Server *s) {
328 log_info("Rotating...");
330 if (s->runtime_journal) {
331 r = journal_file_rotate(&s->runtime_journal);
333 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
335 server_fix_perms(s, s->runtime_journal, 0);
338 if (s->system_journal) {
339 r = journal_file_rotate(&s->system_journal);
341 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
343 server_fix_perms(s, s->system_journal, 0);
346 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
347 r = journal_file_rotate(&f);
349 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
351 hashmap_replace(s->user_journals, k, f);
352 server_fix_perms(s, s->system_journal, PTR_TO_UINT32(k));
357 static void server_vacuum(Server *s) {
363 log_info("Vacuuming...");
365 r = sd_id128_get_machine(&machine);
367 log_error("Failed to get machine ID: %s", strerror(-r));
371 sd_id128_to_string(machine, ids);
373 if (s->system_journal) {
374 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
375 log_error("Out of memory.");
379 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
380 if (r < 0 && r != -ENOENT)
381 log_error("Failed to vacuum %s: %s", p, strerror(-r));
386 if (s->runtime_journal) {
387 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
388 log_error("Out of memory.");
392 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
393 if (r < 0 && r != -ENOENT)
394 log_error("Failed to vacuum %s: %s", p, strerror(-r));
398 s->cached_available_space_timestamp = 0;
401 static char *shortened_cgroup_path(pid_t pid) {
403 char *process_path, *init_path, *path;
407 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
411 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
417 if (endswith(init_path, "/system"))
418 init_path[strlen(init_path) - 7] = 0;
419 else if (streq(init_path, "/"))
422 if (startswith(process_path, init_path)) {
425 p = strdup(process_path + strlen(init_path));
443 static void dispatch_message_real(
445 struct iovec *iovec, unsigned n, unsigned m,
448 const char *label, size_t label_len) {
450 char *pid = NULL, *uid = NULL, *gid = NULL,
451 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
452 *comm = NULL, *cmdline = NULL, *hostname = NULL,
453 *audit_session = NULL, *audit_loginuid = NULL,
454 *exe = NULL, *cgroup = NULL, *session = NULL,
455 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
461 uid_t loginuid = 0, realuid = 0;
463 bool vacuumed = false;
468 assert(n + N_IOVEC_META_FIELDS <= m);
474 realuid = ucred->uid;
476 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
477 IOVEC_SET_STRING(iovec[n++], pid);
479 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
480 IOVEC_SET_STRING(iovec[n++], uid);
482 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
483 IOVEC_SET_STRING(iovec[n++], gid);
485 r = get_process_comm(ucred->pid, &t);
487 comm = strappend("_COMM=", t);
491 IOVEC_SET_STRING(iovec[n++], comm);
494 r = get_process_exe(ucred->pid, &t);
496 exe = strappend("_EXE=", t);
500 IOVEC_SET_STRING(iovec[n++], exe);
503 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
505 cmdline = strappend("_CMDLINE=", t);
509 IOVEC_SET_STRING(iovec[n++], cmdline);
512 r = audit_session_from_pid(ucred->pid, &audit);
514 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
515 IOVEC_SET_STRING(iovec[n++], audit_session);
517 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
519 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
520 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
522 t = shortened_cgroup_path(ucred->pid);
524 cgroup = strappend("_SYSTEMD_CGROUP=", t);
528 IOVEC_SET_STRING(iovec[n++], cgroup);
531 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
532 session = strappend("_SYSTEMD_SESSION=", t);
536 IOVEC_SET_STRING(iovec[n++], session);
539 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
540 unit = strappend("_SYSTEMD_UNIT=", t);
544 IOVEC_SET_STRING(iovec[n++], unit);
547 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
548 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
549 IOVEC_SET_STRING(iovec[n++], owner_uid);
553 selinux_context = malloc(sizeof("_SELINUX_CONTEXT=") + label_len);
554 if (selinux_context) {
555 memcpy(selinux_context, "_SELINUX_CONTEXT=", sizeof("_SELINUX_CONTEXT=")-1);
556 memcpy(selinux_context+sizeof("_SELINUX_CONTEXT=")-1, label, label_len);
557 selinux_context[sizeof("_SELINUX_CONTEXT=")-1+label_len] = 0;
558 IOVEC_SET_STRING(iovec[n++], selinux_context);
561 security_context_t con;
563 if (getpidcon(ucred->pid, &con) >= 0) {
564 selinux_context = strappend("_SELINUX_CONTEXT=", con);
566 IOVEC_SET_STRING(iovec[n++], selinux_context);
575 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
576 (unsigned long long) timeval_load(tv)) >= 0)
577 IOVEC_SET_STRING(iovec[n++], source_time);
580 /* Note that strictly speaking storing the boot id here is
581 * redundant since the entry includes this in-line
582 * anyway. However, we need this indexed, too. */
583 r = sd_id128_get_boot(&id);
585 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
586 IOVEC_SET_STRING(iovec[n++], boot_id);
588 r = sd_id128_get_machine(&id);
590 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
591 IOVEC_SET_STRING(iovec[n++], machine_id);
593 t = gethostname_malloc();
595 hostname = strappend("_HOSTNAME=", t);
598 IOVEC_SET_STRING(iovec[n++], hostname);
603 server_flush_to_var(s);
606 f = find_journal(s, realuid == 0 ? 0 : loginuid);
608 log_warning("Dropping message, as we can't find a place to store the data.");
610 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
612 if ((r == -EBADMSG || r == -E2BIG) && !vacuumed) {
615 log_info("Allocation limit reached, rotating.");
617 log_warning("Journal file corrupted, rotating.");
623 log_info("Retrying write.");
628 log_error("Failed to write entry, ignoring: %s", strerror(-r));
642 free(audit_loginuid);
647 free(selinux_context);
650 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
651 char mid[11 + 32 + 1];
652 char buffer[16 + LINE_MAX + 1];
653 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
661 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
662 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
664 memcpy(buffer, "MESSAGE=", 8);
665 va_start(ap, format);
666 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
668 char_array_0(buffer);
669 IOVEC_SET_STRING(iovec[n++], buffer);
671 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
673 IOVEC_SET_STRING(iovec[n++], mid);
676 ucred.pid = getpid();
677 ucred.uid = getuid();
678 ucred.gid = getgid();
680 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0);
683 static void dispatch_message(Server *s,
684 struct iovec *iovec, unsigned n, unsigned m,
687 const char *label, size_t label_len,
690 char *path = NULL, *c;
693 assert(iovec || n == 0);
701 path = shortened_cgroup_path(ucred->pid);
705 /* example: /user/lennart/3/foobar
706 * /system/dbus.service/foobar
708 * So let's cut of everything past the third /, since that is
709 * wher user directories start */
711 c = strchr(path, '/');
713 c = strchr(c+1, '/');
715 c = strchr(c+1, '/');
721 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
728 /* Write a suppression message if we suppressed something */
730 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
735 dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len);
738 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
739 struct msghdr msghdr;
740 struct cmsghdr *cmsg;
742 struct cmsghdr cmsghdr;
743 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
745 union sockaddr_union sa;
752 msghdr.msg_iov = (struct iovec*) iovec;
753 msghdr.msg_iovlen = n_iovec;
756 sa.un.sun_family = AF_UNIX;
757 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
758 msghdr.msg_name = &sa;
759 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
763 msghdr.msg_control = &control;
764 msghdr.msg_controllen = sizeof(control);
766 cmsg = CMSG_FIRSTHDR(&msghdr);
767 cmsg->cmsg_level = SOL_SOCKET;
768 cmsg->cmsg_type = SCM_CREDENTIALS;
769 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
770 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
771 msghdr.msg_controllen = cmsg->cmsg_len;
774 /* Forward the syslog message we received via /dev/log to
775 * /run/systemd/syslog. Unfortunately we currently can't set
776 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
778 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
781 /* The socket is full? I guess the syslog implementation is
782 * too slow, and we shouldn't wait for that... */
786 if (ucred && errno == ESRCH) {
789 /* Hmm, presumably the sender process vanished
790 * by now, so let's fix it as good as we
795 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
797 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
804 log_debug("Failed to forward syslog message: %m");
807 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
813 IOVEC_SET_STRING(iovec, buffer);
814 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
817 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
818 struct iovec iovec[5];
819 char header_priority[6], header_time[64], header_pid[16];
823 char *ident_buf = NULL;
826 assert(priority >= 0);
827 assert(priority <= 999);
830 /* First: priority field */
831 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
832 char_array_0(header_priority);
833 IOVEC_SET_STRING(iovec[n++], header_priority);
835 /* Second: timestamp */
836 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
840 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
842 IOVEC_SET_STRING(iovec[n++], header_time);
844 /* Third: identifier and PID */
847 get_process_comm(ucred->pid, &ident_buf);
848 identifier = ident_buf;
851 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
852 char_array_0(header_pid);
855 IOVEC_SET_STRING(iovec[n++], identifier);
857 IOVEC_SET_STRING(iovec[n++], header_pid);
858 } else if (identifier) {
859 IOVEC_SET_STRING(iovec[n++], identifier);
860 IOVEC_SET_STRING(iovec[n++], ": ");
863 /* Fourth: message */
864 IOVEC_SET_STRING(iovec[n++], message);
866 forward_syslog_iovec(s, iovec, n, ucred, tv);
871 static int fixup_priority(int priority) {
873 if ((priority & LOG_FACMASK) == 0)
874 return (priority & LOG_PRIMASK) | LOG_USER;
879 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
880 struct iovec iovec[5];
881 char header_priority[6], header_pid[16];
883 char *ident_buf = NULL;
887 assert(priority >= 0);
888 assert(priority <= 999);
891 /* Never allow messages with kernel facility to be written to
892 * kmsg, regardless where the data comes from. */
893 priority = fixup_priority(priority);
895 /* First: priority field */
896 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
897 char_array_0(header_priority);
898 IOVEC_SET_STRING(iovec[n++], header_priority);
900 /* Second: identifier and PID */
903 get_process_comm(ucred->pid, &ident_buf);
904 identifier = ident_buf;
907 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
908 char_array_0(header_pid);
911 IOVEC_SET_STRING(iovec[n++], identifier);
913 IOVEC_SET_STRING(iovec[n++], header_pid);
914 } else if (identifier) {
915 IOVEC_SET_STRING(iovec[n++], identifier);
916 IOVEC_SET_STRING(iovec[n++], ": ");
919 /* Fourth: message */
920 IOVEC_SET_STRING(iovec[n++], message);
921 IOVEC_SET_STRING(iovec[n++], "\n");
923 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
925 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
929 if (writev(fd, iovec, n) < 0)
930 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
932 close_nointr_nofail(fd);
938 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
939 struct iovec iovec[4];
942 char *ident_buf = NULL;
947 /* First: identifier and PID */
950 get_process_comm(ucred->pid, &ident_buf);
951 identifier = ident_buf;
954 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
955 char_array_0(header_pid);
958 IOVEC_SET_STRING(iovec[n++], identifier);
960 IOVEC_SET_STRING(iovec[n++], header_pid);
961 } else if (identifier) {
962 IOVEC_SET_STRING(iovec[n++], identifier);
963 IOVEC_SET_STRING(iovec[n++], ": ");
967 IOVEC_SET_STRING(iovec[n++], message);
968 IOVEC_SET_STRING(iovec[n++], "\n");
970 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
972 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
976 if (writev(fd, iovec, n) < 0)
977 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
979 close_nointr_nofail(fd);
985 static void read_identifier(const char **buf, char **identifier, char **pid) {
996 p += strspn(p, WHITESPACE);
997 l = strcspn(p, WHITESPACE);
1006 if (p[l-1] == ']') {
1012 t = strndup(p+k+1, l-k-2);
1032 *buf += strspn(*buf, WHITESPACE);
1035 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) {
1036 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1037 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1039 int priority = LOG_USER | LOG_INFO;
1040 char *identifier = NULL, *pid = NULL;
1045 if (s->forward_to_syslog)
1046 forward_syslog_raw(s, buf, ucred, tv);
1048 parse_syslog_priority((char**) &buf, &priority);
1049 skip_syslog_date((char**) &buf);
1050 read_identifier(&buf, &identifier, &pid);
1052 if (s->forward_to_kmsg)
1053 forward_kmsg(s, priority, identifier, buf, ucred);
1055 if (s->forward_to_console)
1056 forward_console(s, identifier, buf, ucred);
1058 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1060 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1061 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1063 if (priority & LOG_FACMASK)
1064 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1065 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1068 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1069 if (syslog_identifier)
1070 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1074 syslog_pid = strappend("SYSLOG_PID=", pid);
1076 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1079 message = strappend("MESSAGE=", buf);
1081 IOVEC_SET_STRING(iovec[n++], message);
1083 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, label, label_len, priority);
1088 free(syslog_priority);
1089 free(syslog_facility);
1090 free(syslog_identifier);
1093 static bool valid_user_field(const char *p, size_t l) {
1096 /* We kinda enforce POSIX syntax recommendations for
1097 environment variables here, but make a couple of additional
1100 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1102 /* No empty field names */
1106 /* Don't allow names longer than 64 chars */
1110 /* Variables starting with an underscore are protected */
1114 /* Don't allow digits as first character */
1115 if (p[0] >= '0' && p[0] <= '9')
1118 /* Only allow A-Z0-9 and '_' */
1119 for (a = p; a < p + l; a++)
1120 if (!((*a >= 'A' && *a <= 'Z') ||
1121 (*a >= '0' && *a <= '9') ||
1128 static void process_native_message(
1130 const void *buffer, size_t buffer_size,
1131 struct ucred *ucred,
1133 const char *label, size_t label_len) {
1135 struct iovec *iovec = NULL;
1136 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1139 int priority = LOG_INFO;
1140 char *identifier = NULL, *message = NULL;
1143 assert(buffer || n == 0);
1146 remaining = buffer_size;
1148 while (remaining > 0) {
1151 e = memchr(p, '\n', remaining);
1154 /* Trailing noise, let's ignore it, and flush what we collected */
1155 log_debug("Received message with trailing noise, ignoring.");
1160 /* Entry separator */
1161 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1163 priority = LOG_INFO;
1170 if (*p == '.' || *p == '#') {
1171 /* Ignore control commands for now, and
1173 remaining -= (e - p) + 1;
1178 /* A property follows */
1180 if (n+N_IOVEC_META_FIELDS >= m) {
1184 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1185 c = realloc(iovec, u * sizeof(struct iovec));
1187 log_error("Out of memory");
1195 q = memchr(p, '=', e - p);
1197 if (valid_user_field(p, q - p)) {
1202 /* If the field name starts with an
1203 * underscore, skip the variable,
1204 * since that indidates a trusted
1206 iovec[n].iov_base = (char*) p;
1207 iovec[n].iov_len = l;
1210 /* We need to determine the priority
1211 * of this entry for the rate limiting
1214 memcmp(p, "PRIORITY=", 9) == 0 &&
1215 p[9] >= '0' && p[9] <= '9')
1216 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1219 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1220 p[16] >= '0' && p[16] <= '9')
1221 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1224 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1225 p[16] >= '0' && p[16] <= '9' &&
1226 p[17] >= '0' && p[17] <= '9')
1227 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1230 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1233 t = strndup(p + 11, l - 11);
1238 } else if (l >= 8 &&
1239 memcmp(p, "MESSAGE=", 8) == 0) {
1242 t = strndup(p + 8, l - 8);
1250 remaining -= (e - p) + 1;
1257 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1258 log_debug("Failed to parse message, ignoring.");
1262 memcpy(&l, e + 1, sizeof(uint64_t));
1265 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1266 e[1+sizeof(uint64_t)+l] != '\n') {
1267 log_debug("Failed to parse message, ignoring.");
1271 k = malloc((e - p) + 1 + l);
1273 log_error("Out of memory");
1277 memcpy(k, p, e - p);
1279 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1281 if (valid_user_field(p, e - p)) {
1282 iovec[n].iov_base = k;
1283 iovec[n].iov_len = (e - p) + 1 + l;
1288 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1289 p = e + 1 + sizeof(uint64_t) + l + 1;
1297 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1300 if (s->forward_to_syslog)
1301 forward_syslog(s, priority, identifier, message, ucred, tv);
1303 if (s->forward_to_kmsg)
1304 forward_kmsg(s, priority, identifier, message, ucred);
1306 if (s->forward_to_console)
1307 forward_console(s, identifier, message, ucred);
1310 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1313 for (j = 0; j < n; j++) {
1317 if (iovec[j].iov_base < buffer ||
1318 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1319 free(iovec[j].iov_base);
1327 static void process_native_file(
1330 struct ucred *ucred,
1332 const char *label, size_t label_len) {
1341 /* Data is in the passed file, since it didn't fit in a
1342 * datagram. We can't map the file here, since clients might
1343 * then truncate it and trigger a SIGBUS for us. So let's
1344 * stupidly read it */
1346 if (fstat(fd, &st) < 0) {
1347 log_error("Failed to stat passed file, ignoring: %m");
1351 if (!S_ISREG(st.st_mode)) {
1352 log_error("File passed is not regular. Ignoring.");
1356 if (st.st_size <= 0)
1359 if (st.st_size > ENTRY_SIZE_MAX) {
1360 log_error("File passed too large. Ignoring.");
1364 p = malloc(st.st_size);
1366 log_error("Out of memory");
1370 n = pread(fd, p, st.st_size, 0);
1372 log_error("Failed to read file, ignoring: %s", strerror(-n));
1374 process_native_message(s, p, n, ucred, tv, label, label_len);
1379 static int stdout_stream_log(StdoutStream *s, const char *p) {
1380 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1381 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1385 size_t label_len = 0;
1393 priority = s->priority;
1395 if (s->level_prefix)
1396 parse_syslog_priority((char**) &p, &priority);
1398 if (s->forward_to_syslog || s->server->forward_to_syslog)
1399 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1401 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1402 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1404 if (s->forward_to_console || s->server->forward_to_console)
1405 forward_console(s->server, s->identifier, p, &s->ucred);
1407 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1409 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1410 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1412 if (priority & LOG_FACMASK)
1413 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1414 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1416 if (s->identifier) {
1417 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1418 if (syslog_identifier)
1419 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1422 message = strappend("MESSAGE=", p);
1424 IOVEC_SET_STRING(iovec[n++], message);
1427 if (s->security_context) {
1428 label = (char*) s->security_context;
1429 label_len = strlen((char*) s->security_context);
1433 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, priority);
1436 free(syslog_priority);
1437 free(syslog_facility);
1438 free(syslog_identifier);
1443 static int stdout_stream_line(StdoutStream *s, char *p) {
1453 case STDOUT_STREAM_IDENTIFIER:
1455 s->identifier = NULL;
1457 s->identifier = strdup(p);
1458 if (!s->identifier) {
1459 log_error("Out of memory");
1464 s->state = STDOUT_STREAM_PRIORITY;
1467 case STDOUT_STREAM_PRIORITY:
1468 r = safe_atoi(p, &s->priority);
1469 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1470 log_warning("Failed to parse log priority line.");
1474 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1477 case STDOUT_STREAM_LEVEL_PREFIX:
1478 r = parse_boolean(p);
1480 log_warning("Failed to parse level prefix line.");
1484 s->level_prefix = !!r;
1485 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1488 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1489 r = parse_boolean(p);
1491 log_warning("Failed to parse forward to syslog line.");
1495 s->forward_to_syslog = !!r;
1496 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1499 case STDOUT_STREAM_FORWARD_TO_KMSG:
1500 r = parse_boolean(p);
1502 log_warning("Failed to parse copy to kmsg line.");
1506 s->forward_to_kmsg = !!r;
1507 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1510 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1511 r = parse_boolean(p);
1513 log_warning("Failed to parse copy to console line.");
1517 s->forward_to_console = !!r;
1518 s->state = STDOUT_STREAM_RUNNING;
1521 case STDOUT_STREAM_RUNNING:
1522 return stdout_stream_log(s, p);
1525 assert_not_reached("Unknown stream state");
1528 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1536 remaining = s->length;
1541 end = memchr(p, '\n', remaining);
1544 else if (remaining >= sizeof(s->buffer) - 1) {
1545 end = p + sizeof(s->buffer) - 1;
1552 r = stdout_stream_line(s, p);
1560 if (force_flush && remaining > 0) {
1562 r = stdout_stream_line(s, p);
1570 if (p > s->buffer) {
1571 memmove(s->buffer, p, remaining);
1572 s->length = remaining;
1578 static int stdout_stream_process(StdoutStream *s) {
1584 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1587 if (errno == EAGAIN)
1590 log_warning("Failed to read from stream: %m");
1595 r = stdout_stream_scan(s, true);
1603 r = stdout_stream_scan(s, false);
1611 static void stdout_stream_free(StdoutStream *s) {
1615 assert(s->server->n_stdout_streams > 0);
1616 s->server->n_stdout_streams --;
1617 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1622 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1624 close_nointr_nofail(s->fd);
1628 if (s->security_context)
1629 freecon(s->security_context);
1632 free(s->identifier);
1636 static int stdout_stream_new(Server *s) {
1637 StdoutStream *stream;
1640 struct epoll_event ev;
1644 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1646 if (errno == EAGAIN)
1649 log_error("Failed to accept stdout connection: %m");
1653 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1654 log_warning("Too many stdout streams, refusing connection.");
1655 close_nointr_nofail(fd);
1659 stream = new0(StdoutStream, 1);
1661 log_error("Out of memory.");
1662 close_nointr_nofail(fd);
1668 len = sizeof(stream->ucred);
1669 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1670 log_error("Failed to determine peer credentials: %m");
1676 if (getpeercon(fd, &stream->security_context) < 0)
1677 log_error("Failed to determine peer security context.");
1680 if (shutdown(fd, SHUT_WR) < 0) {
1681 log_error("Failed to shutdown writing side of socket: %m");
1687 ev.data.ptr = stream;
1688 ev.events = EPOLLIN;
1689 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1690 log_error("Failed to add stream to event loop: %m");
1696 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1697 s->n_stdout_streams ++;
1702 stdout_stream_free(stream);
1706 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1717 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1722 for (i = 1; i <= 5; i++) {
1728 k = undecchar(p[i]);
1735 for (i = 7; i <= 12; i++) {
1738 k = undecchar(p[i]);
1747 *_p += strspn(*_p, WHITESPACE);
1752 static void proc_kmsg_line(Server *s, const char *p) {
1753 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1754 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1755 int priority = LOG_KERN | LOG_INFO;
1758 char *identifier = NULL, *pid = NULL;
1766 parse_syslog_priority((char **) &p, &priority);
1768 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1771 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1772 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1773 (unsigned long long) usec) >= 0)
1774 IOVEC_SET_STRING(iovec[n++], source_time);
1777 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1779 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1780 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1782 if ((priority & LOG_FACMASK) == LOG_KERN) {
1784 if (s->forward_to_syslog)
1785 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1787 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1789 read_identifier(&p, &identifier, &pid);
1791 if (s->forward_to_syslog)
1792 forward_syslog(s, priority, identifier, p, NULL, NULL);
1795 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1796 if (syslog_identifier)
1797 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1801 syslog_pid = strappend("SYSLOG_PID=", pid);
1803 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1806 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1807 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1810 message = strappend("MESSAGE=", p);
1812 IOVEC_SET_STRING(iovec[n++], message);
1814 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, priority);
1817 free(syslog_priority);
1818 free(syslog_identifier);
1820 free(syslog_facility);
1826 static void proc_kmsg_scan(Server *s) {
1832 p = s->proc_kmsg_buffer;
1833 remaining = s->proc_kmsg_length;
1838 end = memchr(p, '\n', remaining);
1841 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1842 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1849 proc_kmsg_line(s, p);
1855 if (p > s->proc_kmsg_buffer) {
1856 memmove(s->proc_kmsg_buffer, p, remaining);
1857 s->proc_kmsg_length = remaining;
1861 static int system_journal_open(Server *s) {
1867 r = sd_id128_get_machine(&machine);
1871 sd_id128_to_string(machine, ids);
1873 if (!s->system_journal) {
1875 /* First try to create the machine path, but not the prefix */
1876 fn = strappend("/var/log/journal/", ids);
1879 (void) mkdir(fn, 0755);
1882 /* The create the system journal file */
1883 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1887 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1891 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1893 s->system_journal->metrics = s->system_metrics;
1894 s->system_journal->compress = s->compress;
1896 server_fix_perms(s, s->system_journal, 0);
1899 if (r != -ENOENT && r != -EROFS)
1900 log_warning("Failed to open system journal: %s", strerror(-r));
1906 if (!s->runtime_journal) {
1908 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1912 if (s->system_journal) {
1914 /* Try to open the runtime journal, but only
1915 * if it already exists, so that we can flush
1916 * it into the system journal */
1918 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1923 log_warning("Failed to open runtime journal: %s", strerror(-r));
1930 /* OK, we really need the runtime journal, so create
1931 * it if necessary. */
1933 (void) mkdir_parents(fn, 0755);
1934 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1938 log_error("Failed to open runtime journal: %s", strerror(-r));
1943 if (s->runtime_journal) {
1944 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1946 s->runtime_journal->metrics = s->runtime_metrics;
1947 s->runtime_journal->compress = s->compress;
1949 server_fix_perms(s, s->runtime_journal, 0);
1956 static int server_flush_to_var(Server *s) {
1957 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1966 if (!s->runtime_journal)
1969 ts = now(CLOCK_MONOTONIC);
1970 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1973 s->var_available_timestamp = ts;
1975 system_journal_open(s);
1977 if (!s->system_journal)
1980 log_info("Flushing to /var...");
1982 r = sd_id128_get_machine(&machine);
1984 log_error("Failed to get machine id: %s", strerror(-r));
1988 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1990 log_error("Failed to read runtime journal: %s", strerror(-r));
1994 SD_JOURNAL_FOREACH(j) {
1997 f = j->current_file;
1998 assert(f && f->current_offset > 0);
2000 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2002 log_error("Can't read entry: %s", strerror(-r));
2006 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2008 log_info("Allocation limit reached.");
2010 journal_file_post_change(s->system_journal);
2014 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2018 log_error("Can't write entry: %s", strerror(-r));
2024 journal_file_post_change(s->system_journal);
2026 journal_file_close(s->runtime_journal);
2027 s->runtime_journal = NULL;
2030 sd_id128_to_string(machine, path + 17);
2031 rm_rf(path, false, true, false);
2037 static int server_read_proc_kmsg(Server *s) {
2040 assert(s->proc_kmsg_fd >= 0);
2042 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
2045 if (errno == EAGAIN || errno == EINTR)
2048 log_error("Failed to read from kernel: %m");
2052 s->proc_kmsg_length += l;
2058 static int server_flush_proc_kmsg(Server *s) {
2063 if (s->proc_kmsg_fd < 0)
2066 log_info("Flushing /proc/kmsg...");
2069 r = server_read_proc_kmsg(s);
2080 static int process_event(Server *s, struct epoll_event *ev) {
2083 if (ev->data.fd == s->signal_fd) {
2084 struct signalfd_siginfo sfsi;
2087 if (ev->events != EPOLLIN) {
2088 log_info("Got invalid event from epoll.");
2092 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2093 if (n != sizeof(sfsi)) {
2098 if (errno == EINTR || errno == EAGAIN)
2104 if (sfsi.ssi_signo == SIGUSR1) {
2105 server_flush_to_var(s);
2109 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2112 } else if (ev->data.fd == s->proc_kmsg_fd) {
2115 if (ev->events != EPOLLIN) {
2116 log_info("Got invalid event from epoll.");
2120 r = server_read_proc_kmsg(s);
2126 } else if (ev->data.fd == s->native_fd ||
2127 ev->data.fd == s->syslog_fd) {
2129 if (ev->events != EPOLLIN) {
2130 log_info("Got invalid event from epoll.");
2135 struct msghdr msghdr;
2137 struct ucred *ucred = NULL;
2138 struct timeval *tv = NULL;
2139 struct cmsghdr *cmsg;
2141 size_t label_len = 0;
2143 struct cmsghdr cmsghdr;
2144 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2145 CMSG_SPACE(sizeof(struct timeval)) +
2146 CMSG_SPACE(sizeof(int)) +
2147 CMSG_SPACE(PAGE_SIZE)]; /* selinux label */
2154 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2155 log_error("SIOCINQ failed: %m");
2159 if (s->buffer_size < (size_t) v) {
2163 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2164 b = realloc(s->buffer, l+1);
2167 log_error("Couldn't increase buffer.");
2176 iovec.iov_base = s->buffer;
2177 iovec.iov_len = s->buffer_size;
2181 msghdr.msg_iov = &iovec;
2182 msghdr.msg_iovlen = 1;
2183 msghdr.msg_control = &control;
2184 msghdr.msg_controllen = sizeof(control);
2186 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2189 if (errno == EINTR || errno == EAGAIN)
2192 log_error("recvmsg() failed: %m");
2196 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2198 if (cmsg->cmsg_level == SOL_SOCKET &&
2199 cmsg->cmsg_type == SCM_CREDENTIALS &&
2200 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2201 ucred = (struct ucred*) CMSG_DATA(cmsg);
2202 else if (cmsg->cmsg_level == SOL_SOCKET &&
2203 cmsg->cmsg_type == SCM_SECURITY) {
2204 label = (char*) CMSG_DATA(cmsg);
2205 label_len = cmsg->cmsg_len - CMSG_LEN(0);
2206 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2207 cmsg->cmsg_type == SO_TIMESTAMP &&
2208 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2209 tv = (struct timeval*) CMSG_DATA(cmsg);
2210 else if (cmsg->cmsg_level == SOL_SOCKET &&
2211 cmsg->cmsg_type == SCM_RIGHTS) {
2212 fds = (int*) CMSG_DATA(cmsg);
2213 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2217 if (ev->data.fd == s->syslog_fd) {
2220 if (n > 0 && n_fds == 0) {
2221 e = memchr(s->buffer, '\n', n);
2227 process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
2228 } else if (n_fds > 0)
2229 log_warning("Got file descriptors via syslog socket. Ignoring.");
2232 if (n > 0 && n_fds == 0)
2233 process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
2234 else if (n == 0 && n_fds == 1)
2235 process_native_file(s, fds[0], ucred, tv, label, label_len);
2237 log_warning("Got too many file descriptors via native socket. Ignoring.");
2240 close_many(fds, n_fds);
2245 } else if (ev->data.fd == s->stdout_fd) {
2247 if (ev->events != EPOLLIN) {
2248 log_info("Got invalid event from epoll.");
2252 stdout_stream_new(s);
2256 StdoutStream *stream;
2258 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2259 log_info("Got invalid event from epoll.");
2263 /* If it is none of the well-known fds, it must be an
2264 * stdout stream fd. Note that this is a bit ugly here
2265 * (since we rely that none of the well-known fds
2266 * could be interpreted as pointer), but nonetheless
2267 * safe, since the well-known fds would never get an
2268 * fd > 4096, i.e. beyond the first memory page */
2270 stream = ev->data.ptr;
2272 if (stdout_stream_process(stream) <= 0)
2273 stdout_stream_free(stream);
2278 log_error("Unknown event.");
2282 static int open_syslog_socket(Server *s) {
2283 union sockaddr_union sa;
2285 struct epoll_event ev;
2289 if (s->syslog_fd < 0) {
2291 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2292 if (s->syslog_fd < 0) {
2293 log_error("socket() failed: %m");
2298 sa.un.sun_family = AF_UNIX;
2299 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2301 unlink(sa.un.sun_path);
2303 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2305 log_error("bind() failed: %m");
2309 chmod(sa.un.sun_path, 0666);
2311 fd_nonblock(s->syslog_fd, 1);
2314 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2316 log_error("SO_PASSCRED failed: %m");
2322 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2324 log_warning("SO_PASSSEC failed: %m");
2328 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2330 log_error("SO_TIMESTAMP failed: %m");
2335 ev.events = EPOLLIN;
2336 ev.data.fd = s->syslog_fd;
2337 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2338 log_error("Failed to add syslog server fd to epoll object: %m");
2345 static int open_native_socket(Server*s) {
2346 union sockaddr_union sa;
2348 struct epoll_event ev;
2352 if (s->native_fd < 0) {
2354 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2355 if (s->native_fd < 0) {
2356 log_error("socket() failed: %m");
2361 sa.un.sun_family = AF_UNIX;
2362 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2364 unlink(sa.un.sun_path);
2366 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2368 log_error("bind() failed: %m");
2372 chmod(sa.un.sun_path, 0666);
2374 fd_nonblock(s->native_fd, 1);
2377 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2379 log_error("SO_PASSCRED failed: %m");
2385 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2387 log_warning("SO_PASSSEC failed: %m");
2391 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2393 log_error("SO_TIMESTAMP failed: %m");
2398 ev.events = EPOLLIN;
2399 ev.data.fd = s->native_fd;
2400 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2401 log_error("Failed to add native server fd to epoll object: %m");
2408 static int open_stdout_socket(Server *s) {
2409 union sockaddr_union sa;
2411 struct epoll_event ev;
2415 if (s->stdout_fd < 0) {
2417 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2418 if (s->stdout_fd < 0) {
2419 log_error("socket() failed: %m");
2424 sa.un.sun_family = AF_UNIX;
2425 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2427 unlink(sa.un.sun_path);
2429 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2431 log_error("bind() failed: %m");
2435 chmod(sa.un.sun_path, 0666);
2437 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2438 log_error("liste() failed: %m");
2442 fd_nonblock(s->stdout_fd, 1);
2445 ev.events = EPOLLIN;
2446 ev.data.fd = s->stdout_fd;
2447 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2448 log_error("Failed to add stdout server fd to epoll object: %m");
2455 static int open_proc_kmsg(Server *s) {
2456 struct epoll_event ev;
2460 if (!s->import_proc_kmsg)
2464 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2465 if (s->proc_kmsg_fd < 0) {
2466 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2471 ev.events = EPOLLIN;
2472 ev.data.fd = s->proc_kmsg_fd;
2473 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2474 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2481 static int open_signalfd(Server *s) {
2483 struct epoll_event ev;
2487 assert_se(sigemptyset(&mask) == 0);
2488 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2489 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2491 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2492 if (s->signal_fd < 0) {
2493 log_error("signalfd(): %m");
2498 ev.events = EPOLLIN;
2499 ev.data.fd = s->signal_fd;
2501 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2502 log_error("epoll_ctl(): %m");
2509 static int server_parse_proc_cmdline(Server *s) {
2510 char *line, *w, *state;
2514 if (detect_container(NULL) > 0)
2517 r = read_one_line_file("/proc/cmdline", &line);
2519 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2523 FOREACH_WORD_QUOTED(w, l, line, state) {
2526 word = strndup(w, l);
2532 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2533 r = parse_boolean(word + 35);
2535 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2537 s->forward_to_syslog = r;
2538 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2539 r = parse_boolean(word + 33);
2541 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2543 s->forward_to_kmsg = r;
2544 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2545 r = parse_boolean(word + 36);
2547 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2549 s->forward_to_console = r;
2562 static int server_parse_config_file(Server *s) {
2569 fn = "/etc/systemd/systemd-journald.conf";
2570 f = fopen(fn, "re");
2572 if (errno == ENOENT)
2575 log_warning("Failed to open configuration file %s: %m", fn);
2579 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2581 log_warning("Failed to parse configuration file: %s", strerror(-r));
2588 static int server_init(Server *s) {
2594 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2597 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2598 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2600 s->forward_to_syslog = true;
2601 s->import_proc_kmsg = true;
2603 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2604 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2606 server_parse_config_file(s);
2607 server_parse_proc_cmdline(s);
2609 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2610 if (!s->user_journals) {
2611 log_error("Out of memory.");
2615 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2616 if (s->epoll_fd < 0) {
2617 log_error("Failed to create epoll object: %m");
2621 n = sd_listen_fds(true);
2623 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2627 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2629 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2631 if (s->native_fd >= 0) {
2632 log_error("Too many native sockets passed.");
2638 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2640 if (s->stdout_fd >= 0) {
2641 log_error("Too many stdout sockets passed.");
2647 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2649 if (s->syslog_fd >= 0) {
2650 log_error("Too many /dev/log sockets passed.");
2657 log_error("Unknown socket passed.");
2662 r = open_syslog_socket(s);
2666 r = open_native_socket(s);
2670 r = open_stdout_socket(s);
2674 r = open_proc_kmsg(s);
2678 r = open_signalfd(s);
2682 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2686 r = system_journal_open(s);
2693 static void server_done(Server *s) {
2697 while (s->stdout_streams)
2698 stdout_stream_free(s->stdout_streams);
2700 if (s->system_journal)
2701 journal_file_close(s->system_journal);
2703 if (s->runtime_journal)
2704 journal_file_close(s->runtime_journal);
2706 while ((f = hashmap_steal_first(s->user_journals)))
2707 journal_file_close(f);
2709 hashmap_free(s->user_journals);
2711 if (s->epoll_fd >= 0)
2712 close_nointr_nofail(s->epoll_fd);
2714 if (s->signal_fd >= 0)
2715 close_nointr_nofail(s->signal_fd);
2717 if (s->syslog_fd >= 0)
2718 close_nointr_nofail(s->syslog_fd);
2720 if (s->native_fd >= 0)
2721 close_nointr_nofail(s->native_fd);
2723 if (s->stdout_fd >= 0)
2724 close_nointr_nofail(s->stdout_fd);
2726 if (s->proc_kmsg_fd >= 0)
2727 close_nointr_nofail(s->proc_kmsg_fd);
2730 journal_rate_limit_free(s->rate_limit);
2735 int main(int argc, char *argv[]) {
2739 /* if (getppid() != 1) { */
2740 /* log_error("This program should be invoked by init only."); */
2741 /* return EXIT_FAILURE; */
2745 log_error("This program does not take arguments.");
2746 return EXIT_FAILURE;
2749 log_set_target(LOG_TARGET_CONSOLE);
2750 log_parse_environment();
2755 r = server_init(&server);
2759 server_vacuum(&server);
2760 server_flush_to_var(&server);
2761 server_flush_proc_kmsg(&server);
2763 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2764 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2768 "STATUS=Processing requests...");
2771 struct epoll_event event;
2773 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2779 log_error("epoll_wait() failed: %m");
2785 r = process_event(&server, &event);
2792 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2793 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2797 "STATUS=Shutting down...");
2799 server_done(&server);
2801 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;