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