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"
42 #define STREAMS_MAX 4096
43 #define SERVER_FD_MAX 16
44 #define TIMEOUT_MSEC ((int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC))
46 typedef struct Stream Stream;
48 typedef struct Server {
55 bool syslog_is_stream;
57 LIST_HEAD(Stream, streams);
61 typedef enum StreamTarget {
66 typedef enum StreamState {
91 char buffer[LINE_MAX];
94 LIST_FIELDS(Stream, stream);
97 static int stream_log(Stream *s, char *p, usec_t ts) {
99 char header_priority[16], header_time[64], header_pid[16];
100 struct iovec iovec[5];
106 priority = s->priority;
109 parse_syslog_priority(&p, &priority);
114 /* Patch in LOG_USER facility if necessary */
115 if ((priority & LOG_FACMASK) == 0)
116 priority = LOG_USER | LOG_PRI(priority);
119 * The format glibc uses to talk to the syslog daemon is:
121 * <priority>time process[pid]: msg
123 * The format the kernel uses is:
127 * We extend the latter to include the process name and pid.
130 snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
131 char_array_0(header_priority);
133 if (s->target == STREAM_SYSLOG) {
137 t = (time_t) (ts / USEC_PER_SEC);
138 if (!(tm = localtime(&t)))
141 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
145 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) s->pid);
146 char_array_0(header_pid);
149 IOVEC_SET_STRING(iovec[0], header_priority);
151 if (s->target == STREAM_SYSLOG) {
152 struct msghdr msghdr;
154 struct cmsghdr cmsghdr;
155 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
160 control.cmsghdr.cmsg_level = SOL_SOCKET;
161 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
162 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
164 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
169 IOVEC_SET_STRING(iovec[1], header_time);
170 IOVEC_SET_STRING(iovec[2], s->process);
171 IOVEC_SET_STRING(iovec[3], header_pid);
172 IOVEC_SET_STRING(iovec[4], p);
174 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
175 if (s->server->syslog_is_stream)
179 msghdr.msg_iov = iovec;
180 msghdr.msg_iovlen = ELEMENTSOF(iovec);
181 msghdr.msg_control = &control;
182 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
187 if ((n = sendmsg(s->server->syslog_fd, &msghdr, MSG_NOSIGNAL)) < 0) {
189 if (errno == ESRCH) {
192 /* Hmm, maybe the process this
193 * line originates from is
194 * dead? Then let's patch in
195 * our own pid and retry,
196 * since we have nothing
201 if (ucred->pid != our_pid) {
202 ucred->pid = our_pid;
210 if (!s->server->syslog_is_stream ||
211 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
214 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
217 } else if (s->target == STREAM_KMSG) {
218 IOVEC_SET_STRING(iovec[1], s->process);
219 IOVEC_SET_STRING(iovec[2], header_pid);
220 IOVEC_SET_STRING(iovec[3], p);
221 IOVEC_SET_STRING(iovec[4], (char*) "\n");
223 if (writev(s->server->kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
226 assert_not_reached("Unknown log target");
228 if (s->tee_console) {
231 if ((console = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) >= 0) {
232 IOVEC_SET_STRING(iovec[0], s->process);
233 IOVEC_SET_STRING(iovec[1], header_pid);
234 IOVEC_SET_STRING(iovec[2], p);
235 IOVEC_SET_STRING(iovec[3], (char*) "\n");
237 writev(console, iovec, 4);
245 static int stream_line(Stream *s, char *p, usec_t ts) {
256 if (streq(p, "syslog") || streq(p, "syslog+console"))
257 s->target = STREAM_SYSLOG;
258 else if (streq(p, "kmsg") || streq(p, "kmsg+console")) {
260 if (s->server->kmsg_fd >= 0 && s->uid == 0)
261 s->target = STREAM_KMSG;
263 log_warning("/dev/kmsg logging not available.");
267 log_warning("Failed to parse log target line.");
271 if (endswith(p, "+console"))
272 s->tee_console = true;
274 s->state = STREAM_PRIORITY;
277 case STREAM_PRIORITY:
278 if ((r = safe_atoi(p, &s->priority)) < 0) {
279 log_warning("Failed to parse log priority line: %m");
283 if (s->priority < 0) {
284 log_warning("Log priority negative: %m");
288 s->state = STREAM_PROCESS;
292 if (!(s->process = strdup(p)))
295 s->state = STREAM_PREFIX;
300 if ((r = parse_boolean(p)) < 0)
304 s->state = STREAM_RUNNING;
308 return stream_log(s, p, ts);
311 assert_not_reached("Unknown stream state");
314 static int stream_scan(Stream *s, usec_t ts) {
322 remaining = s->length;
326 if (!(newline = memchr(p, '\n', remaining)))
331 if ((r = stream_line(s, p, ts)) >= 0) {
332 remaining -= newline-p+1;
338 memmove(s->buffer, p, remaining);
339 s->length = remaining;
345 static int stream_process(Stream *s, usec_t ts) {
350 if ((l = read(s->fd, s->buffer+s->length, LINE_MAX-s->length)) < 0) {
355 log_warning("Failed to read from stream: %m");
364 r = stream_scan(s, ts);
372 static void stream_free(Stream *s) {
376 assert(s->server->n_streams > 0);
377 s->server->n_streams--;
378 LIST_REMOVE(Stream, stream, s->server->streams, s);
384 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
386 close_nointr_nofail(s->fd);
393 static int stream_new(Server *s, int server_fd) {
397 socklen_t len = sizeof(ucred);
398 struct epoll_event ev;
403 if ((fd = accept4(server_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC)) < 0)
406 if (s->n_streams >= STREAMS_MAX) {
407 log_warning("Too many connections, refusing connection.");
408 close_nointr_nofail(fd);
412 if (!socket_tcpwrap(fd, "systemd-logger")) {
413 close_nointr_nofail(fd);
417 if (!(stream = new0(Stream, 1))) {
418 close_nointr_nofail(fd);
424 if (getsockopt(stream->fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) < 0) {
429 if (shutdown(fd, SHUT_WR) < 0) {
435 ev.data.ptr = stream;
437 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
442 stream->pid = ucred.pid;
443 stream->uid = ucred.uid;
444 stream->gid = ucred.gid;
447 LIST_PREPEND(Stream, stream, s->streams, stream);
457 static void server_done(Server *s) {
462 stream_free(s->streams);
464 for (i = 0; i < s->n_server_fd; i++)
465 close_nointr_nofail(SD_LISTEN_FDS_START+i);
467 if (s->syslog_fd >= 0)
468 close_nointr_nofail(s->syslog_fd);
470 if (s->epoll_fd >= 0)
471 close_nointr_nofail(s->epoll_fd);
474 close_nointr_nofail(s->kmsg_fd);
477 static int server_init(Server *s, unsigned n_sockets) {
482 struct sockaddr_un un;
486 assert(n_sockets > 0);
490 s->n_server_fd = n_sockets;
494 if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
496 log_error("Failed to create epoll object: %m");
500 for (i = 0; i < n_sockets; i++) {
501 struct epoll_event ev;
504 fd = SD_LISTEN_FDS_START+i;
506 if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_STREAM, 1)) < 0) {
507 log_error("Failed to determine file descriptor type: %s", strerror(-r));
512 log_error("Wrong file descriptor type.");
517 /* We use ev.data.ptr instead of ev.data.fd here,
518 * since on 64bit archs fd is 32bit while a pointer is
519 * 64bit. To make sure we can easily distinguish fd
520 * values and pointer values we want to make sure to
521 * write the full field unconditionally. */
525 ev.data.ptr = INT_TO_PTR(fd);
526 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
528 log_error("Failed to add server fd to epoll object: %m");
534 sa.un.sun_family = AF_UNIX;
535 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
537 if ((s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
539 log_error("Failed to create log fd: %m");
543 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
544 close_nointr_nofail(s->syslog_fd);
546 if ((s->syslog_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0)) < 0) {
548 log_error("Failed to create log fd: %m");
552 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
554 log_error("Failed to connect log socket to /dev/log: %m");
558 s->syslog_is_stream = true;
560 s->syslog_is_stream = false;
562 /* /dev/kmsg logging is strictly optional */
563 if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
564 log_warning("Failed to open /dev/kmsg for logging, disabling kernel log buffer support: %m");
573 static int process_event(Server *s, struct epoll_event *ev) {
578 /* Yes, this is a bit ugly, we assume that that valid pointers
579 * are > SD_LISTEN_FDS_START+SERVER_FD_MAX. Which is certainly
580 * true on Linux (and probably most other OSes, too, since the
581 * first 4k usually are part of a separate null pointer
582 * dereference page. */
584 if (PTR_TO_INT(ev->data.ptr) >= SD_LISTEN_FDS_START &&
585 PTR_TO_INT(ev->data.ptr) < SD_LISTEN_FDS_START+(int)s->n_server_fd) {
587 if (ev->events != EPOLLIN) {
588 log_info("Got invalid event from epoll. (1)");
592 if ((r = stream_new(s, PTR_TO_INT(ev->data.ptr))) < 0) {
593 log_info("Failed to accept new connection: %s", strerror(-r));
599 Stream *stream = ev->data.ptr;
601 ts = now(CLOCK_REALTIME);
603 if (!(ev->events & EPOLLIN)) {
604 log_info("Got invalid event from epoll. (2)");
609 if ((r = stream_process(stream, ts)) <= 0) {
612 log_info("Got error on stream: %s", strerror(-r));
622 int main(int argc, char *argv[]) {
624 int r = EXIT_FAILURE, n;
626 if (getppid() != 1) {
627 log_error("This program should be invoked by init only.");
632 log_error("This program does not take arguments.");
636 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
637 log_parse_environment();
640 if ((n = sd_listen_fds(true)) < 0) {
641 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
645 if (n <= 0 || n > SERVER_FD_MAX) {
646 log_error("No or too many file descriptors passed.");
650 if (server_init(&server, (unsigned) n) < 0)
653 log_debug("systemd-logger running as pid %lu", (unsigned long) getpid());
657 "STATUS=Processing requests...");
660 struct epoll_event event;
663 if ((k = epoll_wait(server.epoll_fd,
665 server.n_streams <= 0 ? TIMEOUT_MSEC : -1)) < 0) {
670 log_error("epoll_wait() failed: %m");
677 if (process_event(&server, &event) < 0)
683 log_debug("systemd-logger stopped as pid %lu", (unsigned long) getpid());
687 "STATUS=Shutting down...");
689 server_done(&server);