1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2011 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/>.
25 #include <sys/socket.h>
28 #include "journald-server.h"
29 #include "journald-console.h"
31 static bool prefix_timestamp(void) {
33 static int cached_printk_time = -1;
35 if (_unlikely_(cached_printk_time < 0)) {
36 _cleanup_free_ char *p = NULL;
39 read_one_line_file("/sys/module/printk/parameters/time", &p) >= 0
40 && parse_boolean(p) > 0;
43 return cached_printk_time;
46 void server_forward_console(
49 const char *identifier,
51 struct ucred *ucred) {
53 struct iovec iovec[5];
56 char tbuf[4 + DECIMAL_STR_MAX(ts.tv_sec) + DECIMAL_STR_MAX(ts.tv_nsec)-3 + 1];
58 _cleanup_free_ char *ident_buf = NULL;
64 if (LOG_PRI(priority) > s->max_level_console)
67 /* First: timestamp */
68 if (prefix_timestamp()) {
69 assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);
70 snprintf(tbuf, sizeof(tbuf), "[%5llu.%06llu] ",
71 (unsigned long long) ts.tv_sec,
72 (unsigned long long) ts.tv_nsec / 1000);
73 IOVEC_SET_STRING(iovec[n++], tbuf);
76 /* Second: identifier and PID */
79 get_process_comm(ucred->pid, &ident_buf);
80 identifier = ident_buf;
83 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
84 char_array_0(header_pid);
87 IOVEC_SET_STRING(iovec[n++], identifier);
89 IOVEC_SET_STRING(iovec[n++], header_pid);
90 } else if (identifier) {
91 IOVEC_SET_STRING(iovec[n++], identifier);
92 IOVEC_SET_STRING(iovec[n++], ": ");
96 IOVEC_SET_STRING(iovec[n++], message);
97 IOVEC_SET_STRING(iovec[n++], "\n");
99 tty = s->tty_path ? s->tty_path : "/dev/console";
101 fd = open_terminal(tty, O_WRONLY|O_NOCTTY|O_CLOEXEC);
103 log_debug("Failed to open %s for logging: %m", tty);
107 if (writev(fd, iovec, n) < 0)
108 log_debug("Failed to write to %s for logging: %m", tty);
110 close_nointr_nofail(fd);