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 console_fd_is_tty
= -1; /* tri-state: -1 means don't know */
57 static int syslog_fd
= -EBADF
;
58 static int kmsg_fd
= -EBADF
;
59 static int journal_fd
= -EBADF
;
61 static bool syslog_is_stream
= false;
63 static int show_color
= -1; /* tristate */
64 static bool show_location
= false;
65 static bool show_time
= false;
66 static bool show_tid
= false;
68 static bool upgrade_syslog_to_journal
= false;
69 static bool always_reopen_console
= false;
70 static bool open_when_needed
= false;
71 static bool prohibit_ipc
= false;
72 static bool assert_return_is_critical
= BUILD_MODE_DEVELOPER
;
74 /* Akin to glibc's __abort_msg; which is private and we hence cannot
76 static char *log_abort_msg
= NULL
;
78 typedef struct LogContext
{
80 /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
81 * referenced by this is freed or not */
83 struct iovec
*input_iovec
;
88 LIST_FIELDS(struct LogContext
, ll
);
91 static thread_local
LIST_HEAD(LogContext
, _log_context
) = NULL
;
92 static thread_local
size_t _log_context_num_fields
= 0;
94 static thread_local
const char *log_prefix
= NULL
;
96 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
97 bool _log_message_dummy
= false; /* Always false */
100 /* An assert to use in logging functions that does not call recursively
101 * into our logging functions (since that might lead to a loop). */
102 #define assert_raw(expr) \
104 if (_unlikely_(!(expr))) { \
105 fputs(#expr "\n", stderr); \
110 static void log_close_console(void) {
111 /* See comment in log_close_journal() */
112 (void) safe_close_above_stdio(TAKE_FD(console_fd
));
113 console_fd_is_tty
= -1;
116 static int log_open_console(void) {
118 if (!always_reopen_console
) {
119 console_fd
= STDERR_FILENO
;
120 console_fd_is_tty
= -1;
124 if (console_fd
< 3) {
127 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
131 console_fd
= fd_move_above_stdio(fd
);
132 console_fd_is_tty
= true;
138 static void log_close_kmsg(void) {
139 /* See comment in log_close_journal() */
140 (void) safe_close(TAKE_FD(kmsg_fd
));
143 static int log_open_kmsg(void) {
148 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
152 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
156 static void log_close_syslog(void) {
157 /* See comment in log_close_journal() */
158 (void) safe_close(TAKE_FD(syslog_fd
));
161 static int create_log_socket(int type
) {
165 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
169 fd
= fd_move_above_stdio(fd
);
170 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
172 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
173 * in the unlikely case of a deadlock. */
174 if (getpid_cached() == 1)
175 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
177 timeval_store(&tv
, 10 * USEC_PER_SEC
);
178 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
183 static int log_open_syslog(void) {
189 syslog_fd
= create_log_socket(SOCK_DGRAM
);
195 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
197 safe_close(syslog_fd
);
199 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
201 syslog_fd
= create_log_socket(SOCK_STREAM
);
207 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
211 syslog_is_stream
= true;
213 syslog_is_stream
= false;
222 static void log_close_journal(void) {
223 /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
224 * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
225 * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
227 (void) safe_close(TAKE_FD(journal_fd
));
230 static int log_open_journal(void) {
236 journal_fd
= create_log_socket(SOCK_DGRAM
);
237 if (journal_fd
< 0) {
242 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
253 static bool stderr_is_journal(void) {
254 _cleanup_free_
char *w
= NULL
;
259 e
= getenv("JOURNAL_STREAM");
263 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
268 if (safe_atou64(w
, &dev
) < 0)
270 if (safe_atou64(e
, &ino
) < 0)
273 if (fstat(STDERR_FILENO
, &st
) < 0)
276 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
282 /* Do not call from library code. */
284 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
285 * so that a call to a logging function immediately following a log_open() call can still easily
286 * reference an error that happened immediately before the log_open() call. */
289 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
290 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
291 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
292 * because there is no reason to close it. */
294 if (log_target
== LOG_TARGET_NULL
) {
301 if (getpid_cached() == 1 ||
302 stderr_is_journal() ||
306 LOG_TARGET_JOURNAL_OR_KMSG
,
308 LOG_TARGET_SYSLOG_OR_KMSG
)) {
311 if (IN_SET(log_target
,
313 LOG_TARGET_JOURNAL_OR_KMSG
,
314 LOG_TARGET_JOURNAL
)) {
316 r
= log_open_journal();
324 if (IN_SET(log_target
,
325 LOG_TARGET_SYSLOG_OR_KMSG
,
326 LOG_TARGET_SYSLOG
)) {
328 r
= log_open_syslog();
337 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
338 LOG_TARGET_JOURNAL_OR_KMSG
,
339 LOG_TARGET_SYSLOG_OR_KMSG
,
354 return log_open_console();
357 void log_set_target(LogTarget target
) {
359 assert(target
< _LOG_TARGET_MAX
);
361 if (upgrade_syslog_to_journal
) {
362 if (target
== LOG_TARGET_SYSLOG
)
363 target
= LOG_TARGET_JOURNAL
;
364 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
365 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
371 void log_set_target_and_open(LogTarget target
) {
372 log_set_target(target
);
376 void log_close(void) {
377 /* Do not call from library code. */
385 void log_forget_fds(void) {
386 /* Do not call from library code. */
388 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
389 console_fd_is_tty
= -1;
392 void log_set_max_level(int level
) {
393 assert(level
== LOG_NULL
|| (level
& LOG_PRIMASK
) == level
);
395 log_max_level
= level
;
397 /* Also propagate max log level to libc's syslog(), just in case some other component loaded into our
398 * process logs directly via syslog(). You might wonder why we maintain our own log level variable if
399 * libc has the same functionality. This has multiple reasons, first and foremost that we want to
400 * apply this to all our log targets, not just syslog and console. Moreover, we cannot query the
401 * current log mask from glibc without changing it, but that's useful for testing the current log
402 * level before even entering the log functions like we do in our macros. */
403 setlogmask(LOG_UPTO(level
));
405 /* Ensure that our own LOG_NULL define maps sanely to the log mask */
406 assert_cc(LOG_UPTO(LOG_NULL
) == 0);
409 void log_set_facility(int facility
) {
410 log_facility
= facility
;
413 static bool check_console_fd_is_tty(void) {
417 if (console_fd_is_tty
< 0)
418 console_fd_is_tty
= isatty_safe(console_fd
);
420 return console_fd_is_tty
;
423 static int write_to_console(
429 const char *buffer
) {
432 header_time
[FORMAT_TIMESTAMP_MAX
],
433 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
434 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
435 struct iovec iovec
[11];
436 const char *on
= NULL
, *off
= NULL
;
442 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
443 xsprintf(prefix
, "<%i>", level
);
444 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
448 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
449 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
450 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
454 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
455 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
458 if (log_get_show_color())
459 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
462 const char *lon
= "", *loff
= "";
463 if (log_get_show_color()) {
464 lon
= ansi_highlight_yellow4();
465 loff
= ansi_normal();
468 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
469 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
473 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
475 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
476 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
478 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
480 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
482 /* When writing to a TTY we output an extra '\r' (i.e. CR) first, to generate CRNL rather than just
483 * NL. This is a robustness thing in case the TTY is currently in raw mode (specifically: has the
484 * ONLCR flag off). We want that subsequent output definitely starts at the beginning of the line
485 * again, after all. If the TTY is not in raw mode the extra CR should not hurt. */
486 iovec
[n
++] = IOVEC_MAKE_STRING(check_console_fd_is_tty() ? "\r\n" : "\n");
488 if (writev(console_fd
, iovec
, n
) < 0) {
490 if (errno
== EIO
&& getpid_cached() == 1) {
492 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
496 (void) log_open_console();
500 if (writev(console_fd
, iovec
, n
) < 0)
509 static int write_to_syslog(
515 const char *buffer
) {
517 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
519 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
526 xsprintf(header_priority
, "<%i>", level
);
528 t
= (time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
);
529 if (!localtime_r(&t
, &tm
))
532 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
535 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
537 struct iovec iovec
[] = {
538 IOVEC_MAKE_STRING(header_priority
),
539 IOVEC_MAKE_STRING(header_time
),
540 IOVEC_MAKE_STRING(program_invocation_short_name
),
541 IOVEC_MAKE_STRING(header_pid
),
542 IOVEC_MAKE_STRING(strempty(log_prefix
)),
543 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
544 IOVEC_MAKE_STRING(buffer
),
546 const struct msghdr msghdr
= {
548 .msg_iovlen
= ELEMENTSOF(iovec
),
551 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
552 if (syslog_is_stream
)
553 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
558 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
562 if (!syslog_is_stream
)
565 if (iovec_increment(iovec
, ELEMENTSOF(iovec
), n
))
572 static int write_to_kmsg(
578 const char *buffer
) {
580 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
581 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
582 * where we log excessively, but not in a tight loop.
584 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
587 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
589 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
590 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
595 if (ratelimit_kmsg
&& !ratelimit_below(&ratelimit
)) {
596 if (ratelimit_num_dropped(&ratelimit
) > 1)
599 buffer
= "Too many messages being logged to kmsg, ignoring";
602 xsprintf(header_priority
, "<%i>", level
);
603 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
605 const struct iovec iovec
[] = {
606 IOVEC_MAKE_STRING(header_priority
),
607 IOVEC_MAKE_STRING(program_invocation_short_name
),
608 IOVEC_MAKE_STRING(header_pid
),
609 IOVEC_MAKE_STRING(strempty(log_prefix
)),
610 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
611 IOVEC_MAKE_STRING(buffer
),
612 IOVEC_MAKE_STRING("\n"),
615 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
621 static int log_do_header(
626 const char *file
, int line
, const char *func
,
627 const char *object_field
, const char *object
,
628 const char *extra_field
, const char *extra
) {
631 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
633 r
= snprintf(header
, size
,
635 "SYSLOG_FACILITY=%i\n"
637 "%s%.256s%s" /* CODE_FILE */
638 "%s%.*i%s" /* CODE_LINE */
639 "%s%.256s%s" /* CODE_FUNC */
640 "%s%.*i%s" /* ERRNO */
641 "%s%.256s%s" /* object */
642 "%s%.256s%s" /* extra */
643 "SYSLOG_IDENTIFIER=%.256s\n",
647 isempty(file
) ? "" : "CODE_FILE=",
648 isempty(file
) ? "" : file
,
649 isempty(file
) ? "" : "\n",
650 line
? "CODE_LINE=" : "",
651 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
653 isempty(func
) ? "" : "CODE_FUNC=",
654 isempty(func
) ? "" : func
,
655 isempty(func
) ? "" : "\n",
656 error
? "ERRNO=" : "",
657 error
? 1 : 0, error
,
659 isempty(object
) ? "" : object_field
,
660 isempty(object
) ? "" : object
,
661 isempty(object
) ? "" : "\n",
662 isempty(extra
) ? "" : extra_field
,
663 isempty(extra
) ? "" : extra
,
664 isempty(extra
) ? "" : "\n",
665 program_invocation_short_name
);
666 assert_raw((size_t) r
< size
);
671 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
675 LIST_FOREACH(ll
, c
, _log_context
) {
676 STRV_FOREACH(s
, c
->fields
) {
677 if (*n
+ 2 >= iovec_len
)
680 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
681 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
684 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
685 if (*n
+ 2 >= iovec_len
)
688 iovec
[(*n
)++] = c
->input_iovec
[i
];
689 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
692 if (c
->key
&& c
->value
) {
693 if (*n
+ 3 >= iovec_len
)
696 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->key
);
697 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->value
);
698 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
703 static int write_to_journal(
709 const char *object_field
,
711 const char *extra_field
,
713 const char *buffer
) {
715 char header
[LINE_MAX
];
716 size_t n
= 0, iovec_len
;
722 iovec_len
= MIN(6 + _log_context_num_fields
* 2, IOVEC_MAX
);
723 iovec
= newa(struct iovec
, iovec_len
);
725 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
727 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
728 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
730 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
731 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
733 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
734 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
736 log_do_context(iovec
, iovec_len
, &n
);
738 const struct msghdr msghdr
= {
743 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
749 int log_dispatch_internal(
755 const char *object_field
,
757 const char *extra_field
,
763 if (log_target
== LOG_TARGET_NULL
)
764 return -ERRNO_VALUE(error
);
766 /* Patch in LOG_DAEMON facility if necessary */
767 if ((level
& LOG_FACMASK
) == 0)
768 level
|= log_facility
;
770 if (open_when_needed
)
777 buffer
+= strspn(buffer
, NEWLINE
);
782 if ((e
= strpbrk(buffer
, NEWLINE
)))
785 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
786 LOG_TARGET_JOURNAL_OR_KMSG
,
787 LOG_TARGET_JOURNAL
)) {
789 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
790 if (k
< 0 && k
!= -EAGAIN
)
794 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
795 LOG_TARGET_SYSLOG
)) {
797 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
798 if (k
< 0 && k
!= -EAGAIN
)
803 IN_SET(log_target
, LOG_TARGET_AUTO
,
804 LOG_TARGET_SYSLOG_OR_KMSG
,
805 LOG_TARGET_JOURNAL_OR_KMSG
,
811 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
814 (void) log_open_console();
819 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
824 if (open_when_needed
)
827 return -ERRNO_VALUE(error
);
830 int log_dump_internal(
840 /* This modifies the buffer... */
842 if (_likely_(LOG_PRI(level
) > log_max_level
))
843 return -ERRNO_VALUE(error
);
845 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
857 if (_likely_(LOG_PRI(level
) > log_max_level
))
858 return -ERRNO_VALUE(error
);
860 /* Make sure that %m maps to the specified error (or "Success"). */
861 char buffer
[LINE_MAX
];
862 LOCAL_ERRNO(ERRNO_VALUE(error
));
864 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
866 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
875 const char *format
, ...) {
880 va_start(ap
, format
);
881 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
887 int log_object_internalv(
893 const char *object_field
,
895 const char *extra_field
,
902 if (_likely_(LOG_PRI(level
) > log_max_level
))
903 return -ERRNO_VALUE(error
);
905 /* Make sure that %m maps to the specified error (or "Success"). */
906 LOCAL_ERRNO(ERRNO_VALUE(error
));
908 LOG_SET_PREFIX(object
);
910 b
= buffer
= newa(char, LINE_MAX
);
911 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
913 return log_dispatch_internal(level
, error
, file
, line
, func
,
914 object_field
, object
, extra_field
, extra
, buffer
);
917 int log_object_internal(
923 const char *object_field
,
925 const char *extra_field
,
927 const char *format
, ...) {
932 va_start(ap
, format
);
933 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
939 static void log_assert(
945 const char *format
) {
947 static char buffer
[LINE_MAX
];
949 if (_likely_(LOG_PRI(level
) > log_max_level
))
952 DISABLE_WARNING_FORMAT_NONLITERAL
;
953 (void) snprintf(buffer
, sizeof buffer
, format
, text
, file
, line
, func
);
956 log_abort_msg
= buffer
;
958 log_dispatch_internal(level
, 0, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
961 _noreturn_
void log_assert_failed(
966 log_assert(LOG_CRIT
, text
, file
, line
, func
,
967 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
971 _noreturn_
void log_assert_failed_unreachable(
975 log_assert(LOG_CRIT
, "Code should not be reached", file
, line
, func
,
976 "%s at %s:%u, function %s(). Aborting. 💥");
980 void log_assert_failed_return(
986 if (assert_return_is_critical
)
987 log_assert_failed(text
, file
, line
, func
);
990 log_assert(LOG_DEBUG
, text
, file
, line
, func
,
991 "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
994 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
995 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
998 int log_format_iovec(
1002 bool newline_separator
,
1007 static const char nl
= '\n';
1009 while (format
&& *n
+ 1 < iovec_len
) {
1014 /* We need to copy the va_list structure,
1015 * since vasprintf() leaves it afterwards at
1016 * an undefined location */
1018 errno
= ERRNO_VALUE(error
);
1021 r
= vasprintf(&m
, format
, aq
);
1026 /* Now, jump enough ahead, so that we point to
1027 * the next format string */
1028 VA_FORMAT_ADVANCE(format
, ap
);
1030 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
1031 if (newline_separator
)
1032 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
1034 format
= va_arg(ap
, char *);
1039 int log_struct_internal(
1045 const char *format
, ...) {
1052 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1053 log_target
== LOG_TARGET_NULL
)
1054 return -ERRNO_VALUE(error
);
1056 if ((level
& LOG_FACMASK
) == 0)
1057 level
|= log_facility
;
1059 if (IN_SET(log_target
,
1061 LOG_TARGET_JOURNAL_OR_KMSG
,
1062 LOG_TARGET_JOURNAL
)) {
1064 if (open_when_needed
)
1067 if (journal_fd
>= 0) {
1068 char header
[LINE_MAX
];
1069 struct iovec
*iovec
;
1070 size_t n
= 0, m
, iovec_len
;
1072 bool fallback
= false;
1074 iovec_len
= MIN(17 + _log_context_num_fields
* 2, IOVEC_MAX
);
1075 iovec
= newa(struct iovec
, iovec_len
);
1077 /* If the journal is available do structured logging.
1078 * Do not report the errno if it is synthetic. */
1079 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1080 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1082 va_start(ap
, format
);
1083 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1088 log_do_context(iovec
, iovec_len
, &n
);
1090 const struct msghdr msghdr
= {
1095 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1099 for (size_t i
= 1; i
< m
; i
+= 2)
1100 free(iovec
[i
].iov_base
);
1103 if (open_when_needed
)
1106 return -ERRNO_VALUE(error
);
1111 /* Fallback if journal logging is not available or didn't work. */
1113 va_start(ap
, format
);
1117 errno
= ERRNO_VALUE(error
);
1120 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1123 if (startswith(buf
, "MESSAGE=")) {
1128 VA_FORMAT_ADVANCE(format
, ap
);
1130 format
= va_arg(ap
, char *);
1135 if (open_when_needed
)
1138 return -ERRNO_VALUE(error
);
1141 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1144 int log_struct_iovec_internal(
1150 const struct iovec input_iovec
[],
1151 size_t n_input_iovec
) {
1155 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1156 log_target
== LOG_TARGET_NULL
)
1157 return -ERRNO_VALUE(error
);
1159 if ((level
& LOG_FACMASK
) == 0)
1160 level
|= log_facility
;
1162 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1163 LOG_TARGET_JOURNAL_OR_KMSG
,
1164 LOG_TARGET_JOURNAL
) &&
1167 char header
[LINE_MAX
];
1168 struct iovec
*iovec
;
1169 size_t n
= 0, iovec_len
;
1171 iovec_len
= MIN(1 + n_input_iovec
* 2 + _log_context_num_fields
* 2, IOVEC_MAX
);
1172 iovec
= newa(struct iovec
, iovec_len
);
1174 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1176 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1177 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1178 iovec
[n
++] = input_iovec
[i
];
1179 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1182 log_do_context(iovec
, iovec_len
, &n
);
1184 const struct msghdr msghdr
= {
1189 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1190 return -ERRNO_VALUE(error
);
1193 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1194 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1197 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1198 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1200 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1203 /* Couldn't find MESSAGE=. */
1204 return -ERRNO_VALUE(error
);
1207 int log_set_target_from_string(const char *e
) {
1210 t
= log_target_from_string(e
);
1218 int log_set_max_level_from_string(const char *e
) {
1221 r
= log_level_from_string(e
);
1225 log_set_max_level(r
);
1229 static int log_set_ratelimit_kmsg_from_string(const char *e
) {
1232 r
= parse_boolean(e
);
1240 void log_set_assert_return_is_critical(bool b
) {
1241 assert_return_is_critical
= b
;
1244 bool log_get_assert_return_is_critical(void) {
1245 return assert_return_is_critical
;
1248 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1251 * The systemd.log_xyz= settings are parsed by all tools, and
1254 * However, "quiet" is only parsed by PID 1, and only turns of
1255 * status output to /dev/console, but does not alter the log
1259 if (streq(key
, "debug") && !value
)
1260 log_set_max_level(LOG_DEBUG
);
1262 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1264 if (proc_cmdline_value_missing(key
, value
))
1267 if (log_set_target_from_string(value
) < 0)
1268 log_warning("Failed to parse log target '%s'. Ignoring.", value
);
1270 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1272 if (proc_cmdline_value_missing(key
, value
))
1275 if (log_set_max_level_from_string(value
) < 0)
1276 log_warning("Failed to parse log level '%s'. Ignoring.", value
);
1278 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1280 if (log_show_color_from_string(value
?: "1") < 0)
1281 log_warning("Failed to parse log color setting '%s'. Ignoring.", value
);
1283 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1285 if (log_show_location_from_string(value
?: "1") < 0)
1286 log_warning("Failed to parse log location setting '%s'. Ignoring.", value
);
1288 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1290 if (log_show_tid_from_string(value
?: "1") < 0)
1291 log_warning("Failed to parse log tid setting '%s'. Ignoring.", value
);
1293 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1295 if (log_show_time_from_string(value
?: "1") < 0)
1296 log_warning("Failed to parse log time setting '%s'. Ignoring.", value
);
1298 } else if (proc_cmdline_key_streq(key
, "systemd.log_ratelimit_kmsg")) {
1300 if (log_set_ratelimit_kmsg_from_string(value
?: "1") < 0)
1301 log_warning("Failed to parse log ratelimit kmsg boolean '%s'. Ignoring.", value
);
1307 static bool should_parse_proc_cmdline(void) {
1308 /* PID1 always reads the kernel command line. */
1309 if (getpid_cached() == 1)
1312 /* Otherwise, parse the command line if invoked directly by systemd. */
1313 return invoked_by_systemd();
1316 void log_parse_environment_variables(void) {
1319 e
= getenv("SYSTEMD_LOG_TARGET");
1320 if (e
&& log_set_target_from_string(e
) < 0)
1321 log_warning("Failed to parse log target '%s'. Ignoring.", e
);
1323 e
= getenv("SYSTEMD_LOG_LEVEL");
1324 if (e
&& log_set_max_level_from_string(e
) < 0)
1325 log_warning("Failed to parse log level '%s'. Ignoring.", e
);
1327 e
= getenv("SYSTEMD_LOG_COLOR");
1328 if (e
&& log_show_color_from_string(e
) < 0)
1329 log_warning("Failed to parse log color '%s'. Ignoring.", e
);
1331 e
= getenv("SYSTEMD_LOG_LOCATION");
1332 if (e
&& log_show_location_from_string(e
) < 0)
1333 log_warning("Failed to parse log location '%s'. Ignoring.", e
);
1335 e
= getenv("SYSTEMD_LOG_TIME");
1336 if (e
&& log_show_time_from_string(e
) < 0)
1337 log_warning("Failed to parse log time '%s'. Ignoring.", e
);
1339 e
= getenv("SYSTEMD_LOG_TID");
1340 if (e
&& log_show_tid_from_string(e
) < 0)
1341 log_warning("Failed to parse log tid '%s'. Ignoring.", e
);
1343 e
= getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
1344 if (e
&& log_set_ratelimit_kmsg_from_string(e
) < 0)
1345 log_warning("Failed to parse log ratelimit kmsg boolean '%s'. Ignoring.", e
);
1348 void log_parse_environment(void) {
1349 /* Do not call from library code. */
1351 if (should_parse_proc_cmdline())
1352 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1354 log_parse_environment_variables();
1357 LogTarget
log_get_target(void) {
1361 void log_settle_target(void) {
1363 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1364 * stderr is attached to the journal every single log call. However, if we then close all file
1365 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1366 * problem, this function is used to permanently change the log target depending on whether stderr is
1367 * connected to the journal or not. */
1369 LogTarget t
= log_get_target();
1371 if (t
!= LOG_TARGET_AUTO
)
1374 t
= getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc
? LOG_TARGET_KMSG
: LOG_TARGET_JOURNAL_OR_KMSG
)
1375 : LOG_TARGET_CONSOLE
;
1379 int log_get_max_level(void) {
1380 return log_max_level
;
1383 void log_show_color(bool b
) {
1387 bool log_get_show_color(void) {
1388 return show_color
> 0; /* Defaults to false. */
1391 void log_show_location(bool b
) {
1395 bool log_get_show_location(void) {
1396 return show_location
;
1399 void log_show_time(bool b
) {
1403 bool log_get_show_time(void) {
1407 void log_show_tid(bool b
) {
1411 bool log_get_show_tid(void) {
1415 int log_show_color_from_string(const char *e
) {
1418 r
= parse_boolean(e
);
1426 int log_show_location_from_string(const char *e
) {
1429 r
= parse_boolean(e
);
1433 log_show_location(r
);
1437 int log_show_time_from_string(const char *e
) {
1440 r
= parse_boolean(e
);
1448 int log_show_tid_from_string(const char *e
) {
1451 r
= parse_boolean(e
);
1459 bool log_on_console(void) {
1460 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1461 LOG_TARGET_CONSOLE_PREFIXED
))
1464 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1467 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1468 [LOG_TARGET_CONSOLE
] = "console",
1469 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1470 [LOG_TARGET_KMSG
] = "kmsg",
1471 [LOG_TARGET_JOURNAL
] = "journal",
1472 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1473 [LOG_TARGET_SYSLOG
] = "syslog",
1474 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1475 [LOG_TARGET_AUTO
] = "auto",
1476 [LOG_TARGET_NULL
] = "null",
1479 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1481 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1484 if (pid_is_valid(si
->ssi_pid
)) {
1485 _cleanup_free_
char *p
= NULL
;
1487 (void) pid_get_comm(si
->ssi_pid
, &p
);
1490 "Received SIG%s from PID %"PRIu32
" (%s).",
1491 signal_to_string(si
->ssi_signo
),
1492 si
->ssi_pid
, strna(p
));
1496 signal_to_string(si
->ssi_signo
));
1499 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1500 assert(!log_syntax_callback
|| !cb
);
1501 assert(!log_syntax_callback_userdata
|| !userdata
);
1503 log_syntax_callback
= cb
;
1504 log_syntax_callback_userdata
= userdata
;
1507 int log_syntax_internal(
1510 const char *config_file
,
1511 unsigned config_line
,
1516 const char *format
, ...) {
1520 if (log_syntax_callback
)
1521 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1523 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1524 log_target
== LOG_TARGET_NULL
)
1525 return -ERRNO_VALUE(error
);
1527 char buffer
[LINE_MAX
];
1529 const char *unit_fmt
= NULL
;
1531 errno
= ERRNO_VALUE(error
);
1533 va_start(ap
, format
);
1534 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1538 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1541 if (config_line
> 0)
1542 return log_struct_internal(
1546 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1547 "CONFIG_FILE=%s", config_file
,
1548 "CONFIG_LINE=%u", config_line
,
1549 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1553 return log_struct_internal(
1557 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1558 "CONFIG_FILE=%s", config_file
,
1559 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1563 return log_struct_internal(
1567 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1568 LOG_MESSAGE("%s: %s", unit
, buffer
),
1572 return log_struct_internal(
1576 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1577 LOG_MESSAGE("%s", buffer
),
1581 int log_syntax_invalid_utf8_internal(
1584 const char *config_file
,
1585 unsigned config_line
,
1589 const char *rvalue
) {
1591 _cleanup_free_
char *p
= NULL
;
1594 p
= utf8_escape_invalid(rvalue
);
1596 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1597 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1598 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1601 void log_set_upgrade_syslog_to_journal(bool b
) {
1602 upgrade_syslog_to_journal
= b
;
1604 /* Make the change effective immediately */
1606 if (log_target
== LOG_TARGET_SYSLOG
)
1607 log_target
= LOG_TARGET_JOURNAL
;
1608 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1609 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1613 void log_set_always_reopen_console(bool b
) {
1614 always_reopen_console
= b
;
1617 void log_set_open_when_needed(bool b
) {
1618 open_when_needed
= b
;
1621 void log_set_prohibit_ipc(bool b
) {
1625 int log_emergency_level(void) {
1626 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1627 * then the system of the whole system is obviously affected. */
1629 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1632 int log_dup_console(void) {
1635 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1636 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1638 if (console_fd
< 0 || console_fd
>= 3)
1641 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1649 void log_setup(void) {
1650 log_set_target(LOG_TARGET_AUTO
);
1651 log_parse_environment();
1653 if (log_on_console() && show_color
< 0)
1654 log_show_color(true);
1657 const char *_log_set_prefix(const char *prefix
, bool force
) {
1658 const char *old
= log_prefix
;
1660 if (prefix
|| force
)
1661 log_prefix
= prefix
;
1666 static int saved_log_context_enabled
= -1;
1668 bool log_context_enabled(void) {
1671 if (log_get_max_level() == LOG_DEBUG
)
1674 if (saved_log_context_enabled
>= 0)
1675 return saved_log_context_enabled
;
1677 r
= secure_getenv_bool("SYSTEMD_ENABLE_LOG_CONTEXT");
1678 if (r
< 0 && r
!= -ENXIO
)
1679 log_debug_errno(r
, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1681 saved_log_context_enabled
= r
> 0;
1683 return saved_log_context_enabled
;
1686 static LogContext
* log_context_attach(LogContext
*c
) {
1689 _log_context_num_fields
+= strv_length(c
->fields
);
1690 _log_context_num_fields
+= c
->n_input_iovec
;
1691 _log_context_num_fields
+= !!c
->key
;
1693 return LIST_PREPEND(ll
, _log_context
, c
);
1696 static LogContext
* log_context_detach(LogContext
*c
) {
1700 assert(_log_context_num_fields
>= strv_length(c
->fields
) + c
->n_input_iovec
+!!c
->key
);
1701 _log_context_num_fields
-= strv_length(c
->fields
);
1702 _log_context_num_fields
-= c
->n_input_iovec
;
1703 _log_context_num_fields
-= !!c
->key
;
1705 LIST_REMOVE(ll
, _log_context
, c
);
1709 LogContext
* log_context_new(const char *key
, const char *value
) {
1711 assert(endswith(key
, "="));
1714 LIST_FOREACH(ll
, i
, _log_context
)
1715 if (i
->key
== key
&& i
->value
== value
)
1716 return log_context_ref(i
);
1718 LogContext
*c
= new(LogContext
, 1);
1724 .key
= (char *) key
,
1725 .value
= (char *) value
,
1728 return log_context_attach(c
);
1731 LogContext
* log_context_new_strv(char **fields
, bool owned
) {
1735 LIST_FOREACH(ll
, i
, _log_context
)
1736 if (i
->fields
== fields
) {
1738 return log_context_ref(i
);
1741 LogContext
*c
= new(LogContext
, 1);
1751 return log_context_attach(c
);
1754 LogContext
* log_context_new_iov(struct iovec
*input_iovec
, size_t n_input_iovec
, bool owned
) {
1755 if (!input_iovec
|| n_input_iovec
== 0)
1758 LIST_FOREACH(ll
, i
, _log_context
)
1759 if (i
->input_iovec
== input_iovec
&& i
->n_input_iovec
== n_input_iovec
) {
1761 return log_context_ref(i
);
1764 LogContext
*c
= new(LogContext
, 1);
1770 .input_iovec
= input_iovec
,
1771 .n_input_iovec
= n_input_iovec
,
1775 return log_context_attach(c
);
1778 static LogContext
* log_context_free(LogContext
*c
) {
1782 log_context_detach(c
);
1785 strv_free(c
->fields
);
1786 iovec_array_free(c
->input_iovec
, c
->n_input_iovec
);
1794 DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext
, log_context
, log_context_free
);
1796 LogContext
* log_context_new_strv_consume(char **fields
) {
1797 LogContext
*c
= log_context_new_strv(fields
, /*owned=*/ true);
1804 LogContext
* log_context_new_iov_consume(struct iovec
*input_iovec
, size_t n_input_iovec
) {
1805 LogContext
*c
= log_context_new_iov(input_iovec
, n_input_iovec
, /*owned=*/ true);
1807 iovec_array_free(input_iovec
, n_input_iovec
);
1812 size_t log_context_num_contexts(void) {
1815 LIST_FOREACH(ll
, c
, _log_context
)
1821 size_t log_context_num_fields(void) {
1822 return _log_context_num_fields
;