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 "formats-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 /// UNNEEDED by elogind static bool upgrade_syslog_to_journal = false;
76 /* Akin to glibc's __abort_msg; which is private and we hence cannot
78 static char *log_abort_msg = NULL;
80 void log_close_console(void) {
87 safe_close(console_fd);
93 static int log_open_console(void) {
99 console_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
103 console_fd = STDERR_FILENO;
108 void log_close_kmsg(void) {
109 kmsg_fd = safe_close(kmsg_fd);
112 static int log_open_kmsg(void) {
117 kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
124 void log_close_syslog(void) {
125 syslog_fd = safe_close(syslog_fd);
128 static int create_log_socket(int type) {
132 fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
136 fd_inc_sndbuf(fd, SNDBUF_SIZE);
138 /* We need a blocking fd here since we'd otherwise lose
139 messages way too early. However, let's not hang forever in the
140 unlikely case of a deadlock. */
142 timeval_store(&tv, 10 * USEC_PER_MSEC);
144 timeval_store(&tv, 10 * USEC_PER_SEC);
145 (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
150 static int log_open_syslog(void) {
152 static const union sockaddr_union sa = {
153 .un.sun_family = AF_UNIX,
154 .un.sun_path = "/dev/log",
162 syslog_fd = create_log_socket(SOCK_DGRAM);
168 if (connect(syslog_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
169 safe_close(syslog_fd);
171 /* Some legacy syslog systems still use stream
172 * sockets. They really shouldn't. But what can we
174 syslog_fd = create_log_socket(SOCK_STREAM);
180 if (connect(syslog_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
185 syslog_is_stream = true;
187 syslog_is_stream = false;
196 #if 0 /// UNNEEDED by elogind
197 void log_close_journal(void) {
198 journal_fd = safe_close(journal_fd);
201 static int log_open_journal(void) {
203 static const union sockaddr_union sa = {
204 .un.sun_family = AF_UNIX,
205 .un.sun_path = "/run/systemd/journal/socket",
213 journal_fd = create_log_socket(SOCK_DGRAM);
214 if (journal_fd < 0) {
219 if (connect(journal_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
235 /* If we don't use the console we close it here, to not get
236 * killed by SAK. If we don't use syslog we close it here so
237 * that we are not confused by somebody deleting the socket in
238 * the fs. If we don't use /dev/kmsg we still keep it open,
239 * because there is no reason to close it. */
241 if (log_target == LOG_TARGET_NULL) {
242 /// UNNEEDED by elogind log_close_journal();
248 if ((log_target != LOG_TARGET_AUTO && log_target != LOG_TARGET_SAFE) ||
250 isatty(STDERR_FILENO) <= 0) {
252 #if 0 /// elogind does not support logging to systemd-journald
253 if (log_target == LOG_TARGET_AUTO ||
254 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
255 log_target == LOG_TARGET_JOURNAL) {
256 r = log_open_journal();
264 if (log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
265 log_target == LOG_TARGET_SYSLOG) {
266 r = log_open_syslog();
268 /// UNNEEDED by elogind log_close_journal();
274 if (log_target == LOG_TARGET_AUTO ||
275 log_target == LOG_TARGET_SAFE ||
276 /// UNNEEDED by elogind log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
277 log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
278 log_target == LOG_TARGET_KMSG) {
281 /// UNNEEDED by elogind log_close_journal();
289 /// UNNEEDED by elogind log_close_journal();
292 return log_open_console();
295 void log_set_target(LogTarget target) {
297 assert(target < _LOG_TARGET_MAX);
299 #if 0 /// elogind does not support logging to systemd-journald
300 if (upgrade_syslog_to_journal) {
301 if (target == LOG_TARGET_SYSLOG)
302 target = LOG_TARGET_JOURNAL;
303 else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
304 target = LOG_TARGET_JOURNAL_OR_KMSG;
311 void log_close(void) {
312 /// UNNEDED by elogind log_close_journal();
318 #if 0 /// UNNEEDED by elogind
319 void log_forget_fds(void) {
320 console_fd = kmsg_fd = syslog_fd = journal_fd = -1;
324 void log_set_max_level(int level) {
325 assert((level & LOG_PRIMASK) == level);
327 log_max_level = level;
330 void log_set_facility(int facility) {
331 log_facility = facility;
334 static int write_to_console(
340 const char *object_field,
342 const char *buffer) {
344 char location[64], prefix[1 + DECIMAL_STR_MAX(int) + 2];
345 struct iovec iovec[6] = {};
352 if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
353 sprintf(prefix, "<%i>", level);
354 IOVEC_SET_STRING(iovec[n++], prefix);
357 highlight = LOG_PRI(level) <= LOG_ERR && show_color;
360 xsprintf(location, "(%s:%i) ", file, line);
361 IOVEC_SET_STRING(iovec[n++], location);
365 IOVEC_SET_STRING(iovec[n++], ANSI_HIGHLIGHT_RED);
366 IOVEC_SET_STRING(iovec[n++], buffer);
368 IOVEC_SET_STRING(iovec[n++], ANSI_NORMAL);
369 IOVEC_SET_STRING(iovec[n++], "\n");
371 if (writev(console_fd, iovec, n) < 0) {
373 if (errno == EIO && getpid() == 1) {
375 /* If somebody tried to kick us from our
376 * console tty (via vhangup() or suchlike),
377 * try to reconnect */
385 if (writev(console_fd, iovec, n) < 0)
394 static int write_to_syslog(
400 const char *object_field,
402 const char *buffer) {
404 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
406 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
407 struct iovec iovec[5] = {};
408 struct msghdr msghdr = {
410 .msg_iovlen = ELEMENTSOF(iovec),
418 xsprintf(header_priority, "<%i>", level);
420 t = (time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC);
425 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
428 xsprintf(header_pid, "["PID_FMT"]: ", getpid());
430 IOVEC_SET_STRING(iovec[0], header_priority);
431 IOVEC_SET_STRING(iovec[1], header_time);
432 IOVEC_SET_STRING(iovec[2], program_invocation_short_name);
433 IOVEC_SET_STRING(iovec[3], header_pid);
434 IOVEC_SET_STRING(iovec[4], buffer);
436 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
437 if (syslog_is_stream)
443 n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
447 if (!syslog_is_stream ||
448 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
451 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
457 static int write_to_kmsg(
463 const char *object_field,
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) {
498 snprintf(header, size,
500 "SYSLOG_FACILITY=%i\n"
506 "SYSLOG_IDENTIFIER=%s\n",
509 isempty(file) ? "" : "CODE_FILE=",
510 isempty(file) ? "" : file,
511 isempty(file) ? "" : "\n",
512 line ? "CODE_LINE=" : "",
513 line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
515 isempty(func) ? "" : "CODE_FUNCTION=",
516 isempty(func) ? "" : func,
517 isempty(func) ? "" : "\n",
518 error ? "ERRNO=" : "",
519 error ? 1 : 0, error,
521 isempty(object) ? "" : object_field,
522 isempty(object) ? "" : object,
523 isempty(object) ? "" : "\n",
524 program_invocation_short_name);
529 static int write_to_journal(
535 const char *object_field,
537 const char *buffer) {
539 char header[LINE_MAX];
540 struct iovec iovec[4] = {};
541 struct msghdr mh = {};
546 log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object);
548 IOVEC_SET_STRING(iovec[0], header);
549 IOVEC_SET_STRING(iovec[1], "MESSAGE=");
550 IOVEC_SET_STRING(iovec[2], buffer);
551 IOVEC_SET_STRING(iovec[3], "\n");
554 mh.msg_iovlen = ELEMENTSOF(iovec);
556 if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) < 0)
563 static int log_dispatch(
569 const char *object_field,
575 if (log_target == LOG_TARGET_NULL)
578 /* Patch in LOG_DAEMON facility if necessary */
579 if ((level & LOG_FACMASK) == 0)
580 level = log_facility | LOG_PRI(level);
589 buffer += strspn(buffer, NEWLINE);
594 if ((e = strpbrk(buffer, NEWLINE)))
597 #if 0 /// elogind does not support logging to systemd-journald
598 if (log_target == LOG_TARGET_AUTO ||
599 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
600 log_target == LOG_TARGET_JOURNAL) {
602 k = write_to_journal(level, error, file, line, func, object_field, object, buffer);
611 if (log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
612 log_target == LOG_TARGET_SYSLOG) {
614 k = write_to_syslog(level, error, file, line, func, object_field, object, buffer);
623 (log_target == LOG_TARGET_AUTO ||
624 log_target == LOG_TARGET_SAFE ||
625 log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
626 /// UNNEEDED by elogind log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
627 log_target == LOG_TARGET_KMSG)) {
629 k = write_to_kmsg(level, error, file, line, func, object_field, object, buffer);
637 (void) write_to_console(level, error, file, line, func, object_field, object, buffer);
645 int log_dump_internal(
655 /* This modifies the buffer... */
660 if (_likely_(LOG_PRI(level) > log_max_level))
663 return log_dispatch(level, error, file, line, func, NULL, NULL, buffer);
676 char buffer[LINE_MAX];
681 if (_likely_(LOG_PRI(level) > log_max_level))
684 /* Make sure that %m maps to the specified error */
688 vsnprintf(buffer, sizeof(buffer), format, ap);
690 return log_dispatch(level, error, file, line, func, NULL, NULL, buffer);
699 const char *format, ...) {
704 va_start(ap, format);
705 r = log_internalv(level, error, file, line, func, format, ap);
711 int log_object_internalv(
717 const char *object_field,
729 if (_likely_(LOG_PRI(level) > log_max_level))
732 /* Make sure that %m maps to the specified error */
736 /* Prepend the object name before the message */
741 l = n + 2 + LINE_MAX;
743 buffer = newa(char, l);
744 b = stpcpy(stpcpy(buffer, object), ": ");
747 b = buffer = newa(char, l);
750 vsnprintf(b, l, format, ap);
752 return log_dispatch(level, error, file, line, func, object_field, object, buffer);
755 int log_object_internal(
761 const char *object_field,
763 const char *format, ...) {
768 va_start(ap, format);
769 r = log_object_internalv(level, error, file, line, func, object_field, object, format, ap);
775 static void log_assert(
781 const char *format) {
783 static char buffer[LINE_MAX];
785 if (_likely_(LOG_PRI(level) > log_max_level))
788 DISABLE_WARNING_FORMAT_NONLITERAL;
789 xsprintf(buffer, format, text, file, line, func);
792 log_abort_msg = buffer;
794 log_dispatch(level, 0, file, line, func, NULL, NULL, buffer);
797 noreturn void log_assert_failed(const char *text, const char *file, int line, const char *func) {
798 log_assert(LOG_CRIT, text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
802 noreturn void log_assert_failed_unreachable(const char *text, const char *file, int line, const char *func) {
803 log_assert(LOG_CRIT, text, file, line, func, "Code should not be reached '%s' at %s:%u, function %s(). Aborting.");
807 void log_assert_failed_return(const char *text, const char *file, int line, const char *func) {
809 log_assert(LOG_DEBUG, text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
812 int log_oom_internal(const char *file, int line, const char *func) {
813 log_internal(LOG_ERR, ENOMEM, file, line, func, "Out of memory.");
817 int log_format_iovec(
821 bool newline_separator,
826 static const char nl = '\n';
828 while (format && *n + 1 < iovec_len) {
833 /* We need to copy the va_list structure,
834 * since vasprintf() leaves it afterwards at
835 * an undefined location */
841 r = vasprintf(&m, format, aq);
846 /* Now, jump enough ahead, so that we point to
847 * the next format string */
848 VA_FORMAT_ADVANCE(format, ap);
850 IOVEC_SET_STRING(iovec[(*n)++], m);
852 if (newline_separator) {
853 iovec[*n].iov_base = (char*) &nl;
854 iovec[*n].iov_len = 1;
858 format = va_arg(ap, char *);
863 int log_struct_internal(
869 const char *format, ...) {
879 if (_likely_(LOG_PRI(level) > log_max_level))
882 if (log_target == LOG_TARGET_NULL)
885 if ((level & LOG_FACMASK) == 0)
886 level = log_facility | LOG_PRI(level);
888 #if 0 /// elogind does not support logging to systemd-journald
889 if ((log_target == LOG_TARGET_AUTO ||
890 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
891 log_target == LOG_TARGET_JOURNAL) &&
893 char header[LINE_MAX];
894 struct iovec iovec[17] = {};
900 bool fallback = false;
902 /* If the journal is available do structured logging */
903 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL);
904 IOVEC_SET_STRING(iovec[n++], header);
906 va_start(ap, format);
907 r = log_format_iovec(iovec, ELEMENTSOF(iovec), &n, true, error, format, ap);
912 (void) sendmsg(journal_fd, &mh, MSG_NOSIGNAL);
916 for (i = 1; i < n; i += 2)
917 free(iovec[i].iov_base);
924 /* Fallback if journal logging is not available or didn't work. */
926 va_start(ap, format);
934 vsnprintf(buf, sizeof(buf), format, aq);
937 if (startswith(buf, "MESSAGE=")) {
942 VA_FORMAT_ADVANCE(format, ap);
944 format = va_arg(ap, char *);
951 return log_dispatch(level, error, file, line, func, NULL, NULL, buf + 8);
954 int log_set_target_from_string(const char *e) {
957 t = log_target_from_string(e);
965 int log_set_max_level_from_string(const char *e) {
968 t = log_level_from_string(e);
972 log_set_max_level(t);
976 static int parse_proc_cmdline_item(const char *key, const char *value) {
979 * The systemd.log_xyz= settings are parsed by all tools, and
982 * However, "quiet" is only parsed by PID 1, and only turns of
983 * status output to /dev/console, but does not alter the log
987 if (streq(key, "debug") && !value)
988 log_set_max_level(LOG_DEBUG);
990 else if (streq(key, "systemd.log_target") && value) {
992 if (log_set_target_from_string(value) < 0)
993 log_warning("Failed to parse log target '%s'. Ignoring.", value);
995 } else if (streq(key, "systemd.log_level") && value) {
997 if (log_set_max_level_from_string(value) < 0)
998 log_warning("Failed to parse log level '%s'. Ignoring.", value);
1000 } else if (streq(key, "systemd.log_color") && value) {
1002 if (log_show_color_from_string(value) < 0)
1003 log_warning("Failed to parse log color setting '%s'. Ignoring.", value);
1005 } else if (streq(key, "systemd.log_location") && value) {
1007 if (log_show_location_from_string(value) < 0)
1008 log_warning("Failed to parse log location setting '%s'. Ignoring.", value);
1014 void log_parse_environment(void) {
1017 if (get_ctty_devnr(0, NULL) < 0)
1018 /* Only try to read the command line in daemons.
1019 We assume that anything that has a controlling
1020 tty is user stuff. */
1021 (void) parse_proc_cmdline(parse_proc_cmdline_item);
1023 e = secure_getenv("SYSTEMD_LOG_TARGET");
1024 if (e && log_set_target_from_string(e) < 0)
1025 log_warning("Failed to parse log target '%s'. Ignoring.", e);
1027 e = secure_getenv("SYSTEMD_LOG_LEVEL");
1028 if (e && log_set_max_level_from_string(e) < 0)
1029 log_warning("Failed to parse log level '%s'. Ignoring.", e);
1031 e = secure_getenv("SYSTEMD_LOG_COLOR");
1032 if (e && log_show_color_from_string(e) < 0)
1033 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1035 e = secure_getenv("SYSTEMD_LOG_LOCATION");
1036 if (e && log_show_location_from_string(e) < 0)
1037 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1040 LogTarget log_get_target(void) {
1044 int log_get_max_level(void) {
1045 return log_max_level;
1048 void log_show_color(bool b) {
1052 bool log_get_show_color(void) {
1056 void log_show_location(bool b) {
1060 bool log_get_show_location(void) {
1061 return show_location;
1064 int log_show_color_from_string(const char *e) {
1067 t = parse_boolean(e);
1075 int log_show_location_from_string(const char *e) {
1078 t = parse_boolean(e);
1082 log_show_location(t);
1086 bool log_on_console(void) {
1087 if (log_target == LOG_TARGET_CONSOLE ||
1088 log_target == LOG_TARGET_CONSOLE_PREFIXED)
1091 return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
1094 static const char *const log_target_table[_LOG_TARGET_MAX] = {
1095 [LOG_TARGET_CONSOLE] = "console",
1096 [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1097 [LOG_TARGET_KMSG] = "kmsg",
1098 #if 0 /// elogind does not support logging to systemd-journald
1099 [LOG_TARGET_JOURNAL] = "journal",
1100 [LOG_TARGET_JOURNAL_OR_KMSG] = "journal-or-kmsg",
1102 [LOG_TARGET_SYSLOG] = "syslog",
1103 [LOG_TARGET_SYSLOG_OR_KMSG] = "syslog-or-kmsg",
1104 [LOG_TARGET_AUTO] = "auto",
1105 [LOG_TARGET_SAFE] = "safe",
1106 [LOG_TARGET_NULL] = "null"
1109 DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
1111 #if 0 /// UNNEEDED by elogind
1112 void log_received_signal(int level, const struct signalfd_siginfo *si) {
1113 if (si->ssi_pid > 0) {
1114 _cleanup_free_ char *p = NULL;
1116 get_process_comm(si->ssi_pid, &p);
1119 "Received SIG%s from PID %"PRIu32" (%s).",
1120 signal_to_string(si->ssi_signo),
1121 si->ssi_pid, strna(p));
1125 signal_to_string(si->ssi_signo));
1129 void log_set_upgrade_syslog_to_journal(bool b) {
1130 upgrade_syslog_to_journal = b;
1134 int log_syntax_internal(
1137 const char *config_file,
1138 unsigned config_line,
1143 const char *format, ...) {
1146 char buffer[LINE_MAX];
1153 if (_likely_(LOG_PRI(level) > log_max_level))
1156 if (log_target == LOG_TARGET_NULL)
1162 va_start(ap, format);
1163 vsnprintf(buffer, sizeof(buffer), format, ap);
1167 r = log_struct_internal(
1170 getpid() == 1 ? "UNIT=%s" : "USER_UNIT=%s", unit,
1171 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION),
1172 "CONFIG_FILE=%s", config_file,
1173 "CONFIG_LINE=%u", config_line,
1174 LOG_MESSAGE("[%s:%u] %s", config_file, config_line, buffer),
1177 r = log_struct_internal(
1180 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION),
1181 "CONFIG_FILE=%s", config_file,
1182 "CONFIG_LINE=%u", config_line,
1183 LOG_MESSAGE("[%s:%u] %s", config_file, config_line, buffer),