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