chiark / gitweb /
execute: talk directly to the journald, instead to the stdout-syslog-bridge
[elogind.git] / src / stdout-syslog-bridge.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
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.
12
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.
17
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/>.
20 ***/
21
22 #include <sys/socket.h>
23 #include <sys/types.h>
24 #include <assert.h>
25 #include <time.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <sys/poll.h>
31 #include <sys/epoll.h>
32 #include <sys/un.h>
33 #include <fcntl.h>
34
35 #include <systemd/sd-daemon.h>
36
37 #include "util.h"
38 #include "log.h"
39 #include "list.h"
40 #include "tcpwrap.h"
41 #include "def.h"
42
43 #define STREAMS_MAX 4096
44 #define SERVER_FD_MAX 16
45 #define TIMEOUT_MSEC ((int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC))
46
47 typedef struct Stream Stream;
48
49 typedef struct Server {
50         int syslog_fd;
51         int kmsg_fd;
52         int epoll_fd;
53
54         unsigned n_server_fd;
55
56         bool syslog_is_stream;
57
58         LIST_HEAD(Stream, streams);
59         unsigned n_streams;
60 } Server;
61
62 typedef enum StreamTarget {
63         STREAM_SYSLOG,
64         STREAM_KMSG
65 } StreamTarget;
66
67 typedef enum StreamState {
68         STREAM_TARGET,
69         STREAM_PRIORITY,
70         STREAM_PROCESS,
71         STREAM_PREFIX,
72         STREAM_RUNNING
73 } StreamState;
74
75 struct Stream {
76         Server *server;
77
78         StreamState state;
79
80         int fd;
81
82         StreamTarget target;
83         int priority;
84         char *process;
85         pid_t pid;
86         uid_t uid;
87         gid_t gid;
88
89         bool prefix:1;
90         bool tee_console:1;
91
92         char buffer[LINE_MAX+1];
93         size_t length;
94
95         LIST_FIELDS(Stream, stream);
96 };
97
98 static int stream_log(Stream *s, char *p, usec_t ts) {
99
100         char header_priority[16], header_time[64], header_pid[16];
101         struct iovec iovec[5];
102         int priority;
103
104         assert(s);
105         assert(p);
106
107         priority = s->priority;
108
109         if (s->prefix)
110                 parse_syslog_priority(&p, &priority);
111
112         if (*p == 0)
113                 return 0;
114
115         /* Patch in configured facility if necessary */
116         if ((priority & LOG_FACMASK) == 0)
117                 priority = (s->priority & LOG_FACMASK) | priority;
118
119         /*
120          * The format glibc uses to talk to the syslog daemon is:
121          *
122          *     <priority>time process[pid]: msg
123          *
124          * The format the kernel uses is:
125          *
126          *     <priority>msg\n
127          *
128          *  We extend the latter to include the process name and pid.
129          */
130
131         snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
132         char_array_0(header_priority);
133
134         if (s->target == STREAM_SYSLOG) {
135                 time_t t;
136                 struct tm *tm;
137
138                 t = (time_t) (ts / USEC_PER_SEC);
139                 if (!(tm = localtime(&t)))
140                         return -EINVAL;
141
142                 if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
143                         return -EINVAL;
144         }
145
146         snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) s->pid);
147         char_array_0(header_pid);
148
149         zero(iovec);
150         IOVEC_SET_STRING(iovec[0], header_priority);
151
152         if (s->target == STREAM_SYSLOG) {
153                 struct msghdr msghdr;
154                 union {
155                         struct cmsghdr cmsghdr;
156                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
157                 } control;
158                 struct ucred *ucred;
159
160                 zero(control);
161                 control.cmsghdr.cmsg_level = SOL_SOCKET;
162                 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
163                 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
164
165                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
166                 ucred->pid = s->pid;
167                 ucred->uid = s->uid;
168                 ucred->gid = s->gid;
169
170                 IOVEC_SET_STRING(iovec[1], header_time);
171                 IOVEC_SET_STRING(iovec[2], s->process);
172                 IOVEC_SET_STRING(iovec[3], header_pid);
173                 IOVEC_SET_STRING(iovec[4], p);
174
175                 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
176                 if (s->server->syslog_is_stream)
177                         iovec[4].iov_len++;
178
179                 zero(msghdr);
180                 msghdr.msg_iov = iovec;
181                 msghdr.msg_iovlen = ELEMENTSOF(iovec);
182                 msghdr.msg_control = &control;
183                 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
184
185                 for (;;) {
186                         ssize_t n;
187
188                         if ((n = sendmsg(s->server->syslog_fd, &msghdr, MSG_NOSIGNAL)) < 0) {
189
190                                 if (errno == ESRCH) {
191                                         pid_t our_pid;
192
193                                         /* Hmm, maybe the process this
194                                          * line originates from is
195                                          * dead? Then let's patch in
196                                          * our own pid and retry,
197                                          * since we have nothing
198                                          * better */
199
200                                         our_pid = getpid();
201
202                                         if (ucred->pid != our_pid) {
203                                                 ucred->pid = our_pid;
204                                                 continue;
205                                         }
206                                 }
207
208                                 return -errno;
209                         }
210
211                         if (!s->server->syslog_is_stream ||
212                             (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
213                                 break;
214
215                         IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
216                 }
217
218         } else if (s->target == STREAM_KMSG) {
219                 IOVEC_SET_STRING(iovec[1], s->process);
220                 IOVEC_SET_STRING(iovec[2], header_pid);
221                 IOVEC_SET_STRING(iovec[3], p);
222                 IOVEC_SET_STRING(iovec[4], (char*) "\n");
223
224                 if (writev(s->server->kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
225                         return -errno;
226         } else
227                 assert_not_reached("Unknown log target");
228
229         if (s->tee_console) {
230                 int console;
231
232                 if ((console = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) >= 0) {
233                         IOVEC_SET_STRING(iovec[0], s->process);
234                         IOVEC_SET_STRING(iovec[1], header_pid);
235                         IOVEC_SET_STRING(iovec[2], p);
236                         IOVEC_SET_STRING(iovec[3], (char*) "\n");
237
238                         writev(console, iovec, 4);
239                 }
240         }
241
242         return 0;
243 }
244
245 static int stream_line(Stream *s, char *p, usec_t ts) {
246         int r;
247
248         assert(s);
249         assert(p);
250
251         p = strstrip(p);
252
253         switch (s->state) {
254
255         case STREAM_TARGET:
256                 if (streq(p, "syslog") || streq(p, "syslog+console"))
257                         s->target = STREAM_SYSLOG;
258                 else if (streq(p, "kmsg") || streq(p, "kmsg+console")) {
259
260                         if (s->server->kmsg_fd >= 0 && s->uid == 0)
261                                 s->target = STREAM_KMSG;
262                         else {
263                                 log_warning("/dev/kmsg logging not available.");
264                                 return -EPERM;
265                         }
266                 } else {
267                         log_warning("Failed to parse log target line.");
268                         return -EBADMSG;
269                 }
270
271                 if (endswith(p, "+console"))
272                         s->tee_console = true;
273
274                 s->state = STREAM_PRIORITY;
275                 return 0;
276
277         case STREAM_PRIORITY:
278                 if ((r = safe_atoi(p, &s->priority)) < 0) {
279                         log_warning("Failed to parse log priority line: %m");
280                         return r;
281                 }
282
283                 if (s->priority < 0) {
284                         log_warning("Log priority negative: %m");
285                         return -ERANGE;
286                 }
287
288                 s->state = STREAM_PROCESS;
289                 return 0;
290
291         case STREAM_PROCESS:
292                 if (!(s->process = strdup(p)))
293                         return -ENOMEM;
294
295                 s->state = STREAM_PREFIX;
296                 return 0;
297
298         case STREAM_PREFIX:
299
300                 if ((r = parse_boolean(p)) < 0)
301                         return r;
302
303                 s->prefix = r;
304                 s->state = STREAM_RUNNING;
305                 return 0;
306
307         case STREAM_RUNNING:
308                 return stream_log(s, p, ts);
309         }
310
311         assert_not_reached("Unknown stream state");
312 }
313
314 static int stream_scan(Stream *s, usec_t ts) {
315         char *p;
316         size_t remaining;
317         int r = 0;
318
319         assert(s);
320
321         p = s->buffer;
322         remaining = s->length;
323         for (;;) {
324                 char *end;
325                 size_t skip;
326
327                 end = memchr(p, '\n', remaining);
328                 if (!end) {
329                         if (remaining >= LINE_MAX) {
330                                 end = p + LINE_MAX;
331                                 skip = LINE_MAX;
332                         } else
333                                 break;
334                 } else
335                         skip = end - p + 1;
336
337                 *end = 0;
338
339                 r = stream_line(s, p, ts);
340                 if (r >= 0) {
341                         remaining -= skip;
342                         p += skip;
343                 }
344         }
345
346         if (p > s->buffer) {
347                 memmove(s->buffer, p, remaining);
348                 s->length = remaining;
349         }
350
351         return r;
352 }
353
354 static int stream_process(Stream *s, usec_t ts) {
355         ssize_t l;
356         int r;
357         assert(s);
358
359         l = read(s->fd, s->buffer+s->length, LINE_MAX-s->length);
360         if (l < 0) {
361
362                 if (errno == EAGAIN)
363                         return 0;
364
365                 log_warning("Failed to read from stream: %m");
366                 return -errno;
367         }
368
369         if (l == 0)
370                 return 0;
371
372         s->length += l;
373         r = stream_scan(s, ts);
374
375         if (r < 0)
376                 return r;
377
378         return 1;
379 }
380
381 static void stream_free(Stream *s) {
382         assert(s);
383
384         if (s->server) {
385                 assert(s->server->n_streams > 0);
386                 s->server->n_streams--;
387                 LIST_REMOVE(Stream, stream, s->server->streams, s);
388
389         }
390
391         if (s->fd >= 0) {
392                 if (s->server)
393                         epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
394
395                 close_nointr_nofail(s->fd);
396         }
397
398         free(s->process);
399         free(s);
400 }
401
402 static int stream_new(Server *s, int server_fd) {
403         Stream *stream;
404         int fd;
405         struct ucred ucred;
406         socklen_t len = sizeof(ucred);
407         struct epoll_event ev;
408         int r;
409
410         assert(s);
411         assert(server_fd >= 0);
412
413         fd = accept4(server_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
414         if (fd < 0)
415                 return -errno;
416
417         if (s->n_streams >= STREAMS_MAX) {
418                 log_warning("Too many connections, refusing connection.");
419                 close_nointr_nofail(fd);
420                 return 0;
421         }
422
423         if (!socket_tcpwrap(fd, "systemd-stdout-syslog-bridge")) {
424                 close_nointr_nofail(fd);
425                 return 0;
426         }
427
428         if (!(stream = new0(Stream, 1))) {
429                 close_nointr_nofail(fd);
430                 return -ENOMEM;
431         }
432
433         stream->fd = fd;
434
435         if (getsockopt(stream->fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) < 0) {
436                 r = -errno;
437                 goto fail;
438         }
439
440         if (shutdown(fd, SHUT_WR) < 0) {
441                 r = -errno;
442                 goto fail;
443         }
444
445         zero(ev);
446         ev.data.ptr = stream;
447         ev.events = EPOLLIN;
448         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
449                 r = -errno;
450                 goto fail;
451         }
452
453         stream->pid = ucred.pid;
454         stream->uid = ucred.uid;
455         stream->gid = ucred.gid;
456
457         stream->server = s;
458         LIST_PREPEND(Stream, stream, s->streams, stream);
459         s->n_streams ++;
460
461         return 0;
462
463 fail:
464         stream_free(stream);
465         return r;
466 }
467
468 static void server_done(Server *s) {
469         unsigned i;
470         assert(s);
471
472         while (s->streams)
473                 stream_free(s->streams);
474
475         for (i = 0; i < s->n_server_fd; i++)
476                 close_nointr_nofail(SD_LISTEN_FDS_START+i);
477
478         if (s->syslog_fd >= 0)
479                 close_nointr_nofail(s->syslog_fd);
480
481         if (s->epoll_fd >= 0)
482                 close_nointr_nofail(s->epoll_fd);
483
484         if (s->kmsg_fd >= 0)
485                 close_nointr_nofail(s->kmsg_fd);
486 }
487
488 static int server_init(Server *s, unsigned n_sockets) {
489         int r;
490         unsigned i;
491         union {
492                 struct sockaddr sa;
493                 struct sockaddr_un un;
494         } sa;
495
496         assert(s);
497         assert(n_sockets > 0);
498
499         zero(*s);
500
501         s->n_server_fd = n_sockets;
502         s->syslog_fd = -1;
503         s->kmsg_fd = -1;
504
505         if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
506                 r = -errno;
507                 log_error("Failed to create epoll object: %m");
508                 goto fail;
509         }
510
511         for (i = 0; i < n_sockets; i++) {
512                 struct epoll_event ev;
513                 int fd;
514
515                 fd = SD_LISTEN_FDS_START+i;
516
517                 if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_STREAM, 1)) < 0) {
518                         log_error("Failed to determine file descriptor type: %s", strerror(-r));
519                         goto fail;
520                 }
521
522                 if (!r) {
523                         log_error("Wrong file descriptor type.");
524                         r = -EINVAL;
525                         goto fail;
526                 }
527
528                 /* We use ev.data.ptr instead of ev.data.fd here,
529                  * since on 64bit archs fd is 32bit while a pointer is
530                  * 64bit. To make sure we can easily distinguish fd
531                  * values and pointer values we want to make sure to
532                  * write the full field unconditionally. */
533
534                 zero(ev);
535                 ev.events = EPOLLIN;
536                 ev.data.ptr = INT_TO_PTR(fd);
537                 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
538                         r = -errno;
539                         log_error("Failed to add server fd to epoll object: %m");
540                         goto fail;
541                 }
542         }
543
544         zero(sa);
545         sa.un.sun_family = AF_UNIX;
546         strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
547
548         if ((s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
549                 r = -errno;
550                 log_error("Failed to create log fd: %m");
551                 goto fail;
552         }
553
554         if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
555                 close_nointr_nofail(s->syslog_fd);
556
557                 if ((s->syslog_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0)) < 0) {
558                         r = -errno;
559                         log_error("Failed to create log fd: %m");
560                         goto fail;
561                 }
562
563                 if (connect(s->syslog_fd, &sa.sa, sizeof(sa)) < 0) {
564                         r = -errno;
565                         log_error("Failed to connect log socket to /dev/log: %m");
566                         goto fail;
567                 }
568
569                 s->syslog_is_stream = true;
570         } else
571                 s->syslog_is_stream = false;
572
573         /* /dev/kmsg logging is strictly optional */
574         if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
575                 log_warning("Failed to open /dev/kmsg for logging, disabling kernel log buffer support: %m");
576
577         return 0;
578
579 fail:
580         server_done(s);
581         return r;
582 }
583
584 static int process_event(Server *s, struct epoll_event *ev) {
585         int r;
586
587         assert(s);
588
589         /* Yes, this is a bit ugly, we assume that that valid pointers
590          * are > SD_LISTEN_FDS_START+SERVER_FD_MAX. Which is certainly
591          * true on Linux (and probably most other OSes, too, since the
592          * first 4k usually are part of a separate null pointer
593          * dereference page. */
594
595         if (PTR_TO_INT(ev->data.ptr) >= SD_LISTEN_FDS_START &&
596             PTR_TO_INT(ev->data.ptr) < SD_LISTEN_FDS_START+(int)s->n_server_fd) {
597
598                 if (ev->events != EPOLLIN) {
599                         log_info("Got invalid event from epoll. (1)");
600                         return -EIO;
601                 }
602
603                 if ((r = stream_new(s, PTR_TO_INT(ev->data.ptr))) < 0) {
604                         log_info("Failed to accept new connection: %s", strerror(-r));
605                         return r;
606                 }
607
608         } else {
609                 usec_t ts;
610                 Stream *stream = ev->data.ptr;
611
612                 ts = now(CLOCK_REALTIME);
613
614                 if (!(ev->events & EPOLLIN)) {
615                         log_info("Got invalid event from epoll. (2)");
616                         stream_free(stream);
617                         return 0;
618                 }
619
620                 if ((r = stream_process(stream, ts)) <= 0) {
621
622                         if (r < 0)
623                                 log_info("Got error on stream: %s", strerror(-r));
624
625                         stream_free(stream);
626                         return 0;
627                 }
628         }
629
630         return 0;
631 }
632
633 int main(int argc, char *argv[]) {
634         Server server;
635         int r = EXIT_FAILURE, n;
636
637         if (getppid() != 1) {
638                 log_error("This program should be invoked by init only.");
639                 return EXIT_FAILURE;
640         }
641
642         if (argc > 1) {
643                 log_error("This program does not take arguments.");
644                 return EXIT_FAILURE;
645         }
646
647         log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
648         log_parse_environment();
649         log_open();
650
651         umask(0022);
652
653         n = sd_listen_fds(true);
654         if (n < 0) {
655                 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
656                 return EXIT_FAILURE;
657         }
658
659         if (n <= 0 || n > SERVER_FD_MAX) {
660                 log_error("No or too many file descriptors passed.");
661                 return EXIT_FAILURE;
662         }
663
664         if (server_init(&server, (unsigned) n) < 0)
665                 return EXIT_FAILURE;
666
667         log_debug("systemd-stdout-syslog-bridge running as pid %lu", (unsigned long) getpid());
668
669         sd_notify(false,
670                   "READY=1\n"
671                   "STATUS=Processing requests...");
672
673         for (;;) {
674                 struct epoll_event event;
675                 int k;
676
677                 if ((k = epoll_wait(server.epoll_fd,
678                                     &event, 1,
679                                     server.n_streams <= 0 ? TIMEOUT_MSEC : -1)) < 0) {
680
681                         if (errno == EINTR)
682                                 continue;
683
684                         log_error("epoll_wait() failed: %m");
685                         goto fail;
686                 }
687
688                 if (k <= 0)
689                         break;
690
691                 if (process_event(&server, &event) < 0)
692                         goto fail;
693         }
694
695         r = EXIT_SUCCESS;
696
697         log_debug("systemd-stdout-syslog-bridge stopped as pid %lu", (unsigned long) getpid());
698
699 fail:
700         sd_notify(false,
701                   "STATUS=Shutting down...");
702
703         server_done(&server);
704
705         return r;
706 }