chiark / gitweb /
37f8f16754722b47f88ff81eecacaa67e744262a
[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 #include <stddef.h>
31 #include <sys/ioctl.h>
32 #include <linux/sockios.h>
33
34 #include "hashmap.h"
35 #include "journal-file.h"
36 #include "sd-daemon.h"
37 #include "socket-util.h"
38 #include "acl-util.h"
39 #include "cgroup-util.h"
40
41 #define USER_JOURNALS_MAX 1024
42
43 typedef struct Server {
44         int epoll_fd;
45         int signal_fd;
46         int syslog_fd;
47         int native_fd;
48
49         JournalFile *runtime_journal;
50         JournalFile *system_journal;
51         Hashmap *user_journals;
52
53         uint64_t seqnum;
54
55         char *buffer;
56         size_t buffer_size;
57
58         JournalMetrics metrics;
59         uint64_t max_use;
60 } Server;
61
62 static void fix_perms(JournalFile *f, uid_t uid) {
63         acl_t acl;
64         acl_entry_t entry;
65         acl_permset_t permset;
66         int r;
67
68         assert(f);
69
70         r = fchmod_and_fchown(f->fd, 0640, 0, 0);
71         if (r < 0)
72                 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
73
74         if (uid <= 0)
75                 return;
76
77         acl = acl_get_fd(f->fd);
78         if (!acl) {
79                 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
80                 return;
81         }
82
83         r = acl_find_uid(acl, uid, &entry);
84         if (r <= 0) {
85
86                 if (acl_create_entry(&acl, &entry) < 0 ||
87                     acl_set_tag_type(entry, ACL_USER) < 0 ||
88                     acl_set_qualifier(entry, &uid) < 0) {
89                         log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
90                         goto finish;
91                 }
92         }
93
94         if (acl_get_permset(entry, &permset) < 0 ||
95             acl_add_perm(permset, ACL_READ) < 0 ||
96             acl_calc_mask(&acl) < 0) {
97                 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
98                 goto finish;
99         }
100
101         if (acl_set_fd(f->fd, acl) < 0)
102                 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
103
104 finish:
105         acl_free(acl);
106 }
107
108 static JournalFile* find_journal(Server *s, uid_t uid) {
109         char *p;
110         int r;
111         JournalFile *f;
112         char ids[33];
113         sd_id128_t machine;
114
115         assert(s);
116
117         /* We split up user logs only on /var, not on /run */
118         if (!s->system_journal)
119                 return s->runtime_journal;
120
121         if (uid <= 0)
122                 return s->system_journal;
123
124         r = sd_id128_get_machine(&machine);
125         if (r < 0)
126                 return s->system_journal;
127
128         f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
129         if (f)
130                 return f;
131
132         if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
133                 return s->system_journal;
134
135         while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
136                 /* Too many open? Then let's close one */
137                 f = hashmap_steal_first(s->user_journals);
138                 assert(f);
139                 journal_file_close(f);
140         }
141
142         r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
143         free(p);
144
145         if (r < 0)
146                 return s->system_journal;
147
148         fix_perms(f, uid);
149
150         r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
151         if (r < 0) {
152                 journal_file_close(f);
153                 return s->system_journal;
154         }
155
156         return f;
157 }
158
159 static void server_vacuum(Server *s) {
160         Iterator i;
161         void *k;
162         char *p;
163         char ids[33];
164         sd_id128_t machine;
165         int r;
166         JournalFile *f;
167
168         log_info("Rotating...");
169
170         if (s->runtime_journal) {
171                 r = journal_file_rotate(&s->runtime_journal);
172                 if (r < 0)
173                         log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
174         }
175
176         if (s->system_journal) {
177                 r = journal_file_rotate(&s->system_journal);
178                 if (r < 0)
179                         log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
180         }
181
182         HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
183                 r = journal_file_rotate(&f);
184                 if (r < 0)
185                         log_error("Failed to rotate %s: %s", f->path, strerror(-r));
186                 else
187                         hashmap_replace(s->user_journals, k, f);
188         }
189
190         log_info("Vacuuming...");
191
192         r = sd_id128_get_machine(&machine);
193         if (r < 0) {
194                 log_error("Failed to get machine ID: %s", strerror(-r));
195                 return;
196         }
197
198         if (asprintf(&p, "/var/log/journal/%s", sd_id128_to_string(machine, ids)) < 0) {
199                 log_error("Out of memory.");
200                 return;
201         }
202
203         r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
204         if (r < 0 && r != -ENOENT)
205                 log_error("Failed to vacuum %s: %s", p, strerror(-r));
206         free(p);
207
208         if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
209                 log_error("Out of memory.");
210                 return;
211         }
212
213         r = journal_directory_vacuum(p, s->max_use, s->metrics.keep_free);
214         if (r < 0 && r != -ENOENT)
215                 log_error("Failed to vacuum %s: %s", p, strerror(-r));
216         free(p);
217 }
218
219 static void dispatch_message(Server *s, struct iovec *iovec, unsigned n, unsigned m, struct ucred *ucred, struct timeval *tv) {
220         char *pid = NULL, *uid = NULL, *gid = NULL,
221                 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
222                 *comm = NULL, *cmdline = NULL, *hostname = NULL,
223                 *audit_session = NULL, *audit_loginuid = NULL,
224                 *exe = NULL, *cgroup = NULL;
225
226         char idbuf[33];
227         sd_id128_t id;
228         int r;
229         char *t;
230         uid_t loginuid = 0, realuid = 0;
231         JournalFile *f;
232         bool vacuumed = false;
233
234         assert(s);
235         assert(iovec || n == 0);
236
237         if (n == 0)
238                 return;
239
240         assert(n + 13 <= m);
241
242         if (ucred) {
243                 uint32_t session;
244                 char *path;
245
246                 realuid = ucred->uid;
247
248                 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
249                         IOVEC_SET_STRING(iovec[n++], pid);
250
251                 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
252                         IOVEC_SET_STRING(iovec[n++], uid);
253
254                 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
255                         IOVEC_SET_STRING(iovec[n++], gid);
256
257                 r = get_process_comm(ucred->pid, &t);
258                 if (r >= 0) {
259                         comm = strappend("_COMM=", t);
260                         if (comm)
261                                 IOVEC_SET_STRING(iovec[n++], comm);
262                         free(t);
263                 }
264
265                 r = get_process_exe(ucred->pid, &t);
266                 if (r >= 0) {
267                         exe = strappend("_EXE=", t);
268                         if (comm)
269                                 IOVEC_SET_STRING(iovec[n++], exe);
270                         free(t);
271                 }
272
273                 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
274                 if (r >= 0) {
275                         cmdline = strappend("_CMDLINE=", t);
276                         if (cmdline)
277                                 IOVEC_SET_STRING(iovec[n++], cmdline);
278                         free(t);
279                 }
280
281                 r = audit_session_from_pid(ucred->pid, &session);
282                 if (r >= 0)
283                         if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) session) >= 0)
284                                 IOVEC_SET_STRING(iovec[n++], audit_session);
285
286                 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
287                 if (r >= 0)
288                         if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
289                                 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
290
291                 r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, ucred->pid, &path);
292                 if (r >= 0) {
293                         cgroup = strappend("_SYSTEMD_CGROUP=", path);
294                         if (cgroup)
295                                 IOVEC_SET_STRING(iovec[n++], cgroup);
296                         free(path);
297                 }
298         }
299
300         if (tv) {
301                 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
302                              (unsigned long long) timeval_load(tv)) >= 0)
303                         IOVEC_SET_STRING(iovec[n++], source_time);
304         }
305
306         /* Note that strictly speaking storing the boot id here is
307          * redundant since the entry includes this in-line
308          * anyway. However, we need this indexed, too. */
309         r = sd_id128_get_boot(&id);
310         if (r >= 0)
311                 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
312                         IOVEC_SET_STRING(iovec[n++], boot_id);
313
314         r = sd_id128_get_machine(&id);
315         if (r >= 0)
316                 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
317                         IOVEC_SET_STRING(iovec[n++], machine_id);
318
319         t = gethostname_malloc();
320         if (t) {
321                 hostname = strappend("_HOSTNAME=", t);
322                 if (hostname)
323                         IOVEC_SET_STRING(iovec[n++], hostname);
324                 free(t);
325         }
326
327         assert(n <= m);
328
329 retry:
330         f = find_journal(s, realuid == 0 ? 0 : loginuid);
331         if (!f)
332                 log_warning("Dropping message, as we can't find a place to store the data.");
333         else {
334                 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
335
336                 if (r == -E2BIG && !vacuumed) {
337                         log_info("Allocation limit reached.");
338
339                         server_vacuum(s);
340                         vacuumed = true;
341
342                         log_info("Retrying write.");
343                         goto retry;
344                 }
345
346                 if (r < 0)
347                         log_error("Failed to write entry, ignoring: %s", strerror(-r));
348         }
349
350         free(pid);
351         free(uid);
352         free(gid);
353         free(comm);
354         free(exe);
355         free(cmdline);
356         free(source_time);
357         free(boot_id);
358         free(machine_id);
359         free(hostname);
360         free(audit_session);
361         free(audit_loginuid);
362         free(cgroup);
363
364 }
365
366 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
367         char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL;
368         struct iovec iovec[16];
369         unsigned n = 0;
370         int priority = LOG_USER | LOG_INFO;
371
372         assert(s);
373         assert(buf);
374
375         parse_syslog_priority((char**) &buf, &priority);
376         skip_syslog_date((char**) &buf);
377
378         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
379                 IOVEC_SET_STRING(iovec[n++], syslog_priority);
380
381         if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
382                 IOVEC_SET_STRING(iovec[n++], syslog_facility);
383
384         message = strappend("MESSAGE=", buf);
385         if (message)
386                 IOVEC_SET_STRING(iovec[n++], message);
387
388         dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv);
389
390         free(message);
391         free(syslog_facility);
392         free(syslog_priority);
393 }
394
395 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
396         struct iovec *iovec = NULL;
397         unsigned n = 0, m = 0, j;
398         const char *p;
399         size_t remaining;
400
401         assert(s);
402         assert(buffer || n == 0);
403
404         p = buffer;
405         remaining = buffer_size;
406
407         while (remaining > 0) {
408                 const char *e, *q;
409
410                 e = memchr(p, '\n', remaining);
411
412                 if (!e) {
413                         /* Trailing noise, let's ignore it, and flush what we collected */
414                         log_debug("Received message with trailing noise, ignoring.");
415                         break;
416                 }
417
418                 if (e == p) {
419                         /* Entry separator */
420                         dispatch_message(s, iovec, n, m, ucred, tv);
421                         n = 0;
422
423                         p++;
424                         remaining--;
425                         continue;
426                 }
427
428                 if (*p == '.') {
429                         /* Control command, ignore for now */
430                         remaining -= (e - p) + 1;
431                         p = e + 1;
432                         continue;
433                 }
434
435                 /* A property follows */
436
437                 if (n+13 >= m) {
438                         struct iovec *c;
439                         unsigned u;
440
441                         u = MAX((n+13U) * 2U, 4U);
442                         c = realloc(iovec, u * sizeof(struct iovec));
443                         if (!c) {
444                                 log_error("Out of memory");
445                                 break;
446                         }
447
448                         iovec = c;
449                         m = u;
450                 }
451
452                 q = memchr(p, '=', e - p);
453                 if (q) {
454                         if (p[0] != '_') {
455                                 /* If the field name starts with an
456                                  * underscore, skip the variable,
457                                  * since that indidates a trusted
458                                  * field */
459                                 iovec[n].iov_base = (char*) p;
460                                 iovec[n].iov_len = e - p;
461                                 n++;
462                         }
463
464                         remaining -= (e - p) + 1;
465                         p = e + 1;
466                         continue;
467                 } else {
468                         uint64_t l;
469                         char *k;
470
471                         if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
472                                 log_debug("Failed to parse message, ignoring.");
473                                 break;
474                         }
475
476                         memcpy(&l, e + 1, sizeof(uint64_t));
477                         l = le64toh(l);
478
479                         if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
480                             e[1+sizeof(uint64_t)+l] != '\n') {
481                                 log_debug("Failed to parse message, ignoring.");
482                                 break;
483                         }
484
485                         k = malloc((e - p) + 1 + l);
486                         if (!k) {
487                                 log_error("Out of memory");
488                                 break;
489                         }
490
491                         memcpy(k, p, e - p);
492                         k[e - p] = '=';
493                         memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
494
495                         if (k[0] != '_') {
496                                 iovec[n].iov_base = k;
497                                 iovec[n].iov_len = (e - p) + 1 + l;
498                                 n++;
499                         } else
500                                 free(k);
501
502                         remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
503                         p = e + 1 + sizeof(uint64_t) + l + 1;
504                 }
505         }
506
507         dispatch_message(s, iovec, n, m, ucred, tv);
508
509         for (j = 0; j < n; j++)
510                 if (iovec[j].iov_base < buffer ||
511                     (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
512                         free(iovec[j].iov_base);
513 }
514
515 static int process_event(Server *s, struct epoll_event *ev) {
516         assert(s);
517
518         if (ev->events != EPOLLIN) {
519                 log_info("Got invalid event from epoll.");
520                 return -EIO;
521         }
522
523         if (ev->data.fd == s->signal_fd) {
524                 struct signalfd_siginfo sfsi;
525                 ssize_t n;
526
527                 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
528                 if (n != sizeof(sfsi)) {
529
530                         if (n >= 0)
531                                 return -EIO;
532
533                         if (errno == EINTR || errno == EAGAIN)
534                                 return 0;
535
536                         return -errno;
537                 }
538
539                 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
540                 return 0;
541
542         }
543
544         if (ev->data.fd == s->native_fd ||
545             ev->data.fd == s->syslog_fd) {
546                 for (;;) {
547                         struct msghdr msghdr;
548                         struct iovec iovec;
549                         struct ucred *ucred = NULL;
550                         struct timeval *tv = NULL;
551                         struct cmsghdr *cmsg;
552                         union {
553                                 struct cmsghdr cmsghdr;
554                                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
555                                             CMSG_SPACE(sizeof(struct timeval))];
556                         } control;
557                         ssize_t n;
558                         int v;
559
560                         if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
561                                 log_error("SIOCINQ failed: %m");
562                                 return -errno;
563                         }
564
565                         if (v <= 0)
566                                 return 1;
567
568                         if (s->buffer_size < (size_t) v) {
569                                 void *b;
570                                 size_t l;
571
572                                 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
573                                 b = realloc(s->buffer, l+1);
574
575                                 if (!b) {
576                                         log_error("Couldn't increase buffer.");
577                                         return -ENOMEM;
578                                 }
579
580                                 s->buffer_size = l;
581                                 s->buffer = b;
582                         }
583
584                         zero(iovec);
585                         iovec.iov_base = s->buffer;
586                         iovec.iov_len = s->buffer_size;
587
588                         zero(control);
589                         zero(msghdr);
590                         msghdr.msg_iov = &iovec;
591                         msghdr.msg_iovlen = 1;
592                         msghdr.msg_control = &control;
593                         msghdr.msg_controllen = sizeof(control);
594
595                         n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
596                         if (n < 0) {
597
598                                 if (errno == EINTR || errno == EAGAIN)
599                                         return 1;
600
601                                 log_error("recvmsg() failed: %m");
602                                 return -errno;
603                         }
604
605                         for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
606
607                                 if (cmsg->cmsg_level == SOL_SOCKET &&
608                                     cmsg->cmsg_type == SCM_CREDENTIALS &&
609                                     cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
610                                         ucred = (struct ucred*) CMSG_DATA(cmsg);
611                                 else if (cmsg->cmsg_level == SOL_SOCKET &&
612                                          cmsg->cmsg_type == SO_TIMESTAMP &&
613                                          cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
614                                         tv = (struct timeval*) CMSG_DATA(cmsg);
615                         }
616
617                         if (ev->data.fd == s->syslog_fd) {
618                                 char *e;
619
620                                 e = memchr(s->buffer, '\n', n);
621                                 if (e)
622                                         *e = 0;
623                                 else
624                                         s->buffer[n] = 0;
625
626                                 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
627                         } else
628                                 process_native_message(s, s->buffer, n, ucred, tv);
629                 }
630
631                 return 1;
632         }
633
634         log_error("Unknown event.");
635         return 0;
636 }
637
638 static int system_journal_open(Server *s) {
639         int r;
640         char *fn;
641         sd_id128_t machine;
642         char ids[33];
643
644         r = sd_id128_get_machine(&machine);
645         if (r < 0)
646                 return r;
647
648         /* First try to create the machine path, but not the prefix */
649         fn = strappend("/var/log/journal/", sd_id128_to_string(machine, ids));
650         if (!fn)
651                 return -ENOMEM;
652         (void) mkdir(fn, 0755);
653         free(fn);
654
655         /* The create the system journal file */
656         fn = join("/var/log/journal/", ids, "/system.journal", NULL);
657         if (!fn)
658                 return -ENOMEM;
659
660         r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
661         free(fn);
662
663         if (r >= 0) {
664                 fix_perms(s->system_journal, 0);
665                 return r;
666         }
667
668         if (r < 0 && r != -ENOENT) {
669                 log_error("Failed to open system journal: %s", strerror(-r));
670                 return r;
671         }
672
673         /* /var didn't work, so try /run, but this time we
674          * create the prefix too */
675         fn = join("/run/log/journal/", ids, "/system.journal", NULL);
676         if (!fn)
677                 return -ENOMEM;
678
679         (void) mkdir_parents(fn, 0755);
680         r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
681         free(fn);
682
683         if (r < 0) {
684                 log_error("Failed to open runtime journal: %s", strerror(-r));
685                 return r;
686         }
687
688         fix_perms(s->runtime_journal, 0);
689         return r;
690 }
691
692 static int open_syslog_socket(Server *s) {
693         union sockaddr_union sa;
694         int one, r;
695
696         assert(s);
697
698         if (s->syslog_fd < 0) {
699
700                 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
701                 if (s->syslog_fd < 0) {
702                         log_error("socket() failed: %m");
703                         return -errno;
704                 }
705
706                 zero(sa);
707                 sa.un.sun_family = AF_UNIX;
708                 strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
709
710                 unlink(sa.un.sun_path);
711
712                 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
713                 if (r < 0) {
714                         log_error("bind() failed: %m");
715                         return -errno;
716                 }
717
718                 chmod(sa.un.sun_path, 0666);
719         }
720
721         one = 1;
722         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
723         if (r < 0) {
724                 log_error("SO_PASSCRED failed: %m");
725                 return -errno;
726         }
727
728         one = 1;
729         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
730         if (r < 0) {
731                 log_error("SO_TIMESTAMP failed: %m");
732                 return -errno;
733         }
734
735         return 0;
736 }
737
738 static int open_native_socket(Server*s) {
739         union sockaddr_union sa;
740         int one, r;
741
742         assert(s);
743
744         if (s->native_fd < 0) {
745
746                 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
747                 if (s->native_fd < 0) {
748                         log_error("socket() failed: %m");
749                         return -errno;
750                 }
751
752                 zero(sa);
753                 sa.un.sun_family = AF_UNIX;
754                 strncpy(sa.un.sun_path, "/run/systemd/journal", sizeof(sa.un.sun_path));
755
756                 unlink(sa.un.sun_path);
757
758                 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
759                 if (r < 0) {
760                         log_error("bind() failed: %m");
761                         return -errno;
762                 }
763
764                 chmod(sa.un.sun_path, 0666);
765         }
766
767         one = 1;
768         r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
769         if (r < 0) {
770                 log_error("SO_PASSCRED failed: %m");
771                 return -errno;
772         }
773
774         one = 1;
775         r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
776         if (r < 0) {
777                 log_error("SO_TIMESTAMP failed: %m");
778                 return -errno;
779         }
780
781         return 0;
782 }
783
784 static int server_init(Server *s) {
785         int n, r, fd;
786         struct epoll_event ev;
787         sigset_t mask;
788
789         assert(s);
790
791         zero(*s);
792         s->syslog_fd = s->native_fd = s->signal_fd = -1;
793         s->metrics.max_size = DEFAULT_MAX_SIZE;
794         s->metrics.min_size = DEFAULT_MIN_SIZE;
795         s->metrics.keep_free = DEFAULT_KEEP_FREE;
796         s->max_use = DEFAULT_MAX_USE;
797
798         s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
799         if (s->epoll_fd < 0) {
800                 log_error("Failed to create epoll object: %m");
801                 return -errno;
802         }
803
804         n = sd_listen_fds(true);
805         if (n < 0) {
806                 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
807                 return n;
808         }
809
810         for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
811
812                 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
813
814                         if (s->syslog_fd >= 0) {
815                                 log_error("Too many /dev/log sockets passed.");
816                                 return -EINVAL;
817                         }
818
819                         s->syslog_fd = fd;
820
821                 } else if (sd_is_socket(fd, AF_UNIX, SOCK_DGRAM, -1) > 0) {
822
823                         if (s->native_fd >= 0) {
824                                 log_error("Too many native sockets passed.");
825                                 return -EINVAL;
826                         }
827
828                         s->native_fd = fd;
829                 } else {
830                         log_error("Unknown socket passed.");
831                         return -EINVAL;
832                 }
833         }
834
835         r = open_syslog_socket(s);
836         if (r < 0)
837                 return r;
838
839         zero(ev);
840         ev.events = EPOLLIN;
841         ev.data.fd = s->syslog_fd;
842         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
843                 log_error("Failed to add syslog server fd to epoll object: %m");
844                 return -errno;
845         }
846
847         r = open_native_socket(s);
848         if (r < 0)
849                 return r;
850
851         zero(ev);
852         ev.events = EPOLLIN;
853         ev.data.fd = s->native_fd;
854         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
855                 log_error("Failed to add native server fd to epoll object: %m");
856                 return -errno;
857         }
858
859         s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
860         if (!s->user_journals) {
861                 log_error("Out of memory.");
862                 return -ENOMEM;
863         }
864
865         r = system_journal_open(s);
866         if (r < 0)
867                 return r;
868
869         assert_se(sigemptyset(&mask) == 0);
870         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
871         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
872
873         s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
874         if (s->signal_fd < 0) {
875                 log_error("signalfd(): %m");
876                 return -errno;
877         }
878
879         zero(ev);
880         ev.events = EPOLLIN;
881         ev.data.fd = s->signal_fd;
882
883         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
884                 log_error("epoll_ctl(): %m");
885                 return -errno;
886         }
887
888         return 0;
889 }
890
891 static void server_done(Server *s) {
892         JournalFile *f;
893         assert(s);
894
895         if (s->system_journal)
896                 journal_file_close(s->system_journal);
897
898         if (s->runtime_journal)
899                 journal_file_close(s->runtime_journal);
900
901         while ((f = hashmap_steal_first(s->user_journals)))
902                 journal_file_close(f);
903
904         hashmap_free(s->user_journals);
905
906         if (s->epoll_fd >= 0)
907                 close_nointr_nofail(s->epoll_fd);
908
909         if (s->signal_fd >= 0)
910                 close_nointr_nofail(s->signal_fd);
911
912         if (s->syslog_fd >= 0)
913                 close_nointr_nofail(s->syslog_fd);
914
915         if (s->native_fd >= 0)
916                 close_nointr_nofail(s->native_fd);
917 }
918
919 int main(int argc, char *argv[]) {
920         Server server;
921         int r;
922
923         /* if (getppid() != 1) { */
924         /*         log_error("This program should be invoked by init only."); */
925         /*         return EXIT_FAILURE; */
926         /* } */
927
928         if (argc > 1) {
929                 log_error("This program does not take arguments.");
930                 return EXIT_FAILURE;
931         }
932
933         log_set_target(LOG_TARGET_CONSOLE);
934         log_parse_environment();
935         log_open();
936
937         umask(0022);
938
939         r = server_init(&server);
940         if (r < 0)
941                 goto finish;
942
943         log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
944
945         sd_notify(false,
946                   "READY=1\n"
947                   "STATUS=Processing messages...");
948
949         for (;;) {
950                 struct epoll_event event;
951
952                 r = epoll_wait(server.epoll_fd, &event, 1, -1);
953                 if (r < 0) {
954
955                         if (errno == EINTR)
956                                 continue;
957
958                         log_error("epoll_wait() failed: %m");
959                         r = -errno;
960                         goto finish;
961                 } else if (r == 0)
962                         break;
963
964                 r = process_event(&server, &event);
965                 if (r < 0)
966                         goto finish;
967                 else if (r == 0)
968                         break;
969         }
970
971 finish:
972         sd_notify(false,
973                   "STATUS=Shutting down...");
974
975         server_done(&server);
976
977         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
978 }