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
;
53 static bool ratelimit_kmsg
= true;
55 static int console_fd
= STDERR_FILENO
;
56 static int syslog_fd
= -EBADF
;
57 static int kmsg_fd
= -EBADF
;
58 static int journal_fd
= -EBADF
;
60 static bool syslog_is_stream
= false;
62 static int show_color
= -1; /* tristate */
63 static bool show_location
= false;
64 static bool show_time
= false;
65 static bool show_tid
= false;
67 static bool upgrade_syslog_to_journal
= false;
68 static bool always_reopen_console
= false;
69 static bool open_when_needed
= false;
70 static bool prohibit_ipc
= false;
72 /* Akin to glibc's __abort_msg; which is private and we hence cannot
74 static char *log_abort_msg
= NULL
;
76 typedef struct LogContext
{
78 /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
79 * referenced by this is freed or not */
81 struct iovec
*input_iovec
;
86 LIST_FIELDS(struct LogContext
, ll
);
89 static thread_local
LIST_HEAD(LogContext
, _log_context
) = NULL
;
90 static thread_local
size_t _log_context_num_fields
= 0;
92 static thread_local
const char *log_prefix
= NULL
;
94 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
95 bool _log_message_dummy
= false; /* Always false */
98 /* An assert to use in logging functions that does not call recursively
99 * into our logging functions (since that might lead to a loop). */
100 #define assert_raw(expr) \
102 if (_unlikely_(!(expr))) { \
103 fputs(#expr "\n", stderr); \
108 static void log_close_console(void) {
109 console_fd
= safe_close_above_stdio(console_fd
);
112 static int log_open_console(void) {
114 if (!always_reopen_console
) {
115 console_fd
= STDERR_FILENO
;
119 if (console_fd
< 3) {
122 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
126 console_fd
= fd_move_above_stdio(fd
);
132 static void log_close_kmsg(void) {
133 kmsg_fd
= safe_close(kmsg_fd
);
136 static int log_open_kmsg(void) {
141 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
145 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
149 static void log_close_syslog(void) {
150 syslog_fd
= safe_close(syslog_fd
);
153 static int create_log_socket(int type
) {
157 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
161 fd
= fd_move_above_stdio(fd
);
162 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
164 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
165 * in the unlikely case of a deadlock. */
166 if (getpid_cached() == 1)
167 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
169 timeval_store(&tv
, 10 * USEC_PER_SEC
);
170 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
175 static int log_open_syslog(void) {
181 syslog_fd
= create_log_socket(SOCK_DGRAM
);
187 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
189 safe_close(syslog_fd
);
191 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
193 syslog_fd
= create_log_socket(SOCK_STREAM
);
199 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
203 syslog_is_stream
= true;
205 syslog_is_stream
= false;
214 static void log_close_journal(void) {
215 journal_fd
= safe_close(journal_fd
);
218 static int log_open_journal(void) {
224 journal_fd
= create_log_socket(SOCK_DGRAM
);
225 if (journal_fd
< 0) {
230 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
241 static bool stderr_is_journal(void) {
242 _cleanup_free_
char *w
= NULL
;
247 e
= getenv("JOURNAL_STREAM");
251 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
256 if (safe_atou64(w
, &dev
) < 0)
258 if (safe_atou64(e
, &ino
) < 0)
261 if (fstat(STDERR_FILENO
, &st
) < 0)
264 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
270 /* Do not call from library code. */
272 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
273 * so that a call to a logging function immediately following a log_open() call can still easily
274 * reference an error that happened immediately before the log_open() call. */
277 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
278 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
279 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
280 * because there is no reason to close it. */
282 if (log_target
== LOG_TARGET_NULL
) {
289 if (getpid_cached() == 1 ||
290 stderr_is_journal() ||
294 LOG_TARGET_JOURNAL_OR_KMSG
,
296 LOG_TARGET_SYSLOG_OR_KMSG
)) {
299 if (IN_SET(log_target
,
301 LOG_TARGET_JOURNAL_OR_KMSG
,
302 LOG_TARGET_JOURNAL
)) {
304 r
= log_open_journal();
312 if (IN_SET(log_target
,
313 LOG_TARGET_SYSLOG_OR_KMSG
,
314 LOG_TARGET_SYSLOG
)) {
316 r
= log_open_syslog();
325 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
326 LOG_TARGET_JOURNAL_OR_KMSG
,
327 LOG_TARGET_SYSLOG_OR_KMSG
,
342 return log_open_console();
345 void log_set_target(LogTarget target
) {
347 assert(target
< _LOG_TARGET_MAX
);
349 if (upgrade_syslog_to_journal
) {
350 if (target
== LOG_TARGET_SYSLOG
)
351 target
= LOG_TARGET_JOURNAL
;
352 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
353 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
359 void log_set_target_and_open(LogTarget target
) {
360 log_set_target(target
);
364 void log_close(void) {
365 /* Do not call from library code. */
373 void log_forget_fds(void) {
374 /* Do not call from library code. */
376 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
379 void log_set_max_level(int level
) {
380 assert(level
== LOG_NULL
|| (level
& LOG_PRIMASK
) == level
);
382 log_max_level
= level
;
385 void log_set_facility(int facility
) {
386 log_facility
= facility
;
389 static int write_to_console(
395 const char *buffer
) {
398 header_time
[FORMAT_TIMESTAMP_MAX
],
399 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
400 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
401 struct iovec iovec
[11];
402 const char *on
= NULL
, *off
= NULL
;
408 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
409 xsprintf(prefix
, "<%i>", level
);
410 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
414 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
415 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
416 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
420 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
421 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
424 if (log_get_show_color())
425 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
428 const char *lon
= "", *loff
= "";
429 if (log_get_show_color()) {
430 lon
= ansi_highlight_yellow4();
431 loff
= ansi_normal();
434 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
435 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
439 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
441 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
442 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
444 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
446 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
447 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
449 if (writev(console_fd
, iovec
, n
) < 0) {
451 if (errno
== EIO
&& getpid_cached() == 1) {
453 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
457 (void) log_open_console();
461 if (writev(console_fd
, iovec
, n
) < 0)
470 static int write_to_syslog(
476 const char *buffer
) {
478 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
480 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
487 xsprintf(header_priority
, "<%i>", level
);
489 t
= (time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
);
490 if (!localtime_r(&t
, &tm
))
493 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
496 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
498 struct iovec iovec
[] = {
499 IOVEC_MAKE_STRING(header_priority
),
500 IOVEC_MAKE_STRING(header_time
),
501 IOVEC_MAKE_STRING(program_invocation_short_name
),
502 IOVEC_MAKE_STRING(header_pid
),
503 IOVEC_MAKE_STRING(strempty(log_prefix
)),
504 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
505 IOVEC_MAKE_STRING(buffer
),
507 const struct msghdr msghdr
= {
509 .msg_iovlen
= ELEMENTSOF(iovec
),
512 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
513 if (syslog_is_stream
)
514 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
519 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
523 if (!syslog_is_stream
)
526 if (IOVEC_INCREMENT(iovec
, ELEMENTSOF(iovec
), n
))
533 static int write_to_kmsg(
539 const char *buffer
) {
541 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
542 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
543 * where we log excessively, but not in a tight loop.
545 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
548 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
550 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
551 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
556 if (ratelimit_kmsg
&& !ratelimit_below(&ratelimit
)) {
557 if (ratelimit_num_dropped(&ratelimit
) > 1)
560 buffer
= "Too many messages being logged to kmsg, ignoring";
563 xsprintf(header_priority
, "<%i>", level
);
564 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
566 const struct iovec iovec
[] = {
567 IOVEC_MAKE_STRING(header_priority
),
568 IOVEC_MAKE_STRING(program_invocation_short_name
),
569 IOVEC_MAKE_STRING(header_pid
),
570 IOVEC_MAKE_STRING(strempty(log_prefix
)),
571 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
572 IOVEC_MAKE_STRING(buffer
),
573 IOVEC_MAKE_STRING("\n"),
576 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
582 static int log_do_header(
587 const char *file
, int line
, const char *func
,
588 const char *object_field
, const char *object
,
589 const char *extra_field
, const char *extra
) {
592 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
594 r
= snprintf(header
, size
,
596 "SYSLOG_FACILITY=%i\n"
598 "%s%.256s%s" /* CODE_FILE */
599 "%s%.*i%s" /* CODE_LINE */
600 "%s%.256s%s" /* CODE_FUNC */
601 "%s%.*i%s" /* ERRNO */
602 "%s%.256s%s" /* object */
603 "%s%.256s%s" /* extra */
604 "SYSLOG_IDENTIFIER=%.256s\n",
608 isempty(file
) ? "" : "CODE_FILE=",
609 isempty(file
) ? "" : file
,
610 isempty(file
) ? "" : "\n",
611 line
? "CODE_LINE=" : "",
612 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
614 isempty(func
) ? "" : "CODE_FUNC=",
615 isempty(func
) ? "" : func
,
616 isempty(func
) ? "" : "\n",
617 error
? "ERRNO=" : "",
618 error
? 1 : 0, error
,
620 isempty(object
) ? "" : object_field
,
621 isempty(object
) ? "" : object
,
622 isempty(object
) ? "" : "\n",
623 isempty(extra
) ? "" : extra_field
,
624 isempty(extra
) ? "" : extra
,
625 isempty(extra
) ? "" : "\n",
626 program_invocation_short_name
);
627 assert_raw((size_t) r
< size
);
632 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
636 LIST_FOREACH(ll
, c
, _log_context
) {
637 STRV_FOREACH(s
, c
->fields
) {
638 if (*n
+ 2 >= iovec_len
)
641 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
642 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
645 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
646 if (*n
+ 2 >= iovec_len
)
649 iovec
[(*n
)++] = c
->input_iovec
[i
];
650 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
653 if (c
->key
&& c
->value
) {
654 if (*n
+ 3 >= iovec_len
)
657 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->key
);
658 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->value
);
659 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
664 static int write_to_journal(
670 const char *object_field
,
672 const char *extra_field
,
674 const char *buffer
) {
676 char header
[LINE_MAX
];
677 size_t n
= 0, iovec_len
;
683 iovec_len
= MIN(6 + _log_context_num_fields
* 2, IOVEC_MAX
);
684 iovec
= newa(struct iovec
, iovec_len
);
686 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
688 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
689 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
691 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
692 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
694 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
695 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
697 log_do_context(iovec
, iovec_len
, &n
);
699 const struct msghdr msghdr
= {
704 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
710 int log_dispatch_internal(
716 const char *object_field
,
718 const char *extra_field
,
724 if (log_target
== LOG_TARGET_NULL
)
725 return -ERRNO_VALUE(error
);
727 /* Patch in LOG_DAEMON facility if necessary */
728 if ((level
& LOG_FACMASK
) == 0)
729 level
|= log_facility
;
731 if (open_when_needed
)
738 buffer
+= strspn(buffer
, NEWLINE
);
743 if ((e
= strpbrk(buffer
, NEWLINE
)))
746 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
747 LOG_TARGET_JOURNAL_OR_KMSG
,
748 LOG_TARGET_JOURNAL
)) {
750 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
751 if (k
< 0 && k
!= -EAGAIN
)
755 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
756 LOG_TARGET_SYSLOG
)) {
758 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
759 if (k
< 0 && k
!= -EAGAIN
)
764 IN_SET(log_target
, LOG_TARGET_AUTO
,
765 LOG_TARGET_SYSLOG_OR_KMSG
,
766 LOG_TARGET_JOURNAL_OR_KMSG
,
772 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
775 (void) log_open_console();
780 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
785 if (open_when_needed
)
788 return -ERRNO_VALUE(error
);
791 int log_dump_internal(
801 /* This modifies the buffer... */
803 if (_likely_(LOG_PRI(level
) > log_max_level
))
804 return -ERRNO_VALUE(error
);
806 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
818 if (_likely_(LOG_PRI(level
) > log_max_level
))
819 return -ERRNO_VALUE(error
);
821 /* Make sure that %m maps to the specified error (or "Success"). */
822 char buffer
[LINE_MAX
];
823 LOCAL_ERRNO(ERRNO_VALUE(error
));
825 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
827 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
836 const char *format
, ...) {
841 va_start(ap
, format
);
842 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
848 int log_object_internalv(
854 const char *object_field
,
856 const char *extra_field
,
863 if (_likely_(LOG_PRI(level
) > log_max_level
))
864 return -ERRNO_VALUE(error
);
866 /* Make sure that %m maps to the specified error (or "Success"). */
867 LOCAL_ERRNO(ERRNO_VALUE(error
));
869 LOG_SET_PREFIX(object
);
871 b
= buffer
= newa(char, LINE_MAX
);
872 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
874 return log_dispatch_internal(level
, error
, file
, line
, func
,
875 object_field
, object
, extra_field
, extra
, buffer
);
878 int log_object_internal(
884 const char *object_field
,
886 const char *extra_field
,
888 const char *format
, ...) {
893 va_start(ap
, format
);
894 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
900 static void log_assert(
906 const char *format
) {
908 static char buffer
[LINE_MAX
];
910 if (_likely_(LOG_PRI(level
) > log_max_level
))
913 DISABLE_WARNING_FORMAT_NONLITERAL
;
914 (void) snprintf(buffer
, sizeof buffer
, format
, text
, file
, line
, func
);
917 log_abort_msg
= buffer
;
919 log_dispatch_internal(level
, 0, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
922 _noreturn_
void log_assert_failed(
927 log_assert(LOG_CRIT
, text
, file
, line
, func
,
928 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
932 _noreturn_
void log_assert_failed_unreachable(
936 log_assert(LOG_CRIT
, "Code should not be reached", file
, line
, func
,
937 "%s at %s:%u, function %s(). Aborting. 💥");
941 void log_assert_failed_return(
947 log_assert(LOG_DEBUG
, text
, file
, line
, func
,
948 "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
951 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
952 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
955 int log_format_iovec(
959 bool newline_separator
,
964 static const char nl
= '\n';
966 while (format
&& *n
+ 1 < iovec_len
) {
971 /* We need to copy the va_list structure,
972 * since vasprintf() leaves it afterwards at
973 * an undefined location */
975 errno
= ERRNO_VALUE(error
);
978 r
= vasprintf(&m
, format
, aq
);
983 /* Now, jump enough ahead, so that we point to
984 * the next format string */
985 VA_FORMAT_ADVANCE(format
, ap
);
987 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
988 if (newline_separator
)
989 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
991 format
= va_arg(ap
, char *);
996 int log_struct_internal(
1002 const char *format
, ...) {
1009 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1010 log_target
== LOG_TARGET_NULL
)
1011 return -ERRNO_VALUE(error
);
1013 if ((level
& LOG_FACMASK
) == 0)
1014 level
|= log_facility
;
1016 if (IN_SET(log_target
,
1018 LOG_TARGET_JOURNAL_OR_KMSG
,
1019 LOG_TARGET_JOURNAL
)) {
1021 if (open_when_needed
)
1024 if (journal_fd
>= 0) {
1025 char header
[LINE_MAX
];
1026 struct iovec
*iovec
;
1027 size_t n
= 0, m
, iovec_len
;
1029 bool fallback
= false;
1031 iovec_len
= MIN(17 + _log_context_num_fields
* 2, IOVEC_MAX
);
1032 iovec
= newa(struct iovec
, iovec_len
);
1034 /* If the journal is available do structured logging.
1035 * Do not report the errno if it is synthetic. */
1036 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1037 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1039 va_start(ap
, format
);
1040 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1045 log_do_context(iovec
, iovec_len
, &n
);
1047 const struct msghdr msghdr
= {
1052 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1056 for (size_t i
= 1; i
< m
; i
+= 2)
1057 free(iovec
[i
].iov_base
);
1060 if (open_when_needed
)
1063 return -ERRNO_VALUE(error
);
1068 /* Fallback if journal logging is not available or didn't work. */
1070 va_start(ap
, format
);
1074 errno
= ERRNO_VALUE(error
);
1077 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1080 if (startswith(buf
, "MESSAGE=")) {
1085 VA_FORMAT_ADVANCE(format
, ap
);
1087 format
= va_arg(ap
, char *);
1092 if (open_when_needed
)
1095 return -ERRNO_VALUE(error
);
1098 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1101 int log_struct_iovec_internal(
1107 const struct iovec input_iovec
[],
1108 size_t n_input_iovec
) {
1112 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1113 log_target
== LOG_TARGET_NULL
)
1114 return -ERRNO_VALUE(error
);
1116 if ((level
& LOG_FACMASK
) == 0)
1117 level
|= log_facility
;
1119 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1120 LOG_TARGET_JOURNAL_OR_KMSG
,
1121 LOG_TARGET_JOURNAL
) &&
1124 char header
[LINE_MAX
];
1125 struct iovec
*iovec
;
1126 size_t n
= 0, iovec_len
;
1128 iovec_len
= MIN(1 + n_input_iovec
* 2 + _log_context_num_fields
* 2, IOVEC_MAX
);
1129 iovec
= newa(struct iovec
, iovec_len
);
1131 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1133 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1134 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1135 iovec
[n
++] = input_iovec
[i
];
1136 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1139 log_do_context(iovec
, iovec_len
, &n
);
1141 const struct msghdr msghdr
= {
1146 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1147 return -ERRNO_VALUE(error
);
1150 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1151 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1154 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1155 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1157 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1160 /* Couldn't find MESSAGE=. */
1161 return -ERRNO_VALUE(error
);
1164 int log_set_target_from_string(const char *e
) {
1167 t
= log_target_from_string(e
);
1175 int log_set_max_level_from_string(const char *e
) {
1178 t
= log_level_from_string(e
);
1182 log_set_max_level(t
);
1186 static int log_set_ratelimit_kmsg_from_string(const char *e
) {
1189 r
= parse_boolean(e
);
1197 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1200 * The systemd.log_xyz= settings are parsed by all tools, and
1203 * However, "quiet" is only parsed by PID 1, and only turns of
1204 * status output to /dev/console, but does not alter the log
1208 if (streq(key
, "debug") && !value
)
1209 log_set_max_level(LOG_DEBUG
);
1211 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1213 if (proc_cmdline_value_missing(key
, value
))
1216 if (log_set_target_from_string(value
) < 0)
1217 log_warning("Failed to parse log target '%s'. Ignoring.", value
);
1219 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1221 if (proc_cmdline_value_missing(key
, value
))
1224 if (log_set_max_level_from_string(value
) < 0)
1225 log_warning("Failed to parse log level '%s'. Ignoring.", value
);
1227 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1229 if (log_show_color_from_string(value
?: "1") < 0)
1230 log_warning("Failed to parse log color setting '%s'. Ignoring.", value
);
1232 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1234 if (log_show_location_from_string(value
?: "1") < 0)
1235 log_warning("Failed to parse log location setting '%s'. Ignoring.", value
);
1237 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1239 if (log_show_tid_from_string(value
?: "1") < 0)
1240 log_warning("Failed to parse log tid setting '%s'. Ignoring.", value
);
1242 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1244 if (log_show_time_from_string(value
?: "1") < 0)
1245 log_warning("Failed to parse log time setting '%s'. Ignoring.", value
);
1247 } else if (proc_cmdline_key_streq(key
, "systemd.log_ratelimit_kmsg")) {
1249 if (log_set_ratelimit_kmsg_from_string(value
?: "1") < 0)
1250 log_warning("Failed to parse log ratelimit kmsg boolean '%s'. Ignoring.", value
);
1256 static bool should_parse_proc_cmdline(void) {
1257 /* PID1 always reads the kernel command line. */
1258 if (getpid_cached() == 1)
1261 /* Otherwise, parse the commandline if invoked directly by systemd. */
1262 return invoked_by_systemd();
1265 void log_parse_environment_variables(void) {
1268 e
= getenv("SYSTEMD_LOG_TARGET");
1269 if (e
&& log_set_target_from_string(e
) < 0)
1270 log_warning("Failed to parse log target '%s'. Ignoring.", e
);
1272 e
= getenv("SYSTEMD_LOG_LEVEL");
1273 if (e
&& log_set_max_level_from_string(e
) < 0)
1274 log_warning("Failed to parse log level '%s'. Ignoring.", e
);
1276 e
= getenv("SYSTEMD_LOG_COLOR");
1277 if (e
&& log_show_color_from_string(e
) < 0)
1278 log_warning("Failed to parse log color '%s'. Ignoring.", e
);
1280 e
= getenv("SYSTEMD_LOG_LOCATION");
1281 if (e
&& log_show_location_from_string(e
) < 0)
1282 log_warning("Failed to parse log location '%s'. Ignoring.", e
);
1284 e
= getenv("SYSTEMD_LOG_TIME");
1285 if (e
&& log_show_time_from_string(e
) < 0)
1286 log_warning("Failed to parse log time '%s'. Ignoring.", e
);
1288 e
= getenv("SYSTEMD_LOG_TID");
1289 if (e
&& log_show_tid_from_string(e
) < 0)
1290 log_warning("Failed to parse log tid '%s'. Ignoring.", e
);
1292 e
= getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
1293 if (e
&& log_set_ratelimit_kmsg_from_string(e
) < 0)
1294 log_warning("Failed to parse log ratelimit kmsg boolean '%s'. Ignoring.", e
);
1297 void log_parse_environment(void) {
1298 /* Do not call from library code. */
1300 if (should_parse_proc_cmdline())
1301 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1303 log_parse_environment_variables();
1306 LogTarget
log_get_target(void) {
1310 void log_settle_target(void) {
1312 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1313 * stderr is attached to the journal every single log call. However, if we then close all file
1314 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1315 * problem, this function is used to permanently change the log target depending on whether stderr is
1316 * connected to the journal or not. */
1318 LogTarget t
= log_get_target();
1320 if (t
!= LOG_TARGET_AUTO
)
1323 t
= getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc
? LOG_TARGET_KMSG
: LOG_TARGET_JOURNAL_OR_KMSG
)
1324 : LOG_TARGET_CONSOLE
;
1328 int log_get_max_level(void) {
1329 return log_max_level
;
1332 void log_show_color(bool b
) {
1336 bool log_get_show_color(void) {
1337 return show_color
> 0; /* Defaults to false. */
1340 void log_show_location(bool b
) {
1344 bool log_get_show_location(void) {
1345 return show_location
;
1348 void log_show_time(bool b
) {
1352 bool log_get_show_time(void) {
1356 void log_show_tid(bool b
) {
1360 bool log_get_show_tid(void) {
1364 int log_show_color_from_string(const char *e
) {
1367 t
= parse_boolean(e
);
1375 int log_show_location_from_string(const char *e
) {
1378 t
= parse_boolean(e
);
1382 log_show_location(t
);
1386 int log_show_time_from_string(const char *e
) {
1389 t
= parse_boolean(e
);
1397 int log_show_tid_from_string(const char *e
) {
1400 t
= parse_boolean(e
);
1408 bool log_on_console(void) {
1409 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1410 LOG_TARGET_CONSOLE_PREFIXED
))
1413 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1416 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1417 [LOG_TARGET_CONSOLE
] = "console",
1418 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1419 [LOG_TARGET_KMSG
] = "kmsg",
1420 [LOG_TARGET_JOURNAL
] = "journal",
1421 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1422 [LOG_TARGET_SYSLOG
] = "syslog",
1423 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1424 [LOG_TARGET_AUTO
] = "auto",
1425 [LOG_TARGET_NULL
] = "null",
1428 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1430 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1433 if (pid_is_valid(si
->ssi_pid
)) {
1434 _cleanup_free_
char *p
= NULL
;
1436 (void) get_process_comm(si
->ssi_pid
, &p
);
1439 "Received SIG%s from PID %"PRIu32
" (%s).",
1440 signal_to_string(si
->ssi_signo
),
1441 si
->ssi_pid
, strna(p
));
1445 signal_to_string(si
->ssi_signo
));
1448 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1449 assert(!log_syntax_callback
|| !cb
);
1450 assert(!log_syntax_callback_userdata
|| !userdata
);
1452 log_syntax_callback
= cb
;
1453 log_syntax_callback_userdata
= userdata
;
1456 int log_syntax_internal(
1459 const char *config_file
,
1460 unsigned config_line
,
1465 const char *format
, ...) {
1469 if (log_syntax_callback
)
1470 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1472 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1473 log_target
== LOG_TARGET_NULL
)
1474 return -ERRNO_VALUE(error
);
1476 char buffer
[LINE_MAX
];
1478 const char *unit_fmt
= NULL
;
1480 errno
= ERRNO_VALUE(error
);
1482 va_start(ap
, format
);
1483 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1487 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1490 if (config_line
> 0)
1491 return log_struct_internal(
1495 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1496 "CONFIG_FILE=%s", config_file
,
1497 "CONFIG_LINE=%u", config_line
,
1498 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1502 return log_struct_internal(
1506 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1507 "CONFIG_FILE=%s", config_file
,
1508 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1512 return log_struct_internal(
1516 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1517 LOG_MESSAGE("%s: %s", unit
, buffer
),
1521 return log_struct_internal(
1525 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1526 LOG_MESSAGE("%s", buffer
),
1530 int log_syntax_invalid_utf8_internal(
1533 const char *config_file
,
1534 unsigned config_line
,
1538 const char *rvalue
) {
1540 _cleanup_free_
char *p
= NULL
;
1543 p
= utf8_escape_invalid(rvalue
);
1545 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1546 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1547 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1550 void log_set_upgrade_syslog_to_journal(bool b
) {
1551 upgrade_syslog_to_journal
= b
;
1553 /* Make the change effective immediately */
1555 if (log_target
== LOG_TARGET_SYSLOG
)
1556 log_target
= LOG_TARGET_JOURNAL
;
1557 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1558 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1562 void log_set_always_reopen_console(bool b
) {
1563 always_reopen_console
= b
;
1566 void log_set_open_when_needed(bool b
) {
1567 open_when_needed
= b
;
1570 void log_set_prohibit_ipc(bool b
) {
1574 int log_emergency_level(void) {
1575 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1576 * then the system of the whole system is obviously affected. */
1578 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1581 int log_dup_console(void) {
1584 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1585 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1587 if (console_fd
< 0 || console_fd
>= 3)
1590 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1598 void log_setup(void) {
1599 log_set_target(LOG_TARGET_AUTO
);
1600 log_parse_environment();
1602 if (log_on_console() && show_color
< 0)
1603 log_show_color(true);
1606 const char *_log_set_prefix(const char *prefix
, bool force
) {
1607 const char *old
= log_prefix
;
1609 if (prefix
|| force
)
1610 log_prefix
= prefix
;
1615 static int saved_log_context_enabled
= -1;
1617 bool log_context_enabled(void) {
1620 if (log_get_max_level() == LOG_DEBUG
)
1623 if (saved_log_context_enabled
>= 0)
1624 return saved_log_context_enabled
;
1626 r
= getenv_bool_secure("SYSTEMD_ENABLE_LOG_CONTEXT");
1627 if (r
< 0 && r
!= -ENXIO
)
1628 log_debug_errno(r
, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1630 saved_log_context_enabled
= r
> 0;
1632 return saved_log_context_enabled
;
1635 static LogContext
* log_context_attach(LogContext
*c
) {
1638 _log_context_num_fields
+= strv_length(c
->fields
);
1639 _log_context_num_fields
+= c
->n_input_iovec
;
1640 _log_context_num_fields
+= !!c
->key
;
1642 return LIST_PREPEND(ll
, _log_context
, c
);
1645 static LogContext
* log_context_detach(LogContext
*c
) {
1649 assert(_log_context_num_fields
>= strv_length(c
->fields
) + c
->n_input_iovec
+!!c
->key
);
1650 _log_context_num_fields
-= strv_length(c
->fields
);
1651 _log_context_num_fields
-= c
->n_input_iovec
;
1652 _log_context_num_fields
-= !!c
->key
;
1654 LIST_REMOVE(ll
, _log_context
, c
);
1658 LogContext
* log_context_new(const char *key
, const char *value
) {
1660 assert(endswith(key
, "="));
1663 LIST_FOREACH(ll
, i
, _log_context
)
1664 if (i
->key
== key
&& i
->value
== value
)
1665 return log_context_ref(i
);
1667 LogContext
*c
= new(LogContext
, 1);
1673 .key
= (char *) key
,
1674 .value
= (char *) value
,
1677 return log_context_attach(c
);
1680 LogContext
* log_context_new_strv(char **fields
, bool owned
) {
1684 LIST_FOREACH(ll
, i
, _log_context
)
1685 if (i
->fields
== fields
) {
1687 return log_context_ref(i
);
1690 LogContext
*c
= new(LogContext
, 1);
1700 return log_context_attach(c
);
1703 LogContext
* log_context_new_iov(struct iovec
*input_iovec
, size_t n_input_iovec
, bool owned
) {
1704 if (!input_iovec
|| n_input_iovec
== 0)
1707 LIST_FOREACH(ll
, i
, _log_context
)
1708 if (i
->input_iovec
== input_iovec
&& i
->n_input_iovec
== n_input_iovec
) {
1710 return log_context_ref(i
);
1713 LogContext
*c
= new(LogContext
, 1);
1719 .input_iovec
= input_iovec
,
1720 .n_input_iovec
= n_input_iovec
,
1724 return log_context_attach(c
);
1727 static LogContext
* log_context_free(LogContext
*c
) {
1731 log_context_detach(c
);
1734 strv_free(c
->fields
);
1735 iovec_array_free(c
->input_iovec
, c
->n_input_iovec
);
1743 DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext
, log_context
, log_context_free
);
1745 LogContext
* log_context_new_strv_consume(char **fields
) {
1746 LogContext
*c
= log_context_new_strv(fields
, /*owned=*/ true);
1753 LogContext
* log_context_new_iov_consume(struct iovec
*input_iovec
, size_t n_input_iovec
) {
1754 LogContext
*c
= log_context_new_iov(input_iovec
, n_input_iovec
, /*owned=*/ true);
1756 iovec_array_free(input_iovec
, n_input_iovec
);
1761 size_t log_context_num_contexts(void) {
1764 LIST_FOREACH(ll
, c
, _log_context
)
1770 size_t log_context_num_fields(void) {
1771 return _log_context_num_fields
;