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_target_max_level
[] = {
53 [LOG_TARGET_CONSOLE
] = INT_MAX
,
54 [LOG_TARGET_KMSG
] = INT_MAX
,
55 [LOG_TARGET_SYSLOG
] = INT_MAX
,
56 [LOG_TARGET_JOURNAL
] = INT_MAX
,
58 static int log_facility
= LOG_DAEMON
;
59 static bool ratelimit_kmsg
= true;
61 static int console_fd
= STDERR_FILENO
;
62 static int console_fd_is_tty
= -1; /* tri-state: -1 means don't know */
63 static int syslog_fd
= -EBADF
;
64 static int kmsg_fd
= -EBADF
;
65 static int journal_fd
= -EBADF
;
67 static bool syslog_is_stream
= false;
69 static int show_color
= -1; /* tristate */
70 static bool show_location
= false;
71 static bool show_time
= false;
72 static bool show_tid
= false;
74 static bool upgrade_syslog_to_journal
= false;
75 static bool always_reopen_console
= false;
76 static bool open_when_needed
= false;
77 static bool prohibit_ipc
= false;
78 static bool assert_return_is_critical
= BUILD_MODE_DEVELOPER
;
80 /* Akin to glibc's __abort_msg; which is private and we hence cannot
82 static char *log_abort_msg
= NULL
;
84 typedef struct LogContext
{
86 /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
87 * referenced by this is freed or not */
89 struct iovec
*input_iovec
;
94 LIST_FIELDS(struct LogContext
, ll
);
97 static thread_local
LIST_HEAD(LogContext
, _log_context
) = NULL
;
98 static thread_local
size_t _log_context_num_fields
= 0;
100 static thread_local
const char *log_prefix
= NULL
;
102 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
103 bool _log_message_dummy
= false; /* Always false */
106 /* An assert to use in logging functions that does not call recursively
107 * into our logging functions (since that might lead to a loop). */
108 #define assert_raw(expr) \
110 if (_unlikely_(!(expr))) { \
111 fputs(#expr "\n", stderr); \
116 static void log_close_console(void) {
117 /* See comment in log_close_journal() */
118 (void) safe_close_above_stdio(TAKE_FD(console_fd
));
119 console_fd_is_tty
= -1;
122 static int log_open_console(void) {
124 if (!always_reopen_console
) {
125 console_fd
= STDERR_FILENO
;
126 console_fd_is_tty
= -1;
130 if (console_fd
< 3) {
133 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
137 console_fd
= fd_move_above_stdio(fd
);
138 console_fd_is_tty
= true;
144 static void log_close_kmsg(void) {
145 /* See comment in log_close_journal() */
146 (void) safe_close(TAKE_FD(kmsg_fd
));
149 static int log_open_kmsg(void) {
154 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
158 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
162 static void log_close_syslog(void) {
163 /* See comment in log_close_journal() */
164 (void) safe_close(TAKE_FD(syslog_fd
));
167 static int create_log_socket(int type
) {
171 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
175 fd
= fd_move_above_stdio(fd
);
176 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
178 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
179 * in the unlikely case of a deadlock. */
180 if (getpid_cached() == 1)
181 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
183 timeval_store(&tv
, 10 * USEC_PER_SEC
);
184 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
189 static int log_open_syslog(void) {
195 syslog_fd
= create_log_socket(SOCK_DGRAM
);
201 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
203 safe_close(syslog_fd
);
205 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
207 syslog_fd
= create_log_socket(SOCK_STREAM
);
213 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
217 syslog_is_stream
= true;
219 syslog_is_stream
= false;
228 static void log_close_journal(void) {
229 /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
230 * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
231 * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
233 (void) safe_close(TAKE_FD(journal_fd
));
236 static int log_open_journal(void) {
242 journal_fd
= create_log_socket(SOCK_DGRAM
);
243 if (journal_fd
< 0) {
248 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
259 static bool stderr_is_journal(void) {
260 _cleanup_free_
char *w
= NULL
;
265 e
= getenv("JOURNAL_STREAM");
269 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
274 if (safe_atou64(w
, &dev
) < 0)
276 if (safe_atou64(e
, &ino
) < 0)
279 if (fstat(STDERR_FILENO
, &st
) < 0)
282 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
288 /* Do not call from library code. */
290 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
291 * so that a call to a logging function immediately following a log_open() call can still easily
292 * reference an error that happened immediately before the log_open() call. */
295 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
296 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
297 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
298 * because there is no reason to close it. */
300 if (log_target
== LOG_TARGET_NULL
) {
307 if (getpid_cached() == 1 ||
308 stderr_is_journal() ||
312 LOG_TARGET_JOURNAL_OR_KMSG
,
314 LOG_TARGET_SYSLOG_OR_KMSG
)) {
317 if (IN_SET(log_target
,
319 LOG_TARGET_JOURNAL_OR_KMSG
,
320 LOG_TARGET_JOURNAL
)) {
322 r
= log_open_journal();
330 if (IN_SET(log_target
,
331 LOG_TARGET_SYSLOG_OR_KMSG
,
332 LOG_TARGET_SYSLOG
)) {
334 r
= log_open_syslog();
343 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
344 LOG_TARGET_JOURNAL_OR_KMSG
,
345 LOG_TARGET_SYSLOG_OR_KMSG
,
360 return log_open_console();
363 void log_set_target(LogTarget target
) {
365 assert(target
< _LOG_TARGET_MAX
);
367 if (upgrade_syslog_to_journal
) {
368 if (target
== LOG_TARGET_SYSLOG
)
369 target
= LOG_TARGET_JOURNAL
;
370 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
371 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
377 void log_set_target_and_open(LogTarget target
) {
378 log_set_target(target
);
382 void log_close(void) {
383 /* Do not call from library code. */
391 void log_forget_fds(void) {
392 /* Do not call from library code. */
394 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
395 console_fd_is_tty
= -1;
398 void log_set_max_level(int level
) {
399 assert(level
== LOG_NULL
|| (level
& LOG_PRIMASK
) == level
);
401 log_max_level
= level
;
403 /* Also propagate max log level to libc's syslog(), just in case some other component loaded into our
404 * process logs directly via syslog(). You might wonder why we maintain our own log level variable if
405 * libc has the same functionality. This has multiple reasons, first and foremost that we want to
406 * apply this to all our log targets, not just syslog and console. Moreover, we cannot query the
407 * current log mask from glibc without changing it, but that's useful for testing the current log
408 * level before even entering the log functions like we do in our macros. */
409 setlogmask(LOG_UPTO(level
));
411 /* Ensure that our own LOG_NULL define maps sanely to the log mask */
412 assert_cc(LOG_UPTO(LOG_NULL
) == 0);
415 void log_set_facility(int facility
) {
416 log_facility
= facility
;
419 static bool check_console_fd_is_tty(void) {
423 if (console_fd_is_tty
< 0)
424 console_fd_is_tty
= isatty_safe(console_fd
);
426 return console_fd_is_tty
;
429 static int write_to_console(
435 const char *buffer
) {
438 header_time
[FORMAT_TIMESTAMP_MAX
],
439 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
440 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
441 struct iovec iovec
[11];
442 const char *on
= NULL
, *off
= NULL
;
448 if (LOG_PRI(level
) > log_target_max_level
[LOG_TARGET_CONSOLE
])
451 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
452 xsprintf(prefix
, "<%i>", level
);
453 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
457 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
458 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
459 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
463 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
464 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
467 if (log_get_show_color())
468 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
471 const char *lon
= "", *loff
= "";
472 if (log_get_show_color()) {
473 lon
= ansi_highlight_yellow4();
474 loff
= ansi_normal();
477 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
478 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
482 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
484 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
485 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
487 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
489 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
491 /* When writing to a TTY we output an extra '\r' (i.e. CR) first, to generate CRNL rather than just
492 * NL. This is a robustness thing in case the TTY is currently in raw mode (specifically: has the
493 * ONLCR flag off). We want that subsequent output definitely starts at the beginning of the line
494 * again, after all. If the TTY is not in raw mode the extra CR should not hurt. */
495 iovec
[n
++] = IOVEC_MAKE_STRING(check_console_fd_is_tty() ? "\r\n" : "\n");
497 if (writev(console_fd
, iovec
, n
) < 0) {
499 if (errno
== EIO
&& getpid_cached() == 1) {
501 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
505 (void) log_open_console();
509 if (writev(console_fd
, iovec
, n
) < 0)
518 static int write_to_syslog(
524 const char *buffer
) {
526 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
528 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
535 if (LOG_PRI(level
) > log_target_max_level
[LOG_TARGET_SYSLOG
])
538 xsprintf(header_priority
, "<%i>", level
);
540 t
= (time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
);
541 if (!localtime_r(&t
, &tm
))
544 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
547 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
549 struct iovec iovec
[] = {
550 IOVEC_MAKE_STRING(header_priority
),
551 IOVEC_MAKE_STRING(header_time
),
552 IOVEC_MAKE_STRING(program_invocation_short_name
),
553 IOVEC_MAKE_STRING(header_pid
),
554 IOVEC_MAKE_STRING(strempty(log_prefix
)),
555 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
556 IOVEC_MAKE_STRING(buffer
),
558 const struct msghdr msghdr
= {
560 .msg_iovlen
= ELEMENTSOF(iovec
),
563 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
564 if (syslog_is_stream
)
565 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
570 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
574 if (!syslog_is_stream
)
577 if (iovec_increment(iovec
, ELEMENTSOF(iovec
), n
))
584 static int write_to_kmsg(
590 const char *buffer
) {
592 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
593 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
594 * where we log excessively, but not in a tight loop.
596 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
599 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
601 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
602 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
607 if (LOG_PRI(level
) > log_target_max_level
[LOG_TARGET_KMSG
])
610 if (ratelimit_kmsg
&& !ratelimit_below(&ratelimit
)) {
611 if (ratelimit_num_dropped(&ratelimit
) > 1)
614 buffer
= "Too many messages being logged to kmsg, ignoring";
617 xsprintf(header_priority
, "<%i>", level
);
618 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
620 const struct iovec iovec
[] = {
621 IOVEC_MAKE_STRING(header_priority
),
622 IOVEC_MAKE_STRING(program_invocation_short_name
),
623 IOVEC_MAKE_STRING(header_pid
),
624 IOVEC_MAKE_STRING(strempty(log_prefix
)),
625 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
626 IOVEC_MAKE_STRING(buffer
),
627 IOVEC_MAKE_STRING("\n"),
630 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
636 static int log_do_header(
641 const char *file
, int line
, const char *func
,
642 const char *object_field
, const char *object
,
643 const char *extra_field
, const char *extra
) {
646 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
648 r
= snprintf(header
, size
,
650 "SYSLOG_FACILITY=%i\n"
652 "%s%.256s%s" /* CODE_FILE */
653 "%s%.*i%s" /* CODE_LINE */
654 "%s%.256s%s" /* CODE_FUNC */
655 "%s%.*i%s" /* ERRNO */
656 "%s%.256s%s" /* object */
657 "%s%.256s%s" /* extra */
658 "SYSLOG_IDENTIFIER=%.256s\n",
662 isempty(file
) ? "" : "CODE_FILE=",
663 isempty(file
) ? "" : file
,
664 isempty(file
) ? "" : "\n",
665 line
? "CODE_LINE=" : "",
666 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
668 isempty(func
) ? "" : "CODE_FUNC=",
669 isempty(func
) ? "" : func
,
670 isempty(func
) ? "" : "\n",
671 error
? "ERRNO=" : "",
672 error
? 1 : 0, error
,
674 isempty(object
) ? "" : object_field
,
675 isempty(object
) ? "" : object
,
676 isempty(object
) ? "" : "\n",
677 isempty(extra
) ? "" : extra_field
,
678 isempty(extra
) ? "" : extra
,
679 isempty(extra
) ? "" : "\n",
680 program_invocation_short_name
);
681 assert_raw((size_t) r
< size
);
686 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
690 LIST_FOREACH(ll
, c
, _log_context
) {
691 STRV_FOREACH(s
, c
->fields
) {
692 if (*n
+ 2 >= iovec_len
)
695 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
696 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
699 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
700 if (*n
+ 2 >= iovec_len
)
703 iovec
[(*n
)++] = c
->input_iovec
[i
];
704 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
707 if (c
->key
&& c
->value
) {
708 if (*n
+ 3 >= iovec_len
)
711 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->key
);
712 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->value
);
713 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
718 static int write_to_journal(
724 const char *object_field
,
726 const char *extra_field
,
728 const char *buffer
) {
730 char header
[LINE_MAX
];
731 size_t n
= 0, iovec_len
;
737 if (LOG_PRI(level
) > log_target_max_level
[LOG_TARGET_JOURNAL
])
740 iovec_len
= MIN(6 + _log_context_num_fields
* 2, IOVEC_MAX
);
741 iovec
= newa(struct iovec
, iovec_len
);
743 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
745 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
746 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
748 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
749 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
751 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
752 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
754 log_do_context(iovec
, iovec_len
, &n
);
756 const struct msghdr msghdr
= {
761 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
767 int log_dispatch_internal(
773 const char *object_field
,
775 const char *extra_field
,
781 if (log_target
== LOG_TARGET_NULL
)
782 return -ERRNO_VALUE(error
);
784 /* Patch in LOG_DAEMON facility if necessary */
785 if ((level
& LOG_FACMASK
) == 0)
786 level
|= log_facility
;
788 if (open_when_needed
)
795 buffer
+= strspn(buffer
, NEWLINE
);
800 if ((e
= strpbrk(buffer
, NEWLINE
)))
803 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
804 LOG_TARGET_JOURNAL_OR_KMSG
,
805 LOG_TARGET_JOURNAL
)) {
807 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
808 if (k
< 0 && k
!= -EAGAIN
)
812 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
813 LOG_TARGET_SYSLOG
)) {
815 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
816 if (k
< 0 && k
!= -EAGAIN
)
821 IN_SET(log_target
, LOG_TARGET_AUTO
,
822 LOG_TARGET_SYSLOG_OR_KMSG
,
823 LOG_TARGET_JOURNAL_OR_KMSG
,
829 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
832 (void) log_open_console();
837 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
842 if (open_when_needed
)
845 return -ERRNO_VALUE(error
);
848 int log_dump_internal(
858 /* This modifies the buffer... */
860 if (_likely_(LOG_PRI(level
) > log_max_level
))
861 return -ERRNO_VALUE(error
);
863 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
875 if (_likely_(LOG_PRI(level
) > log_max_level
))
876 return -ERRNO_VALUE(error
);
878 /* Make sure that %m maps to the specified error (or "Success"). */
879 char buffer
[LINE_MAX
];
880 LOCAL_ERRNO(ERRNO_VALUE(error
));
882 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
884 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
893 const char *format
, ...) {
898 va_start(ap
, format
);
899 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
905 int log_object_internalv(
911 const char *object_field
,
913 const char *extra_field
,
920 if (_likely_(LOG_PRI(level
) > log_max_level
))
921 return -ERRNO_VALUE(error
);
923 /* Make sure that %m maps to the specified error (or "Success"). */
924 LOCAL_ERRNO(ERRNO_VALUE(error
));
926 LOG_SET_PREFIX(object
);
928 b
= buffer
= newa(char, LINE_MAX
);
929 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
931 return log_dispatch_internal(level
, error
, file
, line
, func
,
932 object_field
, object
, extra_field
, extra
, buffer
);
935 int log_object_internal(
941 const char *object_field
,
943 const char *extra_field
,
945 const char *format
, ...) {
950 va_start(ap
, format
);
951 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
957 static void log_assert(
963 const char *format
) {
965 static char buffer
[LINE_MAX
];
967 if (_likely_(LOG_PRI(level
) > log_max_level
))
970 DISABLE_WARNING_FORMAT_NONLITERAL
;
971 (void) snprintf(buffer
, sizeof buffer
, format
, text
, file
, line
, func
);
974 log_abort_msg
= buffer
;
976 log_dispatch_internal(level
, 0, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
979 _noreturn_
void log_assert_failed(
984 log_assert(LOG_CRIT
, text
, file
, line
, func
,
985 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
989 _noreturn_
void log_assert_failed_unreachable(
993 log_assert(LOG_CRIT
, "Code should not be reached", file
, line
, func
,
994 "%s at %s:%u, function %s(). Aborting. 💥");
998 void log_assert_failed_return(
1004 if (assert_return_is_critical
)
1005 log_assert_failed(text
, file
, line
, func
);
1008 log_assert(LOG_DEBUG
, text
, file
, line
, func
,
1009 "Assertion '%s' failed at %s:%u, function %s(), ignoring.");
1012 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
1013 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
1016 int log_format_iovec(
1017 struct iovec
*iovec
,
1020 bool newline_separator
,
1025 static const char nl
= '\n';
1027 while (format
&& *n
+ 1 < iovec_len
) {
1032 /* We need to copy the va_list structure,
1033 * since vasprintf() leaves it afterwards at
1034 * an undefined location */
1036 errno
= ERRNO_VALUE(error
);
1039 r
= vasprintf(&m
, format
, aq
);
1044 /* Now, jump enough ahead, so that we point to
1045 * the next format string */
1046 VA_FORMAT_ADVANCE(format
, ap
);
1048 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
1049 if (newline_separator
)
1050 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
1052 format
= va_arg(ap
, char *);
1057 int log_struct_internal(
1063 const char *format
, ...) {
1070 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1071 log_target
== LOG_TARGET_NULL
)
1072 return -ERRNO_VALUE(error
);
1074 if ((level
& LOG_FACMASK
) == 0)
1075 level
|= log_facility
;
1077 if (IN_SET(log_target
,
1079 LOG_TARGET_JOURNAL_OR_KMSG
,
1080 LOG_TARGET_JOURNAL
)) {
1082 if (open_when_needed
)
1085 if (journal_fd
>= 0) {
1086 char header
[LINE_MAX
];
1087 struct iovec
*iovec
;
1088 size_t n
= 0, m
, iovec_len
;
1090 bool fallback
= false;
1092 iovec_len
= MIN(17 + _log_context_num_fields
* 2, IOVEC_MAX
);
1093 iovec
= newa(struct iovec
, iovec_len
);
1095 /* If the journal is available do structured logging.
1096 * Do not report the errno if it is synthetic. */
1097 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1098 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1100 va_start(ap
, format
);
1101 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1106 log_do_context(iovec
, iovec_len
, &n
);
1108 const struct msghdr msghdr
= {
1113 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1117 for (size_t i
= 1; i
< m
; i
+= 2)
1118 free(iovec
[i
].iov_base
);
1121 if (open_when_needed
)
1124 return -ERRNO_VALUE(error
);
1129 /* Fallback if journal logging is not available or didn't work. */
1131 va_start(ap
, format
);
1135 errno
= ERRNO_VALUE(error
);
1138 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1141 if (startswith(buf
, "MESSAGE=")) {
1146 VA_FORMAT_ADVANCE(format
, ap
);
1148 format
= va_arg(ap
, char *);
1153 if (open_when_needed
)
1156 return -ERRNO_VALUE(error
);
1159 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1162 int log_struct_iovec_internal(
1168 const struct iovec input_iovec
[],
1169 size_t n_input_iovec
) {
1173 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1174 log_target
== LOG_TARGET_NULL
)
1175 return -ERRNO_VALUE(error
);
1177 if ((level
& LOG_FACMASK
) == 0)
1178 level
|= log_facility
;
1180 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1181 LOG_TARGET_JOURNAL_OR_KMSG
,
1182 LOG_TARGET_JOURNAL
) &&
1185 char header
[LINE_MAX
];
1186 struct iovec
*iovec
;
1187 size_t n
= 0, iovec_len
;
1189 iovec_len
= MIN(1 + n_input_iovec
* 2 + _log_context_num_fields
* 2, IOVEC_MAX
);
1190 iovec
= newa(struct iovec
, iovec_len
);
1192 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1194 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1195 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1196 iovec
[n
++] = input_iovec
[i
];
1197 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1200 log_do_context(iovec
, iovec_len
, &n
);
1202 const struct msghdr msghdr
= {
1207 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1208 return -ERRNO_VALUE(error
);
1211 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1212 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1215 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1216 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1218 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1221 /* Couldn't find MESSAGE=. */
1222 return -ERRNO_VALUE(error
);
1225 int log_set_target_from_string(const char *e
) {
1228 t
= log_target_from_string(e
);
1236 int log_set_max_level_from_string(const char *e
) {
1240 _cleanup_free_
char *word
= NULL
, *prefix
= NULL
;
1244 r
= extract_first_word(&e
, &word
, ",", 0);
1250 colon
= strchr(word
, ':');
1252 r
= log_level_from_string(word
);
1256 log_set_max_level(r
);
1260 prefix
= strndup(word
, colon
- word
);
1264 target
= log_target_from_string(prefix
);
1268 if (target
>= _LOG_TARGET_SINGLE_MAX
)
1271 r
= log_level_from_string(colon
+ 1);
1275 log_target_max_level
[target
] = r
;
1281 int log_max_levels_to_string(int level
, char **ret
) {
1282 _cleanup_free_
char *s
= NULL
;
1287 r
= log_level_to_string_alloc(level
, &s
);
1291 for (LogTarget target
= 0; target
< _LOG_TARGET_SINGLE_MAX
; target
++) {
1292 _cleanup_free_
char *l
= NULL
;
1294 if (log_target_max_level
[target
] == INT_MAX
)
1297 r
= log_level_to_string_alloc(log_target_max_level
[target
], &l
);
1301 r
= strextendf_with_separator(&s
, ",", "%s:%s", log_target_to_string(target
), l
);
1310 static int log_set_ratelimit_kmsg_from_string(const char *e
) {
1313 r
= parse_boolean(e
);
1321 void log_set_assert_return_is_critical(bool b
) {
1322 assert_return_is_critical
= b
;
1325 bool log_get_assert_return_is_critical(void) {
1326 return assert_return_is_critical
;
1329 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1332 * The systemd.log_xyz= settings are parsed by all tools, and
1335 * However, "quiet" is only parsed by PID 1, and only turns of
1336 * status output to /dev/console, but does not alter the log
1340 if (streq(key
, "debug") && !value
)
1341 log_set_max_level(LOG_DEBUG
);
1343 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1345 if (proc_cmdline_value_missing(key
, value
))
1348 if (log_set_target_from_string(value
) < 0)
1349 log_warning("Failed to parse log target '%s', ignoring.", value
);
1351 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1353 if (proc_cmdline_value_missing(key
, value
))
1356 if (log_set_max_level_from_string(value
) < 0)
1357 log_warning("Failed to parse log level setting '%s', ignoring.", value
);
1359 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1361 if (log_show_color_from_string(value
?: "1") < 0)
1362 log_warning("Failed to parse log color setting '%s', ignoring.", value
);
1364 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1366 if (log_show_location_from_string(value
?: "1") < 0)
1367 log_warning("Failed to parse log location setting '%s', ignoring.", value
);
1369 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1371 if (log_show_tid_from_string(value
?: "1") < 0)
1372 log_warning("Failed to parse log tid setting '%s', ignoring.", value
);
1374 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1376 if (log_show_time_from_string(value
?: "1") < 0)
1377 log_warning("Failed to parse log time setting '%s', ignoring.", value
);
1379 } else if (proc_cmdline_key_streq(key
, "systemd.log_ratelimit_kmsg")) {
1381 if (log_set_ratelimit_kmsg_from_string(value
?: "1") < 0)
1382 log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", value
);
1388 static bool should_parse_proc_cmdline(void) {
1389 /* PID1 always reads the kernel command line. */
1390 if (getpid_cached() == 1)
1393 /* Otherwise, parse the command line if invoked directly by systemd. */
1394 return invoked_by_systemd();
1397 void log_parse_environment_variables(void) {
1400 e
= getenv("SYSTEMD_LOG_TARGET");
1401 if (e
&& log_set_target_from_string(e
) < 0)
1402 log_warning("Failed to parse log target '%s', ignoring.", e
);
1404 e
= getenv("SYSTEMD_LOG_LEVEL");
1405 if (e
&& log_set_max_level_from_string(e
) < 0)
1406 log_warning("Failed to parse log level '%s', ignoring.", e
);
1408 e
= getenv("SYSTEMD_LOG_COLOR");
1409 if (e
&& log_show_color_from_string(e
) < 0)
1410 log_warning("Failed to parse log color '%s', ignoring.", e
);
1412 e
= getenv("SYSTEMD_LOG_LOCATION");
1413 if (e
&& log_show_location_from_string(e
) < 0)
1414 log_warning("Failed to parse log location '%s', ignoring.", e
);
1416 e
= getenv("SYSTEMD_LOG_TIME");
1417 if (e
&& log_show_time_from_string(e
) < 0)
1418 log_warning("Failed to parse log time '%s', ignoring.", e
);
1420 e
= getenv("SYSTEMD_LOG_TID");
1421 if (e
&& log_show_tid_from_string(e
) < 0)
1422 log_warning("Failed to parse log tid '%s', ignoring.", e
);
1424 e
= getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
1425 if (e
&& log_set_ratelimit_kmsg_from_string(e
) < 0)
1426 log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", e
);
1429 void log_parse_environment(void) {
1430 /* Do not call from library code. */
1432 if (should_parse_proc_cmdline())
1433 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1435 log_parse_environment_variables();
1438 LogTarget
log_get_target(void) {
1442 void log_settle_target(void) {
1444 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1445 * stderr is attached to the journal every single log call. However, if we then close all file
1446 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1447 * problem, this function is used to permanently change the log target depending on whether stderr is
1448 * connected to the journal or not. */
1450 LogTarget t
= log_get_target();
1452 if (t
!= LOG_TARGET_AUTO
)
1455 t
= getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc
? LOG_TARGET_KMSG
: LOG_TARGET_JOURNAL_OR_KMSG
)
1456 : LOG_TARGET_CONSOLE
;
1460 int log_get_max_level(void) {
1461 return log_max_level
;
1464 void log_show_color(bool b
) {
1468 bool log_get_show_color(void) {
1469 return show_color
> 0; /* Defaults to false. */
1472 void log_show_location(bool b
) {
1476 bool log_get_show_location(void) {
1477 return show_location
;
1480 void log_show_time(bool b
) {
1484 bool log_get_show_time(void) {
1488 void log_show_tid(bool b
) {
1492 bool log_get_show_tid(void) {
1496 int log_show_color_from_string(const char *e
) {
1499 r
= parse_boolean(e
);
1507 int log_show_location_from_string(const char *e
) {
1510 r
= parse_boolean(e
);
1514 log_show_location(r
);
1518 int log_show_time_from_string(const char *e
) {
1521 r
= parse_boolean(e
);
1529 int log_show_tid_from_string(const char *e
) {
1532 r
= parse_boolean(e
);
1540 bool log_on_console(void) {
1541 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1542 LOG_TARGET_CONSOLE_PREFIXED
))
1545 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1548 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1549 [LOG_TARGET_CONSOLE
] = "console",
1550 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1551 [LOG_TARGET_KMSG
] = "kmsg",
1552 [LOG_TARGET_JOURNAL
] = "journal",
1553 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1554 [LOG_TARGET_SYSLOG
] = "syslog",
1555 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1556 [LOG_TARGET_AUTO
] = "auto",
1557 [LOG_TARGET_NULL
] = "null",
1560 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1562 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1565 if (pid_is_valid(si
->ssi_pid
)) {
1566 _cleanup_free_
char *p
= NULL
;
1568 (void) pid_get_comm(si
->ssi_pid
, &p
);
1571 "Received SIG%s from PID %"PRIu32
" (%s).",
1572 signal_to_string(si
->ssi_signo
),
1573 si
->ssi_pid
, strna(p
));
1577 signal_to_string(si
->ssi_signo
));
1580 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1581 assert(!log_syntax_callback
|| !cb
);
1582 assert(!log_syntax_callback_userdata
|| !userdata
);
1584 log_syntax_callback
= cb
;
1585 log_syntax_callback_userdata
= userdata
;
1588 int log_syntax_internal(
1591 const char *config_file
,
1592 unsigned config_line
,
1597 const char *format
, ...) {
1601 if (log_syntax_callback
)
1602 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1604 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1605 log_target
== LOG_TARGET_NULL
)
1606 return -ERRNO_VALUE(error
);
1608 char buffer
[LINE_MAX
];
1610 const char *unit_fmt
= NULL
;
1612 errno
= ERRNO_VALUE(error
);
1614 va_start(ap
, format
);
1615 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1619 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1622 if (config_line
> 0)
1623 return log_struct_internal(
1627 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1628 "CONFIG_FILE=%s", config_file
,
1629 "CONFIG_LINE=%u", config_line
,
1630 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1634 return log_struct_internal(
1638 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1639 "CONFIG_FILE=%s", config_file
,
1640 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1644 return log_struct_internal(
1648 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1649 LOG_MESSAGE("%s: %s", unit
, buffer
),
1653 return log_struct_internal(
1657 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1658 LOG_MESSAGE("%s", buffer
),
1662 int log_syntax_invalid_utf8_internal(
1665 const char *config_file
,
1666 unsigned config_line
,
1670 const char *rvalue
) {
1672 _cleanup_free_
char *p
= NULL
;
1675 p
= utf8_escape_invalid(rvalue
);
1677 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1678 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1679 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1682 void log_set_upgrade_syslog_to_journal(bool b
) {
1683 upgrade_syslog_to_journal
= b
;
1685 /* Make the change effective immediately */
1687 if (log_target
== LOG_TARGET_SYSLOG
)
1688 log_target
= LOG_TARGET_JOURNAL
;
1689 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1690 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1694 void log_set_always_reopen_console(bool b
) {
1695 always_reopen_console
= b
;
1698 void log_set_open_when_needed(bool b
) {
1699 open_when_needed
= b
;
1702 void log_set_prohibit_ipc(bool b
) {
1706 int log_emergency_level(void) {
1707 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1708 * then the system of the whole system is obviously affected. */
1710 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1713 int log_dup_console(void) {
1716 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1717 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1719 if (console_fd
< 0 || console_fd
>= 3)
1722 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1730 void log_setup(void) {
1731 log_set_target(LOG_TARGET_AUTO
);
1732 log_parse_environment();
1734 if (log_on_console() && show_color
< 0)
1735 log_show_color(true);
1738 const char *_log_set_prefix(const char *prefix
, bool force
) {
1739 const char *old
= log_prefix
;
1741 if (prefix
|| force
)
1742 log_prefix
= prefix
;
1747 static int saved_log_context_enabled
= -1;
1749 bool log_context_enabled(void) {
1752 if (log_get_max_level() == LOG_DEBUG
)
1755 if (saved_log_context_enabled
>= 0)
1756 return saved_log_context_enabled
;
1758 r
= secure_getenv_bool("SYSTEMD_ENABLE_LOG_CONTEXT");
1759 if (r
< 0 && r
!= -ENXIO
)
1760 log_debug_errno(r
, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1762 saved_log_context_enabled
= r
> 0;
1764 return saved_log_context_enabled
;
1767 static LogContext
* log_context_attach(LogContext
*c
) {
1770 _log_context_num_fields
+= strv_length(c
->fields
);
1771 _log_context_num_fields
+= c
->n_input_iovec
;
1772 _log_context_num_fields
+= !!c
->key
;
1774 return LIST_PREPEND(ll
, _log_context
, c
);
1777 static LogContext
* log_context_detach(LogContext
*c
) {
1781 assert(_log_context_num_fields
>= strv_length(c
->fields
) + c
->n_input_iovec
+!!c
->key
);
1782 _log_context_num_fields
-= strv_length(c
->fields
);
1783 _log_context_num_fields
-= c
->n_input_iovec
;
1784 _log_context_num_fields
-= !!c
->key
;
1786 LIST_REMOVE(ll
, _log_context
, c
);
1790 LogContext
* log_context_new(const char *key
, const char *value
) {
1792 assert(endswith(key
, "="));
1795 LIST_FOREACH(ll
, i
, _log_context
)
1796 if (i
->key
== key
&& i
->value
== value
)
1797 return log_context_ref(i
);
1799 LogContext
*c
= new(LogContext
, 1);
1805 .key
= (char *) key
,
1806 .value
= (char *) value
,
1809 return log_context_attach(c
);
1812 LogContext
* log_context_new_strv(char **fields
, bool owned
) {
1816 LIST_FOREACH(ll
, i
, _log_context
)
1817 if (i
->fields
== fields
) {
1819 return log_context_ref(i
);
1822 LogContext
*c
= new(LogContext
, 1);
1832 return log_context_attach(c
);
1835 LogContext
* log_context_new_iov(struct iovec
*input_iovec
, size_t n_input_iovec
, bool owned
) {
1836 if (!input_iovec
|| n_input_iovec
== 0)
1839 LIST_FOREACH(ll
, i
, _log_context
)
1840 if (i
->input_iovec
== input_iovec
&& i
->n_input_iovec
== n_input_iovec
) {
1842 return log_context_ref(i
);
1845 LogContext
*c
= new(LogContext
, 1);
1851 .input_iovec
= input_iovec
,
1852 .n_input_iovec
= n_input_iovec
,
1856 return log_context_attach(c
);
1859 static LogContext
* log_context_free(LogContext
*c
) {
1863 log_context_detach(c
);
1866 strv_free(c
->fields
);
1867 iovec_array_free(c
->input_iovec
, c
->n_input_iovec
);
1875 DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext
, log_context
, log_context_free
);
1877 LogContext
* log_context_new_strv_consume(char **fields
) {
1878 LogContext
*c
= log_context_new_strv(fields
, /*owned=*/ true);
1885 LogContext
* log_context_new_iov_consume(struct iovec
*input_iovec
, size_t n_input_iovec
) {
1886 LogContext
*c
= log_context_new_iov(input_iovec
, n_input_iovec
, /*owned=*/ true);
1888 iovec_array_free(input_iovec
, n_input_iovec
);
1893 size_t log_context_num_contexts(void) {
1896 LIST_FOREACH(ll
, c
, _log_context
)
1902 size_t log_context_num_fields(void) {
1903 return _log_context_num_fields
;