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