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 256
42 #define SERVER_FD_MAX 16
43 #define TIMEOUT ((int) (10*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 {
89 char buffer[LINE_MAX];
92 LIST_FIELDS(Stream, stream);
95 static int stream_log(Stream *s, char *p, usec_t ts) {
97 char header_priority[16], header_time[64], header_pid[16];
98 struct iovec iovec[5];
104 priority = s->priority;
108 p[1] >= '0' && p[1] <= '7' &&
111 /* Detected priority prefix */
112 priority = LOG_MAKEPRI(LOG_FAC(priority), (p[1] - '0'));
121 * The format glibc uses to talk to the syslog daemon is:
123 * <priority>time process[pid]: msg
125 * The format the kernel uses is:
129 * We extend the latter to include the process name and pid.
132 snprintf(header_priority, sizeof(header_priority), "<%i>",
133 s->target == STREAM_SYSLOG ? priority : LOG_PRI(priority));
134 char_array_0(header_priority);
136 if (s->target == STREAM_SYSLOG) {
140 t = (time_t) (ts / USEC_PER_SEC);
141 if (!(tm = localtime(&t)))
144 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
148 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) s->pid);
149 char_array_0(header_pid);
152 IOVEC_SET_STRING(iovec[0], header_priority);
154 if (s->target == STREAM_SYSLOG) {
155 struct msghdr msghdr;
157 struct cmsghdr cmsghdr;
158 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
163 control.cmsghdr.cmsg_level = SOL_SOCKET;
164 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
165 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
167 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
172 IOVEC_SET_STRING(iovec[1], header_time);
173 IOVEC_SET_STRING(iovec[2], s->process);
174 IOVEC_SET_STRING(iovec[3], header_pid);
175 IOVEC_SET_STRING(iovec[4], p);
177 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
178 if (s->server->syslog_is_stream)
182 msghdr.msg_iov = iovec;
183 msghdr.msg_iovlen = ELEMENTSOF(iovec);
184 msghdr.msg_control = &control;
185 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
190 if ((n = sendmsg(s->server->syslog_fd, &msghdr, MSG_NOSIGNAL)) < 0) {
192 if (errno == ESRCH) {
195 /* Hmm, maybe the process this
196 * line originates from is
197 * dead? Then let's patch in
198 * our own pid and retry,
199 * since we have nothing
204 if (ucred->pid != our_pid) {
205 ucred->pid = our_pid;
213 if (!s->server->syslog_is_stream ||
214 (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
217 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
220 } else if (s->target == STREAM_KMSG) {
221 IOVEC_SET_STRING(iovec[1], s->process);
222 IOVEC_SET_STRING(iovec[2], header_pid);
223 IOVEC_SET_STRING(iovec[3], p);
224 IOVEC_SET_STRING(iovec[4], (char*) "\n");
226 if (writev(s->server->kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
229 assert_not_reached("Unknown log target");
234 static int stream_line(Stream *s, char *p, usec_t ts) {
245 if (streq(p, "syslog"))
246 s->target = STREAM_SYSLOG;
247 else if (streq(p, "kmsg")) {
249 if (s->server->kmsg_fd >= 0 && s->uid == 0)
250 s->target = STREAM_KMSG;
252 log_warning("/dev/kmsg logging not available.");
256 log_warning("Failed to parse log target line.");
259 s->state = STREAM_PRIORITY;
262 case STREAM_PRIORITY:
263 if ((r = safe_atoi(p, &s->priority)) < 0) {
264 log_warning("Failed to parse log priority line: %m");
268 if (s->priority < 0) {
269 log_warning("Log priority negative: %m");
273 s->state = STREAM_PROCESS;
277 if (!(s->process = strdup(p)))
280 s->state = STREAM_PREFIX;
285 if ((r = parse_boolean(p)) < 0)
289 s->state = STREAM_RUNNING;
293 return stream_log(s, p, ts);
296 assert_not_reached("Unknown stream state");
299 static int stream_scan(Stream *s, usec_t ts) {
307 remaining = s->length;
311 if (!(newline = memchr(p, '\n', remaining)))
316 if ((r = stream_line(s, p, ts)) >= 0) {
317 remaining -= newline-p+1;
323 memmove(s->buffer, p, remaining);
324 s->length = remaining;
330 static int stream_process(Stream *s, usec_t ts) {
335 if ((l = read(s->fd, s->buffer+s->length, LINE_MAX-s->length)) < 0) {
340 log_warning("Failed to read from stream: %m");
349 r = stream_scan(s, ts);
357 static void stream_free(Stream *s) {
361 assert(s->server->n_streams > 0);
362 s->server->n_streams--;
363 LIST_REMOVE(Stream, stream, s->server->streams, s);
369 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
371 close_nointr_nofail(s->fd);
378 static int stream_new(Server *s, int server_fd) {
382 socklen_t len = sizeof(ucred);
383 struct epoll_event ev;
388 if ((fd = accept4(server_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC)) < 0)
391 if (s->n_streams >= STREAMS_MAX) {
392 log_warning("Too many connections, refusing connection.");
393 close_nointr_nofail(fd);
397 if (!socket_tcpwrap(fd, "systemd-logger")) {
398 close_nointr_nofail(fd);
402 if (!(stream = new0(Stream, 1))) {
403 close_nointr_nofail(fd);
409 if (getsockopt(stream->fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) < 0) {
414 if (shutdown(fd, SHUT_WR) < 0) {
420 ev.data.ptr = stream;
422 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
427 stream->pid = ucred.pid;
428 stream->uid = ucred.uid;
429 stream->gid = ucred.gid;
432 LIST_PREPEND(Stream, stream, s->streams, stream);
442 static void server_done(Server *s) {
447 stream_free(s->streams);
449 for (i = 0; i < s->n_server_fd; i++)
450 close_nointr_nofail(SD_LISTEN_FDS_START+i);
452 if (s->syslog_fd >= 0)
453 close_nointr_nofail(s->syslog_fd);
455 if (s->epoll_fd >= 0)
456 close_nointr_nofail(s->epoll_fd);
459 close_nointr_nofail(s->kmsg_fd);
462 static int server_init(Server *s, unsigned n_sockets) {
467 struct sockaddr_un un;
471 assert(n_sockets > 0);
475 s->n_server_fd = n_sockets;
479 if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
481 log_error("Failed to create epoll object: %m");
485 for (i = 0; i < n_sockets; i++) {
486 struct epoll_event ev;
489 fd = SD_LISTEN_FDS_START+i;
491 if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_STREAM, 1)) < 0) {
492 log_error("Failed to determine file descriptor type: %s", strerror(-r));
497 log_error("Wrong file descriptor type.");
502 /* We use ev.data.ptr instead of ev.data.fd here,
503 * since on 64bit archs fd is 32bit while a pointer is
504 * 64bit. To make sure we can easily distuingish fd
505 * values and pointer values we want to make sure to
506 * write the full field unconditionally. */
510 ev.data.ptr = INT_TO_PTR(fd);
511 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
513 log_error("Failed to add server fd to epoll object: %m");
519 sa.un.sun_family = AF_UNIX;
520 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
522 if ((s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
524 log_error("Failed to create log fd: %m");
528 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
529 close_nointr_nofail(s->syslog_fd);
531 if ((s->syslog_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0)) < 0) {
533 log_error("Failed to create log fd: %m");
537 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
539 log_error("Failed to connect log socket to /dev/log: %m");
543 s->syslog_is_stream = true;
545 s->syslog_is_stream = false;
547 /* /dev/kmsg logging is strictly optional */
548 if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
549 log_warning("Failed to open /dev/kmsg for logging, disabling kernel log buffer support: %m");
558 static int process_event(Server *s, struct epoll_event *ev) {
563 /* Yes, this is a bit ugly, we assume that that valid pointers
564 * are > SD_LISTEN_FDS_START+SERVER_FD_MAX. Which is certainly
565 * true on Linux (and probably most other OSes, too, since the
566 * first 4k usually are part of a separate null pointer
567 * dereference page. */
569 if (PTR_TO_INT(ev->data.ptr) >= SD_LISTEN_FDS_START &&
570 PTR_TO_INT(ev->data.ptr) < SD_LISTEN_FDS_START+(int)s->n_server_fd) {
572 if (ev->events != EPOLLIN) {
573 log_info("Got invalid event from epoll. (1)");
577 if ((r = stream_new(s, PTR_TO_INT(ev->data.ptr))) < 0) {
578 log_info("Failed to accept new connection: %s", strerror(-r));
584 Stream *stream = ev->data.ptr;
586 ts = now(CLOCK_REALTIME);
588 if (!(ev->events & EPOLLIN)) {
589 log_info("Got invalid event from epoll. (2)");
594 if ((r = stream_process(stream, ts)) <= 0) {
597 log_info("Got error on stream: %s", strerror(-r));
607 int main(int argc, char *argv[]) {
609 int r = EXIT_FAILURE, n;
611 if (getppid() != 1) {
612 log_error("This program should be invoked by init only.");
617 log_error("This program does not take arguments.");
621 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
622 log_parse_environment();
625 if ((n = sd_listen_fds(true)) < 0) {
626 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
630 if (n <= 0 || n > SERVER_FD_MAX) {
631 log_error("No or too many file descriptors passed.");
635 if (server_init(&server, (unsigned) n) < 0)
638 log_debug("systemd-logger running as pid %lu", (unsigned long) getpid());
642 "STATUS=Processing requests...");
645 struct epoll_event event;
648 if ((k = epoll_wait(server.epoll_fd,
650 server.n_streams <= 0 ? TIMEOUT : -1)) < 0) {
655 log_error("epoll_wait() failed: %m");
662 if (process_event(&server, &event) < 0)
668 log_debug("systemd-logger stopped as pid %lu", (unsigned long) getpid());
672 "STATUS=Shutting down...");
674 server_done(&server);