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>
35 #include <systemd/sd-journal.h>
36 #include <systemd/sd-login.h>
37 #include <systemd/sd-messages.h>
38 #include <systemd/sd-daemon.h>
41 #include "journal-file.h"
42 #include "socket-util.h"
44 #include "cgroup-util.h"
46 #include "journal-rate-limit.h"
47 #include "journal-internal.h"
48 #include "conf-parser.h"
51 #define USER_JOURNALS_MAX 1024
52 #define STDOUT_STREAMS_MAX 4096
54 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
55 #define DEFAULT_RATE_LIMIT_BURST 200
57 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
59 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
61 #define SYSLOG_TIMEOUT_USEC (5*USEC_PER_SEC)
63 #define N_IOVEC_META_FIELDS 16
65 typedef enum StdoutStreamState {
66 STDOUT_STREAM_IDENTIFIER,
67 STDOUT_STREAM_PRIORITY,
68 STDOUT_STREAM_LEVEL_PREFIX,
69 STDOUT_STREAM_FORWARD_TO_SYSLOG,
70 STDOUT_STREAM_FORWARD_TO_KMSG,
71 STDOUT_STREAM_FORWARD_TO_CONSOLE,
77 StdoutStreamState state;
86 bool forward_to_syslog:1;
87 bool forward_to_kmsg:1;
88 bool forward_to_console:1;
90 char buffer[LINE_MAX+1];
93 LIST_FIELDS(StdoutStream, stdout_stream);
96 static int server_flush_to_var(Server *s);
98 static uint64_t available_space(Server *s) {
103 uint64_t sum = 0, avail = 0, ss_avail = 0;
109 ts = now(CLOCK_MONOTONIC);
111 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
112 return s->cached_available_space;
114 r = sd_id128_get_machine(&machine);
118 if (s->system_journal) {
119 f = "/var/log/journal/";
120 m = &s->system_metrics;
122 f = "/run/log/journal/";
123 m = &s->runtime_metrics;
128 p = strappend(f, sd_id128_to_string(machine, ids));
138 if (fstatvfs(dirfd(d), &ss) < 0)
143 struct dirent buf, *de;
146 k = readdir_r(d, &buf, &de);
155 if (!dirent_is_file_with_suffix(de, ".journal"))
158 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
161 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
164 avail = sum >= m->max_use ? 0 : m->max_use - sum;
166 ss_avail = ss.f_bsize * ss.f_bavail;
168 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
170 if (ss_avail < avail)
173 s->cached_available_space = avail;
174 s->cached_available_space_timestamp = ts;
182 static void fix_perms(JournalFile *f, uid_t uid) {
185 acl_permset_t permset;
190 r = fchmod_and_fchown(f->fd, 0640, 0, 0);
192 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
197 acl = acl_get_fd(f->fd);
199 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
203 r = acl_find_uid(acl, uid, &entry);
206 if (acl_create_entry(&acl, &entry) < 0 ||
207 acl_set_tag_type(entry, ACL_USER) < 0 ||
208 acl_set_qualifier(entry, &uid) < 0) {
209 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
214 if (acl_get_permset(entry, &permset) < 0 ||
215 acl_add_perm(permset, ACL_READ) < 0 ||
216 acl_calc_mask(&acl) < 0) {
217 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
221 if (acl_set_fd(f->fd, acl) < 0)
222 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
228 static JournalFile* find_journal(Server *s, uid_t uid) {
237 /* We split up user logs only on /var, not on /run. If the
238 * runtime file is open, we write to it exclusively, in order
239 * to guarantee proper order as soon as we flush /run to
240 * /var and close the runtime file. */
242 if (s->runtime_journal)
243 return s->runtime_journal;
246 return s->system_journal;
248 r = sd_id128_get_machine(&machine);
250 return s->system_journal;
252 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
256 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
257 return s->system_journal;
259 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
260 /* Too many open? Then let's close one */
261 f = hashmap_steal_first(s->user_journals);
263 journal_file_close(f);
266 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
270 return s->system_journal;
273 f->metrics = s->system_metrics;
274 f->compress = s->compress;
276 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
278 journal_file_close(f);
279 return s->system_journal;
285 static void server_rotate(Server *s) {
291 log_info("Rotating...");
293 if (s->runtime_journal) {
294 r = journal_file_rotate(&s->runtime_journal);
296 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
299 if (s->system_journal) {
300 r = journal_file_rotate(&s->system_journal);
302 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
305 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
306 r = journal_file_rotate(&f);
308 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
310 hashmap_replace(s->user_journals, k, f);
314 static void server_vacuum(Server *s) {
320 log_info("Vacuuming...");
322 r = sd_id128_get_machine(&machine);
324 log_error("Failed to get machine ID: %s", strerror(-r));
328 sd_id128_to_string(machine, ids);
330 if (s->system_journal) {
331 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
332 log_error("Out of memory.");
336 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
337 if (r < 0 && r != -ENOENT)
338 log_error("Failed to vacuum %s: %s", p, strerror(-r));
343 if (s->runtime_journal) {
344 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
345 log_error("Out of memory.");
349 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
350 if (r < 0 && r != -ENOENT)
351 log_error("Failed to vacuum %s: %s", p, strerror(-r));
355 s->cached_available_space_timestamp = 0;
358 static char *shortened_cgroup_path(pid_t pid) {
360 char *process_path, *init_path, *path;
364 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
368 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
374 if (endswith(init_path, "/system"))
375 init_path[strlen(init_path) - 7] = 0;
376 else if (streq(init_path, "/"))
379 if (startswith(process_path, init_path)) {
382 p = strdup(process_path + strlen(init_path));
400 static void dispatch_message_real(Server *s,
401 struct iovec *iovec, unsigned n, unsigned m,
403 struct timeval *tv) {
405 char *pid = NULL, *uid = NULL, *gid = NULL,
406 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
407 *comm = NULL, *cmdline = NULL, *hostname = NULL,
408 *audit_session = NULL, *audit_loginuid = NULL,
409 *exe = NULL, *cgroup = NULL, *session = NULL,
410 *owner_uid = NULL, *unit = NULL;
416 uid_t loginuid = 0, realuid = 0;
418 bool vacuumed = false;
423 assert(n + N_IOVEC_META_FIELDS <= m);
429 realuid = ucred->uid;
431 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
432 IOVEC_SET_STRING(iovec[n++], pid);
434 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
435 IOVEC_SET_STRING(iovec[n++], uid);
437 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
438 IOVEC_SET_STRING(iovec[n++], gid);
440 r = get_process_comm(ucred->pid, &t);
442 comm = strappend("_COMM=", t);
446 IOVEC_SET_STRING(iovec[n++], comm);
449 r = get_process_exe(ucred->pid, &t);
451 exe = strappend("_EXE=", t);
455 IOVEC_SET_STRING(iovec[n++], exe);
458 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
460 cmdline = strappend("_CMDLINE=", t);
464 IOVEC_SET_STRING(iovec[n++], cmdline);
467 r = audit_session_from_pid(ucred->pid, &audit);
469 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
470 IOVEC_SET_STRING(iovec[n++], audit_session);
472 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
474 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
475 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
477 t = shortened_cgroup_path(ucred->pid);
479 cgroup = strappend("_SYSTEMD_CGROUP=", t);
483 IOVEC_SET_STRING(iovec[n++], cgroup);
486 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
487 session = strappend("_SYSTEMD_SESSION=", t);
491 IOVEC_SET_STRING(iovec[n++], session);
494 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
495 unit = strappend("_SYSTEMD_UNIT=", t);
499 IOVEC_SET_STRING(iovec[n++], unit);
502 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
503 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
504 IOVEC_SET_STRING(iovec[n++], owner_uid);
508 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
509 (unsigned long long) timeval_load(tv)) >= 0)
510 IOVEC_SET_STRING(iovec[n++], source_time);
513 /* Note that strictly speaking storing the boot id here is
514 * redundant since the entry includes this in-line
515 * anyway. However, we need this indexed, too. */
516 r = sd_id128_get_boot(&id);
518 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
519 IOVEC_SET_STRING(iovec[n++], boot_id);
521 r = sd_id128_get_machine(&id);
523 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
524 IOVEC_SET_STRING(iovec[n++], machine_id);
526 t = gethostname_malloc();
528 hostname = strappend("_HOSTNAME=", t);
531 IOVEC_SET_STRING(iovec[n++], hostname);
536 server_flush_to_var(s);
539 f = find_journal(s, realuid == 0 ? 0 : loginuid);
541 log_warning("Dropping message, as we can't find a place to store the data.");
543 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
545 if (r == -E2BIG && !vacuumed) {
546 log_info("Allocation limit reached.");
552 log_info("Retrying write.");
557 log_error("Failed to write entry, ignoring: %s", strerror(-r));
571 free(audit_loginuid);
578 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
579 char mid[11 + 32 + 1];
580 char buffer[16 + LINE_MAX + 1];
581 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
589 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
590 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
592 memcpy(buffer, "MESSAGE=", 8);
593 va_start(ap, format);
594 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
596 char_array_0(buffer);
597 IOVEC_SET_STRING(iovec[n++], buffer);
599 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
601 IOVEC_SET_STRING(iovec[n++], mid);
604 ucred.pid = getpid();
605 ucred.uid = getuid();
606 ucred.gid = getgid();
608 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL);
611 static void dispatch_message(Server *s,
612 struct iovec *iovec, unsigned n, unsigned m,
617 char *path = NULL, *c;
620 assert(iovec || n == 0);
628 path = shortened_cgroup_path(ucred->pid);
632 /* example: /user/lennart/3/foobar
633 * /system/dbus.service/foobar
635 * So let's cut of everything past the third /, since that is
636 * wher user directories start */
638 c = strchr(path, '/');
640 c = strchr(c+1, '/');
642 c = strchr(c+1, '/');
648 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
655 /* Write a suppression message if we suppressed something */
657 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
662 dispatch_message_real(s, iovec, n, m, ucred, tv);
665 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
666 struct msghdr msghdr;
667 struct cmsghdr *cmsg;
669 struct cmsghdr cmsghdr;
670 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
672 union sockaddr_union sa;
679 msghdr.msg_iov = (struct iovec*) iovec;
680 msghdr.msg_iovlen = n_iovec;
683 sa.un.sun_family = AF_UNIX;
684 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
685 msghdr.msg_name = &sa;
686 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
690 msghdr.msg_control = &control;
691 msghdr.msg_controllen = sizeof(control);
693 cmsg = CMSG_FIRSTHDR(&msghdr);
694 cmsg->cmsg_level = SOL_SOCKET;
695 cmsg->cmsg_type = SCM_CREDENTIALS;
696 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
697 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
698 msghdr.msg_controllen = cmsg->cmsg_len;
701 /* Forward the syslog message we received via /dev/log to
702 * /run/systemd/syslog. Unfortunately we currently can't set
703 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
705 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
708 if (ucred && errno == ESRCH) {
711 /* Hmm, presumably the sender process vanished
712 * by now, so let's fix it as good as we
717 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
719 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
723 log_debug("Failed to forward syslog message: %m");
726 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
732 IOVEC_SET_STRING(iovec, buffer);
733 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
736 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
737 struct iovec iovec[5];
738 char header_priority[6], header_time[64], header_pid[16];
742 char *ident_buf = NULL;
745 assert(priority >= 0);
746 assert(priority <= 999);
749 /* First: priority field */
750 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
751 char_array_0(header_priority);
752 IOVEC_SET_STRING(iovec[n++], header_priority);
754 /* Second: timestamp */
755 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
759 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
761 IOVEC_SET_STRING(iovec[n++], header_time);
763 /* Third: identifier and PID */
766 get_process_comm(ucred->pid, &ident_buf);
767 identifier = ident_buf;
770 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
771 char_array_0(header_pid);
774 IOVEC_SET_STRING(iovec[n++], identifier);
776 IOVEC_SET_STRING(iovec[n++], header_pid);
777 } else if (identifier) {
778 IOVEC_SET_STRING(iovec[n++], identifier);
779 IOVEC_SET_STRING(iovec[n++], ": ");
782 /* Fourth: message */
783 IOVEC_SET_STRING(iovec[n++], message);
785 forward_syslog_iovec(s, iovec, n, ucred, tv);
790 static int fixup_priority(int priority) {
792 if ((priority & LOG_FACMASK) == 0)
793 return (priority & LOG_PRIMASK) | LOG_USER;
798 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
799 struct iovec iovec[5];
800 char header_priority[6], header_pid[16];
802 char *ident_buf = NULL;
806 assert(priority >= 0);
807 assert(priority <= 999);
810 /* Never allow messages with kernel facility to be written to
811 * kmsg, regardless where the data comes from. */
812 priority = fixup_priority(priority);
814 /* First: priority field */
815 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
816 char_array_0(header_priority);
817 IOVEC_SET_STRING(iovec[n++], header_priority);
819 /* Second: identifier and PID */
822 get_process_comm(ucred->pid, &ident_buf);
823 identifier = ident_buf;
826 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
827 char_array_0(header_pid);
830 IOVEC_SET_STRING(iovec[n++], identifier);
832 IOVEC_SET_STRING(iovec[n++], header_pid);
833 } else if (identifier) {
834 IOVEC_SET_STRING(iovec[n++], identifier);
835 IOVEC_SET_STRING(iovec[n++], ": ");
838 /* Fourth: message */
839 IOVEC_SET_STRING(iovec[n++], message);
840 IOVEC_SET_STRING(iovec[n++], "\n");
842 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
844 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
848 if (writev(fd, iovec, n) < 0)
849 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
851 close_nointr_nofail(fd);
857 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
858 struct iovec iovec[4];
861 char *ident_buf = NULL;
866 /* First: identifier and PID */
869 get_process_comm(ucred->pid, &ident_buf);
870 identifier = ident_buf;
873 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
874 char_array_0(header_pid);
877 IOVEC_SET_STRING(iovec[n++], identifier);
879 IOVEC_SET_STRING(iovec[n++], header_pid);
880 } else if (identifier) {
881 IOVEC_SET_STRING(iovec[n++], identifier);
882 IOVEC_SET_STRING(iovec[n++], ": ");
886 IOVEC_SET_STRING(iovec[n++], message);
887 IOVEC_SET_STRING(iovec[n++], "\n");
889 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
891 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
895 if (writev(fd, iovec, n) < 0)
896 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
898 close_nointr_nofail(fd);
904 static void read_identifier(const char **buf, char **identifier) {
914 p += strspn(p, WHITESPACE);
915 l = strcspn(p, WHITESPACE);
946 *buf += strspn(*buf, WHITESPACE);
949 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
950 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
951 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
953 int priority = LOG_USER | LOG_INFO;
954 char *identifier = NULL;
959 if (s->forward_to_syslog)
960 forward_syslog_raw(s, buf, ucred, tv);
962 parse_syslog_priority((char**) &buf, &priority);
963 skip_syslog_date((char**) &buf);
964 read_identifier(&buf, &identifier);
966 if (s->forward_to_kmsg)
967 forward_kmsg(s, priority, identifier, buf, ucred);
969 if (s->forward_to_console)
970 forward_console(s, identifier, buf, ucred);
972 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
974 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
975 IOVEC_SET_STRING(iovec[n++], syslog_priority);
977 if (priority & LOG_FACMASK)
978 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
979 IOVEC_SET_STRING(iovec[n++], syslog_facility);
982 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
983 if (syslog_identifier)
984 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
987 message = strappend("MESSAGE=", buf);
989 IOVEC_SET_STRING(iovec[n++], message);
991 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, priority);
995 free(syslog_priority);
996 free(syslog_facility);
997 free(syslog_identifier);
1000 static bool valid_user_field(const char *p, size_t l) {
1003 /* We kinda enforce POSIX syntax recommendations for
1004 environment variables here, but make a couple of additional
1007 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1009 /* No empty field names */
1013 /* Don't allow names longer than 64 chars */
1017 /* Variables starting with an underscore are protected */
1021 /* Don't allow digits as first character */
1022 if (p[0] >= '0' && p[0] <= '9')
1025 /* Only allow A-Z0-9 and '_' */
1026 for (a = p; a < p + l; a++)
1027 if (!((*a >= 'A' && *a <= 'Z') ||
1028 (*a >= '0' && *a <= '9') ||
1035 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
1036 struct iovec *iovec = NULL;
1037 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1040 int priority = LOG_INFO;
1041 char *identifier = NULL, *message = NULL;
1044 assert(buffer || n == 0);
1047 remaining = buffer_size;
1049 while (remaining > 0) {
1052 e = memchr(p, '\n', remaining);
1055 /* Trailing noise, let's ignore it, and flush what we collected */
1056 log_debug("Received message with trailing noise, ignoring.");
1061 /* Entry separator */
1062 dispatch_message(s, iovec, n, m, ucred, tv, priority);
1064 priority = LOG_INFO;
1071 if (*p == '.' || *p == '#') {
1072 /* Ignore control commands for now, and
1074 remaining -= (e - p) + 1;
1079 /* A property follows */
1081 if (n+N_IOVEC_META_FIELDS >= m) {
1085 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1086 c = realloc(iovec, u * sizeof(struct iovec));
1088 log_error("Out of memory");
1096 q = memchr(p, '=', e - p);
1098 if (valid_user_field(p, q - p)) {
1103 /* If the field name starts with an
1104 * underscore, skip the variable,
1105 * since that indidates a trusted
1107 iovec[n].iov_base = (char*) p;
1108 iovec[n].iov_len = l;
1111 /* We need to determine the priority
1112 * of this entry for the rate limiting
1115 memcmp(p, "PRIORITY=", 9) == 0 &&
1116 p[9] >= '0' && p[9] <= '9')
1117 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1120 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1121 p[16] >= '0' && p[16] <= '9')
1122 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1125 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1126 p[16] >= '0' && p[16] <= '9' &&
1127 p[17] >= '0' && p[17] <= '9')
1128 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1131 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1134 t = strndup(p + 11, l - 11);
1139 } else if (l >= 8 &&
1140 memcmp(p, "MESSAGE=", 8) == 0) {
1143 t = strndup(p + 8, l - 8);
1151 remaining -= (e - p) + 1;
1158 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1159 log_debug("Failed to parse message, ignoring.");
1163 memcpy(&l, e + 1, sizeof(uint64_t));
1166 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1167 e[1+sizeof(uint64_t)+l] != '\n') {
1168 log_debug("Failed to parse message, ignoring.");
1172 k = malloc((e - p) + 1 + l);
1174 log_error("Out of memory");
1178 memcpy(k, p, e - p);
1180 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1182 if (valid_user_field(p, e - p)) {
1183 iovec[n].iov_base = k;
1184 iovec[n].iov_len = (e - p) + 1 + l;
1189 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1190 p = e + 1 + sizeof(uint64_t) + l + 1;
1198 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1201 if (s->forward_to_syslog)
1202 forward_syslog(s, priority, identifier, message, ucred, tv);
1204 if (s->forward_to_kmsg)
1205 forward_kmsg(s, priority, identifier, message, ucred);
1207 if (s->forward_to_console)
1208 forward_console(s, identifier, message, ucred);
1211 dispatch_message(s, iovec, n, m, ucred, tv, priority);
1214 for (j = 0; j < n; j++) {
1218 if (iovec[j].iov_base < buffer ||
1219 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1220 free(iovec[j].iov_base);
1227 static int stdout_stream_log(StdoutStream *s, const char *p) {
1228 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1229 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1236 priority = s->priority;
1238 if (s->level_prefix)
1239 parse_syslog_priority((char**) &p, &priority);
1241 if (s->forward_to_syslog || s->server->forward_to_syslog)
1242 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1244 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1245 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1247 if (s->forward_to_console || s->server->forward_to_console)
1248 forward_console(s->server, s->identifier, p, &s->ucred);
1250 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1252 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1253 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1255 if (priority & LOG_FACMASK)
1256 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1257 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1259 if (s->identifier) {
1260 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1261 if (syslog_identifier)
1262 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1265 message = strappend("MESSAGE=", p);
1267 IOVEC_SET_STRING(iovec[n++], message);
1269 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, priority);
1272 free(syslog_priority);
1273 free(syslog_facility);
1274 free(syslog_identifier);
1279 static int stdout_stream_line(StdoutStream *s, char *p) {
1289 case STDOUT_STREAM_IDENTIFIER:
1290 s->identifier = strdup(p);
1291 if (!s->identifier) {
1292 log_error("Out of memory");
1296 s->state = STDOUT_STREAM_PRIORITY;
1299 case STDOUT_STREAM_PRIORITY:
1300 r = safe_atoi(p, &s->priority);
1301 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1302 log_warning("Failed to parse log priority line.");
1306 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1309 case STDOUT_STREAM_LEVEL_PREFIX:
1310 r = parse_boolean(p);
1312 log_warning("Failed to parse level prefix line.");
1316 s->level_prefix = !!r;
1317 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1320 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1321 r = parse_boolean(p);
1323 log_warning("Failed to parse forward to syslog line.");
1327 s->forward_to_syslog = !!r;
1328 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1331 case STDOUT_STREAM_FORWARD_TO_KMSG:
1332 r = parse_boolean(p);
1334 log_warning("Failed to parse copy to kmsg line.");
1338 s->forward_to_kmsg = !!r;
1339 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1342 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1343 r = parse_boolean(p);
1345 log_warning("Failed to parse copy to console line.");
1349 s->forward_to_console = !!r;
1350 s->state = STDOUT_STREAM_RUNNING;
1353 case STDOUT_STREAM_RUNNING:
1354 return stdout_stream_log(s, p);
1357 assert_not_reached("Unknown stream state");
1360 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1368 remaining = s->length;
1373 end = memchr(p, '\n', remaining);
1376 else if (remaining >= sizeof(s->buffer) - 1) {
1377 end = p + sizeof(s->buffer) - 1;
1378 skip = sizeof(s->buffer) - 1;
1384 r = stdout_stream_line(s, p);
1392 if (force_flush && remaining > 0) {
1394 r = stdout_stream_line(s, p);
1402 if (p > s->buffer) {
1403 memmove(s->buffer, p, remaining);
1404 s->length = remaining;
1410 static int stdout_stream_process(StdoutStream *s) {
1416 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1419 if (errno == EAGAIN)
1422 log_warning("Failed to read from stream: %m");
1427 r = stdout_stream_scan(s, true);
1435 r = stdout_stream_scan(s, false);
1443 static void stdout_stream_free(StdoutStream *s) {
1447 assert(s->server->n_stdout_streams > 0);
1448 s->server->n_stdout_streams --;
1449 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1454 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1456 close_nointr_nofail(s->fd);
1459 free(s->identifier);
1463 static int stdout_stream_new(Server *s) {
1464 StdoutStream *stream;
1467 struct epoll_event ev;
1471 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1473 if (errno == EAGAIN)
1476 log_error("Failed to accept stdout connection: %m");
1480 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1481 log_warning("Too many stdout streams, refusing connection.");
1482 close_nointr_nofail(fd);
1486 stream = new0(StdoutStream, 1);
1488 log_error("Out of memory.");
1489 close_nointr_nofail(fd);
1495 len = sizeof(stream->ucred);
1496 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1497 log_error("Failed to determine peer credentials: %m");
1502 if (shutdown(fd, SHUT_WR) < 0) {
1503 log_error("Failed to shutdown writing side of socket: %m");
1509 ev.data.ptr = stream;
1510 ev.events = EPOLLIN;
1511 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1512 log_error("Failed to add stream to event loop: %m");
1518 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1519 s->n_stdout_streams ++;
1524 stdout_stream_free(stream);
1528 static int system_journal_open(Server *s) {
1534 r = sd_id128_get_machine(&machine);
1538 sd_id128_to_string(machine, ids);
1540 if (!s->system_journal) {
1542 /* First try to create the machine path, but not the prefix */
1543 fn = strappend("/var/log/journal/", ids);
1546 (void) mkdir(fn, 0755);
1549 /* The create the system journal file */
1550 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1554 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1558 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1560 s->system_journal->metrics = s->system_metrics;
1561 s->system_journal->compress = s->compress;
1563 fix_perms(s->system_journal, 0);
1566 if (r != -ENOENT && r != -EROFS)
1567 log_warning("Failed to open system journal: %s", strerror(-r));
1573 if (!s->runtime_journal) {
1575 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1579 if (s->system_journal) {
1581 /* Try to open the runtime journal, but only
1582 * if it already exists, so that we can flush
1583 * it into the system journal */
1585 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1590 log_warning("Failed to open runtime journal: %s", strerror(-r));
1597 /* OK, we really need the runtime journal, so create
1598 * it if necessary. */
1600 (void) mkdir_parents(fn, 0755);
1601 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1605 log_error("Failed to open runtime journal: %s", strerror(-r));
1610 if (s->runtime_journal) {
1611 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1613 s->runtime_journal->metrics = s->runtime_metrics;
1614 s->runtime_journal->compress = s->compress;
1616 fix_perms(s->runtime_journal, 0);
1623 static int server_flush_to_var(Server *s) {
1624 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1633 if (!s->runtime_journal)
1636 ts = now(CLOCK_MONOTONIC);
1637 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1640 s->var_available_timestamp = ts;
1642 system_journal_open(s);
1644 if (!s->system_journal)
1647 r = sd_id128_get_machine(&machine);
1649 log_error("Failed to get machine id: %s", strerror(-r));
1653 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1655 log_error("Failed to read runtime journal: %s", strerror(-r));
1659 SD_JOURNAL_FOREACH(j) {
1662 f = j->current_file;
1663 assert(f && f->current_offset > 0);
1665 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1667 log_error("Can't read entry: %s", strerror(-r));
1671 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1673 log_info("Allocation limit reached.");
1675 journal_file_post_change(s->system_journal);
1679 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1683 log_error("Can't write entry: %s", strerror(-r));
1689 journal_file_post_change(s->system_journal);
1691 journal_file_close(s->runtime_journal);
1692 s->runtime_journal = NULL;
1695 sd_id128_to_string(machine, path + 17);
1696 rm_rf(path, false, true, false);
1702 static int process_event(Server *s, struct epoll_event *ev) {
1705 if (ev->data.fd == s->signal_fd) {
1706 struct signalfd_siginfo sfsi;
1709 if (ev->events != EPOLLIN) {
1710 log_info("Got invalid event from epoll.");
1714 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
1715 if (n != sizeof(sfsi)) {
1720 if (errno == EINTR || errno == EAGAIN)
1726 if (sfsi.ssi_signo == SIGUSR1) {
1727 server_flush_to_var(s);
1731 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
1734 } else if (ev->data.fd == s->native_fd ||
1735 ev->data.fd == s->syslog_fd) {
1737 if (ev->events != EPOLLIN) {
1738 log_info("Got invalid event from epoll.");
1743 struct msghdr msghdr;
1745 struct ucred *ucred = NULL;
1746 struct timeval *tv = NULL;
1747 struct cmsghdr *cmsg;
1749 struct cmsghdr cmsghdr;
1750 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1751 CMSG_SPACE(sizeof(struct timeval))];
1756 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
1757 log_error("SIOCINQ failed: %m");
1764 if (s->buffer_size < (size_t) v) {
1768 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
1769 b = realloc(s->buffer, l+1);
1772 log_error("Couldn't increase buffer.");
1781 iovec.iov_base = s->buffer;
1782 iovec.iov_len = s->buffer_size;
1786 msghdr.msg_iov = &iovec;
1787 msghdr.msg_iovlen = 1;
1788 msghdr.msg_control = &control;
1789 msghdr.msg_controllen = sizeof(control);
1791 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
1794 if (errno == EINTR || errno == EAGAIN)
1797 log_error("recvmsg() failed: %m");
1801 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
1803 if (cmsg->cmsg_level == SOL_SOCKET &&
1804 cmsg->cmsg_type == SCM_CREDENTIALS &&
1805 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
1806 ucred = (struct ucred*) CMSG_DATA(cmsg);
1807 else if (cmsg->cmsg_level == SOL_SOCKET &&
1808 cmsg->cmsg_type == SO_TIMESTAMP &&
1809 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
1810 tv = (struct timeval*) CMSG_DATA(cmsg);
1813 if (ev->data.fd == s->syslog_fd) {
1816 e = memchr(s->buffer, '\n', n);
1822 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
1824 process_native_message(s, s->buffer, n, ucred, tv);
1829 } else if (ev->data.fd == s->stdout_fd) {
1831 if (ev->events != EPOLLIN) {
1832 log_info("Got invalid event from epoll.");
1836 stdout_stream_new(s);
1840 StdoutStream *stream;
1842 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
1843 log_info("Got invalid event from epoll.");
1847 /* If it is none of the well-known fds, it must be an
1848 * stdout stream fd. Note that this is a bit ugly here
1849 * (since we rely that none of the well-known fds
1850 * could be interpreted as pointer), but nonetheless
1851 * safe, since the well-known fds would never get an
1852 * fd > 4096, i.e. beyond the first memory page */
1854 stream = ev->data.ptr;
1856 if (stdout_stream_process(stream) <= 0)
1857 stdout_stream_free(stream);
1862 log_error("Unknown event.");
1866 static int open_syslog_socket(Server *s) {
1867 union sockaddr_union sa;
1869 struct epoll_event ev;
1874 if (s->syslog_fd < 0) {
1876 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1877 if (s->syslog_fd < 0) {
1878 log_error("socket() failed: %m");
1883 sa.un.sun_family = AF_UNIX;
1884 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
1886 unlink(sa.un.sun_path);
1888 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1890 log_error("bind() failed: %m");
1894 chmod(sa.un.sun_path, 0666);
1898 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1900 log_error("SO_PASSCRED failed: %m");
1905 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1907 log_error("SO_TIMESTAMP failed: %m");
1911 /* Since we use the same socket for forwarding this to some
1912 * other syslog implementation, make sure we don't hang
1914 timeval_store(&tv, SYSLOG_TIMEOUT_USEC);
1915 if (setsockopt(s->syslog_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) {
1916 log_error("SO_SNDTIMEO failed: %m");
1921 ev.events = EPOLLIN;
1922 ev.data.fd = s->syslog_fd;
1923 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
1924 log_error("Failed to add syslog server fd to epoll object: %m");
1931 static int open_native_socket(Server*s) {
1932 union sockaddr_union sa;
1934 struct epoll_event ev;
1938 if (s->native_fd < 0) {
1940 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1941 if (s->native_fd < 0) {
1942 log_error("socket() failed: %m");
1947 sa.un.sun_family = AF_UNIX;
1948 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
1950 unlink(sa.un.sun_path);
1952 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
1954 log_error("bind() failed: %m");
1958 chmod(sa.un.sun_path, 0666);
1962 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1964 log_error("SO_PASSCRED failed: %m");
1969 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
1971 log_error("SO_TIMESTAMP failed: %m");
1976 ev.events = EPOLLIN;
1977 ev.data.fd = s->native_fd;
1978 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
1979 log_error("Failed to add native server fd to epoll object: %m");
1986 static int open_stdout_socket(Server *s) {
1987 union sockaddr_union sa;
1989 struct epoll_event ev;
1993 if (s->stdout_fd < 0) {
1995 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1996 if (s->stdout_fd < 0) {
1997 log_error("socket() failed: %m");
2002 sa.un.sun_family = AF_UNIX;
2003 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2005 unlink(sa.un.sun_path);
2007 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2009 log_error("bind() failed: %m");
2013 chmod(sa.un.sun_path, 0666);
2015 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2016 log_error("liste() failed: %m");
2022 ev.events = EPOLLIN;
2023 ev.data.fd = s->stdout_fd;
2024 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2025 log_error("Failed to add stdout server fd to epoll object: %m");
2032 static int open_signalfd(Server *s) {
2034 struct epoll_event ev;
2038 assert_se(sigemptyset(&mask) == 0);
2039 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2040 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2042 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2043 if (s->signal_fd < 0) {
2044 log_error("signalfd(): %m");
2049 ev.events = EPOLLIN;
2050 ev.data.fd = s->signal_fd;
2052 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2053 log_error("epoll_ctl(): %m");
2060 static int server_parse_config_file(Server *s) {
2067 fn = "/etc/systemd/systemd-journald.conf";
2068 f = fopen(fn, "re");
2070 if (errno == ENOENT)
2073 log_warning("Failed to open configuration file %s: %m", fn);
2077 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2079 log_warning("Failed to parse configuration file: %s", strerror(-r));
2086 static int server_init(Server *s) {
2092 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = -1;
2095 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2096 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2098 s->forward_to_syslog = true;
2100 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2101 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2103 server_parse_config_file(s);
2105 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2106 if (!s->user_journals) {
2107 log_error("Out of memory.");
2111 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2112 if (s->epoll_fd < 0) {
2113 log_error("Failed to create epoll object: %m");
2117 n = sd_listen_fds(true);
2119 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2123 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2125 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2127 if (s->native_fd >= 0) {
2128 log_error("Too many native sockets passed.");
2134 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2136 if (s->stdout_fd >= 0) {
2137 log_error("Too many stdout sockets passed.");
2143 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2145 if (s->syslog_fd >= 0) {
2146 log_error("Too many /dev/log sockets passed.");
2153 log_error("Unknown socket passed.");
2158 r = open_syslog_socket(s);
2162 r = open_native_socket(s);
2166 r = open_stdout_socket(s);
2170 r = system_journal_open(s);
2174 r = open_signalfd(s);
2178 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2185 static void server_done(Server *s) {
2189 while (s->stdout_streams)
2190 stdout_stream_free(s->stdout_streams);
2192 if (s->system_journal)
2193 journal_file_close(s->system_journal);
2195 if (s->runtime_journal)
2196 journal_file_close(s->runtime_journal);
2198 while ((f = hashmap_steal_first(s->user_journals)))
2199 journal_file_close(f);
2201 hashmap_free(s->user_journals);
2203 if (s->epoll_fd >= 0)
2204 close_nointr_nofail(s->epoll_fd);
2206 if (s->signal_fd >= 0)
2207 close_nointr_nofail(s->signal_fd);
2209 if (s->syslog_fd >= 0)
2210 close_nointr_nofail(s->syslog_fd);
2212 if (s->native_fd >= 0)
2213 close_nointr_nofail(s->native_fd);
2215 if (s->stdout_fd >= 0)
2216 close_nointr_nofail(s->stdout_fd);
2219 journal_rate_limit_free(s->rate_limit);
2224 int main(int argc, char *argv[]) {
2228 /* if (getppid() != 1) { */
2229 /* log_error("This program should be invoked by init only."); */
2230 /* return EXIT_FAILURE; */
2234 log_error("This program does not take arguments.");
2235 return EXIT_FAILURE;
2238 log_set_target(LOG_TARGET_CONSOLE);
2239 log_parse_environment();
2244 r = server_init(&server);
2248 server_vacuum(&server);
2249 server_flush_to_var(&server);
2251 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2252 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2256 "STATUS=Processing requests...");
2259 struct epoll_event event;
2261 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2267 log_error("epoll_wait() failed: %m");
2273 r = process_event(&server, &event);
2280 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2281 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2285 "STATUS=Shutting down...");
2287 server_done(&server);
2289 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;