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);
149 /* Patch in LOG_USER facility if necessary */
150 if ((priority & LOG_FACMASK) == 0)
151 priority = LOG_USER | LOG_PRI(priority);
154 * The format glibc uses to talk to the syslog daemon is:
156 * <priority>time process[pid]: msg
158 * The format the kernel uses is:
162 * We extend the latter to include the process name and pid.
165 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
166 char_array_0(header_priority);
168 if (s->target == STREAM_SYSLOG) {
172 t = (time_t) (ts / USEC_PER_SEC);
173 if (!(tm = localtime(&t)))
176 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
180 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) s->pid);
181 char_array_0(header_pid);
184 IOVEC_SET_STRING(iovec[0], header_priority);
186 if (s->target == STREAM_SYSLOG) {
187 struct msghdr msghdr;
189 struct cmsghdr cmsghdr;
190 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
195 control.cmsghdr.cmsg_level = SOL_SOCKET;
196 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
197 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
199 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
204 IOVEC_SET_STRING(iovec[1], header_time);
205 IOVEC_SET_STRING(iovec[2], s->process);
206 IOVEC_SET_STRING(iovec[3], header_pid);
207 IOVEC_SET_STRING(iovec[4], p);
209 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
210 if (s->server->syslog_is_stream)
214 msghdr.msg_iov = iovec;
215 msghdr.msg_iovlen = ELEMENTSOF(iovec);
216 msghdr.msg_control = &control;
217 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
222 if ((n = sendmsg(s->server->syslog_fd, &msghdr, MSG_NOSIGNAL)) < 0) {
224 if (errno == ESRCH) {
227 /* Hmm, maybe the process this
228 * line originates from is
229 * dead? Then let's patch in
230 * our own pid and retry,
231 * since we have nothing
236 if (ucred->pid != our_pid) {
237 ucred->pid = our_pid;
245 if (!s->server->syslog_is_stream ||
246 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
249 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
252 } else if (s->target == STREAM_KMSG) {
253 IOVEC_SET_STRING(iovec[1], s->process);
254 IOVEC_SET_STRING(iovec[2], header_pid);
255 IOVEC_SET_STRING(iovec[3], p);
256 IOVEC_SET_STRING(iovec[4], (char*) "\n");
258 if (writev(s->server->kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
261 assert_not_reached("Unknown log target");
263 if (s->tee_console) {
266 if ((console = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) >= 0) {
267 IOVEC_SET_STRING(iovec[0], s->process);
268 IOVEC_SET_STRING(iovec[1], header_pid);
269 IOVEC_SET_STRING(iovec[2], p);
270 IOVEC_SET_STRING(iovec[3], (char*) "\n");
272 writev(console, iovec, 4);
280 static int stream_line(Stream *s, char *p, usec_t ts) {
291 if (streq(p, "syslog") || streq(p, "syslog+console"))
292 s->target = STREAM_SYSLOG;
293 else if (streq(p, "kmsg") || streq(p, "kmsg+console")) {
295 if (s->server->kmsg_fd >= 0 && s->uid == 0)
296 s->target = STREAM_KMSG;
298 log_warning("/dev/kmsg logging not available.");
302 log_warning("Failed to parse log target line.");
306 if (endswith(p, "+console"))
307 s->tee_console = true;
309 s->state = STREAM_PRIORITY;
312 case STREAM_PRIORITY:
313 if ((r = safe_atoi(p, &s->priority)) < 0) {
314 log_warning("Failed to parse log priority line: %m");
318 if (s->priority < 0) {
319 log_warning("Log priority negative: %m");
323 s->state = STREAM_PROCESS;
327 if (!(s->process = strdup(p)))
330 s->state = STREAM_PREFIX;
335 if ((r = parse_boolean(p)) < 0)
339 s->state = STREAM_RUNNING;
343 return stream_log(s, p, ts);
346 assert_not_reached("Unknown stream state");
349 static int stream_scan(Stream *s, usec_t ts) {
357 remaining = s->length;
361 if (!(newline = memchr(p, '\n', remaining)))
366 if ((r = stream_line(s, p, ts)) >= 0) {
367 remaining -= newline-p+1;
373 memmove(s->buffer, p, remaining);
374 s->length = remaining;
380 static int stream_process(Stream *s, usec_t ts) {
385 if ((l = read(s->fd, s->buffer+s->length, LINE_MAX-s->length)) < 0) {
390 log_warning("Failed to read from stream: %m");
399 r = stream_scan(s, ts);
407 static void stream_free(Stream *s) {
411 assert(s->server->n_streams > 0);
412 s->server->n_streams--;
413 LIST_REMOVE(Stream, stream, s->server->streams, s);
419 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
421 close_nointr_nofail(s->fd);
428 static int stream_new(Server *s, int server_fd) {
432 socklen_t len = sizeof(ucred);
433 struct epoll_event ev;
438 if ((fd = accept4(server_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC)) < 0)
441 if (s->n_streams >= STREAMS_MAX) {
442 log_warning("Too many connections, refusing connection.");
443 close_nointr_nofail(fd);
447 if (!socket_tcpwrap(fd, "systemd-logger")) {
448 close_nointr_nofail(fd);
452 if (!(stream = new0(Stream, 1))) {
453 close_nointr_nofail(fd);
459 if (getsockopt(stream->fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) < 0) {
464 if (shutdown(fd, SHUT_WR) < 0) {
470 ev.data.ptr = stream;
472 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
477 stream->pid = ucred.pid;
478 stream->uid = ucred.uid;
479 stream->gid = ucred.gid;
482 LIST_PREPEND(Stream, stream, s->streams, stream);
492 static void server_done(Server *s) {
497 stream_free(s->streams);
499 for (i = 0; i < s->n_server_fd; i++)
500 close_nointr_nofail(SD_LISTEN_FDS_START+i);
502 if (s->syslog_fd >= 0)
503 close_nointr_nofail(s->syslog_fd);
505 if (s->epoll_fd >= 0)
506 close_nointr_nofail(s->epoll_fd);
509 close_nointr_nofail(s->kmsg_fd);
512 static int server_init(Server *s, unsigned n_sockets) {
517 struct sockaddr_un un;
521 assert(n_sockets > 0);
525 s->n_server_fd = n_sockets;
529 if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
531 log_error("Failed to create epoll object: %m");
535 for (i = 0; i < n_sockets; i++) {
536 struct epoll_event ev;
539 fd = SD_LISTEN_FDS_START+i;
541 if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_STREAM, 1)) < 0) {
542 log_error("Failed to determine file descriptor type: %s", strerror(-r));
547 log_error("Wrong file descriptor type.");
552 /* We use ev.data.ptr instead of ev.data.fd here,
553 * since on 64bit archs fd is 32bit while a pointer is
554 * 64bit. To make sure we can easily distinguish fd
555 * values and pointer values we want to make sure to
556 * write the full field unconditionally. */
560 ev.data.ptr = INT_TO_PTR(fd);
561 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
563 log_error("Failed to add server fd to epoll object: %m");
569 sa.un.sun_family = AF_UNIX;
570 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
572 if ((s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
574 log_error("Failed to create log fd: %m");
578 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
579 close_nointr_nofail(s->syslog_fd);
581 if ((s->syslog_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0)) < 0) {
583 log_error("Failed to create log fd: %m");
587 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
589 log_error("Failed to connect log socket to /dev/log: %m");
593 s->syslog_is_stream = true;
595 s->syslog_is_stream = false;
597 /* /dev/kmsg logging is strictly optional */
598 if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
599 log_warning("Failed to open /dev/kmsg for logging, disabling kernel log buffer support: %m");
608 static int process_event(Server *s, struct epoll_event *ev) {
613 /* Yes, this is a bit ugly, we assume that that valid pointers
614 * are > SD_LISTEN_FDS_START+SERVER_FD_MAX. Which is certainly
615 * true on Linux (and probably most other OSes, too, since the
616 * first 4k usually are part of a separate null pointer
617 * dereference page. */
619 if (PTR_TO_INT(ev->data.ptr) >= SD_LISTEN_FDS_START &&
620 PTR_TO_INT(ev->data.ptr) < SD_LISTEN_FDS_START+(int)s->n_server_fd) {
622 if (ev->events != EPOLLIN) {
623 log_info("Got invalid event from epoll. (1)");
627 if ((r = stream_new(s, PTR_TO_INT(ev->data.ptr))) < 0) {
628 log_info("Failed to accept new connection: %s", strerror(-r));
634 Stream *stream = ev->data.ptr;
636 ts = now(CLOCK_REALTIME);
638 if (!(ev->events & EPOLLIN)) {
639 log_info("Got invalid event from epoll. (2)");
644 if ((r = stream_process(stream, ts)) <= 0) {
647 log_info("Got error on stream: %s", strerror(-r));
657 int main(int argc, char *argv[]) {
659 int r = EXIT_FAILURE, n;
661 if (getppid() != 1) {
662 log_error("This program should be invoked by init only.");
667 log_error("This program does not take arguments.");
671 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
672 log_parse_environment();
675 if ((n = sd_listen_fds(true)) < 0) {
676 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
680 if (n <= 0 || n > SERVER_FD_MAX) {
681 log_error("No or too many file descriptors passed.");
685 if (server_init(&server, (unsigned) n) < 0)
688 log_debug("systemd-logger running as pid %lu", (unsigned long) getpid());
692 "STATUS=Processing requests...");
695 struct epoll_event event;
698 if ((k = epoll_wait(server.epoll_fd,
700 server.n_streams <= 0 ? TIMEOUT : -1)) < 0) {
705 log_error("epoll_wait() failed: %m");
712 if (process_event(&server, &event) < 0)
718 log_debug("systemd-logger stopped as pid %lu", (unsigned long) getpid());
722 "STATUS=Shutting down...");
724 server_done(&server);