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;
159 k = readdir_r(d, &buf, &de);
168 if (!endswith(de->d_name, ".journal") &&
169 !endswith(de->d_name, ".journal~"))
172 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
175 if (!S_ISREG(st.st_mode))
178 sum += (uint64_t) st.st_blocks * 512UL;
181 avail = sum >= m->max_use ? 0 : m->max_use - sum;
183 ss_avail = ss.f_bsize * ss.f_bavail;
185 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
187 if (ss_avail < avail)
190 s->cached_available_space = avail;
191 s->cached_available_space_timestamp = ts;
199 static void server_read_file_gid(Server *s) {
200 const char *adm = "adm";
205 if (s->file_gid_valid)
208 r = get_group_creds(&adm, &s->file_gid);
210 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
212 /* if we couldn't read the gid, then it will be 0, but that's
213 * fine and we shouldn't try to resolve the group again, so
214 * let's just pretend it worked right-away. */
215 s->file_gid_valid = true;
218 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
223 acl_permset_t permset;
228 server_read_file_gid(s);
230 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
232 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
238 acl = acl_get_fd(f->fd);
240 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
244 r = acl_find_uid(acl, uid, &entry);
247 if (acl_create_entry(&acl, &entry) < 0 ||
248 acl_set_tag_type(entry, ACL_USER) < 0 ||
249 acl_set_qualifier(entry, &uid) < 0) {
250 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
255 if (acl_get_permset(entry, &permset) < 0 ||
256 acl_add_perm(permset, ACL_READ) < 0 ||
257 acl_calc_mask(&acl) < 0) {
258 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
262 if (acl_set_fd(f->fd, acl) < 0)
263 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
270 static JournalFile* find_journal(Server *s, uid_t uid) {
279 /* We split up user logs only on /var, not on /run. If the
280 * runtime file is open, we write to it exclusively, in order
281 * to guarantee proper order as soon as we flush /run to
282 * /var and close the runtime file. */
284 if (s->runtime_journal)
285 return s->runtime_journal;
288 return s->system_journal;
290 r = sd_id128_get_machine(&machine);
292 return s->system_journal;
294 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
298 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
299 return s->system_journal;
301 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
302 /* Too many open? Then let's close one */
303 f = hashmap_steal_first(s->user_journals);
305 journal_file_close(f);
308 r = journal_file_open_reliably(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
312 return s->system_journal;
314 server_fix_perms(s, f, uid);
316 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
318 journal_file_close(f);
319 return s->system_journal;
325 static void server_rotate(Server *s) {
331 log_info("Rotating...");
333 if (s->runtime_journal) {
334 r = journal_file_rotate(&s->runtime_journal);
336 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
339 if (s->system_journal) {
340 r = journal_file_rotate(&s->system_journal);
342 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
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);
354 static void server_vacuum(Server *s) {
360 log_info("Vacuuming...");
362 r = sd_id128_get_machine(&machine);
364 log_error("Failed to get machine ID: %s", strerror(-r));
368 sd_id128_to_string(machine, ids);
370 if (s->system_journal) {
371 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
372 log_error("Out of memory.");
376 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
377 if (r < 0 && r != -ENOENT)
378 log_error("Failed to vacuum %s: %s", p, strerror(-r));
383 if (s->runtime_journal) {
384 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
385 log_error("Out of memory.");
389 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
390 if (r < 0 && r != -ENOENT)
391 log_error("Failed to vacuum %s: %s", p, strerror(-r));
395 s->cached_available_space_timestamp = 0;
398 static char *shortened_cgroup_path(pid_t pid) {
400 char *process_path, *init_path, *path;
404 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
408 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
414 if (endswith(init_path, "/system"))
415 init_path[strlen(init_path) - 7] = 0;
416 else if (streq(init_path, "/"))
419 if (startswith(process_path, init_path)) {
422 p = strdup(process_path + strlen(init_path));
440 static void dispatch_message_real(
442 struct iovec *iovec, unsigned n, unsigned m,
445 const char *label, size_t label_len) {
447 char *pid = NULL, *uid = NULL, *gid = NULL,
448 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
449 *comm = NULL, *cmdline = NULL, *hostname = NULL,
450 *audit_session = NULL, *audit_loginuid = NULL,
451 *exe = NULL, *cgroup = NULL, *session = NULL,
452 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
458 uid_t loginuid = 0, realuid = 0;
460 bool vacuumed = false;
465 assert(n + N_IOVEC_META_FIELDS <= m);
471 realuid = ucred->uid;
473 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
474 IOVEC_SET_STRING(iovec[n++], pid);
476 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
477 IOVEC_SET_STRING(iovec[n++], uid);
479 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
480 IOVEC_SET_STRING(iovec[n++], gid);
482 r = get_process_comm(ucred->pid, &t);
484 comm = strappend("_COMM=", t);
488 IOVEC_SET_STRING(iovec[n++], comm);
491 r = get_process_exe(ucred->pid, &t);
493 exe = strappend("_EXE=", t);
497 IOVEC_SET_STRING(iovec[n++], exe);
500 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
502 cmdline = strappend("_CMDLINE=", t);
506 IOVEC_SET_STRING(iovec[n++], cmdline);
509 r = audit_session_from_pid(ucred->pid, &audit);
511 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
512 IOVEC_SET_STRING(iovec[n++], audit_session);
514 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
516 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
517 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
519 t = shortened_cgroup_path(ucred->pid);
521 cgroup = strappend("_SYSTEMD_CGROUP=", t);
525 IOVEC_SET_STRING(iovec[n++], cgroup);
528 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
529 session = strappend("_SYSTEMD_SESSION=", t);
533 IOVEC_SET_STRING(iovec[n++], session);
536 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
537 unit = strappend("_SYSTEMD_UNIT=", t);
541 IOVEC_SET_STRING(iovec[n++], unit);
544 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
545 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
546 IOVEC_SET_STRING(iovec[n++], owner_uid);
550 selinux_context = malloc(sizeof("_SELINUX_CONTEXT=") + label_len);
551 if (selinux_context) {
552 memcpy(selinux_context, "_SELINUX_CONTEXT=", sizeof("_SELINUX_CONTEXT=")-1);
553 memcpy(selinux_context+sizeof("_SELINUX_CONTEXT=")-1, label, label_len);
554 selinux_context[sizeof("_SELINUX_CONTEXT=")-1+label_len] = 0;
555 IOVEC_SET_STRING(iovec[n++], selinux_context);
558 security_context_t con;
560 if (getpidcon(ucred->pid, &con) >= 0) {
561 selinux_context = strappend("_SELINUX_CONTEXT=", con);
563 IOVEC_SET_STRING(iovec[n++], selinux_context);
572 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
573 (unsigned long long) timeval_load(tv)) >= 0)
574 IOVEC_SET_STRING(iovec[n++], source_time);
577 /* Note that strictly speaking storing the boot id here is
578 * redundant since the entry includes this in-line
579 * anyway. However, we need this indexed, too. */
580 r = sd_id128_get_boot(&id);
582 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
583 IOVEC_SET_STRING(iovec[n++], boot_id);
585 r = sd_id128_get_machine(&id);
587 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
588 IOVEC_SET_STRING(iovec[n++], machine_id);
590 t = gethostname_malloc();
592 hostname = strappend("_HOSTNAME=", t);
595 IOVEC_SET_STRING(iovec[n++], hostname);
600 server_flush_to_var(s);
603 f = find_journal(s, realuid == 0 ? 0 : loginuid);
605 log_warning("Dropping message, as we can't find a place to store the data.");
607 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
609 if ((r == -EBADMSG || r == -E2BIG) && !vacuumed) {
612 log_info("Allocation limit reached, rotating.");
614 log_warning("Journal file corrupted, rotating.");
620 log_info("Retrying write.");
625 log_error("Failed to write entry, ignoring: %s", strerror(-r));
639 free(audit_loginuid);
644 free(selinux_context);
647 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
648 char mid[11 + 32 + 1];
649 char buffer[16 + LINE_MAX + 1];
650 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
658 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
659 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
661 memcpy(buffer, "MESSAGE=", 8);
662 va_start(ap, format);
663 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
665 char_array_0(buffer);
666 IOVEC_SET_STRING(iovec[n++], buffer);
668 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
670 IOVEC_SET_STRING(iovec[n++], mid);
673 ucred.pid = getpid();
674 ucred.uid = getuid();
675 ucred.gid = getgid();
677 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0);
680 static void dispatch_message(Server *s,
681 struct iovec *iovec, unsigned n, unsigned m,
684 const char *label, size_t label_len,
687 char *path = NULL, *c;
690 assert(iovec || n == 0);
698 path = shortened_cgroup_path(ucred->pid);
702 /* example: /user/lennart/3/foobar
703 * /system/dbus.service/foobar
705 * So let's cut of everything past the third /, since that is
706 * wher user directories start */
708 c = strchr(path, '/');
710 c = strchr(c+1, '/');
712 c = strchr(c+1, '/');
718 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
725 /* Write a suppression message if we suppressed something */
727 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
732 dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len);
735 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
736 struct msghdr msghdr;
737 struct cmsghdr *cmsg;
739 struct cmsghdr cmsghdr;
740 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
742 union sockaddr_union sa;
749 msghdr.msg_iov = (struct iovec*) iovec;
750 msghdr.msg_iovlen = n_iovec;
753 sa.un.sun_family = AF_UNIX;
754 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
755 msghdr.msg_name = &sa;
756 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
760 msghdr.msg_control = &control;
761 msghdr.msg_controllen = sizeof(control);
763 cmsg = CMSG_FIRSTHDR(&msghdr);
764 cmsg->cmsg_level = SOL_SOCKET;
765 cmsg->cmsg_type = SCM_CREDENTIALS;
766 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
767 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
768 msghdr.msg_controllen = cmsg->cmsg_len;
771 /* Forward the syslog message we received via /dev/log to
772 * /run/systemd/syslog. Unfortunately we currently can't set
773 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
775 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
778 /* The socket is full? I guess the syslog implementation is
779 * too slow, and we shouldn't wait for that... */
783 if (ucred && errno == ESRCH) {
786 /* Hmm, presumably the sender process vanished
787 * by now, so let's fix it as good as we
792 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
794 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
801 log_debug("Failed to forward syslog message: %m");
804 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
810 IOVEC_SET_STRING(iovec, buffer);
811 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
814 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
815 struct iovec iovec[5];
816 char header_priority[6], header_time[64], header_pid[16];
820 char *ident_buf = NULL;
823 assert(priority >= 0);
824 assert(priority <= 999);
827 /* First: priority field */
828 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
829 char_array_0(header_priority);
830 IOVEC_SET_STRING(iovec[n++], header_priority);
832 /* Second: timestamp */
833 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
837 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
839 IOVEC_SET_STRING(iovec[n++], header_time);
841 /* Third: identifier and PID */
844 get_process_comm(ucred->pid, &ident_buf);
845 identifier = ident_buf;
848 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
849 char_array_0(header_pid);
852 IOVEC_SET_STRING(iovec[n++], identifier);
854 IOVEC_SET_STRING(iovec[n++], header_pid);
855 } else if (identifier) {
856 IOVEC_SET_STRING(iovec[n++], identifier);
857 IOVEC_SET_STRING(iovec[n++], ": ");
860 /* Fourth: message */
861 IOVEC_SET_STRING(iovec[n++], message);
863 forward_syslog_iovec(s, iovec, n, ucred, tv);
868 static int fixup_priority(int priority) {
870 if ((priority & LOG_FACMASK) == 0)
871 return (priority & LOG_PRIMASK) | LOG_USER;
876 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
877 struct iovec iovec[5];
878 char header_priority[6], header_pid[16];
880 char *ident_buf = NULL;
884 assert(priority >= 0);
885 assert(priority <= 999);
888 /* Never allow messages with kernel facility to be written to
889 * kmsg, regardless where the data comes from. */
890 priority = fixup_priority(priority);
892 /* First: priority field */
893 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
894 char_array_0(header_priority);
895 IOVEC_SET_STRING(iovec[n++], header_priority);
897 /* Second: identifier and PID */
900 get_process_comm(ucred->pid, &ident_buf);
901 identifier = ident_buf;
904 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
905 char_array_0(header_pid);
908 IOVEC_SET_STRING(iovec[n++], identifier);
910 IOVEC_SET_STRING(iovec[n++], header_pid);
911 } else if (identifier) {
912 IOVEC_SET_STRING(iovec[n++], identifier);
913 IOVEC_SET_STRING(iovec[n++], ": ");
916 /* Fourth: message */
917 IOVEC_SET_STRING(iovec[n++], message);
918 IOVEC_SET_STRING(iovec[n++], "\n");
920 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
922 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
926 if (writev(fd, iovec, n) < 0)
927 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
929 close_nointr_nofail(fd);
935 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
936 struct iovec iovec[4];
939 char *ident_buf = NULL;
944 /* First: identifier and PID */
947 get_process_comm(ucred->pid, &ident_buf);
948 identifier = ident_buf;
951 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
952 char_array_0(header_pid);
955 IOVEC_SET_STRING(iovec[n++], identifier);
957 IOVEC_SET_STRING(iovec[n++], header_pid);
958 } else if (identifier) {
959 IOVEC_SET_STRING(iovec[n++], identifier);
960 IOVEC_SET_STRING(iovec[n++], ": ");
964 IOVEC_SET_STRING(iovec[n++], message);
965 IOVEC_SET_STRING(iovec[n++], "\n");
967 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
969 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
973 if (writev(fd, iovec, n) < 0)
974 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
976 close_nointr_nofail(fd);
982 static void read_identifier(const char **buf, char **identifier, char **pid) {
993 p += strspn(p, WHITESPACE);
994 l = strcspn(p, WHITESPACE);
1003 if (p[l-1] == ']') {
1009 t = strndup(p+k+1, l-k-2);
1029 *buf += strspn(*buf, WHITESPACE);
1032 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) {
1033 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1034 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1036 int priority = LOG_USER | LOG_INFO;
1037 char *identifier = NULL, *pid = NULL;
1042 if (s->forward_to_syslog)
1043 forward_syslog_raw(s, buf, ucred, tv);
1045 parse_syslog_priority((char**) &buf, &priority);
1046 skip_syslog_date((char**) &buf);
1047 read_identifier(&buf, &identifier, &pid);
1049 if (s->forward_to_kmsg)
1050 forward_kmsg(s, priority, identifier, buf, ucred);
1052 if (s->forward_to_console)
1053 forward_console(s, identifier, buf, ucred);
1055 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1057 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1058 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1060 if (priority & LOG_FACMASK)
1061 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1062 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1065 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1066 if (syslog_identifier)
1067 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1071 syslog_pid = strappend("SYSLOG_PID=", pid);
1073 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1076 message = strappend("MESSAGE=", buf);
1078 IOVEC_SET_STRING(iovec[n++], message);
1080 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, label, label_len, priority);
1085 free(syslog_priority);
1086 free(syslog_facility);
1087 free(syslog_identifier);
1090 static bool valid_user_field(const char *p, size_t l) {
1093 /* We kinda enforce POSIX syntax recommendations for
1094 environment variables here, but make a couple of additional
1097 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1099 /* No empty field names */
1103 /* Don't allow names longer than 64 chars */
1107 /* Variables starting with an underscore are protected */
1111 /* Don't allow digits as first character */
1112 if (p[0] >= '0' && p[0] <= '9')
1115 /* Only allow A-Z0-9 and '_' */
1116 for (a = p; a < p + l; a++)
1117 if (!((*a >= 'A' && *a <= 'Z') ||
1118 (*a >= '0' && *a <= '9') ||
1125 static void process_native_message(
1127 const void *buffer, size_t buffer_size,
1128 struct ucred *ucred,
1130 const char *label, size_t label_len) {
1132 struct iovec *iovec = NULL;
1133 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1136 int priority = LOG_INFO;
1137 char *identifier = NULL, *message = NULL;
1140 assert(buffer || n == 0);
1143 remaining = buffer_size;
1145 while (remaining > 0) {
1148 e = memchr(p, '\n', remaining);
1151 /* Trailing noise, let's ignore it, and flush what we collected */
1152 log_debug("Received message with trailing noise, ignoring.");
1157 /* Entry separator */
1158 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1160 priority = LOG_INFO;
1167 if (*p == '.' || *p == '#') {
1168 /* Ignore control commands for now, and
1170 remaining -= (e - p) + 1;
1175 /* A property follows */
1177 if (n+N_IOVEC_META_FIELDS >= m) {
1181 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1182 c = realloc(iovec, u * sizeof(struct iovec));
1184 log_error("Out of memory");
1192 q = memchr(p, '=', e - p);
1194 if (valid_user_field(p, q - p)) {
1199 /* If the field name starts with an
1200 * underscore, skip the variable,
1201 * since that indidates a trusted
1203 iovec[n].iov_base = (char*) p;
1204 iovec[n].iov_len = l;
1207 /* We need to determine the priority
1208 * of this entry for the rate limiting
1211 memcmp(p, "PRIORITY=", 9) == 0 &&
1212 p[9] >= '0' && p[9] <= '9')
1213 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1216 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1217 p[16] >= '0' && p[16] <= '9')
1218 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1221 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1222 p[16] >= '0' && p[16] <= '9' &&
1223 p[17] >= '0' && p[17] <= '9')
1224 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1227 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1230 t = strndup(p + 11, l - 11);
1235 } else if (l >= 8 &&
1236 memcmp(p, "MESSAGE=", 8) == 0) {
1239 t = strndup(p + 8, l - 8);
1247 remaining -= (e - p) + 1;
1254 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1255 log_debug("Failed to parse message, ignoring.");
1259 memcpy(&l, e + 1, sizeof(uint64_t));
1262 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1263 e[1+sizeof(uint64_t)+l] != '\n') {
1264 log_debug("Failed to parse message, ignoring.");
1268 k = malloc((e - p) + 1 + l);
1270 log_error("Out of memory");
1274 memcpy(k, p, e - p);
1276 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1278 if (valid_user_field(p, e - p)) {
1279 iovec[n].iov_base = k;
1280 iovec[n].iov_len = (e - p) + 1 + l;
1285 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1286 p = e + 1 + sizeof(uint64_t) + l + 1;
1294 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1297 if (s->forward_to_syslog)
1298 forward_syslog(s, priority, identifier, message, ucred, tv);
1300 if (s->forward_to_kmsg)
1301 forward_kmsg(s, priority, identifier, message, ucred);
1303 if (s->forward_to_console)
1304 forward_console(s, identifier, message, ucred);
1307 dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1310 for (j = 0; j < n; j++) {
1314 if (iovec[j].iov_base < buffer ||
1315 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1316 free(iovec[j].iov_base);
1324 static void process_native_file(
1327 struct ucred *ucred,
1329 const char *label, size_t label_len) {
1338 /* Data is in the passed file, since it didn't fit in a
1339 * datagram. We can't map the file here, since clients might
1340 * then truncate it and trigger a SIGBUS for us. So let's
1341 * stupidly read it */
1343 if (fstat(fd, &st) < 0) {
1344 log_error("Failed to stat passed file, ignoring: %m");
1348 if (!S_ISREG(st.st_mode)) {
1349 log_error("File passed is not regular. Ignoring.");
1353 if (st.st_size <= 0)
1356 if (st.st_size > ENTRY_SIZE_MAX) {
1357 log_error("File passed too large. Ignoring.");
1361 p = malloc(st.st_size);
1363 log_error("Out of memory");
1367 n = pread(fd, p, st.st_size, 0);
1369 log_error("Failed to read file, ignoring: %s", strerror(-n));
1371 process_native_message(s, p, n, ucred, tv, label, label_len);
1376 static int stdout_stream_log(StdoutStream *s, const char *p) {
1377 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1378 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1382 size_t label_len = 0;
1390 priority = s->priority;
1392 if (s->level_prefix)
1393 parse_syslog_priority((char**) &p, &priority);
1395 if (s->forward_to_syslog || s->server->forward_to_syslog)
1396 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1398 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1399 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1401 if (s->forward_to_console || s->server->forward_to_console)
1402 forward_console(s->server, s->identifier, p, &s->ucred);
1404 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1406 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1407 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1409 if (priority & LOG_FACMASK)
1410 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1411 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1413 if (s->identifier) {
1414 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1415 if (syslog_identifier)
1416 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1419 message = strappend("MESSAGE=", p);
1421 IOVEC_SET_STRING(iovec[n++], message);
1424 if (s->security_context) {
1425 label = (char*) s->security_context;
1426 label_len = strlen((char*) s->security_context);
1430 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, priority);
1433 free(syslog_priority);
1434 free(syslog_facility);
1435 free(syslog_identifier);
1440 static int stdout_stream_line(StdoutStream *s, char *p) {
1450 case STDOUT_STREAM_IDENTIFIER:
1452 s->identifier = NULL;
1454 s->identifier = strdup(p);
1455 if (!s->identifier) {
1456 log_error("Out of memory");
1461 s->state = STDOUT_STREAM_PRIORITY;
1464 case STDOUT_STREAM_PRIORITY:
1465 r = safe_atoi(p, &s->priority);
1466 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1467 log_warning("Failed to parse log priority line.");
1471 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1474 case STDOUT_STREAM_LEVEL_PREFIX:
1475 r = parse_boolean(p);
1477 log_warning("Failed to parse level prefix line.");
1481 s->level_prefix = !!r;
1482 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1485 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1486 r = parse_boolean(p);
1488 log_warning("Failed to parse forward to syslog line.");
1492 s->forward_to_syslog = !!r;
1493 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1496 case STDOUT_STREAM_FORWARD_TO_KMSG:
1497 r = parse_boolean(p);
1499 log_warning("Failed to parse copy to kmsg line.");
1503 s->forward_to_kmsg = !!r;
1504 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1507 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1508 r = parse_boolean(p);
1510 log_warning("Failed to parse copy to console line.");
1514 s->forward_to_console = !!r;
1515 s->state = STDOUT_STREAM_RUNNING;
1518 case STDOUT_STREAM_RUNNING:
1519 return stdout_stream_log(s, p);
1522 assert_not_reached("Unknown stream state");
1525 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1533 remaining = s->length;
1538 end = memchr(p, '\n', remaining);
1541 else if (remaining >= sizeof(s->buffer) - 1) {
1542 end = p + sizeof(s->buffer) - 1;
1549 r = stdout_stream_line(s, p);
1557 if (force_flush && remaining > 0) {
1559 r = stdout_stream_line(s, p);
1567 if (p > s->buffer) {
1568 memmove(s->buffer, p, remaining);
1569 s->length = remaining;
1575 static int stdout_stream_process(StdoutStream *s) {
1581 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1584 if (errno == EAGAIN)
1587 log_warning("Failed to read from stream: %m");
1592 r = stdout_stream_scan(s, true);
1600 r = stdout_stream_scan(s, false);
1608 static void stdout_stream_free(StdoutStream *s) {
1612 assert(s->server->n_stdout_streams > 0);
1613 s->server->n_stdout_streams --;
1614 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1619 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1621 close_nointr_nofail(s->fd);
1625 if (s->security_context)
1626 freecon(s->security_context);
1629 free(s->identifier);
1633 static int stdout_stream_new(Server *s) {
1634 StdoutStream *stream;
1637 struct epoll_event ev;
1641 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1643 if (errno == EAGAIN)
1646 log_error("Failed to accept stdout connection: %m");
1650 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1651 log_warning("Too many stdout streams, refusing connection.");
1652 close_nointr_nofail(fd);
1656 stream = new0(StdoutStream, 1);
1658 log_error("Out of memory.");
1659 close_nointr_nofail(fd);
1665 len = sizeof(stream->ucred);
1666 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1667 log_error("Failed to determine peer credentials: %m");
1673 if (getpeercon(fd, &stream->security_context) < 0)
1674 log_error("Failed to determine peer security context.");
1677 if (shutdown(fd, SHUT_WR) < 0) {
1678 log_error("Failed to shutdown writing side of socket: %m");
1684 ev.data.ptr = stream;
1685 ev.events = EPOLLIN;
1686 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1687 log_error("Failed to add stream to event loop: %m");
1693 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1694 s->n_stdout_streams ++;
1699 stdout_stream_free(stream);
1703 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1714 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1719 for (i = 1; i <= 5; i++) {
1725 k = undecchar(p[i]);
1732 for (i = 7; i <= 12; i++) {
1735 k = undecchar(p[i]);
1744 *_p += strspn(*_p, WHITESPACE);
1749 static void proc_kmsg_line(Server *s, const char *p) {
1750 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1751 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1752 int priority = LOG_KERN | LOG_INFO;
1755 char *identifier = NULL, *pid = NULL;
1763 parse_syslog_priority((char **) &p, &priority);
1765 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1768 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1769 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1770 (unsigned long long) usec) >= 0)
1771 IOVEC_SET_STRING(iovec[n++], source_time);
1774 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1776 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1777 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1779 if ((priority & LOG_FACMASK) == LOG_KERN) {
1781 if (s->forward_to_syslog)
1782 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1784 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1786 read_identifier(&p, &identifier, &pid);
1788 if (s->forward_to_syslog)
1789 forward_syslog(s, priority, identifier, p, NULL, NULL);
1792 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1793 if (syslog_identifier)
1794 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1798 syslog_pid = strappend("SYSLOG_PID=", pid);
1800 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1803 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1804 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1807 message = strappend("MESSAGE=", p);
1809 IOVEC_SET_STRING(iovec[n++], message);
1811 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, priority);
1814 free(syslog_priority);
1815 free(syslog_identifier);
1817 free(syslog_facility);
1823 static void proc_kmsg_scan(Server *s) {
1829 p = s->proc_kmsg_buffer;
1830 remaining = s->proc_kmsg_length;
1835 end = memchr(p, '\n', remaining);
1838 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1839 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1846 proc_kmsg_line(s, p);
1852 if (p > s->proc_kmsg_buffer) {
1853 memmove(s->proc_kmsg_buffer, p, remaining);
1854 s->proc_kmsg_length = remaining;
1858 static int system_journal_open(Server *s) {
1864 r = sd_id128_get_machine(&machine);
1868 sd_id128_to_string(machine, ids);
1870 if (!s->system_journal) {
1872 /* First try to create the machine path, but not the prefix */
1873 fn = strappend("/var/log/journal/", ids);
1876 (void) mkdir(fn, 0755);
1879 /* The create the system journal file */
1880 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1884 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1888 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1890 s->system_journal->metrics = s->system_metrics;
1891 s->system_journal->compress = s->compress;
1893 server_fix_perms(s, s->system_journal, 0);
1896 if (r != -ENOENT && r != -EROFS)
1897 log_warning("Failed to open system journal: %s", strerror(-r));
1903 if (!s->runtime_journal) {
1905 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1909 if (s->system_journal) {
1911 /* Try to open the runtime journal, but only
1912 * if it already exists, so that we can flush
1913 * it into the system journal */
1915 r = journal_file_open_reliably(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1920 log_warning("Failed to open runtime journal: %s", strerror(-r));
1927 /* OK, we really need the runtime journal, so create
1928 * it if necessary. */
1930 (void) mkdir_parents(fn, 0755);
1931 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1935 log_error("Failed to open runtime journal: %s", strerror(-r));
1940 if (s->runtime_journal) {
1941 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1943 s->runtime_journal->metrics = s->runtime_metrics;
1944 s->runtime_journal->compress = s->compress;
1946 server_fix_perms(s, s->runtime_journal, 0);
1953 static int server_flush_to_var(Server *s) {
1954 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1963 if (!s->runtime_journal)
1966 ts = now(CLOCK_MONOTONIC);
1967 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1970 s->var_available_timestamp = ts;
1972 system_journal_open(s);
1974 if (!s->system_journal)
1977 log_info("Flushing to /var...");
1979 r = sd_id128_get_machine(&machine);
1981 log_error("Failed to get machine id: %s", strerror(-r));
1985 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1987 log_error("Failed to read runtime journal: %s", strerror(-r));
1991 SD_JOURNAL_FOREACH(j) {
1994 f = j->current_file;
1995 assert(f && f->current_offset > 0);
1997 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1999 log_error("Can't read entry: %s", strerror(-r));
2003 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2005 log_info("Allocation limit reached.");
2007 journal_file_post_change(s->system_journal);
2011 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2015 log_error("Can't write entry: %s", strerror(-r));
2021 journal_file_post_change(s->system_journal);
2023 journal_file_close(s->runtime_journal);
2024 s->runtime_journal = NULL;
2027 sd_id128_to_string(machine, path + 17);
2028 rm_rf(path, false, true, false);
2034 static int server_read_proc_kmsg(Server *s) {
2037 assert(s->proc_kmsg_fd >= 0);
2039 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
2042 if (errno == EAGAIN || errno == EINTR)
2045 log_error("Failed to read from kernel: %m");
2049 s->proc_kmsg_length += l;
2055 static int server_flush_proc_kmsg(Server *s) {
2060 if (s->proc_kmsg_fd < 0)
2063 log_info("Flushing /proc/kmsg...");
2066 r = server_read_proc_kmsg(s);
2077 static int process_event(Server *s, struct epoll_event *ev) {
2080 if (ev->data.fd == s->signal_fd) {
2081 struct signalfd_siginfo sfsi;
2084 if (ev->events != EPOLLIN) {
2085 log_info("Got invalid event from epoll.");
2089 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2090 if (n != sizeof(sfsi)) {
2095 if (errno == EINTR || errno == EAGAIN)
2101 if (sfsi.ssi_signo == SIGUSR1) {
2102 server_flush_to_var(s);
2106 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2109 } else if (ev->data.fd == s->proc_kmsg_fd) {
2112 if (ev->events != EPOLLIN) {
2113 log_info("Got invalid event from epoll.");
2117 r = server_read_proc_kmsg(s);
2123 } else if (ev->data.fd == s->native_fd ||
2124 ev->data.fd == s->syslog_fd) {
2126 if (ev->events != EPOLLIN) {
2127 log_info("Got invalid event from epoll.");
2132 struct msghdr msghdr;
2134 struct ucred *ucred = NULL;
2135 struct timeval *tv = NULL;
2136 struct cmsghdr *cmsg;
2138 size_t label_len = 0;
2140 struct cmsghdr cmsghdr;
2141 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2142 CMSG_SPACE(sizeof(struct timeval)) +
2143 CMSG_SPACE(sizeof(int)) +
2144 CMSG_SPACE(PAGE_SIZE)]; /* selinux label */
2151 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2152 log_error("SIOCINQ failed: %m");
2156 if (s->buffer_size < (size_t) v) {
2160 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2161 b = realloc(s->buffer, l+1);
2164 log_error("Couldn't increase buffer.");
2173 iovec.iov_base = s->buffer;
2174 iovec.iov_len = s->buffer_size;
2178 msghdr.msg_iov = &iovec;
2179 msghdr.msg_iovlen = 1;
2180 msghdr.msg_control = &control;
2181 msghdr.msg_controllen = sizeof(control);
2183 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2186 if (errno == EINTR || errno == EAGAIN)
2189 log_error("recvmsg() failed: %m");
2193 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2195 if (cmsg->cmsg_level == SOL_SOCKET &&
2196 cmsg->cmsg_type == SCM_CREDENTIALS &&
2197 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2198 ucred = (struct ucred*) CMSG_DATA(cmsg);
2199 else if (cmsg->cmsg_level == SOL_SOCKET &&
2200 cmsg->cmsg_type == SCM_SECURITY) {
2201 label = (char*) CMSG_DATA(cmsg);
2202 label_len = cmsg->cmsg_len - CMSG_LEN(0);
2203 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2204 cmsg->cmsg_type == SO_TIMESTAMP &&
2205 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2206 tv = (struct timeval*) CMSG_DATA(cmsg);
2207 else if (cmsg->cmsg_level == SOL_SOCKET &&
2208 cmsg->cmsg_type == SCM_RIGHTS) {
2209 fds = (int*) CMSG_DATA(cmsg);
2210 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2214 if (ev->data.fd == s->syslog_fd) {
2217 if (n > 0 && n_fds == 0) {
2218 e = memchr(s->buffer, '\n', n);
2224 process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
2225 } else if (n_fds > 0)
2226 log_warning("Got file descriptors via syslog socket. Ignoring.");
2229 if (n > 0 && n_fds == 0)
2230 process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
2231 else if (n == 0 && n_fds == 1)
2232 process_native_file(s, fds[0], ucred, tv, label, label_len);
2234 log_warning("Got too many file descriptors via native socket. Ignoring.");
2237 close_many(fds, n_fds);
2242 } else if (ev->data.fd == s->stdout_fd) {
2244 if (ev->events != EPOLLIN) {
2245 log_info("Got invalid event from epoll.");
2249 stdout_stream_new(s);
2253 StdoutStream *stream;
2255 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2256 log_info("Got invalid event from epoll.");
2260 /* If it is none of the well-known fds, it must be an
2261 * stdout stream fd. Note that this is a bit ugly here
2262 * (since we rely that none of the well-known fds
2263 * could be interpreted as pointer), but nonetheless
2264 * safe, since the well-known fds would never get an
2265 * fd > 4096, i.e. beyond the first memory page */
2267 stream = ev->data.ptr;
2269 if (stdout_stream_process(stream) <= 0)
2270 stdout_stream_free(stream);
2275 log_error("Unknown event.");
2279 static int open_syslog_socket(Server *s) {
2280 union sockaddr_union sa;
2282 struct epoll_event ev;
2286 if (s->syslog_fd < 0) {
2288 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2289 if (s->syslog_fd < 0) {
2290 log_error("socket() failed: %m");
2295 sa.un.sun_family = AF_UNIX;
2296 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2298 unlink(sa.un.sun_path);
2300 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2302 log_error("bind() failed: %m");
2306 chmod(sa.un.sun_path, 0666);
2308 fd_nonblock(s->syslog_fd, 1);
2311 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2313 log_error("SO_PASSCRED failed: %m");
2319 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2321 log_warning("SO_PASSSEC failed: %m");
2325 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2327 log_error("SO_TIMESTAMP failed: %m");
2332 ev.events = EPOLLIN;
2333 ev.data.fd = s->syslog_fd;
2334 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2335 log_error("Failed to add syslog server fd to epoll object: %m");
2342 static int open_native_socket(Server*s) {
2343 union sockaddr_union sa;
2345 struct epoll_event ev;
2349 if (s->native_fd < 0) {
2351 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2352 if (s->native_fd < 0) {
2353 log_error("socket() failed: %m");
2358 sa.un.sun_family = AF_UNIX;
2359 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2361 unlink(sa.un.sun_path);
2363 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2365 log_error("bind() failed: %m");
2369 chmod(sa.un.sun_path, 0666);
2371 fd_nonblock(s->native_fd, 1);
2374 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2376 log_error("SO_PASSCRED failed: %m");
2382 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2384 log_warning("SO_PASSSEC failed: %m");
2388 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2390 log_error("SO_TIMESTAMP failed: %m");
2395 ev.events = EPOLLIN;
2396 ev.data.fd = s->native_fd;
2397 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2398 log_error("Failed to add native server fd to epoll object: %m");
2405 static int open_stdout_socket(Server *s) {
2406 union sockaddr_union sa;
2408 struct epoll_event ev;
2412 if (s->stdout_fd < 0) {
2414 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2415 if (s->stdout_fd < 0) {
2416 log_error("socket() failed: %m");
2421 sa.un.sun_family = AF_UNIX;
2422 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2424 unlink(sa.un.sun_path);
2426 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2428 log_error("bind() failed: %m");
2432 chmod(sa.un.sun_path, 0666);
2434 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2435 log_error("liste() failed: %m");
2439 fd_nonblock(s->stdout_fd, 1);
2442 ev.events = EPOLLIN;
2443 ev.data.fd = s->stdout_fd;
2444 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2445 log_error("Failed to add stdout server fd to epoll object: %m");
2452 static int open_proc_kmsg(Server *s) {
2453 struct epoll_event ev;
2457 if (!s->import_proc_kmsg)
2461 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2462 if (s->proc_kmsg_fd < 0) {
2463 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2468 ev.events = EPOLLIN;
2469 ev.data.fd = s->proc_kmsg_fd;
2470 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2471 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2478 static int open_signalfd(Server *s) {
2480 struct epoll_event ev;
2484 assert_se(sigemptyset(&mask) == 0);
2485 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2486 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2488 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2489 if (s->signal_fd < 0) {
2490 log_error("signalfd(): %m");
2495 ev.events = EPOLLIN;
2496 ev.data.fd = s->signal_fd;
2498 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2499 log_error("epoll_ctl(): %m");
2506 static int server_parse_proc_cmdline(Server *s) {
2507 char *line, *w, *state;
2511 if (detect_container(NULL) > 0)
2514 r = read_one_line_file("/proc/cmdline", &line);
2516 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2520 FOREACH_WORD_QUOTED(w, l, line, state) {
2523 word = strndup(w, l);
2529 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2530 r = parse_boolean(word + 35);
2532 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2534 s->forward_to_syslog = r;
2535 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2536 r = parse_boolean(word + 33);
2538 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2540 s->forward_to_kmsg = r;
2541 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2542 r = parse_boolean(word + 36);
2544 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2546 s->forward_to_console = r;
2559 static int server_parse_config_file(Server *s) {
2566 fn = "/etc/systemd/systemd-journald.conf";
2567 f = fopen(fn, "re");
2569 if (errno == ENOENT)
2572 log_warning("Failed to open configuration file %s: %m", fn);
2576 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2578 log_warning("Failed to parse configuration file: %s", strerror(-r));
2585 static int server_init(Server *s) {
2591 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2594 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2595 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2597 s->forward_to_syslog = true;
2598 s->import_proc_kmsg = true;
2600 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2601 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2603 server_parse_config_file(s);
2604 server_parse_proc_cmdline(s);
2606 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2607 if (!s->user_journals) {
2608 log_error("Out of memory.");
2612 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2613 if (s->epoll_fd < 0) {
2614 log_error("Failed to create epoll object: %m");
2618 n = sd_listen_fds(true);
2620 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2624 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2626 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2628 if (s->native_fd >= 0) {
2629 log_error("Too many native sockets passed.");
2635 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2637 if (s->stdout_fd >= 0) {
2638 log_error("Too many stdout sockets passed.");
2644 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2646 if (s->syslog_fd >= 0) {
2647 log_error("Too many /dev/log sockets passed.");
2654 log_error("Unknown socket passed.");
2659 r = open_syslog_socket(s);
2663 r = open_native_socket(s);
2667 r = open_stdout_socket(s);
2671 r = open_proc_kmsg(s);
2675 r = open_signalfd(s);
2679 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2683 r = system_journal_open(s);
2690 static void server_done(Server *s) {
2694 while (s->stdout_streams)
2695 stdout_stream_free(s->stdout_streams);
2697 if (s->system_journal)
2698 journal_file_close(s->system_journal);
2700 if (s->runtime_journal)
2701 journal_file_close(s->runtime_journal);
2703 while ((f = hashmap_steal_first(s->user_journals)))
2704 journal_file_close(f);
2706 hashmap_free(s->user_journals);
2708 if (s->epoll_fd >= 0)
2709 close_nointr_nofail(s->epoll_fd);
2711 if (s->signal_fd >= 0)
2712 close_nointr_nofail(s->signal_fd);
2714 if (s->syslog_fd >= 0)
2715 close_nointr_nofail(s->syslog_fd);
2717 if (s->native_fd >= 0)
2718 close_nointr_nofail(s->native_fd);
2720 if (s->stdout_fd >= 0)
2721 close_nointr_nofail(s->stdout_fd);
2723 if (s->proc_kmsg_fd >= 0)
2724 close_nointr_nofail(s->proc_kmsg_fd);
2727 journal_rate_limit_free(s->rate_limit);
2732 int main(int argc, char *argv[]) {
2736 /* if (getppid() != 1) { */
2737 /* log_error("This program should be invoked by init only."); */
2738 /* return EXIT_FAILURE; */
2742 log_error("This program does not take arguments.");
2743 return EXIT_FAILURE;
2746 log_set_target(LOG_TARGET_CONSOLE);
2747 log_parse_environment();
2752 r = server_init(&server);
2756 server_vacuum(&server);
2757 server_flush_to_var(&server);
2758 server_flush_proc_kmsg(&server);
2760 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2761 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2765 "STATUS=Processing requests...");
2768 struct epoll_event event;
2770 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2776 log_error("epoll_wait() failed: %m");
2782 r = process_event(&server, &event);
2789 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2790 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2794 "STATUS=Shutting down...");
2796 server_done(&server);
2798 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;