]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/journal/journalctl.c
journalctl: add new --sync switch for syncing the journal to disk
[thirdparty/systemd.git] / src / journal / journalctl.c
CommitLineData
87d2c1ff
LP
1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3/***
4 This file is part of systemd.
5
6 Copyright 2011 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
87d2c1ff
LP
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 16 Lesser General Public License for more details.
87d2c1ff 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
87d2c1ff
LP
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
3f6fd1ba 22#include <errno.h>
87d2c1ff 23#include <fcntl.h>
ea18a4b5 24#include <fnmatch.h>
3f6fd1ba
LP
25#include <getopt.h>
26#include <linux/fs.h>
27#include <locale.h>
28#include <poll.h>
29#include <signal.h>
87d2c1ff 30#include <stddef.h>
3fbf9cbb 31#include <stdio.h>
3fbf9cbb 32#include <stdlib.h>
3f6fd1ba 33#include <string.h>
74055aa7 34#include <sys/inotify.h>
3f6fd1ba
LP
35#include <sys/stat.h>
36#include <unistd.h>
87d2c1ff 37
74055aa7 38#include "sd-bus.h"
3f6fd1ba
LP
39#include "sd-journal.h"
40
f8eeeaf9 41#include "acl-util.h"
b5efdb8a 42#include "alloc-util.h"
3f6fd1ba
LP
43#include "bus-error.h"
44#include "bus-util.h"
45#include "catalog.h"
c8b3094d 46#include "chattr-util.h"
3ffd4af2 47#include "fd-util.h"
68fee104 48#include "fileio.h"
f4f15635 49#include "fs-util.h"
3f6fd1ba 50#include "fsprg.h"
7d50b32a 51#include "glob-util.h"
3f6fd1ba 52#include "hostname-util.h"
c004493c 53#include "io-util.h"
7560fffc 54#include "journal-def.h"
3f6fd1ba 55#include "journal-internal.h"
f6a971bc 56#include "journal-qrcode.h"
dbd2a83f 57#include "journal-vacuum.h"
3f6fd1ba 58#include "journal-verify.h"
8752c575 59#include "locale-util.h"
3f6fd1ba
LP
60#include "log.h"
61#include "logs-show.h"
74055aa7 62#include "mkdir.h"
3f6fd1ba 63#include "pager.h"
6bedfcbb 64#include "parse-util.h"
3f6fd1ba 65#include "path-util.h"
78f22b97 66#include "rlimit-util.h"
3f6fd1ba
LP
67#include "set.h"
68#include "sigbus.h"
69#include "strv.h"
7ccbd1ae 70#include "syslog-util.h"
288a74cc 71#include "terminal-util.h"
3f6fd1ba 72#include "unit-name.h"
b1d4f8e1 73#include "user-util.h"
7560fffc 74
baed47c3 75#define DEFAULT_FSS_INTERVAL_USEC (15*USEC_PER_MINUTE)
250d54b5 76
97e1cc8b
LP
77enum {
78 /* Special values for arg_lines */
79 ARG_LINES_DEFAULT = -2,
80 ARG_LINES_ALL = -1,
81};
82
df50185b 83static OutputMode arg_output = OUTPUT_SHORT;
9fd29044 84static bool arg_utc = false;
1b12a7b5 85static bool arg_pager_end = false;
72f59706 86static bool arg_follow = false;
2b8f6883 87static bool arg_full = true;
cd4b13e0 88static bool arg_all = false;
0d43c694 89static bool arg_no_pager = false;
97e1cc8b 90static int arg_lines = ARG_LINES_DEFAULT;
e91af489 91static bool arg_no_tail = false;
43673799 92static bool arg_quiet = false;
9e8a535f 93static bool arg_merge = false;
d121b396 94static bool arg_boot = false;
442e2def
LP
95static sd_id128_t arg_boot_id = {};
96static int arg_boot_offset = 0;
99271804 97static bool arg_dmesg = false;
8f14c832 98static const char *arg_cursor = NULL;
248fc619
ZJS
99static const char *arg_after_cursor = NULL;
100static bool arg_show_cursor = false;
a963990f 101static const char *arg_directory = NULL;
8d98da3f 102static char **arg_file = NULL;
941e990d 103static int arg_priorities = 0xFF;
baed47c3 104static const char *arg_verify_key = NULL;
feb12d3e 105#ifdef HAVE_GCRYPT
baed47c3 106static usec_t arg_interval = DEFAULT_FSS_INTERVAL_USEC;
b8547c10 107static bool arg_force = false;
feb12d3e 108#endif
cfbc22ab
LP
109static usec_t arg_since, arg_until;
110static bool arg_since_set = false, arg_until_set = false;
73083640 111static char **arg_syslog_identifier = NULL;
b9e40524
HH
112static char **arg_system_units = NULL;
113static char **arg_user_units = NULL;
3c1668da 114static const char *arg_field = NULL;
d4205751 115static bool arg_catalog = false;
d89d6c86 116static bool arg_reverse = false;
3f3a438f 117static int arg_journal_type = 0;
0f03c2a4 118static char *arg_root = NULL;
b6741478 119static const char *arg_machine = NULL;
8580d1f7
LP
120static uint64_t arg_vacuum_size = 0;
121static uint64_t arg_vacuum_n_files = 0;
122static usec_t arg_vacuum_time = 0;
50f20cfd 123
7560fffc
LP
124static enum {
125 ACTION_SHOW,
126 ACTION_NEW_ID128,
127 ACTION_PRINT_HEADER,
beec0085 128 ACTION_SETUP_KEYS,
a1a03e30
LP
129 ACTION_VERIFY,
130 ACTION_DISK_USAGE,
d4205751 131 ACTION_LIST_CATALOG,
54b7254c 132 ACTION_DUMP_CATALOG,
f1188074
ZJS
133 ACTION_UPDATE_CATALOG,
134 ACTION_LIST_BOOTS,
74055aa7 135 ACTION_FLUSH,
e3fdfb49 136 ACTION_ROTATE,
dbd2a83f 137 ACTION_VACUUM,
94b65516 138 ACTION_SYNC,
7560fffc
LP
139} arg_action = ACTION_SHOW;
140
45bc27b6 141typedef struct BootId {
a331b5e6 142 sd_id128_t id;
f1188074
ZJS
143 uint64_t first;
144 uint64_t last;
45bc27b6
LP
145 LIST_FIELDS(struct BootId, boot_list);
146} BootId;
a331b5e6 147
faf5077f
DH
148static void pager_open_if_enabled(void) {
149
150 if (arg_no_pager)
151 return;
152
153 pager_open(arg_pager_end);
154}
155
5ab99e07
LP
156static char *format_timestamp_maybe_utc(char *buf, size_t l, usec_t t) {
157
158 if (arg_utc)
159 return format_timestamp_utc(buf, l, t);
160
161 return format_timestamp(buf, l, t);
162}
163
442e2def
LP
164static int parse_boot_descriptor(const char *x, sd_id128_t *boot_id, int *offset) {
165 sd_id128_t id = SD_ID128_NULL;
166 int off = 0, r;
167
168 if (strlen(x) >= 32) {
169 char *t;
170
171 t = strndupa(x, 32);
172 r = sd_id128_from_string(t, &id);
173 if (r >= 0)
174 x += 32;
175
176 if (*x != '-' && *x != '+' && *x != 0)
177 return -EINVAL;
178
179 if (*x != 0) {
180 r = safe_atoi(x, &off);
181 if (r < 0)
182 return r;
183 }
184 } else {
185 r = safe_atoi(x, &off);
186 if (r < 0)
187 return r;
188 }
189
190 if (boot_id)
191 *boot_id = id;
192
193 if (offset)
194 *offset = off;
195
196 return 0;
197}
198
601185b4 199static void help(void) {
0d43c694 200
faf5077f
DH
201 pager_open_if_enabled();
202
cd4b13e0 203 printf("%s [OPTIONS...] [MATCHES...]\n\n"
15119c16 204 "Query the journal.\n\n"
94b65516 205 "Options:\n"
eacbb4d3
ZJS
206 " --system Show the system journal\n"
207 " --user Show the user journal for the current user\n"
b6741478 208 " -M --machine=CONTAINER Operate on local container\n"
66f52924
JS
209 " -S --since=DATE Show entries not older than the specified date\n"
210 " -U --until=DATE Show entries not newer than the specified date\n"
40f0b71b
ZJS
211 " -c --cursor=CURSOR Show entries starting at the specified cursor\n"
212 " --after-cursor=CURSOR Show entries after the specified cursor\n"
248fc619 213 " --show-cursor Print the cursor after all the entries\n"
40f0b71b 214 " -b --boot[=ID] Show current boot or the specified boot\n"
f1188074 215 " --list-boots Show terse information about recorded boots\n"
c736283b 216 " -k --dmesg Show kernel message log from the current boot\n"
40f0b71b
ZJS
217 " -u --unit=UNIT Show logs from the specified unit\n"
218 " --user-unit=UNIT Show logs from the specified user unit\n"
219 " -t --identifier=STRING Show entries with the specified syslog identifier\n"
220 " -p --priority=RANGE Show entries with the specified priority\n"
221 " -e --pager-end Immediately jump to the end in the pager\n"
c736283b 222 " -f --follow Follow the journal\n"
248fc619
ZJS
223 " -n --lines[=INTEGER] Number of journal entries to show\n"
224 " --no-tail Show all lines, even in follow mode\n"
225 " -r --reverse Show the newest entries first\n"
f02d8367 226 " -o --output=STRING Change journal output mode (short, short-iso,\n"
c736283b
JSJ
227 " short-precise, short-monotonic, verbose,\n"
228 " export, json, json-pretty, json-sse, cat)\n"
9fd29044 229 " --utc Express time in Coordinated Universal Time (UTC)\n"
248fc619 230 " -x --catalog Add message explanations where available\n"
2b8f6883 231 " --no-full Ellipsize fields\n"
248fc619 232 " -a --all Show all fields, including long and unprintable\n"
20d936ba 233 " -q --quiet Do not show info messages and privilege warning\n"
248fc619
ZJS
234 " --no-pager Do not pipe output into a pager\n"
235 " -m --merge Show entries from all available journals\n"
236 " -D --directory=PATH Show journal files from directory\n"
237 " --file=PATH Show journal file\n"
94b65516 238 " --root=ROOT Operate on catalog files below a root directory\n"
15119c16 239#ifdef HAVE_GCRYPT
248fc619
ZJS
240 " --interval=TIME Time interval for changing the FSS sealing key\n"
241 " --verify-key=KEY Specify FSS verification key\n"
40f0b71b 242 " --force Override of the FSS key pair with --setup-keys\n"
15119c16
LP
243#endif
244 "\nCommands:\n"
c736283b 245 " -h --help Show this help text\n"
248fc619 246 " --version Show package version\n"
dbd2a83f 247 " -F --field=FIELD List all values that a specified field takes\n"
c736283b 248 " --disk-usage Show total disk usage of all journal files\n"
40f0b71b 249 " --vacuum-size=BYTES Reduce disk usage below specified size\n"
8580d1f7
LP
250 " --vacuum-files=INT Leave only the specified number of journal files\n"
251 " --vacuum-time=TIME Remove journal files older than specified time\n"
94b65516
LP
252 " --verify Verify journal file consistency\n"
253 " --sync Synchronize unwritten journal messages to disk\n"
dbd2a83f 254 " --flush Flush all journal data from /run into /var\n"
e3fdfb49 255 " --rotate Request immediate rotation of the journal files\n"
dbd2a83f 256 " --header Show journal header information\n"
40f0b71b 257 " --list-catalog Show all message IDs in the catalog\n"
248fc619
ZJS
258 " --dump-catalog Show entries in the message catalog\n"
259 " --update-catalog Update the message catalog database\n"
94b65516 260 " --new-id128 Generate a new 128-bit ID\n"
feb12d3e 261#ifdef HAVE_GCRYPT
c736283b 262 " --setup-keys Generate a new FSS key pair\n"
feb12d3e
LP
263#endif
264 , program_invocation_short_name);
0d43c694
LP
265}
266
267static int parse_argv(int argc, char *argv[]) {
268
269 enum {
270 ARG_VERSION = 0x100,
e91af489 271 ARG_NO_PAGER,
2b8f6883 272 ARG_NO_FULL,
55ee336c 273 ARG_NO_TAIL,
dca6219e 274 ARG_NEW_ID128,
f1188074 275 ARG_LIST_BOOTS,
3f3a438f
ZJS
276 ARG_USER,
277 ARG_SYSTEM,
13cbf3a5 278 ARG_ROOT,
7560fffc 279 ARG_HEADER,
beec0085 280 ARG_SETUP_KEYS,
8d98da3f 281 ARG_FILE,
baed47c3 282 ARG_INTERVAL,
4da416aa 283 ARG_VERIFY,
a1a03e30 284 ARG_VERIFY_KEY,
cfbc22ab 285 ARG_DISK_USAGE,
248fc619
ZJS
286 ARG_AFTER_CURSOR,
287 ARG_SHOW_CURSOR,
ffa7cd15 288 ARG_USER_UNIT,
d4205751 289 ARG_LIST_CATALOG,
54b7254c 290 ARG_DUMP_CATALOG,
3f3a438f 291 ARG_UPDATE_CATALOG,
b8547c10 292 ARG_FORCE,
9fd29044 293 ARG_UTC,
94b65516 294 ARG_SYNC,
74055aa7 295 ARG_FLUSH,
e3fdfb49 296 ARG_ROTATE,
dbd2a83f 297 ARG_VACUUM_SIZE,
8580d1f7 298 ARG_VACUUM_FILES,
dbd2a83f 299 ARG_VACUUM_TIME,
0d43c694
LP
300 };
301
302 static const struct option options[] = {
248fc619
ZJS
303 { "help", no_argument, NULL, 'h' },
304 { "version" , no_argument, NULL, ARG_VERSION },
305 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
306 { "pager-end", no_argument, NULL, 'e' },
307 { "follow", no_argument, NULL, 'f' },
308 { "force", no_argument, NULL, ARG_FORCE },
309 { "output", required_argument, NULL, 'o' },
310 { "all", no_argument, NULL, 'a' },
311 { "full", no_argument, NULL, 'l' },
2b8f6883 312 { "no-full", no_argument, NULL, ARG_NO_FULL },
248fc619
ZJS
313 { "lines", optional_argument, NULL, 'n' },
314 { "no-tail", no_argument, NULL, ARG_NO_TAIL },
315 { "new-id128", no_argument, NULL, ARG_NEW_ID128 },
316 { "quiet", no_argument, NULL, 'q' },
317 { "merge", no_argument, NULL, 'm' },
318 { "boot", optional_argument, NULL, 'b' },
f1188074 319 { "list-boots", no_argument, NULL, ARG_LIST_BOOTS },
248fc619
ZJS
320 { "this-boot", optional_argument, NULL, 'b' }, /* deprecated */
321 { "dmesg", no_argument, NULL, 'k' },
322 { "system", no_argument, NULL, ARG_SYSTEM },
323 { "user", no_argument, NULL, ARG_USER },
324 { "directory", required_argument, NULL, 'D' },
325 { "file", required_argument, NULL, ARG_FILE },
326 { "root", required_argument, NULL, ARG_ROOT },
327 { "header", no_argument, NULL, ARG_HEADER },
73083640 328 { "identifier", required_argument, NULL, 't' },
248fc619
ZJS
329 { "priority", required_argument, NULL, 'p' },
330 { "setup-keys", no_argument, NULL, ARG_SETUP_KEYS },
331 { "interval", required_argument, NULL, ARG_INTERVAL },
332 { "verify", no_argument, NULL, ARG_VERIFY },
333 { "verify-key", required_argument, NULL, ARG_VERIFY_KEY },
334 { "disk-usage", no_argument, NULL, ARG_DISK_USAGE },
335 { "cursor", required_argument, NULL, 'c' },
336 { "after-cursor", required_argument, NULL, ARG_AFTER_CURSOR },
337 { "show-cursor", no_argument, NULL, ARG_SHOW_CURSOR },
66f52924
JS
338 { "since", required_argument, NULL, 'S' },
339 { "until", required_argument, NULL, 'U' },
248fc619
ZJS
340 { "unit", required_argument, NULL, 'u' },
341 { "user-unit", required_argument, NULL, ARG_USER_UNIT },
342 { "field", required_argument, NULL, 'F' },
343 { "catalog", no_argument, NULL, 'x' },
344 { "list-catalog", no_argument, NULL, ARG_LIST_CATALOG },
345 { "dump-catalog", no_argument, NULL, ARG_DUMP_CATALOG },
346 { "update-catalog", no_argument, NULL, ARG_UPDATE_CATALOG },
347 { "reverse", no_argument, NULL, 'r' },
b6741478 348 { "machine", required_argument, NULL, 'M' },
9fd29044 349 { "utc", no_argument, NULL, ARG_UTC },
74055aa7 350 { "flush", no_argument, NULL, ARG_FLUSH },
94b65516 351 { "sync", no_argument, NULL, ARG_SYNC },
e3fdfb49 352 { "rotate", no_argument, NULL, ARG_ROTATE },
dbd2a83f 353 { "vacuum-size", required_argument, NULL, ARG_VACUUM_SIZE },
8580d1f7 354 { "vacuum-files", required_argument, NULL, ARG_VACUUM_FILES },
dbd2a83f 355 { "vacuum-time", required_argument, NULL, ARG_VACUUM_TIME },
eb9da376 356 {}
0d43c694
LP
357 };
358
2100675e 359 int c, r;
0d43c694
LP
360
361 assert(argc >= 0);
362 assert(argv);
363
66f52924 364 while ((c = getopt_long(argc, argv, "hefo:aln::qmb::kD:p:c:S:U:t:u:F:xrM:", options, NULL)) >= 0)
0d43c694
LP
365
366 switch (c) {
367
368 case 'h':
601185b4
ZJS
369 help();
370 return 0;
0d43c694
LP
371
372 case ARG_VERSION:
3f6fd1ba 373 return version();
0d43c694
LP
374
375 case ARG_NO_PAGER:
376 arg_no_pager = true;
377 break;
378
1b12a7b5
HH
379 case 'e':
380 arg_pager_end = true;
fe59e38b 381
97e1cc8b 382 if (arg_lines == ARG_LINES_DEFAULT)
fe59e38b
LP
383 arg_lines = 1000;
384
1b12a7b5
HH
385 break;
386
0d43c694
LP
387 case 'f':
388 arg_follow = true;
389 break;
390
391 case 'o':
1705594f 392 arg_output = output_mode_from_string(optarg);
df50185b 393 if (arg_output < 0) {
edfb521a 394 log_error("Unknown output format '%s'.", optarg);
0d43c694
LP
395 return -EINVAL;
396 }
df50185b 397
edfb521a
ZJS
398 if (arg_output == OUTPUT_EXPORT ||
399 arg_output == OUTPUT_JSON ||
400 arg_output == OUTPUT_JSON_PRETTY ||
401 arg_output == OUTPUT_JSON_SSE ||
402 arg_output == OUTPUT_CAT)
403 arg_quiet = true;
404
0d43c694
LP
405 break;
406
98a6e132 407 case 'l':
e3657ecd
ZJS
408 arg_full = true;
409 break;
410
2b8f6883
ZJS
411 case ARG_NO_FULL:
412 arg_full = false;
413 break;
414
0d43c694 415 case 'a':
cd4b13e0 416 arg_all = true;
0d43c694
LP
417 break;
418
2100675e 419 case 'n':
1705594f 420 if (optarg) {
48382487 421 if (streq(optarg, "all"))
97e1cc8b 422 arg_lines = ARG_LINES_ALL;
48382487
JJ
423 else {
424 r = safe_atoi(optarg, &arg_lines);
425 if (r < 0 || arg_lines < 0) {
426 log_error("Failed to parse lines '%s'", optarg);
427 return -EINVAL;
428 }
1705594f 429 }
96088db0 430 } else {
48382487 431 arg_lines = 10;
96088db0
LP
432
433 /* Hmm, no argument? Maybe the next
434 * word on the command line is
435 * supposed to be the argument? Let's
436 * see if there is one, and is
48382487
JJ
437 * parsable. */
438 if (optind < argc) {
439 int n;
440 if (streq(argv[optind], "all")) {
97e1cc8b 441 arg_lines = ARG_LINES_ALL;
48382487
JJ
442 optind++;
443 } else if (safe_atoi(argv[optind], &n) >= 0 && n >= 0) {
444 arg_lines = n;
445 optind++;
446 }
447 }
96088db0 448 }
1705594f 449
2100675e
LP
450 break;
451
e91af489
LP
452 case ARG_NO_TAIL:
453 arg_no_tail = true;
454 break;
455
39f7f5c1 456 case ARG_NEW_ID128:
7560fffc 457 arg_action = ACTION_NEW_ID128;
55ee336c
LP
458 break;
459
43673799
LP
460 case 'q':
461 arg_quiet = true;
490e567d 462 break;
43673799 463
9e8a535f
LP
464 case 'm':
465 arg_merge = true;
2bd3c38a
LP
466 break;
467
59cea26a 468 case 'b':
d121b396 469 arg_boot = true;
6cebe83c 470
442e2def 471 if (optarg) {
909dea0c 472 r = parse_boot_descriptor(optarg, &arg_boot_id, &arg_boot_offset);
442e2def
LP
473 if (r < 0) {
474 log_error("Failed to parse boot descriptor '%s'", optarg);
475 return -EINVAL;
476 }
477 } else {
6cebe83c 478
442e2def
LP
479 /* Hmm, no argument? Maybe the next
480 * word on the command line is
481 * supposed to be the argument? Let's
482 * see if there is one and is parsable
483 * as a boot descriptor... */
484
485 if (optind < argc &&
486 parse_boot_descriptor(argv[optind], &arg_boot_id, &arg_boot_offset) >= 0)
6cebe83c 487 optind++;
6cebe83c 488 }
d121b396 489
59cea26a
LP
490 break;
491
f1188074
ZJS
492 case ARG_LIST_BOOTS:
493 arg_action = ACTION_LIST_BOOTS;
494 break;
495
99271804 496 case 'k':
d121b396 497 arg_boot = arg_dmesg = true;
99271804
ZJS
498 break;
499
3f3a438f
ZJS
500 case ARG_SYSTEM:
501 arg_journal_type |= SD_JOURNAL_SYSTEM;
502 break;
503
504 case ARG_USER:
505 arg_journal_type |= SD_JOURNAL_CURRENT_USER;
506 break;
507
b6741478
LP
508 case 'M':
509 arg_machine = optarg;
510 break;
511
a963990f
LP
512 case 'D':
513 arg_directory = optarg;
514 break;
515
8d98da3f
ZJS
516 case ARG_FILE:
517 r = glob_extend(&arg_file, optarg);
23bbb0de
MS
518 if (r < 0)
519 return log_error_errno(r, "Failed to add paths: %m");
8d98da3f
ZJS
520 break;
521
13cbf3a5 522 case ARG_ROOT:
0f03c2a4
LP
523 r = parse_path_argument_and_warn(optarg, true, &arg_root);
524 if (r < 0)
525 return r;
13cbf3a5
ZJS
526 break;
527
8f14c832
LP
528 case 'c':
529 arg_cursor = optarg;
530 break;
531
248fc619
ZJS
532 case ARG_AFTER_CURSOR:
533 arg_after_cursor = optarg;
534 break;
535
536 case ARG_SHOW_CURSOR:
537 arg_show_cursor = true;
538 break;
539
dca6219e 540 case ARG_HEADER:
7560fffc
LP
541 arg_action = ACTION_PRINT_HEADER;
542 break;
543
feb12d3e
LP
544 case ARG_VERIFY:
545 arg_action = ACTION_VERIFY;
546 break;
547
a1a03e30
LP
548 case ARG_DISK_USAGE:
549 arg_action = ACTION_DISK_USAGE;
550 break;
551
dbd2a83f
LP
552 case ARG_VACUUM_SIZE:
553 r = parse_size(optarg, 1024, &arg_vacuum_size);
554 if (r < 0) {
555 log_error("Failed to parse vacuum size: %s", optarg);
556 return r;
557 }
558
559 arg_action = ACTION_VACUUM;
560 break;
561
8580d1f7
LP
562 case ARG_VACUUM_FILES:
563 r = safe_atou64(optarg, &arg_vacuum_n_files);
564 if (r < 0) {
565 log_error("Failed to parse vacuum files: %s", optarg);
566 return r;
567 }
568
569 arg_action = ACTION_VACUUM;
570 break;
571
dbd2a83f
LP
572 case ARG_VACUUM_TIME:
573 r = parse_sec(optarg, &arg_vacuum_time);
574 if (r < 0) {
575 log_error("Failed to parse vacuum time: %s", optarg);
576 return r;
577 }
578
579 arg_action = ACTION_VACUUM;
580 break;
581
feb12d3e 582#ifdef HAVE_GCRYPT
b8547c10
SL
583 case ARG_FORCE:
584 arg_force = true;
585 break;
586
7560fffc
LP
587 case ARG_SETUP_KEYS:
588 arg_action = ACTION_SETUP_KEYS;
dca6219e
LP
589 break;
590
beec0085 591
baed47c3 592 case ARG_VERIFY_KEY:
4da416aa 593 arg_action = ACTION_VERIFY;
baed47c3 594 arg_verify_key = optarg;
9e8a535f 595 arg_merge = false;
4da416aa
LP
596 break;
597
baed47c3 598 case ARG_INTERVAL:
7f602784 599 r = parse_sec(optarg, &arg_interval);
baed47c3
LP
600 if (r < 0 || arg_interval <= 0) {
601 log_error("Failed to parse sealing key change interval: %s", optarg);
14d10188
LP
602 return -EINVAL;
603 }
604 break;
feb12d3e
LP
605#else
606 case ARG_SETUP_KEYS:
607 case ARG_VERIFY_KEY:
608 case ARG_INTERVAL:
b8547c10 609 case ARG_FORCE:
feb12d3e 610 log_error("Forward-secure sealing not available.");
15411c0c 611 return -EOPNOTSUPP;
feb12d3e 612#endif
14d10188 613
941e990d
LP
614 case 'p': {
615 const char *dots;
616
617 dots = strstr(optarg, "..");
618 if (dots) {
619 char *a;
620 int from, to, i;
621
622 /* a range */
623 a = strndup(optarg, dots - optarg);
624 if (!a)
625 return log_oom();
626
627 from = log_level_from_string(a);
628 to = log_level_from_string(dots + 2);
629 free(a);
630
631 if (from < 0 || to < 0) {
632 log_error("Failed to parse log level range %s", optarg);
633 return -EINVAL;
634 }
635
636 arg_priorities = 0;
637
638 if (from < to) {
639 for (i = from; i <= to; i++)
640 arg_priorities |= 1 << i;
641 } else {
642 for (i = to; i <= from; i++)
643 arg_priorities |= 1 << i;
644 }
645
646 } else {
647 int p, i;
648
649 p = log_level_from_string(optarg);
650 if (p < 0) {
651 log_error("Unknown log level %s", optarg);
652 return -EINVAL;
653 }
654
655 arg_priorities = 0;
656
657 for (i = 0; i <= p; i++)
658 arg_priorities |= 1 << i;
659 }
660
661 break;
662 }
663
66f52924 664 case 'S':
cfbc22ab
LP
665 r = parse_timestamp(optarg, &arg_since);
666 if (r < 0) {
667 log_error("Failed to parse timestamp: %s", optarg);
668 return -EINVAL;
669 }
670 arg_since_set = true;
671 break;
672
66f52924 673 case 'U':
cfbc22ab
LP
674 r = parse_timestamp(optarg, &arg_until);
675 if (r < 0) {
676 log_error("Failed to parse timestamp: %s", optarg);
677 return -EINVAL;
678 }
679 arg_until_set = true;
680 break;
681
73083640
HH
682 case 't':
683 r = strv_extend(&arg_syslog_identifier, optarg);
684 if (r < 0)
685 return log_oom();
686 break;
687
7199aa96 688 case 'u':
b9e40524
HH
689 r = strv_extend(&arg_system_units, optarg);
690 if (r < 0)
691 return log_oom();
ffa7cd15
DW
692 break;
693
7199aa96 694 case ARG_USER_UNIT:
b9e40524
HH
695 r = strv_extend(&arg_user_units, optarg);
696 if (r < 0)
697 return log_oom();
c3f60ec5
LP
698 break;
699
15119c16
LP
700 case 'F':
701 arg_field = optarg;
702 break;
703
d4205751
LP
704 case 'x':
705 arg_catalog = true;
706 break;
707
708 case ARG_LIST_CATALOG:
709 arg_action = ACTION_LIST_CATALOG;
710 break;
711
54b7254c
ZJS
712 case ARG_DUMP_CATALOG:
713 arg_action = ACTION_DUMP_CATALOG;
714 break;
715
d4205751
LP
716 case ARG_UPDATE_CATALOG:
717 arg_action = ACTION_UPDATE_CATALOG;
718 break;
719
d89d6c86
LN
720 case 'r':
721 arg_reverse = true;
722 break;
723
9fd29044
JS
724 case ARG_UTC:
725 arg_utc = true;
726 break;
727
74055aa7
LP
728 case ARG_FLUSH:
729 arg_action = ACTION_FLUSH;
730 break;
731
e3fdfb49
EV
732 case ARG_ROTATE:
733 arg_action = ACTION_ROTATE;
734 break;
735
94b65516
LP
736 case ARG_SYNC:
737 arg_action = ACTION_SYNC;
738 break;
739
eb9da376 740 case '?':
0d43c694 741 return -EINVAL;
eb9da376
LP
742
743 default:
744 assert_not_reached("Unhandled option");
0d43c694 745 }
0d43c694 746
70af7b8a 747 if (arg_follow && !arg_no_tail && !arg_since && arg_lines == ARG_LINES_DEFAULT)
e91af489
LP
748 arg_lines = 10;
749
b6741478
LP
750 if (!!arg_directory + !!arg_file + !!arg_machine > 1) {
751 log_error("Please specify either -D/--directory= or --file= or -M/--machine=, not more than one.");
8d98da3f
ZJS
752 return -EINVAL;
753 }
754
3ba09ee8 755 if (arg_since_set && arg_until_set && arg_since > arg_until) {
cfbc22ab
LP
756 log_error("--since= must be before --until=.");
757 return -EINVAL;
758 }
759
248fc619
ZJS
760 if (!!arg_cursor + !!arg_after_cursor + !!arg_since_set > 1) {
761 log_error("Please specify only one of --since=, --cursor=, and --after-cursor.");
cfbc22ab
LP
762 return -EINVAL;
763 }
764
d89d6c86
LN
765 if (arg_follow && arg_reverse) {
766 log_error("Please specify either --reverse= or --follow=, not both.");
767 return -EINVAL;
768 }
769
f98a41c2 770 if (!IN_SET(arg_action, ACTION_SHOW, ACTION_DUMP_CATALOG, ACTION_LIST_CATALOG) && optind < argc) {
0b6b7c20
ZJS
771 log_error("Extraneous arguments starting with '%s'", argv[optind]);
772 return -EINVAL;
773 }
774
596a2329
JJ
775 if ((arg_boot || arg_action == ACTION_LIST_BOOTS) && (arg_file || arg_directory || arg_merge)) {
776 log_error("Using --boot or --list-boots with --file, --directory or --merge is not supported.");
777 return -EINVAL;
778 }
779
0d43c694
LP
780 return 1;
781}
782
39f7f5c1 783static int generate_new_id128(void) {
55ee336c
LP
784 sd_id128_t id;
785 int r;
786 unsigned i;
787
788 r = sd_id128_randomize(&id);
23bbb0de
MS
789 if (r < 0)
790 return log_error_errno(r, "Failed to generate ID: %m");
55ee336c
LP
791
792 printf("As string:\n"
793 SD_ID128_FORMAT_STR "\n\n"
794 "As UUID:\n"
795 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n\n"
796 "As macro:\n"
d489071f 797 "#define MESSAGE_XYZ SD_ID128_MAKE(",
55ee336c
LP
798 SD_ID128_FORMAT_VAL(id),
799 SD_ID128_FORMAT_VAL(id));
55ee336c
LP
800 for (i = 0; i < 16; i++)
801 printf("%02x%s", id.bytes[i], i != 15 ? "," : "");
d489071f 802 fputs(")\n\n", stdout);
55ee336c 803
d489071f
ZJS
804 printf("As Python constant:\n"
805 ">>> import uuid\n"
806 ">>> MESSAGE_XYZ = uuid.UUID('" SD_ID128_FORMAT_STR "')\n",
807 SD_ID128_FORMAT_VAL(id));
55ee336c
LP
808
809 return 0;
810}
811
a963990f
LP
812static int add_matches(sd_journal *j, char **args) {
813 char **i;
4e602943 814 bool have_term = false;
59cea26a 815
a963990f 816 assert(j);
59cea26a 817
a963990f 818 STRV_FOREACH(i, args) {
52aeb63c 819 int r;
59cea26a 820
4e602943
ZJS
821 if (streq(*i, "+")) {
822 if (!have_term)
823 break;
cbdca852 824 r = sd_journal_add_disjunction(j);
4e602943
ZJS
825 have_term = false;
826
827 } else if (path_is_absolute(*i)) {
68fee104 828 _cleanup_free_ char *p, *t = NULL, *t2 = NULL;
e5124088 829 const char *path;
68fee104 830 _cleanup_free_ char *interpreter = NULL;
a963990f 831 struct stat st;
e5124088 832
a963990f
LP
833 p = canonicalize_file_name(*i);
834 path = p ? p : *i;
e5124088 835
26b9f165 836 if (lstat(path, &st) < 0)
4a62c710 837 return log_error_errno(errno, "Couldn't stat file: %m");
e5124088 838
68fee104
ZJS
839 if (S_ISREG(st.st_mode) && (0111 & st.st_mode)) {
840 if (executable_is_script(path, &interpreter) > 0) {
841 _cleanup_free_ char *comm;
842
2b6bf07d 843 comm = strndup(basename(path), 15);
68fee104
ZJS
844 if (!comm)
845 return log_oom();
846
847 t = strappend("_COMM=", comm);
848
849 /* Append _EXE only if the interpreter is not a link.
73e231ab 850 Otherwise, it might be outdated often. */
68fee104
ZJS
851 if (lstat(interpreter, &st) == 0 &&
852 !S_ISLNK(st.st_mode)) {
853 t2 = strappend("_EXE=", interpreter);
854 if (!t2)
855 return log_oom();
856 }
857 } else
858 t = strappend("_EXE=", path);
b56d608e
LP
859 } else if (S_ISCHR(st.st_mode))
860 (void) asprintf(&t, "_KERNEL_DEVICE=c%u:%u", major(st.st_rdev), minor(st.st_rdev));
861 else if (S_ISBLK(st.st_mode))
862 (void) asprintf(&t, "_KERNEL_DEVICE=b%u:%u", major(st.st_rdev), minor(st.st_rdev));
863 else {
fb93cf73 864 log_error("File is neither a device node, nor regular file, nor executable: %s", *i);
a963990f 865 return -EINVAL;
50940700 866 }
e5124088 867
b6a34514
LP
868 if (!t)
869 return log_oom();
870
871 r = sd_journal_add_match(j, t, 0);
68fee104
ZJS
872 if (t2)
873 r = sd_journal_add_match(j, t2, 0);
4e602943
ZJS
874 have_term = true;
875
876 } else {
cbdca852 877 r = sd_journal_add_match(j, *i, 0);
4e602943
ZJS
878 have_term = true;
879 }
e5124088 880
23bbb0de
MS
881 if (r < 0)
882 return log_error_errno(r, "Failed to add match '%s': %m", *i);
de7b95cd
LP
883 }
884
4e602943
ZJS
885 if (!strv_isempty(args) && !have_term) {
886 log_error("\"+\" can only be used between terms");
887 return -EINVAL;
888 }
889
a963990f
LP
890 return 0;
891}
892
9530e0d0
LP
893static void boot_id_free_all(BootId *l) {
894
895 while (l) {
896 BootId *i = l;
897 LIST_REMOVE(boot_list, l, i);
898 free(i);
899 }
900}
901
45bc27b6
LP
902static int discover_next_boot(
903 sd_journal *j,
904 BootId **boot,
905 bool advance_older,
906 bool read_realtime) {
907
f1188074 908 int r;
596a2329 909 char match[9+32+1] = "_BOOT_ID=";
45bc27b6 910 _cleanup_free_ BootId *next_boot = NULL;
ea7061e4
JJ
911
912 assert(j);
596a2329
JJ
913 assert(boot);
914
915 /* We expect the journal to be on the last position of a boot
916 * (in relation to the direction we are going), so that the next
917 * invocation of sd_journal_next/previous will be from a different
918 * boot. We then collect any information we desire and then jump
919 * to the last location of the new boot by using a _BOOT_ID match
920 * coming from the other journal direction. */
921
922 /* Make sure we aren't restricted by any _BOOT_ID matches, so that
923 * we can actually advance to a *different* boot. */
924 sd_journal_flush_matches(j);
925
926 if (advance_older)
927 r = sd_journal_previous(j);
928 else
929 r = sd_journal_next(j);
930 if (r < 0)
931 return r;
932 else if (r == 0)
933 return 0; /* End of journal, yay. */
934
45bc27b6 935 next_boot = new0(BootId, 1);
596a2329 936 if (!next_boot)
b56d608e 937 return -ENOMEM;
f1188074 938
596a2329 939 r = sd_journal_get_monotonic_usec(j, NULL, &next_boot->id);
f1188074
ZJS
940 if (r < 0)
941 return r;
942
596a2329
JJ
943 if (read_realtime) {
944 r = sd_journal_get_realtime_usec(j, &next_boot->first);
945 if (r < 0)
946 return r;
947 }
ea7061e4 948
596a2329
JJ
949 /* Now seek to the last occurrence of this boot ID. */
950 sd_id128_to_string(next_boot->id, match + 9);
951 r = sd_journal_add_match(j, match, sizeof(match) - 1);
952 if (r < 0)
953 return r;
f1188074 954
596a2329
JJ
955 if (advance_older)
956 r = sd_journal_seek_head(j);
957 else
958 r = sd_journal_seek_tail(j);
959 if (r < 0)
960 return r;
f1188074 961
596a2329
JJ
962 if (advance_older)
963 r = sd_journal_next(j);
964 else
965 r = sd_journal_previous(j);
966 if (r < 0)
967 return r;
968 else if (r == 0)
969 return -ENODATA; /* This shouldn't happen. We just came from this very boot ID. */
f1188074 970
596a2329
JJ
971 if (read_realtime) {
972 r = sd_journal_get_realtime_usec(j, &next_boot->last);
f1188074 973 if (r < 0)
596a2329
JJ
974 return r;
975 }
976
977 *boot = next_boot;
978 next_boot = NULL;
9530e0d0 979
596a2329
JJ
980 return 0;
981}
982
45bc27b6
LP
983static int get_boots(
984 sd_journal *j,
985 BootId **boots,
986 BootId *query_ref_boot,
987 int ref_boot_offset) {
988
596a2329
JJ
989 bool skip_once;
990 int r, count = 0;
45bc27b6 991 BootId *head = NULL, *tail = NULL;
596a2329
JJ
992 const bool advance_older = query_ref_boot && ref_boot_offset <= 0;
993
994 assert(j);
f1188074 995
596a2329
JJ
996 /* Adjust for the asymmetry that offset 0 is
997 * the last (and current) boot, while 1 is considered the
998 * (chronological) first boot in the journal. */
999 skip_once = query_ref_boot && sd_id128_is_null(query_ref_boot->id) && ref_boot_offset < 0;
1000
1001 /* Advance to the earliest/latest occurrence of our reference
1002 * boot ID (taking our lookup direction into account), so that
1003 * discover_next_boot() can do its job.
1004 * If no reference is given, the journal head/tail will do,
1005 * they're "virtual" boots after all. */
1006 if (query_ref_boot && !sd_id128_is_null(query_ref_boot->id)) {
1007 char match[9+32+1] = "_BOOT_ID=";
1008
1009 sd_journal_flush_matches(j);
1010
1011 sd_id128_to_string(query_ref_boot->id, match + 9);
1012 r = sd_journal_add_match(j, match, sizeof(match) - 1);
f1188074
ZJS
1013 if (r < 0)
1014 return r;
1015
596a2329
JJ
1016 if (advance_older)
1017 r = sd_journal_seek_head(j);
1018 else
1019 r = sd_journal_seek_tail(j);
f1188074
ZJS
1020 if (r < 0)
1021 return r;
1022
596a2329
JJ
1023 if (advance_older)
1024 r = sd_journal_next(j);
1025 else
1026 r = sd_journal_previous(j);
f1188074
ZJS
1027 if (r < 0)
1028 return r;
1029 else if (r == 0)
596a2329
JJ
1030 goto finish;
1031 else if (ref_boot_offset == 0) {
1032 count = 1;
1033 goto finish;
1034 }
1035 } else {
1036 if (advance_older)
1037 r = sd_journal_seek_tail(j);
1038 else
1039 r = sd_journal_seek_head(j);
f1188074
ZJS
1040 if (r < 0)
1041 return r;
1042
596a2329
JJ
1043 /* No sd_journal_next/previous here. */
1044 }
f1188074 1045
45bc27b6
LP
1046 for (;;) {
1047 _cleanup_free_ BootId *current = NULL;
f1188074 1048
596a2329
JJ
1049 r = discover_next_boot(j, &current, advance_older, !query_ref_boot);
1050 if (r < 0) {
9530e0d0 1051 boot_id_free_all(head);
596a2329 1052 return r;
ea7061e4 1053 }
f1188074 1054
596a2329
JJ
1055 if (!current)
1056 break;
1057
1058 if (query_ref_boot) {
1059 if (!skip_once)
1060 ref_boot_offset += advance_older ? 1 : -1;
1061 skip_once = false;
1062
1063 if (ref_boot_offset == 0) {
1064 count = 1;
1065 query_ref_boot->id = current->id;
1066 break;
1067 }
1068 } else {
1069 LIST_INSERT_AFTER(boot_list, head, tail, current);
1070 tail = current;
1071 current = NULL;
1072 count++;
1073 }
f1188074
ZJS
1074 }
1075
596a2329
JJ
1076finish:
1077 if (boots)
1078 *boots = head;
1079
1080 sd_journal_flush_matches(j);
1081
1082 return count;
ea7061e4
JJ
1083}
1084
1085static int list_boots(sd_journal *j) {
596a2329 1086 int w, i, count;
9530e0d0 1087 BootId *id, *all_ids;
ea7061e4
JJ
1088
1089 assert(j);
1090
596a2329 1091 count = get_boots(j, &all_ids, NULL, 0);
b56d608e
LP
1092 if (count < 0)
1093 return log_error_errno(count, "Failed to determine boots: %m");
1094 if (count == 0)
596a2329 1095 return count;
ea7061e4
JJ
1096
1097 pager_open_if_enabled();
f1188074
ZJS
1098
1099 /* numbers are one less, but we need an extra char for the sign */
1100 w = DECIMAL_STR_WIDTH(count - 1) + 1;
1101
596a2329 1102 i = 0;
9530e0d0 1103 LIST_FOREACH(boot_list, id, all_ids) {
f1188074
ZJS
1104 char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX];
1105
1106 printf("% *i " SD_ID128_FORMAT_STR " %s—%s\n",
1107 w, i - count + 1,
1108 SD_ID128_FORMAT_VAL(id->id),
5ab99e07
LP
1109 format_timestamp_maybe_utc(a, sizeof(a), id->first),
1110 format_timestamp_maybe_utc(b, sizeof(b), id->last));
596a2329 1111 i++;
d121b396 1112 }
a963990f 1113
9530e0d0
LP
1114 boot_id_free_all(all_ids);
1115
a331b5e6
JJ
1116 return 0;
1117}
1118
1119static int add_boot(sd_journal *j) {
1120 char match[9+32+1] = "_BOOT_ID=";
442e2def 1121 int r;
45bc27b6 1122 BootId ref_boot_id = {};
a331b5e6
JJ
1123
1124 assert(j);
1125
d121b396 1126 if (!arg_boot)
a331b5e6
JJ
1127 return 0;
1128
442e2def 1129 if (arg_boot_offset == 0 && sd_id128_equal(arg_boot_id, SD_ID128_NULL))
b6741478 1130 return add_match_this_boot(j, arg_machine);
a331b5e6 1131
596a2329
JJ
1132 ref_boot_id.id = arg_boot_id;
1133 r = get_boots(j, NULL, &ref_boot_id, arg_boot_offset);
1134 assert(r <= 1);
1135 if (r <= 0) {
1136 const char *reason = (r == 0) ? "No such boot ID in journal" : strerror(-r);
1137
1138 if (sd_id128_is_null(arg_boot_id))
1139 log_error("Failed to look up boot %+i: %s", arg_boot_offset, reason);
d121b396 1140 else
442e2def 1141 log_error("Failed to look up boot ID "SD_ID128_FORMAT_STR"%+i: %s",
596a2329
JJ
1142 SD_ID128_FORMAT_VAL(arg_boot_id), arg_boot_offset, reason);
1143
1144 return r == 0 ? -ENODATA : r;
a331b5e6
JJ
1145 }
1146
596a2329 1147 sd_id128_to_string(ref_boot_id.id, match + 9);
d121b396
ZJS
1148
1149 r = sd_journal_add_match(j, match, sizeof(match) - 1);
23bbb0de
MS
1150 if (r < 0)
1151 return log_error_errno(r, "Failed to add match: %m");
a331b5e6
JJ
1152
1153 r = sd_journal_add_conjunction(j);
1154 if (r < 0)
b56d608e 1155 return log_error_errno(r, "Failed to add conjunction: %m");
a331b5e6
JJ
1156
1157 return 0;
a963990f
LP
1158}
1159
99271804
ZJS
1160static int add_dmesg(sd_journal *j) {
1161 int r;
1162 assert(j);
1163
1164 if (!arg_dmesg)
1165 return 0;
1166
1167 r = sd_journal_add_match(j, "_TRANSPORT=kernel", strlen("_TRANSPORT=kernel"));
23bbb0de
MS
1168 if (r < 0)
1169 return log_error_errno(r, "Failed to add match: %m");
99271804
ZJS
1170
1171 r = sd_journal_add_conjunction(j);
1172 if (r < 0)
b56d608e 1173 return log_error_errno(r, "Failed to add conjunction: %m");
99271804
ZJS
1174
1175 return 0;
1176}
1177
b56d608e
LP
1178static int get_possible_units(
1179 sd_journal *j,
1180 const char *fields,
1181 char **patterns,
1182 Set **units) {
1183
ea18a4b5
ZJS
1184 _cleanup_set_free_free_ Set *found;
1185 const char *field;
c3f60ec5 1186 int r;
ea18a4b5 1187
d5099efc 1188 found = set_new(&string_hash_ops);
ea18a4b5 1189 if (!found)
b56d608e 1190 return -ENOMEM;
ea18a4b5
ZJS
1191
1192 NULSTR_FOREACH(field, fields) {
1193 const void *data;
1194 size_t size;
1195
1196 r = sd_journal_query_unique(j, field);
1197 if (r < 0)
1198 return r;
1199
1200 SD_JOURNAL_FOREACH_UNIQUE(j, data, size) {
1201 char **pattern, *eq;
1202 size_t prefix;
1203 _cleanup_free_ char *u = NULL;
1204
1205 eq = memchr(data, '=', size);
1206 if (eq)
1207 prefix = eq - (char*) data + 1;
1208 else
1209 prefix = 0;
1210
1211 u = strndup((char*) data + prefix, size - prefix);
1212 if (!u)
b56d608e 1213 return -ENOMEM;
ea18a4b5
ZJS
1214
1215 STRV_FOREACH(pattern, patterns)
1216 if (fnmatch(*pattern, u, FNM_NOESCAPE) == 0) {
1217 log_debug("Matched %s with pattern %s=%s", u, field, *pattern);
1218
1219 r = set_consume(found, u);
1220 u = NULL;
1221 if (r < 0 && r != -EEXIST)
1222 return r;
1223
1224 break;
1225 }
1226 }
1227 }
1228
1229 *units = found;
1230 found = NULL;
1231 return 0;
1232}
1233
1234/* This list is supposed to return the superset of unit names
1235 * possibly matched by rules added with add_matches_for_unit... */
1236#define SYSTEM_UNITS \
1237 "_SYSTEMD_UNIT\0" \
1238 "COREDUMP_UNIT\0" \
1239 "UNIT\0" \
1240 "OBJECT_SYSTEMD_UNIT\0" \
1241 "_SYSTEMD_SLICE\0"
1242
1243/* ... and add_matches_for_user_unit */
1244#define USER_UNITS \
1245 "_SYSTEMD_USER_UNIT\0" \
1246 "USER_UNIT\0" \
1247 "COREDUMP_USER_UNIT\0" \
1248 "OBJECT_SYSTEMD_USER_UNIT\0"
1249
1250static int add_units(sd_journal *j) {
1251 _cleanup_strv_free_ char **patterns = NULL;
1252 int r, count = 0;
b9e40524 1253 char **i;
c3f60ec5
LP
1254
1255 assert(j);
1256
b9e40524 1257 STRV_FOREACH(i, arg_system_units) {
ea18a4b5
ZJS
1258 _cleanup_free_ char *u = NULL;
1259
7410616c
LP
1260 r = unit_name_mangle(*i, UNIT_NAME_GLOB, &u);
1261 if (r < 0)
1262 return r;
ea18a4b5
ZJS
1263
1264 if (string_is_glob(u)) {
1265 r = strv_push(&patterns, u);
1266 if (r < 0)
1267 return r;
1268 u = NULL;
1269 } else {
1270 r = add_matches_for_unit(j, u);
1271 if (r < 0)
1272 return r;
1273 r = sd_journal_add_disjunction(j);
1274 if (r < 0)
1275 return r;
1276 count ++;
1277 }
1278 }
1279
1280 if (!strv_isempty(patterns)) {
1281 _cleanup_set_free_free_ Set *units = NULL;
1282 Iterator it;
1283 char *u;
1284
1285 r = get_possible_units(j, SYSTEM_UNITS, patterns, &units);
b9e40524
HH
1286 if (r < 0)
1287 return r;
ea18a4b5
ZJS
1288
1289 SET_FOREACH(u, units, it) {
1290 r = add_matches_for_unit(j, u);
1291 if (r < 0)
1292 return r;
1293 r = sd_journal_add_disjunction(j);
1294 if (r < 0)
1295 return r;
1296 count ++;
1297 }
b9e40524 1298 }
c3f60ec5 1299
97b11eed 1300 patterns = strv_free(patterns);
ea18a4b5 1301
b9e40524 1302 STRV_FOREACH(i, arg_user_units) {
ea18a4b5
ZJS
1303 _cleanup_free_ char *u = NULL;
1304
7410616c
LP
1305 r = unit_name_mangle(*i, UNIT_NAME_GLOB, &u);
1306 if (r < 0)
1307 return r;
c3f60ec5 1308
ea18a4b5
ZJS
1309 if (string_is_glob(u)) {
1310 r = strv_push(&patterns, u);
1311 if (r < 0)
1312 return r;
1313 u = NULL;
1314 } else {
1315 r = add_matches_for_user_unit(j, u, getuid());
1316 if (r < 0)
1317 return r;
1318 r = sd_journal_add_disjunction(j);
1319 if (r < 0)
1320 return r;
1321 count ++;
1322 }
1323 }
1324
1325 if (!strv_isempty(patterns)) {
1326 _cleanup_set_free_free_ Set *units = NULL;
1327 Iterator it;
1328 char *u;
b9e40524 1329
ea18a4b5 1330 r = get_possible_units(j, USER_UNITS, patterns, &units);
b9e40524
HH
1331 if (r < 0)
1332 return r;
1333
ea18a4b5
ZJS
1334 SET_FOREACH(u, units, it) {
1335 r = add_matches_for_user_unit(j, u, getuid());
1336 if (r < 0)
1337 return r;
1338 r = sd_journal_add_disjunction(j);
1339 if (r < 0)
1340 return r;
1341 count ++;
1342 }
b9e40524 1343 }
c3f60ec5 1344
ea18a4b5
ZJS
1345 /* Complain if the user request matches but nothing whatsoever was
1346 * found, since otherwise everything would be matched. */
1347 if (!(strv_isempty(arg_system_units) && strv_isempty(arg_user_units)) && count == 0)
1348 return -ENODATA;
1349
cd34b3c6
HH
1350 r = sd_journal_add_conjunction(j);
1351 if (r < 0)
1352 return r;
1353
c3f60ec5
LP
1354 return 0;
1355}
1356
941e990d
LP
1357static int add_priorities(sd_journal *j) {
1358 char match[] = "PRIORITY=0";
1359 int i, r;
941e990d
LP
1360 assert(j);
1361
1362 if (arg_priorities == 0xFF)
1363 return 0;
1364
1365 for (i = LOG_EMERG; i <= LOG_DEBUG; i++)
1366 if (arg_priorities & (1 << i)) {
1367 match[sizeof(match)-2] = '0' + i;
1368
941e990d 1369 r = sd_journal_add_match(j, match, strlen(match));
23bbb0de
MS
1370 if (r < 0)
1371 return log_error_errno(r, "Failed to add match: %m");
941e990d
LP
1372 }
1373
cd34b3c6
HH
1374 r = sd_journal_add_conjunction(j);
1375 if (r < 0)
b56d608e 1376 return log_error_errno(r, "Failed to add conjunction: %m");
cd34b3c6 1377
941e990d
LP
1378 return 0;
1379}
1380
73083640
HH
1381
1382static int add_syslog_identifier(sd_journal *j) {
1383 int r;
1384 char **i;
1385
1386 assert(j);
1387
1388 STRV_FOREACH(i, arg_syslog_identifier) {
1389 char *u;
1390
63c372cb 1391 u = strjoina("SYSLOG_IDENTIFIER=", *i);
73083640
HH
1392 r = sd_journal_add_match(j, u, 0);
1393 if (r < 0)
1394 return r;
1395 r = sd_journal_add_disjunction(j);
1396 if (r < 0)
1397 return r;
1398 }
1399
1400 r = sd_journal_add_conjunction(j);
1401 if (r < 0)
1402 return r;
1403
1404 return 0;
1405}
1406
7560fffc
LP
1407static int setup_keys(void) {
1408#ifdef HAVE_GCRYPT
1409 size_t mpk_size, seed_size, state_size, i;
1410 uint8_t *mpk, *seed, *state;
11689d2a 1411 int fd = -1, r;
7560fffc
LP
1412 sd_id128_t machine, boot;
1413 char *p = NULL, *k = NULL;
baed47c3 1414 struct FSSHeader h;
14d10188 1415 uint64_t n;
b98e3866
SL
1416 struct stat st;
1417
1418 r = stat("/var/log/journal", &st);
4a62c710
MS
1419 if (r < 0 && errno != ENOENT && errno != ENOTDIR)
1420 return log_error_errno(errno, "stat(\"%s\") failed: %m", "/var/log/journal");
b98e3866
SL
1421
1422 if (r < 0 || !S_ISDIR(st.st_mode)) {
1423 log_error("%s is not a directory, must be using persistent logging for FSS.",
1424 "/var/log/journal");
1425 return r < 0 ? -errno : -ENOTDIR;
1426 }
7560fffc
LP
1427
1428 r = sd_id128_get_machine(&machine);
23bbb0de
MS
1429 if (r < 0)
1430 return log_error_errno(r, "Failed to get machine ID: %m");
7560fffc
LP
1431
1432 r = sd_id128_get_boot(&boot);
23bbb0de
MS
1433 if (r < 0)
1434 return log_error_errno(r, "Failed to get boot ID: %m");
7560fffc 1435
baed47c3 1436 if (asprintf(&p, "/var/log/journal/" SD_ID128_FORMAT_STR "/fss",
7560fffc
LP
1437 SD_ID128_FORMAT_VAL(machine)) < 0)
1438 return log_oom();
1439
faf9da01
ZJS
1440 if (arg_force) {
1441 r = unlink(p);
1442 if (r < 0 && errno != ENOENT) {
1443 r = log_error_errno(errno, "unlink(\"%s\") failed: %m", p);
b8547c10
SL
1444 goto finish;
1445 }
faf9da01
ZJS
1446 } else if (access(p, F_OK) >= 0) {
1447 log_error("Sealing key file %s exists already. Use --force to recreate.", p);
1448 r = -EEXIST;
1449 goto finish;
7560fffc
LP
1450 }
1451
baed47c3 1452 if (asprintf(&k, "/var/log/journal/" SD_ID128_FORMAT_STR "/fss.tmp.XXXXXX",
7560fffc
LP
1453 SD_ID128_FORMAT_VAL(machine)) < 0) {
1454 r = log_oom();
1455 goto finish;
1456 }
1457
1458 mpk_size = FSPRG_mskinbytes(FSPRG_RECOMMENDED_SECPAR);
1459 mpk = alloca(mpk_size);
1460
1461 seed_size = FSPRG_RECOMMENDED_SEEDLEN;
1462 seed = alloca(seed_size);
1463
1464 state_size = FSPRG_stateinbytes(FSPRG_RECOMMENDED_SECPAR);
1465 state = alloca(state_size);
1466
1467 fd = open("/dev/random", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1468 if (fd < 0) {
76ef789d 1469 r = log_error_errno(errno, "Failed to open /dev/random: %m");
7560fffc
LP
1470 goto finish;
1471 }
1472
1473 log_info("Generating seed...");
a6dcc7e5
ZJS
1474 r = loop_read_exact(fd, seed, seed_size, true);
1475 if (r < 0) {
1476 log_error_errno(r, "Failed to read random seed: %m");
7560fffc
LP
1477 goto finish;
1478 }
1479
1480 log_info("Generating key pair...");
1481 FSPRG_GenMK(NULL, mpk, seed, seed_size, FSPRG_RECOMMENDED_SECPAR);
1482
baed47c3 1483 log_info("Generating sealing key...");
7560fffc
LP
1484 FSPRG_GenState0(state, mpk, seed, seed_size);
1485
baed47c3
LP
1486 assert(arg_interval > 0);
1487
7560fffc 1488 n = now(CLOCK_REALTIME);
baed47c3 1489 n /= arg_interval;
7560fffc 1490
03e334a1 1491 safe_close(fd);
2d5bdf5b 1492 fd = mkostemp_safe(k, O_WRONLY|O_CLOEXEC);
7560fffc 1493 if (fd < 0) {
709f6e46 1494 r = log_error_errno(fd, "Failed to open %s: %m", k);
7560fffc
LP
1495 goto finish;
1496 }
1497
f982e6f7
LP
1498 /* Enable secure remove, exclusion from dump, synchronous
1499 * writing and in-place updating */
1ed8f8c1 1500 r = chattr_fd(fd, FS_SECRM_FL|FS_NODUMP_FL|FS_SYNC_FL|FS_NOCOW_FL, FS_SECRM_FL|FS_NODUMP_FL|FS_SYNC_FL|FS_NOCOW_FL);
11689d2a 1501 if (r < 0)
709f6e46 1502 log_warning_errno(r, "Failed to set file attributes: %m");
f982e6f7 1503
7560fffc
LP
1504 zero(h);
1505 memcpy(h.signature, "KSHHRHLP", 8);
1506 h.machine_id = machine;
1507 h.boot_id = boot;
1508 h.header_size = htole64(sizeof(h));
baed47c3
LP
1509 h.start_usec = htole64(n * arg_interval);
1510 h.interval_usec = htole64(arg_interval);
1511 h.fsprg_secpar = htole16(FSPRG_RECOMMENDED_SECPAR);
1512 h.fsprg_state_size = htole64(state_size);
7560fffc 1513
553acb7b
ZJS
1514 r = loop_write(fd, &h, sizeof(h), false);
1515 if (r < 0) {
1516 log_error_errno(r, "Failed to write header: %m");
7560fffc
LP
1517 goto finish;
1518 }
1519
553acb7b
ZJS
1520 r = loop_write(fd, state, state_size, false);
1521 if (r < 0) {
1522 log_error_errno(r, "Failed to write state: %m");
7560fffc
LP
1523 goto finish;
1524 }
1525
1526 if (link(k, p) < 0) {
76ef789d 1527 r = log_error_errno(errno, "Failed to link file: %m");
7560fffc
LP
1528 goto finish;
1529 }
1530
8481248b 1531 if (on_tty()) {
7560fffc
LP
1532 fprintf(stderr,
1533 "\n"
1fc464f6 1534 "The new key pair has been generated. The " ANSI_HIGHLIGHT "secret sealing key" ANSI_NORMAL " has been written to\n"
c05276f2
LP
1535 "the following local file. This key file is automatically updated when the\n"
1536 "sealing key is advanced. It should not be used on multiple hosts.\n"
7560fffc
LP
1537 "\n"
1538 "\t%s\n"
1539 "\n"
1fc464f6 1540 "Please write down the following " ANSI_HIGHLIGHT "secret verification key" ANSI_NORMAL ". It should be stored\n"
baed47c3 1541 "at a safe location and should not be saved locally on disk.\n"
1fc464f6 1542 "\n\t" ANSI_HIGHLIGHT_RED, p);
7560fffc
LP
1543 fflush(stderr);
1544 }
1545 for (i = 0; i < seed_size; i++) {
1546 if (i > 0 && i % 3 == 0)
1547 putchar('-');
1548 printf("%02x", ((uint8_t*) seed)[i]);
1549 }
1550
baed47c3
LP
1551 printf("/%llx-%llx\n", (unsigned long long) n, (unsigned long long) arg_interval);
1552
8481248b 1553 if (on_tty()) {
f6a971bc 1554 char tsb[FORMAT_TIMESPAN_MAX], *hn;
7560fffc 1555
baed47c3 1556 fprintf(stderr,
1fc464f6 1557 ANSI_NORMAL "\n"
baed47c3 1558 "The sealing key is automatically changed every %s.\n",
2fa4092c 1559 format_timespan(tsb, sizeof(tsb), arg_interval, 0));
f6a971bc
LP
1560
1561 hn = gethostname_malloc();
1562
1563 if (hn) {
ae691c1d 1564 hostname_cleanup(hn);
adac1c93 1565 fprintf(stderr, "\nThe keys have been generated for host %s/" SD_ID128_FORMAT_STR ".\n", hn, SD_ID128_FORMAT_VAL(machine));
f6a971bc 1566 } else
adac1c93 1567 fprintf(stderr, "\nThe keys have been generated for host " SD_ID128_FORMAT_STR ".\n", SD_ID128_FORMAT_VAL(machine));
f6a971bc
LP
1568
1569#ifdef HAVE_QRENCODE
cf5a3432 1570 /* If this is not an UTF-8 system don't print any QR codes */
09017585 1571 if (is_locale_utf8()) {
cf5a3432
LP
1572 fputs("\nTo transfer the verification key to your phone please scan the QR code below:\n\n", stderr);
1573 print_qr_code(stderr, seed, seed_size, n, arg_interval, hn, machine);
1574 }
f6a971bc
LP
1575#endif
1576 free(hn);
baed47c3 1577 }
7560fffc
LP
1578
1579 r = 0;
1580
1581finish:
03e334a1 1582 safe_close(fd);
7560fffc
LP
1583
1584 if (k) {
1585 unlink(k);
1586 free(k);
1587 }
1588
1589 free(p);
1590
1591 return r;
1592#else
feb12d3e 1593 log_error("Forward-secure sealing not available.");
15411c0c 1594 return -EOPNOTSUPP;
7560fffc
LP
1595#endif
1596}
1597
beec0085
LP
1598static int verify(sd_journal *j) {
1599 int r = 0;
1600 Iterator i;
1601 JournalFile *f;
1602
1603 assert(j);
1604
cedb42bb
LP
1605 log_show_color(true);
1606
c1f906bd 1607 ORDERED_HASHMAP_FOREACH(f, j->files, i) {
beec0085 1608 int k;
a7f7d1bd 1609 usec_t first = 0, validated = 0, last = 0;
beec0085 1610
56e81f7c 1611#ifdef HAVE_GCRYPT
feb12d3e 1612 if (!arg_verify_key && JOURNAL_HEADER_SEALED(f->header))
cedb42bb 1613 log_notice("Journal file %s has sealing enabled but verification key has not been passed using --verify-key=.", f->path);
56e81f7c 1614#endif
4da416aa 1615
2a7b539a 1616 k = journal_file_verify(f, arg_verify_key, &first, &validated, &last, true);
56e81f7c 1617 if (k == -EINVAL) {
baed47c3 1618 /* If the key was invalid give up right-away. */
56e81f7c
LP
1619 return k;
1620 } else if (k < 0) {
e53fc357 1621 log_warning_errno(k, "FAIL: %s (%m)", f->path);
56e81f7c 1622 r = k;
6c7be122
LP
1623 } else {
1624 char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX], c[FORMAT_TIMESPAN_MAX];
beec0085 1625 log_info("PASS: %s", f->path);
6c7be122 1626
c0ca7aee 1627 if (arg_verify_key && JOURNAL_HEADER_SEALED(f->header)) {
2a7b539a 1628 if (validated > 0) {
c0ca7aee 1629 log_info("=> Validated from %s to %s, final %s entries not sealed.",
5ab99e07
LP
1630 format_timestamp_maybe_utc(a, sizeof(a), first),
1631 format_timestamp_maybe_utc(b, sizeof(b), validated),
2fa4092c 1632 format_timespan(c, sizeof(c), last > validated ? last - validated : 0, 0));
2a7b539a 1633 } else if (last > 0)
c0ca7aee 1634 log_info("=> No sealing yet, %s of entries not sealed.",
2fa4092c 1635 format_timespan(c, sizeof(c), last - first, 0));
c0ca7aee
LP
1636 else
1637 log_info("=> No sealing yet, no entries in file.");
1638 }
6c7be122 1639 }
beec0085
LP
1640 }
1641
1642 return r;
1643}
1644
6fe391c5 1645static int access_check_var_log_journal(sd_journal *j) {
e346512c 1646#ifdef HAVE_ACL
6fe391c5 1647 _cleanup_strv_free_ char **g = NULL;
e346512c
LP
1648 const char* dir;
1649#endif
6fe391c5
ZJS
1650 int r;
1651
1652 assert(j);
1653
e346512c
LP
1654 if (arg_quiet)
1655 return 0;
05c18530 1656
e346512c
LP
1657 /* If we are root, we should have access, don't warn. */
1658 if (getuid() == 0)
1659 return 0;
05c18530 1660
e346512c
LP
1661 /* If we are in the 'systemd-journal' group, we should have
1662 * access too. */
1663 r = in_group("systemd-journal");
1664 if (r < 0)
1665 return log_error_errno(r, "Failed to check if we are in the 'systemd-journal' group: %m");
1666 if (r > 0)
1667 return 0;
15804ceb 1668
e346512c
LP
1669#ifdef HAVE_ACL
1670 if (laccess("/run/log/journal", F_OK) >= 0)
1671 dir = "/run/log/journal";
1672 else
1673 dir = "/var/log/journal";
1674
1675 /* If we are in any of the groups listed in the journal ACLs,
1676 * then all is good, too. Let's enumerate all groups from the
1677 * default ACL of the directory, which generally should allow
1678 * access to most journal files too. */
1679 r = acl_search_groups(dir, &g);
1680 if (r < 0)
1681 return log_error_errno(r, "Failed to search journal ACL: %m");
1682 if (r > 0)
1683 return 0;
4468addc 1684
e346512c
LP
1685 /* Print a pretty list, if there were ACLs set. */
1686 if (!strv_isempty(g)) {
1687 _cleanup_free_ char *s = NULL;
4468addc 1688
e346512c
LP
1689 /* Thre are groups in the ACL, let's list them */
1690 r = strv_extend(&g, "systemd-journal");
1691 if (r < 0)
1692 return log_oom();
6fe391c5 1693
e346512c
LP
1694 strv_sort(g);
1695 strv_uniq(g);
6fe391c5 1696
e346512c
LP
1697 s = strv_join(g, "', '");
1698 if (!s)
1699 return log_oom();
6fe391c5 1700
e346512c
LP
1701 log_notice("Hint: You are currently not seeing messages from other users and the system.\n"
1702 " Users in groups '%s' can see all messages.\n"
1703 " Pass -q to turn off this notice.", s);
1704 return 1;
6fe391c5 1705 }
e346512c 1706#endif
4468addc 1707
e346512c
LP
1708 /* If no ACLs were found, print a short version of the message. */
1709 log_notice("Hint: You are currently not seeing messages from other users and the system.\n"
1710 " Users in the 'systemd-journal' group can see all messages. Pass -q to\n"
1711 " turn off this notice.");
1712
1713 return 1;
6fe391c5 1714}
4468addc 1715
6fe391c5 1716static int access_check(sd_journal *j) {
6fe391c5 1717 Iterator it;
3ac251b8 1718 void *code;
5768d259 1719 char *path;
6fe391c5 1720 int r = 0;
4468addc 1721
6fe391c5 1722 assert(j);
4468addc 1723
5768d259 1724 if (hashmap_isempty(j->errors)) {
c1f906bd 1725 if (ordered_hashmap_isempty(j->files))
3ac251b8 1726 log_notice("No journal files were found.");
e346512c 1727
6fe391c5
ZJS
1728 return 0;
1729 }
4468addc 1730
5768d259 1731 if (hashmap_contains(j->errors, INT_TO_PTR(-EACCES))) {
e346512c 1732 (void) access_check_var_log_journal(j);
3ac251b8 1733
e346512c
LP
1734 if (ordered_hashmap_isempty(j->files))
1735 r = log_error_errno(EACCES, "No journal files were opened due to insufficient permissions.");
6fe391c5 1736 }
15804ceb 1737
5768d259 1738 HASHMAP_FOREACH_KEY(path, code, j->errors, it) {
3ac251b8
LP
1739 int err;
1740
4f52b822 1741 err = abs(PTR_TO_INT(code));
3ac251b8 1742
5768d259
LP
1743 switch (err) {
1744 case EACCES:
e346512c
LP
1745 continue;
1746
5768d259
LP
1747 case ENODATA:
1748 log_warning_errno(err, "Journal file %s is truncated, ignoring file.", path);
1749 break;
1750
1751 case EPROTONOSUPPORT:
1752 log_warning_errno(err, "Journal file %s uses an unsupported feature, ignoring file.", path);
1753 break;
1754
1755 case EBADMSG:
1756 log_warning_errno(err, "Journal file %s corrupted, ignoring file.", path);
1757 break;
1758
1759 default:
1760 log_warning_errno(err, "An error was encountered while opening journal file %s, ignoring file.", path);
1761 break;
1762 }
6fe391c5
ZJS
1763 }
1764
6fe391c5 1765 return r;
15804ceb
LP
1766}
1767
74055aa7
LP
1768static int flush_to_var(void) {
1769 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
03976f7b 1770 _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
74055aa7
LP
1771 _cleanup_close_ int watch_fd = -1;
1772 int r;
1773
1774 /* Quick exit */
1775 if (access("/run/systemd/journal/flushed", F_OK) >= 0)
1776 return 0;
1777
1778 /* OK, let's actually do the full logic, send SIGUSR1 to the
1779 * daemon and set up inotify to wait for the flushed file to appear */
266f3e26 1780 r = bus_connect_system_systemd(&bus);
23bbb0de
MS
1781 if (r < 0)
1782 return log_error_errno(r, "Failed to get D-Bus connection: %m");
74055aa7
LP
1783
1784 r = sd_bus_call_method(
1785 bus,
1786 "org.freedesktop.systemd1",
1787 "/org/freedesktop/systemd1",
1788 "org.freedesktop.systemd1.Manager",
1789 "KillUnit",
1790 &error,
1791 NULL,
1792 "ssi", "systemd-journald.service", "main", SIGUSR1);
94b65516
LP
1793 if (r < 0)
1794 return log_error_errno(r, "Failed to kill journal service: %s", bus_error_message(&error, r));
74055aa7
LP
1795
1796 mkdir_p("/run/systemd/journal", 0755);
1797
1798 watch_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
4a62c710
MS
1799 if (watch_fd < 0)
1800 return log_error_errno(errno, "Failed to create inotify watch: %m");
74055aa7
LP
1801
1802 r = inotify_add_watch(watch_fd, "/run/systemd/journal", IN_CREATE|IN_DONT_FOLLOW|IN_ONLYDIR);
4a62c710
MS
1803 if (r < 0)
1804 return log_error_errno(errno, "Failed to watch journal directory: %m");
74055aa7
LP
1805
1806 for (;;) {
1807 if (access("/run/systemd/journal/flushed", F_OK) >= 0)
1808 break;
1809
4a62c710 1810 if (errno != ENOENT)
f131770b 1811 return log_error_errno(errno, "Failed to check for existence of /run/systemd/journal/flushed: %m");
74055aa7
LP
1812
1813 r = fd_wait_for_event(watch_fd, POLLIN, USEC_INFINITY);
23bbb0de
MS
1814 if (r < 0)
1815 return log_error_errno(r, "Failed to wait for event: %m");
74055aa7
LP
1816
1817 r = flush_fd(watch_fd);
23bbb0de
MS
1818 if (r < 0)
1819 return log_error_errno(r, "Failed to flush inotify events: %m");
74055aa7
LP
1820 }
1821
1822 return 0;
1823}
1824
e3fdfb49
EV
1825static int rotate(void) {
1826 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1827 _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
1828 int r;
1829
1830 r = bus_connect_system_systemd(&bus);
1831 if (r < 0)
1832 return log_error_errno(r, "Failed to get D-Bus connection: %m");
1833
1834 r = sd_bus_call_method(
1835 bus,
1836 "org.freedesktop.systemd1",
1837 "/org/freedesktop/systemd1",
1838 "org.freedesktop.systemd1.Manager",
1839 "KillUnit",
1840 &error,
1841 NULL,
1842 "ssi", "systemd-journald.service", "main", SIGUSR2);
1843 if (r < 0)
1844 return log_error_errno(r, "Failed to kill journal service: %s", bus_error_message(&error, r));
1845
1846 return 0;
1847}
1848
94b65516
LP
1849static int sync_journal(void) {
1850 _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
1851 _cleanup_close_ int watch_fd = -1;
1852 usec_t start;
1853 int r;
1854
1855 start = now(CLOCK_REALTIME);
1856
1857 /* Let's watch /run/systemd/sync until it's mtime is above
1858 * the time we started the sync. Let's enqueue SIGRTMIN+1 to
1859 * start the sync. */
1860
1861 for (;;) {
1862 struct stat st;
1863
1864 /* See if a sync happened by now. */
1865 if (stat("/run/systemd/journal/synced", &st) < 0) {
1866 if (errno != ENOENT)
1867 return log_error_errno(errno, "Failed to stat /run/systemd/journal/synced: %m");
1868 } else {
1869 if (timespec_load(&st.st_mtim) >= start)
1870 return 0;
1871 }
1872
1873 /* Let's ask for a sync, but only once. */
1874 if (!bus) {
1875 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1876
1877 r = bus_connect_system_systemd(&bus);
1878 if (r < 0)
1879 return log_error_errno(r, "Failed to get D-Bus connection: %m");
1880
1881 r = sd_bus_call_method(
1882 bus,
1883 "org.freedesktop.systemd1",
1884 "/org/freedesktop/systemd1",
1885 "org.freedesktop.systemd1.Manager",
1886 "KillUnit",
1887 &error,
1888 NULL,
1889 "ssi", "systemd-journald.service", "main", SIGRTMIN+1);
1890 if (r < 0)
1891 return log_error_errno(r, "Failed to kill journal service: %s", bus_error_message(&error, r));
1892
1893 continue;
1894 }
1895
1896 /* Let's install the inotify watch, if we didn't do that yet. */
1897 if (watch_fd < 0) {
1898
1899 mkdir_p("/run/systemd/journal", 0755);
1900
1901 watch_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1902 if (watch_fd < 0)
1903 return log_error_errno(errno, "Failed to create inotify watch: %m");
1904
1905 r = inotify_add_watch(watch_fd, "/run/systemd/journal", IN_CREATE|IN_ATTRIB|IN_DONT_FOLLOW|IN_ONLYDIR);
1906 if (r < 0)
1907 return log_error_errno(errno, "Failed to watch journal directory: %m");
1908
1909 /* Recheck the flag file immediately, so that we don't miss any event since the last check. */
1910 continue;
1911 }
1912
1913 /* OK, all preparatory steps done, let's wait until
1914 * inotify reports an event. */
1915
1916 r = fd_wait_for_event(watch_fd, POLLIN, USEC_INFINITY);
1917 if (r < 0)
1918 return log_error_errno(r, "Failed to wait for event: %m");
1919
1920 r = flush_fd(watch_fd);
1921 if (r < 0)
1922 return log_error_errno(r, "Failed to flush inotify events: %m");
1923 }
1924
1925 return 0;
1926}
1927
a963990f
LP
1928int main(int argc, char *argv[]) {
1929 int r;
289f910e 1930 _cleanup_journal_close_ sd_journal *j = NULL;
a963990f 1931 bool need_seek = false;
14a65d65 1932 sd_id128_t previous_boot_id;
67e04a48
ZJS
1933 bool previous_boot_id_valid = false, first_line = true;
1934 int n_shown = 0;
94e0bd7d 1935 bool ellipsized = false;
a963990f 1936
a9cdc94f 1937 setlocale(LC_ALL, "");
a963990f
LP
1938 log_parse_environment();
1939 log_open();
1940
1941 r = parse_argv(argc, argv);
1942 if (r <= 0)
1943 goto finish;
1944
ed757c0c 1945 signal(SIGWINCH, columns_lines_cache_reset);
2cf4172a 1946 sigbus_install();
ed757c0c 1947
de45d726
LP
1948 /* Increase max number of open files to 16K if we can, we
1949 * might needs this when browsing journal files, which might
1950 * be split up into many files. */
1951 setrlimit_closest(RLIMIT_NOFILE, &RLIMIT_MAKE_CONST(16384));
1952
7560fffc 1953 if (arg_action == ACTION_NEW_ID128) {
a963990f
LP
1954 r = generate_new_id128();
1955 goto finish;
1956 }
1957
74055aa7
LP
1958 if (arg_action == ACTION_FLUSH) {
1959 r = flush_to_var();
1960 goto finish;
1961 }
1962
94b65516
LP
1963 if (arg_action == ACTION_SYNC) {
1964 r = sync_journal();
1965 goto finish;
1966 }
1967
e3fdfb49
EV
1968 if (arg_action == ACTION_ROTATE) {
1969 r = rotate();
1970 goto finish;
1971 }
1972
7560fffc
LP
1973 if (arg_action == ACTION_SETUP_KEYS) {
1974 r = setup_keys();
1975 goto finish;
1976 }
1977
844ec79b
ZJS
1978 if (arg_action == ACTION_UPDATE_CATALOG ||
1979 arg_action == ACTION_LIST_CATALOG ||
1980 arg_action == ACTION_DUMP_CATALOG) {
1981
0c6ea3a4
ZJS
1982 _cleanup_free_ char *database;
1983
1984 database = path_join(arg_root, CATALOG_DATABASE, NULL);
1985 if (!database) {
1986 r = log_oom();
1987 goto finish;
13cbf3a5
ZJS
1988 }
1989
844ec79b 1990 if (arg_action == ACTION_UPDATE_CATALOG) {
13cbf3a5 1991 r = catalog_update(database, arg_root, catalog_file_dirs);
844ec79b 1992 if (r < 0)
da927ba9 1993 log_error_errno(r, "Failed to list catalog: %m");
844ec79b
ZJS
1994 } else {
1995 bool oneline = arg_action == ACTION_LIST_CATALOG;
1996
dd598123 1997 pager_open_if_enabled();
844ec79b 1998 if (optind < argc)
13cbf3a5 1999 r = catalog_list_items(stdout, database,
844ec79b
ZJS
2000 oneline, argv + optind);
2001 else
13cbf3a5 2002 r = catalog_list(stdout, database, oneline);
844ec79b 2003 if (r < 0)
da927ba9 2004 log_error_errno(r, "Failed to list catalog: %m");
844ec79b 2005 }
d4205751 2006
d4205751
LP
2007 goto finish;
2008 }
2009
a963990f 2010 if (arg_directory)
3f3a438f 2011 r = sd_journal_open_directory(&j, arg_directory, arg_journal_type);
8d98da3f
ZJS
2012 else if (arg_file)
2013 r = sd_journal_open_files(&j, (const char**) arg_file, 0);
b6741478
LP
2014 else if (arg_machine)
2015 r = sd_journal_open_container(&j, arg_machine, 0);
a963990f 2016 else
3f3a438f 2017 r = sd_journal_open(&j, !arg_merge*SD_JOURNAL_LOCAL_ONLY + arg_journal_type);
a963990f 2018 if (r < 0) {
c33b3297
MS
2019 log_error_errno(r, "Failed to open %s: %m",
2020 arg_directory ? arg_directory : arg_file ? "files" : "journal");
909dea0c 2021 goto finish;
a963990f
LP
2022 }
2023
6fe391c5
ZJS
2024 r = access_check(j);
2025 if (r < 0)
909dea0c 2026 goto finish;
6fe391c5 2027
beec0085
LP
2028 if (arg_action == ACTION_VERIFY) {
2029 r = verify(j);
2030 goto finish;
2031 }
2032
7560fffc 2033 if (arg_action == ACTION_PRINT_HEADER) {
dca6219e 2034 journal_print_header(j);
909dea0c
LP
2035 r = 0;
2036 goto finish;
dca6219e
LP
2037 }
2038
a1a03e30 2039 if (arg_action == ACTION_DISK_USAGE) {
39883f62 2040 uint64_t bytes = 0;
a1a03e30
LP
2041 char sbytes[FORMAT_BYTES_MAX];
2042
2043 r = sd_journal_get_usage(j, &bytes);
2044 if (r < 0)
909dea0c 2045 goto finish;
a1a03e30 2046
dbd2a83f 2047 printf("Archived and active journals take up %s on disk.\n",
763c7aa2 2048 format_bytes(sbytes, sizeof(sbytes), bytes));
909dea0c 2049 goto finish;
a1a03e30
LP
2050 }
2051
dbd2a83f
LP
2052 if (arg_action == ACTION_VACUUM) {
2053 Directory *d;
2054 Iterator i;
2055
2056 HASHMAP_FOREACH(d, j->directories_by_path, i) {
2057 int q;
2058
2059 if (d->is_root)
2060 continue;
2061
8580d1f7 2062 q = journal_directory_vacuum(d->path, arg_vacuum_size, arg_vacuum_n_files, arg_vacuum_time, NULL, true);
dbd2a83f 2063 if (q < 0) {
8580d1f7 2064 log_error_errno(q, "Failed to vacuum %s: %m", d->path);
dbd2a83f
LP
2065 r = q;
2066 }
2067 }
2068
909dea0c 2069 goto finish;
dbd2a83f
LP
2070 }
2071
f1188074
ZJS
2072 if (arg_action == ACTION_LIST_BOOTS) {
2073 r = list_boots(j);
2074 goto finish;
2075 }
2076
a331b5e6
JJ
2077 /* add_boot() must be called first!
2078 * It may need to seek the journal to find parent boot IDs. */
2079 r = add_boot(j);
a963990f 2080 if (r < 0)
909dea0c 2081 goto finish;
a963990f 2082
99271804
ZJS
2083 r = add_dmesg(j);
2084 if (r < 0)
909dea0c 2085 goto finish;
99271804 2086
b9e40524 2087 r = add_units(j);
ea18a4b5 2088 if (r < 0) {
da927ba9 2089 log_error_errno(r, "Failed to add filter for units: %m");
909dea0c 2090 goto finish;
ea18a4b5 2091 }
c3f60ec5 2092
73083640
HH
2093 r = add_syslog_identifier(j);
2094 if (r < 0) {
da927ba9 2095 log_error_errno(r, "Failed to add filter for syslog identifiers: %m");
909dea0c 2096 goto finish;
73083640
HH
2097 }
2098
cd34b3c6 2099 r = add_priorities(j);
b56d608e 2100 if (r < 0)
909dea0c 2101 goto finish;
a963990f 2102
cd34b3c6 2103 r = add_matches(j, argv + optind);
b56d608e 2104 if (r < 0)
909dea0c 2105 goto finish;
941e990d 2106
553d2243 2107 if (_unlikely_(log_get_max_level() >= LOG_DEBUG)) {
4ad16808
ZJS
2108 _cleanup_free_ char *filter;
2109
2110 filter = journal_make_match_string(j);
b56d608e
LP
2111 if (!filter)
2112 return log_oom();
2113
4ad16808
ZJS
2114 log_debug("Journal filter: %s", filter);
2115 }
67e04a48 2116
15119c16
LP
2117 if (arg_field) {
2118 const void *data;
2119 size_t size;
2120
21ae4593
ZJS
2121 r = sd_journal_set_data_threshold(j, 0);
2122 if (r < 0) {
b56d608e 2123 log_error_errno(r, "Failed to unset data size threshold: %m");
909dea0c 2124 goto finish;
21ae4593
ZJS
2125 }
2126
15119c16
LP
2127 r = sd_journal_query_unique(j, arg_field);
2128 if (r < 0) {
da927ba9 2129 log_error_errno(r, "Failed to query unique data objects: %m");
909dea0c 2130 goto finish;
15119c16
LP
2131 }
2132
2133 SD_JOURNAL_FOREACH_UNIQUE(j, data, size) {
2134 const void *eq;
2135
67e04a48 2136 if (arg_lines >= 0 && n_shown >= arg_lines)
fd6e8875
LP
2137 break;
2138
15119c16
LP
2139 eq = memchr(data, '=', size);
2140 if (eq)
2141 printf("%.*s\n", (int) (size - ((const uint8_t*) eq - (const uint8_t*) data + 1)), (const char*) eq + 1);
2142 else
2143 printf("%.*s\n", (int) size, (const char*) data);
fd6e8875
LP
2144
2145 n_shown ++;
15119c16
LP
2146 }
2147
909dea0c
LP
2148 r = 0;
2149 goto finish;
15119c16
LP
2150 }
2151
8d98da3f
ZJS
2152 /* Opening the fd now means the first sd_journal_wait() will actually wait */
2153 if (arg_follow) {
2154 r = sd_journal_get_fd(j);
b56d608e
LP
2155 if (r < 0) {
2156 log_error_errno(r, "Failed to get journal fd: %m");
909dea0c 2157 goto finish;
b56d608e 2158 }
8d98da3f
ZJS
2159 }
2160
248fc619 2161 if (arg_cursor || arg_after_cursor) {
eacbb4d3 2162 r = sd_journal_seek_cursor(j, arg_cursor ?: arg_after_cursor);
08984293 2163 if (r < 0) {
da927ba9 2164 log_error_errno(r, "Failed to seek to cursor: %m");
909dea0c 2165 goto finish;
08984293 2166 }
909dea0c 2167
d89d6c86 2168 if (!arg_reverse)
248fc619 2169 r = sd_journal_next_skip(j, 1 + !!arg_after_cursor);
d89d6c86 2170 else
248fc619
ZJS
2171 r = sd_journal_previous_skip(j, 1 + !!arg_after_cursor);
2172
8ee8e536 2173 if (arg_after_cursor && r < 2) {
248fc619 2174 /* We couldn't find the next entry after the cursor. */
8ee8e536
WD
2175 if (arg_follow)
2176 need_seek = true;
2177 else
2178 arg_lines = 0;
2179 }
08984293 2180
d89d6c86 2181 } else if (arg_since_set && !arg_reverse) {
cfbc22ab 2182 r = sd_journal_seek_realtime_usec(j, arg_since);
8f14c832 2183 if (r < 0) {
da927ba9 2184 log_error_errno(r, "Failed to seek to date: %m");
909dea0c 2185 goto finish;
8f14c832 2186 }
8f14c832
LP
2187 r = sd_journal_next(j);
2188
d89d6c86
LN
2189 } else if (arg_until_set && arg_reverse) {
2190 r = sd_journal_seek_realtime_usec(j, arg_until);
2191 if (r < 0) {
da927ba9 2192 log_error_errno(r, "Failed to seek to date: %m");
909dea0c 2193 goto finish;
d89d6c86
LN
2194 }
2195 r = sd_journal_previous(j);
2196
67e04a48 2197 } else if (arg_lines >= 0) {
2100675e
LP
2198 r = sd_journal_seek_tail(j);
2199 if (r < 0) {
da927ba9 2200 log_error_errno(r, "Failed to seek to tail: %m");
909dea0c 2201 goto finish;
2100675e
LP
2202 }
2203
2204 r = sd_journal_previous_skip(j, arg_lines);
8f14c832 2205
d89d6c86
LN
2206 } else if (arg_reverse) {
2207 r = sd_journal_seek_tail(j);
2208 if (r < 0) {
da927ba9 2209 log_error_errno(r, "Failed to seek to tail: %m");
909dea0c 2210 goto finish;
d89d6c86
LN
2211 }
2212
2213 r = sd_journal_previous(j);
2214
2100675e
LP
2215 } else {
2216 r = sd_journal_seek_head(j);
2217 if (r < 0) {
da927ba9 2218 log_error_errno(r, "Failed to seek to head: %m");
909dea0c 2219 goto finish;
2100675e 2220 }
6f003b43
LP
2221
2222 r = sd_journal_next(j);
2223 }
2224
2225 if (r < 0) {
da927ba9 2226 log_error_errno(r, "Failed to iterate through journal: %m");
909dea0c 2227 goto finish;
50f20cfd 2228 }
02ab86c7 2229 if (r == 0) {
c51e1a96
SW
2230 if (arg_follow)
2231 need_seek = true;
2232 else {
2233 printf("-- No entries --\n");
2234 goto finish;
2235 }
02ab86c7 2236 }
87d2c1ff 2237
faf5077f
DH
2238 if (!arg_follow)
2239 pager_open_if_enabled();
0d43c694 2240
cfbc22ab
LP
2241 if (!arg_quiet) {
2242 usec_t start, end;
2243 char start_buf[FORMAT_TIMESTAMP_MAX], end_buf[FORMAT_TIMESTAMP_MAX];
2244
2245 r = sd_journal_get_cutoff_realtime_usec(j, &start, &end);
2246 if (r < 0) {
da927ba9 2247 log_error_errno(r, "Failed to get cutoff: %m");
cfbc22ab
LP
2248 goto finish;
2249 }
2250
2251 if (r > 0) {
2252 if (arg_follow)
9048b11f 2253 printf("-- Logs begin at %s. --\n",
5ab99e07 2254 format_timestamp_maybe_utc(start_buf, sizeof(start_buf), start));
cfbc22ab 2255 else
9048b11f 2256 printf("-- Logs begin at %s, end at %s. --\n",
5ab99e07
LP
2257 format_timestamp_maybe_utc(start_buf, sizeof(start_buf), start),
2258 format_timestamp_maybe_utc(end_buf, sizeof(end_buf), end));
cfbc22ab
LP
2259 }
2260 }
2261
50f20cfd 2262 for (;;) {
67e04a48 2263 while (arg_lines < 0 || n_shown < arg_lines || (arg_follow && !first_line)) {
cfbc22ab
LP
2264 int flags;
2265
6f003b43 2266 if (need_seek) {
99613ec5 2267 if (!arg_reverse)
d89d6c86
LN
2268 r = sd_journal_next(j);
2269 else
2270 r = sd_journal_previous(j);
6f003b43 2271 if (r < 0) {
da927ba9 2272 log_error_errno(r, "Failed to iterate through journal: %m");
6f003b43
LP
2273 goto finish;
2274 }
a72b6353
ZJS
2275 if (r == 0)
2276 break;
0d43c694
LP
2277 }
2278
d89d6c86 2279 if (arg_until_set && !arg_reverse) {
cfbc22ab
LP
2280 usec_t usec;
2281
2282 r = sd_journal_get_realtime_usec(j, &usec);
2283 if (r < 0) {
da927ba9 2284 log_error_errno(r, "Failed to determine timestamp: %m");
cfbc22ab
LP
2285 goto finish;
2286 }
3ba09ee8
PF
2287 if (usec > arg_until)
2288 goto finish;
cfbc22ab
LP
2289 }
2290
d89d6c86
LN
2291 if (arg_since_set && arg_reverse) {
2292 usec_t usec;
2293
2294 r = sd_journal_get_realtime_usec(j, &usec);
2295 if (r < 0) {
da927ba9 2296 log_error_errno(r, "Failed to determine timestamp: %m");
d89d6c86
LN
2297 goto finish;
2298 }
2299 if (usec < arg_since)
2300 goto finish;
2301 }
2302
4bed2485 2303 if (!arg_merge && !arg_quiet) {
cd931c0a 2304 sd_id128_t boot_id;
14a65d65 2305
cd931c0a
LP
2306 r = sd_journal_get_monotonic_usec(j, NULL, &boot_id);
2307 if (r >= 0) {
2308 if (previous_boot_id_valid &&
2309 !sd_id128_equal(boot_id, previous_boot_id))
0b5a519c 2310 printf("%s-- Reboot --%s\n",
1fc464f6 2311 ansi_highlight(), ansi_normal());
cd931c0a
LP
2312
2313 previous_boot_id = boot_id;
2314 previous_boot_id_valid = true;
2315 }
14a65d65
LP
2316 }
2317
cfbc22ab 2318 flags =
cd4b13e0 2319 arg_all * OUTPUT_SHOW_ALL |
2b8f6883 2320 arg_full * OUTPUT_FULL_WIDTH |
d4205751 2321 on_tty() * OUTPUT_COLOR |
9fd29044
JS
2322 arg_catalog * OUTPUT_CATALOG |
2323 arg_utc * OUTPUT_UTC;
cfbc22ab 2324
94e0bd7d 2325 r = output_journal(stdout, j, arg_output, 0, flags, &ellipsized);
a72b6353
ZJS
2326 need_seek = true;
2327 if (r == -EADDRNOTAVAIL)
2328 break;
2329 else if (r < 0 || ferror(stdout))
72f59706 2330 goto finish;
6f003b43 2331
cfbc22ab 2332 n_shown++;
87d2c1ff
LP
2333 }
2334
248fc619
ZJS
2335 if (!arg_follow) {
2336 if (arg_show_cursor) {
2337 _cleanup_free_ char *cursor = NULL;
2338
2339 r = sd_journal_get_cursor(j, &cursor);
2340 if (r < 0 && r != -EADDRNOTAVAIL)
da927ba9 2341 log_error_errno(r, "Failed to get cursor: %m");
248fc619
ZJS
2342 else if (r >= 0)
2343 printf("-- cursor: %s\n", cursor);
2344 }
2345
50f20cfd 2346 break;
248fc619 2347 }
50f20cfd 2348
e02d1cf7 2349 r = sd_journal_wait(j, (uint64_t) -1);
50f20cfd 2350 if (r < 0) {
da927ba9 2351 log_error_errno(r, "Couldn't wait for journal event: %m");
50f20cfd
LP
2352 goto finish;
2353 }
67e04a48
ZJS
2354
2355 first_line = false;
de190aef 2356 }
87d2c1ff
LP
2357
2358finish:
0d43c694
LP
2359 pager_close();
2360
a36b8deb
ZJS
2361 strv_free(arg_file);
2362
d52da205
LP
2363 strv_free(arg_syslog_identifier);
2364 strv_free(arg_system_units);
2365 strv_free(arg_user_units);
2366
0f03c2a4
LP
2367 free(arg_root);
2368
3fbf9cbb 2369 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
87d2c1ff 2370}