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