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 <acl/libacl.h>
31 #include <sys/ioctl.h>
32 #include <linux/sockios.h>
35 #include "journal-file.h"
36 #include "sd-daemon.h"
37 #include "socket-util.h"
39 #include "cgroup-util.h"
41 #define USER_JOURNALS_MAX 1024
43 typedef struct Server {
49 JournalFile *runtime_journal;
50 JournalFile *system_journal;
51 Hashmap *user_journals;
58 JournalMetrics metrics;
63 static void fix_perms(JournalFile *f, uid_t uid) {
66 acl_permset_t permset;
71 r = fchmod_and_fchown(f->fd, 0640, 0, 0);
73 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
78 acl = acl_get_fd(f->fd);
80 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
84 r = acl_find_uid(acl, uid, &entry);
87 if (acl_create_entry(&acl, &entry) < 0 ||
88 acl_set_tag_type(entry, ACL_USER) < 0 ||
89 acl_set_qualifier(entry, &uid) < 0) {
90 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
95 if (acl_get_permset(entry, &permset) < 0 ||
96 acl_add_perm(permset, ACL_READ) < 0 ||
97 acl_calc_mask(&acl) < 0) {
98 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
102 if (acl_set_fd(f->fd, acl) < 0)
103 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
109 static JournalFile* find_journal(Server *s, uid_t uid) {
118 /* We split up user logs only on /var, not on /run */
119 if (!s->system_journal)
120 return s->runtime_journal;
123 return s->system_journal;
125 r = sd_id128_get_machine(&machine);
127 return s->system_journal;
129 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
133 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
134 return s->system_journal;
136 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
137 /* Too many open? Then let's close one */
138 f = hashmap_steal_first(s->user_journals);
140 journal_file_close(f);
143 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
147 return s->system_journal;
150 f->metrics = s->metrics;
151 f->compress = s->compress;
153 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
155 journal_file_close(f);
156 return s->system_journal;
162 static void server_vacuum(Server *s) {
171 log_info("Rotating...");
173 if (s->runtime_journal) {
174 r = journal_file_rotate(&s->runtime_journal);
176 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
179 if (s->system_journal) {
180 r = journal_file_rotate(&s->system_journal);
182 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
185 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
186 r = journal_file_rotate(&f);
188 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
190 hashmap_replace(s->user_journals, k, f);
193 log_info("Vacuuming...");
195 r = sd_id128_get_machine(&machine);
197 log_error("Failed to get machine ID: %s", strerror(-r));
201 if (asprintf(&p, "/var/log/journal/%s", sd_id128_to_string(machine, ids)) < 0) {
202 log_error("Out of memory.");
206 r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
207 if (r < 0 && r != -ENOENT)
208 log_error("Failed to vacuum %s: %s", p, strerror(-r));
211 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
212 log_error("Out of memory.");
216 r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
217 if (r < 0 && r != -ENOENT)
218 log_error("Failed to vacuum %s: %s", p, strerror(-r));
222 static void dispatch_message(Server *s, struct iovec *iovec, unsigned n, unsigned m, struct ucred *ucred, struct timeval *tv) {
223 char *pid = NULL, *uid = NULL, *gid = NULL,
224 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
225 *comm = NULL, *cmdline = NULL, *hostname = NULL,
226 *audit_session = NULL, *audit_loginuid = NULL,
227 *exe = NULL, *cgroup = NULL;
233 uid_t loginuid = 0, realuid = 0;
235 bool vacuumed = false;
238 assert(iovec || n == 0);
249 realuid = ucred->uid;
251 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
252 IOVEC_SET_STRING(iovec[n++], pid);
254 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
255 IOVEC_SET_STRING(iovec[n++], uid);
257 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
258 IOVEC_SET_STRING(iovec[n++], gid);
260 r = get_process_comm(ucred->pid, &t);
262 comm = strappend("_COMM=", t);
264 IOVEC_SET_STRING(iovec[n++], comm);
268 r = get_process_exe(ucred->pid, &t);
270 exe = strappend("_EXE=", t);
272 IOVEC_SET_STRING(iovec[n++], exe);
276 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
278 cmdline = strappend("_CMDLINE=", t);
280 IOVEC_SET_STRING(iovec[n++], cmdline);
284 r = audit_session_from_pid(ucred->pid, &session);
286 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) session) >= 0)
287 IOVEC_SET_STRING(iovec[n++], audit_session);
289 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
291 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
292 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
294 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, ucred->pid, &path);
296 cgroup = strappend("_SYSTEMD_CGROUP=", path);
298 IOVEC_SET_STRING(iovec[n++], cgroup);
304 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
305 (unsigned long long) timeval_load(tv)) >= 0)
306 IOVEC_SET_STRING(iovec[n++], source_time);
309 /* Note that strictly speaking storing the boot id here is
310 * redundant since the entry includes this in-line
311 * anyway. However, we need this indexed, too. */
312 r = sd_id128_get_boot(&id);
314 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
315 IOVEC_SET_STRING(iovec[n++], boot_id);
317 r = sd_id128_get_machine(&id);
319 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
320 IOVEC_SET_STRING(iovec[n++], machine_id);
322 t = gethostname_malloc();
324 hostname = strappend("_HOSTNAME=", t);
326 IOVEC_SET_STRING(iovec[n++], hostname);
333 f = find_journal(s, realuid == 0 ? 0 : loginuid);
335 log_warning("Dropping message, as we can't find a place to store the data.");
337 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
339 if (r == -E2BIG && !vacuumed) {
340 log_info("Allocation limit reached.");
345 log_info("Retrying write.");
350 log_error("Failed to write entry, ignoring: %s", strerror(-r));
364 free(audit_loginuid);
369 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
370 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL;
371 struct iovec iovec[16];
373 int priority = LOG_USER | LOG_INFO;
378 parse_syslog_priority((char**) &buf, &priority);
379 skip_syslog_date((char**) &buf);
381 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
382 IOVEC_SET_STRING(iovec[n++], syslog_priority);
384 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
385 IOVEC_SET_STRING(iovec[n++], syslog_facility);
387 message = strappend("MESSAGE=", buf);
389 IOVEC_SET_STRING(iovec[n++], message);
391 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv);
394 free(syslog_facility);
395 free(syslog_priority);
398 static bool valid_user_field(const char *p, size_t l) {
401 /* We kinda enforce POSIX syntax recommendations for
402 environment variables here, but make a couple of additional
405 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
407 /* No empty field names */
411 /* Don't allow names longer than 64 chars */
415 /* Variables starting with an underscore are protected */
419 /* Don't allow digits as first character */
420 if (p[0] >= '0' && p[0] <= '9')
423 /* Only allow A-Z0-9 and '_' */
424 for (a = p; a < p + l; a++)
425 if (!((*a >= 'A' && *a <= 'Z') ||
426 (*a >= '0' && *a <= '9') ||
433 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
434 struct iovec *iovec = NULL;
435 unsigned n = 0, m = 0, j;
440 assert(buffer || n == 0);
443 remaining = buffer_size;
445 while (remaining > 0) {
448 e = memchr(p, '\n', remaining);
451 /* Trailing noise, let's ignore it, and flush what we collected */
452 log_debug("Received message with trailing noise, ignoring.");
457 /* Entry separator */
458 dispatch_message(s, iovec, n, m, ucred, tv);
466 if (*p == '.' || *p == '#') {
467 /* Ignore control commands for now, and
469 remaining -= (e - p) + 1;
474 /* A property follows */
480 u = MAX((n+13U) * 2U, 4U);
481 c = realloc(iovec, u * sizeof(struct iovec));
483 log_error("Out of memory");
491 q = memchr(p, '=', e - p);
493 if (valid_user_field(p, q - p)) {
494 /* If the field name starts with an
495 * underscore, skip the variable,
496 * since that indidates a trusted
498 iovec[n].iov_base = (char*) p;
499 iovec[n].iov_len = e - p;
503 remaining -= (e - p) + 1;
510 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
511 log_debug("Failed to parse message, ignoring.");
515 memcpy(&l, e + 1, sizeof(uint64_t));
518 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
519 e[1+sizeof(uint64_t)+l] != '\n') {
520 log_debug("Failed to parse message, ignoring.");
524 k = malloc((e - p) + 1 + l);
526 log_error("Out of memory");
532 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
534 if (valid_user_field(p, e - p)) {
535 iovec[n].iov_base = k;
536 iovec[n].iov_len = (e - p) + 1 + l;
541 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
542 p = e + 1 + sizeof(uint64_t) + l + 1;
546 dispatch_message(s, iovec, n, m, ucred, tv);
548 for (j = 0; j < n; j++)
549 if (iovec[j].iov_base < buffer ||
550 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
551 free(iovec[j].iov_base);
554 static int process_event(Server *s, struct epoll_event *ev) {
557 if (ev->events != EPOLLIN) {
558 log_info("Got invalid event from epoll.");
562 if (ev->data.fd == s->signal_fd) {
563 struct signalfd_siginfo sfsi;
566 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
567 if (n != sizeof(sfsi)) {
572 if (errno == EINTR || errno == EAGAIN)
578 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
583 if (ev->data.fd == s->native_fd ||
584 ev->data.fd == s->syslog_fd) {
586 struct msghdr msghdr;
588 struct ucred *ucred = NULL;
589 struct timeval *tv = NULL;
590 struct cmsghdr *cmsg;
592 struct cmsghdr cmsghdr;
593 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
594 CMSG_SPACE(sizeof(struct timeval))];
599 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
600 log_error("SIOCINQ failed: %m");
607 if (s->buffer_size < (size_t) v) {
611 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
612 b = realloc(s->buffer, l+1);
615 log_error("Couldn't increase buffer.");
624 iovec.iov_base = s->buffer;
625 iovec.iov_len = s->buffer_size;
629 msghdr.msg_iov = &iovec;
630 msghdr.msg_iovlen = 1;
631 msghdr.msg_control = &control;
632 msghdr.msg_controllen = sizeof(control);
634 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
637 if (errno == EINTR || errno == EAGAIN)
640 log_error("recvmsg() failed: %m");
644 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
646 if (cmsg->cmsg_level == SOL_SOCKET &&
647 cmsg->cmsg_type == SCM_CREDENTIALS &&
648 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
649 ucred = (struct ucred*) CMSG_DATA(cmsg);
650 else if (cmsg->cmsg_level == SOL_SOCKET &&
651 cmsg->cmsg_type == SO_TIMESTAMP &&
652 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
653 tv = (struct timeval*) CMSG_DATA(cmsg);
656 if (ev->data.fd == s->syslog_fd) {
659 e = memchr(s->buffer, '\n', n);
665 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
667 process_native_message(s, s->buffer, n, ucred, tv);
673 log_error("Unknown event.");
677 static int system_journal_open(Server *s) {
683 r = sd_id128_get_machine(&machine);
687 /* First try to create the machine path, but not the prefix */
688 fn = strappend("/var/log/journal/", sd_id128_to_string(machine, ids));
691 (void) mkdir(fn, 0755);
694 /* The create the system journal file */
695 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
699 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
703 s->system_journal->metrics = s->metrics;
704 s->system_journal->compress = s->compress;
706 fix_perms(s->system_journal, 0);
710 if (r < 0 && r != -ENOENT) {
711 log_error("Failed to open system journal: %s", strerror(-r));
715 /* /var didn't work, so try /run, but this time we
716 * create the prefix too */
717 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
721 (void) mkdir_parents(fn, 0755);
722 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
726 log_error("Failed to open runtime journal: %s", strerror(-r));
730 s->runtime_journal->metrics = s->metrics;
731 s->runtime_journal->compress = s->compress;
733 fix_perms(s->runtime_journal, 0);
737 static int open_syslog_socket(Server *s) {
738 union sockaddr_union sa;
743 if (s->syslog_fd < 0) {
745 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
746 if (s->syslog_fd < 0) {
747 log_error("socket() failed: %m");
752 sa.un.sun_family = AF_UNIX;
753 strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
755 unlink(sa.un.sun_path);
757 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
759 log_error("bind() failed: %m");
763 chmod(sa.un.sun_path, 0666);
767 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
769 log_error("SO_PASSCRED failed: %m");
774 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
776 log_error("SO_TIMESTAMP failed: %m");
783 static int open_native_socket(Server*s) {
784 union sockaddr_union sa;
789 if (s->native_fd < 0) {
791 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
792 if (s->native_fd < 0) {
793 log_error("socket() failed: %m");
798 sa.un.sun_family = AF_UNIX;
799 strncpy(sa.un.sun_path, "/run/systemd/journal", sizeof(sa.un.sun_path));
801 unlink(sa.un.sun_path);
803 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
805 log_error("bind() failed: %m");
809 chmod(sa.un.sun_path, 0666);
813 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
815 log_error("SO_PASSCRED failed: %m");
820 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
822 log_error("SO_TIMESTAMP failed: %m");
829 static int server_init(Server *s) {
831 struct epoll_event ev;
837 s->syslog_fd = s->native_fd = s->signal_fd = -1;
838 s->metrics.max_size = DEFAULT_MAX_SIZE;
839 s->metrics.min_size = DEFAULT_MIN_SIZE;
840 s->metrics.keep_free = DEFAULT_KEEP_FREE;
841 s->max_use = DEFAULT_MAX_USE;
844 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
845 if (s->epoll_fd < 0) {
846 log_error("Failed to create epoll object: %m");
850 n = sd_listen_fds(true);
852 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
856 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
858 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
860 if (s->syslog_fd >= 0) {
861 log_error("Too many /dev/log sockets passed.");
867 } else if (sd_is_socket(fd, AF_UNIX, SOCK_DGRAM, -1) > 0) {
869 if (s->native_fd >= 0) {
870 log_error("Too many native sockets passed.");
876 log_error("Unknown socket passed.");
881 r = open_syslog_socket(s);
887 ev.data.fd = s->syslog_fd;
888 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
889 log_error("Failed to add syslog server fd to epoll object: %m");
893 r = open_native_socket(s);
899 ev.data.fd = s->native_fd;
900 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
901 log_error("Failed to add native server fd to epoll object: %m");
905 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
906 if (!s->user_journals) {
907 log_error("Out of memory.");
911 r = system_journal_open(s);
915 assert_se(sigemptyset(&mask) == 0);
916 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
917 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
919 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
920 if (s->signal_fd < 0) {
921 log_error("signalfd(): %m");
927 ev.data.fd = s->signal_fd;
929 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
930 log_error("epoll_ctl(): %m");
937 static void server_done(Server *s) {
941 if (s->system_journal)
942 journal_file_close(s->system_journal);
944 if (s->runtime_journal)
945 journal_file_close(s->runtime_journal);
947 while ((f = hashmap_steal_first(s->user_journals)))
948 journal_file_close(f);
950 hashmap_free(s->user_journals);
952 if (s->epoll_fd >= 0)
953 close_nointr_nofail(s->epoll_fd);
955 if (s->signal_fd >= 0)
956 close_nointr_nofail(s->signal_fd);
958 if (s->syslog_fd >= 0)
959 close_nointr_nofail(s->syslog_fd);
961 if (s->native_fd >= 0)
962 close_nointr_nofail(s->native_fd);
965 int main(int argc, char *argv[]) {
969 /* if (getppid() != 1) { */
970 /* log_error("This program should be invoked by init only."); */
971 /* return EXIT_FAILURE; */
975 log_error("This program does not take arguments.");
979 log_set_target(LOG_TARGET_CONSOLE);
980 log_set_max_level(LOG_DEBUG);
981 log_parse_environment();
986 r = server_init(&server);
990 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
994 "STATUS=Processing messages...");
997 struct epoll_event event;
999 r = epoll_wait(server.epoll_fd, &event, 1, -1);
1005 log_error("epoll_wait() failed: %m");
1011 r = process_event(&server, &event);
1020 "STATUS=Shutting down...");
1022 server_done(&server);
1024 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;