1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include <sys/signalfd.h>
16 #include "sd-messages.h"
18 #include "alloc-util.h"
19 #include "argv-util.h"
21 #include "errno-util.h"
23 #include "format-util.h"
24 #include "iovec-util.h"
27 #include "missing_syscall.h"
28 #include "missing_threads.h"
29 #include "parse-util.h"
30 #include "proc-cmdline.h"
31 #include "process-util.h"
32 #include "ratelimit.h"
33 #include "signal-util.h"
34 #include "socket-util.h"
35 #include "stdio-util.h"
36 #include "string-table.h"
37 #include "string-util.h"
39 #include "syslog-util.h"
40 #include "terminal-util.h"
41 #include "time-util.h"
44 #define SNDBUF_SIZE (8*1024*1024)
45 #define IOVEC_MAX 256U
47 static log_syntax_callback_t log_syntax_callback
= NULL
;
48 static void *log_syntax_callback_userdata
= NULL
;
50 static LogTarget log_target
= LOG_TARGET_CONSOLE
;
51 static int log_max_level
= LOG_INFO
;
52 static int log_facility
= LOG_DAEMON
;
53 static bool ratelimit_kmsg
= true;
55 static int console_fd
= STDERR_FILENO
;
56 static int syslog_fd
= -EBADF
;
57 static int kmsg_fd
= -EBADF
;
58 static int journal_fd
= -EBADF
;
60 static bool syslog_is_stream
= false;
62 static int show_color
= -1; /* tristate */
63 static bool show_location
= false;
64 static bool show_time
= false;
65 static bool show_tid
= false;
67 static bool upgrade_syslog_to_journal
= false;
68 static bool always_reopen_console
= false;
69 static bool open_when_needed
= false;
70 static bool prohibit_ipc
= false;
72 /* Akin to glibc's __abort_msg; which is private and we hence cannot
74 static char *log_abort_msg
= NULL
;
76 typedef struct LogContext
{
78 /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
79 * referenced by this is freed or not */
81 struct iovec
*input_iovec
;
86 LIST_FIELDS(struct LogContext
, ll
);
89 static thread_local
LIST_HEAD(LogContext
, _log_context
) = NULL
;
90 static thread_local
size_t _log_context_num_fields
= 0;
92 static thread_local
const char *log_prefix
= NULL
;
94 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
95 bool _log_message_dummy
= false; /* Always false */
98 /* An assert to use in logging functions that does not call recursively
99 * into our logging functions (since that might lead to a loop). */
100 #define assert_raw(expr) \
102 if (_unlikely_(!(expr))) { \
103 fputs(#expr "\n", stderr); \
108 static void log_close_console(void) {
109 /* See comment in log_close_journal() */
110 (void) safe_close_above_stdio(TAKE_FD(console_fd
));
113 static int log_open_console(void) {
115 if (!always_reopen_console
) {
116 console_fd
= STDERR_FILENO
;
120 if (console_fd
< 3) {
123 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
127 console_fd
= fd_move_above_stdio(fd
);
133 static void log_close_kmsg(void) {
134 /* See comment in log_close_journal() */
135 (void) safe_close(TAKE_FD(kmsg_fd
));
138 static int log_open_kmsg(void) {
143 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
147 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
151 static void log_close_syslog(void) {
152 /* See comment in log_close_journal() */
153 (void) safe_close(TAKE_FD(syslog_fd
));
156 static int create_log_socket(int type
) {
160 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
164 fd
= fd_move_above_stdio(fd
);
165 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
167 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
168 * in the unlikely case of a deadlock. */
169 if (getpid_cached() == 1)
170 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
172 timeval_store(&tv
, 10 * USEC_PER_SEC
);
173 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
178 static int log_open_syslog(void) {
184 syslog_fd
= create_log_socket(SOCK_DGRAM
);
190 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
192 safe_close(syslog_fd
);
194 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
196 syslog_fd
= create_log_socket(SOCK_STREAM
);
202 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
206 syslog_is_stream
= true;
208 syslog_is_stream
= false;
217 static void log_close_journal(void) {
218 /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
219 * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
220 * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
222 (void) safe_close(TAKE_FD(journal_fd
));
225 static int log_open_journal(void) {
231 journal_fd
= create_log_socket(SOCK_DGRAM
);
232 if (journal_fd
< 0) {
237 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
248 static bool stderr_is_journal(void) {
249 _cleanup_free_
char *w
= NULL
;
254 e
= getenv("JOURNAL_STREAM");
258 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
263 if (safe_atou64(w
, &dev
) < 0)
265 if (safe_atou64(e
, &ino
) < 0)
268 if (fstat(STDERR_FILENO
, &st
) < 0)
271 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
277 /* Do not call from library code. */
279 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
280 * so that a call to a logging function immediately following a log_open() call can still easily
281 * reference an error that happened immediately before the log_open() call. */
284 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
285 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
286 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
287 * because there is no reason to close it. */
289 if (log_target
== LOG_TARGET_NULL
) {
296 if (getpid_cached() == 1 ||
297 stderr_is_journal() ||
301 LOG_TARGET_JOURNAL_OR_KMSG
,
303 LOG_TARGET_SYSLOG_OR_KMSG
)) {
306 if (IN_SET(log_target
,
308 LOG_TARGET_JOURNAL_OR_KMSG
,
309 LOG_TARGET_JOURNAL
)) {
311 r
= log_open_journal();
319 if (IN_SET(log_target
,
320 LOG_TARGET_SYSLOG_OR_KMSG
,
321 LOG_TARGET_SYSLOG
)) {
323 r
= log_open_syslog();
332 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
333 LOG_TARGET_JOURNAL_OR_KMSG
,
334 LOG_TARGET_SYSLOG_OR_KMSG
,
349 return log_open_console();
352 void log_set_target(LogTarget target
) {
354 assert(target
< _LOG_TARGET_MAX
);
356 if (upgrade_syslog_to_journal
) {
357 if (target
== LOG_TARGET_SYSLOG
)
358 target
= LOG_TARGET_JOURNAL
;
359 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
360 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
366 void log_set_target_and_open(LogTarget target
) {
367 log_set_target(target
);
371 void log_close(void) {
372 /* Do not call from library code. */
380 void log_forget_fds(void) {
381 /* Do not call from library code. */
383 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
386 void log_set_max_level(int level
) {
387 assert(level
== LOG_NULL
|| (level
& LOG_PRIMASK
) == level
);
389 log_max_level
= level
;
391 /* Also propagate max log level to libc's syslog(), just in case some other component loaded into our
392 * process logs directly via syslog(). You might wonder why we maintain our own log level variable if
393 * libc has the same functionality. This has multiple reasons, first and foremost that we want to
394 * apply this to all our log targets, not just syslog and console. Moreover, we cannot query the
395 * current log mask from glibc without changing it, but that's useful for testing the current log
396 * level before even entering the log functions like we do in our macros. */
397 setlogmask(LOG_UPTO(level
));
399 /* Ensure that our own LOG_NULL define maps sanely to the log mask */
400 assert_cc(LOG_UPTO(LOG_NULL
) == 0);
403 void log_set_facility(int facility
) {
404 log_facility
= facility
;
407 static int write_to_console(
413 const char *buffer
) {
416 header_time
[FORMAT_TIMESTAMP_MAX
],
417 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
418 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
419 struct iovec iovec
[11];
420 const char *on
= NULL
, *off
= NULL
;
426 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
427 xsprintf(prefix
, "<%i>", level
);
428 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
432 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
433 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
434 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
438 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
439 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
442 if (log_get_show_color())
443 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
446 const char *lon
= "", *loff
= "";
447 if (log_get_show_color()) {
448 lon
= ansi_highlight_yellow4();
449 loff
= ansi_normal();
452 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
453 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
457 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
459 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
460 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
462 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
464 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
465 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
467 if (writev(console_fd
, iovec
, n
) < 0) {
469 if (errno
== EIO
&& getpid_cached() == 1) {
471 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
475 (void) log_open_console();
479 if (writev(console_fd
, iovec
, n
) < 0)
488 static int write_to_syslog(
494 const char *buffer
) {
496 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
498 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
505 xsprintf(header_priority
, "<%i>", level
);
507 t
= (time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
);
508 if (!localtime_r(&t
, &tm
))
511 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
514 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
516 struct iovec iovec
[] = {
517 IOVEC_MAKE_STRING(header_priority
),
518 IOVEC_MAKE_STRING(header_time
),
519 IOVEC_MAKE_STRING(program_invocation_short_name
),
520 IOVEC_MAKE_STRING(header_pid
),
521 IOVEC_MAKE_STRING(strempty(log_prefix
)),
522 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
523 IOVEC_MAKE_STRING(buffer
),
525 const struct msghdr msghdr
= {
527 .msg_iovlen
= ELEMENTSOF(iovec
),
530 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
531 if (syslog_is_stream
)
532 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
537 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
541 if (!syslog_is_stream
)
544 if (iovec_increment(iovec
, ELEMENTSOF(iovec
), n
))
551 static int write_to_kmsg(
557 const char *buffer
) {
559 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
560 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
561 * where we log excessively, but not in a tight loop.
563 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
566 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
568 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
569 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
574 if (ratelimit_kmsg
&& !ratelimit_below(&ratelimit
)) {
575 if (ratelimit_num_dropped(&ratelimit
) > 1)
578 buffer
= "Too many messages being logged to kmsg, ignoring";
581 xsprintf(header_priority
, "<%i>", level
);
582 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
584 const struct iovec iovec
[] = {
585 IOVEC_MAKE_STRING(header_priority
),
586 IOVEC_MAKE_STRING(program_invocation_short_name
),
587 IOVEC_MAKE_STRING(header_pid
),
588 IOVEC_MAKE_STRING(strempty(log_prefix
)),
589 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
590 IOVEC_MAKE_STRING(buffer
),
591 IOVEC_MAKE_STRING("\n"),
594 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
600 static int log_do_header(
605 const char *file
, int line
, const char *func
,
606 const char *object_field
, const char *object
,
607 const char *extra_field
, const char *extra
) {
610 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
612 r
= snprintf(header
, size
,
614 "SYSLOG_FACILITY=%i\n"
616 "%s%.256s%s" /* CODE_FILE */
617 "%s%.*i%s" /* CODE_LINE */
618 "%s%.256s%s" /* CODE_FUNC */
619 "%s%.*i%s" /* ERRNO */
620 "%s%.256s%s" /* object */
621 "%s%.256s%s" /* extra */
622 "SYSLOG_IDENTIFIER=%.256s\n",
626 isempty(file
) ? "" : "CODE_FILE=",
627 isempty(file
) ? "" : file
,
628 isempty(file
) ? "" : "\n",
629 line
? "CODE_LINE=" : "",
630 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
632 isempty(func
) ? "" : "CODE_FUNC=",
633 isempty(func
) ? "" : func
,
634 isempty(func
) ? "" : "\n",
635 error
? "ERRNO=" : "",
636 error
? 1 : 0, error
,
638 isempty(object
) ? "" : object_field
,
639 isempty(object
) ? "" : object
,
640 isempty(object
) ? "" : "\n",
641 isempty(extra
) ? "" : extra_field
,
642 isempty(extra
) ? "" : extra
,
643 isempty(extra
) ? "" : "\n",
644 program_invocation_short_name
);
645 assert_raw((size_t) r
< size
);
650 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
654 LIST_FOREACH(ll
, c
, _log_context
) {
655 STRV_FOREACH(s
, c
->fields
) {
656 if (*n
+ 2 >= iovec_len
)
659 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
660 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
663 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
664 if (*n
+ 2 >= iovec_len
)
667 iovec
[(*n
)++] = c
->input_iovec
[i
];
668 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
671 if (c
->key
&& c
->value
) {
672 if (*n
+ 3 >= iovec_len
)
675 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->key
);
676 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->value
);
677 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
682 static int write_to_journal(
688 const char *object_field
,
690 const char *extra_field
,
692 const char *buffer
) {
694 char header
[LINE_MAX
];
695 size_t n
= 0, iovec_len
;
701 iovec_len
= MIN(6 + _log_context_num_fields
* 2, IOVEC_MAX
);
702 iovec
= newa(struct iovec
, iovec_len
);
704 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
706 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
707 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
709 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
710 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
712 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
713 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
715 log_do_context(iovec
, iovec_len
, &n
);
717 const struct msghdr msghdr
= {
722 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
728 int log_dispatch_internal(
734 const char *object_field
,
736 const char *extra_field
,
742 if (log_target
== LOG_TARGET_NULL
)
743 return -ERRNO_VALUE(error
);
745 /* Patch in LOG_DAEMON facility if necessary */
746 if ((level
& LOG_FACMASK
) == 0)
747 level
|= log_facility
;
749 if (open_when_needed
)
756 buffer
+= strspn(buffer
, NEWLINE
);
761 if ((e
= strpbrk(buffer
, NEWLINE
)))
764 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
765 LOG_TARGET_JOURNAL_OR_KMSG
,
766 LOG_TARGET_JOURNAL
)) {
768 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
769 if (k
< 0 && k
!= -EAGAIN
)
773 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
774 LOG_TARGET_SYSLOG
)) {
776 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
777 if (k
< 0 && k
!= -EAGAIN
)
782 IN_SET(log_target
, LOG_TARGET_AUTO
,
783 LOG_TARGET_SYSLOG_OR_KMSG
,
784 LOG_TARGET_JOURNAL_OR_KMSG
,
790 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
793 (void) log_open_console();
798 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
803 if (open_when_needed
)
806 return -ERRNO_VALUE(error
);
809 int log_dump_internal(
819 /* This modifies the buffer... */
821 if (_likely_(LOG_PRI(level
) > log_max_level
))
822 return -ERRNO_VALUE(error
);
824 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
836 if (_likely_(LOG_PRI(level
) > log_max_level
))
837 return -ERRNO_VALUE(error
);
839 /* Make sure that %m maps to the specified error (or "Success"). */
840 char buffer
[LINE_MAX
];
841 LOCAL_ERRNO(ERRNO_VALUE(error
));
843 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
845 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
854 const char *format
, ...) {
859 va_start(ap
, format
);
860 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
866 int log_object_internalv(
872 const char *object_field
,
874 const char *extra_field
,
881 if (_likely_(LOG_PRI(level
) > log_max_level
))
882 return -ERRNO_VALUE(error
);
884 /* Make sure that %m maps to the specified error (or "Success"). */
885 LOCAL_ERRNO(ERRNO_VALUE(error
));
887 LOG_SET_PREFIX(object
);
889 b
= buffer
= newa(char, LINE_MAX
);
890 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
892 return log_dispatch_internal(level
, error
, file
, line
, func
,
893 object_field
, object
, extra_field
, extra
, buffer
);
896 int log_object_internal(
902 const char *object_field
,
904 const char *extra_field
,
906 const char *format
, ...) {
911 va_start(ap
, format
);
912 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
918 static void log_assert(
924 const char *format
) {
926 static char buffer
[LINE_MAX
];
928 if (_likely_(LOG_PRI(level
) > log_max_level
))
931 DISABLE_WARNING_FORMAT_NONLITERAL
;
932 (void) snprintf(buffer
, sizeof buffer
, format
, text
, file
, line
, func
);
935 log_abort_msg
= buffer
;
937 log_dispatch_internal(level
, 0, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
940 _noreturn_
void log_assert_failed(
945 log_assert(LOG_CRIT
, text
, file
, line
, func
,
946 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
950 _noreturn_
void log_assert_failed_unreachable(
954 log_assert(LOG_CRIT
, "Code should not be reached", file
, line
, func
,
955 "%s at %s:%u, function %s(). Aborting. 💥");
959 void log_assert_failed_return(
965 log_assert(LOG_DEBUG
, text
, file
, line
, func
,
966 "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
969 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
970 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
973 int log_format_iovec(
977 bool newline_separator
,
982 static const char nl
= '\n';
984 while (format
&& *n
+ 1 < iovec_len
) {
989 /* We need to copy the va_list structure,
990 * since vasprintf() leaves it afterwards at
991 * an undefined location */
993 errno
= ERRNO_VALUE(error
);
996 r
= vasprintf(&m
, format
, aq
);
1001 /* Now, jump enough ahead, so that we point to
1002 * the next format string */
1003 VA_FORMAT_ADVANCE(format
, ap
);
1005 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
1006 if (newline_separator
)
1007 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
1009 format
= va_arg(ap
, char *);
1014 int log_struct_internal(
1020 const char *format
, ...) {
1027 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1028 log_target
== LOG_TARGET_NULL
)
1029 return -ERRNO_VALUE(error
);
1031 if ((level
& LOG_FACMASK
) == 0)
1032 level
|= log_facility
;
1034 if (IN_SET(log_target
,
1036 LOG_TARGET_JOURNAL_OR_KMSG
,
1037 LOG_TARGET_JOURNAL
)) {
1039 if (open_when_needed
)
1042 if (journal_fd
>= 0) {
1043 char header
[LINE_MAX
];
1044 struct iovec
*iovec
;
1045 size_t n
= 0, m
, iovec_len
;
1047 bool fallback
= false;
1049 iovec_len
= MIN(17 + _log_context_num_fields
* 2, IOVEC_MAX
);
1050 iovec
= newa(struct iovec
, iovec_len
);
1052 /* If the journal is available do structured logging.
1053 * Do not report the errno if it is synthetic. */
1054 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1055 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1057 va_start(ap
, format
);
1058 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1063 log_do_context(iovec
, iovec_len
, &n
);
1065 const struct msghdr msghdr
= {
1070 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1074 for (size_t i
= 1; i
< m
; i
+= 2)
1075 free(iovec
[i
].iov_base
);
1078 if (open_when_needed
)
1081 return -ERRNO_VALUE(error
);
1086 /* Fallback if journal logging is not available or didn't work. */
1088 va_start(ap
, format
);
1092 errno
= ERRNO_VALUE(error
);
1095 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1098 if (startswith(buf
, "MESSAGE=")) {
1103 VA_FORMAT_ADVANCE(format
, ap
);
1105 format
= va_arg(ap
, char *);
1110 if (open_when_needed
)
1113 return -ERRNO_VALUE(error
);
1116 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1119 int log_struct_iovec_internal(
1125 const struct iovec input_iovec
[],
1126 size_t n_input_iovec
) {
1130 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1131 log_target
== LOG_TARGET_NULL
)
1132 return -ERRNO_VALUE(error
);
1134 if ((level
& LOG_FACMASK
) == 0)
1135 level
|= log_facility
;
1137 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1138 LOG_TARGET_JOURNAL_OR_KMSG
,
1139 LOG_TARGET_JOURNAL
) &&
1142 char header
[LINE_MAX
];
1143 struct iovec
*iovec
;
1144 size_t n
= 0, iovec_len
;
1146 iovec_len
= MIN(1 + n_input_iovec
* 2 + _log_context_num_fields
* 2, IOVEC_MAX
);
1147 iovec
= newa(struct iovec
, iovec_len
);
1149 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1151 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1152 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1153 iovec
[n
++] = input_iovec
[i
];
1154 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1157 log_do_context(iovec
, iovec_len
, &n
);
1159 const struct msghdr msghdr
= {
1164 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1165 return -ERRNO_VALUE(error
);
1168 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1169 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1172 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1173 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1175 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1178 /* Couldn't find MESSAGE=. */
1179 return -ERRNO_VALUE(error
);
1182 int log_set_target_from_string(const char *e
) {
1185 t
= log_target_from_string(e
);
1193 int log_set_max_level_from_string(const char *e
) {
1196 t
= log_level_from_string(e
);
1200 log_set_max_level(t
);
1204 static int log_set_ratelimit_kmsg_from_string(const char *e
) {
1207 r
= parse_boolean(e
);
1215 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1218 * The systemd.log_xyz= settings are parsed by all tools, and
1221 * However, "quiet" is only parsed by PID 1, and only turns of
1222 * status output to /dev/console, but does not alter the log
1226 if (streq(key
, "debug") && !value
)
1227 log_set_max_level(LOG_DEBUG
);
1229 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1231 if (proc_cmdline_value_missing(key
, value
))
1234 if (log_set_target_from_string(value
) < 0)
1235 log_warning("Failed to parse log target '%s'. Ignoring.", value
);
1237 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1239 if (proc_cmdline_value_missing(key
, value
))
1242 if (log_set_max_level_from_string(value
) < 0)
1243 log_warning("Failed to parse log level '%s'. Ignoring.", value
);
1245 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1247 if (log_show_color_from_string(value
?: "1") < 0)
1248 log_warning("Failed to parse log color setting '%s'. Ignoring.", value
);
1250 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1252 if (log_show_location_from_string(value
?: "1") < 0)
1253 log_warning("Failed to parse log location setting '%s'. Ignoring.", value
);
1255 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1257 if (log_show_tid_from_string(value
?: "1") < 0)
1258 log_warning("Failed to parse log tid setting '%s'. Ignoring.", value
);
1260 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1262 if (log_show_time_from_string(value
?: "1") < 0)
1263 log_warning("Failed to parse log time setting '%s'. Ignoring.", value
);
1265 } else if (proc_cmdline_key_streq(key
, "systemd.log_ratelimit_kmsg")) {
1267 if (log_set_ratelimit_kmsg_from_string(value
?: "1") < 0)
1268 log_warning("Failed to parse log ratelimit kmsg boolean '%s'. Ignoring.", value
);
1274 static bool should_parse_proc_cmdline(void) {
1275 /* PID1 always reads the kernel command line. */
1276 if (getpid_cached() == 1)
1279 /* Otherwise, parse the command line if invoked directly by systemd. */
1280 return invoked_by_systemd();
1283 void log_parse_environment_variables(void) {
1286 e
= getenv("SYSTEMD_LOG_TARGET");
1287 if (e
&& log_set_target_from_string(e
) < 0)
1288 log_warning("Failed to parse log target '%s'. Ignoring.", e
);
1290 e
= getenv("SYSTEMD_LOG_LEVEL");
1291 if (e
&& log_set_max_level_from_string(e
) < 0)
1292 log_warning("Failed to parse log level '%s'. Ignoring.", e
);
1294 e
= getenv("SYSTEMD_LOG_COLOR");
1295 if (e
&& log_show_color_from_string(e
) < 0)
1296 log_warning("Failed to parse log color '%s'. Ignoring.", e
);
1298 e
= getenv("SYSTEMD_LOG_LOCATION");
1299 if (e
&& log_show_location_from_string(e
) < 0)
1300 log_warning("Failed to parse log location '%s'. Ignoring.", e
);
1302 e
= getenv("SYSTEMD_LOG_TIME");
1303 if (e
&& log_show_time_from_string(e
) < 0)
1304 log_warning("Failed to parse log time '%s'. Ignoring.", e
);
1306 e
= getenv("SYSTEMD_LOG_TID");
1307 if (e
&& log_show_tid_from_string(e
) < 0)
1308 log_warning("Failed to parse log tid '%s'. Ignoring.", e
);
1310 e
= getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
1311 if (e
&& log_set_ratelimit_kmsg_from_string(e
) < 0)
1312 log_warning("Failed to parse log ratelimit kmsg boolean '%s'. Ignoring.", e
);
1315 void log_parse_environment(void) {
1316 /* Do not call from library code. */
1318 if (should_parse_proc_cmdline())
1319 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1321 log_parse_environment_variables();
1324 LogTarget
log_get_target(void) {
1328 void log_settle_target(void) {
1330 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1331 * stderr is attached to the journal every single log call. However, if we then close all file
1332 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1333 * problem, this function is used to permanently change the log target depending on whether stderr is
1334 * connected to the journal or not. */
1336 LogTarget t
= log_get_target();
1338 if (t
!= LOG_TARGET_AUTO
)
1341 t
= getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc
? LOG_TARGET_KMSG
: LOG_TARGET_JOURNAL_OR_KMSG
)
1342 : LOG_TARGET_CONSOLE
;
1346 int log_get_max_level(void) {
1347 return log_max_level
;
1350 void log_show_color(bool b
) {
1354 bool log_get_show_color(void) {
1355 return show_color
> 0; /* Defaults to false. */
1358 void log_show_location(bool b
) {
1362 bool log_get_show_location(void) {
1363 return show_location
;
1366 void log_show_time(bool b
) {
1370 bool log_get_show_time(void) {
1374 void log_show_tid(bool b
) {
1378 bool log_get_show_tid(void) {
1382 int log_show_color_from_string(const char *e
) {
1385 t
= parse_boolean(e
);
1393 int log_show_location_from_string(const char *e
) {
1396 t
= parse_boolean(e
);
1400 log_show_location(t
);
1404 int log_show_time_from_string(const char *e
) {
1407 t
= parse_boolean(e
);
1415 int log_show_tid_from_string(const char *e
) {
1418 t
= parse_boolean(e
);
1426 bool log_on_console(void) {
1427 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1428 LOG_TARGET_CONSOLE_PREFIXED
))
1431 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1434 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1435 [LOG_TARGET_CONSOLE
] = "console",
1436 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1437 [LOG_TARGET_KMSG
] = "kmsg",
1438 [LOG_TARGET_JOURNAL
] = "journal",
1439 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1440 [LOG_TARGET_SYSLOG
] = "syslog",
1441 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1442 [LOG_TARGET_AUTO
] = "auto",
1443 [LOG_TARGET_NULL
] = "null",
1446 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1448 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1451 if (pid_is_valid(si
->ssi_pid
)) {
1452 _cleanup_free_
char *p
= NULL
;
1454 (void) pid_get_comm(si
->ssi_pid
, &p
);
1457 "Received SIG%s from PID %"PRIu32
" (%s).",
1458 signal_to_string(si
->ssi_signo
),
1459 si
->ssi_pid
, strna(p
));
1463 signal_to_string(si
->ssi_signo
));
1466 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1467 assert(!log_syntax_callback
|| !cb
);
1468 assert(!log_syntax_callback_userdata
|| !userdata
);
1470 log_syntax_callback
= cb
;
1471 log_syntax_callback_userdata
= userdata
;
1474 int log_syntax_internal(
1477 const char *config_file
,
1478 unsigned config_line
,
1483 const char *format
, ...) {
1487 if (log_syntax_callback
)
1488 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1490 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1491 log_target
== LOG_TARGET_NULL
)
1492 return -ERRNO_VALUE(error
);
1494 char buffer
[LINE_MAX
];
1496 const char *unit_fmt
= NULL
;
1498 errno
= ERRNO_VALUE(error
);
1500 va_start(ap
, format
);
1501 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1505 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1508 if (config_line
> 0)
1509 return log_struct_internal(
1513 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1514 "CONFIG_FILE=%s", config_file
,
1515 "CONFIG_LINE=%u", config_line
,
1516 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1520 return log_struct_internal(
1524 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1525 "CONFIG_FILE=%s", config_file
,
1526 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1530 return log_struct_internal(
1534 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1535 LOG_MESSAGE("%s: %s", unit
, buffer
),
1539 return log_struct_internal(
1543 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1544 LOG_MESSAGE("%s", buffer
),
1548 int log_syntax_invalid_utf8_internal(
1551 const char *config_file
,
1552 unsigned config_line
,
1556 const char *rvalue
) {
1558 _cleanup_free_
char *p
= NULL
;
1561 p
= utf8_escape_invalid(rvalue
);
1563 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1564 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1565 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1568 void log_set_upgrade_syslog_to_journal(bool b
) {
1569 upgrade_syslog_to_journal
= b
;
1571 /* Make the change effective immediately */
1573 if (log_target
== LOG_TARGET_SYSLOG
)
1574 log_target
= LOG_TARGET_JOURNAL
;
1575 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1576 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1580 void log_set_always_reopen_console(bool b
) {
1581 always_reopen_console
= b
;
1584 void log_set_open_when_needed(bool b
) {
1585 open_when_needed
= b
;
1588 void log_set_prohibit_ipc(bool b
) {
1592 int log_emergency_level(void) {
1593 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1594 * then the system of the whole system is obviously affected. */
1596 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1599 int log_dup_console(void) {
1602 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1603 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1605 if (console_fd
< 0 || console_fd
>= 3)
1608 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1616 void log_setup(void) {
1617 log_set_target(LOG_TARGET_AUTO
);
1618 log_parse_environment();
1620 if (log_on_console() && show_color
< 0)
1621 log_show_color(true);
1624 const char *_log_set_prefix(const char *prefix
, bool force
) {
1625 const char *old
= log_prefix
;
1627 if (prefix
|| force
)
1628 log_prefix
= prefix
;
1633 static int saved_log_context_enabled
= -1;
1635 bool log_context_enabled(void) {
1638 if (log_get_max_level() == LOG_DEBUG
)
1641 if (saved_log_context_enabled
>= 0)
1642 return saved_log_context_enabled
;
1644 r
= getenv_bool_secure("SYSTEMD_ENABLE_LOG_CONTEXT");
1645 if (r
< 0 && r
!= -ENXIO
)
1646 log_debug_errno(r
, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1648 saved_log_context_enabled
= r
> 0;
1650 return saved_log_context_enabled
;
1653 static LogContext
* log_context_attach(LogContext
*c
) {
1656 _log_context_num_fields
+= strv_length(c
->fields
);
1657 _log_context_num_fields
+= c
->n_input_iovec
;
1658 _log_context_num_fields
+= !!c
->key
;
1660 return LIST_PREPEND(ll
, _log_context
, c
);
1663 static LogContext
* log_context_detach(LogContext
*c
) {
1667 assert(_log_context_num_fields
>= strv_length(c
->fields
) + c
->n_input_iovec
+!!c
->key
);
1668 _log_context_num_fields
-= strv_length(c
->fields
);
1669 _log_context_num_fields
-= c
->n_input_iovec
;
1670 _log_context_num_fields
-= !!c
->key
;
1672 LIST_REMOVE(ll
, _log_context
, c
);
1676 LogContext
* log_context_new(const char *key
, const char *value
) {
1678 assert(endswith(key
, "="));
1681 LIST_FOREACH(ll
, i
, _log_context
)
1682 if (i
->key
== key
&& i
->value
== value
)
1683 return log_context_ref(i
);
1685 LogContext
*c
= new(LogContext
, 1);
1691 .key
= (char *) key
,
1692 .value
= (char *) value
,
1695 return log_context_attach(c
);
1698 LogContext
* log_context_new_strv(char **fields
, bool owned
) {
1702 LIST_FOREACH(ll
, i
, _log_context
)
1703 if (i
->fields
== fields
) {
1705 return log_context_ref(i
);
1708 LogContext
*c
= new(LogContext
, 1);
1718 return log_context_attach(c
);
1721 LogContext
* log_context_new_iov(struct iovec
*input_iovec
, size_t n_input_iovec
, bool owned
) {
1722 if (!input_iovec
|| n_input_iovec
== 0)
1725 LIST_FOREACH(ll
, i
, _log_context
)
1726 if (i
->input_iovec
== input_iovec
&& i
->n_input_iovec
== n_input_iovec
) {
1728 return log_context_ref(i
);
1731 LogContext
*c
= new(LogContext
, 1);
1737 .input_iovec
= input_iovec
,
1738 .n_input_iovec
= n_input_iovec
,
1742 return log_context_attach(c
);
1745 static LogContext
* log_context_free(LogContext
*c
) {
1749 log_context_detach(c
);
1752 strv_free(c
->fields
);
1753 iovec_array_free(c
->input_iovec
, c
->n_input_iovec
);
1761 DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext
, log_context
, log_context_free
);
1763 LogContext
* log_context_new_strv_consume(char **fields
) {
1764 LogContext
*c
= log_context_new_strv(fields
, /*owned=*/ true);
1771 LogContext
* log_context_new_iov_consume(struct iovec
*input_iovec
, size_t n_input_iovec
) {
1772 LogContext
*c
= log_context_new_iov(input_iovec
, n_input_iovec
, /*owned=*/ true);
1774 iovec_array_free(input_iovec
, n_input_iovec
);
1779 size_t log_context_num_contexts(void) {
1782 LIST_FOREACH(ll
, c
, _log_context
)
1788 size_t log_context_num_fields(void) {
1789 return _log_context_num_fields
;