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
) {
915 p
+= strspn(p
, WHITESPACE
);
916 l
= strcspn(p
, WHITESPACE
);
947 *buf
+= strspn(*buf
, WHITESPACE
);
950 static void process_syslog_message(Server
*s
, const char *buf
, struct ucred
*ucred
, struct timeval
*tv
) {
951 char *message
= NULL
, *syslog_priority
= NULL
, *syslog_facility
= NULL
, *syslog_identifier
= NULL
;
952 struct iovec iovec
[N_IOVEC_META_FIELDS
+ 5];
954 int priority
= LOG_USER
| LOG_INFO
;
955 char *identifier
= NULL
;
960 if (s
->forward_to_syslog
)
961 forward_syslog_raw(s
, buf
, ucred
, tv
);
963 parse_syslog_priority((char**) &buf
, &priority
);
964 skip_syslog_date((char**) &buf
);
965 read_identifier(&buf
, &identifier
);
967 if (s
->forward_to_kmsg
)
968 forward_kmsg(s
, priority
, identifier
, buf
, ucred
);
970 if (s
->forward_to_console
)
971 forward_console(s
, identifier
, buf
, ucred
);
973 IOVEC_SET_STRING(iovec
[n
++], "_TRANSPORT=syslog");
975 if (asprintf(&syslog_priority
, "PRIORITY=%i", priority
& LOG_PRIMASK
) >= 0)
976 IOVEC_SET_STRING(iovec
[n
++], syslog_priority
);
978 if (priority
& LOG_FACMASK
)
979 if (asprintf(&syslog_facility
, "SYSLOG_FACILITY=%i", LOG_FAC(priority
)) >= 0)
980 IOVEC_SET_STRING(iovec
[n
++], syslog_facility
);
983 syslog_identifier
= strappend("SYSLOG_IDENTIFIER=", identifier
);
984 if (syslog_identifier
)
985 IOVEC_SET_STRING(iovec
[n
++], syslog_identifier
);
988 message
= strappend("MESSAGE=", buf
);
990 IOVEC_SET_STRING(iovec
[n
++], message
);
992 dispatch_message(s
, iovec
, n
, ELEMENTSOF(iovec
), ucred
, tv
, priority
);
996 free(syslog_priority
);
997 free(syslog_facility
);
998 free(syslog_identifier
);
1001 static bool valid_user_field(const char *p
, size_t l
) {
1004 /* We kinda enforce POSIX syntax recommendations for
1005 environment variables here, but make a couple of additional
1008 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1010 /* No empty field names */
1014 /* Don't allow names longer than 64 chars */
1018 /* Variables starting with an underscore are protected */
1022 /* Don't allow digits as first character */
1023 if (p
[0] >= '0' && p
[0] <= '9')
1026 /* Only allow A-Z0-9 and '_' */
1027 for (a
= p
; a
< p
+ l
; a
++)
1028 if (!((*a
>= 'A' && *a
<= 'Z') ||
1029 (*a
>= '0' && *a
<= '9') ||
1036 static void process_native_message(Server
*s
, const void *buffer
, size_t buffer_size
, struct ucred
*ucred
, struct timeval
*tv
) {
1037 struct iovec
*iovec
= NULL
;
1038 unsigned n
= 0, m
= 0, j
, tn
= (unsigned) -1;
1041 int priority
= LOG_INFO
;
1042 char *identifier
= NULL
, *message
= NULL
;
1045 assert(buffer
|| n
== 0);
1048 remaining
= buffer_size
;
1050 while (remaining
> 0) {
1053 e
= memchr(p
, '\n', remaining
);
1056 /* Trailing noise, let's ignore it, and flush what we collected */
1057 log_debug("Received message with trailing noise, ignoring.");
1062 /* Entry separator */
1063 dispatch_message(s
, iovec
, n
, m
, ucred
, tv
, priority
);
1065 priority
= LOG_INFO
;
1072 if (*p
== '.' || *p
== '#') {
1073 /* Ignore control commands for now, and
1075 remaining
-= (e
- p
) + 1;
1080 /* A property follows */
1082 if (n
+N_IOVEC_META_FIELDS
>= m
) {
1086 u
= MAX((n
+N_IOVEC_META_FIELDS
+1) * 2U, 4U);
1087 c
= realloc(iovec
, u
* sizeof(struct iovec
));
1089 log_error("Out of memory");
1097 q
= memchr(p
, '=', e
- p
);
1099 if (valid_user_field(p
, q
- p
)) {
1104 /* If the field name starts with an
1105 * underscore, skip the variable,
1106 * since that indidates a trusted
1108 iovec
[n
].iov_base
= (char*) p
;
1109 iovec
[n
].iov_len
= l
;
1112 /* We need to determine the priority
1113 * of this entry for the rate limiting
1116 memcmp(p
, "PRIORITY=", 9) == 0 &&
1117 p
[9] >= '0' && p
[9] <= '9')
1118 priority
= (priority
& LOG_FACMASK
) | (p
[9] - '0');
1121 memcmp(p
, "SYSLOG_FACILITY=", 16) == 0 &&
1122 p
[16] >= '0' && p
[16] <= '9')
1123 priority
= (priority
& LOG_PRIMASK
) | ((p
[16] - '0') << 3);
1126 memcmp(p
, "SYSLOG_FACILITY=", 16) == 0 &&
1127 p
[16] >= '0' && p
[16] <= '9' &&
1128 p
[17] >= '0' && p
[17] <= '9')
1129 priority
= (priority
& LOG_PRIMASK
) | (((p
[16] - '0')*10 + (p
[17] - '0')) << 3);
1132 memcmp(p
, "SYSLOG_IDENTIFIER=", 11) == 0) {
1135 t
= strndup(p
+ 11, l
- 11);
1140 } else if (l
>= 8 &&
1141 memcmp(p
, "MESSAGE=", 8) == 0) {
1144 t
= strndup(p
+ 8, l
- 8);
1152 remaining
-= (e
- p
) + 1;
1159 if (remaining
< e
- p
+ 1 + sizeof(uint64_t) + 1) {
1160 log_debug("Failed to parse message, ignoring.");
1164 memcpy(&l
, e
+ 1, sizeof(uint64_t));
1167 if (remaining
< e
- p
+ 1 + sizeof(uint64_t) + l
+ 1 ||
1168 e
[1+sizeof(uint64_t)+l
] != '\n') {
1169 log_debug("Failed to parse message, ignoring.");
1173 k
= malloc((e
- p
) + 1 + l
);
1175 log_error("Out of memory");
1179 memcpy(k
, p
, e
- p
);
1181 memcpy(k
+ (e
- p
) + 1, e
+ 1 + sizeof(uint64_t), l
);
1183 if (valid_user_field(p
, e
- p
)) {
1184 iovec
[n
].iov_base
= k
;
1185 iovec
[n
].iov_len
= (e
- p
) + 1 + l
;
1190 remaining
-= (e
- p
) + 1 + sizeof(uint64_t) + l
+ 1;
1191 p
= e
+ 1 + sizeof(uint64_t) + l
+ 1;
1199 IOVEC_SET_STRING(iovec
[tn
], "_TRANSPORT=journal");
1202 if (s
->forward_to_syslog
)
1203 forward_syslog(s
, priority
, identifier
, message
, ucred
, tv
);
1205 if (s
->forward_to_kmsg
)
1206 forward_kmsg(s
, priority
, identifier
, message
, ucred
);
1208 if (s
->forward_to_console
)
1209 forward_console(s
, identifier
, message
, ucred
);
1212 dispatch_message(s
, iovec
, n
, m
, ucred
, tv
, priority
);
1215 for (j
= 0; j
< n
; j
++) {
1219 if (iovec
[j
].iov_base
< buffer
||
1220 (const uint8_t*) iovec
[j
].iov_base
>= (const uint8_t*) buffer
+ buffer_size
)
1221 free(iovec
[j
].iov_base
);
1228 static int stdout_stream_log(StdoutStream
*s
, const char *p
) {
1229 struct iovec iovec
[N_IOVEC_META_FIELDS
+ 5];
1230 char *message
= NULL
, *syslog_priority
= NULL
, *syslog_facility
= NULL
, *syslog_identifier
= NULL
;
1237 priority
= s
->priority
;
1239 if (s
->level_prefix
)
1240 parse_syslog_priority((char**) &p
, &priority
);
1242 if (s
->forward_to_syslog
|| s
->server
->forward_to_syslog
)
1243 forward_syslog(s
->server
, fixup_priority(priority
), s
->identifier
, p
, &s
->ucred
, NULL
);
1245 if (s
->forward_to_kmsg
|| s
->server
->forward_to_kmsg
)
1246 forward_kmsg(s
->server
, priority
, s
->identifier
, p
, &s
->ucred
);
1248 if (s
->forward_to_console
|| s
->server
->forward_to_console
)
1249 forward_console(s
->server
, s
->identifier
, p
, &s
->ucred
);
1251 IOVEC_SET_STRING(iovec
[n
++], "_TRANSPORT=stdout");
1253 if (asprintf(&syslog_priority
, "PRIORITY=%i", priority
& LOG_PRIMASK
) >= 0)
1254 IOVEC_SET_STRING(iovec
[n
++], syslog_priority
);
1256 if (priority
& LOG_FACMASK
)
1257 if (asprintf(&syslog_facility
, "SYSLOG_FACILITY=%i", LOG_FAC(priority
)) >= 0)
1258 IOVEC_SET_STRING(iovec
[n
++], syslog_facility
);
1260 if (s
->identifier
) {
1261 syslog_identifier
= strappend("SYSLOG_IDENTIFIER=", s
->identifier
);
1262 if (syslog_identifier
)
1263 IOVEC_SET_STRING(iovec
[n
++], syslog_identifier
);
1266 message
= strappend("MESSAGE=", p
);
1268 IOVEC_SET_STRING(iovec
[n
++], message
);
1270 dispatch_message(s
->server
, iovec
, n
, ELEMENTSOF(iovec
), &s
->ucred
, NULL
, priority
);
1273 free(syslog_priority
);
1274 free(syslog_facility
);
1275 free(syslog_identifier
);
1280 static int stdout_stream_line(StdoutStream
*s
, char *p
) {
1290 case STDOUT_STREAM_IDENTIFIER
:
1291 s
->identifier
= strdup(p
);
1292 if (!s
->identifier
) {
1293 log_error("Out of memory");
1297 s
->state
= STDOUT_STREAM_PRIORITY
;
1300 case STDOUT_STREAM_PRIORITY
:
1301 r
= safe_atoi(p
, &s
->priority
);
1302 if (r
< 0 || s
->priority
<= 0 || s
->priority
>= 999) {
1303 log_warning("Failed to parse log priority line.");
1307 s
->state
= STDOUT_STREAM_LEVEL_PREFIX
;
1310 case STDOUT_STREAM_LEVEL_PREFIX
:
1311 r
= parse_boolean(p
);
1313 log_warning("Failed to parse level prefix line.");
1317 s
->level_prefix
= !!r
;
1318 s
->state
= STDOUT_STREAM_FORWARD_TO_SYSLOG
;
1321 case STDOUT_STREAM_FORWARD_TO_SYSLOG
:
1322 r
= parse_boolean(p
);
1324 log_warning("Failed to parse forward to syslog line.");
1328 s
->forward_to_syslog
= !!r
;
1329 s
->state
= STDOUT_STREAM_FORWARD_TO_KMSG
;
1332 case STDOUT_STREAM_FORWARD_TO_KMSG
:
1333 r
= parse_boolean(p
);
1335 log_warning("Failed to parse copy to kmsg line.");
1339 s
->forward_to_kmsg
= !!r
;
1340 s
->state
= STDOUT_STREAM_FORWARD_TO_CONSOLE
;
1343 case STDOUT_STREAM_FORWARD_TO_CONSOLE
:
1344 r
= parse_boolean(p
);
1346 log_warning("Failed to parse copy to console line.");
1350 s
->forward_to_console
= !!r
;
1351 s
->state
= STDOUT_STREAM_RUNNING
;
1354 case STDOUT_STREAM_RUNNING
:
1355 return stdout_stream_log(s
, p
);
1358 assert_not_reached("Unknown stream state");
1361 static int stdout_stream_scan(StdoutStream
*s
, bool force_flush
) {
1369 remaining
= s
->length
;
1374 end
= memchr(p
, '\n', remaining
);
1377 else if (remaining
>= sizeof(s
->buffer
) - 1) {
1378 end
= p
+ sizeof(s
->buffer
) - 1;
1379 skip
= sizeof(s
->buffer
) - 1;
1385 r
= stdout_stream_line(s
, p
);
1393 if (force_flush
&& remaining
> 0) {
1395 r
= stdout_stream_line(s
, p
);
1403 if (p
> s
->buffer
) {
1404 memmove(s
->buffer
, p
, remaining
);
1405 s
->length
= remaining
;
1411 static int stdout_stream_process(StdoutStream
*s
) {
1417 l
= read(s
->fd
, s
->buffer
+s
->length
, sizeof(s
->buffer
)-1-s
->length
);
1420 if (errno
== EAGAIN
)
1423 log_warning("Failed to read from stream: %m");
1428 r
= stdout_stream_scan(s
, true);
1436 r
= stdout_stream_scan(s
, false);
1444 static void stdout_stream_free(StdoutStream
*s
) {
1448 assert(s
->server
->n_stdout_streams
> 0);
1449 s
->server
->n_stdout_streams
--;
1450 LIST_REMOVE(StdoutStream
, stdout_stream
, s
->server
->stdout_streams
, s
);
1455 epoll_ctl(s
->server
->epoll_fd
, EPOLL_CTL_DEL
, s
->fd
, NULL
);
1457 close_nointr_nofail(s
->fd
);
1460 free(s
->identifier
);
1464 static int stdout_stream_new(Server
*s
) {
1465 StdoutStream
*stream
;
1468 struct epoll_event ev
;
1472 fd
= accept4(s
->stdout_fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1474 if (errno
== EAGAIN
)
1477 log_error("Failed to accept stdout connection: %m");
1481 if (s
->n_stdout_streams
>= STDOUT_STREAMS_MAX
) {
1482 log_warning("Too many stdout streams, refusing connection.");
1483 close_nointr_nofail(fd
);
1487 stream
= new0(StdoutStream
, 1);
1489 log_error("Out of memory.");
1490 close_nointr_nofail(fd
);
1496 len
= sizeof(stream
->ucred
);
1497 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &stream
->ucred
, &len
) < 0) {
1498 log_error("Failed to determine peer credentials: %m");
1503 if (shutdown(fd
, SHUT_WR
) < 0) {
1504 log_error("Failed to shutdown writing side of socket: %m");
1510 ev
.data
.ptr
= stream
;
1511 ev
.events
= EPOLLIN
;
1512 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0) {
1513 log_error("Failed to add stream to event loop: %m");
1519 LIST_PREPEND(StdoutStream
, stdout_stream
, s
->stdout_streams
, stream
);
1520 s
->n_stdout_streams
++;
1525 stdout_stream_free(stream
);
1529 static int system_journal_open(Server
*s
) {
1535 r
= sd_id128_get_machine(&machine
);
1539 sd_id128_to_string(machine
, ids
);
1541 if (!s
->system_journal
) {
1543 /* First try to create the machine path, but not the prefix */
1544 fn
= strappend("/var/log/journal/", ids
);
1547 (void) mkdir(fn
, 0755);
1550 /* The create the system journal file */
1551 fn
= join("/var/log/journal/", ids
, "/system.journal", NULL
);
1555 r
= journal_file_open(fn
, O_RDWR
|O_CREAT
, 0640, NULL
, &s
->system_journal
);
1559 journal_default_metrics(&s
->system_metrics
, s
->system_journal
->fd
);
1561 s
->system_journal
->metrics
= s
->system_metrics
;
1562 s
->system_journal
->compress
= s
->compress
;
1564 fix_perms(s
->system_journal
, 0);
1567 if (r
!= -ENOENT
&& r
!= -EROFS
)
1568 log_warning("Failed to open system journal: %s", strerror(-r
));
1574 if (!s
->runtime_journal
) {
1576 fn
= join("/run/log/journal/", ids
, "/system.journal", NULL
);
1580 if (s
->system_journal
) {
1582 /* Try to open the runtime journal, but only
1583 * if it already exists, so that we can flush
1584 * it into the system journal */
1586 r
= journal_file_open(fn
, O_RDWR
, 0640, NULL
, &s
->runtime_journal
);
1591 log_warning("Failed to open runtime journal: %s", strerror(-r
));
1598 /* OK, we really need the runtime journal, so create
1599 * it if necessary. */
1601 (void) mkdir_parents(fn
, 0755);
1602 r
= journal_file_open(fn
, O_RDWR
|O_CREAT
, 0640, NULL
, &s
->runtime_journal
);
1606 log_error("Failed to open runtime journal: %s", strerror(-r
));
1611 if (s
->runtime_journal
) {
1612 journal_default_metrics(&s
->runtime_metrics
, s
->runtime_journal
->fd
);
1614 s
->runtime_journal
->metrics
= s
->runtime_metrics
;
1615 s
->runtime_journal
->compress
= s
->compress
;
1617 fix_perms(s
->runtime_journal
, 0);
1624 static int server_flush_to_var(Server
*s
) {
1625 char path
[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1634 if (!s
->runtime_journal
)
1637 ts
= now(CLOCK_MONOTONIC
);
1638 if (s
->var_available_timestamp
+ RECHECK_VAR_AVAILABLE_USEC
> ts
)
1641 s
->var_available_timestamp
= ts
;
1643 system_journal_open(s
);
1645 if (!s
->system_journal
)
1648 r
= sd_id128_get_machine(&machine
);
1650 log_error("Failed to get machine id: %s", strerror(-r
));
1654 r
= sd_journal_open(&j
, SD_JOURNAL_RUNTIME_ONLY
);
1656 log_error("Failed to read runtime journal: %s", strerror(-r
));
1660 SD_JOURNAL_FOREACH(j
) {
1663 f
= j
->current_file
;
1664 assert(f
&& f
->current_offset
> 0);
1666 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, f
->current_offset
, &o
);
1668 log_error("Can't read entry: %s", strerror(-r
));
1672 r
= journal_file_copy_entry(f
, s
->system_journal
, o
, f
->current_offset
, NULL
, NULL
, NULL
);
1674 log_info("Allocation limit reached.");
1676 journal_file_post_change(s
->system_journal
);
1680 r
= journal_file_copy_entry(f
, s
->system_journal
, o
, f
->current_offset
, NULL
, NULL
, NULL
);
1684 log_error("Can't write entry: %s", strerror(-r
));
1690 journal_file_post_change(s
->system_journal
);
1692 journal_file_close(s
->runtime_journal
);
1693 s
->runtime_journal
= NULL
;
1696 sd_id128_to_string(machine
, path
+ 17);
1697 rm_rf(path
, false, true, false);
1703 static int process_event(Server
*s
, struct epoll_event
*ev
) {
1706 if (ev
->data
.fd
== s
->signal_fd
) {
1707 struct signalfd_siginfo sfsi
;
1710 if (ev
->events
!= EPOLLIN
) {
1711 log_info("Got invalid event from epoll.");
1715 n
= read(s
->signal_fd
, &sfsi
, sizeof(sfsi
));
1716 if (n
!= sizeof(sfsi
)) {
1721 if (errno
== EINTR
|| errno
== EAGAIN
)
1727 if (sfsi
.ssi_signo
== SIGUSR1
) {
1728 server_flush_to_var(s
);
1732 log_debug("Received SIG%s", signal_to_string(sfsi
.ssi_signo
));
1735 } else if (ev
->data
.fd
== s
->native_fd
||
1736 ev
->data
.fd
== s
->syslog_fd
) {
1738 if (ev
->events
!= EPOLLIN
) {
1739 log_info("Got invalid event from epoll.");
1744 struct msghdr msghdr
;
1746 struct ucred
*ucred
= NULL
;
1747 struct timeval
*tv
= NULL
;
1748 struct cmsghdr
*cmsg
;
1750 struct cmsghdr cmsghdr
;
1751 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
)) +
1752 CMSG_SPACE(sizeof(struct timeval
))];
1757 if (ioctl(ev
->data
.fd
, SIOCINQ
, &v
) < 0) {
1758 log_error("SIOCINQ failed: %m");
1765 if (s
->buffer_size
< (size_t) v
) {
1769 l
= MAX(LINE_MAX
+ (size_t) v
, s
->buffer_size
* 2);
1770 b
= realloc(s
->buffer
, l
+1);
1773 log_error("Couldn't increase buffer.");
1782 iovec
.iov_base
= s
->buffer
;
1783 iovec
.iov_len
= s
->buffer_size
;
1787 msghdr
.msg_iov
= &iovec
;
1788 msghdr
.msg_iovlen
= 1;
1789 msghdr
.msg_control
= &control
;
1790 msghdr
.msg_controllen
= sizeof(control
);
1792 n
= recvmsg(ev
->data
.fd
, &msghdr
, MSG_DONTWAIT
);
1795 if (errno
== EINTR
|| errno
== EAGAIN
)
1798 log_error("recvmsg() failed: %m");
1802 for (cmsg
= CMSG_FIRSTHDR(&msghdr
); cmsg
; cmsg
= CMSG_NXTHDR(&msghdr
, cmsg
)) {
1804 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1805 cmsg
->cmsg_type
== SCM_CREDENTIALS
&&
1806 cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)))
1807 ucred
= (struct ucred
*) CMSG_DATA(cmsg
);
1808 else if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1809 cmsg
->cmsg_type
== SO_TIMESTAMP
&&
1810 cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct timeval
)))
1811 tv
= (struct timeval
*) CMSG_DATA(cmsg
);
1814 if (ev
->data
.fd
== s
->syslog_fd
) {
1817 e
= memchr(s
->buffer
, '\n', n
);
1823 process_syslog_message(s
, strstrip(s
->buffer
), ucred
, tv
);
1825 process_native_message(s
, s
->buffer
, n
, ucred
, tv
);
1830 } else if (ev
->data
.fd
== s
->stdout_fd
) {
1832 if (ev
->events
!= EPOLLIN
) {
1833 log_info("Got invalid event from epoll.");
1837 stdout_stream_new(s
);
1841 StdoutStream
*stream
;
1843 if ((ev
->events
|EPOLLIN
|EPOLLHUP
) != (EPOLLIN
|EPOLLHUP
)) {
1844 log_info("Got invalid event from epoll.");
1848 /* If it is none of the well-known fds, it must be an
1849 * stdout stream fd. Note that this is a bit ugly here
1850 * (since we rely that none of the well-known fds
1851 * could be interpreted as pointer), but nonetheless
1852 * safe, since the well-known fds would never get an
1853 * fd > 4096, i.e. beyond the first memory page */
1855 stream
= ev
->data
.ptr
;
1857 if (stdout_stream_process(stream
) <= 0)
1858 stdout_stream_free(stream
);
1863 log_error("Unknown event.");
1867 static int open_syslog_socket(Server
*s
) {
1868 union sockaddr_union sa
;
1870 struct epoll_event ev
;
1875 if (s
->syslog_fd
< 0) {
1877 s
->syslog_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1878 if (s
->syslog_fd
< 0) {
1879 log_error("socket() failed: %m");
1884 sa
.un
.sun_family
= AF_UNIX
;
1885 strncpy(sa
.un
.sun_path
, "/dev/log", sizeof(sa
.un
.sun_path
));
1887 unlink(sa
.un
.sun_path
);
1889 r
= bind(s
->syslog_fd
, &sa
.sa
, offsetof(union sockaddr_union
, un
.sun_path
) + strlen(sa
.un
.sun_path
));
1891 log_error("bind() failed: %m");
1895 chmod(sa
.un
.sun_path
, 0666);
1899 r
= setsockopt(s
->syslog_fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
));
1901 log_error("SO_PASSCRED failed: %m");
1906 r
= setsockopt(s
->syslog_fd
, SOL_SOCKET
, SO_TIMESTAMP
, &one
, sizeof(one
));
1908 log_error("SO_TIMESTAMP failed: %m");
1912 /* Since we use the same socket for forwarding this to some
1913 * other syslog implementation, make sure we don't hang
1915 timeval_store(&tv
, SYSLOG_TIMEOUT_USEC
);
1916 if (setsockopt(s
->syslog_fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
)) < 0) {
1917 log_error("SO_SNDTIMEO failed: %m");
1922 ev
.events
= EPOLLIN
;
1923 ev
.data
.fd
= s
->syslog_fd
;
1924 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->syslog_fd
, &ev
) < 0) {
1925 log_error("Failed to add syslog server fd to epoll object: %m");
1932 static int open_native_socket(Server
*s
) {
1933 union sockaddr_union sa
;
1935 struct epoll_event ev
;
1939 if (s
->native_fd
< 0) {
1941 s
->native_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1942 if (s
->native_fd
< 0) {
1943 log_error("socket() failed: %m");
1948 sa
.un
.sun_family
= AF_UNIX
;
1949 strncpy(sa
.un
.sun_path
, "/run/systemd/journal/socket", sizeof(sa
.un
.sun_path
));
1951 unlink(sa
.un
.sun_path
);
1953 r
= bind(s
->native_fd
, &sa
.sa
, offsetof(union sockaddr_union
, un
.sun_path
) + strlen(sa
.un
.sun_path
));
1955 log_error("bind() failed: %m");
1959 chmod(sa
.un
.sun_path
, 0666);
1963 r
= setsockopt(s
->native_fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
));
1965 log_error("SO_PASSCRED failed: %m");
1970 r
= setsockopt(s
->native_fd
, SOL_SOCKET
, SO_TIMESTAMP
, &one
, sizeof(one
));
1972 log_error("SO_TIMESTAMP failed: %m");
1977 ev
.events
= EPOLLIN
;
1978 ev
.data
.fd
= s
->native_fd
;
1979 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->native_fd
, &ev
) < 0) {
1980 log_error("Failed to add native server fd to epoll object: %m");
1987 static int open_stdout_socket(Server
*s
) {
1988 union sockaddr_union sa
;
1990 struct epoll_event ev
;
1994 if (s
->stdout_fd
< 0) {
1996 s
->stdout_fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
, 0);
1997 if (s
->stdout_fd
< 0) {
1998 log_error("socket() failed: %m");
2003 sa
.un
.sun_family
= AF_UNIX
;
2004 strncpy(sa
.un
.sun_path
, "/run/systemd/journal/stdout", sizeof(sa
.un
.sun_path
));
2006 unlink(sa
.un
.sun_path
);
2008 r
= bind(s
->stdout_fd
, &sa
.sa
, offsetof(union sockaddr_union
, un
.sun_path
) + strlen(sa
.un
.sun_path
));
2010 log_error("bind() failed: %m");
2014 chmod(sa
.un
.sun_path
, 0666);
2016 if (listen(s
->stdout_fd
, SOMAXCONN
) < 0) {
2017 log_error("liste() failed: %m");
2023 ev
.events
= EPOLLIN
;
2024 ev
.data
.fd
= s
->stdout_fd
;
2025 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->stdout_fd
, &ev
) < 0) {
2026 log_error("Failed to add stdout server fd to epoll object: %m");
2033 static int open_signalfd(Server
*s
) {
2035 struct epoll_event ev
;
2039 assert_se(sigemptyset(&mask
) == 0);
2040 sigset_add_many(&mask
, SIGINT
, SIGTERM
, SIGUSR1
, -1);
2041 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) == 0);
2043 s
->signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
2044 if (s
->signal_fd
< 0) {
2045 log_error("signalfd(): %m");
2050 ev
.events
= EPOLLIN
;
2051 ev
.data
.fd
= s
->signal_fd
;
2053 if (epoll_ctl(s
->epoll_fd
, EPOLL_CTL_ADD
, s
->signal_fd
, &ev
) < 0) {
2054 log_error("epoll_ctl(): %m");
2061 static int server_parse_proc_cmdline(Server
*s
) {
2062 char *line
, *w
, *state
;
2066 if (detect_container(NULL
) > 0)
2069 r
= read_one_line_file("/proc/cmdline", &line
);
2071 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r
));
2075 FOREACH_WORD_QUOTED(w
, l
, line
, state
) {
2078 word
= strndup(w
, l
);
2084 if (startswith(word
, "systemd_journald.forward_to_syslog=")) {
2085 r
= parse_boolean(word
+ 35);
2087 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word
+ 35);
2089 s
->forward_to_syslog
= r
;
2090 } else if (startswith(word
, "systemd_journald.forward_to_kmsg=")) {
2091 r
= parse_boolean(word
+ 33);
2093 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word
+ 33);
2095 s
->forward_to_kmsg
= r
;
2096 } else if (startswith(word
, "systemd_journald.forward_to_console=")) {
2097 r
= parse_boolean(word
+ 36);
2099 log_warning("Failed to parse forward to console switch %s. Ignoring.", word
+ 36);
2101 s
->forward_to_console
= r
;
2114 static int server_parse_config_file(Server
*s
) {
2121 fn
= "/etc/systemd/systemd-journald.conf";
2122 f
= fopen(fn
, "re");
2124 if (errno
== ENOENT
)
2127 log_warning("Failed to open configuration file %s: %m", fn
);
2131 r
= config_parse(fn
, f
, "Journal\0", config_item_perf_lookup
, (void*) journald_gperf_lookup
, false, s
);
2133 log_warning("Failed to parse configuration file: %s", strerror(-r
));
2140 static int server_init(Server
*s
) {
2146 s
->syslog_fd
= s
->native_fd
= s
->stdout_fd
= s
->signal_fd
= s
->epoll_fd
= -1;
2149 s
->rate_limit_interval
= DEFAULT_RATE_LIMIT_INTERVAL
;
2150 s
->rate_limit_burst
= DEFAULT_RATE_LIMIT_BURST
;
2152 s
->forward_to_syslog
= true;
2154 memset(&s
->system_metrics
, 0xFF, sizeof(s
->system_metrics
));
2155 memset(&s
->runtime_metrics
, 0xFF, sizeof(s
->runtime_metrics
));
2157 server_parse_config_file(s
);
2158 server_parse_proc_cmdline(s
);
2160 s
->user_journals
= hashmap_new(trivial_hash_func
, trivial_compare_func
);
2161 if (!s
->user_journals
) {
2162 log_error("Out of memory.");
2166 s
->epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
2167 if (s
->epoll_fd
< 0) {
2168 log_error("Failed to create epoll object: %m");
2172 n
= sd_listen_fds(true);
2174 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n
));
2178 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
2180 if (sd_is_socket_unix(fd
, SOCK_DGRAM
, -1, "/run/systemd/journal/socket", 0) > 0) {
2182 if (s
->native_fd
>= 0) {
2183 log_error("Too many native sockets passed.");
2189 } else if (sd_is_socket_unix(fd
, SOCK_STREAM
, 1, "/run/systemd/journal/stdout", 0) > 0) {
2191 if (s
->stdout_fd
>= 0) {
2192 log_error("Too many stdout sockets passed.");
2198 } else if (sd_is_socket_unix(fd
, SOCK_DGRAM
, -1, "/dev/log", 0) > 0) {
2200 if (s
->syslog_fd
>= 0) {
2201 log_error("Too many /dev/log sockets passed.");
2208 log_error("Unknown socket passed.");
2213 r
= open_syslog_socket(s
);
2217 r
= open_native_socket(s
);
2221 r
= open_stdout_socket(s
);
2225 r
= system_journal_open(s
);
2229 r
= open_signalfd(s
);
2233 s
->rate_limit
= journal_rate_limit_new(s
->rate_limit_interval
, s
->rate_limit_burst
);
2240 static void server_done(Server
*s
) {
2244 while (s
->stdout_streams
)
2245 stdout_stream_free(s
->stdout_streams
);
2247 if (s
->system_journal
)
2248 journal_file_close(s
->system_journal
);
2250 if (s
->runtime_journal
)
2251 journal_file_close(s
->runtime_journal
);
2253 while ((f
= hashmap_steal_first(s
->user_journals
)))
2254 journal_file_close(f
);
2256 hashmap_free(s
->user_journals
);
2258 if (s
->epoll_fd
>= 0)
2259 close_nointr_nofail(s
->epoll_fd
);
2261 if (s
->signal_fd
>= 0)
2262 close_nointr_nofail(s
->signal_fd
);
2264 if (s
->syslog_fd
>= 0)
2265 close_nointr_nofail(s
->syslog_fd
);
2267 if (s
->native_fd
>= 0)
2268 close_nointr_nofail(s
->native_fd
);
2270 if (s
->stdout_fd
>= 0)
2271 close_nointr_nofail(s
->stdout_fd
);
2274 journal_rate_limit_free(s
->rate_limit
);
2279 int main(int argc
, char *argv
[]) {
2283 /* if (getppid() != 1) { */
2284 /* log_error("This program should be invoked by init only."); */
2285 /* return EXIT_FAILURE; */
2289 log_error("This program does not take arguments.");
2290 return EXIT_FAILURE
;
2293 log_set_target(LOG_TARGET_CONSOLE
);
2294 log_parse_environment();
2299 r
= server_init(&server
);
2303 server_vacuum(&server
);
2304 server_flush_to_var(&server
);
2306 log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2307 driver_message(&server
, SD_MESSAGE_JOURNAL_START
, "Journal started");
2311 "STATUS=Processing requests...");
2314 struct epoll_event event
;
2316 r
= epoll_wait(server
.epoll_fd
, &event
, 1, -1);
2322 log_error("epoll_wait() failed: %m");
2328 r
= process_event(&server
, &event
);
2335 log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2336 driver_message(&server
, SD_MESSAGE_JOURNAL_STOP
, "Journal stopped");
2340 "STATUS=Shutting down...");
2342 server_done(&server
);
2344 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;