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 General Public License as published by
10 the Free Software Foundation; either version 2 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 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/socket.h>
23 #include <sys/types.h>
31 #include <sys/epoll.h>
38 #include "sd-daemon.h"
41 #define STREAMS_MAX 4096
42 #define SERVER_FD_MAX 16
43 #define TIMEOUT ((int) (5*60*MSEC_PER_SEC))
45 typedef struct Stream Stream;
47 typedef struct Server {
54 bool syslog_is_stream;
56 LIST_HEAD(Stream, streams);
60 typedef enum StreamTarget {
65 typedef enum StreamState {
90 char buffer[LINE_MAX];
93 LIST_FIELDS(Stream, stream);
96 static int stream_log(Stream *s, char *p, usec_t ts) {
98 char header_priority[16], header_time[64], header_pid[16];
99 struct iovec iovec[5];
105 priority = s->priority;
109 p[1] >= '0' && p[1] <= '7' &&
112 /* Detected priority prefix */
113 priority = LOG_MAKEPRI(LOG_FAC(priority), (p[1] - '0'));
122 * The format glibc uses to talk to the syslog daemon is:
124 * <priority>time process[pid]: msg
126 * The format the kernel uses is:
130 * We extend the latter to include the process name and pid.
133 snprintf(header_priority, sizeof(header_priority), "<%i>",
134 s->target == STREAM_SYSLOG ? priority : LOG_PRI(priority));
135 char_array_0(header_priority);
137 if (s->target == STREAM_SYSLOG) {
141 t = (time_t) (ts / USEC_PER_SEC);
142 if (!(tm = localtime(&t)))
145 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
149 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) s->pid);
150 char_array_0(header_pid);
153 IOVEC_SET_STRING(iovec[0], header_priority);
155 if (s->target == STREAM_SYSLOG) {
156 struct msghdr msghdr;
158 struct cmsghdr cmsghdr;
159 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
164 control.cmsghdr.cmsg_level = SOL_SOCKET;
165 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
166 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
168 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
173 IOVEC_SET_STRING(iovec[1], header_time);
174 IOVEC_SET_STRING(iovec[2], s->process);
175 IOVEC_SET_STRING(iovec[3], header_pid);
176 IOVEC_SET_STRING(iovec[4], p);
178 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
179 if (s->server->syslog_is_stream)
183 msghdr.msg_iov = iovec;
184 msghdr.msg_iovlen = ELEMENTSOF(iovec);
185 msghdr.msg_control = &control;
186 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
191 if ((n = sendmsg(s->server->syslog_fd, &msghdr, MSG_NOSIGNAL)) < 0) {
193 if (errno == ESRCH) {
196 /* Hmm, maybe the process this
197 * line originates from is
198 * dead? Then let's patch in
199 * our own pid and retry,
200 * since we have nothing
205 if (ucred->pid != our_pid) {
206 ucred->pid = our_pid;
214 if (!s->server->syslog_is_stream ||
215 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
218 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
221 } else if (s->target == STREAM_KMSG) {
222 IOVEC_SET_STRING(iovec[1], s->process);
223 IOVEC_SET_STRING(iovec[2], header_pid);
224 IOVEC_SET_STRING(iovec[3], p);
225 IOVEC_SET_STRING(iovec[4], (char*) "\n");
227 if (writev(s->server->kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
230 assert_not_reached("Unknown log target");
232 if (s->tee_console) {
235 if ((console = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) >= 0) {
236 IOVEC_SET_STRING(iovec[0], s->process);
237 IOVEC_SET_STRING(iovec[1], header_pid);
238 IOVEC_SET_STRING(iovec[2], p);
239 IOVEC_SET_STRING(iovec[3], (char*) "\n");
241 writev(console, iovec, 4);
249 static int stream_line(Stream *s, char *p, usec_t ts) {
260 if (streq(p, "syslog") || streq(p, "syslog+console"))
261 s->target = STREAM_SYSLOG;
262 else if (streq(p, "kmsg") || streq(p, "kmsg+console")) {
264 if (s->server->kmsg_fd >= 0 && s->uid == 0)
265 s->target = STREAM_KMSG;
267 log_warning("/dev/kmsg logging not available.");
271 log_warning("Failed to parse log target line.");
275 if (endswith(p, "+console"))
276 s->tee_console = true;
278 s->state = STREAM_PRIORITY;
281 case STREAM_PRIORITY:
282 if ((r = safe_atoi(p, &s->priority)) < 0) {
283 log_warning("Failed to parse log priority line: %m");
287 if (s->priority < 0) {
288 log_warning("Log priority negative: %m");
292 s->state = STREAM_PROCESS;
296 if (!(s->process = strdup(p)))
299 s->state = STREAM_PREFIX;
304 if ((r = parse_boolean(p)) < 0)
308 s->state = STREAM_RUNNING;
312 return stream_log(s, p, ts);
315 assert_not_reached("Unknown stream state");
318 static int stream_scan(Stream *s, usec_t ts) {
326 remaining = s->length;
330 if (!(newline = memchr(p, '\n', remaining)))
335 if ((r = stream_line(s, p, ts)) >= 0) {
336 remaining -= newline-p+1;
342 memmove(s->buffer, p, remaining);
343 s->length = remaining;
349 static int stream_process(Stream *s, usec_t ts) {
354 if ((l = read(s->fd, s->buffer+s->length, LINE_MAX-s->length)) < 0) {
359 log_warning("Failed to read from stream: %m");
368 r = stream_scan(s, ts);
376 static void stream_free(Stream *s) {
380 assert(s->server->n_streams > 0);
381 s->server->n_streams--;
382 LIST_REMOVE(Stream, stream, s->server->streams, s);
388 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
390 close_nointr_nofail(s->fd);
397 static int stream_new(Server *s, int server_fd) {
401 socklen_t len = sizeof(ucred);
402 struct epoll_event ev;
407 if ((fd = accept4(server_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC)) < 0)
410 if (s->n_streams >= STREAMS_MAX) {
411 log_warning("Too many connections, refusing connection.");
412 close_nointr_nofail(fd);
416 if (!socket_tcpwrap(fd, "systemd-logger")) {
417 close_nointr_nofail(fd);
421 if (!(stream = new0(Stream, 1))) {
422 close_nointr_nofail(fd);
428 if (getsockopt(stream->fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) < 0) {
433 if (shutdown(fd, SHUT_WR) < 0) {
439 ev.data.ptr = stream;
441 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
446 stream->pid = ucred.pid;
447 stream->uid = ucred.uid;
448 stream->gid = ucred.gid;
451 LIST_PREPEND(Stream, stream, s->streams, stream);
461 static void server_done(Server *s) {
466 stream_free(s->streams);
468 for (i = 0; i < s->n_server_fd; i++)
469 close_nointr_nofail(SD_LISTEN_FDS_START+i);
471 if (s->syslog_fd >= 0)
472 close_nointr_nofail(s->syslog_fd);
474 if (s->epoll_fd >= 0)
475 close_nointr_nofail(s->epoll_fd);
478 close_nointr_nofail(s->kmsg_fd);
481 static int server_init(Server *s, unsigned n_sockets) {
486 struct sockaddr_un un;
490 assert(n_sockets > 0);
494 s->n_server_fd = n_sockets;
498 if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
500 log_error("Failed to create epoll object: %m");
504 for (i = 0; i < n_sockets; i++) {
505 struct epoll_event ev;
508 fd = SD_LISTEN_FDS_START+i;
510 if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_STREAM, 1)) < 0) {
511 log_error("Failed to determine file descriptor type: %s", strerror(-r));
516 log_error("Wrong file descriptor type.");
521 /* We use ev.data.ptr instead of ev.data.fd here,
522 * since on 64bit archs fd is 32bit while a pointer is
523 * 64bit. To make sure we can easily distinguish fd
524 * values and pointer values we want to make sure to
525 * write the full field unconditionally. */
529 ev.data.ptr = INT_TO_PTR(fd);
530 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
532 log_error("Failed to add server fd to epoll object: %m");
538 sa.un.sun_family = AF_UNIX;
539 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
541 if ((s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
543 log_error("Failed to create log fd: %m");
547 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
548 close_nointr_nofail(s->syslog_fd);
550 if ((s->syslog_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0)) < 0) {
552 log_error("Failed to create log fd: %m");
556 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
558 log_error("Failed to connect log socket to /dev/log: %m");
562 s->syslog_is_stream = true;
564 s->syslog_is_stream = false;
566 /* /dev/kmsg logging is strictly optional */
567 if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
568 log_warning("Failed to open /dev/kmsg for logging, disabling kernel log buffer support: %m");
577 static int process_event(Server *s, struct epoll_event *ev) {
582 /* Yes, this is a bit ugly, we assume that that valid pointers
583 * are > SD_LISTEN_FDS_START+SERVER_FD_MAX. Which is certainly
584 * true on Linux (and probably most other OSes, too, since the
585 * first 4k usually are part of a separate null pointer
586 * dereference page. */
588 if (PTR_TO_INT(ev->data.ptr) >= SD_LISTEN_FDS_START &&
589 PTR_TO_INT(ev->data.ptr) < SD_LISTEN_FDS_START+(int)s->n_server_fd) {
591 if (ev->events != EPOLLIN) {
592 log_info("Got invalid event from epoll. (1)");
596 if ((r = stream_new(s, PTR_TO_INT(ev->data.ptr))) < 0) {
597 log_info("Failed to accept new connection: %s", strerror(-r));
603 Stream *stream = ev->data.ptr;
605 ts = now(CLOCK_REALTIME);
607 if (!(ev->events & EPOLLIN)) {
608 log_info("Got invalid event from epoll. (2)");
613 if ((r = stream_process(stream, ts)) <= 0) {
616 log_info("Got error on stream: %s", strerror(-r));
626 int main(int argc, char *argv[]) {
628 int r = EXIT_FAILURE, n;
630 if (getppid() != 1) {
631 log_error("This program should be invoked by init only.");
636 log_error("This program does not take arguments.");
640 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
641 log_parse_environment();
644 if ((n = sd_listen_fds(true)) < 0) {
645 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
649 if (n <= 0 || n > SERVER_FD_MAX) {
650 log_error("No or too many file descriptors passed.");
654 if (server_init(&server, (unsigned) n) < 0)
657 log_debug("systemd-logger running as pid %lu", (unsigned long) getpid());
661 "STATUS=Processing requests...");
664 struct epoll_event event;
667 if ((k = epoll_wait(server.epoll_fd,
669 server.n_streams <= 0 ? TIMEOUT : -1)) < 0) {
674 log_error("epoll_wait() failed: %m");
681 if (process_event(&server, &event) < 0)
687 log_debug("systemd-logger stopped as pid %lu", (unsigned long) getpid());
691 "STATUS=Shutting down...");
693 server_done(&server);