]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/journal/journald-server.c
Merge pull request #29242 from fbuihuu/update-main-config-file-headers
[thirdparty/systemd.git] / src / journal / journald-server.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #if HAVE_SELINUX
4 #include <selinux/selinux.h>
5 #endif
6 #include <sys/ioctl.h>
7 #include <sys/mman.h>
8 #include <sys/signalfd.h>
9 #include <sys/statvfs.h>
10 #include <linux/sockios.h>
11
12 #include "sd-daemon.h"
13 #include "sd-journal.h"
14 #include "sd-messages.h"
15
16 #include "acl-util.h"
17 #include "alloc-util.h"
18 #include "audit-util.h"
19 #include "cgroup-util.h"
20 #include "conf-parser.h"
21 #include "dirent-util.h"
22 #include "extract-word.h"
23 #include "fd-util.h"
24 #include "fileio.h"
25 #include "format-util.h"
26 #include "fs-util.h"
27 #include "hashmap.h"
28 #include "hostname-util.h"
29 #include "id128-util.h"
30 #include "initrd-util.h"
31 #include "io-util.h"
32 #include "journal-authenticate.h"
33 #include "journal-file-util.h"
34 #include "journal-internal.h"
35 #include "journal-vacuum.h"
36 #include "journald-audit.h"
37 #include "journald-context.h"
38 #include "journald-kmsg.h"
39 #include "journald-native.h"
40 #include "journald-rate-limit.h"
41 #include "journald-server.h"
42 #include "journald-stream.h"
43 #include "journald-syslog.h"
44 #include "log.h"
45 #include "missing_audit.h"
46 #include "mkdir.h"
47 #include "parse-util.h"
48 #include "path-util.h"
49 #include "proc-cmdline.h"
50 #include "process-util.h"
51 #include "rm-rf.h"
52 #include "selinux-util.h"
53 #include "signal-util.h"
54 #include "socket-util.h"
55 #include "stdio-util.h"
56 #include "string-table.h"
57 #include "string-util.h"
58 #include "syslog-util.h"
59 #include "uid-alloc-range.h"
60 #include "user-util.h"
61 #include "varlink-io.systemd.Journal.h"
62
63 #define USER_JOURNALS_MAX 1024
64
65 #define DEFAULT_SYNC_INTERVAL_USEC (5*USEC_PER_MINUTE)
66 #define DEFAULT_RATE_LIMIT_INTERVAL (30*USEC_PER_SEC)
67 #define DEFAULT_RATE_LIMIT_BURST 10000
68 #define DEFAULT_MAX_FILE_USEC USEC_PER_MONTH
69
70 #define DEFAULT_KMSG_OWN_INTERVAL (5 * USEC_PER_SEC)
71 #define DEFAULT_KMSG_OWN_BURST 50
72
73 #define RECHECK_SPACE_USEC (30*USEC_PER_SEC)
74
75 #define NOTIFY_SNDBUF_SIZE (8*1024*1024)
76
77 /* The period to insert between posting changes for coalescing */
78 #define POST_CHANGE_TIMER_INTERVAL_USEC (250*USEC_PER_MSEC)
79
80 /* Pick a good default that is likely to fit into AF_UNIX and AF_INET SOCK_DGRAM datagrams, and even leaves some room
81 * for a bit of additional metadata. */
82 #define DEFAULT_LINE_MAX (48*1024)
83
84 #define DEFERRED_CLOSES_MAX (4096)
85
86 #define IDLE_TIMEOUT_USEC (30*USEC_PER_SEC)
87
88 #define FAILED_TO_WRITE_ENTRY_RATELIMIT ((const RateLimit) { .interval = 1 * USEC_PER_SEC, .burst = 1 })
89
90 static int server_determine_path_usage(
91 Server *s,
92 const char *path,
93 uint64_t *ret_used,
94 uint64_t *ret_free) {
95
96 _cleanup_closedir_ DIR *d = NULL;
97 struct statvfs ss;
98
99 assert(s);
100 assert(path);
101 assert(ret_used);
102 assert(ret_free);
103
104 d = opendir(path);
105 if (!d)
106 return log_ratelimit_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR,
107 errno, JOURNAL_LOG_RATELIMIT, "Failed to open %s: %m", path);
108
109 if (fstatvfs(dirfd(d), &ss) < 0)
110 return log_ratelimit_error_errno(errno, JOURNAL_LOG_RATELIMIT,
111 "Failed to fstatvfs(%s): %m", path);
112
113 *ret_free = ss.f_bsize * ss.f_bavail;
114 *ret_used = 0;
115 FOREACH_DIRENT_ALL(de, d, break) {
116 struct stat st;
117
118 if (!endswith(de->d_name, ".journal") &&
119 !endswith(de->d_name, ".journal~"))
120 continue;
121
122 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
123 log_debug_errno(errno, "Failed to stat %s/%s, ignoring: %m", path, de->d_name);
124 continue;
125 }
126
127 if (!S_ISREG(st.st_mode))
128 continue;
129
130 *ret_used += (uint64_t) st.st_blocks * 512UL;
131 }
132
133 return 0;
134 }
135
136 static void cache_space_invalidate(JournalStorageSpace *space) {
137 zero(*space);
138 }
139
140 static int cache_space_refresh(Server *s, JournalStorage *storage) {
141 JournalStorageSpace *space;
142 JournalMetrics *metrics;
143 uint64_t vfs_used, vfs_avail, avail;
144 usec_t ts;
145 int r;
146
147 assert(s);
148
149 metrics = &storage->metrics;
150 space = &storage->space;
151
152 ts = now(CLOCK_MONOTONIC);
153
154 if (space->timestamp != 0 && usec_add(space->timestamp, RECHECK_SPACE_USEC) > ts)
155 return 0;
156
157 r = server_determine_path_usage(s, storage->path, &vfs_used, &vfs_avail);
158 if (r < 0)
159 return r;
160
161 space->vfs_used = vfs_used;
162 space->vfs_available = vfs_avail;
163
164 avail = LESS_BY(vfs_avail, metrics->keep_free);
165
166 space->limit = CLAMP(vfs_used + avail, metrics->min_use, metrics->max_use);
167 space->available = LESS_BY(space->limit, vfs_used);
168 space->timestamp = ts;
169 return 1;
170 }
171
172 static void patch_min_use(JournalStorage *storage) {
173 assert(storage);
174
175 /* Let's bump the min_use limit to the current usage on disk. We do
176 * this when starting up and first opening the journal files. This way
177 * sudden spikes in disk usage will not cause journald to vacuum files
178 * without bounds. Note that this means that only a restart of journald
179 * will make it reset this value. */
180
181 storage->metrics.min_use = MAX(storage->metrics.min_use, storage->space.vfs_used);
182 }
183
184 static JournalStorage* server_current_storage(Server *s) {
185 assert(s);
186
187 return s->system_journal ? &s->system_storage : &s->runtime_storage;
188 }
189
190 static int server_determine_space(Server *s, uint64_t *available, uint64_t *limit) {
191 JournalStorage *js;
192 int r;
193
194 assert(s);
195
196 js = server_current_storage(s);
197
198 r = cache_space_refresh(s, js);
199 if (r >= 0) {
200 if (available)
201 *available = js->space.available;
202 if (limit)
203 *limit = js->space.limit;
204 }
205 return r;
206 }
207
208 void server_space_usage_message(Server *s, JournalStorage *storage) {
209 assert(s);
210
211 if (!storage)
212 storage = server_current_storage(s);
213
214 if (cache_space_refresh(s, storage) < 0)
215 return;
216
217 const JournalMetrics *metrics = &storage->metrics;
218
219 server_driver_message(s, 0,
220 "MESSAGE_ID=" SD_MESSAGE_JOURNAL_USAGE_STR,
221 LOG_MESSAGE("%s (%s) is %s, max %s, %s free.",
222 storage->name, storage->path,
223 FORMAT_BYTES(storage->space.vfs_used),
224 FORMAT_BYTES(storage->space.limit),
225 FORMAT_BYTES(storage->space.available)),
226 "JOURNAL_NAME=%s", storage->name,
227 "JOURNAL_PATH=%s", storage->path,
228 "CURRENT_USE=%"PRIu64, storage->space.vfs_used,
229 "CURRENT_USE_PRETTY=%s", FORMAT_BYTES(storage->space.vfs_used),
230 "MAX_USE=%"PRIu64, metrics->max_use,
231 "MAX_USE_PRETTY=%s", FORMAT_BYTES(metrics->max_use),
232 "DISK_KEEP_FREE=%"PRIu64, metrics->keep_free,
233 "DISK_KEEP_FREE_PRETTY=%s", FORMAT_BYTES(metrics->keep_free),
234 "DISK_AVAILABLE=%"PRIu64, storage->space.vfs_available,
235 "DISK_AVAILABLE_PRETTY=%s", FORMAT_BYTES(storage->space.vfs_available),
236 "LIMIT=%"PRIu64, storage->space.limit,
237 "LIMIT_PRETTY=%s", FORMAT_BYTES(storage->space.limit),
238 "AVAILABLE=%"PRIu64, storage->space.available,
239 "AVAILABLE_PRETTY=%s", FORMAT_BYTES(storage->space.available),
240 NULL);
241 }
242
243 static void server_add_acls(JournalFile *f, uid_t uid) {
244 assert(f);
245
246 #if HAVE_ACL
247 int r;
248
249 if (uid_for_system_journal(uid))
250 return;
251
252 r = fd_add_uid_acl_permission(f->fd, uid, ACL_READ);
253 if (r < 0)
254 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
255 "Failed to set ACL on %s, ignoring: %m", f->path);
256 #endif
257 }
258
259 static int server_open_journal(
260 Server *s,
261 bool reliably,
262 const char *fname,
263 int open_flags,
264 bool seal,
265 JournalMetrics *metrics,
266 JournalFile **ret) {
267
268 _cleanup_(journal_file_offline_closep) JournalFile *f = NULL;
269 JournalFileFlags file_flags;
270 int r;
271
272 assert(s);
273 assert(fname);
274 assert(ret);
275
276 file_flags =
277 (s->compress.enabled ? JOURNAL_COMPRESS : 0) |
278 (seal ? JOURNAL_SEAL : 0) |
279 JOURNAL_STRICT_ORDER;
280
281 set_clear_with_destructor(s->deferred_closes, journal_file_offline_close);
282
283 if (reliably)
284 r = journal_file_open_reliably(
285 fname,
286 open_flags,
287 file_flags,
288 0640,
289 s->compress.threshold_bytes,
290 metrics,
291 s->mmap,
292 /* template= */ NULL,
293 &f);
294 else
295 r = journal_file_open(
296 /* fd= */ -1,
297 fname,
298 open_flags,
299 file_flags,
300 0640,
301 s->compress.threshold_bytes,
302 metrics,
303 s->mmap,
304 /* template= */ NULL,
305 &f);
306 if (r < 0)
307 return r;
308
309 r = journal_file_enable_post_change_timer(f, s->event, POST_CHANGE_TIMER_INTERVAL_USEC);
310 if (r < 0)
311 return r;
312
313 *ret = TAKE_PTR(f);
314 return r;
315 }
316
317 static bool server_flushed_flag_is_set(Server *s) {
318 const char *fn;
319
320 assert(s);
321
322 /* We don't support the "flushing" concept for namespace instances, we assume them to always have
323 * access to /var */
324 if (s->namespace)
325 return true;
326
327 fn = strjoina(s->runtime_directory, "/flushed");
328 return access(fn, F_OK) >= 0;
329 }
330
331 static int server_system_journal_open(
332 Server *s,
333 bool flush_requested,
334 bool relinquish_requested) {
335
336 const char *fn;
337 int r = 0;
338
339 if (!s->system_journal &&
340 IN_SET(s->storage, STORAGE_PERSISTENT, STORAGE_AUTO) &&
341 (flush_requested || server_flushed_flag_is_set(s)) &&
342 !relinquish_requested) {
343
344 /* If in auto mode: first try to create the machine path, but not the prefix.
345 *
346 * If in persistent mode: create /var/log/journal and the machine path */
347
348 if (s->storage == STORAGE_PERSISTENT)
349 (void) mkdir_parents(s->system_storage.path, 0755);
350
351 (void) mkdir(s->system_storage.path, 0755);
352
353 fn = strjoina(s->system_storage.path, "/system.journal");
354 r = server_open_journal(
355 s,
356 /* reliably= */ true,
357 fn,
358 O_RDWR|O_CREAT,
359 s->seal,
360 &s->system_storage.metrics,
361 &s->system_journal);
362 if (r >= 0) {
363 server_add_acls(s->system_journal, 0);
364 (void) cache_space_refresh(s, &s->system_storage);
365 patch_min_use(&s->system_storage);
366 } else {
367 if (!IN_SET(r, -ENOENT, -EROFS))
368 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
369 "Failed to open system journal: %m");
370
371 r = 0;
372 }
373
374 /* If the runtime journal is open, and we're post-flush, we're recovering from a failed
375 * system journal rotate (ENOSPC) for which the runtime journal was reopened.
376 *
377 * Perform an implicit flush to var, leaving the runtime journal closed, now that the system
378 * journal is back.
379 */
380 if (!flush_requested)
381 (void) server_flush_to_var(s, true);
382 }
383
384 if (!s->runtime_journal &&
385 (s->storage != STORAGE_NONE)) {
386
387 fn = strjoina(s->runtime_storage.path, "/system.journal");
388
389 if (!s->system_journal || relinquish_requested) {
390
391 /* OK, we really need the runtime journal, so create it if necessary. */
392
393 (void) mkdir_parents(s->runtime_storage.path, 0755);
394 (void) mkdir(s->runtime_storage.path, 0750);
395
396 r = server_open_journal(
397 s,
398 /* reliably= */ true,
399 fn,
400 O_RDWR|O_CREAT,
401 /* seal= */ false,
402 &s->runtime_storage.metrics,
403 &s->runtime_journal);
404 if (r < 0)
405 return log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
406 "Failed to open runtime journal: %m");
407
408 } else if (!server_flushed_flag_is_set(s)) {
409 /* Try to open the runtime journal, but only if it already exists, so that we can
410 * flush it into the system journal */
411
412 r = server_open_journal(
413 s,
414 /* reliably= */ false,
415 fn,
416 O_RDWR,
417 /* seal= */ false,
418 &s->runtime_storage.metrics,
419 &s->runtime_journal);
420 if (r < 0) {
421 if (r != -ENOENT)
422 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
423 "Failed to open runtime journal: %m");
424
425 r = 0;
426 }
427 }
428
429 if (s->runtime_journal) {
430 server_add_acls(s->runtime_journal, 0);
431 (void) cache_space_refresh(s, &s->runtime_storage);
432 patch_min_use(&s->runtime_storage);
433 }
434 }
435
436 return r;
437 }
438
439 static int server_find_user_journal(Server *s, uid_t uid, JournalFile **ret) {
440 _cleanup_(journal_file_offline_closep) JournalFile *f = NULL;
441 _cleanup_free_ char *p = NULL;
442 int r;
443
444 assert(!uid_for_system_journal(uid));
445
446 f = ordered_hashmap_get(s->user_journals, UID_TO_PTR(uid));
447 if (f)
448 goto found;
449
450 if (asprintf(&p, "%s/user-" UID_FMT ".journal", s->system_storage.path, uid) < 0)
451 return log_oom();
452
453 /* Too many open? Then let's close one (or more) */
454 while (ordered_hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
455 JournalFile *first;
456
457 assert_se(first = ordered_hashmap_steal_first(s->user_journals));
458 (void) journal_file_offline_close(first);
459 }
460
461 r = server_open_journal(
462 s,
463 /* reliably= */ true,
464 p,
465 O_RDWR|O_CREAT,
466 s->seal,
467 &s->system_storage.metrics,
468 &f);
469 if (r < 0)
470 return r;
471
472 r = ordered_hashmap_put(s->user_journals, UID_TO_PTR(uid), f);
473 if (r < 0)
474 return r;
475
476 server_add_acls(f, uid);
477
478 found:
479 *ret = TAKE_PTR(f);
480 return 0;
481 }
482
483 static JournalFile* server_find_journal(Server *s, uid_t uid) {
484 int r;
485
486 assert(s);
487
488 /* A rotate that fails to create the new journal (ENOSPC) leaves the rotated journal as NULL. Unless
489 * we revisit opening, even after space is made available we'll continue to return NULL indefinitely.
490 *
491 * system_journal_open() is a noop if the journals are already open, so we can just call it here to
492 * recover from failed rotates (or anything else that's left the journals as NULL).
493 *
494 * Fixes https://github.com/systemd/systemd/issues/3968 */
495 (void) server_system_journal_open(s, /* flush_requested= */ false, /* relinquish_requested= */ false);
496
497 /* We split up user logs only on /var, not on /run. If the runtime file is open, we write to it
498 * exclusively, in order to guarantee proper order as soon as we flush /run to /var and close the
499 * runtime file. */
500
501 if (s->runtime_journal)
502 return s->runtime_journal;
503
504 /* If we are not in persistent mode, then we need return NULL immediately rather than opening a
505 * persistent journal of any sort.
506 *
507 * Fixes https://github.com/systemd/systemd/issues/20390 */
508 if (!IN_SET(s->storage, STORAGE_AUTO, STORAGE_PERSISTENT))
509 return NULL;
510
511 if (!uid_for_system_journal(uid)) {
512 JournalFile *f = NULL;
513
514 r = server_find_user_journal(s, uid, &f);
515 if (r >= 0)
516 return ASSERT_PTR(f);
517
518 log_warning_errno(r, "Failed to open user journal file, falling back to system journal: %m");
519 }
520
521 return s->system_journal;
522 }
523
524 static int server_do_rotate(
525 Server *s,
526 JournalFile **f,
527 const char* name,
528 bool seal,
529 uint32_t uid) {
530
531 JournalFileFlags file_flags;
532 int r;
533
534 assert(s);
535
536 if (!*f)
537 return -EINVAL;
538
539 file_flags =
540 (s->compress.enabled ? JOURNAL_COMPRESS : 0)|
541 (seal ? JOURNAL_SEAL : 0) |
542 JOURNAL_STRICT_ORDER;
543
544 r = journal_file_rotate(f, s->mmap, file_flags, s->compress.threshold_bytes, s->deferred_closes);
545 if (r < 0) {
546 if (*f)
547 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT,
548 "Failed to rotate %s: %m", (*f)->path);
549 else
550 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT,
551 "Failed to create new %s journal: %m", name);
552 }
553
554 server_add_acls(*f, uid);
555 return r;
556 }
557
558 static void server_process_deferred_closes(Server *s) {
559 JournalFile *f;
560
561 /* Perform any deferred closes which aren't still offlining. */
562 SET_FOREACH(f, s->deferred_closes) {
563 if (journal_file_is_offlining(f))
564 continue;
565
566 (void) set_remove(s->deferred_closes, f);
567 (void) journal_file_offline_close(f);
568 }
569 }
570
571 static void server_vacuum_deferred_closes(Server *s) {
572 assert(s);
573
574 /* Make some room in the deferred closes list, so that it doesn't grow without bounds */
575 if (set_size(s->deferred_closes) < DEFERRED_CLOSES_MAX)
576 return;
577
578 /* Let's first remove all journal files that might already have completed closing */
579 server_process_deferred_closes(s);
580
581 /* And now, let's close some more until we reach the limit again. */
582 while (set_size(s->deferred_closes) >= DEFERRED_CLOSES_MAX) {
583 JournalFile *f;
584
585 assert_se(f = set_steal_first(s->deferred_closes));
586 journal_file_offline_close(f);
587 }
588 }
589
590 static int server_archive_offline_user_journals(Server *s) {
591 _cleanup_closedir_ DIR *d = NULL;
592 int r;
593
594 assert(s);
595
596 d = opendir(s->system_storage.path);
597 if (!d) {
598 if (errno == ENOENT)
599 return 0;
600
601 return log_ratelimit_error_errno(errno, JOURNAL_LOG_RATELIMIT,
602 "Failed to open %s: %m", s->system_storage.path);
603 }
604
605 for (;;) {
606 _cleanup_free_ char *full = NULL;
607 _cleanup_close_ int fd = -EBADF;
608 struct dirent *de;
609 JournalFile *f;
610 uid_t uid;
611
612 errno = 0;
613 de = readdir_no_dot(d);
614 if (!de) {
615 if (errno != 0)
616 log_ratelimit_warning_errno(errno, JOURNAL_LOG_RATELIMIT,
617 "Failed to enumerate %s, ignoring: %m",
618 s->system_storage.path);
619 break;
620 }
621
622 r = journal_file_parse_uid_from_filename(de->d_name, &uid);
623 if (r < 0) {
624 /* Don't warn if the file is not an online or offline user journal. */
625 if (r != -EREMOTE)
626 log_warning_errno(r, "Failed to parse UID from file name '%s', ignoring: %m", de->d_name);
627 continue;
628 }
629
630 /* Already rotated in the above loop? i.e. is it an open user journal? */
631 if (ordered_hashmap_contains(s->user_journals, UID_TO_PTR(uid)))
632 continue;
633
634 full = path_join(s->system_storage.path, de->d_name);
635 if (!full)
636 return log_oom();
637
638 fd = openat(dirfd(d), de->d_name, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_NONBLOCK);
639 if (fd < 0) {
640 log_ratelimit_full_errno(IN_SET(errno, ELOOP, ENOENT) ? LOG_DEBUG : LOG_WARNING,
641 errno, JOURNAL_LOG_RATELIMIT,
642 "Failed to open journal file '%s' for rotation: %m", full);
643 continue;
644 }
645
646 /* Make some room in the set of deferred close()s */
647 server_vacuum_deferred_closes(s);
648
649 /* Open the file briefly, so that we can archive it */
650 r = journal_file_open(
651 fd,
652 full,
653 O_RDWR,
654 (s->compress.enabled ? JOURNAL_COMPRESS : 0) |
655 (s->seal ? JOURNAL_SEAL : 0), /* strict order does not matter here */
656 0640,
657 s->compress.threshold_bytes,
658 &s->system_storage.metrics,
659 s->mmap,
660 /* template= */ NULL,
661 &f);
662 if (r < 0) {
663 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
664 "Failed to read journal file %s for rotation, trying to move it out of the way: %m",
665 full);
666
667 r = journal_file_dispose(dirfd(d), de->d_name);
668 if (r < 0)
669 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
670 "Failed to move %s out of the way, ignoring: %m",
671 full);
672 else
673 log_debug("Successfully moved %s out of the way.", full);
674
675 continue;
676 }
677
678 TAKE_FD(fd); /* Donated to journal_file_open() */
679
680 r = journal_file_archive(f, NULL);
681 if (r < 0)
682 log_debug_errno(r, "Failed to archive journal file '%s', ignoring: %m", full);
683
684 journal_file_initiate_close(TAKE_PTR(f), s->deferred_closes);
685 }
686
687 return 0;
688 }
689
690 void server_rotate(Server *s) {
691 JournalFile *f;
692 void *k;
693 int r;
694
695 log_debug("Rotating...");
696
697 /* First, rotate the system journal (either in its runtime flavour or in its runtime flavour) */
698 (void) server_do_rotate(s, &s->runtime_journal, "runtime", /* seal= */ false, /* uid= */ 0);
699 (void) server_do_rotate(s, &s->system_journal, "system", s->seal, /* uid= */ 0);
700
701 /* Then, rotate all user journals we have open (keeping them open) */
702 ORDERED_HASHMAP_FOREACH_KEY(f, k, s->user_journals) {
703 r = server_do_rotate(s, &f, "user", s->seal, PTR_TO_UID(k));
704 if (r >= 0)
705 ordered_hashmap_replace(s->user_journals, k, f);
706 else if (!f)
707 /* Old file has been closed and deallocated */
708 ordered_hashmap_remove(s->user_journals, k);
709 }
710
711 /* Finally, also rotate all user journals we currently do not have open. (But do so only if we
712 * actually have access to /var, i.e. are not in the log-to-runtime-journal mode). */
713 if (!s->runtime_journal)
714 (void) server_archive_offline_user_journals(s);
715
716 server_process_deferred_closes(s);
717 }
718
719 void server_sync(Server *s) {
720 JournalFile *f;
721 int r;
722
723 if (s->system_journal) {
724 r = journal_file_set_offline(s->system_journal, false);
725 if (r < 0)
726 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
727 "Failed to sync system journal, ignoring: %m");
728 }
729
730 ORDERED_HASHMAP_FOREACH(f, s->user_journals) {
731 r = journal_file_set_offline(f, false);
732 if (r < 0)
733 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
734 "Failed to sync user journal, ignoring: %m");
735 }
736
737 if (s->sync_event_source) {
738 r = sd_event_source_set_enabled(s->sync_event_source, SD_EVENT_OFF);
739 if (r < 0)
740 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT,
741 "Failed to disable sync timer source: %m");
742 }
743
744 s->sync_scheduled = false;
745 }
746
747 static void server_do_vacuum(Server *s, JournalStorage *storage, bool verbose) {
748
749 int r;
750
751 assert(s);
752 assert(storage);
753
754 (void) cache_space_refresh(s, storage);
755
756 if (verbose)
757 server_space_usage_message(s, storage);
758
759 r = journal_directory_vacuum(storage->path, storage->space.limit,
760 storage->metrics.n_max_files, s->max_retention_usec,
761 &s->oldest_file_usec, verbose);
762 if (r < 0 && r != -ENOENT)
763 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
764 "Failed to vacuum %s, ignoring: %m", storage->path);
765
766 cache_space_invalidate(&storage->space);
767 }
768
769 void server_vacuum(Server *s, bool verbose) {
770 assert(s);
771
772 log_debug("Vacuuming...");
773
774 s->oldest_file_usec = 0;
775
776 if (s->system_journal)
777 server_do_vacuum(s, &s->system_storage, verbose);
778 if (s->runtime_journal)
779 server_do_vacuum(s, &s->runtime_storage, verbose);
780 }
781
782 static void server_cache_machine_id(Server *s) {
783 sd_id128_t id;
784 int r;
785
786 assert(s);
787
788 r = sd_id128_get_machine(&id);
789 if (r < 0)
790 return;
791
792 sd_id128_to_string(id, stpcpy(s->machine_id_field, "_MACHINE_ID="));
793 }
794
795 static void server_cache_boot_id(Server *s) {
796 sd_id128_t id;
797 int r;
798
799 assert(s);
800
801 r = sd_id128_get_boot(&id);
802 if (r < 0)
803 return;
804
805 sd_id128_to_string(id, stpcpy(s->boot_id_field, "_BOOT_ID="));
806 }
807
808 static void server_cache_hostname(Server *s) {
809 _cleanup_free_ char *t = NULL;
810 char *x;
811
812 assert(s);
813
814 t = gethostname_malloc();
815 if (!t)
816 return;
817
818 x = strjoin("_HOSTNAME=", t);
819 if (!x)
820 return;
821
822 free_and_replace(s->hostname_field, x);
823 }
824
825 static bool shall_try_append_again(JournalFile *f, int r) {
826 switch (r) {
827
828 case -E2BIG: /* Hit configured limit */
829 case -EFBIG: /* Hit fs limit */
830 case -EDQUOT: /* Quota limit hit */
831 case -ENOSPC: /* Disk full */
832 log_debug_errno(r, "%s: Allocation limit reached, rotating.", f->path);
833 return true;
834
835 case -EROFS: /* Read-only file system */
836 /* When appending an entry fails if shall_try_append_again returns true, the journal is
837 * rotated. If the FS is read-only, rotation will fail and s->system_journal will be set to
838 * NULL. After that, when find_journal will try to open the journal since s->system_journal
839 * will be NULL, it will open the runtime journal. */
840 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Read-only file system, rotating.", f->path);
841 return true;
842
843 case -EIO: /* I/O error of some kind (mmap) */
844 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT, "%s: IO error, rotating.", f->path);
845 return true;
846
847 case -EHOSTDOWN: /* Other machine */
848 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Journal file from other machine, rotating.", f->path);
849 return true;
850
851 case -EBUSY: /* Unclean shutdown */
852 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Unclean shutdown, rotating.", f->path);
853 return true;
854
855 case -EPROTONOSUPPORT: /* Unsupported feature */
856 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Unsupported feature, rotating.", f->path);
857 return true;
858
859 case -EBADMSG: /* Corrupted */
860 case -ENODATA: /* Truncated */
861 case -ESHUTDOWN: /* Already archived */
862 case -EADDRNOTAVAIL: /* Referenced object offset out of bounds */
863 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Journal file corrupted, rotating.", f->path);
864 return true;
865
866 case -EIDRM: /* Journal file has been deleted */
867 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Journal file has been deleted, rotating.", f->path);
868 return true;
869
870 case -EREMCHG: /* Wallclock time (CLOCK_REALTIME) jumped backwards relative to last journal entry */
871 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Realtime clock jumped backwards relative to last journal entry, rotating.", f->path);
872 return true;
873
874 case -ENOTNAM: /* Monotonic time (CLOCK_MONOTONIC) jumped backwards relative to last journal entry with the same boot ID */
875 log_ratelimit_info_errno(
876 r,
877 JOURNAL_LOG_RATELIMIT,
878 "%s: Monotonic clock jumped backwards relative to last journal entry with the same boot ID, rotating.",
879 f->path);
880 return true;
881
882 case -EILSEQ: /* seqnum ID last used in the file doesn't match the one we'd passed when writing an entry to it */
883 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Journal file uses a different sequence number ID, rotating.", f->path);
884 return true;
885
886 case -EAFNOSUPPORT:
887 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Underlying file system does not support memory mapping or another required file system feature.", f->path);
888 return false;
889
890 default:
891 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Unexpected error while writing to journal file: %m", f->path);
892 return false;
893 }
894 }
895
896 static void server_write_to_journal(
897 Server *s,
898 uid_t uid,
899 const struct iovec *iovec,
900 size_t n,
901 int priority) {
902
903 bool vacuumed = false, rotate = false;
904 struct dual_timestamp ts;
905 JournalFile *f;
906 int r;
907
908 assert(s);
909 assert(iovec);
910 assert(n > 0);
911
912 /* Get the closest, linearized time we have for this log event from the event loop. (Note that we do not use
913 * the source time, and not even the time the event was originally seen, but instead simply the time we started
914 * processing it, as we want strictly linear ordering in what we write out.) */
915 assert_se(sd_event_now(s->event, CLOCK_REALTIME, &ts.realtime) >= 0);
916 assert_se(sd_event_now(s->event, CLOCK_MONOTONIC, &ts.monotonic) >= 0);
917
918 if (ts.realtime < s->last_realtime_clock) {
919 /* When the time jumps backwards, let's immediately rotate. Of course, this should not happen during
920 * regular operation. However, when it does happen, then we should make sure that we start fresh files
921 * to ensure that the entries in the journal files are strictly ordered by time, in order to ensure
922 * bisection works correctly. */
923
924 log_ratelimit_info(JOURNAL_LOG_RATELIMIT, "Time jumped backwards, rotating.");
925 rotate = true;
926 } else {
927
928 f = server_find_journal(s, uid);
929 if (!f)
930 return;
931
932 if (journal_file_rotate_suggested(f, s->max_file_usec, LOG_DEBUG)) {
933 log_debug("%s: Journal header limits reached or header out-of-date, rotating.",
934 f->path);
935 rotate = true;
936 }
937 }
938
939 if (rotate) {
940 server_rotate(s);
941 server_vacuum(s, false);
942 vacuumed = true;
943
944 f = server_find_journal(s, uid);
945 if (!f)
946 return;
947 }
948
949 s->last_realtime_clock = ts.realtime;
950
951 r = journal_file_append_entry(
952 f,
953 &ts,
954 /* boot_id= */ NULL,
955 iovec, n,
956 &s->seqnum->seqnum,
957 &s->seqnum->id,
958 /* ret_object= */ NULL,
959 /* ret_offset= */ NULL);
960 if (r >= 0) {
961 server_schedule_sync(s, priority);
962 return;
963 }
964
965 log_debug_errno(r, "Failed to write entry to %s (%zu items, %zu bytes): %m", f->path, n, IOVEC_TOTAL_SIZE(iovec, n));
966
967 if (!shall_try_append_again(f, r))
968 return;
969 if (vacuumed) {
970 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
971 "Suppressing rotation, as we already rotated immediately before write attempt. Giving up.");
972 return;
973 }
974
975 server_rotate(s);
976 server_vacuum(s, false);
977
978 f = server_find_journal(s, uid);
979 if (!f)
980 return;
981
982 log_debug_errno(r, "Retrying write.");
983 r = journal_file_append_entry(
984 f,
985 &ts,
986 /* boot_id= */ NULL,
987 iovec, n,
988 &s->seqnum->seqnum,
989 &s->seqnum->id,
990 /* ret_object= */ NULL,
991 /* ret_offset= */ NULL);
992 if (r < 0)
993 log_ratelimit_error_errno(r, FAILED_TO_WRITE_ENTRY_RATELIMIT,
994 "Failed to write entry to %s (%zu items, %zu bytes) despite vacuuming, ignoring: %m",
995 f->path, n, IOVEC_TOTAL_SIZE(iovec, n));
996 else
997 server_schedule_sync(s, priority);
998 }
999
1000 #define IOVEC_ADD_NUMERIC_FIELD(iovec, n, value, type, isset, format, field) \
1001 if (isset(value)) { \
1002 char *k; \
1003 k = newa(char, STRLEN(field "=") + DECIMAL_STR_MAX(type) + 1); \
1004 sprintf(k, field "=" format, value); \
1005 iovec[n++] = IOVEC_MAKE_STRING(k); \
1006 }
1007
1008 #define IOVEC_ADD_STRING_FIELD(iovec, n, value, field) \
1009 if (!isempty(value)) { \
1010 char *k; \
1011 k = strjoina(field "=", value); \
1012 iovec[n++] = IOVEC_MAKE_STRING(k); \
1013 }
1014
1015 #define IOVEC_ADD_ID128_FIELD(iovec, n, value, field) \
1016 if (!sd_id128_is_null(value)) { \
1017 char *k; \
1018 k = newa(char, STRLEN(field "=") + SD_ID128_STRING_MAX); \
1019 sd_id128_to_string(value, stpcpy(k, field "=")); \
1020 iovec[n++] = IOVEC_MAKE_STRING(k); \
1021 }
1022
1023 #define IOVEC_ADD_SIZED_FIELD(iovec, n, value, value_size, field) \
1024 if (value_size > 0) { \
1025 char *k; \
1026 k = newa(char, STRLEN(field "=") + value_size + 1); \
1027 *((char*) mempcpy(stpcpy(k, field "="), value, value_size)) = 0; \
1028 iovec[n++] = IOVEC_MAKE_STRING(k); \
1029 } \
1030
1031 static void server_dispatch_message_real(
1032 Server *s,
1033 struct iovec *iovec, size_t n, size_t m,
1034 const ClientContext *c,
1035 const struct timeval *tv,
1036 int priority,
1037 pid_t object_pid) {
1038
1039 char source_time[sizeof("_SOURCE_REALTIME_TIMESTAMP=") + DECIMAL_STR_MAX(usec_t)];
1040 _unused_ _cleanup_free_ char *cmdline1 = NULL, *cmdline2 = NULL;
1041 uid_t journal_uid;
1042 ClientContext *o;
1043
1044 assert(s);
1045 assert(iovec);
1046 assert(n > 0);
1047 assert(n +
1048 N_IOVEC_META_FIELDS +
1049 (pid_is_valid(object_pid) ? N_IOVEC_OBJECT_FIELDS : 0) +
1050 client_context_extra_fields_n_iovec(c) <= m);
1051
1052 if (c) {
1053 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->pid, pid_t, pid_is_valid, PID_FMT, "_PID");
1054 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->uid, uid_t, uid_is_valid, UID_FMT, "_UID");
1055 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->gid, gid_t, gid_is_valid, GID_FMT, "_GID");
1056
1057 IOVEC_ADD_STRING_FIELD(iovec, n, c->comm, "_COMM"); /* At most TASK_COMM_LENGTH (16 bytes) */
1058 IOVEC_ADD_STRING_FIELD(iovec, n, c->exe, "_EXE"); /* A path, so at most PATH_MAX (4096 bytes) */
1059
1060 if (c->cmdline)
1061 /* At most _SC_ARG_MAX (2MB usually), which is too much to put on stack.
1062 * Let's use a heap allocation for this one. */
1063 cmdline1 = set_iovec_string_field(iovec, &n, "_CMDLINE=", c->cmdline);
1064
1065 IOVEC_ADD_STRING_FIELD(iovec, n, c->capeff, "_CAP_EFFECTIVE"); /* Read from /proc/.../status */
1066 IOVEC_ADD_SIZED_FIELD(iovec, n, c->label, c->label_size, "_SELINUX_CONTEXT");
1067 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->auditid, uint32_t, audit_session_is_valid, "%" PRIu32, "_AUDIT_SESSION");
1068 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->loginuid, uid_t, uid_is_valid, UID_FMT, "_AUDIT_LOGINUID");
1069
1070 IOVEC_ADD_STRING_FIELD(iovec, n, c->cgroup, "_SYSTEMD_CGROUP"); /* A path */
1071 IOVEC_ADD_STRING_FIELD(iovec, n, c->session, "_SYSTEMD_SESSION");
1072 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->owner_uid, uid_t, uid_is_valid, UID_FMT, "_SYSTEMD_OWNER_UID");
1073 IOVEC_ADD_STRING_FIELD(iovec, n, c->unit, "_SYSTEMD_UNIT"); /* Unit names are bounded by UNIT_NAME_MAX */
1074 IOVEC_ADD_STRING_FIELD(iovec, n, c->user_unit, "_SYSTEMD_USER_UNIT");
1075 IOVEC_ADD_STRING_FIELD(iovec, n, c->slice, "_SYSTEMD_SLICE");
1076 IOVEC_ADD_STRING_FIELD(iovec, n, c->user_slice, "_SYSTEMD_USER_SLICE");
1077
1078 IOVEC_ADD_ID128_FIELD(iovec, n, c->invocation_id, "_SYSTEMD_INVOCATION_ID");
1079
1080 if (c->extra_fields_n_iovec > 0) {
1081 memcpy(iovec + n, c->extra_fields_iovec, c->extra_fields_n_iovec * sizeof(struct iovec));
1082 n += c->extra_fields_n_iovec;
1083 }
1084 }
1085
1086 assert(n <= m);
1087
1088 if (pid_is_valid(object_pid) && client_context_get(s, object_pid, NULL, NULL, 0, NULL, &o) >= 0) {
1089
1090 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->pid, pid_t, pid_is_valid, PID_FMT, "OBJECT_PID");
1091 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->uid, uid_t, uid_is_valid, UID_FMT, "OBJECT_UID");
1092 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->gid, gid_t, gid_is_valid, GID_FMT, "OBJECT_GID");
1093
1094 /* See above for size limits, only ->cmdline may be large, so use a heap allocation for it. */
1095 IOVEC_ADD_STRING_FIELD(iovec, n, o->comm, "OBJECT_COMM");
1096 IOVEC_ADD_STRING_FIELD(iovec, n, o->exe, "OBJECT_EXE");
1097 if (o->cmdline)
1098 cmdline2 = set_iovec_string_field(iovec, &n, "OBJECT_CMDLINE=", o->cmdline);
1099
1100 IOVEC_ADD_STRING_FIELD(iovec, n, o->capeff, "OBJECT_CAP_EFFECTIVE");
1101 IOVEC_ADD_SIZED_FIELD(iovec, n, o->label, o->label_size, "OBJECT_SELINUX_CONTEXT");
1102 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->auditid, uint32_t, audit_session_is_valid, "%" PRIu32, "OBJECT_AUDIT_SESSION");
1103 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->loginuid, uid_t, uid_is_valid, UID_FMT, "OBJECT_AUDIT_LOGINUID");
1104
1105 IOVEC_ADD_STRING_FIELD(iovec, n, o->cgroup, "OBJECT_SYSTEMD_CGROUP");
1106 IOVEC_ADD_STRING_FIELD(iovec, n, o->session, "OBJECT_SYSTEMD_SESSION");
1107 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->owner_uid, uid_t, uid_is_valid, UID_FMT, "OBJECT_SYSTEMD_OWNER_UID");
1108 IOVEC_ADD_STRING_FIELD(iovec, n, o->unit, "OBJECT_SYSTEMD_UNIT");
1109 IOVEC_ADD_STRING_FIELD(iovec, n, o->user_unit, "OBJECT_SYSTEMD_USER_UNIT");
1110 IOVEC_ADD_STRING_FIELD(iovec, n, o->slice, "OBJECT_SYSTEMD_SLICE");
1111 IOVEC_ADD_STRING_FIELD(iovec, n, o->user_slice, "OBJECT_SYSTEMD_USER_SLICE");
1112
1113 IOVEC_ADD_ID128_FIELD(iovec, n, o->invocation_id, "OBJECT_SYSTEMD_INVOCATION_ID=");
1114 }
1115
1116 assert(n <= m);
1117
1118 if (tv) {
1119 sprintf(source_time, "_SOURCE_REALTIME_TIMESTAMP=" USEC_FMT, timeval_load(tv));
1120 iovec[n++] = IOVEC_MAKE_STRING(source_time);
1121 }
1122
1123 /* Note that strictly speaking storing the boot id here is
1124 * redundant since the entry includes this in-line
1125 * anyway. However, we need this indexed, too. */
1126 if (!isempty(s->boot_id_field))
1127 iovec[n++] = IOVEC_MAKE_STRING(s->boot_id_field);
1128
1129 if (!isempty(s->machine_id_field))
1130 iovec[n++] = IOVEC_MAKE_STRING(s->machine_id_field);
1131
1132 if (!isempty(s->hostname_field))
1133 iovec[n++] = IOVEC_MAKE_STRING(s->hostname_field);
1134
1135 if (!isempty(s->namespace_field))
1136 iovec[n++] = IOVEC_MAKE_STRING(s->namespace_field);
1137
1138 iovec[n++] = in_initrd() ? IOVEC_MAKE_STRING("_RUNTIME_SCOPE=initrd") : IOVEC_MAKE_STRING("_RUNTIME_SCOPE=system");
1139 assert(n <= m);
1140
1141 if (s->split_mode == SPLIT_UID && c && uid_is_valid(c->uid))
1142 /* Split up strictly by (non-root) UID */
1143 journal_uid = c->uid;
1144 else if (s->split_mode == SPLIT_LOGIN && c && c->uid > 0 && uid_is_valid(c->owner_uid))
1145 /* Split up by login UIDs. We do this only if the
1146 * realuid is not root, in order not to accidentally
1147 * leak privileged information to the user that is
1148 * logged by a privileged process that is part of an
1149 * unprivileged session. */
1150 journal_uid = c->owner_uid;
1151 else
1152 journal_uid = 0;
1153
1154 server_write_to_journal(s, journal_uid, iovec, n, priority);
1155 }
1156
1157 void server_driver_message(Server *s, pid_t object_pid, const char *message_id, const char *format, ...) {
1158
1159 struct iovec *iovec;
1160 size_t n = 0, k, m;
1161 va_list ap;
1162 int r;
1163
1164 assert(s);
1165 assert(format);
1166
1167 m = N_IOVEC_META_FIELDS + 5 + N_IOVEC_PAYLOAD_FIELDS + client_context_extra_fields_n_iovec(s->my_context) + N_IOVEC_OBJECT_FIELDS;
1168 iovec = newa(struct iovec, m);
1169
1170 assert_cc(3 == LOG_FAC(LOG_DAEMON));
1171 iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_FACILITY=3");
1172 iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_IDENTIFIER=systemd-journald");
1173
1174 iovec[n++] = IOVEC_MAKE_STRING("_TRANSPORT=driver");
1175 assert_cc(6 == LOG_INFO);
1176 iovec[n++] = IOVEC_MAKE_STRING("PRIORITY=6");
1177
1178 if (message_id)
1179 iovec[n++] = IOVEC_MAKE_STRING(message_id);
1180 k = n;
1181
1182 va_start(ap, format);
1183 r = log_format_iovec(iovec, m, &n, false, 0, format, ap);
1184 /* Error handling below */
1185 va_end(ap);
1186
1187 if (r >= 0)
1188 server_dispatch_message_real(s, iovec, n, m, s->my_context, /* tv= */ NULL, LOG_INFO, object_pid);
1189
1190 while (k < n)
1191 free(iovec[k++].iov_base);
1192
1193 if (r < 0) {
1194 /* We failed to format the message. Emit a warning instead. */
1195 char buf[LINE_MAX];
1196
1197 errno = -r;
1198 xsprintf(buf, "MESSAGE=Entry printing failed: %m");
1199
1200 n = 3;
1201 iovec[n++] = IOVEC_MAKE_STRING("PRIORITY=4");
1202 iovec[n++] = IOVEC_MAKE_STRING(buf);
1203 server_dispatch_message_real(s, iovec, n, m, s->my_context, /* tv= */ NULL, LOG_INFO, object_pid);
1204 }
1205 }
1206
1207 void server_dispatch_message(
1208 Server *s,
1209 struct iovec *iovec, size_t n, size_t m,
1210 ClientContext *c,
1211 const struct timeval *tv,
1212 int priority,
1213 pid_t object_pid) {
1214
1215 uint64_t available = 0;
1216 int rl;
1217
1218 assert(s);
1219 assert(iovec || n == 0);
1220
1221 if (n == 0)
1222 return;
1223
1224 if (LOG_PRI(priority) > s->max_level_store)
1225 return;
1226
1227 /* Stop early in case the information will not be stored
1228 * in a journal. */
1229 if (s->storage == STORAGE_NONE)
1230 return;
1231
1232 if (c && c->unit) {
1233 (void) server_determine_space(s, &available, /* limit= */ NULL);
1234
1235 rl = journal_ratelimit_test(s->ratelimit, c->unit, c->log_ratelimit_interval, c->log_ratelimit_burst, priority & LOG_PRIMASK, available);
1236 if (rl == 0)
1237 return;
1238
1239 /* Write a suppression message if we suppressed something */
1240 if (rl > 1)
1241 server_driver_message(s, c->pid,
1242 "MESSAGE_ID=" SD_MESSAGE_JOURNAL_DROPPED_STR,
1243 LOG_MESSAGE("Suppressed %i messages from %s", rl - 1, c->unit),
1244 "N_DROPPED=%i", rl - 1,
1245 NULL);
1246 }
1247
1248 server_dispatch_message_real(s, iovec, n, m, c, tv, priority, object_pid);
1249 }
1250
1251 int server_flush_to_var(Server *s, bool require_flag_file) {
1252 sd_journal *j = NULL;
1253 const char *fn;
1254 unsigned n = 0;
1255 usec_t start;
1256 int r, k;
1257
1258 assert(s);
1259
1260 if (!IN_SET(s->storage, STORAGE_AUTO, STORAGE_PERSISTENT))
1261 return 0;
1262
1263 if (s->namespace) /* Flushing concept does not exist for namespace instances */
1264 return 0;
1265
1266 if (!s->runtime_journal) /* Nothing to flush? */
1267 return 0;
1268
1269 if (require_flag_file && !server_flushed_flag_is_set(s))
1270 return 0;
1271
1272 (void) server_system_journal_open(s, /* flush_requested=*/ true, /* relinquish_requested= */ false);
1273
1274 if (!s->system_journal)
1275 return 0;
1276
1277 log_debug("Flushing to %s...", s->system_storage.path);
1278
1279 start = now(CLOCK_MONOTONIC);
1280
1281 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
1282 if (r < 0)
1283 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT,
1284 "Failed to read runtime journal: %m");
1285
1286 sd_journal_set_data_threshold(j, 0);
1287
1288 SD_JOURNAL_FOREACH(j) {
1289 Object *o = NULL;
1290 JournalFile *f;
1291
1292 f = j->current_file;
1293 assert(f && f->current_offset > 0);
1294
1295 n++;
1296
1297 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1298 if (r < 0) {
1299 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Can't read entry: %m");
1300 goto finish;
1301 }
1302
1303 r = journal_file_copy_entry(
1304 f,
1305 s->system_journal,
1306 o,
1307 f->current_offset,
1308 &s->seqnum->seqnum,
1309 &s->seqnum->id);
1310 if (r >= 0)
1311 continue;
1312
1313 if (!shall_try_append_again(s->system_journal, r)) {
1314 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Can't write entry: %m");
1315 goto finish;
1316 }
1317
1318 log_ratelimit_info(JOURNAL_LOG_RATELIMIT, "Rotating system journal.");
1319
1320 server_rotate(s);
1321 server_vacuum(s, false);
1322
1323 if (!s->system_journal) {
1324 log_ratelimit_notice(JOURNAL_LOG_RATELIMIT,
1325 "Didn't flush runtime journal since rotation of system journal wasn't successful.");
1326 r = -EIO;
1327 goto finish;
1328 }
1329
1330 log_debug("Retrying write.");
1331 r = journal_file_copy_entry(
1332 f,
1333 s->system_journal,
1334 o,
1335 f->current_offset,
1336 &s->seqnum->seqnum,
1337 &s->seqnum->id);
1338 if (r < 0) {
1339 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Can't write entry: %m");
1340 goto finish;
1341 }
1342 }
1343
1344 r = 0;
1345
1346 finish:
1347 if (s->system_journal)
1348 journal_file_post_change(s->system_journal);
1349
1350 s->runtime_journal = journal_file_offline_close(s->runtime_journal);
1351
1352 if (r >= 0)
1353 (void) rm_rf(s->runtime_storage.path, REMOVE_ROOT);
1354
1355 sd_journal_close(j);
1356
1357 server_driver_message(s, 0, NULL,
1358 LOG_MESSAGE("Time spent on flushing to %s is %s for %u entries.",
1359 s->system_storage.path,
1360 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0),
1361 n),
1362 NULL);
1363
1364 fn = strjoina(s->runtime_directory, "/flushed");
1365 k = touch(fn);
1366 if (k < 0)
1367 log_ratelimit_warning_errno(k, JOURNAL_LOG_RATELIMIT,
1368 "Failed to touch %s, ignoring: %m", fn);
1369
1370 server_refresh_idle_timer(s);
1371 return r;
1372 }
1373
1374 static int server_relinquish_var(Server *s) {
1375 const char *fn;
1376 assert(s);
1377
1378 if (s->storage == STORAGE_NONE)
1379 return 0;
1380
1381 if (s->namespace) /* Concept does not exist for namespaced instances */
1382 return -EOPNOTSUPP;
1383
1384 if (s->runtime_journal && !s->system_journal)
1385 return 0;
1386
1387 log_debug("Relinquishing %s...", s->system_storage.path);
1388
1389 (void) server_system_journal_open(s, /* flush_requested */ false, /* relinquish_requested=*/ true);
1390
1391 s->system_journal = journal_file_offline_close(s->system_journal);
1392 ordered_hashmap_clear_with_destructor(s->user_journals, journal_file_offline_close);
1393 set_clear_with_destructor(s->deferred_closes, journal_file_offline_close);
1394
1395 fn = strjoina(s->runtime_directory, "/flushed");
1396 if (unlink(fn) < 0 && errno != ENOENT)
1397 log_ratelimit_warning_errno(errno, JOURNAL_LOG_RATELIMIT,
1398 "Failed to unlink %s, ignoring: %m", fn);
1399
1400 server_refresh_idle_timer(s);
1401 return 0;
1402 }
1403
1404 int server_process_datagram(
1405 sd_event_source *es,
1406 int fd,
1407 uint32_t revents,
1408 void *userdata) {
1409
1410 size_t label_len = 0, m;
1411 Server *s = ASSERT_PTR(userdata);
1412 struct ucred *ucred = NULL;
1413 struct timeval tv_buf, *tv = NULL;
1414 struct cmsghdr *cmsg;
1415 char *label = NULL;
1416 struct iovec iovec;
1417 ssize_t n;
1418 int *fds = NULL, v = 0;
1419 size_t n_fds = 0;
1420
1421 /* We use NAME_MAX space for the SELinux label here. The kernel currently enforces no limit, but
1422 * according to suggestions from the SELinux people this will change and it will probably be
1423 * identical to NAME_MAX. For now we use that, but this should be updated one day when the final
1424 * limit is known.
1425 *
1426 * Here, we need to explicitly initialize the buffer with zero, as glibc has a bug in
1427 * __convert_scm_timestamps(), which assumes the buffer is initialized. See #20741. */
1428 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) +
1429 CMSG_SPACE_TIMEVAL +
1430 CMSG_SPACE(sizeof(int)) + /* fd */
1431 CMSG_SPACE(NAME_MAX) /* selinux label */) control = {};
1432
1433 union sockaddr_union sa = {};
1434
1435 struct msghdr msghdr = {
1436 .msg_iov = &iovec,
1437 .msg_iovlen = 1,
1438 .msg_control = &control,
1439 .msg_controllen = sizeof(control),
1440 .msg_name = &sa,
1441 .msg_namelen = sizeof(sa),
1442 };
1443
1444 assert(fd == s->native_fd || fd == s->syslog_fd || fd == s->audit_fd);
1445
1446 if (revents != EPOLLIN)
1447 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1448 "Got invalid event from epoll for datagram fd: %" PRIx32,
1449 revents);
1450
1451 /* Try to get the right size, if we can. (Not all sockets support SIOCINQ, hence we just try, but don't rely on
1452 * it.) */
1453 (void) ioctl(fd, SIOCINQ, &v);
1454
1455 /* Fix it up, if it is too small. We use the same fixed value as auditd here. Awful! */
1456 m = PAGE_ALIGN(MAX3((size_t) v + 1,
1457 (size_t) LINE_MAX,
1458 ALIGN(sizeof(struct nlmsghdr)) + ALIGN((size_t) MAX_AUDIT_MESSAGE_LENGTH)) + 1);
1459
1460 if (!GREEDY_REALLOC(s->buffer, m))
1461 return log_oom();
1462
1463 iovec = IOVEC_MAKE(s->buffer, MALLOC_ELEMENTSOF(s->buffer) - 1); /* Leave room for trailing NUL we add later */
1464
1465 n = recvmsg_safe(fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
1466 if (n < 0) {
1467 if (ERRNO_IS_TRANSIENT(n))
1468 return 0;
1469 if (n == -EXFULL) {
1470 log_ratelimit_warning(JOURNAL_LOG_RATELIMIT,
1471 "Got message with truncated control data (too many fds sent?), ignoring.");
1472 return 0;
1473 }
1474 return log_ratelimit_error_errno(n, JOURNAL_LOG_RATELIMIT, "recvmsg() failed: %m");
1475 }
1476
1477 CMSG_FOREACH(cmsg, &msghdr)
1478 if (cmsg->cmsg_level == SOL_SOCKET &&
1479 cmsg->cmsg_type == SCM_CREDENTIALS &&
1480 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
1481 assert(!ucred);
1482 ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
1483 } else if (cmsg->cmsg_level == SOL_SOCKET &&
1484 cmsg->cmsg_type == SCM_SECURITY) {
1485 assert(!label);
1486 label = CMSG_TYPED_DATA(cmsg, char);
1487 label_len = cmsg->cmsg_len - CMSG_LEN(0);
1488 } else if (cmsg->cmsg_level == SOL_SOCKET &&
1489 cmsg->cmsg_type == SCM_TIMESTAMP &&
1490 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval))) {
1491 assert(!tv);
1492 tv = memcpy(&tv_buf, CMSG_DATA(cmsg), sizeof(struct timeval));
1493 } else if (cmsg->cmsg_level == SOL_SOCKET &&
1494 cmsg->cmsg_type == SCM_RIGHTS) {
1495 assert(!fds);
1496 fds = CMSG_TYPED_DATA(cmsg, int);
1497 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1498 }
1499
1500 /* And a trailing NUL, just in case */
1501 s->buffer[n] = 0;
1502
1503 if (fd == s->syslog_fd) {
1504 if (n > 0 && n_fds == 0)
1505 server_process_syslog_message(s, s->buffer, n, ucred, tv, label, label_len);
1506 else if (n_fds > 0)
1507 log_ratelimit_warning(JOURNAL_LOG_RATELIMIT,
1508 "Got file descriptors via syslog socket. Ignoring.");
1509
1510 } else if (fd == s->native_fd) {
1511 if (n > 0 && n_fds == 0)
1512 server_process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
1513 else if (n == 0 && n_fds == 1)
1514 server_process_native_file(s, fds[0], ucred, tv, label, label_len);
1515 else if (n_fds > 0)
1516 log_ratelimit_warning(JOURNAL_LOG_RATELIMIT,
1517 "Got too many file descriptors via native socket. Ignoring.");
1518
1519 } else {
1520 assert(fd == s->audit_fd);
1521
1522 if (n > 0 && n_fds == 0)
1523 server_process_audit_message(s, s->buffer, n, ucred, &sa, msghdr.msg_namelen);
1524 else if (n_fds > 0)
1525 log_ratelimit_warning(JOURNAL_LOG_RATELIMIT,
1526 "Got file descriptors via audit socket. Ignoring.");
1527 }
1528
1529 close_many(fds, n_fds);
1530
1531 server_refresh_idle_timer(s);
1532 return 0;
1533 }
1534
1535 static void server_full_flush(Server *s) {
1536 assert(s);
1537
1538 (void) server_flush_to_var(s, false);
1539 server_sync(s);
1540 server_vacuum(s, false);
1541
1542 server_space_usage_message(s, NULL);
1543
1544 server_refresh_idle_timer(s);
1545 }
1546
1547 static int dispatch_sigusr1(sd_event_source *es, const struct signalfd_siginfo *si, void *userdata) {
1548 Server *s = ASSERT_PTR(userdata);
1549
1550 if (s->namespace) {
1551 log_error("Received SIGUSR1 signal from PID %u, but flushing runtime journals not supported for namespaced instances.", si->ssi_pid);
1552 return 0;
1553 }
1554
1555 log_info("Received SIGUSR1 signal from PID %u, as request to flush runtime journal.", si->ssi_pid);
1556 server_full_flush(s);
1557
1558 return 0;
1559 }
1560
1561 static void server_full_rotate(Server *s) {
1562 const char *fn;
1563 int r;
1564
1565 assert(s);
1566
1567 server_rotate(s);
1568 server_vacuum(s, true);
1569
1570 if (s->system_journal)
1571 patch_min_use(&s->system_storage);
1572 if (s->runtime_journal)
1573 patch_min_use(&s->runtime_storage);
1574
1575 /* Let clients know when the most recent rotation happened. */
1576 fn = strjoina(s->runtime_directory, "/rotated");
1577 r = write_timestamp_file_atomic(fn, now(CLOCK_MONOTONIC));
1578 if (r < 0)
1579 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
1580 "Failed to write %s, ignoring: %m", fn);
1581 }
1582
1583 static int dispatch_sigusr2(sd_event_source *es, const struct signalfd_siginfo *si, void *userdata) {
1584 Server *s = ASSERT_PTR(userdata);
1585
1586 log_info("Received SIGUSR2 signal from PID %u, as request to rotate journal, rotating.", si->ssi_pid);
1587 server_full_rotate(s);
1588
1589 return 0;
1590 }
1591
1592 static int dispatch_sigterm(sd_event_source *es, const struct signalfd_siginfo *si, void *userdata) {
1593 _cleanup_(sd_event_source_disable_unrefp) sd_event_source *news = NULL;
1594 Server *s = ASSERT_PTR(userdata);
1595 int r;
1596
1597 log_received_signal(LOG_INFO, si);
1598
1599 (void) sd_event_source_set_enabled(es, SD_EVENT_OFF); /* Make sure this handler is called at most once */
1600
1601 /* So on one hand we want to ensure that SIGTERMs are definitely handled in appropriate, bounded
1602 * time. On the other hand we want that everything pending is first comprehensively processed and
1603 * written to disk. These goals are incompatible, hence we try to find a middle ground: we'll process
1604 * SIGTERM with high priority, but from the handler (this one right here) we'll install two new event
1605 * sources: one low priority idle one that will issue the exit once everything else is processed (and
1606 * which is hopefully the regular, clean codepath); and one high priority timer that acts as safety
1607 * net: if our idle handler isn't run within 10s, we'll exit anyway.
1608 *
1609 * TLDR: we'll exit either when everything is processed, or after 10s max, depending on what happens
1610 * first.
1611 *
1612 * Note that exiting before the idle event is hit doesn't typically mean that we lose any data, as
1613 * messages will remain queued in the sockets they came in from, and thus can be processed when we
1614 * start up next – unless we are going down for the final system shutdown, in which case everything
1615 * is lost. */
1616
1617 r = sd_event_add_defer(s->event, &news, NULL, NULL); /* NULL handler means → exit when triggered */
1618 if (r < 0) {
1619 log_error_errno(r, "Failed to allocate exit idle event handler: %m");
1620 goto fail;
1621 }
1622
1623 (void) sd_event_source_set_description(news, "exit-idle");
1624
1625 /* Run everything relevant before this. */
1626 r = sd_event_source_set_priority(news, SD_EVENT_PRIORITY_NORMAL+20);
1627 if (r < 0) {
1628 log_error_errno(r, "Failed to adjust priority of exit idle event handler: %m");
1629 goto fail;
1630 }
1631
1632 /* Give up ownership, so that this event source is freed automatically when the event loop is freed. */
1633 r = sd_event_source_set_floating(news, true);
1634 if (r < 0) {
1635 log_error_errno(r, "Failed to make exit idle event handler floating: %m");
1636 goto fail;
1637 }
1638
1639 news = sd_event_source_unref(news);
1640
1641 r = sd_event_add_time_relative(s->event, &news, CLOCK_MONOTONIC, 10 * USEC_PER_SEC, 0, NULL, NULL);
1642 if (r < 0) {
1643 log_error_errno(r, "Failed to allocate exit timeout event handler: %m");
1644 goto fail;
1645 }
1646
1647 (void) sd_event_source_set_description(news, "exit-timeout");
1648
1649 r = sd_event_source_set_priority(news, SD_EVENT_PRIORITY_IMPORTANT-20); /* This is a safety net, with highest priority */
1650 if (r < 0) {
1651 log_error_errno(r, "Failed to adjust priority of exit timeout event handler: %m");
1652 goto fail;
1653 }
1654
1655 r = sd_event_source_set_floating(news, true);
1656 if (r < 0) {
1657 log_error_errno(r, "Failed to make exit timeout event handler floating: %m");
1658 goto fail;
1659 }
1660
1661 news = sd_event_source_unref(news);
1662
1663 log_debug("Exit event sources are now pending.");
1664 return 0;
1665
1666 fail:
1667 sd_event_exit(s->event, 0);
1668 return 0;
1669 }
1670
1671 static void server_full_sync(Server *s) {
1672 const char *fn;
1673 int r;
1674
1675 assert(s);
1676
1677 server_sync(s);
1678
1679 /* Let clients know when the most recent sync happened. */
1680 fn = strjoina(s->runtime_directory, "/synced");
1681 r = write_timestamp_file_atomic(fn, now(CLOCK_MONOTONIC));
1682 if (r < 0)
1683 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
1684 "Failed to write %s, ignoring: %m", fn);
1685
1686 return;
1687 }
1688
1689 static int dispatch_sigrtmin1(sd_event_source *es, const struct signalfd_siginfo *si, void *userdata) {
1690 Server *s = ASSERT_PTR(userdata);
1691
1692 log_debug("Received SIGRTMIN1 signal from PID %u, as request to sync.", si->ssi_pid);
1693 server_full_sync(s);
1694
1695 return 0;
1696 }
1697
1698 static int server_setup_signals(Server *s) {
1699 int r;
1700
1701 assert(s);
1702
1703 assert_se(sigprocmask_many(SIG_SETMASK, NULL, SIGINT, SIGTERM, SIGUSR1, SIGUSR2, SIGRTMIN+1, SIGRTMIN+18, -1) >= 0);
1704
1705 r = sd_event_add_signal(s->event, &s->sigusr1_event_source, SIGUSR1, dispatch_sigusr1, s);
1706 if (r < 0)
1707 return r;
1708
1709 r = sd_event_add_signal(s->event, &s->sigusr2_event_source, SIGUSR2, dispatch_sigusr2, s);
1710 if (r < 0)
1711 return r;
1712
1713 r = sd_event_add_signal(s->event, &s->sigterm_event_source, SIGTERM, dispatch_sigterm, s);
1714 if (r < 0)
1715 return r;
1716
1717 /* Let's process SIGTERM early, so that we definitely react to it */
1718 r = sd_event_source_set_priority(s->sigterm_event_source, SD_EVENT_PRIORITY_IMPORTANT-10);
1719 if (r < 0)
1720 return r;
1721
1722 /* When journald is invoked on the terminal (when debugging), it's useful if C-c is handled
1723 * equivalent to SIGTERM. */
1724 r = sd_event_add_signal(s->event, &s->sigint_event_source, SIGINT, dispatch_sigterm, s);
1725 if (r < 0)
1726 return r;
1727
1728 r = sd_event_source_set_priority(s->sigint_event_source, SD_EVENT_PRIORITY_IMPORTANT-10);
1729 if (r < 0)
1730 return r;
1731
1732 /* SIGRTMIN+1 causes an immediate sync. We process this very late, so that everything else queued at
1733 * this point is really written to disk. Clients can watch /run/systemd/journal/synced with inotify
1734 * until its mtime changes to see when a sync happened. */
1735 r = sd_event_add_signal(s->event, &s->sigrtmin1_event_source, SIGRTMIN+1, dispatch_sigrtmin1, s);
1736 if (r < 0)
1737 return r;
1738
1739 r = sd_event_source_set_priority(s->sigrtmin1_event_source, SD_EVENT_PRIORITY_NORMAL+15);
1740 if (r < 0)
1741 return r;
1742
1743 r = sd_event_add_signal(s->event, NULL, SIGRTMIN+18, sigrtmin18_handler, &s->sigrtmin18_info);
1744 if (r < 0)
1745 return r;
1746
1747 return 0;
1748 }
1749
1750 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
1751 Server *s = ASSERT_PTR(data);
1752 int r;
1753
1754 if (proc_cmdline_key_streq(key, "systemd.journald.forward_to_syslog")) {
1755
1756 r = value ? parse_boolean(value) : true;
1757 if (r < 0)
1758 log_warning("Failed to parse forward to syslog switch \"%s\". Ignoring.", value);
1759 else
1760 s->forward_to_syslog = r;
1761
1762 } else if (proc_cmdline_key_streq(key, "systemd.journald.forward_to_kmsg")) {
1763
1764 r = value ? parse_boolean(value) : true;
1765 if (r < 0)
1766 log_warning("Failed to parse forward to kmsg switch \"%s\". Ignoring.", value);
1767 else
1768 s->forward_to_kmsg = r;
1769
1770 } else if (proc_cmdline_key_streq(key, "systemd.journald.forward_to_console")) {
1771
1772 r = value ? parse_boolean(value) : true;
1773 if (r < 0)
1774 log_warning("Failed to parse forward to console switch \"%s\". Ignoring.", value);
1775 else
1776 s->forward_to_console = r;
1777
1778 } else if (proc_cmdline_key_streq(key, "systemd.journald.forward_to_wall")) {
1779
1780 r = value ? parse_boolean(value) : true;
1781 if (r < 0)
1782 log_warning("Failed to parse forward to wall switch \"%s\". Ignoring.", value);
1783 else
1784 s->forward_to_wall = r;
1785
1786 } else if (proc_cmdline_key_streq(key, "systemd.journald.max_level_console")) {
1787
1788 if (proc_cmdline_value_missing(key, value))
1789 return 0;
1790
1791 r = log_level_from_string(value);
1792 if (r < 0)
1793 log_warning("Failed to parse max level console value \"%s\". Ignoring.", value);
1794 else
1795 s->max_level_console = r;
1796
1797 } else if (proc_cmdline_key_streq(key, "systemd.journald.max_level_store")) {
1798
1799 if (proc_cmdline_value_missing(key, value))
1800 return 0;
1801
1802 r = log_level_from_string(value);
1803 if (r < 0)
1804 log_warning("Failed to parse max level store value \"%s\". Ignoring.", value);
1805 else
1806 s->max_level_store = r;
1807
1808 } else if (proc_cmdline_key_streq(key, "systemd.journald.max_level_syslog")) {
1809
1810 if (proc_cmdline_value_missing(key, value))
1811 return 0;
1812
1813 r = log_level_from_string(value);
1814 if (r < 0)
1815 log_warning("Failed to parse max level syslog value \"%s\". Ignoring.", value);
1816 else
1817 s->max_level_syslog = r;
1818
1819 } else if (proc_cmdline_key_streq(key, "systemd.journald.max_level_kmsg")) {
1820
1821 if (proc_cmdline_value_missing(key, value))
1822 return 0;
1823
1824 r = log_level_from_string(value);
1825 if (r < 0)
1826 log_warning("Failed to parse max level kmsg value \"%s\". Ignoring.", value);
1827 else
1828 s->max_level_kmsg = r;
1829
1830 } else if (proc_cmdline_key_streq(key, "systemd.journald.max_level_wall")) {
1831
1832 if (proc_cmdline_value_missing(key, value))
1833 return 0;
1834
1835 r = log_level_from_string(value);
1836 if (r < 0)
1837 log_warning("Failed to parse max level wall value \"%s\". Ignoring.", value);
1838 else
1839 s->max_level_wall = r;
1840
1841 } else if (startswith(key, "systemd.journald"))
1842 log_warning("Unknown journald kernel command line option \"%s\". Ignoring.", key);
1843
1844 /* do not warn about state here, since probably systemd already did */
1845 return 0;
1846 }
1847
1848 static int server_parse_config_file(Server *s) {
1849 const char *conf_file = "journald.conf";
1850
1851 assert(s);
1852
1853 if (s->namespace)
1854 conf_file = strjoina("journald@", s->namespace, ".conf");
1855
1856 return config_parse_config_file(conf_file, "Journal\0",
1857 config_item_perf_lookup, journald_gperf_lookup,
1858 CONFIG_PARSE_WARN, s);
1859 }
1860
1861 static int server_dispatch_sync(sd_event_source *es, usec_t t, void *userdata) {
1862 Server *s = ASSERT_PTR(userdata);
1863
1864 server_sync(s);
1865 return 0;
1866 }
1867
1868 int server_schedule_sync(Server *s, int priority) {
1869 int r;
1870
1871 assert(s);
1872
1873 if (priority <= LOG_CRIT) {
1874 /* Immediately sync to disk when this is of priority CRIT, ALERT, EMERG */
1875 server_sync(s);
1876 return 0;
1877 }
1878
1879 if (s->sync_scheduled)
1880 return 0;
1881
1882 if (s->sync_interval_usec > 0) {
1883
1884 if (!s->sync_event_source) {
1885 r = sd_event_add_time_relative(
1886 s->event,
1887 &s->sync_event_source,
1888 CLOCK_MONOTONIC,
1889 s->sync_interval_usec, 0,
1890 server_dispatch_sync, s);
1891 if (r < 0)
1892 return r;
1893
1894 r = sd_event_source_set_priority(s->sync_event_source, SD_EVENT_PRIORITY_IMPORTANT);
1895 } else {
1896 r = sd_event_source_set_time_relative(s->sync_event_source, s->sync_interval_usec);
1897 if (r < 0)
1898 return r;
1899
1900 r = sd_event_source_set_enabled(s->sync_event_source, SD_EVENT_ONESHOT);
1901 }
1902 if (r < 0)
1903 return r;
1904
1905 s->sync_scheduled = true;
1906 }
1907
1908 return 0;
1909 }
1910
1911 static int dispatch_hostname_change(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
1912 Server *s = ASSERT_PTR(userdata);
1913
1914 server_cache_hostname(s);
1915 return 0;
1916 }
1917
1918 static int server_open_hostname(Server *s) {
1919 int r;
1920
1921 assert(s);
1922
1923 s->hostname_fd = open("/proc/sys/kernel/hostname",
1924 O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1925 if (s->hostname_fd < 0)
1926 return log_error_errno(errno, "Failed to open /proc/sys/kernel/hostname: %m");
1927
1928 r = sd_event_add_io(s->event, &s->hostname_event_source, s->hostname_fd, 0, dispatch_hostname_change, s);
1929 if (r < 0) {
1930 /* kernels prior to 3.2 don't support polling this file. Ignore
1931 * the failure. */
1932 if (r == -EPERM) {
1933 log_warning_errno(r, "Failed to register hostname fd in event loop, ignoring: %m");
1934 s->hostname_fd = safe_close(s->hostname_fd);
1935 return 0;
1936 }
1937
1938 return log_error_errno(r, "Failed to register hostname fd in event loop: %m");
1939 }
1940
1941 r = sd_event_source_set_priority(s->hostname_event_source, SD_EVENT_PRIORITY_IMPORTANT-10);
1942 if (r < 0)
1943 return log_error_errno(r, "Failed to adjust priority of hostname event source: %m");
1944
1945 return 0;
1946 }
1947
1948 static int dispatch_notify_event(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
1949 Server *s = ASSERT_PTR(userdata);
1950 int r;
1951
1952 assert(s->notify_event_source == es);
1953 assert(s->notify_fd == fd);
1954
1955 /* The $NOTIFY_SOCKET is writable again, now send exactly one
1956 * message on it. Either it's the watchdog event, the initial
1957 * READY=1 event or an stdout stream event. If there's nothing
1958 * to write anymore, turn our event source off. The next time
1959 * there's something to send it will be turned on again. */
1960
1961 if (!s->sent_notify_ready) {
1962 static const char p[] = "READY=1\n"
1963 "STATUS=Processing requests...";
1964
1965 if (send(s->notify_fd, p, strlen(p), MSG_DONTWAIT) < 0) {
1966 if (errno == EAGAIN)
1967 return 0;
1968
1969 return log_error_errno(errno, "Failed to send READY=1 notification message: %m");
1970 }
1971
1972 s->sent_notify_ready = true;
1973 log_debug("Sent READY=1 notification.");
1974
1975 } else if (s->send_watchdog) {
1976 static const char p[] = "WATCHDOG=1";
1977
1978 if (send(s->notify_fd, p, strlen(p), MSG_DONTWAIT) < 0) {
1979 if (errno == EAGAIN)
1980 return 0;
1981
1982 return log_error_errno(errno, "Failed to send WATCHDOG=1 notification message: %m");
1983 }
1984
1985 s->send_watchdog = false;
1986 log_debug("Sent WATCHDOG=1 notification.");
1987
1988 } else if (s->stdout_streams_notify_queue)
1989 /* Dispatch one stream notification event */
1990 stdout_stream_send_notify(s->stdout_streams_notify_queue);
1991
1992 /* Leave us enabled if there's still more to do. */
1993 if (s->send_watchdog || s->stdout_streams_notify_queue)
1994 return 0;
1995
1996 /* There was nothing to do anymore, let's turn ourselves off. */
1997 r = sd_event_source_set_enabled(es, SD_EVENT_OFF);
1998 if (r < 0)
1999 return log_error_errno(r, "Failed to turn off notify event source: %m");
2000
2001 return 0;
2002 }
2003
2004 static int dispatch_watchdog(sd_event_source *es, uint64_t usec, void *userdata) {
2005 Server *s = ASSERT_PTR(userdata);
2006 int r;
2007
2008 s->send_watchdog = true;
2009
2010 r = sd_event_source_set_enabled(s->notify_event_source, SD_EVENT_ON);
2011 if (r < 0)
2012 log_warning_errno(r, "Failed to turn on notify event source: %m");
2013
2014 r = sd_event_source_set_time(s->watchdog_event_source, usec + s->watchdog_usec / 2);
2015 if (r < 0)
2016 return log_error_errno(r, "Failed to restart watchdog event source: %m");
2017
2018 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ON);
2019 if (r < 0)
2020 return log_error_errno(r, "Failed to enable watchdog event source: %m");
2021
2022 return 0;
2023 }
2024
2025 static int server_connect_notify(Server *s) {
2026 union sockaddr_union sa;
2027 socklen_t sa_len;
2028 const char *e;
2029 int r;
2030
2031 assert(s);
2032 assert(s->notify_fd < 0);
2033 assert(!s->notify_event_source);
2034
2035 /*
2036 * So here's the problem: we'd like to send notification messages to PID 1, but we cannot do that via
2037 * sd_notify(), since that's synchronous, and we might end up blocking on it. Specifically: given
2038 * that PID 1 might block on dbus-daemon during IPC, and dbus-daemon is logging to us, and might
2039 * hence block on us, we might end up in a deadlock if we block on sending PID 1 notification
2040 * messages — by generating a full blocking circle. To avoid this, let's create a non-blocking
2041 * socket, and connect it to the notification socket, and then wait for POLLOUT before we send
2042 * anything. This should efficiently avoid any deadlocks, as we'll never block on PID 1, hence PID 1
2043 * can safely block on dbus-daemon which can safely block on us again.
2044 *
2045 * Don't think that this issue is real? It is, see: https://github.com/systemd/systemd/issues/1505
2046 */
2047
2048 e = getenv("NOTIFY_SOCKET");
2049 if (!e)
2050 return 0;
2051
2052 r = sockaddr_un_set_path(&sa.un, e);
2053 if (r < 0)
2054 return log_error_errno(r, "NOTIFY_SOCKET set to invalid value '%s': %m", e);
2055 sa_len = r;
2056
2057 s->notify_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2058 if (s->notify_fd < 0)
2059 return log_error_errno(errno, "Failed to create notify socket: %m");
2060
2061 (void) fd_inc_sndbuf(s->notify_fd, NOTIFY_SNDBUF_SIZE);
2062
2063 r = connect(s->notify_fd, &sa.sa, sa_len);
2064 if (r < 0)
2065 return log_error_errno(errno, "Failed to connect to notify socket: %m");
2066
2067 r = sd_event_add_io(s->event, &s->notify_event_source, s->notify_fd, EPOLLOUT, dispatch_notify_event, s);
2068 if (r < 0)
2069 return log_error_errno(r, "Failed to watch notification socket: %m");
2070
2071 if (sd_watchdog_enabled(false, &s->watchdog_usec) > 0) {
2072 s->send_watchdog = true;
2073
2074 r = sd_event_add_time_relative(s->event, &s->watchdog_event_source, CLOCK_MONOTONIC, s->watchdog_usec/2, s->watchdog_usec/4, dispatch_watchdog, s);
2075 if (r < 0)
2076 return log_error_errno(r, "Failed to add watchdog time event: %m");
2077 }
2078
2079 /* This should fire pretty soon, which we'll use to send the READY=1 event. */
2080
2081 return 0;
2082 }
2083
2084 static int synchronize_second_half(sd_event_source *event_source, void *userdata) {
2085 Varlink *link = ASSERT_PTR(userdata);
2086 Server *s;
2087 int r;
2088
2089 assert_se(s = varlink_get_userdata(link));
2090
2091 /* This is the "second half" of the Synchronize() varlink method. This function is called as deferred
2092 * event source at a low priority to ensure the synchronization completes after all queued log
2093 * messages are processed. */
2094 server_full_sync(s);
2095
2096 /* Let's get rid of the event source now, by marking it as non-floating again. It then has no ref
2097 * anymore and is immediately destroyed after we return from this function, i.e. from this event
2098 * source handler at the end. */
2099 r = sd_event_source_set_floating(event_source, false);
2100 if (r < 0)
2101 return log_error_errno(r, "Failed to mark event source as non-floating: %m");
2102
2103 return varlink_reply(link, NULL);
2104 }
2105
2106 static void synchronize_destroy(void *userdata) {
2107 varlink_unref(userdata);
2108 }
2109
2110 static int vl_method_synchronize(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
2111 _cleanup_(sd_event_source_unrefp) sd_event_source *event_source = NULL;
2112 Server *s = ASSERT_PTR(userdata);
2113 int r;
2114
2115 assert(link);
2116
2117 if (json_variant_elements(parameters) > 0)
2118 return varlink_error_invalid_parameter(link, parameters);
2119
2120 log_info("Received client request to sync journal.");
2121
2122 /* We don't do the main work now, but instead enqueue a deferred event loop job which will do
2123 * it. That job is scheduled at low priority, so that we return from this method call only after all
2124 * queued but not processed log messages are written to disk, so that this method call returning can
2125 * be used as nice synchronization point. */
2126 r = sd_event_add_defer(s->event, &event_source, synchronize_second_half, link);
2127 if (r < 0)
2128 return log_error_errno(r, "Failed to allocate defer event source: %m");
2129
2130 r = sd_event_source_set_destroy_callback(event_source, synchronize_destroy);
2131 if (r < 0)
2132 return log_error_errno(r, "Failed to set event source destroy callback: %m");
2133
2134 varlink_ref(link); /* The varlink object is now left to the destroy callback to unref */
2135
2136 r = sd_event_source_set_priority(event_source, SD_EVENT_PRIORITY_NORMAL+15);
2137 if (r < 0)
2138 return log_error_errno(r, "Failed to set defer event source priority: %m");
2139
2140 /* Give up ownership of this event source. It will now be destroyed along with event loop itself,
2141 * unless it destroys itself earlier. */
2142 r = sd_event_source_set_floating(event_source, true);
2143 if (r < 0)
2144 return log_error_errno(r, "Failed to mark event source as floating: %m");
2145
2146 (void) sd_event_source_set_description(event_source, "deferred-sync");
2147
2148 return 0;
2149 }
2150
2151 static int vl_method_rotate(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
2152 Server *s = ASSERT_PTR(userdata);
2153
2154 assert(link);
2155
2156 if (json_variant_elements(parameters) > 0)
2157 return varlink_error_invalid_parameter(link, parameters);
2158
2159 log_info("Received client request to rotate journal, rotating.");
2160 server_full_rotate(s);
2161
2162 return varlink_reply(link, NULL);
2163 }
2164
2165 static int vl_method_flush_to_var(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
2166 Server *s = ASSERT_PTR(userdata);
2167
2168 assert(link);
2169
2170 if (json_variant_elements(parameters) > 0)
2171 return varlink_error_invalid_parameter(link, parameters);
2172 if (s->namespace)
2173 return varlink_error(link, "io.systemd.Journal.NotSupportedByNamespaces", NULL);
2174
2175 log_info("Received client request to flush runtime journal.");
2176 server_full_flush(s);
2177
2178 return varlink_reply(link, NULL);
2179 }
2180
2181 static int vl_method_relinquish_var(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
2182 Server *s = ASSERT_PTR(userdata);
2183
2184 assert(link);
2185
2186 if (json_variant_elements(parameters) > 0)
2187 return varlink_error_invalid_parameter(link, parameters);
2188 if (s->namespace)
2189 return varlink_error(link, "io.systemd.Journal.NotSupportedByNamespaces", NULL);
2190
2191 log_info("Received client request to relinquish %s access.", s->system_storage.path);
2192 server_relinquish_var(s);
2193
2194 return varlink_reply(link, NULL);
2195 }
2196
2197 static int vl_connect(VarlinkServer *server, Varlink *link, void *userdata) {
2198 Server *s = ASSERT_PTR(userdata);
2199
2200 assert(server);
2201 assert(link);
2202
2203 (void) server_start_or_stop_idle_timer(s); /* maybe we are no longer idle */
2204
2205 return 0;
2206 }
2207
2208 static void vl_disconnect(VarlinkServer *server, Varlink *link, void *userdata) {
2209 Server *s = ASSERT_PTR(userdata);
2210
2211 assert(server);
2212 assert(link);
2213
2214 (void) server_start_or_stop_idle_timer(s); /* maybe we are idle now */
2215 }
2216
2217 static int server_open_varlink(Server *s, const char *socket, int fd) {
2218 int r;
2219
2220 assert(s);
2221
2222 r = varlink_server_new(&s->varlink_server, VARLINK_SERVER_ROOT_ONLY|VARLINK_SERVER_INHERIT_USERDATA);
2223 if (r < 0)
2224 return r;
2225
2226 varlink_server_set_userdata(s->varlink_server, s);
2227
2228 r = varlink_server_add_interface(s->varlink_server, &vl_interface_io_systemd_Journal);
2229 if (r < 0)
2230 return log_error_errno(r, "Failed to add Journal interface to varlink server: %m");
2231
2232 r = varlink_server_bind_method_many(
2233 s->varlink_server,
2234 "io.systemd.Journal.Synchronize", vl_method_synchronize,
2235 "io.systemd.Journal.Rotate", vl_method_rotate,
2236 "io.systemd.Journal.FlushToVar", vl_method_flush_to_var,
2237 "io.systemd.Journal.RelinquishVar", vl_method_relinquish_var);
2238 if (r < 0)
2239 return r;
2240
2241 r = varlink_server_bind_connect(s->varlink_server, vl_connect);
2242 if (r < 0)
2243 return r;
2244
2245 r = varlink_server_bind_disconnect(s->varlink_server, vl_disconnect);
2246 if (r < 0)
2247 return r;
2248
2249 if (fd < 0)
2250 r = varlink_server_listen_address(s->varlink_server, socket, 0600);
2251 else
2252 r = varlink_server_listen_fd(s->varlink_server, fd);
2253 if (r < 0)
2254 return r;
2255
2256 r = varlink_server_attach_event(s->varlink_server, s->event, SD_EVENT_PRIORITY_NORMAL);
2257 if (r < 0)
2258 return r;
2259
2260 return 0;
2261 }
2262
2263 int server_map_seqnum_file(
2264 Server *s,
2265 const char *fname,
2266 size_t size,
2267 void **ret) {
2268
2269 _cleanup_free_ char *fn = NULL;
2270 _cleanup_close_ int fd = -EBADF;
2271 uint64_t *p;
2272 int r;
2273
2274 assert(s);
2275 assert(fname);
2276 assert(size > 0);
2277 assert(ret);
2278
2279 fn = path_join(s->runtime_directory, fname);
2280 if (!fn)
2281 return -ENOMEM;
2282
2283 fd = open(fn, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0644);
2284 if (fd < 0)
2285 return -errno;
2286
2287 r = posix_fallocate_loop(fd, 0, size);
2288 if (r < 0)
2289 return r;
2290
2291 p = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
2292 if (p == MAP_FAILED)
2293 return -errno;
2294
2295 *ret = p;
2296 return 0;
2297 }
2298
2299 void server_unmap_seqnum_file(void *p, size_t size) {
2300 assert(size > 0);
2301
2302 if (!p)
2303 return;
2304
2305 assert_se(munmap(p, size) >= 0);
2306 }
2307
2308 static bool server_is_idle(Server *s) {
2309 assert(s);
2310
2311 /* The server for the main namespace is never idle */
2312 if (!s->namespace)
2313 return false;
2314
2315 /* If a retention maximum is set larger than the idle time we need to be running to enforce it, hence
2316 * turn off the idle logic. */
2317 if (s->max_retention_usec > IDLE_TIMEOUT_USEC)
2318 return false;
2319
2320 /* We aren't idle if we have a varlink client */
2321 if (varlink_server_current_connections(s->varlink_server) > 0)
2322 return false;
2323
2324 /* If we have stdout streams we aren't idle */
2325 if (s->n_stdout_streams > 0)
2326 return false;
2327
2328 return true;
2329 }
2330
2331 static int server_idle_handler(sd_event_source *source, uint64_t usec, void *userdata) {
2332 Server *s = ASSERT_PTR(userdata);
2333
2334 assert(source);
2335
2336 log_debug("Server is idle, exiting.");
2337 sd_event_exit(s->event, 0);
2338 return 0;
2339 }
2340
2341 int server_start_or_stop_idle_timer(Server *s) {
2342 _cleanup_(sd_event_source_unrefp) sd_event_source *source = NULL;
2343 int r;
2344
2345 assert(s);
2346
2347 if (!server_is_idle(s)) {
2348 s->idle_event_source = sd_event_source_disable_unref(s->idle_event_source);
2349 return 0;
2350 }
2351
2352 if (s->idle_event_source)
2353 return 1;
2354
2355 r = sd_event_add_time_relative(s->event, &source, CLOCK_MONOTONIC, IDLE_TIMEOUT_USEC, 0, server_idle_handler, s);
2356 if (r < 0)
2357 return log_error_errno(r, "Failed to allocate idle timer: %m");
2358
2359 r = sd_event_source_set_priority(source, SD_EVENT_PRIORITY_IDLE);
2360 if (r < 0)
2361 return log_error_errno(r, "Failed to set idle timer priority: %m");
2362
2363 (void) sd_event_source_set_description(source, "idle-timer");
2364
2365 s->idle_event_source = TAKE_PTR(source);
2366 return 1;
2367 }
2368
2369 int server_refresh_idle_timer(Server *s) {
2370 int r;
2371
2372 assert(s);
2373
2374 if (!s->idle_event_source)
2375 return 0;
2376
2377 r = sd_event_source_set_time_relative(s->idle_event_source, IDLE_TIMEOUT_USEC);
2378 if (r < 0)
2379 return log_error_errno(r, "Failed to refresh idle timer: %m");
2380
2381 return 1;
2382 }
2383
2384 static int server_set_namespace(Server *s, const char *namespace) {
2385 assert(s);
2386
2387 if (!namespace)
2388 return 0;
2389
2390 if (!log_namespace_name_valid(namespace))
2391 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specified namespace name not valid, refusing: %s", namespace);
2392
2393 s->namespace = strdup(namespace);
2394 if (!s->namespace)
2395 return log_oom();
2396
2397 s->namespace_field = strjoin("_NAMESPACE=", namespace);
2398 if (!s->namespace_field)
2399 return log_oom();
2400
2401 return 1;
2402 }
2403
2404 static int server_memory_pressure(sd_event_source *es, void *userdata) {
2405 Server *s = ASSERT_PTR(userdata);
2406
2407 log_info("Under memory pressure, flushing caches.");
2408
2409 /* Flushed the cached info we might have about client processes */
2410 client_context_flush_regular(s);
2411
2412 /* Let's also close all user files (but keep the system/runtime one open) */
2413 for (;;) {
2414 JournalFile *first = ordered_hashmap_steal_first(s->user_journals);
2415
2416 if (!first)
2417 break;
2418
2419 (void) journal_file_offline_close(first);
2420 }
2421
2422 sd_event_trim_memory();
2423
2424 return 0;
2425 }
2426
2427 static int server_setup_memory_pressure(Server *s) {
2428 int r;
2429
2430 assert(s);
2431
2432 r = sd_event_add_memory_pressure(s->event, NULL, server_memory_pressure, s);
2433 if (r < 0)
2434 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r) || (r == -EHOSTDOWN) ? LOG_DEBUG : LOG_NOTICE, r,
2435 "Failed to install memory pressure event source, ignoring: %m");
2436
2437 return 0;
2438 }
2439
2440 int server_init(Server *s, const char *namespace) {
2441 const char *native_socket, *syslog_socket, *stdout_socket, *varlink_socket, *e;
2442 _cleanup_fdset_free_ FDSet *fds = NULL;
2443 int n, r, fd, varlink_fd = -EBADF;
2444 bool no_sockets;
2445
2446 assert(s);
2447
2448 *s = (Server) {
2449 .syslog_fd = -EBADF,
2450 .native_fd = -EBADF,
2451 .stdout_fd = -EBADF,
2452 .dev_kmsg_fd = -EBADF,
2453 .audit_fd = -EBADF,
2454 .hostname_fd = -EBADF,
2455 .notify_fd = -EBADF,
2456
2457 .compress.enabled = true,
2458 .compress.threshold_bytes = UINT64_MAX,
2459 .seal = true,
2460
2461 .set_audit = true,
2462
2463 .watchdog_usec = USEC_INFINITY,
2464
2465 .sync_interval_usec = DEFAULT_SYNC_INTERVAL_USEC,
2466 .sync_scheduled = false,
2467
2468 .ratelimit_interval = DEFAULT_RATE_LIMIT_INTERVAL,
2469 .ratelimit_burst = DEFAULT_RATE_LIMIT_BURST,
2470
2471 .forward_to_wall = true,
2472
2473 .max_file_usec = DEFAULT_MAX_FILE_USEC,
2474
2475 .max_level_store = LOG_DEBUG,
2476 .max_level_syslog = LOG_DEBUG,
2477 .max_level_kmsg = LOG_NOTICE,
2478 .max_level_console = LOG_INFO,
2479 .max_level_wall = LOG_EMERG,
2480
2481 .line_max = DEFAULT_LINE_MAX,
2482
2483 .runtime_storage.name = "Runtime Journal",
2484 .system_storage.name = "System Journal",
2485
2486 .kmsg_own_ratelimit = {
2487 .interval = DEFAULT_KMSG_OWN_INTERVAL,
2488 .burst = DEFAULT_KMSG_OWN_BURST,
2489 },
2490
2491 .sigrtmin18_info.memory_pressure_handler = server_memory_pressure,
2492 .sigrtmin18_info.memory_pressure_userdata = s,
2493 };
2494
2495 r = server_set_namespace(s, namespace);
2496 if (r < 0)
2497 return r;
2498
2499 /* By default, only read from /dev/kmsg if are the main namespace */
2500 s->read_kmsg = !s->namespace;
2501 s->storage = s->namespace ? STORAGE_PERSISTENT : STORAGE_AUTO;
2502
2503 journal_reset_metrics(&s->system_storage.metrics);
2504 journal_reset_metrics(&s->runtime_storage.metrics);
2505
2506 server_parse_config_file(s);
2507
2508 if (!s->namespace) {
2509 /* Parse kernel command line, but only if we are not a namespace instance */
2510 r = proc_cmdline_parse(parse_proc_cmdline_item, s, PROC_CMDLINE_STRIP_RD_PREFIX);
2511 if (r < 0)
2512 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
2513 }
2514
2515 if (!!s->ratelimit_interval != !!s->ratelimit_burst) { /* One set to 0 and the other not? */
2516 log_debug("Setting both rate limit interval and burst from "USEC_FMT",%u to 0,0",
2517 s->ratelimit_interval, s->ratelimit_burst);
2518 s->ratelimit_interval = s->ratelimit_burst = 0;
2519 }
2520
2521 e = getenv("RUNTIME_DIRECTORY");
2522 if (e)
2523 s->runtime_directory = strdup(e);
2524 else if (s->namespace)
2525 s->runtime_directory = strjoin("/run/systemd/journal.", s->namespace);
2526 else
2527 s->runtime_directory = strdup("/run/systemd/journal");
2528 if (!s->runtime_directory)
2529 return log_oom();
2530
2531 (void) mkdir_p(s->runtime_directory, 0755);
2532
2533 s->user_journals = ordered_hashmap_new(NULL);
2534 if (!s->user_journals)
2535 return log_oom();
2536
2537 s->mmap = mmap_cache_new();
2538 if (!s->mmap)
2539 return log_oom();
2540
2541 s->deferred_closes = set_new(NULL);
2542 if (!s->deferred_closes)
2543 return log_oom();
2544
2545 r = sd_event_default(&s->event);
2546 if (r < 0)
2547 return log_error_errno(r, "Failed to create event loop: %m");
2548
2549 n = sd_listen_fds(true);
2550 if (n < 0)
2551 return log_error_errno(n, "Failed to read listening file descriptors from environment: %m");
2552
2553 native_socket = strjoina(s->runtime_directory, "/socket");
2554 stdout_socket = strjoina(s->runtime_directory, "/stdout");
2555 syslog_socket = strjoina(s->runtime_directory, "/dev-log");
2556 varlink_socket = strjoina(s->runtime_directory, "/io.systemd.journal");
2557
2558 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
2559
2560 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, native_socket, 0) > 0) {
2561
2562 if (s->native_fd >= 0)
2563 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2564 "Too many native sockets passed.");
2565
2566 s->native_fd = fd;
2567
2568 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, stdout_socket, 0) > 0) {
2569
2570 if (s->stdout_fd >= 0)
2571 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2572 "Too many stdout sockets passed.");
2573
2574 s->stdout_fd = fd;
2575
2576 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, syslog_socket, 0) > 0) {
2577
2578 if (s->syslog_fd >= 0)
2579 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2580 "Too many /dev/log sockets passed.");
2581
2582 s->syslog_fd = fd;
2583
2584 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, varlink_socket, 0) > 0) {
2585
2586 if (varlink_fd >= 0)
2587 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2588 "Too many varlink sockets passed.");
2589
2590 varlink_fd = fd;
2591 } else if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1) > 0) {
2592
2593 if (s->audit_fd >= 0)
2594 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2595 "Too many audit sockets passed.");
2596
2597 s->audit_fd = fd;
2598
2599 } else {
2600
2601 if (!fds) {
2602 fds = fdset_new();
2603 if (!fds)
2604 return log_oom();
2605 }
2606
2607 r = fdset_put(fds, fd);
2608 if (r < 0)
2609 return log_oom();
2610 }
2611 }
2612
2613 /* Try to restore streams, but don't bother if this fails */
2614 (void) server_restore_streams(s, fds);
2615
2616 if (fdset_size(fds) > 0) {
2617 log_warning("%u unknown file descriptors passed, closing.", fdset_size(fds));
2618 fds = fdset_free(fds);
2619 }
2620
2621 no_sockets = s->native_fd < 0 && s->stdout_fd < 0 && s->syslog_fd < 0 && s->audit_fd < 0 && varlink_fd < 0;
2622
2623 /* always open stdout, syslog, native, and kmsg sockets */
2624
2625 /* systemd-journald.socket: /run/systemd/journal/stdout */
2626 r = server_open_stdout_socket(s, stdout_socket);
2627 if (r < 0)
2628 return r;
2629
2630 /* systemd-journald-dev-log.socket: /run/systemd/journal/dev-log */
2631 r = server_open_syslog_socket(s, syslog_socket);
2632 if (r < 0)
2633 return r;
2634
2635 /* systemd-journald.socket: /run/systemd/journal/socket */
2636 r = server_open_native_socket(s, native_socket);
2637 if (r < 0)
2638 return r;
2639
2640 /* /dev/kmsg */
2641 r = server_open_dev_kmsg(s);
2642 if (r < 0)
2643 return r;
2644
2645 /* Unless we got *some* sockets and not audit, open audit socket */
2646 if (s->audit_fd >= 0 || no_sockets) {
2647 log_info("Collecting audit messages is enabled.");
2648
2649 r = server_open_audit(s);
2650 if (r < 0)
2651 return r;
2652 } else
2653 log_info("Collecting audit messages is disabled.");
2654
2655 r = server_open_varlink(s, varlink_socket, varlink_fd);
2656 if (r < 0)
2657 return r;
2658
2659 r = server_map_seqnum_file(s, "seqnum", sizeof(SeqnumData), (void**) &s->seqnum);
2660 if (r < 0)
2661 return log_error_errno(r, "Failed to map main seqnum file: %m");
2662
2663 r = server_open_kernel_seqnum(s);
2664 if (r < 0)
2665 return r;
2666
2667 r = server_open_hostname(s);
2668 if (r < 0)
2669 return r;
2670
2671 r = server_setup_signals(s);
2672 if (r < 0)
2673 return r;
2674
2675 r = server_setup_memory_pressure(s);
2676 if (r < 0)
2677 return r;
2678
2679 s->ratelimit = journal_ratelimit_new();
2680 if (!s->ratelimit)
2681 return log_oom();
2682
2683 r = cg_get_root_path(&s->cgroup_root);
2684 if (r < 0)
2685 return log_error_errno(r, "Failed to acquire cgroup root path: %m");
2686
2687 server_cache_hostname(s);
2688 server_cache_boot_id(s);
2689 server_cache_machine_id(s);
2690
2691 if (s->namespace)
2692 s->runtime_storage.path = strjoin("/run/log/journal/", SERVER_MACHINE_ID(s), ".", s->namespace);
2693 else
2694 s->runtime_storage.path = strjoin("/run/log/journal/", SERVER_MACHINE_ID(s));
2695 if (!s->runtime_storage.path)
2696 return log_oom();
2697
2698 e = getenv("LOGS_DIRECTORY");
2699 if (e)
2700 s->system_storage.path = strdup(e);
2701 else if (s->namespace)
2702 s->system_storage.path = strjoin("/var/log/journal/", SERVER_MACHINE_ID(s), ".", s->namespace);
2703 else
2704 s->system_storage.path = strjoin("/var/log/journal/", SERVER_MACHINE_ID(s));
2705 if (!s->system_storage.path)
2706 return log_oom();
2707
2708 (void) server_connect_notify(s);
2709
2710 (void) client_context_acquire_default(s);
2711
2712 r = server_system_journal_open(s, /* flush_requested= */ false, /* relinquish_requested= */ false);
2713 if (r < 0)
2714 return r;
2715
2716 server_start_or_stop_idle_timer(s);
2717 return 0;
2718 }
2719
2720 void server_maybe_append_tags(Server *s) {
2721 #if HAVE_GCRYPT
2722 JournalFile *f;
2723 usec_t n;
2724
2725 n = now(CLOCK_REALTIME);
2726
2727 if (s->system_journal)
2728 journal_file_maybe_append_tag(s->system_journal, n);
2729
2730 ORDERED_HASHMAP_FOREACH(f, s->user_journals)
2731 journal_file_maybe_append_tag(f, n);
2732 #endif
2733 }
2734
2735 void server_done(Server *s) {
2736 assert(s);
2737
2738 free(s->namespace);
2739 free(s->namespace_field);
2740
2741 set_free_with_destructor(s->deferred_closes, journal_file_offline_close);
2742
2743 while (s->stdout_streams)
2744 stdout_stream_free(s->stdout_streams);
2745
2746 client_context_flush_all(s);
2747
2748 (void) journal_file_offline_close(s->system_journal);
2749 (void) journal_file_offline_close(s->runtime_journal);
2750
2751 ordered_hashmap_free_with_destructor(s->user_journals, journal_file_offline_close);
2752
2753 varlink_server_unref(s->varlink_server);
2754
2755 sd_event_source_unref(s->syslog_event_source);
2756 sd_event_source_unref(s->native_event_source);
2757 sd_event_source_unref(s->stdout_event_source);
2758 sd_event_source_unref(s->dev_kmsg_event_source);
2759 sd_event_source_unref(s->audit_event_source);
2760 sd_event_source_unref(s->sync_event_source);
2761 sd_event_source_unref(s->sigusr1_event_source);
2762 sd_event_source_unref(s->sigusr2_event_source);
2763 sd_event_source_unref(s->sigterm_event_source);
2764 sd_event_source_unref(s->sigint_event_source);
2765 sd_event_source_unref(s->sigrtmin1_event_source);
2766 sd_event_source_unref(s->hostname_event_source);
2767 sd_event_source_unref(s->notify_event_source);
2768 sd_event_source_unref(s->watchdog_event_source);
2769 sd_event_source_unref(s->idle_event_source);
2770 sd_event_unref(s->event);
2771
2772 safe_close(s->syslog_fd);
2773 safe_close(s->native_fd);
2774 safe_close(s->stdout_fd);
2775 safe_close(s->dev_kmsg_fd);
2776 safe_close(s->audit_fd);
2777 safe_close(s->hostname_fd);
2778 safe_close(s->notify_fd);
2779
2780 if (s->ratelimit)
2781 journal_ratelimit_free(s->ratelimit);
2782
2783 server_unmap_seqnum_file(s->seqnum, sizeof(*s->seqnum));
2784 server_unmap_seqnum_file(s->kernel_seqnum, sizeof(*s->kernel_seqnum));
2785
2786 free(s->buffer);
2787 free(s->tty_path);
2788 free(s->cgroup_root);
2789 free(s->hostname_field);
2790 free(s->runtime_storage.path);
2791 free(s->system_storage.path);
2792 free(s->runtime_directory);
2793
2794 mmap_cache_unref(s->mmap);
2795 }
2796
2797 static const char* const storage_table[_STORAGE_MAX] = {
2798 [STORAGE_AUTO] = "auto",
2799 [STORAGE_VOLATILE] = "volatile",
2800 [STORAGE_PERSISTENT] = "persistent",
2801 [STORAGE_NONE] = "none"
2802 };
2803
2804 DEFINE_STRING_TABLE_LOOKUP(storage, Storage);
2805 DEFINE_CONFIG_PARSE_ENUM(config_parse_storage, storage, Storage, "Failed to parse storage setting");
2806
2807 static const char* const split_mode_table[_SPLIT_MAX] = {
2808 [SPLIT_LOGIN] = "login",
2809 [SPLIT_UID] = "uid",
2810 [SPLIT_NONE] = "none",
2811 };
2812
2813 DEFINE_STRING_TABLE_LOOKUP(split_mode, SplitMode);
2814 DEFINE_CONFIG_PARSE_ENUM(config_parse_split_mode, split_mode, SplitMode, "Failed to parse split mode setting");
2815
2816 int config_parse_line_max(
2817 const char* unit,
2818 const char *filename,
2819 unsigned line,
2820 const char *section,
2821 unsigned section_line,
2822 const char *lvalue,
2823 int ltype,
2824 const char *rvalue,
2825 void *data,
2826 void *userdata) {
2827
2828 size_t *sz = ASSERT_PTR(data);
2829 int r;
2830
2831 assert(filename);
2832 assert(lvalue);
2833 assert(rvalue);
2834
2835 if (isempty(rvalue))
2836 /* Empty assignment means default */
2837 *sz = DEFAULT_LINE_MAX;
2838 else {
2839 uint64_t v;
2840
2841 r = parse_size(rvalue, 1024, &v);
2842 if (r < 0) {
2843 log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse LineMax= value, ignoring: %s", rvalue);
2844 return 0;
2845 }
2846
2847 if (v < 79) {
2848 /* Why specify 79 here as minimum line length? Simply, because the most common traditional
2849 * terminal size is 80ch, and it might make sense to break one character before the natural
2850 * line break would occur on that. */
2851 log_syntax(unit, LOG_WARNING, filename, line, 0, "LineMax= too small, clamping to 79: %s", rvalue);
2852 *sz = 79;
2853 } else if (v > (uint64_t) (SSIZE_MAX-1)) {
2854 /* So, why specify SSIZE_MAX-1 here? Because that's one below the largest size value read()
2855 * can return, and we need one extra byte for the trailing NUL byte. Of course IRL such large
2856 * memory allocations will fail anyway, hence this limit is mostly theoretical anyway, as we'll
2857 * fail much earlier anyway. */
2858 log_syntax(unit, LOG_WARNING, filename, line, 0, "LineMax= too large, clamping to %" PRIu64 ": %s", (uint64_t) (SSIZE_MAX-1), rvalue);
2859 *sz = SSIZE_MAX-1;
2860 } else
2861 *sz = (size_t) v;
2862 }
2863
2864 return 0;
2865 }
2866
2867 int config_parse_compress(
2868 const char* unit,
2869 const char *filename,
2870 unsigned line,
2871 const char *section,
2872 unsigned section_line,
2873 const char *lvalue,
2874 int ltype,
2875 const char *rvalue,
2876 void *data,
2877 void *userdata) {
2878
2879 JournalCompressOptions* compress = data;
2880 int r;
2881
2882 if (isempty(rvalue)) {
2883 compress->enabled = true;
2884 compress->threshold_bytes = UINT64_MAX;
2885 } else if (streq(rvalue, "1")) {
2886 log_syntax(unit, LOG_WARNING, filename, line, 0,
2887 "Compress= ambiguously specified as 1, enabling compression with default threshold");
2888 compress->enabled = true;
2889 } else if (streq(rvalue, "0")) {
2890 log_syntax(unit, LOG_WARNING, filename, line, 0,
2891 "Compress= ambiguously specified as 0, disabling compression");
2892 compress->enabled = false;
2893 } else {
2894 r = parse_boolean(rvalue);
2895 if (r < 0) {
2896 r = parse_size(rvalue, 1024, &compress->threshold_bytes);
2897 if (r < 0)
2898 log_syntax(unit, LOG_WARNING, filename, line, r,
2899 "Failed to parse Compress= value, ignoring: %s", rvalue);
2900 else
2901 compress->enabled = true;
2902 } else
2903 compress->enabled = r;
2904 }
2905
2906 return 0;
2907 }