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"
52 #define USER_JOURNALS_MAX 1024
53 #define STDOUT_STREAMS_MAX 4096
55 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
56 #define DEFAULT_RATE_LIMIT_BURST 200
58 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
60 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
62 #define SYSLOG_TIMEOUT_USEC (250*USEC_PER_MSEC)
64 #define N_IOVEC_META_FIELDS 16
66 typedef enum StdoutStreamState {
67 STDOUT_STREAM_IDENTIFIER,
68 STDOUT_STREAM_PRIORITY,
69 STDOUT_STREAM_LEVEL_PREFIX,
70 STDOUT_STREAM_FORWARD_TO_SYSLOG,
71 STDOUT_STREAM_FORWARD_TO_KMSG,
72 STDOUT_STREAM_FORWARD_TO_CONSOLE,
78 StdoutStreamState state;
87 bool forward_to_syslog:1;
88 bool forward_to_kmsg:1;
89 bool forward_to_console:1;
91 char buffer[LINE_MAX+1];
94 LIST_FIELDS(StdoutStream, stdout_stream);
97 static int server_flush_to_var(Server *s);
99 static uint64_t available_space(Server *s) {
104 uint64_t sum = 0, avail = 0, ss_avail = 0;
110 ts = now(CLOCK_MONOTONIC);
112 if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
113 return s->cached_available_space;
115 r = sd_id128_get_machine(&machine);
119 if (s->system_journal) {
120 f = "/var/log/journal/";
121 m = &s->system_metrics;
123 f = "/run/log/journal/";
124 m = &s->runtime_metrics;
129 p = strappend(f, sd_id128_to_string(machine, ids));
139 if (fstatvfs(dirfd(d), &ss) < 0)
144 struct dirent buf, *de;
147 k = readdir_r(d, &buf, &de);
156 if (!dirent_is_file_with_suffix(de, ".journal"))
159 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
162 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
165 avail = sum >= m->max_use ? 0 : m->max_use - sum;
167 ss_avail = ss.f_bsize * ss.f_bavail;
169 ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
171 if (ss_avail < avail)
174 s->cached_available_space = avail;
175 s->cached_available_space_timestamp = ts;
183 static void fix_perms(JournalFile *f, uid_t uid) {
186 acl_permset_t permset;
191 r = fchmod_and_fchown(f->fd, 0640, 0, 0);
193 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
198 acl = acl_get_fd(f->fd);
200 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
204 r = acl_find_uid(acl, uid, &entry);
207 if (acl_create_entry(&acl, &entry) < 0 ||
208 acl_set_tag_type(entry, ACL_USER) < 0 ||
209 acl_set_qualifier(entry, &uid) < 0) {
210 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
215 if (acl_get_permset(entry, &permset) < 0 ||
216 acl_add_perm(permset, ACL_READ) < 0 ||
217 acl_calc_mask(&acl) < 0) {
218 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
222 if (acl_set_fd(f->fd, acl) < 0)
223 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
229 static JournalFile* find_journal(Server *s, uid_t uid) {
238 /* We split up user logs only on /var, not on /run. If the
239 * runtime file is open, we write to it exclusively, in order
240 * to guarantee proper order as soon as we flush /run to
241 * /var and close the runtime file. */
243 if (s->runtime_journal)
244 return s->runtime_journal;
247 return s->system_journal;
249 r = sd_id128_get_machine(&machine);
251 return s->system_journal;
253 f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
257 if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
258 return s->system_journal;
260 while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
261 /* Too many open? Then let's close one */
262 f = hashmap_steal_first(s->user_journals);
264 journal_file_close(f);
267 r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
271 return s->system_journal;
274 f->metrics = s->system_metrics;
275 f->compress = s->compress;
277 r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
279 journal_file_close(f);
280 return s->system_journal;
286 static void server_rotate(Server *s) {
292 log_info("Rotating...");
294 if (s->runtime_journal) {
295 r = journal_file_rotate(&s->runtime_journal);
297 log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
300 if (s->system_journal) {
301 r = journal_file_rotate(&s->system_journal);
303 log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
306 HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
307 r = journal_file_rotate(&f);
309 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
311 hashmap_replace(s->user_journals, k, f);
315 static void server_vacuum(Server *s) {
321 log_info("Vacuuming...");
323 r = sd_id128_get_machine(&machine);
325 log_error("Failed to get machine ID: %s", strerror(-r));
329 sd_id128_to_string(machine, ids);
331 if (s->system_journal) {
332 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
333 log_error("Out of memory.");
337 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
338 if (r < 0 && r != -ENOENT)
339 log_error("Failed to vacuum %s: %s", p, strerror(-r));
344 if (s->runtime_journal) {
345 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
346 log_error("Out of memory.");
350 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
351 if (r < 0 && r != -ENOENT)
352 log_error("Failed to vacuum %s: %s", p, strerror(-r));
356 s->cached_available_space_timestamp = 0;
359 static char *shortened_cgroup_path(pid_t pid) {
361 char *process_path, *init_path, *path;
365 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
369 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
375 if (endswith(init_path, "/system"))
376 init_path[strlen(init_path) - 7] = 0;
377 else if (streq(init_path, "/"))
380 if (startswith(process_path, init_path)) {
383 p = strdup(process_path + strlen(init_path));
401 static void dispatch_message_real(Server *s,
402 struct iovec *iovec, unsigned n, unsigned m,
404 struct timeval *tv) {
406 char *pid = NULL, *uid = NULL, *gid = NULL,
407 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
408 *comm = NULL, *cmdline = NULL, *hostname = NULL,
409 *audit_session = NULL, *audit_loginuid = NULL,
410 *exe = NULL, *cgroup = NULL, *session = NULL,
411 *owner_uid = NULL, *unit = NULL;
417 uid_t loginuid = 0, realuid = 0;
419 bool vacuumed = false;
424 assert(n + N_IOVEC_META_FIELDS <= m);
430 realuid = ucred->uid;
432 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
433 IOVEC_SET_STRING(iovec[n++], pid);
435 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
436 IOVEC_SET_STRING(iovec[n++], uid);
438 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
439 IOVEC_SET_STRING(iovec[n++], gid);
441 r = get_process_comm(ucred->pid, &t);
443 comm = strappend("_COMM=", t);
447 IOVEC_SET_STRING(iovec[n++], comm);
450 r = get_process_exe(ucred->pid, &t);
452 exe = strappend("_EXE=", t);
456 IOVEC_SET_STRING(iovec[n++], exe);
459 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
461 cmdline = strappend("_CMDLINE=", t);
465 IOVEC_SET_STRING(iovec[n++], cmdline);
468 r = audit_session_from_pid(ucred->pid, &audit);
470 if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
471 IOVEC_SET_STRING(iovec[n++], audit_session);
473 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
475 if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
476 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
478 t = shortened_cgroup_path(ucred->pid);
480 cgroup = strappend("_SYSTEMD_CGROUP=", t);
484 IOVEC_SET_STRING(iovec[n++], cgroup);
487 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
488 session = strappend("_SYSTEMD_SESSION=", t);
492 IOVEC_SET_STRING(iovec[n++], session);
495 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
496 unit = strappend("_SYSTEMD_UNIT=", t);
500 IOVEC_SET_STRING(iovec[n++], unit);
503 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
504 if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
505 IOVEC_SET_STRING(iovec[n++], owner_uid);
509 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
510 (unsigned long long) timeval_load(tv)) >= 0)
511 IOVEC_SET_STRING(iovec[n++], source_time);
514 /* Note that strictly speaking storing the boot id here is
515 * redundant since the entry includes this in-line
516 * anyway. However, we need this indexed, too. */
517 r = sd_id128_get_boot(&id);
519 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
520 IOVEC_SET_STRING(iovec[n++], boot_id);
522 r = sd_id128_get_machine(&id);
524 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
525 IOVEC_SET_STRING(iovec[n++], machine_id);
527 t = gethostname_malloc();
529 hostname = strappend("_HOSTNAME=", t);
532 IOVEC_SET_STRING(iovec[n++], hostname);
537 server_flush_to_var(s);
540 f = find_journal(s, realuid == 0 ? 0 : loginuid);
542 log_warning("Dropping message, as we can't find a place to store the data.");
544 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
546 if (r == -E2BIG && !vacuumed) {
547 log_info("Allocation limit reached.");
553 log_info("Retrying write.");
558 log_error("Failed to write entry, ignoring: %s", strerror(-r));
572 free(audit_loginuid);
579 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
580 char mid[11 + 32 + 1];
581 char buffer[16 + LINE_MAX + 1];
582 struct iovec iovec[N_IOVEC_META_FIELDS + 4];
590 IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
591 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
593 memcpy(buffer, "MESSAGE=", 8);
594 va_start(ap, format);
595 vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
597 char_array_0(buffer);
598 IOVEC_SET_STRING(iovec[n++], buffer);
600 snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
602 IOVEC_SET_STRING(iovec[n++], mid);
605 ucred.pid = getpid();
606 ucred.uid = getuid();
607 ucred.gid = getgid();
609 dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL);
612 static void dispatch_message(Server *s,
613 struct iovec *iovec, unsigned n, unsigned m,
618 char *path = NULL, *c;
621 assert(iovec || n == 0);
629 path = shortened_cgroup_path(ucred->pid);
633 /* example: /user/lennart/3/foobar
634 * /system/dbus.service/foobar
636 * So let's cut of everything past the third /, since that is
637 * wher user directories start */
639 c = strchr(path, '/');
641 c = strchr(c+1, '/');
643 c = strchr(c+1, '/');
649 rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
656 /* Write a suppression message if we suppressed something */
658 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
663 dispatch_message_real(s, iovec, n, m, ucred, tv);
666 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
667 struct msghdr msghdr;
668 struct cmsghdr *cmsg;
670 struct cmsghdr cmsghdr;
671 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
673 union sockaddr_union sa;
680 msghdr.msg_iov = (struct iovec*) iovec;
681 msghdr.msg_iovlen = n_iovec;
684 sa.un.sun_family = AF_UNIX;
685 strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
686 msghdr.msg_name = &sa;
687 msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
691 msghdr.msg_control = &control;
692 msghdr.msg_controllen = sizeof(control);
694 cmsg = CMSG_FIRSTHDR(&msghdr);
695 cmsg->cmsg_level = SOL_SOCKET;
696 cmsg->cmsg_type = SCM_CREDENTIALS;
697 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
698 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
699 msghdr.msg_controllen = cmsg->cmsg_len;
702 /* Forward the syslog message we received via /dev/log to
703 * /run/systemd/syslog. Unfortunately we currently can't set
704 * the SO_TIMESTAMP auxiliary data, and hence we don't. */
706 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
709 if (ucred && errno == ESRCH) {
712 /* Hmm, presumably the sender process vanished
713 * by now, so let's fix it as good as we
718 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
720 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
724 log_debug("Failed to forward syslog message: %m");
727 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
733 IOVEC_SET_STRING(iovec, buffer);
734 forward_syslog_iovec(s, &iovec, 1, ucred, tv);
737 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
738 struct iovec iovec[5];
739 char header_priority[6], header_time[64], header_pid[16];
743 char *ident_buf = NULL;
746 assert(priority >= 0);
747 assert(priority <= 999);
750 /* First: priority field */
751 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
752 char_array_0(header_priority);
753 IOVEC_SET_STRING(iovec[n++], header_priority);
755 /* Second: timestamp */
756 t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
760 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
762 IOVEC_SET_STRING(iovec[n++], header_time);
764 /* Third: identifier and PID */
767 get_process_comm(ucred->pid, &ident_buf);
768 identifier = ident_buf;
771 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
772 char_array_0(header_pid);
775 IOVEC_SET_STRING(iovec[n++], identifier);
777 IOVEC_SET_STRING(iovec[n++], header_pid);
778 } else if (identifier) {
779 IOVEC_SET_STRING(iovec[n++], identifier);
780 IOVEC_SET_STRING(iovec[n++], ": ");
783 /* Fourth: message */
784 IOVEC_SET_STRING(iovec[n++], message);
786 forward_syslog_iovec(s, iovec, n, ucred, tv);
791 static int fixup_priority(int priority) {
793 if ((priority & LOG_FACMASK) == 0)
794 return (priority & LOG_PRIMASK) | LOG_USER;
799 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
800 struct iovec iovec[5];
801 char header_priority[6], header_pid[16];
803 char *ident_buf = NULL;
807 assert(priority >= 0);
808 assert(priority <= 999);
811 /* Never allow messages with kernel facility to be written to
812 * kmsg, regardless where the data comes from. */
813 priority = fixup_priority(priority);
815 /* First: priority field */
816 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
817 char_array_0(header_priority);
818 IOVEC_SET_STRING(iovec[n++], header_priority);
820 /* Second: identifier and PID */
823 get_process_comm(ucred->pid, &ident_buf);
824 identifier = ident_buf;
827 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
828 char_array_0(header_pid);
831 IOVEC_SET_STRING(iovec[n++], identifier);
833 IOVEC_SET_STRING(iovec[n++], header_pid);
834 } else if (identifier) {
835 IOVEC_SET_STRING(iovec[n++], identifier);
836 IOVEC_SET_STRING(iovec[n++], ": ");
839 /* Fourth: message */
840 IOVEC_SET_STRING(iovec[n++], message);
841 IOVEC_SET_STRING(iovec[n++], "\n");
843 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
845 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
849 if (writev(fd, iovec, n) < 0)
850 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
852 close_nointr_nofail(fd);
858 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
859 struct iovec iovec[4];
862 char *ident_buf = NULL;
867 /* First: identifier and PID */
870 get_process_comm(ucred->pid, &ident_buf);
871 identifier = ident_buf;
874 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
875 char_array_0(header_pid);
878 IOVEC_SET_STRING(iovec[n++], identifier);
880 IOVEC_SET_STRING(iovec[n++], header_pid);
881 } else if (identifier) {
882 IOVEC_SET_STRING(iovec[n++], identifier);
883 IOVEC_SET_STRING(iovec[n++], ": ");
887 IOVEC_SET_STRING(iovec[n++], message);
888 IOVEC_SET_STRING(iovec[n++], "\n");
890 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
892 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
896 if (writev(fd, iovec, n) < 0)
897 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
899 close_nointr_nofail(fd);
905 static void read_identifier(const char **buf, char **identifier, char **pid) {
916 p += strspn(p, WHITESPACE);
917 l = strcspn(p, WHITESPACE);
932 t = strndup(p+k+1, l-k-2);
952 *buf += strspn(*buf, WHITESPACE);
955 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
956 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
957 struct iovec iovec[N_IOVEC_META_FIELDS + 6];
959 int priority = LOG_USER | LOG_INFO;
960 char *identifier = NULL, *pid = NULL;
965 if (s->forward_to_syslog)
966 forward_syslog_raw(s, buf, ucred, tv);
968 parse_syslog_priority((char**) &buf, &priority);
969 skip_syslog_date((char**) &buf);
970 read_identifier(&buf, &identifier, &pid);
972 if (s->forward_to_kmsg)
973 forward_kmsg(s, priority, identifier, buf, ucred);
975 if (s->forward_to_console)
976 forward_console(s, identifier, buf, ucred);
978 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
980 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
981 IOVEC_SET_STRING(iovec[n++], syslog_priority);
983 if (priority & LOG_FACMASK)
984 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
985 IOVEC_SET_STRING(iovec[n++], syslog_facility);
988 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
989 if (syslog_identifier)
990 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
994 syslog_pid = strappend("SYSLOG_PID=", pid);
996 IOVEC_SET_STRING(iovec[n++], syslog_pid);
999 message = strappend("MESSAGE=", buf);
1001 IOVEC_SET_STRING(iovec[n++], message);
1003 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, priority);
1008 free(syslog_priority);
1009 free(syslog_facility);
1010 free(syslog_identifier);
1013 static bool valid_user_field(const char *p, size_t l) {
1016 /* We kinda enforce POSIX syntax recommendations for
1017 environment variables here, but make a couple of additional
1020 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1022 /* No empty field names */
1026 /* Don't allow names longer than 64 chars */
1030 /* Variables starting with an underscore are protected */
1034 /* Don't allow digits as first character */
1035 if (p[0] >= '0' && p[0] <= '9')
1038 /* Only allow A-Z0-9 and '_' */
1039 for (a = p; a < p + l; a++)
1040 if (!((*a >= 'A' && *a <= 'Z') ||
1041 (*a >= '0' && *a <= '9') ||
1048 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
1049 struct iovec *iovec = NULL;
1050 unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1053 int priority = LOG_INFO;
1054 char *identifier = NULL, *message = NULL;
1057 assert(buffer || n == 0);
1060 remaining = buffer_size;
1062 while (remaining > 0) {
1065 e = memchr(p, '\n', remaining);
1068 /* Trailing noise, let's ignore it, and flush what we collected */
1069 log_debug("Received message with trailing noise, ignoring.");
1074 /* Entry separator */
1075 dispatch_message(s, iovec, n, m, ucred, tv, priority);
1077 priority = LOG_INFO;
1084 if (*p == '.' || *p == '#') {
1085 /* Ignore control commands for now, and
1087 remaining -= (e - p) + 1;
1092 /* A property follows */
1094 if (n+N_IOVEC_META_FIELDS >= m) {
1098 u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1099 c = realloc(iovec, u * sizeof(struct iovec));
1101 log_error("Out of memory");
1109 q = memchr(p, '=', e - p);
1111 if (valid_user_field(p, q - p)) {
1116 /* If the field name starts with an
1117 * underscore, skip the variable,
1118 * since that indidates a trusted
1120 iovec[n].iov_base = (char*) p;
1121 iovec[n].iov_len = l;
1124 /* We need to determine the priority
1125 * of this entry for the rate limiting
1128 memcmp(p, "PRIORITY=", 9) == 0 &&
1129 p[9] >= '0' && p[9] <= '9')
1130 priority = (priority & LOG_FACMASK) | (p[9] - '0');
1133 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1134 p[16] >= '0' && p[16] <= '9')
1135 priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1138 memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1139 p[16] >= '0' && p[16] <= '9' &&
1140 p[17] >= '0' && p[17] <= '9')
1141 priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1144 memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1147 t = strndup(p + 11, l - 11);
1152 } else if (l >= 8 &&
1153 memcmp(p, "MESSAGE=", 8) == 0) {
1156 t = strndup(p + 8, l - 8);
1164 remaining -= (e - p) + 1;
1171 if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1172 log_debug("Failed to parse message, ignoring.");
1176 memcpy(&l, e + 1, sizeof(uint64_t));
1179 if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1180 e[1+sizeof(uint64_t)+l] != '\n') {
1181 log_debug("Failed to parse message, ignoring.");
1185 k = malloc((e - p) + 1 + l);
1187 log_error("Out of memory");
1191 memcpy(k, p, e - p);
1193 memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1195 if (valid_user_field(p, e - p)) {
1196 iovec[n].iov_base = k;
1197 iovec[n].iov_len = (e - p) + 1 + l;
1202 remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1203 p = e + 1 + sizeof(uint64_t) + l + 1;
1211 IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1214 if (s->forward_to_syslog)
1215 forward_syslog(s, priority, identifier, message, ucred, tv);
1217 if (s->forward_to_kmsg)
1218 forward_kmsg(s, priority, identifier, message, ucred);
1220 if (s->forward_to_console)
1221 forward_console(s, identifier, message, ucred);
1224 dispatch_message(s, iovec, n, m, ucred, tv, priority);
1227 for (j = 0; j < n; j++) {
1231 if (iovec[j].iov_base < buffer ||
1232 (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1233 free(iovec[j].iov_base);
1240 static int stdout_stream_log(StdoutStream *s, const char *p) {
1241 struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1242 char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1249 priority = s->priority;
1251 if (s->level_prefix)
1252 parse_syslog_priority((char**) &p, &priority);
1254 if (s->forward_to_syslog || s->server->forward_to_syslog)
1255 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1257 if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1258 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1260 if (s->forward_to_console || s->server->forward_to_console)
1261 forward_console(s->server, s->identifier, p, &s->ucred);
1263 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1265 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1266 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1268 if (priority & LOG_FACMASK)
1269 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1270 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1272 if (s->identifier) {
1273 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1274 if (syslog_identifier)
1275 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1278 message = strappend("MESSAGE=", p);
1280 IOVEC_SET_STRING(iovec[n++], message);
1282 dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, priority);
1285 free(syslog_priority);
1286 free(syslog_facility);
1287 free(syslog_identifier);
1292 static int stdout_stream_line(StdoutStream *s, char *p) {
1302 case STDOUT_STREAM_IDENTIFIER:
1303 s->identifier = strdup(p);
1304 if (!s->identifier) {
1305 log_error("Out of memory");
1309 s->state = STDOUT_STREAM_PRIORITY;
1312 case STDOUT_STREAM_PRIORITY:
1313 r = safe_atoi(p, &s->priority);
1314 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1315 log_warning("Failed to parse log priority line.");
1319 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1322 case STDOUT_STREAM_LEVEL_PREFIX:
1323 r = parse_boolean(p);
1325 log_warning("Failed to parse level prefix line.");
1329 s->level_prefix = !!r;
1330 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1333 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1334 r = parse_boolean(p);
1336 log_warning("Failed to parse forward to syslog line.");
1340 s->forward_to_syslog = !!r;
1341 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1344 case STDOUT_STREAM_FORWARD_TO_KMSG:
1345 r = parse_boolean(p);
1347 log_warning("Failed to parse copy to kmsg line.");
1351 s->forward_to_kmsg = !!r;
1352 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1355 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1356 r = parse_boolean(p);
1358 log_warning("Failed to parse copy to console line.");
1362 s->forward_to_console = !!r;
1363 s->state = STDOUT_STREAM_RUNNING;
1366 case STDOUT_STREAM_RUNNING:
1367 return stdout_stream_log(s, p);
1370 assert_not_reached("Unknown stream state");
1373 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1381 remaining = s->length;
1386 end = memchr(p, '\n', remaining);
1389 else if (remaining >= sizeof(s->buffer) - 1) {
1390 end = p + sizeof(s->buffer) - 1;
1397 r = stdout_stream_line(s, p);
1405 if (force_flush && remaining > 0) {
1407 r = stdout_stream_line(s, p);
1415 if (p > s->buffer) {
1416 memmove(s->buffer, p, remaining);
1417 s->length = remaining;
1423 static int stdout_stream_process(StdoutStream *s) {
1429 l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1432 if (errno == EAGAIN)
1435 log_warning("Failed to read from stream: %m");
1440 r = stdout_stream_scan(s, true);
1448 r = stdout_stream_scan(s, false);
1456 static void stdout_stream_free(StdoutStream *s) {
1460 assert(s->server->n_stdout_streams > 0);
1461 s->server->n_stdout_streams --;
1462 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1467 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1469 close_nointr_nofail(s->fd);
1472 free(s->identifier);
1476 static int stdout_stream_new(Server *s) {
1477 StdoutStream *stream;
1480 struct epoll_event ev;
1484 fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1486 if (errno == EAGAIN)
1489 log_error("Failed to accept stdout connection: %m");
1493 if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1494 log_warning("Too many stdout streams, refusing connection.");
1495 close_nointr_nofail(fd);
1499 stream = new0(StdoutStream, 1);
1501 log_error("Out of memory.");
1502 close_nointr_nofail(fd);
1508 len = sizeof(stream->ucred);
1509 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1510 log_error("Failed to determine peer credentials: %m");
1515 if (shutdown(fd, SHUT_WR) < 0) {
1516 log_error("Failed to shutdown writing side of socket: %m");
1522 ev.data.ptr = stream;
1523 ev.events = EPOLLIN;
1524 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1525 log_error("Failed to add stream to event loop: %m");
1531 LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1532 s->n_stdout_streams ++;
1537 stdout_stream_free(stream);
1541 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1552 if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1557 for (i = 1; i <= 5; i++) {
1563 k = undecchar(p[i]);
1570 for (i = 7; i <= 12; i++) {
1573 k = undecchar(p[i]);
1582 *_p += strspn(*_p, WHITESPACE);
1587 static void proc_kmsg_line(Server *s, const char *p) {
1588 struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1589 char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1590 int priority = LOG_KERN | LOG_INFO;
1593 char *identifier = NULL, *pid = NULL;
1598 parse_syslog_priority((char **) &p, &priority);
1600 if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1603 if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1604 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1605 (unsigned long long) usec) >= 0)
1606 IOVEC_SET_STRING(iovec[n++], source_time);
1609 IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1611 if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1612 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1614 if ((priority & LOG_FACMASK) == LOG_KERN) {
1616 if (s->forward_to_syslog)
1617 forward_syslog(s, priority, "kernel", p, NULL, NULL);
1619 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1621 read_identifier(&p, &identifier, &pid);
1623 if (s->forward_to_syslog)
1624 forward_syslog(s, priority, identifier, p, NULL, NULL);
1627 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1628 if (syslog_identifier)
1629 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1633 syslog_pid = strappend("SYSLOG_PID=", pid);
1635 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1638 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1639 IOVEC_SET_STRING(iovec[n++], syslog_facility);
1642 message = strappend("MESSAGE=", p);
1644 IOVEC_SET_STRING(iovec[n++], message);
1647 dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, priority);
1650 free(syslog_priority);
1651 free(syslog_identifier);
1653 free(syslog_facility);
1659 static void proc_kmsg_scan(Server *s) {
1665 p = s->proc_kmsg_buffer;
1666 remaining = s->proc_kmsg_length;
1671 end = memchr(p, '\n', remaining);
1674 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1675 end = p + sizeof(s->proc_kmsg_buffer) - 1;
1682 proc_kmsg_line(s, p);
1688 if (p > s->proc_kmsg_buffer) {
1689 memmove(s->proc_kmsg_buffer, p, remaining);
1690 s->proc_kmsg_length = remaining;
1694 static int system_journal_open(Server *s) {
1700 r = sd_id128_get_machine(&machine);
1704 sd_id128_to_string(machine, ids);
1706 if (!s->system_journal) {
1708 /* First try to create the machine path, but not the prefix */
1709 fn = strappend("/var/log/journal/", ids);
1712 (void) mkdir(fn, 0755);
1715 /* The create the system journal file */
1716 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1720 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1724 journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1726 s->system_journal->metrics = s->system_metrics;
1727 s->system_journal->compress = s->compress;
1729 fix_perms(s->system_journal, 0);
1732 if (r != -ENOENT && r != -EROFS)
1733 log_warning("Failed to open system journal: %s", strerror(-r));
1739 if (!s->runtime_journal) {
1741 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1745 if (s->system_journal) {
1747 /* Try to open the runtime journal, but only
1748 * if it already exists, so that we can flush
1749 * it into the system journal */
1751 r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1756 log_warning("Failed to open runtime journal: %s", strerror(-r));
1763 /* OK, we really need the runtime journal, so create
1764 * it if necessary. */
1766 (void) mkdir_parents(fn, 0755);
1767 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1771 log_error("Failed to open runtime journal: %s", strerror(-r));
1776 if (s->runtime_journal) {
1777 journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1779 s->runtime_journal->metrics = s->runtime_metrics;
1780 s->runtime_journal->compress = s->compress;
1782 fix_perms(s->runtime_journal, 0);
1789 static int server_flush_to_var(Server *s) {
1790 char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1799 if (!s->runtime_journal)
1802 ts = now(CLOCK_MONOTONIC);
1803 if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1806 s->var_available_timestamp = ts;
1808 system_journal_open(s);
1810 if (!s->system_journal)
1813 log_info("Flushing to /var...");
1815 r = sd_id128_get_machine(&machine);
1817 log_error("Failed to get machine id: %s", strerror(-r));
1821 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1823 log_error("Failed to read runtime journal: %s", strerror(-r));
1827 SD_JOURNAL_FOREACH(j) {
1830 f = j->current_file;
1831 assert(f && f->current_offset > 0);
1833 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1835 log_error("Can't read entry: %s", strerror(-r));
1839 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1841 log_info("Allocation limit reached.");
1843 journal_file_post_change(s->system_journal);
1847 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1851 log_error("Can't write entry: %s", strerror(-r));
1857 journal_file_post_change(s->system_journal);
1859 journal_file_close(s->runtime_journal);
1860 s->runtime_journal = NULL;
1863 sd_id128_to_string(machine, path + 17);
1864 rm_rf(path, false, true, false);
1870 static int server_read_proc_kmsg(Server *s) {
1873 assert(s->proc_kmsg_fd >= 0);
1875 l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
1878 if (errno == EAGAIN || errno == EINTR)
1881 log_error("Failed to read from kernel: %m");
1885 s->proc_kmsg_length += l;
1891 static int server_flush_proc_kmsg(Server *s) {
1896 if (s->proc_kmsg_fd < 0)
1899 log_info("Flushing /proc/kmsg...");
1902 r = server_read_proc_kmsg(s);
1913 static int process_event(Server *s, struct epoll_event *ev) {
1916 if (ev->data.fd == s->signal_fd) {
1917 struct signalfd_siginfo sfsi;
1920 if (ev->events != EPOLLIN) {
1921 log_info("Got invalid event from epoll.");
1925 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
1926 if (n != sizeof(sfsi)) {
1931 if (errno == EINTR || errno == EAGAIN)
1937 if (sfsi.ssi_signo == SIGUSR1) {
1938 server_flush_to_var(s);
1942 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
1945 } else if (ev->data.fd == s->proc_kmsg_fd) {
1948 if (ev->events != EPOLLIN) {
1949 log_info("Got invalid event from epoll.");
1953 r = server_read_proc_kmsg(s);
1959 } else if (ev->data.fd == s->native_fd ||
1960 ev->data.fd == s->syslog_fd) {
1962 if (ev->events != EPOLLIN) {
1963 log_info("Got invalid event from epoll.");
1968 struct msghdr msghdr;
1970 struct ucred *ucred = NULL;
1971 struct timeval *tv = NULL;
1972 struct cmsghdr *cmsg;
1974 struct cmsghdr cmsghdr;
1975 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1976 CMSG_SPACE(sizeof(struct timeval))];
1981 if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
1982 log_error("SIOCINQ failed: %m");
1989 if (s->buffer_size < (size_t) v) {
1993 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
1994 b = realloc(s->buffer, l+1);
1997 log_error("Couldn't increase buffer.");
2006 iovec.iov_base = s->buffer;
2007 iovec.iov_len = s->buffer_size;
2011 msghdr.msg_iov = &iovec;
2012 msghdr.msg_iovlen = 1;
2013 msghdr.msg_control = &control;
2014 msghdr.msg_controllen = sizeof(control);
2016 n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
2019 if (errno == EINTR || errno == EAGAIN)
2022 log_error("recvmsg() failed: %m");
2026 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2028 if (cmsg->cmsg_level == SOL_SOCKET &&
2029 cmsg->cmsg_type == SCM_CREDENTIALS &&
2030 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2031 ucred = (struct ucred*) CMSG_DATA(cmsg);
2032 else if (cmsg->cmsg_level == SOL_SOCKET &&
2033 cmsg->cmsg_type == SO_TIMESTAMP &&
2034 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2035 tv = (struct timeval*) CMSG_DATA(cmsg);
2038 if (ev->data.fd == s->syslog_fd) {
2041 e = memchr(s->buffer, '\n', n);
2047 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
2049 process_native_message(s, s->buffer, n, ucred, tv);
2054 } else if (ev->data.fd == s->stdout_fd) {
2056 if (ev->events != EPOLLIN) {
2057 log_info("Got invalid event from epoll.");
2061 stdout_stream_new(s);
2065 StdoutStream *stream;
2067 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2068 log_info("Got invalid event from epoll.");
2072 /* If it is none of the well-known fds, it must be an
2073 * stdout stream fd. Note that this is a bit ugly here
2074 * (since we rely that none of the well-known fds
2075 * could be interpreted as pointer), but nonetheless
2076 * safe, since the well-known fds would never get an
2077 * fd > 4096, i.e. beyond the first memory page */
2079 stream = ev->data.ptr;
2081 if (stdout_stream_process(stream) <= 0)
2082 stdout_stream_free(stream);
2087 log_error("Unknown event.");
2091 static int open_syslog_socket(Server *s) {
2092 union sockaddr_union sa;
2094 struct epoll_event ev;
2099 if (s->syslog_fd < 0) {
2101 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2102 if (s->syslog_fd < 0) {
2103 log_error("socket() failed: %m");
2108 sa.un.sun_family = AF_UNIX;
2109 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2111 unlink(sa.un.sun_path);
2113 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2115 log_error("bind() failed: %m");
2119 chmod(sa.un.sun_path, 0666);
2123 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2125 log_error("SO_PASSCRED failed: %m");
2130 r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2132 log_error("SO_TIMESTAMP failed: %m");
2136 /* Since we use the same socket for forwarding this to some
2137 * other syslog implementation, make sure we don't hang
2139 timeval_store(&tv, SYSLOG_TIMEOUT_USEC);
2140 if (setsockopt(s->syslog_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) {
2141 log_error("SO_SNDTIMEO failed: %m");
2146 ev.events = EPOLLIN;
2147 ev.data.fd = s->syslog_fd;
2148 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2149 log_error("Failed to add syslog server fd to epoll object: %m");
2156 static int open_native_socket(Server*s) {
2157 union sockaddr_union sa;
2159 struct epoll_event ev;
2163 if (s->native_fd < 0) {
2165 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2166 if (s->native_fd < 0) {
2167 log_error("socket() failed: %m");
2172 sa.un.sun_family = AF_UNIX;
2173 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2175 unlink(sa.un.sun_path);
2177 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2179 log_error("bind() failed: %m");
2183 chmod(sa.un.sun_path, 0666);
2187 r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2189 log_error("SO_PASSCRED failed: %m");
2194 r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2196 log_error("SO_TIMESTAMP failed: %m");
2201 ev.events = EPOLLIN;
2202 ev.data.fd = s->native_fd;
2203 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2204 log_error("Failed to add native server fd to epoll object: %m");
2211 static int open_stdout_socket(Server *s) {
2212 union sockaddr_union sa;
2214 struct epoll_event ev;
2218 if (s->stdout_fd < 0) {
2220 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2221 if (s->stdout_fd < 0) {
2222 log_error("socket() failed: %m");
2227 sa.un.sun_family = AF_UNIX;
2228 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2230 unlink(sa.un.sun_path);
2232 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2234 log_error("bind() failed: %m");
2238 chmod(sa.un.sun_path, 0666);
2240 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2241 log_error("liste() failed: %m");
2247 ev.events = EPOLLIN;
2248 ev.data.fd = s->stdout_fd;
2249 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2250 log_error("Failed to add stdout server fd to epoll object: %m");
2257 static int open_proc_kmsg(Server *s) {
2258 struct epoll_event ev;
2262 if (!s->import_proc_kmsg)
2266 s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2267 if (s->proc_kmsg_fd < 0) {
2268 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2273 ev.events = EPOLLIN;
2274 ev.data.fd = s->proc_kmsg_fd;
2275 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2276 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2283 static int open_signalfd(Server *s) {
2285 struct epoll_event ev;
2289 assert_se(sigemptyset(&mask) == 0);
2290 sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2291 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2293 s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2294 if (s->signal_fd < 0) {
2295 log_error("signalfd(): %m");
2300 ev.events = EPOLLIN;
2301 ev.data.fd = s->signal_fd;
2303 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2304 log_error("epoll_ctl(): %m");
2311 static int server_parse_proc_cmdline(Server *s) {
2312 char *line, *w, *state;
2316 if (detect_container(NULL) > 0)
2319 r = read_one_line_file("/proc/cmdline", &line);
2321 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2325 FOREACH_WORD_QUOTED(w, l, line, state) {
2328 word = strndup(w, l);
2334 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2335 r = parse_boolean(word + 35);
2337 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2339 s->forward_to_syslog = r;
2340 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2341 r = parse_boolean(word + 33);
2343 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2345 s->forward_to_kmsg = r;
2346 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2347 r = parse_boolean(word + 36);
2349 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2351 s->forward_to_console = r;
2364 static int server_parse_config_file(Server *s) {
2371 fn = "/etc/systemd/systemd-journald.conf";
2372 f = fopen(fn, "re");
2374 if (errno == ENOENT)
2377 log_warning("Failed to open configuration file %s: %m", fn);
2381 r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2383 log_warning("Failed to parse configuration file: %s", strerror(-r));
2390 static int server_init(Server *s) {
2396 s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2399 s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2400 s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2402 s->forward_to_syslog = true;
2403 s->import_proc_kmsg = true;
2405 memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2406 memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2408 server_parse_config_file(s);
2409 server_parse_proc_cmdline(s);
2411 s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2412 if (!s->user_journals) {
2413 log_error("Out of memory.");
2417 s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2418 if (s->epoll_fd < 0) {
2419 log_error("Failed to create epoll object: %m");
2423 n = sd_listen_fds(true);
2425 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2429 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2431 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2433 if (s->native_fd >= 0) {
2434 log_error("Too many native sockets passed.");
2440 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2442 if (s->stdout_fd >= 0) {
2443 log_error("Too many stdout sockets passed.");
2449 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2451 if (s->syslog_fd >= 0) {
2452 log_error("Too many /dev/log sockets passed.");
2459 log_error("Unknown socket passed.");
2464 r = open_syslog_socket(s);
2468 r = open_native_socket(s);
2472 r = open_stdout_socket(s);
2476 r = open_proc_kmsg(s);
2480 r = system_journal_open(s);
2484 r = open_signalfd(s);
2488 s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2495 static void server_done(Server *s) {
2499 while (s->stdout_streams)
2500 stdout_stream_free(s->stdout_streams);
2502 if (s->system_journal)
2503 journal_file_close(s->system_journal);
2505 if (s->runtime_journal)
2506 journal_file_close(s->runtime_journal);
2508 while ((f = hashmap_steal_first(s->user_journals)))
2509 journal_file_close(f);
2511 hashmap_free(s->user_journals);
2513 if (s->epoll_fd >= 0)
2514 close_nointr_nofail(s->epoll_fd);
2516 if (s->signal_fd >= 0)
2517 close_nointr_nofail(s->signal_fd);
2519 if (s->syslog_fd >= 0)
2520 close_nointr_nofail(s->syslog_fd);
2522 if (s->native_fd >= 0)
2523 close_nointr_nofail(s->native_fd);
2525 if (s->stdout_fd >= 0)
2526 close_nointr_nofail(s->stdout_fd);
2528 if (s->proc_kmsg_fd >= 0)
2529 close_nointr_nofail(s->proc_kmsg_fd);
2532 journal_rate_limit_free(s->rate_limit);
2537 int main(int argc, char *argv[]) {
2541 /* if (getppid() != 1) { */
2542 /* log_error("This program should be invoked by init only."); */
2543 /* return EXIT_FAILURE; */
2547 log_error("This program does not take arguments.");
2548 return EXIT_FAILURE;
2551 log_set_target(LOG_TARGET_CONSOLE);
2552 log_parse_environment();
2557 r = server_init(&server);
2561 server_vacuum(&server);
2562 server_flush_to_var(&server);
2563 server_flush_proc_kmsg(&server);
2565 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2566 driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2570 "STATUS=Processing requests...");
2573 struct epoll_event event;
2575 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2581 log_error("epoll_wait() failed: %m");
2587 r = process_event(&server, &event);
2594 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2595 driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2599 "STATUS=Shutting down...");
2601 server_done(&server);
2603 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;