2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
28 #include <sys/signalfd.h>
29 #include <sys/socket.h>
36 #include "sd-messages.h"
38 #include "alloc-util.h"
40 #include "format-util.h"
45 #include "parse-util.h"
46 #include "proc-cmdline.h"
47 #include "process-util.h"
48 #include "signal-util.h"
49 #include "socket-util.h"
50 #include "stdio-util.h"
51 #include "string-table.h"
52 #include "string-util.h"
53 #include "syslog-util.h"
54 #include "terminal-util.h"
55 #include "time-util.h"
58 #define SNDBUF_SIZE (8*1024*1024)
60 static LogTarget log_target = LOG_TARGET_CONSOLE;
61 static int log_max_level = LOG_INFO;
62 static int log_facility = LOG_DAEMON;
64 static int console_fd = STDERR_FILENO;
65 static int syslog_fd = -1;
66 static int kmsg_fd = -1;
67 static int journal_fd = -1;
69 static bool syslog_is_stream = false;
71 static bool show_color = false;
72 static bool show_location = false;
74 #if 0 /// UNNEEDED by elogind
75 static bool upgrade_syslog_to_journal = false;
77 static bool always_reopen_console = false;
79 /* Akin to glibc's __abort_msg; which is private and we hence cannot
81 static char *log_abort_msg = NULL;
83 void log_close_console(void) {
90 safe_close(console_fd);
96 static int log_open_console(void) {
101 if (always_reopen_console) {
102 console_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
106 console_fd = STDERR_FILENO;
111 void log_close_kmsg(void) {
112 kmsg_fd = safe_close(kmsg_fd);
115 static int log_open_kmsg(void) {
120 kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
127 void log_close_syslog(void) {
128 syslog_fd = safe_close(syslog_fd);
131 static int create_log_socket(int type) {
135 fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
139 (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
141 /* We need a blocking fd here since we'd otherwise lose
142 messages way too early. However, let's not hang forever in the
143 unlikely case of a deadlock. */
145 timeval_store(&tv, 10 * USEC_PER_MSEC);
147 timeval_store(&tv, 10 * USEC_PER_SEC);
148 (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
153 static int log_open_syslog(void) {
155 static const union sockaddr_union sa = {
156 .un.sun_family = AF_UNIX,
157 .un.sun_path = "/dev/log",
165 syslog_fd = create_log_socket(SOCK_DGRAM);
171 if (connect(syslog_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
172 safe_close(syslog_fd);
174 /* Some legacy syslog systems still use stream
175 * sockets. They really shouldn't. But what can we
177 syslog_fd = create_log_socket(SOCK_STREAM);
183 if (connect(syslog_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
188 syslog_is_stream = true;
190 syslog_is_stream = false;
199 void log_close_journal(void) {
200 #if 0 /// elogind does not support journald
201 journal_fd = safe_close(journal_fd);
205 #if 0 /// UNNEEDED by elogind
206 static int log_open_journal(void) {
208 static const union sockaddr_union sa = {
209 .un.sun_family = AF_UNIX,
210 .un.sun_path = "/run/systemd/journal/socket",
218 journal_fd = create_log_socket(SOCK_DGRAM);
219 if (journal_fd < 0) {
224 if (connect(journal_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
240 /* If we don't use the console we close it here, to not get
241 * killed by SAK. If we don't use syslog we close it here so
242 * that we are not confused by somebody deleting the socket in
243 * the fs. If we don't use /dev/kmsg we still keep it open,
244 * because there is no reason to close it. */
246 if (log_target == LOG_TARGET_NULL) {
253 if (!IN_SET(log_target, LOG_TARGET_AUTO, LOG_TARGET_SAFE) ||
255 isatty(STDERR_FILENO) <= 0) {
257 #if 0 /// elogind does not support logging to systemd-journald
258 if (IN_SET(log_target, LOG_TARGET_AUTO,
259 LOG_TARGET_JOURNAL_OR_KMSG,
260 LOG_TARGET_JOURNAL)) {
261 r = log_open_journal();
270 if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
271 LOG_TARGET_SYSLOG)) {
272 r = log_open_syslog();
280 if (IN_SET(log_target, LOG_TARGET_AUTO,
282 LOG_TARGET_JOURNAL_OR_KMSG,
283 LOG_TARGET_SYSLOG_OR_KMSG,
298 return log_open_console();
301 void log_set_target(LogTarget target) {
303 assert(target < _LOG_TARGET_MAX);
305 #if 0 /// elogind does not support logging to systemd-journald
306 if (upgrade_syslog_to_journal) {
307 if (target == LOG_TARGET_SYSLOG)
308 target = LOG_TARGET_JOURNAL;
309 else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
310 target = LOG_TARGET_JOURNAL_OR_KMSG;
317 void log_close(void) {
324 #if 0 /// UNNEEDED by elogind
325 void log_forget_fds(void) {
326 console_fd = kmsg_fd = syslog_fd = journal_fd = -1;
330 void log_set_max_level(int level) {
331 assert((level & LOG_PRIMASK) == level);
333 log_max_level = level;
336 void log_set_facility(int facility) {
337 log_facility = facility;
340 static int write_to_console(
346 const char *buffer) {
348 char location[256], prefix[1 + DECIMAL_STR_MAX(int) + 2];
349 struct iovec iovec[6] = {};
356 if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
357 xsprintf(prefix, "<%i>", level);
358 IOVEC_SET_STRING(iovec[n++], prefix);
361 highlight = LOG_PRI(level) <= LOG_ERR && show_color;
364 snprintf(location, sizeof(location), "(%s:%i) ", file, line);
365 IOVEC_SET_STRING(iovec[n++], location);
369 IOVEC_SET_STRING(iovec[n++], ANSI_HIGHLIGHT_RED);
370 IOVEC_SET_STRING(iovec[n++], buffer);
372 IOVEC_SET_STRING(iovec[n++], ANSI_NORMAL);
373 IOVEC_SET_STRING(iovec[n++], "\n");
375 if (writev(console_fd, iovec, n) < 0) {
377 if (errno == EIO && getpid() == 1) {
379 /* If somebody tried to kick us from our
380 * console tty (via vhangup() or suchlike),
381 * try to reconnect */
389 if (writev(console_fd, iovec, n) < 0)
398 static int write_to_syslog(
404 const char *buffer) {
406 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
408 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
409 struct iovec iovec[5] = {};
410 struct msghdr msghdr = {
412 .msg_iovlen = ELEMENTSOF(iovec),
420 xsprintf(header_priority, "<%i>", level);
422 t = (time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC);
427 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
430 xsprintf(header_pid, "["PID_FMT"]: ", getpid());
432 IOVEC_SET_STRING(iovec[0], header_priority);
433 IOVEC_SET_STRING(iovec[1], header_time);
434 IOVEC_SET_STRING(iovec[2], program_invocation_short_name);
435 IOVEC_SET_STRING(iovec[3], header_pid);
436 IOVEC_SET_STRING(iovec[4], buffer);
438 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
439 if (syslog_is_stream)
445 n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
449 if (!syslog_is_stream ||
450 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
453 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
459 static int write_to_kmsg(
465 const char *buffer) {
467 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
468 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
469 struct iovec iovec[5] = {};
474 xsprintf(header_priority, "<%i>", level);
475 xsprintf(header_pid, "["PID_FMT"]: ", getpid());
477 IOVEC_SET_STRING(iovec[0], header_priority);
478 IOVEC_SET_STRING(iovec[1], program_invocation_short_name);
479 IOVEC_SET_STRING(iovec[2], header_pid);
480 IOVEC_SET_STRING(iovec[3], buffer);
481 IOVEC_SET_STRING(iovec[4], "\n");
483 if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
489 #if 0 /// UNNEEDED by elogind
490 static int log_do_header(
495 const char *file, int line, const char *func,
496 const char *object_field, const char *object,
497 const char *extra_field, const char *extra) {
499 snprintf(header, size,
501 "SYSLOG_FACILITY=%i\n"
508 "SYSLOG_IDENTIFIER=%s\n",
511 isempty(file) ? "" : "CODE_FILE=",
512 isempty(file) ? "" : file,
513 isempty(file) ? "" : "\n",
514 line ? "CODE_LINE=" : "",
515 line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
517 isempty(func) ? "" : "CODE_FUNC=",
518 isempty(func) ? "" : func,
519 isempty(func) ? "" : "\n",
520 error ? "ERRNO=" : "",
521 error ? 1 : 0, error,
523 isempty(object) ? "" : object_field,
524 isempty(object) ? "" : object,
525 isempty(object) ? "" : "\n",
526 isempty(extra) ? "" : extra_field,
527 isempty(extra) ? "" : extra,
528 isempty(extra) ? "" : "\n",
529 program_invocation_short_name);
534 static int write_to_journal(
540 const char *object_field,
542 const char *extra_field,
544 const char *buffer) {
546 char header[LINE_MAX];
547 struct iovec iovec[4] = {};
548 struct msghdr mh = {};
553 log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object, extra_field, extra);
555 IOVEC_SET_STRING(iovec[0], header);
556 IOVEC_SET_STRING(iovec[1], "MESSAGE=");
557 IOVEC_SET_STRING(iovec[2], buffer);
558 IOVEC_SET_STRING(iovec[3], "\n");
561 mh.msg_iovlen = ELEMENTSOF(iovec);
563 if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) < 0)
570 int log_dispatch_internal(
576 const char *object_field,
579 const char *extra_field,
587 if (log_target == LOG_TARGET_NULL)
590 /* Patch in LOG_DAEMON facility if necessary */
591 if ((level & LOG_FACMASK) == 0)
592 level = log_facility | LOG_PRI(level);
598 buffer += strspn(buffer, NEWLINE);
603 if ((e = strpbrk(buffer, NEWLINE)))
606 #if 0 /// elogind does not support logging to systemd-journald
607 if (IN_SET(log_target, LOG_TARGET_AUTO,
608 LOG_TARGET_JOURNAL_OR_KMSG,
609 LOG_TARGET_JOURNAL)) {
611 k = write_to_journal(level, error, file, line, func, object_field, object, extra_field, extra, buffer);
620 if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
621 LOG_TARGET_SYSLOG)) {
623 k = write_to_syslog(level, error, file, line, func, buffer);
632 IN_SET(log_target, LOG_TARGET_AUTO,
634 LOG_TARGET_SYSLOG_OR_KMSG,
635 LOG_TARGET_JOURNAL_OR_KMSG,
638 k = write_to_kmsg(level, error, file, line, func, buffer);
646 (void) write_to_console(level, error, file, line, func, buffer);
654 int log_dump_internal(
664 /* This modifies the buffer... */
669 if (_likely_(LOG_PRI(level) > log_max_level))
672 return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
685 char buffer[LINE_MAX];
690 if (_likely_(LOG_PRI(level) > log_max_level))
693 /* Make sure that %m maps to the specified error */
697 vsnprintf(buffer, sizeof(buffer), format, ap);
699 return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
708 const char *format, ...) {
713 va_start(ap, format);
714 r = log_internalv(level, error, file, line, func, format, ap);
720 int log_object_internalv(
726 const char *object_field,
728 const char *extra_field,
740 if (_likely_(LOG_PRI(level) > log_max_level))
743 /* Make sure that %m maps to the specified error */
747 /* Prepend the object name before the message */
752 l = n + 2 + LINE_MAX;
754 buffer = newa(char, l);
755 b = stpcpy(stpcpy(buffer, object), ": ");
758 b = buffer = newa(char, l);
761 vsnprintf(b, l, format, ap);
763 return log_dispatch_internal(level, error, file, line, func,
764 object_field, object, extra_field, extra, buffer);
767 int log_object_internal(
773 const char *object_field,
775 const char *extra_field,
777 const char *format, ...) {
782 va_start(ap, format);
783 r = log_object_internalv(level, error, file, line, func, object_field, object, extra_field, extra, format, ap);
789 static void log_assert(
795 const char *format) {
797 static char buffer[LINE_MAX];
799 if (_likely_(LOG_PRI(level) > log_max_level))
802 DISABLE_WARNING_FORMAT_NONLITERAL;
803 snprintf(buffer, sizeof buffer, format, text, file, line, func);
806 log_abort_msg = buffer;
808 log_dispatch_internal(level, 0, file, line, func, NULL, NULL, NULL, NULL, buffer);
811 noreturn void log_assert_failed(const char *text, const char *file, int line, const char *func) {
812 log_assert(LOG_CRIT, text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
816 noreturn void log_assert_failed_unreachable(const char *text, const char *file, int line, const char *func) {
817 log_assert(LOG_CRIT, text, file, line, func, "Code should not be reached '%s' at %s:%u, function %s(). Aborting.");
821 void log_assert_failed_return(const char *text, const char *file, int line, const char *func) {
823 log_assert(LOG_DEBUG, text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
826 int log_oom_internal(const char *file, int line, const char *func) {
827 log_internal(LOG_ERR, ENOMEM, file, line, func, "Out of memory.");
831 int log_format_iovec(
835 bool newline_separator,
840 static const char nl = '\n';
842 while (format && *n + 1 < iovec_len) {
847 /* We need to copy the va_list structure,
848 * since vasprintf() leaves it afterwards at
849 * an undefined location */
855 r = vasprintf(&m, format, aq);
860 /* Now, jump enough ahead, so that we point to
861 * the next format string */
862 VA_FORMAT_ADVANCE(format, ap);
864 IOVEC_SET_STRING(iovec[(*n)++], m);
866 if (newline_separator) {
867 iovec[*n].iov_base = (char*) &nl;
868 iovec[*n].iov_len = 1;
872 format = va_arg(ap, char *);
877 int log_struct_internal(
883 const char *format, ...) {
893 if (_likely_(LOG_PRI(level) > log_max_level))
896 if (log_target == LOG_TARGET_NULL)
899 if ((level & LOG_FACMASK) == 0)
900 level = log_facility | LOG_PRI(level);
902 #if 0 /// elogind does not support logging to systemd-journald
903 if (IN_SET(log_target, LOG_TARGET_AUTO,
904 LOG_TARGET_JOURNAL_OR_KMSG,
905 LOG_TARGET_JOURNAL) &&
907 char header[LINE_MAX];
908 struct iovec iovec[17] = {};
914 bool fallback = false;
916 /* If the journal is available do structured logging */
917 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
918 IOVEC_SET_STRING(iovec[n++], header);
920 va_start(ap, format);
921 r = log_format_iovec(iovec, ELEMENTSOF(iovec), &n, true, error, format, ap);
926 (void) sendmsg(journal_fd, &mh, MSG_NOSIGNAL);
930 for (i = 1; i < n; i += 2)
931 free(iovec[i].iov_base);
938 /* Fallback if journal logging is not available or didn't work. */
940 va_start(ap, format);
948 vsnprintf(buf, sizeof(buf), format, aq);
951 if (startswith(buf, "MESSAGE=")) {
956 VA_FORMAT_ADVANCE(format, ap);
958 format = va_arg(ap, char *);
965 return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buf + 8);
968 int log_set_target_from_string(const char *e) {
971 t = log_target_from_string(e);
979 int log_set_max_level_from_string(const char *e) {
982 t = log_level_from_string(e);
986 log_set_max_level(t);
990 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
993 * The systemd.log_xyz= settings are parsed by all tools, and
996 * However, "quiet" is only parsed by PID 1, and only turns of
997 * status output to /dev/console, but does not alter the log
1001 if (streq(key, "debug") && !value)
1002 log_set_max_level(LOG_DEBUG);
1004 else if (proc_cmdline_key_streq(key, "systemd.log_target")) {
1006 if (proc_cmdline_value_missing(key, value))
1009 if (log_set_target_from_string(value) < 0)
1010 log_warning("Failed to parse log target '%s'. Ignoring.", value);
1012 } else if (proc_cmdline_key_streq(key, "systemd.log_level")) {
1014 if (proc_cmdline_value_missing(key, value))
1017 if (log_set_max_level_from_string(value) < 0)
1018 log_warning("Failed to parse log level '%s'. Ignoring.", value);
1020 } else if (proc_cmdline_key_streq(key, "systemd.log_color")) {
1022 if (log_show_color_from_string(value ?: "1") < 0)
1023 log_warning("Failed to parse log color setting '%s'. Ignoring.", value);
1025 } else if (proc_cmdline_key_streq(key, "systemd.log_location")) {
1027 if (log_show_location_from_string(value ?: "1") < 0)
1028 log_warning("Failed to parse log location setting '%s'. Ignoring.", value);
1034 void log_parse_environment(void) {
1037 if (get_ctty_devnr(0, NULL) < 0)
1038 /* Only try to read the command line in daemons. We assume that anything that has a controlling tty is
1040 (void) proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
1042 e = secure_getenv("SYSTEMD_LOG_TARGET");
1043 if (e && log_set_target_from_string(e) < 0)
1044 log_warning("Failed to parse log target '%s'. Ignoring.", e);
1046 e = secure_getenv("SYSTEMD_LOG_LEVEL");
1047 if (e && log_set_max_level_from_string(e) < 0)
1048 log_warning("Failed to parse log level '%s'. Ignoring.", e);
1050 e = secure_getenv("SYSTEMD_LOG_COLOR");
1051 if (e && log_show_color_from_string(e) < 0)
1052 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1054 e = secure_getenv("SYSTEMD_LOG_LOCATION");
1055 if (e && log_show_location_from_string(e) < 0)
1056 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1059 LogTarget log_get_target(void) {
1063 int log_get_max_level(void) {
1064 return log_max_level;
1067 void log_show_color(bool b) {
1071 bool log_get_show_color(void) {
1075 void log_show_location(bool b) {
1079 bool log_get_show_location(void) {
1080 return show_location;
1083 int log_show_color_from_string(const char *e) {
1086 t = parse_boolean(e);
1094 int log_show_location_from_string(const char *e) {
1097 t = parse_boolean(e);
1101 log_show_location(t);
1105 bool log_on_console(void) {
1106 if (IN_SET(log_target, LOG_TARGET_CONSOLE,
1107 LOG_TARGET_CONSOLE_PREFIXED))
1110 return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
1113 static const char *const log_target_table[_LOG_TARGET_MAX] = {
1114 [LOG_TARGET_CONSOLE] = "console",
1115 [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1116 [LOG_TARGET_KMSG] = "kmsg",
1117 #if 0 /// elogind does not support logging to systemd-journald
1118 [LOG_TARGET_JOURNAL] = "journal",
1119 [LOG_TARGET_JOURNAL_OR_KMSG] = "journal-or-kmsg",
1121 [LOG_TARGET_SYSLOG] = "syslog",
1122 [LOG_TARGET_SYSLOG_OR_KMSG] = "syslog-or-kmsg",
1123 [LOG_TARGET_AUTO] = "auto",
1124 [LOG_TARGET_SAFE] = "safe",
1125 [LOG_TARGET_NULL] = "null"
1128 DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
1130 #if 0 /// UNNEEDED by elogind
1131 void log_received_signal(int level, const struct signalfd_siginfo *si) {
1132 if (si->ssi_pid > 0) {
1133 _cleanup_free_ char *p = NULL;
1135 get_process_comm(si->ssi_pid, &p);
1138 "Received SIG%s from PID %"PRIu32" (%s).",
1139 signal_to_string(si->ssi_signo),
1140 si->ssi_pid, strna(p));
1144 signal_to_string(si->ssi_signo));
1148 void log_set_upgrade_syslog_to_journal(bool b) {
1149 upgrade_syslog_to_journal = b;
1153 int log_syntax_internal(
1156 const char *config_file,
1157 unsigned config_line,
1162 const char *format, ...) {
1165 char buffer[LINE_MAX];
1167 const char *unit_fmt = NULL;
1172 if (_likely_(LOG_PRI(level) > log_max_level))
1175 if (log_target == LOG_TARGET_NULL)
1181 va_start(ap, format);
1182 vsnprintf(buffer, sizeof(buffer), format, ap);
1186 unit_fmt = getpid() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1188 return log_struct_internal(
1191 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1192 "CONFIG_FILE=%s", config_file,
1193 "CONFIG_LINE=%u", config_line,
1194 LOG_MESSAGE("%s:%u: %s", config_file, config_line, buffer),
1199 #if 0 /// UNNEEDED by elogind
1200 void log_set_always_reopen_console(bool b) {
1201 always_reopen_console = b;