1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include <sys/socket.h>
36 #include "socket-util.h"
37 #include "formats-util.h"
39 #define SNDBUF_SIZE (8*1024*1024)
41 static LogTarget log_target = LOG_TARGET_CONSOLE;
42 static int log_max_level = LOG_INFO;
43 static int log_facility = LOG_DAEMON;
45 static int console_fd = STDERR_FILENO;
46 static int syslog_fd = -1;
47 static int kmsg_fd = -1;
48 static int journal_fd = -1;
50 static bool syslog_is_stream = false;
52 static bool show_color = false;
53 static bool show_location = false;
55 static bool upgrade_syslog_to_journal = false;
57 /* Akin to glibc's __abort_msg; which is private and we hence cannot
59 static char *log_abort_msg = NULL;
61 void log_close_console(void) {
68 safe_close(console_fd);
74 static int log_open_console(void) {
80 console_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
84 console_fd = STDERR_FILENO;
89 void log_close_kmsg(void) {
90 kmsg_fd = safe_close(kmsg_fd);
93 static int log_open_kmsg(void) {
98 kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
105 void log_close_syslog(void) {
106 syslog_fd = safe_close(syslog_fd);
109 static int create_log_socket(int type) {
113 fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
117 fd_inc_sndbuf(fd, SNDBUF_SIZE);
119 /* We need a blocking fd here since we'd otherwise lose
120 messages way too early. However, let's not hang forever in the
121 unlikely case of a deadlock. */
123 timeval_store(&tv, 10 * USEC_PER_MSEC);
125 timeval_store(&tv, 10 * USEC_PER_SEC);
126 (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
131 static int log_open_syslog(void) {
133 static const union sockaddr_union sa = {
134 .un.sun_family = AF_UNIX,
135 .un.sun_path = "/dev/log",
143 syslog_fd = create_log_socket(SOCK_DGRAM);
149 if (connect(syslog_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
150 safe_close(syslog_fd);
152 /* Some legacy syslog systems still use stream
153 * sockets. They really shouldn't. But what can we
155 syslog_fd = create_log_socket(SOCK_STREAM);
161 if (connect(syslog_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
166 syslog_is_stream = true;
168 syslog_is_stream = false;
177 void log_close_journal(void) {
178 journal_fd = safe_close(journal_fd);
181 static int log_open_journal(void) {
183 static const union sockaddr_union sa = {
184 .un.sun_family = AF_UNIX,
185 .un.sun_path = "/run/systemd/journal/socket",
193 journal_fd = create_log_socket(SOCK_DGRAM);
194 if (journal_fd < 0) {
199 if (connect(journal_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
214 /* If we don't use the console we close it here, to not get
215 * killed by SAK. If we don't use syslog we close it here so
216 * that we are not confused by somebody deleting the socket in
217 * the fs. If we don't use /dev/kmsg we still keep it open,
218 * because there is no reason to close it. */
220 if (log_target == LOG_TARGET_NULL) {
227 if ((log_target != LOG_TARGET_AUTO && log_target != LOG_TARGET_SAFE) ||
229 isatty(STDERR_FILENO) <= 0) {
231 if (log_target == LOG_TARGET_AUTO ||
232 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
233 log_target == LOG_TARGET_JOURNAL) {
234 r = log_open_journal();
242 if (log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
243 log_target == LOG_TARGET_SYSLOG) {
244 r = log_open_syslog();
252 if (log_target == LOG_TARGET_AUTO ||
253 log_target == LOG_TARGET_SAFE ||
254 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
255 log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
256 log_target == LOG_TARGET_KMSG) {
270 return log_open_console();
273 void log_set_target(LogTarget target) {
275 assert(target < _LOG_TARGET_MAX);
277 if (upgrade_syslog_to_journal) {
278 if (target == LOG_TARGET_SYSLOG)
279 target = LOG_TARGET_JOURNAL;
280 else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
281 target = LOG_TARGET_JOURNAL_OR_KMSG;
287 void log_close(void) {
294 void log_forget_fds(void) {
295 console_fd = kmsg_fd = syslog_fd = journal_fd = -1;
298 void log_set_max_level(int level) {
299 assert((level & LOG_PRIMASK) == level);
301 log_max_level = level;
304 void log_set_facility(int facility) {
305 log_facility = facility;
308 static int write_to_console(
314 const char *object_field,
316 const char *buffer) {
318 char location[64], prefix[1 + DECIMAL_STR_MAX(int) + 2];
319 struct iovec iovec[6] = {};
326 if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
327 sprintf(prefix, "<%i>", level);
328 IOVEC_SET_STRING(iovec[n++], prefix);
331 highlight = LOG_PRI(level) <= LOG_ERR && show_color;
334 snprintf(location, sizeof(location), "(%s:%i) ", file, line);
335 IOVEC_SET_STRING(iovec[n++], location);
339 IOVEC_SET_STRING(iovec[n++], ANSI_HIGHLIGHT_RED_ON);
340 IOVEC_SET_STRING(iovec[n++], buffer);
342 IOVEC_SET_STRING(iovec[n++], ANSI_HIGHLIGHT_OFF);
343 IOVEC_SET_STRING(iovec[n++], "\n");
345 if (writev(console_fd, iovec, n) < 0) {
347 if (errno == EIO && getpid() == 1) {
349 /* If somebody tried to kick us from our
350 * console tty (via vhangup() or suchlike),
351 * try to reconnect */
359 if (writev(console_fd, iovec, n) < 0)
368 static int write_to_syslog(
374 const char *object_field,
376 const char *buffer) {
378 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
380 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
381 struct iovec iovec[5] = {};
382 struct msghdr msghdr = {
384 .msg_iovlen = ELEMENTSOF(iovec),
392 xsprintf(header_priority, "<%i>", level);
394 t = (time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC);
399 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
402 xsprintf(header_pid, "["PID_FMT"]: ", getpid());
404 IOVEC_SET_STRING(iovec[0], header_priority);
405 IOVEC_SET_STRING(iovec[1], header_time);
406 IOVEC_SET_STRING(iovec[2], program_invocation_short_name);
407 IOVEC_SET_STRING(iovec[3], header_pid);
408 IOVEC_SET_STRING(iovec[4], buffer);
410 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
411 if (syslog_is_stream)
417 n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
421 if (!syslog_is_stream ||
422 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
425 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
431 static int write_to_kmsg(
437 const char *object_field,
439 const char *buffer) {
441 char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
442 header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
443 struct iovec iovec[5] = {};
448 xsprintf(header_priority, "<%i>", level);
449 xsprintf(header_pid, "["PID_FMT"]: ", getpid());
451 IOVEC_SET_STRING(iovec[0], header_priority);
452 IOVEC_SET_STRING(iovec[1], program_invocation_short_name);
453 IOVEC_SET_STRING(iovec[2], header_pid);
454 IOVEC_SET_STRING(iovec[3], buffer);
455 IOVEC_SET_STRING(iovec[4], "\n");
457 if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
463 static int log_do_header(
468 const char *file, int line, const char *func,
469 const char *object_field, const char *object) {
471 snprintf(header, size,
473 "SYSLOG_FACILITY=%i\n"
479 "SYSLOG_IDENTIFIER=%s\n",
482 isempty(file) ? "" : "CODE_FILE=",
483 isempty(file) ? "" : file,
484 isempty(file) ? "" : "\n",
485 line ? "CODE_LINE=" : "",
486 line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
488 isempty(func) ? "" : "CODE_FUNCTION=",
489 isempty(func) ? "" : func,
490 isempty(func) ? "" : "\n",
491 error ? "ERRNO=" : "",
492 error ? 1 : 0, error,
494 isempty(object) ? "" : object_field,
495 isempty(object) ? "" : object,
496 isempty(object) ? "" : "\n",
497 program_invocation_short_name);
502 static int write_to_journal(
508 const char *object_field,
510 const char *buffer) {
512 char header[LINE_MAX];
513 struct iovec iovec[4] = {};
514 struct msghdr mh = {};
519 log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object);
521 IOVEC_SET_STRING(iovec[0], header);
522 IOVEC_SET_STRING(iovec[1], "MESSAGE=");
523 IOVEC_SET_STRING(iovec[2], buffer);
524 IOVEC_SET_STRING(iovec[3], "\n");
527 mh.msg_iovlen = ELEMENTSOF(iovec);
529 if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) < 0)
535 static int log_dispatch(
541 const char *object_field,
547 if (log_target == LOG_TARGET_NULL)
550 /* Patch in LOG_DAEMON facility if necessary */
551 if ((level & LOG_FACMASK) == 0)
552 level = log_facility | LOG_PRI(level);
561 buffer += strspn(buffer, NEWLINE);
566 if ((e = strpbrk(buffer, NEWLINE)))
569 if (log_target == LOG_TARGET_AUTO ||
570 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
571 log_target == LOG_TARGET_JOURNAL) {
573 k = write_to_journal(level, error, file, line, func, object_field, object, buffer);
581 if (log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
582 log_target == LOG_TARGET_SYSLOG) {
584 k = write_to_syslog(level, error, file, line, func, object_field, object, buffer);
593 (log_target == LOG_TARGET_AUTO ||
594 log_target == LOG_TARGET_SAFE ||
595 log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
596 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
597 log_target == LOG_TARGET_KMSG)) {
599 k = write_to_kmsg(level, error, file, line, func, object_field, object, buffer);
607 (void) write_to_console(level, error, file, line, func, object_field, object, buffer);
615 int log_dump_internal(
625 /* This modifies the buffer... */
630 if (_likely_(LOG_PRI(level) > log_max_level))
633 return log_dispatch(level, error, file, line, func, NULL, NULL, buffer);
646 char buffer[LINE_MAX];
651 if (_likely_(LOG_PRI(level) > log_max_level))
654 /* Make sure that %m maps to the specified error */
658 vsnprintf(buffer, sizeof(buffer), format, ap);
660 return log_dispatch(level, error, file, line, func, NULL, NULL, buffer);
669 const char *format, ...) {
674 va_start(ap, format);
675 r = log_internalv(level, error, file, line, func, format, ap);
681 int log_object_internalv(
687 const char *object_field,
693 char buffer[LINE_MAX];
698 if (_likely_(LOG_PRI(level) > log_max_level))
701 /* Make sure that %m maps to the specified error */
705 vsnprintf(buffer, sizeof(buffer), format, ap);
707 return log_dispatch(level, error, file, line, func, object_field, object, buffer);
710 int log_object_internal(
716 const char *object_field,
718 const char *format, ...) {
723 va_start(ap, format);
724 r = log_object_internalv(level, error, file, line, func, object_field, object, format, ap);
730 static void log_assert(
736 const char *format) {
738 static char buffer[LINE_MAX];
740 if (_likely_(LOG_PRI(level) > log_max_level))
743 DISABLE_WARNING_FORMAT_NONLITERAL;
744 snprintf(buffer, sizeof(buffer), format, text, file, line, func);
747 log_abort_msg = buffer;
749 log_dispatch(level, 0, file, line, func, NULL, NULL, buffer);
752 noreturn void log_assert_failed(const char *text, const char *file, int line, const char *func) {
753 log_assert(LOG_CRIT, text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
757 noreturn void log_assert_failed_unreachable(const char *text, const char *file, int line, const char *func) {
758 log_assert(LOG_CRIT, text, file, line, func, "Code should not be reached '%s' at %s:%u, function %s(). Aborting.");
762 void log_assert_failed_return(const char *text, const char *file, int line, const char *func) {
764 log_assert(LOG_DEBUG, text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
767 int log_oom_internal(const char *file, int line, const char *func) {
768 log_internal(LOG_ERR, ENOMEM, file, line, func, "Out of memory.");
772 int log_struct_internal(
778 const char *format, ...) {
788 if (_likely_(LOG_PRI(level) > log_max_level))
791 if (log_target == LOG_TARGET_NULL)
794 if ((level & LOG_FACMASK) == 0)
795 level = log_facility | LOG_PRI(level);
797 if ((log_target == LOG_TARGET_AUTO ||
798 log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
799 log_target == LOG_TARGET_JOURNAL) &&
801 char header[LINE_MAX];
802 struct iovec iovec[17] = {};
807 static const char nl = '\n';
808 bool fallback = false;
810 /* If the journal is available do structured logging */
811 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL);
812 IOVEC_SET_STRING(iovec[n++], header);
814 va_start(ap, format);
815 while (format && n + 1 < ELEMENTSOF(iovec)) {
819 /* We need to copy the va_list structure,
820 * since vasprintf() leaves it afterwards at
821 * an undefined location */
827 if (vasprintf(&m, format, aq) < 0) {
834 /* Now, jump enough ahead, so that we point to
835 * the next format string */
836 VA_FORMAT_ADVANCE(format, ap);
838 IOVEC_SET_STRING(iovec[n++], m);
840 iovec[n].iov_base = (char*) &nl;
841 iovec[n].iov_len = 1;
844 format = va_arg(ap, char *);
849 (void) sendmsg(journal_fd, &mh, MSG_NOSIGNAL);
853 for (i = 1; i < n; i += 2)
854 free(iovec[i].iov_base);
860 /* Fallback if journal logging is not available or didn't work. */
862 va_start(ap, format);
870 vsnprintf(buf, sizeof(buf), format, aq);
873 if (startswith(buf, "MESSAGE=")) {
878 VA_FORMAT_ADVANCE(format, ap);
880 format = va_arg(ap, char *);
887 return log_dispatch(level, error, file, line, func, NULL, NULL, buf + 8);
890 int log_set_target_from_string(const char *e) {
893 t = log_target_from_string(e);
901 int log_set_max_level_from_string(const char *e) {
904 t = log_level_from_string(e);
908 log_set_max_level(t);
912 static int parse_proc_cmdline_item(const char *key, const char *value) {
915 * The systemd.log_xyz= settings are parsed by all tools, and
918 * However, "quiet" is only parsed by PID 1, and only turns of
919 * status output to /dev/console, but does not alter the log
923 if (streq(key, "debug") && !value)
924 log_set_max_level(LOG_DEBUG);
926 else if (streq(key, "systemd.log_target") && value) {
928 if (log_set_target_from_string(value) < 0)
929 log_warning("Failed to parse log target '%s'. Ignoring.", value);
931 } else if (streq(key, "systemd.log_level") && value) {
933 if (log_set_max_level_from_string(value) < 0)
934 log_warning("Failed to parse log level '%s'. Ignoring.", value);
936 } else if (streq(key, "systemd.log_color") && value) {
938 if (log_show_color_from_string(value) < 0)
939 log_warning("Failed to parse log color setting '%s'. Ignoring.", value);
941 } else if (streq(key, "systemd.log_location") && value) {
943 if (log_show_location_from_string(value) < 0)
944 log_warning("Failed to parse log location setting '%s'. Ignoring.", value);
950 void log_parse_environment(void) {
953 if (get_ctty_devnr(0, NULL) < 0)
954 /* Only try to read the command line in daemons.
955 We assume that anything that has a controlling
956 tty is user stuff. */
957 (void) parse_proc_cmdline(parse_proc_cmdline_item);
959 e = secure_getenv("SYSTEMD_LOG_TARGET");
960 if (e && log_set_target_from_string(e) < 0)
961 log_warning("Failed to parse log target '%s'. Ignoring.", e);
963 e = secure_getenv("SYSTEMD_LOG_LEVEL");
964 if (e && log_set_max_level_from_string(e) < 0)
965 log_warning("Failed to parse log level '%s'. Ignoring.", e);
967 e = secure_getenv("SYSTEMD_LOG_COLOR");
968 if (e && log_show_color_from_string(e) < 0)
969 log_warning("Failed to parse bool '%s'. Ignoring.", e);
971 e = secure_getenv("SYSTEMD_LOG_LOCATION");
972 if (e && log_show_location_from_string(e) < 0)
973 log_warning("Failed to parse bool '%s'. Ignoring.", e);
976 LogTarget log_get_target(void) {
980 int log_get_max_level(void) {
981 return log_max_level;
984 void log_show_color(bool b) {
988 bool log_get_show_color(void) {
992 void log_show_location(bool b) {
996 bool log_get_show_location(void) {
997 return show_location;
1000 int log_show_color_from_string(const char *e) {
1003 t = parse_boolean(e);
1011 int log_show_location_from_string(const char *e) {
1014 t = parse_boolean(e);
1018 log_show_location(t);
1022 bool log_on_console(void) {
1023 if (log_target == LOG_TARGET_CONSOLE ||
1024 log_target == LOG_TARGET_CONSOLE_PREFIXED)
1027 return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
1030 static const char *const log_target_table[_LOG_TARGET_MAX] = {
1031 [LOG_TARGET_CONSOLE] = "console",
1032 [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1033 [LOG_TARGET_KMSG] = "kmsg",
1034 [LOG_TARGET_JOURNAL] = "journal",
1035 [LOG_TARGET_JOURNAL_OR_KMSG] = "journal-or-kmsg",
1036 [LOG_TARGET_SYSLOG] = "syslog",
1037 [LOG_TARGET_SYSLOG_OR_KMSG] = "syslog-or-kmsg",
1038 [LOG_TARGET_AUTO] = "auto",
1039 [LOG_TARGET_SAFE] = "safe",
1040 [LOG_TARGET_NULL] = "null"
1043 DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
1045 void log_received_signal(int level, const struct signalfd_siginfo *si) {
1046 if (si->ssi_pid > 0) {
1047 _cleanup_free_ char *p = NULL;
1049 get_process_comm(si->ssi_pid, &p);
1052 "Received SIG%s from PID %"PRIu32" (%s).",
1053 signal_to_string(si->ssi_signo),
1054 si->ssi_pid, strna(p));
1058 signal_to_string(si->ssi_signo));
1062 void log_set_upgrade_syslog_to_journal(bool b) {
1063 upgrade_syslog_to_journal = b;