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