]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/log.c
Merge pull request #31670 from CodethinkLabs/vmspawn/generate_ssh_keys
[thirdparty/systemd.git] / src / basic / log.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <inttypes.h>
6 #include <limits.h>
7 #include <stdarg.h>
8 #include <stddef.h>
9 #include <sys/signalfd.h>
10 #include <sys/stat.h>
11 #include <sys/time.h>
12 #include <sys/uio.h>
13 #include <sys/un.h>
14 #include <unistd.h>
15
16 #include "sd-messages.h"
17
18 #include "alloc-util.h"
19 #include "argv-util.h"
20 #include "env-util.h"
21 #include "errno-util.h"
22 #include "fd-util.h"
23 #include "format-util.h"
24 #include "iovec-util.h"
25 #include "log.h"
26 #include "macro.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"
38 #include "strv.h"
39 #include "syslog-util.h"
40 #include "terminal-util.h"
41 #include "time-util.h"
42 #include "utf8.h"
43
44 #define SNDBUF_SIZE (8*1024*1024)
45 #define IOVEC_MAX 256U
46
47 static log_syntax_callback_t log_syntax_callback = NULL;
48 static void *log_syntax_callback_userdata = NULL;
49
50 static LogTarget log_target = LOG_TARGET_CONSOLE;
51 static int log_max_level = LOG_INFO;
52 static int log_target_max_level[] = {
53 [LOG_TARGET_CONSOLE] = INT_MAX,
54 [LOG_TARGET_KMSG] = INT_MAX,
55 [LOG_TARGET_SYSLOG] = INT_MAX,
56 [LOG_TARGET_JOURNAL] = INT_MAX,
57 };
58 static int log_facility = LOG_DAEMON;
59 static bool ratelimit_kmsg = true;
60
61 static int console_fd = STDERR_FILENO;
62 static int console_fd_is_tty = -1; /* tri-state: -1 means don't know */
63 static int syslog_fd = -EBADF;
64 static int kmsg_fd = -EBADF;
65 static int journal_fd = -EBADF;
66
67 static bool syslog_is_stream = false;
68
69 static int show_color = -1; /* tristate */
70 static bool show_location = false;
71 static bool show_time = false;
72 static bool show_tid = false;
73
74 static bool upgrade_syslog_to_journal = false;
75 static bool always_reopen_console = false;
76 static bool open_when_needed = false;
77 static bool prohibit_ipc = false;
78 static bool assert_return_is_critical = BUILD_MODE_DEVELOPER;
79
80 /* Akin to glibc's __abort_msg; which is private and we hence cannot
81 * use here. */
82 static char *log_abort_msg = NULL;
83
84 typedef struct LogContext {
85 unsigned n_ref;
86 /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
87 * referenced by this is freed or not */
88 char **fields;
89 struct iovec *input_iovec;
90 size_t n_input_iovec;
91 char *key;
92 char *value;
93 bool owned;
94 LIST_FIELDS(struct LogContext, ll);
95 } LogContext;
96
97 static thread_local LIST_HEAD(LogContext, _log_context) = NULL;
98 static thread_local size_t _log_context_num_fields = 0;
99
100 static thread_local const char *log_prefix = NULL;
101
102 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
103 bool _log_message_dummy = false; /* Always false */
104 #endif
105
106 /* An assert to use in logging functions that does not call recursively
107 * into our logging functions (since that might lead to a loop). */
108 #define assert_raw(expr) \
109 do { \
110 if (_unlikely_(!(expr))) { \
111 fputs(#expr "\n", stderr); \
112 abort(); \
113 } \
114 } while (false)
115
116 static void log_close_console(void) {
117 /* See comment in log_close_journal() */
118 (void) safe_close_above_stdio(TAKE_FD(console_fd));
119 console_fd_is_tty = -1;
120 }
121
122 static int log_open_console(void) {
123
124 if (!always_reopen_console) {
125 console_fd = STDERR_FILENO;
126 console_fd_is_tty = -1;
127 return 0;
128 }
129
130 if (console_fd < 3) {
131 int fd;
132
133 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
134 if (fd < 0)
135 return fd;
136
137 console_fd = fd_move_above_stdio(fd);
138 console_fd_is_tty = true;
139 }
140
141 return 0;
142 }
143
144 static void log_close_kmsg(void) {
145 /* See comment in log_close_journal() */
146 (void) safe_close(TAKE_FD(kmsg_fd));
147 }
148
149 static int log_open_kmsg(void) {
150
151 if (kmsg_fd >= 0)
152 return 0;
153
154 kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
155 if (kmsg_fd < 0)
156 return -errno;
157
158 kmsg_fd = fd_move_above_stdio(kmsg_fd);
159 return 0;
160 }
161
162 static void log_close_syslog(void) {
163 /* See comment in log_close_journal() */
164 (void) safe_close(TAKE_FD(syslog_fd));
165 }
166
167 static int create_log_socket(int type) {
168 struct timeval tv;
169 int fd;
170
171 fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
172 if (fd < 0)
173 return -errno;
174
175 fd = fd_move_above_stdio(fd);
176 (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
177
178 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
179 * in the unlikely case of a deadlock. */
180 if (getpid_cached() == 1)
181 timeval_store(&tv, 10 * USEC_PER_MSEC);
182 else
183 timeval_store(&tv, 10 * USEC_PER_SEC);
184 (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
185
186 return fd;
187 }
188
189 static int log_open_syslog(void) {
190 int r;
191
192 if (syslog_fd >= 0)
193 return 0;
194
195 syslog_fd = create_log_socket(SOCK_DGRAM);
196 if (syslog_fd < 0) {
197 r = syslog_fd;
198 goto fail;
199 }
200
201 r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
202 if (r < 0) {
203 safe_close(syslog_fd);
204
205 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
206 * we do... */
207 syslog_fd = create_log_socket(SOCK_STREAM);
208 if (syslog_fd < 0) {
209 r = syslog_fd;
210 goto fail;
211 }
212
213 r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
214 if (r < 0)
215 goto fail;
216
217 syslog_is_stream = true;
218 } else
219 syslog_is_stream = false;
220
221 return 0;
222
223 fail:
224 log_close_syslog();
225 return r;
226 }
227
228 static void log_close_journal(void) {
229 /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
230 * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
231 * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
232 * stack. */
233 (void) safe_close(TAKE_FD(journal_fd));
234 }
235
236 static int log_open_journal(void) {
237 int r;
238
239 if (journal_fd >= 0)
240 return 0;
241
242 journal_fd = create_log_socket(SOCK_DGRAM);
243 if (journal_fd < 0) {
244 r = journal_fd;
245 goto fail;
246 }
247
248 r = connect_unix_path(journal_fd, AT_FDCWD, "/run/systemd/journal/socket");
249 if (r < 0)
250 goto fail;
251
252 return 0;
253
254 fail:
255 log_close_journal();
256 return r;
257 }
258
259 static bool stderr_is_journal(void) {
260 _cleanup_free_ char *w = NULL;
261 const char *e;
262 uint64_t dev, ino;
263 struct stat st;
264
265 e = getenv("JOURNAL_STREAM");
266 if (!e)
267 return false;
268
269 if (extract_first_word(&e, &w, ":", EXTRACT_DONT_COALESCE_SEPARATORS) <= 0)
270 return false;
271 if (!e)
272 return false;
273
274 if (safe_atou64(w, &dev) < 0)
275 return false;
276 if (safe_atou64(e, &ino) < 0)
277 return false;
278
279 if (fstat(STDERR_FILENO, &st) < 0)
280 return false;
281
282 return st.st_dev == dev && st.st_ino == ino;
283 }
284
285 int log_open(void) {
286 int r;
287
288 /* Do not call from library code. */
289
290 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
291 * so that a call to a logging function immediately following a log_open() call can still easily
292 * reference an error that happened immediately before the log_open() call. */
293 PROTECT_ERRNO;
294
295 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
296 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
297 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
298 * because there is no reason to close it. */
299
300 if (log_target == LOG_TARGET_NULL) {
301 log_close_journal();
302 log_close_syslog();
303 log_close_console();
304 return 0;
305 }
306
307 if (getpid_cached() == 1 ||
308 stderr_is_journal() ||
309 IN_SET(log_target,
310 LOG_TARGET_KMSG,
311 LOG_TARGET_JOURNAL,
312 LOG_TARGET_JOURNAL_OR_KMSG,
313 LOG_TARGET_SYSLOG,
314 LOG_TARGET_SYSLOG_OR_KMSG)) {
315
316 if (!prohibit_ipc) {
317 if (IN_SET(log_target,
318 LOG_TARGET_AUTO,
319 LOG_TARGET_JOURNAL_OR_KMSG,
320 LOG_TARGET_JOURNAL)) {
321
322 r = log_open_journal();
323 if (r >= 0) {
324 log_close_syslog();
325 log_close_console();
326 return r;
327 }
328 }
329
330 if (IN_SET(log_target,
331 LOG_TARGET_SYSLOG_OR_KMSG,
332 LOG_TARGET_SYSLOG)) {
333
334 r = log_open_syslog();
335 if (r >= 0) {
336 log_close_journal();
337 log_close_console();
338 return r;
339 }
340 }
341 }
342
343 if (IN_SET(log_target, LOG_TARGET_AUTO,
344 LOG_TARGET_JOURNAL_OR_KMSG,
345 LOG_TARGET_SYSLOG_OR_KMSG,
346 LOG_TARGET_KMSG)) {
347 r = log_open_kmsg();
348 if (r >= 0) {
349 log_close_journal();
350 log_close_syslog();
351 log_close_console();
352 return r;
353 }
354 }
355 }
356
357 log_close_journal();
358 log_close_syslog();
359
360 return log_open_console();
361 }
362
363 void log_set_target(LogTarget target) {
364 assert(target >= 0);
365 assert(target < _LOG_TARGET_MAX);
366
367 if (upgrade_syslog_to_journal) {
368 if (target == LOG_TARGET_SYSLOG)
369 target = LOG_TARGET_JOURNAL;
370 else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
371 target = LOG_TARGET_JOURNAL_OR_KMSG;
372 }
373
374 log_target = target;
375 }
376
377 void log_set_target_and_open(LogTarget target) {
378 log_set_target(target);
379 log_open();
380 }
381
382 void log_close(void) {
383 /* Do not call from library code. */
384
385 log_close_journal();
386 log_close_syslog();
387 log_close_kmsg();
388 log_close_console();
389 }
390
391 void log_forget_fds(void) {
392 /* Do not call from library code. */
393
394 console_fd = kmsg_fd = syslog_fd = journal_fd = -EBADF;
395 console_fd_is_tty = -1;
396 }
397
398 void log_set_max_level(int level) {
399 assert(level == LOG_NULL || (level & LOG_PRIMASK) == level);
400
401 log_max_level = level;
402
403 /* Also propagate max log level to libc's syslog(), just in case some other component loaded into our
404 * process logs directly via syslog(). You might wonder why we maintain our own log level variable if
405 * libc has the same functionality. This has multiple reasons, first and foremost that we want to
406 * apply this to all our log targets, not just syslog and console. Moreover, we cannot query the
407 * current log mask from glibc without changing it, but that's useful for testing the current log
408 * level before even entering the log functions like we do in our macros. */
409 setlogmask(LOG_UPTO(level));
410
411 /* Ensure that our own LOG_NULL define maps sanely to the log mask */
412 assert_cc(LOG_UPTO(LOG_NULL) == 0);
413 }
414
415 void log_set_facility(int facility) {
416 log_facility = facility;
417 }
418
419 static bool check_console_fd_is_tty(void) {
420 if (console_fd < 0)
421 return false;
422
423 if (console_fd_is_tty < 0)
424 console_fd_is_tty = isatty_safe(console_fd);
425
426 return console_fd_is_tty;
427 }
428
429 static int write_to_console(
430 int level,
431 int error,
432 const char *file,
433 int line,
434 const char *func,
435 const char *buffer) {
436
437 char location[256],
438 header_time[FORMAT_TIMESTAMP_MAX],
439 prefix[1 + DECIMAL_STR_MAX(int) + 2],
440 tid_string[3 + DECIMAL_STR_MAX(pid_t) + 1];
441 struct iovec iovec[11];
442 const char *on = NULL, *off = NULL;
443 size_t n = 0;
444
445 if (console_fd < 0)
446 return 0;
447
448 if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_CONSOLE])
449 return 0;
450
451 if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
452 xsprintf(prefix, "<%i>", level);
453 iovec[n++] = IOVEC_MAKE_STRING(prefix);
454 }
455
456 if (show_time &&
457 format_timestamp(header_time, sizeof(header_time), now(CLOCK_REALTIME))) {
458 iovec[n++] = IOVEC_MAKE_STRING(header_time);
459 iovec[n++] = IOVEC_MAKE_STRING(" ");
460 }
461
462 if (show_tid) {
463 xsprintf(tid_string, "(" PID_FMT ") ", gettid());
464 iovec[n++] = IOVEC_MAKE_STRING(tid_string);
465 }
466
467 if (log_get_show_color())
468 get_log_colors(LOG_PRI(level), &on, &off, NULL);
469
470 if (show_location) {
471 const char *lon = "", *loff = "";
472 if (log_get_show_color()) {
473 lon = ansi_highlight_yellow4();
474 loff = ansi_normal();
475 }
476
477 (void) snprintf(location, sizeof location, "%s%s:%i%s: ", lon, file, line, loff);
478 iovec[n++] = IOVEC_MAKE_STRING(location);
479 }
480
481 if (on)
482 iovec[n++] = IOVEC_MAKE_STRING(on);
483 if (log_prefix) {
484 iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
485 iovec[n++] = IOVEC_MAKE_STRING(": ");
486 }
487 iovec[n++] = IOVEC_MAKE_STRING(buffer);
488 if (off)
489 iovec[n++] = IOVEC_MAKE_STRING(off);
490
491 /* When writing to a TTY we output an extra '\r' (i.e. CR) first, to generate CRNL rather than just
492 * NL. This is a robustness thing in case the TTY is currently in raw mode (specifically: has the
493 * ONLCR flag off). We want that subsequent output definitely starts at the beginning of the line
494 * again, after all. If the TTY is not in raw mode the extra CR should not hurt. */
495 iovec[n++] = IOVEC_MAKE_STRING(check_console_fd_is_tty() ? "\r\n" : "\n");
496
497 if (writev(console_fd, iovec, n) < 0) {
498
499 if (errno == EIO && getpid_cached() == 1) {
500
501 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
502 * to reconnect. */
503
504 log_close_console();
505 (void) log_open_console();
506 if (console_fd < 0)
507 return 0;
508
509 if (writev(console_fd, iovec, n) < 0)
510 return -errno;
511 } else
512 return -errno;
513 }
514
515 return 1;
516 }
517
518 static int write_to_syslog(
519 int level,
520 int error,
521 const char *file,
522 int line,
523 const char *func,
524 const char *buffer) {
525
526 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
527 header_time[64],
528 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
529 time_t t;
530 struct tm tm;
531
532 if (syslog_fd < 0)
533 return 0;
534
535 if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_SYSLOG])
536 return 0;
537
538 xsprintf(header_priority, "<%i>", level);
539
540 t = (time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC);
541 if (!localtime_r(&t, &tm))
542 return -EINVAL;
543
544 if (strftime(header_time, sizeof(header_time), "%h %e %T ", &tm) <= 0)
545 return -EINVAL;
546
547 xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
548
549 struct iovec iovec[] = {
550 IOVEC_MAKE_STRING(header_priority),
551 IOVEC_MAKE_STRING(header_time),
552 IOVEC_MAKE_STRING(program_invocation_short_name),
553 IOVEC_MAKE_STRING(header_pid),
554 IOVEC_MAKE_STRING(strempty(log_prefix)),
555 IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
556 IOVEC_MAKE_STRING(buffer),
557 };
558 const struct msghdr msghdr = {
559 .msg_iov = iovec,
560 .msg_iovlen = ELEMENTSOF(iovec),
561 };
562
563 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
564 if (syslog_is_stream)
565 iovec[ELEMENTSOF(iovec) - 1].iov_len++;
566
567 for (;;) {
568 ssize_t n;
569
570 n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
571 if (n < 0)
572 return -errno;
573
574 if (!syslog_is_stream)
575 break;
576
577 if (iovec_increment(iovec, ELEMENTSOF(iovec), n))
578 break;
579 }
580
581 return 1;
582 }
583
584 static int write_to_kmsg(
585 int level,
586 int error,
587 const char *file,
588 int line,
589 const char *func,
590 const char *buffer) {
591
592 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
593 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
594 * where we log excessively, but not in a tight loop.
595 *
596 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
597 * loggers.
598 */
599 static thread_local RateLimit ratelimit = { 5 * USEC_PER_SEC, 200 };
600
601 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
602 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
603
604 if (kmsg_fd < 0)
605 return 0;
606
607 if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_KMSG])
608 return 0;
609
610 if (ratelimit_kmsg && !ratelimit_below(&ratelimit)) {
611 if (ratelimit_num_dropped(&ratelimit) > 1)
612 return 0;
613
614 buffer = "Too many messages being logged to kmsg, ignoring";
615 }
616
617 xsprintf(header_priority, "<%i>", level);
618 xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
619
620 const struct iovec iovec[] = {
621 IOVEC_MAKE_STRING(header_priority),
622 IOVEC_MAKE_STRING(program_invocation_short_name),
623 IOVEC_MAKE_STRING(header_pid),
624 IOVEC_MAKE_STRING(strempty(log_prefix)),
625 IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
626 IOVEC_MAKE_STRING(buffer),
627 IOVEC_MAKE_STRING("\n"),
628 };
629
630 if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
631 return -errno;
632
633 return 1;
634 }
635
636 static int log_do_header(
637 char *header,
638 size_t size,
639 int level,
640 int error,
641 const char *file, int line, const char *func,
642 const char *object_field, const char *object,
643 const char *extra_field, const char *extra) {
644 int r;
645
646 error = IS_SYNTHETIC_ERRNO(error) ? 0 : ERRNO_VALUE(error);
647
648 r = snprintf(header, size,
649 "PRIORITY=%i\n"
650 "SYSLOG_FACILITY=%i\n"
651 "TID=" PID_FMT "\n"
652 "%s%.256s%s" /* CODE_FILE */
653 "%s%.*i%s" /* CODE_LINE */
654 "%s%.256s%s" /* CODE_FUNC */
655 "%s%.*i%s" /* ERRNO */
656 "%s%.256s%s" /* object */
657 "%s%.256s%s" /* extra */
658 "SYSLOG_IDENTIFIER=%.256s\n",
659 LOG_PRI(level),
660 LOG_FAC(level),
661 gettid(),
662 isempty(file) ? "" : "CODE_FILE=",
663 isempty(file) ? "" : file,
664 isempty(file) ? "" : "\n",
665 line ? "CODE_LINE=" : "",
666 line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
667 line ? "\n" : "",
668 isempty(func) ? "" : "CODE_FUNC=",
669 isempty(func) ? "" : func,
670 isempty(func) ? "" : "\n",
671 error ? "ERRNO=" : "",
672 error ? 1 : 0, error,
673 error ? "\n" : "",
674 isempty(object) ? "" : object_field,
675 isempty(object) ? "" : object,
676 isempty(object) ? "" : "\n",
677 isempty(extra) ? "" : extra_field,
678 isempty(extra) ? "" : extra,
679 isempty(extra) ? "" : "\n",
680 program_invocation_short_name);
681 assert_raw((size_t) r < size);
682
683 return 0;
684 }
685
686 static void log_do_context(struct iovec *iovec, size_t iovec_len, size_t *n) {
687 assert(iovec);
688 assert(n);
689
690 LIST_FOREACH(ll, c, _log_context) {
691 STRV_FOREACH(s, c->fields) {
692 if (*n + 2 >= iovec_len)
693 return;
694
695 iovec[(*n)++] = IOVEC_MAKE_STRING(*s);
696 iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
697 }
698
699 for (size_t i = 0; i < c->n_input_iovec; i++) {
700 if (*n + 2 >= iovec_len)
701 return;
702
703 iovec[(*n)++] = c->input_iovec[i];
704 iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
705 }
706
707 if (c->key && c->value) {
708 if (*n + 3 >= iovec_len)
709 return;
710
711 iovec[(*n)++] = IOVEC_MAKE_STRING(c->key);
712 iovec[(*n)++] = IOVEC_MAKE_STRING(c->value);
713 iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
714 }
715 }
716 }
717
718 static int write_to_journal(
719 int level,
720 int error,
721 const char *file,
722 int line,
723 const char *func,
724 const char *object_field,
725 const char *object,
726 const char *extra_field,
727 const char *extra,
728 const char *buffer) {
729
730 char header[LINE_MAX];
731 size_t n = 0, iovec_len;
732 struct iovec *iovec;
733
734 if (journal_fd < 0)
735 return 0;
736
737 if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_JOURNAL])
738 return 0;
739
740 iovec_len = MIN(6 + _log_context_num_fields * 2, IOVEC_MAX);
741 iovec = newa(struct iovec, iovec_len);
742
743 log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object, extra_field, extra);
744
745 iovec[n++] = IOVEC_MAKE_STRING(header);
746 iovec[n++] = IOVEC_MAKE_STRING("MESSAGE=");
747 if (log_prefix) {
748 iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
749 iovec[n++] = IOVEC_MAKE_STRING(": ");
750 }
751 iovec[n++] = IOVEC_MAKE_STRING(buffer);
752 iovec[n++] = IOVEC_MAKE_STRING("\n");
753
754 log_do_context(iovec, iovec_len, &n);
755
756 const struct msghdr msghdr = {
757 .msg_iov = iovec,
758 .msg_iovlen = n,
759 };
760
761 if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) < 0)
762 return -errno;
763
764 return 1;
765 }
766
767 int log_dispatch_internal(
768 int level,
769 int error,
770 const char *file,
771 int line,
772 const char *func,
773 const char *object_field,
774 const char *object,
775 const char *extra_field,
776 const char *extra,
777 char *buffer) {
778
779 assert_raw(buffer);
780
781 if (log_target == LOG_TARGET_NULL)
782 return -ERRNO_VALUE(error);
783
784 /* Patch in LOG_DAEMON facility if necessary */
785 if ((level & LOG_FACMASK) == 0)
786 level |= log_facility;
787
788 if (open_when_needed)
789 (void) log_open();
790
791 do {
792 char *e;
793 int k = 0;
794
795 buffer += strspn(buffer, NEWLINE);
796
797 if (buffer[0] == 0)
798 break;
799
800 if ((e = strpbrk(buffer, NEWLINE)))
801 *(e++) = 0;
802
803 if (IN_SET(log_target, LOG_TARGET_AUTO,
804 LOG_TARGET_JOURNAL_OR_KMSG,
805 LOG_TARGET_JOURNAL)) {
806
807 k = write_to_journal(level, error, file, line, func, object_field, object, extra_field, extra, buffer);
808 if (k < 0 && k != -EAGAIN)
809 log_close_journal();
810 }
811
812 if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
813 LOG_TARGET_SYSLOG)) {
814
815 k = write_to_syslog(level, error, file, line, func, buffer);
816 if (k < 0 && k != -EAGAIN)
817 log_close_syslog();
818 }
819
820 if (k <= 0 &&
821 IN_SET(log_target, LOG_TARGET_AUTO,
822 LOG_TARGET_SYSLOG_OR_KMSG,
823 LOG_TARGET_JOURNAL_OR_KMSG,
824 LOG_TARGET_KMSG)) {
825
826 if (k < 0)
827 log_open_kmsg();
828
829 k = write_to_kmsg(level, error, file, line, func, buffer);
830 if (k < 0) {
831 log_close_kmsg();
832 (void) log_open_console();
833 }
834 }
835
836 if (k <= 0)
837 (void) write_to_console(level, error, file, line, func, buffer);
838
839 buffer = e;
840 } while (buffer);
841
842 if (open_when_needed)
843 log_close();
844
845 return -ERRNO_VALUE(error);
846 }
847
848 int log_dump_internal(
849 int level,
850 int error,
851 const char *file,
852 int line,
853 const char *func,
854 char *buffer) {
855
856 PROTECT_ERRNO;
857
858 /* This modifies the buffer... */
859
860 if (_likely_(LOG_PRI(level) > log_max_level))
861 return -ERRNO_VALUE(error);
862
863 return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
864 }
865
866 int log_internalv(
867 int level,
868 int error,
869 const char *file,
870 int line,
871 const char *func,
872 const char *format,
873 va_list ap) {
874
875 if (_likely_(LOG_PRI(level) > log_max_level))
876 return -ERRNO_VALUE(error);
877
878 /* Make sure that %m maps to the specified error (or "Success"). */
879 char buffer[LINE_MAX];
880 LOCAL_ERRNO(ERRNO_VALUE(error));
881
882 (void) vsnprintf(buffer, sizeof buffer, format, ap);
883
884 return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
885 }
886
887 int log_internal(
888 int level,
889 int error,
890 const char *file,
891 int line,
892 const char *func,
893 const char *format, ...) {
894
895 va_list ap;
896 int r;
897
898 va_start(ap, format);
899 r = log_internalv(level, error, file, line, func, format, ap);
900 va_end(ap);
901
902 return r;
903 }
904
905 int log_object_internalv(
906 int level,
907 int error,
908 const char *file,
909 int line,
910 const char *func,
911 const char *object_field,
912 const char *object,
913 const char *extra_field,
914 const char *extra,
915 const char *format,
916 va_list ap) {
917
918 char *buffer, *b;
919
920 if (_likely_(LOG_PRI(level) > log_max_level))
921 return -ERRNO_VALUE(error);
922
923 /* Make sure that %m maps to the specified error (or "Success"). */
924 LOCAL_ERRNO(ERRNO_VALUE(error));
925
926 LOG_SET_PREFIX(object);
927
928 b = buffer = newa(char, LINE_MAX);
929 (void) vsnprintf(b, LINE_MAX, format, ap);
930
931 return log_dispatch_internal(level, error, file, line, func,
932 object_field, object, extra_field, extra, buffer);
933 }
934
935 int log_object_internal(
936 int level,
937 int error,
938 const char *file,
939 int line,
940 const char *func,
941 const char *object_field,
942 const char *object,
943 const char *extra_field,
944 const char *extra,
945 const char *format, ...) {
946
947 va_list ap;
948 int r;
949
950 va_start(ap, format);
951 r = log_object_internalv(level, error, file, line, func, object_field, object, extra_field, extra, format, ap);
952 va_end(ap);
953
954 return r;
955 }
956
957 static void log_assert(
958 int level,
959 const char *text,
960 const char *file,
961 int line,
962 const char *func,
963 const char *format) {
964
965 static char buffer[LINE_MAX];
966
967 if (_likely_(LOG_PRI(level) > log_max_level))
968 return;
969
970 DISABLE_WARNING_FORMAT_NONLITERAL;
971 (void) snprintf(buffer, sizeof buffer, format, text, file, line, func);
972 REENABLE_WARNING;
973
974 log_abort_msg = buffer;
975
976 log_dispatch_internal(level, 0, file, line, func, NULL, NULL, NULL, NULL, buffer);
977 }
978
979 _noreturn_ void log_assert_failed(
980 const char *text,
981 const char *file,
982 int line,
983 const char *func) {
984 log_assert(LOG_CRIT, text, file, line, func,
985 "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
986 abort();
987 }
988
989 _noreturn_ void log_assert_failed_unreachable(
990 const char *file,
991 int line,
992 const char *func) {
993 log_assert(LOG_CRIT, "Code should not be reached", file, line, func,
994 "%s at %s:%u, function %s(). Aborting. 💥");
995 abort();
996 }
997
998 void log_assert_failed_return(
999 const char *text,
1000 const char *file,
1001 int line,
1002 const char *func) {
1003
1004 if (assert_return_is_critical)
1005 log_assert_failed(text, file, line, func);
1006
1007 PROTECT_ERRNO;
1008 log_assert(LOG_DEBUG, text, file, line, func,
1009 "Assertion '%s' failed at %s:%u, function %s(), ignoring.");
1010 }
1011
1012 int log_oom_internal(int level, const char *file, int line, const char *func) {
1013 return log_internal(level, ENOMEM, file, line, func, "Out of memory.");
1014 }
1015
1016 int log_format_iovec(
1017 struct iovec *iovec,
1018 size_t iovec_len,
1019 size_t *n,
1020 bool newline_separator,
1021 int error,
1022 const char *format,
1023 va_list ap) {
1024
1025 static const char nl = '\n';
1026
1027 while (format && *n + 1 < iovec_len) {
1028 va_list aq;
1029 char *m;
1030 int r;
1031
1032 /* We need to copy the va_list structure,
1033 * since vasprintf() leaves it afterwards at
1034 * an undefined location */
1035
1036 errno = ERRNO_VALUE(error);
1037
1038 va_copy(aq, ap);
1039 r = vasprintf(&m, format, aq);
1040 va_end(aq);
1041 if (r < 0)
1042 return -EINVAL;
1043
1044 /* Now, jump enough ahead, so that we point to
1045 * the next format string */
1046 VA_FORMAT_ADVANCE(format, ap);
1047
1048 iovec[(*n)++] = IOVEC_MAKE_STRING(m);
1049 if (newline_separator)
1050 iovec[(*n)++] = IOVEC_MAKE((char *)&nl, 1);
1051
1052 format = va_arg(ap, char *);
1053 }
1054 return 0;
1055 }
1056
1057 int log_struct_internal(
1058 int level,
1059 int error,
1060 const char *file,
1061 int line,
1062 const char *func,
1063 const char *format, ...) {
1064
1065 char buf[LINE_MAX];
1066 bool found = false;
1067 PROTECT_ERRNO;
1068 va_list ap;
1069
1070 if (_likely_(LOG_PRI(level) > log_max_level) ||
1071 log_target == LOG_TARGET_NULL)
1072 return -ERRNO_VALUE(error);
1073
1074 if ((level & LOG_FACMASK) == 0)
1075 level |= log_facility;
1076
1077 if (IN_SET(log_target,
1078 LOG_TARGET_AUTO,
1079 LOG_TARGET_JOURNAL_OR_KMSG,
1080 LOG_TARGET_JOURNAL)) {
1081
1082 if (open_when_needed)
1083 log_open_journal();
1084
1085 if (journal_fd >= 0) {
1086 char header[LINE_MAX];
1087 struct iovec *iovec;
1088 size_t n = 0, m, iovec_len;
1089 int r;
1090 bool fallback = false;
1091
1092 iovec_len = MIN(17 + _log_context_num_fields * 2, IOVEC_MAX);
1093 iovec = newa(struct iovec, iovec_len);
1094
1095 /* If the journal is available do structured logging.
1096 * Do not report the errno if it is synthetic. */
1097 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
1098 iovec[n++] = IOVEC_MAKE_STRING(header);
1099
1100 va_start(ap, format);
1101 r = log_format_iovec(iovec, iovec_len, &n, true, error, format, ap);
1102 m = n;
1103 if (r < 0)
1104 fallback = true;
1105 else {
1106 log_do_context(iovec, iovec_len, &n);
1107
1108 const struct msghdr msghdr = {
1109 .msg_iov = iovec,
1110 .msg_iovlen = n,
1111 };
1112
1113 (void) sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL);
1114 }
1115
1116 va_end(ap);
1117 for (size_t i = 1; i < m; i += 2)
1118 free(iovec[i].iov_base);
1119
1120 if (!fallback) {
1121 if (open_when_needed)
1122 log_close();
1123
1124 return -ERRNO_VALUE(error);
1125 }
1126 }
1127 }
1128
1129 /* Fallback if journal logging is not available or didn't work. */
1130
1131 va_start(ap, format);
1132 while (format) {
1133 va_list aq;
1134
1135 errno = ERRNO_VALUE(error);
1136
1137 va_copy(aq, ap);
1138 (void) vsnprintf(buf, sizeof buf, format, aq);
1139 va_end(aq);
1140
1141 if (startswith(buf, "MESSAGE=")) {
1142 found = true;
1143 break;
1144 }
1145
1146 VA_FORMAT_ADVANCE(format, ap);
1147
1148 format = va_arg(ap, char *);
1149 }
1150 va_end(ap);
1151
1152 if (!found) {
1153 if (open_when_needed)
1154 log_close();
1155
1156 return -ERRNO_VALUE(error);
1157 }
1158
1159 return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buf + 8);
1160 }
1161
1162 int log_struct_iovec_internal(
1163 int level,
1164 int error,
1165 const char *file,
1166 int line,
1167 const char *func,
1168 const struct iovec input_iovec[],
1169 size_t n_input_iovec) {
1170
1171 PROTECT_ERRNO;
1172
1173 if (_likely_(LOG_PRI(level) > log_max_level) ||
1174 log_target == LOG_TARGET_NULL)
1175 return -ERRNO_VALUE(error);
1176
1177 if ((level & LOG_FACMASK) == 0)
1178 level |= log_facility;
1179
1180 if (IN_SET(log_target, LOG_TARGET_AUTO,
1181 LOG_TARGET_JOURNAL_OR_KMSG,
1182 LOG_TARGET_JOURNAL) &&
1183 journal_fd >= 0) {
1184
1185 char header[LINE_MAX];
1186 struct iovec *iovec;
1187 size_t n = 0, iovec_len;
1188
1189 iovec_len = MIN(1 + n_input_iovec * 2 + _log_context_num_fields * 2, IOVEC_MAX);
1190 iovec = newa(struct iovec, iovec_len);
1191
1192 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
1193
1194 iovec[n++] = IOVEC_MAKE_STRING(header);
1195 for (size_t i = 0; i < n_input_iovec; i++) {
1196 iovec[n++] = input_iovec[i];
1197 iovec[n++] = IOVEC_MAKE_STRING("\n");
1198 }
1199
1200 log_do_context(iovec, iovec_len, &n);
1201
1202 const struct msghdr msghdr = {
1203 .msg_iov = iovec,
1204 .msg_iovlen = n,
1205 };
1206
1207 if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) >= 0)
1208 return -ERRNO_VALUE(error);
1209 }
1210
1211 for (size_t i = 0; i < n_input_iovec; i++)
1212 if (memory_startswith(input_iovec[i].iov_base, input_iovec[i].iov_len, "MESSAGE=")) {
1213 char *m;
1214
1215 m = strndupa_safe((char*) input_iovec[i].iov_base + STRLEN("MESSAGE="),
1216 input_iovec[i].iov_len - STRLEN("MESSAGE="));
1217
1218 return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, m);
1219 }
1220
1221 /* Couldn't find MESSAGE=. */
1222 return -ERRNO_VALUE(error);
1223 }
1224
1225 int log_set_target_from_string(const char *e) {
1226 LogTarget t;
1227
1228 t = log_target_from_string(e);
1229 if (t < 0)
1230 return t;
1231
1232 log_set_target(t);
1233 return 0;
1234 }
1235
1236 int log_set_max_level_from_string(const char *e) {
1237 int r;
1238
1239 for (;;) {
1240 _cleanup_free_ char *word = NULL, *prefix = NULL;
1241 LogTarget target;
1242 const char *colon;
1243
1244 r = extract_first_word(&e, &word, ",", 0);
1245 if (r < 0)
1246 return r;
1247 if (r == 0)
1248 break;
1249
1250 colon = strchr(word, ':');
1251 if (!colon) {
1252 r = log_level_from_string(word);
1253 if (r < 0)
1254 return r;
1255
1256 log_set_max_level(r);
1257 continue;
1258 }
1259
1260 prefix = strndup(word, colon - word);
1261 if (!prefix)
1262 return -ENOMEM;
1263
1264 target = log_target_from_string(prefix);
1265 if (target < 0)
1266 return target;
1267
1268 if (target >= _LOG_TARGET_SINGLE_MAX)
1269 return -EINVAL;
1270
1271 r = log_level_from_string(colon + 1);
1272 if (r < 0)
1273 return r;
1274
1275 log_target_max_level[target] = r;
1276 }
1277
1278 return 0;
1279 }
1280
1281 int log_max_levels_to_string(int level, char **ret) {
1282 _cleanup_free_ char *s = NULL;
1283 int r;
1284
1285 assert(ret);
1286
1287 r = log_level_to_string_alloc(level, &s);
1288 if (r < 0)
1289 return r;
1290
1291 for (LogTarget target = 0; target < _LOG_TARGET_SINGLE_MAX; target++) {
1292 _cleanup_free_ char *l = NULL;
1293
1294 if (log_target_max_level[target] == INT_MAX)
1295 continue;
1296
1297 r = log_level_to_string_alloc(log_target_max_level[target], &l);
1298 if (r < 0)
1299 return r;
1300
1301 r = strextendf_with_separator(&s, ",", "%s:%s", log_target_to_string(target), l);
1302 if (r < 0)
1303 return r;
1304 }
1305
1306 *ret = TAKE_PTR(s);
1307 return 0;
1308 }
1309
1310 static int log_set_ratelimit_kmsg_from_string(const char *e) {
1311 int r;
1312
1313 r = parse_boolean(e);
1314 if (r < 0)
1315 return r;
1316
1317 ratelimit_kmsg = r;
1318 return 0;
1319 }
1320
1321 void log_set_assert_return_is_critical(bool b) {
1322 assert_return_is_critical = b;
1323 }
1324
1325 bool log_get_assert_return_is_critical(void) {
1326 return assert_return_is_critical;
1327 }
1328
1329 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
1330
1331 /*
1332 * The systemd.log_xyz= settings are parsed by all tools, and
1333 * so is "debug".
1334 *
1335 * However, "quiet" is only parsed by PID 1, and only turns of
1336 * status output to /dev/console, but does not alter the log
1337 * level.
1338 */
1339
1340 if (streq(key, "debug") && !value)
1341 log_set_max_level(LOG_DEBUG);
1342
1343 else if (proc_cmdline_key_streq(key, "systemd.log_target")) {
1344
1345 if (proc_cmdline_value_missing(key, value))
1346 return 0;
1347
1348 if (log_set_target_from_string(value) < 0)
1349 log_warning("Failed to parse log target '%s', ignoring.", value);
1350
1351 } else if (proc_cmdline_key_streq(key, "systemd.log_level")) {
1352
1353 if (proc_cmdline_value_missing(key, value))
1354 return 0;
1355
1356 if (log_set_max_level_from_string(value) < 0)
1357 log_warning("Failed to parse log level setting '%s', ignoring.", value);
1358
1359 } else if (proc_cmdline_key_streq(key, "systemd.log_color")) {
1360
1361 if (log_show_color_from_string(value ?: "1") < 0)
1362 log_warning("Failed to parse log color setting '%s', ignoring.", value);
1363
1364 } else if (proc_cmdline_key_streq(key, "systemd.log_location")) {
1365
1366 if (log_show_location_from_string(value ?: "1") < 0)
1367 log_warning("Failed to parse log location setting '%s', ignoring.", value);
1368
1369 } else if (proc_cmdline_key_streq(key, "systemd.log_tid")) {
1370
1371 if (log_show_tid_from_string(value ?: "1") < 0)
1372 log_warning("Failed to parse log tid setting '%s', ignoring.", value);
1373
1374 } else if (proc_cmdline_key_streq(key, "systemd.log_time")) {
1375
1376 if (log_show_time_from_string(value ?: "1") < 0)
1377 log_warning("Failed to parse log time setting '%s', ignoring.", value);
1378
1379 } else if (proc_cmdline_key_streq(key, "systemd.log_ratelimit_kmsg")) {
1380
1381 if (log_set_ratelimit_kmsg_from_string(value ?: "1") < 0)
1382 log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", value);
1383 }
1384
1385 return 0;
1386 }
1387
1388 static bool should_parse_proc_cmdline(void) {
1389 /* PID1 always reads the kernel command line. */
1390 if (getpid_cached() == 1)
1391 return true;
1392
1393 /* Otherwise, parse the command line if invoked directly by systemd. */
1394 return invoked_by_systemd();
1395 }
1396
1397 void log_parse_environment_variables(void) {
1398 const char *e;
1399
1400 e = getenv("SYSTEMD_LOG_TARGET");
1401 if (e && log_set_target_from_string(e) < 0)
1402 log_warning("Failed to parse log target '%s', ignoring.", e);
1403
1404 e = getenv("SYSTEMD_LOG_LEVEL");
1405 if (e && log_set_max_level_from_string(e) < 0)
1406 log_warning("Failed to parse log level '%s', ignoring.", e);
1407
1408 e = getenv("SYSTEMD_LOG_COLOR");
1409 if (e && log_show_color_from_string(e) < 0)
1410 log_warning("Failed to parse log color '%s', ignoring.", e);
1411
1412 e = getenv("SYSTEMD_LOG_LOCATION");
1413 if (e && log_show_location_from_string(e) < 0)
1414 log_warning("Failed to parse log location '%s', ignoring.", e);
1415
1416 e = getenv("SYSTEMD_LOG_TIME");
1417 if (e && log_show_time_from_string(e) < 0)
1418 log_warning("Failed to parse log time '%s', ignoring.", e);
1419
1420 e = getenv("SYSTEMD_LOG_TID");
1421 if (e && log_show_tid_from_string(e) < 0)
1422 log_warning("Failed to parse log tid '%s', ignoring.", e);
1423
1424 e = getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
1425 if (e && log_set_ratelimit_kmsg_from_string(e) < 0)
1426 log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", e);
1427 }
1428
1429 void log_parse_environment(void) {
1430 /* Do not call from library code. */
1431
1432 if (should_parse_proc_cmdline())
1433 (void) proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
1434
1435 log_parse_environment_variables();
1436 }
1437
1438 LogTarget log_get_target(void) {
1439 return log_target;
1440 }
1441
1442 void log_settle_target(void) {
1443
1444 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1445 * stderr is attached to the journal every single log call. However, if we then close all file
1446 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1447 * problem, this function is used to permanently change the log target depending on whether stderr is
1448 * connected to the journal or not. */
1449
1450 LogTarget t = log_get_target();
1451
1452 if (t != LOG_TARGET_AUTO)
1453 return;
1454
1455 t = getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc ? LOG_TARGET_KMSG : LOG_TARGET_JOURNAL_OR_KMSG)
1456 : LOG_TARGET_CONSOLE;
1457 log_set_target(t);
1458 }
1459
1460 int log_get_max_level(void) {
1461 return log_max_level;
1462 }
1463
1464 void log_show_color(bool b) {
1465 show_color = b;
1466 }
1467
1468 bool log_get_show_color(void) {
1469 return show_color > 0; /* Defaults to false. */
1470 }
1471
1472 void log_show_location(bool b) {
1473 show_location = b;
1474 }
1475
1476 bool log_get_show_location(void) {
1477 return show_location;
1478 }
1479
1480 void log_show_time(bool b) {
1481 show_time = b;
1482 }
1483
1484 bool log_get_show_time(void) {
1485 return show_time;
1486 }
1487
1488 void log_show_tid(bool b) {
1489 show_tid = b;
1490 }
1491
1492 bool log_get_show_tid(void) {
1493 return show_tid;
1494 }
1495
1496 int log_show_color_from_string(const char *e) {
1497 int r;
1498
1499 r = parse_boolean(e);
1500 if (r < 0)
1501 return r;
1502
1503 log_show_color(r);
1504 return 0;
1505 }
1506
1507 int log_show_location_from_string(const char *e) {
1508 int r;
1509
1510 r = parse_boolean(e);
1511 if (r < 0)
1512 return r;
1513
1514 log_show_location(r);
1515 return 0;
1516 }
1517
1518 int log_show_time_from_string(const char *e) {
1519 int r;
1520
1521 r = parse_boolean(e);
1522 if (r < 0)
1523 return r;
1524
1525 log_show_time(r);
1526 return 0;
1527 }
1528
1529 int log_show_tid_from_string(const char *e) {
1530 int r;
1531
1532 r = parse_boolean(e);
1533 if (r < 0)
1534 return r;
1535
1536 log_show_tid(r);
1537 return 0;
1538 }
1539
1540 bool log_on_console(void) {
1541 if (IN_SET(log_target, LOG_TARGET_CONSOLE,
1542 LOG_TARGET_CONSOLE_PREFIXED))
1543 return true;
1544
1545 return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
1546 }
1547
1548 static const char *const log_target_table[_LOG_TARGET_MAX] = {
1549 [LOG_TARGET_CONSOLE] = "console",
1550 [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1551 [LOG_TARGET_KMSG] = "kmsg",
1552 [LOG_TARGET_JOURNAL] = "journal",
1553 [LOG_TARGET_JOURNAL_OR_KMSG] = "journal-or-kmsg",
1554 [LOG_TARGET_SYSLOG] = "syslog",
1555 [LOG_TARGET_SYSLOG_OR_KMSG] = "syslog-or-kmsg",
1556 [LOG_TARGET_AUTO] = "auto",
1557 [LOG_TARGET_NULL] = "null",
1558 };
1559
1560 DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
1561
1562 void log_received_signal(int level, const struct signalfd_siginfo *si) {
1563 assert(si);
1564
1565 if (pid_is_valid(si->ssi_pid)) {
1566 _cleanup_free_ char *p = NULL;
1567
1568 (void) pid_get_comm(si->ssi_pid, &p);
1569
1570 log_full(level,
1571 "Received SIG%s from PID %"PRIu32" (%s).",
1572 signal_to_string(si->ssi_signo),
1573 si->ssi_pid, strna(p));
1574 } else
1575 log_full(level,
1576 "Received SIG%s.",
1577 signal_to_string(si->ssi_signo));
1578 }
1579
1580 void set_log_syntax_callback(log_syntax_callback_t cb, void *userdata) {
1581 assert(!log_syntax_callback || !cb);
1582 assert(!log_syntax_callback_userdata || !userdata);
1583
1584 log_syntax_callback = cb;
1585 log_syntax_callback_userdata = userdata;
1586 }
1587
1588 int log_syntax_internal(
1589 const char *unit,
1590 int level,
1591 const char *config_file,
1592 unsigned config_line,
1593 int error,
1594 const char *file,
1595 int line,
1596 const char *func,
1597 const char *format, ...) {
1598
1599 PROTECT_ERRNO;
1600
1601 if (log_syntax_callback)
1602 log_syntax_callback(unit, level, log_syntax_callback_userdata);
1603
1604 if (_likely_(LOG_PRI(level) > log_max_level) ||
1605 log_target == LOG_TARGET_NULL)
1606 return -ERRNO_VALUE(error);
1607
1608 char buffer[LINE_MAX];
1609 va_list ap;
1610 const char *unit_fmt = NULL;
1611
1612 errno = ERRNO_VALUE(error);
1613
1614 va_start(ap, format);
1615 (void) vsnprintf(buffer, sizeof buffer, format, ap);
1616 va_end(ap);
1617
1618 if (unit)
1619 unit_fmt = getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1620
1621 if (config_file) {
1622 if (config_line > 0)
1623 return log_struct_internal(
1624 level,
1625 error,
1626 file, line, func,
1627 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1628 "CONFIG_FILE=%s", config_file,
1629 "CONFIG_LINE=%u", config_line,
1630 LOG_MESSAGE("%s:%u: %s", config_file, config_line, buffer),
1631 unit_fmt, unit,
1632 NULL);
1633 else
1634 return log_struct_internal(
1635 level,
1636 error,
1637 file, line, func,
1638 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1639 "CONFIG_FILE=%s", config_file,
1640 LOG_MESSAGE("%s: %s", config_file, buffer),
1641 unit_fmt, unit,
1642 NULL);
1643 } else if (unit)
1644 return log_struct_internal(
1645 level,
1646 error,
1647 file, line, func,
1648 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1649 LOG_MESSAGE("%s: %s", unit, buffer),
1650 unit_fmt, unit,
1651 NULL);
1652 else
1653 return log_struct_internal(
1654 level,
1655 error,
1656 file, line, func,
1657 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1658 LOG_MESSAGE("%s", buffer),
1659 NULL);
1660 }
1661
1662 int log_syntax_invalid_utf8_internal(
1663 const char *unit,
1664 int level,
1665 const char *config_file,
1666 unsigned config_line,
1667 const char *file,
1668 int line,
1669 const char *func,
1670 const char *rvalue) {
1671
1672 _cleanup_free_ char *p = NULL;
1673
1674 if (rvalue)
1675 p = utf8_escape_invalid(rvalue);
1676
1677 return log_syntax_internal(unit, level, config_file, config_line,
1678 SYNTHETIC_ERRNO(EINVAL), file, line, func,
1679 "String is not UTF-8 clean, ignoring assignment: %s", strna(p));
1680 }
1681
1682 void log_set_upgrade_syslog_to_journal(bool b) {
1683 upgrade_syslog_to_journal = b;
1684
1685 /* Make the change effective immediately */
1686 if (b) {
1687 if (log_target == LOG_TARGET_SYSLOG)
1688 log_target = LOG_TARGET_JOURNAL;
1689 else if (log_target == LOG_TARGET_SYSLOG_OR_KMSG)
1690 log_target = LOG_TARGET_JOURNAL_OR_KMSG;
1691 }
1692 }
1693
1694 void log_set_always_reopen_console(bool b) {
1695 always_reopen_console = b;
1696 }
1697
1698 void log_set_open_when_needed(bool b) {
1699 open_when_needed = b;
1700 }
1701
1702 void log_set_prohibit_ipc(bool b) {
1703 prohibit_ipc = b;
1704 }
1705
1706 int log_emergency_level(void) {
1707 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1708 * then the system of the whole system is obviously affected. */
1709
1710 return getpid_cached() == 1 ? LOG_EMERG : LOG_ERR;
1711 }
1712
1713 int log_dup_console(void) {
1714 int copy;
1715
1716 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1717 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1718
1719 if (console_fd < 0 || console_fd >= 3)
1720 return 0;
1721
1722 copy = fcntl(console_fd, F_DUPFD_CLOEXEC, 3);
1723 if (copy < 0)
1724 return -errno;
1725
1726 console_fd = copy;
1727 return 0;
1728 }
1729
1730 void log_setup(void) {
1731 log_set_target(LOG_TARGET_AUTO);
1732 log_parse_environment();
1733 (void) log_open();
1734 if (log_on_console() && show_color < 0)
1735 log_show_color(true);
1736 }
1737
1738 const char *_log_set_prefix(const char *prefix, bool force) {
1739 const char *old = log_prefix;
1740
1741 if (prefix || force)
1742 log_prefix = prefix;
1743
1744 return old;
1745 }
1746
1747 static int saved_log_context_enabled = -1;
1748
1749 bool log_context_enabled(void) {
1750 int r;
1751
1752 if (log_get_max_level() == LOG_DEBUG)
1753 return true;
1754
1755 if (saved_log_context_enabled >= 0)
1756 return saved_log_context_enabled;
1757
1758 r = secure_getenv_bool("SYSTEMD_ENABLE_LOG_CONTEXT");
1759 if (r < 0 && r != -ENXIO)
1760 log_debug_errno(r, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
1761
1762 saved_log_context_enabled = r > 0;
1763
1764 return saved_log_context_enabled;
1765 }
1766
1767 static LogContext* log_context_attach(LogContext *c) {
1768 assert(c);
1769
1770 _log_context_num_fields += strv_length(c->fields);
1771 _log_context_num_fields += c->n_input_iovec;
1772 _log_context_num_fields += !!c->key;
1773
1774 return LIST_PREPEND(ll, _log_context, c);
1775 }
1776
1777 static LogContext* log_context_detach(LogContext *c) {
1778 if (!c)
1779 return NULL;
1780
1781 assert(_log_context_num_fields >= strv_length(c->fields) + c->n_input_iovec +!!c->key);
1782 _log_context_num_fields -= strv_length(c->fields);
1783 _log_context_num_fields -= c->n_input_iovec;
1784 _log_context_num_fields -= !!c->key;
1785
1786 LIST_REMOVE(ll, _log_context, c);
1787 return NULL;
1788 }
1789
1790 LogContext* log_context_new(const char *key, const char *value) {
1791 assert(key);
1792 assert(endswith(key, "="));
1793 assert(value);
1794
1795 LIST_FOREACH(ll, i, _log_context)
1796 if (i->key == key && i->value == value)
1797 return log_context_ref(i);
1798
1799 LogContext *c = new(LogContext, 1);
1800 if (!c)
1801 return NULL;
1802
1803 *c = (LogContext) {
1804 .n_ref = 1,
1805 .key = (char *) key,
1806 .value = (char *) value,
1807 };
1808
1809 return log_context_attach(c);
1810 }
1811
1812 LogContext* log_context_new_strv(char **fields, bool owned) {
1813 if (!fields)
1814 return NULL;
1815
1816 LIST_FOREACH(ll, i, _log_context)
1817 if (i->fields == fields) {
1818 assert(!owned);
1819 return log_context_ref(i);
1820 }
1821
1822 LogContext *c = new(LogContext, 1);
1823 if (!c)
1824 return NULL;
1825
1826 *c = (LogContext) {
1827 .n_ref = 1,
1828 .fields = fields,
1829 .owned = owned,
1830 };
1831
1832 return log_context_attach(c);
1833 }
1834
1835 LogContext* log_context_new_iov(struct iovec *input_iovec, size_t n_input_iovec, bool owned) {
1836 if (!input_iovec || n_input_iovec == 0)
1837 return NULL;
1838
1839 LIST_FOREACH(ll, i, _log_context)
1840 if (i->input_iovec == input_iovec && i->n_input_iovec == n_input_iovec) {
1841 assert(!owned);
1842 return log_context_ref(i);
1843 }
1844
1845 LogContext *c = new(LogContext, 1);
1846 if (!c)
1847 return NULL;
1848
1849 *c = (LogContext) {
1850 .n_ref = 1,
1851 .input_iovec = input_iovec,
1852 .n_input_iovec = n_input_iovec,
1853 .owned = owned,
1854 };
1855
1856 return log_context_attach(c);
1857 }
1858
1859 static LogContext* log_context_free(LogContext *c) {
1860 if (!c)
1861 return NULL;
1862
1863 log_context_detach(c);
1864
1865 if (c->owned) {
1866 strv_free(c->fields);
1867 iovec_array_free(c->input_iovec, c->n_input_iovec);
1868 free(c->key);
1869 free(c->value);
1870 }
1871
1872 return mfree(c);
1873 }
1874
1875 DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext, log_context, log_context_free);
1876
1877 LogContext* log_context_new_strv_consume(char **fields) {
1878 LogContext *c = log_context_new_strv(fields, /*owned=*/ true);
1879 if (!c)
1880 strv_free(fields);
1881
1882 return c;
1883 }
1884
1885 LogContext* log_context_new_iov_consume(struct iovec *input_iovec, size_t n_input_iovec) {
1886 LogContext *c = log_context_new_iov(input_iovec, n_input_iovec, /*owned=*/ true);
1887 if (!c)
1888 iovec_array_free(input_iovec, n_input_iovec);
1889
1890 return c;
1891 }
1892
1893 size_t log_context_num_contexts(void) {
1894 size_t n = 0;
1895
1896 LIST_FOREACH(ll, c, _log_context)
1897 n++;
1898
1899 return n;
1900 }
1901
1902 size_t log_context_num_fields(void) {
1903 return _log_context_num_fields;
1904 }