]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/logs-show.c
tree-wide: introduce PIPE_EBADF macro
[thirdparty/systemd.git] / src / shared / logs-show.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
86aa7ba4 2
86aa7ba4 3#include <errno.h>
b6741478 4#include <fcntl.h>
a8fbdf54
TA
5#include <signal.h>
6#include <stdint.h>
7#include <stdlib.h>
07630cea 8#include <sys/socket.h>
a8fbdf54 9#include <syslog.h>
a8fbdf54
TA
10#include <unistd.h>
11
12#include "sd-id128.h"
13#include "sd-journal.h"
86aa7ba4 14
b5efdb8a 15#include "alloc-util.h"
3ffd4af2 16#include "fd-util.h"
f97b34a6 17#include "format-util.h"
d8e32c47 18#include "glyph-util.h"
d99ae53a 19#include "hashmap.h"
07630cea 20#include "hostname-util.h"
b5ea030d 21#include "id128-util.h"
c004493c 22#include "io-util.h"
dfb33a97 23#include "journal-internal.h"
1a8f0ce6 24#include "journal-util.h"
8e044443 25#include "json.h"
2108b567 26#include "locale-util.h"
07630cea 27#include "log.h"
3ffd4af2 28#include "logs-show.h"
a8fbdf54 29#include "macro.h"
0cb8e3d1 30#include "namespace-util.h"
a8fbdf54 31#include "output-mode.h"
6bedfcbb 32#include "parse-util.h"
76f7cc3f 33#include "pretty-print.h"
b5ea030d 34#include "process-util.h"
a8fbdf54 35#include "sparse-endian.h"
29a753df 36#include "stdio-util.h"
8b43440b 37#include "string-table.h"
07630cea 38#include "string-util.h"
cc25a67e 39#include "strv.h"
288a74cc 40#include "terminal-util.h"
a8fbdf54 41#include "time-util.h"
07630cea 42#include "utf8.h"
2108b567 43#include "web-util.h"
86aa7ba4 44
07630cea 45/* up to three lines (each up to 100 characters) or 300 characters, whichever is less */
a6f0104a
ZJS
46#define PRINT_LINE_THRESHOLD 3
47#define PRINT_CHAR_THRESHOLD 300
48
8e044443 49#define JSON_THRESHOLD 4096U
86aa7ba4 50
d4205751 51static int print_catalog(FILE *f, sd_journal *j) {
d4205751 52 _cleanup_free_ char *t = NULL, *z = NULL;
ee5c1311 53 const char *newline, *prefix;
2108b567
LP
54 int r;
55
56 assert(j);
d4205751 57
d4205751 58 r = sd_journal_get_catalog(j, &t);
2108b567
LP
59 if (r == -ENOENT)
60 return 0;
d4205751 61 if (r < 0)
2108b567 62 return log_error_errno(r, "Failed to find catalog entry: %m");
d4205751 63
ee5c1311
LP
64 if (is_locale_utf8())
65 prefix = strjoina(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE), special_glyph(SPECIAL_GLYPH_LIGHT_SHADE));
66 else
67 prefix = "--";
68
cd7ae1b4 69 newline = strjoina(ansi_normal(), "\n", ansi_grey(), prefix, ansi_normal(), " ", ansi_green());
ee5c1311
LP
70
71 z = strreplace(strstrip(t), "\n", newline);
d4205751
LP
72 if (!z)
73 return log_oom();
74
cd7ae1b4 75 fprintf(f, "%s%s %s%s", ansi_grey(), prefix, ansi_normal(), ansi_green());
ee5c1311 76
d4205751 77 fputs(z, f);
ee5c1311 78
cd7ae1b4 79 fprintf(f, "%s\n", ansi_normal());
d4205751 80
2108b567
LP
81 return 1;
82}
83
84static int url_from_catalog(sd_journal *j, char **ret) {
85 _cleanup_free_ char *t = NULL, *url = NULL;
86 const char *weblink;
87 int r;
88
89 assert(j);
90 assert(ret);
91
92 r = sd_journal_get_catalog(j, &t);
93 if (r == -ENOENT)
94 goto notfound;
95 if (r < 0)
96 return log_error_errno(r, "Failed to find catalog entry: %m");
97
98 weblink = startswith(t, "Documentation:");
99 if (!weblink) {
100 weblink = strstr(t + 1, "\nDocumentation:");
101 if (!weblink)
102 goto notfound;
103
104 weblink += 15;
105 }
106
107 /* Skip whitespace to value */
108 weblink += strspn(weblink, " \t");
109
110 /* Cut out till next whitespace/newline */
111 url = strndup(weblink, strcspn(weblink, WHITESPACE));
112 if (!url)
113 return log_oom();
114
115 if (!documentation_url_is_valid(url))
116 goto notfound;
117
118 *ret = TAKE_PTR(url);
119 return 1;
120
121notfound:
122 *ret = NULL;
d4205751
LP
123 return 0;
124}
125
ed054520
VC
126static int parse_field(const void *data, size_t length, const char *field, size_t field_len, char **target, size_t *target_len) {
127 size_t nl;
d813d7a3 128 char *buf;
55d7bfc1
LP
129
130 assert(data);
131 assert(field);
132 assert(target);
55d7bfc1 133
ed054520 134 if (length < field_len)
55d7bfc1
LP
135 return 0;
136
ed054520 137 if (memcmp(data, field, field_len))
55d7bfc1
LP
138 return 0;
139
ed054520 140 nl = length - field_len;
c165d97d 141
ed054520 142 buf = newdup_suffix0(char, (const char*) data + field_len, nl);
0d0f0c50
SL
143 if (!buf)
144 return log_oom();
55d7bfc1 145
6c1e6b98 146 free(*target);
55d7bfc1 147 *target = buf;
d813d7a3 148
ed054520
VC
149 if (target_len)
150 *target_len = nl;
55d7bfc1
LP
151
152 return 1;
153}
154
ed054520
VC
155typedef struct ParseFieldVec {
156 const char *field;
157 size_t field_len;
158 char **target;
159 size_t *target_len;
160} ParseFieldVec;
161
e3eec1fd
LP
162#define PARSE_FIELD_VEC_ENTRY(_field, _target, _target_len) { \
163 .field = _field, \
164 .field_len = strlen(_field), \
165 .target = _target, \
166 .target_len = _target_len \
167 }
ed054520
VC
168
169static int parse_fieldv(const void *data, size_t length, const ParseFieldVec *fields, unsigned n_fields) {
170 unsigned i;
171
172 for (i = 0; i < n_fields; i++) {
173 const ParseFieldVec *f = &fields[i];
174 int r;
175
176 r = parse_field(data, length, f->field, f->field_len, f->target, f->target_len);
177 if (r < 0)
178 return r;
179 else if (r > 0)
180 break;
181 }
182
183 return 0;
184}
185
2f063186
ZJS
186static int field_set_test(const Set *fields, const char *name, size_t n) {
187 char *s;
cc25a67e
LK
188
189 if (!fields)
190 return 1;
191
2f82562b 192 s = strndupa_safe(name, n);
54ff74d2 193 return set_contains(fields, s);
cc25a67e
LK
194}
195
08ace05b
LP
196static bool shall_print(const char *p, size_t l, OutputFlags flags) {
197 assert(p);
198
199 if (flags & OUTPUT_SHOW_ALL)
55d7bfc1
LP
200 return true;
201
a6f0104a 202 if (l >= PRINT_CHAR_THRESHOLD)
55d7bfc1
LP
203 return false;
204
31f7bf19 205 if (!utf8_is_printable(p, l))
55d7bfc1
LP
206 return false;
207
208 return true;
209}
210
b4766d5f
ZJS
211static bool print_multiline(
212 FILE *f,
213 unsigned prefix,
214 unsigned n_columns,
215 OutputFlags flags,
216 int priority,
194da5ca 217 bool audit,
b4766d5f
ZJS
218 const char* message,
219 size_t message_len,
05c7d9bf 220 size_t highlight[2]) {
b4766d5f
ZJS
221
222 const char *color_on = "", *color_off = "", *highlight_on = "";
31f7bf19 223 const char *pos, *end;
94e0bd7d 224 bool ellipsized = false;
a6f0104a 225 int line = 0;
31f7bf19 226
194da5ca 227 if (flags & OUTPUT_COLOR) {
37b8d2f6 228 get_log_colors(priority, &color_on, &color_off, &highlight_on);
31f7bf19 229
194da5ca
ZJS
230 if (audit && strempty(color_on)) {
231 color_on = ANSI_BLUE;
232 color_off = ANSI_NORMAL;
233 }
234 }
235
47d80904
UU
236 /* A special case: make sure that we print a newline when
237 the message is empty. */
238 if (message_len == 0)
239 fputs("\n", f);
240
a6f0104a
ZJS
241 for (pos = message;
242 pos < message + message_len;
243 pos = end + 1, line++) {
a6f0104a 244 bool tail_line;
f996072f 245 int len, indent = (line > 0) * prefix;
31f7bf19
ZJS
246 for (end = pos; end < message + message_len && *end != '\n'; end++)
247 ;
248 len = end - pos;
249 assert(len >= 0);
250
2526d626 251 /* We need to figure out when we are showing not-last line, *and*
a6f0104a
ZJS
252 * will skip subsequent lines. In that case, we will put the dots
253 * at the end of the line, instead of putting dots in the middle
254 * or not at all.
255 */
256 tail_line =
257 line + 1 == PRINT_LINE_THRESHOLD ||
2526d626 258 end + 1 >= message + PRINT_CHAR_THRESHOLD;
a6f0104a
ZJS
259
260 if (flags & (OUTPUT_FULL_WIDTH | OUTPUT_SHOW_ALL) ||
261 (prefix + len + 1 < n_columns && !tail_line)) {
b4766d5f
ZJS
262 if (highlight &&
263 (size_t) (pos - message) <= highlight[0] &&
264 highlight[0] < (size_t) len) {
265
266 fprintf(f, "%*s%s%.*s",
f996072f 267 indent, "",
b4766d5f
ZJS
268 color_on, (int) highlight[0], pos);
269 fprintf(f, "%s%.*s",
270 highlight_on,
271 (int) (MIN((size_t) len, highlight[1]) - highlight[0]),
272 pos + highlight[0]);
273 if ((size_t) len > highlight[1])
274 fprintf(f, "%s%.*s",
275 color_on,
276 (int) (len - highlight[1]),
277 pos + highlight[1]);
278 fprintf(f, "%s\n", color_off);
279
280 } else
281 fprintf(f, "%*s%s%.*s%s\n",
f996072f 282 indent, "",
b4766d5f 283 color_on, len, pos, color_off);
a6f0104a
ZJS
284 continue;
285 }
31f7bf19 286
a6f0104a
ZJS
287 /* Beyond this point, ellipsization will happen. */
288 ellipsized = true;
31f7bf19 289
a6f0104a
ZJS
290 if (prefix < n_columns && n_columns - prefix >= 3) {
291 if (n_columns - prefix > (unsigned) len + 3)
292 fprintf(f, "%*s%s%.*s...%s\n",
f996072f 293 indent, "",
b4b02cbe 294 color_on, len, pos, color_off);
a6f0104a 295 else {
c2b2df60 296 _cleanup_free_ char *e = NULL;
a6f0104a
ZJS
297
298 e = ellipsize_mem(pos, len, n_columns - prefix,
299 tail_line ? 100 : 90);
300 if (!e)
301 fprintf(f, "%*s%s%.*s%s\n",
f996072f 302 indent, "",
a6f0104a
ZJS
303 color_on, len, pos, color_off);
304 else
305 fprintf(f, "%*s%s%s%s\n",
f996072f 306 indent, "",
a6f0104a
ZJS
307 color_on, e, color_off);
308 }
309 } else
31f7bf19
ZJS
310 fputs("...\n", f);
311
a6f0104a
ZJS
312 if (tail_line)
313 break;
31f7bf19 314 }
94e0bd7d
ZJS
315
316 return ellipsized;
31f7bf19
ZJS
317}
318
893bcd3d
DB
319static int output_timestamp_monotonic(
320 FILE *f, OutputMode mode,
321 const dual_timestamp *ts,
322 const sd_id128_t *boot_id,
323 const dual_timestamp *previous_ts,
324 const sd_id128_t *previous_boot_id) {
325
326 int written_chars = 0;
327
29a753df 328 assert(f);
275e6be0 329 assert(ts);
893bcd3d
DB
330 assert(boot_id);
331 assert(previous_ts);
332 assert(previous_boot_id);
29a753df 333
275e6be0
DB
334 if (!VALID_MONOTONIC(ts->monotonic))
335 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No valid monotonic timestamp available");
29a753df 336
893bcd3d
DB
337 written_chars += fprintf(f, "[%5"PRI_USEC".%06"PRI_USEC, ts->monotonic / USEC_PER_SEC, ts->monotonic % USEC_PER_SEC);
338
339 if (mode == OUTPUT_SHORT_DELTA) {
340 uint64_t delta;
341 bool reliable_ts = true;
342
343 if (VALID_MONOTONIC(previous_ts->monotonic) && sd_id128_equal(*boot_id, *previous_boot_id))
344 delta = usec_sub_unsigned(ts->monotonic, previous_ts->monotonic);
345 else if (VALID_REALTIME(ts->realtime) && VALID_REALTIME(previous_ts->realtime)) {
346 delta = usec_sub_unsigned(ts->realtime, previous_ts->realtime);
347 reliable_ts = false;
348 } else {
349 written_chars += fprintf(f, "%16s", "");
350 goto finish;
351 }
352
353 written_chars += fprintf(f, " <%5"PRI_USEC".%06"PRI_USEC"%s>", delta / USEC_PER_SEC, delta % USEC_PER_SEC, reliable_ts ? " " : "*");
354 }
355
356finish:
357 written_chars += fprintf(f, "%s", "]");
358
359 return written_chars;
29a753df
LP
360}
361
275e6be0
DB
362static int output_timestamp_realtime(
363 FILE *f,
364 sd_journal *j,
365 OutputMode mode,
366 OutputFlags flags,
367 const dual_timestamp *ts) {
368
89eb3d7c 369 char buf[CONST_MAX(FORMAT_TIMESTAMP_MAX, 64U)];
29a753df
LP
370 int r;
371
372 assert(f);
373 assert(j);
275e6be0 374 assert(ts);
29a753df 375
275e6be0
DB
376 if (!VALID_REALTIME(ts->realtime))
377 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No valid realtime timestamp available");
29a753df 378
49805b3d 379 if (IN_SET(mode, OUTPUT_SHORT_FULL, OUTPUT_WITH_UNIT)) {
29a753df
LP
380 const char *k;
381
382 if (flags & OUTPUT_UTC)
275e6be0 383 k = format_timestamp_style(buf, sizeof(buf), ts->realtime, TIMESTAMP_UTC);
29a753df 384 else
275e6be0 385 k = format_timestamp(buf, sizeof(buf), ts->realtime);
baaa35ad
ZJS
386 if (!k)
387 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
275e6be0 388 "Failed to format timestamp: %" PRIu64, ts->realtime);
29a753df
LP
389
390 } else {
f9c443b7
YW
391 struct tm tm;
392 time_t t;
7e563bfc 393
275e6be0 394 t = (time_t) (ts->realtime / USEC_PER_SEC);
29a753df
LP
395
396 switch (mode) {
397
398 case OUTPUT_SHORT_UNIX:
275e6be0 399 xsprintf(buf, "%10"PRI_TIME".%06"PRIu64, t, ts->realtime % USEC_PER_SEC);
29a753df
LP
400 break;
401
402 case OUTPUT_SHORT_ISO:
f9c443b7
YW
403 if (strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S%z",
404 localtime_or_gmtime_r(&t, &tm, flags & OUTPUT_UTC)) <= 0)
baaa35ad
ZJS
405 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
406 "Failed to format ISO time");
7e563bfc
IW
407 break;
408
f9c443b7
YW
409 case OUTPUT_SHORT_ISO_PRECISE: {
410 char usec[7];
411
7e563bfc 412 /* No usec in strftime, so we leave space and copy over */
f9c443b7
YW
413 if (strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.xxxxxx%z",
414 localtime_or_gmtime_r(&t, &tm, flags & OUTPUT_UTC)) <= 0)
baaa35ad
ZJS
415 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
416 "Failed to format ISO-precise time");
275e6be0 417 xsprintf(usec, "%06"PRI_USEC, ts->realtime % USEC_PER_SEC);
7e563bfc 418 memcpy(buf + 20, usec, 6);
29a753df 419 break;
f9c443b7 420 }
29a753df
LP
421 case OUTPUT_SHORT:
422 case OUTPUT_SHORT_PRECISE:
423
f9c443b7
YW
424 if (strftime(buf, sizeof(buf), "%b %d %H:%M:%S",
425 localtime_or_gmtime_r(&t, &tm, flags & OUTPUT_UTC)) <= 0)
baaa35ad
ZJS
426 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
427 "Failed to format syslog time");
29a753df
LP
428
429 if (mode == OUTPUT_SHORT_PRECISE) {
430 size_t k;
431
432 assert(sizeof(buf) > strlen(buf));
433 k = sizeof(buf) - strlen(buf);
434
275e6be0 435 r = snprintf(buf + strlen(buf), k, ".%06"PRIu64, ts->realtime % USEC_PER_SEC);
baaa35ad
ZJS
436 if (r <= 0 || (size_t) r >= k) /* too long? */
437 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
438 "Failed to format precise time");
29a753df
LP
439 }
440 break;
441
442 default:
04499a70 443 assert_not_reached();
29a753df
LP
444 }
445 }
446
447 fputs(buf, f);
448 return (int) strlen(buf);
449}
450
08ace05b
LP
451static int output_short(
452 FILE *f,
453 sd_journal *j,
454 OutputMode mode,
455 unsigned n_columns,
cc25a67e 456 OutputFlags flags,
2f063186 457 const Set *output_fields,
275e6be0
DB
458 const size_t highlight[2],
459 const dual_timestamp *ts,
893bcd3d
DB
460 const sd_id128_t *boot_id,
461 const dual_timestamp *previous_ts,
462 const sd_id128_t *previous_boot_id) {
08ace05b 463
86aa7ba4 464 int r;
86aa7ba4 465 const void *data;
2108b567
LP
466 size_t length, n = 0;
467 _cleanup_free_ char *hostname = NULL, *identifier = NULL, *comm = NULL, *pid = NULL, *fake_pid = NULL,
275e6be0 468 *message = NULL, *priority = NULL, *transport = NULL,
2108b567
LP
469 *config_file = NULL, *unit = NULL, *user_unit = NULL, *documentation_url = NULL;
470 size_t hostname_len = 0, identifier_len = 0, comm_len = 0, pid_len = 0, fake_pid_len = 0, message_len = 0,
275e6be0 471 priority_len = 0, transport_len = 0, config_file_len = 0,
2108b567 472 unit_len = 0, user_unit_len = 0, documentation_url_len = 0;
49826187 473 int p = LOG_INFO;
194da5ca 474 bool ellipsized = false, audit;
ed054520
VC
475 const ParseFieldVec fields[] = {
476 PARSE_FIELD_VEC_ENTRY("_PID=", &pid, &pid_len),
477 PARSE_FIELD_VEC_ENTRY("_COMM=", &comm, &comm_len),
478 PARSE_FIELD_VEC_ENTRY("MESSAGE=", &message, &message_len),
479 PARSE_FIELD_VEC_ENTRY("PRIORITY=", &priority, &priority_len),
194da5ca 480 PARSE_FIELD_VEC_ENTRY("_TRANSPORT=", &transport, &transport_len),
ed054520
VC
481 PARSE_FIELD_VEC_ENTRY("_HOSTNAME=", &hostname, &hostname_len),
482 PARSE_FIELD_VEC_ENTRY("SYSLOG_PID=", &fake_pid, &fake_pid_len),
483 PARSE_FIELD_VEC_ENTRY("SYSLOG_IDENTIFIER=", &identifier, &identifier_len),
76f7cc3f 484 PARSE_FIELD_VEC_ENTRY("CONFIG_FILE=", &config_file, &config_file_len),
49805b3d
LB
485 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_UNIT=", &unit, &unit_len),
486 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_USER_UNIT=", &user_unit, &user_unit_len),
2108b567 487 PARSE_FIELD_VEC_ENTRY("DOCUMENTATION=", &documentation_url, &documentation_url_len),
ed054520 488 };
b4766d5f 489 size_t highlight_shifted[] = {highlight ? highlight[0] : 0, highlight ? highlight[1] : 0};
86aa7ba4 490
08ace05b 491 assert(f);
86aa7ba4 492 assert(j);
275e6be0
DB
493 assert(ts);
494 assert(boot_id);
893bcd3d
DB
495 assert(previous_ts);
496 assert(previous_boot_id);
86aa7ba4 497
a6f0104a 498 /* Set the threshold to one bigger than the actual print
69ab8088 499 * threshold, so that if the line is actually longer than what
a6f0104a
ZJS
500 * we're willing to print, ellipsization will occur. This way
501 * we won't output a misleading line without any indication of
502 * truncation.
503 */
504 sd_journal_set_data_threshold(j, flags & (OUTPUT_SHOW_ALL|OUTPUT_FULL_WIDTH) ? 0 : PRINT_CHAR_THRESHOLD + 1);
93b73b06 505
a72b6353 506 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
ed054520 507 r = parse_fieldv(data, length, fields, ELEMENTSOF(fields));
55d7bfc1 508 if (r < 0)
08ace05b 509 return r;
55d7bfc1 510 }
d00f1d57
LP
511 if (r == -EBADMSG) {
512 log_debug_errno(r, "Skipping message we can't read: %m");
513 return 0;
514 }
a72b6353 515 if (r < 0)
b56d608e 516 return log_error_errno(r, "Failed to get journal fields: %m");
a72b6353 517
07d21025
LP
518 if (!message) {
519 log_debug("Skipping message without MESSAGE= field.");
08ace05b 520 return 0;
07d21025 521 }
55d7bfc1 522
e8bc0ea2 523 if (!(flags & OUTPUT_SHOW_ALL))
b4766d5f 524 strip_tab_ansi(&message, &message_len, highlight_shifted);
e8bc0ea2 525
49826187
LP
526 if (priority_len == 1 && *priority >= '0' && *priority <= '7')
527 p = *priority - '0';
528
194da5ca
ZJS
529 audit = streq_ptr(transport, "audit");
530
893bcd3d
DB
531 if (IN_SET(mode, OUTPUT_SHORT_MONOTONIC, OUTPUT_SHORT_DELTA))
532 r = output_timestamp_monotonic(f, mode, ts, boot_id, previous_ts, previous_boot_id);
29a753df 533 else
275e6be0 534 r = output_timestamp_realtime(f, j, mode, flags, ts);
29a753df
LP
535 if (r < 0)
536 return r;
537 n += r;
86aa7ba4 538
29a753df 539 if (flags & OUTPUT_NO_HOSTNAME) {
991e274b 540 /* Suppress display of the hostname if this is requested. */
12104159 541 hostname = mfree(hostname);
991e274b
LP
542 hostname_len = 0;
543 }
544
08ace05b
LP
545 if (hostname && shall_print(hostname, hostname_len, flags)) {
546 fprintf(f, " %.*s", (int) hostname_len, hostname);
55d7bfc1
LP
547 n += hostname_len + 1;
548 }
549
76f7cc3f
ZJS
550 if (mode == OUTPUT_WITH_UNIT && ((unit && shall_print(unit, unit_len, flags)) ||
551 (user_unit && shall_print(user_unit, user_unit_len, flags)))) {
49805b3d
LB
552 if (unit) {
553 fprintf(f, " %.*s", (int) unit_len, unit);
554 n += unit_len + 1;
555 }
556 if (user_unit) {
557 if (unit)
558 fprintf(f, "/%.*s", (int) user_unit_len, user_unit);
559 else
560 fprintf(f, " %.*s", (int) user_unit_len, user_unit);
561 n += unit_len + 1;
562 }
563 } else if (identifier && shall_print(identifier, identifier_len, flags)) {
08ace05b 564 fprintf(f, " %.*s", (int) identifier_len, identifier);
4cd9a9d9 565 n += identifier_len + 1;
08ace05b
LP
566 } else if (comm && shall_print(comm, comm_len, flags)) {
567 fprintf(f, " %.*s", (int) comm_len, comm);
55d7bfc1 568 n += comm_len + 1;
b5936820 569 } else
1248e840 570 fputs(" unknown", f);
86aa7ba4 571
08ace05b
LP
572 if (pid && shall_print(pid, pid_len, flags)) {
573 fprintf(f, "[%.*s]", (int) pid_len, pid);
55d7bfc1 574 n += pid_len + 2;
08ace05b
LP
575 } else if (fake_pid && shall_print(fake_pid, fake_pid_len, flags)) {
576 fprintf(f, "[%.*s]", (int) fake_pid_len, fake_pid);
6c1e6b98 577 n += fake_pid_len + 2;
86aa7ba4
LP
578 }
579
2108b567
LP
580 fputs(": ", f);
581
582 if (urlify_enabled()) {
583 _cleanup_free_ char *c = NULL;
584
585 /* Insert a hyperlink to a documentation URL before the message. Note that we don't make the
586 * whole message a hyperlink, since otherwise the whole screen might end up being just
587 * hyperlinks. Moreover, we want to be able to highlight parts of the message (such as the
588 * config file, see below) hence let's keep the documentation URL link separate. */
589
590 if (documentation_url && shall_print(documentation_url, documentation_url_len, flags)) {
591 c = strndup(documentation_url, documentation_url_len);
592 if (!c)
593 return log_oom();
594
595 if (!documentation_url_is_valid(c)) /* Eat up invalid links */
596 c = mfree(c);
597 }
598
599 if (!c)
600 (void) url_from_catalog(j, &c); /* Acquire from catalog if not embedded in log message itself */
601
602 if (c) {
603 _cleanup_free_ char *urlified = NULL;
604
605 if (terminal_urlify(c, special_glyph(SPECIAL_GLYPH_EXTERNAL_LINK), &urlified) >= 0) {
606 fputs(urlified, f);
607 fputc(' ', f);
608 }
609 }
610 }
611
2b59bf51
ZJS
612 if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(message, message_len))
613 fprintf(f, "[%s blob data]\n", FORMAT_BYTES(message_len));
614 else {
76f7cc3f
ZJS
615
616 /* URLify config_file string in message, if the message starts with it.
617 * Skip URLification if the highlighted pattern overlaps. */
618 if (config_file &&
619 message_len >= config_file_len &&
620 memcmp(message, config_file, config_file_len) == 0 &&
85fbebe6 621 (message_len == config_file_len || IN_SET(message[config_file_len], ':', ' ')) &&
76f7cc3f
ZJS
622 (!highlight || highlight_shifted[0] == 0 || highlight_shifted[0] > config_file_len)) {
623
624 _cleanup_free_ char *t = NULL, *urlified = NULL;
625
626 t = strndup(config_file, config_file_len);
627 if (t && terminal_urlify_path(t, NULL, &urlified) >= 0) {
85fbebe6
ZJS
628 size_t urlified_len = strlen(urlified);
629 size_t shift = urlified_len - config_file_len;
76f7cc3f
ZJS
630 char *joined;
631
85fbebe6 632 joined = realloc(urlified, message_len + shift);
76f7cc3f 633 if (joined) {
85fbebe6 634 memcpy(joined + urlified_len, message + config_file_len, message_len - config_file_len);
76f7cc3f 635 free_and_replace(message, joined);
85fbebe6 636 TAKE_PTR(urlified);
76f7cc3f
ZJS
637 message_len += shift;
638 if (highlight) {
639 highlight_shifted[0] += shift;
640 highlight_shifted[1] += shift;
641 }
642 }
643 }
644 }
645
94e0bd7d 646 ellipsized |=
194da5ca 647 print_multiline(f, n + 2, n_columns, flags, p, audit,
b4766d5f
ZJS
648 message, message_len,
649 highlight_shifted);
31f7bf19 650 }
55d7bfc1 651
d4205751 652 if (flags & OUTPUT_CATALOG)
2108b567 653 (void) print_catalog(f, j);
d4205751 654
94e0bd7d 655 return ellipsized;
86aa7ba4
LP
656}
657
08ace05b
LP
658static int output_verbose(
659 FILE *f,
660 sd_journal *j,
661 OutputMode mode,
662 unsigned n_columns,
cc25a67e 663 OutputFlags flags,
2f063186 664 const Set *output_fields,
275e6be0
DB
665 const size_t highlight[2],
666 const dual_timestamp *ts,
893bcd3d
DB
667 const sd_id128_t *boot_id,
668 const dual_timestamp *previous_ts,
669 const sd_id128_t *previous_boot_id) {
08ace05b 670
86aa7ba4
LP
671 const void *data;
672 size_t length;
7fd1b19b 673 _cleanup_free_ char *cursor = NULL;
275e6be0 674 char buf[FORMAT_TIMESTAMP_MAX + 7];
8924973a 675 const char *timestamp;
86aa7ba4
LP
676 int r;
677
08ace05b 678 assert(f);
86aa7ba4 679 assert(j);
275e6be0
DB
680 assert(ts);
681 assert(boot_id);
893bcd3d
DB
682 assert(previous_ts);
683 assert(previous_boot_id);
86aa7ba4 684
93b73b06
LP
685 sd_journal_set_data_threshold(j, 0);
686
275e6be0
DB
687 if (!VALID_REALTIME(ts->realtime))
688 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No valid realtime timestamp available");
86aa7ba4
LP
689
690 r = sd_journal_get_cursor(j, &cursor);
f647962d
MS
691 if (r < 0)
692 return log_error_errno(r, "Failed to get cursor: %m");
86aa7ba4 693
275e6be0 694 timestamp = format_timestamp_style(buf, sizeof buf, ts->realtime,
7b3eb5c9 695 flags & OUTPUT_UTC ? TIMESTAMP_US_UTC : TIMESTAMP_US);
08ace05b 696 fprintf(f, "%s [%s]\n",
8924973a 697 timestamp ?: "(no timestamp)",
08ace05b 698 cursor);
86aa7ba4 699
a72b6353 700 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
79dc477f 701 const char *c, *p;
31f7bf19 702 int fieldlen;
7ac4fa7e 703 const char *on = "", *off = "";
79dc477f
ZJS
704 _cleanup_free_ char *urlified = NULL;
705 size_t valuelen;
7ac4fa7e 706
31f7bf19 707 c = memchr(data, '=', length);
baaa35ad 708 if (!c)
805d67c5
YW
709 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid field.");
710
31f7bf19 711 fieldlen = c - (const char*) data;
805d67c5
YW
712 if (!journal_field_valid(data, fieldlen, true))
713 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid field.");
86aa7ba4 714
cc25a67e
LK
715 r = field_set_test(output_fields, data, fieldlen);
716 if (r < 0)
717 return r;
79dc477f 718 if (r == 0)
cc25a67e
LK
719 continue;
720
79dc477f
ZJS
721 valuelen = length - 1 - fieldlen;
722
723 if ((flags & OUTPUT_COLOR) && (p = startswith(data, "MESSAGE="))) {
1fc464f6
LP
724 on = ANSI_HIGHLIGHT;
725 off = ANSI_NORMAL;
79dc477f
ZJS
726 } else if ((p = startswith(data, "CONFIG_FILE="))) {
727 if (terminal_urlify_path(p, NULL, &urlified) >= 0) {
728 p = urlified;
729 valuelen = strlen(urlified);
730 }
731 } else
732 p = c + 1;
7ac4fa7e 733
8980058a 734 if ((flags & OUTPUT_SHOW_ALL) ||
a6f0104a
ZJS
735 (((length < PRINT_CHAR_THRESHOLD) || flags & OUTPUT_FULL_WIDTH)
736 && utf8_is_printable(data, length))) {
7ac4fa7e 737 fprintf(f, " %s%.*s=", on, fieldlen, (const char*)data);
194da5ca 738 print_multiline(f, 4 + fieldlen + 1, 0, OUTPUT_FULL_WIDTH, 0, false,
79dc477f 739 p, valuelen,
194da5ca 740 NULL);
7ac4fa7e 741 fputs(off, f);
2b59bf51 742 } else
7ac4fa7e
ZJS
743 fprintf(f, " %s%.*s=[%s blob data]%s\n",
744 on,
31f7bf19
ZJS
745 (int) (c - (const char*) data),
746 (const char*) data,
2b59bf51 747 FORMAT_BYTES(length - (c - (const char *) data) - 1),
7ac4fa7e 748 off);
86aa7ba4
LP
749 }
750
a72b6353
ZJS
751 if (r < 0)
752 return r;
753
d4205751 754 if (flags & OUTPUT_CATALOG)
2108b567 755 (void) print_catalog(f, j);
d4205751 756
86aa7ba4
LP
757 return 0;
758}
759
08ace05b
LP
760static int output_export(
761 FILE *f,
762 sd_journal *j,
763 OutputMode mode,
764 unsigned n_columns,
cc25a67e 765 OutputFlags flags,
2f063186 766 const Set *output_fields,
275e6be0
DB
767 const size_t highlight[2],
768 const dual_timestamp *ts,
893bcd3d
DB
769 const sd_id128_t *boot_id,
770 const dual_timestamp *previous_ts,
771 const sd_id128_t *previous_boot_id) {
08ace05b 772
7fd1b19b 773 _cleanup_free_ char *cursor = NULL;
86aa7ba4
LP
774 const void *data;
775 size_t length;
417cbcd6 776 usec_t monotonic, realtime;
777 sd_id128_t journal_boot_id;
85b55869 778 int r;
86aa7ba4
LP
779
780 assert(j);
275e6be0
DB
781 assert(ts);
782 assert(boot_id);
893bcd3d
DB
783 assert(previous_ts);
784 assert(previous_boot_id);
86aa7ba4 785
93b73b06
LP
786 sd_journal_set_data_threshold(j, 0);
787
86aa7ba4 788 r = sd_journal_get_cursor(j, &cursor);
f647962d
MS
789 if (r < 0)
790 return log_error_errno(r, "Failed to get cursor: %m");
86aa7ba4 791
417cbcd6 792 r = sd_journal_get_realtime_usec(j, &realtime);
793 if (r < 0)
794 return log_error_errno(r, "Failed to get realtime timestamp: %m");
795
796 r = sd_journal_get_monotonic_usec(j, &monotonic, &journal_boot_id);
797 if (r < 0)
798 return log_error_errno(r, "Failed to get monotonic timestamp: %m");
799
08ace05b
LP
800 fprintf(f,
801 "__CURSOR=%s\n"
de0671ee
ZJS
802 "__REALTIME_TIMESTAMP="USEC_FMT"\n"
803 "__MONOTONIC_TIMESTAMP="USEC_FMT"\n"
08ace05b
LP
804 "_BOOT_ID=%s\n",
805 cursor,
417cbcd6 806 realtime,
807 monotonic,
808 SD_ID128_TO_STRING(journal_boot_id));
86aa7ba4 809
a72b6353 810 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
805d67c5 811 size_t fieldlen;
cc25a67e 812 const char *c;
86aa7ba4 813
0ab896b3
ZJS
814 /* We already printed the boot id from the data in the header, hence let's suppress it here */
815 if (memory_startswith(data, length, "_BOOT_ID="))
112301ae
LP
816 continue;
817
cc25a67e 818 c = memchr(data, '=', length);
baaa35ad 819 if (!c)
805d67c5 820 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid field.");
cc25a67e 821
805d67c5
YW
822 fieldlen = c - (const char*) data;
823 if (!journal_field_valid(data, fieldlen, true))
824 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid field.");
825
826 r = field_set_test(output_fields, data, fieldlen);
cc25a67e
LK
827 if (r < 0)
828 return r;
829 if (!r)
830 continue;
831
0ade5ffe
ZJS
832 if (utf8_is_printable_newline(data, length, false))
833 fwrite(data, length, 1, f);
834 else {
86aa7ba4
LP
835 uint64_t le64;
836
805d67c5 837 fwrite(data, fieldlen, 1, f);
08ace05b 838 fputc('\n', f);
805d67c5 839 le64 = htole64(length - fieldlen - 1);
08ace05b 840 fwrite(&le64, sizeof(le64), 1, f);
805d67c5 841 fwrite(c + 1, length - fieldlen - 1, 1, f);
0ade5ffe 842 }
86aa7ba4 843
08ace05b 844 fputc('\n', f);
86aa7ba4 845 }
4f5e1723
AW
846 if (r == -EBADMSG) {
847 log_debug_errno(r, "Skipping message we can't read: %m");
848 return 0;
849 }
86aa7ba4 850
a72b6353
ZJS
851 if (r < 0)
852 return r;
853
08ace05b 854 fputc('\n', f);
86aa7ba4
LP
855
856 return 0;
857}
858
240a5fe8 859void json_escape(
08ace05b
LP
860 FILE *f,
861 const char* p,
862 size_t l,
863 OutputFlags flags) {
864
865 assert(f);
866 assert(p);
867
93b73b06 868 if (!(flags & OUTPUT_SHOW_ALL) && l >= JSON_THRESHOLD)
08ace05b
LP
869 fputs("null", f);
870
8980058a 871 else if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(p, l)) {
86aa7ba4
LP
872 bool not_first = false;
873
08ace05b 874 fputs("[ ", f);
86aa7ba4
LP
875
876 while (l > 0) {
877 if (not_first)
08ace05b 878 fprintf(f, ", %u", (uint8_t) *p);
86aa7ba4
LP
879 else {
880 not_first = true;
08ace05b 881 fprintf(f, "%u", (uint8_t) *p);
86aa7ba4
LP
882 }
883
884 p++;
885 l--;
886 }
887
08ace05b 888 fputs(" ]", f);
86aa7ba4 889 } else {
e768a4f0 890 fputc('"', f);
86aa7ba4
LP
891
892 while (l > 0) {
4c701096 893 if (IN_SET(*p, '"', '\\')) {
08ace05b
LP
894 fputc('\\', f);
895 fputc(*p, f);
31f7bf19
ZJS
896 } else if (*p == '\n')
897 fputs("\\n", f);
91a8a108
DM
898 else if ((uint8_t) *p < ' ')
899 fprintf(f, "\\u%04x", (uint8_t) *p);
08ace05b
LP
900 else
901 fputc(*p, f);
86aa7ba4
LP
902
903 p++;
904 l--;
905 }
906
e768a4f0 907 fputc('"', f);
86aa7ba4
LP
908 }
909}
910
8e044443
LP
911struct json_data {
912 JsonVariant* name;
913 size_t n_values;
914 JsonVariant* values[];
915};
916
917static int update_json_data(
918 Hashmap *h,
919 OutputFlags flags,
920 const char *name,
921 const void *value,
922 size_t size) {
923
924 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
925 struct json_data *d;
926 int r;
927
928 if (!(flags & OUTPUT_SHOW_ALL) && strlen(name) + 1 + size >= JSON_THRESHOLD)
929 r = json_variant_new_null(&v);
930 else if (utf8_is_printable(value, size))
931 r = json_variant_new_stringn(&v, value, size);
932 else
933 r = json_variant_new_array_bytes(&v, value, size);
934 if (r < 0)
935 return log_error_errno(r, "Failed to allocate JSON data: %m");
936
937 d = hashmap_get(h, name);
938 if (d) {
939 struct json_data *w;
940
941 w = realloc(d, offsetof(struct json_data, values) + sizeof(JsonVariant*) * (d->n_values + 1));
942 if (!w)
943 return log_oom();
944
945 d = w;
946 assert_se(hashmap_update(h, json_variant_string(d->name), d) >= 0);
947 } else {
948 _cleanup_(json_variant_unrefp) JsonVariant *n = NULL;
949
950 r = json_variant_new_string(&n, name);
951 if (r < 0)
952 return log_error_errno(r, "Failed to allocate JSON name variant: %m");
953
954 d = malloc0(offsetof(struct json_data, values) + sizeof(JsonVariant*));
955 if (!d)
956 return log_oom();
957
958 r = hashmap_put(h, json_variant_string(n), d);
959 if (r < 0) {
960 free(d);
961 return log_error_errno(r, "Failed to insert JSON name into hashmap: %m");
962 }
963
964 d->name = TAKE_PTR(n);
965 }
966
967 d->values[d->n_values++] = TAKE_PTR(v);
968 return 0;
969}
970
971static int update_json_data_split(
972 Hashmap *h,
973 OutputFlags flags,
2f063186 974 const Set *output_fields,
8e044443
LP
975 const void *data,
976 size_t size) {
977
805d67c5 978 size_t fieldlen;
8e044443
LP
979 const char *eq;
980 char *name;
981
982 assert(h);
983 assert(data || size == 0);
984
985 if (memory_startswith(data, size, "_BOOT_ID="))
986 return 0;
987
988 eq = memchr(data, '=', MIN(size, JSON_THRESHOLD));
989 if (!eq)
990 return 0;
991
805d67c5
YW
992 fieldlen = eq - (const char*) data;
993 if (!journal_field_valid(data, fieldlen, true))
994 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid field.");
8e044443 995
2f82562b 996 name = strndupa_safe(data, fieldlen);
2f063186 997 if (output_fields && !set_contains(output_fields, name))
8e044443
LP
998 return 0;
999
805d67c5 1000 return update_json_data(h, flags, name, eq + 1, size - fieldlen - 1);
8e044443
LP
1001}
1002
08ace05b
LP
1003static int output_json(
1004 FILE *f,
1005 sd_journal *j,
1006 OutputMode mode,
1007 unsigned n_columns,
cc25a67e 1008 OutputFlags flags,
2f063186 1009 const Set *output_fields,
275e6be0
DB
1010 const size_t highlight[2],
1011 const dual_timestamp *ts,
893bcd3d
DB
1012 const sd_id128_t *boot_id,
1013 const dual_timestamp *previous_ts,
1014 const sd_id128_t *previous_boot_id) {
08ace05b 1015
8e044443
LP
1016 char sid[SD_ID128_STRING_MAX], usecbuf[DECIMAL_STR_MAX(usec_t)];
1017 _cleanup_(json_variant_unrefp) JsonVariant *object = NULL;
7fd1b19b 1018 _cleanup_free_ char *cursor = NULL;
8e044443
LP
1019 JsonVariant **array = NULL;
1020 struct json_data *d;
d99ae53a 1021 Hashmap *h = NULL;
8e044443 1022 size_t n = 0;
417cbcd6 1023 usec_t realtime, monotonic;
1024 sd_id128_t journal_boot_id;
8e044443 1025 int r;
86aa7ba4
LP
1026
1027 assert(j);
275e6be0
DB
1028 assert(ts);
1029 assert(boot_id);
893bcd3d
DB
1030 assert(previous_ts);
1031 assert(previous_boot_id);
86aa7ba4 1032
8e044443 1033 (void) sd_journal_set_data_threshold(j, flags & OUTPUT_SHOW_ALL ? 0 : JSON_THRESHOLD);
93b73b06 1034
86aa7ba4 1035 r = sd_journal_get_cursor(j, &cursor);
f647962d
MS
1036 if (r < 0)
1037 return log_error_errno(r, "Failed to get cursor: %m");
86aa7ba4 1038
417cbcd6 1039 r = sd_journal_get_realtime_usec(j, &realtime);
1040 if (r < 0)
1041 return log_error_errno(r, "Failed to get realtime timestamp: %m");
1042
1043 r = sd_journal_get_monotonic_usec(j, &monotonic, &journal_boot_id);
1044 if (r < 0)
1045 return log_error_errno(r, "Failed to get monotonic timestamp: %m");
1046
d5099efc 1047 h = hashmap_new(&string_hash_ops);
d99ae53a 1048 if (!h)
b56d608e 1049 return log_oom();
d99ae53a 1050
8e044443 1051 r = update_json_data(h, flags, "__CURSOR", cursor, strlen(cursor));
a72b6353 1052 if (r < 0)
8e044443 1053 goto finish;
d99ae53a 1054
417cbcd6 1055 xsprintf(usecbuf, USEC_FMT, realtime);
8e044443
LP
1056 r = update_json_data(h, flags, "__REALTIME_TIMESTAMP", usecbuf, strlen(usecbuf));
1057 if (r < 0)
1058 goto finish;
d99ae53a 1059
417cbcd6 1060 xsprintf(usecbuf, USEC_FMT, monotonic);
8e044443
LP
1061 r = update_json_data(h, flags, "__MONOTONIC_TIMESTAMP", usecbuf, strlen(usecbuf));
1062 if (r < 0)
1063 goto finish;
d99ae53a 1064
417cbcd6 1065 sd_id128_to_string(journal_boot_id, sid);
8e044443
LP
1066 r = update_json_data(h, flags, "_BOOT_ID", sid, strlen(sid));
1067 if (r < 0)
1068 goto finish;
d99ae53a 1069
8e044443
LP
1070 for (;;) {
1071 const void *data;
1072 size_t size;
d99ae53a 1073
8e044443
LP
1074 r = sd_journal_enumerate_data(j, &data, &size);
1075 if (r == -EBADMSG) {
1076 log_debug_errno(r, "Skipping message we can't read: %m");
1077 r = 0;
1078 goto finish;
1079 }
1080 if (r < 0) {
1081 log_error_errno(r, "Failed to read journal: %m");
1082 goto finish;
1083 }
1084 if (r == 0)
1085 break;
d99ae53a 1086
8e044443
LP
1087 r = update_json_data_split(h, flags, output_fields, data, size);
1088 if (r < 0)
1089 goto finish;
1090 }
d99ae53a 1091
8e044443
LP
1092 array = new(JsonVariant*, hashmap_size(h)*2);
1093 if (!array) {
1094 r = log_oom();
1095 goto finish;
1096 }
d99ae53a 1097
90e74a66 1098 HASHMAP_FOREACH(d, h) {
8e044443 1099 assert(d->n_values > 0);
d99ae53a 1100
8e044443 1101 array[n++] = json_variant_ref(d->name);
d99ae53a 1102
8e044443
LP
1103 if (d->n_values == 1)
1104 array[n++] = json_variant_ref(d->values[0]);
1105 else {
1106 _cleanup_(json_variant_unrefp) JsonVariant *q = NULL;
d99ae53a 1107
8e044443
LP
1108 r = json_variant_new_array(&q, d->values, d->n_values);
1109 if (r < 0) {
1110 log_error_errno(r, "Failed to create JSON array: %m");
1111 goto finish;
d99ae53a 1112 }
8e044443
LP
1113
1114 array[n++] = TAKE_PTR(q);
d99ae53a 1115 }
8e044443 1116 }
d99ae53a 1117
8e044443
LP
1118 r = json_variant_new_object(&object, array, n);
1119 if (r < 0) {
1120 log_error_errno(r, "Failed to allocate JSON object: %m");
1121 goto finish;
1122 }
d99ae53a 1123
8e044443 1124 json_variant_dump(object,
9e964bb8 1125 output_mode_to_json_format_flags(mode) |
8e044443
LP
1126 (FLAGS_SET(flags, OUTPUT_COLOR) ? JSON_FORMAT_COLOR : 0),
1127 f, NULL);
86aa7ba4 1128
d99ae53a
LP
1129 r = 0;
1130
1131finish:
8e044443
LP
1132 while ((d = hashmap_steal_first(h))) {
1133 size_t k;
1134
1135 json_variant_unref(d->name);
1136 for (k = 0; k < d->n_values; k++)
1137 json_variant_unref(d->values[k]);
1138
1139 free(d);
1140 }
d99ae53a
LP
1141
1142 hashmap_free(h);
1143
8e044443
LP
1144 json_variant_unref_many(array, n);
1145 free(array);
1146
d99ae53a 1147 return r;
86aa7ba4
LP
1148}
1149
4d5d1bba 1150static int output_cat_field(
08ace05b
LP
1151 FILE *f,
1152 sd_journal *j,
cc25a67e 1153 OutputFlags flags,
e3eec1fd 1154 int prio,
4d5d1bba 1155 const char *field,
05c7d9bf 1156 const size_t highlight[2]) {
08ace05b 1157
e3eec1fd 1158 const char *color_on = "", *color_off = "", *highlight_on = "";
d3f2bdbf 1159 const void *data;
4d5d1bba 1160 size_t l, fl;
d3f2bdbf
LP
1161 int r;
1162
e3eec1fd
LP
1163 if (FLAGS_SET(flags, OUTPUT_COLOR))
1164 get_log_colors(prio, &color_on, &color_off, &highlight_on);
93b73b06 1165
4d5d1bba 1166 r = sd_journal_get_data(j, field, &data, &l);
4f5e1723
AW
1167 if (r == -EBADMSG) {
1168 log_debug_errno(r, "Skipping message we can't read: %m");
1169 return 0;
1170 }
4d5d1bba
LP
1171 if (r == -ENOENT) /* An entry without the requested field */
1172 return 0;
1173 if (r < 0)
8d3d7072 1174 return log_error_errno(r, "Failed to get data: %m");
d3f2bdbf 1175
4d5d1bba
LP
1176 fl = strlen(field);
1177 assert(l >= fl + 1);
1178 assert(((char*) data)[fl] == '=');
1179
1180 data = (const uint8_t*) data + fl + 1;
1181 l -= fl + 1;
d3f2bdbf 1182
e3eec1fd
LP
1183 if (FLAGS_SET(flags, OUTPUT_COLOR)) {
1184 if (highlight) {
1185 assert(highlight[0] <= highlight[1]);
1186 assert(highlight[1] <= l);
1187
1188 fputs(color_on, f);
1189 fwrite((const char*) data, 1, highlight[0], f);
1190 fputs(highlight_on, f);
1191 fwrite((const char*) data + highlight[0], 1, highlight[1] - highlight[0], f);
1192 fputs(color_on, f);
1193 fwrite((const char*) data + highlight[1], 1, l - highlight[1], f);
1194 fputs(color_off, f);
1195 } else {
1196 fputs(color_on, f);
1197 fwrite((const char*) data, 1, l, f);
1198 fputs(color_off, f);
1199 }
b4766d5f 1200 } else
4d5d1bba
LP
1201 fwrite((const char*) data, 1, l, f);
1202
08ace05b 1203 fputc('\n', f);
4d5d1bba
LP
1204 return 0;
1205}
1206
1207static int output_cat(
1208 FILE *f,
1209 sd_journal *j,
1210 OutputMode mode,
1211 unsigned n_columns,
1212 OutputFlags flags,
2f063186 1213 const Set *output_fields,
275e6be0
DB
1214 const size_t highlight[2],
1215 const dual_timestamp *ts,
893bcd3d
DB
1216 const sd_id128_t *boot_id,
1217 const dual_timestamp *previous_ts,
1218 const sd_id128_t *previous_boot_id) {
4d5d1bba 1219
e3eec1fd 1220 int r, prio = LOG_INFO;
4d5d1bba 1221 const char *field;
4d5d1bba
LP
1222
1223 assert(j);
1224 assert(f);
275e6be0
DB
1225 assert(ts);
1226 assert(boot_id);
893bcd3d
DB
1227 assert(previous_ts);
1228 assert(previous_boot_id);
4d5d1bba
LP
1229
1230 (void) sd_journal_set_data_threshold(j, 0);
1231
e3eec1fd
LP
1232 if (FLAGS_SET(flags, OUTPUT_COLOR)) {
1233 const void *data;
1234 size_t l;
1235
1236 /* Determine priority of this entry, so that we can color it nicely */
1237
1238 r = sd_journal_get_data(j, "PRIORITY", &data, &l);
1239 if (r == -EBADMSG) {
1240 log_debug_errno(r, "Skipping message we can't read: %m");
1241 return 0;
1242 }
1243 if (r < 0) {
1244 if (r != -ENOENT)
1245 return log_error_errno(r, "Failed to get data: %m");
1246
1247 /* An entry without PRIORITY */
1248 } else if (l == 10 && memcmp(data, "PRIORITY=", 9) == 0) {
1249 char c = ((char*) data)[9];
1250
1251 if (c >= '0' && c <= '7')
1252 prio = c - '0';
1253 }
1254 }
1255
4d5d1bba 1256 if (set_isempty(output_fields))
e3eec1fd 1257 return output_cat_field(f, j, flags, prio, "MESSAGE", highlight);
4d5d1bba 1258
90e74a66 1259 SET_FOREACH(field, output_fields) {
e3eec1fd 1260 r = output_cat_field(f, j, flags, prio, field, streq(field, "MESSAGE") ? highlight : NULL);
4d5d1bba
LP
1261 if (r < 0)
1262 return r;
1263 }
d3f2bdbf
LP
1264
1265 return 0;
1266}
1267
275e6be0
DB
1268static int get_dual_timestamp(sd_journal *j, dual_timestamp *ret_ts, sd_id128_t *ret_boot_id) {
1269 const void *data;
1270 _cleanup_free_ char *realtime = NULL, *monotonic = NULL;
1271 size_t length = 0, realtime_len = 0, monotonic_len = 0;
1272 const ParseFieldVec message_fields[] = {
1273 PARSE_FIELD_VEC_ENTRY("_SOURCE_REALTIME_TIMESTAMP=", &realtime, &realtime_len),
1274 PARSE_FIELD_VEC_ENTRY("_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic, &monotonic_len),
1275 };
1276 int r;
4ba5536f 1277 bool realtime_good = false, monotonic_good = false, boot_id_good = false;
275e6be0
DB
1278
1279 assert(j);
1280 assert(ret_ts);
1281 assert(ret_boot_id);
1282
1283 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
1284 r = parse_fieldv(data, length, message_fields, ELEMENTSOF(message_fields));
1285 if (r < 0)
1286 return r;
86850391
LP
1287
1288 if (realtime && monotonic)
1289 break;
275e6be0
DB
1290 }
1291 if (r < 0)
1292 return r;
1293
1294 if (realtime)
4ba5536f
LP
1295 realtime_good = safe_atou64(realtime, &ret_ts->realtime) >= 0;
1296 if (!realtime_good || !VALID_REALTIME(ret_ts->realtime))
1297 realtime_good = sd_journal_get_realtime_usec(j, &ret_ts->realtime) >= 0;
1298 if (!realtime_good)
275e6be0
DB
1299 ret_ts->realtime = USEC_INFINITY;
1300
1301 if (monotonic)
4ba5536f
LP
1302 monotonic_good = safe_atou64(monotonic, &ret_ts->monotonic) >= 0;
1303 if (!monotonic_good || !VALID_MONOTONIC(ret_ts->monotonic))
1304 monotonic_good = boot_id_good = sd_journal_get_monotonic_usec(j, &ret_ts->monotonic, ret_boot_id) >= 0;
1305 if (!monotonic_good)
275e6be0
DB
1306 ret_ts->monotonic = USEC_INFINITY;
1307
4ba5536f
LP
1308 if (!boot_id_good)
1309 boot_id_good = sd_journal_get_monotonic_usec(j, NULL, ret_boot_id) >= 0;
1310 if (!boot_id_good)
1311 *ret_boot_id = SD_ID128_NULL;
1312
275e6be0
DB
1313 /* Restart all data before */
1314 sd_journal_restart_data(j);
1315 sd_journal_restart_unique(j);
1316 sd_journal_restart_fields(j);
1317
1318 return 0;
1319}
1320
08ace05b
LP
1321static int (*output_funcs[_OUTPUT_MODE_MAX])(
1322 FILE *f,
f2a3de01 1323 sd_journal *j,
08ace05b
LP
1324 OutputMode mode,
1325 unsigned n_columns,
cc25a67e 1326 OutputFlags flags,
2f063186 1327 const Set *output_fields,
275e6be0
DB
1328 const size_t highlight[2],
1329 const dual_timestamp *ts,
893bcd3d
DB
1330 const sd_id128_t *boot_id,
1331 const dual_timestamp *previous_ts,
1332 const sd_id128_t *previous_boot_id) = {
08ace05b 1333
71b7a6c4
ZJS
1334 [OUTPUT_SHORT] = output_short,
1335 [OUTPUT_SHORT_ISO] = output_short,
7e563bfc 1336 [OUTPUT_SHORT_ISO_PRECISE] = output_short,
71b7a6c4
ZJS
1337 [OUTPUT_SHORT_PRECISE] = output_short,
1338 [OUTPUT_SHORT_MONOTONIC] = output_short,
893bcd3d 1339 [OUTPUT_SHORT_DELTA] = output_short,
71b7a6c4
ZJS
1340 [OUTPUT_SHORT_UNIX] = output_short,
1341 [OUTPUT_SHORT_FULL] = output_short,
1342 [OUTPUT_VERBOSE] = output_verbose,
1343 [OUTPUT_EXPORT] = output_export,
1344 [OUTPUT_JSON] = output_json,
1345 [OUTPUT_JSON_PRETTY] = output_json,
1346 [OUTPUT_JSON_SSE] = output_json,
1347 [OUTPUT_JSON_SEQ] = output_json,
1348 [OUTPUT_CAT] = output_cat,
1349 [OUTPUT_WITH_UNIT] = output_short,
86aa7ba4
LP
1350};
1351
9b972c9a 1352int show_journal_entry(
08ace05b
LP
1353 FILE *f,
1354 sd_journal *j,
1355 OutputMode mode,
1356 unsigned n_columns,
94e0bd7d 1357 OutputFlags flags,
cc25a67e 1358 char **output_fields,
05c7d9bf 1359 const size_t highlight[2],
893bcd3d
DB
1360 bool *ellipsized,
1361 dual_timestamp *previous_ts,
1362 sd_id128_t *previous_boot_id) {
08ace05b 1363
be327321 1364 _cleanup_set_free_ Set *fields = NULL;
275e6be0
DB
1365 dual_timestamp ts = DUAL_TIMESTAMP_NULL;
1366 sd_id128_t boot_id = SD_ID128_NULL;
be327321
ZJS
1367 int r;
1368
df50185b 1369 assert(mode >= 0);
86aa7ba4 1370 assert(mode < _OUTPUT_MODE_MAX);
893bcd3d
DB
1371 assert(previous_ts);
1372 assert(previous_boot_id);
86aa7ba4 1373
34a35ece
LP
1374 if (n_columns <= 0)
1375 n_columns = columns();
1376
be327321
ZJS
1377 r = set_put_strdupv(&fields, output_fields);
1378 if (r < 0)
1379 return r;
cc25a67e 1380
275e6be0
DB
1381 r = get_dual_timestamp(j, &ts, &boot_id);
1382 if (r == -EBADMSG) {
1383 log_debug_errno(r, "Skipping message we can't read: %m");
1384 return 0;
1385 }
1386 if (r < 0)
1387 return log_error_errno(r, "Failed to get journal fields: %m");
1388
893bcd3d
DB
1389 r = output_funcs[mode](f, j, mode, n_columns, flags, fields, highlight, &ts, &boot_id, previous_ts, previous_boot_id);
1390
1391 /* Store timestamp and boot ID for next iteration */
1392 *previous_ts = ts;
1393 *previous_boot_id = boot_id;
94e0bd7d 1394
be327321 1395 if (ellipsized && r > 0)
94e0bd7d
ZJS
1396 *ellipsized = true;
1397
be327321 1398 return r;
86aa7ba4
LP
1399}
1400
ea6c2dd1
LP
1401static int maybe_print_begin_newline(FILE *f, OutputFlags *flags) {
1402 assert(f);
1403 assert(flags);
1404
1405 if (!(*flags & OUTPUT_BEGIN_NEWLINE))
1406 return 0;
1407
1408 /* Print a beginning new line if that's request, but only once
1409 * on the first line we print. */
1410
1411 fputc('\n', f);
1412 *flags &= ~OUTPUT_BEGIN_NEWLINE;
1413 return 0;
1414}
1415
889e3960
ZJS
1416int show_journal(
1417 FILE *f,
1418 sd_journal *j,
1419 OutputMode mode,
1420 unsigned n_columns,
1421 usec_t not_before,
1422 unsigned how_many,
1423 OutputFlags flags,
1424 bool *ellipsized) {
86aa7ba4 1425
86aa7ba4 1426 int r;
df50185b
LP
1427 unsigned line = 0;
1428 bool need_seek = false;
085d7120 1429 int warn_cutoff = flags & OUTPUT_WARN_CUTOFF;
893bcd3d
DB
1430 dual_timestamp previous_ts = DUAL_TIMESTAMP_NULL;
1431 sd_id128_t previous_boot_id = SD_ID128_NULL;
86aa7ba4 1432
1a6c43e9 1433 assert(j);
df50185b
LP
1434 assert(mode >= 0);
1435 assert(mode < _OUTPUT_MODE_MAX);
1946b0bd 1436
f5fbe71d 1437 if (how_many == UINT_MAX)
889e3960
ZJS
1438 need_seek = true;
1439 else {
1440 /* Seek to end */
1441 r = sd_journal_seek_tail(j);
1442 if (r < 0)
1443 return log_error_errno(r, "Failed to seek to tail: %m");
86aa7ba4 1444
889e3960
ZJS
1445 r = sd_journal_previous_skip(j, how_many);
1446 if (r < 0)
1447 return log_error_errno(r, "Failed to skip previous: %m");
1448 }
86aa7ba4 1449
df50185b 1450 for (;;) {
27f31daf 1451 usec_t usec;
df50185b 1452
27f31daf
HD
1453 if (need_seek) {
1454 r = sd_journal_next(j);
1455 if (r < 0)
1456 return log_error_errno(r, "Failed to iterate through journal: %m");
1457 }
df50185b 1458
27f31daf
HD
1459 if (r == 0)
1460 break;
df50185b 1461
27f31daf 1462 need_seek = true;
df50185b 1463
27f31daf
HD
1464 if (not_before > 0) {
1465 r = sd_journal_get_monotonic_usec(j, &usec, NULL);
df50185b 1466
27f31daf
HD
1467 /* -ESTALE is returned if the timestamp is not from this boot */
1468 if (r == -ESTALE)
1469 continue;
1470 else if (r < 0)
1471 return log_error_errno(r, "Failed to get journal time: %m");
df50185b 1472
27f31daf
HD
1473 if (usec < not_before)
1474 continue;
df50185b
LP
1475 }
1476
27f31daf
HD
1477 line++;
1478 maybe_print_begin_newline(f, &flags);
08984293 1479
893bcd3d
DB
1480 r = show_journal_entry(f, j, mode, n_columns, flags, NULL, NULL, ellipsized,
1481 &previous_ts, &previous_boot_id);
27f31daf
HD
1482 if (r < 0)
1483 return r;
1484 }
08984293 1485
27f31daf
HD
1486 if (warn_cutoff && line < how_many && not_before > 0) {
1487 sd_id128_t boot_id;
1488 usec_t cutoff = 0;
08984293 1489
27f31daf 1490 /* Check whether the cutoff line is too early */
1a8f0ce6 1491
27f31daf
HD
1492 r = sd_id128_get_boot(&boot_id);
1493 if (r < 0)
1494 return log_error_errno(r, "Failed to get boot id: %m");
1a8f0ce6 1495
27f31daf
HD
1496 r = sd_journal_get_cutoff_monotonic_usec(j, boot_id, &cutoff, NULL);
1497 if (r < 0)
1498 return log_error_errno(r, "Failed to get journal cutoff time: %m");
1a8f0ce6 1499
27f31daf
HD
1500 if (r > 0 && not_before < cutoff) {
1501 maybe_print_begin_newline(f, &flags);
08984293 1502
27f31daf
HD
1503 /* If we logged *something* and no permission error happened, than we can reliably
1504 * emit the warning about rotation. If we didn't log anything and access errors
1505 * happened, emit hint about permissions. Otherwise, give a generic message, since we
1506 * can't diagnose the issue. */
08984293 1507
27f31daf 1508 bool noaccess = journal_access_blocked(j);
86aa7ba4 1509
27f31daf 1510 if (line == 0 && noaccess)
17e90001 1511 fprintf(f, "Warning: some journal files were not opened due to insufficient permissions.\n");
27f31daf 1512 else if (!noaccess)
71311efe 1513 fprintf(f, "Notice: journal has been rotated since unit was started, output may be incomplete.\n");
27f31daf
HD
1514 else
1515 fprintf(f, "Warning: journal has been rotated since unit was started and some journal "
1516 "files were not opened due to insufficient permissions, output may be incomplete.\n");
1517 }
df50185b 1518
27f31daf 1519 warn_cutoff = false;
86aa7ba4
LP
1520 }
1521
b56d608e 1522 return 0;
1a6c43e9
MT
1523}
1524
886a64fe 1525int add_matches_for_unit(sd_journal *j, const char *unit) {
2b45d881 1526 const char *m1, *m2, *m3, *m4;
1a6c43e9
MT
1527 int r;
1528
886a64fe 1529 assert(j);
1a6c43e9
MT
1530 assert(unit);
1531
63c372cb
LP
1532 m1 = strjoina("_SYSTEMD_UNIT=", unit);
1533 m2 = strjoina("COREDUMP_UNIT=", unit);
1534 m3 = strjoina("UNIT=", unit);
1535 m4 = strjoina("OBJECT_SYSTEMD_UNIT=", unit);
1a6c43e9 1536
886a64fe
ZJS
1537 (void)(
1538 /* Look for messages from the service itself */
1539 (r = sd_journal_add_match(j, m1, 0)) ||
1540
1541 /* Look for coredumps of the service */
1542 (r = sd_journal_add_disjunction(j)) ||
fdcd37df
ZJS
1543 (r = sd_journal_add_match(j, "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1", 0)) ||
1544 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
886a64fe
ZJS
1545 (r = sd_journal_add_match(j, m2, 0)) ||
1546
1547 /* Look for messages from PID 1 about this service */
1548 (r = sd_journal_add_disjunction(j)) ||
1549 (r = sd_journal_add_match(j, "_PID=1", 0)) ||
2d0b2e87
ZJS
1550 (r = sd_journal_add_match(j, m3, 0)) ||
1551
1552 /* Look for messages from authorized daemons about this service */
1553 (r = sd_journal_add_disjunction(j)) ||
1554 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
1555 (r = sd_journal_add_match(j, m4, 0))
886a64fe 1556 );
2d0b2e87 1557
69ae3ee0 1558 if (r == 0 && endswith(unit, ".slice")) {
2b45d881
LP
1559 const char *m5;
1560
1561 m5 = strjoina("_SYSTEMD_SLICE=", unit);
69ae3ee0
ZJS
1562
1563 /* Show all messages belonging to a slice */
1564 (void)(
1565 (r = sd_journal_add_disjunction(j)) ||
1566 (r = sd_journal_add_match(j, m5, 0))
1567 );
1568 }
1569
886a64fe
ZJS
1570 return r;
1571}
1a6c43e9 1572
886a64fe
ZJS
1573int add_matches_for_user_unit(sd_journal *j, const char *unit, uid_t uid) {
1574 int r;
2d0b2e87
ZJS
1575 char *m1, *m2, *m3, *m4;
1576 char muid[sizeof("_UID=") + DECIMAL_STR_MAX(uid_t)];
1a6c43e9 1577
886a64fe
ZJS
1578 assert(j);
1579 assert(unit);
1a6c43e9 1580
63c372cb
LP
1581 m1 = strjoina("_SYSTEMD_USER_UNIT=", unit);
1582 m2 = strjoina("USER_UNIT=", unit);
1583 m3 = strjoina("COREDUMP_USER_UNIT=", unit);
1584 m4 = strjoina("OBJECT_SYSTEMD_USER_UNIT=", unit);
de0671ee 1585 sprintf(muid, "_UID="UID_FMT, uid);
1a6c43e9 1586
886a64fe
ZJS
1587 (void) (
1588 /* Look for messages from the user service itself */
1589 (r = sd_journal_add_match(j, m1, 0)) ||
2d0b2e87 1590 (r = sd_journal_add_match(j, muid, 0)) ||
886a64fe
ZJS
1591
1592 /* Look for messages from systemd about this service */
1593 (r = sd_journal_add_disjunction(j)) ||
1594 (r = sd_journal_add_match(j, m2, 0)) ||
2d0b2e87 1595 (r = sd_journal_add_match(j, muid, 0)) ||
886a64fe
ZJS
1596
1597 /* Look for coredumps of the service */
1598 (r = sd_journal_add_disjunction(j)) ||
1599 (r = sd_journal_add_match(j, m3, 0)) ||
2d0b2e87
ZJS
1600 (r = sd_journal_add_match(j, muid, 0)) ||
1601 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
1602
1603 /* Look for messages from authorized daemons about this service */
1604 (r = sd_journal_add_disjunction(j)) ||
fdcd37df 1605 (r = sd_journal_add_match(j, m4, 0)) ||
2d0b2e87 1606 (r = sd_journal_add_match(j, muid, 0)) ||
fdcd37df 1607 (r = sd_journal_add_match(j, "_UID=0", 0))
886a64fe 1608 );
69ae3ee0
ZJS
1609
1610 if (r == 0 && endswith(unit, ".slice")) {
2b45d881
LP
1611 const char *m5;
1612
3daf1f91 1613 m5 = strjoina("_SYSTEMD_USER_SLICE=", unit);
69ae3ee0
ZJS
1614
1615 /* Show all messages belonging to a slice */
1616 (void)(
1617 (r = sd_journal_add_disjunction(j)) ||
1618 (r = sd_journal_add_match(j, m5, 0)) ||
1619 (r = sd_journal_add_match(j, muid, 0))
1620 );
1621 }
1622
1a6c43e9
MT
1623 return r;
1624}
1625
b6741478 1626static int get_boot_id_for_machine(const char *machine, sd_id128_t *boot_id) {
19ee48a6 1627 _cleanup_close_pair_ int pair[2] = PIPE_EBADF;
254d1313 1628 _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, rootfd = -EBADF;
b7416360 1629 char buf[SD_ID128_UUID_STRING_MAX];
b6741478 1630 pid_t pid, child;
b6741478
LP
1631 ssize_t k;
1632 int r;
1633
1634 assert(machine);
1635 assert(boot_id);
1636
e04b0cdb 1637 r = container_get_leader(machine, &pid);
b6741478
LP
1638 if (r < 0)
1639 return r;
e04b0cdb 1640
671c3419 1641 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, NULL, &rootfd);
b6741478
LP
1642 if (r < 0)
1643 return r;
1644
e04b0cdb 1645 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
b6741478
LP
1646 return -errno;
1647
1edcb6a9
LP
1648 r = namespace_fork("(sd-bootidns)", "(sd-bootid)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1649 pidnsfd, mntnsfd, -1, -1, rootfd, &child);
4c253ed1
LP
1650 if (r < 0)
1651 return r;
1652 if (r == 0) {
b6741478
LP
1653 int fd;
1654
03e334a1 1655 pair[0] = safe_close(pair[0]);
b6741478 1656
b6741478
LP
1657 fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1658 if (fd < 0)
1659 _exit(EXIT_FAILURE);
1660
a6dcc7e5 1661 r = loop_read_exact(fd, buf, 36, false);
03e334a1 1662 safe_close(fd);
6c767d1e 1663 if (r < 0)
b6741478
LP
1664 _exit(EXIT_FAILURE);
1665
e04b0cdb 1666 k = send(pair[1], buf, 36, MSG_NOSIGNAL);
b6741478
LP
1667 if (k != 36)
1668 _exit(EXIT_FAILURE);
1669
1670 _exit(EXIT_SUCCESS);
1671 }
1672
03e334a1 1673 pair[1] = safe_close(pair[1]);
b6741478 1674
1edcb6a9 1675 r = wait_for_terminate_and_check("(sd-bootidns)", child, 0);
2e87a1fd
LP
1676 if (r < 0)
1677 return r;
1678 if (r != EXIT_SUCCESS)
1679 return -EIO;
b6741478 1680
fbadf045
LP
1681 k = recv(pair[0], buf, 36, 0);
1682 if (k != 36)
1683 return -EIO;
1684
b6741478
LP
1685 buf[36] = 0;
1686 r = sd_id128_from_string(buf, boot_id);
1687 if (r < 0)
1688 return r;
1689
1690 return 0;
1691}
1692
1693int add_match_this_boot(sd_journal *j, const char *machine) {
5ec76417
ZJS
1694 char match[9+32+1] = "_BOOT_ID=";
1695 sd_id128_t boot_id;
1696 int r;
1697
1698 assert(j);
1699
b6741478
LP
1700 if (machine) {
1701 r = get_boot_id_for_machine(machine, &boot_id);
f647962d
MS
1702 if (r < 0)
1703 return log_error_errno(r, "Failed to get boot id of container %s: %m", machine);
b6741478
LP
1704 } else {
1705 r = sd_id128_get_boot(&boot_id);
f647962d
MS
1706 if (r < 0)
1707 return log_error_errno(r, "Failed to get boot id: %m");
5ec76417
ZJS
1708 }
1709
1710 sd_id128_to_string(boot_id, match + 9);
1711 r = sd_journal_add_match(j, match, strlen(match));
f647962d
MS
1712 if (r < 0)
1713 return log_error_errno(r, "Failed to add match: %m");
5ec76417
ZJS
1714
1715 r = sd_journal_add_conjunction(j);
1716 if (r < 0)
b56d608e 1717 return log_error_errno(r, "Failed to add conjunction: %m");
5ec76417
ZJS
1718
1719 return 0;
1720}
1721
886a64fe 1722int show_journal_by_unit(
1a6c43e9
MT
1723 FILE *f,
1724 const char *unit,
d93dda3a 1725 const char *log_namespace,
1a6c43e9
MT
1726 OutputMode mode,
1727 unsigned n_columns,
1728 usec_t not_before,
1729 unsigned how_many,
1730 uid_t uid,
886a64fe 1731 OutputFlags flags,
3c756001
LP
1732 int journal_open_flags,
1733 bool system_unit,
94e0bd7d 1734 bool *ellipsized) {
1a6c43e9 1735
4afd3348 1736 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
1a6c43e9
MT
1737 int r;
1738
1739 assert(mode >= 0);
1740 assert(mode < _OUTPUT_MODE_MAX);
1741 assert(unit);
1742
1a6c43e9
MT
1743 if (how_many <= 0)
1744 return 0;
1745
d93dda3a 1746 r = sd_journal_open_namespace(&j, log_namespace, journal_open_flags | SD_JOURNAL_INCLUDE_DEFAULT_NAMESPACE);
f9045468 1747 if (r < 0)
b56d608e 1748 return log_error_errno(r, "Failed to open journal: %m");
f9045468 1749
3c756001 1750 if (system_unit)
886a64fe
ZJS
1751 r = add_matches_for_unit(j, unit);
1752 else
1753 r = add_matches_for_user_unit(j, unit, uid);
1a6c43e9 1754 if (r < 0)
b56d608e 1755 return log_error_errno(r, "Failed to add unit matches: %m");
1a6c43e9 1756
f8202704
VC
1757 r = sd_journal_add_conjunction(j);
1758 if (r < 0)
1759 return log_error_errno(r, "Failed to add conjunction: %m");
1760
1761 r = add_match_this_boot(j, NULL);
1762 if (r < 0)
1763 return r;
1764
f1d34068 1765 if (DEBUG_LOGGING) {
c2b2df60 1766 _cleanup_free_ char *filter = NULL;
4ad16808
ZJS
1767
1768 filter = journal_make_match_string(j);
b56d608e
LP
1769 if (!filter)
1770 return log_oom();
1771
4ad16808
ZJS
1772 log_debug("Journal filter: %s", filter);
1773 }
5ec76417 1774
94e0bd7d 1775 return show_journal(f, j, mode, n_columns, not_before, how_many, flags, ellipsized);
86aa7ba4 1776}