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