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;
73 /* Akin to glibc's __abort_msg; which is private and we hence cannot
75 static char *log_abort_msg
= NULL
;
77 typedef struct LogContext
{
79 /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
80 * referenced by this is freed or not */
82 struct iovec
*input_iovec
;
87 LIST_FIELDS(struct LogContext
, ll
);
90 static thread_local
LIST_HEAD(LogContext
, _log_context
) = NULL
;
91 static thread_local
size_t _log_context_num_fields
= 0;
93 static thread_local
const char *log_prefix
= NULL
;
95 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
96 bool _log_message_dummy
= false; /* Always false */
99 /* An assert to use in logging functions that does not call recursively
100 * into our logging functions (since that might lead to a loop). */
101 #define assert_raw(expr) \
103 if (_unlikely_(!(expr))) { \
104 fputs(#expr "\n", stderr); \
109 static void log_close_console(void) {
110 /* See comment in log_close_journal() */
111 (void) safe_close_above_stdio(TAKE_FD(console_fd
));
112 console_fd_is_tty
= -1;
115 static int log_open_console(void) {
117 if (!always_reopen_console
) {
118 console_fd
= STDERR_FILENO
;
119 console_fd_is_tty
= -1;
123 if (console_fd
< 3) {
126 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
130 console_fd
= fd_move_above_stdio(fd
);
131 console_fd_is_tty
= true;
137 static void log_close_kmsg(void) {
138 /* See comment in log_close_journal() */
139 (void) safe_close(TAKE_FD(kmsg_fd
));
142 static int log_open_kmsg(void) {
147 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
151 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
155 static void log_close_syslog(void) {
156 /* See comment in log_close_journal() */
157 (void) safe_close(TAKE_FD(syslog_fd
));
160 static int create_log_socket(int type
) {
164 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
168 fd
= fd_move_above_stdio(fd
);
169 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
171 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
172 * in the unlikely case of a deadlock. */
173 if (getpid_cached() == 1)
174 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
176 timeval_store(&tv
, 10 * USEC_PER_SEC
);
177 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
182 static int log_open_syslog(void) {
188 syslog_fd
= create_log_socket(SOCK_DGRAM
);
194 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
196 safe_close(syslog_fd
);
198 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
200 syslog_fd
= create_log_socket(SOCK_STREAM
);
206 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
210 syslog_is_stream
= true;
212 syslog_is_stream
= false;
221 static void log_close_journal(void) {
222 /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
223 * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
224 * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
226 (void) safe_close(TAKE_FD(journal_fd
));
229 static int log_open_journal(void) {
235 journal_fd
= create_log_socket(SOCK_DGRAM
);
236 if (journal_fd
< 0) {
241 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
252 static bool stderr_is_journal(void) {
253 _cleanup_free_
char *w
= NULL
;
258 e
= getenv("JOURNAL_STREAM");
262 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
267 if (safe_atou64(w
, &dev
) < 0)
269 if (safe_atou64(e
, &ino
) < 0)
272 if (fstat(STDERR_FILENO
, &st
) < 0)
275 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
281 /* Do not call from library code. */
283 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
284 * so that a call to a logging function immediately following a log_open() call can still easily
285 * reference an error that happened immediately before the log_open() call. */
288 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
289 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
290 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
291 * because there is no reason to close it. */
293 if (log_target
== LOG_TARGET_NULL
) {
300 if (getpid_cached() == 1 ||
301 stderr_is_journal() ||
305 LOG_TARGET_JOURNAL_OR_KMSG
,
307 LOG_TARGET_SYSLOG_OR_KMSG
)) {
310 if (IN_SET(log_target
,
312 LOG_TARGET_JOURNAL_OR_KMSG
,
313 LOG_TARGET_JOURNAL
)) {
315 r
= log_open_journal();
323 if (IN_SET(log_target
,
324 LOG_TARGET_SYSLOG_OR_KMSG
,
325 LOG_TARGET_SYSLOG
)) {
327 r
= log_open_syslog();
336 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
337 LOG_TARGET_JOURNAL_OR_KMSG
,
338 LOG_TARGET_SYSLOG_OR_KMSG
,
353 return log_open_console();
356 void log_set_target(LogTarget target
) {
358 assert(target
< _LOG_TARGET_MAX
);
360 if (upgrade_syslog_to_journal
) {
361 if (target
== LOG_TARGET_SYSLOG
)
362 target
= LOG_TARGET_JOURNAL
;
363 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
364 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
370 void log_set_target_and_open(LogTarget target
) {
371 log_set_target(target
);
375 void log_close(void) {
376 /* Do not call from library code. */
384 void log_forget_fds(void) {
385 /* Do not call from library code. */
387 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
388 console_fd_is_tty
= -1;
391 void log_set_max_level(int level
) {
392 assert(level
== LOG_NULL
|| (level
& LOG_PRIMASK
) == level
);
394 log_max_level
= level
;
396 /* Also propagate max log level to libc's syslog(), just in case some other component loaded into our
397 * process logs directly via syslog(). You might wonder why we maintain our own log level variable if
398 * libc has the same functionality. This has multiple reasons, first and foremost that we want to
399 * apply this to all our log targets, not just syslog and console. Moreover, we cannot query the
400 * current log mask from glibc without changing it, but that's useful for testing the current log
401 * level before even entering the log functions like we do in our macros. */
402 setlogmask(LOG_UPTO(level
));
404 /* Ensure that our own LOG_NULL define maps sanely to the log mask */
405 assert_cc(LOG_UPTO(LOG_NULL
) == 0);
408 void log_set_facility(int facility
) {
409 log_facility
= facility
;
412 static bool check_console_fd_is_tty(void) {
416 if (console_fd_is_tty
< 0)
417 console_fd_is_tty
= isatty(console_fd
) > 0;
419 return console_fd_is_tty
;
422 static int write_to_console(
428 const char *buffer
) {
431 header_time
[FORMAT_TIMESTAMP_MAX
],
432 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
433 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
434 struct iovec iovec
[11];
435 const char *on
= NULL
, *off
= NULL
;
441 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
442 xsprintf(prefix
, "<%i>", level
);
443 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
447 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
448 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
449 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
453 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
454 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
457 if (log_get_show_color())
458 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
461 const char *lon
= "", *loff
= "";
462 if (log_get_show_color()) {
463 lon
= ansi_highlight_yellow4();
464 loff
= ansi_normal();
467 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
468 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
472 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
474 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
475 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
477 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
479 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
481 /* When writing to a TTY we output an extra '\r' (i.e. CR) first, to generate CRNL rather than just
482 * NL. This is a robustness thing in case the TTY is currently in raw mode (specifically: has the
483 * ONLCR flag off). We want that subsequent output definitely starts at the beginning of the line
484 * again, after all. If the TTY is not in raw mode the extra CR should not hurt. */
485 iovec
[n
++] = IOVEC_MAKE_STRING(check_console_fd_is_tty() ? "\r\n" : "\n");
487 if (writev(console_fd
, iovec
, n
) < 0) {
489 if (errno
== EIO
&& getpid_cached() == 1) {
491 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
495 (void) log_open_console();
499 if (writev(console_fd
, iovec
, n
) < 0)
508 static int write_to_syslog(
514 const char *buffer
) {
516 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
518 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
525 xsprintf(header_priority
, "<%i>", level
);
527 t
= (time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
);
528 if (!localtime_r(&t
, &tm
))
531 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
534 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
536 struct iovec iovec
[] = {
537 IOVEC_MAKE_STRING(header_priority
),
538 IOVEC_MAKE_STRING(header_time
),
539 IOVEC_MAKE_STRING(program_invocation_short_name
),
540 IOVEC_MAKE_STRING(header_pid
),
541 IOVEC_MAKE_STRING(strempty(log_prefix
)),
542 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
543 IOVEC_MAKE_STRING(buffer
),
545 const struct msghdr msghdr
= {
547 .msg_iovlen
= ELEMENTSOF(iovec
),
550 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
551 if (syslog_is_stream
)
552 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
557 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
561 if (!syslog_is_stream
)
564 if (iovec_increment(iovec
, ELEMENTSOF(iovec
), n
))
571 static int write_to_kmsg(
577 const char *buffer
) {
579 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
580 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
581 * where we log excessively, but not in a tight loop.
583 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
586 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
588 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
589 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
594 if (ratelimit_kmsg
&& !ratelimit_below(&ratelimit
)) {
595 if (ratelimit_num_dropped(&ratelimit
) > 1)
598 buffer
= "Too many messages being logged to kmsg, ignoring";
601 xsprintf(header_priority
, "<%i>", level
);
602 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
604 const struct iovec iovec
[] = {
605 IOVEC_MAKE_STRING(header_priority
),
606 IOVEC_MAKE_STRING(program_invocation_short_name
),
607 IOVEC_MAKE_STRING(header_pid
),
608 IOVEC_MAKE_STRING(strempty(log_prefix
)),
609 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
610 IOVEC_MAKE_STRING(buffer
),
611 IOVEC_MAKE_STRING("\n"),
614 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
620 static int log_do_header(
625 const char *file
, int line
, const char *func
,
626 const char *object_field
, const char *object
,
627 const char *extra_field
, const char *extra
) {
630 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
632 r
= snprintf(header
, size
,
634 "SYSLOG_FACILITY=%i\n"
636 "%s%.256s%s" /* CODE_FILE */
637 "%s%.*i%s" /* CODE_LINE */
638 "%s%.256s%s" /* CODE_FUNC */
639 "%s%.*i%s" /* ERRNO */
640 "%s%.256s%s" /* object */
641 "%s%.256s%s" /* extra */
642 "SYSLOG_IDENTIFIER=%.256s\n",
646 isempty(file
) ? "" : "CODE_FILE=",
647 isempty(file
) ? "" : file
,
648 isempty(file
) ? "" : "\n",
649 line
? "CODE_LINE=" : "",
650 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
652 isempty(func
) ? "" : "CODE_FUNC=",
653 isempty(func
) ? "" : func
,
654 isempty(func
) ? "" : "\n",
655 error
? "ERRNO=" : "",
656 error
? 1 : 0, error
,
658 isempty(object
) ? "" : object_field
,
659 isempty(object
) ? "" : object
,
660 isempty(object
) ? "" : "\n",
661 isempty(extra
) ? "" : extra_field
,
662 isempty(extra
) ? "" : extra
,
663 isempty(extra
) ? "" : "\n",
664 program_invocation_short_name
);
665 assert_raw((size_t) r
< size
);
670 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
674 LIST_FOREACH(ll
, c
, _log_context
) {
675 STRV_FOREACH(s
, c
->fields
) {
676 if (*n
+ 2 >= iovec_len
)
679 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
680 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
683 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
684 if (*n
+ 2 >= iovec_len
)
687 iovec
[(*n
)++] = c
->input_iovec
[i
];
688 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
691 if (c
->key
&& c
->value
) {
692 if (*n
+ 3 >= iovec_len
)
695 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->key
);
696 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->value
);
697 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
702 static int write_to_journal(
708 const char *object_field
,
710 const char *extra_field
,
712 const char *buffer
) {
714 char header
[LINE_MAX
];
715 size_t n
= 0, iovec_len
;
721 iovec_len
= MIN(6 + _log_context_num_fields
* 2, IOVEC_MAX
);
722 iovec
= newa(struct iovec
, iovec_len
);
724 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
726 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
727 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
729 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
730 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
732 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
733 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
735 log_do_context(iovec
, iovec_len
, &n
);
737 const struct msghdr msghdr
= {
742 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
748 int log_dispatch_internal(
754 const char *object_field
,
756 const char *extra_field
,
762 if (log_target
== LOG_TARGET_NULL
)
763 return -ERRNO_VALUE(error
);
765 /* Patch in LOG_DAEMON facility if necessary */
766 if ((level
& LOG_FACMASK
) == 0)
767 level
|= log_facility
;
769 if (open_when_needed
)
776 buffer
+= strspn(buffer
, NEWLINE
);
781 if ((e
= strpbrk(buffer
, NEWLINE
)))
784 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
785 LOG_TARGET_JOURNAL_OR_KMSG
,
786 LOG_TARGET_JOURNAL
)) {
788 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
789 if (k
< 0 && k
!= -EAGAIN
)
793 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
794 LOG_TARGET_SYSLOG
)) {
796 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
797 if (k
< 0 && k
!= -EAGAIN
)
802 IN_SET(log_target
, LOG_TARGET_AUTO
,
803 LOG_TARGET_SYSLOG_OR_KMSG
,
804 LOG_TARGET_JOURNAL_OR_KMSG
,
810 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
813 (void) log_open_console();
818 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
823 if (open_when_needed
)
826 return -ERRNO_VALUE(error
);
829 int log_dump_internal(
839 /* This modifies the buffer... */
841 if (_likely_(LOG_PRI(level
) > log_max_level
))
842 return -ERRNO_VALUE(error
);
844 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
856 if (_likely_(LOG_PRI(level
) > log_max_level
))
857 return -ERRNO_VALUE(error
);
859 /* Make sure that %m maps to the specified error (or "Success"). */
860 char buffer
[LINE_MAX
];
861 LOCAL_ERRNO(ERRNO_VALUE(error
));
863 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
865 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
874 const char *format
, ...) {
879 va_start(ap
, format
);
880 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
886 int log_object_internalv(
892 const char *object_field
,
894 const char *extra_field
,
901 if (_likely_(LOG_PRI(level
) > log_max_level
))
902 return -ERRNO_VALUE(error
);
904 /* Make sure that %m maps to the specified error (or "Success"). */
905 LOCAL_ERRNO(ERRNO_VALUE(error
));
907 LOG_SET_PREFIX(object
);
909 b
= buffer
= newa(char, LINE_MAX
);
910 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
912 return log_dispatch_internal(level
, error
, file
, line
, func
,
913 object_field
, object
, extra_field
, extra
, buffer
);
916 int log_object_internal(
922 const char *object_field
,
924 const char *extra_field
,
926 const char *format
, ...) {
931 va_start(ap
, format
);
932 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
938 static void log_assert(
944 const char *format
) {
946 static char buffer
[LINE_MAX
];
948 if (_likely_(LOG_PRI(level
) > log_max_level
))
951 DISABLE_WARNING_FORMAT_NONLITERAL
;
952 (void) snprintf(buffer
, sizeof buffer
, format
, text
, file
, line
, func
);
955 log_abort_msg
= buffer
;
957 log_dispatch_internal(level
, 0, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
960 _noreturn_
void log_assert_failed(
965 log_assert(LOG_CRIT
, text
, file
, line
, func
,
966 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
970 _noreturn_
void log_assert_failed_unreachable(
974 log_assert(LOG_CRIT
, "Code should not be reached", file
, line
, func
,
975 "%s at %s:%u, function %s(). Aborting. 💥");
979 void log_assert_failed_return(
985 log_assert(LOG_DEBUG
, text
, file
, line
, func
,
986 "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
989 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
990 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
993 int log_format_iovec(
997 bool newline_separator
,
1002 static const char nl
= '\n';
1004 while (format
&& *n
+ 1 < iovec_len
) {
1009 /* We need to copy the va_list structure,
1010 * since vasprintf() leaves it afterwards at
1011 * an undefined location */
1013 errno
= ERRNO_VALUE(error
);
1016 r
= vasprintf(&m
, format
, aq
);
1021 /* Now, jump enough ahead, so that we point to
1022 * the next format string */
1023 VA_FORMAT_ADVANCE(format
, ap
);
1025 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
1026 if (newline_separator
)
1027 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
1029 format
= va_arg(ap
, char *);
1034 int log_struct_internal(
1040 const char *format
, ...) {
1047 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1048 log_target
== LOG_TARGET_NULL
)
1049 return -ERRNO_VALUE(error
);
1051 if ((level
& LOG_FACMASK
) == 0)
1052 level
|= log_facility
;
1054 if (IN_SET(log_target
,
1056 LOG_TARGET_JOURNAL_OR_KMSG
,
1057 LOG_TARGET_JOURNAL
)) {
1059 if (open_when_needed
)
1062 if (journal_fd
>= 0) {
1063 char header
[LINE_MAX
];
1064 struct iovec
*iovec
;
1065 size_t n
= 0, m
, iovec_len
;
1067 bool fallback
= false;
1069 iovec_len
= MIN(17 + _log_context_num_fields
* 2, IOVEC_MAX
);
1070 iovec
= newa(struct iovec
, iovec_len
);
1072 /* If the journal is available do structured logging.
1073 * Do not report the errno if it is synthetic. */
1074 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1075 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1077 va_start(ap
, format
);
1078 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1083 log_do_context(iovec
, iovec_len
, &n
);
1085 const struct msghdr msghdr
= {
1090 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1094 for (size_t i
= 1; i
< m
; i
+= 2)
1095 free(iovec
[i
].iov_base
);
1098 if (open_when_needed
)
1101 return -ERRNO_VALUE(error
);
1106 /* Fallback if journal logging is not available or didn't work. */
1108 va_start(ap
, format
);
1112 errno
= ERRNO_VALUE(error
);
1115 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1118 if (startswith(buf
, "MESSAGE=")) {
1123 VA_FORMAT_ADVANCE(format
, ap
);
1125 format
= va_arg(ap
, char *);
1130 if (open_when_needed
)
1133 return -ERRNO_VALUE(error
);
1136 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1139 int log_struct_iovec_internal(
1145 const struct iovec input_iovec
[],
1146 size_t n_input_iovec
) {
1150 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1151 log_target
== LOG_TARGET_NULL
)
1152 return -ERRNO_VALUE(error
);
1154 if ((level
& LOG_FACMASK
) == 0)
1155 level
|= log_facility
;
1157 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1158 LOG_TARGET_JOURNAL_OR_KMSG
,
1159 LOG_TARGET_JOURNAL
) &&
1162 char header
[LINE_MAX
];
1163 struct iovec
*iovec
;
1164 size_t n
= 0, iovec_len
;
1166 iovec_len
= MIN(1 + n_input_iovec
* 2 + _log_context_num_fields
* 2, IOVEC_MAX
);
1167 iovec
= newa(struct iovec
, iovec_len
);
1169 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1171 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1172 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1173 iovec
[n
++] = input_iovec
[i
];
1174 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1177 log_do_context(iovec
, iovec_len
, &n
);
1179 const struct msghdr msghdr
= {
1184 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1185 return -ERRNO_VALUE(error
);
1188 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1189 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1192 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1193 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1195 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1198 /* Couldn't find MESSAGE=. */
1199 return -ERRNO_VALUE(error
);
1202 int log_set_target_from_string(const char *e
) {
1205 t
= log_target_from_string(e
);
1213 int log_set_max_level_from_string(const char *e
) {
1216 r
= log_level_from_string(e
);
1220 log_set_max_level(r
);
1224 static int log_set_ratelimit_kmsg_from_string(const char *e
) {
1227 r
= parse_boolean(e
);
1235 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1238 * The systemd.log_xyz= settings are parsed by all tools, and
1241 * However, "quiet" is only parsed by PID 1, and only turns of
1242 * status output to /dev/console, but does not alter the log
1246 if (streq(key
, "debug") && !value
)
1247 log_set_max_level(LOG_DEBUG
);
1249 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1251 if (proc_cmdline_value_missing(key
, value
))
1254 if (log_set_target_from_string(value
) < 0)
1255 log_warning("Failed to parse log target '%s'. Ignoring.", value
);
1257 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1259 if (proc_cmdline_value_missing(key
, value
))
1262 if (log_set_max_level_from_string(value
) < 0)
1263 log_warning("Failed to parse log level '%s'. Ignoring.", value
);
1265 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1267 if (log_show_color_from_string(value
?: "1") < 0)
1268 log_warning("Failed to parse log color setting '%s'. Ignoring.", value
);
1270 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1272 if (log_show_location_from_string(value
?: "1") < 0)
1273 log_warning("Failed to parse log location setting '%s'. Ignoring.", value
);
1275 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1277 if (log_show_tid_from_string(value
?: "1") < 0)
1278 log_warning("Failed to parse log tid setting '%s'. Ignoring.", value
);
1280 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1282 if (log_show_time_from_string(value
?: "1") < 0)
1283 log_warning("Failed to parse log time setting '%s'. Ignoring.", value
);
1285 } else if (proc_cmdline_key_streq(key
, "systemd.log_ratelimit_kmsg")) {
1287 if (log_set_ratelimit_kmsg_from_string(value
?: "1") < 0)
1288 log_warning("Failed to parse log ratelimit kmsg boolean '%s'. Ignoring.", value
);
1294 static bool should_parse_proc_cmdline(void) {
1295 /* PID1 always reads the kernel command line. */
1296 if (getpid_cached() == 1)
1299 /* Otherwise, parse the command line if invoked directly by systemd. */
1300 return invoked_by_systemd();
1303 void log_parse_environment_variables(void) {
1306 e
= getenv("SYSTEMD_LOG_TARGET");
1307 if (e
&& log_set_target_from_string(e
) < 0)
1308 log_warning("Failed to parse log target '%s'. Ignoring.", e
);
1310 e
= getenv("SYSTEMD_LOG_LEVEL");
1311 if (e
&& log_set_max_level_from_string(e
) < 0)
1312 log_warning("Failed to parse log level '%s'. Ignoring.", e
);
1314 e
= getenv("SYSTEMD_LOG_COLOR");
1315 if (e
&& log_show_color_from_string(e
) < 0)
1316 log_warning("Failed to parse log color '%s'. Ignoring.", e
);
1318 e
= getenv("SYSTEMD_LOG_LOCATION");
1319 if (e
&& log_show_location_from_string(e
) < 0)
1320 log_warning("Failed to parse log location '%s'. Ignoring.", e
);
1322 e
= getenv("SYSTEMD_LOG_TIME");
1323 if (e
&& log_show_time_from_string(e
) < 0)
1324 log_warning("Failed to parse log time '%s'. Ignoring.", e
);
1326 e
= getenv("SYSTEMD_LOG_TID");
1327 if (e
&& log_show_tid_from_string(e
) < 0)
1328 log_warning("Failed to parse log tid '%s'. Ignoring.", e
);
1330 e
= getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
1331 if (e
&& log_set_ratelimit_kmsg_from_string(e
) < 0)
1332 log_warning("Failed to parse log ratelimit kmsg boolean '%s'. Ignoring.", e
);
1335 void log_parse_environment(void) {
1336 /* Do not call from library code. */
1338 if (should_parse_proc_cmdline())
1339 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1341 log_parse_environment_variables();
1344 LogTarget
log_get_target(void) {
1348 void log_settle_target(void) {
1350 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1351 * stderr is attached to the journal every single log call. However, if we then close all file
1352 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1353 * problem, this function is used to permanently change the log target depending on whether stderr is
1354 * connected to the journal or not. */
1356 LogTarget t
= log_get_target();
1358 if (t
!= LOG_TARGET_AUTO
)
1361 t
= getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc
? LOG_TARGET_KMSG
: LOG_TARGET_JOURNAL_OR_KMSG
)
1362 : LOG_TARGET_CONSOLE
;
1366 int log_get_max_level(void) {
1367 return log_max_level
;
1370 void log_show_color(bool b
) {
1374 bool log_get_show_color(void) {
1375 return show_color
> 0; /* Defaults to false. */
1378 void log_show_location(bool b
) {
1382 bool log_get_show_location(void) {
1383 return show_location
;
1386 void log_show_time(bool b
) {
1390 bool log_get_show_time(void) {
1394 void log_show_tid(bool b
) {
1398 bool log_get_show_tid(void) {
1402 int log_show_color_from_string(const char *e
) {
1405 r
= parse_boolean(e
);
1413 int log_show_location_from_string(const char *e
) {
1416 r
= parse_boolean(e
);
1420 log_show_location(r
);
1424 int log_show_time_from_string(const char *e
) {
1427 r
= parse_boolean(e
);
1435 int log_show_tid_from_string(const char *e
) {
1438 r
= parse_boolean(e
);
1446 bool log_on_console(void) {
1447 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1448 LOG_TARGET_CONSOLE_PREFIXED
))
1451 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1454 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1455 [LOG_TARGET_CONSOLE
] = "console",
1456 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1457 [LOG_TARGET_KMSG
] = "kmsg",
1458 [LOG_TARGET_JOURNAL
] = "journal",
1459 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1460 [LOG_TARGET_SYSLOG
] = "syslog",
1461 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1462 [LOG_TARGET_AUTO
] = "auto",
1463 [LOG_TARGET_NULL
] = "null",
1466 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1468 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1471 if (pid_is_valid(si
->ssi_pid
)) {
1472 _cleanup_free_
char *p
= NULL
;
1474 (void) pid_get_comm(si
->ssi_pid
, &p
);
1477 "Received SIG%s from PID %"PRIu32
" (%s).",
1478 signal_to_string(si
->ssi_signo
),
1479 si
->ssi_pid
, strna(p
));
1483 signal_to_string(si
->ssi_signo
));
1486 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1487 assert(!log_syntax_callback
|| !cb
);
1488 assert(!log_syntax_callback_userdata
|| !userdata
);
1490 log_syntax_callback
= cb
;
1491 log_syntax_callback_userdata
= userdata
;
1494 int log_syntax_internal(
1497 const char *config_file
,
1498 unsigned config_line
,
1503 const char *format
, ...) {
1507 if (log_syntax_callback
)
1508 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1510 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1511 log_target
== LOG_TARGET_NULL
)
1512 return -ERRNO_VALUE(error
);
1514 char buffer
[LINE_MAX
];
1516 const char *unit_fmt
= NULL
;
1518 errno
= ERRNO_VALUE(error
);
1520 va_start(ap
, format
);
1521 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1525 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1528 if (config_line
> 0)
1529 return log_struct_internal(
1533 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1534 "CONFIG_FILE=%s", config_file
,
1535 "CONFIG_LINE=%u", config_line
,
1536 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1540 return log_struct_internal(
1544 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1545 "CONFIG_FILE=%s", config_file
,
1546 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1550 return log_struct_internal(
1554 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1555 LOG_MESSAGE("%s: %s", unit
, buffer
),
1559 return log_struct_internal(
1563 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1564 LOG_MESSAGE("%s", buffer
),
1568 int log_syntax_invalid_utf8_internal(
1571 const char *config_file
,
1572 unsigned config_line
,
1576 const char *rvalue
) {
1578 _cleanup_free_
char *p
= NULL
;
1581 p
= utf8_escape_invalid(rvalue
);
1583 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1584 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1585 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1588 void log_set_upgrade_syslog_to_journal(bool b
) {
1589 upgrade_syslog_to_journal
= b
;
1591 /* Make the change effective immediately */
1593 if (log_target
== LOG_TARGET_SYSLOG
)
1594 log_target
= LOG_TARGET_JOURNAL
;
1595 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1596 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1600 void log_set_always_reopen_console(bool b
) {
1601 always_reopen_console
= b
;
1604 void log_set_open_when_needed(bool b
) {
1605 open_when_needed
= b
;
1608 void log_set_prohibit_ipc(bool b
) {
1612 int log_emergency_level(void) {
1613 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1614 * then the system of the whole system is obviously affected. */
1616 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1619 int log_dup_console(void) {
1622 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1623 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1625 if (console_fd
< 0 || console_fd
>= 3)
1628 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1636 void log_setup(void) {
1637 log_set_target(LOG_TARGET_AUTO
);
1638 log_parse_environment();
1640 if (log_on_console() && show_color
< 0)
1641 log_show_color(true);
1644 const char *_log_set_prefix(const char *prefix
, bool force
) {
1645 const char *old
= log_prefix
;
1647 if (prefix
|| force
)
1648 log_prefix
= prefix
;
1653 static int saved_log_context_enabled
= -1;
1655 bool log_context_enabled(void) {
1658 if (log_get_max_level() == LOG_DEBUG
)
1661 if (saved_log_context_enabled
>= 0)
1662 return saved_log_context_enabled
;
1664 r
= getenv_bool_secure("SYSTEMD_ENABLE_LOG_CONTEXT");
1665 if (r
< 0 && r
!= -ENXIO
)
1666 log_debug_errno(r
, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1668 saved_log_context_enabled
= r
> 0;
1670 return saved_log_context_enabled
;
1673 static LogContext
* log_context_attach(LogContext
*c
) {
1676 _log_context_num_fields
+= strv_length(c
->fields
);
1677 _log_context_num_fields
+= c
->n_input_iovec
;
1678 _log_context_num_fields
+= !!c
->key
;
1680 return LIST_PREPEND(ll
, _log_context
, c
);
1683 static LogContext
* log_context_detach(LogContext
*c
) {
1687 assert(_log_context_num_fields
>= strv_length(c
->fields
) + c
->n_input_iovec
+!!c
->key
);
1688 _log_context_num_fields
-= strv_length(c
->fields
);
1689 _log_context_num_fields
-= c
->n_input_iovec
;
1690 _log_context_num_fields
-= !!c
->key
;
1692 LIST_REMOVE(ll
, _log_context
, c
);
1696 LogContext
* log_context_new(const char *key
, const char *value
) {
1698 assert(endswith(key
, "="));
1701 LIST_FOREACH(ll
, i
, _log_context
)
1702 if (i
->key
== key
&& i
->value
== value
)
1703 return log_context_ref(i
);
1705 LogContext
*c
= new(LogContext
, 1);
1711 .key
= (char *) key
,
1712 .value
= (char *) value
,
1715 return log_context_attach(c
);
1718 LogContext
* log_context_new_strv(char **fields
, bool owned
) {
1722 LIST_FOREACH(ll
, i
, _log_context
)
1723 if (i
->fields
== fields
) {
1725 return log_context_ref(i
);
1728 LogContext
*c
= new(LogContext
, 1);
1738 return log_context_attach(c
);
1741 LogContext
* log_context_new_iov(struct iovec
*input_iovec
, size_t n_input_iovec
, bool owned
) {
1742 if (!input_iovec
|| n_input_iovec
== 0)
1745 LIST_FOREACH(ll
, i
, _log_context
)
1746 if (i
->input_iovec
== input_iovec
&& i
->n_input_iovec
== n_input_iovec
) {
1748 return log_context_ref(i
);
1751 LogContext
*c
= new(LogContext
, 1);
1757 .input_iovec
= input_iovec
,
1758 .n_input_iovec
= n_input_iovec
,
1762 return log_context_attach(c
);
1765 static LogContext
* log_context_free(LogContext
*c
) {
1769 log_context_detach(c
);
1772 strv_free(c
->fields
);
1773 iovec_array_free(c
->input_iovec
, c
->n_input_iovec
);
1781 DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext
, log_context
, log_context_free
);
1783 LogContext
* log_context_new_strv_consume(char **fields
) {
1784 LogContext
*c
= log_context_new_strv(fields
, /*owned=*/ true);
1791 LogContext
* log_context_new_iov_consume(struct iovec
*input_iovec
, size_t n_input_iovec
) {
1792 LogContext
*c
= log_context_new_iov(input_iovec
, n_input_iovec
, /*owned=*/ true);
1794 iovec_array_free(input_iovec
, n_input_iovec
);
1799 size_t log_context_num_contexts(void) {
1802 LIST_FOREACH(ll
, c
, _log_context
)
1808 size_t log_context_num_fields(void) {
1809 return _log_context_num_fields
;