chiark / gitweb /
89d8bee2a2120a48c1472e3a245df589f111cbd5
[elogind.git] / src / journal / journald.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2011 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/epoll.h>
23 #include <sys/socket.h>
24 #include <errno.h>
25 #include <sys/signalfd.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/acl.h>
29 #include <acl/libacl.h>
30
31 #include "hashmap.h"
32 #include "journal-file.h"
33 #include "sd-daemon.h"
34 #include "socket-util.h"
35 #include "acl-util.h"
36 #include "cgroup-util.h"
37
38 typedef struct Server {
39         int syslog_fd;
40         int epoll_fd;
41         int signal_fd;
42
43         JournalFile *runtime_journal;
44         JournalFile *system_journal;
45         Hashmap *user_journals;
46
47         uint64_t seqnum;
48 } Server;
49
50 static void fix_perms(JournalFile *f, uid_t uid) {
51         acl_t acl;
52         acl_entry_t entry;
53         acl_permset_t permset;
54         int r;
55
56         assert(f);
57
58         r = fchmod_and_fchown(f->fd, 0640, 0, 0);
59         if (r < 0)
60                 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
61
62         if (uid <= 0)
63                 return;
64
65         acl = acl_get_fd(f->fd);
66         if (!acl) {
67                 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
68                 return;
69         }
70
71         r = acl_find_uid(acl, uid, &entry);
72         if (r <= 0) {
73
74                 if (acl_create_entry(&acl, &entry) < 0 ||
75                     acl_set_tag_type(entry, ACL_USER) < 0 ||
76                     acl_set_qualifier(entry, &uid) < 0) {
77                         log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
78                         goto finish;
79                 }
80         }
81
82         if (acl_get_permset(entry, &permset) < 0 ||
83             acl_add_perm(permset, ACL_READ) < 0 ||
84             acl_calc_mask(&acl) < 0) {
85                 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
86                 goto finish;
87         }
88
89         if (acl_set_fd(f->fd, acl) < 0)
90                 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
91
92 finish:
93         acl_free(acl);
94 }
95
96 static JournalFile* find_journal(Server *s, uid_t uid) {
97         char *p;
98         int r;
99         JournalFile *f;
100         char ids[33];
101         sd_id128_t machine;
102
103         assert(s);
104
105         /* We split up user logs only on /var, not on /run */
106         if (!s->system_journal)
107                 return s->runtime_journal;
108
109         if (uid <= 0)
110                 return s->system_journal;
111
112         r = sd_id128_get_machine(&machine);
113         if (r < 0)
114                 return s->system_journal;
115
116         f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
117         if (f)
118                 return f;
119
120         if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
121                 return s->system_journal;
122
123         r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
124         free(p);
125
126         if (r < 0)
127                 return s->system_journal;
128
129         fix_perms(f, uid);
130
131         r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
132         if (r < 0) {
133                 journal_file_close(f);
134                 return s->system_journal;
135         }
136
137         return f;
138 }
139
140 static void process_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
141         char *message = NULL, *pid = NULL, *uid = NULL, *gid = NULL,
142                 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
143                 *comm = NULL, *cmdline = NULL, *hostname = NULL,
144                 *audit_session = NULL, *audit_loginuid = NULL,
145                 *syslog_priority = NULL, *syslog_facility = NULL,
146                 *exe = NULL, *cgroup = NULL;
147         struct iovec iovec[17];
148         unsigned n = 0;
149         char idbuf[33];
150         sd_id128_t id;
151         int r;
152         char *t;
153         int priority = LOG_USER | LOG_INFO;
154         uid_t loginuid = 0, realuid = 0;
155         JournalFile *f;
156
157         parse_syslog_priority((char**) &buf, &priority);
158         skip_syslog_date((char**) &buf);
159
160         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
161                 IOVEC_SET_STRING(iovec[n++], syslog_priority);
162
163         if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
164                 IOVEC_SET_STRING(iovec[n++], syslog_facility);
165
166         message = strappend("MESSAGE=", buf);
167         if (message)
168                 IOVEC_SET_STRING(iovec[n++], message);
169
170         if (ucred) {
171                 uint32_t session;
172                 char *path;
173
174                 realuid = ucred->uid;
175
176                 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
177                         IOVEC_SET_STRING(iovec[n++], pid);
178
179                 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
180                         IOVEC_SET_STRING(iovec[n++], uid);
181
182                 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
183                         IOVEC_SET_STRING(iovec[n++], gid);
184
185                 r = get_process_comm(ucred->pid, &t);
186                 if (r >= 0) {
187                         comm = strappend("_COMM=", t);
188                         if (comm)
189                                 IOVEC_SET_STRING(iovec[n++], comm);
190                         free(t);
191                 }
192
193                 r = get_process_exe(ucred->pid, &t);
194                 if (r >= 0) {
195                         exe = strappend("_EXE=", t);
196                         if (comm)
197                                 IOVEC_SET_STRING(iovec[n++], exe);
198                         free(t);
199                 }
200
201                 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
202                 if (r >= 0) {
203                         cmdline = strappend("_CMDLINE=", t);
204                         if (cmdline)
205                                 IOVEC_SET_STRING(iovec[n++], cmdline);
206                         free(t);
207                 }
208
209                 r = audit_session_from_pid(ucred->pid, &session);
210                 if (r >= 0)
211                         if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) session) >= 0)
212                                 IOVEC_SET_STRING(iovec[n++], audit_session);
213
214                 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
215                 if (r >= 0)
216                         if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
217                                 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
218
219                 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, ucred->pid, &path);
220                 if (r >= 0) {
221                         cgroup = strappend("_SYSTEMD_CGROUP=", path);
222                         if (cgroup)
223                                 IOVEC_SET_STRING(iovec[n++], cgroup);
224                         free(path);
225                 }
226         }
227
228         if (tv) {
229                 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
230                              (unsigned long long) timeval_load(tv)) >= 0)
231                         IOVEC_SET_STRING(iovec[n++], source_time);
232         }
233
234         /* Note that strictly speaking storing the boot id here is
235          * redundant since the entry includes this in-line
236          * anyway. However, we need this indexed, too. */
237         r = sd_id128_get_boot(&id);
238         if (r >= 0)
239                 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
240                         IOVEC_SET_STRING(iovec[n++], boot_id);
241
242         r = sd_id128_get_machine(&id);
243         if (r >= 0)
244                 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
245                         IOVEC_SET_STRING(iovec[n++], machine_id);
246
247         t = gethostname_malloc();
248         if (t) {
249                 hostname = strappend("_HOSTNAME=", t);
250                 if (hostname)
251                         IOVEC_SET_STRING(iovec[n++], hostname);
252                 free(t);
253         }
254
255         f = find_journal(s, realuid == 0 ? 0 : loginuid);
256         if (!f)
257                 log_warning("Dropping message, as we can't find a place to store the data.");
258         else {
259                 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
260
261                 if (r < 0)
262                         log_error("Failed to write entry, ignoring: %s", strerror(-r));
263         }
264
265         free(message);
266         free(pid);
267         free(uid);
268         free(gid);
269         free(comm);
270         free(exe);
271         free(cmdline);
272         free(source_time);
273         free(boot_id);
274         free(machine_id);
275         free(hostname);
276         free(audit_session);
277         free(audit_loginuid);
278         free(syslog_facility);
279         free(syslog_priority);
280         free(cgroup);
281 }
282
283 static int process_event(Server *s, struct epoll_event *ev) {
284         assert(s);
285
286         if (ev->events != EPOLLIN) {
287                 log_info("Got invalid event from epoll.");
288                 return -EIO;
289         }
290
291         if (ev->data.fd == s->signal_fd) {
292                 struct signalfd_siginfo sfsi;
293                 ssize_t n;
294
295                 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
296                 if (n != sizeof(sfsi)) {
297
298                         if (n >= 0)
299                                 return -EIO;
300
301                         if (errno == EINTR || errno == EAGAIN)
302                                 return 0;
303
304                         return -errno;
305                 }
306
307                 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
308                 return 0;
309
310         }
311
312         if (ev->data.fd == s->syslog_fd) {
313                 for (;;) {
314                         char buf[LINE_MAX+1];
315                         struct msghdr msghdr;
316                         struct iovec iovec;
317                         struct ucred *ucred = NULL;
318                         struct timeval *tv = NULL;
319                         struct cmsghdr *cmsg;
320                         union {
321                                 struct cmsghdr cmsghdr;
322                                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
323                                             CMSG_SPACE(sizeof(struct timeval))];
324                         } control;
325                         ssize_t n;
326                         char *e;
327
328                         zero(iovec);
329                         iovec.iov_base = buf;
330                         iovec.iov_len = sizeof(buf)-1;
331
332                         zero(control);
333                         zero(msghdr);
334                         msghdr.msg_iov = &iovec;
335                         msghdr.msg_iovlen = 1;
336                         msghdr.msg_control = &control;
337                         msghdr.msg_controllen = sizeof(control);
338
339                         n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
340                         if (n < 0) {
341
342                                 if (errno == EINTR || errno == EAGAIN)
343                                         return 1;
344
345                                 log_error("recvmsg() failed: %m");
346                                 return -errno;
347                         }
348
349                         for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
350
351                                 if (cmsg->cmsg_level == SOL_SOCKET &&
352                                     cmsg->cmsg_type == SCM_CREDENTIALS &&
353                                     cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
354                                         ucred = (struct ucred*) CMSG_DATA(cmsg);
355                                 else if (cmsg->cmsg_level == SOL_SOCKET &&
356                                          cmsg->cmsg_type == SO_TIMESTAMP &&
357                                          cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
358                                         tv = (struct timeval*) CMSG_DATA(cmsg);
359                         }
360
361                         e = memchr(buf, '\n', n);
362                         if (e)
363                                 *e = 0;
364                         else
365                                 buf[n] = 0;
366
367                         process_message(s, strstrip(buf), ucred, tv);
368                 }
369
370                 return 1;
371         }
372
373         log_error("Unknown event.");
374         return 0;
375 }
376
377 static int system_journal_open(Server *s) {
378         int r;
379         char *fn;
380         sd_id128_t machine;
381         char ids[33];
382
383         r = sd_id128_get_machine(&machine);
384         if (r < 0)
385                 return r;
386
387         /* First try to create the machine path, but not the prefix */
388         fn = strappend("/var/log/journal/", sd_id128_to_string(machine, ids));
389         if (!fn)
390                 return -ENOMEM;
391         (void) mkdir(fn, 0755);
392         free(fn);
393
394         /* The create the system journal file */
395         fn = join("/var/log/journal/", ids, "/system.journal", NULL);
396         if (!fn)
397                 return -ENOMEM;
398
399         r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
400         free(fn);
401
402         if (r >= 0) {
403                 fix_perms(s->system_journal, 0);
404                 return r;
405         }
406
407         if (r < 0 && r != -ENOENT) {
408                 log_error("Failed to open system journal: %s", strerror(-r));
409                 return r;
410         }
411
412         /* /var didn't work, so try /run, but this time we
413          * create the prefix too */
414         fn = join("/run/log/journal/", ids, "/system.journal", NULL);
415         if (!fn)
416                 return -ENOMEM;
417
418         (void) mkdir_parents(fn, 0755);
419         r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
420         free(fn);
421
422         if (r < 0) {
423                 log_error("Failed to open runtime journal: %s", strerror(-r));
424                 return r;
425         }
426
427         fix_perms(s->runtime_journal, 0);
428         return r;
429 }
430
431 static int server_init(Server *s) {
432         int n, one, r;
433         struct epoll_event ev;
434         sigset_t mask;
435
436         assert(s);
437
438         zero(*s);
439         s->syslog_fd = s->signal_fd = -1;
440
441         s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
442         if (s->epoll_fd < 0) {
443                 log_error("Failed to create epoll object: %m");
444                 return -errno;
445         }
446
447         n = sd_listen_fds(true);
448         if (n < 0) {
449                 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
450                 return n;
451         }
452
453         if (n > 1) {
454                 log_error("Too many file descriptors passed.");
455                 return -EINVAL;
456         }
457
458         if (n == 1)
459                 s->syslog_fd = SD_LISTEN_FDS_START;
460         else {
461                 union sockaddr_union sa;
462
463                 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
464                 if (s->syslog_fd < 0) {
465                         log_error("socket() failed: %m");
466                         return -errno;
467                 }
468
469                 zero(sa);
470                 sa.un.sun_family = AF_UNIX;
471                 strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
472
473                 unlink(sa.un.sun_path);
474
475                 r = bind(s->syslog_fd, &sa.sa, sizeof(sa.un));
476                 if (r < 0) {
477                         log_error("bind() failed: %m");
478                         return -errno;
479                 }
480
481                 chmod(sa.un.sun_path, 0666);
482         }
483
484         one = 1;
485         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
486         if (r < 0) {
487                 log_error("SO_PASSCRED failed: %m");
488                 return -errno;
489         }
490
491         one = 1;
492         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
493         if (r < 0) {
494                 log_error("SO_TIMESTAMP failed: %m");
495                 return -errno;
496         }
497
498         zero(ev);
499         ev.events = EPOLLIN;
500         ev.data.fd = s->syslog_fd;
501         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
502                 log_error("Failed to add server fd to epoll object: %m");
503                 return -errno;
504         }
505
506         s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
507         if (!s->user_journals) {
508                 log_error("Out of memory.");
509                 return -ENOMEM;
510         }
511
512         r = system_journal_open(s);
513         if (r < 0)
514                 return r;
515
516         assert_se(sigemptyset(&mask) == 0);
517         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
518         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
519
520         s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
521         if (s->signal_fd < 0) {
522                 log_error("signalfd(): %m");
523                 return -errno;
524         }
525
526         zero(ev);
527         ev.events = EPOLLIN;
528         ev.data.fd = s->signal_fd;
529
530         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
531                 log_error("epoll_ctl(): %m");
532                 return -errno;
533         }
534
535         return 0;
536 }
537
538 static void server_done(Server *s) {
539         JournalFile *f;
540         assert(s);
541
542         if (s->system_journal)
543                 journal_file_close(s->system_journal);
544
545         if (s->runtime_journal)
546                 journal_file_close(s->runtime_journal);
547
548         while ((f = hashmap_steal_first(s->user_journals)))
549                 journal_file_close(f);
550
551         hashmap_free(s->user_journals);
552
553         if (s->epoll_fd >= 0)
554                 close_nointr_nofail(s->epoll_fd);
555
556         if (s->signal_fd >= 0)
557                 close_nointr_nofail(s->signal_fd);
558
559         if (s->syslog_fd >= 0)
560                 close_nointr_nofail(s->syslog_fd);
561 }
562
563 int main(int argc, char *argv[]) {
564         Server server;
565         int r;
566
567         /* if (getppid() != 1) { */
568         /*         log_error("This program should be invoked by init only."); */
569         /*         return EXIT_FAILURE; */
570         /* } */
571
572         if (argc > 1) {
573                 log_error("This program does not take arguments.");
574                 return EXIT_FAILURE;
575         }
576
577         log_set_target(LOG_TARGET_CONSOLE);
578         log_parse_environment();
579         log_open();
580
581         umask(0022);
582
583         r = server_init(&server);
584         if (r < 0)
585                 goto finish;
586
587         log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
588
589         sd_notify(false,
590                   "READY=1\n"
591                   "STATUS=Processing messages...");
592 #
593         for (;;) {
594                 struct epoll_event event;
595
596                 r = epoll_wait(server.epoll_fd, &event, 1, -1);
597                 if (r < 0) {
598
599                         if (errno == EINTR)
600                                 continue;
601
602                         log_error("epoll_wait() failed: %m");
603                         r = -errno;
604                         goto finish;
605                 } else if (r == 0)
606                         break;
607
608                 r = process_event(&server, &event);
609                 if (r < 0)
610                         goto finish;
611                 else if (r == 0)
612                         break;
613         }
614
615 finish:
616         sd_notify(false,
617                   "STATUS=Shutting down...");
618
619         server_done(&server);
620
621         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
622 }