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