]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/logs-show.c
Merge pull request #13010 from poettering/fsck-usr-wants
[thirdparty/systemd.git] / src / shared / logs-show.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <signal.h>
6 #include <stdint.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/socket.h>
10 #include <syslog.h>
11 #include <time.h>
12 #include <unistd.h>
13
14 #include "sd-id128.h"
15 #include "sd-journal.h"
16
17 #include "alloc-util.h"
18 #include "fd-util.h"
19 #include "format-util.h"
20 #include "hashmap.h"
21 #include "hostname-util.h"
22 #include "io-util.h"
23 #include "journal-internal.h"
24 #include "json.h"
25 #include "log.h"
26 #include "logs-show.h"
27 #include "macro.h"
28 #include "namespace-util.h"
29 #include "output-mode.h"
30 #include "parse-util.h"
31 #include "process-util.h"
32 #include "pretty-print.h"
33 #include "sparse-endian.h"
34 #include "stdio-util.h"
35 #include "string-table.h"
36 #include "string-util.h"
37 #include "strv.h"
38 #include "terminal-util.h"
39 #include "time-util.h"
40 #include "utf8.h"
41 #include "util.h"
42
43 /* up to three lines (each up to 100 characters) or 300 characters, whichever is less */
44 #define PRINT_LINE_THRESHOLD 3
45 #define PRINT_CHAR_THRESHOLD 300
46
47 #define JSON_THRESHOLD 4096U
48
49 static int print_catalog(FILE *f, sd_journal *j) {
50 int r;
51 _cleanup_free_ char *t = NULL, *z = NULL;
52
53 r = sd_journal_get_catalog(j, &t);
54 if (r < 0)
55 return r;
56
57 z = strreplace(strstrip(t), "\n", "\n-- ");
58 if (!z)
59 return log_oom();
60
61 fputs("-- ", f);
62 fputs(z, f);
63 fputc('\n', f);
64
65 return 0;
66 }
67
68 static int parse_field(const void *data, size_t length, const char *field, size_t field_len, char **target, size_t *target_len) {
69 size_t nl;
70 char *buf;
71
72 assert(data);
73 assert(field);
74 assert(target);
75
76 if (length < field_len)
77 return 0;
78
79 if (memcmp(data, field, field_len))
80 return 0;
81
82 nl = length - field_len;
83
84 buf = newdup_suffix0(char, (const char*) data + field_len, nl);
85 if (!buf)
86 return log_oom();
87
88 free(*target);
89 *target = buf;
90
91 if (target_len)
92 *target_len = nl;
93
94 return 1;
95 }
96
97 typedef struct ParseFieldVec {
98 const char *field;
99 size_t field_len;
100 char **target;
101 size_t *target_len;
102 } ParseFieldVec;
103
104 #define PARSE_FIELD_VEC_ENTRY(_field, _target, _target_len) \
105 { .field = _field, .field_len = strlen(_field), .target = _target, .target_len = _target_len }
106
107 static int parse_fieldv(const void *data, size_t length, const ParseFieldVec *fields, unsigned n_fields) {
108 unsigned i;
109
110 for (i = 0; i < n_fields; i++) {
111 const ParseFieldVec *f = &fields[i];
112 int r;
113
114 r = parse_field(data, length, f->field, f->field_len, f->target, f->target_len);
115 if (r < 0)
116 return r;
117 else if (r > 0)
118 break;
119 }
120
121 return 0;
122 }
123
124 static int field_set_test(Set *fields, const char *name, size_t n) {
125 char *s = NULL;
126
127 if (!fields)
128 return 1;
129
130 s = strndupa(name, n);
131 if (!s)
132 return log_oom();
133
134 return set_get(fields, s) ? 1 : 0;
135 }
136
137 static bool shall_print(const char *p, size_t l, OutputFlags flags) {
138 assert(p);
139
140 if (flags & OUTPUT_SHOW_ALL)
141 return true;
142
143 if (l >= PRINT_CHAR_THRESHOLD)
144 return false;
145
146 if (!utf8_is_printable(p, l))
147 return false;
148
149 return true;
150 }
151
152 static bool print_multiline(
153 FILE *f,
154 unsigned prefix,
155 unsigned n_columns,
156 OutputFlags flags,
157 int priority,
158 bool audit,
159 const char* message,
160 size_t message_len,
161 size_t highlight[2]) {
162
163 const char *color_on = "", *color_off = "", *highlight_on = "";
164 const char *pos, *end;
165 bool ellipsized = false;
166 int line = 0;
167
168 if (flags & OUTPUT_COLOR) {
169 get_log_colors(priority, &color_on, &color_off, &highlight_on);
170
171 if (audit && strempty(color_on)) {
172 color_on = ANSI_BLUE;
173 color_off = ANSI_NORMAL;
174 }
175 }
176
177 /* A special case: make sure that we print a newline when
178 the message is empty. */
179 if (message_len == 0)
180 fputs("\n", f);
181
182 for (pos = message;
183 pos < message + message_len;
184 pos = end + 1, line++) {
185 bool continuation = line > 0;
186 bool tail_line;
187 int len;
188 for (end = pos; end < message + message_len && *end != '\n'; end++)
189 ;
190 len = end - pos;
191 assert(len >= 0);
192
193 /* We need to figure out when we are showing not-last line, *and*
194 * will skip subsequent lines. In that case, we will put the dots
195 * at the end of the line, instead of putting dots in the middle
196 * or not at all.
197 */
198 tail_line =
199 line + 1 == PRINT_LINE_THRESHOLD ||
200 end + 1 >= message + PRINT_CHAR_THRESHOLD;
201
202 if (flags & (OUTPUT_FULL_WIDTH | OUTPUT_SHOW_ALL) ||
203 (prefix + len + 1 < n_columns && !tail_line)) {
204 if (highlight &&
205 (size_t) (pos - message) <= highlight[0] &&
206 highlight[0] < (size_t) len) {
207
208 fprintf(f, "%*s%s%.*s",
209 continuation * prefix, "",
210 color_on, (int) highlight[0], pos);
211 fprintf(f, "%s%.*s",
212 highlight_on,
213 (int) (MIN((size_t) len, highlight[1]) - highlight[0]),
214 pos + highlight[0]);
215 if ((size_t) len > highlight[1])
216 fprintf(f, "%s%.*s",
217 color_on,
218 (int) (len - highlight[1]),
219 pos + highlight[1]);
220 fprintf(f, "%s\n", color_off);
221
222 } else
223 fprintf(f, "%*s%s%.*s%s\n",
224 continuation * prefix, "",
225 color_on, len, pos, color_off);
226 continue;
227 }
228
229 /* Beyond this point, ellipsization will happen. */
230 ellipsized = true;
231
232 if (prefix < n_columns && n_columns - prefix >= 3) {
233 if (n_columns - prefix > (unsigned) len + 3)
234 fprintf(f, "%*s%s%.*s...%s\n",
235 continuation * prefix, "",
236 color_on, len, pos, color_off);
237 else {
238 _cleanup_free_ char *e;
239
240 e = ellipsize_mem(pos, len, n_columns - prefix,
241 tail_line ? 100 : 90);
242 if (!e)
243 fprintf(f, "%*s%s%.*s%s\n",
244 continuation * prefix, "",
245 color_on, len, pos, color_off);
246 else
247 fprintf(f, "%*s%s%s%s\n",
248 continuation * prefix, "",
249 color_on, e, color_off);
250 }
251 } else
252 fputs("...\n", f);
253
254 if (tail_line)
255 break;
256 }
257
258 return ellipsized;
259 }
260
261 static int output_timestamp_monotonic(FILE *f, sd_journal *j, const char *monotonic) {
262 sd_id128_t boot_id;
263 uint64_t t;
264 int r;
265
266 assert(f);
267 assert(j);
268
269 r = -ENXIO;
270 if (monotonic)
271 r = safe_atou64(monotonic, &t);
272 if (r < 0)
273 r = sd_journal_get_monotonic_usec(j, &t, &boot_id);
274 if (r < 0)
275 return log_error_errno(r, "Failed to get monotonic timestamp: %m");
276
277 fprintf(f, "[%5"PRI_USEC".%06"PRI_USEC"]", t / USEC_PER_SEC, t % USEC_PER_SEC);
278 return 1 + 5 + 1 + 6 + 1;
279 }
280
281 static int output_timestamp_realtime(FILE *f, sd_journal *j, OutputMode mode, OutputFlags flags, const char *realtime) {
282 char buf[MAX(FORMAT_TIMESTAMP_MAX, 64)];
283 struct tm *(*gettime_r)(const time_t *, struct tm *);
284 struct tm tm;
285 uint64_t x;
286 time_t t;
287 int r;
288
289 assert(f);
290 assert(j);
291
292 if (realtime)
293 r = safe_atou64(realtime, &x);
294 if (!realtime || r < 0 || !VALID_REALTIME(x))
295 r = sd_journal_get_realtime_usec(j, &x);
296 if (r < 0)
297 return log_error_errno(r, "Failed to get realtime timestamp: %m");
298
299 if (IN_SET(mode, OUTPUT_SHORT_FULL, OUTPUT_WITH_UNIT)) {
300 const char *k;
301
302 if (flags & OUTPUT_UTC)
303 k = format_timestamp_utc(buf, sizeof(buf), x);
304 else
305 k = format_timestamp(buf, sizeof(buf), x);
306 if (!k)
307 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
308 "Failed to format timestamp: %" PRIu64, x);
309
310 } else {
311 char usec[7];
312
313 gettime_r = (flags & OUTPUT_UTC) ? gmtime_r : localtime_r;
314 t = (time_t) (x / USEC_PER_SEC);
315
316 switch (mode) {
317
318 case OUTPUT_SHORT_UNIX:
319 xsprintf(buf, "%10"PRI_TIME".%06"PRIu64, t, x % USEC_PER_SEC);
320 break;
321
322 case OUTPUT_SHORT_ISO:
323 if (strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S%z", gettime_r(&t, &tm)) <= 0)
324 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
325 "Failed to format ISO time");
326 break;
327
328 case OUTPUT_SHORT_ISO_PRECISE:
329 /* No usec in strftime, so we leave space and copy over */
330 if (strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.xxxxxx%z", gettime_r(&t, &tm)) <= 0)
331 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
332 "Failed to format ISO-precise time");
333 xsprintf(usec, "%06"PRI_USEC, x % USEC_PER_SEC);
334 memcpy(buf + 20, usec, 6);
335 break;
336
337 case OUTPUT_SHORT:
338 case OUTPUT_SHORT_PRECISE:
339
340 if (strftime(buf, sizeof(buf), "%b %d %H:%M:%S", gettime_r(&t, &tm)) <= 0)
341 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
342 "Failed to format syslog time");
343
344 if (mode == OUTPUT_SHORT_PRECISE) {
345 size_t k;
346
347 assert(sizeof(buf) > strlen(buf));
348 k = sizeof(buf) - strlen(buf);
349
350 r = snprintf(buf + strlen(buf), k, ".%06"PRIu64, x % USEC_PER_SEC);
351 if (r <= 0 || (size_t) r >= k) /* too long? */
352 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
353 "Failed to format precise time");
354 }
355 break;
356
357 default:
358 assert_not_reached("Unknown time format");
359 }
360 }
361
362 fputs(buf, f);
363 return (int) strlen(buf);
364 }
365
366 static int output_short(
367 FILE *f,
368 sd_journal *j,
369 OutputMode mode,
370 unsigned n_columns,
371 OutputFlags flags,
372 Set *output_fields,
373 const size_t highlight[2]) {
374
375 int r;
376 const void *data;
377 size_t length;
378 size_t n = 0;
379 _cleanup_free_ char *hostname = NULL, *identifier = NULL, *comm = NULL, *pid = NULL, *fake_pid = NULL, *message = NULL, *realtime = NULL, *monotonic = NULL, *priority = NULL, *transport = NULL, *config_file = NULL, *unit = NULL, *user_unit = NULL;
380 size_t hostname_len = 0, identifier_len = 0, comm_len = 0, pid_len = 0, fake_pid_len = 0, message_len = 0, realtime_len = 0, monotonic_len = 0, priority_len = 0, transport_len = 0, config_file_len = 0, unit_len = 0, user_unit_len = 0;
381 int p = LOG_INFO;
382 bool ellipsized = false, audit;
383 const ParseFieldVec fields[] = {
384 PARSE_FIELD_VEC_ENTRY("_PID=", &pid, &pid_len),
385 PARSE_FIELD_VEC_ENTRY("_COMM=", &comm, &comm_len),
386 PARSE_FIELD_VEC_ENTRY("MESSAGE=", &message, &message_len),
387 PARSE_FIELD_VEC_ENTRY("PRIORITY=", &priority, &priority_len),
388 PARSE_FIELD_VEC_ENTRY("_TRANSPORT=", &transport, &transport_len),
389 PARSE_FIELD_VEC_ENTRY("_HOSTNAME=", &hostname, &hostname_len),
390 PARSE_FIELD_VEC_ENTRY("SYSLOG_PID=", &fake_pid, &fake_pid_len),
391 PARSE_FIELD_VEC_ENTRY("SYSLOG_IDENTIFIER=", &identifier, &identifier_len),
392 PARSE_FIELD_VEC_ENTRY("_SOURCE_REALTIME_TIMESTAMP=", &realtime, &realtime_len),
393 PARSE_FIELD_VEC_ENTRY("_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic, &monotonic_len),
394 PARSE_FIELD_VEC_ENTRY("CONFIG_FILE=", &config_file, &config_file_len),
395 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_UNIT=", &unit, &unit_len),
396 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_USER_UNIT=", &user_unit, &user_unit_len),
397 };
398 size_t highlight_shifted[] = {highlight ? highlight[0] : 0, highlight ? highlight[1] : 0};
399
400 assert(f);
401 assert(j);
402
403 /* Set the threshold to one bigger than the actual print
404 * threshold, so that if the line is actually longer than what
405 * we're willing to print, ellipsization will occur. This way
406 * we won't output a misleading line without any indication of
407 * truncation.
408 */
409 sd_journal_set_data_threshold(j, flags & (OUTPUT_SHOW_ALL|OUTPUT_FULL_WIDTH) ? 0 : PRINT_CHAR_THRESHOLD + 1);
410
411 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
412 r = parse_fieldv(data, length, fields, ELEMENTSOF(fields));
413 if (r < 0)
414 return r;
415 }
416 if (r == -EBADMSG) {
417 log_debug_errno(r, "Skipping message we can't read: %m");
418 return 0;
419 }
420 if (r < 0)
421 return log_error_errno(r, "Failed to get journal fields: %m");
422
423 if (!message) {
424 log_debug("Skipping message without MESSAGE= field.");
425 return 0;
426 }
427
428 if (!(flags & OUTPUT_SHOW_ALL))
429 strip_tab_ansi(&message, &message_len, highlight_shifted);
430
431 if (priority_len == 1 && *priority >= '0' && *priority <= '7')
432 p = *priority - '0';
433
434
435 audit = streq_ptr(transport, "audit");
436
437 if (mode == OUTPUT_SHORT_MONOTONIC)
438 r = output_timestamp_monotonic(f, j, monotonic);
439 else
440 r = output_timestamp_realtime(f, j, mode, flags, realtime);
441 if (r < 0)
442 return r;
443 n += r;
444
445 if (flags & OUTPUT_NO_HOSTNAME) {
446 /* Suppress display of the hostname if this is requested. */
447 hostname = mfree(hostname);
448 hostname_len = 0;
449 }
450
451 if (hostname && shall_print(hostname, hostname_len, flags)) {
452 fprintf(f, " %.*s", (int) hostname_len, hostname);
453 n += hostname_len + 1;
454 }
455
456 if (mode == OUTPUT_WITH_UNIT && ((unit && shall_print(unit, unit_len, flags)) ||
457 (user_unit && shall_print(user_unit, user_unit_len, flags)))) {
458 if (unit) {
459 fprintf(f, " %.*s", (int) unit_len, unit);
460 n += unit_len + 1;
461 }
462 if (user_unit) {
463 if (unit)
464 fprintf(f, "/%.*s", (int) user_unit_len, user_unit);
465 else
466 fprintf(f, " %.*s", (int) user_unit_len, user_unit);
467 n += unit_len + 1;
468 }
469 } else if (identifier && shall_print(identifier, identifier_len, flags)) {
470 fprintf(f, " %.*s", (int) identifier_len, identifier);
471 n += identifier_len + 1;
472 } else if (comm && shall_print(comm, comm_len, flags)) {
473 fprintf(f, " %.*s", (int) comm_len, comm);
474 n += comm_len + 1;
475 } else
476 fputs(" unknown", f);
477
478 if (pid && shall_print(pid, pid_len, flags)) {
479 fprintf(f, "[%.*s]", (int) pid_len, pid);
480 n += pid_len + 2;
481 } else if (fake_pid && shall_print(fake_pid, fake_pid_len, flags)) {
482 fprintf(f, "[%.*s]", (int) fake_pid_len, fake_pid);
483 n += fake_pid_len + 2;
484 }
485
486 if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(message, message_len)) {
487 char bytes[FORMAT_BYTES_MAX];
488 fprintf(f, ": [%s blob data]\n", format_bytes(bytes, sizeof(bytes), message_len));
489 } else {
490 fputs(": ", f);
491
492 /* URLify config_file string in message, if the message starts with it.
493 * Skip URLification if the highlighted pattern overlaps. */
494 if (config_file &&
495 message_len >= config_file_len &&
496 memcmp(message, config_file, config_file_len) == 0 &&
497 IN_SET(message[config_file_len], ':', ' ', '\0') &&
498 (!highlight || highlight_shifted[0] == 0 || highlight_shifted[0] > config_file_len)) {
499
500 _cleanup_free_ char *t = NULL, *urlified = NULL;
501
502 t = strndup(config_file, config_file_len);
503 if (t && terminal_urlify_path(t, NULL, &urlified) >= 0) {
504 size_t shift = strlen(urlified) - config_file_len;
505 char *joined;
506
507 joined = strjoin(urlified, message + config_file_len);
508 if (joined) {
509 free_and_replace(message, joined);
510 message_len += shift;
511 if (highlight) {
512 highlight_shifted[0] += shift;
513 highlight_shifted[1] += shift;
514 }
515 }
516 }
517 }
518
519 ellipsized |=
520 print_multiline(f, n + 2, n_columns, flags, p, audit,
521 message, message_len,
522 highlight_shifted);
523 }
524
525 if (flags & OUTPUT_CATALOG)
526 print_catalog(f, j);
527
528 return ellipsized;
529 }
530
531 static int output_verbose(
532 FILE *f,
533 sd_journal *j,
534 OutputMode mode,
535 unsigned n_columns,
536 OutputFlags flags,
537 Set *output_fields,
538 const size_t highlight[2]) {
539
540 const void *data;
541 size_t length;
542 _cleanup_free_ char *cursor = NULL;
543 uint64_t realtime = 0;
544 char ts[FORMAT_TIMESTAMP_MAX + 7];
545 const char *timestamp;
546 int r;
547
548 assert(f);
549 assert(j);
550
551 sd_journal_set_data_threshold(j, 0);
552
553 r = sd_journal_get_data(j, "_SOURCE_REALTIME_TIMESTAMP", &data, &length);
554 if (r == -ENOENT)
555 log_debug("Source realtime timestamp not found");
556 else if (r < 0)
557 return log_full_errno(r == -EADDRNOTAVAIL ? LOG_DEBUG : LOG_ERR, r, "Failed to get source realtime timestamp: %m");
558 else {
559 _cleanup_free_ char *value = NULL;
560
561 r = parse_field(data, length, "_SOURCE_REALTIME_TIMESTAMP=",
562 STRLEN("_SOURCE_REALTIME_TIMESTAMP="), &value,
563 NULL);
564 if (r < 0)
565 return r;
566 assert(r > 0);
567
568 r = safe_atou64(value, &realtime);
569 if (r < 0)
570 log_debug_errno(r, "Failed to parse realtime timestamp: %m");
571 }
572
573 if (r < 0) {
574 r = sd_journal_get_realtime_usec(j, &realtime);
575 if (r < 0)
576 return log_full_errno(r == -EADDRNOTAVAIL ? LOG_DEBUG : LOG_ERR, r, "Failed to get realtime timestamp: %m");
577 }
578
579 r = sd_journal_get_cursor(j, &cursor);
580 if (r < 0)
581 return log_error_errno(r, "Failed to get cursor: %m");
582
583 timestamp = flags & OUTPUT_UTC ? format_timestamp_us_utc(ts, sizeof ts, realtime)
584 : format_timestamp_us(ts, sizeof ts, realtime);
585 fprintf(f, "%s [%s]\n",
586 timestamp ?: "(no timestamp)",
587 cursor);
588
589 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
590 const char *c, *p;
591 int fieldlen;
592 const char *on = "", *off = "";
593 _cleanup_free_ char *urlified = NULL;
594 size_t valuelen;
595
596 c = memchr(data, '=', length);
597 if (!c)
598 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
599 "Invalid field.");
600 fieldlen = c - (const char*) data;
601
602 r = field_set_test(output_fields, data, fieldlen);
603 if (r < 0)
604 return r;
605 if (r == 0)
606 continue;
607
608 valuelen = length - 1 - fieldlen;
609
610 if ((flags & OUTPUT_COLOR) && (p = startswith(data, "MESSAGE="))) {
611 on = ANSI_HIGHLIGHT;
612 off = ANSI_NORMAL;
613 } else if ((p = startswith(data, "CONFIG_FILE="))) {
614 if (terminal_urlify_path(p, NULL, &urlified) >= 0) {
615 p = urlified;
616 valuelen = strlen(urlified);
617 }
618 } else
619 p = c + 1;
620
621 if ((flags & OUTPUT_SHOW_ALL) ||
622 (((length < PRINT_CHAR_THRESHOLD) || flags & OUTPUT_FULL_WIDTH)
623 && utf8_is_printable(data, length))) {
624 fprintf(f, " %s%.*s=", on, fieldlen, (const char*)data);
625 print_multiline(f, 4 + fieldlen + 1, 0, OUTPUT_FULL_WIDTH, 0, false,
626 p, valuelen,
627 NULL);
628 fputs(off, f);
629 } else {
630 char bytes[FORMAT_BYTES_MAX];
631
632 fprintf(f, " %s%.*s=[%s blob data]%s\n",
633 on,
634 (int) (c - (const char*) data),
635 (const char*) data,
636 format_bytes(bytes, sizeof(bytes), length - (c - (const char *) data) - 1),
637 off);
638 }
639 }
640
641 if (r < 0)
642 return r;
643
644 if (flags & OUTPUT_CATALOG)
645 print_catalog(f, j);
646
647 return 0;
648 }
649
650 static int output_export(
651 FILE *f,
652 sd_journal *j,
653 OutputMode mode,
654 unsigned n_columns,
655 OutputFlags flags,
656 Set *output_fields,
657 const size_t highlight[2]) {
658
659 sd_id128_t boot_id;
660 char sid[33];
661 int r;
662 usec_t realtime, monotonic;
663 _cleanup_free_ char *cursor = NULL;
664 const void *data;
665 size_t length;
666
667 assert(j);
668
669 sd_journal_set_data_threshold(j, 0);
670
671 r = sd_journal_get_realtime_usec(j, &realtime);
672 if (r < 0)
673 return log_error_errno(r, "Failed to get realtime timestamp: %m");
674
675 r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
676 if (r < 0)
677 return log_error_errno(r, "Failed to get monotonic timestamp: %m");
678
679 r = sd_journal_get_cursor(j, &cursor);
680 if (r < 0)
681 return log_error_errno(r, "Failed to get cursor: %m");
682
683 fprintf(f,
684 "__CURSOR=%s\n"
685 "__REALTIME_TIMESTAMP="USEC_FMT"\n"
686 "__MONOTONIC_TIMESTAMP="USEC_FMT"\n"
687 "_BOOT_ID=%s\n",
688 cursor,
689 realtime,
690 monotonic,
691 sd_id128_to_string(boot_id, sid));
692
693 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
694 const char *c;
695
696 /* We already printed the boot id from the data in the header, hence let's suppress it here */
697 if (memory_startswith(data, length, "_BOOT_ID="))
698 continue;
699
700 c = memchr(data, '=', length);
701 if (!c)
702 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
703 "Invalid field.");
704
705 r = field_set_test(output_fields, data, c - (const char *) data);
706 if (r < 0)
707 return r;
708 if (!r)
709 continue;
710
711 if (utf8_is_printable_newline(data, length, false))
712 fwrite(data, length, 1, f);
713 else {
714 uint64_t le64;
715
716 fwrite(data, c - (const char*) data, 1, f);
717 fputc('\n', f);
718 le64 = htole64(length - (c - (const char*) data) - 1);
719 fwrite(&le64, sizeof(le64), 1, f);
720 fwrite(c + 1, length - (c - (const char*) data) - 1, 1, f);
721 }
722
723 fputc('\n', f);
724 }
725 if (r == -EBADMSG) {
726 log_debug_errno(r, "Skipping message we can't read: %m");
727 return 0;
728 }
729
730 if (r < 0)
731 return r;
732
733 fputc('\n', f);
734
735 return 0;
736 }
737
738 void json_escape(
739 FILE *f,
740 const char* p,
741 size_t l,
742 OutputFlags flags) {
743
744 assert(f);
745 assert(p);
746
747 if (!(flags & OUTPUT_SHOW_ALL) && l >= JSON_THRESHOLD)
748 fputs("null", f);
749
750 else if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(p, l)) {
751 bool not_first = false;
752
753 fputs("[ ", f);
754
755 while (l > 0) {
756 if (not_first)
757 fprintf(f, ", %u", (uint8_t) *p);
758 else {
759 not_first = true;
760 fprintf(f, "%u", (uint8_t) *p);
761 }
762
763 p++;
764 l--;
765 }
766
767 fputs(" ]", f);
768 } else {
769 fputc('"', f);
770
771 while (l > 0) {
772 if (IN_SET(*p, '"', '\\')) {
773 fputc('\\', f);
774 fputc(*p, f);
775 } else if (*p == '\n')
776 fputs("\\n", f);
777 else if ((uint8_t) *p < ' ')
778 fprintf(f, "\\u%04x", (uint8_t) *p);
779 else
780 fputc(*p, f);
781
782 p++;
783 l--;
784 }
785
786 fputc('"', f);
787 }
788 }
789
790 struct json_data {
791 JsonVariant* name;
792 size_t n_values;
793 JsonVariant* values[];
794 };
795
796 static int update_json_data(
797 Hashmap *h,
798 OutputFlags flags,
799 const char *name,
800 const void *value,
801 size_t size) {
802
803 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
804 struct json_data *d;
805 int r;
806
807 if (!(flags & OUTPUT_SHOW_ALL) && strlen(name) + 1 + size >= JSON_THRESHOLD)
808 r = json_variant_new_null(&v);
809 else if (utf8_is_printable(value, size))
810 r = json_variant_new_stringn(&v, value, size);
811 else
812 r = json_variant_new_array_bytes(&v, value, size);
813 if (r < 0)
814 return log_error_errno(r, "Failed to allocate JSON data: %m");
815
816 d = hashmap_get(h, name);
817 if (d) {
818 struct json_data *w;
819
820 w = realloc(d, offsetof(struct json_data, values) + sizeof(JsonVariant*) * (d->n_values + 1));
821 if (!w)
822 return log_oom();
823
824 d = w;
825 assert_se(hashmap_update(h, json_variant_string(d->name), d) >= 0);
826 } else {
827 _cleanup_(json_variant_unrefp) JsonVariant *n = NULL;
828
829 r = json_variant_new_string(&n, name);
830 if (r < 0)
831 return log_error_errno(r, "Failed to allocate JSON name variant: %m");
832
833 d = malloc0(offsetof(struct json_data, values) + sizeof(JsonVariant*));
834 if (!d)
835 return log_oom();
836
837 r = hashmap_put(h, json_variant_string(n), d);
838 if (r < 0) {
839 free(d);
840 return log_error_errno(r, "Failed to insert JSON name into hashmap: %m");
841 }
842
843 d->name = TAKE_PTR(n);
844 }
845
846 d->values[d->n_values++] = TAKE_PTR(v);
847 return 0;
848 }
849
850 static int update_json_data_split(
851 Hashmap *h,
852 OutputFlags flags,
853 Set *output_fields,
854 const void *data,
855 size_t size) {
856
857 const char *eq;
858 char *name;
859
860 assert(h);
861 assert(data || size == 0);
862
863 if (memory_startswith(data, size, "_BOOT_ID="))
864 return 0;
865
866 eq = memchr(data, '=', MIN(size, JSON_THRESHOLD));
867 if (!eq)
868 return 0;
869
870 if (eq == data)
871 return 0;
872
873 name = strndupa(data, eq - (const char*) data);
874 if (output_fields && !set_get(output_fields, name))
875 return 0;
876
877 return update_json_data(h, flags, name, eq + 1, size - (eq - (const char*) data) - 1);
878 }
879
880 static int output_json(
881 FILE *f,
882 sd_journal *j,
883 OutputMode mode,
884 unsigned n_columns,
885 OutputFlags flags,
886 Set *output_fields,
887 const size_t highlight[2]) {
888
889 char sid[SD_ID128_STRING_MAX], usecbuf[DECIMAL_STR_MAX(usec_t)];
890 _cleanup_(json_variant_unrefp) JsonVariant *object = NULL;
891 _cleanup_free_ char *cursor = NULL;
892 uint64_t realtime, monotonic;
893 JsonVariant **array = NULL;
894 struct json_data *d;
895 sd_id128_t boot_id;
896 Hashmap *h = NULL;
897 size_t n = 0;
898 Iterator i;
899 int r;
900
901 assert(j);
902
903 (void) sd_journal_set_data_threshold(j, flags & OUTPUT_SHOW_ALL ? 0 : JSON_THRESHOLD);
904
905 r = sd_journal_get_realtime_usec(j, &realtime);
906 if (r < 0)
907 return log_error_errno(r, "Failed to get realtime timestamp: %m");
908
909 r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
910 if (r < 0)
911 return log_error_errno(r, "Failed to get monotonic timestamp: %m");
912
913 r = sd_journal_get_cursor(j, &cursor);
914 if (r < 0)
915 return log_error_errno(r, "Failed to get cursor: %m");
916
917 h = hashmap_new(&string_hash_ops);
918 if (!h)
919 return log_oom();
920
921 r = update_json_data(h, flags, "__CURSOR", cursor, strlen(cursor));
922 if (r < 0)
923 goto finish;
924
925 xsprintf(usecbuf, USEC_FMT, realtime);
926 r = update_json_data(h, flags, "__REALTIME_TIMESTAMP", usecbuf, strlen(usecbuf));
927 if (r < 0)
928 goto finish;
929
930 xsprintf(usecbuf, USEC_FMT, monotonic);
931 r = update_json_data(h, flags, "__MONOTONIC_TIMESTAMP", usecbuf, strlen(usecbuf));
932 if (r < 0)
933 goto finish;
934
935 sd_id128_to_string(boot_id, sid);
936 r = update_json_data(h, flags, "_BOOT_ID", sid, strlen(sid));
937 if (r < 0)
938 goto finish;
939
940 for (;;) {
941 const void *data;
942 size_t size;
943
944 r = sd_journal_enumerate_data(j, &data, &size);
945 if (r == -EBADMSG) {
946 log_debug_errno(r, "Skipping message we can't read: %m");
947 r = 0;
948 goto finish;
949 }
950 if (r < 0) {
951 log_error_errno(r, "Failed to read journal: %m");
952 goto finish;
953 }
954 if (r == 0)
955 break;
956
957 r = update_json_data_split(h, flags, output_fields, data, size);
958 if (r < 0)
959 goto finish;
960 }
961
962 array = new(JsonVariant*, hashmap_size(h)*2);
963 if (!array) {
964 r = log_oom();
965 goto finish;
966 }
967
968 HASHMAP_FOREACH(d, h, i) {
969 assert(d->n_values > 0);
970
971 array[n++] = json_variant_ref(d->name);
972
973 if (d->n_values == 1)
974 array[n++] = json_variant_ref(d->values[0]);
975 else {
976 _cleanup_(json_variant_unrefp) JsonVariant *q = NULL;
977
978 r = json_variant_new_array(&q, d->values, d->n_values);
979 if (r < 0) {
980 log_error_errno(r, "Failed to create JSON array: %m");
981 goto finish;
982 }
983
984 array[n++] = TAKE_PTR(q);
985 }
986 }
987
988 r = json_variant_new_object(&object, array, n);
989 if (r < 0) {
990 log_error_errno(r, "Failed to allocate JSON object: %m");
991 goto finish;
992 }
993
994 json_variant_dump(object,
995 output_mode_to_json_format_flags(mode) |
996 (FLAGS_SET(flags, OUTPUT_COLOR) ? JSON_FORMAT_COLOR : 0),
997 f, NULL);
998
999 r = 0;
1000
1001 finish:
1002 while ((d = hashmap_steal_first(h))) {
1003 size_t k;
1004
1005 json_variant_unref(d->name);
1006 for (k = 0; k < d->n_values; k++)
1007 json_variant_unref(d->values[k]);
1008
1009 free(d);
1010 }
1011
1012 hashmap_free(h);
1013
1014 json_variant_unref_many(array, n);
1015 free(array);
1016
1017 return r;
1018 }
1019
1020 static int output_cat(
1021 FILE *f,
1022 sd_journal *j,
1023 OutputMode mode,
1024 unsigned n_columns,
1025 OutputFlags flags,
1026 Set *output_fields,
1027 const size_t highlight[2]) {
1028
1029 const void *data;
1030 size_t l;
1031 int r;
1032 const char *highlight_on = "", *highlight_off = "";
1033
1034 assert(j);
1035 assert(f);
1036
1037 if (flags & OUTPUT_COLOR) {
1038 highlight_on = ANSI_HIGHLIGHT_RED;
1039 highlight_off = ANSI_NORMAL;
1040 }
1041
1042 sd_journal_set_data_threshold(j, 0);
1043
1044 r = sd_journal_get_data(j, "MESSAGE", &data, &l);
1045 if (r == -EBADMSG) {
1046 log_debug_errno(r, "Skipping message we can't read: %m");
1047 return 0;
1048 }
1049 if (r < 0) {
1050 /* An entry without MESSAGE=? */
1051 if (r == -ENOENT)
1052 return 0;
1053
1054 return log_error_errno(r, "Failed to get data: %m");
1055 }
1056
1057 assert(l >= 8);
1058
1059 if (highlight && (flags & OUTPUT_COLOR)) {
1060 assert(highlight[0] <= highlight[1]);
1061 assert(highlight[1] <= l - 8);
1062
1063 fwrite((const char*) data + 8, 1, highlight[0], f);
1064 fwrite(highlight_on, 1, strlen(highlight_on), f);
1065 fwrite((const char*) data + 8 + highlight[0], 1, highlight[1] - highlight[0], f);
1066 fwrite(highlight_off, 1, strlen(highlight_off), f);
1067 fwrite((const char*) data + 8 + highlight[1], 1, l - 8 - highlight[1], f);
1068 } else
1069 fwrite((const char*) data + 8, 1, l - 8, f);
1070 fputc('\n', f);
1071
1072 return 0;
1073 }
1074
1075 static int (*output_funcs[_OUTPUT_MODE_MAX])(
1076 FILE *f,
1077 sd_journal *j,
1078 OutputMode mode,
1079 unsigned n_columns,
1080 OutputFlags flags,
1081 Set *output_fields,
1082 const size_t highlight[2]) = {
1083
1084 [OUTPUT_SHORT] = output_short,
1085 [OUTPUT_SHORT_ISO] = output_short,
1086 [OUTPUT_SHORT_ISO_PRECISE] = output_short,
1087 [OUTPUT_SHORT_PRECISE] = output_short,
1088 [OUTPUT_SHORT_MONOTONIC] = output_short,
1089 [OUTPUT_SHORT_UNIX] = output_short,
1090 [OUTPUT_SHORT_FULL] = output_short,
1091 [OUTPUT_VERBOSE] = output_verbose,
1092 [OUTPUT_EXPORT] = output_export,
1093 [OUTPUT_JSON] = output_json,
1094 [OUTPUT_JSON_PRETTY] = output_json,
1095 [OUTPUT_JSON_SSE] = output_json,
1096 [OUTPUT_JSON_SEQ] = output_json,
1097 [OUTPUT_CAT] = output_cat,
1098 [OUTPUT_WITH_UNIT] = output_short,
1099 };
1100
1101 int show_journal_entry(
1102 FILE *f,
1103 sd_journal *j,
1104 OutputMode mode,
1105 unsigned n_columns,
1106 OutputFlags flags,
1107 char **output_fields,
1108 const size_t highlight[2],
1109 bool *ellipsized) {
1110
1111 int ret;
1112 _cleanup_set_free_free_ Set *fields = NULL;
1113 assert(mode >= 0);
1114 assert(mode < _OUTPUT_MODE_MAX);
1115
1116 if (n_columns <= 0)
1117 n_columns = columns();
1118
1119 if (output_fields) {
1120 fields = set_new(&string_hash_ops);
1121 if (!fields)
1122 return log_oom();
1123
1124 ret = set_put_strdupv(fields, output_fields);
1125 if (ret < 0)
1126 return ret;
1127 }
1128
1129 ret = output_funcs[mode](f, j, mode, n_columns, flags, fields, highlight);
1130
1131 if (ellipsized && ret > 0)
1132 *ellipsized = true;
1133
1134 return ret;
1135 }
1136
1137 static int maybe_print_begin_newline(FILE *f, OutputFlags *flags) {
1138 assert(f);
1139 assert(flags);
1140
1141 if (!(*flags & OUTPUT_BEGIN_NEWLINE))
1142 return 0;
1143
1144 /* Print a beginning new line if that's request, but only once
1145 * on the first line we print. */
1146
1147 fputc('\n', f);
1148 *flags &= ~OUTPUT_BEGIN_NEWLINE;
1149 return 0;
1150 }
1151
1152 int show_journal(
1153 FILE *f,
1154 sd_journal *j,
1155 OutputMode mode,
1156 unsigned n_columns,
1157 usec_t not_before,
1158 unsigned how_many,
1159 OutputFlags flags,
1160 bool *ellipsized) {
1161
1162 int r;
1163 unsigned line = 0;
1164 bool need_seek = false;
1165 int warn_cutoff = flags & OUTPUT_WARN_CUTOFF;
1166
1167 assert(j);
1168 assert(mode >= 0);
1169 assert(mode < _OUTPUT_MODE_MAX);
1170
1171 if (how_many == (unsigned) -1)
1172 need_seek = true;
1173 else {
1174 /* Seek to end */
1175 r = sd_journal_seek_tail(j);
1176 if (r < 0)
1177 return log_error_errno(r, "Failed to seek to tail: %m");
1178
1179 r = sd_journal_previous_skip(j, how_many);
1180 if (r < 0)
1181 return log_error_errno(r, "Failed to skip previous: %m");
1182 }
1183
1184 for (;;) {
1185 for (;;) {
1186 usec_t usec;
1187
1188 if (need_seek) {
1189 r = sd_journal_next(j);
1190 if (r < 0)
1191 return log_error_errno(r, "Failed to iterate through journal: %m");
1192 }
1193
1194 if (r == 0)
1195 break;
1196
1197 need_seek = true;
1198
1199 if (not_before > 0) {
1200 r = sd_journal_get_monotonic_usec(j, &usec, NULL);
1201
1202 /* -ESTALE is returned if the
1203 timestamp is not from this boot */
1204 if (r == -ESTALE)
1205 continue;
1206 else if (r < 0)
1207 return log_error_errno(r, "Failed to get journal time: %m");
1208
1209 if (usec < not_before)
1210 continue;
1211 }
1212
1213 line++;
1214 maybe_print_begin_newline(f, &flags);
1215
1216 r = show_journal_entry(f, j, mode, n_columns, flags, NULL, NULL, ellipsized);
1217 if (r < 0)
1218 return r;
1219 }
1220
1221 if (warn_cutoff && line < how_many && not_before > 0) {
1222 sd_id128_t boot_id;
1223 usec_t cutoff = 0;
1224
1225 /* Check whether the cutoff line is too early */
1226
1227 r = sd_id128_get_boot(&boot_id);
1228 if (r < 0)
1229 return log_error_errno(r, "Failed to get boot id: %m");
1230
1231 r = sd_journal_get_cutoff_monotonic_usec(j, boot_id, &cutoff, NULL);
1232 if (r < 0)
1233 return log_error_errno(r, "Failed to get journal cutoff time: %m");
1234
1235 if (r > 0 && not_before < cutoff) {
1236 maybe_print_begin_newline(f, &flags);
1237 fprintf(f, "Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.\n");
1238 }
1239
1240 warn_cutoff = false;
1241 }
1242
1243 if (!(flags & OUTPUT_FOLLOW))
1244 break;
1245
1246 r = sd_journal_wait(j, USEC_INFINITY);
1247 if (r < 0)
1248 return log_error_errno(r, "Failed to wait for journal: %m");
1249
1250 }
1251
1252 return 0;
1253 }
1254
1255 int add_matches_for_unit(sd_journal *j, const char *unit) {
1256 const char *m1, *m2, *m3, *m4;
1257 int r;
1258
1259 assert(j);
1260 assert(unit);
1261
1262 m1 = strjoina("_SYSTEMD_UNIT=", unit);
1263 m2 = strjoina("COREDUMP_UNIT=", unit);
1264 m3 = strjoina("UNIT=", unit);
1265 m4 = strjoina("OBJECT_SYSTEMD_UNIT=", unit);
1266
1267 (void)(
1268 /* Look for messages from the service itself */
1269 (r = sd_journal_add_match(j, m1, 0)) ||
1270
1271 /* Look for coredumps of the service */
1272 (r = sd_journal_add_disjunction(j)) ||
1273 (r = sd_journal_add_match(j, "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1", 0)) ||
1274 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
1275 (r = sd_journal_add_match(j, m2, 0)) ||
1276
1277 /* Look for messages from PID 1 about this service */
1278 (r = sd_journal_add_disjunction(j)) ||
1279 (r = sd_journal_add_match(j, "_PID=1", 0)) ||
1280 (r = sd_journal_add_match(j, m3, 0)) ||
1281
1282 /* Look for messages from authorized daemons about this service */
1283 (r = sd_journal_add_disjunction(j)) ||
1284 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
1285 (r = sd_journal_add_match(j, m4, 0))
1286 );
1287
1288 if (r == 0 && endswith(unit, ".slice")) {
1289 const char *m5;
1290
1291 m5 = strjoina("_SYSTEMD_SLICE=", unit);
1292
1293 /* Show all messages belonging to a slice */
1294 (void)(
1295 (r = sd_journal_add_disjunction(j)) ||
1296 (r = sd_journal_add_match(j, m5, 0))
1297 );
1298 }
1299
1300 return r;
1301 }
1302
1303 int add_matches_for_user_unit(sd_journal *j, const char *unit, uid_t uid) {
1304 int r;
1305 char *m1, *m2, *m3, *m4;
1306 char muid[sizeof("_UID=") + DECIMAL_STR_MAX(uid_t)];
1307
1308 assert(j);
1309 assert(unit);
1310
1311 m1 = strjoina("_SYSTEMD_USER_UNIT=", unit);
1312 m2 = strjoina("USER_UNIT=", unit);
1313 m3 = strjoina("COREDUMP_USER_UNIT=", unit);
1314 m4 = strjoina("OBJECT_SYSTEMD_USER_UNIT=", unit);
1315 sprintf(muid, "_UID="UID_FMT, uid);
1316
1317 (void) (
1318 /* Look for messages from the user service itself */
1319 (r = sd_journal_add_match(j, m1, 0)) ||
1320 (r = sd_journal_add_match(j, muid, 0)) ||
1321
1322 /* Look for messages from systemd about this service */
1323 (r = sd_journal_add_disjunction(j)) ||
1324 (r = sd_journal_add_match(j, m2, 0)) ||
1325 (r = sd_journal_add_match(j, muid, 0)) ||
1326
1327 /* Look for coredumps of the service */
1328 (r = sd_journal_add_disjunction(j)) ||
1329 (r = sd_journal_add_match(j, m3, 0)) ||
1330 (r = sd_journal_add_match(j, muid, 0)) ||
1331 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
1332
1333 /* Look for messages from authorized daemons about this service */
1334 (r = sd_journal_add_disjunction(j)) ||
1335 (r = sd_journal_add_match(j, m4, 0)) ||
1336 (r = sd_journal_add_match(j, muid, 0)) ||
1337 (r = sd_journal_add_match(j, "_UID=0", 0))
1338 );
1339
1340 if (r == 0 && endswith(unit, ".slice")) {
1341 const char *m5;
1342
1343 m5 = strjoina("_SYSTEMD_SLICE=", unit);
1344
1345 /* Show all messages belonging to a slice */
1346 (void)(
1347 (r = sd_journal_add_disjunction(j)) ||
1348 (r = sd_journal_add_match(j, m5, 0)) ||
1349 (r = sd_journal_add_match(j, muid, 0))
1350 );
1351 }
1352
1353 return r;
1354 }
1355
1356 static int get_boot_id_for_machine(const char *machine, sd_id128_t *boot_id) {
1357 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1358 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
1359 pid_t pid, child;
1360 char buf[37];
1361 ssize_t k;
1362 int r;
1363
1364 assert(machine);
1365 assert(boot_id);
1366
1367 if (!machine_name_is_valid(machine))
1368 return -EINVAL;
1369
1370 r = container_get_leader(machine, &pid);
1371 if (r < 0)
1372 return r;
1373
1374 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, NULL, &rootfd);
1375 if (r < 0)
1376 return r;
1377
1378 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1379 return -errno;
1380
1381 r = namespace_fork("(sd-bootidns)", "(sd-bootid)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1382 pidnsfd, mntnsfd, -1, -1, rootfd, &child);
1383 if (r < 0)
1384 return r;
1385 if (r == 0) {
1386 int fd;
1387
1388 pair[0] = safe_close(pair[0]);
1389
1390 fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1391 if (fd < 0)
1392 _exit(EXIT_FAILURE);
1393
1394 r = loop_read_exact(fd, buf, 36, false);
1395 safe_close(fd);
1396 if (r < 0)
1397 _exit(EXIT_FAILURE);
1398
1399 k = send(pair[1], buf, 36, MSG_NOSIGNAL);
1400 if (k != 36)
1401 _exit(EXIT_FAILURE);
1402
1403 _exit(EXIT_SUCCESS);
1404 }
1405
1406 pair[1] = safe_close(pair[1]);
1407
1408 r = wait_for_terminate_and_check("(sd-bootidns)", child, 0);
1409 if (r < 0)
1410 return r;
1411 if (r != EXIT_SUCCESS)
1412 return -EIO;
1413
1414 k = recv(pair[0], buf, 36, 0);
1415 if (k != 36)
1416 return -EIO;
1417
1418 buf[36] = 0;
1419 r = sd_id128_from_string(buf, boot_id);
1420 if (r < 0)
1421 return r;
1422
1423 return 0;
1424 }
1425
1426 int add_match_this_boot(sd_journal *j, const char *machine) {
1427 char match[9+32+1] = "_BOOT_ID=";
1428 sd_id128_t boot_id;
1429 int r;
1430
1431 assert(j);
1432
1433 if (machine) {
1434 r = get_boot_id_for_machine(machine, &boot_id);
1435 if (r < 0)
1436 return log_error_errno(r, "Failed to get boot id of container %s: %m", machine);
1437 } else {
1438 r = sd_id128_get_boot(&boot_id);
1439 if (r < 0)
1440 return log_error_errno(r, "Failed to get boot id: %m");
1441 }
1442
1443 sd_id128_to_string(boot_id, match + 9);
1444 r = sd_journal_add_match(j, match, strlen(match));
1445 if (r < 0)
1446 return log_error_errno(r, "Failed to add match: %m");
1447
1448 r = sd_journal_add_conjunction(j);
1449 if (r < 0)
1450 return log_error_errno(r, "Failed to add conjunction: %m");
1451
1452 return 0;
1453 }
1454
1455 int show_journal_by_unit(
1456 FILE *f,
1457 const char *unit,
1458 OutputMode mode,
1459 unsigned n_columns,
1460 usec_t not_before,
1461 unsigned how_many,
1462 uid_t uid,
1463 OutputFlags flags,
1464 int journal_open_flags,
1465 bool system_unit,
1466 bool *ellipsized) {
1467
1468 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
1469 int r;
1470
1471 assert(mode >= 0);
1472 assert(mode < _OUTPUT_MODE_MAX);
1473 assert(unit);
1474
1475 if (how_many <= 0)
1476 return 0;
1477
1478 r = sd_journal_open(&j, journal_open_flags);
1479 if (r < 0)
1480 return log_error_errno(r, "Failed to open journal: %m");
1481
1482 r = add_match_this_boot(j, NULL);
1483 if (r < 0)
1484 return r;
1485
1486 if (system_unit)
1487 r = add_matches_for_unit(j, unit);
1488 else
1489 r = add_matches_for_user_unit(j, unit, uid);
1490 if (r < 0)
1491 return log_error_errno(r, "Failed to add unit matches: %m");
1492
1493 if (DEBUG_LOGGING) {
1494 _cleanup_free_ char *filter;
1495
1496 filter = journal_make_match_string(j);
1497 if (!filter)
1498 return log_oom();
1499
1500 log_debug("Journal filter: %s", filter);
1501 }
1502
1503 return show_journal(f, j, mode, n_columns, not_before, how_many, flags, ellipsized);
1504 }