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