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 <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <sys/statvfs.h>
33 #include <systemd/sd-journal.h>
34 #include <systemd/sd-login.h>
35 #include <systemd/sd-messages.h>
36 #include <systemd/sd-daemon.h>
39 #include "journal-file.h"
40 #include "socket-util.h"
41 #include "cgroup-util.h"
43 #include "journal-rate-limit.h"
44 #include "journal-internal.h"
45 #include "conf-parser.h"
51 #include <acl/libacl.h>
56 #include <selinux/selinux.h>
59 #define USER_JOURNALS_MAX 1024
60 #define STDOUT_STREAMS_MAX 4096
62 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
63 #define DEFAULT_RATE_LIMIT_BURST 200
65 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
67 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
69 #define SYSLOG_TIMEOUT_USEC (250*USEC_PER_MSEC)
71 #define N_IOVEC_META_FIELDS 17
73 typedef enum StdoutStreamState {
74 STDOUT_STREAM_IDENTIFIER,
75 STDOUT_STREAM_PRIORITY,
76 STDOUT_STREAM_LEVEL_PREFIX,
77 STDOUT_STREAM_FORWARD_TO_SYSLOG,
78 STDOUT_STREAM_FORWARD_TO_KMSG,
79 STDOUT_STREAM_FORWARD_TO_CONSOLE,
85 StdoutStreamState state;
94 bool forward_to_syslog:1;
95 bool forward_to_kmsg:1;
96 bool forward_to_console:1;
98 char buffer[LINE_MAX+1];
101 LIST_FIELDS(StdoutStream, stdout_stream);
104 static int server_flush_to_var(Server *s);
106 static uint64_t available_space(Server *s) {
111 uint64_t sum = 0, avail = 0, ss_avail = 0;
117 ts = now(CLOCK_MONOTONIC);
119 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
120 return s->cached_available_space;
122 r = sd_id128_get_machine(&machine);
126 if (s->system_journal) {
127 f = "/var/log/journal/";
128 m = &s->system_metrics;
130 f = "/run/log/journal/";
131 m = &s->runtime_metrics;
136 p = strappend(f, sd_id128_to_string(machine, ids));
146 if (fstatvfs(dirfd(d), &ss) < 0)
151 struct dirent buf, *de;
154 k = readdir_r(d, &buf, &de);
163 if (!dirent_is_file_with_suffix(de, ".journal"))
166 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
169 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
172 avail = sum >= m->max_use ? 0 : m->max_use - sum;
174 ss_avail = ss.f_bsize * ss.f_bavail;
176 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
178 if (ss_avail < avail)
181 s->cached_available_space = avail;
182 s->cached_available_space_timestamp = ts;
190 static void server_read_file_gid(Server *s) {
191 const char *adm = "adm";
196 if (s->file_gid_valid)
199 r = get_group_creds(&adm, &s->file_gid);
201 log_warning("Failed to resolve 'adm' group: %s", strerror(-r));
203 /* if we couldn't read the gid, then it will be 0, but that's
204 * fine and we shouldn't try to resolve the group again, so
205 * let's just pretend it worked right-away. */
206 s->file_gid_valid = true;
209 static void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
214 acl_permset_t permset;
219 server_read_file_gid(s);
221 r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
223 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
229 acl = acl_get_fd(f->fd);
231 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
235 r = acl_find_uid(acl, uid, &entry);
238 if (acl_create_entry(&acl, &entry) < 0 ||
239 acl_set_tag_type(entry, ACL_USER) < 0 ||
240 acl_set_qualifier(entry, &uid) < 0) {
241 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
246 if (acl_get_permset(entry, &permset) < 0 ||
247 acl_add_perm(permset, ACL_READ) < 0 ||
248 acl_calc_mask(&acl) < 0) {
249 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
253 if (acl_set_fd(f->fd, acl) < 0)
254 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
261 static JournalFile* find_journal(Server *s, uid_t uid) {
270 /* We split up user logs only on /var, not on /run. If the
271 * runtime file is open, we write to it exclusively, in order
272 * to guarantee proper order as soon as we flush /run to
273 * /var and close the runtime file. */
275 if (s->runtime_journal)
276 return s->runtime_journal;
279 return s->system_journal;
281 r = sd_id128_get_machine(&machine);
283 return s->system_journal;
285 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
289 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
290 return s->system_journal;
292 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
293 /* Too many open? Then let's close one */
294 f = hashmap_steal_first(s->user_journals);
296 journal_file_close(f);
299 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
303 return s->system_journal;
305 server_fix_perms(s, f, uid);
306 f->metrics = s->system_metrics;
307 f->compress = s->compress;
309 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
311 journal_file_close(f);
312 return s->system_journal;
318 static void server_rotate(Server *s) {
324 log_info("Rotating...");
326 if (s->runtime_journal) {
327 r = journal_file_rotate(&s->runtime_journal);
329 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
332 if (s->system_journal) {
333 r = journal_file_rotate(&s->system_journal);
335 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
338 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
339 r = journal_file_rotate(&f);
341 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
343 hashmap_replace(s->user_journals, k, f);
347 static void server_vacuum(Server *s) {
353 log_info("Vacuuming...");
355 r = sd_id128_get_machine(&machine);
357 log_error("Failed to get machine ID: %s", strerror(-r));
361 sd_id128_to_string(machine, ids);
363 if (s->system_journal) {
364 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
365 log_error("Out of memory.");
369 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
370 if (r < 0 && r != -ENOENT)
371 log_error("Failed to vacuum %s: %s", p, strerror(-r));
376 if (s->runtime_journal) {
377 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
378 log_error("Out of memory.");
382 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
383 if (r < 0 && r != -ENOENT)
384 log_error("Failed to vacuum %s: %s", p, strerror(-r));
388 s->cached_available_space_timestamp = 0;
391 static char *shortened_cgroup_path(pid_t pid) {
393 char *process_path, *init_path, *path;
397 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
401 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
407 if (endswith(init_path, "/system"))
408 init_path[strlen(init_path) - 7] = 0;
409 else if (streq(init_path, "/"))
412 if (startswith(process_path, init_path)) {
415 p = strdup(process_path + strlen(init_path));
433 static void dispatch_message_real(Server *s,
434 struct iovec *iovec, unsigned n, unsigned m,
436 struct timeval *tv) {
438 char *pid = NULL, *uid = NULL, *gid = NULL,
439 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
440 *comm = NULL, *cmdline = NULL, *hostname = NULL,
441 *audit_session = NULL, *audit_loginuid = NULL,
442 *exe = NULL, *cgroup = NULL, *session = NULL,
443 *owner_uid = NULL, *unit = NULL, *selinux_context = NULL;
449 uid_t loginuid = 0, realuid = 0;
451 bool vacuumed = false;
456 assert(n + N_IOVEC_META_FIELDS <= m);
462 security_context_t con;
465 realuid = ucred->uid;
467 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
468 IOVEC_SET_STRING(iovec[n++], pid);
470 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
471 IOVEC_SET_STRING(iovec[n++], uid);
473 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
474 IOVEC_SET_STRING(iovec[n++], gid);
476 r = get_process_comm(ucred->pid, &t);
478 comm = strappend("_COMM=", t);
482 IOVEC_SET_STRING(iovec[n++], comm);
485 r = get_process_exe(ucred->pid, &t);
487 exe = strappend("_EXE=", t);
491 IOVEC_SET_STRING(iovec[n++], exe);
494 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
496 cmdline = strappend("_CMDLINE=", t);
500 IOVEC_SET_STRING(iovec[n++], cmdline);
503 r = audit_session_from_pid(ucred->pid, &audit);
505 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
506 IOVEC_SET_STRING(iovec[n++], audit_session);
508 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
510 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
511 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
513 t = shortened_cgroup_path(ucred->pid);
515 cgroup = strappend("_SYSTEMD_CGROUP=", t);
519 IOVEC_SET_STRING(iovec[n++], cgroup);
522 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
523 session = strappend("_SYSTEMD_SESSION=", t);
527 IOVEC_SET_STRING(iovec[n++], session);
530 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
531 unit = strappend("_SYSTEMD_UNIT=", t);
535 IOVEC_SET_STRING(iovec[n++], unit);
538 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
539 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
540 IOVEC_SET_STRING(iovec[n++], owner_uid);
543 if (getpidcon(ucred->pid, &con) >= 0) {
544 selinux_context = strappend("_SELINUX_CONTEXT=", con);
546 IOVEC_SET_STRING(iovec[n++], selinux_context);
554 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
555 (unsigned long long) timeval_load(tv)) >= 0)
556 IOVEC_SET_STRING(iovec[n++], source_time);
559 /* Note that strictly speaking storing the boot id here is
560 * redundant since the entry includes this in-line
561 * anyway. However, we need this indexed, too. */
562 r = sd_id128_get_boot(&id);
564 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
565 IOVEC_SET_STRING(iovec[n++], boot_id);
567 r = sd_id128_get_machine(&id);
569 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
570 IOVEC_SET_STRING(iovec[n++], machine_id);
572 t = gethostname_malloc();
574 hostname = strappend("_HOSTNAME=", t);
577 IOVEC_SET_STRING(iovec[n++], hostname);
582 server_flush_to_var(s);
585 f = find_journal(s, realuid == 0 ? 0 : loginuid);
587 log_warning("Dropping message, as we can't find a place to store the data.");
589 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
591 if (r == -E2BIG && !vacuumed) {
592 log_info("Allocation limit reached.");
598 log_info("Retrying write.");
603 log_error("Failed to write entry, ignoring: %s", strerror(-r));
617 free(audit_loginuid);
622 free(selinux_context);
625 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
626 char mid[11 + 32 + 1];
627 char buffer[16 + LINE_MAX + 1];
628 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
636 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
637 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
639 memcpy(buffer, "MESSAGE=", 8);
640 va_start(ap, format);
641 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
643 char_array_0(buffer);
644 IOVEC_SET_STRING(iovec[n++], buffer);
646 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
648 IOVEC_SET_STRING(iovec[n++], mid);
651 ucred.pid = getpid();
652 ucred.uid = getuid();
653 ucred.gid = getgid();
655 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL);
658 static void dispatch_message(Server *s,
659 struct iovec *iovec, unsigned n, unsigned m,
664 char *path = NULL, *c;
667 assert(iovec || n == 0);
675 path = shortened_cgroup_path(ucred->pid);
679 /* example: /user/lennart/3/foobar
680 * /system/dbus.service/foobar
682 * So let's cut of everything past the third /, since that is
683 * wher user directories start */
685 c = strchr(path, '/');
687 c = strchr(c+1, '/');
689 c = strchr(c+1, '/');
695 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
702 /* Write a suppression message if we suppressed something */
704 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
709 dispatch_message_real(s, iovec, n, m, ucred, tv);
712 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
713 struct msghdr msghdr;
714 struct cmsghdr *cmsg;
716 struct cmsghdr cmsghdr;
717 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
719 union sockaddr_union sa;
726 msghdr.msg_iov = (struct iovec*) iovec;
727 msghdr.msg_iovlen = n_iovec;
730 sa.un.sun_family = AF_UNIX;
731 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
732 msghdr.msg_name = &sa;
733 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
737 msghdr.msg_control = &control;
738 msghdr.msg_controllen = sizeof(control);
740 cmsg = CMSG_FIRSTHDR(&msghdr);
741 cmsg->cmsg_level = SOL_SOCKET;
742 cmsg->cmsg_type = SCM_CREDENTIALS;
743 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
744 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
745 msghdr.msg_controllen = cmsg->cmsg_len;
748 /* Forward the syslog message we received via /dev/log to
749 * /run/systemd/syslog. Unfortunately we currently can't set
750 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
752 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
755 /* The socket is full? I guess the syslog implementation is
756 * too slow, and we shouldn't wait for that... */
760 if (ucred && errno == ESRCH) {
763 /* Hmm, presumably the sender process vanished
764 * by now, so let's fix it as good as we
769 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
771 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
778 log_debug("Failed to forward syslog message: %m");
781 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
787 IOVEC_SET_STRING(iovec, buffer);
788 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
791 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
792 struct iovec iovec[5];
793 char header_priority[6], header_time[64], header_pid[16];
797 char *ident_buf = NULL;
800 assert(priority >= 0);
801 assert(priority <= 999);
804 /* First: priority field */
805 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
806 char_array_0(header_priority);
807 IOVEC_SET_STRING(iovec[n++], header_priority);
809 /* Second: timestamp */
810 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
814 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
816 IOVEC_SET_STRING(iovec[n++], header_time);
818 /* Third: identifier and PID */
821 get_process_comm(ucred->pid, &ident_buf);
822 identifier = ident_buf;
825 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
826 char_array_0(header_pid);
829 IOVEC_SET_STRING(iovec[n++], identifier);
831 IOVEC_SET_STRING(iovec[n++], header_pid);
832 } else if (identifier) {
833 IOVEC_SET_STRING(iovec[n++], identifier);
834 IOVEC_SET_STRING(iovec[n++], ": ");
837 /* Fourth: message */
838 IOVEC_SET_STRING(iovec[n++], message);
840 forward_syslog_iovec(s, iovec, n, ucred, tv);
845 static int fixup_priority(int priority) {
847 if ((priority & LOG_FACMASK) == 0)
848 return (priority & LOG_PRIMASK) | LOG_USER;
853 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
854 struct iovec iovec[5];
855 char header_priority[6], header_pid[16];
857 char *ident_buf = NULL;
861 assert(priority >= 0);
862 assert(priority <= 999);
865 /* Never allow messages with kernel facility to be written to
866 * kmsg, regardless where the data comes from. */
867 priority = fixup_priority(priority);
869 /* First: priority field */
870 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
871 char_array_0(header_priority);
872 IOVEC_SET_STRING(iovec[n++], header_priority);
874 /* Second: identifier and PID */
877 get_process_comm(ucred->pid, &ident_buf);
878 identifier = ident_buf;
881 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
882 char_array_0(header_pid);
885 IOVEC_SET_STRING(iovec[n++], identifier);
887 IOVEC_SET_STRING(iovec[n++], header_pid);
888 } else if (identifier) {
889 IOVEC_SET_STRING(iovec[n++], identifier);
890 IOVEC_SET_STRING(iovec[n++], ": ");
893 /* Fourth: message */
894 IOVEC_SET_STRING(iovec[n++], message);
895 IOVEC_SET_STRING(iovec[n++], "\n");
897 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
899 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
903 if (writev(fd, iovec, n) < 0)
904 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
906 close_nointr_nofail(fd);
912 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
913 struct iovec iovec[4];
916 char *ident_buf = NULL;
921 /* First: identifier and PID */
924 get_process_comm(ucred->pid, &ident_buf);
925 identifier = ident_buf;
928 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
929 char_array_0(header_pid);
932 IOVEC_SET_STRING(iovec[n++], identifier);
934 IOVEC_SET_STRING(iovec[n++], header_pid);
935 } else if (identifier) {
936 IOVEC_SET_STRING(iovec[n++], identifier);
937 IOVEC_SET_STRING(iovec[n++], ": ");
941 IOVEC_SET_STRING(iovec[n++], message);
942 IOVEC_SET_STRING(iovec[n++], "\n");
944 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
946 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
950 if (writev(fd, iovec, n) < 0)
951 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
953 close_nointr_nofail(fd);
959 static void read_identifier(const char **buf, char **identifier, char **pid) {
970 p += strspn(p, WHITESPACE);
971 l = strcspn(p, WHITESPACE);
986 t = strndup(p+k+1, l-k-2);
1006 *buf += strspn(*buf, WHITESPACE);
1009 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
1010 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1011 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1013 int priority = LOG_USER | LOG_INFO;
1014 char *identifier = NULL, *pid = NULL;
1019 if (s->forward_to_syslog)
1020 forward_syslog_raw(s, buf, ucred, tv);
1022 parse_syslog_priority((char**) &buf, &priority);
1023 skip_syslog_date((char**) &buf);
1024 read_identifier(&buf, &identifier, &pid);
1026 if (s->forward_to_kmsg)
1027 forward_kmsg(s, priority, identifier, buf, ucred);
1029 if (s->forward_to_console)
1030 forward_console(s, identifier, buf, ucred);
1032 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1034 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1035 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1037 if (priority & LOG_FACMASK)
1038 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1039 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1042 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1043 if (syslog_identifier)
1044 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1048 syslog_pid = strappend("SYSLOG_PID=", pid);
1050 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1053 message = strappend("MESSAGE=", buf);
1055 IOVEC_SET_STRING(iovec[n++], message);
1057 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, priority);
1062 free(syslog_priority);
1063 free(syslog_facility);
1064 free(syslog_identifier);
1067 static bool valid_user_field(const char *p, size_t l) {
1070 /* We kinda enforce POSIX syntax recommendations for
1071 environment variables here, but make a couple of additional
1074 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1076 /* No empty field names */
1080 /* Don't allow names longer than 64 chars */
1084 /* Variables starting with an underscore are protected */
1088 /* Don't allow digits as first character */
1089 if (p[0] >= '0' && p[0] <= '9')
1092 /* Only allow A-Z0-9 and '_' */
1093 for (a = p; a < p + l; a++)
1094 if (!((*a >= 'A' && *a <= 'Z') ||
1095 (*a >= '0' && *a <= '9') ||
1102 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
1103 struct iovec *iovec = NULL;
1104 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1107 int priority = LOG_INFO;
1108 char *identifier = NULL, *message = NULL;
1111 assert(buffer || n == 0);
1114 remaining = buffer_size;
1116 while (remaining > 0) {
1119 e = memchr(p, '\n', remaining);
1122 /* Trailing noise, let's ignore it, and flush what we collected */
1123 log_debug("Received message with trailing noise, ignoring.");
1128 /* Entry separator */
1129 dispatch_message(s, iovec, n, m, ucred, tv, priority);
1131 priority = LOG_INFO;
1138 if (*p == '.' || *p == '#') {
1139 /* Ignore control commands for now, and
1141 remaining -= (e - p) + 1;
1146 /* A property follows */
1148 if (n+N_IOVEC_META_FIELDS >= m) {
1152 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1153 c = realloc(iovec, u * sizeof(struct iovec));
1155 log_error("Out of memory");
1163 q = memchr(p, '=', e - p);
1165 if (valid_user_field(p, q - p)) {
1170 /* If the field name starts with an
1171 * underscore, skip the variable,
1172 * since that indidates a trusted
1174 iovec[n].iov_base = (char*) p;
1175 iovec[n].iov_len = l;
1178 /* We need to determine the priority
1179 * of this entry for the rate limiting
1182 memcmp(p, "PRIORITY=", 9) == 0 &&
1183 p[9] >= '0' && p[9] <= '9')
1184 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1187 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1188 p[16] >= '0' && p[16] <= '9')
1189 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1192 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1193 p[16] >= '0' && p[16] <= '9' &&
1194 p[17] >= '0' && p[17] <= '9')
1195 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1198 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1201 t = strndup(p + 11, l - 11);
1206 } else if (l >= 8 &&
1207 memcmp(p, "MESSAGE=", 8) == 0) {
1210 t = strndup(p + 8, l - 8);
1218 remaining -= (e - p) + 1;
1225 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1226 log_debug("Failed to parse message, ignoring.");
1230 memcpy(&l, e + 1, sizeof(uint64_t));
1233 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1234 e[1+sizeof(uint64_t)+l] != '\n') {
1235 log_debug("Failed to parse message, ignoring.");
1239 k = malloc((e - p) + 1 + l);
1241 log_error("Out of memory");
1245 memcpy(k, p, e - p);
1247 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1249 if (valid_user_field(p, e - p)) {
1250 iovec[n].iov_base = k;
1251 iovec[n].iov_len = (e - p) + 1 + l;
1256 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1257 p = e + 1 + sizeof(uint64_t) + l + 1;
1265 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1268 if (s->forward_to_syslog)
1269 forward_syslog(s, priority, identifier, message, ucred, tv);
1271 if (s->forward_to_kmsg)
1272 forward_kmsg(s, priority, identifier, message, ucred);
1274 if (s->forward_to_console)
1275 forward_console(s, identifier, message, ucred);
1278 dispatch_message(s, iovec, n, m, ucred, tv, priority);
1281 for (j = 0; j < n; j++) {
1285 if (iovec[j].iov_base < buffer ||
1286 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1287 free(iovec[j].iov_base);
1294 static int stdout_stream_log(StdoutStream *s, const char *p) {
1295 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1296 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1303 priority = s->priority;
1305 if (s->level_prefix)
1306 parse_syslog_priority((char**) &p, &priority);
1308 if (s->forward_to_syslog || s->server->forward_to_syslog)
1309 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1311 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1312 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1314 if (s->forward_to_console || s->server->forward_to_console)
1315 forward_console(s->server, s->identifier, p, &s->ucred);
1317 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1319 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1320 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1322 if (priority & LOG_FACMASK)
1323 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1324 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1326 if (s->identifier) {
1327 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1328 if (syslog_identifier)
1329 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1332 message = strappend("MESSAGE=", p);
1334 IOVEC_SET_STRING(iovec[n++], message);
1336 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, priority);
1339 free(syslog_priority);
1340 free(syslog_facility);
1341 free(syslog_identifier);
1346 static int stdout_stream_line(StdoutStream *s, char *p) {
1356 case STDOUT_STREAM_IDENTIFIER:
1357 s->identifier = strdup(p);
1358 if (!s->identifier) {
1359 log_error("Out of memory");
1363 s->state = STDOUT_STREAM_PRIORITY;
1366 case STDOUT_STREAM_PRIORITY:
1367 r = safe_atoi(p, &s->priority);
1368 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1369 log_warning("Failed to parse log priority line.");
1373 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1376 case STDOUT_STREAM_LEVEL_PREFIX:
1377 r = parse_boolean(p);
1379 log_warning("Failed to parse level prefix line.");
1383 s->level_prefix = !!r;
1384 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1387 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1388 r = parse_boolean(p);
1390 log_warning("Failed to parse forward to syslog line.");
1394 s->forward_to_syslog = !!r;
1395 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1398 case STDOUT_STREAM_FORWARD_TO_KMSG:
1399 r = parse_boolean(p);
1401 log_warning("Failed to parse copy to kmsg line.");
1405 s->forward_to_kmsg = !!r;
1406 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1409 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1410 r = parse_boolean(p);
1412 log_warning("Failed to parse copy to console line.");
1416 s->forward_to_console = !!r;
1417 s->state = STDOUT_STREAM_RUNNING;
1420 case STDOUT_STREAM_RUNNING:
1421 return stdout_stream_log(s, p);
1424 assert_not_reached("Unknown stream state");
1427 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1435 remaining = s->length;
1440 end = memchr(p, '\n', remaining);
1443 else if (remaining >= sizeof(s->buffer) - 1) {
1444 end = p + sizeof(s->buffer) - 1;
1451 r = stdout_stream_line(s, p);
1459 if (force_flush && remaining > 0) {
1461 r = stdout_stream_line(s, p);
1469 if (p > s->buffer) {
1470 memmove(s->buffer, p, remaining);
1471 s->length = remaining;
1477 static int stdout_stream_process(StdoutStream *s) {
1483 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1486 if (errno == EAGAIN)
1489 log_warning("Failed to read from stream: %m");
1494 r = stdout_stream_scan(s, true);
1502 r = stdout_stream_scan(s, false);
1510 static void stdout_stream_free(StdoutStream *s) {
1514 assert(s->server->n_stdout_streams > 0);
1515 s->server->n_stdout_streams --;
1516 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1521 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1523 close_nointr_nofail(s->fd);
1526 free(s->identifier);
1530 static int stdout_stream_new(Server *s) {
1531 StdoutStream *stream;
1534 struct epoll_event ev;
1538 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1540 if (errno == EAGAIN)
1543 log_error("Failed to accept stdout connection: %m");
1547 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1548 log_warning("Too many stdout streams, refusing connection.");
1549 close_nointr_nofail(fd);
1553 stream = new0(StdoutStream, 1);
1555 log_error("Out of memory.");
1556 close_nointr_nofail(fd);
1562 len = sizeof(stream->ucred);
1563 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1564 log_error("Failed to determine peer credentials: %m");
1569 if (shutdown(fd, SHUT_WR) < 0) {
1570 log_error("Failed to shutdown writing side of socket: %m");
1576 ev.data.ptr = stream;
1577 ev.events = EPOLLIN;
1578 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1579 log_error("Failed to add stream to event loop: %m");
1585 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1586 s->n_stdout_streams ++;
1591 stdout_stream_free(stream);
1595 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1606 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1611 for (i = 1; i <= 5; i++) {
1617 k = undecchar(p[i]);
1624 for (i = 7; i <= 12; i++) {
1627 k = undecchar(p[i]);
1636 *_p += strspn(*_p, WHITESPACE);
1641 static void proc_kmsg_line(Server *s, const char *p) {
1642 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1643 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1644 int priority = LOG_KERN | LOG_INFO;
1647 char *identifier = NULL, *pid = NULL;
1652 parse_syslog_priority((char **) &p, &priority);
1654 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1657 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1658 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1659 (unsigned long long) usec) >= 0)
1660 IOVEC_SET_STRING(iovec[n++], source_time);
1663 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1665 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1666 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1668 if ((priority & LOG_FACMASK) == LOG_KERN) {
1670 if (s->forward_to_syslog)
1671 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1673 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1675 read_identifier(&p, &identifier, &pid);
1677 if (s->forward_to_syslog)
1678 forward_syslog(s, priority, identifier, p, NULL, NULL);
1681 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1682 if (syslog_identifier)
1683 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1687 syslog_pid = strappend("SYSLOG_PID=", pid);
1689 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1692 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1693 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1696 message = strappend("MESSAGE=", p);
1698 IOVEC_SET_STRING(iovec[n++], message);
1701 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, priority);
1704 free(syslog_priority);
1705 free(syslog_identifier);
1707 free(syslog_facility);
1713 static void proc_kmsg_scan(Server *s) {
1719 p = s->proc_kmsg_buffer;
1720 remaining = s->proc_kmsg_length;
1725 end = memchr(p, '\n', remaining);
1728 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1729 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1736 proc_kmsg_line(s, p);
1742 if (p > s->proc_kmsg_buffer) {
1743 memmove(s->proc_kmsg_buffer, p, remaining);
1744 s->proc_kmsg_length = remaining;
1748 static int system_journal_open(Server *s) {
1754 r = sd_id128_get_machine(&machine);
1758 sd_id128_to_string(machine, ids);
1760 if (!s->system_journal) {
1762 /* First try to create the machine path, but not the prefix */
1763 fn = strappend("/var/log/journal/", ids);
1766 (void) mkdir(fn, 0755);
1769 /* The create the system journal file */
1770 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1774 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1778 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1780 s->system_journal->metrics = s->system_metrics;
1781 s->system_journal->compress = s->compress;
1783 server_fix_perms(s, s->system_journal, 0);
1786 if (r != -ENOENT && r != -EROFS)
1787 log_warning("Failed to open system journal: %s", strerror(-r));
1793 if (!s->runtime_journal) {
1795 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1799 if (s->system_journal) {
1801 /* Try to open the runtime journal, but only
1802 * if it already exists, so that we can flush
1803 * it into the system journal */
1805 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1810 log_warning("Failed to open runtime journal: %s", strerror(-r));
1817 /* OK, we really need the runtime journal, so create
1818 * it if necessary. */
1820 (void) mkdir_parents(fn, 0755);
1821 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1825 log_error("Failed to open runtime journal: %s", strerror(-r));
1830 if (s->runtime_journal) {
1831 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1833 s->runtime_journal->metrics = s->runtime_metrics;
1834 s->runtime_journal->compress = s->compress;
1836 server_fix_perms(s, s->runtime_journal, 0);
1843 static int server_flush_to_var(Server *s) {
1844 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1853 if (!s->runtime_journal)
1856 ts = now(CLOCK_MONOTONIC);
1857 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1860 s->var_available_timestamp = ts;
1862 system_journal_open(s);
1864 if (!s->system_journal)
1867 log_info("Flushing to /var...");
1869 r = sd_id128_get_machine(&machine);
1871 log_error("Failed to get machine id: %s", strerror(-r));
1875 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1877 log_error("Failed to read runtime journal: %s", strerror(-r));
1881 SD_JOURNAL_FOREACH(j) {
1884 f = j->current_file;
1885 assert(f && f->current_offset > 0);
1887 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1889 log_error("Can't read entry: %s", strerror(-r));
1893 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1895 log_info("Allocation limit reached.");
1897 journal_file_post_change(s->system_journal);
1901 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1905 log_error("Can't write entry: %s", strerror(-r));
1911 journal_file_post_change(s->system_journal);
1913 journal_file_close(s->runtime_journal);
1914 s->runtime_journal = NULL;
1917 sd_id128_to_string(machine, path + 17);
1918 rm_rf(path, false, true, false);
1924 static int server_read_proc_kmsg(Server *s) {
1927 assert(s->proc_kmsg_fd >= 0);
1929 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
1932 if (errno == EAGAIN || errno == EINTR)
1935 log_error("Failed to read from kernel: %m");
1939 s->proc_kmsg_length += l;
1945 static int server_flush_proc_kmsg(Server *s) {
1950 if (s->proc_kmsg_fd < 0)
1953 log_info("Flushing /proc/kmsg...");
1956 r = server_read_proc_kmsg(s);
1967 static int process_event(Server *s, struct epoll_event *ev) {
1970 if (ev->data.fd == s->signal_fd) {
1971 struct signalfd_siginfo sfsi;
1974 if (ev->events != EPOLLIN) {
1975 log_info("Got invalid event from epoll.");
1979 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
1980 if (n != sizeof(sfsi)) {
1985 if (errno == EINTR || errno == EAGAIN)
1991 if (sfsi.ssi_signo == SIGUSR1) {
1992 server_flush_to_var(s);
1996 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
1999 } else if (ev->data.fd == s->proc_kmsg_fd) {
2002 if (ev->events != EPOLLIN) {
2003 log_info("Got invalid event from epoll.");
2007 r = server_read_proc_kmsg(s);
2013 } else if (ev->data.fd == s->native_fd ||
2014 ev->data.fd == s->syslog_fd) {
2016 if (ev->events != EPOLLIN) {
2017 log_info("Got invalid event from epoll.");
2022 struct msghdr msghdr;
2024 struct ucred *ucred = NULL;
2025 struct timeval *tv = NULL;
2026 struct cmsghdr *cmsg;
2028 struct cmsghdr cmsghdr;
2029 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2030 CMSG_SPACE(sizeof(struct timeval))];
2035 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2036 log_error("SIOCINQ failed: %m");
2043 if (s->buffer_size < (size_t) v) {
2047 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2048 b = realloc(s->buffer, l+1);
2051 log_error("Couldn't increase buffer.");
2060 iovec.iov_base = s->buffer;
2061 iovec.iov_len = s->buffer_size;
2065 msghdr.msg_iov = &iovec;
2066 msghdr.msg_iovlen = 1;
2067 msghdr.msg_control = &control;
2068 msghdr.msg_controllen = sizeof(control);
2070 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
2073 if (errno == EINTR || errno == EAGAIN)
2076 log_error("recvmsg() failed: %m");
2080 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2082 if (cmsg->cmsg_level == SOL_SOCKET &&
2083 cmsg->cmsg_type == SCM_CREDENTIALS &&
2084 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2085 ucred = (struct ucred*) CMSG_DATA(cmsg);
2086 else if (cmsg->cmsg_level == SOL_SOCKET &&
2087 cmsg->cmsg_type == SO_TIMESTAMP &&
2088 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2089 tv = (struct timeval*) CMSG_DATA(cmsg);
2092 if (ev->data.fd == s->syslog_fd) {
2095 e = memchr(s->buffer, '\n', n);
2101 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
2103 process_native_message(s, s->buffer, n, ucred, tv);
2108 } else if (ev->data.fd == s->stdout_fd) {
2110 if (ev->events != EPOLLIN) {
2111 log_info("Got invalid event from epoll.");
2115 stdout_stream_new(s);
2119 StdoutStream *stream;
2121 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2122 log_info("Got invalid event from epoll.");
2126 /* If it is none of the well-known fds, it must be an
2127 * stdout stream fd. Note that this is a bit ugly here
2128 * (since we rely that none of the well-known fds
2129 * could be interpreted as pointer), but nonetheless
2130 * safe, since the well-known fds would never get an
2131 * fd > 4096, i.e. beyond the first memory page */
2133 stream = ev->data.ptr;
2135 if (stdout_stream_process(stream) <= 0)
2136 stdout_stream_free(stream);
2141 log_error("Unknown event.");
2145 static int open_syslog_socket(Server *s) {
2146 union sockaddr_union sa;
2148 struct epoll_event ev;
2153 if (s->syslog_fd < 0) {
2155 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2156 if (s->syslog_fd < 0) {
2157 log_error("socket() failed: %m");
2162 sa.un.sun_family = AF_UNIX;
2163 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2165 unlink(sa.un.sun_path);
2167 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2169 log_error("bind() failed: %m");
2173 chmod(sa.un.sun_path, 0666);
2177 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2179 log_error("SO_PASSCRED failed: %m");
2184 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2186 log_error("SO_TIMESTAMP failed: %m");
2190 /* Since we use the same socket for forwarding this to some
2191 * other syslog implementation, make sure we don't hang
2193 timeval_store(&tv, SYSLOG_TIMEOUT_USEC);
2194 if (setsockopt(s->syslog_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) {
2195 log_error("SO_SNDTIMEO failed: %m");
2200 ev.events = EPOLLIN;
2201 ev.data.fd = s->syslog_fd;
2202 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2203 log_error("Failed to add syslog server fd to epoll object: %m");
2210 static int open_native_socket(Server*s) {
2211 union sockaddr_union sa;
2213 struct epoll_event ev;
2217 if (s->native_fd < 0) {
2219 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2220 if (s->native_fd < 0) {
2221 log_error("socket() failed: %m");
2226 sa.un.sun_family = AF_UNIX;
2227 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2229 unlink(sa.un.sun_path);
2231 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2233 log_error("bind() failed: %m");
2237 chmod(sa.un.sun_path, 0666);
2241 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2243 log_error("SO_PASSCRED failed: %m");
2248 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2250 log_error("SO_TIMESTAMP failed: %m");
2255 ev.events = EPOLLIN;
2256 ev.data.fd = s->native_fd;
2257 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2258 log_error("Failed to add native server fd to epoll object: %m");
2265 static int open_stdout_socket(Server *s) {
2266 union sockaddr_union sa;
2268 struct epoll_event ev;
2272 if (s->stdout_fd < 0) {
2274 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2275 if (s->stdout_fd < 0) {
2276 log_error("socket() failed: %m");
2281 sa.un.sun_family = AF_UNIX;
2282 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2284 unlink(sa.un.sun_path);
2286 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2288 log_error("bind() failed: %m");
2292 chmod(sa.un.sun_path, 0666);
2294 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2295 log_error("liste() failed: %m");
2301 ev.events = EPOLLIN;
2302 ev.data.fd = s->stdout_fd;
2303 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2304 log_error("Failed to add stdout server fd to epoll object: %m");
2311 static int open_proc_kmsg(Server *s) {
2312 struct epoll_event ev;
2316 if (!s->import_proc_kmsg)
2320 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2321 if (s->proc_kmsg_fd < 0) {
2322 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2327 ev.events = EPOLLIN;
2328 ev.data.fd = s->proc_kmsg_fd;
2329 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2330 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2337 static int open_signalfd(Server *s) {
2339 struct epoll_event ev;
2343 assert_se(sigemptyset(&mask) == 0);
2344 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2345 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2347 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2348 if (s->signal_fd < 0) {
2349 log_error("signalfd(): %m");
2354 ev.events = EPOLLIN;
2355 ev.data.fd = s->signal_fd;
2357 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2358 log_error("epoll_ctl(): %m");
2365 static int server_parse_proc_cmdline(Server *s) {
2366 char *line, *w, *state;
2370 if (detect_container(NULL) > 0)
2373 r = read_one_line_file("/proc/cmdline", &line);
2375 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2379 FOREACH_WORD_QUOTED(w, l, line, state) {
2382 word = strndup(w, l);
2388 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2389 r = parse_boolean(word + 35);
2391 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2393 s->forward_to_syslog = r;
2394 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2395 r = parse_boolean(word + 33);
2397 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2399 s->forward_to_kmsg = r;
2400 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2401 r = parse_boolean(word + 36);
2403 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2405 s->forward_to_console = r;
2418 static int server_parse_config_file(Server *s) {
2425 fn = "/etc/systemd/systemd-journald.conf";
2426 f = fopen(fn, "re");
2428 if (errno == ENOENT)
2431 log_warning("Failed to open configuration file %s: %m", fn);
2435 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2437 log_warning("Failed to parse configuration file: %s", strerror(-r));
2444 static int server_init(Server *s) {
2450 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2453 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2454 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2456 s->forward_to_syslog = true;
2457 s->import_proc_kmsg = true;
2459 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2460 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2462 server_parse_config_file(s);
2463 server_parse_proc_cmdline(s);
2465 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2466 if (!s->user_journals) {
2467 log_error("Out of memory.");
2471 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2472 if (s->epoll_fd < 0) {
2473 log_error("Failed to create epoll object: %m");
2477 n = sd_listen_fds(true);
2479 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2483 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2485 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2487 if (s->native_fd >= 0) {
2488 log_error("Too many native sockets passed.");
2494 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2496 if (s->stdout_fd >= 0) {
2497 log_error("Too many stdout sockets passed.");
2503 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2505 if (s->syslog_fd >= 0) {
2506 log_error("Too many /dev/log sockets passed.");
2513 log_error("Unknown socket passed.");
2518 r = open_syslog_socket(s);
2522 r = open_native_socket(s);
2526 r = open_stdout_socket(s);
2530 r = open_proc_kmsg(s);
2534 r = system_journal_open(s);
2538 r = open_signalfd(s);
2542 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2549 static void server_done(Server *s) {
2553 while (s->stdout_streams)
2554 stdout_stream_free(s->stdout_streams);
2556 if (s->system_journal)
2557 journal_file_close(s->system_journal);
2559 if (s->runtime_journal)
2560 journal_file_close(s->runtime_journal);
2562 while ((f = hashmap_steal_first(s->user_journals)))
2563 journal_file_close(f);
2565 hashmap_free(s->user_journals);
2567 if (s->epoll_fd >= 0)
2568 close_nointr_nofail(s->epoll_fd);
2570 if (s->signal_fd >= 0)
2571 close_nointr_nofail(s->signal_fd);
2573 if (s->syslog_fd >= 0)
2574 close_nointr_nofail(s->syslog_fd);
2576 if (s->native_fd >= 0)
2577 close_nointr_nofail(s->native_fd);
2579 if (s->stdout_fd >= 0)
2580 close_nointr_nofail(s->stdout_fd);
2582 if (s->proc_kmsg_fd >= 0)
2583 close_nointr_nofail(s->proc_kmsg_fd);
2586 journal_rate_limit_free(s->rate_limit);
2591 int main(int argc, char *argv[]) {
2595 /* if (getppid() != 1) { */
2596 /* log_error("This program should be invoked by init only."); */
2597 /* return EXIT_FAILURE; */
2601 log_error("This program does not take arguments.");
2602 return EXIT_FAILURE;
2605 log_set_target(LOG_TARGET_CONSOLE);
2606 log_parse_environment();
2611 r = server_init(&server);
2615 server_vacuum(&server);
2616 server_flush_to_var(&server);
2617 server_flush_proc_kmsg(&server);
2619 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2620 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2624 "STATUS=Processing requests...");
2627 struct epoll_event event;
2629 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2635 log_error("epoll_wait() failed: %m");
2641 r = process_event(&server, &event);
2648 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2649 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2653 "STATUS=Shutting down...");
2655 server_done(&server);
2657 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;