1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2011 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/epoll.h>
23 #include <sys/socket.h>
25 #include <sys/signalfd.h>
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <sys/statvfs.h>
33 #include <systemd/sd-journal.h>
34 #include <systemd/sd-login.h>
35 #include <systemd/sd-messages.h>
36 #include <systemd/sd-daemon.h>
39 #include "journal-file.h"
40 #include "socket-util.h"
41 #include "cgroup-util.h"
43 #include "journal-rate-limit.h"
44 #include "journal-internal.h"
45 #include "conf-parser.h"
51 #include <acl/libacl.h>
56 #include <selinux/selinux.h>
59 #define USER_JOURNALS_MAX 1024
60 #define STDOUT_STREAMS_MAX 4096
62 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
63 #define DEFAULT_RATE_LIMIT_BURST 200
65 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
67 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
69 #define SYSLOG_TIMEOUT_USEC (250*USEC_PER_MSEC)
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;
96 bool forward_to_syslog:1;
97 bool forward_to_kmsg:1;
98 bool forward_to_console:1;
100 char buffer[LINE_MAX+1];
103 LIST_FIELDS(StdoutStream, stdout_stream);
106 static int server_flush_to_var(Server *s);
108 static uint64_t available_space(Server *s) {
113 uint64_t sum = 0, avail = 0, ss_avail = 0;
119 ts = now(CLOCK_MONOTONIC);
121 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
122 return s->cached_available_space;
124 r = sd_id128_get_machine(&machine);
128 if (s->system_journal) {
129 f = "/var/log/journal/";
130 m = &s->system_metrics;
132 f = "/run/log/journal/";
133 m = &s->runtime_metrics;
138 p = strappend(f, sd_id128_to_string(machine, ids));
148 if (fstatvfs(dirfd(d), &ss) < 0)
153 struct dirent buf, *de;
156 k = readdir_r(d, &buf, &de);
165 if (!dirent_is_file_with_suffix(de, ".journal"))
168 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
171 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
174 avail = sum >= m->max_use ? 0 : m->max_use - sum;
176 ss_avail = ss.f_bsize * ss.f_bavail;
178 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
180 if (ss_avail < avail)
183 s->cached_available_space = avail;
184 s->cached_available_space_timestamp = ts;
192 static void server_read_file_gid(Server *s) {
193 const char *adm = "adm";
198 if (s->file_gid_valid)
201 r = get_group_creds(&adm, &s->file_gid);
203 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
205 /* if we couldn't read the gid, then it will be 0, but that's
206 * fine and we shouldn't try to resolve the group again, so
207 * let's just pretend it worked right-away. */
208 s->file_gid_valid = true;
211 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
216 acl_permset_t permset;
221 server_read_file_gid(s);
223 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
225 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
231 acl = acl_get_fd(f->fd);
233 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
237 r = acl_find_uid(acl, uid, &entry);
240 if (acl_create_entry(&acl, &entry) < 0 ||
241 acl_set_tag_type(entry, ACL_USER) < 0 ||
242 acl_set_qualifier(entry, &uid) < 0) {
243 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
248 if (acl_get_permset(entry, &permset) < 0 ||
249 acl_add_perm(permset, ACL_READ) < 0 ||
250 acl_calc_mask(&acl) < 0) {
251 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
255 if (acl_set_fd(f->fd, acl) < 0)
256 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
263 static JournalFile* find_journal(Server *s, uid_t uid) {
272 /* We split up user logs only on /var, not on /run. If the
273 * runtime file is open, we write to it exclusively, in order
274 * to guarantee proper order as soon as we flush /run to
275 * /var and close the runtime file. */
277 if (s->runtime_journal)
278 return s->runtime_journal;
281 return s->system_journal;
283 r = sd_id128_get_machine(&machine);
285 return s->system_journal;
287 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
291 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
292 return s->system_journal;
294 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
295 /* Too many open? Then let's close one */
296 f = hashmap_steal_first(s->user_journals);
298 journal_file_close(f);
301 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
305 return s->system_journal;
307 server_fix_perms(s, f, uid);
308 f->metrics = s->system_metrics;
309 f->compress = s->compress;
311 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
313 journal_file_close(f);
314 return s->system_journal;
320 static void server_rotate(Server *s) {
326 log_info("Rotating...");
328 if (s->runtime_journal) {
329 r = journal_file_rotate(&s->runtime_journal);
331 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
334 if (s->system_journal) {
335 r = journal_file_rotate(&s->system_journal);
337 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
340 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
341 r = journal_file_rotate(&f);
343 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
345 hashmap_replace(s->user_journals, k, f);
349 static void server_vacuum(Server *s) {
355 log_info("Vacuuming...");
357 r = sd_id128_get_machine(&machine);
359 log_error("Failed to get machine ID: %s", strerror(-r));
363 sd_id128_to_string(machine, ids);
365 if (s->system_journal) {
366 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
367 log_error("Out of memory.");
371 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
372 if (r < 0 && r != -ENOENT)
373 log_error("Failed to vacuum %s: %s", p, strerror(-r));
378 if (s->runtime_journal) {
379 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
380 log_error("Out of memory.");
384 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
385 if (r < 0 && r != -ENOENT)
386 log_error("Failed to vacuum %s: %s", p, strerror(-r));
390 s->cached_available_space_timestamp = 0;
393 static char *shortened_cgroup_path(pid_t pid) {
395 char *process_path, *init_path, *path;
399 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
403 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
409 if (endswith(init_path, "/system"))
410 init_path[strlen(init_path) - 7] = 0;
411 else if (streq(init_path, "/"))
414 if (startswith(process_path, init_path)) {
417 p = strdup(process_path + strlen(init_path));
435 static void dispatch_message_real(Server *s,
436 struct iovec *iovec, unsigned n, unsigned m,
438 struct timeval *tv) {
440 char *pid = NULL, *uid = NULL, *gid = NULL,
441 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
442 *comm = NULL, *cmdline = NULL, *hostname = NULL,
443 *audit_session = NULL, *audit_loginuid = NULL,
444 *exe = NULL, *cgroup = NULL, *session = NULL,
445 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
451 uid_t loginuid = 0, realuid = 0;
453 bool vacuumed = false;
458 assert(n + N_IOVEC_META_FIELDS <= m);
464 security_context_t con;
467 realuid = ucred->uid;
469 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
470 IOVEC_SET_STRING(iovec[n++], pid);
472 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
473 IOVEC_SET_STRING(iovec[n++], uid);
475 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
476 IOVEC_SET_STRING(iovec[n++], gid);
478 r = get_process_comm(ucred->pid, &t);
480 comm = strappend("_COMM=", t);
484 IOVEC_SET_STRING(iovec[n++], comm);
487 r = get_process_exe(ucred->pid, &t);
489 exe = strappend("_EXE=", t);
493 IOVEC_SET_STRING(iovec[n++], exe);
496 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
498 cmdline = strappend("_CMDLINE=", t);
502 IOVEC_SET_STRING(iovec[n++], cmdline);
505 r = audit_session_from_pid(ucred->pid, &audit);
507 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
508 IOVEC_SET_STRING(iovec[n++], audit_session);
510 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
512 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
513 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
515 t = shortened_cgroup_path(ucred->pid);
517 cgroup = strappend("_SYSTEMD_CGROUP=", t);
521 IOVEC_SET_STRING(iovec[n++], cgroup);
524 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
525 session = strappend("_SYSTEMD_SESSION=", t);
529 IOVEC_SET_STRING(iovec[n++], session);
532 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
533 unit = strappend("_SYSTEMD_UNIT=", t);
537 IOVEC_SET_STRING(iovec[n++], unit);
540 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
541 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
542 IOVEC_SET_STRING(iovec[n++], owner_uid);
545 if (getpidcon(ucred->pid, &con) >= 0) {
546 selinux_context = strappend("_SELINUX_CONTEXT=", con);
548 IOVEC_SET_STRING(iovec[n++], selinux_context);
556 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
557 (unsigned long long) timeval_load(tv)) >= 0)
558 IOVEC_SET_STRING(iovec[n++], source_time);
561 /* Note that strictly speaking storing the boot id here is
562 * redundant since the entry includes this in-line
563 * anyway. However, we need this indexed, too. */
564 r = sd_id128_get_boot(&id);
566 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
567 IOVEC_SET_STRING(iovec[n++], boot_id);
569 r = sd_id128_get_machine(&id);
571 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
572 IOVEC_SET_STRING(iovec[n++], machine_id);
574 t = gethostname_malloc();
576 hostname = strappend("_HOSTNAME=", t);
579 IOVEC_SET_STRING(iovec[n++], hostname);
584 server_flush_to_var(s);
587 f = find_journal(s, realuid == 0 ? 0 : loginuid);
589 log_warning("Dropping message, as we can't find a place to store the data.");
591 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
593 if (r == -E2BIG && !vacuumed) {
594 log_info("Allocation limit reached.");
600 log_info("Retrying write.");
605 log_error("Failed to write entry, ignoring: %s", strerror(-r));
619 free(audit_loginuid);
624 free(selinux_context);
627 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
628 char mid[11 + 32 + 1];
629 char buffer[16 + LINE_MAX + 1];
630 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
638 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
639 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
641 memcpy(buffer, "MESSAGE=", 8);
642 va_start(ap, format);
643 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
645 char_array_0(buffer);
646 IOVEC_SET_STRING(iovec[n++], buffer);
648 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
650 IOVEC_SET_STRING(iovec[n++], mid);
653 ucred.pid = getpid();
654 ucred.uid = getuid();
655 ucred.gid = getgid();
657 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL);
660 static void dispatch_message(Server *s,
661 struct iovec *iovec, unsigned n, unsigned m,
666 char *path = NULL, *c;
669 assert(iovec || n == 0);
677 path = shortened_cgroup_path(ucred->pid);
681 /* example: /user/lennart/3/foobar
682 * /system/dbus.service/foobar
684 * So let's cut of everything past the third /, since that is
685 * wher user directories start */
687 c = strchr(path, '/');
689 c = strchr(c+1, '/');
691 c = strchr(c+1, '/');
697 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
704 /* Write a suppression message if we suppressed something */
706 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
711 dispatch_message_real(s, iovec, n, m, ucred, tv);
714 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
715 struct msghdr msghdr;
716 struct cmsghdr *cmsg;
718 struct cmsghdr cmsghdr;
719 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
721 union sockaddr_union sa;
728 msghdr.msg_iov = (struct iovec*) iovec;
729 msghdr.msg_iovlen = n_iovec;
732 sa.un.sun_family = AF_UNIX;
733 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
734 msghdr.msg_name = &sa;
735 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
739 msghdr.msg_control = &control;
740 msghdr.msg_controllen = sizeof(control);
742 cmsg = CMSG_FIRSTHDR(&msghdr);
743 cmsg->cmsg_level = SOL_SOCKET;
744 cmsg->cmsg_type = SCM_CREDENTIALS;
745 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
746 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
747 msghdr.msg_controllen = cmsg->cmsg_len;
750 /* Forward the syslog message we received via /dev/log to
751 * /run/systemd/syslog. Unfortunately we currently can't set
752 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
754 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
757 /* The socket is full? I guess the syslog implementation is
758 * too slow, and we shouldn't wait for that... */
762 if (ucred && errno == ESRCH) {
765 /* Hmm, presumably the sender process vanished
766 * by now, so let's fix it as good as we
771 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
773 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
780 log_debug("Failed to forward syslog message: %m");
783 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
789 IOVEC_SET_STRING(iovec, buffer);
790 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
793 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
794 struct iovec iovec[5];
795 char header_priority[6], header_time[64], header_pid[16];
799 char *ident_buf = NULL;
802 assert(priority >= 0);
803 assert(priority <= 999);
806 /* First: priority field */
807 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
808 char_array_0(header_priority);
809 IOVEC_SET_STRING(iovec[n++], header_priority);
811 /* Second: timestamp */
812 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
816 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
818 IOVEC_SET_STRING(iovec[n++], header_time);
820 /* Third: identifier and PID */
823 get_process_comm(ucred->pid, &ident_buf);
824 identifier = ident_buf;
827 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
828 char_array_0(header_pid);
831 IOVEC_SET_STRING(iovec[n++], identifier);
833 IOVEC_SET_STRING(iovec[n++], header_pid);
834 } else if (identifier) {
835 IOVEC_SET_STRING(iovec[n++], identifier);
836 IOVEC_SET_STRING(iovec[n++], ": ");
839 /* Fourth: message */
840 IOVEC_SET_STRING(iovec[n++], message);
842 forward_syslog_iovec(s, iovec, n, ucred, tv);
847 static int fixup_priority(int priority) {
849 if ((priority & LOG_FACMASK) == 0)
850 return (priority & LOG_PRIMASK) | LOG_USER;
855 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
856 struct iovec iovec[5];
857 char header_priority[6], header_pid[16];
859 char *ident_buf = NULL;
863 assert(priority >= 0);
864 assert(priority <= 999);
867 /* Never allow messages with kernel facility to be written to
868 * kmsg, regardless where the data comes from. */
869 priority = fixup_priority(priority);
871 /* First: priority field */
872 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
873 char_array_0(header_priority);
874 IOVEC_SET_STRING(iovec[n++], header_priority);
876 /* Second: identifier and PID */
879 get_process_comm(ucred->pid, &ident_buf);
880 identifier = ident_buf;
883 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
884 char_array_0(header_pid);
887 IOVEC_SET_STRING(iovec[n++], identifier);
889 IOVEC_SET_STRING(iovec[n++], header_pid);
890 } else if (identifier) {
891 IOVEC_SET_STRING(iovec[n++], identifier);
892 IOVEC_SET_STRING(iovec[n++], ": ");
895 /* Fourth: message */
896 IOVEC_SET_STRING(iovec[n++], message);
897 IOVEC_SET_STRING(iovec[n++], "\n");
899 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
901 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
905 if (writev(fd, iovec, n) < 0)
906 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
908 close_nointr_nofail(fd);
914 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
915 struct iovec iovec[4];
918 char *ident_buf = NULL;
923 /* First: identifier and PID */
926 get_process_comm(ucred->pid, &ident_buf);
927 identifier = ident_buf;
930 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
931 char_array_0(header_pid);
934 IOVEC_SET_STRING(iovec[n++], identifier);
936 IOVEC_SET_STRING(iovec[n++], header_pid);
937 } else if (identifier) {
938 IOVEC_SET_STRING(iovec[n++], identifier);
939 IOVEC_SET_STRING(iovec[n++], ": ");
943 IOVEC_SET_STRING(iovec[n++], message);
944 IOVEC_SET_STRING(iovec[n++], "\n");
946 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
948 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
952 if (writev(fd, iovec, n) < 0)
953 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
955 close_nointr_nofail(fd);
961 static void read_identifier(const char **buf, char **identifier, char **pid) {
972 p += strspn(p, WHITESPACE);
973 l = strcspn(p, WHITESPACE);
988 t = strndup(p+k+1, l-k-2);
1008 *buf += strspn(*buf, WHITESPACE);
1011 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
1012 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1013 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1015 int priority = LOG_USER | LOG_INFO;
1016 char *identifier = NULL, *pid = NULL;
1021 if (s->forward_to_syslog)
1022 forward_syslog_raw(s, buf, ucred, tv);
1024 parse_syslog_priority((char**) &buf, &priority);
1025 skip_syslog_date((char**) &buf);
1026 read_identifier(&buf, &identifier, &pid);
1028 if (s->forward_to_kmsg)
1029 forward_kmsg(s, priority, identifier, buf, ucred);
1031 if (s->forward_to_console)
1032 forward_console(s, identifier, buf, ucred);
1034 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1036 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1037 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1039 if (priority & LOG_FACMASK)
1040 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1041 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1044 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1045 if (syslog_identifier)
1046 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1050 syslog_pid = strappend("SYSLOG_PID=", pid);
1052 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1055 message = strappend("MESSAGE=", buf);
1057 IOVEC_SET_STRING(iovec[n++], message);
1059 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, priority);
1064 free(syslog_priority);
1065 free(syslog_facility);
1066 free(syslog_identifier);
1069 static bool valid_user_field(const char *p, size_t l) {
1072 /* We kinda enforce POSIX syntax recommendations for
1073 environment variables here, but make a couple of additional
1076 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1078 /* No empty field names */
1082 /* Don't allow names longer than 64 chars */
1086 /* Variables starting with an underscore are protected */
1090 /* Don't allow digits as first character */
1091 if (p[0] >= '0' && p[0] <= '9')
1094 /* Only allow A-Z0-9 and '_' */
1095 for (a = p; a < p + l; a++)
1096 if (!((*a >= 'A' && *a <= 'Z') ||
1097 (*a >= '0' && *a <= '9') ||
1104 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
1105 struct iovec *iovec = NULL;
1106 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1109 int priority = LOG_INFO;
1110 char *identifier = NULL, *message = NULL;
1113 assert(buffer || n == 0);
1116 remaining = buffer_size;
1118 while (remaining > 0) {
1121 e = memchr(p, '\n', remaining);
1124 /* Trailing noise, let's ignore it, and flush what we collected */
1125 log_debug("Received message with trailing noise, ignoring.");
1130 /* Entry separator */
1131 dispatch_message(s, iovec, n, m, ucred, tv, priority);
1133 priority = LOG_INFO;
1140 if (*p == '.' || *p == '#') {
1141 /* Ignore control commands for now, and
1143 remaining -= (e - p) + 1;
1148 /* A property follows */
1150 if (n+N_IOVEC_META_FIELDS >= m) {
1154 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1155 c = realloc(iovec, u * sizeof(struct iovec));
1157 log_error("Out of memory");
1165 q = memchr(p, '=', e - p);
1167 if (valid_user_field(p, q - p)) {
1172 /* If the field name starts with an
1173 * underscore, skip the variable,
1174 * since that indidates a trusted
1176 iovec[n].iov_base = (char*) p;
1177 iovec[n].iov_len = l;
1180 /* We need to determine the priority
1181 * of this entry for the rate limiting
1184 memcmp(p, "PRIORITY=", 9) == 0 &&
1185 p[9] >= '0' && p[9] <= '9')
1186 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1189 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1190 p[16] >= '0' && p[16] <= '9')
1191 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1194 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1195 p[16] >= '0' && p[16] <= '9' &&
1196 p[17] >= '0' && p[17] <= '9')
1197 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1200 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1203 t = strndup(p + 11, l - 11);
1208 } else if (l >= 8 &&
1209 memcmp(p, "MESSAGE=", 8) == 0) {
1212 t = strndup(p + 8, l - 8);
1220 remaining -= (e - p) + 1;
1227 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1228 log_debug("Failed to parse message, ignoring.");
1232 memcpy(&l, e + 1, sizeof(uint64_t));
1235 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1236 e[1+sizeof(uint64_t)+l] != '\n') {
1237 log_debug("Failed to parse message, ignoring.");
1241 k = malloc((e - p) + 1 + l);
1243 log_error("Out of memory");
1247 memcpy(k, p, e - p);
1249 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1251 if (valid_user_field(p, e - p)) {
1252 iovec[n].iov_base = k;
1253 iovec[n].iov_len = (e - p) + 1 + l;
1258 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1259 p = e + 1 + sizeof(uint64_t) + l + 1;
1267 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1270 if (s->forward_to_syslog)
1271 forward_syslog(s, priority, identifier, message, ucred, tv);
1273 if (s->forward_to_kmsg)
1274 forward_kmsg(s, priority, identifier, message, ucred);
1276 if (s->forward_to_console)
1277 forward_console(s, identifier, message, ucred);
1280 dispatch_message(s, iovec, n, m, ucred, tv, priority);
1283 for (j = 0; j < n; j++) {
1287 if (iovec[j].iov_base < buffer ||
1288 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1289 free(iovec[j].iov_base);
1296 static void process_native_file(Server *s, int fd, struct ucred *ucred, struct timeval *tv) {
1304 /* Data is in the passed file, since it didn't fit in a
1305 * datagram. We can't map the file here, since clients might
1306 * then truncate it and trigger a SIGBUS for us. So let's
1307 * stupidly read it */
1309 if (fstat(fd, &st) < 0) {
1310 log_error("Failed to stat passed file, ignoring: %m");
1314 if (!S_ISREG(st.st_mode)) {
1315 log_error("File passed is not regular. Ignoring.");
1319 if (st.st_size <= 0)
1322 if (st.st_size > ENTRY_SIZE_MAX) {
1323 log_error("File passed too large. Ignoring.");
1327 p = malloc(st.st_size);
1329 log_error("Out of memory");
1333 n = pread(fd, p, st.st_size, 0);
1335 log_error("Failed to read file, ignoring: %s", strerror(-n));
1337 process_native_message(s, p, n, ucred, tv);
1342 static int stdout_stream_log(StdoutStream *s, const char *p) {
1343 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1344 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1354 priority = s->priority;
1356 if (s->level_prefix)
1357 parse_syslog_priority((char**) &p, &priority);
1359 if (s->forward_to_syslog || s->server->forward_to_syslog)
1360 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1362 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1363 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1365 if (s->forward_to_console || s->server->forward_to_console)
1366 forward_console(s->server, s->identifier, p, &s->ucred);
1368 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1370 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1371 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1373 if (priority & LOG_FACMASK)
1374 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1375 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1377 if (s->identifier) {
1378 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1379 if (syslog_identifier)
1380 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1383 message = strappend("MESSAGE=", p);
1385 IOVEC_SET_STRING(iovec[n++], message);
1387 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, priority);
1390 free(syslog_priority);
1391 free(syslog_facility);
1392 free(syslog_identifier);
1397 static int stdout_stream_line(StdoutStream *s, char *p) {
1407 case STDOUT_STREAM_IDENTIFIER:
1408 s->identifier = strdup(p);
1409 if (!s->identifier) {
1410 log_error("Out of memory");
1414 s->state = STDOUT_STREAM_PRIORITY;
1417 case STDOUT_STREAM_PRIORITY:
1418 r = safe_atoi(p, &s->priority);
1419 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1420 log_warning("Failed to parse log priority line.");
1424 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1427 case STDOUT_STREAM_LEVEL_PREFIX:
1428 r = parse_boolean(p);
1430 log_warning("Failed to parse level prefix line.");
1434 s->level_prefix = !!r;
1435 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1438 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1439 r = parse_boolean(p);
1441 log_warning("Failed to parse forward to syslog line.");
1445 s->forward_to_syslog = !!r;
1446 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1449 case STDOUT_STREAM_FORWARD_TO_KMSG:
1450 r = parse_boolean(p);
1452 log_warning("Failed to parse copy to kmsg line.");
1456 s->forward_to_kmsg = !!r;
1457 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1460 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1461 r = parse_boolean(p);
1463 log_warning("Failed to parse copy to console line.");
1467 s->forward_to_console = !!r;
1468 s->state = STDOUT_STREAM_RUNNING;
1471 case STDOUT_STREAM_RUNNING:
1472 return stdout_stream_log(s, p);
1475 assert_not_reached("Unknown stream state");
1478 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1486 remaining = s->length;
1491 end = memchr(p, '\n', remaining);
1494 else if (remaining >= sizeof(s->buffer) - 1) {
1495 end = p + sizeof(s->buffer) - 1;
1502 r = stdout_stream_line(s, p);
1510 if (force_flush && remaining > 0) {
1512 r = stdout_stream_line(s, p);
1520 if (p > s->buffer) {
1521 memmove(s->buffer, p, remaining);
1522 s->length = remaining;
1528 static int stdout_stream_process(StdoutStream *s) {
1534 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1537 if (errno == EAGAIN)
1540 log_warning("Failed to read from stream: %m");
1545 r = stdout_stream_scan(s, true);
1553 r = stdout_stream_scan(s, false);
1561 static void stdout_stream_free(StdoutStream *s) {
1565 assert(s->server->n_stdout_streams > 0);
1566 s->server->n_stdout_streams --;
1567 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1572 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1574 close_nointr_nofail(s->fd);
1577 free(s->identifier);
1581 static int stdout_stream_new(Server *s) {
1582 StdoutStream *stream;
1585 struct epoll_event ev;
1589 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1591 if (errno == EAGAIN)
1594 log_error("Failed to accept stdout connection: %m");
1598 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1599 log_warning("Too many stdout streams, refusing connection.");
1600 close_nointr_nofail(fd);
1604 stream = new0(StdoutStream, 1);
1606 log_error("Out of memory.");
1607 close_nointr_nofail(fd);
1613 len = sizeof(stream->ucred);
1614 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1615 log_error("Failed to determine peer credentials: %m");
1620 if (shutdown(fd, SHUT_WR) < 0) {
1621 log_error("Failed to shutdown writing side of socket: %m");
1627 ev.data.ptr = stream;
1628 ev.events = EPOLLIN;
1629 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1630 log_error("Failed to add stream to event loop: %m");
1636 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1637 s->n_stdout_streams ++;
1642 stdout_stream_free(stream);
1646 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1657 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1662 for (i = 1; i <= 5; i++) {
1668 k = undecchar(p[i]);
1675 for (i = 7; i <= 12; i++) {
1678 k = undecchar(p[i]);
1687 *_p += strspn(*_p, WHITESPACE);
1692 static void proc_kmsg_line(Server *s, const char *p) {
1693 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1694 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1695 int priority = LOG_KERN | LOG_INFO;
1698 char *identifier = NULL, *pid = NULL;
1706 parse_syslog_priority((char **) &p, &priority);
1708 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1711 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1712 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1713 (unsigned long long) usec) >= 0)
1714 IOVEC_SET_STRING(iovec[n++], source_time);
1717 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1719 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1720 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1722 if ((priority & LOG_FACMASK) == LOG_KERN) {
1724 if (s->forward_to_syslog)
1725 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1727 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1729 read_identifier(&p, &identifier, &pid);
1731 if (s->forward_to_syslog)
1732 forward_syslog(s, priority, identifier, p, NULL, NULL);
1735 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1736 if (syslog_identifier)
1737 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1741 syslog_pid = strappend("SYSLOG_PID=", pid);
1743 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1746 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1747 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1750 message = strappend("MESSAGE=", p);
1752 IOVEC_SET_STRING(iovec[n++], message);
1754 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, priority);
1757 free(syslog_priority);
1758 free(syslog_identifier);
1760 free(syslog_facility);
1766 static void proc_kmsg_scan(Server *s) {
1772 p = s->proc_kmsg_buffer;
1773 remaining = s->proc_kmsg_length;
1778 end = memchr(p, '\n', remaining);
1781 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1782 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1789 proc_kmsg_line(s, p);
1795 if (p > s->proc_kmsg_buffer) {
1796 memmove(s->proc_kmsg_buffer, p, remaining);
1797 s->proc_kmsg_length = remaining;
1801 static int system_journal_open(Server *s) {
1807 r = sd_id128_get_machine(&machine);
1811 sd_id128_to_string(machine, ids);
1813 if (!s->system_journal) {
1815 /* First try to create the machine path, but not the prefix */
1816 fn = strappend("/var/log/journal/", ids);
1819 (void) mkdir(fn, 0755);
1822 /* The create the system journal file */
1823 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1827 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1831 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1833 s->system_journal->metrics = s->system_metrics;
1834 s->system_journal->compress = s->compress;
1836 server_fix_perms(s, s->system_journal, 0);
1839 if (r != -ENOENT && r != -EROFS)
1840 log_warning("Failed to open system journal: %s", strerror(-r));
1846 if (!s->runtime_journal) {
1848 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1852 if (s->system_journal) {
1854 /* Try to open the runtime journal, but only
1855 * if it already exists, so that we can flush
1856 * it into the system journal */
1858 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1863 log_warning("Failed to open runtime journal: %s", strerror(-r));
1870 /* OK, we really need the runtime journal, so create
1871 * it if necessary. */
1873 (void) mkdir_parents(fn, 0755);
1874 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1878 log_error("Failed to open runtime journal: %s", strerror(-r));
1883 if (s->runtime_journal) {
1884 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1886 s->runtime_journal->metrics = s->runtime_metrics;
1887 s->runtime_journal->compress = s->compress;
1889 server_fix_perms(s, s->runtime_journal, 0);
1896 static int server_flush_to_var(Server *s) {
1897 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1906 if (!s->runtime_journal)
1909 ts = now(CLOCK_MONOTONIC);
1910 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1913 s->var_available_timestamp = ts;
1915 system_journal_open(s);
1917 if (!s->system_journal)
1920 log_info("Flushing to /var...");
1922 r = sd_id128_get_machine(&machine);
1924 log_error("Failed to get machine id: %s", strerror(-r));
1928 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1930 log_error("Failed to read runtime journal: %s", strerror(-r));
1934 SD_JOURNAL_FOREACH(j) {
1937 f = j->current_file;
1938 assert(f && f->current_offset > 0);
1940 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1942 log_error("Can't read entry: %s", strerror(-r));
1946 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1948 log_info("Allocation limit reached.");
1950 journal_file_post_change(s->system_journal);
1954 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1958 log_error("Can't write entry: %s", strerror(-r));
1964 journal_file_post_change(s->system_journal);
1966 journal_file_close(s->runtime_journal);
1967 s->runtime_journal = NULL;
1970 sd_id128_to_string(machine, path + 17);
1971 rm_rf(path, false, true, false);
1977 static int server_read_proc_kmsg(Server *s) {
1980 assert(s->proc_kmsg_fd >= 0);
1982 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
1985 if (errno == EAGAIN || errno == EINTR)
1988 log_error("Failed to read from kernel: %m");
1992 s->proc_kmsg_length += l;
1998 static int server_flush_proc_kmsg(Server *s) {
2003 if (s->proc_kmsg_fd < 0)
2006 log_info("Flushing /proc/kmsg...");
2009 r = server_read_proc_kmsg(s);
2020 static int process_event(Server *s, struct epoll_event *ev) {
2023 if (ev->data.fd == s->signal_fd) {
2024 struct signalfd_siginfo sfsi;
2027 if (ev->events != EPOLLIN) {
2028 log_info("Got invalid event from epoll.");
2032 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2033 if (n != sizeof(sfsi)) {
2038 if (errno == EINTR || errno == EAGAIN)
2044 if (sfsi.ssi_signo == SIGUSR1) {
2045 server_flush_to_var(s);
2049 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2052 } else if (ev->data.fd == s->proc_kmsg_fd) {
2055 if (ev->events != EPOLLIN) {
2056 log_info("Got invalid event from epoll.");
2060 r = server_read_proc_kmsg(s);
2066 } else if (ev->data.fd == s->native_fd ||
2067 ev->data.fd == s->syslog_fd) {
2069 if (ev->events != EPOLLIN) {
2070 log_info("Got invalid event from epoll.");
2075 struct msghdr msghdr;
2077 struct ucred *ucred = NULL;
2078 struct timeval *tv = NULL;
2079 struct cmsghdr *cmsg;
2081 struct cmsghdr cmsghdr;
2082 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2083 CMSG_SPACE(sizeof(struct timeval)) +
2084 CMSG_SPACE(sizeof(int))];
2091 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2092 log_error("SIOCINQ failed: %m");
2096 if (s->buffer_size < (size_t) v) {
2100 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2101 b = realloc(s->buffer, l+1);
2104 log_error("Couldn't increase buffer.");
2113 iovec.iov_base = s->buffer;
2114 iovec.iov_len = s->buffer_size;
2118 msghdr.msg_iov = &iovec;
2119 msghdr.msg_iovlen = 1;
2120 msghdr.msg_control = &control;
2121 msghdr.msg_controllen = sizeof(control);
2123 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2126 if (errno == EINTR || errno == EAGAIN)
2129 log_error("recvmsg() failed: %m");
2133 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2135 if (cmsg->cmsg_level == SOL_SOCKET &&
2136 cmsg->cmsg_type == SCM_CREDENTIALS &&
2137 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2138 ucred = (struct ucred*) CMSG_DATA(cmsg);
2139 else if (cmsg->cmsg_level == SOL_SOCKET &&
2140 cmsg->cmsg_type == SO_TIMESTAMP &&
2141 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2142 tv = (struct timeval*) CMSG_DATA(cmsg);
2143 else if (cmsg->cmsg_level == SOL_SOCKET &&
2144 cmsg->cmsg_type == SCM_RIGHTS) {
2145 fds = (int*) CMSG_DATA(cmsg);
2146 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2150 if (ev->data.fd == s->syslog_fd) {
2153 if (n > 0 && n_fds == 0) {
2154 e = memchr(s->buffer, '\n', n);
2160 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
2161 } else if (n_fds > 0)
2162 log_warning("Got file descriptors via syslog socket. Ignoring.");
2165 if (n > 0 && n_fds == 0)
2166 process_native_message(s, s->buffer, n, ucred, tv);
2167 else if (n == 0 && n_fds == 1)
2168 process_native_file(s, fds[0], ucred, tv);
2170 log_warning("Got too many file descriptors via native socket. Ignoring.");
2173 close_many(fds, n_fds);
2178 } else if (ev->data.fd == s->stdout_fd) {
2180 if (ev->events != EPOLLIN) {
2181 log_info("Got invalid event from epoll.");
2185 stdout_stream_new(s);
2189 StdoutStream *stream;
2191 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2192 log_info("Got invalid event from epoll.");
2196 /* If it is none of the well-known fds, it must be an
2197 * stdout stream fd. Note that this is a bit ugly here
2198 * (since we rely that none of the well-known fds
2199 * could be interpreted as pointer), but nonetheless
2200 * safe, since the well-known fds would never get an
2201 * fd > 4096, i.e. beyond the first memory page */
2203 stream = ev->data.ptr;
2205 if (stdout_stream_process(stream) <= 0)
2206 stdout_stream_free(stream);
2211 log_error("Unknown event.");
2215 static int open_syslog_socket(Server *s) {
2216 union sockaddr_union sa;
2218 struct epoll_event ev;
2223 if (s->syslog_fd < 0) {
2225 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2226 if (s->syslog_fd < 0) {
2227 log_error("socket() failed: %m");
2232 sa.un.sun_family = AF_UNIX;
2233 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2235 unlink(sa.un.sun_path);
2237 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2239 log_error("bind() failed: %m");
2243 chmod(sa.un.sun_path, 0666);
2247 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2249 log_error("SO_PASSCRED failed: %m");
2254 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2256 log_error("SO_TIMESTAMP failed: %m");
2260 /* Since we use the same socket for forwarding this to some
2261 * other syslog implementation, make sure we don't hang
2263 timeval_store(&tv, SYSLOG_TIMEOUT_USEC);
2264 if (setsockopt(s->syslog_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) {
2265 log_error("SO_SNDTIMEO failed: %m");
2270 ev.events = EPOLLIN;
2271 ev.data.fd = s->syslog_fd;
2272 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2273 log_error("Failed to add syslog server fd to epoll object: %m");
2280 static int open_native_socket(Server*s) {
2281 union sockaddr_union sa;
2283 struct epoll_event ev;
2287 if (s->native_fd < 0) {
2289 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2290 if (s->native_fd < 0) {
2291 log_error("socket() failed: %m");
2296 sa.un.sun_family = AF_UNIX;
2297 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2299 unlink(sa.un.sun_path);
2301 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2303 log_error("bind() failed: %m");
2307 chmod(sa.un.sun_path, 0666);
2311 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2313 log_error("SO_PASSCRED failed: %m");
2318 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2320 log_error("SO_TIMESTAMP failed: %m");
2325 ev.events = EPOLLIN;
2326 ev.data.fd = s->native_fd;
2327 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2328 log_error("Failed to add native server fd to epoll object: %m");
2335 static int open_stdout_socket(Server *s) {
2336 union sockaddr_union sa;
2338 struct epoll_event ev;
2342 if (s->stdout_fd < 0) {
2344 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2345 if (s->stdout_fd < 0) {
2346 log_error("socket() failed: %m");
2351 sa.un.sun_family = AF_UNIX;
2352 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2354 unlink(sa.un.sun_path);
2356 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2358 log_error("bind() failed: %m");
2362 chmod(sa.un.sun_path, 0666);
2364 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2365 log_error("liste() failed: %m");
2371 ev.events = EPOLLIN;
2372 ev.data.fd = s->stdout_fd;
2373 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2374 log_error("Failed to add stdout server fd to epoll object: %m");
2381 static int open_proc_kmsg(Server *s) {
2382 struct epoll_event ev;
2386 if (!s->import_proc_kmsg)
2390 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2391 if (s->proc_kmsg_fd < 0) {
2392 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2397 ev.events = EPOLLIN;
2398 ev.data.fd = s->proc_kmsg_fd;
2399 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2400 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2407 static int open_signalfd(Server *s) {
2409 struct epoll_event ev;
2413 assert_se(sigemptyset(&mask) == 0);
2414 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2415 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2417 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2418 if (s->signal_fd < 0) {
2419 log_error("signalfd(): %m");
2424 ev.events = EPOLLIN;
2425 ev.data.fd = s->signal_fd;
2427 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2428 log_error("epoll_ctl(): %m");
2435 static int server_parse_proc_cmdline(Server *s) {
2436 char *line, *w, *state;
2440 if (detect_container(NULL) > 0)
2443 r = read_one_line_file("/proc/cmdline", &line);
2445 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2449 FOREACH_WORD_QUOTED(w, l, line, state) {
2452 word = strndup(w, l);
2458 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2459 r = parse_boolean(word + 35);
2461 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2463 s->forward_to_syslog = r;
2464 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2465 r = parse_boolean(word + 33);
2467 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2469 s->forward_to_kmsg = r;
2470 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2471 r = parse_boolean(word + 36);
2473 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2475 s->forward_to_console = r;
2488 static int server_parse_config_file(Server *s) {
2495 fn = "/etc/systemd/systemd-journald.conf";
2496 f = fopen(fn, "re");
2498 if (errno == ENOENT)
2501 log_warning("Failed to open configuration file %s: %m", fn);
2505 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2507 log_warning("Failed to parse configuration file: %s", strerror(-r));
2514 static int server_init(Server *s) {
2520 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2523 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2524 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2526 s->forward_to_syslog = true;
2527 s->import_proc_kmsg = true;
2529 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2530 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2532 server_parse_config_file(s);
2533 server_parse_proc_cmdline(s);
2535 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2536 if (!s->user_journals) {
2537 log_error("Out of memory.");
2541 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2542 if (s->epoll_fd < 0) {
2543 log_error("Failed to create epoll object: %m");
2547 n = sd_listen_fds(true);
2549 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2553 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2555 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2557 if (s->native_fd >= 0) {
2558 log_error("Too many native sockets passed.");
2564 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2566 if (s->stdout_fd >= 0) {
2567 log_error("Too many stdout sockets passed.");
2573 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2575 if (s->syslog_fd >= 0) {
2576 log_error("Too many /dev/log sockets passed.");
2583 log_error("Unknown socket passed.");
2588 r = open_syslog_socket(s);
2592 r = open_native_socket(s);
2596 r = open_stdout_socket(s);
2600 r = open_proc_kmsg(s);
2604 r = system_journal_open(s);
2608 r = open_signalfd(s);
2612 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2619 static void server_done(Server *s) {
2623 while (s->stdout_streams)
2624 stdout_stream_free(s->stdout_streams);
2626 if (s->system_journal)
2627 journal_file_close(s->system_journal);
2629 if (s->runtime_journal)
2630 journal_file_close(s->runtime_journal);
2632 while ((f = hashmap_steal_first(s->user_journals)))
2633 journal_file_close(f);
2635 hashmap_free(s->user_journals);
2637 if (s->epoll_fd >= 0)
2638 close_nointr_nofail(s->epoll_fd);
2640 if (s->signal_fd >= 0)
2641 close_nointr_nofail(s->signal_fd);
2643 if (s->syslog_fd >= 0)
2644 close_nointr_nofail(s->syslog_fd);
2646 if (s->native_fd >= 0)
2647 close_nointr_nofail(s->native_fd);
2649 if (s->stdout_fd >= 0)
2650 close_nointr_nofail(s->stdout_fd);
2652 if (s->proc_kmsg_fd >= 0)
2653 close_nointr_nofail(s->proc_kmsg_fd);
2656 journal_rate_limit_free(s->rate_limit);
2661 int main(int argc, char *argv[]) {
2665 /* if (getppid() != 1) { */
2666 /* log_error("This program should be invoked by init only."); */
2667 /* return EXIT_FAILURE; */
2671 log_error("This program does not take arguments.");
2672 return EXIT_FAILURE;
2675 log_set_target(LOG_TARGET_CONSOLE);
2676 log_parse_environment();
2681 r = server_init(&server);
2685 server_vacuum(&server);
2686 server_flush_to_var(&server);
2687 server_flush_proc_kmsg(&server);
2689 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2690 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2694 "STATUS=Processing requests...");
2697 struct epoll_event event;
2699 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2705 log_error("epoll_wait() failed: %m");
2711 r = process_event(&server, &event);
2718 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2719 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2723 "STATUS=Shutting down...");
2725 server_done(&server);
2727 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;