chiark / gitweb /
d27cb60ac7e7791b137c4c9a7c44859e544272dd
[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 == -E2BIG || /* hit limit */
613                      r == -EFBIG || /* hit fs limit */
614                      r == -EDQUOT || /* quota hit */
615                      r == -ENOSPC || /* disk full */
616                      r == -EBADMSG || /* corrupted */
617                      r == -ENODATA || /* truncated */
618                      r == -EHOSTDOWN || /* other machine */
619                      r == -EPROTONOSUPPORT) && /* unsupported feature */
620                     !vacuumed) {
621
622                         if (r == -E2BIG)
623                                 log_info("Allocation limit reached, rotating.");
624                         else
625                                 log_warning("Journal file corrupted, rotating.");
626
627                         server_rotate(s);
628                         server_vacuum(s);
629                         vacuumed = true;
630
631                         log_info("Retrying write.");
632                         goto retry;
633                 }
634
635                 if (r < 0)
636                         log_error("Failed to write entry, ignoring: %s", strerror(-r));
637         }
638
639         free(pid);
640         free(uid);
641         free(gid);
642         free(comm);
643         free(exe);
644         free(cmdline);
645         free(source_time);
646         free(boot_id);
647         free(machine_id);
648         free(hostname);
649         free(audit_session);
650         free(audit_loginuid);
651         free(cgroup);
652         free(session);
653         free(owner_uid);
654         free(unit);
655         free(selinux_context);
656 }
657
658 static void driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
659         char mid[11 + 32 + 1];
660         char buffer[16 + LINE_MAX + 1];
661         struct iovec iovec[N_IOVEC_META_FIELDS + 4];
662         int n = 0;
663         va_list ap;
664         struct ucred ucred;
665
666         assert(s);
667         assert(format);
668
669         IOVEC_SET_STRING(iovec[n++], "PRIORITY=5");
670         IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
671
672         memcpy(buffer, "MESSAGE=", 8);
673         va_start(ap, format);
674         vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
675         va_end(ap);
676         char_array_0(buffer);
677         IOVEC_SET_STRING(iovec[n++], buffer);
678
679         snprintf(mid, sizeof(mid), "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(message_id));
680         char_array_0(mid);
681         IOVEC_SET_STRING(iovec[n++], mid);
682
683         zero(ucred);
684         ucred.pid = getpid();
685         ucred.uid = getuid();
686         ucred.gid = getgid();
687
688         dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0);
689 }
690
691 static void dispatch_message(Server *s,
692                              struct iovec *iovec, unsigned n, unsigned m,
693                              struct ucred *ucred,
694                              struct timeval *tv,
695                              const char *label, size_t label_len,
696                              int priority) {
697         int rl;
698         char *path = NULL, *c;
699
700         assert(s);
701         assert(iovec || n == 0);
702
703         if (n == 0)
704                 return;
705
706         if (!ucred)
707                 goto finish;
708
709         path = shortened_cgroup_path(ucred->pid);
710         if (!path)
711                 goto finish;
712
713         /* example: /user/lennart/3/foobar
714          *          /system/dbus.service/foobar
715          *
716          * So let's cut of everything past the third /, since that is
717          * wher user directories start */
718
719         c = strchr(path, '/');
720         if (c) {
721                 c = strchr(c+1, '/');
722                 if (c) {
723                         c = strchr(c+1, '/');
724                         if (c)
725                                 *c = 0;
726                 }
727         }
728
729         rl = journal_rate_limit_test(s->rate_limit, path, priority & LOG_PRIMASK, available_space(s));
730
731         if (rl == 0) {
732                 free(path);
733                 return;
734         }
735
736         /* Write a suppression message if we suppressed something */
737         if (rl > 1)
738                 driver_message(s, SD_MESSAGE_JOURNAL_DROPPED, "Suppressed %u messages from %s", rl - 1, path);
739
740         free(path);
741
742 finish:
743         dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len);
744 }
745
746 static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
747         struct msghdr msghdr;
748         struct cmsghdr *cmsg;
749         union {
750                 struct cmsghdr cmsghdr;
751                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
752         } control;
753         union sockaddr_union sa;
754
755         assert(s);
756         assert(iovec);
757         assert(n_iovec > 0);
758
759         zero(msghdr);
760         msghdr.msg_iov = (struct iovec*) iovec;
761         msghdr.msg_iovlen = n_iovec;
762
763         zero(sa);
764         sa.un.sun_family = AF_UNIX;
765         strncpy(sa.un.sun_path, "/run/systemd/journal/syslog", sizeof(sa.un.sun_path));
766         msghdr.msg_name = &sa;
767         msghdr.msg_namelen = offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path);
768
769         if (ucred) {
770                 zero(control);
771                 msghdr.msg_control = &control;
772                 msghdr.msg_controllen = sizeof(control);
773
774                 cmsg = CMSG_FIRSTHDR(&msghdr);
775                 cmsg->cmsg_level = SOL_SOCKET;
776                 cmsg->cmsg_type = SCM_CREDENTIALS;
777                 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
778                 memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
779                 msghdr.msg_controllen = cmsg->cmsg_len;
780         }
781
782         /* Forward the syslog message we received via /dev/log to
783          * /run/systemd/syslog. Unfortunately we currently can't set
784          * the SO_TIMESTAMP auxiliary data, and hence we don't. */
785
786         if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
787                 return;
788
789         /* The socket is full? I guess the syslog implementation is
790          * too slow, and we shouldn't wait for that... */
791         if (errno == EAGAIN)
792                 return;
793
794         if (ucred && errno == ESRCH) {
795                 struct ucred u;
796
797                 /* Hmm, presumably the sender process vanished
798                  * by now, so let's fix it as good as we
799                  * can, and retry */
800
801                 u = *ucred;
802                 u.pid = getpid();
803                 memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
804
805                 if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
806                         return;
807
808                 if (errno == EAGAIN)
809                         return;
810         }
811
812         log_debug("Failed to forward syslog message: %m");
813 }
814
815 static void forward_syslog_raw(Server *s, const char *buffer, struct ucred *ucred, struct timeval *tv) {
816         struct iovec iovec;
817
818         assert(s);
819         assert(buffer);
820
821         IOVEC_SET_STRING(iovec, buffer);
822         forward_syslog_iovec(s, &iovec, 1, ucred, tv);
823 }
824
825 static void forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
826         struct iovec iovec[5];
827         char header_priority[6], header_time[64], header_pid[16];
828         int n = 0;
829         time_t t;
830         struct tm *tm;
831         char *ident_buf = NULL;
832
833         assert(s);
834         assert(priority >= 0);
835         assert(priority <= 999);
836         assert(message);
837
838         /* First: priority field */
839         snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
840         char_array_0(header_priority);
841         IOVEC_SET_STRING(iovec[n++], header_priority);
842
843         /* Second: timestamp */
844         t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
845         tm = localtime(&t);
846         if (!tm)
847                 return;
848         if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
849                 return;
850         IOVEC_SET_STRING(iovec[n++], header_time);
851
852         /* Third: identifier and PID */
853         if (ucred) {
854                 if (!identifier) {
855                         get_process_comm(ucred->pid, &ident_buf);
856                         identifier = ident_buf;
857                 }
858
859                 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
860                 char_array_0(header_pid);
861
862                 if (identifier)
863                         IOVEC_SET_STRING(iovec[n++], identifier);
864
865                 IOVEC_SET_STRING(iovec[n++], header_pid);
866         } else if (identifier) {
867                 IOVEC_SET_STRING(iovec[n++], identifier);
868                 IOVEC_SET_STRING(iovec[n++], ": ");
869         }
870
871         /* Fourth: message */
872         IOVEC_SET_STRING(iovec[n++], message);
873
874         forward_syslog_iovec(s, iovec, n, ucred, tv);
875
876         free(ident_buf);
877 }
878
879 static int fixup_priority(int priority) {
880
881         if ((priority & LOG_FACMASK) == 0)
882                 return (priority & LOG_PRIMASK) | LOG_USER;
883
884         return priority;
885 }
886
887 static void forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred) {
888         struct iovec iovec[5];
889         char header_priority[6], header_pid[16];
890         int n = 0;
891         char *ident_buf = NULL;
892         int fd;
893
894         assert(s);
895         assert(priority >= 0);
896         assert(priority <= 999);
897         assert(message);
898
899         /* Never allow messages with kernel facility to be written to
900          * kmsg, regardless where the data comes from. */
901         priority = fixup_priority(priority);
902
903         /* First: priority field */
904         snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
905         char_array_0(header_priority);
906         IOVEC_SET_STRING(iovec[n++], header_priority);
907
908         /* Second: identifier and PID */
909         if (ucred) {
910                 if (!identifier) {
911                         get_process_comm(ucred->pid, &ident_buf);
912                         identifier = ident_buf;
913                 }
914
915                 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
916                 char_array_0(header_pid);
917
918                 if (identifier)
919                         IOVEC_SET_STRING(iovec[n++], identifier);
920
921                 IOVEC_SET_STRING(iovec[n++], header_pid);
922         } else if (identifier) {
923                 IOVEC_SET_STRING(iovec[n++], identifier);
924                 IOVEC_SET_STRING(iovec[n++], ": ");
925         }
926
927         /* Fourth: message */
928         IOVEC_SET_STRING(iovec[n++], message);
929         IOVEC_SET_STRING(iovec[n++], "\n");
930
931         fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
932         if (fd < 0) {
933                 log_debug("Failed to open /dev/kmsg for logging: %s", strerror(errno));
934                 goto finish;
935         }
936
937         if (writev(fd, iovec, n) < 0)
938                 log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
939
940         close_nointr_nofail(fd);
941
942 finish:
943         free(ident_buf);
944 }
945
946 static void forward_console(Server *s, const char *identifier, const char *message, struct ucred *ucred) {
947         struct iovec iovec[4];
948         char header_pid[16];
949         int n = 0, fd;
950         char *ident_buf = NULL;
951
952         assert(s);
953         assert(message);
954
955         /* First: identifier and PID */
956         if (ucred) {
957                 if (!identifier) {
958                         get_process_comm(ucred->pid, &ident_buf);
959                         identifier = ident_buf;
960                 }
961
962                 snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
963                 char_array_0(header_pid);
964
965                 if (identifier)
966                         IOVEC_SET_STRING(iovec[n++], identifier);
967
968                 IOVEC_SET_STRING(iovec[n++], header_pid);
969         } else if (identifier) {
970                 IOVEC_SET_STRING(iovec[n++], identifier);
971                 IOVEC_SET_STRING(iovec[n++], ": ");
972         }
973
974         /* Third: message */
975         IOVEC_SET_STRING(iovec[n++], message);
976         IOVEC_SET_STRING(iovec[n++], "\n");
977
978         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
979         if (fd < 0) {
980                 log_debug("Failed to open /dev/console for logging: %s", strerror(errno));
981                 goto finish;
982         }
983
984         if (writev(fd, iovec, n) < 0)
985                 log_debug("Failed to write to /dev/console for logging: %s", strerror(errno));
986
987         close_nointr_nofail(fd);
988
989 finish:
990         free(ident_buf);
991 }
992
993 static void read_identifier(const char **buf, char **identifier, char **pid) {
994         const char *p;
995         char *t;
996         size_t l, e;
997
998         assert(buf);
999         assert(identifier);
1000         assert(pid);
1001
1002         p = *buf;
1003
1004         p += strspn(p, WHITESPACE);
1005         l = strcspn(p, WHITESPACE);
1006
1007         if (l <= 0 ||
1008             p[l-1] != ':')
1009                 return;
1010
1011         e = l;
1012         l--;
1013
1014         if (p[l-1] == ']') {
1015                 size_t k = l-1;
1016
1017                 for (;;) {
1018
1019                         if (p[k] == '[') {
1020                                 t = strndup(p+k+1, l-k-2);
1021                                 if (t)
1022                                         *pid = t;
1023
1024                                 l = k;
1025                                 break;
1026                         }
1027
1028                         if (k == 0)
1029                                 break;
1030
1031                         k--;
1032                 }
1033         }
1034
1035         t = strndup(p, l);
1036         if (t)
1037                 *identifier = t;
1038
1039         *buf = p + e;
1040         *buf += strspn(*buf, WHITESPACE);
1041 }
1042
1043 static void process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) {
1044         char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
1045         struct iovec iovec[N_IOVEC_META_FIELDS + 6];
1046         unsigned n = 0;
1047         int priority = LOG_USER | LOG_INFO;
1048         char *identifier = NULL, *pid = NULL;
1049
1050         assert(s);
1051         assert(buf);
1052
1053         if (s->forward_to_syslog)
1054                 forward_syslog_raw(s, buf, ucred, tv);
1055
1056         parse_syslog_priority((char**) &buf, &priority);
1057         skip_syslog_date((char**) &buf);
1058         read_identifier(&buf, &identifier, &pid);
1059
1060         if (s->forward_to_kmsg)
1061                 forward_kmsg(s, priority, identifier, buf, ucred);
1062
1063         if (s->forward_to_console)
1064                 forward_console(s, identifier, buf, ucred);
1065
1066         IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
1067
1068         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1069                 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1070
1071         if (priority & LOG_FACMASK)
1072                 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1073                         IOVEC_SET_STRING(iovec[n++], syslog_facility);
1074
1075         if (identifier) {
1076                 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1077                 if (syslog_identifier)
1078                         IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1079         }
1080
1081         if (pid) {
1082                 syslog_pid = strappend("SYSLOG_PID=", pid);
1083                 if (syslog_pid)
1084                         IOVEC_SET_STRING(iovec[n++], syslog_pid);
1085         }
1086
1087         message = strappend("MESSAGE=", buf);
1088         if (message)
1089                 IOVEC_SET_STRING(iovec[n++], message);
1090
1091         dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, label, label_len, priority);
1092
1093         free(message);
1094         free(identifier);
1095         free(pid);
1096         free(syslog_priority);
1097         free(syslog_facility);
1098         free(syslog_identifier);
1099 }
1100
1101 static bool valid_user_field(const char *p, size_t l) {
1102         const char *a;
1103
1104         /* We kinda enforce POSIX syntax recommendations for
1105            environment variables here, but make a couple of additional
1106            requirements.
1107
1108            http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1109
1110         /* No empty field names */
1111         if (l <= 0)
1112                 return false;
1113
1114         /* Don't allow names longer than 64 chars */
1115         if (l > 64)
1116                 return false;
1117
1118         /* Variables starting with an underscore are protected */
1119         if (p[0] == '_')
1120                 return false;
1121
1122         /* Don't allow digits as first character */
1123         if (p[0] >= '0' && p[0] <= '9')
1124                 return false;
1125
1126         /* Only allow A-Z0-9 and '_' */
1127         for (a = p; a < p + l; a++)
1128                 if (!((*a >= 'A' && *a <= 'Z') ||
1129                       (*a >= '0' && *a <= '9') ||
1130                       *a == '_'))
1131                         return false;
1132
1133         return true;
1134 }
1135
1136 static void process_native_message(
1137                 Server *s,
1138                 const void *buffer, size_t buffer_size,
1139                 struct ucred *ucred,
1140                 struct timeval *tv,
1141                 const char *label, size_t label_len) {
1142
1143         struct iovec *iovec = NULL;
1144         unsigned n = 0, m = 0, j, tn = (unsigned) -1;
1145         const char *p;
1146         size_t remaining;
1147         int priority = LOG_INFO;
1148         char *identifier = NULL, *message = NULL;
1149
1150         assert(s);
1151         assert(buffer || n == 0);
1152
1153         p = buffer;
1154         remaining = buffer_size;
1155
1156         while (remaining > 0) {
1157                 const char *e, *q;
1158
1159                 e = memchr(p, '\n', remaining);
1160
1161                 if (!e) {
1162                         /* Trailing noise, let's ignore it, and flush what we collected */
1163                         log_debug("Received message with trailing noise, ignoring.");
1164                         break;
1165                 }
1166
1167                 if (e == p) {
1168                         /* Entry separator */
1169                         dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1170                         n = 0;
1171                         priority = LOG_INFO;
1172
1173                         p++;
1174                         remaining--;
1175                         continue;
1176                 }
1177
1178                 if (*p == '.' || *p == '#') {
1179                         /* Ignore control commands for now, and
1180                          * comments too. */
1181                         remaining -= (e - p) + 1;
1182                         p = e + 1;
1183                         continue;
1184                 }
1185
1186                 /* A property follows */
1187
1188                 if (n+N_IOVEC_META_FIELDS >= m) {
1189                         struct iovec *c;
1190                         unsigned u;
1191
1192                         u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U);
1193                         c = realloc(iovec, u * sizeof(struct iovec));
1194                         if (!c) {
1195                                 log_error("Out of memory");
1196                                 break;
1197                         }
1198
1199                         iovec = c;
1200                         m = u;
1201                 }
1202
1203                 q = memchr(p, '=', e - p);
1204                 if (q) {
1205                         if (valid_user_field(p, q - p)) {
1206                                 size_t l;
1207
1208                                 l = e - p;
1209
1210                                 /* If the field name starts with an
1211                                  * underscore, skip the variable,
1212                                  * since that indidates a trusted
1213                                  * field */
1214                                 iovec[n].iov_base = (char*) p;
1215                                 iovec[n].iov_len = l;
1216                                 n++;
1217
1218                                 /* We need to determine the priority
1219                                  * of this entry for the rate limiting
1220                                  * logic */
1221                                 if (l == 10 &&
1222                                     memcmp(p, "PRIORITY=", 9) == 0 &&
1223                                     p[9] >= '0' && p[9] <= '9')
1224                                         priority = (priority & LOG_FACMASK) | (p[9] - '0');
1225
1226                                 else if (l == 17 &&
1227                                          memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1228                                          p[16] >= '0' && p[16] <= '9')
1229                                         priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
1230
1231                                 else if (l == 18 &&
1232                                          memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
1233                                          p[16] >= '0' && p[16] <= '9' &&
1234                                          p[17] >= '0' && p[17] <= '9')
1235                                         priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
1236
1237                                 else if (l >= 12 &&
1238                                          memcmp(p, "SYSLOG_IDENTIFIER=", 11) == 0) {
1239                                         char *t;
1240
1241                                         t = strndup(p + 11, l - 11);
1242                                         if (t) {
1243                                                 free(identifier);
1244                                                 identifier = t;
1245                                         }
1246                                 } else if (l >= 8 &&
1247                                            memcmp(p, "MESSAGE=", 8) == 0) {
1248                                         char *t;
1249
1250                                         t = strndup(p + 8, l - 8);
1251                                         if (t) {
1252                                                 free(message);
1253                                                 message = t;
1254                                         }
1255                                 }
1256                         }
1257
1258                         remaining -= (e - p) + 1;
1259                         p = e + 1;
1260                         continue;
1261                 } else {
1262                         uint64_t l;
1263                         char *k;
1264
1265                         if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
1266                                 log_debug("Failed to parse message, ignoring.");
1267                                 break;
1268                         }
1269
1270                         memcpy(&l, e + 1, sizeof(uint64_t));
1271                         l = le64toh(l);
1272
1273                         if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
1274                             e[1+sizeof(uint64_t)+l] != '\n') {
1275                                 log_debug("Failed to parse message, ignoring.");
1276                                 break;
1277                         }
1278
1279                         k = malloc((e - p) + 1 + l);
1280                         if (!k) {
1281                                 log_error("Out of memory");
1282                                 break;
1283                         }
1284
1285                         memcpy(k, p, e - p);
1286                         k[e - p] = '=';
1287                         memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
1288
1289                         if (valid_user_field(p, e - p)) {
1290                                 iovec[n].iov_base = k;
1291                                 iovec[n].iov_len = (e - p) + 1 + l;
1292                                 n++;
1293                         } else
1294                                 free(k);
1295
1296                         remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
1297                         p = e + 1 + sizeof(uint64_t) + l + 1;
1298                 }
1299         }
1300
1301         if (n <= 0)
1302                 goto finish;
1303
1304         tn = n++;
1305         IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
1306
1307         if (message) {
1308                 if (s->forward_to_syslog)
1309                         forward_syslog(s, priority, identifier, message, ucred, tv);
1310
1311                 if (s->forward_to_kmsg)
1312                         forward_kmsg(s, priority, identifier, message, ucred);
1313
1314                 if (s->forward_to_console)
1315                         forward_console(s, identifier, message, ucred);
1316         }
1317
1318         dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, priority);
1319
1320 finish:
1321         for (j = 0; j < n; j++)  {
1322                 if (j == tn)
1323                         continue;
1324
1325                 if (iovec[j].iov_base < buffer ||
1326                     (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
1327                         free(iovec[j].iov_base);
1328         }
1329
1330         free(iovec);
1331         free(identifier);
1332         free(message);
1333 }
1334
1335 static void process_native_file(
1336                 Server *s,
1337                 int fd,
1338                 struct ucred *ucred,
1339                 struct timeval *tv,
1340                 const char *label, size_t label_len) {
1341
1342         struct stat st;
1343         void *p;
1344         ssize_t n;
1345
1346         assert(s);
1347         assert(fd >= 0);
1348
1349         /* Data is in the passed file, since it didn't fit in a
1350          * datagram. We can't map the file here, since clients might
1351          * then truncate it and trigger a SIGBUS for us. So let's
1352          * stupidly read it */
1353
1354         if (fstat(fd, &st) < 0) {
1355                 log_error("Failed to stat passed file, ignoring: %m");
1356                 return;
1357         }
1358
1359         if (!S_ISREG(st.st_mode)) {
1360                 log_error("File passed is not regular. Ignoring.");
1361                 return;
1362         }
1363
1364         if (st.st_size <= 0)
1365                 return;
1366
1367         if (st.st_size > ENTRY_SIZE_MAX) {
1368                 log_error("File passed too large. Ignoring.");
1369                 return;
1370         }
1371
1372         p = malloc(st.st_size);
1373         if (!p) {
1374                 log_error("Out of memory");
1375                 return;
1376         }
1377
1378         n = pread(fd, p, st.st_size, 0);
1379         if (n < 0)
1380                 log_error("Failed to read file, ignoring: %s", strerror(-n));
1381         else if (n > 0)
1382                 process_native_message(s, p, n, ucred, tv, label, label_len);
1383
1384         free(p);
1385 }
1386
1387 static int stdout_stream_log(StdoutStream *s, const char *p) {
1388         struct iovec iovec[N_IOVEC_META_FIELDS + 5];
1389         char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
1390         unsigned n = 0;
1391         int priority;
1392         char *label = NULL;
1393         size_t label_len = 0;
1394
1395         assert(s);
1396         assert(p);
1397
1398         if (isempty(p))
1399                 return 0;
1400
1401         priority = s->priority;
1402
1403         if (s->level_prefix)
1404                 parse_syslog_priority((char**) &p, &priority);
1405
1406         if (s->forward_to_syslog || s->server->forward_to_syslog)
1407                 forward_syslog(s->server, fixup_priority(priority), s->identifier, p, &s->ucred, NULL);
1408
1409         if (s->forward_to_kmsg || s->server->forward_to_kmsg)
1410                 forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
1411
1412         if (s->forward_to_console || s->server->forward_to_console)
1413                 forward_console(s->server, s->identifier, p, &s->ucred);
1414
1415         IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
1416
1417         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1418                 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1419
1420         if (priority & LOG_FACMASK)
1421                 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1422                         IOVEC_SET_STRING(iovec[n++], syslog_facility);
1423
1424         if (s->identifier) {
1425                 syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
1426                 if (syslog_identifier)
1427                         IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1428         }
1429
1430         message = strappend("MESSAGE=", p);
1431         if (message)
1432                 IOVEC_SET_STRING(iovec[n++], message);
1433
1434 #ifdef HAVE_SELINUX
1435         if (s->security_context) {
1436                 label = (char*) s->security_context;
1437                 label_len = strlen((char*) s->security_context);
1438         }
1439 #endif
1440
1441         dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, priority);
1442
1443         free(message);
1444         free(syslog_priority);
1445         free(syslog_facility);
1446         free(syslog_identifier);
1447
1448         return 0;
1449 }
1450
1451 static int stdout_stream_line(StdoutStream *s, char *p) {
1452         int r;
1453
1454         assert(s);
1455         assert(p);
1456
1457         p = strstrip(p);
1458
1459         switch (s->state) {
1460
1461         case STDOUT_STREAM_IDENTIFIER:
1462                 if (isempty(p))
1463                         s->identifier = NULL;
1464                 else  {
1465                         s->identifier = strdup(p);
1466                         if (!s->identifier) {
1467                                 log_error("Out of memory");
1468                                 return -ENOMEM;
1469                         }
1470                 }
1471
1472                 s->state = STDOUT_STREAM_PRIORITY;
1473                 return 0;
1474
1475         case STDOUT_STREAM_PRIORITY:
1476                 r = safe_atoi(p, &s->priority);
1477                 if (r < 0 || s->priority <= 0 || s->priority >= 999) {
1478                         log_warning("Failed to parse log priority line.");
1479                         return -EINVAL;
1480                 }
1481
1482                 s->state = STDOUT_STREAM_LEVEL_PREFIX;
1483                 return 0;
1484
1485         case STDOUT_STREAM_LEVEL_PREFIX:
1486                 r = parse_boolean(p);
1487                 if (r < 0) {
1488                         log_warning("Failed to parse level prefix line.");
1489                         return -EINVAL;
1490                 }
1491
1492                 s->level_prefix = !!r;
1493                 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
1494                 return 0;
1495
1496         case STDOUT_STREAM_FORWARD_TO_SYSLOG:
1497                 r = parse_boolean(p);
1498                 if (r < 0) {
1499                         log_warning("Failed to parse forward to syslog line.");
1500                         return -EINVAL;
1501                 }
1502
1503                 s->forward_to_syslog = !!r;
1504                 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
1505                 return 0;
1506
1507         case STDOUT_STREAM_FORWARD_TO_KMSG:
1508                 r = parse_boolean(p);
1509                 if (r < 0) {
1510                         log_warning("Failed to parse copy to kmsg line.");
1511                         return -EINVAL;
1512                 }
1513
1514                 s->forward_to_kmsg = !!r;
1515                 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
1516                 return 0;
1517
1518         case STDOUT_STREAM_FORWARD_TO_CONSOLE:
1519                 r = parse_boolean(p);
1520                 if (r < 0) {
1521                         log_warning("Failed to parse copy to console line.");
1522                         return -EINVAL;
1523                 }
1524
1525                 s->forward_to_console = !!r;
1526                 s->state = STDOUT_STREAM_RUNNING;
1527                 return 0;
1528
1529         case STDOUT_STREAM_RUNNING:
1530                 return stdout_stream_log(s, p);
1531         }
1532
1533         assert_not_reached("Unknown stream state");
1534 }
1535
1536 static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
1537         char *p;
1538         size_t remaining;
1539         int r;
1540
1541         assert(s);
1542
1543         p = s->buffer;
1544         remaining = s->length;
1545         for (;;) {
1546                 char *end;
1547                 size_t skip;
1548
1549                 end = memchr(p, '\n', remaining);
1550                 if (end)
1551                         skip = end - p + 1;
1552                 else if (remaining >= sizeof(s->buffer) - 1) {
1553                         end = p + sizeof(s->buffer) - 1;
1554                         skip = remaining;
1555                 } else
1556                         break;
1557
1558                 *end = 0;
1559
1560                 r = stdout_stream_line(s, p);
1561                 if (r < 0)
1562                         return r;
1563
1564                 remaining -= skip;
1565                 p += skip;
1566         }
1567
1568         if (force_flush && remaining > 0) {
1569                 p[remaining] = 0;
1570                 r = stdout_stream_line(s, p);
1571                 if (r < 0)
1572                         return r;
1573
1574                 p += remaining;
1575                 remaining = 0;
1576         }
1577
1578         if (p > s->buffer) {
1579                 memmove(s->buffer, p, remaining);
1580                 s->length = remaining;
1581         }
1582
1583         return 0;
1584 }
1585
1586 static int stdout_stream_process(StdoutStream *s) {
1587         ssize_t l;
1588         int r;
1589
1590         assert(s);
1591
1592         l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
1593         if (l < 0) {
1594
1595                 if (errno == EAGAIN)
1596                         return 0;
1597
1598                 log_warning("Failed to read from stream: %m");
1599                 return -errno;
1600         }
1601
1602         if (l == 0) {
1603                 r = stdout_stream_scan(s, true);
1604                 if (r < 0)
1605                         return r;
1606
1607                 return 0;
1608         }
1609
1610         s->length += l;
1611         r = stdout_stream_scan(s, false);
1612         if (r < 0)
1613                 return r;
1614
1615         return 1;
1616
1617 }
1618
1619 static void stdout_stream_free(StdoutStream *s) {
1620         assert(s);
1621
1622         if (s->server) {
1623                 assert(s->server->n_stdout_streams > 0);
1624                 s->server->n_stdout_streams --;
1625                 LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
1626         }
1627
1628         if (s->fd >= 0) {
1629                 if (s->server)
1630                         epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
1631
1632                 close_nointr_nofail(s->fd);
1633         }
1634
1635 #ifdef HAVE_SELINUX
1636         if (s->security_context)
1637                 freecon(s->security_context);
1638 #endif
1639
1640         free(s->identifier);
1641         free(s);
1642 }
1643
1644 static int stdout_stream_new(Server *s) {
1645         StdoutStream *stream;
1646         int fd, r;
1647         socklen_t len;
1648         struct epoll_event ev;
1649
1650         assert(s);
1651
1652         fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1653         if (fd < 0) {
1654                 if (errno == EAGAIN)
1655                         return 0;
1656
1657                 log_error("Failed to accept stdout connection: %m");
1658                 return -errno;
1659         }
1660
1661         if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
1662                 log_warning("Too many stdout streams, refusing connection.");
1663                 close_nointr_nofail(fd);
1664                 return 0;
1665         }
1666
1667         stream = new0(StdoutStream, 1);
1668         if (!stream) {
1669                 log_error("Out of memory.");
1670                 close_nointr_nofail(fd);
1671                 return -ENOMEM;
1672         }
1673
1674         stream->fd = fd;
1675
1676         len = sizeof(stream->ucred);
1677         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
1678                 log_error("Failed to determine peer credentials: %m");
1679                 r = -errno;
1680                 goto fail;
1681         }
1682
1683 #ifdef HAVE_SELINUX
1684         if (getpeercon(fd, &stream->security_context) < 0)
1685                 log_error("Failed to determine peer security context.");
1686 #endif
1687
1688         if (shutdown(fd, SHUT_WR) < 0) {
1689                 log_error("Failed to shutdown writing side of socket: %m");
1690                 r = -errno;
1691                 goto fail;
1692         }
1693
1694         zero(ev);
1695         ev.data.ptr = stream;
1696         ev.events = EPOLLIN;
1697         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
1698                 log_error("Failed to add stream to event loop: %m");
1699                 r = -errno;
1700                 goto fail;
1701         }
1702
1703         stream->server = s;
1704         LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
1705         s->n_stdout_streams ++;
1706
1707         return 0;
1708
1709 fail:
1710         stdout_stream_free(stream);
1711         return r;
1712 }
1713
1714 static int parse_kernel_timestamp(char **_p, usec_t *t) {
1715         usec_t r;
1716         int k, i;
1717         char *p;
1718
1719         assert(_p);
1720         assert(*_p);
1721         assert(t);
1722
1723         p = *_p;
1724
1725         if (strlen(p) < 14 || p[0] != '[' || p[13] != ']' || p[6] != '.')
1726                 return 0;
1727
1728         r = 0;
1729
1730         for (i = 1; i <= 5; i++) {
1731                 r *= 10;
1732
1733                 if (p[i] == ' ')
1734                         continue;
1735
1736                 k = undecchar(p[i]);
1737                 if (k < 0)
1738                         return 0;
1739
1740                 r += k;
1741         }
1742
1743         for (i = 7; i <= 12; i++) {
1744                 r *= 10;
1745
1746                 k = undecchar(p[i]);
1747                 if (k < 0)
1748                         return 0;
1749
1750                 r += k;
1751         }
1752
1753         *t = r;
1754         *_p += 14;
1755         *_p += strspn(*_p, WHITESPACE);
1756
1757         return 1;
1758 }
1759
1760 static void proc_kmsg_line(Server *s, const char *p) {
1761         struct iovec iovec[N_IOVEC_META_FIELDS + 7];
1762         char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
1763         int priority = LOG_KERN | LOG_INFO;
1764         unsigned n = 0;
1765         usec_t usec;
1766         char *identifier = NULL, *pid = NULL;
1767
1768         assert(s);
1769         assert(p);
1770
1771         if (isempty(p))
1772                 return;
1773
1774         parse_syslog_priority((char **) &p, &priority);
1775
1776         if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
1777                 return;
1778
1779         if (parse_kernel_timestamp((char **) &p, &usec) > 0) {
1780                 if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu",
1781                              (unsigned long long) usec) >= 0)
1782                         IOVEC_SET_STRING(iovec[n++], source_time);
1783         }
1784
1785         IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
1786
1787         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
1788                 IOVEC_SET_STRING(iovec[n++], syslog_priority);
1789
1790         if ((priority & LOG_FACMASK) == LOG_KERN) {
1791
1792                 if (s->forward_to_syslog)
1793                         forward_syslog(s, priority, "kernel", p, NULL, NULL);
1794
1795                 IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
1796         } else {
1797                 read_identifier(&p, &identifier, &pid);
1798
1799                 if (s->forward_to_syslog)
1800                         forward_syslog(s, priority, identifier, p, NULL, NULL);
1801
1802                 if (identifier) {
1803                         syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
1804                         if (syslog_identifier)
1805                                 IOVEC_SET_STRING(iovec[n++], syslog_identifier);
1806                 }
1807
1808                 if (pid) {
1809                         syslog_pid = strappend("SYSLOG_PID=", pid);
1810                         if (syslog_pid)
1811                                 IOVEC_SET_STRING(iovec[n++], syslog_pid);
1812                 }
1813
1814                 if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
1815                         IOVEC_SET_STRING(iovec[n++], syslog_facility);
1816         }
1817
1818         message = strappend("MESSAGE=", p);
1819         if (message)
1820                 IOVEC_SET_STRING(iovec[n++], message);
1821
1822         dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, priority);
1823
1824         free(message);
1825         free(syslog_priority);
1826         free(syslog_identifier);
1827         free(syslog_pid);
1828         free(syslog_facility);
1829         free(source_time);
1830         free(identifier);
1831         free(pid);
1832 }
1833
1834 static void proc_kmsg_scan(Server *s) {
1835         char *p;
1836         size_t remaining;
1837
1838         assert(s);
1839
1840         p = s->proc_kmsg_buffer;
1841         remaining = s->proc_kmsg_length;
1842         for (;;) {
1843                 char *end;
1844                 size_t skip;
1845
1846                 end = memchr(p, '\n', remaining);
1847                 if (end)
1848                         skip = end - p + 1;
1849                 else if (remaining >= sizeof(s->proc_kmsg_buffer) - 1) {
1850                         end = p + sizeof(s->proc_kmsg_buffer) - 1;
1851                         skip = remaining;
1852                 } else
1853                         break;
1854
1855                 *end = 0;
1856
1857                 proc_kmsg_line(s, p);
1858
1859                 remaining -= skip;
1860                 p += skip;
1861         }
1862
1863         if (p > s->proc_kmsg_buffer) {
1864                 memmove(s->proc_kmsg_buffer, p, remaining);
1865                 s->proc_kmsg_length = remaining;
1866         }
1867 }
1868
1869 static int system_journal_open(Server *s) {
1870         int r;
1871         char *fn;
1872         sd_id128_t machine;
1873         char ids[33];
1874
1875         r = sd_id128_get_machine(&machine);
1876         if (r < 0)
1877                 return r;
1878
1879         sd_id128_to_string(machine, ids);
1880
1881         if (!s->system_journal) {
1882
1883                 /* First try to create the machine path, but not the prefix */
1884                 fn = strappend("/var/log/journal/", ids);
1885                 if (!fn)
1886                         return -ENOMEM;
1887                 (void) mkdir(fn, 0755);
1888                 free(fn);
1889
1890                 /* The create the system journal file */
1891                 fn = join("/var/log/journal/", ids, "/system.journal", NULL);
1892                 if (!fn)
1893                         return -ENOMEM;
1894
1895                 r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->system_journal);
1896                 free(fn);
1897
1898                 if (r >= 0) {
1899                         journal_default_metrics(&s->system_metrics, s->system_journal->fd);
1900
1901                         s->system_journal->metrics = s->system_metrics;
1902                         s->system_journal->compress = s->compress;
1903
1904                         server_fix_perms(s, s->system_journal, 0);
1905                 } else if (r < 0) {
1906
1907                         if (r != -ENOENT && r != -EROFS)
1908                                 log_warning("Failed to open system journal: %s", strerror(-r));
1909
1910                         r = 0;
1911                 }
1912         }
1913
1914         if (!s->runtime_journal) {
1915
1916                 fn = join("/run/log/journal/", ids, "/system.journal", NULL);
1917                 if (!fn)
1918                         return -ENOMEM;
1919
1920                 if (s->system_journal) {
1921
1922                         /* Try to open the runtime journal, but only
1923                          * if it already exists, so that we can flush
1924                          * it into the system journal */
1925
1926                         r = journal_file_open(fn, O_RDWR, 0640, NULL, &s->runtime_journal);
1927                         free(fn);
1928
1929                         if (r < 0) {
1930                                 if (r != -ENOENT)
1931                                         log_warning("Failed to open runtime journal: %s", strerror(-r));
1932
1933                                 r = 0;
1934                         }
1935
1936                 } else {
1937
1938                         /* OK, we really need the runtime journal, so create
1939                          * it if necessary. */
1940
1941                         (void) mkdir_parents(fn, 0755);
1942                         r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, NULL, &s->runtime_journal);
1943                         free(fn);
1944
1945                         if (r < 0) {
1946                                 log_error("Failed to open runtime journal: %s", strerror(-r));
1947                                 return r;
1948                         }
1949                 }
1950
1951                 if (s->runtime_journal) {
1952                         journal_default_metrics(&s->runtime_metrics, s->runtime_journal->fd);
1953
1954                         s->runtime_journal->metrics = s->runtime_metrics;
1955                         s->runtime_journal->compress = s->compress;
1956
1957                         server_fix_perms(s, s->runtime_journal, 0);
1958                 }
1959         }
1960
1961         return r;
1962 }
1963
1964 static int server_flush_to_var(Server *s) {
1965         char path[] = "/run/log/journal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1966         Object *o = NULL;
1967         int r;
1968         sd_id128_t machine;
1969         sd_journal *j;
1970         usec_t ts;
1971
1972         assert(s);
1973
1974         if (!s->runtime_journal)
1975                 return 0;
1976
1977         ts = now(CLOCK_MONOTONIC);
1978         if (s->var_available_timestamp + RECHECK_VAR_AVAILABLE_USEC > ts)
1979                 return 0;
1980
1981         s->var_available_timestamp = ts;
1982
1983         system_journal_open(s);
1984
1985         if (!s->system_journal)
1986                 return 0;
1987
1988         log_info("Flushing to /var...");
1989
1990         r = sd_id128_get_machine(&machine);
1991         if (r < 0) {
1992                 log_error("Failed to get machine id: %s", strerror(-r));
1993                 return r;
1994         }
1995
1996         r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1997         if (r < 0) {
1998                 log_error("Failed to read runtime journal: %s", strerror(-r));
1999                 return r;
2000         }
2001
2002         SD_JOURNAL_FOREACH(j) {
2003                 JournalFile *f;
2004
2005                 f = j->current_file;
2006                 assert(f && f->current_offset > 0);
2007
2008                 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2009                 if (r < 0) {
2010                         log_error("Can't read entry: %s", strerror(-r));
2011                         goto finish;
2012                 }
2013
2014                 r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2015                 if (r == -E2BIG) {
2016                         log_info("Allocation limit reached.");
2017
2018                         journal_file_post_change(s->system_journal);
2019                         server_rotate(s);
2020                         server_vacuum(s);
2021
2022                         r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
2023                 }
2024
2025                 if (r < 0) {
2026                         log_error("Can't write entry: %s", strerror(-r));
2027                         goto finish;
2028                 }
2029         }
2030
2031 finish:
2032         journal_file_post_change(s->system_journal);
2033
2034         journal_file_close(s->runtime_journal);
2035         s->runtime_journal = NULL;
2036
2037         if (r >= 0) {
2038                 sd_id128_to_string(machine, path + 17);
2039                 rm_rf(path, false, true, false);
2040         }
2041
2042         return r;
2043 }
2044
2045 static int server_read_proc_kmsg(Server *s) {
2046         ssize_t l;
2047         assert(s);
2048         assert(s->proc_kmsg_fd >= 0);
2049
2050         l = read(s->proc_kmsg_fd, s->proc_kmsg_buffer + s->proc_kmsg_length, sizeof(s->proc_kmsg_buffer) - 1 - s->proc_kmsg_length);
2051         if (l < 0) {
2052
2053                 if (errno == EAGAIN || errno == EINTR)
2054                         return 0;
2055
2056                 log_error("Failed to read from kernel: %m");
2057                 return -errno;
2058         }
2059
2060         s->proc_kmsg_length += l;
2061
2062         proc_kmsg_scan(s);
2063         return 1;
2064 }
2065
2066 static int server_flush_proc_kmsg(Server *s) {
2067         int r;
2068
2069         assert(s);
2070
2071         if (s->proc_kmsg_fd < 0)
2072                 return 0;
2073
2074         log_info("Flushing /proc/kmsg...");
2075
2076         for (;;) {
2077                 r = server_read_proc_kmsg(s);
2078                 if (r < 0)
2079                         return r;
2080
2081                 if (r == 0)
2082                         break;
2083         }
2084
2085         return 0;
2086 }
2087
2088 static int process_event(Server *s, struct epoll_event *ev) {
2089         assert(s);
2090
2091         if (ev->data.fd == s->signal_fd) {
2092                 struct signalfd_siginfo sfsi;
2093                 ssize_t n;
2094
2095                 if (ev->events != EPOLLIN) {
2096                         log_info("Got invalid event from epoll.");
2097                         return -EIO;
2098                 }
2099
2100                 n = read(s->signal_fd, &sfsi, sizeof(sfsi));
2101                 if (n != sizeof(sfsi)) {
2102
2103                         if (n >= 0)
2104                                 return -EIO;
2105
2106                         if (errno == EINTR || errno == EAGAIN)
2107                                 return 1;
2108
2109                         return -errno;
2110                 }
2111
2112                 if (sfsi.ssi_signo == SIGUSR1) {
2113                         server_flush_to_var(s);
2114                         return 0;
2115                 }
2116
2117                 log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
2118                 return 0;
2119
2120         } else if (ev->data.fd == s->proc_kmsg_fd) {
2121                 int r;
2122
2123                 if (ev->events != EPOLLIN) {
2124                         log_info("Got invalid event from epoll.");
2125                         return -EIO;
2126                 }
2127
2128                 r = server_read_proc_kmsg(s);
2129                 if (r < 0)
2130                         return r;
2131
2132                 return 1;
2133
2134         } else if (ev->data.fd == s->native_fd ||
2135                    ev->data.fd == s->syslog_fd) {
2136
2137                 if (ev->events != EPOLLIN) {
2138                         log_info("Got invalid event from epoll.");
2139                         return -EIO;
2140                 }
2141
2142                 for (;;) {
2143                         struct msghdr msghdr;
2144                         struct iovec iovec;
2145                         struct ucred *ucred = NULL;
2146                         struct timeval *tv = NULL;
2147                         struct cmsghdr *cmsg;
2148                         char *label = NULL;
2149                         size_t label_len = 0;
2150                         union {
2151                                 struct cmsghdr cmsghdr;
2152                                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
2153                                             CMSG_SPACE(sizeof(struct timeval)) +
2154                                             CMSG_SPACE(sizeof(int)) +
2155                                             CMSG_SPACE(PAGE_SIZE)]; /* selinux label */
2156                         } control;
2157                         ssize_t n;
2158                         int v;
2159                         int *fds = NULL;
2160                         unsigned n_fds = 0;
2161
2162                         if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
2163                                 log_error("SIOCINQ failed: %m");
2164                                 return -errno;
2165                         }
2166
2167                         if (s->buffer_size < (size_t) v) {
2168                                 void *b;
2169                                 size_t l;
2170
2171                                 l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
2172                                 b = realloc(s->buffer, l+1);
2173
2174                                 if (!b) {
2175                                         log_error("Couldn't increase buffer.");
2176                                         return -ENOMEM;
2177                                 }
2178
2179                                 s->buffer_size = l;
2180                                 s->buffer = b;
2181                         }
2182
2183                         zero(iovec);
2184                         iovec.iov_base = s->buffer;
2185                         iovec.iov_len = s->buffer_size;
2186
2187                         zero(control);
2188                         zero(msghdr);
2189                         msghdr.msg_iov = &iovec;
2190                         msghdr.msg_iovlen = 1;
2191                         msghdr.msg_control = &control;
2192                         msghdr.msg_controllen = sizeof(control);
2193
2194                         n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2195                         if (n < 0) {
2196
2197                                 if (errno == EINTR || errno == EAGAIN)
2198                                         return 1;
2199
2200                                 log_error("recvmsg() failed: %m");
2201                                 return -errno;
2202                         }
2203
2204                         for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
2205
2206                                 if (cmsg->cmsg_level == SOL_SOCKET &&
2207                                     cmsg->cmsg_type == SCM_CREDENTIALS &&
2208                                     cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
2209                                         ucred = (struct ucred*) CMSG_DATA(cmsg);
2210                                 else if (cmsg->cmsg_level == SOL_SOCKET &&
2211                                          cmsg->cmsg_type == SCM_SECURITY) {
2212                                         label = (char*) CMSG_DATA(cmsg);
2213                                         label_len = cmsg->cmsg_len - CMSG_LEN(0);
2214                                 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2215                                          cmsg->cmsg_type == SO_TIMESTAMP &&
2216                                          cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
2217                                         tv = (struct timeval*) CMSG_DATA(cmsg);
2218                                 else if (cmsg->cmsg_level == SOL_SOCKET &&
2219                                          cmsg->cmsg_type == SCM_RIGHTS) {
2220                                         fds = (int*) CMSG_DATA(cmsg);
2221                                         n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
2222                                 }
2223                         }
2224
2225                         if (ev->data.fd == s->syslog_fd) {
2226                                 char *e;
2227
2228                                 if (n > 0 && n_fds == 0) {
2229                                         e = memchr(s->buffer, '\n', n);
2230                                         if (e)
2231                                                 *e = 0;
2232                                         else
2233                                                 s->buffer[n] = 0;
2234
2235                                         process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
2236                                 } else if (n_fds > 0)
2237                                         log_warning("Got file descriptors via syslog socket. Ignoring.");
2238
2239                         } else {
2240                                 if (n > 0 && n_fds == 0)
2241                                         process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
2242                                 else if (n == 0 && n_fds == 1)
2243                                         process_native_file(s, fds[0], ucred, tv, label, label_len);
2244                                 else if (n_fds > 0)
2245                                         log_warning("Got too many file descriptors via native socket. Ignoring.");
2246                         }
2247
2248                         close_many(fds, n_fds);
2249                 }
2250
2251                 return 1;
2252
2253         } else if (ev->data.fd == s->stdout_fd) {
2254
2255                 if (ev->events != EPOLLIN) {
2256                         log_info("Got invalid event from epoll.");
2257                         return -EIO;
2258                 }
2259
2260                 stdout_stream_new(s);
2261                 return 1;
2262
2263         } else {
2264                 StdoutStream *stream;
2265
2266                 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
2267                         log_info("Got invalid event from epoll.");
2268                         return -EIO;
2269                 }
2270
2271                 /* If it is none of the well-known fds, it must be an
2272                  * stdout stream fd. Note that this is a bit ugly here
2273                  * (since we rely that none of the well-known fds
2274                  * could be interpreted as pointer), but nonetheless
2275                  * safe, since the well-known fds would never get an
2276                  * fd > 4096, i.e. beyond the first memory page */
2277
2278                 stream = ev->data.ptr;
2279
2280                 if (stdout_stream_process(stream) <= 0)
2281                         stdout_stream_free(stream);
2282
2283                 return 1;
2284         }
2285
2286         log_error("Unknown event.");
2287         return 0;
2288 }
2289
2290 static int open_syslog_socket(Server *s) {
2291         union sockaddr_union sa;
2292         int one, r;
2293         struct epoll_event ev;
2294
2295         assert(s);
2296
2297         if (s->syslog_fd < 0) {
2298
2299                 s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2300                 if (s->syslog_fd < 0) {
2301                         log_error("socket() failed: %m");
2302                         return -errno;
2303                 }
2304
2305                 zero(sa);
2306                 sa.un.sun_family = AF_UNIX;
2307                 strncpy(sa.un.sun_path, "/dev/log", sizeof(sa.un.sun_path));
2308
2309                 unlink(sa.un.sun_path);
2310
2311                 r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2312                 if (r < 0) {
2313                         log_error("bind() failed: %m");
2314                         return -errno;
2315                 }
2316
2317                 chmod(sa.un.sun_path, 0666);
2318         } else
2319                 fd_nonblock(s->syslog_fd, 1);
2320
2321         one = 1;
2322         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2323         if (r < 0) {
2324                 log_error("SO_PASSCRED failed: %m");
2325                 return -errno;
2326         }
2327
2328 #ifdef HAVE_SELINUX
2329         one = 1;
2330         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2331         if (r < 0)
2332                 log_warning("SO_PASSSEC failed: %m");
2333 #endif
2334
2335         one = 1;
2336         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2337         if (r < 0) {
2338                 log_error("SO_TIMESTAMP failed: %m");
2339                 return -errno;
2340         }
2341
2342         zero(ev);
2343         ev.events = EPOLLIN;
2344         ev.data.fd = s->syslog_fd;
2345         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
2346                 log_error("Failed to add syslog server fd to epoll object: %m");
2347                 return -errno;
2348         }
2349
2350         return 0;
2351 }
2352
2353 static int open_native_socket(Server*s) {
2354         union sockaddr_union sa;
2355         int one, r;
2356         struct epoll_event ev;
2357
2358         assert(s);
2359
2360         if (s->native_fd < 0) {
2361
2362                 s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2363                 if (s->native_fd < 0) {
2364                         log_error("socket() failed: %m");
2365                         return -errno;
2366                 }
2367
2368                 zero(sa);
2369                 sa.un.sun_family = AF_UNIX;
2370                 strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
2371
2372                 unlink(sa.un.sun_path);
2373
2374                 r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2375                 if (r < 0) {
2376                         log_error("bind() failed: %m");
2377                         return -errno;
2378                 }
2379
2380                 chmod(sa.un.sun_path, 0666);
2381         } else
2382                 fd_nonblock(s->native_fd, 1);
2383
2384         one = 1;
2385         r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
2386         if (r < 0) {
2387                 log_error("SO_PASSCRED failed: %m");
2388                 return -errno;
2389         }
2390
2391 #ifdef HAVE_SELINUX
2392         one = 1;
2393         r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
2394         if (r < 0)
2395                 log_warning("SO_PASSSEC failed: %m");
2396 #endif
2397
2398         one = 1;
2399         r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
2400         if (r < 0) {
2401                 log_error("SO_TIMESTAMP failed: %m");
2402                 return -errno;
2403         }
2404
2405         zero(ev);
2406         ev.events = EPOLLIN;
2407         ev.data.fd = s->native_fd;
2408         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
2409                 log_error("Failed to add native server fd to epoll object: %m");
2410                 return -errno;
2411         }
2412
2413         return 0;
2414 }
2415
2416 static int open_stdout_socket(Server *s) {
2417         union sockaddr_union sa;
2418         int r;
2419         struct epoll_event ev;
2420
2421         assert(s);
2422
2423         if (s->stdout_fd < 0) {
2424
2425                 s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2426                 if (s->stdout_fd < 0) {
2427                         log_error("socket() failed: %m");
2428                         return -errno;
2429                 }
2430
2431                 zero(sa);
2432                 sa.un.sun_family = AF_UNIX;
2433                 strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
2434
2435                 unlink(sa.un.sun_path);
2436
2437                 r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
2438                 if (r < 0) {
2439                         log_error("bind() failed: %m");
2440                         return -errno;
2441                 }
2442
2443                 chmod(sa.un.sun_path, 0666);
2444
2445                 if (listen(s->stdout_fd, SOMAXCONN) < 0) {
2446                         log_error("liste() failed: %m");
2447                         return -errno;
2448                 }
2449         } else
2450                 fd_nonblock(s->stdout_fd, 1);
2451
2452         zero(ev);
2453         ev.events = EPOLLIN;
2454         ev.data.fd = s->stdout_fd;
2455         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
2456                 log_error("Failed to add stdout server fd to epoll object: %m");
2457                 return -errno;
2458         }
2459
2460         return 0;
2461 }
2462
2463 static int open_proc_kmsg(Server *s) {
2464         struct epoll_event ev;
2465
2466         assert(s);
2467
2468         if (!s->import_proc_kmsg)
2469                 return 0;
2470
2471
2472         s->proc_kmsg_fd = open("/proc/kmsg", O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2473         if (s->proc_kmsg_fd < 0) {
2474                 log_warning("Failed to open /proc/kmsg, ignoring: %m");
2475                 return 0;
2476         }
2477
2478         zero(ev);
2479         ev.events = EPOLLIN;
2480         ev.data.fd = s->proc_kmsg_fd;
2481         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->proc_kmsg_fd, &ev) < 0) {
2482                 log_error("Failed to add /proc/kmsg fd to epoll object: %m");
2483                 return -errno;
2484         }
2485
2486         return 0;
2487 }
2488
2489 static int open_signalfd(Server *s) {
2490         sigset_t mask;
2491         struct epoll_event ev;
2492
2493         assert(s);
2494
2495         assert_se(sigemptyset(&mask) == 0);
2496         sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, -1);
2497         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
2498
2499         s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
2500         if (s->signal_fd < 0) {
2501                 log_error("signalfd(): %m");
2502                 return -errno;
2503         }
2504
2505         zero(ev);
2506         ev.events = EPOLLIN;
2507         ev.data.fd = s->signal_fd;
2508
2509         if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
2510                 log_error("epoll_ctl(): %m");
2511                 return -errno;
2512         }
2513
2514         return 0;
2515 }
2516
2517 static int server_parse_proc_cmdline(Server *s) {
2518         char *line, *w, *state;
2519         int r;
2520         size_t l;
2521
2522         if (detect_container(NULL) > 0)
2523                 return 0;
2524
2525         r = read_one_line_file("/proc/cmdline", &line);
2526         if (r < 0) {
2527                 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
2528                 return 0;
2529         }
2530
2531         FOREACH_WORD_QUOTED(w, l, line, state) {
2532                 char *word;
2533
2534                 word = strndup(w, l);
2535                 if (!word) {
2536                         r = -ENOMEM;
2537                         goto finish;
2538                 }
2539
2540                 if (startswith(word, "systemd_journald.forward_to_syslog=")) {
2541                         r = parse_boolean(word + 35);
2542                         if (r < 0)
2543                                 log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
2544                         else
2545                                 s->forward_to_syslog = r;
2546                 } else if (startswith(word, "systemd_journald.forward_to_kmsg=")) {
2547                         r = parse_boolean(word + 33);
2548                         if (r < 0)
2549                                 log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
2550                         else
2551                                 s->forward_to_kmsg = r;
2552                 } else if (startswith(word, "systemd_journald.forward_to_console=")) {
2553                         r = parse_boolean(word + 36);
2554                         if (r < 0)
2555                                 log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
2556                         else
2557                                 s->forward_to_console = r;
2558                 }
2559
2560                 free(word);
2561         }
2562
2563         r = 0;
2564
2565 finish:
2566         free(line);
2567         return r;
2568 }
2569
2570 static int server_parse_config_file(Server *s) {
2571         FILE *f;
2572         const char *fn;
2573         int r;
2574
2575         assert(s);
2576
2577         fn = "/etc/systemd/systemd-journald.conf";
2578         f = fopen(fn, "re");
2579         if (!f) {
2580                 if (errno == ENOENT)
2581                         return 0;
2582
2583                 log_warning("Failed to open configuration file %s: %m", fn);
2584                 return -errno;
2585         }
2586
2587         r = config_parse(fn, f, "Journal\0", config_item_perf_lookup, (void*) journald_gperf_lookup, false, s);
2588         if (r < 0)
2589                 log_warning("Failed to parse configuration file: %s", strerror(-r));
2590
2591         fclose(f);
2592
2593         return r;
2594 }
2595
2596 static int server_init(Server *s) {
2597         int n, r, fd;
2598
2599         assert(s);
2600
2601         zero(*s);
2602         s->syslog_fd = s->native_fd = s->stdout_fd = s->signal_fd = s->epoll_fd = s->proc_kmsg_fd = -1;
2603         s->compress = true;
2604
2605         s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
2606         s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
2607
2608         s->forward_to_syslog = true;
2609         s->import_proc_kmsg = true;
2610
2611         memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
2612         memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
2613
2614         server_parse_config_file(s);
2615         server_parse_proc_cmdline(s);
2616
2617         s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
2618         if (!s->user_journals) {
2619                 log_error("Out of memory.");
2620                 return -ENOMEM;
2621         }
2622
2623         s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2624         if (s->epoll_fd < 0) {
2625                 log_error("Failed to create epoll object: %m");
2626                 return -errno;
2627         }
2628
2629         n = sd_listen_fds(true);
2630         if (n < 0) {
2631                 log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
2632                 return n;
2633         }
2634
2635         for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2636
2637                 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
2638
2639                         if (s->native_fd >= 0) {
2640                                 log_error("Too many native sockets passed.");
2641                                 return -EINVAL;
2642                         }
2643
2644                         s->native_fd = fd;
2645
2646                 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
2647
2648                         if (s->stdout_fd >= 0) {
2649                                 log_error("Too many stdout sockets passed.");
2650                                 return -EINVAL;
2651                         }
2652
2653                         s->stdout_fd = fd;
2654
2655                 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
2656
2657                         if (s->syslog_fd >= 0) {
2658                                 log_error("Too many /dev/log sockets passed.");
2659                                 return -EINVAL;
2660                         }
2661
2662                         s->syslog_fd = fd;
2663
2664                 } else {
2665                         log_error("Unknown socket passed.");
2666                         return -EINVAL;
2667                 }
2668         }
2669
2670         r = open_syslog_socket(s);
2671         if (r < 0)
2672                 return r;
2673
2674         r = open_native_socket(s);
2675         if (r < 0)
2676                 return r;
2677
2678         r = open_stdout_socket(s);
2679         if (r < 0)
2680                 return r;
2681
2682         r = open_proc_kmsg(s);
2683         if (r < 0)
2684                 return r;
2685
2686         r = open_signalfd(s);
2687         if (r < 0)
2688                 return r;
2689
2690         s->rate_limit = journal_rate_limit_new(s->rate_limit_interval, s->rate_limit_burst);
2691         if (!s->rate_limit)
2692                 return -ENOMEM;
2693
2694         r = system_journal_open(s);
2695         if (r < 0)
2696                 return r;
2697
2698         return 0;
2699 }
2700
2701 static void server_done(Server *s) {
2702         JournalFile *f;
2703         assert(s);
2704
2705         while (s->stdout_streams)
2706                 stdout_stream_free(s->stdout_streams);
2707
2708         if (s->system_journal)
2709                 journal_file_close(s->system_journal);
2710
2711         if (s->runtime_journal)
2712                 journal_file_close(s->runtime_journal);
2713
2714         while ((f = hashmap_steal_first(s->user_journals)))
2715                 journal_file_close(f);
2716
2717         hashmap_free(s->user_journals);
2718
2719         if (s->epoll_fd >= 0)
2720                 close_nointr_nofail(s->epoll_fd);
2721
2722         if (s->signal_fd >= 0)
2723                 close_nointr_nofail(s->signal_fd);
2724
2725         if (s->syslog_fd >= 0)
2726                 close_nointr_nofail(s->syslog_fd);
2727
2728         if (s->native_fd >= 0)
2729                 close_nointr_nofail(s->native_fd);
2730
2731         if (s->stdout_fd >= 0)
2732                 close_nointr_nofail(s->stdout_fd);
2733
2734         if (s->proc_kmsg_fd >= 0)
2735                 close_nointr_nofail(s->proc_kmsg_fd);
2736
2737         if (s->rate_limit)
2738                 journal_rate_limit_free(s->rate_limit);
2739
2740         free(s->buffer);
2741 }
2742
2743 int main(int argc, char *argv[]) {
2744         Server server;
2745         int r;
2746
2747         /* if (getppid() != 1) { */
2748         /*         log_error("This program should be invoked by init only."); */
2749         /*         return EXIT_FAILURE; */
2750         /* } */
2751
2752         if (argc > 1) {
2753                 log_error("This program does not take arguments.");
2754                 return EXIT_FAILURE;
2755         }
2756
2757         log_set_target(LOG_TARGET_CONSOLE);
2758         log_parse_environment();
2759         log_open();
2760
2761         umask(0022);
2762
2763         r = server_init(&server);
2764         if (r < 0)
2765                 goto finish;
2766
2767         server_vacuum(&server);
2768         server_flush_to_var(&server);
2769         server_flush_proc_kmsg(&server);
2770
2771         log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
2772         driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
2773
2774         sd_notify(false,
2775                   "READY=1\n"
2776                   "STATUS=Processing requests...");
2777
2778         for (;;) {
2779                 struct epoll_event event;
2780
2781                 r = epoll_wait(server.epoll_fd, &event, 1, -1);
2782                 if (r < 0) {
2783
2784                         if (errno == EINTR)
2785                                 continue;
2786
2787                         log_error("epoll_wait() failed: %m");
2788                         r = -errno;
2789                         goto finish;
2790                 } else if (r == 0)
2791                         break;
2792
2793                 r = process_event(&server, &event);
2794                 if (r < 0)
2795                         goto finish;
2796                 else if (r == 0)
2797                         break;
2798         }
2799
2800         log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
2801         driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
2802
2803 finish:
2804         sd_notify(false,
2805                   "STATUS=Shutting down...");
2806
2807         server_done(&server);
2808
2809         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
2810 }