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 128U
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
{
76 /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
77 * referenced by this is freed or not */
79 struct iovec
*input_iovec
;
82 LIST_FIELDS(struct LogContext
, ll
);
85 static thread_local
LIST_HEAD(LogContext
, _log_context
) = NULL
;
86 static thread_local
size_t _log_context_num_fields
= 0;
88 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
89 bool _log_message_dummy
= false; /* Always false */
92 /* An assert to use in logging functions that does not call recursively
93 * into our logging functions (since that might lead to a loop). */
94 #define assert_raw(expr) \
96 if (_unlikely_(!(expr))) { \
97 fputs(#expr "\n", stderr); \
102 static void log_close_console(void) {
103 console_fd
= safe_close_above_stdio(console_fd
);
106 static int log_open_console(void) {
108 if (!always_reopen_console
) {
109 console_fd
= STDERR_FILENO
;
113 if (console_fd
< 3) {
116 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
120 console_fd
= fd_move_above_stdio(fd
);
126 static void log_close_kmsg(void) {
127 kmsg_fd
= safe_close(kmsg_fd
);
130 static int log_open_kmsg(void) {
135 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
139 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
143 static void log_close_syslog(void) {
144 syslog_fd
= safe_close(syslog_fd
);
147 static int create_log_socket(int type
) {
151 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
155 fd
= fd_move_above_stdio(fd
);
156 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
158 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
159 * in the unlikely case of a deadlock. */
160 if (getpid_cached() == 1)
161 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
163 timeval_store(&tv
, 10 * USEC_PER_SEC
);
164 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
169 static int log_open_syslog(void) {
175 syslog_fd
= create_log_socket(SOCK_DGRAM
);
181 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
183 safe_close(syslog_fd
);
185 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
187 syslog_fd
= create_log_socket(SOCK_STREAM
);
193 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
197 syslog_is_stream
= true;
199 syslog_is_stream
= false;
208 static void log_close_journal(void) {
209 journal_fd
= safe_close(journal_fd
);
212 static int log_open_journal(void) {
218 journal_fd
= create_log_socket(SOCK_DGRAM
);
219 if (journal_fd
< 0) {
224 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
235 static bool stderr_is_journal(void) {
236 _cleanup_free_
char *w
= NULL
;
241 e
= getenv("JOURNAL_STREAM");
245 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
250 if (safe_atou64(w
, &dev
) < 0)
252 if (safe_atou64(e
, &ino
) < 0)
255 if (fstat(STDERR_FILENO
, &st
) < 0)
258 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
264 /* Do not call from library code. */
266 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
267 * so that a call to a logging function immediately following a log_open() call can still easily
268 * reference an error that happened immediately before the log_open() call. */
271 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
272 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
273 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
274 * because there is no reason to close it. */
276 if (log_target
== LOG_TARGET_NULL
) {
283 if (getpid_cached() == 1 ||
284 stderr_is_journal() ||
288 LOG_TARGET_JOURNAL_OR_KMSG
,
290 LOG_TARGET_SYSLOG_OR_KMSG
)) {
293 if (IN_SET(log_target
,
295 LOG_TARGET_JOURNAL_OR_KMSG
,
296 LOG_TARGET_JOURNAL
)) {
298 r
= log_open_journal();
306 if (IN_SET(log_target
,
307 LOG_TARGET_SYSLOG_OR_KMSG
,
308 LOG_TARGET_SYSLOG
)) {
310 r
= log_open_syslog();
319 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
320 LOG_TARGET_JOURNAL_OR_KMSG
,
321 LOG_TARGET_SYSLOG_OR_KMSG
,
336 return log_open_console();
339 void log_set_target(LogTarget target
) {
341 assert(target
< _LOG_TARGET_MAX
);
343 if (upgrade_syslog_to_journal
) {
344 if (target
== LOG_TARGET_SYSLOG
)
345 target
= LOG_TARGET_JOURNAL
;
346 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
347 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
353 void log_set_target_and_open(LogTarget target
) {
354 log_set_target(target
);
358 void log_close(void) {
359 /* Do not call from library code. */
367 void log_forget_fds(void) {
368 /* Do not call from library code. */
370 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
373 void log_set_max_level(int level
) {
374 assert(level
== LOG_NULL
|| (level
& LOG_PRIMASK
) == level
);
376 log_max_level
= level
;
379 void log_set_facility(int facility
) {
380 log_facility
= facility
;
383 static int write_to_console(
389 const char *buffer
) {
392 header_time
[FORMAT_TIMESTAMP_MAX
],
393 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
394 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
395 struct iovec iovec
[9];
396 const char *on
= NULL
, *off
= NULL
;
402 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
403 xsprintf(prefix
, "<%i>", level
);
404 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
408 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
409 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
410 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
414 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
415 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
418 if (log_get_show_color())
419 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
422 const char *lon
= "", *loff
= "";
423 if (log_get_show_color()) {
424 lon
= ansi_highlight_yellow4();
425 loff
= ansi_normal();
428 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
429 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
433 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
434 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
436 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
437 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
439 if (writev(console_fd
, iovec
, n
) < 0) {
441 if (errno
== EIO
&& getpid_cached() == 1) {
443 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
447 (void) log_open_console();
451 if (writev(console_fd
, iovec
, n
) < 0)
460 static int write_to_syslog(
466 const char *buffer
) {
468 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
470 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
477 xsprintf(header_priority
, "<%i>", level
);
479 t
= (time_t) (now(CLOCK_REALTIME
) / USEC_PER_SEC
);
480 if (!localtime_r(&t
, &tm
))
483 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
486 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
488 struct iovec iovec
[] = {
489 IOVEC_MAKE_STRING(header_priority
),
490 IOVEC_MAKE_STRING(header_time
),
491 IOVEC_MAKE_STRING(program_invocation_short_name
),
492 IOVEC_MAKE_STRING(header_pid
),
493 IOVEC_MAKE_STRING(buffer
),
495 const struct msghdr msghdr
= {
497 .msg_iovlen
= ELEMENTSOF(iovec
),
500 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
501 if (syslog_is_stream
)
502 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
507 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
511 if (!syslog_is_stream
)
514 if (IOVEC_INCREMENT(iovec
, ELEMENTSOF(iovec
), n
))
521 static int write_to_kmsg(
527 const char *buffer
) {
529 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
530 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
531 * where we log excessively, but not in a tight loop.
533 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
536 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
538 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
539 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
544 if (!ratelimit_below(&ratelimit
))
547 xsprintf(header_priority
, "<%i>", level
);
548 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
550 const struct iovec iovec
[] = {
551 IOVEC_MAKE_STRING(header_priority
),
552 IOVEC_MAKE_STRING(program_invocation_short_name
),
553 IOVEC_MAKE_STRING(header_pid
),
554 IOVEC_MAKE_STRING(buffer
),
555 IOVEC_MAKE_STRING("\n"),
558 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
564 static int log_do_header(
569 const char *file
, int line
, const char *func
,
570 const char *object_field
, const char *object
,
571 const char *extra_field
, const char *extra
) {
574 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
576 r
= snprintf(header
, size
,
578 "SYSLOG_FACILITY=%i\n"
580 "%s%.256s%s" /* CODE_FILE */
581 "%s%.*i%s" /* CODE_LINE */
582 "%s%.256s%s" /* CODE_FUNC */
583 "%s%.*i%s" /* ERRNO */
584 "%s%.256s%s" /* object */
585 "%s%.256s%s" /* extra */
586 "SYSLOG_IDENTIFIER=%.256s\n",
590 isempty(file
) ? "" : "CODE_FILE=",
591 isempty(file
) ? "" : file
,
592 isempty(file
) ? "" : "\n",
593 line
? "CODE_LINE=" : "",
594 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
596 isempty(func
) ? "" : "CODE_FUNC=",
597 isempty(func
) ? "" : func
,
598 isempty(func
) ? "" : "\n",
599 error
? "ERRNO=" : "",
600 error
? 1 : 0, error
,
602 isempty(object
) ? "" : object_field
,
603 isempty(object
) ? "" : object
,
604 isempty(object
) ? "" : "\n",
605 isempty(extra
) ? "" : extra_field
,
606 isempty(extra
) ? "" : extra
,
607 isempty(extra
) ? "" : "\n",
608 program_invocation_short_name
);
609 assert_raw((size_t) r
< size
);
614 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
618 LIST_FOREACH(ll
, c
, _log_context
) {
619 STRV_FOREACH(s
, c
->fields
) {
620 if (*n
+ 2 >= iovec_len
)
623 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
624 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
627 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
628 if (*n
+ 2 >= iovec_len
)
631 iovec
[(*n
)++] = c
->input_iovec
[i
];
632 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
637 static int write_to_journal(
643 const char *object_field
,
645 const char *extra_field
,
647 const char *buffer
) {
649 char header
[LINE_MAX
];
650 size_t n
= 0, iovec_len
;
656 iovec_len
= MIN(4 + _log_context_num_fields
* 2, IOVEC_MAX
);
657 iovec
= newa(struct iovec
, iovec_len
);
659 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
661 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
662 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
663 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
664 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
666 log_do_context(iovec
, iovec_len
, &n
);
668 const struct msghdr msghdr
= {
673 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
679 int log_dispatch_internal(
685 const char *object_field
,
687 const char *extra_field
,
693 if (log_target
== LOG_TARGET_NULL
)
694 return -ERRNO_VALUE(error
);
696 /* Patch in LOG_DAEMON facility if necessary */
697 if ((level
& LOG_FACMASK
) == 0)
698 level
|= log_facility
;
700 if (open_when_needed
)
707 buffer
+= strspn(buffer
, NEWLINE
);
712 if ((e
= strpbrk(buffer
, NEWLINE
)))
715 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
716 LOG_TARGET_JOURNAL_OR_KMSG
,
717 LOG_TARGET_JOURNAL
)) {
719 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
720 if (k
< 0 && k
!= -EAGAIN
)
724 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
725 LOG_TARGET_SYSLOG
)) {
727 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
728 if (k
< 0 && k
!= -EAGAIN
)
733 IN_SET(log_target
, LOG_TARGET_AUTO
,
734 LOG_TARGET_SYSLOG_OR_KMSG
,
735 LOG_TARGET_JOURNAL_OR_KMSG
,
741 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
744 (void) log_open_console();
749 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
754 if (open_when_needed
)
757 return -ERRNO_VALUE(error
);
760 int log_dump_internal(
770 /* This modifies the buffer... */
772 if (_likely_(LOG_PRI(level
) > log_max_level
))
773 return -ERRNO_VALUE(error
);
775 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
787 if (_likely_(LOG_PRI(level
) > log_max_level
))
788 return -ERRNO_VALUE(error
);
790 /* Make sure that %m maps to the specified error (or "Success"). */
791 char buffer
[LINE_MAX
];
792 LOCAL_ERRNO(ERRNO_VALUE(error
));
794 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
796 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
805 const char *format
, ...) {
810 va_start(ap
, format
);
811 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
817 int log_object_internalv(
823 const char *object_field
,
825 const char *extra_field
,
832 if (_likely_(LOG_PRI(level
) > log_max_level
))
833 return -ERRNO_VALUE(error
);
835 /* Make sure that %m maps to the specified error (or "Success"). */
836 LOCAL_ERRNO(ERRNO_VALUE(error
));
838 /* Prepend the object name before the message */
843 buffer
= newa(char, n
+ 2 + LINE_MAX
);
844 b
= stpcpy(stpcpy(buffer
, object
), ": ");
846 b
= buffer
= newa(char, LINE_MAX
);
848 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
850 return log_dispatch_internal(level
, error
, file
, line
, func
,
851 object_field
, object
, extra_field
, extra
, buffer
);
854 int log_object_internal(
860 const char *object_field
,
862 const char *extra_field
,
864 const char *format
, ...) {
869 va_start(ap
, format
);
870 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
876 static void log_assert(
882 const char *format
) {
884 static char buffer
[LINE_MAX
];
886 if (_likely_(LOG_PRI(level
) > log_max_level
))
889 DISABLE_WARNING_FORMAT_NONLITERAL
;
890 (void) snprintf(buffer
, sizeof buffer
, format
, text
, file
, line
, func
);
893 log_abort_msg
= buffer
;
895 log_dispatch_internal(level
, 0, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
898 _noreturn_
void log_assert_failed(
903 log_assert(LOG_CRIT
, text
, file
, line
, func
,
904 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
908 _noreturn_
void log_assert_failed_unreachable(
912 log_assert(LOG_CRIT
, "Code should not be reached", file
, line
, func
,
913 "%s at %s:%u, function %s(). Aborting. 💥");
917 void log_assert_failed_return(
923 log_assert(LOG_DEBUG
, text
, file
, line
, func
,
924 "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
927 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
928 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
931 int log_format_iovec(
935 bool newline_separator
,
940 static const char nl
= '\n';
942 while (format
&& *n
+ 1 < iovec_len
) {
947 /* We need to copy the va_list structure,
948 * since vasprintf() leaves it afterwards at
949 * an undefined location */
951 errno
= ERRNO_VALUE(error
);
954 r
= vasprintf(&m
, format
, aq
);
959 /* Now, jump enough ahead, so that we point to
960 * the next format string */
961 VA_FORMAT_ADVANCE(format
, ap
);
963 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
964 if (newline_separator
)
965 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
967 format
= va_arg(ap
, char *);
972 int log_struct_internal(
978 const char *format
, ...) {
985 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
986 log_target
== LOG_TARGET_NULL
)
987 return -ERRNO_VALUE(error
);
989 if ((level
& LOG_FACMASK
) == 0)
990 level
|= log_facility
;
992 if (IN_SET(log_target
,
994 LOG_TARGET_JOURNAL_OR_KMSG
,
995 LOG_TARGET_JOURNAL
)) {
997 if (open_when_needed
)
1000 if (journal_fd
>= 0) {
1001 char header
[LINE_MAX
];
1002 struct iovec
*iovec
;
1003 size_t n
= 0, m
, iovec_len
;
1005 bool fallback
= false;
1007 iovec_len
= MIN(17 + _log_context_num_fields
* 2, IOVEC_MAX
);
1008 iovec
= newa(struct iovec
, iovec_len
);
1010 /* If the journal is available do structured logging.
1011 * Do not report the errno if it is synthetic. */
1012 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1013 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1015 va_start(ap
, format
);
1016 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1021 log_do_context(iovec
, iovec_len
, &n
);
1023 const struct msghdr msghdr
= {
1028 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1032 for (size_t i
= 1; i
< m
; i
+= 2)
1033 free(iovec
[i
].iov_base
);
1036 if (open_when_needed
)
1039 return -ERRNO_VALUE(error
);
1044 /* Fallback if journal logging is not available or didn't work. */
1046 va_start(ap
, format
);
1050 errno
= ERRNO_VALUE(error
);
1053 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1056 if (startswith(buf
, "MESSAGE=")) {
1061 VA_FORMAT_ADVANCE(format
, ap
);
1063 format
= va_arg(ap
, char *);
1068 if (open_when_needed
)
1071 return -ERRNO_VALUE(error
);
1074 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1077 int log_struct_iovec_internal(
1083 const struct iovec input_iovec
[],
1084 size_t n_input_iovec
) {
1088 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1089 log_target
== LOG_TARGET_NULL
)
1090 return -ERRNO_VALUE(error
);
1092 if ((level
& LOG_FACMASK
) == 0)
1093 level
|= log_facility
;
1095 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1096 LOG_TARGET_JOURNAL_OR_KMSG
,
1097 LOG_TARGET_JOURNAL
) &&
1100 char header
[LINE_MAX
];
1101 struct iovec
*iovec
;
1102 size_t n
= 0, iovec_len
;
1104 iovec_len
= MIN(1 + n_input_iovec
* 2 + _log_context_num_fields
* 2, IOVEC_MAX
);
1105 iovec
= newa(struct iovec
, iovec_len
);
1107 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1109 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1110 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1111 iovec
[n
++] = input_iovec
[i
];
1112 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1115 log_do_context(iovec
, iovec_len
, &n
);
1117 const struct msghdr msghdr
= {
1122 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1123 return -ERRNO_VALUE(error
);
1126 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1127 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1130 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1131 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1133 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1136 /* Couldn't find MESSAGE=. */
1137 return -ERRNO_VALUE(error
);
1140 int log_set_target_from_string(const char *e
) {
1143 t
= log_target_from_string(e
);
1151 int log_set_max_level_from_string(const char *e
) {
1154 t
= log_level_from_string(e
);
1158 log_set_max_level(t
);
1162 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1165 * The systemd.log_xyz= settings are parsed by all tools, and
1168 * However, "quiet" is only parsed by PID 1, and only turns of
1169 * status output to /dev/console, but does not alter the log
1173 if (streq(key
, "debug") && !value
)
1174 log_set_max_level(LOG_DEBUG
);
1176 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1178 if (proc_cmdline_value_missing(key
, value
))
1181 if (log_set_target_from_string(value
) < 0)
1182 log_warning("Failed to parse log target '%s'. Ignoring.", value
);
1184 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1186 if (proc_cmdline_value_missing(key
, value
))
1189 if (log_set_max_level_from_string(value
) < 0)
1190 log_warning("Failed to parse log level '%s'. Ignoring.", value
);
1192 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1194 if (log_show_color_from_string(value
?: "1") < 0)
1195 log_warning("Failed to parse log color setting '%s'. Ignoring.", value
);
1197 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1199 if (log_show_location_from_string(value
?: "1") < 0)
1200 log_warning("Failed to parse log location setting '%s'. Ignoring.", value
);
1202 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1204 if (log_show_tid_from_string(value
?: "1") < 0)
1205 log_warning("Failed to parse log tid setting '%s'. Ignoring.", value
);
1207 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1209 if (log_show_time_from_string(value
?: "1") < 0)
1210 log_warning("Failed to parse log time setting '%s'. Ignoring.", value
);
1217 static bool should_parse_proc_cmdline(void) {
1218 /* PID1 always reads the kernel command line. */
1219 if (getpid_cached() == 1)
1222 /* Otherwise, parse the commandline if invoked directly by systemd. */
1223 return invoked_by_systemd();
1226 void log_parse_environment_variables(void) {
1229 e
= getenv("SYSTEMD_LOG_TARGET");
1230 if (e
&& log_set_target_from_string(e
) < 0)
1231 log_warning("Failed to parse log target '%s'. Ignoring.", e
);
1233 e
= getenv("SYSTEMD_LOG_LEVEL");
1234 if (e
&& log_set_max_level_from_string(e
) < 0)
1235 log_warning("Failed to parse log level '%s'. Ignoring.", e
);
1237 e
= getenv("SYSTEMD_LOG_COLOR");
1238 if (e
&& log_show_color_from_string(e
) < 0)
1239 log_warning("Failed to parse log color '%s'. Ignoring.", e
);
1241 e
= getenv("SYSTEMD_LOG_LOCATION");
1242 if (e
&& log_show_location_from_string(e
) < 0)
1243 log_warning("Failed to parse log location '%s'. Ignoring.", e
);
1245 e
= getenv("SYSTEMD_LOG_TIME");
1246 if (e
&& log_show_time_from_string(e
) < 0)
1247 log_warning("Failed to parse log time '%s'. Ignoring.", e
);
1249 e
= getenv("SYSTEMD_LOG_TID");
1250 if (e
&& log_show_tid_from_string(e
) < 0)
1251 log_warning("Failed to parse log tid '%s'. Ignoring.", e
);
1254 void log_parse_environment(void) {
1255 /* Do not call from library code. */
1257 if (should_parse_proc_cmdline())
1258 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1260 log_parse_environment_variables();
1263 LogTarget
log_get_target(void) {
1267 int log_get_max_level(void) {
1268 return log_max_level
;
1271 void log_show_color(bool b
) {
1275 bool log_get_show_color(void) {
1276 return show_color
> 0; /* Defaults to false. */
1279 void log_show_location(bool b
) {
1283 bool log_get_show_location(void) {
1284 return show_location
;
1287 void log_show_time(bool b
) {
1291 bool log_get_show_time(void) {
1295 void log_show_tid(bool b
) {
1299 bool log_get_show_tid(void) {
1303 int log_show_color_from_string(const char *e
) {
1306 t
= parse_boolean(e
);
1314 int log_show_location_from_string(const char *e
) {
1317 t
= parse_boolean(e
);
1321 log_show_location(t
);
1325 int log_show_time_from_string(const char *e
) {
1328 t
= parse_boolean(e
);
1336 int log_show_tid_from_string(const char *e
) {
1339 t
= parse_boolean(e
);
1347 bool log_on_console(void) {
1348 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1349 LOG_TARGET_CONSOLE_PREFIXED
))
1352 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1355 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1356 [LOG_TARGET_CONSOLE
] = "console",
1357 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1358 [LOG_TARGET_KMSG
] = "kmsg",
1359 [LOG_TARGET_JOURNAL
] = "journal",
1360 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1361 [LOG_TARGET_SYSLOG
] = "syslog",
1362 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1363 [LOG_TARGET_AUTO
] = "auto",
1364 [LOG_TARGET_NULL
] = "null",
1367 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1369 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1372 if (pid_is_valid(si
->ssi_pid
)) {
1373 _cleanup_free_
char *p
= NULL
;
1375 (void) get_process_comm(si
->ssi_pid
, &p
);
1378 "Received SIG%s from PID %"PRIu32
" (%s).",
1379 signal_to_string(si
->ssi_signo
),
1380 si
->ssi_pid
, strna(p
));
1384 signal_to_string(si
->ssi_signo
));
1387 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1388 assert(!log_syntax_callback
|| !cb
);
1389 assert(!log_syntax_callback_userdata
|| !userdata
);
1391 log_syntax_callback
= cb
;
1392 log_syntax_callback_userdata
= userdata
;
1395 int log_syntax_internal(
1398 const char *config_file
,
1399 unsigned config_line
,
1404 const char *format
, ...) {
1408 if (log_syntax_callback
)
1409 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1411 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1412 log_target
== LOG_TARGET_NULL
)
1413 return -ERRNO_VALUE(error
);
1415 char buffer
[LINE_MAX
];
1417 const char *unit_fmt
= NULL
;
1419 errno
= ERRNO_VALUE(error
);
1421 va_start(ap
, format
);
1422 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1426 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1429 if (config_line
> 0)
1430 return log_struct_internal(
1434 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1435 "CONFIG_FILE=%s", config_file
,
1436 "CONFIG_LINE=%u", config_line
,
1437 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1441 return log_struct_internal(
1445 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1446 "CONFIG_FILE=%s", config_file
,
1447 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1451 return log_struct_internal(
1455 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1456 LOG_MESSAGE("%s: %s", unit
, buffer
),
1460 return log_struct_internal(
1464 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
1465 LOG_MESSAGE("%s", buffer
),
1469 int log_syntax_invalid_utf8_internal(
1472 const char *config_file
,
1473 unsigned config_line
,
1477 const char *rvalue
) {
1479 _cleanup_free_
char *p
= NULL
;
1482 p
= utf8_escape_invalid(rvalue
);
1484 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1485 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1486 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1489 void log_set_upgrade_syslog_to_journal(bool b
) {
1490 upgrade_syslog_to_journal
= b
;
1492 /* Make the change effective immediately */
1494 if (log_target
== LOG_TARGET_SYSLOG
)
1495 log_target
= LOG_TARGET_JOURNAL
;
1496 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1497 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1501 void log_set_always_reopen_console(bool b
) {
1502 always_reopen_console
= b
;
1505 void log_set_open_when_needed(bool b
) {
1506 open_when_needed
= b
;
1509 void log_set_prohibit_ipc(bool b
) {
1513 int log_emergency_level(void) {
1514 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1515 * then the system of the whole system is obviously affected. */
1517 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1520 int log_dup_console(void) {
1523 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1524 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1526 if (console_fd
< 0 || console_fd
>= 3)
1529 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1537 void log_setup(void) {
1538 log_set_target(LOG_TARGET_AUTO
);
1539 log_parse_environment();
1541 if (log_on_console() && show_color
< 0)
1542 log_show_color(true);
1545 static int saved_log_context_enabled
= -1;
1547 bool log_context_enabled(void) {
1550 if (log_get_max_level() == LOG_DEBUG
)
1553 if (saved_log_context_enabled
>= 0)
1554 return saved_log_context_enabled
;
1556 r
= getenv_bool_secure("SYSTEMD_ENABLE_LOG_CONTEXT");
1557 if (r
< 0 && r
!= -ENXIO
)
1558 log_debug_errno(r
, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1560 saved_log_context_enabled
= r
> 0;
1562 return saved_log_context_enabled
;
1565 LogContext
* log_context_attach(LogContext
*c
) {
1568 _log_context_num_fields
+= strv_length(c
->fields
);
1569 _log_context_num_fields
+= c
->n_input_iovec
;
1571 return LIST_PREPEND(ll
, _log_context
, c
);
1574 LogContext
* log_context_detach(LogContext
*c
) {
1578 assert(_log_context_num_fields
>= strv_length(c
->fields
) + c
->n_input_iovec
);
1579 _log_context_num_fields
-= strv_length(c
->fields
);
1580 _log_context_num_fields
-= c
->n_input_iovec
;
1582 LIST_REMOVE(ll
, _log_context
, c
);
1586 LogContext
* log_context_new(char **fields
, bool owned
) {
1587 LogContext
*c
= new(LogContext
, 1);
1596 return log_context_attach(c
);
1599 LogContext
* log_context_newv(struct iovec
*input_iovec
, size_t n_input_iovec
, bool owned
) {
1600 if (!input_iovec
|| n_input_iovec
== 0)
1601 return NULL
; /* Nothing to do */
1603 LogContext
*c
= new(LogContext
, 1);
1608 .input_iovec
= input_iovec
,
1609 .n_input_iovec
= n_input_iovec
,
1613 return log_context_attach(c
);
1616 LogContext
* log_context_free(LogContext
*c
) {
1620 log_context_detach(c
);
1623 strv_free(c
->fields
);
1624 iovec_array_free(c
->input_iovec
, c
->n_input_iovec
);
1630 LogContext
* log_context_new_consume(char **fields
) {
1631 LogContext
*c
= log_context_new(fields
, /*owned=*/ true);
1638 LogContext
* log_context_new_consumev(struct iovec
*input_iovec
, size_t n_input_iovec
) {
1639 LogContext
*c
= log_context_newv(input_iovec
, n_input_iovec
, /*owned=*/ true);
1641 iovec_array_free(input_iovec
, n_input_iovec
);
1646 size_t log_context_num_contexts(void) {
1649 LIST_FOREACH(ll
, c
, _log_context
)
1655 size_t log_context_num_fields(void) {
1656 return _log_context_num_fields
;