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