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