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;
62 static void fix_perms(JournalFile *f, uid_t uid) {
65 acl_permset_t permset;
70 r = fchmod_and_fchown(f->fd, 0640, 0, 0);
72 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
77 acl = acl_get_fd(f->fd);
79 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
83 r = acl_find_uid(acl, uid, &entry);
86 if (acl_create_entry(&acl, &entry) < 0 ||
87 acl_set_tag_type(entry, ACL_USER) < 0 ||
88 acl_set_qualifier(entry, &uid) < 0) {
89 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
94 if (acl_get_permset(entry, &permset) < 0 ||
95 acl_add_perm(permset, ACL_READ) < 0 ||
96 acl_calc_mask(&acl) < 0) {
97 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
101 if (acl_set_fd(f->fd, acl) < 0)
102 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
108 static JournalFile* find_journal(Server *s, uid_t uid) {
117 /* We split up user logs only on /var, not on /run */
118 if (!s->system_journal)
119 return s->runtime_journal;
122 return s->system_journal;
124 r = sd_id128_get_machine(&machine);
126 return s->system_journal;
128 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
132 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
133 return s->system_journal;
135 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
136 /* Too many open? Then let's close one */
137 f = hashmap_steal_first(s->user_journals);
139 journal_file_close(f);
142 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
146 return s->system_journal;
150 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
152 journal_file_close(f);
153 return s->system_journal;
159 static void server_vacuum(Server *s) {
168 log_info("Rotating...");
170 if (s->runtime_journal) {
171 r = journal_file_rotate(&s->runtime_journal);
173 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
176 if (s->system_journal) {
177 r = journal_file_rotate(&s->system_journal);
179 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
182 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
183 r = journal_file_rotate(&f);
185 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
187 hashmap_replace(s->user_journals, k, f);
190 log_info("Vacuuming...");
192 r = sd_id128_get_machine(&machine);
194 log_error("Failed to get machine ID: %s", strerror(-r));
198 if (asprintf(&p, "/var/log/journal/%s", sd_id128_to_string(machine, ids)) < 0) {
199 log_error("Out of memory.");
203 r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
204 if (r < 0 && r != -ENOENT)
205 log_error("Failed to vacuum %s: %s", p, strerror(-r));
208 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
209 log_error("Out of memory.");
213 r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
214 if (r < 0 && r != -ENOENT)
215 log_error("Failed to vacuum %s: %s", p, strerror(-r));
219 static void dispatch_message(Server *s, struct iovec *iovec, unsigned n, unsigned m, struct ucred *ucred, struct timeval *tv) {
220 char *pid = NULL, *uid = NULL, *gid = NULL,
221 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
222 *comm = NULL, *cmdline = NULL, *hostname = NULL,
223 *audit_session = NULL, *audit_loginuid = NULL,
224 *exe = NULL, *cgroup = NULL;
230 uid_t loginuid = 0, realuid = 0;
232 bool vacuumed = false;
235 assert(iovec || n == 0);
246 realuid = ucred->uid;
248 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
249 IOVEC_SET_STRING(iovec[n++], pid);
251 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
252 IOVEC_SET_STRING(iovec[n++], uid);
254 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
255 IOVEC_SET_STRING(iovec[n++], gid);
257 r = get_process_comm(ucred->pid, &t);
259 comm = strappend("_COMM=", t);
261 IOVEC_SET_STRING(iovec[n++], comm);
265 r = get_process_exe(ucred->pid, &t);
267 exe = strappend("_EXE=", t);
269 IOVEC_SET_STRING(iovec[n++], exe);
273 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
275 cmdline = strappend("_CMDLINE=", t);
277 IOVEC_SET_STRING(iovec[n++], cmdline);
281 r = audit_session_from_pid(ucred->pid, &session);
283 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) session) >= 0)
284 IOVEC_SET_STRING(iovec[n++], audit_session);
286 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
288 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
289 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
291 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, ucred->pid, &path);
293 cgroup = strappend("_SYSTEMD_CGROUP=", path);
295 IOVEC_SET_STRING(iovec[n++], cgroup);
301 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
302 (unsigned long long) timeval_load(tv)) >= 0)
303 IOVEC_SET_STRING(iovec[n++], source_time);
306 /* Note that strictly speaking storing the boot id here is
307 * redundant since the entry includes this in-line
308 * anyway. However, we need this indexed, too. */
309 r = sd_id128_get_boot(&id);
311 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
312 IOVEC_SET_STRING(iovec[n++], boot_id);
314 r = sd_id128_get_machine(&id);
316 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
317 IOVEC_SET_STRING(iovec[n++], machine_id);
319 t = gethostname_malloc();
321 hostname = strappend("_HOSTNAME=", t);
323 IOVEC_SET_STRING(iovec[n++], hostname);
330 f = find_journal(s, realuid == 0 ? 0 : loginuid);
332 log_warning("Dropping message, as we can't find a place to store the data.");
334 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
336 if (r == -E2BIG && !vacuumed) {
337 log_info("Allocation limit reached.");
342 log_info("Retrying write.");
347 log_error("Failed to write entry, ignoring: %s", strerror(-r));
361 free(audit_loginuid);
366 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
367 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL;
368 struct iovec iovec[16];
370 int priority = LOG_USER | LOG_INFO;
375 parse_syslog_priority((char**) &buf, &priority);
376 skip_syslog_date((char**) &buf);
378 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
379 IOVEC_SET_STRING(iovec[n++], syslog_priority);
381 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
382 IOVEC_SET_STRING(iovec[n++], syslog_facility);
384 message = strappend("MESSAGE=", buf);
386 IOVEC_SET_STRING(iovec[n++], message);
388 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv);
391 free(syslog_facility);
392 free(syslog_priority);
395 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
396 struct iovec *iovec = NULL;
397 unsigned n = 0, m = 0, j;
402 assert(buffer || n == 0);
405 remaining = buffer_size;
407 while (remaining > 0) {
410 e = memchr(p, '\n', remaining);
413 /* Trailing noise, let's ignore it, and flush what we collected */
414 log_debug("Received message with trailing noise, ignoring.");
419 /* Entry separator */
420 dispatch_message(s, iovec, n, m, ucred, tv);
429 /* Control command, ignore for now */
430 remaining -= (e - p) + 1;
435 /* A property follows */
441 u = MAX((n+13U) * 2U, 4U);
442 c = realloc(iovec, u * sizeof(struct iovec));
444 log_error("Out of memory");
452 q = memchr(p, '=', e - p);
455 /* If the field name starts with an
456 * underscore, skip the variable,
457 * since that indidates a trusted
459 iovec[n].iov_base = (char*) p;
460 iovec[n].iov_len = e - p;
464 remaining -= (e - p) + 1;
471 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
472 log_debug("Failed to parse message, ignoring.");
476 memcpy(&l, e + 1, sizeof(uint64_t));
479 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
480 e[1+sizeof(uint64_t)+l] != '\n') {
481 log_debug("Failed to parse message, ignoring.");
485 k = malloc((e - p) + 1 + l);
487 log_error("Out of memory");
493 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
496 iovec[n].iov_base = k;
497 iovec[n].iov_len = (e - p) + 1 + l;
502 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
503 p = e + 1 + sizeof(uint64_t) + l + 1;
507 dispatch_message(s, iovec, n, m, ucred, tv);
509 for (j = 0; j < n; j++)
510 if (iovec[j].iov_base < buffer ||
511 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
512 free(iovec[j].iov_base);
515 static int process_event(Server *s, struct epoll_event *ev) {
518 if (ev->events != EPOLLIN) {
519 log_info("Got invalid event from epoll.");
523 if (ev->data.fd == s->signal_fd) {
524 struct signalfd_siginfo sfsi;
527 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
528 if (n != sizeof(sfsi)) {
533 if (errno == EINTR || errno == EAGAIN)
539 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
544 if (ev->data.fd == s->native_fd ||
545 ev->data.fd == s->syslog_fd) {
547 struct msghdr msghdr;
549 struct ucred *ucred = NULL;
550 struct timeval *tv = NULL;
551 struct cmsghdr *cmsg;
553 struct cmsghdr cmsghdr;
554 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
555 CMSG_SPACE(sizeof(struct timeval))];
560 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
561 log_error("SIOCINQ failed: %m");
568 if (s->buffer_size < (size_t) v) {
572 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
573 b = realloc(s->buffer, l+1);
576 log_error("Couldn't increase buffer.");
585 iovec.iov_base = s->buffer;
586 iovec.iov_len = s->buffer_size;
590 msghdr.msg_iov = &iovec;
591 msghdr.msg_iovlen = 1;
592 msghdr.msg_control = &control;
593 msghdr.msg_controllen = sizeof(control);
595 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
598 if (errno == EINTR || errno == EAGAIN)
601 log_error("recvmsg() failed: %m");
605 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
607 if (cmsg->cmsg_level == SOL_SOCKET &&
608 cmsg->cmsg_type == SCM_CREDENTIALS &&
609 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
610 ucred = (struct ucred*) CMSG_DATA(cmsg);
611 else if (cmsg->cmsg_level == SOL_SOCKET &&
612 cmsg->cmsg_type == SO_TIMESTAMP &&
613 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
614 tv = (struct timeval*) CMSG_DATA(cmsg);
617 if (ev->data.fd == s->syslog_fd) {
620 e = memchr(s->buffer, '\n', n);
626 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
628 process_native_message(s, s->buffer, n, ucred, tv);
634 log_error("Unknown event.");
638 static int system_journal_open(Server *s) {
644 r = sd_id128_get_machine(&machine);
648 /* First try to create the machine path, but not the prefix */
649 fn = strappend("/var/log/journal/", sd_id128_to_string(machine, ids));
652 (void) mkdir(fn, 0755);
655 /* The create the system journal file */
656 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
660 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
664 fix_perms(s->system_journal, 0);
668 if (r < 0 && r != -ENOENT) {
669 log_error("Failed to open system journal: %s", strerror(-r));
673 /* /var didn't work, so try /run, but this time we
674 * create the prefix too */
675 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
679 (void) mkdir_parents(fn, 0755);
680 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
684 log_error("Failed to open runtime journal: %s", strerror(-r));
688 fix_perms(s->runtime_journal, 0);
692 static int open_syslog_socket(Server *s) {
693 union sockaddr_union sa;
698 if (s->syslog_fd < 0) {
700 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
701 if (s->syslog_fd < 0) {
702 log_error("socket() failed: %m");
707 sa.un.sun_family = AF_UNIX;
708 strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
710 unlink(sa.un.sun_path);
712 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
714 log_error("bind() failed: %m");
718 chmod(sa.un.sun_path, 0666);
722 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
724 log_error("SO_PASSCRED failed: %m");
729 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
731 log_error("SO_TIMESTAMP failed: %m");
738 static int open_native_socket(Server*s) {
739 union sockaddr_union sa;
744 if (s->native_fd < 0) {
746 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
747 if (s->native_fd < 0) {
748 log_error("socket() failed: %m");
753 sa.un.sun_family = AF_UNIX;
754 strncpy(sa.un.sun_path, "/run/systemd/journal", sizeof(sa.un.sun_path));
756 unlink(sa.un.sun_path);
758 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
760 log_error("bind() failed: %m");
764 chmod(sa.un.sun_path, 0666);
768 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
770 log_error("SO_PASSCRED failed: %m");
775 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
777 log_error("SO_TIMESTAMP failed: %m");
784 static int server_init(Server *s) {
786 struct epoll_event ev;
792 s->syslog_fd = s->native_fd = s->signal_fd = -1;
793 s->metrics.max_size = DEFAULT_MAX_SIZE;
794 s->metrics.min_size = DEFAULT_MIN_SIZE;
795 s->metrics.keep_free = DEFAULT_KEEP_FREE;
796 s->max_use = DEFAULT_MAX_USE;
798 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
799 if (s->epoll_fd < 0) {
800 log_error("Failed to create epoll object: %m");
804 n = sd_listen_fds(true);
806 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
810 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
812 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
814 if (s->syslog_fd >= 0) {
815 log_error("Too many /dev/log sockets passed.");
821 } else if (sd_is_socket(fd, AF_UNIX, SOCK_DGRAM, -1) > 0) {
823 if (s->native_fd >= 0) {
824 log_error("Too many native sockets passed.");
830 log_error("Unknown socket passed.");
835 r = open_syslog_socket(s);
841 ev.data.fd = s->syslog_fd;
842 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
843 log_error("Failed to add syslog server fd to epoll object: %m");
847 r = open_native_socket(s);
853 ev.data.fd = s->native_fd;
854 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
855 log_error("Failed to add native server fd to epoll object: %m");
859 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
860 if (!s->user_journals) {
861 log_error("Out of memory.");
865 r = system_journal_open(s);
869 assert_se(sigemptyset(&mask) == 0);
870 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
871 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
873 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
874 if (s->signal_fd < 0) {
875 log_error("signalfd(): %m");
881 ev.data.fd = s->signal_fd;
883 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
884 log_error("epoll_ctl(): %m");
891 static void server_done(Server *s) {
895 if (s->system_journal)
896 journal_file_close(s->system_journal);
898 if (s->runtime_journal)
899 journal_file_close(s->runtime_journal);
901 while ((f = hashmap_steal_first(s->user_journals)))
902 journal_file_close(f);
904 hashmap_free(s->user_journals);
906 if (s->epoll_fd >= 0)
907 close_nointr_nofail(s->epoll_fd);
909 if (s->signal_fd >= 0)
910 close_nointr_nofail(s->signal_fd);
912 if (s->syslog_fd >= 0)
913 close_nointr_nofail(s->syslog_fd);
915 if (s->native_fd >= 0)
916 close_nointr_nofail(s->native_fd);
919 int main(int argc, char *argv[]) {
923 /* if (getppid() != 1) { */
924 /* log_error("This program should be invoked by init only."); */
925 /* return EXIT_FAILURE; */
929 log_error("This program does not take arguments.");
933 log_set_target(LOG_TARGET_CONSOLE);
934 log_parse_environment();
939 r = server_init(&server);
943 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
947 "STATUS=Processing messages...");
950 struct epoll_event event;
952 r = epoll_wait(server.epoll_fd, &event, 1, -1);
958 log_error("epoll_wait() failed: %m");
964 r = process_event(&server, &event);
973 "STATUS=Shutting down...");
975 server_done(&server);
977 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;