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 void parse_priority(char **p, int *priority) {
97 int a = 0, b = 0, c = 0;
107 if (!strchr(*p, '>'))
110 if ((*p)[2] == '>') {
111 c = undecchar((*p)[1]);
113 } else if ((*p)[3] == '>') {
114 b = undecchar((*p)[1]);
115 c = undecchar((*p)[2]);
117 } else if ((*p)[4] == '>') {
118 a = undecchar((*p)[1]);
119 b = undecchar((*p)[2]);
120 c = undecchar((*p)[3]);
125 if (a < 0 || b < 0 || c < 0)
128 *priority = a*100+b*10+c;
132 static int stream_log(Stream *s, char *p, usec_t ts) {
134 char header_priority[16], header_time[64], header_pid[16];
135 struct iovec iovec[5];
141 priority = s->priority;
144 parse_priority(&p, &priority);
148 p[1] >= '0' && p[1] <= '7' &&
151 /* Detected priority prefix */
152 priority = LOG_MAKEPRI(LOG_FAC(priority), (p[1] - '0'));
160 /* Patch in LOG_USER facility if necessary */
161 if (LOG_FAC(priority) == 0)
162 priority = LOG_MAKEPRI(LOG_USER, LOG_PRI(priority));
165 * The format glibc uses to talk to the syslog daemon is:
167 * <priority>time process[pid]: msg
169 * The format the kernel uses is:
173 * We extend the latter to include the process name and pid.
176 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
177 char_array_0(header_priority);
179 if (s->target == STREAM_SYSLOG) {
183 t = (time_t) (ts / USEC_PER_SEC);
184 if (!(tm = localtime(&t)))
187 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
191 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) s->pid);
192 char_array_0(header_pid);
195 IOVEC_SET_STRING(iovec[0], header_priority);
197 if (s->target == STREAM_SYSLOG) {
198 struct msghdr msghdr;
200 struct cmsghdr cmsghdr;
201 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
206 control.cmsghdr.cmsg_level = SOL_SOCKET;
207 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
208 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
210 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
215 IOVEC_SET_STRING(iovec[1], header_time);
216 IOVEC_SET_STRING(iovec[2], s->process);
217 IOVEC_SET_STRING(iovec[3], header_pid);
218 IOVEC_SET_STRING(iovec[4], p);
220 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
221 if (s->server->syslog_is_stream)
225 msghdr.msg_iov = iovec;
226 msghdr.msg_iovlen = ELEMENTSOF(iovec);
227 msghdr.msg_control = &control;
228 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
233 if ((n = sendmsg(s->server->syslog_fd, &msghdr, MSG_NOSIGNAL)) < 0) {
235 if (errno == ESRCH) {
238 /* Hmm, maybe the process this
239 * line originates from is
240 * dead? Then let's patch in
241 * our own pid and retry,
242 * since we have nothing
247 if (ucred->pid != our_pid) {
248 ucred->pid = our_pid;
256 if (!s->server->syslog_is_stream ||
257 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
260 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
263 } else if (s->target == STREAM_KMSG) {
264 IOVEC_SET_STRING(iovec[1], s->process);
265 IOVEC_SET_STRING(iovec[2], header_pid);
266 IOVEC_SET_STRING(iovec[3], p);
267 IOVEC_SET_STRING(iovec[4], (char*) "\n");
269 if (writev(s->server->kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
272 assert_not_reached("Unknown log target");
274 if (s->tee_console) {
277 if ((console = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) >= 0) {
278 IOVEC_SET_STRING(iovec[0], s->process);
279 IOVEC_SET_STRING(iovec[1], header_pid);
280 IOVEC_SET_STRING(iovec[2], p);
281 IOVEC_SET_STRING(iovec[3], (char*) "\n");
283 writev(console, iovec, 4);
291 static int stream_line(Stream *s, char *p, usec_t ts) {
302 if (streq(p, "syslog") || streq(p, "syslog+console"))
303 s->target = STREAM_SYSLOG;
304 else if (streq(p, "kmsg") || streq(p, "kmsg+console")) {
306 if (s->server->kmsg_fd >= 0 && s->uid == 0)
307 s->target = STREAM_KMSG;
309 log_warning("/dev/kmsg logging not available.");
313 log_warning("Failed to parse log target line.");
317 if (endswith(p, "+console"))
318 s->tee_console = true;
320 s->state = STREAM_PRIORITY;
323 case STREAM_PRIORITY:
324 if ((r = safe_atoi(p, &s->priority)) < 0) {
325 log_warning("Failed to parse log priority line: %m");
329 if (s->priority < 0) {
330 log_warning("Log priority negative: %m");
334 s->state = STREAM_PROCESS;
338 if (!(s->process = strdup(p)))
341 s->state = STREAM_PREFIX;
346 if ((r = parse_boolean(p)) < 0)
350 s->state = STREAM_RUNNING;
354 return stream_log(s, p, ts);
357 assert_not_reached("Unknown stream state");
360 static int stream_scan(Stream *s, usec_t ts) {
368 remaining = s->length;
372 if (!(newline = memchr(p, '\n', remaining)))
377 if ((r = stream_line(s, p, ts)) >= 0) {
378 remaining -= newline-p+1;
384 memmove(s->buffer, p, remaining);
385 s->length = remaining;
391 static int stream_process(Stream *s, usec_t ts) {
396 if ((l = read(s->fd, s->buffer+s->length, LINE_MAX-s->length)) < 0) {
401 log_warning("Failed to read from stream: %m");
410 r = stream_scan(s, ts);
418 static void stream_free(Stream *s) {
422 assert(s->server->n_streams > 0);
423 s->server->n_streams--;
424 LIST_REMOVE(Stream, stream, s->server->streams, s);
430 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
432 close_nointr_nofail(s->fd);
439 static int stream_new(Server *s, int server_fd) {
443 socklen_t len = sizeof(ucred);
444 struct epoll_event ev;
449 if ((fd = accept4(server_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC)) < 0)
452 if (s->n_streams >= STREAMS_MAX) {
453 log_warning("Too many connections, refusing connection.");
454 close_nointr_nofail(fd);
458 if (!socket_tcpwrap(fd, "systemd-logger")) {
459 close_nointr_nofail(fd);
463 if (!(stream = new0(Stream, 1))) {
464 close_nointr_nofail(fd);
470 if (getsockopt(stream->fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) < 0) {
475 if (shutdown(fd, SHUT_WR) < 0) {
481 ev.data.ptr = stream;
483 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
488 stream->pid = ucred.pid;
489 stream->uid = ucred.uid;
490 stream->gid = ucred.gid;
493 LIST_PREPEND(Stream, stream, s->streams, stream);
503 static void server_done(Server *s) {
508 stream_free(s->streams);
510 for (i = 0; i < s->n_server_fd; i++)
511 close_nointr_nofail(SD_LISTEN_FDS_START+i);
513 if (s->syslog_fd >= 0)
514 close_nointr_nofail(s->syslog_fd);
516 if (s->epoll_fd >= 0)
517 close_nointr_nofail(s->epoll_fd);
520 close_nointr_nofail(s->kmsg_fd);
523 static int server_init(Server *s, unsigned n_sockets) {
528 struct sockaddr_un un;
532 assert(n_sockets > 0);
536 s->n_server_fd = n_sockets;
540 if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
542 log_error("Failed to create epoll object: %m");
546 for (i = 0; i < n_sockets; i++) {
547 struct epoll_event ev;
550 fd = SD_LISTEN_FDS_START+i;
552 if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_STREAM, 1)) < 0) {
553 log_error("Failed to determine file descriptor type: %s", strerror(-r));
558 log_error("Wrong file descriptor type.");
563 /* We use ev.data.ptr instead of ev.data.fd here,
564 * since on 64bit archs fd is 32bit while a pointer is
565 * 64bit. To make sure we can easily distinguish fd
566 * values and pointer values we want to make sure to
567 * write the full field unconditionally. */
571 ev.data.ptr = INT_TO_PTR(fd);
572 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
574 log_error("Failed to add server fd to epoll object: %m");
580 sa.un.sun_family = AF_UNIX;
581 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
583 if ((s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
585 log_error("Failed to create log fd: %m");
589 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
590 close_nointr_nofail(s->syslog_fd);
592 if ((s->syslog_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0)) < 0) {
594 log_error("Failed to create log fd: %m");
598 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
600 log_error("Failed to connect log socket to /dev/log: %m");
604 s->syslog_is_stream = true;
606 s->syslog_is_stream = false;
608 /* /dev/kmsg logging is strictly optional */
609 if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
610 log_warning("Failed to open /dev/kmsg for logging, disabling kernel log buffer support: %m");
619 static int process_event(Server *s, struct epoll_event *ev) {
624 /* Yes, this is a bit ugly, we assume that that valid pointers
625 * are > SD_LISTEN_FDS_START+SERVER_FD_MAX. Which is certainly
626 * true on Linux (and probably most other OSes, too, since the
627 * first 4k usually are part of a separate null pointer
628 * dereference page. */
630 if (PTR_TO_INT(ev->data.ptr) >= SD_LISTEN_FDS_START &&
631 PTR_TO_INT(ev->data.ptr) < SD_LISTEN_FDS_START+(int)s->n_server_fd) {
633 if (ev->events != EPOLLIN) {
634 log_info("Got invalid event from epoll. (1)");
638 if ((r = stream_new(s, PTR_TO_INT(ev->data.ptr))) < 0) {
639 log_info("Failed to accept new connection: %s", strerror(-r));
645 Stream *stream = ev->data.ptr;
647 ts = now(CLOCK_REALTIME);
649 if (!(ev->events & EPOLLIN)) {
650 log_info("Got invalid event from epoll. (2)");
655 if ((r = stream_process(stream, ts)) <= 0) {
658 log_info("Got error on stream: %s", strerror(-r));
668 int main(int argc, char *argv[]) {
670 int r = EXIT_FAILURE, n;
672 if (getppid() != 1) {
673 log_error("This program should be invoked by init only.");
678 log_error("This program does not take arguments.");
682 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
683 log_parse_environment();
686 if ((n = sd_listen_fds(true)) < 0) {
687 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
691 if (n <= 0 || n > SERVER_FD_MAX) {
692 log_error("No or too many file descriptors passed.");
696 if (server_init(&server, (unsigned) n) < 0)
699 log_debug("systemd-logger running as pid %lu", (unsigned long) getpid());
703 "STATUS=Processing requests...");
706 struct epoll_event event;
709 if ((k = epoll_wait(server.epoll_fd,
711 server.n_streams <= 0 ? TIMEOUT : -1)) < 0) {
716 log_error("epoll_wait() failed: %m");
723 if (process_event(&server, &event) < 0)
729 log_debug("systemd-logger stopped as pid %lu", (unsigned long) getpid());
733 "STATUS=Shutting down...");
735 server_done(&server);