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