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