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"
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
;
54 static int console_fd
= STDERR_FILENO
;
55 static int syslog_fd
= -EBADF
;
56 static int kmsg_fd
= -EBADF
;
57 static int journal_fd
= -EBADF
;
59 static bool syslog_is_stream
= false;
61 static int show_color
= -1; /* tristate */
62 static bool show_location
= false;
63 static bool show_time
= false;
64 static bool show_tid
= false;
66 static bool upgrade_syslog_to_journal
= false;
67 static bool always_reopen_console
= false;
68 static bool open_when_needed
= false;
69 static bool prohibit_ipc
= false;
71 /* Akin to glibc's __abort_msg; which is private and we hence cannot
73 static char *log_abort_msg
= NULL
;
75 typedef struct LogContext
{
77 /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
78 * referenced by this is freed or not */
80 struct iovec
*input_iovec
;
85 LIST_FIELDS(struct LogContext
, ll
);
88 static thread_local
LIST_HEAD(LogContext
, _log_context
) = NULL
;
89 static thread_local
size_t _log_context_num_fields
= 0;
91 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
92 bool _log_message_dummy
= false; /* Always false */
95 /* An assert to use in logging functions that does not call recursively
96 * into our logging functions (since that might lead to a loop). */
97 #define assert_raw(expr) \
99 if (_unlikely_(!(expr))) { \
100 fputs(#expr "\n", stderr); \
105 static void log_close_console(void) {
106 console_fd
= safe_close_above_stdio(console_fd
);
109 static int log_open_console(void) {
111 if (!always_reopen_console
) {
112 console_fd
= STDERR_FILENO
;
116 if (console_fd
< 3) {
119 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
123 console_fd
= fd_move_above_stdio(fd
);
129 static void log_close_kmsg(void) {
130 kmsg_fd
= safe_close(kmsg_fd
);
133 static int log_open_kmsg(void) {
138 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
142 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
146 static void log_close_syslog(void) {
147 syslog_fd
= safe_close(syslog_fd
);
150 static int create_log_socket(int type
) {
154 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
158 fd
= fd_move_above_stdio(fd
);
159 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
161 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
162 * in the unlikely case of a deadlock. */
163 if (getpid_cached() == 1)
164 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
166 timeval_store(&tv
, 10 * USEC_PER_SEC
);
167 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
172 static int log_open_syslog(void) {
178 syslog_fd
= create_log_socket(SOCK_DGRAM
);
184 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
186 safe_close(syslog_fd
);
188 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
190 syslog_fd
= create_log_socket(SOCK_STREAM
);
196 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
200 syslog_is_stream
= true;
202 syslog_is_stream
= false;
211 static void log_close_journal(void) {
212 journal_fd
= safe_close(journal_fd
);
215 static int log_open_journal(void) {
221 journal_fd
= create_log_socket(SOCK_DGRAM
);
222 if (journal_fd
< 0) {
227 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
238 static bool stderr_is_journal(void) {
239 _cleanup_free_
char *w
= NULL
;
244 e
= getenv("JOURNAL_STREAM");
248 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
253 if (safe_atou64(w
, &dev
) < 0)
255 if (safe_atou64(e
, &ino
) < 0)
258 if (fstat(STDERR_FILENO
, &st
) < 0)
261 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
267 /* Do not call from library code. */
269 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
270 * so that a call to a logging function immediately following a log_open() call can still easily
271 * reference an error that happened immediately before the log_open() call. */
274 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
275 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
276 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
277 * because there is no reason to close it. */
279 if (log_target
== LOG_TARGET_NULL
) {
286 if (getpid_cached() == 1 ||
287 stderr_is_journal() ||
291 LOG_TARGET_JOURNAL_OR_KMSG
,
293 LOG_TARGET_SYSLOG_OR_KMSG
)) {
296 if (IN_SET(log_target
,
298 LOG_TARGET_JOURNAL_OR_KMSG
,
299 LOG_TARGET_JOURNAL
)) {
301 r
= log_open_journal();
309 if (IN_SET(log_target
,
310 LOG_TARGET_SYSLOG_OR_KMSG
,
311 LOG_TARGET_SYSLOG
)) {
313 r
= log_open_syslog();
322 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
323 LOG_TARGET_JOURNAL_OR_KMSG
,
324 LOG_TARGET_SYSLOG_OR_KMSG
,
339 return log_open_console();
342 void log_set_target(LogTarget target
) {
344 assert(target
< _LOG_TARGET_MAX
);
346 if (upgrade_syslog_to_journal
) {
347 if (target
== LOG_TARGET_SYSLOG
)
348 target
= LOG_TARGET_JOURNAL
;
349 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
350 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
356 void log_set_target_and_open(LogTarget target
) {
357 log_set_target(target
);
361 void log_close(void) {
362 /* Do not call from library code. */
370 void log_forget_fds(void) {
371 /* Do not call from library code. */
373 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
376 void log_set_max_level(int level
) {
377 assert(level
== LOG_NULL
|| (level
& LOG_PRIMASK
) == level
);
379 log_max_level
= level
;
382 void log_set_facility(int facility
) {
383 log_facility
= facility
;
386 static int write_to_console(
392 const char *buffer
) {
395 header_time
[FORMAT_TIMESTAMP_MAX
],
396 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
397 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
398 struct iovec iovec
[9];
399 const char *on
= NULL
, *off
= NULL
;
405 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
406 xsprintf(prefix
, "<%i>", level
);
407 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
411 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
412 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
413 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
417 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
418 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
421 if (log_get_show_color())
422 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
425 const char *lon
= "", *loff
= "";
426 if (log_get_show_color()) {
427 lon
= ansi_highlight_yellow4();
428 loff
= ansi_normal();
431 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
432 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
436 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
437 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
439 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
440 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
442 if (writev(console_fd
, iovec
, n
) < 0) {
444 if (errno
== EIO
&& getpid_cached() == 1) {
446 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
450 (void) log_open_console();
454 if (writev(console_fd
, iovec
, n
) < 0)
463 static int write_to_syslog(
469 const char *buffer
) {
471 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
473 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
480 xsprintf(header_priority
, "<%i>", level
);
482 t
= (time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
);
483 if (!localtime_r(&t
, &tm
))
486 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
489 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
491 struct iovec iovec
[] = {
492 IOVEC_MAKE_STRING(header_priority
),
493 IOVEC_MAKE_STRING(header_time
),
494 IOVEC_MAKE_STRING(program_invocation_short_name
),
495 IOVEC_MAKE_STRING(header_pid
),
496 IOVEC_MAKE_STRING(buffer
),
498 const struct msghdr msghdr
= {
500 .msg_iovlen
= ELEMENTSOF(iovec
),
503 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
504 if (syslog_is_stream
)
505 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
510 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
514 if (!syslog_is_stream
)
517 if (IOVEC_INCREMENT(iovec
, ELEMENTSOF(iovec
), n
))
524 static int write_to_kmsg(
530 const char *buffer
) {
532 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
533 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
534 * where we log excessively, but not in a tight loop.
536 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
539 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
541 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
542 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
547 if (!ratelimit_below(&ratelimit
))
550 xsprintf(header_priority
, "<%i>", level
);
551 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
553 const struct iovec iovec
[] = {
554 IOVEC_MAKE_STRING(header_priority
),
555 IOVEC_MAKE_STRING(program_invocation_short_name
),
556 IOVEC_MAKE_STRING(header_pid
),
557 IOVEC_MAKE_STRING(buffer
),
558 IOVEC_MAKE_STRING("\n"),
561 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
567 static int log_do_header(
572 const char *file
, int line
, const char *func
,
573 const char *object_field
, const char *object
,
574 const char *extra_field
, const char *extra
) {
577 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
579 r
= snprintf(header
, size
,
581 "SYSLOG_FACILITY=%i\n"
583 "%s%.256s%s" /* CODE_FILE */
584 "%s%.*i%s" /* CODE_LINE */
585 "%s%.256s%s" /* CODE_FUNC */
586 "%s%.*i%s" /* ERRNO */
587 "%s%.256s%s" /* object */
588 "%s%.256s%s" /* extra */
589 "SYSLOG_IDENTIFIER=%.256s\n",
593 isempty(file
) ? "" : "CODE_FILE=",
594 isempty(file
) ? "" : file
,
595 isempty(file
) ? "" : "\n",
596 line
? "CODE_LINE=" : "",
597 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
599 isempty(func
) ? "" : "CODE_FUNC=",
600 isempty(func
) ? "" : func
,
601 isempty(func
) ? "" : "\n",
602 error
? "ERRNO=" : "",
603 error
? 1 : 0, error
,
605 isempty(object
) ? "" : object_field
,
606 isempty(object
) ? "" : object
,
607 isempty(object
) ? "" : "\n",
608 isempty(extra
) ? "" : extra_field
,
609 isempty(extra
) ? "" : extra
,
610 isempty(extra
) ? "" : "\n",
611 program_invocation_short_name
);
612 assert_raw((size_t) r
< size
);
617 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
621 LIST_FOREACH(ll
, c
, _log_context
) {
622 STRV_FOREACH(s
, c
->fields
) {
623 if (*n
+ 2 >= iovec_len
)
626 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
627 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
630 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
631 if (*n
+ 2 >= iovec_len
)
634 iovec
[(*n
)++] = c
->input_iovec
[i
];
635 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
638 if (c
->key
&& c
->value
) {
639 if (*n
+ 3 >= iovec_len
)
642 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->key
);
643 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->value
);
644 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
649 static int write_to_journal(
655 const char *object_field
,
657 const char *extra_field
,
659 const char *buffer
) {
661 char header
[LINE_MAX
];
662 size_t n
= 0, iovec_len
;
668 iovec_len
= MIN(4 + _log_context_num_fields
* 2, IOVEC_MAX
);
669 iovec
= newa(struct iovec
, iovec_len
);
671 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
673 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
674 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
675 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
676 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
678 log_do_context(iovec
, iovec_len
, &n
);
680 const struct msghdr msghdr
= {
685 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
691 int log_dispatch_internal(
697 const char *object_field
,
699 const char *extra_field
,
705 if (log_target
== LOG_TARGET_NULL
)
706 return -ERRNO_VALUE(error
);
708 /* Patch in LOG_DAEMON facility if necessary */
709 if ((level
& LOG_FACMASK
) == 0)
710 level
|= log_facility
;
712 if (open_when_needed
)
719 buffer
+= strspn(buffer
, NEWLINE
);
724 if ((e
= strpbrk(buffer
, NEWLINE
)))
727 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
728 LOG_TARGET_JOURNAL_OR_KMSG
,
729 LOG_TARGET_JOURNAL
)) {
731 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
732 if (k
< 0 && k
!= -EAGAIN
)
736 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
737 LOG_TARGET_SYSLOG
)) {
739 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
740 if (k
< 0 && k
!= -EAGAIN
)
745 IN_SET(log_target
, LOG_TARGET_AUTO
,
746 LOG_TARGET_SYSLOG_OR_KMSG
,
747 LOG_TARGET_JOURNAL_OR_KMSG
,
753 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
756 (void) log_open_console();
761 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
766 if (open_when_needed
)
769 return -ERRNO_VALUE(error
);
772 int log_dump_internal(
782 /* This modifies the buffer... */
784 if (_likely_(LOG_PRI(level
) > log_max_level
))
785 return -ERRNO_VALUE(error
);
787 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
799 if (_likely_(LOG_PRI(level
) > log_max_level
))
800 return -ERRNO_VALUE(error
);
802 /* Make sure that %m maps to the specified error (or "Success"). */
803 char buffer
[LINE_MAX
];
804 LOCAL_ERRNO(ERRNO_VALUE(error
));
806 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
808 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
817 const char *format
, ...) {
822 va_start(ap
, format
);
823 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
829 int log_object_internalv(
835 const char *object_field
,
837 const char *extra_field
,
844 if (_likely_(LOG_PRI(level
) > log_max_level
))
845 return -ERRNO_VALUE(error
);
847 /* Make sure that %m maps to the specified error (or "Success"). */
848 LOCAL_ERRNO(ERRNO_VALUE(error
));
850 /* Prepend the object name before the message */
855 buffer
= newa(char, n
+ 2 + LINE_MAX
);
856 b
= stpcpy(stpcpy(buffer
, object
), ": ");
858 b
= buffer
= newa(char, LINE_MAX
);
860 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
862 return log_dispatch_internal(level
, error
, file
, line
, func
,
863 object_field
, object
, extra_field
, extra
, buffer
);
866 int log_object_internal(
872 const char *object_field
,
874 const char *extra_field
,
876 const char *format
, ...) {
881 va_start(ap
, format
);
882 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
888 static void log_assert(
894 const char *format
) {
896 static char buffer
[LINE_MAX
];
898 if (_likely_(LOG_PRI(level
) > log_max_level
))
901 DISABLE_WARNING_FORMAT_NONLITERAL
;
902 (void) snprintf(buffer
, sizeof buffer
, format
, text
, file
, line
, func
);
905 log_abort_msg
= buffer
;
907 log_dispatch_internal(level
, 0, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
910 _noreturn_
void log_assert_failed(
915 log_assert(LOG_CRIT
, text
, file
, line
, func
,
916 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
920 _noreturn_
void log_assert_failed_unreachable(
924 log_assert(LOG_CRIT
, "Code should not be reached", file
, line
, func
,
925 "%s at %s:%u, function %s(). Aborting. 💥");
929 void log_assert_failed_return(
935 log_assert(LOG_DEBUG
, text
, file
, line
, func
,
936 "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
939 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
940 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
943 int log_format_iovec(
947 bool newline_separator
,
952 static const char nl
= '\n';
954 while (format
&& *n
+ 1 < iovec_len
) {
959 /* We need to copy the va_list structure,
960 * since vasprintf() leaves it afterwards at
961 * an undefined location */
963 errno
= ERRNO_VALUE(error
);
966 r
= vasprintf(&m
, format
, aq
);
971 /* Now, jump enough ahead, so that we point to
972 * the next format string */
973 VA_FORMAT_ADVANCE(format
, ap
);
975 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
976 if (newline_separator
)
977 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
979 format
= va_arg(ap
, char *);
984 int log_struct_internal(
990 const char *format
, ...) {
997 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
998 log_target
== LOG_TARGET_NULL
)
999 return -ERRNO_VALUE(error
);
1001 if ((level
& LOG_FACMASK
) == 0)
1002 level
|= log_facility
;
1004 if (IN_SET(log_target
,
1006 LOG_TARGET_JOURNAL_OR_KMSG
,
1007 LOG_TARGET_JOURNAL
)) {
1009 if (open_when_needed
)
1012 if (journal_fd
>= 0) {
1013 char header
[LINE_MAX
];
1014 struct iovec
*iovec
;
1015 size_t n
= 0, m
, iovec_len
;
1017 bool fallback
= false;
1019 iovec_len
= MIN(17 + _log_context_num_fields
* 2, IOVEC_MAX
);
1020 iovec
= newa(struct iovec
, iovec_len
);
1022 /* If the journal is available do structured logging.
1023 * Do not report the errno if it is synthetic. */
1024 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1025 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1027 va_start(ap
, format
);
1028 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1033 log_do_context(iovec
, iovec_len
, &n
);
1035 const struct msghdr msghdr
= {
1040 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1044 for (size_t i
= 1; i
< m
; i
+= 2)
1045 free(iovec
[i
].iov_base
);
1048 if (open_when_needed
)
1051 return -ERRNO_VALUE(error
);
1056 /* Fallback if journal logging is not available or didn't work. */
1058 va_start(ap
, format
);
1062 errno
= ERRNO_VALUE(error
);
1065 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1068 if (startswith(buf
, "MESSAGE=")) {
1073 VA_FORMAT_ADVANCE(format
, ap
);
1075 format
= va_arg(ap
, char *);
1080 if (open_when_needed
)
1083 return -ERRNO_VALUE(error
);
1086 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1089 int log_struct_iovec_internal(
1095 const struct iovec input_iovec
[],
1096 size_t n_input_iovec
) {
1100 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1101 log_target
== LOG_TARGET_NULL
)
1102 return -ERRNO_VALUE(error
);
1104 if ((level
& LOG_FACMASK
) == 0)
1105 level
|= log_facility
;
1107 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1108 LOG_TARGET_JOURNAL_OR_KMSG
,
1109 LOG_TARGET_JOURNAL
) &&
1112 char header
[LINE_MAX
];
1113 struct iovec
*iovec
;
1114 size_t n
= 0, iovec_len
;
1116 iovec_len
= MIN(1 + n_input_iovec
* 2 + _log_context_num_fields
* 2, IOVEC_MAX
);
1117 iovec
= newa(struct iovec
, iovec_len
);
1119 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1121 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1122 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1123 iovec
[n
++] = input_iovec
[i
];
1124 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1127 log_do_context(iovec
, iovec_len
, &n
);
1129 const struct msghdr msghdr
= {
1134 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1135 return -ERRNO_VALUE(error
);
1138 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1139 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1142 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1143 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1145 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1148 /* Couldn't find MESSAGE=. */
1149 return -ERRNO_VALUE(error
);
1152 int log_set_target_from_string(const char *e
) {
1155 t
= log_target_from_string(e
);
1163 int log_set_max_level_from_string(const char *e
) {
1166 t
= log_level_from_string(e
);
1170 log_set_max_level(t
);
1174 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1177 * The systemd.log_xyz= settings are parsed by all tools, and
1180 * However, "quiet" is only parsed by PID 1, and only turns of
1181 * status output to /dev/console, but does not alter the log
1185 if (streq(key
, "debug") && !value
)
1186 log_set_max_level(LOG_DEBUG
);
1188 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1190 if (proc_cmdline_value_missing(key
, value
))
1193 if (log_set_target_from_string(value
) < 0)
1194 log_warning("Failed to parse log target '%s'. Ignoring.", value
);
1196 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1198 if (proc_cmdline_value_missing(key
, value
))
1201 if (log_set_max_level_from_string(value
) < 0)
1202 log_warning("Failed to parse log level '%s'. Ignoring.", value
);
1204 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1206 if (log_show_color_from_string(value
?: "1") < 0)
1207 log_warning("Failed to parse log color setting '%s'. Ignoring.", value
);
1209 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1211 if (log_show_location_from_string(value
?: "1") < 0)
1212 log_warning("Failed to parse log location setting '%s'. Ignoring.", value
);
1214 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1216 if (log_show_tid_from_string(value
?: "1") < 0)
1217 log_warning("Failed to parse log tid setting '%s'. Ignoring.", value
);
1219 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1221 if (log_show_time_from_string(value
?: "1") < 0)
1222 log_warning("Failed to parse log time setting '%s'. Ignoring.", value
);
1229 static bool should_parse_proc_cmdline(void) {
1230 /* PID1 always reads the kernel command line. */
1231 if (getpid_cached() == 1)
1234 /* Otherwise, parse the commandline if invoked directly by systemd. */
1235 return invoked_by_systemd();
1238 void log_parse_environment_variables(void) {
1241 e
= getenv("SYSTEMD_LOG_TARGET");
1242 if (e
&& log_set_target_from_string(e
) < 0)
1243 log_warning("Failed to parse log target '%s'. Ignoring.", e
);
1245 e
= getenv("SYSTEMD_LOG_LEVEL");
1246 if (e
&& log_set_max_level_from_string(e
) < 0)
1247 log_warning("Failed to parse log level '%s'. Ignoring.", e
);
1249 e
= getenv("SYSTEMD_LOG_COLOR");
1250 if (e
&& log_show_color_from_string(e
) < 0)
1251 log_warning("Failed to parse log color '%s'. Ignoring.", e
);
1253 e
= getenv("SYSTEMD_LOG_LOCATION");
1254 if (e
&& log_show_location_from_string(e
) < 0)
1255 log_warning("Failed to parse log location '%s'. Ignoring.", e
);
1257 e
= getenv("SYSTEMD_LOG_TIME");
1258 if (e
&& log_show_time_from_string(e
) < 0)
1259 log_warning("Failed to parse log time '%s'. Ignoring.", e
);
1261 e
= getenv("SYSTEMD_LOG_TID");
1262 if (e
&& log_show_tid_from_string(e
) < 0)
1263 log_warning("Failed to parse log tid '%s'. Ignoring.", e
);
1266 void log_parse_environment(void) {
1267 /* Do not call from library code. */
1269 if (should_parse_proc_cmdline())
1270 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1272 log_parse_environment_variables();
1275 LogTarget
log_get_target(void) {
1279 void log_settle_target(void) {
1281 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1282 * stderr is attached to the journal every single log call. However, if we then close all file
1283 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1284 * problem, this function is used to permanently change the log target depending on whether stderr is
1285 * connected to the journal or not. */
1287 LogTarget t
= log_get_target();
1289 if (t
!= LOG_TARGET_AUTO
)
1292 t
= getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc
? LOG_TARGET_KMSG
: LOG_TARGET_JOURNAL_OR_KMSG
)
1293 : LOG_TARGET_CONSOLE
;
1297 int log_get_max_level(void) {
1298 return log_max_level
;
1301 void log_show_color(bool b
) {
1305 bool log_get_show_color(void) {
1306 return show_color
> 0; /* Defaults to false. */
1309 void log_show_location(bool b
) {
1313 bool log_get_show_location(void) {
1314 return show_location
;
1317 void log_show_time(bool b
) {
1321 bool log_get_show_time(void) {
1325 void log_show_tid(bool b
) {
1329 bool log_get_show_tid(void) {
1333 int log_show_color_from_string(const char *e
) {
1336 t
= parse_boolean(e
);
1344 int log_show_location_from_string(const char *e
) {
1347 t
= parse_boolean(e
);
1351 log_show_location(t
);
1355 int log_show_time_from_string(const char *e
) {
1358 t
= parse_boolean(e
);
1366 int log_show_tid_from_string(const char *e
) {
1369 t
= parse_boolean(e
);
1377 bool log_on_console(void) {
1378 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1379 LOG_TARGET_CONSOLE_PREFIXED
))
1382 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1385 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1386 [LOG_TARGET_CONSOLE
] = "console",
1387 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1388 [LOG_TARGET_KMSG
] = "kmsg",
1389 [LOG_TARGET_JOURNAL
] = "journal",
1390 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1391 [LOG_TARGET_SYSLOG
] = "syslog",
1392 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1393 [LOG_TARGET_AUTO
] = "auto",
1394 [LOG_TARGET_NULL
] = "null",
1397 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1399 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1402 if (pid_is_valid(si
->ssi_pid
)) {
1403 _cleanup_free_
char *p
= NULL
;
1405 (void) get_process_comm(si
->ssi_pid
, &p
);
1408 "Received SIG%s from PID %"PRIu32
" (%s).",
1409 signal_to_string(si
->ssi_signo
),
1410 si
->ssi_pid
, strna(p
));
1414 signal_to_string(si
->ssi_signo
));
1417 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1418 assert(!log_syntax_callback
|| !cb
);
1419 assert(!log_syntax_callback_userdata
|| !userdata
);
1421 log_syntax_callback
= cb
;
1422 log_syntax_callback_userdata
= userdata
;
1425 int log_syntax_internal(
1428 const char *config_file
,
1429 unsigned config_line
,
1434 const char *format
, ...) {
1438 if (log_syntax_callback
)
1439 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1441 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1442 log_target
== LOG_TARGET_NULL
)
1443 return -ERRNO_VALUE(error
);
1445 char buffer
[LINE_MAX
];
1447 const char *unit_fmt
= NULL
;
1449 errno
= ERRNO_VALUE(error
);
1451 va_start(ap
, format
);
1452 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1456 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1459 if (config_line
> 0)
1460 return log_struct_internal(
1464 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1465 "CONFIG_FILE=%s", config_file
,
1466 "CONFIG_LINE=%u", config_line
,
1467 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1471 return log_struct_internal(
1475 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1476 "CONFIG_FILE=%s", config_file
,
1477 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1481 return log_struct_internal(
1485 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1486 LOG_MESSAGE("%s: %s", unit
, buffer
),
1490 return log_struct_internal(
1494 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1495 LOG_MESSAGE("%s", buffer
),
1499 int log_syntax_invalid_utf8_internal(
1502 const char *config_file
,
1503 unsigned config_line
,
1507 const char *rvalue
) {
1509 _cleanup_free_
char *p
= NULL
;
1512 p
= utf8_escape_invalid(rvalue
);
1514 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1515 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1516 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1519 void log_set_upgrade_syslog_to_journal(bool b
) {
1520 upgrade_syslog_to_journal
= b
;
1522 /* Make the change effective immediately */
1524 if (log_target
== LOG_TARGET_SYSLOG
)
1525 log_target
= LOG_TARGET_JOURNAL
;
1526 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1527 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1531 void log_set_always_reopen_console(bool b
) {
1532 always_reopen_console
= b
;
1535 void log_set_open_when_needed(bool b
) {
1536 open_when_needed
= b
;
1539 void log_set_prohibit_ipc(bool b
) {
1543 int log_emergency_level(void) {
1544 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1545 * then the system of the whole system is obviously affected. */
1547 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1550 int log_dup_console(void) {
1553 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1554 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1556 if (console_fd
< 0 || console_fd
>= 3)
1559 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1567 void log_setup(void) {
1568 log_set_target(LOG_TARGET_AUTO
);
1569 log_parse_environment();
1571 if (log_on_console() && show_color
< 0)
1572 log_show_color(true);
1575 static int saved_log_context_enabled
= -1;
1577 bool log_context_enabled(void) {
1580 if (log_get_max_level() == LOG_DEBUG
)
1583 if (saved_log_context_enabled
>= 0)
1584 return saved_log_context_enabled
;
1586 r
= getenv_bool_secure("SYSTEMD_ENABLE_LOG_CONTEXT");
1587 if (r
< 0 && r
!= -ENXIO
)
1588 log_debug_errno(r
, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1590 saved_log_context_enabled
= r
> 0;
1592 return saved_log_context_enabled
;
1595 static LogContext
* log_context_attach(LogContext
*c
) {
1598 _log_context_num_fields
+= strv_length(c
->fields
);
1599 _log_context_num_fields
+= c
->n_input_iovec
;
1600 _log_context_num_fields
+= !!c
->key
;
1602 return LIST_PREPEND(ll
, _log_context
, c
);
1605 static LogContext
* log_context_detach(LogContext
*c
) {
1609 assert(_log_context_num_fields
>= strv_length(c
->fields
) + c
->n_input_iovec
+!!c
->key
);
1610 _log_context_num_fields
-= strv_length(c
->fields
);
1611 _log_context_num_fields
-= c
->n_input_iovec
;
1612 _log_context_num_fields
-= !!c
->key
;
1614 LIST_REMOVE(ll
, _log_context
, c
);
1618 LogContext
* log_context_new(const char *key
, const char *value
) {
1620 assert(endswith(key
, "="));
1623 LIST_FOREACH(ll
, i
, _log_context
)
1624 if (i
->key
== key
&& i
->value
== value
)
1625 return log_context_ref(i
);
1627 LogContext
*c
= new(LogContext
, 1);
1633 .key
= (char *) key
,
1634 .value
= (char *) value
,
1637 return log_context_attach(c
);
1640 LogContext
* log_context_new_strv(char **fields
, bool owned
) {
1644 LIST_FOREACH(ll
, i
, _log_context
)
1645 if (i
->fields
== fields
) {
1647 return log_context_ref(i
);
1650 LogContext
*c
= new(LogContext
, 1);
1660 return log_context_attach(c
);
1663 LogContext
* log_context_new_iov(struct iovec
*input_iovec
, size_t n_input_iovec
, bool owned
) {
1664 if (!input_iovec
|| n_input_iovec
== 0)
1667 LIST_FOREACH(ll
, i
, _log_context
)
1668 if (i
->input_iovec
== input_iovec
&& i
->n_input_iovec
== n_input_iovec
) {
1670 return log_context_ref(i
);
1673 LogContext
*c
= new(LogContext
, 1);
1679 .input_iovec
= input_iovec
,
1680 .n_input_iovec
= n_input_iovec
,
1684 return log_context_attach(c
);
1687 static LogContext
* log_context_free(LogContext
*c
) {
1691 log_context_detach(c
);
1694 strv_free(c
->fields
);
1695 iovec_array_free(c
->input_iovec
, c
->n_input_iovec
);
1703 DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext
, log_context
, log_context_free
);
1705 LogContext
* log_context_new_strv_consume(char **fields
) {
1706 LogContext
*c
= log_context_new_strv(fields
, /*owned=*/ true);
1713 LogContext
* log_context_new_iov_consume(struct iovec
*input_iovec
, size_t n_input_iovec
) {
1714 LogContext
*c
= log_context_new_iov(input_iovec
, n_input_iovec
, /*owned=*/ true);
1716 iovec_array_free(input_iovec
, n_input_iovec
);
1721 size_t log_context_num_contexts(void) {
1724 LIST_FOREACH(ll
, c
, _log_context
)
1730 size_t log_context_num_fields(void) {
1731 return _log_context_num_fields
;