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 static thread_local
const char *log_prefix
= NULL
;
93 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
94 bool _log_message_dummy
= false; /* Always false */
97 /* An assert to use in logging functions that does not call recursively
98 * into our logging functions (since that might lead to a loop). */
99 #define assert_raw(expr) \
101 if (_unlikely_(!(expr))) { \
102 fputs(#expr "\n", stderr); \
107 static void log_close_console(void) {
108 console_fd
= safe_close_above_stdio(console_fd
);
111 static int log_open_console(void) {
113 if (!always_reopen_console
) {
114 console_fd
= STDERR_FILENO
;
118 if (console_fd
< 3) {
121 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
125 console_fd
= fd_move_above_stdio(fd
);
131 static void log_close_kmsg(void) {
132 kmsg_fd
= safe_close(kmsg_fd
);
135 static int log_open_kmsg(void) {
140 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
144 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
148 static void log_close_syslog(void) {
149 syslog_fd
= safe_close(syslog_fd
);
152 static int create_log_socket(int type
) {
156 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
160 fd
= fd_move_above_stdio(fd
);
161 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
163 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
164 * in the unlikely case of a deadlock. */
165 if (getpid_cached() == 1)
166 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
168 timeval_store(&tv
, 10 * USEC_PER_SEC
);
169 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
174 static int log_open_syslog(void) {
180 syslog_fd
= create_log_socket(SOCK_DGRAM
);
186 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
188 safe_close(syslog_fd
);
190 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
192 syslog_fd
= create_log_socket(SOCK_STREAM
);
198 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
202 syslog_is_stream
= true;
204 syslog_is_stream
= false;
213 static void log_close_journal(void) {
214 journal_fd
= safe_close(journal_fd
);
217 static int log_open_journal(void) {
223 journal_fd
= create_log_socket(SOCK_DGRAM
);
224 if (journal_fd
< 0) {
229 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
240 static bool stderr_is_journal(void) {
241 _cleanup_free_
char *w
= NULL
;
246 e
= getenv("JOURNAL_STREAM");
250 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
255 if (safe_atou64(w
, &dev
) < 0)
257 if (safe_atou64(e
, &ino
) < 0)
260 if (fstat(STDERR_FILENO
, &st
) < 0)
263 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
269 /* Do not call from library code. */
271 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
272 * so that a call to a logging function immediately following a log_open() call can still easily
273 * reference an error that happened immediately before the log_open() call. */
276 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
277 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
278 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
279 * because there is no reason to close it. */
281 if (log_target
== LOG_TARGET_NULL
) {
288 if (getpid_cached() == 1 ||
289 stderr_is_journal() ||
293 LOG_TARGET_JOURNAL_OR_KMSG
,
295 LOG_TARGET_SYSLOG_OR_KMSG
)) {
298 if (IN_SET(log_target
,
300 LOG_TARGET_JOURNAL_OR_KMSG
,
301 LOG_TARGET_JOURNAL
)) {
303 r
= log_open_journal();
311 if (IN_SET(log_target
,
312 LOG_TARGET_SYSLOG_OR_KMSG
,
313 LOG_TARGET_SYSLOG
)) {
315 r
= log_open_syslog();
324 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
325 LOG_TARGET_JOURNAL_OR_KMSG
,
326 LOG_TARGET_SYSLOG_OR_KMSG
,
341 return log_open_console();
344 void log_set_target(LogTarget target
) {
346 assert(target
< _LOG_TARGET_MAX
);
348 if (upgrade_syslog_to_journal
) {
349 if (target
== LOG_TARGET_SYSLOG
)
350 target
= LOG_TARGET_JOURNAL
;
351 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
352 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
358 void log_set_target_and_open(LogTarget target
) {
359 log_set_target(target
);
363 void log_close(void) {
364 /* Do not call from library code. */
372 void log_forget_fds(void) {
373 /* Do not call from library code. */
375 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
378 void log_set_max_level(int level
) {
379 assert(level
== LOG_NULL
|| (level
& LOG_PRIMASK
) == level
);
381 log_max_level
= level
;
384 void log_set_facility(int facility
) {
385 log_facility
= facility
;
388 static int write_to_console(
394 const char *buffer
) {
397 header_time
[FORMAT_TIMESTAMP_MAX
],
398 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
399 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
400 struct iovec iovec
[11];
401 const char *on
= NULL
, *off
= NULL
;
407 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
408 xsprintf(prefix
, "<%i>", level
);
409 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
413 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
414 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
415 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
419 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
420 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
423 if (log_get_show_color())
424 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
427 const char *lon
= "", *loff
= "";
428 if (log_get_show_color()) {
429 lon
= ansi_highlight_yellow4();
430 loff
= ansi_normal();
433 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
434 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
438 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
440 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
441 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
443 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
445 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
446 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
448 if (writev(console_fd
, iovec
, n
) < 0) {
450 if (errno
== EIO
&& getpid_cached() == 1) {
452 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
456 (void) log_open_console();
460 if (writev(console_fd
, iovec
, n
) < 0)
469 static int write_to_syslog(
475 const char *buffer
) {
477 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
479 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
486 xsprintf(header_priority
, "<%i>", level
);
488 t
= (time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
);
489 if (!localtime_r(&t
, &tm
))
492 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
495 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
497 struct iovec iovec
[] = {
498 IOVEC_MAKE_STRING(header_priority
),
499 IOVEC_MAKE_STRING(header_time
),
500 IOVEC_MAKE_STRING(program_invocation_short_name
),
501 IOVEC_MAKE_STRING(header_pid
),
502 IOVEC_MAKE_STRING(strempty(log_prefix
)),
503 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
504 IOVEC_MAKE_STRING(buffer
),
506 const struct msghdr msghdr
= {
508 .msg_iovlen
= ELEMENTSOF(iovec
),
511 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
512 if (syslog_is_stream
)
513 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
518 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
522 if (!syslog_is_stream
)
525 if (IOVEC_INCREMENT(iovec
, ELEMENTSOF(iovec
), n
))
532 static int write_to_kmsg(
538 const char *buffer
) {
540 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
541 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
542 * where we log excessively, but not in a tight loop.
544 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
547 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
549 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
550 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
555 if (!ratelimit_below(&ratelimit
))
558 xsprintf(header_priority
, "<%i>", level
);
559 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
561 const struct iovec iovec
[] = {
562 IOVEC_MAKE_STRING(header_priority
),
563 IOVEC_MAKE_STRING(program_invocation_short_name
),
564 IOVEC_MAKE_STRING(header_pid
),
565 IOVEC_MAKE_STRING(strempty(log_prefix
)),
566 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
567 IOVEC_MAKE_STRING(buffer
),
568 IOVEC_MAKE_STRING("\n"),
571 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
577 static int log_do_header(
582 const char *file
, int line
, const char *func
,
583 const char *object_field
, const char *object
,
584 const char *extra_field
, const char *extra
) {
587 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
589 r
= snprintf(header
, size
,
591 "SYSLOG_FACILITY=%i\n"
593 "%s%.256s%s" /* CODE_FILE */
594 "%s%.*i%s" /* CODE_LINE */
595 "%s%.256s%s" /* CODE_FUNC */
596 "%s%.*i%s" /* ERRNO */
597 "%s%.256s%s" /* object */
598 "%s%.256s%s" /* extra */
599 "SYSLOG_IDENTIFIER=%.256s\n",
603 isempty(file
) ? "" : "CODE_FILE=",
604 isempty(file
) ? "" : file
,
605 isempty(file
) ? "" : "\n",
606 line
? "CODE_LINE=" : "",
607 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
609 isempty(func
) ? "" : "CODE_FUNC=",
610 isempty(func
) ? "" : func
,
611 isempty(func
) ? "" : "\n",
612 error
? "ERRNO=" : "",
613 error
? 1 : 0, error
,
615 isempty(object
) ? "" : object_field
,
616 isempty(object
) ? "" : object
,
617 isempty(object
) ? "" : "\n",
618 isempty(extra
) ? "" : extra_field
,
619 isempty(extra
) ? "" : extra
,
620 isempty(extra
) ? "" : "\n",
621 program_invocation_short_name
);
622 assert_raw((size_t) r
< size
);
627 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
631 LIST_FOREACH(ll
, c
, _log_context
) {
632 STRV_FOREACH(s
, c
->fields
) {
633 if (*n
+ 2 >= iovec_len
)
636 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
637 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
640 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
641 if (*n
+ 2 >= iovec_len
)
644 iovec
[(*n
)++] = c
->input_iovec
[i
];
645 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
648 if (c
->key
&& c
->value
) {
649 if (*n
+ 3 >= iovec_len
)
652 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->key
);
653 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->value
);
654 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
659 static int write_to_journal(
665 const char *object_field
,
667 const char *extra_field
,
669 const char *buffer
) {
671 char header
[LINE_MAX
];
672 size_t n
= 0, iovec_len
;
678 iovec_len
= MIN(6 + _log_context_num_fields
* 2, IOVEC_MAX
);
679 iovec
= newa(struct iovec
, iovec_len
);
681 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
683 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
684 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
686 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
687 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
689 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
690 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
692 log_do_context(iovec
, iovec_len
, &n
);
694 const struct msghdr msghdr
= {
699 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
705 int log_dispatch_internal(
711 const char *object_field
,
713 const char *extra_field
,
719 if (log_target
== LOG_TARGET_NULL
)
720 return -ERRNO_VALUE(error
);
722 /* Patch in LOG_DAEMON facility if necessary */
723 if ((level
& LOG_FACMASK
) == 0)
724 level
|= log_facility
;
726 if (open_when_needed
)
733 buffer
+= strspn(buffer
, NEWLINE
);
738 if ((e
= strpbrk(buffer
, NEWLINE
)))
741 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
742 LOG_TARGET_JOURNAL_OR_KMSG
,
743 LOG_TARGET_JOURNAL
)) {
745 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
746 if (k
< 0 && k
!= -EAGAIN
)
750 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
751 LOG_TARGET_SYSLOG
)) {
753 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
754 if (k
< 0 && k
!= -EAGAIN
)
759 IN_SET(log_target
, LOG_TARGET_AUTO
,
760 LOG_TARGET_SYSLOG_OR_KMSG
,
761 LOG_TARGET_JOURNAL_OR_KMSG
,
767 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
770 (void) log_open_console();
775 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
780 if (open_when_needed
)
783 return -ERRNO_VALUE(error
);
786 int log_dump_internal(
796 /* This modifies the buffer... */
798 if (_likely_(LOG_PRI(level
) > log_max_level
))
799 return -ERRNO_VALUE(error
);
801 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
813 if (_likely_(LOG_PRI(level
) > log_max_level
))
814 return -ERRNO_VALUE(error
);
816 /* Make sure that %m maps to the specified error (or "Success"). */
817 char buffer
[LINE_MAX
];
818 LOCAL_ERRNO(ERRNO_VALUE(error
));
820 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
822 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
831 const char *format
, ...) {
836 va_start(ap
, format
);
837 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
843 int log_object_internalv(
849 const char *object_field
,
851 const char *extra_field
,
858 if (_likely_(LOG_PRI(level
) > log_max_level
))
859 return -ERRNO_VALUE(error
);
861 /* Make sure that %m maps to the specified error (or "Success"). */
862 LOCAL_ERRNO(ERRNO_VALUE(error
));
864 LOG_SET_PREFIX(object
);
866 b
= buffer
= newa(char, LINE_MAX
);
867 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
869 return log_dispatch_internal(level
, error
, file
, line
, func
,
870 object_field
, object
, extra_field
, extra
, buffer
);
873 int log_object_internal(
879 const char *object_field
,
881 const char *extra_field
,
883 const char *format
, ...) {
888 va_start(ap
, format
);
889 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
895 static void log_assert(
901 const char *format
) {
903 static char buffer
[LINE_MAX
];
905 if (_likely_(LOG_PRI(level
) > log_max_level
))
908 DISABLE_WARNING_FORMAT_NONLITERAL
;
909 (void) snprintf(buffer
, sizeof buffer
, format
, text
, file
, line
, func
);
912 log_abort_msg
= buffer
;
914 log_dispatch_internal(level
, 0, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
917 _noreturn_
void log_assert_failed(
922 log_assert(LOG_CRIT
, text
, file
, line
, func
,
923 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
927 _noreturn_
void log_assert_failed_unreachable(
931 log_assert(LOG_CRIT
, "Code should not be reached", file
, line
, func
,
932 "%s at %s:%u, function %s(). Aborting. 💥");
936 void log_assert_failed_return(
942 log_assert(LOG_DEBUG
, text
, file
, line
, func
,
943 "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
946 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
947 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
950 int log_format_iovec(
954 bool newline_separator
,
959 static const char nl
= '\n';
961 while (format
&& *n
+ 1 < iovec_len
) {
966 /* We need to copy the va_list structure,
967 * since vasprintf() leaves it afterwards at
968 * an undefined location */
970 errno
= ERRNO_VALUE(error
);
973 r
= vasprintf(&m
, format
, aq
);
978 /* Now, jump enough ahead, so that we point to
979 * the next format string */
980 VA_FORMAT_ADVANCE(format
, ap
);
982 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
983 if (newline_separator
)
984 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
986 format
= va_arg(ap
, char *);
991 int log_struct_internal(
997 const char *format
, ...) {
1004 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1005 log_target
== LOG_TARGET_NULL
)
1006 return -ERRNO_VALUE(error
);
1008 if ((level
& LOG_FACMASK
) == 0)
1009 level
|= log_facility
;
1011 if (IN_SET(log_target
,
1013 LOG_TARGET_JOURNAL_OR_KMSG
,
1014 LOG_TARGET_JOURNAL
)) {
1016 if (open_when_needed
)
1019 if (journal_fd
>= 0) {
1020 char header
[LINE_MAX
];
1021 struct iovec
*iovec
;
1022 size_t n
= 0, m
, iovec_len
;
1024 bool fallback
= false;
1026 iovec_len
= MIN(17 + _log_context_num_fields
* 2, IOVEC_MAX
);
1027 iovec
= newa(struct iovec
, iovec_len
);
1029 /* If the journal is available do structured logging.
1030 * Do not report the errno if it is synthetic. */
1031 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1032 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1034 va_start(ap
, format
);
1035 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1040 log_do_context(iovec
, iovec_len
, &n
);
1042 const struct msghdr msghdr
= {
1047 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1051 for (size_t i
= 1; i
< m
; i
+= 2)
1052 free(iovec
[i
].iov_base
);
1055 if (open_when_needed
)
1058 return -ERRNO_VALUE(error
);
1063 /* Fallback if journal logging is not available or didn't work. */
1065 va_start(ap
, format
);
1069 errno
= ERRNO_VALUE(error
);
1072 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1075 if (startswith(buf
, "MESSAGE=")) {
1080 VA_FORMAT_ADVANCE(format
, ap
);
1082 format
= va_arg(ap
, char *);
1087 if (open_when_needed
)
1090 return -ERRNO_VALUE(error
);
1093 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1096 int log_struct_iovec_internal(
1102 const struct iovec input_iovec
[],
1103 size_t n_input_iovec
) {
1107 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1108 log_target
== LOG_TARGET_NULL
)
1109 return -ERRNO_VALUE(error
);
1111 if ((level
& LOG_FACMASK
) == 0)
1112 level
|= log_facility
;
1114 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1115 LOG_TARGET_JOURNAL_OR_KMSG
,
1116 LOG_TARGET_JOURNAL
) &&
1119 char header
[LINE_MAX
];
1120 struct iovec
*iovec
;
1121 size_t n
= 0, iovec_len
;
1123 iovec_len
= MIN(1 + n_input_iovec
* 2 + _log_context_num_fields
* 2, IOVEC_MAX
);
1124 iovec
= newa(struct iovec
, iovec_len
);
1126 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1128 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1129 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1130 iovec
[n
++] = input_iovec
[i
];
1131 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1134 log_do_context(iovec
, iovec_len
, &n
);
1136 const struct msghdr msghdr
= {
1141 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1142 return -ERRNO_VALUE(error
);
1145 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1146 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1149 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1150 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1152 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1155 /* Couldn't find MESSAGE=. */
1156 return -ERRNO_VALUE(error
);
1159 int log_set_target_from_string(const char *e
) {
1162 t
= log_target_from_string(e
);
1170 int log_set_max_level_from_string(const char *e
) {
1173 t
= log_level_from_string(e
);
1177 log_set_max_level(t
);
1181 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1184 * The systemd.log_xyz= settings are parsed by all tools, and
1187 * However, "quiet" is only parsed by PID 1, and only turns of
1188 * status output to /dev/console, but does not alter the log
1192 if (streq(key
, "debug") && !value
)
1193 log_set_max_level(LOG_DEBUG
);
1195 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1197 if (proc_cmdline_value_missing(key
, value
))
1200 if (log_set_target_from_string(value
) < 0)
1201 log_warning("Failed to parse log target '%s'. Ignoring.", value
);
1203 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1205 if (proc_cmdline_value_missing(key
, value
))
1208 if (log_set_max_level_from_string(value
) < 0)
1209 log_warning("Failed to parse log level '%s'. Ignoring.", value
);
1211 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1213 if (log_show_color_from_string(value
?: "1") < 0)
1214 log_warning("Failed to parse log color setting '%s'. Ignoring.", value
);
1216 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1218 if (log_show_location_from_string(value
?: "1") < 0)
1219 log_warning("Failed to parse log location setting '%s'. Ignoring.", value
);
1221 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1223 if (log_show_tid_from_string(value
?: "1") < 0)
1224 log_warning("Failed to parse log tid setting '%s'. Ignoring.", value
);
1226 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1228 if (log_show_time_from_string(value
?: "1") < 0)
1229 log_warning("Failed to parse log time setting '%s'. Ignoring.", value
);
1236 static bool should_parse_proc_cmdline(void) {
1237 /* PID1 always reads the kernel command line. */
1238 if (getpid_cached() == 1)
1241 /* Otherwise, parse the commandline if invoked directly by systemd. */
1242 return invoked_by_systemd();
1245 void log_parse_environment_variables(void) {
1248 e
= getenv("SYSTEMD_LOG_TARGET");
1249 if (e
&& log_set_target_from_string(e
) < 0)
1250 log_warning("Failed to parse log target '%s'. Ignoring.", e
);
1252 e
= getenv("SYSTEMD_LOG_LEVEL");
1253 if (e
&& log_set_max_level_from_string(e
) < 0)
1254 log_warning("Failed to parse log level '%s'. Ignoring.", e
);
1256 e
= getenv("SYSTEMD_LOG_COLOR");
1257 if (e
&& log_show_color_from_string(e
) < 0)
1258 log_warning("Failed to parse log color '%s'. Ignoring.", e
);
1260 e
= getenv("SYSTEMD_LOG_LOCATION");
1261 if (e
&& log_show_location_from_string(e
) < 0)
1262 log_warning("Failed to parse log location '%s'. Ignoring.", e
);
1264 e
= getenv("SYSTEMD_LOG_TIME");
1265 if (e
&& log_show_time_from_string(e
) < 0)
1266 log_warning("Failed to parse log time '%s'. Ignoring.", e
);
1268 e
= getenv("SYSTEMD_LOG_TID");
1269 if (e
&& log_show_tid_from_string(e
) < 0)
1270 log_warning("Failed to parse log tid '%s'. Ignoring.", e
);
1273 void log_parse_environment(void) {
1274 /* Do not call from library code. */
1276 if (should_parse_proc_cmdline())
1277 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1279 log_parse_environment_variables();
1282 LogTarget
log_get_target(void) {
1286 void log_settle_target(void) {
1288 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1289 * stderr is attached to the journal every single log call. However, if we then close all file
1290 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1291 * problem, this function is used to permanently change the log target depending on whether stderr is
1292 * connected to the journal or not. */
1294 LogTarget t
= log_get_target();
1296 if (t
!= LOG_TARGET_AUTO
)
1299 t
= getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc
? LOG_TARGET_KMSG
: LOG_TARGET_JOURNAL_OR_KMSG
)
1300 : LOG_TARGET_CONSOLE
;
1304 int log_get_max_level(void) {
1305 return log_max_level
;
1308 void log_show_color(bool b
) {
1312 bool log_get_show_color(void) {
1313 return show_color
> 0; /* Defaults to false. */
1316 void log_show_location(bool b
) {
1320 bool log_get_show_location(void) {
1321 return show_location
;
1324 void log_show_time(bool b
) {
1328 bool log_get_show_time(void) {
1332 void log_show_tid(bool b
) {
1336 bool log_get_show_tid(void) {
1340 int log_show_color_from_string(const char *e
) {
1343 t
= parse_boolean(e
);
1351 int log_show_location_from_string(const char *e
) {
1354 t
= parse_boolean(e
);
1358 log_show_location(t
);
1362 int log_show_time_from_string(const char *e
) {
1365 t
= parse_boolean(e
);
1373 int log_show_tid_from_string(const char *e
) {
1376 t
= parse_boolean(e
);
1384 bool log_on_console(void) {
1385 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1386 LOG_TARGET_CONSOLE_PREFIXED
))
1389 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1392 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1393 [LOG_TARGET_CONSOLE
] = "console",
1394 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1395 [LOG_TARGET_KMSG
] = "kmsg",
1396 [LOG_TARGET_JOURNAL
] = "journal",
1397 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1398 [LOG_TARGET_SYSLOG
] = "syslog",
1399 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1400 [LOG_TARGET_AUTO
] = "auto",
1401 [LOG_TARGET_NULL
] = "null",
1404 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1406 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1409 if (pid_is_valid(si
->ssi_pid
)) {
1410 _cleanup_free_
char *p
= NULL
;
1412 (void) get_process_comm(si
->ssi_pid
, &p
);
1415 "Received SIG%s from PID %"PRIu32
" (%s).",
1416 signal_to_string(si
->ssi_signo
),
1417 si
->ssi_pid
, strna(p
));
1421 signal_to_string(si
->ssi_signo
));
1424 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1425 assert(!log_syntax_callback
|| !cb
);
1426 assert(!log_syntax_callback_userdata
|| !userdata
);
1428 log_syntax_callback
= cb
;
1429 log_syntax_callback_userdata
= userdata
;
1432 int log_syntax_internal(
1435 const char *config_file
,
1436 unsigned config_line
,
1441 const char *format
, ...) {
1445 if (log_syntax_callback
)
1446 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1448 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1449 log_target
== LOG_TARGET_NULL
)
1450 return -ERRNO_VALUE(error
);
1452 char buffer
[LINE_MAX
];
1454 const char *unit_fmt
= NULL
;
1456 errno
= ERRNO_VALUE(error
);
1458 va_start(ap
, format
);
1459 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1463 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1466 if (config_line
> 0)
1467 return log_struct_internal(
1471 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1472 "CONFIG_FILE=%s", config_file
,
1473 "CONFIG_LINE=%u", config_line
,
1474 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1478 return log_struct_internal(
1482 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1483 "CONFIG_FILE=%s", config_file
,
1484 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1488 return log_struct_internal(
1492 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1493 LOG_MESSAGE("%s: %s", unit
, buffer
),
1497 return log_struct_internal(
1501 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1502 LOG_MESSAGE("%s", buffer
),
1506 int log_syntax_invalid_utf8_internal(
1509 const char *config_file
,
1510 unsigned config_line
,
1514 const char *rvalue
) {
1516 _cleanup_free_
char *p
= NULL
;
1519 p
= utf8_escape_invalid(rvalue
);
1521 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1522 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1523 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1526 void log_set_upgrade_syslog_to_journal(bool b
) {
1527 upgrade_syslog_to_journal
= b
;
1529 /* Make the change effective immediately */
1531 if (log_target
== LOG_TARGET_SYSLOG
)
1532 log_target
= LOG_TARGET_JOURNAL
;
1533 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1534 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1538 void log_set_always_reopen_console(bool b
) {
1539 always_reopen_console
= b
;
1542 void log_set_open_when_needed(bool b
) {
1543 open_when_needed
= b
;
1546 void log_set_prohibit_ipc(bool b
) {
1550 int log_emergency_level(void) {
1551 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1552 * then the system of the whole system is obviously affected. */
1554 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1557 int log_dup_console(void) {
1560 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1561 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1563 if (console_fd
< 0 || console_fd
>= 3)
1566 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1574 void log_setup(void) {
1575 log_set_target(LOG_TARGET_AUTO
);
1576 log_parse_environment();
1578 if (log_on_console() && show_color
< 0)
1579 log_show_color(true);
1582 const char *_log_set_prefix(const char *prefix
, bool force
) {
1583 const char *old
= log_prefix
;
1585 if (prefix
|| force
)
1586 log_prefix
= prefix
;
1591 static int saved_log_context_enabled
= -1;
1593 bool log_context_enabled(void) {
1596 if (log_get_max_level() == LOG_DEBUG
)
1599 if (saved_log_context_enabled
>= 0)
1600 return saved_log_context_enabled
;
1602 r
= getenv_bool_secure("SYSTEMD_ENABLE_LOG_CONTEXT");
1603 if (r
< 0 && r
!= -ENXIO
)
1604 log_debug_errno(r
, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1606 saved_log_context_enabled
= r
> 0;
1608 return saved_log_context_enabled
;
1611 static LogContext
* log_context_attach(LogContext
*c
) {
1614 _log_context_num_fields
+= strv_length(c
->fields
);
1615 _log_context_num_fields
+= c
->n_input_iovec
;
1616 _log_context_num_fields
+= !!c
->key
;
1618 return LIST_PREPEND(ll
, _log_context
, c
);
1621 static LogContext
* log_context_detach(LogContext
*c
) {
1625 assert(_log_context_num_fields
>= strv_length(c
->fields
) + c
->n_input_iovec
+!!c
->key
);
1626 _log_context_num_fields
-= strv_length(c
->fields
);
1627 _log_context_num_fields
-= c
->n_input_iovec
;
1628 _log_context_num_fields
-= !!c
->key
;
1630 LIST_REMOVE(ll
, _log_context
, c
);
1634 LogContext
* log_context_new(const char *key
, const char *value
) {
1636 assert(endswith(key
, "="));
1639 LIST_FOREACH(ll
, i
, _log_context
)
1640 if (i
->key
== key
&& i
->value
== value
)
1641 return log_context_ref(i
);
1643 LogContext
*c
= new(LogContext
, 1);
1649 .key
= (char *) key
,
1650 .value
= (char *) value
,
1653 return log_context_attach(c
);
1656 LogContext
* log_context_new_strv(char **fields
, bool owned
) {
1660 LIST_FOREACH(ll
, i
, _log_context
)
1661 if (i
->fields
== fields
) {
1663 return log_context_ref(i
);
1666 LogContext
*c
= new(LogContext
, 1);
1676 return log_context_attach(c
);
1679 LogContext
* log_context_new_iov(struct iovec
*input_iovec
, size_t n_input_iovec
, bool owned
) {
1680 if (!input_iovec
|| n_input_iovec
== 0)
1683 LIST_FOREACH(ll
, i
, _log_context
)
1684 if (i
->input_iovec
== input_iovec
&& i
->n_input_iovec
== n_input_iovec
) {
1686 return log_context_ref(i
);
1689 LogContext
*c
= new(LogContext
, 1);
1695 .input_iovec
= input_iovec
,
1696 .n_input_iovec
= n_input_iovec
,
1700 return log_context_attach(c
);
1703 static LogContext
* log_context_free(LogContext
*c
) {
1707 log_context_detach(c
);
1710 strv_free(c
->fields
);
1711 iovec_array_free(c
->input_iovec
, c
->n_input_iovec
);
1719 DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext
, log_context
, log_context_free
);
1721 LogContext
* log_context_new_strv_consume(char **fields
) {
1722 LogContext
*c
= log_context_new_strv(fields
, /*owned=*/ true);
1729 LogContext
* log_context_new_iov_consume(struct iovec
*input_iovec
, size_t n_input_iovec
) {
1730 LogContext
*c
= log_context_new_iov(input_iovec
, n_input_iovec
, /*owned=*/ true);
1732 iovec_array_free(input_iovec
, n_input_iovec
);
1737 size_t log_context_num_contexts(void) {
1740 LIST_FOREACH(ll
, c
, _log_context
)
1746 size_t log_context_num_fields(void) {
1747 return _log_context_num_fields
;