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 STREAM_BUFFER 2048
42 #define STREAMS_MAX 256
43 #define SERVER_FD_MAX 16
44 #define TIMEOUT ((int) (10*MSEC_PER_SEC))
46 typedef struct Stream Stream;
48 typedef struct Server {
55 LIST_HEAD(Stream, streams);
59 typedef enum StreamTarget {
64 typedef enum StreamState {
88 char buffer[STREAM_BUFFER];
91 LIST_FIELDS(Stream, stream);
94 static int stream_log(Stream *s, char *p, usec_t ts) {
96 char header_priority[16], header_time[64], header_pid[16];
97 struct iovec iovec[5];
103 priority = s->priority;
107 p[1] >= '0' && p[1] <= '7' &&
110 /* Detected priority prefix */
111 priority = LOG_MAKEPRI(LOG_FAC(priority), (p[1] - '0'));
120 * The format glibc uses to talk to the syslog daemon is:
122 * <priority>time process[pid]: msg
124 * The format the kernel uses is:
128 * We extend the latter to include the process name and pid.
131 snprintf(header_priority, sizeof(header_priority), "<%i>",
132 s->target == STREAM_SYSLOG ? priority : LOG_PRI(priority));
133 char_array_0(header_priority);
135 if (s->target == STREAM_SYSLOG) {
139 t = (time_t) (ts / USEC_PER_SEC);
140 if (!(tm = localtime(&t)))
143 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
147 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) s->pid);
148 char_array_0(header_pid);
151 IOVEC_SET_STRING(iovec[0], header_priority);
153 if (s->target == STREAM_SYSLOG) {
154 struct msghdr msghdr;
156 struct cmsghdr cmsghdr;
157 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
162 control.cmsghdr.cmsg_level = SOL_SOCKET;
163 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
164 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
166 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
171 IOVEC_SET_STRING(iovec[1], header_time);
172 IOVEC_SET_STRING(iovec[2], s->process);
173 IOVEC_SET_STRING(iovec[3], header_pid);
174 IOVEC_SET_STRING(iovec[4], p);
177 msghdr.msg_iov = iovec;
178 msghdr.msg_iovlen = ELEMENTSOF(iovec);
179 msghdr.msg_control = &control;
180 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
182 if (sendmsg(s->server->syslog_fd, &msghdr, MSG_NOSIGNAL) < 0)
185 } else if (s->target == STREAM_KMSG) {
186 IOVEC_SET_STRING(iovec[1], s->process);
187 IOVEC_SET_STRING(iovec[2], header_pid);
188 IOVEC_SET_STRING(iovec[3], p);
189 IOVEC_SET_STRING(iovec[4], (char*) "\n");
191 if (writev(s->server->kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
194 assert_not_reached("Unknown log target");
199 static int stream_line(Stream *s, char *p, usec_t ts) {
210 if (streq(p, "syslog"))
211 s->target = STREAM_SYSLOG;
212 else if (streq(p, "kmsg")) {
214 if (s->server->kmsg_fd >= 0 && s->uid == 0)
215 s->target = STREAM_KMSG;
217 log_warning("/dev/kmsg logging not available.");
221 log_warning("Failed to parse log target line.");
224 s->state = STREAM_PRIORITY;
227 case STREAM_PRIORITY:
228 if ((r = safe_atoi(p, &s->priority)) < 0) {
229 log_warning("Failed to parse log priority line: %m");
233 if (s->priority < 0) {
234 log_warning("Log priority negative: %m");
238 s->state = STREAM_PROCESS;
242 if (!(s->process = strdup(p)))
245 s->state = STREAM_PREFIX;
250 if ((r = parse_boolean(p)) < 0)
254 s->state = STREAM_RUNNING;
258 return stream_log(s, p, ts);
261 assert_not_reached("Unknown stream state");
264 static int stream_scan(Stream *s, usec_t ts) {
272 remaining = s->length;
276 if (!(newline = memchr(p, '\n', remaining)))
281 if ((r = stream_line(s, p, ts)) >= 0) {
282 remaining -= newline-p+1;
288 memmove(s->buffer, p, remaining);
289 s->length = remaining;
295 static int stream_process(Stream *s, usec_t ts) {
300 if ((l = read(s->fd, s->buffer+s->length, STREAM_BUFFER-s->length)) < 0) {
305 log_warning("Failed to read from stream: %m");
314 r = stream_scan(s, ts);
322 static void stream_free(Stream *s) {
326 assert(s->server->n_streams > 0);
327 s->server->n_streams--;
328 LIST_REMOVE(Stream, stream, s->server->streams, s);
334 epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
336 close_nointr_nofail(s->fd);
343 static int stream_new(Server *s, int server_fd) {
347 socklen_t len = sizeof(ucred);
348 struct epoll_event ev;
353 if ((fd = accept4(server_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC)) < 0)
356 if (s->n_streams >= STREAMS_MAX) {
357 log_warning("Too many connections, refusing connection.");
358 close_nointr_nofail(fd);
362 if (!socket_tcpwrap(fd, "systemd-logger")) {
363 close_nointr_nofail(fd);
367 if (!(stream = new0(Stream, 1))) {
368 close_nointr_nofail(fd);
374 if (getsockopt(stream->fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) < 0) {
379 if (shutdown(fd, SHUT_WR) < 0) {
385 ev.data.ptr = stream;
387 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
392 stream->pid = ucred.pid;
393 stream->uid = ucred.uid;
394 stream->gid = ucred.gid;
397 LIST_PREPEND(Stream, stream, s->streams, stream);
407 static void server_done(Server *s) {
412 stream_free(s->streams);
414 for (i = 0; i < s->n_server_fd; i++)
415 close_nointr_nofail(SD_LISTEN_FDS_START+i);
417 if (s->syslog_fd >= 0)
418 close_nointr_nofail(s->syslog_fd);
420 if (s->epoll_fd >= 0)
421 close_nointr_nofail(s->epoll_fd);
424 close_nointr_nofail(s->kmsg_fd);
427 static int server_init(Server *s, unsigned n_sockets) {
432 struct sockaddr_un un;
436 assert(n_sockets > 0);
440 s->n_server_fd = n_sockets;
444 if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
446 log_error("Failed to create epoll object: %m");
450 for (i = 0; i < n_sockets; i++) {
451 struct epoll_event ev;
454 fd = SD_LISTEN_FDS_START+i;
456 if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_STREAM, 1)) < 0) {
457 log_error("Failed to determine file descriptor type: %s", strerror(-r));
462 log_error("Wrong file descriptor type.");
467 /* We use ev.data.ptr instead of ev.data.fd here,
468 * since on 64bit archs fd is 32bit while a pointer is
469 * 64bit. To make sure we can easily distuingish fd
470 * values and pointer values we want to make sure to
471 * write the full field unconditionally. */
475 ev.data.ptr = INT_TO_PTR(fd);
476 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
478 log_error("Failed to add server fd to epoll object: %m");
483 if ((s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
485 log_error("Failed to create log fd: %m");
490 sa.un.sun_family = AF_UNIX;
491 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
493 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
495 log_error("Failed to connect log socket to /dev/log: %m");
499 /* /dev/kmsg logging is strictly optional */
500 if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
501 log_warning("Failed to open /dev/kmsg for logging, disabling kernel log buffer support: %m");
510 static int process_event(Server *s, struct epoll_event *ev) {
515 /* Yes, this is a bit ugly, we assume that that valid pointers
516 * are > SD_LISTEN_FDS_START+SERVER_FD_MAX. Which is certainly
517 * true on Linux (and probably most other OSes, too, since the
518 * first 4k usually are part of a seperate null pointer
519 * dereference page. */
521 if (PTR_TO_INT(ev->data.ptr) >= SD_LISTEN_FDS_START &&
522 PTR_TO_INT(ev->data.ptr) < SD_LISTEN_FDS_START+(int)s->n_server_fd) {
524 if (ev->events != EPOLLIN) {
525 log_info("Got invalid event from epoll. (1)");
529 if ((r = stream_new(s, PTR_TO_INT(ev->data.ptr))) < 0) {
530 log_info("Failed to accept new connection: %s", strerror(-r));
536 Stream *stream = ev->data.ptr;
538 ts = now(CLOCK_REALTIME);
540 if (!(ev->events & EPOLLIN)) {
541 log_info("Got invalid event from epoll. (2)");
546 if ((r = stream_process(stream, ts)) <= 0) {
549 log_info("Got error on stream: %s", strerror(-r));
559 int main(int argc, char *argv[]) {
563 if (getppid() != 1) {
564 log_error("This program should be invoked by init only.");
569 log_error("This program does not take arguments.");
573 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
574 log_parse_environment();
577 if ((n = sd_listen_fds(true)) < 0) {
578 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
582 if (n <= 0 || n > SERVER_FD_MAX) {
583 log_error("No or too many file descriptors passed.");
587 if (server_init(&server, (unsigned) n) < 0)
590 log_debug("systemd-logger running as pid %lu", (unsigned long) getpid());
594 "STATUS=Processing requests...");
597 struct epoll_event event;
600 if ((k = epoll_wait(server.epoll_fd,
602 server.n_streams <= 0 ? TIMEOUT : -1)) < 0) {
607 log_error("epoll_wait() failed: %m");
614 if (process_event(&server, &event) < 0)
620 log_info("systemd-logger stopped as pid %lu", (unsigned long) getpid());
624 "STATUS=Shutting down...");
626 server_done(&server);