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