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