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 void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
399 struct iovec *iovec = NULL;
400 unsigned n = 0, m = 0, j;
405 assert(buffer || n == 0);
408 remaining = buffer_size;
410 while (remaining > 0) {
413 e = memchr(p, '\n', remaining);
416 /* Trailing noise, let's ignore it, and flush what we collected */
417 log_debug("Received message with trailing noise, ignoring.");
422 /* Entry separator */
423 dispatch_message(s, iovec, n, m, ucred, tv);
432 /* Control command, ignore for now */
433 remaining -= (e - p) + 1;
438 /* A property follows */
444 u = MAX((n+13U) * 2U, 4U);
445 c = realloc(iovec, u * sizeof(struct iovec));
447 log_error("Out of memory");
455 q = memchr(p, '=', e - p);
458 /* If the field name starts with an
459 * underscore, skip the variable,
460 * since that indidates a trusted
462 iovec[n].iov_base = (char*) p;
463 iovec[n].iov_len = e - p;
467 remaining -= (e - p) + 1;
474 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
475 log_debug("Failed to parse message, ignoring.");
479 memcpy(&l, e + 1, sizeof(uint64_t));
482 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
483 e[1+sizeof(uint64_t)+l] != '\n') {
484 log_debug("Failed to parse message, ignoring.");
488 k = malloc((e - p) + 1 + l);
490 log_error("Out of memory");
496 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
499 iovec[n].iov_base = k;
500 iovec[n].iov_len = (e - p) + 1 + l;
505 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
506 p = e + 1 + sizeof(uint64_t) + l + 1;
510 dispatch_message(s, iovec, n, m, ucred, tv);
512 for (j = 0; j < n; j++)
513 if (iovec[j].iov_base < buffer ||
514 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
515 free(iovec[j].iov_base);
518 static int process_event(Server *s, struct epoll_event *ev) {
521 if (ev->events != EPOLLIN) {
522 log_info("Got invalid event from epoll.");
526 if (ev->data.fd == s->signal_fd) {
527 struct signalfd_siginfo sfsi;
530 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
531 if (n != sizeof(sfsi)) {
536 if (errno == EINTR || errno == EAGAIN)
542 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
547 if (ev->data.fd == s->native_fd ||
548 ev->data.fd == s->syslog_fd) {
550 struct msghdr msghdr;
552 struct ucred *ucred = NULL;
553 struct timeval *tv = NULL;
554 struct cmsghdr *cmsg;
556 struct cmsghdr cmsghdr;
557 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
558 CMSG_SPACE(sizeof(struct timeval))];
563 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
564 log_error("SIOCINQ failed: %m");
571 if (s->buffer_size < (size_t) v) {
575 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
576 b = realloc(s->buffer, l+1);
579 log_error("Couldn't increase buffer.");
588 iovec.iov_base = s->buffer;
589 iovec.iov_len = s->buffer_size;
593 msghdr.msg_iov = &iovec;
594 msghdr.msg_iovlen = 1;
595 msghdr.msg_control = &control;
596 msghdr.msg_controllen = sizeof(control);
598 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
601 if (errno == EINTR || errno == EAGAIN)
604 log_error("recvmsg() failed: %m");
608 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
610 if (cmsg->cmsg_level == SOL_SOCKET &&
611 cmsg->cmsg_type == SCM_CREDENTIALS &&
612 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
613 ucred = (struct ucred*) CMSG_DATA(cmsg);
614 else if (cmsg->cmsg_level == SOL_SOCKET &&
615 cmsg->cmsg_type == SO_TIMESTAMP &&
616 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
617 tv = (struct timeval*) CMSG_DATA(cmsg);
620 if (ev->data.fd == s->syslog_fd) {
623 e = memchr(s->buffer, '\n', n);
629 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
631 process_native_message(s, s->buffer, n, ucred, tv);
637 log_error("Unknown event.");
641 static int system_journal_open(Server *s) {
647 r = sd_id128_get_machine(&machine);
651 /* First try to create the machine path, but not the prefix */
652 fn = strappend("/var/log/journal/", sd_id128_to_string(machine, ids));
655 (void) mkdir(fn, 0755);
658 /* The create the system journal file */
659 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
663 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
667 s->system_journal->metrics = s->metrics;
668 s->system_journal->compress = s->compress;
670 fix_perms(s->system_journal, 0);
674 if (r < 0 && r != -ENOENT) {
675 log_error("Failed to open system journal: %s", strerror(-r));
679 /* /var didn't work, so try /run, but this time we
680 * create the prefix too */
681 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
685 (void) mkdir_parents(fn, 0755);
686 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
690 log_error("Failed to open runtime journal: %s", strerror(-r));
694 s->runtime_journal->metrics = s->metrics;
695 s->runtime_journal->compress = s->compress;
697 fix_perms(s->runtime_journal, 0);
701 static int open_syslog_socket(Server *s) {
702 union sockaddr_union sa;
707 if (s->syslog_fd < 0) {
709 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
710 if (s->syslog_fd < 0) {
711 log_error("socket() failed: %m");
716 sa.un.sun_family = AF_UNIX;
717 strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
719 unlink(sa.un.sun_path);
721 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
723 log_error("bind() failed: %m");
727 chmod(sa.un.sun_path, 0666);
731 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
733 log_error("SO_PASSCRED failed: %m");
738 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
740 log_error("SO_TIMESTAMP failed: %m");
747 static int open_native_socket(Server*s) {
748 union sockaddr_union sa;
753 if (s->native_fd < 0) {
755 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
756 if (s->native_fd < 0) {
757 log_error("socket() failed: %m");
762 sa.un.sun_family = AF_UNIX;
763 strncpy(sa.un.sun_path, "/run/systemd/journal", sizeof(sa.un.sun_path));
765 unlink(sa.un.sun_path);
767 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
769 log_error("bind() failed: %m");
773 chmod(sa.un.sun_path, 0666);
777 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
779 log_error("SO_PASSCRED failed: %m");
784 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
786 log_error("SO_TIMESTAMP failed: %m");
793 static int server_init(Server *s) {
795 struct epoll_event ev;
801 s->syslog_fd = s->native_fd = s->signal_fd = -1;
802 s->metrics.max_size = DEFAULT_MAX_SIZE;
803 s->metrics.min_size = DEFAULT_MIN_SIZE;
804 s->metrics.keep_free = DEFAULT_KEEP_FREE;
805 s->max_use = DEFAULT_MAX_USE;
808 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
809 if (s->epoll_fd < 0) {
810 log_error("Failed to create epoll object: %m");
814 n = sd_listen_fds(true);
816 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
820 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
822 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
824 if (s->syslog_fd >= 0) {
825 log_error("Too many /dev/log sockets passed.");
831 } else if (sd_is_socket(fd, AF_UNIX, SOCK_DGRAM, -1) > 0) {
833 if (s->native_fd >= 0) {
834 log_error("Too many native sockets passed.");
840 log_error("Unknown socket passed.");
845 r = open_syslog_socket(s);
851 ev.data.fd = s->syslog_fd;
852 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
853 log_error("Failed to add syslog server fd to epoll object: %m");
857 r = open_native_socket(s);
863 ev.data.fd = s->native_fd;
864 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
865 log_error("Failed to add native server fd to epoll object: %m");
869 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
870 if (!s->user_journals) {
871 log_error("Out of memory.");
875 r = system_journal_open(s);
879 assert_se(sigemptyset(&mask) == 0);
880 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
881 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
883 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
884 if (s->signal_fd < 0) {
885 log_error("signalfd(): %m");
891 ev.data.fd = s->signal_fd;
893 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
894 log_error("epoll_ctl(): %m");
901 static void server_done(Server *s) {
905 if (s->system_journal)
906 journal_file_close(s->system_journal);
908 if (s->runtime_journal)
909 journal_file_close(s->runtime_journal);
911 while ((f = hashmap_steal_first(s->user_journals)))
912 journal_file_close(f);
914 hashmap_free(s->user_journals);
916 if (s->epoll_fd >= 0)
917 close_nointr_nofail(s->epoll_fd);
919 if (s->signal_fd >= 0)
920 close_nointr_nofail(s->signal_fd);
922 if (s->syslog_fd >= 0)
923 close_nointr_nofail(s->syslog_fd);
925 if (s->native_fd >= 0)
926 close_nointr_nofail(s->native_fd);
929 int main(int argc, char *argv[]) {
933 /* if (getppid() != 1) { */
934 /* log_error("This program should be invoked by init only."); */
935 /* return EXIT_FAILURE; */
939 log_error("This program does not take arguments.");
943 log_set_target(LOG_TARGET_CONSOLE);
944 log_set_max_level(LOG_DEBUG);
945 log_parse_environment();
950 r = server_init(&server);
954 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
958 "STATUS=Processing messages...");
961 struct epoll_event event;
963 r = epoll_wait(server.epoll_fd, &event, 1, -1);
969 log_error("epoll_wait() failed: %m");
975 r = process_event(&server, &event);
984 "STATUS=Shutting down...");
986 server_done(&server);
988 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;