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