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"
45 #include "journal-internal.h"
47 #define USER_JOURNALS_MAX 1024
48 #define STDOUT_STREAMS_MAX 4096
50 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
51 #define DEFAULT_RATE_LIMIT_BURST 200
53 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
55 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
57 #define SYSLOG_TIMEOUT_USEC (5*USEC_PER_SEC)
59 typedef struct StdoutStream StdoutStream;
61 typedef struct Server {
68 JournalFile *runtime_journal;
69 JournalFile *system_journal;
70 Hashmap *user_journals;
77 JournalRateLimit *rate_limit;
79 JournalMetrics runtime_metrics;
80 JournalMetrics system_metrics;
84 uint64_t cached_available_space;
85 usec_t cached_available_space_timestamp;
87 uint64_t var_available_timestamp;
89 LIST_HEAD(StdoutStream, stdout_streams);
90 unsigned n_stdout_streams;
93 typedef enum StdoutStreamState {
95 STDOUT_STREAM_PRIORITY,
96 STDOUT_STREAM_PRIORITY_PREFIX,
97 STDOUT_STREAM_TEE_CONSOLE,
101 struct StdoutStream {
103 StdoutStreamState state;
111 bool priority_prefix:1;
114 char buffer[LINE_MAX+1];
117 LIST_FIELDS(StdoutStream, stdout_stream);
120 static int server_flush_to_var(Server *s);
122 static uint64_t available_space(Server *s) {
127 uint64_t sum = 0, avail = 0, ss_avail = 0;
133 ts = now(CLOCK_MONOTONIC);
135 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
136 return s->cached_available_space;
138 r = sd_id128_get_machine(&machine);
142 if (s->system_journal) {
143 f = "/var/log/journal/";
144 m = &s->system_metrics;
146 f = "/run/log/journal/";
147 m = &s->runtime_metrics;
152 p = strappend(f, sd_id128_to_string(machine, ids));
162 if (fstatvfs(dirfd(d), &ss) < 0)
167 struct dirent buf, *de;
170 k = readdir_r(d, &buf, &de);
179 if (!dirent_is_file_with_suffix(de, ".journal"))
182 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
185 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
188 avail = sum >= m->max_use ? 0 : m->max_use - sum;
190 ss_avail = ss.f_bsize * ss.f_bavail;
192 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
194 if (ss_avail < avail)
197 s->cached_available_space = avail;
198 s->cached_available_space_timestamp = ts;
206 static void fix_perms(JournalFile *f, uid_t uid) {
209 acl_permset_t permset;
214 r = fchmod_and_fchown(f->fd, 0640, 0, 0);
216 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
221 acl = acl_get_fd(f->fd);
223 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
227 r = acl_find_uid(acl, uid, &entry);
230 if (acl_create_entry(&acl, &entry) < 0 ||
231 acl_set_tag_type(entry, ACL_USER) < 0 ||
232 acl_set_qualifier(entry, &uid) < 0) {
233 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
238 if (acl_get_permset(entry, &permset) < 0 ||
239 acl_add_perm(permset, ACL_READ) < 0 ||
240 acl_calc_mask(&acl) < 0) {
241 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
245 if (acl_set_fd(f->fd, acl) < 0)
246 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
252 static JournalFile* find_journal(Server *s, uid_t uid) {
261 /* We split up user logs only on /var, not on /run. If the
262 * runtime file is open, we write to it exclusively, in order
263 * to guarantee proper order as soon as we flush /run to
264 * /var and close the runtime file. */
266 if (s->runtime_journal)
267 return s->runtime_journal;
270 return s->system_journal;
272 r = sd_id128_get_machine(&machine);
274 return s->system_journal;
276 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
280 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
281 return s->system_journal;
283 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
284 /* Too many open? Then let's close one */
285 f = hashmap_steal_first(s->user_journals);
287 journal_file_close(f);
290 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
294 return s->system_journal;
297 f->metrics = s->system_metrics;
298 f->compress = s->compress;
300 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
302 journal_file_close(f);
303 return s->system_journal;
309 static void server_rotate(Server *s) {
315 log_info("Rotating...");
317 if (s->runtime_journal) {
318 r = journal_file_rotate(&s->runtime_journal);
320 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
323 if (s->system_journal) {
324 r = journal_file_rotate(&s->system_journal);
326 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
329 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
330 r = journal_file_rotate(&f);
332 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
334 hashmap_replace(s->user_journals, k, f);
338 static void server_vacuum(Server *s) {
344 log_info("Vacuuming...");
346 r = sd_id128_get_machine(&machine);
348 log_error("Failed to get machine ID: %s", strerror(-r));
352 sd_id128_to_string(machine, ids);
354 if (s->system_journal) {
355 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
356 log_error("Out of memory.");
360 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
361 if (r < 0 && r != -ENOENT)
362 log_error("Failed to vacuum %s: %s", p, strerror(-r));
367 if (s->runtime_journal) {
368 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
369 log_error("Out of memory.");
373 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
374 if (r < 0 && r != -ENOENT)
375 log_error("Failed to vacuum %s: %s", p, strerror(-r));
379 s->cached_available_space_timestamp = 0;
382 static char *shortened_cgroup_path(pid_t pid) {
384 char *process_path, *init_path, *path;
388 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
392 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
398 if (endswith(init_path, "/system"))
399 init_path[strlen(init_path) - 7] = 0;
400 else if (streq(init_path, "/"))
403 if (startswith(process_path, init_path)) {
406 p = strdup(process_path + strlen(init_path));
424 static void dispatch_message_real(Server *s,
425 struct iovec *iovec, unsigned n, unsigned m,
427 struct timeval *tv) {
429 char *pid = NULL, *uid = NULL, *gid = NULL,
430 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
431 *comm = NULL, *cmdline = NULL, *hostname = NULL,
432 *audit_session = NULL, *audit_loginuid = NULL,
433 *exe = NULL, *cgroup = NULL, *session = NULL,
434 *owner_uid = NULL, *service = NULL;
440 uid_t loginuid = 0, realuid = 0;
442 bool vacuumed = false;
453 realuid = ucred->uid;
455 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
456 IOVEC_SET_STRING(iovec[n++], pid);
458 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
459 IOVEC_SET_STRING(iovec[n++], uid);
461 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
462 IOVEC_SET_STRING(iovec[n++], gid);
464 r = get_process_comm(ucred->pid, &t);
466 comm = strappend("_COMM=", t);
470 IOVEC_SET_STRING(iovec[n++], comm);
473 r = get_process_exe(ucred->pid, &t);
475 exe = strappend("_EXE=", t);
479 IOVEC_SET_STRING(iovec[n++], exe);
482 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
484 cmdline = strappend("_CMDLINE=", t);
488 IOVEC_SET_STRING(iovec[n++], cmdline);
491 r = audit_session_from_pid(ucred->pid, &audit);
493 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
494 IOVEC_SET_STRING(iovec[n++], audit_session);
496 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
498 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
499 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
501 t = shortened_cgroup_path(ucred->pid);
503 cgroup = strappend("_SYSTEMD_CGROUP=", t);
507 IOVEC_SET_STRING(iovec[n++], cgroup);
510 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
511 session = strappend("_SYSTEMD_SESSION=", t);
515 IOVEC_SET_STRING(iovec[n++], session);
518 if (sd_pid_get_service(ucred->pid, &t) >= 0) {
519 service = strappend("_SYSTEMD_SERVICE=", t);
523 IOVEC_SET_STRING(iovec[n++], service);
526 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
527 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
528 IOVEC_SET_STRING(iovec[n++], owner_uid);
532 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
533 (unsigned long long) timeval_load(tv)) >= 0)
534 IOVEC_SET_STRING(iovec[n++], source_time);
537 /* Note that strictly speaking storing the boot id here is
538 * redundant since the entry includes this in-line
539 * anyway. However, we need this indexed, too. */
540 r = sd_id128_get_boot(&id);
542 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
543 IOVEC_SET_STRING(iovec[n++], boot_id);
545 r = sd_id128_get_machine(&id);
547 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
548 IOVEC_SET_STRING(iovec[n++], machine_id);
550 t = gethostname_malloc();
552 hostname = strappend("_HOSTNAME=", t);
555 IOVEC_SET_STRING(iovec[n++], hostname);
560 server_flush_to_var(s);
563 f = find_journal(s, realuid == 0 ? 0 : loginuid);
565 log_warning("Dropping message, as we can't find a place to store the data.");
567 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
569 if (r == -E2BIG && !vacuumed) {
570 log_info("Allocation limit reached.");
576 log_info("Retrying write.");
581 log_error("Failed to write entry, ignoring: %s", strerror(-r));
595 free(audit_loginuid);
602 static void dispatch_message(Server *s,
603 struct iovec *iovec, unsigned n, unsigned m,
608 char *path = NULL, *c;
611 assert(iovec || n == 0);
619 path = shortened_cgroup_path(ucred->pid);
623 /* example: /user/lennart/3/foobar
624 * /system/dbus.service/foobar
626 * So let's cut of everything past the third /, since that is
627 * wher user directories start */
629 c = strchr(path, '/');
631 c = strchr(c+1, '/');
633 c = strchr(c+1, '/');
639 rl = journal_rate_limit_test(s->rate_limit, path, priority, available_space(s));
648 char suppress_message[LINE_MAX];
649 struct iovec suppress_iovec[18];
651 /* Write a suppression message if we suppressed something */
653 snprintf(suppress_message, sizeof(suppress_message), "MESSAGE=Suppressed %u messages from %s", rl - 1, path);
654 char_array_0(suppress_message);
656 IOVEC_SET_STRING(suppress_iovec[j++], "PRIORITY=5");
657 IOVEC_SET_STRING(suppress_iovec[j++], suppress_message);
659 dispatch_message_real(s, suppress_iovec, j, ELEMENTSOF(suppress_iovec), NULL, NULL);
665 dispatch_message_real(s, iovec, n, m, ucred, tv);
668 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
669 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL;
670 struct iovec iovec[19];
672 int priority = LOG_USER | LOG_INFO;
677 parse_syslog_priority((char**) &buf, &priority);
678 skip_syslog_date((char**) &buf);
680 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
681 IOVEC_SET_STRING(iovec[n++], syslog_priority);
683 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
684 IOVEC_SET_STRING(iovec[n++], syslog_facility);
686 message = strappend("MESSAGE=", buf);
688 IOVEC_SET_STRING(iovec[n++], message);
690 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, priority & LOG_PRIMASK);
693 free(syslog_facility);
694 free(syslog_priority);
697 static bool valid_user_field(const char *p, size_t l) {
700 /* We kinda enforce POSIX syntax recommendations for
701 environment variables here, but make a couple of additional
704 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
706 /* No empty field names */
710 /* Don't allow names longer than 64 chars */
714 /* Variables starting with an underscore are protected */
718 /* Don't allow digits as first character */
719 if (p[0] >= '0' && p[0] <= '9')
722 /* Only allow A-Z0-9 and '_' */
723 for (a = p; a < p + l; a++)
724 if (!((*a >= 'A' && *a <= 'Z') ||
725 (*a >= '0' && *a <= '9') ||
732 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
733 struct iovec *iovec = NULL;
734 unsigned n = 0, m = 0, j;
737 int priority = LOG_INFO;
740 assert(buffer || n == 0);
743 remaining = buffer_size;
745 while (remaining > 0) {
748 e = memchr(p, '\n', remaining);
751 /* Trailing noise, let's ignore it, and flush what we collected */
752 log_debug("Received message with trailing noise, ignoring.");
757 /* Entry separator */
758 dispatch_message(s, iovec, n, m, ucred, tv, priority);
767 if (*p == '.' || *p == '#') {
768 /* Ignore control commands for now, and
770 remaining -= (e - p) + 1;
775 /* A property follows */
781 u = MAX((n+16U) * 2U, 4U);
782 c = realloc(iovec, u * sizeof(struct iovec));
784 log_error("Out of memory");
792 q = memchr(p, '=', e - p);
794 if (valid_user_field(p, q - p)) {
795 /* If the field name starts with an
796 * underscore, skip the variable,
797 * since that indidates a trusted
799 iovec[n].iov_base = (char*) p;
800 iovec[n].iov_len = e - p;
803 /* We need to determine the priority
804 * of this entry for the rate limiting
807 memcmp(p, "PRIORITY=", 10) == 0 &&
810 priority = p[10] - '0';
813 remaining -= (e - p) + 1;
820 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
821 log_debug("Failed to parse message, ignoring.");
825 memcpy(&l, e + 1, sizeof(uint64_t));
828 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
829 e[1+sizeof(uint64_t)+l] != '\n') {
830 log_debug("Failed to parse message, ignoring.");
834 k = malloc((e - p) + 1 + l);
836 log_error("Out of memory");
842 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
844 if (valid_user_field(p, e - p)) {
845 iovec[n].iov_base = k;
846 iovec[n].iov_len = (e - p) + 1 + l;
851 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
852 p = e + 1 + sizeof(uint64_t) + l + 1;
856 dispatch_message(s, iovec, n, m, ucred, tv, priority);
858 for (j = 0; j < n; j++)
859 if (iovec[j].iov_base < buffer ||
860 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
861 free(iovec[j].iov_base);
864 static int stdout_stream_log(StdoutStream *s, const char *p, size_t l) {
865 struct iovec iovec[18];
866 char *message = NULL, *syslog_priority = NULL;
874 priority = s->priority;
876 if (s->priority_prefix &&
879 p[1] >= '0' && p[1] <= '7' &&
882 priority = p[1] - '0';
890 if (asprintf(&syslog_priority, "PRIORITY=%i", priority) >= 0)
891 IOVEC_SET_STRING(iovec[n++], syslog_priority);
893 tag_len = s->tag ? strlen(s->tag) + 2: 0;
894 message = malloc(8 + tag_len + l);
896 memcpy(message, "MESSAGE=", 8);
899 memcpy(message+8, s->tag, tag_len-2);
900 memcpy(message+8+tag_len-2, ": ", 2);
903 memcpy(message+8+tag_len, p, l);
904 iovec[n].iov_base = message;
905 iovec[n].iov_len = 8+tag_len+l;
909 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, priority);
911 if (s->tee_console) {
914 console = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
918 IOVEC_SET_STRING(iovec[n++], s->tag);
919 IOVEC_SET_STRING(iovec[n++], ": ");
922 iovec[n].iov_base = (void*) p;
923 iovec[n].iov_len = l;
926 IOVEC_SET_STRING(iovec[n++], (char*) "\n");
928 writev(console, iovec, n);
933 free(syslog_priority);
938 static int stdout_stream_line(StdoutStream *s, const char *p, size_t l) {
942 while (l > 0 && strchr(WHITESPACE, *p)) {
947 while (l > 0 && strchr(WHITESPACE, *(p+l-1)))
952 case STDOUT_STREAM_TAG:
955 s->tag = strndup(p, l);
957 log_error("Out of memory");
962 s->state = STDOUT_STREAM_PRIORITY;
965 case STDOUT_STREAM_PRIORITY:
966 if (l != 1 || *p < '0' || *p > '7') {
967 log_warning("Failed to parse log priority line.");
971 s->priority = *p - '0';
972 s->state = STDOUT_STREAM_PRIORITY_PREFIX;
975 case STDOUT_STREAM_PRIORITY_PREFIX:
976 if (l != 1 || *p < '0' || *p > '1') {
977 log_warning("Failed to parse priority prefix line.");
981 s->priority_prefix = *p - '0';
982 s->state = STDOUT_STREAM_TEE_CONSOLE;
985 case STDOUT_STREAM_TEE_CONSOLE:
986 if (l != 1 || *p < '0' || *p > '1') {
987 log_warning("Failed to parse tee to console line.");
991 s->tee_console = *p - '0';
992 s->state = STDOUT_STREAM_RUNNING;
995 case STDOUT_STREAM_RUNNING:
996 return stdout_stream_log(s, p, l);
999 assert_not_reached("Unknown stream state");
1002 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1010 remaining = s->length;
1015 end = memchr(p, '\n', remaining);
1017 if (remaining >= LINE_MAX) {
1025 r = stdout_stream_line(s, p, end - p);
1033 if (force_flush && remaining > 0) {
1034 r = stdout_stream_line(s, p, remaining);
1042 if (p > s->buffer) {
1043 memmove(s->buffer, p, remaining);
1044 s->length = remaining;
1050 static int stdout_stream_process(StdoutStream *s) {
1056 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1059 if (errno == EAGAIN)
1062 log_warning("Failed to read from stream: %m");
1067 r = stdout_stream_scan(s, true);
1075 r = stdout_stream_scan(s, false);
1083 static void stdout_stream_free(StdoutStream *s) {
1087 assert(s->server->n_stdout_streams > 0);
1088 s->server->n_stdout_streams --;
1089 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1094 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1096 close_nointr_nofail(s->fd);
1103 static int stdout_stream_new(Server *s) {
1104 StdoutStream *stream;
1107 struct epoll_event ev;
1111 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1113 if (errno == EAGAIN)
1116 log_error("Failed to accept stdout connection: %m");
1120 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1121 log_warning("Too many stdout streams, refusing connection.");
1122 close_nointr_nofail(fd);
1126 stream = new0(StdoutStream, 1);
1128 log_error("Out of memory.");
1129 close_nointr_nofail(fd);
1135 len = sizeof(stream->ucred);
1136 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1137 log_error("Failed to determine peer credentials: %m");
1142 if (shutdown(fd, SHUT_WR) < 0) {
1143 log_error("Failed to shutdown writing side of socket: %m");
1149 ev.data.ptr = stream;
1150 ev.events = EPOLLIN;
1151 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1152 log_error("Failed to add stream to event loop: %m");
1158 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1159 s->n_stdout_streams ++;
1164 stdout_stream_free(stream);
1168 static int system_journal_open(Server *s) {
1174 r = sd_id128_get_machine(&machine);
1178 sd_id128_to_string(machine, ids);
1180 if (!s->system_journal) {
1182 /* First try to create the machine path, but not the prefix */
1183 fn = strappend("/var/log/journal/", ids);
1186 (void) mkdir(fn, 0755);
1189 /* The create the system journal file */
1190 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1194 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1198 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1200 s->system_journal->metrics = s->system_metrics;
1201 s->system_journal->compress = s->compress;
1203 fix_perms(s->system_journal, 0);
1206 if (r != -ENOENT && r != -EROFS)
1207 log_warning("Failed to open system journal: %s", strerror(-r));
1213 if (!s->runtime_journal) {
1215 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1219 if (s->system_journal) {
1221 /* Try to open the runtime journal, but only
1222 * if it already exists, so that we can flush
1223 * it into the system journal */
1225 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1230 log_warning("Failed to open runtime journal: %s", strerror(-r));
1237 /* OK, we really need the runtime journal, so create
1238 * it if necessary. */
1240 (void) mkdir_parents(fn, 0755);
1241 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1245 log_error("Failed to open runtime journal: %s", strerror(-r));
1250 if (s->runtime_journal) {
1251 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1253 s->runtime_journal->metrics = s->runtime_metrics;
1254 s->runtime_journal->compress = s->compress;
1256 fix_perms(s->runtime_journal, 0);
1263 static int server_flush_to_var(Server *s) {
1264 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1273 if (!s->runtime_journal)
1276 ts = now(CLOCK_MONOTONIC);
1277 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1280 s->var_available_timestamp = ts;
1282 system_journal_open(s);
1284 if (!s->system_journal)
1287 r = sd_id128_get_machine(&machine);
1289 log_error("Failed to get machine id: %s", strerror(-r));
1293 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1295 log_error("Failed to read runtime journal: %s", strerror(-r));
1299 SD_JOURNAL_FOREACH(j) {
1302 f = j->current_file;
1303 assert(f && f->current_offset > 0);
1305 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1307 log_error("Can't read entry: %s", strerror(-r));
1311 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1313 log_info("Allocation limit reached.");
1315 journal_file_post_change(s->system_journal);
1319 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1323 log_error("Can't write entry: %s", strerror(-r));
1329 journal_file_post_change(s->system_journal);
1331 journal_file_close(s->runtime_journal);
1332 s->runtime_journal = NULL;
1335 sd_id128_to_string(machine, path + 17);
1336 rm_rf(path, false, true, false);
1342 static void forward_syslog(Server *s, const void *buffer, size_t length, struct ucred *ucred, struct timeval *tv) {
1343 struct msghdr msghdr;
1345 struct cmsghdr *cmsg;
1347 struct cmsghdr cmsghdr;
1348 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1349 CMSG_SPACE(sizeof(struct timeval))];
1351 union sockaddr_union sa;
1358 iovec.iov_base = (void*) buffer;
1359 iovec.iov_len = length;
1360 msghdr.msg_iov = &iovec;
1361 msghdr.msg_iovlen = 1;
1364 sa.un.sun_family = AF_UNIX;
1365 strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
1366 msghdr.msg_name = &sa;
1367 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
1370 msghdr.msg_control = &control;
1371 msghdr.msg_controllen = sizeof(control);
1373 cmsg = CMSG_FIRSTHDR(&msghdr);
1374 cmsg->cmsg_level = SOL_SOCKET;
1375 cmsg->cmsg_type = SCM_CREDENTIALS;
1376 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
1377 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
1378 msghdr.msg_controllen = cmsg->cmsg_len;
1380 /* Forward the syslog message we received via /dev/log to
1381 * /run/systemd/syslog. Unfortunately we currently can't set
1382 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
1384 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
1387 if (errno == ESRCH) {
1390 /* Hmm, presumably the sender process vanished
1391 * by now, so let's fix it as good as we
1396 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
1398 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
1402 log_debug("Failed to forward syslog message: %m");
1405 static int process_event(Server *s, struct epoll_event *ev) {
1408 if (ev->data.fd == s->signal_fd) {
1409 struct signalfd_siginfo sfsi;
1412 if (ev->events != EPOLLIN) {
1413 log_info("Got invalid event from epoll.");
1417 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
1418 if (n != sizeof(sfsi)) {
1423 if (errno == EINTR || errno == EAGAIN)
1429 if (sfsi.ssi_signo == SIGUSR1) {
1430 server_flush_to_var(s);
1434 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
1437 } else if (ev->data.fd == s->native_fd ||
1438 ev->data.fd == s->syslog_fd) {
1440 if (ev->events != EPOLLIN) {
1441 log_info("Got invalid event from epoll.");
1446 struct msghdr msghdr;
1448 struct ucred *ucred = NULL;
1449 struct timeval *tv = NULL;
1450 struct cmsghdr *cmsg;
1452 struct cmsghdr cmsghdr;
1453 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1454 CMSG_SPACE(sizeof(struct timeval))];
1459 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
1460 log_error("SIOCINQ failed: %m");
1467 if (s->buffer_size < (size_t) v) {
1471 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
1472 b = realloc(s->buffer, l+1);
1475 log_error("Couldn't increase buffer.");
1484 iovec.iov_base = s->buffer;
1485 iovec.iov_len = s->buffer_size;
1489 msghdr.msg_iov = &iovec;
1490 msghdr.msg_iovlen = 1;
1491 msghdr.msg_control = &control;
1492 msghdr.msg_controllen = sizeof(control);
1494 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
1497 if (errno == EINTR || errno == EAGAIN)
1500 log_error("recvmsg() failed: %m");
1504 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
1506 if (cmsg->cmsg_level == SOL_SOCKET &&
1507 cmsg->cmsg_type == SCM_CREDENTIALS &&
1508 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
1509 ucred = (struct ucred*) CMSG_DATA(cmsg);
1510 else if (cmsg->cmsg_level == SOL_SOCKET &&
1511 cmsg->cmsg_type == SO_TIMESTAMP &&
1512 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
1513 tv = (struct timeval*) CMSG_DATA(cmsg);
1516 if (ev->data.fd == s->syslog_fd) {
1519 e = memchr(s->buffer, '\n', n);
1525 forward_syslog(s, s->buffer, n, ucred, tv);
1526 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
1528 process_native_message(s, s->buffer, n, ucred, tv);
1533 } else if (ev->data.fd == s->stdout_fd) {
1535 if (ev->events != EPOLLIN) {
1536 log_info("Got invalid event from epoll.");
1540 stdout_stream_new(s);
1544 StdoutStream *stream;
1546 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
1547 log_info("Got invalid event from epoll.");
1551 /* If it is none of the well-known fds, it must be an
1552 * stdout stream fd. Note that this is a bit ugly here
1553 * (since we rely that none of the well-known fds
1554 * could be interpreted as pointer), but nonetheless
1555 * safe, since the well-known fds would never get an
1556 * fd > 4096, i.e. beyond the first memory page */
1558 stream = ev->data.ptr;
1560 if (stdout_stream_process(stream) <= 0)
1561 stdout_stream_free(stream);
1566 log_error("Unknown event.");
1570 static int open_syslog_socket(Server *s) {
1571 union sockaddr_union sa;
1573 struct epoll_event ev;
1578 if (s->syslog_fd < 0) {
1580 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1581 if (s->syslog_fd < 0) {
1582 log_error("socket() failed: %m");
1587 sa.un.sun_family = AF_UNIX;
1588 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
1590 unlink(sa.un.sun_path);
1592 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1594 log_error("bind() failed: %m");
1598 chmod(sa.un.sun_path, 0666);
1602 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1604 log_error("SO_PASSCRED failed: %m");
1609 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1611 log_error("SO_TIMESTAMP failed: %m");
1615 /* Since we use the same socket for forwarding this to some
1616 * other syslog implementation, make sure we don't hang
1618 timeval_store(&tv, SYSLOG_TIMEOUT_USEC);
1619 if (setsockopt(s->syslog_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) {
1620 log_error("SO_SNDTIMEO failed: %m");
1625 ev.events = EPOLLIN;
1626 ev.data.fd = s->syslog_fd;
1627 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
1628 log_error("Failed to add syslog server fd to epoll object: %m");
1635 static int open_native_socket(Server*s) {
1636 union sockaddr_union sa;
1638 struct epoll_event ev;
1642 if (s->native_fd < 0) {
1644 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1645 if (s->native_fd < 0) {
1646 log_error("socket() failed: %m");
1651 sa.un.sun_family = AF_UNIX;
1652 strncpy(sa.un.sun_path, "/run/systemd/journal", sizeof(sa.un.sun_path));
1654 unlink(sa.un.sun_path);
1656 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1658 log_error("bind() failed: %m");
1662 chmod(sa.un.sun_path, 0666);
1666 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1668 log_error("SO_PASSCRED failed: %m");
1673 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1675 log_error("SO_TIMESTAMP failed: %m");
1680 ev.events = EPOLLIN;
1681 ev.data.fd = s->native_fd;
1682 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
1683 log_error("Failed to add native server fd to epoll object: %m");
1690 static int open_stdout_socket(Server *s) {
1691 union sockaddr_union sa;
1693 struct epoll_event ev;
1697 if (s->stdout_fd < 0) {
1699 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1700 if (s->stdout_fd < 0) {
1701 log_error("socket() failed: %m");
1706 sa.un.sun_family = AF_UNIX;
1707 strncpy(sa.un.sun_path, "/run/systemd/stdout", sizeof(sa.un.sun_path));
1709 unlink(sa.un.sun_path);
1711 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1713 log_error("bind() failed: %m");
1717 chmod(sa.un.sun_path, 0666);
1719 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
1720 log_error("liste() failed: %m");
1726 ev.events = EPOLLIN;
1727 ev.data.fd = s->stdout_fd;
1728 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
1729 log_error("Failed to add stdout server fd to epoll object: %m");
1736 static int open_signalfd(Server *s) {
1738 struct epoll_event ev;
1742 assert_se(sigemptyset(&mask) == 0);
1743 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
1744 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1746 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1747 if (s->signal_fd < 0) {
1748 log_error("signalfd(): %m");
1753 ev.events = EPOLLIN;
1754 ev.data.fd = s->signal_fd;
1756 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
1757 log_error("epoll_ctl(): %m");
1764 static int server_init(Server *s) {
1770 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = -1;
1773 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
1774 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
1776 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
1777 if (!s->user_journals) {
1778 log_error("Out of memory.");
1782 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1783 if (s->epoll_fd < 0) {
1784 log_error("Failed to create epoll object: %m");
1788 n = sd_listen_fds(true);
1790 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
1794 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
1796 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/native", 0) > 0) {
1798 if (s->native_fd >= 0) {
1799 log_error("Too many native sockets passed.");
1805 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/stdout", 0) > 0) {
1807 if (s->stdout_fd >= 0) {
1808 log_error("Too many stdout sockets passed.");
1814 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
1816 if (s->syslog_fd >= 0) {
1817 log_error("Too many /dev/log sockets passed.");
1824 log_error("Unknown socket passed.");
1829 r = open_syslog_socket(s);
1833 r = open_native_socket(s);
1837 r = open_stdout_socket(s);
1841 r = system_journal_open(s);
1845 r = open_signalfd(s);
1849 s->rate_limit = journal_rate_limit_new(DEFAULT_RATE_LIMIT_INTERVAL, DEFAULT_RATE_LIMIT_BURST);
1856 static void server_done(Server *s) {
1860 while (s->stdout_streams)
1861 stdout_stream_free(s->stdout_streams);
1863 if (s->system_journal)
1864 journal_file_close(s->system_journal);
1866 if (s->runtime_journal)
1867 journal_file_close(s->runtime_journal);
1869 while ((f = hashmap_steal_first(s->user_journals)))
1870 journal_file_close(f);
1872 hashmap_free(s->user_journals);
1874 if (s->epoll_fd >= 0)
1875 close_nointr_nofail(s->epoll_fd);
1877 if (s->signal_fd >= 0)
1878 close_nointr_nofail(s->signal_fd);
1880 if (s->syslog_fd >= 0)
1881 close_nointr_nofail(s->syslog_fd);
1883 if (s->native_fd >= 0)
1884 close_nointr_nofail(s->native_fd);
1886 if (s->stdout_fd >= 0)
1887 close_nointr_nofail(s->stdout_fd);
1890 journal_rate_limit_free(s->rate_limit);
1895 int main(int argc, char *argv[]) {
1899 /* if (getppid() != 1) { */
1900 /* log_error("This program should be invoked by init only."); */
1901 /* return EXIT_FAILURE; */
1905 log_error("This program does not take arguments.");
1906 return EXIT_FAILURE;
1909 log_set_target(LOG_TARGET_CONSOLE);
1910 log_parse_environment();
1915 r = server_init(&server);
1919 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
1923 "STATUS=Processing requests...");
1925 server_vacuum(&server);
1926 server_flush_to_var(&server);
1929 struct epoll_event event;
1931 r = epoll_wait(server.epoll_fd, &event, 1, -1);
1937 log_error("epoll_wait() failed: %m");
1943 r = process_event(&server, &event);
1950 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
1954 "STATUS=Shutting down...");
1956 server_done(&server);
1958 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;