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