chiark / gitweb /
core: move abstract namespace sockets to /dev/.run
[elogind.git] / src / kmsg-syslogd.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 #include <sys/signalfd.h>
35
36 #include "util.h"
37 #include "log.h"
38 #include "sd-daemon.h"
39 #include "fdset.h"
40
41 #define SERVER_FD_MAX 16
42
43 typedef struct Stream Stream;
44
45 typedef struct Server {
46         FDSet *syslog_fds;
47         int kmsg_fd;
48         int epoll_fd;
49         int signal_fd;
50 } Server;
51
52 static void server_done(Server *s) {
53         assert(s);
54
55         if (s->epoll_fd >= 0)
56                 close_nointr_nofail(s->epoll_fd);
57
58         if (s->kmsg_fd >= 0)
59                 close_nointr_nofail(s->kmsg_fd);
60
61         if (s->signal_fd >= 0)
62                 close_nointr_nofail(s->signal_fd);
63
64         if (s->syslog_fds)
65                 fdset_free(s->syslog_fds);
66 }
67
68 static int server_init(Server *s, unsigned n_sockets) {
69         int r;
70         unsigned i;
71         struct epoll_event ev;
72         sigset_t mask;
73
74         assert(s);
75         assert(n_sockets > 0);
76
77         zero(*s);
78
79         s->kmsg_fd = s->signal_fd = -1;
80
81         if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
82                 r = -errno;
83                 log_error("Failed to create epoll object: %s", strerror(errno));
84                 goto fail;
85         }
86
87         if (!(s->syslog_fds = fdset_new())) {
88                 r = -ENOMEM;
89                 log_error("Failed to allocate file descriptor set: %s", strerror(errno));
90                 goto fail;
91         }
92
93         for (i = 0; i < n_sockets; i++) {
94                 int fd, one = 1;
95
96                 fd = SD_LISTEN_FDS_START+i;
97
98                 if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_DGRAM, -1)) < 0) {
99                         log_error("Failed to determine file descriptor type: %s", strerror(-r));
100                         goto fail;
101                 }
102
103                 if (!r) {
104                         log_error("Wrong file descriptor type.");
105                         r = -EINVAL;
106                         goto fail;
107                 }
108
109                 if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0)
110                         log_error("SO_PASSCRED failed: %m");
111
112                 zero(ev);
113                 ev.events = EPOLLIN;
114                 ev.data.fd = fd;
115                 if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
116                         r = -errno;
117                         log_error("Failed to add server fd to epoll object: %s", strerror(errno));
118                         goto fail;
119                 }
120
121                 if ((r = fdset_put(s->syslog_fds, fd)) < 0) {
122                         log_error("Failed to store file descriptor in set: %s", strerror(-r));
123                         goto fail;
124                 }
125         }
126
127         if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0) {
128                 log_error("Failed to open /dev/kmsg for logging: %m");
129                 return -errno;
130         }
131
132         assert_se(sigemptyset(&mask) == 0);
133         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
134         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
135
136         if ((s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
137                 log_error("signalfd(): %m");
138                 return -errno;
139         }
140
141         zero(ev);
142         ev.events = EPOLLIN;
143         ev.data.fd = s->signal_fd;
144
145         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
146                 log_error("epoll_ctl(): %m");
147                 return -errno;
148         }
149
150         return 0;
151
152 fail:
153         server_done(s);
154         return r;
155 }
156
157 static int read_priority(const char **buf) {
158         int priority;
159         size_t n;
160         const char *p;
161         int a, b, c;
162
163         assert(buf);
164         assert(*buf);
165
166         p = *buf;
167         n = strlen(p);
168
169         if (n < 3 || p[0] != '<')
170                 goto fail;
171
172         if (p[2] == '>') {
173                 a = b = 0;
174                 c = undecchar(p[1]);
175                 p += 3;
176         } else if (n >= 4 && p[3] == '>') {
177                 a = 0;
178                 b = undecchar(p[1]);
179                 c = undecchar(p[2]);
180                 p += 4;
181         } else if (n >= 5 && p[4] == '>') {
182                 a = undecchar(p[1]);
183                 b = undecchar(p[2]);
184                 c = undecchar(p[3]);
185                 p += 5;
186         } else
187                 goto fail;
188
189         if (a < 0 || b < 0 || c < 0)
190                 goto fail;
191
192         *buf = p;
193
194         priority = 100*a + 10*b + c;
195         return LOG_PRI(priority);
196
197 fail:
198         return LOG_INFO;
199 }
200
201 static void skip_date(const char **buf) {
202         enum {
203                 LETTER,
204                 SPACE,
205                 NUMBER,
206                 SPACE_OR_NUMBER,
207                 COLON
208         } sequence[] = {
209                 LETTER, LETTER, LETTER,
210                 SPACE,
211                 SPACE_OR_NUMBER, NUMBER,
212                 SPACE,
213                 SPACE_OR_NUMBER, NUMBER,
214                 COLON,
215                 SPACE_OR_NUMBER, NUMBER,
216                 COLON,
217                 SPACE_OR_NUMBER, NUMBER,
218                 SPACE
219         };
220
221         const char *p;
222         unsigned i;
223
224         assert(buf);
225         assert(*buf);
226
227         p = *buf;
228
229         for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
230
231                 if (!*p)
232                         return;
233
234                 switch (sequence[i]) {
235
236                 case SPACE:
237                         if (*p != ' ')
238                                 return;
239                         break;
240
241                 case SPACE_OR_NUMBER:
242                         if (*p == ' ')
243                                 break;
244
245                         /* fall through */
246
247                 case NUMBER:
248                         if (*p < '0' || *p > '9')
249                                 return;
250
251                         break;
252
253                 case LETTER:
254                         if (!(*p >= 'A' && *p <= 'Z') &&
255                             !(*p >= 'a' && *p <= 'z'))
256                                 return;
257
258                         break;
259
260                 case COLON:
261                         if (*p != ':')
262                                 return;
263                         break;
264
265                 }
266         }
267
268         *buf = p;
269 }
270
271 static int read_process(const char **buf, struct iovec *iovec) {
272         const char *p;
273         size_t l;
274
275         assert(buf);
276         assert(*buf);
277         assert(iovec);
278
279         p = *buf;
280
281         p += strspn(p, WHITESPACE);
282         l = strcspn(p, WHITESPACE);
283
284         if (l <= 0 ||
285             p[l-1] != ':')
286                 return 0;
287
288         l--;
289
290         if (p[l-1] == ']') {
291                 size_t k = l-1;
292
293                 for (;;) {
294
295                         if (p[k] == '[') {
296                                 l = k;
297                                 break;
298                         }
299
300                         if (k == 0)
301                                 break;
302
303                         k--;
304                 }
305         }
306
307         iovec->iov_base = (char*) p;
308         iovec->iov_len = l;
309         *buf = p + l;
310         return 1;
311 }
312
313 static void skip_pid(const char **buf) {
314         const char *p;
315
316         assert(buf);
317         assert(*buf);
318
319         p = *buf;
320
321         if (*p != '[')
322                 return;
323
324         p++;
325         p += strspn(p, "0123456789");
326
327         if (*p != ']')
328                 return;
329
330         p++;
331
332         *buf = p;
333 }
334
335 static int write_message(Server *s, const char *buf, struct ucred *ucred) {
336         ssize_t k;
337         char priority[4], pid[16];
338         struct iovec iovec[5];
339         unsigned i = 0;
340         char *process = NULL;
341         int r = 0;
342
343         assert(s);
344         assert(buf);
345
346         /* First, set priority field */
347         snprintf(priority, sizeof(priority), "<%i>", read_priority(&buf));
348         char_array_0(priority);
349         IOVEC_SET_STRING(iovec[i++], priority);
350
351         /* Second, skip date */
352         skip_date(&buf);
353
354         /* Then, add process if set */
355         if (read_process(&buf, &iovec[i]) > 0)
356                 i++;
357         else if (ucred && get_process_name(ucred->pid, &process) >= 0)
358                 IOVEC_SET_STRING(iovec[i++], process);
359
360         /* Skip the stored PID if we have a better one */
361         if (ucred) {
362                 snprintf(pid, sizeof(pid), "[%lu]: ", (unsigned long) ucred->pid);
363                 char_array_0(pid);
364                 IOVEC_SET_STRING(iovec[i++], pid);
365
366                 skip_pid(&buf);
367
368                 if (*buf == ':')
369                         buf++;
370
371                 buf += strspn(buf, WHITESPACE);
372         }
373
374         /* Is the remaining message empty? */
375         if (*buf) {
376
377                 /* And the rest is the message */
378                 IOVEC_SET_STRING(iovec[i++], buf);
379                 IOVEC_SET_STRING(iovec[i++], "\n");
380
381                 if ((k = writev(s->kmsg_fd, iovec, i)) <= 0) {
382                         log_error("Failed to write log message to kmsg: %s", k < 0 ? strerror(errno) : "short write");
383                         r = k < 0 ? -errno : -EIO;
384                 }
385         }
386
387         free(process);
388
389         return r;
390 }
391
392 static int process_event(Server *s, struct epoll_event *ev) {
393         assert(s);
394
395         if (ev->events != EPOLLIN) {
396                 log_info("Got invalid event from epoll.");
397                 return -EIO;
398         }
399
400         if (ev->data.fd == s->signal_fd) {
401                 struct signalfd_siginfo sfsi;
402                 ssize_t n;
403
404                 if ((n = read(s->signal_fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
405
406                         if (n >= 0)
407                                 return -EIO;
408
409                         if (errno == EINTR || errno == EAGAIN)
410                                 return 0;
411
412                         return -errno;
413                 }
414
415                 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
416                 return 0;
417
418         } else {
419                 for (;;) {
420                         char buf[LINE_MAX+1];
421                         struct msghdr msghdr;
422                         struct iovec iovec;
423                         struct ucred *ucred;
424                         union {
425                                 struct cmsghdr cmsghdr;
426                                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
427                         } control;
428                         ssize_t n;
429                         int k;
430                         char *e;
431
432                         zero(iovec);
433                         iovec.iov_base = buf;
434                         iovec.iov_len = sizeof(buf)-1;
435
436                         zero(control);
437                         zero(msghdr);
438                         msghdr.msg_iov = &iovec;
439                         msghdr.msg_iovlen = 1;
440                         msghdr.msg_control = &control;
441                         msghdr.msg_controllen = sizeof(control);
442
443                         if ((n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT)) < 0) {
444
445                                 if (errno == EINTR || errno == EAGAIN)
446                                         return 1;
447
448                                 log_error("recvmsg() failed: %m");
449                                 return -errno;
450                         }
451
452                         if (msghdr.msg_controllen >= CMSG_LEN(sizeof(struct ucred)) &&
453                             control.cmsghdr.cmsg_level == SOL_SOCKET &&
454                             control.cmsghdr.cmsg_type == SCM_CREDENTIALS &&
455                             control.cmsghdr.cmsg_len == CMSG_LEN(sizeof(struct ucred)))
456                                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
457                         else
458                                 ucred = NULL;
459
460                         if ((e = memchr(buf, '\n', n)))
461                                 *e = 0;
462                         else
463                                 buf[n] = 0;
464
465                         if ((k = write_message(s, strstrip(buf), ucred)) < 0)
466                                 return k;
467                 }
468         }
469
470         return 1;
471 }
472
473 int main(int argc, char *argv[]) {
474         Server server;
475         int r = EXIT_FAILURE, n;
476
477         if (getppid() != 1) {
478                 log_error("This program should be invoked by init only.");
479                 return EXIT_FAILURE;
480         }
481
482         if (argc > 1) {
483                 log_error("This program does not take arguments.");
484                 return EXIT_FAILURE;
485         }
486
487         log_set_target(LOG_TARGET_KMSG);
488         log_parse_environment();
489         log_open();
490
491         if ((n = sd_listen_fds(true)) < 0) {
492                 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
493                 return EXIT_FAILURE;
494         }
495
496         if (n <= 0 || n > SERVER_FD_MAX) {
497                 log_error("No or too many file descriptors passed.");
498                 return EXIT_FAILURE;
499         }
500
501         if (server_init(&server, (unsigned) n) < 0)
502                 return EXIT_FAILURE;
503
504         log_debug("systemd-kmsg-syslogd running as pid %lu", (unsigned long) getpid());
505
506         sd_notify(false,
507                   "READY=1\n"
508                   "STATUS=Processing messages...");
509
510         for (;;) {
511                 struct epoll_event event;
512                 int k;
513
514                 if ((k = epoll_wait(server.epoll_fd, &event, 1, -1)) < 0) {
515
516                         if (errno == EINTR)
517                                 continue;
518
519                         log_error("epoll_wait() failed: %m");
520                         goto fail;
521                 }
522
523                 if (k <= 0)
524                         break;
525
526                 if ((k = process_event(&server, &event)) < 0)
527                         goto fail;
528
529                 if (k == 0)
530                         break;
531         }
532
533         r = EXIT_SUCCESS;
534
535         log_debug("systemd-kmsg-syslogd stopped as pid %lu", (unsigned long) getpid());
536
537 fail:
538         sd_notify(false,
539                   "STATUS=Shutting down...");
540
541         server_done(&server);
542
543         return r;
544 }