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