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