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