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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser 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 <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <sys/statvfs.h>
35 #include <systemd/sd-journal.h>
36 #include <systemd/sd-messages.h>
37 #include <systemd/sd-daemon.h>
40 #include <systemd/sd-login.h>
45 #include "journal-file.h"
46 #include "socket-util.h"
47 #include "cgroup-util.h"
51 #include "conf-parser.h"
52 #include "journal-rate-limit.h"
53 #include "journal-internal.h"
54 #include "journal-vacuum.h"
55 #include "journal-authenticate.h"
57 #include "journald-kmsg.h"
58 #include "journald-syslog.h"
62 #include <acl/libacl.h>
67 #include <selinux/selinux.h>
70 #define USER_JOURNALS_MAX 1024
71 #define STDOUT_STREAMS_MAX 4096
73 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
74 #define DEFAULT_RATE_LIMIT_BURST 200
76 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
78 #define ENTRY_SIZE_MAX (1024*1024*32)
80 typedef enum StdoutStreamState {
81 STDOUT_STREAM_IDENTIFIER,
82 STDOUT_STREAM_UNIT_ID,
83 STDOUT_STREAM_PRIORITY,
84 STDOUT_STREAM_LEVEL_PREFIX,
85 STDOUT_STREAM_FORWARD_TO_SYSLOG,
86 STDOUT_STREAM_FORWARD_TO_KMSG,
87 STDOUT_STREAM_FORWARD_TO_CONSOLE,
93 StdoutStreamState state;
99 security_context_t security_context;
106 bool forward_to_syslog:1;
107 bool forward_to_kmsg:1;
108 bool forward_to_console:1;
110 char buffer[LINE_MAX+1];
113 LIST_FIELDS(StdoutStream, stdout_stream);
116 static const char* const storage_table[] = {
117 [STORAGE_AUTO] = "auto",
118 [STORAGE_VOLATILE] = "volatile",
119 [STORAGE_PERSISTENT] = "persistent",
120 [STORAGE_NONE] = "none"
123 DEFINE_STRING_TABLE_LOOKUP(storage, Storage);
124 DEFINE_CONFIG_PARSE_ENUM(config_parse_storage, storage, Storage, "Failed to parse storage setting");
126 static uint64_t available_space(Server *s) {
131 uint64_t sum = 0, avail = 0, ss_avail = 0;
137 ts = now(CLOCK_MONOTONIC);
139 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
140 return s->cached_available_space;
142 r = sd_id128_get_machine(&machine);
146 if (s->system_journal) {
147 f = "/var/log/journal/";
148 m = &s->system_metrics;
150 f = "/run/log/journal/";
151 m = &s->runtime_metrics;
156 p = strappend(f, sd_id128_to_string(machine, ids));
166 if (fstatvfs(dirfd(d), &ss) < 0)
171 struct dirent buf, *de;
173 r = readdir_r(d, &buf, &de);
180 if (!endswith(de->d_name, ".journal") &&
181 !endswith(de->d_name, ".journal~"))
184 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
187 if (!S_ISREG(st.st_mode))
190 sum += (uint64_t) st.st_blocks * 512UL;
193 avail = sum >= m->max_use ? 0 : m->max_use - sum;
195 ss_avail = ss.f_bsize * ss.f_bavail;
197 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
199 if (ss_avail < avail)
202 s->cached_available_space = avail;
203 s->cached_available_space_timestamp = ts;
211 static void server_read_file_gid(Server *s) {
212 const char *adm = "adm";
217 if (s->file_gid_valid)
220 r = get_group_creds(&adm, &s->file_gid);
222 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
224 /* if we couldn't read the gid, then it will be 0, but that's
225 * fine and we shouldn't try to resolve the group again, so
226 * let's just pretend it worked right-away. */
227 s->file_gid_valid = true;
230 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
235 acl_permset_t permset;
240 server_read_file_gid(s);
242 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
244 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
250 acl = acl_get_fd(f->fd);
252 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
256 r = acl_find_uid(acl, uid, &entry);
259 if (acl_create_entry(&acl, &entry) < 0 ||
260 acl_set_tag_type(entry, ACL_USER) < 0 ||
261 acl_set_qualifier(entry, &uid) < 0) {
262 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
267 if (acl_get_permset(entry, &permset) < 0 ||
268 acl_add_perm(permset, ACL_READ) < 0 ||
269 acl_calc_mask(&acl) < 0) {
270 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
274 if (acl_set_fd(f->fd, acl) < 0)
275 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
282 static JournalFile* find_journal(Server *s, uid_t uid) {
290 /* We split up user logs only on /var, not on /run. If the
291 * runtime file is open, we write to it exclusively, in order
292 * to guarantee proper order as soon as we flush /run to
293 * /var and close the runtime file. */
295 if (s->runtime_journal)
296 return s->runtime_journal;
299 return s->system_journal;
301 r = sd_id128_get_machine(&machine);
303 return s->system_journal;
305 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
309 if (asprintf(&p, "/var/log/journal/" SD_ID128_FORMAT_STR "/user-%lu.journal",
310 SD_ID128_FORMAT_VAL(machine), (unsigned long) uid) < 0)
311 return s->system_journal;
313 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
314 /* Too many open? Then let's close one */
315 f = hashmap_steal_first(s->user_journals);
317 journal_file_close(f);
320 r = journal_file_open_reliably(p, O_RDWR|O_CREAT, 0640, s->compress, s->seal, &s->system_metrics, s->mmap, s->system_journal, &f);
324 return s->system_journal;
326 server_fix_perms(s, f, uid);
328 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
330 journal_file_close(f);
331 return s->system_journal;
337 static void server_rotate(Server *s) {
343 log_info("Rotating...");
345 if (s->runtime_journal) {
346 r = journal_file_rotate(&s->runtime_journal, s->compress, false);
348 if (s->runtime_journal)
349 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
351 log_error("Failed to create new runtime journal: %s", strerror(-r));
353 server_fix_perms(s, s->runtime_journal, 0);
356 if (s->system_journal) {
357 r = journal_file_rotate(&s->system_journal, s->compress, s->seal);
359 if (s->system_journal)
360 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
362 log_error("Failed to create new system journal: %s", strerror(-r));
365 server_fix_perms(s, s->system_journal, 0);
368 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
369 r = journal_file_rotate(&f, s->compress, s->seal);
372 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
374 log_error("Failed to create user journal: %s", strerror(-r));
376 hashmap_replace(s->user_journals, k, f);
377 server_fix_perms(s, s->system_journal, PTR_TO_UINT32(k));
382 static void server_vacuum(Server *s) {
388 log_info("Vacuuming...");
390 r = sd_id128_get_machine(&machine);
392 log_error("Failed to get machine ID: %s", strerror(-r));
396 sd_id128_to_string(machine, ids);
398 if (s->system_journal) {
399 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
404 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
405 if (r < 0 && r != -ENOENT)
406 log_error("Failed to vacuum %s: %s", p, strerror(-r));
410 if (s->runtime_journal) {
411 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
416 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
417 if (r < 0 && r != -ENOENT)
418 log_error("Failed to vacuum %s: %s", p, strerror(-r));
422 s->cached_available_space_timestamp = 0;
425 static char *shortened_cgroup_path(pid_t pid) {
427 char *process_path, *init_path, *path;
431 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
435 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
441 if (endswith(init_path, "/system"))
442 init_path[strlen(init_path) - 7] = 0;
443 else if (streq(init_path, "/"))
446 if (startswith(process_path, init_path)) {
449 p = strdup(process_path + strlen(init_path));
467 static void write_to_journal(Server *s, uid_t uid, struct iovec *iovec, unsigned n) {
469 bool vacuumed = false;
476 f = find_journal(s, uid);
480 if (journal_file_rotate_suggested(f)) {
481 log_info("Journal header limits reached or header out-of-date, rotating.");
486 f = find_journal(s, uid);
492 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
497 (r != -E2BIG && /* hit limit */
498 r != -EFBIG && /* hit fs limit */
499 r != -EDQUOT && /* quota hit */
500 r != -ENOSPC && /* disk full */
501 r != -EBADMSG && /* corrupted */
502 r != -ENODATA && /* truncated */
503 r != -EHOSTDOWN && /* other machine */
504 r != -EPROTONOSUPPORT && /* unsupported feature */
505 r != -EBUSY && /* unclean shutdown */
506 r != -ESHUTDOWN /* already archived */)) {
507 log_error("Failed to write entry, ignoring: %s", strerror(-r));
511 if (r == -E2BIG || r == -EFBIG || r == EDQUOT || r == ENOSPC)
512 log_info("Allocation limit reached, rotating.");
513 else if (r == -EHOSTDOWN)
514 log_info("Journal file from other machine, rotating.");
515 else if (r == -EBUSY)
516 log_info("Unlcean shutdown, rotating.");
518 log_warning("Journal file corrupted, rotating.");
524 f = find_journal(s, uid);
528 log_info("Retrying write.");
532 static void dispatch_message_real(
534 struct iovec *iovec, unsigned n, unsigned m,
537 const char *label, size_t label_len,
538 const char *unit_id) {
540 char *pid = NULL, *uid = NULL, *gid = NULL,
541 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
542 *comm = NULL, *cmdline = NULL, *hostname = NULL,
543 *audit_session = NULL, *audit_loginuid = NULL,
544 *exe = NULL, *cgroup = NULL, *session = NULL,
545 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
551 uid_t loginuid = 0, realuid = 0;
556 assert(n + N_IOVEC_META_FIELDS <= m);
564 realuid = ucred->uid;
566 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
567 IOVEC_SET_STRING(iovec[n++], pid);
569 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
570 IOVEC_SET_STRING(iovec[n++], uid);
572 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
573 IOVEC_SET_STRING(iovec[n++], gid);
575 r = get_process_comm(ucred->pid, &t);
577 comm = strappend("_COMM=", t);
581 IOVEC_SET_STRING(iovec[n++], comm);
584 r = get_process_exe(ucred->pid, &t);
586 exe = strappend("_EXE=", t);
590 IOVEC_SET_STRING(iovec[n++], exe);
593 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
595 cmdline = strappend("_CMDLINE=", t);
599 IOVEC_SET_STRING(iovec[n++], cmdline);
602 r = audit_session_from_pid(ucred->pid, &audit);
604 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
605 IOVEC_SET_STRING(iovec[n++], audit_session);
607 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
609 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
610 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
612 t = shortened_cgroup_path(ucred->pid);
614 cgroup = strappend("_SYSTEMD_CGROUP=", t);
618 IOVEC_SET_STRING(iovec[n++], cgroup);
622 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
623 session = strappend("_SYSTEMD_SESSION=", t);
627 IOVEC_SET_STRING(iovec[n++], session);
630 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
631 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
632 IOVEC_SET_STRING(iovec[n++], owner_uid);
635 if (cg_pid_get_unit(ucred->pid, &t) >= 0) {
636 unit = strappend("_SYSTEMD_UNIT=", t);
639 unit = strappend("_SYSTEMD_UNIT=", unit_id);
642 IOVEC_SET_STRING(iovec[n++], unit);
646 selinux_context = malloc(sizeof("_SELINUX_CONTEXT=") + label_len);
647 if (selinux_context) {
648 memcpy(selinux_context, "_SELINUX_CONTEXT=", sizeof("_SELINUX_CONTEXT=")-1);
649 memcpy(selinux_context+sizeof("_SELINUX_CONTEXT=")-1, label, label_len);
650 selinux_context[sizeof("_SELINUX_CONTEXT=")-1+label_len] = 0;
651 IOVEC_SET_STRING(iovec[n++], selinux_context);
654 security_context_t con;
656 if (getpidcon(ucred->pid, &con) >= 0) {
657 selinux_context = strappend("_SELINUX_CONTEXT=", con);
659 IOVEC_SET_STRING(iovec[n++], selinux_context);
668 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
669 (unsigned long long) timeval_load(tv)) >= 0)
670 IOVEC_SET_STRING(iovec[n++], source_time);
673 /* Note that strictly speaking storing the boot id here is
674 * redundant since the entry includes this in-line
675 * anyway. However, we need this indexed, too. */
676 r = sd_id128_get_boot(&id);
678 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
679 IOVEC_SET_STRING(iovec[n++], boot_id);
681 r = sd_id128_get_machine(&id);
683 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
684 IOVEC_SET_STRING(iovec[n++], machine_id);
686 t = gethostname_malloc();
688 hostname = strappend("_HOSTNAME=", t);
691 IOVEC_SET_STRING(iovec[n++], hostname);
696 write_to_journal(s, realuid == 0 ? 0 : loginuid, iovec, n);
709 free(audit_loginuid);
714 free(selinux_context);
717 void server_driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
718 char mid[11 + 32 + 1];
719 char buffer[16 + LINE_MAX + 1];
720 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
728 IOVEC_SET_STRING(iovec[n++], "PRIORITY=6");
729 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
731 memcpy(buffer, "MESSAGE=", 8);
732 va_start(ap, format);
733 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
735 char_array_0(buffer);
736 IOVEC_SET_STRING(iovec[n++], buffer);
738 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
740 IOVEC_SET_STRING(iovec[n++], mid);
743 ucred.pid = getpid();
744 ucred.uid = getuid();
745 ucred.gid = getgid();
747 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0, NULL);
750 void server_dispatch_message(
752 struct iovec *iovec, unsigned n, unsigned m,
755 const char *label, size_t label_len,
760 char *path = NULL, *c;
763 assert(iovec || n == 0);
768 if (LOG_PRI(priority) > s->max_level_store)
774 path = shortened_cgroup_path(ucred->pid);
778 /* example: /user/lennart/3/foobar
779 * /system/dbus.service/foobar
781 * So let's cut of everything past the third /, since that is
782 * wher user directories start */
784 c = strchr(path, '/');
786 c = strchr(c+1, '/');
788 c = strchr(c+1, '/');
794 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
801 /* Write a suppression message if we suppressed something */
803 server_driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
808 dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len, unit_id);
811 void server_forward_console(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
812 struct iovec iovec[4];
815 char *ident_buf = NULL;
821 if (LOG_PRI(priority) > s->max_level_console)
824 /* First: identifier and PID */
827 get_process_comm(ucred->pid, &ident_buf);
828 identifier = ident_buf;
831 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
832 char_array_0(header_pid);
835 IOVEC_SET_STRING(iovec[n++], identifier);
837 IOVEC_SET_STRING(iovec[n++], header_pid);
838 } else if (identifier) {
839 IOVEC_SET_STRING(iovec[n++], identifier);
840 IOVEC_SET_STRING(iovec[n++], ": ");
844 IOVEC_SET_STRING(iovec[n++], message);
845 IOVEC_SET_STRING(iovec[n++], "\n");
847 tty = s->tty_path ? s->tty_path : "/dev/console";
849 fd = open_terminal(tty, O_WRONLY|O_NOCTTY|O_CLOEXEC);
851 log_debug("Failed to open %s for logging: %s", tty, strerror(errno));
855 if (writev(fd, iovec, n) < 0)
856 log_debug("Failed to write to %s for logging: %s", tty, strerror(errno));
858 close_nointr_nofail(fd);
866 static bool valid_user_field(const char *p, size_t l) {
869 /* We kinda enforce POSIX syntax recommendations for
870 environment variables here, but make a couple of additional
873 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
875 /* No empty field names */
879 /* Don't allow names longer than 64 chars */
883 /* Variables starting with an underscore are protected */
887 /* Don't allow digits as first character */
888 if (p[0] >= '0' && p[0] <= '9')
891 /* Only allow A-Z0-9 and '_' */
892 for (a = p; a < p + l; a++)
893 if (!((*a >= 'A' && *a <= 'Z') ||
894 (*a >= '0' && *a <= '9') ||
901 static void process_native_message(
903 const void *buffer, size_t buffer_size,
906 const char *label, size_t label_len) {
908 struct iovec *iovec = NULL;
909 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
912 int priority = LOG_INFO;
913 char *identifier = NULL, *message = NULL;
916 assert(buffer || buffer_size == 0);
919 remaining = buffer_size;
921 while (remaining > 0) {
924 e = memchr(p, '\n', remaining);
927 /* Trailing noise, let's ignore it, and flush what we collected */
928 log_debug("Received message with trailing noise, ignoring.");
933 /* Entry separator */
934 server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority);
943 if (*p == '.' || *p == '#') {
944 /* Ignore control commands for now, and
946 remaining -= (e - p) + 1;
951 /* A property follows */
953 if (n+N_IOVEC_META_FIELDS >= m) {
957 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
958 c = realloc(iovec, u * sizeof(struct iovec));
968 q = memchr(p, '=', e - p);
970 if (valid_user_field(p, q - p)) {
975 /* If the field name starts with an
976 * underscore, skip the variable,
977 * since that indidates a trusted
979 iovec[n].iov_base = (char*) p;
980 iovec[n].iov_len = l;
983 /* We need to determine the priority
984 * of this entry for the rate limiting
987 memcmp(p, "PRIORITY=", 9) == 0 &&
988 p[9] >= '0' && p[9] <= '9')
989 priority = (priority & LOG_FACMASK) | (p[9] - '0');
992 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
993 p[16] >= '0' && p[16] <= '9')
994 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
997 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
998 p[16] >= '0' && p[16] <= '9' &&
999 p[17] >= '0' && p[17] <= '9')
1000 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1003 memcmp(p, "SYSLOG_IDENTIFIER=", 18) == 0) {
1006 t = strndup(p + 18, l - 18);
1011 } else if (l >= 8 &&
1012 memcmp(p, "MESSAGE=", 8) == 0) {
1015 t = strndup(p + 8, l - 8);
1023 remaining -= (e - p) + 1;
1031 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1032 log_debug("Failed to parse message, ignoring.");
1036 memcpy(&l_le, e + 1, sizeof(uint64_t));
1039 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1040 e[1+sizeof(uint64_t)+l] != '\n') {
1041 log_debug("Failed to parse message, ignoring.");
1045 k = malloc((e - p) + 1 + l);
1051 memcpy(k, p, e - p);
1053 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1055 if (valid_user_field(p, e - p)) {
1056 iovec[n].iov_base = k;
1057 iovec[n].iov_len = (e - p) + 1 + l;
1062 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1063 p = e + 1 + sizeof(uint64_t) + l + 1;
1071 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1074 if (s->forward_to_syslog)
1075 server_forward_syslog(s, priority, identifier, message, ucred, tv);
1077 if (s->forward_to_kmsg)
1078 server_forward_kmsg(s, priority, identifier, message, ucred);
1080 if (s->forward_to_console)
1081 server_forward_console(s, priority, identifier, message, ucred);
1084 server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority);
1087 for (j = 0; j < n; j++) {
1091 if (iovec[j].iov_base < buffer ||
1092 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1093 free(iovec[j].iov_base);
1101 static void process_native_file(
1104 struct ucred *ucred,
1106 const char *label, size_t label_len) {
1115 /* Data is in the passed file, since it didn't fit in a
1116 * datagram. We can't map the file here, since clients might
1117 * then truncate it and trigger a SIGBUS for us. So let's
1118 * stupidly read it */
1120 if (fstat(fd, &st) < 0) {
1121 log_error("Failed to stat passed file, ignoring: %m");
1125 if (!S_ISREG(st.st_mode)) {
1126 log_error("File passed is not regular. Ignoring.");
1130 if (st.st_size <= 0)
1133 if (st.st_size > ENTRY_SIZE_MAX) {
1134 log_error("File passed too large. Ignoring.");
1138 p = malloc(st.st_size);
1144 n = pread(fd, p, st.st_size, 0);
1146 log_error("Failed to read file, ignoring: %s", strerror(-n));
1148 process_native_message(s, p, n, ucred, tv, label, label_len);
1153 static int stdout_stream_log(StdoutStream *s, const char *p) {
1154 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1155 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1159 size_t label_len = 0;
1167 priority = s->priority;
1169 if (s->level_prefix)
1170 syslog_parse_priority((char**) &p, &priority);
1172 if (s->forward_to_syslog || s->server->forward_to_syslog)
1173 server_forward_syslog(s->server, syslog_fixup_facility(priority), s->identifier, p, &s->ucred, NULL);
1175 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1176 server_forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1178 if (s->forward_to_console || s->server->forward_to_console)
1179 server_forward_console(s->server, priority, s->identifier, p, &s->ucred);
1181 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1183 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1184 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1186 if (priority & LOG_FACMASK)
1187 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1188 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1190 if (s->identifier) {
1191 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1192 if (syslog_identifier)
1193 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1196 message = strappend("MESSAGE=", p);
1198 IOVEC_SET_STRING(iovec[n++], message);
1201 if (s->security_context) {
1202 label = (char*) s->security_context;
1203 label_len = strlen((char*) s->security_context);
1207 server_dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, s->unit_id, priority);
1210 free(syslog_priority);
1211 free(syslog_facility);
1212 free(syslog_identifier);
1217 static int stdout_stream_line(StdoutStream *s, char *p) {
1227 case STDOUT_STREAM_IDENTIFIER:
1229 s->identifier = NULL;
1231 s->identifier = strdup(p);
1236 s->state = STDOUT_STREAM_UNIT_ID;
1239 case STDOUT_STREAM_UNIT_ID:
1240 if (s->ucred.uid == 0) {
1244 s->unit_id = strdup(p);
1250 s->state = STDOUT_STREAM_PRIORITY;
1253 case STDOUT_STREAM_PRIORITY:
1254 r = safe_atoi(p, &s->priority);
1255 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1256 log_warning("Failed to parse log priority line.");
1260 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1263 case STDOUT_STREAM_LEVEL_PREFIX:
1264 r = parse_boolean(p);
1266 log_warning("Failed to parse level prefix line.");
1270 s->level_prefix = !!r;
1271 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1274 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1275 r = parse_boolean(p);
1277 log_warning("Failed to parse forward to syslog line.");
1281 s->forward_to_syslog = !!r;
1282 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1285 case STDOUT_STREAM_FORWARD_TO_KMSG:
1286 r = parse_boolean(p);
1288 log_warning("Failed to parse copy to kmsg line.");
1292 s->forward_to_kmsg = !!r;
1293 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1296 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1297 r = parse_boolean(p);
1299 log_warning("Failed to parse copy to console line.");
1303 s->forward_to_console = !!r;
1304 s->state = STDOUT_STREAM_RUNNING;
1307 case STDOUT_STREAM_RUNNING:
1308 return stdout_stream_log(s, p);
1311 assert_not_reached("Unknown stream state");
1314 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1322 remaining = s->length;
1327 end = memchr(p, '\n', remaining);
1330 else if (remaining >= sizeof(s->buffer) - 1) {
1331 end = p + sizeof(s->buffer) - 1;
1338 r = stdout_stream_line(s, p);
1346 if (force_flush && remaining > 0) {
1348 r = stdout_stream_line(s, p);
1356 if (p > s->buffer) {
1357 memmove(s->buffer, p, remaining);
1358 s->length = remaining;
1364 static int stdout_stream_process(StdoutStream *s) {
1370 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1373 if (errno == EAGAIN)
1376 log_warning("Failed to read from stream: %m");
1381 r = stdout_stream_scan(s, true);
1389 r = stdout_stream_scan(s, false);
1397 static void stdout_stream_free(StdoutStream *s) {
1401 assert(s->server->n_stdout_streams > 0);
1402 s->server->n_stdout_streams --;
1403 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1408 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1410 close_nointr_nofail(s->fd);
1414 if (s->security_context)
1415 freecon(s->security_context);
1418 free(s->identifier);
1422 static int stdout_stream_new(Server *s) {
1423 StdoutStream *stream;
1426 struct epoll_event ev;
1430 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1432 if (errno == EAGAIN)
1435 log_error("Failed to accept stdout connection: %m");
1439 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1440 log_warning("Too many stdout streams, refusing connection.");
1441 close_nointr_nofail(fd);
1445 stream = new0(StdoutStream, 1);
1447 close_nointr_nofail(fd);
1453 len = sizeof(stream->ucred);
1454 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1455 log_error("Failed to determine peer credentials: %m");
1461 if (getpeercon(fd, &stream->security_context) < 0 && errno != ENOPROTOOPT)
1462 log_error("Failed to determine peer security context: %m");
1465 if (shutdown(fd, SHUT_WR) < 0) {
1466 log_error("Failed to shutdown writing side of socket: %m");
1472 ev.data.ptr = stream;
1473 ev.events = EPOLLIN;
1474 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1475 log_error("Failed to add stream to event loop: %m");
1481 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1482 s->n_stdout_streams ++;
1487 stdout_stream_free(stream);
1491 static int system_journal_open(Server *s) {
1497 r = sd_id128_get_machine(&machine);
1501 sd_id128_to_string(machine, ids);
1503 if (!s->system_journal &&
1504 (s->storage == STORAGE_PERSISTENT || s->storage == STORAGE_AUTO) &&
1505 access("/run/systemd/journal/flushed", F_OK) >= 0) {
1507 /* If in auto mode: first try to create the machine
1508 * path, but not the prefix.
1510 * If in persistent mode: create /var/log/journal and
1511 * the machine path */
1513 if (s->storage == STORAGE_PERSISTENT)
1514 (void) mkdir("/var/log/journal/", 0755);
1516 fn = strappend("/var/log/journal/", ids);
1520 (void) mkdir(fn, 0755);
1523 fn = strjoin("/var/log/journal/", ids, "/system.journal", NULL);
1527 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, s->compress, s->seal, &s->system_metrics, s->mmap, NULL, &s->system_journal);
1531 server_fix_perms(s, s->system_journal, 0);
1534 if (r != -ENOENT && r != -EROFS)
1535 log_warning("Failed to open system journal: %s", strerror(-r));
1541 if (!s->runtime_journal &&
1542 (s->storage != STORAGE_NONE)) {
1544 fn = strjoin("/run/log/journal/", ids, "/system.journal", NULL);
1548 if (s->system_journal) {
1550 /* Try to open the runtime journal, but only
1551 * if it already exists, so that we can flush
1552 * it into the system journal */
1554 r = journal_file_open(fn, O_RDWR, 0640, s->compress, false, &s->runtime_metrics, s->mmap, NULL, &s->runtime_journal);
1559 log_warning("Failed to open runtime journal: %s", strerror(-r));
1566 /* OK, we really need the runtime journal, so create
1567 * it if necessary. */
1569 (void) mkdir_parents(fn, 0755);
1570 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, s->compress, false, &s->runtime_metrics, s->mmap, NULL, &s->runtime_journal);
1574 log_error("Failed to open runtime journal: %s", strerror(-r));
1579 if (s->runtime_journal)
1580 server_fix_perms(s, s->runtime_journal, 0);
1586 static int server_flush_to_var(Server *s) {
1594 if (s->storage != STORAGE_AUTO &&
1595 s->storage != STORAGE_PERSISTENT)
1598 if (!s->runtime_journal)
1601 system_journal_open(s);
1603 if (!s->system_journal)
1606 log_info("Flushing to /var...");
1608 r = sd_id128_get_machine(&machine);
1610 log_error("Failed to get machine id: %s", strerror(-r));
1614 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1616 log_error("Failed to read runtime journal: %s", strerror(-r));
1620 SD_JOURNAL_FOREACH(j) {
1623 f = j->current_file;
1624 assert(f && f->current_offset > 0);
1626 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1628 log_error("Can't read entry: %s", strerror(-r));
1632 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1634 log_info("Allocation limit reached.");
1636 journal_file_post_change(s->system_journal);
1640 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1644 log_error("Can't write entry: %s", strerror(-r));
1650 journal_file_post_change(s->system_journal);
1652 journal_file_close(s->runtime_journal);
1653 s->runtime_journal = NULL;
1656 rm_rf("/run/log/journal", false, true, false);
1661 static int process_event(Server *s, struct epoll_event *ev) {
1665 if (ev->data.fd == s->signal_fd) {
1666 struct signalfd_siginfo sfsi;
1669 if (ev->events != EPOLLIN) {
1670 log_info("Got invalid event from epoll.");
1674 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
1675 if (n != sizeof(sfsi)) {
1680 if (errno == EINTR || errno == EAGAIN)
1686 log_info("Received SIG%s", signal_to_string(sfsi.ssi_signo));
1688 if (sfsi.ssi_signo == SIGUSR1) {
1689 touch("/run/systemd/journal/flushed");
1690 server_flush_to_var(s);
1694 if (sfsi.ssi_signo == SIGUSR2) {
1702 } else if (ev->data.fd == s->dev_kmsg_fd) {
1705 if (ev->events != EPOLLIN) {
1706 log_info("Got invalid event from epoll.");
1710 r = server_read_dev_kmsg(s);
1716 } else if (ev->data.fd == s->native_fd ||
1717 ev->data.fd == s->syslog_fd) {
1719 if (ev->events != EPOLLIN) {
1720 log_info("Got invalid event from epoll.");
1725 struct msghdr msghdr;
1727 struct ucred *ucred = NULL;
1728 struct timeval *tv = NULL;
1729 struct cmsghdr *cmsg;
1731 size_t label_len = 0;
1733 struct cmsghdr cmsghdr;
1735 /* We use NAME_MAX space for the
1736 * SELinux label here. The kernel
1737 * currently enforces no limit, but
1738 * according to suggestions from the
1739 * SELinux people this will change and
1740 * it will probably be identical to
1741 * NAME_MAX. For now we use that, but
1742 * this should be updated one day when
1743 * the final limit is known.*/
1744 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1745 CMSG_SPACE(sizeof(struct timeval)) +
1746 CMSG_SPACE(sizeof(int)) + /* fd */
1747 CMSG_SPACE(NAME_MAX)]; /* selinux label */
1754 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
1755 log_error("SIOCINQ failed: %m");
1759 if (s->buffer_size < (size_t) v) {
1763 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
1764 b = realloc(s->buffer, l+1);
1767 log_error("Couldn't increase buffer.");
1776 iovec.iov_base = s->buffer;
1777 iovec.iov_len = s->buffer_size;
1781 msghdr.msg_iov = &iovec;
1782 msghdr.msg_iovlen = 1;
1783 msghdr.msg_control = &control;
1784 msghdr.msg_controllen = sizeof(control);
1786 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
1789 if (errno == EINTR || errno == EAGAIN)
1792 log_error("recvmsg() failed: %m");
1796 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
1798 if (cmsg->cmsg_level == SOL_SOCKET &&
1799 cmsg->cmsg_type == SCM_CREDENTIALS &&
1800 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
1801 ucred = (struct ucred*) CMSG_DATA(cmsg);
1802 else if (cmsg->cmsg_level == SOL_SOCKET &&
1803 cmsg->cmsg_type == SCM_SECURITY) {
1804 label = (char*) CMSG_DATA(cmsg);
1805 label_len = cmsg->cmsg_len - CMSG_LEN(0);
1806 } else if (cmsg->cmsg_level == SOL_SOCKET &&
1807 cmsg->cmsg_type == SO_TIMESTAMP &&
1808 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
1809 tv = (struct timeval*) CMSG_DATA(cmsg);
1810 else if (cmsg->cmsg_level == SOL_SOCKET &&
1811 cmsg->cmsg_type == SCM_RIGHTS) {
1812 fds = (int*) CMSG_DATA(cmsg);
1813 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1817 if (ev->data.fd == s->syslog_fd) {
1820 if (n > 0 && n_fds == 0) {
1821 e = memchr(s->buffer, '\n', n);
1827 server_process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
1828 } else if (n_fds > 0)
1829 log_warning("Got file descriptors via syslog socket. Ignoring.");
1832 if (n > 0 && n_fds == 0)
1833 process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
1834 else if (n == 0 && n_fds == 1)
1835 process_native_file(s, fds[0], ucred, tv, label, label_len);
1837 log_warning("Got too many file descriptors via native socket. Ignoring.");
1840 close_many(fds, n_fds);
1845 } else if (ev->data.fd == s->stdout_fd) {
1847 if (ev->events != EPOLLIN) {
1848 log_info("Got invalid event from epoll.");
1852 stdout_stream_new(s);
1856 StdoutStream *stream;
1858 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
1859 log_info("Got invalid event from epoll.");
1863 /* If it is none of the well-known fds, it must be an
1864 * stdout stream fd. Note that this is a bit ugly here
1865 * (since we rely that none of the well-known fds
1866 * could be interpreted as pointer), but nonetheless
1867 * safe, since the well-known fds would never get an
1868 * fd > 4096, i.e. beyond the first memory page */
1870 stream = ev->data.ptr;
1872 if (stdout_stream_process(stream) <= 0)
1873 stdout_stream_free(stream);
1878 log_error("Unknown event.");
1883 static int open_native_socket(Server*s) {
1884 union sockaddr_union sa;
1886 struct epoll_event ev;
1890 if (s->native_fd < 0) {
1892 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
1893 if (s->native_fd < 0) {
1894 log_error("socket() failed: %m");
1899 sa.un.sun_family = AF_UNIX;
1900 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
1902 unlink(sa.un.sun_path);
1904 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1906 log_error("bind() failed: %m");
1910 chmod(sa.un.sun_path, 0666);
1912 fd_nonblock(s->native_fd, 1);
1915 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1917 log_error("SO_PASSCRED failed: %m");
1923 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
1925 log_warning("SO_PASSSEC failed: %m");
1929 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1931 log_error("SO_TIMESTAMP failed: %m");
1936 ev.events = EPOLLIN;
1937 ev.data.fd = s->native_fd;
1938 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
1939 log_error("Failed to add native server fd to epoll object: %m");
1946 static int open_stdout_socket(Server *s) {
1947 union sockaddr_union sa;
1949 struct epoll_event ev;
1953 if (s->stdout_fd < 0) {
1955 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
1956 if (s->stdout_fd < 0) {
1957 log_error("socket() failed: %m");
1962 sa.un.sun_family = AF_UNIX;
1963 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
1965 unlink(sa.un.sun_path);
1967 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1969 log_error("bind() failed: %m");
1973 chmod(sa.un.sun_path, 0666);
1975 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
1976 log_error("liste() failed: %m");
1980 fd_nonblock(s->stdout_fd, 1);
1983 ev.events = EPOLLIN;
1984 ev.data.fd = s->stdout_fd;
1985 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
1986 log_error("Failed to add stdout server fd to epoll object: %m");
1993 static int open_signalfd(Server *s) {
1995 struct epoll_event ev;
1999 assert_se(sigemptyset(&mask) == 0);
2000 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, SIGUSR2, -1);
2001 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2003 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2004 if (s->signal_fd < 0) {
2005 log_error("signalfd(): %m");
2010 ev.events = EPOLLIN;
2011 ev.data.fd = s->signal_fd;
2013 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2014 log_error("epoll_ctl(): %m");
2021 static int server_parse_proc_cmdline(Server *s) {
2022 char *line, *w, *state;
2026 if (detect_container(NULL) > 0)
2029 r = read_one_line_file("/proc/cmdline", &line);
2031 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2035 FOREACH_WORD_QUOTED(w, l, line, state) {
2038 word = strndup(w, l);
2044 if (startswith(word, "systemd.journald.forward_to_syslog=")) {
2045 r = parse_boolean(word + 35);
2047 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2049 s->forward_to_syslog = r;
2050 } else if (startswith(word, "systemd.journald.forward_to_kmsg=")) {
2051 r = parse_boolean(word + 33);
2053 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2055 s->forward_to_kmsg = r;
2056 } else if (startswith(word, "systemd.journald.forward_to_console=")) {
2057 r = parse_boolean(word + 36);
2059 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2061 s->forward_to_console = r;
2062 } else if (startswith(word, "systemd.journald"))
2063 log_warning("Invalid systemd.journald parameter. Ignoring.");
2075 static int server_parse_config_file(Server *s) {
2082 fn = "/etc/systemd/journald.conf";
2083 f = fopen(fn, "re");
2085 if (errno == ENOENT)
2088 log_warning("Failed to open configuration file %s: %m", fn);
2092 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2094 log_warning("Failed to parse configuration file: %s", strerror(-r));
2101 static int server_init(Server *s) {
2107 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->dev_kmsg_fd = -1;
2111 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2112 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2114 s->forward_to_syslog = true;
2116 s->max_level_store = LOG_DEBUG;
2117 s->max_level_syslog = LOG_DEBUG;
2118 s->max_level_kmsg = LOG_NOTICE;
2119 s->max_level_console = LOG_INFO;
2121 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2122 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2124 server_parse_config_file(s);
2125 server_parse_proc_cmdline(s);
2127 mkdir_p("/run/systemd/journal", 0755);
2129 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2130 if (!s->user_journals)
2133 s->mmap = mmap_cache_new();
2137 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2138 if (s->epoll_fd < 0) {
2139 log_error("Failed to create epoll object: %m");
2143 n = sd_listen_fds(true);
2145 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2149 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2151 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2153 if (s->native_fd >= 0) {
2154 log_error("Too many native sockets passed.");
2160 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2162 if (s->stdout_fd >= 0) {
2163 log_error("Too many stdout sockets passed.");
2169 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2171 if (s->syslog_fd >= 0) {
2172 log_error("Too many /dev/log sockets passed.");
2179 log_error("Unknown socket passed.");
2184 r = server_open_syslog_socket(s);
2188 r = open_native_socket(s);
2192 r = open_stdout_socket(s);
2196 r = server_open_dev_kmsg(s);
2200 r = server_open_kernel_seqnum(s);
2204 r = open_signalfd(s);
2208 s->udev = udev_new();
2212 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2216 r = system_journal_open(s);
2223 static void maybe_append_tags(Server *s) {
2229 n = now(CLOCK_REALTIME);
2231 if (s->system_journal)
2232 journal_file_maybe_append_tag(s->system_journal, n);
2234 HASHMAP_FOREACH(f, s->user_journals, i)
2235 journal_file_maybe_append_tag(f, n);
2239 static void server_done(Server *s) {
2243 while (s->stdout_streams)
2244 stdout_stream_free(s->stdout_streams);
2246 if (s->system_journal)
2247 journal_file_close(s->system_journal);
2249 if (s->runtime_journal)
2250 journal_file_close(s->runtime_journal);
2252 while ((f = hashmap_steal_first(s->user_journals)))
2253 journal_file_close(f);
2255 hashmap_free(s->user_journals);
2257 if (s->epoll_fd >= 0)
2258 close_nointr_nofail(s->epoll_fd);
2260 if (s->signal_fd >= 0)
2261 close_nointr_nofail(s->signal_fd);
2263 if (s->syslog_fd >= 0)
2264 close_nointr_nofail(s->syslog_fd);
2266 if (s->native_fd >= 0)
2267 close_nointr_nofail(s->native_fd);
2269 if (s->stdout_fd >= 0)
2270 close_nointr_nofail(s->stdout_fd);
2272 if (s->dev_kmsg_fd >= 0)
2273 close_nointr_nofail(s->dev_kmsg_fd);
2276 journal_rate_limit_free(s->rate_limit);
2278 if (s->kernel_seqnum)
2279 munmap(s->kernel_seqnum, sizeof(uint64_t));
2285 mmap_cache_unref(s->mmap);
2288 udev_unref(s->udev);
2291 int main(int argc, char *argv[]) {
2295 /* if (getppid() != 1) { */
2296 /* log_error("This program should be invoked by init only."); */
2297 /* return EXIT_FAILURE; */
2301 log_error("This program does not take arguments.");
2302 return EXIT_FAILURE;
2305 log_set_target(LOG_TARGET_SAFE);
2306 log_set_facility(LOG_SYSLOG);
2307 log_set_max_level(LOG_DEBUG);
2308 log_parse_environment();
2313 r = server_init(&server);
2317 server_vacuum(&server);
2318 server_flush_to_var(&server);
2319 server_flush_dev_kmsg(&server);
2321 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2322 server_driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2326 "STATUS=Processing requests...");
2329 struct epoll_event event;
2335 if (server.system_journal &&
2336 journal_file_next_evolve_usec(server.system_journal, &u)) {
2339 n = now(CLOCK_REALTIME);
2344 t = (int) ((u - n + USEC_PER_MSEC - 1) / USEC_PER_MSEC);
2349 r = epoll_wait(server.epoll_fd, &event, 1, t);
2355 log_error("epoll_wait() failed: %m");
2361 r = process_event(&server, &event);
2368 maybe_append_tags(&server);
2371 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2372 server_driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2376 "STATUS=Shutting down...");
2378 server_done(&server);
2380 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;