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