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