chiark / gitweb /
journalctl: add new short-monotonic output mode
[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 #include <sys/statvfs.h>
34
35 #include <systemd/sd-journal.h>
36 #include <systemd/sd-login.h>
37 #include <systemd/sd-messages.h>
38 #include <systemd/sd-daemon.h>
39
40 #include "hashmap.h"
41 #include "journal-file.h"
42 #include "socket-util.h"
43 #include "acl-util.h"
44 #include "cgroup-util.h"
45 #include "list.h"
46 #include "journal-rate-limit.h"
47 #include "journal-internal.h"
48 #include "conf-parser.h"
49 #include "journald.h"
50 #include "virt.h"
51
52 #define USER_JOURNALS_MAX 1024
53 #define STDOUT_STREAMS_MAX 4096
54
55 #define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
56 #define DEFAULT_RATE_LIMIT_BURST 200
57
58 #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
59
60 #define RECHECK_VAR_AVAILABLE_USEC (30*USEC_PER_SEC)
61
62 #define SYSLOG_TIMEOUT_USEC (250*USEC_PER_MSEC)
63
64 #define N_IOVEC_META_FIELDS 16
65
66 typedef enum StdoutStreamState {
67         STDOUT_STREAM_IDENTIFIER,
68         STDOUT_STREAM_PRIORITY,
69         STDOUT_STREAM_LEVEL_PREFIX,
70         STDOUT_STREAM_FORWARD_TO_SYSLOG,
71         STDOUT_STREAM_FORWARD_TO_KMSG,
72         STDOUT_STREAM_FORWARD_TO_CONSOLE,
73         STDOUT_STREAM_RUNNING
74 } StdoutStreamState;
75
76 struct StdoutStream {
77         Server *server;
78         StdoutStreamState state;
79
80         int fd;
81
82         struct ucred ucred;
83
84         char *identifier;
85         int priority;
86         bool level_prefix:1;
87         bool forward_to_syslog:1;
88         bool forward_to_kmsg:1;
89         bool forward_to_console:1;
90
91         char buffer[LINE_MAX+1];
92         size_t length;
93
94         LIST_FIELDS(StdoutStream, stdout_stream);
95 };
96
97 static int server_flush_to_var(Server *s);
98
99 static uint64_t available_space(Server *s) {
100         char ids[33], *p;
101         const char *f;
102         sd_id128_t machine;
103         struct statvfs ss;
104         uint64_t sum = 0, avail = 0, ss_avail = 0;
105         int r;
106         DIR *d;
107         usec_t ts;
108         JournalMetrics *m;
109
110         ts = now(CLOCK_MONOTONIC);
111
112         if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
113                 return s->cached_available_space;
114
115         r = sd_id128_get_machine(&machine);
116         if (r < 0)
117                 return 0;
118
119         if (s->system_journal) {
120                 f = "/var/log/journal/";
121                 m = &s->system_metrics;
122         } else {
123                 f = "/run/log/journal/";
124                 m = &s->runtime_metrics;
125         }
126
127         assert(m);
128
129         p = strappend(f, sd_id128_to_string(machine, ids));
130         if (!p)
131                 return 0;
132
133         d = opendir(p);
134         free(p);
135
136         if (!d)
137                 return 0;
138
139         if (fstatvfs(dirfd(d), &ss) < 0)
140                 goto finish;
141
142         for (;;) {
143                 struct stat st;
144                 struct dirent buf, *de;
145                 int k;
146
147                 k = readdir_r(d, &buf, &de);
148                 if (k != 0) {
149                         r = -k;
150                         goto finish;
151                 }
152
153                 if (!de)
154                         break;
155
156                 if (!dirent_is_file_with_suffix(de, ".journal"))
157                         continue;
158
159                 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
160                         continue;
161
162                 sum += (uint64_t) st.st_blocks * (uint64_t) st.st_blksize;
163         }
164
165         avail = sum >= m->max_use ? 0 : m->max_use - sum;
166
167         ss_avail = ss.f_bsize * ss.f_bavail;
168
169         ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
170
171         if (ss_avail < avail)
172                 avail = ss_avail;
173
174         s->cached_available_space = avail;
175         s->cached_available_space_timestamp = ts;
176
177 finish:
178         closedir(d);
179
180         return avail;
181 }
182
183 static void fix_perms(JournalFile *f, uid_t uid) {
184         acl_t acl;
185         acl_entry_t entry;
186         acl_permset_t permset;
187         int r;
188
189         assert(f);
190
191         r = fchmod_and_fchown(f->fd, 0640, 0, 0);
192         if (r < 0)
193                 log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
194
195         if (uid <= 0)
196                 return;
197
198         acl = acl_get_fd(f->fd);
199         if (!acl) {
200                 log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
201                 return;
202         }
203
204         r = acl_find_uid(acl, uid, &entry);
205         if (r <= 0) {
206
207                 if (acl_create_entry(&acl, &entry) < 0 ||
208                     acl_set_tag_type(entry, ACL_USER) < 0 ||
209                     acl_set_qualifier(entry, &uid) < 0) {
210                         log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
211                         goto finish;
212                 }
213         }
214
215         if (acl_get_permset(entry, &permset) < 0 ||
216             acl_add_perm(permset, ACL_READ) < 0 ||
217             acl_calc_mask(&acl) < 0) {
218                 log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
219                 goto finish;
220         }
221
222         if (acl_set_fd(f->fd, acl) < 0)
223                 log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
224
225 finish:
226         acl_free(acl);
227 }
228
229 static JournalFile* find_journal(Server *s, uid_t uid) {
230         char *p;
231         int r;
232         JournalFile *f;
233         char ids[33];
234         sd_id128_t machine;
235
236         assert(s);
237
238         /* We split up user logs only on /var, not on /run. If the
239          * runtime file is open, we write to it exclusively, in order
240          * to guarantee proper order as soon as we flush /run to
241          * /var and close the runtime file. */
242
243         if (s->runtime_journal)
244                 return s->runtime_journal;
245
246         if (uid <= 0)
247                 return s->system_journal;
248
249         r = sd_id128_get_machine(&machine);
250         if (r < 0)
251                 return s->system_journal;
252
253         f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
254         if (f)
255                 return f;
256
257         if (asprintf(&p, "/var/log/journal/%s/user-%lu.journal", sd_id128_to_string(machine, ids), (unsigned long) uid) < 0)
258                 return s->system_journal;
259
260         while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
261                 /* Too many open? Then let's close one */
262                 f = hashmap_steal_first(s->user_journals);
263                 assert(f);
264                 journal_file_close(f);
265         }
266
267         r = journal_file_open(p, O_RDWR|O_CREAT, 0640, s->system_journal, &f);
268         free(p);
269
270         if (r < 0)
271                 return s->system_journal;
272
273         fix_perms(f, uid);
274         f->metrics = s->system_metrics;
275         f->compress = s->compress;
276
277         r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
278         if (r < 0) {
279                 journal_file_close(f);
280                 return s->system_journal;
281         }
282
283         return f;
284 }
285
286 static void server_rotate(Server *s) {
287         JournalFile *f;
288         void *k;
289         Iterator i;
290         int r;
291
292         log_info("Rotating...");
293
294         if (s->runtime_journal) {
295                 r = journal_file_rotate(&s->runtime_journal);
296                 if (r < 0)
297                         log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
298         }
299
300         if (s->system_journal) {
301                 r = journal_file_rotate(&s->system_journal);
302                 if (r < 0)
303                         log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
304         }
305
306         HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
307                 r = journal_file_rotate(&f);
308                 if (r < 0)
309                         log_error("Failed to rotate %s: %s", f->path, strerror(-r));
310                 else
311                         hashmap_replace(s->user_journals, k, f);
312         }
313 }
314
315 static void server_vacuum(Server *s) {
316         char *p;
317         char ids[33];
318         sd_id128_t machine;
319         int r;
320
321         log_info("Vacuuming...");
322
323         r = sd_id128_get_machine(&machine);
324         if (r < 0) {
325                 log_error("Failed to get machine ID: %s", strerror(-r));
326                 return;
327         }
328
329         sd_id128_to_string(machine, ids);
330
331         if (s->system_journal) {
332                 if (asprintf(&p, "/var/log/journal/%s", ids) < 0) {
333                         log_error("Out of memory.");
334                         return;
335                 }
336
337                 r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free);
338                 if (r < 0 && r != -ENOENT)
339                         log_error("Failed to vacuum %s: %s", p, strerror(-r));
340                 free(p);
341         }
342
343
344         if (s->runtime_journal) {
345                 if (asprintf(&p, "/run/log/journal/%s", ids) < 0) {
346                         log_error("Out of memory.");
347                         return;
348                 }
349
350                 r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free);
351                 if (r < 0 && r != -ENOENT)
352                         log_error("Failed to vacuum %s: %s", p, strerror(-r));
353                 free(p);
354         }
355
356         s->cached_available_space_timestamp = 0;
357 }
358
359 static char *shortened_cgroup_path(pid_t pid) {
360         int r;
361         char *process_path, *init_path, *path;
362
363         assert(pid > 0);
364
365         r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, pid, &process_path);
366         if (r < 0)
367                 return NULL;
368
369         r = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 1, &init_path);
370         if (r < 0) {
371                 free(process_path);
372                 return NULL;
373         }
374
375         if (endswith(init_path, "/system"))
376                 init_path[strlen(init_path) - 7] = 0;
377         else if (streq(init_path, "/"))
378                 init_path[0] = 0;
379
380         if (startswith(process_path, init_path)) {
381                 char *p;
382
383                 p = strdup(process_path + strlen(init_path));
384                 if (!p) {
385                         free(process_path);
386                         free(init_path);
387                         return NULL;
388                 }
389                 path = p;
390         } else {
391                 path = process_path;
392                 process_path = NULL;
393         }
394
395         free(process_path);
396         free(init_path);
397
398         return path;
399 }
400
401 static void dispatch_message_real(Server *s,
402                              struct iovec *iovec, unsigned n, unsigned m,
403                              struct ucred *ucred,
404                              struct timeval *tv) {
405
406         char *pid = NULL, *uid = NULL, *gid = NULL,
407                 *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
408                 *comm = NULL, *cmdline = NULL, *hostname = NULL,
409                 *audit_session = NULL, *audit_loginuid = NULL,
410                 *exe = NULL, *cgroup = NULL, *session = NULL,
411                 *owner_uid = NULL, *unit = NULL;
412
413         char idbuf[33];
414         sd_id128_t id;
415         int r;
416         char *t;
417         uid_t loginuid = 0, realuid = 0;
418         JournalFile *f;
419         bool vacuumed = false;
420
421         assert(s);
422         assert(iovec);
423         assert(n > 0);
424         assert(n + N_IOVEC_META_FIELDS <= m);
425
426         if (ucred) {
427                 uint32_t audit;
428                 uid_t owner;
429
430                 realuid = ucred->uid;
431
432                 if (asprintf(&pid, "_PID=%lu", (unsigned long) ucred->pid) >= 0)
433                         IOVEC_SET_STRING(iovec[n++], pid);
434
435                 if (asprintf(&uid, "_UID=%lu", (unsigned long) ucred->uid) >= 0)
436                         IOVEC_SET_STRING(iovec[n++], uid);
437
438                 if (asprintf(&gid, "_GID=%lu", (unsigned long) ucred->gid) >= 0)
439                         IOVEC_SET_STRING(iovec[n++], gid);
440
441                 r = get_process_comm(ucred->pid, &t);
442                 if (r >= 0) {
443                         comm = strappend("_COMM=", t);
444                         free(t);
445
446                         if (comm)
447                                 IOVEC_SET_STRING(iovec[n++], comm);
448                 }
449
450                 r = get_process_exe(ucred->pid, &t);
451                 if (r >= 0) {
452                         exe = strappend("_EXE=", t);
453                         free(t);
454
455                         if (comm)
456                                 IOVEC_SET_STRING(iovec[n++], exe);
457                 }
458
459                 r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
460                 if (r >= 0) {
461                         cmdline = strappend("_CMDLINE=", t);
462                         free(t);
463
464                         if (cmdline)
465                                 IOVEC_SET_STRING(iovec[n++], cmdline);
466                 }
467
468                 r = audit_session_from_pid(ucred->pid, &audit);
469                 if (r >= 0)
470                         if (asprintf(&audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit) >= 0)
471                                 IOVEC_SET_STRING(iovec[n++], audit_session);
472
473                 r = audit_loginuid_from_pid(ucred->pid, &loginuid);
474                 if (r >= 0)
475                         if (asprintf(&audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
476                                 IOVEC_SET_STRING(iovec[n++], audit_loginuid);
477
478                 t = shortened_cgroup_path(ucred->pid);
479                 if (t) {
480                         cgroup = strappend("_SYSTEMD_CGROUP=", t);
481                         free(t);
482
483                         if (cgroup)
484                                 IOVEC_SET_STRING(iovec[n++], cgroup);
485                 }
486
487                 if (sd_pid_get_session(ucred->pid, &t) >= 0) {
488                         session = strappend("_SYSTEMD_SESSION=", t);
489                         free(t);
490
491                         if (session)
492                                 IOVEC_SET_STRING(iovec[n++], session);
493                 }
494
495                 if (sd_pid_get_unit(ucred->pid, &t) >= 0) {
496                         unit = strappend("_SYSTEMD_UNIT=", t);
497                         free(t);
498
499                         if (unit)
500                                 IOVEC_SET_STRING(iovec[n++], unit);
501                 }
502
503                 if (sd_pid_get_owner_uid(ucred->uid, &owner) >= 0)
504                         if (asprintf(&owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner) >= 0)
505                                 IOVEC_SET_STRING(iovec[n++], owner_uid);
506         }
507
508         if (tv) {
509                 if (asprintf(&source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu",
510                              (unsigned long long) timeval_load(tv)) >= 0)
511                         IOVEC_SET_STRING(iovec[n++], source_time);
512         }
513
514         /* Note that strictly speaking storing the boot id here is
515          * redundant since the entry includes this in-line
516          * anyway. However, we need this indexed, too. */
517         r = sd_id128_get_boot(&id);
518         if (r >= 0)
519                 if (asprintf(&boot_id, "_BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
520                         IOVEC_SET_STRING(iovec[n++], boot_id);
521
522         r = sd_id128_get_machine(&id);
523         if (r >= 0)
524                 if (asprintf(&machine_id, "_MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
525                         IOVEC_SET_STRING(iovec[n++], machine_id);
526
527         t = gethostname_malloc();
528         if (t) {
529                 hostname = strappend("_HOSTNAME=", t);
530                 free(t);
531                 if (hostname)
532                         IOVEC_SET_STRING(iovec[n++], hostname);
533         }
534
535         assert(n <= m);
536
537         server_flush_to_var(s);
538
539 retry:
540         f = find_journal(s, realuid == 0 ? 0 : loginuid);
541         if (!f)
542                 log_warning("Dropping message, as we can't find a place to store the data.");
543         else {
544                 r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
545
546                 if (r == -E2BIG && !vacuumed) {
547                         log_info("Allocation limit reached.");
548
549                         server_rotate(s);
550                         server_vacuum(s);
551                         vacuumed = true;
552
553                         log_info("Retrying write.");
554                         goto retry;
555                 }
556
557                 if (r < 0)
558                         log_error("Failed to write entry, ignoring: %s", strerror(-r));
559         }
560
561         free(pid);
562         free(uid);
563         free(gid);
564         free(comm);
565         free(exe);
566         free(cmdline);
567         free(source_time);
568         free(boot_id);
569         free(machine_id);
570         free(hostname);
571         free(audit_session);
572         free(audit_loginuid);
573         free(cgroup);
574         free(session);
575         free(owner_uid);
576         free(unit);
577 }
578
579 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
580         char mid[11 + 32 + 1];
581         char buffer[16 + LINE_MAX + 1];
582         struct iovec iovec[N_IOVEC_META_FIELDS + 4];
583         int n = 0;
584         va_list ap;
585         struct ucred ucred;
586
587         assert(s);
588         assert(format);
589
590         IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
591         IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
592
593         memcpy(buffer, "MESSAGE=", 8);
594         va_start(ap, format);
595         vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
596         va_end(ap);
597         char_array_0(buffer);
598         IOVEC_SET_STRING(iovec[n++], buffer);
599
600         snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
601         char_array_0(mid);
602         IOVEC_SET_STRING(iovec[n++], mid);
603
604         zero(ucred);
605         ucred.pid = getpid();
606         ucred.uid = getuid();
607         ucred.gid = getgid();
608
609         dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL);
610 }
611
612 static void dispatch_message(Server *s,
613                              struct iovec *iovec, unsigned n, unsigned m,
614                              struct ucred *ucred,
615                              struct timeval *tv,
616                              int priority) {
617         int rl;
618         char *path = NULL, *c;
619
620         assert(s);
621         assert(iovec || n == 0);
622
623         if (n == 0)
624                 return;
625
626         if (!ucred)
627                 goto finish;
628
629         path = shortened_cgroup_path(ucred->pid);
630         if (!path)
631                 goto finish;
632
633         /* example: /user/lennart/3/foobar
634          *          /system/dbus.service/foobar
635          *
636          * So let's cut of everything past the third /, since that is
637          * wher user directories start */
638
639         c = strchr(path, '/');
640         if (c) {
641                 c = strchr(c+1, '/');
642                 if (c) {
643                         c = strchr(c+1, '/');
644                         if (c)
645                                 *c = 0;
646                 }
647         }
648
649         rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
650
651         if (rl == 0) {
652                 free(path);
653                 return;
654         }
655
656         /* Write a suppression message if we suppressed something */
657         if (rl > 1)
658                 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
659
660         free(path);
661
662 finish:
663         dispatch_message_real(s, iovec, n, m, ucred, tv);
664 }
665
666 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
667         struct msghdr msghdr;
668         struct cmsghdr *cmsg;
669         union {
670                 struct cmsghdr cmsghdr;
671                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
672         } control;
673         union sockaddr_union sa;
674
675         assert(s);
676         assert(iovec);
677         assert(n_iovec > 0);
678
679         zero(msghdr);
680         msghdr.msg_iov = (struct iovec*) iovec;
681         msghdr.msg_iovlen = n_iovec;
682
683         zero(sa);
684         sa.un.sun_family = AF_UNIX;
685         strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
686         msghdr.msg_name = &sa;
687         msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
688
689         if (ucred) {
690                 zero(control);
691                 msghdr.msg_control = &control;
692                 msghdr.msg_controllen = sizeof(control);
693
694                 cmsg = CMSG_FIRSTHDR(&msghdr);
695                 cmsg->cmsg_level = SOL_SOCKET;
696                 cmsg->cmsg_type = SCM_CREDENTIALS;
697                 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
698                 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
699                 msghdr.msg_controllen = cmsg->cmsg_len;
700         }
701
702         /* Forward the syslog message we received via /dev/log to
703          * /run/systemd/syslog. Unfortunately we currently can't set
704          * the SO_TIMESTAMP auxiliary data, and hence we don't. */
705
706         if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
707                 return;
708
709         if (ucred && errno == ESRCH) {
710                 struct ucred u;
711
712                 /* Hmm, presumably the sender process vanished
713                  * by now, so let's fix it as good as we
714                  * can, and retry */
715
716                 u = *ucred;
717                 u.pid = getpid();
718                 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
719
720                 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
721                         return;
722         }
723
724         log_debug("Failed to forward syslog message: %m");
725 }
726
727 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
728         struct iovec iovec;
729
730         assert(s);
731         assert(buffer);
732
733         IOVEC_SET_STRING(iovec, buffer);
734         forward_syslog_iovec(s, &iovec, 1, ucred, tv);
735 }
736
737 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
738         struct iovec iovec[5];
739         char header_priority[6], header_time[64], header_pid[16];
740         int n = 0;
741         time_t t;
742         struct tm *tm;
743         char *ident_buf = NULL;
744
745         assert(s);
746         assert(priority >= 0);
747         assert(priority <= 999);
748         assert(message);
749
750         /* First: priority field */
751         snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
752         char_array_0(header_priority);
753         IOVEC_SET_STRING(iovec[n++], header_priority);
754
755         /* Second: timestamp */
756         t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
757         tm = localtime(&t);
758         if (!tm)
759                 return;
760         if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
761                 return;
762         IOVEC_SET_STRING(iovec[n++], header_time);
763
764         /* Third: identifier and PID */
765         if (ucred) {
766                 if (!identifier) {
767                         get_process_comm(ucred->pid, &ident_buf);
768                         identifier = ident_buf;
769                 }
770
771                 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
772                 char_array_0(header_pid);
773
774                 if (identifier)
775                         IOVEC_SET_STRING(iovec[n++], identifier);
776
777                 IOVEC_SET_STRING(iovec[n++], header_pid);
778         } else if (identifier) {
779                 IOVEC_SET_STRING(iovec[n++], identifier);
780                 IOVEC_SET_STRING(iovec[n++], ": ");
781         }
782
783         /* Fourth: message */
784         IOVEC_SET_STRING(iovec[n++], message);
785
786         forward_syslog_iovec(s, iovec, n, ucred, tv);
787
788         free(ident_buf);
789 }
790
791 static int fixup_priority(int priority) {
792
793         if ((priority & LOG_FACMASK) == 0)
794                 return (priority & LOG_PRIMASK) | LOG_USER;
795
796         return priority;
797 }
798
799 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
800         struct iovec iovec[5];
801         char header_priority[6], header_pid[16];
802         int n = 0;
803         char *ident_buf = NULL;
804         int fd;
805
806         assert(s);
807         assert(priority >= 0);
808         assert(priority <= 999);
809         assert(message);
810
811         /* Never allow messages with kernel facility to be written to
812          * kmsg, regardless where the data comes from. */
813         priority = fixup_priority(priority);
814
815         /* First: priority field */
816         snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
817         char_array_0(header_priority);
818         IOVEC_SET_STRING(iovec[n++], header_priority);
819
820         /* Second: identifier and PID */
821         if (ucred) {
822                 if (!identifier) {
823                         get_process_comm(ucred->pid, &ident_buf);
824                         identifier = ident_buf;
825                 }
826
827                 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
828                 char_array_0(header_pid);
829
830                 if (identifier)
831                         IOVEC_SET_STRING(iovec[n++], identifier);
832
833                 IOVEC_SET_STRING(iovec[n++], header_pid);
834         } else if (identifier) {
835                 IOVEC_SET_STRING(iovec[n++], identifier);
836                 IOVEC_SET_STRING(iovec[n++], ": ");
837         }
838
839         /* Fourth: message */
840         IOVEC_SET_STRING(iovec[n++], message);
841         IOVEC_SET_STRING(iovec[n++], "\n");
842
843         fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
844         if (fd < 0) {
845                 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
846                 goto finish;
847         }
848
849         if (writev(fd, iovec, n) < 0)
850                 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
851
852         close_nointr_nofail(fd);
853
854 finish:
855         free(ident_buf);
856 }
857
858 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
859         struct iovec iovec[4];
860         char header_pid[16];
861         int n = 0, fd;
862         char *ident_buf = NULL;
863
864         assert(s);
865         assert(message);
866
867         /* First: identifier and PID */
868         if (ucred) {
869                 if (!identifier) {
870                         get_process_comm(ucred->pid, &ident_buf);
871                         identifier = ident_buf;
872                 }
873
874                 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
875                 char_array_0(header_pid);
876
877                 if (identifier)
878                         IOVEC_SET_STRING(iovec[n++], identifier);
879
880                 IOVEC_SET_STRING(iovec[n++], header_pid);
881         } else if (identifier) {
882                 IOVEC_SET_STRING(iovec[n++], identifier);
883                 IOVEC_SET_STRING(iovec[n++], ": ");
884         }
885
886         /* Third: message */
887         IOVEC_SET_STRING(iovec[n++], message);
888         IOVEC_SET_STRING(iovec[n++], "\n");
889
890         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
891         if (fd < 0) {
892                 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
893                 goto finish;
894         }
895
896         if (writev(fd, iovec, n) < 0)
897                 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
898
899         close_nointr_nofail(fd);
900
901 finish:
902         free(ident_buf);
903 }
904
905 static void read_identifier(const char **buf, char **identifier, char **pid) {
906         const char *p;
907         char *t;
908         size_t l, e;
909
910         assert(buf);
911         assert(identifier);
912         assert(pid);
913
914         p = *buf;
915
916         p += strspn(p, WHITESPACE);
917         l = strcspn(p, WHITESPACE);
918
919         if (l <= 0 ||
920             p[l-1] != ':')
921                 return;
922
923         e = l;
924         l--;
925
926         if (p[l-1] == ']') {
927                 size_t k = l-1;
928
929                 for (;;) {
930
931                         if (p[k] == '[') {
932                                 t = strndup(p+k+1, l-k-2);
933                                 if (t)
934                                         *pid = t;
935
936                                 l = k;
937                                 break;
938                         }
939
940                         if (k == 0)
941                                 break;
942
943                         k--;
944                 }
945         }
946
947         t = strndup(p, l);
948         if (t)
949                 *identifier = t;
950
951         *buf = p + e;
952         *buf += strspn(*buf, WHITESPACE);
953 }
954
955 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
956         char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
957         struct iovec iovec[N_IOVEC_META_FIELDS + 6];
958         unsigned n = 0;
959         int priority = LOG_USER | LOG_INFO;
960         char *identifier = NULL, *pid = NULL;
961
962         assert(s);
963         assert(buf);
964
965         if (s->forward_to_syslog)
966                 forward_syslog_raw(s, buf, ucred, tv);
967
968         parse_syslog_priority((char**) &buf, &priority);
969         skip_syslog_date((char**) &buf);
970         read_identifier(&buf, &identifier, &pid);
971
972         if (s->forward_to_kmsg)
973                 forward_kmsg(s, priority, identifier, buf, ucred);
974
975         if (s->forward_to_console)
976                 forward_console(s, identifier, buf, ucred);
977
978         IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
979
980         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
981                 IOVEC_SET_STRING(iovec[n++], syslog_priority);
982
983         if (priority & LOG_FACMASK)
984                 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
985                         IOVEC_SET_STRING(iovec[n++], syslog_facility);
986
987         if (identifier) {
988                 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
989                 if (syslog_identifier)
990                         IOVEC_SET_STRING(iovec[n++], syslog_identifier);
991         }
992
993         if (pid) {
994                 syslog_pid = strappend("SYSLOG_PID=", pid);
995                 if (syslog_pid)
996                         IOVEC_SET_STRING(iovec[n++], syslog_pid);
997         }
998
999         message = strappend("MESSAGE=", buf);
1000         if (message)
1001                 IOVEC_SET_STRING(iovec[n++], message);
1002
1003         dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, priority);
1004
1005         free(message);
1006         free(identifier);
1007         free(pid);
1008         free(syslog_priority);
1009         free(syslog_facility);
1010         free(syslog_identifier);
1011 }
1012
1013 static bool valid_user_field(const char *p, size_t l) {
1014         const char *a;
1015
1016         /* We kinda enforce POSIX syntax recommendations for
1017            environment variables here, but make a couple of additional
1018            requirements.
1019
1020            http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1021
1022         /* No empty field names */
1023         if (l <= 0)
1024                 return false;
1025
1026         /* Don't allow names longer than 64 chars */
1027         if (l > 64)
1028                 return false;
1029
1030         /* Variables starting with an underscore are protected */
1031         if (p[0] == '_')
1032                 return false;
1033
1034         /* Don't allow digits as first character */
1035         if (p[0] >= '0' && p[0] <= '9')
1036                 return false;
1037
1038         /* Only allow A-Z0-9 and '_' */
1039         for (a = p; a < p + l; a++)
1040                 if (!((*a >= 'A' && *a <= 'Z') ||
1041                       (*a >= '0' && *a <= '9') ||
1042                       *a == '_'))
1043                         return false;
1044
1045         return true;
1046 }
1047
1048 static void process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv) {
1049         struct iovec *iovec = NULL;
1050         unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1051         const char *p;
1052         size_t remaining;
1053         int priority = LOG_INFO;
1054         char *identifier = NULL, *message = NULL;
1055
1056         assert(s);
1057         assert(buffer || n == 0);
1058
1059         p = buffer;
1060         remaining = buffer_size;
1061
1062         while (remaining > 0) {
1063                 const char *e, *q;
1064
1065                 e = memchr(p, '\n', remaining);
1066
1067                 if (!e) {
1068                         /* Trailing noise, let's ignore it, and flush what we collected */
1069                         log_debug("Received message with trailing noise, ignoring.");
1070                         break;
1071                 }
1072
1073                 if (e == p) {
1074                         /* Entry separator */
1075                         dispatch_message(s, iovec, n, m, ucred, tv, priority);
1076                         n = 0;
1077                         priority = LOG_INFO;
1078
1079                         p++;
1080                         remaining--;
1081                         continue;
1082                 }
1083
1084                 if (*p == '.' || *p == '#') {
1085                         /* Ignore control commands for now, and
1086                          * comments too. */
1087                         remaining -= (e - p) + 1;
1088                         p = e + 1;
1089                         continue;
1090                 }
1091
1092                 /* A property follows */
1093
1094                 if (n+N_IOVEC_META_FIELDS >= m) {
1095                         struct iovec *c;
1096                         unsigned u;
1097
1098                         u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1099                         c = realloc(iovec, u * sizeof(struct iovec));
1100                         if (!c) {
1101                                 log_error("Out of memory");
1102                                 break;
1103                         }
1104
1105                         iovec = c;
1106                         m = u;
1107                 }
1108
1109                 q = memchr(p, '=', e - p);
1110                 if (q) {
1111                         if (valid_user_field(p, q - p)) {
1112                                 size_t l;
1113
1114                                 l = e - p;
1115
1116                                 /* If the field name starts with an
1117                                  * underscore, skip the variable,
1118                                  * since that indidates a trusted
1119                                  * field */
1120                                 iovec[n].iov_base = (char*) p;
1121                                 iovec[n].iov_len = l;
1122                                 n++;
1123
1124                                 /* We need to determine the priority
1125                                  * of this entry for the rate limiting
1126                                  * logic */
1127                                 if (l == 10 &&
1128                                     memcmp(p, "PRIORITY=", 9) == 0 &&
1129                                     p[9] >= '0' && p[9] <= '9')
1130                                         priority = (priority & LOG_FACMASK) | (p[9] - '0');
1131
1132                                 else if (l == 17 &&
1133                                          memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1134                                          p[16] >= '0' && p[16] <= '9')
1135                                         priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1136
1137                                 else if (l == 18 &&
1138                                          memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1139                                          p[16] >= '0' && p[16] <= '9' &&
1140                                          p[17] >= '0' && p[17] <= '9')
1141                                         priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1142
1143                                 else if (l >= 12 &&
1144                                          memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1145                                         char *t;
1146
1147                                         t = strndup(p + 11, l - 11);
1148                                         if (t) {
1149                                                 free(identifier);
1150                                                 identifier = t;
1151                                         }
1152                                 } else if (l >= 8 &&
1153                                            memcmp(p, "MESSAGE=", 8) == 0) {
1154                                         char *t;
1155
1156                                         t = strndup(p + 8, l - 8);
1157                                         if (t) {
1158                                                 free(message);
1159                                                 message = t;
1160                                         }
1161                                 }
1162                         }
1163
1164                         remaining -= (e - p) + 1;
1165                         p = e + 1;
1166                         continue;
1167                 } else {
1168                         uint64_t l;
1169                         char *k;
1170
1171                         if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1172                                 log_debug("Failed to parse message, ignoring.");
1173                                 break;
1174                         }
1175
1176                         memcpy(&l, e + 1, sizeof(uint64_t));
1177                         l = le64toh(l);
1178
1179                         if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1180                             e[1+sizeof(uint64_t)+l] != '\n') {
1181                                 log_debug("Failed to parse message, ignoring.");
1182                                 break;
1183                         }
1184
1185                         k = malloc((e - p) + 1 + l);
1186                         if (!k) {
1187                                 log_error("Out of memory");
1188                                 break;
1189                         }
1190
1191                         memcpy(k, p, e - p);
1192                         k[e - p] = '=';
1193                         memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1194
1195                         if (valid_user_field(p, e - p)) {
1196                                 iovec[n].iov_base = k;
1197                                 iovec[n].iov_len = (e - p) + 1 + l;
1198                                 n++;
1199                         } else
1200                                 free(k);
1201
1202                         remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1203                         p = e + 1 + sizeof(uint64_t) + l + 1;
1204                 }
1205         }
1206
1207         if (n <= 0)
1208                 goto finish;
1209
1210         tn = n++;
1211         IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1212
1213         if (message) {
1214                 if (s->forward_to_syslog)
1215                         forward_syslog(s, priority, identifier, message, ucred, tv);
1216
1217                 if (s->forward_to_kmsg)
1218                         forward_kmsg(s, priority, identifier, message, ucred);
1219
1220                 if (s->forward_to_console)
1221                         forward_console(s, identifier, message, ucred);
1222         }
1223
1224         dispatch_message(s, iovec, n, m, ucred, tv, priority);
1225
1226 finish:
1227         for (j = 0; j < n; j++)  {
1228                 if (j == tn)
1229                         continue;
1230
1231                 if (iovec[j].iov_base < buffer ||
1232                     (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1233                         free(iovec[j].iov_base);
1234         }
1235
1236         free(identifier);
1237         free(message);
1238 }
1239
1240 static int stdout_stream_log(StdoutStream *s, const char *p) {
1241         struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1242         char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1243         unsigned n = 0;
1244         int priority;
1245
1246         assert(s);
1247         assert(p);
1248
1249         priority = s->priority;
1250
1251         if (s->level_prefix)
1252                 parse_syslog_priority((char**) &p, &priority);
1253
1254         if (s->forward_to_syslog || s->server->forward_to_syslog)
1255                 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1256
1257         if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1258                 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1259
1260         if (s->forward_to_console || s->server->forward_to_console)
1261                 forward_console(s->server, s->identifier, p, &s->ucred);
1262
1263         IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1264
1265         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1266                 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1267
1268         if (priority & LOG_FACMASK)
1269                 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1270                         IOVEC_SET_STRING(iovec[n++], syslog_facility);
1271
1272         if (s->identifier) {
1273                 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1274                 if (syslog_identifier)
1275                         IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1276         }
1277
1278         message = strappend("MESSAGE=", p);
1279         if (message)
1280                 IOVEC_SET_STRING(iovec[n++], message);
1281
1282         dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, priority);
1283
1284         free(message);
1285         free(syslog_priority);
1286         free(syslog_facility);
1287         free(syslog_identifier);
1288
1289         return 0;
1290 }
1291
1292 static int stdout_stream_line(StdoutStream *s, char *p) {
1293         int r;
1294
1295         assert(s);
1296         assert(p);
1297
1298         p = strstrip(p);
1299
1300         switch (s->state) {
1301
1302         case STDOUT_STREAM_IDENTIFIER:
1303                 s->identifier = strdup(p);
1304                 if (!s->identifier) {
1305                         log_error("Out of memory");
1306                         return -ENOMEM;
1307                 }
1308
1309                 s->state = STDOUT_STREAM_PRIORITY;
1310                 return 0;
1311
1312         case STDOUT_STREAM_PRIORITY:
1313                 r = safe_atoi(p, &s->priority);
1314                 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1315                         log_warning("Failed to parse log priority line.");
1316                         return -EINVAL;
1317                 }
1318
1319                 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1320                 return 0;
1321
1322         case STDOUT_STREAM_LEVEL_PREFIX:
1323                 r = parse_boolean(p);
1324                 if (r < 0) {
1325                         log_warning("Failed to parse level prefix line.");
1326                         return -EINVAL;
1327                 }
1328
1329                 s->level_prefix = !!r;
1330                 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1331                 return 0;
1332
1333         case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1334                 r = parse_boolean(p);
1335                 if (r < 0) {
1336                         log_warning("Failed to parse forward to syslog line.");
1337                         return -EINVAL;
1338                 }
1339
1340                 s->forward_to_syslog = !!r;
1341                 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1342                 return 0;
1343
1344         case STDOUT_STREAM_FORWARD_TO_KMSG:
1345                 r = parse_boolean(p);
1346                 if (r < 0) {
1347                         log_warning("Failed to parse copy to kmsg line.");
1348                         return -EINVAL;
1349                 }
1350
1351                 s->forward_to_kmsg = !!r;
1352                 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1353                 return 0;
1354
1355         case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1356                 r = parse_boolean(p);
1357                 if (r < 0) {
1358                         log_warning("Failed to parse copy to console line.");
1359                         return -EINVAL;
1360                 }
1361
1362                 s->forward_to_console = !!r;
1363                 s->state = STDOUT_STREAM_RUNNING;
1364                 return 0;
1365
1366         case STDOUT_STREAM_RUNNING:
1367                 return stdout_stream_log(s, p);
1368         }
1369
1370         assert_not_reached("Unknown stream state");
1371 }
1372
1373 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1374         char *p;
1375         size_t remaining;
1376         int r;
1377
1378         assert(s);
1379
1380         p = s->buffer;
1381         remaining = s->length;
1382         for (;;) {
1383                 char *end;
1384                 size_t skip;
1385
1386                 end = memchr(p, '\n', remaining);
1387                 if (end)
1388                         skip = end - p + 1;
1389                 else if (remaining >= sizeof(s->buffer) - 1) {
1390                         end = p + sizeof(s->buffer) - 1;
1391                         skip = remaining;
1392                 } else
1393                         break;
1394
1395                 *end = 0;
1396
1397                 r = stdout_stream_line(s, p);
1398                 if (r < 0)
1399                         return r;
1400
1401                 remaining -= skip;
1402                 p += skip;
1403         }
1404
1405         if (force_flush && remaining > 0) {
1406                 p[remaining] = 0;
1407                 r = stdout_stream_line(s, p);
1408                 if (r < 0)
1409                         return r;
1410
1411                 p += remaining;
1412                 remaining = 0;
1413         }
1414
1415         if (p > s->buffer) {
1416                 memmove(s->buffer, p, remaining);
1417                 s->length = remaining;
1418         }
1419
1420         return 0;
1421 }
1422
1423 static int stdout_stream_process(StdoutStream *s) {
1424         ssize_t l;
1425         int r;
1426
1427         assert(s);
1428
1429         l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1430         if (l < 0) {
1431
1432                 if (errno == EAGAIN)
1433                         return 0;
1434
1435                 log_warning("Failed to read from stream: %m");
1436                 return -errno;
1437         }
1438
1439         if (l == 0) {
1440                 r = stdout_stream_scan(s, true);
1441                 if (r < 0)
1442                         return r;
1443
1444                 return 0;
1445         }
1446
1447         s->length += l;
1448         r = stdout_stream_scan(s, false);
1449         if (r < 0)
1450                 return r;
1451
1452         return 1;
1453
1454 }
1455
1456 static void stdout_stream_free(StdoutStream *s) {
1457         assert(s);
1458
1459         if (s->server) {
1460                 assert(s->server->n_stdout_streams > 0);
1461                 s->server->n_stdout_streams --;
1462                 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1463         }
1464
1465         if (s->fd >= 0) {
1466                 if (s->server)
1467                         epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1468
1469                 close_nointr_nofail(s->fd);
1470         }
1471
1472         free(s->identifier);
1473         free(s);
1474 }
1475
1476 static int stdout_stream_new(Server *s) {
1477         StdoutStream *stream;
1478         int fd, r;
1479         socklen_t len;
1480         struct epoll_event ev;
1481
1482         assert(s);
1483
1484         fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1485         if (fd < 0) {
1486                 if (errno == EAGAIN)
1487                         return 0;
1488
1489                 log_error("Failed to accept stdout connection: %m");
1490                 return -errno;
1491         }
1492
1493         if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1494                 log_warning("Too many stdout streams, refusing connection.");
1495                 close_nointr_nofail(fd);
1496                 return 0;
1497         }
1498
1499         stream = new0(StdoutStream, 1);
1500         if (!stream) {
1501                 log_error("Out of memory.");
1502                 close_nointr_nofail(fd);
1503                 return -ENOMEM;
1504         }
1505
1506         stream->fd = fd;
1507
1508         len = sizeof(stream->ucred);
1509         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1510                 log_error("Failed to determine peer credentials: %m");
1511                 r = -errno;
1512                 goto fail;
1513         }
1514
1515         if (shutdown(fd, SHUT_WR) < 0) {
1516                 log_error("Failed to shutdown writing side of socket: %m");
1517                 r = -errno;
1518                 goto fail;
1519         }
1520
1521         zero(ev);
1522         ev.data.ptr = stream;
1523         ev.events = EPOLLIN;
1524         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1525                 log_error("Failed to add stream to event loop: %m");
1526                 r = -errno;
1527                 goto fail;
1528         }
1529
1530         stream->server = s;
1531         LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1532         s->n_stdout_streams ++;
1533
1534         return 0;
1535
1536 fail:
1537         stdout_stream_free(stream);
1538         return r;
1539 }
1540
1541 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1542         usec_t r;
1543         int k, i;
1544         char *p;
1545
1546         assert(_p);
1547         assert(*_p);
1548         assert(t);
1549
1550         p = *_p;
1551
1552         if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1553                 return 0;
1554
1555         r = 0;
1556
1557         for (i = 1; i <= 5; i++) {
1558                 r *= 10;
1559
1560                 if (p[i] == ' ')
1561                         continue;
1562
1563                 k = undecchar(p[i]);
1564                 if (k < 0)
1565                         return 0;
1566
1567                 r += k;
1568         }
1569
1570         for (i = 7; i <= 12; i++) {
1571                 r *= 10;
1572
1573                 k = undecchar(p[i]);
1574                 if (k < 0)
1575                         return 0;
1576
1577                 r += k;
1578         }
1579
1580         *t = r;
1581         *_p += 14;
1582         *_p += strspn(*_p, WHITESPACE);
1583
1584         return 1;
1585 }
1586
1587 static void proc_kmsg_line(Server *s, const char *p) {
1588         struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1589         char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1590         int priority = LOG_KERN | LOG_INFO;
1591         unsigned n = 0;
1592         usec_t usec;
1593         char *identifier = NULL, *pid = NULL;
1594
1595         assert(s);
1596         assert(p);
1597
1598         parse_syslog_priority((char **) &p, &priority);
1599
1600         if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1601                 return;
1602
1603         if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1604                 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1605                              (unsigned long long) usec) >= 0)
1606                         IOVEC_SET_STRING(iovec[n++], source_time);
1607         }
1608
1609         IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1610
1611         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1612                 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1613
1614         if ((priority & LOG_FACMASK) == LOG_KERN) {
1615
1616                 if (s->forward_to_syslog)
1617                         forward_syslog(s, priority, "kernel", p, NULL, NULL);
1618
1619                 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1620         } else {
1621                 read_identifier(&p, &identifier, &pid);
1622
1623                 if (s->forward_to_syslog)
1624                         forward_syslog(s, priority, identifier, p, NULL, NULL);
1625
1626                 if (identifier) {
1627                         syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1628                         if (syslog_identifier)
1629                                 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1630                 }
1631
1632                 if (pid) {
1633                         syslog_pid = strappend("SYSLOG_PID=", pid);
1634                         if (syslog_pid)
1635                                 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1636                 }
1637
1638                 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1639                         IOVEC_SET_STRING(iovec[n++], syslog_facility);
1640         }
1641
1642         message = strappend("MESSAGE=", p);
1643         if (message)
1644                 IOVEC_SET_STRING(iovec[n++], message);
1645
1646
1647         dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, priority);
1648
1649         free(message);
1650         free(syslog_priority);
1651         free(syslog_identifier);
1652         free(syslog_pid);
1653         free(syslog_facility);
1654         free(source_time);
1655         free(identifier);
1656         free(pid);
1657 }
1658
1659 static void proc_kmsg_scan(Server *s) {
1660         char *p;
1661         size_t remaining;
1662
1663         assert(s);
1664
1665         p = s->proc_kmsg_buffer;
1666         remaining = s->proc_kmsg_length;
1667         for (;;) {
1668                 char *end;
1669                 size_t skip;
1670
1671                 end = memchr(p, '\n', remaining);
1672                 if (end)
1673                         skip = end - p + 1;
1674                 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1675                         end = p + sizeof(s->proc_kmsg_buffer) - 1;
1676                         skip = remaining;
1677                 } else
1678                         break;
1679
1680                 *end = 0;
1681
1682                 proc_kmsg_line(s, p);
1683
1684                 remaining -= skip;
1685                 p += skip;
1686         }
1687
1688         if (p > s->proc_kmsg_buffer) {
1689                 memmove(s->proc_kmsg_buffer, p, remaining);
1690                 s->proc_kmsg_length = remaining;
1691         }
1692 }
1693
1694 static int system_journal_open(Server *s) {
1695         int r;
1696         char *fn;
1697         sd_id128_t machine;
1698         char ids[33];
1699
1700         r = sd_id128_get_machine(&machine);
1701         if (r < 0)
1702                 return r;
1703
1704         sd_id128_to_string(machine, ids);
1705
1706         if (!s->system_journal) {
1707
1708                 /* First try to create the machine path, but not the prefix */
1709                 fn = strappend("/var/log/journal/", ids);
1710                 if (!fn)
1711                         return -ENOMEM;
1712                 (void) mkdir(fn, 0755);
1713                 free(fn);
1714
1715                 /* The create the system journal file */
1716                 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1717                 if (!fn)
1718                         return -ENOMEM;
1719
1720                 r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1721                 free(fn);
1722
1723                 if (r >= 0) {
1724                         journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1725
1726                         s->system_journal->metrics = s->system_metrics;
1727                         s->system_journal->compress = s->compress;
1728
1729                         fix_perms(s->system_journal, 0);
1730                 } else if (r < 0) {
1731
1732                         if (r != -ENOENT && r != -EROFS)
1733                                 log_warning("Failed to open system journal: %s", strerror(-r));
1734
1735                         r = 0;
1736                 }
1737         }
1738
1739         if (!s->runtime_journal) {
1740
1741                 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1742                 if (!fn)
1743                         return -ENOMEM;
1744
1745                 if (s->system_journal) {
1746
1747                         /* Try to open the runtime journal, but only
1748                          * if it already exists, so that we can flush
1749                          * it into the system journal */
1750
1751                         r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1752                         free(fn);
1753
1754                         if (r < 0) {
1755                                 if (r != -ENOENT)
1756                                         log_warning("Failed to open runtime journal: %s", strerror(-r));
1757
1758                                 r = 0;
1759                         }
1760
1761                 } else {
1762
1763                         /* OK, we really need the runtime journal, so create
1764                          * it if necessary. */
1765
1766                         (void) mkdir_parents(fn, 0755);
1767                         r = journal_file_open(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1768                         free(fn);
1769
1770                         if (r < 0) {
1771                                 log_error("Failed to open runtime journal: %s", strerror(-r));
1772                                 return r;
1773                         }
1774                 }
1775
1776                 if (s->runtime_journal) {
1777                         journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1778
1779                         s->runtime_journal->metrics = s->runtime_metrics;
1780                         s->runtime_journal->compress = s->compress;
1781
1782                         fix_perms(s->runtime_journal, 0);
1783                 }
1784         }
1785
1786         return r;
1787 }
1788
1789 static int server_flush_to_var(Server *s) {
1790         char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1791         Object *o = NULL;
1792         int r;
1793         sd_id128_t machine;
1794         sd_journal *j;
1795         usec_t ts;
1796
1797         assert(s);
1798
1799         if (!s->runtime_journal)
1800                 return 0;
1801
1802         ts = now(CLOCK_MONOTONIC);
1803         if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1804                 return 0;
1805
1806         s->var_available_timestamp = ts;
1807
1808         system_journal_open(s);
1809
1810         if (!s->system_journal)
1811                 return 0;
1812
1813         log_info("Flushing to /var...");
1814
1815         r = sd_id128_get_machine(&machine);
1816         if (r < 0) {
1817                 log_error("Failed to get machine id: %s", strerror(-r));
1818                 return r;
1819         }
1820
1821         r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1822         if (r < 0) {
1823                 log_error("Failed to read runtime journal: %s", strerror(-r));
1824                 return r;
1825         }
1826
1827         SD_JOURNAL_FOREACH(j) {
1828                 JournalFile *f;
1829
1830                 f = j->current_file;
1831                 assert(f && f->current_offset > 0);
1832
1833                 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1834                 if (r < 0) {
1835                         log_error("Can't read entry: %s", strerror(-r));
1836                         goto finish;
1837                 }
1838
1839                 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1840                 if (r == -E2BIG) {
1841                         log_info("Allocation limit reached.");
1842
1843                         journal_file_post_change(s->system_journal);
1844                         server_rotate(s);
1845                         server_vacuum(s);
1846
1847                         r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
1848                 }
1849
1850                 if (r < 0) {
1851                         log_error("Can't write entry: %s", strerror(-r));
1852                         goto finish;
1853                 }
1854         }
1855
1856 finish:
1857         journal_file_post_change(s->system_journal);
1858
1859         journal_file_close(s->runtime_journal);
1860         s->runtime_journal = NULL;
1861
1862         if (r >= 0) {
1863                 sd_id128_to_string(machine, path + 17);
1864                 rm_rf(path, false, true, false);
1865         }
1866
1867         return r;
1868 }
1869
1870 static int server_read_proc_kmsg(Server *s) {
1871         ssize_t l;
1872         assert(s);
1873         assert(s->proc_kmsg_fd >= 0);
1874
1875         l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
1876         if (l < 0) {
1877
1878                 if (errno == EAGAIN || errno == EINTR)
1879                         return 0;
1880
1881                 log_error("Failed to read from kernel: %m");
1882                 return -errno;
1883         }
1884
1885         s->proc_kmsg_length += l;
1886
1887         proc_kmsg_scan(s);
1888         return 1;
1889 }
1890
1891 static int server_flush_proc_kmsg(Server *s) {
1892         int r;
1893
1894         assert(s);
1895
1896         if (s->proc_kmsg_fd < 0)
1897                 return 0;
1898
1899         log_info("Flushing /proc/kmsg...");
1900
1901         for (;;) {
1902                 r = server_read_proc_kmsg(s);
1903                 if (r < 0)
1904                         return r;
1905
1906                 if (r == 0)
1907                         break;
1908         }
1909
1910         return 0;
1911 }
1912
1913 static int process_event(Server *s, struct epoll_event *ev) {
1914         assert(s);
1915
1916         if (ev->data.fd == s->signal_fd) {
1917                 struct signalfd_siginfo sfsi;
1918                 ssize_t n;
1919
1920                 if (ev->events != EPOLLIN) {
1921                         log_info("Got invalid event from epoll.");
1922                         return -EIO;
1923                 }
1924
1925                 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
1926                 if (n != sizeof(sfsi)) {
1927
1928                         if (n >= 0)
1929                                 return -EIO;
1930
1931                         if (errno == EINTR || errno == EAGAIN)
1932                                 return 1;
1933
1934                         return -errno;
1935                 }
1936
1937                 if (sfsi.ssi_signo == SIGUSR1) {
1938                         server_flush_to_var(s);
1939                         return 0;
1940                 }
1941
1942                 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
1943                 return 0;
1944
1945         } else if (ev->data.fd == s->proc_kmsg_fd) {
1946                 int r;
1947
1948                 if (ev->events != EPOLLIN) {
1949                         log_info("Got invalid event from epoll.");
1950                         return -EIO;
1951                 }
1952
1953                 r = server_read_proc_kmsg(s);
1954                 if (r < 0)
1955                         return r;
1956
1957                 return 1;
1958
1959         } else if (ev->data.fd == s->native_fd ||
1960                    ev->data.fd == s->syslog_fd) {
1961
1962                 if (ev->events != EPOLLIN) {
1963                         log_info("Got invalid event from epoll.");
1964                         return -EIO;
1965                 }
1966
1967                 for (;;) {
1968                         struct msghdr msghdr;
1969                         struct iovec iovec;
1970                         struct ucred *ucred = NULL;
1971                         struct timeval *tv = NULL;
1972                         struct cmsghdr *cmsg;
1973                         union {
1974                                 struct cmsghdr cmsghdr;
1975                                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1976                                             CMSG_SPACE(sizeof(struct timeval))];
1977                         } control;
1978                         ssize_t n;
1979                         int v;
1980
1981                         if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
1982                                 log_error("SIOCINQ failed: %m");
1983                                 return -errno;
1984                         }
1985
1986                         if (v <= 0)
1987                                 return 1;
1988
1989                         if (s->buffer_size < (size_t) v) {
1990                                 void *b;
1991                                 size_t l;
1992
1993                                 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
1994                                 b = realloc(s->buffer, l+1);
1995
1996                                 if (!b) {
1997                                         log_error("Couldn't increase buffer.");
1998                                         return -ENOMEM;
1999                                 }
2000
2001                                 s->buffer_size = l;
2002                                 s->buffer = b;
2003                         }
2004
2005                         zero(iovec);
2006                         iovec.iov_base = s->buffer;
2007                         iovec.iov_len = s->buffer_size;
2008
2009                         zero(control);
2010                         zero(msghdr);
2011                         msghdr.msg_iov = &iovec;
2012                         msghdr.msg_iovlen = 1;
2013                         msghdr.msg_control = &control;
2014                         msghdr.msg_controllen = sizeof(control);
2015
2016                         n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
2017                         if (n < 0) {
2018
2019                                 if (errno == EINTR || errno == EAGAIN)
2020                                         return 1;
2021
2022                                 log_error("recvmsg() failed: %m");
2023                                 return -errno;
2024                         }
2025
2026                         for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2027
2028                                 if (cmsg->cmsg_level == SOL_SOCKET &&
2029                                     cmsg->cmsg_type == SCM_CREDENTIALS &&
2030                                     cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2031                                         ucred = (struct ucred*) CMSG_DATA(cmsg);
2032                                 else if (cmsg->cmsg_level == SOL_SOCKET &&
2033                                          cmsg->cmsg_type == SO_TIMESTAMP &&
2034                                          cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2035                                         tv = (struct timeval*) CMSG_DATA(cmsg);
2036                         }
2037
2038                         if (ev->data.fd == s->syslog_fd) {
2039                                 char *e;
2040
2041                                 e = memchr(s->buffer, '\n', n);
2042                                 if (e)
2043                                         *e = 0;
2044                                 else
2045                                         s->buffer[n] = 0;
2046
2047                                 process_syslog_message(s, strstrip(s->buffer), ucred, tv);
2048                         } else
2049                                 process_native_message(s, s->buffer, n, ucred, tv);
2050                 }
2051
2052                 return 1;
2053
2054         } else if (ev->data.fd == s->stdout_fd) {
2055
2056                 if (ev->events != EPOLLIN) {
2057                         log_info("Got invalid event from epoll.");
2058                         return -EIO;
2059                 }
2060
2061                 stdout_stream_new(s);
2062                 return 1;
2063
2064         } else {
2065                 StdoutStream *stream;
2066
2067                 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2068                         log_info("Got invalid event from epoll.");
2069                         return -EIO;
2070                 }
2071
2072                 /* If it is none of the well-known fds, it must be an
2073                  * stdout stream fd. Note that this is a bit ugly here
2074                  * (since we rely that none of the well-known fds
2075                  * could be interpreted as pointer), but nonetheless
2076                  * safe, since the well-known fds would never get an
2077                  * fd > 4096, i.e. beyond the first memory page */
2078
2079                 stream = ev->data.ptr;
2080
2081                 if (stdout_stream_process(stream) <= 0)
2082                         stdout_stream_free(stream);
2083
2084                 return 1;
2085         }
2086
2087         log_error("Unknown event.");
2088         return 0;
2089 }
2090
2091 static int open_syslog_socket(Server *s) {
2092         union sockaddr_union sa;
2093         int one, r;
2094         struct epoll_event ev;
2095         struct timeval tv;
2096
2097         assert(s);
2098
2099         if (s->syslog_fd < 0) {
2100
2101                 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2102                 if (s->syslog_fd < 0) {
2103                         log_error("socket() failed: %m");
2104                         return -errno;
2105                 }
2106
2107                 zero(sa);
2108                 sa.un.sun_family = AF_UNIX;
2109                 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2110
2111                 unlink(sa.un.sun_path);
2112
2113                 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2114                 if (r < 0) {
2115                         log_error("bind() failed: %m");
2116                         return -errno;
2117                 }
2118
2119                 chmod(sa.un.sun_path, 0666);
2120         }
2121
2122         one = 1;
2123         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2124         if (r < 0) {
2125                 log_error("SO_PASSCRED failed: %m");
2126                 return -errno;
2127         }
2128
2129         one = 1;
2130         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2131         if (r < 0) {
2132                 log_error("SO_TIMESTAMP failed: %m");
2133                 return -errno;
2134         }
2135
2136         /* Since we use the same socket for forwarding this to some
2137          * other syslog implementation, make sure we don't hang
2138          * forever */
2139         timeval_store(&tv, SYSLOG_TIMEOUT_USEC);
2140         if (setsockopt(s->syslog_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) {
2141                 log_error("SO_SNDTIMEO failed: %m");
2142                 return -errno;
2143         }
2144
2145         zero(ev);
2146         ev.events = EPOLLIN;
2147         ev.data.fd = s->syslog_fd;
2148         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2149                 log_error("Failed to add syslog server fd to epoll object: %m");
2150                 return -errno;
2151         }
2152
2153         return 0;
2154 }
2155
2156 static int open_native_socket(Server*s) {
2157         union sockaddr_union sa;
2158         int one, r;
2159         struct epoll_event ev;
2160
2161         assert(s);
2162
2163         if (s->native_fd < 0) {
2164
2165                 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2166                 if (s->native_fd < 0) {
2167                         log_error("socket() failed: %m");
2168                         return -errno;
2169                 }
2170
2171                 zero(sa);
2172                 sa.un.sun_family = AF_UNIX;
2173                 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2174
2175                 unlink(sa.un.sun_path);
2176
2177                 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2178                 if (r < 0) {
2179                         log_error("bind() failed: %m");
2180                         return -errno;
2181                 }
2182
2183                 chmod(sa.un.sun_path, 0666);
2184         }
2185
2186         one = 1;
2187         r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2188         if (r < 0) {
2189                 log_error("SO_PASSCRED failed: %m");
2190                 return -errno;
2191         }
2192
2193         one = 1;
2194         r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2195         if (r < 0) {
2196                 log_error("SO_TIMESTAMP failed: %m");
2197                 return -errno;
2198         }
2199
2200         zero(ev);
2201         ev.events = EPOLLIN;
2202         ev.data.fd = s->native_fd;
2203         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2204                 log_error("Failed to add native server fd to epoll object: %m");
2205                 return -errno;
2206         }
2207
2208         return 0;
2209 }
2210
2211 static int open_stdout_socket(Server *s) {
2212         union sockaddr_union sa;
2213         int r;
2214         struct epoll_event ev;
2215
2216         assert(s);
2217
2218         if (s->stdout_fd < 0) {
2219
2220                 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2221                 if (s->stdout_fd < 0) {
2222                         log_error("socket() failed: %m");
2223                         return -errno;
2224                 }
2225
2226                 zero(sa);
2227                 sa.un.sun_family = AF_UNIX;
2228                 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2229
2230                 unlink(sa.un.sun_path);
2231
2232                 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2233                 if (r < 0) {
2234                         log_error("bind() failed: %m");
2235                         return -errno;
2236                 }
2237
2238                 chmod(sa.un.sun_path, 0666);
2239
2240                 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2241                         log_error("liste() failed: %m");
2242                         return -errno;
2243                 }
2244         }
2245
2246         zero(ev);
2247         ev.events = EPOLLIN;
2248         ev.data.fd = s->stdout_fd;
2249         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2250                 log_error("Failed to add stdout server fd to epoll object: %m");
2251                 return -errno;
2252         }
2253
2254         return 0;
2255 }
2256
2257 static int open_proc_kmsg(Server *s) {
2258         struct epoll_event ev;
2259
2260         assert(s);
2261
2262         if (!s->import_proc_kmsg)
2263                 return 0;
2264
2265
2266         s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2267         if (s->proc_kmsg_fd < 0) {
2268                 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2269                 return 0;
2270         }
2271
2272         zero(ev);
2273         ev.events = EPOLLIN;
2274         ev.data.fd = s->proc_kmsg_fd;
2275         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2276                 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2277                 return -errno;
2278         }
2279
2280         return 0;
2281 }
2282
2283 static int open_signalfd(Server *s) {
2284         sigset_t mask;
2285         struct epoll_event ev;
2286
2287         assert(s);
2288
2289         assert_se(sigemptyset(&mask) == 0);
2290         sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2291         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2292
2293         s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2294         if (s->signal_fd < 0) {
2295                 log_error("signalfd(): %m");
2296                 return -errno;
2297         }
2298
2299         zero(ev);
2300         ev.events = EPOLLIN;
2301         ev.data.fd = s->signal_fd;
2302
2303         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2304                 log_error("epoll_ctl(): %m");
2305                 return -errno;
2306         }
2307
2308         return 0;
2309 }
2310
2311 static int server_parse_proc_cmdline(Server *s) {
2312         char *line, *w, *state;
2313         int r;
2314         size_t l;
2315
2316         if (detect_container(NULL) > 0)
2317                 return 0;
2318
2319         r = read_one_line_file("/proc/cmdline", &line);
2320         if (r < 0) {
2321                 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2322                 return 0;
2323         }
2324
2325         FOREACH_WORD_QUOTED(w, l, line, state) {
2326                 char *word;
2327
2328                 word = strndup(w, l);
2329                 if (!word) {
2330                         r = -ENOMEM;
2331                         goto finish;
2332                 }
2333
2334                 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2335                         r = parse_boolean(word + 35);
2336                         if (r < 0)
2337                                 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2338                         else
2339                                 s->forward_to_syslog = r;
2340                 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2341                         r = parse_boolean(word + 33);
2342                         if (r < 0)
2343                                 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2344                         else
2345                                 s->forward_to_kmsg = r;
2346                 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2347                         r = parse_boolean(word + 36);
2348                         if (r < 0)
2349                                 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2350                         else
2351                                 s->forward_to_console = r;
2352                 }
2353
2354                 free(word);
2355         }
2356
2357         r = 0;
2358
2359 finish:
2360         free(line);
2361         return r;
2362 }
2363
2364 static int server_parse_config_file(Server *s) {
2365         FILE *f;
2366         const char *fn;
2367         int r;
2368
2369         assert(s);
2370
2371         fn = "/etc/systemd/systemd-journald.conf";
2372         f = fopen(fn, "re");
2373         if (!f) {
2374                 if (errno == ENOENT)
2375                         return 0;
2376
2377                 log_warning("Failed to open configuration file %s: %m", fn);
2378                 return -errno;
2379         }
2380
2381         r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2382         if (r < 0)
2383                 log_warning("Failed to parse configuration file: %s", strerror(-r));
2384
2385         fclose(f);
2386
2387         return r;
2388 }
2389
2390 static int server_init(Server *s) {
2391         int n, r, fd;
2392
2393         assert(s);
2394
2395         zero(*s);
2396         s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2397         s->compress = true;
2398
2399         s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2400         s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2401
2402         s->forward_to_syslog = true;
2403         s->import_proc_kmsg = true;
2404
2405         memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2406         memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2407
2408         server_parse_config_file(s);
2409         server_parse_proc_cmdline(s);
2410
2411         s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2412         if (!s->user_journals) {
2413                 log_error("Out of memory.");
2414                 return -ENOMEM;
2415         }
2416
2417         s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2418         if (s->epoll_fd < 0) {
2419                 log_error("Failed to create epoll object: %m");
2420                 return -errno;
2421         }
2422
2423         n = sd_listen_fds(true);
2424         if (n < 0) {
2425                 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2426                 return n;
2427         }
2428
2429         for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2430
2431                 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2432
2433                         if (s->native_fd >= 0) {
2434                                 log_error("Too many native sockets passed.");
2435                                 return -EINVAL;
2436                         }
2437
2438                         s->native_fd = fd;
2439
2440                 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2441
2442                         if (s->stdout_fd >= 0) {
2443                                 log_error("Too many stdout sockets passed.");
2444                                 return -EINVAL;
2445                         }
2446
2447                         s->stdout_fd = fd;
2448
2449                 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2450
2451                         if (s->syslog_fd >= 0) {
2452                                 log_error("Too many /dev/log sockets passed.");
2453                                 return -EINVAL;
2454                         }
2455
2456                         s->syslog_fd = fd;
2457
2458                 } else {
2459                         log_error("Unknown socket passed.");
2460                         return -EINVAL;
2461                 }
2462         }
2463
2464         r = open_syslog_socket(s);
2465         if (r < 0)
2466                 return r;
2467
2468         r = open_native_socket(s);
2469         if (r < 0)
2470                 return r;
2471
2472         r = open_stdout_socket(s);
2473         if (r < 0)
2474                 return r;
2475
2476         r = open_proc_kmsg(s);
2477         if (r < 0)
2478                 return r;
2479
2480         r = system_journal_open(s);
2481         if (r < 0)
2482                 return r;
2483
2484         r = open_signalfd(s);
2485         if (r < 0)
2486                 return r;
2487
2488         s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2489         if (!s->rate_limit)
2490                 return -ENOMEM;
2491
2492         return 0;
2493 }
2494
2495 static void server_done(Server *s) {
2496         JournalFile *f;
2497         assert(s);
2498
2499         while (s->stdout_streams)
2500                 stdout_stream_free(s->stdout_streams);
2501
2502         if (s->system_journal)
2503                 journal_file_close(s->system_journal);
2504
2505         if (s->runtime_journal)
2506                 journal_file_close(s->runtime_journal);
2507
2508         while ((f = hashmap_steal_first(s->user_journals)))
2509                 journal_file_close(f);
2510
2511         hashmap_free(s->user_journals);
2512
2513         if (s->epoll_fd >= 0)
2514                 close_nointr_nofail(s->epoll_fd);
2515
2516         if (s->signal_fd >= 0)
2517                 close_nointr_nofail(s->signal_fd);
2518
2519         if (s->syslog_fd >= 0)
2520                 close_nointr_nofail(s->syslog_fd);
2521
2522         if (s->native_fd >= 0)
2523                 close_nointr_nofail(s->native_fd);
2524
2525         if (s->stdout_fd >= 0)
2526                 close_nointr_nofail(s->stdout_fd);
2527
2528         if (s->proc_kmsg_fd >= 0)
2529                 close_nointr_nofail(s->proc_kmsg_fd);
2530
2531         if (s->rate_limit)
2532                 journal_rate_limit_free(s->rate_limit);
2533
2534         free(s->buffer);
2535 }
2536
2537 int main(int argc, char *argv[]) {
2538         Server server;
2539         int r;
2540
2541         /* if (getppid() != 1) { */
2542         /*         log_error("This program should be invoked by init only."); */
2543         /*         return EXIT_FAILURE; */
2544         /* } */
2545
2546         if (argc > 1) {
2547                 log_error("This program does not take arguments.");
2548                 return EXIT_FAILURE;
2549         }
2550
2551         log_set_target(LOG_TARGET_CONSOLE);
2552         log_parse_environment();
2553         log_open();
2554
2555         umask(0022);
2556
2557         r = server_init(&server);
2558         if (r < 0)
2559                 goto finish;
2560
2561         server_vacuum(&server);
2562         server_flush_to_var(&server);
2563         server_flush_proc_kmsg(&server);
2564
2565         log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2566         driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2567
2568         sd_notify(false,
2569                   "READY=1\n"
2570                   "STATUS=Processing requests...");
2571
2572         for (;;) {
2573                 struct epoll_event event;
2574
2575                 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2576                 if (r < 0) {
2577
2578                         if (errno == EINTR)
2579                                 continue;
2580
2581                         log_error("epoll_wait() failed: %m");
2582                         r = -errno;
2583                         goto finish;
2584                 } else if (r == 0)
2585                         break;
2586
2587                 r = process_event(&server, &event);
2588                 if (r < 0)
2589                         goto finish;
2590                 else if (r == 0)
2591                         break;
2592         }
2593
2594         log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2595         driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2596
2597 finish:
2598         sd_notify(false,
2599                   "STATUS=Shutting down...");
2600
2601         server_done(&server);
2602
2603         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
2604 }