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