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