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