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