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