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"
43 #include "sd-journal.h"
44 #include "journal-internal.h"
46 #define USER_JOURNALS_MAX 1024
47 #define STDOUT_STREAMS_MAX 4096
49 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
50 #define DEFAULT_RATE_LIMIT_BURST 200
52 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
54 typedef struct StdoutStream StdoutStream;
56 typedef struct Server {
63 JournalFile *runtime_journal;
64 JournalFile *system_journal;
65 Hashmap *user_journals;
72 JournalRateLimit *rate_limit;
74 JournalMetrics metrics;
78 uint64_t cached_available_space;
79 usec_t cached_available_space_timestamp;
81 LIST_HEAD(StdoutStream, stdout_streams);
82 unsigned n_stdout_streams;
85 typedef enum StdoutStreamState {
87 STDOUT_STREAM_PRIORITY,
88 STDOUT_STREAM_PRIORITY_PREFIX,
89 STDOUT_STREAM_TEE_CONSOLE,
95 StdoutStreamState state;
103 bool priority_prefix:1;
106 char buffer[LINE_MAX+1];
109 LIST_FIELDS(StdoutStream, stdout_stream);
112 static int server_flush_to_var(Server *s);
114 static uint64_t available_space(Server *s) {
120 uint64_t sum = 0, avail = 0, ss_avail = 0;
123 usec_t ts = now(CLOCK_MONOTONIC);
125 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
126 return s->cached_available_space;
128 r = sd_id128_get_machine(&machine);
132 if (s->system_journal)
133 f = "/var/log/journal/";
135 f = "/run/log/journal/";
137 p = strappend(f, sd_id128_to_string(machine, ids));
147 if (fstatvfs(dirfd(d), &ss) < 0)
152 struct dirent buf, *de;
155 k = readdir_r(d, &buf, &de);
164 if (!dirent_is_file_with_suffix(de, ".journal"))
167 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
170 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
173 avail = sum >= s->max_use ? 0 : s->max_use - sum;
175 ss_avail = ss.f_bsize * ss.f_bavail;
177 ss_avail = ss_avail < s->metrics.keep_free ? 0 : ss_avail - s->metrics.keep_free;
179 if (ss_avail < avail)
182 s->cached_available_space = avail;
183 s->cached_available_space_timestamp = ts;
191 static void fix_perms(JournalFile *f, uid_t uid) {
194 acl_permset_t permset;
199 r = fchmod_and_fchown(f->fd, 0640, 0, 0);
201 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
206 acl = acl_get_fd(f->fd);
208 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
212 r = acl_find_uid(acl, uid, &entry);
215 if (acl_create_entry(&acl, &entry) < 0 ||
216 acl_set_tag_type(entry, ACL_USER) < 0 ||
217 acl_set_qualifier(entry, &uid) < 0) {
218 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
223 if (acl_get_permset(entry, &permset) < 0 ||
224 acl_add_perm(permset, ACL_READ) < 0 ||
225 acl_calc_mask(&acl) < 0) {
226 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
230 if (acl_set_fd(f->fd, acl) < 0)
231 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
237 static JournalFile* find_journal(Server *s, uid_t uid) {
246 /* We split up user logs only on /var, not on /run. If the
247 * runtime file is open, we write to it exclusively, in order
248 * to guarantee proper order as soon as we flush /run to
249 * /var and close the runtime file. */
251 if (s->runtime_journal)
252 return s->runtime_journal;
255 return s->system_journal;
257 r = sd_id128_get_machine(&machine);
259 return s->system_journal;
261 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
265 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
266 return s->system_journal;
268 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
269 /* Too many open? Then let's close one */
270 f = hashmap_steal_first(s->user_journals);
272 journal_file_close(f);
275 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
279 return s->system_journal;
282 f->metrics = s->metrics;
283 f->compress = s->compress;
285 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
287 journal_file_close(f);
288 return s->system_journal;
294 static void server_vacuum(Server *s) {
303 log_info("Rotating...");
305 if (s->runtime_journal) {
306 r = journal_file_rotate(&s->runtime_journal);
308 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
311 if (s->system_journal) {
312 r = journal_file_rotate(&s->system_journal);
314 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
317 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
318 r = journal_file_rotate(&f);
320 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
322 hashmap_replace(s->user_journals, k, f);
325 log_info("Vacuuming...");
327 r = sd_id128_get_machine(&machine);
329 log_error("Failed to get machine ID: %s", strerror(-r));
333 if (asprintf(&p, "/var/log/journal/%s", sd_id128_to_string(machine, ids)) < 0) {
334 log_error("Out of memory.");
338 r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
339 if (r < 0 && r != -ENOENT)
340 log_error("Failed to vacuum %s: %s", p, strerror(-r));
343 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
344 log_error("Out of memory.");
348 r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
349 if (r < 0 && r != -ENOENT)
350 log_error("Failed to vacuum %s: %s", p, strerror(-r));
353 s->cached_available_space_timestamp = 0;
356 static char *shortened_cgroup_path(pid_t pid) {
358 char *process_path, *init_path, *path;
362 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
366 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
372 if (streq(init_path, "/"))
375 if (startswith(process_path, init_path))
376 path = process_path + strlen(init_path);
385 static void dispatch_message_real(Server *s,
386 struct iovec *iovec, unsigned n, unsigned m,
388 struct timeval *tv) {
390 char *pid = NULL, *uid = NULL, *gid = NULL,
391 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
392 *comm = NULL, *cmdline = NULL, *hostname = NULL,
393 *audit_session = NULL, *audit_loginuid = NULL,
394 *exe = NULL, *cgroup = NULL;
400 uid_t loginuid = 0, realuid = 0;
402 bool vacuumed = false;
413 realuid = ucred->uid;
415 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
416 IOVEC_SET_STRING(iovec[n++], pid);
418 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
419 IOVEC_SET_STRING(iovec[n++], uid);
421 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
422 IOVEC_SET_STRING(iovec[n++], gid);
424 r = get_process_comm(ucred->pid, &t);
426 comm = strappend("_COMM=", t);
428 IOVEC_SET_STRING(iovec[n++], comm);
432 r = get_process_exe(ucred->pid, &t);
434 exe = strappend("_EXE=", t);
436 IOVEC_SET_STRING(iovec[n++], exe);
440 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
442 cmdline = strappend("_CMDLINE=", t);
444 IOVEC_SET_STRING(iovec[n++], cmdline);
448 r = audit_session_from_pid(ucred->pid, &session);
450 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) session) >= 0)
451 IOVEC_SET_STRING(iovec[n++], audit_session);
453 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
455 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
456 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
458 path = shortened_cgroup_path(ucred->pid);
460 cgroup = strappend("_SYSTEMD_CGROUP=", path);
462 IOVEC_SET_STRING(iovec[n++], cgroup);
469 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
470 (unsigned long long) timeval_load(tv)) >= 0)
471 IOVEC_SET_STRING(iovec[n++], source_time);
474 /* Note that strictly speaking storing the boot id here is
475 * redundant since the entry includes this in-line
476 * anyway. However, we need this indexed, too. */
477 r = sd_id128_get_boot(&id);
479 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
480 IOVEC_SET_STRING(iovec[n++], boot_id);
482 r = sd_id128_get_machine(&id);
484 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
485 IOVEC_SET_STRING(iovec[n++], machine_id);
487 t = gethostname_malloc();
489 hostname = strappend("_HOSTNAME=", t);
491 IOVEC_SET_STRING(iovec[n++], hostname);
497 server_flush_to_var(s);
500 f = find_journal(s, realuid == 0 ? 0 : loginuid);
502 log_warning("Dropping message, as we can't find a place to store the data.");
504 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
506 if (r == -E2BIG && !vacuumed) {
507 log_info("Allocation limit reached.");
512 log_info("Retrying write.");
517 log_error("Failed to write entry, ignoring: %s", strerror(-r));
531 free(audit_loginuid);
535 static void dispatch_message(Server *s,
536 struct iovec *iovec, unsigned n, unsigned m,
544 assert(iovec || n == 0);
552 path = shortened_cgroup_path(ucred->pid);
556 /* example: /user/lennart/3/foobar
557 * /system/dbus.service/foobar
559 * So let's cut of everything past the third /, since that is
560 * wher user directories start */
562 c = strchr(path, '/');
564 c = strchr(c+1, '/');
566 c = strchr(c+1, '/');
572 rl = journal_rate_limit_test(s->rate_limit, path, priority, available_space(s));
581 char suppress_message[LINE_MAX];
582 struct iovec suppress_iovec[15];
584 /* Write a suppression message if we suppressed something */
586 snprintf(suppress_message, sizeof(suppress_message), "MESSAGE=Suppressed %u messages from %s", rl - 1, path);
587 char_array_0(suppress_message);
589 IOVEC_SET_STRING(suppress_iovec[j++], "PRIORITY=5");
590 IOVEC_SET_STRING(suppress_iovec[j++], suppress_message);
592 dispatch_message_real(s, suppress_iovec, j, ELEMENTSOF(suppress_iovec), NULL, NULL);
598 dispatch_message_real(s, iovec, n, m, ucred, tv);
601 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
602 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL;
603 struct iovec iovec[16];
605 int priority = LOG_USER | LOG_INFO;
610 parse_syslog_priority((char**) &buf, &priority);
611 skip_syslog_date((char**) &buf);
613 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
614 IOVEC_SET_STRING(iovec[n++], syslog_priority);
616 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
617 IOVEC_SET_STRING(iovec[n++], syslog_facility);
619 message = strappend("MESSAGE=", buf);
621 IOVEC_SET_STRING(iovec[n++], message);
623 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, priority & LOG_PRIMASK);
626 free(syslog_facility);
627 free(syslog_priority);
630 static bool valid_user_field(const char *p, size_t l) {
633 /* We kinda enforce POSIX syntax recommendations for
634 environment variables here, but make a couple of additional
637 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
639 /* No empty field names */
643 /* Don't allow names longer than 64 chars */
647 /* Variables starting with an underscore are protected */
651 /* Don't allow digits as first character */
652 if (p[0] >= '0' && p[0] <= '9')
655 /* Only allow A-Z0-9 and '_' */
656 for (a = p; a < p + l; a++)
657 if (!((*a >= 'A' && *a <= 'Z') ||
658 (*a >= '0' && *a <= '9') ||
665 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
666 struct iovec *iovec = NULL;
667 unsigned n = 0, m = 0, j;
670 int priority = LOG_INFO;
673 assert(buffer || n == 0);
676 remaining = buffer_size;
678 while (remaining > 0) {
681 e = memchr(p, '\n', remaining);
684 /* Trailing noise, let's ignore it, and flush what we collected */
685 log_debug("Received message with trailing noise, ignoring.");
690 /* Entry separator */
691 dispatch_message(s, iovec, n, m, ucred, tv, priority);
700 if (*p == '.' || *p == '#') {
701 /* Ignore control commands for now, and
703 remaining -= (e - p) + 1;
708 /* A property follows */
714 u = MAX((n+13U) * 2U, 4U);
715 c = realloc(iovec, u * sizeof(struct iovec));
717 log_error("Out of memory");
725 q = memchr(p, '=', e - p);
727 if (valid_user_field(p, q - p)) {
728 /* If the field name starts with an
729 * underscore, skip the variable,
730 * since that indidates a trusted
732 iovec[n].iov_base = (char*) p;
733 iovec[n].iov_len = e - p;
736 /* We need to determine the priority
737 * of this entry for the rate limiting
740 memcmp(p, "PRIORITY=", 10) == 0 &&
743 priority = p[10] - '0';
746 remaining -= (e - p) + 1;
753 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
754 log_debug("Failed to parse message, ignoring.");
758 memcpy(&l, e + 1, sizeof(uint64_t));
761 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
762 e[1+sizeof(uint64_t)+l] != '\n') {
763 log_debug("Failed to parse message, ignoring.");
767 k = malloc((e - p) + 1 + l);
769 log_error("Out of memory");
775 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
777 if (valid_user_field(p, e - p)) {
778 iovec[n].iov_base = k;
779 iovec[n].iov_len = (e - p) + 1 + l;
784 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
785 p = e + 1 + sizeof(uint64_t) + l + 1;
789 dispatch_message(s, iovec, n, m, ucred, tv, priority);
791 for (j = 0; j < n; j++)
792 if (iovec[j].iov_base < buffer ||
793 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
794 free(iovec[j].iov_base);
797 static int stdout_stream_log(StdoutStream *s, const char *p, size_t l) {
798 struct iovec iovec[15];
799 char *message = NULL, *syslog_priority = NULL;
807 priority = s->priority;
809 if (s->priority_prefix &&
812 p[1] >= '0' && p[1] <= '7' &&
815 priority = p[1] - '0';
823 if (asprintf(&syslog_priority, "PRIORITY=%i", priority) >= 0)
824 IOVEC_SET_STRING(iovec[n++], syslog_priority);
826 tag_len = s->tag ? strlen(s->tag) + 2: 0;
827 message = malloc(8 + tag_len + l);
829 memcpy(message, "MESSAGE=", 8);
832 memcpy(message+8, s->tag, tag_len-2);
833 memcpy(message+8+tag_len-2, ": ", 2);
836 memcpy(message+8+tag_len, p, l);
837 iovec[n].iov_base = message;
838 iovec[n].iov_len = 8+tag_len+l;
842 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, priority);
844 if (s->tee_console) {
847 console = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
851 IOVEC_SET_STRING(iovec[n++], s->tag);
852 IOVEC_SET_STRING(iovec[n++], ": ");
855 iovec[n].iov_base = (void*) p;
856 iovec[n].iov_len = l;
859 IOVEC_SET_STRING(iovec[n++], (char*) "\n");
861 writev(console, iovec, n);
866 free(syslog_priority);
871 static int stdout_stream_line(StdoutStream *s, const char *p, size_t l) {
875 while (l > 0 && strchr(WHITESPACE, *p)) {
880 while (l > 0 && strchr(WHITESPACE, *(p+l-1)))
885 case STDOUT_STREAM_TAG:
888 s->tag = strndup(p, l);
890 log_error("Out of memory");
895 s->state = STDOUT_STREAM_PRIORITY;
898 case STDOUT_STREAM_PRIORITY:
899 if (l != 1 || *p < '0' || *p > '7') {
900 log_warning("Failed to parse log priority line.");
904 s->priority = *p - '0';
905 s->state = STDOUT_STREAM_PRIORITY_PREFIX;
908 case STDOUT_STREAM_PRIORITY_PREFIX:
909 if (l != 1 || *p < '0' || *p > '1') {
910 log_warning("Failed to parse priority prefix line.");
914 s->priority_prefix = *p - '0';
915 s->state = STDOUT_STREAM_TEE_CONSOLE;
918 case STDOUT_STREAM_TEE_CONSOLE:
919 if (l != 1 || *p < '0' || *p > '1') {
920 log_warning("Failed to parse tee to console line.");
924 s->tee_console = *p - '0';
925 s->state = STDOUT_STREAM_RUNNING;
928 case STDOUT_STREAM_RUNNING:
929 return stdout_stream_log(s, p, l);
932 assert_not_reached("Unknown stream state");
935 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
943 remaining = s->length;
948 end = memchr(p, '\n', remaining);
950 if (remaining >= LINE_MAX) {
958 r = stdout_stream_line(s, p, end - p);
966 if (force_flush && remaining > 0) {
967 r = stdout_stream_line(s, p, remaining);
976 memmove(s->buffer, p, remaining);
977 s->length = remaining;
983 static int stdout_stream_process(StdoutStream *s) {
989 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
995 log_warning("Failed to read from stream: %m");
1000 r = stdout_stream_scan(s, true);
1008 r = stdout_stream_scan(s, false);
1016 static void stdout_stream_free(StdoutStream *s) {
1020 assert(s->server->n_stdout_streams > 0);
1021 s->server->n_stdout_streams --;
1022 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1027 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1029 close_nointr_nofail(s->fd);
1036 static int stdout_stream_new(Server *s) {
1037 StdoutStream *stream;
1040 struct epoll_event ev;
1044 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1046 if (errno == EAGAIN)
1049 log_error("Failed to accept stdout connection: %m");
1053 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1054 log_warning("Too many stdout streams, refusing connection.");
1055 close_nointr_nofail(fd);
1059 stream = new0(StdoutStream, 1);
1061 log_error("Out of memory.");
1062 close_nointr_nofail(fd);
1068 len = sizeof(stream->ucred);
1069 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1070 log_error("Failed to determine peer credentials: %m");
1075 if (shutdown(fd, SHUT_WR) < 0) {
1076 log_error("Failed to shutdown writing side of socket: %m");
1082 ev.data.ptr = stream;
1083 ev.events = EPOLLIN;
1084 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1085 log_error("Failed to add stream to event loop: %m");
1091 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1092 s->n_stdout_streams ++;
1097 stdout_stream_free(stream);
1101 static int system_journal_open(Server *s) {
1107 r = sd_id128_get_machine(&machine);
1111 sd_id128_to_string(machine, ids);
1113 if (!s->system_journal) {
1115 /* First try to create the machine path, but not the prefix */
1116 fn = strappend("/var/log/journal/", ids);
1119 (void) mkdir(fn, 0755);
1122 /* The create the system journal file */
1123 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1127 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1131 s->system_journal->metrics = s->metrics;
1132 s->system_journal->compress = s->compress;
1134 fix_perms(s->system_journal, 0);
1140 log_error("Failed to open system journal: %s", strerror(-r));
1146 if (!s->runtime_journal) {
1148 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1152 if (s->system_journal) {
1154 /* Try to open the runtime journal, but only
1155 * if it already exists, so that we can flush
1156 * it into the system journal */
1158 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1166 log_error("Failed to open runtime journal: %s", strerror(-r));
1173 /* OK, we really need the runtime journal, so create
1174 * it if necessary. */
1176 (void) mkdir_parents(fn, 0755);
1177 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1181 log_error("Failed to open runtime journal: %s", strerror(-r));
1186 if (s->runtime_journal) {
1187 s->runtime_journal->metrics = s->metrics;
1188 s->runtime_journal->compress = s->compress;
1190 fix_perms(s->runtime_journal, 0);
1197 static int server_flush_to_var(Server *s) {
1198 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1206 system_journal_open(s);
1208 if (!s->system_journal || !s->runtime_journal)
1211 r = sd_id128_get_machine(&machine);
1213 log_error("Failed to get machine id: %s", strerror(-r));
1217 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1219 log_error("Failed to read runtime journal: %s", strerror(-r));
1223 SD_JOURNAL_FOREACH(j) {
1226 f = j->current_file;
1227 assert(f && f->current_offset > 0);
1229 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1231 log_error("Can't read entry: %s", strerror(-r));
1235 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1237 log_info("Allocation limit reached.");
1239 journal_file_post_change(s->system_journal);
1242 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1246 log_error("Can't write entry: %s", strerror(-r));
1252 journal_file_post_change(s->system_journal);
1254 journal_file_close(s->runtime_journal);
1255 s->runtime_journal = NULL;
1258 sd_id128_to_string(machine, path + 17);
1259 rm_rf(path, false, true, false);
1265 static int process_event(Server *s, struct epoll_event *ev) {
1268 if (ev->data.fd == s->signal_fd) {
1269 struct signalfd_siginfo sfsi;
1272 if (ev->events != EPOLLIN) {
1273 log_info("Got invalid event from epoll.");
1277 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
1278 if (n != sizeof(sfsi)) {
1283 if (errno == EINTR || errno == EAGAIN)
1289 if (sfsi.ssi_signo == SIGUSR1) {
1290 server_flush_to_var(s);
1294 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
1297 } else if (ev->data.fd == s->native_fd ||
1298 ev->data.fd == s->syslog_fd) {
1300 if (ev->events != EPOLLIN) {
1301 log_info("Got invalid event from epoll.");
1306 struct msghdr msghdr;
1308 struct ucred *ucred = NULL;
1309 struct timeval *tv = NULL;
1310 struct cmsghdr *cmsg;
1312 struct cmsghdr cmsghdr;
1313 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1314 CMSG_SPACE(sizeof(struct timeval))];
1319 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
1320 log_error("SIOCINQ failed: %m");
1327 if (s->buffer_size < (size_t) v) {
1331 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
1332 b = realloc(s->buffer, l+1);
1335 log_error("Couldn't increase buffer.");
1344 iovec.iov_base = s->buffer;
1345 iovec.iov_len = s->buffer_size;
1349 msghdr.msg_iov = &iovec;
1350 msghdr.msg_iovlen = 1;
1351 msghdr.msg_control = &control;
1352 msghdr.msg_controllen = sizeof(control);
1354 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
1357 if (errno == EINTR || errno == EAGAIN)
1360 log_error("recvmsg() failed: %m");
1364 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
1366 if (cmsg->cmsg_level == SOL_SOCKET &&
1367 cmsg->cmsg_type == SCM_CREDENTIALS &&
1368 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
1369 ucred = (struct ucred*) CMSG_DATA(cmsg);
1370 else if (cmsg->cmsg_level == SOL_SOCKET &&
1371 cmsg->cmsg_type == SO_TIMESTAMP &&
1372 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
1373 tv = (struct timeval*) CMSG_DATA(cmsg);
1376 if (ev->data.fd == s->syslog_fd) {
1379 e = memchr(s->buffer, '\n', n);
1385 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
1387 process_native_message(s, s->buffer, n, ucred, tv);
1392 } else if (ev->data.fd == s->stdout_fd) {
1394 if (ev->events != EPOLLIN) {
1395 log_info("Got invalid event from epoll.");
1399 stdout_stream_new(s);
1403 StdoutStream *stream;
1405 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
1406 log_info("Got invalid event from epoll.");
1410 /* If it is none of the well-known fds, it must be an
1411 * stdout stream fd. Note that this is a bit ugly here
1412 * (since we rely that none of the well-known fds
1413 * could be interpreted as pointer), but nonetheless
1414 * safe, since the well-known fds would never get an
1415 * fd > 4096, i.e. beyond the first memory page */
1417 stream = ev->data.ptr;
1419 if (stdout_stream_process(stream) <= 0)
1420 stdout_stream_free(stream);
1425 log_error("Unknown event.");
1429 static int open_syslog_socket(Server *s) {
1430 union sockaddr_union sa;
1432 struct epoll_event ev;
1436 if (s->syslog_fd < 0) {
1438 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1439 if (s->syslog_fd < 0) {
1440 log_error("socket() failed: %m");
1445 sa.un.sun_family = AF_UNIX;
1446 strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
1448 unlink(sa.un.sun_path);
1450 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1452 log_error("bind() failed: %m");
1456 chmod(sa.un.sun_path, 0666);
1460 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1462 log_error("SO_PASSCRED failed: %m");
1467 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1469 log_error("SO_TIMESTAMP failed: %m");
1474 ev.events = EPOLLIN;
1475 ev.data.fd = s->syslog_fd;
1476 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
1477 log_error("Failed to add syslog server fd to epoll object: %m");
1484 static int open_native_socket(Server*s) {
1485 union sockaddr_union sa;
1487 struct epoll_event ev;
1491 if (s->native_fd < 0) {
1493 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1494 if (s->native_fd < 0) {
1495 log_error("socket() failed: %m");
1500 sa.un.sun_family = AF_UNIX;
1501 strncpy(sa.un.sun_path, "/run/systemd/journal", sizeof(sa.un.sun_path));
1503 unlink(sa.un.sun_path);
1505 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1507 log_error("bind() failed: %m");
1511 chmod(sa.un.sun_path, 0666);
1515 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1517 log_error("SO_PASSCRED failed: %m");
1522 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1524 log_error("SO_TIMESTAMP failed: %m");
1529 ev.events = EPOLLIN;
1530 ev.data.fd = s->native_fd;
1531 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
1532 log_error("Failed to add native server fd to epoll object: %m");
1539 static int open_stdout_socket(Server *s) {
1540 union sockaddr_union sa;
1542 struct epoll_event ev;
1546 if (s->stdout_fd < 0) {
1548 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1549 if (s->stdout_fd < 0) {
1550 log_error("socket() failed: %m");
1555 sa.un.sun_family = AF_UNIX;
1556 strncpy(sa.un.sun_path, "/run/systemd/stdout", sizeof(sa.un.sun_path));
1558 unlink(sa.un.sun_path);
1560 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1562 log_error("bind() failed: %m");
1566 chmod(sa.un.sun_path, 0666);
1568 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
1569 log_error("liste() failed: %m");
1575 ev.events = EPOLLIN;
1576 ev.data.fd = s->stdout_fd;
1577 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
1578 log_error("Failed to add stdout server fd to epoll object: %m");
1585 static int open_signalfd(Server *s) {
1587 struct epoll_event ev;
1591 assert_se(sigemptyset(&mask) == 0);
1592 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
1593 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1595 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1596 if (s->signal_fd < 0) {
1597 log_error("signalfd(): %m");
1602 ev.events = EPOLLIN;
1603 ev.data.fd = s->signal_fd;
1605 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
1606 log_error("epoll_ctl(): %m");
1613 static int server_init(Server *s) {
1619 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = -1;
1620 s->metrics.max_size = DEFAULT_MAX_SIZE;
1621 s->metrics.min_size = DEFAULT_MIN_SIZE;
1622 s->metrics.keep_free = DEFAULT_KEEP_FREE;
1623 s->max_use = DEFAULT_MAX_USE;
1626 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
1627 if (!s->user_journals) {
1628 log_error("Out of memory.");
1632 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1633 if (s->epoll_fd < 0) {
1634 log_error("Failed to create epoll object: %m");
1638 n = sd_listen_fds(true);
1640 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
1644 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
1646 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/native", 0) > 0) {
1648 if (s->native_fd >= 0) {
1649 log_error("Too many native sockets passed.");
1655 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/stdout", 0) > 0) {
1657 if (s->stdout_fd >= 0) {
1658 log_error("Too many stdout sockets passed.");
1664 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
1666 if (s->syslog_fd >= 0) {
1667 log_error("Too many /dev/log sockets passed.");
1674 log_error("Unknown socket passed.");
1679 r = open_syslog_socket(s);
1683 r = open_native_socket(s);
1687 r = open_stdout_socket(s);
1691 r = system_journal_open(s);
1695 r = open_signalfd(s);
1699 s->rate_limit = journal_rate_limit_new(DEFAULT_RATE_LIMIT_INTERVAL, DEFAULT_RATE_LIMIT_BURST);
1706 static void server_done(Server *s) {
1710 while (s->stdout_streams)
1711 stdout_stream_free(s->stdout_streams);
1713 if (s->system_journal)
1714 journal_file_close(s->system_journal);
1716 if (s->runtime_journal)
1717 journal_file_close(s->runtime_journal);
1719 while ((f = hashmap_steal_first(s->user_journals)))
1720 journal_file_close(f);
1722 hashmap_free(s->user_journals);
1724 if (s->epoll_fd >= 0)
1725 close_nointr_nofail(s->epoll_fd);
1727 if (s->signal_fd >= 0)
1728 close_nointr_nofail(s->signal_fd);
1730 if (s->syslog_fd >= 0)
1731 close_nointr_nofail(s->syslog_fd);
1733 if (s->native_fd >= 0)
1734 close_nointr_nofail(s->native_fd);
1736 if (s->stdout_fd >= 0)
1737 close_nointr_nofail(s->stdout_fd);
1740 journal_rate_limit_free(s->rate_limit);
1743 int main(int argc, char *argv[]) {
1747 /* if (getppid() != 1) { */
1748 /* log_error("This program should be invoked by init only."); */
1749 /* return EXIT_FAILURE; */
1753 log_error("This program does not take arguments.");
1754 return EXIT_FAILURE;
1757 log_set_target(LOG_TARGET_CONSOLE);
1758 log_set_max_level(LOG_DEBUG);
1759 log_parse_environment();
1764 r = server_init(&server);
1768 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
1772 "STATUS=Processing requests...");
1774 server_vacuum(&server);
1775 server_flush_to_var(&server);
1778 struct epoll_event event;
1780 r = epoll_wait(server.epoll_fd, &event, 1, -1);
1786 log_error("epoll_wait() failed: %m");
1792 r = process_event(&server, &event);
1799 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
1803 "STATUS=Shutting down...");
1805 server_done(&server);
1807 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;