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 #if 0 /// UNNEEDED by elogind
75 static bool upgrade_syslog_to_journal = false;
78 /* Akin to glibc's __abort_msg; which is private and we hence cannot
80 static char *log_abort_msg = NULL;
82 void log_close_console(void) {
89 safe_close(console_fd);
95 static int log_open_console(void) {
101 console_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
105 console_fd = STDERR_FILENO;
110 void log_close_kmsg(void) {
111 kmsg_fd = safe_close(kmsg_fd);
114 static int log_open_kmsg(void) {
119 kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
126 void log_close_syslog(void) {
127 syslog_fd = safe_close(syslog_fd);
130 static int create_log_socket(int type) {
134 fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
138 fd_inc_sndbuf(fd, SNDBUF_SIZE);
140 /* We need a blocking fd here since we'd otherwise lose
141 messages way too early. However, let's not hang forever in the
142 unlikely case of a deadlock. */
144 timeval_store(&tv, 10 * USEC_PER_MSEC);
146 timeval_store(&tv, 10 * USEC_PER_SEC);
147 (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
152 static int log_open_syslog(void) {
154 static const union sockaddr_union sa = {
155 .un.sun_family = AF_UNIX,
156 .un.sun_path = "/dev/log",
164 syslog_fd = create_log_socket(SOCK_DGRAM);
170 if (connect(syslog_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
171 safe_close(syslog_fd);
173 /* Some legacy syslog systems still use stream
174 * sockets. They really shouldn't. But what can we
176 syslog_fd = create_log_socket(SOCK_STREAM);
182 if (connect(syslog_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
187 syslog_is_stream = true;
189 syslog_is_stream = false;
198 void log_close_journal(void) {
199 #if 0 /// elogind does not support journald
200 journal_fd = safe_close(journal_fd);
204 #if 0 /// UNNEEDED by elogind
205 static int log_open_journal(void) {
207 static const union sockaddr_union sa = {
208 .un.sun_family = AF_UNIX,
209 .un.sun_path = "/run/systemd/journal/socket",
217 journal_fd = create_log_socket(SOCK_DGRAM);
218 if (journal_fd < 0) {
223 if (connect(journal_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
239 /* If we don't use the console we close it here, to not get
240 * killed by SAK. If we don't use syslog we close it here so
241 * that we are not confused by somebody deleting the socket in
242 * the fs. If we don't use /dev/kmsg we still keep it open,
243 * because there is no reason to close it. */
245 if (log_target == LOG_TARGET_NULL) {
252 if ((log_target != LOG_TARGET_AUTO && log_target != LOG_TARGET_SAFE) ||
254 isatty(STDERR_FILENO) <= 0) {
256 #if 0 /// elogind does not support logging to systemd-journald
257 if (log_target == LOG_TARGET_AUTO ||
258 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
259 log_target == LOG_TARGET_JOURNAL) {
260 r = log_open_journal();
269 if (log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
270 log_target == LOG_TARGET_SYSLOG) {
271 r = log_open_syslog();
279 if (log_target == LOG_TARGET_AUTO ||
280 log_target == LOG_TARGET_SAFE ||
281 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
282 log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
283 log_target == LOG_TARGET_KMSG) {
297 return log_open_console();
300 void log_set_target(LogTarget target) {
302 assert(target < _LOG_TARGET_MAX);
304 #if 0 /// elogind does not support logging to systemd-journald
305 if (upgrade_syslog_to_journal) {
306 if (target == LOG_TARGET_SYSLOG)
307 target = LOG_TARGET_JOURNAL;
308 else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
309 target = LOG_TARGET_JOURNAL_OR_KMSG;
316 void log_close(void) {
323 #if 0 /// UNNEEDED by elogind
324 void log_forget_fds(void) {
325 console_fd = kmsg_fd = syslog_fd = journal_fd = -1;
329 void log_set_max_level(int level) {
330 assert((level & LOG_PRIMASK) == level);
332 log_max_level = level;
335 void log_set_facility(int facility) {
336 log_facility = facility;
339 static int write_to_console(
345 const char *object_field,
347 const char *buffer) {
349 char location[256], prefix[1 + DECIMAL_STR_MAX(int) + 2];
350 struct iovec iovec[6] = {};
357 if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
358 sprintf(prefix, "<%i>", level);
359 IOVEC_SET_STRING(iovec[n++], prefix);
362 highlight = LOG_PRI(level) <= LOG_ERR && show_color;
365 snprintf(location, sizeof(location), "(%s:%i) ", file, line);
366 IOVEC_SET_STRING(iovec[n++], location);
370 IOVEC_SET_STRING(iovec[n++], ANSI_HIGHLIGHT_RED);
371 IOVEC_SET_STRING(iovec[n++], buffer);
373 IOVEC_SET_STRING(iovec[n++], ANSI_NORMAL);
374 IOVEC_SET_STRING(iovec[n++], "\n");
376 if (writev(console_fd, iovec, n) < 0) {
378 if (errno == EIO && getpid() == 1) {
380 /* If somebody tried to kick us from our
381 * console tty (via vhangup() or suchlike),
382 * try to reconnect */
390 if (writev(console_fd, iovec, n) < 0)
399 static int write_to_syslog(
405 const char *object_field,
407 const char *buffer) {
409 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
411 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
412 struct iovec iovec[5] = {};
413 struct msghdr msghdr = {
415 .msg_iovlen = ELEMENTSOF(iovec),
423 xsprintf(header_priority, "<%i>", level);
425 t = (time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC);
430 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
433 xsprintf(header_pid, "["PID_FMT"]: ", getpid());
435 IOVEC_SET_STRING(iovec[0], header_priority);
436 IOVEC_SET_STRING(iovec[1], header_time);
437 IOVEC_SET_STRING(iovec[2], program_invocation_short_name);
438 IOVEC_SET_STRING(iovec[3], header_pid);
439 IOVEC_SET_STRING(iovec[4], buffer);
441 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
442 if (syslog_is_stream)
448 n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
452 if (!syslog_is_stream ||
453 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
456 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
462 static int write_to_kmsg(
468 const char *object_field,
470 const char *buffer) {
472 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
473 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
474 struct iovec iovec[5] = {};
479 xsprintf(header_priority, "<%i>", level);
480 xsprintf(header_pid, "["PID_FMT"]: ", getpid());
482 IOVEC_SET_STRING(iovec[0], header_priority);
483 IOVEC_SET_STRING(iovec[1], program_invocation_short_name);
484 IOVEC_SET_STRING(iovec[2], header_pid);
485 IOVEC_SET_STRING(iovec[3], buffer);
486 IOVEC_SET_STRING(iovec[4], "\n");
488 if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
494 #if 0 /// UNNEEDED by elogind
495 static int log_do_header(
500 const char *file, int line, const char *func,
501 const char *object_field, const char *object) {
503 snprintf(header, size,
505 "SYSLOG_FACILITY=%i\n"
511 "SYSLOG_IDENTIFIER=%s\n",
514 isempty(file) ? "" : "CODE_FILE=",
515 isempty(file) ? "" : file,
516 isempty(file) ? "" : "\n",
517 line ? "CODE_LINE=" : "",
518 line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
520 isempty(func) ? "" : "CODE_FUNCTION=",
521 isempty(func) ? "" : func,
522 isempty(func) ? "" : "\n",
523 error ? "ERRNO=" : "",
524 error ? 1 : 0, error,
526 isempty(object) ? "" : object_field,
527 isempty(object) ? "" : object,
528 isempty(object) ? "" : "\n",
529 program_invocation_short_name);
534 static int write_to_journal(
540 const char *object_field,
542 const char *buffer) {
544 char header[LINE_MAX];
545 struct iovec iovec[4] = {};
546 struct msghdr mh = {};
551 log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object);
553 IOVEC_SET_STRING(iovec[0], header);
554 IOVEC_SET_STRING(iovec[1], "MESSAGE=");
555 IOVEC_SET_STRING(iovec[2], buffer);
556 IOVEC_SET_STRING(iovec[3], "\n");
559 mh.msg_iovlen = ELEMENTSOF(iovec);
561 if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) < 0)
568 static int log_dispatch(
574 const char *object_field,
580 if (log_target == LOG_TARGET_NULL)
583 /* Patch in LOG_DAEMON facility if necessary */
584 if ((level & LOG_FACMASK) == 0)
585 level = log_facility | LOG_PRI(level);
594 buffer += strspn(buffer, NEWLINE);
599 if ((e = strpbrk(buffer, NEWLINE)))
602 #if 0 /// elogind does not support logging to systemd-journald
603 if (log_target == LOG_TARGET_AUTO ||
604 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
605 log_target == LOG_TARGET_JOURNAL) {
607 k = write_to_journal(level, error, file, line, func, object_field, object, buffer);
616 if (log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
617 log_target == LOG_TARGET_SYSLOG) {
619 k = write_to_syslog(level, error, file, line, func, object_field, object, buffer);
628 (log_target == LOG_TARGET_AUTO ||
629 log_target == LOG_TARGET_SAFE ||
630 log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
631 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
632 log_target == LOG_TARGET_KMSG)) {
634 k = write_to_kmsg(level, error, file, line, func, object_field, object, buffer);
642 (void) write_to_console(level, error, file, line, func, object_field, object, buffer);
650 int log_dump_internal(
660 /* This modifies the buffer... */
665 if (_likely_(LOG_PRI(level) > log_max_level))
668 return log_dispatch(level, error, file, line, func, NULL, NULL, buffer);
681 char buffer[LINE_MAX];
686 if (_likely_(LOG_PRI(level) > log_max_level))
689 /* Make sure that %m maps to the specified error */
693 vsnprintf(buffer, sizeof(buffer), format, ap);
695 return log_dispatch(level, error, file, line, func, NULL, NULL, buffer);
704 const char *format, ...) {
709 va_start(ap, format);
710 r = log_internalv(level, error, file, line, func, format, ap);
716 int log_object_internalv(
722 const char *object_field,
734 if (_likely_(LOG_PRI(level) > log_max_level))
737 /* Make sure that %m maps to the specified error */
741 /* Prepend the object name before the message */
746 l = n + 2 + LINE_MAX;
748 buffer = newa(char, l);
749 b = stpcpy(stpcpy(buffer, object), ": ");
752 b = buffer = newa(char, l);
755 vsnprintf(b, l, format, ap);
757 return log_dispatch(level, error, file, line, func, object_field, object, buffer);
760 int log_object_internal(
766 const char *object_field,
768 const char *format, ...) {
773 va_start(ap, format);
774 r = log_object_internalv(level, error, file, line, func, object_field, object, format, ap);
780 static void log_assert(
786 const char *format) {
788 static char buffer[LINE_MAX];
790 if (_likely_(LOG_PRI(level) > log_max_level))
793 DISABLE_WARNING_FORMAT_NONLITERAL;
794 xsprintf(buffer, format, text, file, line, func);
797 log_abort_msg = buffer;
799 log_dispatch(level, 0, file, line, func, NULL, NULL, buffer);
802 noreturn void log_assert_failed(const char *text, const char *file, int line, const char *func) {
803 log_assert(LOG_CRIT, text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
807 noreturn void log_assert_failed_unreachable(const char *text, const char *file, int line, const char *func) {
808 log_assert(LOG_CRIT, text, file, line, func, "Code should not be reached '%s' at %s:%u, function %s(). Aborting.");
812 void log_assert_failed_return(const char *text, const char *file, int line, const char *func) {
814 log_assert(LOG_DEBUG, text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
817 int log_oom_internal(const char *file, int line, const char *func) {
818 log_internal(LOG_ERR, ENOMEM, file, line, func, "Out of memory.");
822 int log_format_iovec(
826 bool newline_separator,
831 static const char nl = '\n';
833 while (format && *n + 1 < iovec_len) {
838 /* We need to copy the va_list structure,
839 * since vasprintf() leaves it afterwards at
840 * an undefined location */
846 r = vasprintf(&m, format, aq);
851 /* Now, jump enough ahead, so that we point to
852 * the next format string */
853 VA_FORMAT_ADVANCE(format, ap);
855 IOVEC_SET_STRING(iovec[(*n)++], m);
857 if (newline_separator) {
858 iovec[*n].iov_base = (char*) &nl;
859 iovec[*n].iov_len = 1;
863 format = va_arg(ap, char *);
868 int log_struct_internal(
874 const char *format, ...) {
884 if (_likely_(LOG_PRI(level) > log_max_level))
887 if (log_target == LOG_TARGET_NULL)
890 if ((level & LOG_FACMASK) == 0)
891 level = log_facility | LOG_PRI(level);
893 #if 0 /// elogind does not support logging to systemd-journald
894 if ((log_target == LOG_TARGET_AUTO ||
895 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
896 log_target == LOG_TARGET_JOURNAL) &&
898 char header[LINE_MAX];
899 struct iovec iovec[17] = {};
905 bool fallback = false;
907 /* If the journal is available do structured logging */
908 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL);
909 IOVEC_SET_STRING(iovec[n++], header);
911 va_start(ap, format);
912 r = log_format_iovec(iovec, ELEMENTSOF(iovec), &n, true, error, format, ap);
917 (void) sendmsg(journal_fd, &mh, MSG_NOSIGNAL);
921 for (i = 1; i < n; i += 2)
922 free(iovec[i].iov_base);
929 /* Fallback if journal logging is not available or didn't work. */
931 va_start(ap, format);
939 vsnprintf(buf, sizeof(buf), format, aq);
942 if (startswith(buf, "MESSAGE=")) {
947 VA_FORMAT_ADVANCE(format, ap);
949 format = va_arg(ap, char *);
956 return log_dispatch(level, error, file, line, func, NULL, NULL, buf + 8);
959 int log_set_target_from_string(const char *e) {
962 t = log_target_from_string(e);
970 int log_set_max_level_from_string(const char *e) {
973 t = log_level_from_string(e);
977 log_set_max_level(t);
981 static int parse_proc_cmdline_item(const char *key, const char *value) {
984 * The systemd.log_xyz= settings are parsed by all tools, and
987 * However, "quiet" is only parsed by PID 1, and only turns of
988 * status output to /dev/console, but does not alter the log
992 if (streq(key, "debug") && !value)
993 log_set_max_level(LOG_DEBUG);
995 else if (streq(key, "systemd.log_target") && value) {
997 if (log_set_target_from_string(value) < 0)
998 log_warning("Failed to parse log target '%s'. Ignoring.", value);
1000 } else if (streq(key, "systemd.log_level") && value) {
1002 if (log_set_max_level_from_string(value) < 0)
1003 log_warning("Failed to parse log level '%s'. Ignoring.", value);
1005 } else if (streq(key, "systemd.log_color") && value) {
1007 if (log_show_color_from_string(value) < 0)
1008 log_warning("Failed to parse log color setting '%s'. Ignoring.", value);
1010 } else if (streq(key, "systemd.log_location") && value) {
1012 if (log_show_location_from_string(value) < 0)
1013 log_warning("Failed to parse log location setting '%s'. Ignoring.", value);
1019 void log_parse_environment(void) {
1022 if (get_ctty_devnr(0, NULL) < 0)
1023 /* Only try to read the command line in daemons.
1024 We assume that anything that has a controlling
1025 tty is user stuff. */
1026 (void) parse_proc_cmdline(parse_proc_cmdline_item);
1028 e = secure_getenv("SYSTEMD_LOG_TARGET");
1029 if (e && log_set_target_from_string(e) < 0)
1030 log_warning("Failed to parse log target '%s'. Ignoring.", e);
1032 e = secure_getenv("SYSTEMD_LOG_LEVEL");
1033 if (e && log_set_max_level_from_string(e) < 0)
1034 log_warning("Failed to parse log level '%s'. Ignoring.", e);
1036 e = secure_getenv("SYSTEMD_LOG_COLOR");
1037 if (e && log_show_color_from_string(e) < 0)
1038 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1040 e = secure_getenv("SYSTEMD_LOG_LOCATION");
1041 if (e && log_show_location_from_string(e) < 0)
1042 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1045 LogTarget log_get_target(void) {
1049 int log_get_max_level(void) {
1050 return log_max_level;
1053 void log_show_color(bool b) {
1057 bool log_get_show_color(void) {
1061 void log_show_location(bool b) {
1065 bool log_get_show_location(void) {
1066 return show_location;
1069 int log_show_color_from_string(const char *e) {
1072 t = parse_boolean(e);
1080 int log_show_location_from_string(const char *e) {
1083 t = parse_boolean(e);
1087 log_show_location(t);
1091 bool log_on_console(void) {
1092 if (log_target == LOG_TARGET_CONSOLE ||
1093 log_target == LOG_TARGET_CONSOLE_PREFIXED)
1096 return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
1099 static const char *const log_target_table[_LOG_TARGET_MAX] = {
1100 [LOG_TARGET_CONSOLE] = "console",
1101 [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1102 [LOG_TARGET_KMSG] = "kmsg",
1103 #if 0 /// elogind does not support logging to systemd-journald
1104 [LOG_TARGET_JOURNAL] = "journal",
1105 [LOG_TARGET_JOURNAL_OR_KMSG] = "journal-or-kmsg",
1107 [LOG_TARGET_SYSLOG] = "syslog",
1108 [LOG_TARGET_SYSLOG_OR_KMSG] = "syslog-or-kmsg",
1109 [LOG_TARGET_AUTO] = "auto",
1110 [LOG_TARGET_SAFE] = "safe",
1111 [LOG_TARGET_NULL] = "null"
1114 DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
1116 #if 0 /// UNNEEDED by elogind
1117 void log_received_signal(int level, const struct signalfd_siginfo *si) {
1118 if (si->ssi_pid > 0) {
1119 _cleanup_free_ char *p = NULL;
1121 get_process_comm(si->ssi_pid, &p);
1124 "Received SIG%s from PID %"PRIu32" (%s).",
1125 signal_to_string(si->ssi_signo),
1126 si->ssi_pid, strna(p));
1130 signal_to_string(si->ssi_signo));
1134 void log_set_upgrade_syslog_to_journal(bool b) {
1135 upgrade_syslog_to_journal = b;
1139 int log_syntax_internal(
1142 const char *config_file,
1143 unsigned config_line,
1148 const char *format, ...) {
1151 char buffer[LINE_MAX];
1158 if (_likely_(LOG_PRI(level) > log_max_level))
1161 if (log_target == LOG_TARGET_NULL)
1167 va_start(ap, format);
1168 vsnprintf(buffer, sizeof(buffer), format, ap);
1172 r = log_struct_internal(
1175 getpid() == 1 ? "UNIT=%s" : "USER_UNIT=%s", unit,
1176 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION),
1177 "CONFIG_FILE=%s", config_file,
1178 "CONFIG_LINE=%u", config_line,
1179 LOG_MESSAGE("[%s:%u] %s", config_file, config_line, buffer),
1182 r = log_struct_internal(
1185 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION),
1186 "CONFIG_FILE=%s", config_file,
1187 "CONFIG_LINE=%u", config_line,
1188 LOG_MESSAGE("[%s:%u] %s", config_file, config_line, buffer),