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>
33 #include <sys/statvfs.h>
36 #include "journal-file.h"
37 #include "sd-daemon.h"
38 #include "socket-util.h"
40 #include "cgroup-util.h"
42 #include "journal-rate-limit.h"
44 #define USER_JOURNALS_MAX 1024
45 #define STDOUT_STREAMS_MAX 4096
47 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
49 typedef struct StdoutStream StdoutStream;
51 typedef struct Server {
58 JournalFile *runtime_journal;
59 JournalFile *system_journal;
60 Hashmap *user_journals;
67 JournalRateLimit *rate_limit;
69 JournalMetrics metrics;
73 uint64_t cached_available_space;
74 usec_t cached_available_space_timestamp;
76 LIST_HEAD(StdoutStream, stdout_streams);
77 unsigned n_stdout_streams;
80 typedef enum StdoutStreamState {
82 STDOUT_STREAM_PRIORITY,
83 STDOUT_STREAM_PRIORITY_PREFIX,
84 STDOUT_STREAM_TEE_CONSOLE,
90 StdoutStreamState state;
98 bool priority_prefix:1;
101 char buffer[LINE_MAX+1];
104 LIST_FIELDS(StdoutStream, stdout_stream);
107 static uint64_t available_space(Server *s) {
113 uint64_t sum = 0, avail = 0, ss_avail = 0;
116 usec_t ts = now(CLOCK_MONOTONIC);
118 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
119 return s->cached_available_space;
121 r = sd_id128_get_machine(&machine);
125 if (s->system_journal)
126 f = "/var/log/journal/";
128 f = "/run/log/journal/";
130 p = strappend(f, sd_id128_to_string(machine, ids));
140 if (fstatvfs(dirfd(d), &ss) < 0)
145 struct dirent buf, *de;
148 k = readdir_r(d, &buf, &de);
157 if (!dirent_is_file_with_suffix(de, ".journal"))
160 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
163 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
166 avail = sum >= s->max_use ? 0 : s->max_use - sum;
168 ss_avail = ss.f_bsize * ss.f_bavail;
170 ss_avail = ss_avail < s->metrics.keep_free ? 0 : ss_avail - s->metrics.keep_free;
172 if (ss_avail < avail)
175 s->cached_available_space = avail;
176 s->cached_available_space_timestamp = ts;
184 static void fix_perms(JournalFile *f, uid_t uid) {
187 acl_permset_t permset;
192 r = fchmod_and_fchown(f->fd, 0640, 0, 0);
194 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
199 acl = acl_get_fd(f->fd);
201 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
205 r = acl_find_uid(acl, uid, &entry);
208 if (acl_create_entry(&acl, &entry) < 0 ||
209 acl_set_tag_type(entry, ACL_USER) < 0 ||
210 acl_set_qualifier(entry, &uid) < 0) {
211 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
216 if (acl_get_permset(entry, &permset) < 0 ||
217 acl_add_perm(permset, ACL_READ) < 0 ||
218 acl_calc_mask(&acl) < 0) {
219 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
223 if (acl_set_fd(f->fd, acl) < 0)
224 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
230 static JournalFile* find_journal(Server *s, uid_t uid) {
239 /* We split up user logs only on /var, not on /run */
240 if (!s->system_journal)
241 return s->runtime_journal;
244 return s->system_journal;
246 r = sd_id128_get_machine(&machine);
248 return s->system_journal;
250 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
254 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
255 return s->system_journal;
257 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
258 /* Too many open? Then let's close one */
259 f = hashmap_steal_first(s->user_journals);
261 journal_file_close(f);
264 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
268 return s->system_journal;
271 f->metrics = s->metrics;
272 f->compress = s->compress;
274 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
276 journal_file_close(f);
277 return s->system_journal;
283 static void server_vacuum(Server *s) {
292 log_info("Rotating...");
294 if (s->runtime_journal) {
295 r = journal_file_rotate(&s->runtime_journal);
297 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
300 if (s->system_journal) {
301 r = journal_file_rotate(&s->system_journal);
303 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
306 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
307 r = journal_file_rotate(&f);
309 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
311 hashmap_replace(s->user_journals, k, f);
314 log_info("Vacuuming...");
316 r = sd_id128_get_machine(&machine);
318 log_error("Failed to get machine ID: %s", strerror(-r));
322 if (asprintf(&p, "/var/log/journal/%s", sd_id128_to_string(machine, ids)) < 0) {
323 log_error("Out of memory.");
327 r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
328 if (r < 0 && r != -ENOENT)
329 log_error("Failed to vacuum %s: %s", p, strerror(-r));
332 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
333 log_error("Out of memory.");
337 r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
338 if (r < 0 && r != -ENOENT)
339 log_error("Failed to vacuum %s: %s", p, strerror(-r));
342 s->cached_available_space_timestamp = 0;
345 static char *shortened_cgroup_path(pid_t pid) {
347 char *process_path, *init_path, *path;
351 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
355 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
361 if (streq(init_path, "/"))
364 if (startswith(process_path, init_path))
365 path = process_path + strlen(init_path);
374 static void dispatch_message_real(Server *s,
375 struct iovec *iovec, unsigned n, unsigned m,
377 struct timeval *tv) {
379 char *pid = NULL, *uid = NULL, *gid = NULL,
380 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
381 *comm = NULL, *cmdline = NULL, *hostname = NULL,
382 *audit_session = NULL, *audit_loginuid = NULL,
383 *exe = NULL, *cgroup = NULL;
389 uid_t loginuid = 0, realuid = 0;
391 bool vacuumed = false;
402 realuid = ucred->uid;
404 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
405 IOVEC_SET_STRING(iovec[n++], pid);
407 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
408 IOVEC_SET_STRING(iovec[n++], uid);
410 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
411 IOVEC_SET_STRING(iovec[n++], gid);
413 r = get_process_comm(ucred->pid, &t);
415 comm = strappend("_COMM=", t);
417 IOVEC_SET_STRING(iovec[n++], comm);
421 r = get_process_exe(ucred->pid, &t);
423 exe = strappend("_EXE=", t);
425 IOVEC_SET_STRING(iovec[n++], exe);
429 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
431 cmdline = strappend("_CMDLINE=", t);
433 IOVEC_SET_STRING(iovec[n++], cmdline);
437 r = audit_session_from_pid(ucred->pid, &session);
439 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) session) >= 0)
440 IOVEC_SET_STRING(iovec[n++], audit_session);
442 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
444 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
445 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
447 path = shortened_cgroup_path(ucred->pid);
449 cgroup = strappend("_SYSTEMD_CGROUP=", path);
451 IOVEC_SET_STRING(iovec[n++], cgroup);
458 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
459 (unsigned long long) timeval_load(tv)) >= 0)
460 IOVEC_SET_STRING(iovec[n++], source_time);
463 /* Note that strictly speaking storing the boot id here is
464 * redundant since the entry includes this in-line
465 * anyway. However, we need this indexed, too. */
466 r = sd_id128_get_boot(&id);
468 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
469 IOVEC_SET_STRING(iovec[n++], boot_id);
471 r = sd_id128_get_machine(&id);
473 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
474 IOVEC_SET_STRING(iovec[n++], machine_id);
476 t = gethostname_malloc();
478 hostname = strappend("_HOSTNAME=", t);
480 IOVEC_SET_STRING(iovec[n++], hostname);
487 f = find_journal(s, realuid == 0 ? 0 : loginuid);
489 log_warning("Dropping message, as we can't find a place to store the data.");
491 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
493 if (r == -E2BIG && !vacuumed) {
494 log_info("Allocation limit reached.");
499 log_info("Retrying write.");
504 log_error("Failed to write entry, ignoring: %s", strerror(-r));
518 free(audit_loginuid);
522 static void dispatch_message(Server *s,
523 struct iovec *iovec, unsigned n, unsigned m,
531 assert(iovec || n == 0);
539 path = shortened_cgroup_path(ucred->pid);
543 /* example: /user/lennart/3/foobar
544 * /system/dbus.service/foobar
546 * So let's cut of everything past the third /, since that is
547 * wher user directories start */
549 c = strchr(path, '/');
551 c = strchr(c+1, '/');
553 c = strchr(c+1, '/');
559 rl = journal_rate_limit_test(s->rate_limit, path, priority, available_space(s));
568 char suppress_message[LINE_MAX];
569 struct iovec suppress_iovec[15];
571 /* Write a suppression message if we suppressed something */
573 snprintf(suppress_message, sizeof(suppress_message), "MESSAGE=Suppressed %u messages from %s", rl - 1, path);
574 char_array_0(suppress_message);
576 IOVEC_SET_STRING(suppress_iovec[j++], "PRIORITY=5");
577 IOVEC_SET_STRING(suppress_iovec[j++], suppress_message);
579 dispatch_message_real(s, suppress_iovec, j, ELEMENTSOF(suppress_iovec), NULL, NULL);
585 dispatch_message_real(s, iovec, n, m, ucred, tv);
588 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
589 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL;
590 struct iovec iovec[16];
592 int priority = LOG_USER | LOG_INFO;
597 parse_syslog_priority((char**) &buf, &priority);
598 skip_syslog_date((char**) &buf);
600 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
601 IOVEC_SET_STRING(iovec[n++], syslog_priority);
603 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
604 IOVEC_SET_STRING(iovec[n++], syslog_facility);
606 message = strappend("MESSAGE=", buf);
608 IOVEC_SET_STRING(iovec[n++], message);
610 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, priority & LOG_PRIMASK);
613 free(syslog_facility);
614 free(syslog_priority);
617 static bool valid_user_field(const char *p, size_t l) {
620 /* We kinda enforce POSIX syntax recommendations for
621 environment variables here, but make a couple of additional
624 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
626 /* No empty field names */
630 /* Don't allow names longer than 64 chars */
634 /* Variables starting with an underscore are protected */
638 /* Don't allow digits as first character */
639 if (p[0] >= '0' && p[0] <= '9')
642 /* Only allow A-Z0-9 and '_' */
643 for (a = p; a < p + l; a++)
644 if (!((*a >= 'A' && *a <= 'Z') ||
645 (*a >= '0' && *a <= '9') ||
652 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
653 struct iovec *iovec = NULL;
654 unsigned n = 0, m = 0, j;
657 int priority = LOG_INFO;
660 assert(buffer || n == 0);
663 remaining = buffer_size;
665 while (remaining > 0) {
668 e = memchr(p, '\n', remaining);
671 /* Trailing noise, let's ignore it, and flush what we collected */
672 log_debug("Received message with trailing noise, ignoring.");
677 /* Entry separator */
678 dispatch_message(s, iovec, n, m, ucred, tv, priority);
687 if (*p == '.' || *p == '#') {
688 /* Ignore control commands for now, and
690 remaining -= (e - p) + 1;
695 /* A property follows */
701 u = MAX((n+13U) * 2U, 4U);
702 c = realloc(iovec, u * sizeof(struct iovec));
704 log_error("Out of memory");
712 q = memchr(p, '=', e - p);
714 if (valid_user_field(p, q - p)) {
715 /* If the field name starts with an
716 * underscore, skip the variable,
717 * since that indidates a trusted
719 iovec[n].iov_base = (char*) p;
720 iovec[n].iov_len = e - p;
723 /* We need to determine the priority
724 * of this entry for the rate limiting
727 memcmp(p, "PRIORITY=", 10) == 0 &&
730 priority = p[10] - '0';
733 remaining -= (e - p) + 1;
740 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
741 log_debug("Failed to parse message, ignoring.");
745 memcpy(&l, e + 1, sizeof(uint64_t));
748 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
749 e[1+sizeof(uint64_t)+l] != '\n') {
750 log_debug("Failed to parse message, ignoring.");
754 k = malloc((e - p) + 1 + l);
756 log_error("Out of memory");
762 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
764 if (valid_user_field(p, e - p)) {
765 iovec[n].iov_base = k;
766 iovec[n].iov_len = (e - p) + 1 + l;
771 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
772 p = e + 1 + sizeof(uint64_t) + l + 1;
776 dispatch_message(s, iovec, n, m, ucred, tv, priority);
778 for (j = 0; j < n; j++)
779 if (iovec[j].iov_base < buffer ||
780 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
781 free(iovec[j].iov_base);
784 static int stdout_stream_log(StdoutStream *s, const char *p, size_t l) {
785 struct iovec iovec[15];
786 char *message = NULL, *syslog_priority = NULL;
794 priority = s->priority;
796 if (s->priority_prefix &&
799 p[1] >= '0' && p[1] <= '7' &&
802 priority = p[1] - '0';
810 if (asprintf(&syslog_priority, "PRIORITY=%i", priority) >= 0)
811 IOVEC_SET_STRING(iovec[n++], syslog_priority);
813 tag_len = s->tag ? strlen(s->tag) + 2: 0;
814 message = malloc(8 + tag_len + l);
816 memcpy(message, "MESSAGE=", 8);
819 memcpy(message+8, s->tag, tag_len-2);
820 memcpy(message+8+tag_len-2, ": ", 2);
823 memcpy(message+8+tag_len, p, l);
824 iovec[n].iov_base = message;
825 iovec[n].iov_len = 8+tag_len+l;
829 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, priority);
831 if (s->tee_console) {
834 console = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
838 IOVEC_SET_STRING(iovec[n++], s->tag);
839 IOVEC_SET_STRING(iovec[n++], ": ");
842 iovec[n].iov_base = (void*) p;
843 iovec[n].iov_len = l;
846 IOVEC_SET_STRING(iovec[n++], (char*) "\n");
848 writev(console, iovec, n);
853 free(syslog_priority);
858 static int stdout_stream_line(StdoutStream *s, const char *p, size_t l) {
862 while (l > 0 && strchr(WHITESPACE, *p)) {
867 while (l > 0 && strchr(WHITESPACE, *(p+l-1)))
872 case STDOUT_STREAM_TAG:
875 s->tag = strndup(p, l);
877 log_error("Out of memory");
882 s->state = STDOUT_STREAM_PRIORITY;
885 case STDOUT_STREAM_PRIORITY:
886 if (l != 1 || *p < '0' || *p > '7') {
887 log_warning("Failed to parse log priority line.");
891 s->priority = *p - '0';
892 s->state = STDOUT_STREAM_PRIORITY_PREFIX;
895 case STDOUT_STREAM_PRIORITY_PREFIX:
896 if (l != 1 || *p < '0' || *p > '1') {
897 log_warning("Failed to parse priority prefix line.");
901 s->priority_prefix = *p - '0';
902 s->state = STDOUT_STREAM_TEE_CONSOLE;
905 case STDOUT_STREAM_TEE_CONSOLE:
906 if (l != 1 || *p < '0' || *p > '1') {
907 log_warning("Failed to parse tee to console line.");
911 s->tee_console = *p - '0';
912 s->state = STDOUT_STREAM_RUNNING;
915 case STDOUT_STREAM_RUNNING:
916 return stdout_stream_log(s, p, l);
919 assert_not_reached("Unknown stream state");
922 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
930 remaining = s->length;
935 end = memchr(p, '\n', remaining);
937 if (remaining >= LINE_MAX) {
945 r = stdout_stream_line(s, p, end - p);
953 if (force_flush && remaining > 0) {
954 r = stdout_stream_line(s, p, remaining);
963 memmove(s->buffer, p, remaining);
964 s->length = remaining;
970 static int stdout_stream_process(StdoutStream *s) {
976 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
982 log_warning("Failed to read from stream: %m");
987 r = stdout_stream_scan(s, true);
995 r = stdout_stream_scan(s, false);
1003 static void stdout_stream_free(StdoutStream *s) {
1007 assert(s->server->n_stdout_streams > 0);
1008 s->server->n_stdout_streams --;
1009 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1014 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1016 close_nointr_nofail(s->fd);
1023 static int stdout_stream_new(Server *s) {
1024 StdoutStream *stream;
1027 struct epoll_event ev;
1031 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1033 if (errno == EAGAIN)
1036 log_error("Failed to accept stdout connection: %m");
1040 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1041 log_warning("Too many stdout streams, refusing connection.");
1042 close_nointr_nofail(fd);
1046 stream = new0(StdoutStream, 1);
1048 log_error("Out of memory.");
1049 close_nointr_nofail(fd);
1055 len = sizeof(stream->ucred);
1056 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1057 log_error("Failed to determine peer credentials: %m");
1062 if (shutdown(fd, SHUT_WR) < 0) {
1063 log_error("Failed to shutdown writing side of socket: %m");
1069 ev.data.ptr = stream;
1070 ev.events = EPOLLIN;
1071 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1072 log_error("Failed to add stream to event loop: %m");
1078 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1079 s->n_stdout_streams ++;
1084 stdout_stream_free(stream);
1088 static int process_event(Server *s, struct epoll_event *ev) {
1091 if (ev->data.fd == s->signal_fd) {
1092 struct signalfd_siginfo sfsi;
1095 if (ev->events != EPOLLIN) {
1096 log_info("Got invalid event from epoll.");
1100 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
1101 if (n != sizeof(sfsi)) {
1106 if (errno == EINTR || errno == EAGAIN)
1112 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
1115 } else if (ev->data.fd == s->native_fd ||
1116 ev->data.fd == s->syslog_fd) {
1118 if (ev->events != EPOLLIN) {
1119 log_info("Got invalid event from epoll.");
1124 struct msghdr msghdr;
1126 struct ucred *ucred = NULL;
1127 struct timeval *tv = NULL;
1128 struct cmsghdr *cmsg;
1130 struct cmsghdr cmsghdr;
1131 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1132 CMSG_SPACE(sizeof(struct timeval))];
1137 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
1138 log_error("SIOCINQ failed: %m");
1145 if (s->buffer_size < (size_t) v) {
1149 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
1150 b = realloc(s->buffer, l+1);
1153 log_error("Couldn't increase buffer.");
1162 iovec.iov_base = s->buffer;
1163 iovec.iov_len = s->buffer_size;
1167 msghdr.msg_iov = &iovec;
1168 msghdr.msg_iovlen = 1;
1169 msghdr.msg_control = &control;
1170 msghdr.msg_controllen = sizeof(control);
1172 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
1175 if (errno == EINTR || errno == EAGAIN)
1178 log_error("recvmsg() failed: %m");
1182 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
1184 if (cmsg->cmsg_level == SOL_SOCKET &&
1185 cmsg->cmsg_type == SCM_CREDENTIALS &&
1186 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
1187 ucred = (struct ucred*) CMSG_DATA(cmsg);
1188 else if (cmsg->cmsg_level == SOL_SOCKET &&
1189 cmsg->cmsg_type == SO_TIMESTAMP &&
1190 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
1191 tv = (struct timeval*) CMSG_DATA(cmsg);
1194 if (ev->data.fd == s->syslog_fd) {
1197 e = memchr(s->buffer, '\n', n);
1203 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
1205 process_native_message(s, s->buffer, n, ucred, tv);
1210 } else if (ev->data.fd == s->stdout_fd) {
1212 if (ev->events != EPOLLIN) {
1213 log_info("Got invalid event from epoll.");
1217 stdout_stream_new(s);
1221 StdoutStream *stream;
1223 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
1224 log_info("Got invalid event from epoll.");
1228 /* If it is none of the well-known fds, it must be an
1229 * stdout stream fd. Note that this is a bit ugly here
1230 * (since we rely that none of the well-known fds
1231 * could be interpreted as pointer), but nonetheless
1232 * safe, since the well-known fds would never get an
1233 * fd > 4096, i.e. beyond the first memory page */
1235 stream = ev->data.ptr;
1237 if (stdout_stream_process(stream) <= 0)
1238 stdout_stream_free(stream);
1243 log_error("Unknown event.");
1247 static int system_journal_open(Server *s) {
1253 r = sd_id128_get_machine(&machine);
1257 /* First try to create the machine path, but not the prefix */
1258 fn = strappend("/var/log/journal/", sd_id128_to_string(machine, ids));
1261 (void) mkdir(fn, 0755);
1264 /* The create the system journal file */
1265 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1269 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1273 s->system_journal->metrics = s->metrics;
1274 s->system_journal->compress = s->compress;
1276 fix_perms(s->system_journal, 0);
1280 if (r < 0 && r != -ENOENT) {
1281 log_error("Failed to open system journal: %s", strerror(-r));
1285 /* /var didn't work, so try /run, but this time we
1286 * create the prefix too */
1287 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1291 (void) mkdir_parents(fn, 0755);
1292 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1296 log_error("Failed to open runtime journal: %s", strerror(-r));
1300 s->runtime_journal->metrics = s->metrics;
1301 s->runtime_journal->compress = s->compress;
1303 fix_perms(s->runtime_journal, 0);
1307 static int open_syslog_socket(Server *s) {
1308 union sockaddr_union sa;
1310 struct epoll_event ev;
1314 if (s->syslog_fd < 0) {
1316 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1317 if (s->syslog_fd < 0) {
1318 log_error("socket() failed: %m");
1323 sa.un.sun_family = AF_UNIX;
1324 strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
1326 unlink(sa.un.sun_path);
1328 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1330 log_error("bind() failed: %m");
1334 chmod(sa.un.sun_path, 0666);
1338 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1340 log_error("SO_PASSCRED failed: %m");
1345 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1347 log_error("SO_TIMESTAMP failed: %m");
1352 ev.events = EPOLLIN;
1353 ev.data.fd = s->syslog_fd;
1354 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
1355 log_error("Failed to add syslog server fd to epoll object: %m");
1362 static int open_native_socket(Server*s) {
1363 union sockaddr_union sa;
1365 struct epoll_event ev;
1369 if (s->native_fd < 0) {
1371 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1372 if (s->native_fd < 0) {
1373 log_error("socket() failed: %m");
1378 sa.un.sun_family = AF_UNIX;
1379 strncpy(sa.un.sun_path, "/run/systemd/journal", sizeof(sa.un.sun_path));
1381 unlink(sa.un.sun_path);
1383 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1385 log_error("bind() failed: %m");
1389 chmod(sa.un.sun_path, 0666);
1393 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1395 log_error("SO_PASSCRED failed: %m");
1400 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1402 log_error("SO_TIMESTAMP failed: %m");
1407 ev.events = EPOLLIN;
1408 ev.data.fd = s->native_fd;
1409 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
1410 log_error("Failed to add native server fd to epoll object: %m");
1417 static int open_stdout_socket(Server *s) {
1418 union sockaddr_union sa;
1420 struct epoll_event ev;
1424 if (s->stdout_fd < 0) {
1426 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1427 if (s->stdout_fd < 0) {
1428 log_error("socket() failed: %m");
1433 sa.un.sun_family = AF_UNIX;
1434 strncpy(sa.un.sun_path, "/run/systemd/stdout", sizeof(sa.un.sun_path));
1436 unlink(sa.un.sun_path);
1438 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1440 log_error("bind() failed: %m");
1444 chmod(sa.un.sun_path, 0666);
1446 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
1447 log_error("liste() failed: %m");
1453 ev.events = EPOLLIN;
1454 ev.data.fd = s->stdout_fd;
1455 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
1456 log_error("Failed to add stdout server fd to epoll object: %m");
1463 static int open_signalfd(Server *s) {
1465 struct epoll_event ev;
1469 assert_se(sigemptyset(&mask) == 0);
1470 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
1471 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1473 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1474 if (s->signal_fd < 0) {
1475 log_error("signalfd(): %m");
1480 ev.events = EPOLLIN;
1481 ev.data.fd = s->signal_fd;
1483 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
1484 log_error("epoll_ctl(): %m");
1491 static int server_init(Server *s) {
1497 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = -1;
1498 s->metrics.max_size = DEFAULT_MAX_SIZE;
1499 s->metrics.min_size = DEFAULT_MIN_SIZE;
1500 s->metrics.keep_free = DEFAULT_KEEP_FREE;
1501 s->max_use = DEFAULT_MAX_USE;
1504 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
1505 if (!s->user_journals) {
1506 log_error("Out of memory.");
1510 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1511 if (s->epoll_fd < 0) {
1512 log_error("Failed to create epoll object: %m");
1516 n = sd_listen_fds(true);
1518 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
1522 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
1524 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/native", 0) > 0) {
1526 if (s->native_fd >= 0) {
1527 log_error("Too many native sockets passed.");
1533 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/stdout", 0) > 0) {
1535 if (s->stdout_fd >= 0) {
1536 log_error("Too many stdout sockets passed.");
1542 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
1544 if (s->syslog_fd >= 0) {
1545 log_error("Too many /dev/log sockets passed.");
1552 log_error("Unknown socket passed.");
1557 r = open_syslog_socket(s);
1561 r = open_native_socket(s);
1565 r = open_stdout_socket(s);
1569 r = system_journal_open(s);
1573 r = open_signalfd(s);
1577 s->rate_limit = journal_rate_limit_new(10*USEC_PER_SEC, 2);
1584 static void server_done(Server *s) {
1588 while (s->stdout_streams)
1589 stdout_stream_free(s->stdout_streams);
1591 if (s->system_journal)
1592 journal_file_close(s->system_journal);
1594 if (s->runtime_journal)
1595 journal_file_close(s->runtime_journal);
1597 while ((f = hashmap_steal_first(s->user_journals)))
1598 journal_file_close(f);
1600 hashmap_free(s->user_journals);
1602 if (s->epoll_fd >= 0)
1603 close_nointr_nofail(s->epoll_fd);
1605 if (s->signal_fd >= 0)
1606 close_nointr_nofail(s->signal_fd);
1608 if (s->syslog_fd >= 0)
1609 close_nointr_nofail(s->syslog_fd);
1611 if (s->native_fd >= 0)
1612 close_nointr_nofail(s->native_fd);
1614 if (s->stdout_fd >= 0)
1615 close_nointr_nofail(s->stdout_fd);
1618 journal_rate_limit_free(s->rate_limit);
1621 int main(int argc, char *argv[]) {
1625 /* if (getppid() != 1) { */
1626 /* log_error("This program should be invoked by init only."); */
1627 /* return EXIT_FAILURE; */
1631 log_error("This program does not take arguments.");
1632 return EXIT_FAILURE;
1635 log_set_target(LOG_TARGET_CONSOLE);
1636 log_set_max_level(LOG_DEBUG);
1637 log_parse_environment();
1642 r = server_init(&server);
1646 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
1650 "STATUS=Processing requests...");
1653 struct epoll_event event;
1655 r = epoll_wait(server.epoll_fd, &event, 1, -1);
1661 log_error("epoll_wait() failed: %m");
1667 r = process_event(&server, &event);
1674 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
1678 "STATUS=Shutting down...");
1680 server_done(&server);
1682 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;