1 /* SPDX-License-Identifier: LGPL-2.1+ */
8 #include <sys/socket.h>
13 #include "sd-journal.h"
15 #include "alloc-util.h"
17 #include "format-util.h"
19 #include "hostname-util.h"
20 #include "id128-util.h"
22 #include "journal-internal.h"
23 #include "journal-util.h"
25 #include "locale-util.h"
27 #include "logs-show.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"
39 #include "terminal-util.h"
40 #include "time-util.h"
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
49 #define JSON_THRESHOLD 4096U
51 static int print_catalog(FILE *f
, sd_journal
*j
) {
52 _cleanup_free_
char *t
= NULL
, *z
= NULL
;
57 r
= sd_journal_get_catalog(j
, &t
);
61 return log_error_errno(r
, "Failed to find catalog entry: %m");
63 z
= strreplace(strstrip(t
), "\n", "\n-- ");
74 static int url_from_catalog(sd_journal
*j
, char **ret
) {
75 _cleanup_free_
char *t
= NULL
, *url
= NULL
;
82 r
= sd_journal_get_catalog(j
, &t
);
86 return log_error_errno(r
, "Failed to find catalog entry: %m");
88 weblink
= startswith(t
, "Documentation:");
90 weblink
= strstr(t
+ 1, "\nDocumentation:");
97 /* Skip whitespace to value */
98 weblink
+= strspn(weblink
, " \t");
100 /* Cut out till next whitespace/newline */
101 url
= strndup(weblink
, strcspn(weblink
, WHITESPACE
));
105 if (!documentation_url_is_valid(url
))
108 *ret
= TAKE_PTR(url
);
116 static int parse_field(const void *data
, size_t length
, const char *field
, size_t field_len
, char **target
, size_t *target_len
) {
124 if (length
< field_len
)
127 if (memcmp(data
, field
, field_len
))
130 nl
= length
- field_len
;
132 buf
= newdup_suffix0(char, (const char*) data
+ field_len
, nl
);
145 typedef struct ParseFieldVec
{
152 #define PARSE_FIELD_VEC_ENTRY(_field, _target, _target_len) \
153 { .field = _field, .field_len = strlen(_field), .target = _target, .target_len = _target_len }
155 static int parse_fieldv(const void *data
, size_t length
, const ParseFieldVec
*fields
, unsigned n_fields
) {
158 for (i
= 0; i
< n_fields
; i
++) {
159 const ParseFieldVec
*f
= &fields
[i
];
162 r
= parse_field(data
, length
, f
->field
, f
->field_len
, f
->target
, f
->target_len
);
172 static int field_set_test(const Set
*fields
, const char *name
, size_t n
) {
178 s
= strndupa(name
, n
);
179 return set_contains(fields
, s
);
182 static bool shall_print(const char *p
, size_t l
, OutputFlags flags
) {
185 if (flags
& OUTPUT_SHOW_ALL
)
188 if (l
>= PRINT_CHAR_THRESHOLD
)
191 if (!utf8_is_printable(p
, l
))
197 static bool print_multiline(
206 size_t highlight
[2]) {
208 const char *color_on
= "", *color_off
= "", *highlight_on
= "";
209 const char *pos
, *end
;
210 bool ellipsized
= false;
213 if (flags
& OUTPUT_COLOR
) {
214 get_log_colors(priority
, &color_on
, &color_off
, &highlight_on
);
216 if (audit
&& strempty(color_on
)) {
217 color_on
= ANSI_BLUE
;
218 color_off
= ANSI_NORMAL
;
222 /* A special case: make sure that we print a newline when
223 the message is empty. */
224 if (message_len
== 0)
228 pos
< message
+ message_len
;
229 pos
= end
+ 1, line
++) {
230 bool continuation
= line
> 0;
233 for (end
= pos
; end
< message
+ message_len
&& *end
!= '\n'; end
++)
238 /* We need to figure out when we are showing not-last line, *and*
239 * will skip subsequent lines. In that case, we will put the dots
240 * at the end of the line, instead of putting dots in the middle
244 line
+ 1 == PRINT_LINE_THRESHOLD
||
245 end
+ 1 >= message
+ PRINT_CHAR_THRESHOLD
;
247 if (flags
& (OUTPUT_FULL_WIDTH
| OUTPUT_SHOW_ALL
) ||
248 (prefix
+ len
+ 1 < n_columns
&& !tail_line
)) {
250 (size_t) (pos
- message
) <= highlight
[0] &&
251 highlight
[0] < (size_t) len
) {
253 fprintf(f
, "%*s%s%.*s",
254 continuation
* prefix
, "",
255 color_on
, (int) highlight
[0], pos
);
258 (int) (MIN((size_t) len
, highlight
[1]) - highlight
[0]),
260 if ((size_t) len
> highlight
[1])
263 (int) (len
- highlight
[1]),
265 fprintf(f
, "%s\n", color_off
);
268 fprintf(f
, "%*s%s%.*s%s\n",
269 continuation
* prefix
, "",
270 color_on
, len
, pos
, color_off
);
274 /* Beyond this point, ellipsization will happen. */
277 if (prefix
< n_columns
&& n_columns
- prefix
>= 3) {
278 if (n_columns
- prefix
> (unsigned) len
+ 3)
279 fprintf(f
, "%*s%s%.*s...%s\n",
280 continuation
* prefix
, "",
281 color_on
, len
, pos
, color_off
);
283 _cleanup_free_
char *e
;
285 e
= ellipsize_mem(pos
, len
, n_columns
- prefix
,
286 tail_line
? 100 : 90);
288 fprintf(f
, "%*s%s%.*s%s\n",
289 continuation
* prefix
, "",
290 color_on
, len
, pos
, color_off
);
292 fprintf(f
, "%*s%s%s%s\n",
293 continuation
* prefix
, "",
294 color_on
, e
, color_off
);
306 static int output_timestamp_monotonic(FILE *f
, sd_journal
*j
, const char *monotonic
) {
316 r
= safe_atou64(monotonic
, &t
);
318 r
= sd_journal_get_monotonic_usec(j
, &t
, &boot_id
);
320 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
322 fprintf(f
, "[%5"PRI_USEC
".%06"PRI_USEC
"]", t
/ USEC_PER_SEC
, t
% USEC_PER_SEC
);
323 return 1 + 5 + 1 + 6 + 1;
326 static int output_timestamp_realtime(FILE *f
, sd_journal
*j
, OutputMode mode
, OutputFlags flags
, const char *realtime
) {
327 char buf
[MAX(FORMAT_TIMESTAMP_MAX
, 64)];
328 struct tm
*(*gettime_r
)(const time_t *, struct tm
*);
338 r
= safe_atou64(realtime
, &x
);
339 if (!realtime
|| r
< 0 || !VALID_REALTIME(x
))
340 r
= sd_journal_get_realtime_usec(j
, &x
);
342 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
344 if (IN_SET(mode
, OUTPUT_SHORT_FULL
, OUTPUT_WITH_UNIT
)) {
347 if (flags
& OUTPUT_UTC
)
348 k
= format_timestamp_utc(buf
, sizeof(buf
), x
);
350 k
= format_timestamp(buf
, sizeof(buf
), x
);
352 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
353 "Failed to format timestamp: %" PRIu64
, x
);
358 gettime_r
= (flags
& OUTPUT_UTC
) ? gmtime_r
: localtime_r
;
359 t
= (time_t) (x
/ USEC_PER_SEC
);
363 case OUTPUT_SHORT_UNIX
:
364 xsprintf(buf
, "%10"PRI_TIME
".%06"PRIu64
, t
, x
% USEC_PER_SEC
);
367 case OUTPUT_SHORT_ISO
:
368 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%H:%M:%S%z", gettime_r(&t
, &tm
)) <= 0)
369 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
370 "Failed to format ISO time");
373 case OUTPUT_SHORT_ISO_PRECISE
:
374 /* No usec in strftime, so we leave space and copy over */
375 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%H:%M:%S.xxxxxx%z", gettime_r(&t
, &tm
)) <= 0)
376 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
377 "Failed to format ISO-precise time");
378 xsprintf(usec
, "%06"PRI_USEC
, x
% USEC_PER_SEC
);
379 memcpy(buf
+ 20, usec
, 6);
383 case OUTPUT_SHORT_PRECISE
:
385 if (strftime(buf
, sizeof(buf
), "%b %d %H:%M:%S", gettime_r(&t
, &tm
)) <= 0)
386 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
387 "Failed to format syslog time");
389 if (mode
== OUTPUT_SHORT_PRECISE
) {
392 assert(sizeof(buf
) > strlen(buf
));
393 k
= sizeof(buf
) - strlen(buf
);
395 r
= snprintf(buf
+ strlen(buf
), k
, ".%06"PRIu64
, x
% USEC_PER_SEC
);
396 if (r
<= 0 || (size_t) r
>= k
) /* too long? */
397 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
398 "Failed to format precise time");
403 assert_not_reached("Unknown time format");
408 return (int) strlen(buf
);
411 static int output_short(
417 const Set
*output_fields
,
418 const size_t highlight
[2]) {
422 size_t length
, n
= 0;
423 _cleanup_free_
char *hostname
= NULL
, *identifier
= NULL
, *comm
= NULL
, *pid
= NULL
, *fake_pid
= NULL
,
424 *message
= NULL
, *realtime
= NULL
, *monotonic
= NULL
, *priority
= NULL
, *transport
= NULL
,
425 *config_file
= NULL
, *unit
= NULL
, *user_unit
= NULL
, *documentation_url
= NULL
;
426 size_t hostname_len
= 0, identifier_len
= 0, comm_len
= 0, pid_len
= 0, fake_pid_len
= 0, message_len
= 0,
427 realtime_len
= 0, monotonic_len
= 0, priority_len
= 0, transport_len
= 0, config_file_len
= 0,
428 unit_len
= 0, user_unit_len
= 0, documentation_url_len
= 0;
430 bool ellipsized
= false, audit
;
431 const ParseFieldVec fields
[] = {
432 PARSE_FIELD_VEC_ENTRY("_PID=", &pid
, &pid_len
),
433 PARSE_FIELD_VEC_ENTRY("_COMM=", &comm
, &comm_len
),
434 PARSE_FIELD_VEC_ENTRY("MESSAGE=", &message
, &message_len
),
435 PARSE_FIELD_VEC_ENTRY("PRIORITY=", &priority
, &priority_len
),
436 PARSE_FIELD_VEC_ENTRY("_TRANSPORT=", &transport
, &transport_len
),
437 PARSE_FIELD_VEC_ENTRY("_HOSTNAME=", &hostname
, &hostname_len
),
438 PARSE_FIELD_VEC_ENTRY("SYSLOG_PID=", &fake_pid
, &fake_pid_len
),
439 PARSE_FIELD_VEC_ENTRY("SYSLOG_IDENTIFIER=", &identifier
, &identifier_len
),
440 PARSE_FIELD_VEC_ENTRY("_SOURCE_REALTIME_TIMESTAMP=", &realtime
, &realtime_len
),
441 PARSE_FIELD_VEC_ENTRY("_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic
, &monotonic_len
),
442 PARSE_FIELD_VEC_ENTRY("CONFIG_FILE=", &config_file
, &config_file_len
),
443 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_UNIT=", &unit
, &unit_len
),
444 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_USER_UNIT=", &user_unit
, &user_unit_len
),
445 PARSE_FIELD_VEC_ENTRY("DOCUMENTATION=", &documentation_url
, &documentation_url_len
),
447 size_t highlight_shifted
[] = {highlight
? highlight
[0] : 0, highlight
? highlight
[1] : 0};
452 /* Set the threshold to one bigger than the actual print
453 * threshold, so that if the line is actually longer than what
454 * we're willing to print, ellipsization will occur. This way
455 * we won't output a misleading line without any indication of
458 sd_journal_set_data_threshold(j
, flags
& (OUTPUT_SHOW_ALL
|OUTPUT_FULL_WIDTH
) ? 0 : PRINT_CHAR_THRESHOLD
+ 1);
460 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
461 r
= parse_fieldv(data
, length
, fields
, ELEMENTSOF(fields
));
466 log_debug_errno(r
, "Skipping message we can't read: %m");
470 return log_error_errno(r
, "Failed to get journal fields: %m");
473 log_debug("Skipping message without MESSAGE= field.");
477 if (!(flags
& OUTPUT_SHOW_ALL
))
478 strip_tab_ansi(&message
, &message_len
, highlight_shifted
);
480 if (priority_len
== 1 && *priority
>= '0' && *priority
<= '7')
483 audit
= streq_ptr(transport
, "audit");
485 if (mode
== OUTPUT_SHORT_MONOTONIC
)
486 r
= output_timestamp_monotonic(f
, j
, monotonic
);
488 r
= output_timestamp_realtime(f
, j
, mode
, flags
, realtime
);
493 if (flags
& OUTPUT_NO_HOSTNAME
) {
494 /* Suppress display of the hostname if this is requested. */
495 hostname
= mfree(hostname
);
499 if (hostname
&& shall_print(hostname
, hostname_len
, flags
)) {
500 fprintf(f
, " %.*s", (int) hostname_len
, hostname
);
501 n
+= hostname_len
+ 1;
504 if (mode
== OUTPUT_WITH_UNIT
&& ((unit
&& shall_print(unit
, unit_len
, flags
)) ||
505 (user_unit
&& shall_print(user_unit
, user_unit_len
, flags
)))) {
507 fprintf(f
, " %.*s", (int) unit_len
, unit
);
512 fprintf(f
, "/%.*s", (int) user_unit_len
, user_unit
);
514 fprintf(f
, " %.*s", (int) user_unit_len
, user_unit
);
517 } else if (identifier
&& shall_print(identifier
, identifier_len
, flags
)) {
518 fprintf(f
, " %.*s", (int) identifier_len
, identifier
);
519 n
+= identifier_len
+ 1;
520 } else if (comm
&& shall_print(comm
, comm_len
, flags
)) {
521 fprintf(f
, " %.*s", (int) comm_len
, comm
);
524 fputs(" unknown", f
);
526 if (pid
&& shall_print(pid
, pid_len
, flags
)) {
527 fprintf(f
, "[%.*s]", (int) pid_len
, pid
);
529 } else if (fake_pid
&& shall_print(fake_pid
, fake_pid_len
, flags
)) {
530 fprintf(f
, "[%.*s]", (int) fake_pid_len
, fake_pid
);
531 n
+= fake_pid_len
+ 2;
536 if (urlify_enabled()) {
537 _cleanup_free_
char *c
= NULL
;
539 /* Insert a hyperlink to a documentation URL before the message. Note that we don't make the
540 * whole message a hyperlink, since otherwise the whole screen might end up being just
541 * hyperlinks. Moreover, we want to be able to highlight parts of the message (such as the
542 * config file, see below) hence let's keep the documentation URL link separate. */
544 if (documentation_url
&& shall_print(documentation_url
, documentation_url_len
, flags
)) {
545 c
= strndup(documentation_url
, documentation_url_len
);
549 if (!documentation_url_is_valid(c
)) /* Eat up invalid links */
554 (void) url_from_catalog(j
, &c
); /* Acquire from catalog if not embedded in log message itself */
557 _cleanup_free_
char *urlified
= NULL
;
559 if (terminal_urlify(c
, special_glyph(SPECIAL_GLYPH_EXTERNAL_LINK
), &urlified
) >= 0) {
566 if (!(flags
& OUTPUT_SHOW_ALL
) && !utf8_is_printable(message
, message_len
)) {
567 char bytes
[FORMAT_BYTES_MAX
];
568 fprintf(f
, "[%s blob data]\n", format_bytes(bytes
, sizeof(bytes
), message_len
));
571 /* URLify config_file string in message, if the message starts with it.
572 * Skip URLification if the highlighted pattern overlaps. */
574 message_len
>= config_file_len
&&
575 memcmp(message
, config_file
, config_file_len
) == 0 &&
576 IN_SET(message
[config_file_len
], ':', ' ', '\0') &&
577 (!highlight
|| highlight_shifted
[0] == 0 || highlight_shifted
[0] > config_file_len
)) {
579 _cleanup_free_
char *t
= NULL
, *urlified
= NULL
;
581 t
= strndup(config_file
, config_file_len
);
582 if (t
&& terminal_urlify_path(t
, NULL
, &urlified
) >= 0) {
583 size_t shift
= strlen(urlified
) - config_file_len
;
586 joined
= strjoin(urlified
, message
+ config_file_len
);
588 free_and_replace(message
, joined
);
589 message_len
+= shift
;
591 highlight_shifted
[0] += shift
;
592 highlight_shifted
[1] += shift
;
599 print_multiline(f
, n
+ 2, n_columns
, flags
, p
, audit
,
600 message
, message_len
,
604 if (flags
& OUTPUT_CATALOG
)
605 (void) print_catalog(f
, j
);
610 static int output_verbose(
616 const Set
*output_fields
,
617 const size_t highlight
[2]) {
621 _cleanup_free_
char *cursor
= NULL
;
622 uint64_t realtime
= 0;
623 char ts
[FORMAT_TIMESTAMP_MAX
+ 7];
624 const char *timestamp
;
630 sd_journal_set_data_threshold(j
, 0);
632 r
= sd_journal_get_data(j
, "_SOURCE_REALTIME_TIMESTAMP", &data
, &length
);
634 log_debug("Source realtime timestamp not found");
636 return log_full_errno(r
== -EADDRNOTAVAIL
? LOG_DEBUG
: LOG_ERR
, r
, "Failed to get source realtime timestamp: %m");
638 _cleanup_free_
char *value
= NULL
;
640 r
= parse_field(data
, length
, "_SOURCE_REALTIME_TIMESTAMP=",
641 STRLEN("_SOURCE_REALTIME_TIMESTAMP="), &value
,
647 r
= safe_atou64(value
, &realtime
);
649 log_debug_errno(r
, "Failed to parse realtime timestamp: %m");
653 r
= sd_journal_get_realtime_usec(j
, &realtime
);
655 return log_full_errno(r
== -EADDRNOTAVAIL
? LOG_DEBUG
: LOG_ERR
, r
, "Failed to get realtime timestamp: %m");
658 r
= sd_journal_get_cursor(j
, &cursor
);
660 return log_error_errno(r
, "Failed to get cursor: %m");
662 timestamp
= flags
& OUTPUT_UTC
? format_timestamp_us_utc(ts
, sizeof ts
, realtime
)
663 : format_timestamp_us(ts
, sizeof ts
, realtime
);
664 fprintf(f
, "%s [%s]\n",
665 timestamp
?: "(no timestamp)",
668 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
671 const char *on
= "", *off
= "";
672 _cleanup_free_
char *urlified
= NULL
;
675 c
= memchr(data
, '=', length
);
677 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
679 fieldlen
= c
- (const char*) data
;
681 r
= field_set_test(output_fields
, data
, fieldlen
);
687 valuelen
= length
- 1 - fieldlen
;
689 if ((flags
& OUTPUT_COLOR
) && (p
= startswith(data
, "MESSAGE="))) {
692 } else if ((p
= startswith(data
, "CONFIG_FILE="))) {
693 if (terminal_urlify_path(p
, NULL
, &urlified
) >= 0) {
695 valuelen
= strlen(urlified
);
700 if ((flags
& OUTPUT_SHOW_ALL
) ||
701 (((length
< PRINT_CHAR_THRESHOLD
) || flags
& OUTPUT_FULL_WIDTH
)
702 && utf8_is_printable(data
, length
))) {
703 fprintf(f
, " %s%.*s=", on
, fieldlen
, (const char*)data
);
704 print_multiline(f
, 4 + fieldlen
+ 1, 0, OUTPUT_FULL_WIDTH
, 0, false,
709 char bytes
[FORMAT_BYTES_MAX
];
711 fprintf(f
, " %s%.*s=[%s blob data]%s\n",
713 (int) (c
- (const char*) data
),
715 format_bytes(bytes
, sizeof(bytes
), length
- (c
- (const char *) data
) - 1),
723 if (flags
& OUTPUT_CATALOG
)
724 (void) print_catalog(f
, j
);
729 static int output_export(
735 const Set
*output_fields
,
736 const size_t highlight
[2]) {
739 char sid
[SD_ID128_STRING_MAX
];
741 usec_t realtime
, monotonic
;
742 _cleanup_free_
char *cursor
= NULL
;
748 sd_journal_set_data_threshold(j
, 0);
750 r
= sd_journal_get_realtime_usec(j
, &realtime
);
752 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
754 r
= sd_journal_get_monotonic_usec(j
, &monotonic
, &boot_id
);
756 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
758 r
= sd_journal_get_cursor(j
, &cursor
);
760 return log_error_errno(r
, "Failed to get cursor: %m");
764 "__REALTIME_TIMESTAMP="USEC_FMT
"\n"
765 "__MONOTONIC_TIMESTAMP="USEC_FMT
"\n"
770 sd_id128_to_string(boot_id
, sid
));
772 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
775 /* We already printed the boot id from the data in the header, hence let's suppress it here */
776 if (memory_startswith(data
, length
, "_BOOT_ID="))
779 c
= memchr(data
, '=', length
);
781 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
784 r
= field_set_test(output_fields
, data
, c
- (const char *) data
);
790 if (utf8_is_printable_newline(data
, length
, false))
791 fwrite(data
, length
, 1, f
);
795 fwrite(data
, c
- (const char*) data
, 1, f
);
797 le64
= htole64(length
- (c
- (const char*) data
) - 1);
798 fwrite(&le64
, sizeof(le64
), 1, f
);
799 fwrite(c
+ 1, length
- (c
- (const char*) data
) - 1, 1, f
);
805 log_debug_errno(r
, "Skipping message we can't read: %m");
826 if (!(flags
& OUTPUT_SHOW_ALL
) && l
>= JSON_THRESHOLD
)
829 else if (!(flags
& OUTPUT_SHOW_ALL
) && !utf8_is_printable(p
, l
)) {
830 bool not_first
= false;
836 fprintf(f
, ", %u", (uint8_t) *p
);
839 fprintf(f
, "%u", (uint8_t) *p
);
851 if (IN_SET(*p
, '"', '\\')) {
854 } else if (*p
== '\n')
856 else if ((uint8_t) *p
< ' ')
857 fprintf(f
, "\\u%04x", (uint8_t) *p
);
872 JsonVariant
* values
[];
875 static int update_json_data(
882 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
886 if (!(flags
& OUTPUT_SHOW_ALL
) && strlen(name
) + 1 + size
>= JSON_THRESHOLD
)
887 r
= json_variant_new_null(&v
);
888 else if (utf8_is_printable(value
, size
))
889 r
= json_variant_new_stringn(&v
, value
, size
);
891 r
= json_variant_new_array_bytes(&v
, value
, size
);
893 return log_error_errno(r
, "Failed to allocate JSON data: %m");
895 d
= hashmap_get(h
, name
);
899 w
= realloc(d
, offsetof(struct json_data
, values
) + sizeof(JsonVariant
*) * (d
->n_values
+ 1));
904 assert_se(hashmap_update(h
, json_variant_string(d
->name
), d
) >= 0);
906 _cleanup_(json_variant_unrefp
) JsonVariant
*n
= NULL
;
908 r
= json_variant_new_string(&n
, name
);
910 return log_error_errno(r
, "Failed to allocate JSON name variant: %m");
912 d
= malloc0(offsetof(struct json_data
, values
) + sizeof(JsonVariant
*));
916 r
= hashmap_put(h
, json_variant_string(n
), d
);
919 return log_error_errno(r
, "Failed to insert JSON name into hashmap: %m");
922 d
->name
= TAKE_PTR(n
);
925 d
->values
[d
->n_values
++] = TAKE_PTR(v
);
929 static int update_json_data_split(
932 const Set
*output_fields
,
940 assert(data
|| size
== 0);
942 if (memory_startswith(data
, size
, "_BOOT_ID="))
945 eq
= memchr(data
, '=', MIN(size
, JSON_THRESHOLD
));
952 name
= strndupa(data
, eq
- (const char*) data
);
953 if (output_fields
&& !set_contains(output_fields
, name
))
956 return update_json_data(h
, flags
, name
, eq
+ 1, size
- (eq
- (const char*) data
) - 1);
959 static int output_json(
965 const Set
*output_fields
,
966 const size_t highlight
[2]) {
968 char sid
[SD_ID128_STRING_MAX
], usecbuf
[DECIMAL_STR_MAX(usec_t
)];
969 _cleanup_(json_variant_unrefp
) JsonVariant
*object
= NULL
;
970 _cleanup_free_
char *cursor
= NULL
;
971 uint64_t realtime
, monotonic
;
972 JsonVariant
**array
= NULL
;
982 (void) sd_journal_set_data_threshold(j
, flags
& OUTPUT_SHOW_ALL
? 0 : JSON_THRESHOLD
);
984 r
= sd_journal_get_realtime_usec(j
, &realtime
);
986 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
988 r
= sd_journal_get_monotonic_usec(j
, &monotonic
, &boot_id
);
990 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
992 r
= sd_journal_get_cursor(j
, &cursor
);
994 return log_error_errno(r
, "Failed to get cursor: %m");
996 h
= hashmap_new(&string_hash_ops
);
1000 r
= update_json_data(h
, flags
, "__CURSOR", cursor
, strlen(cursor
));
1004 xsprintf(usecbuf
, USEC_FMT
, realtime
);
1005 r
= update_json_data(h
, flags
, "__REALTIME_TIMESTAMP", usecbuf
, strlen(usecbuf
));
1009 xsprintf(usecbuf
, USEC_FMT
, monotonic
);
1010 r
= update_json_data(h
, flags
, "__MONOTONIC_TIMESTAMP", usecbuf
, strlen(usecbuf
));
1014 sd_id128_to_string(boot_id
, sid
);
1015 r
= update_json_data(h
, flags
, "_BOOT_ID", sid
, strlen(sid
));
1023 r
= sd_journal_enumerate_data(j
, &data
, &size
);
1024 if (r
== -EBADMSG
) {
1025 log_debug_errno(r
, "Skipping message we can't read: %m");
1030 log_error_errno(r
, "Failed to read journal: %m");
1036 r
= update_json_data_split(h
, flags
, output_fields
, data
, size
);
1041 array
= new(JsonVariant
*, hashmap_size(h
)*2);
1047 HASHMAP_FOREACH(d
, h
, i
) {
1048 assert(d
->n_values
> 0);
1050 array
[n
++] = json_variant_ref(d
->name
);
1052 if (d
->n_values
== 1)
1053 array
[n
++] = json_variant_ref(d
->values
[0]);
1055 _cleanup_(json_variant_unrefp
) JsonVariant
*q
= NULL
;
1057 r
= json_variant_new_array(&q
, d
->values
, d
->n_values
);
1059 log_error_errno(r
, "Failed to create JSON array: %m");
1063 array
[n
++] = TAKE_PTR(q
);
1067 r
= json_variant_new_object(&object
, array
, n
);
1069 log_error_errno(r
, "Failed to allocate JSON object: %m");
1073 json_variant_dump(object
,
1074 output_mode_to_json_format_flags(mode
) |
1075 (FLAGS_SET(flags
, OUTPUT_COLOR
) ? JSON_FORMAT_COLOR
: 0),
1081 while ((d
= hashmap_steal_first(h
))) {
1084 json_variant_unref(d
->name
);
1085 for (k
= 0; k
< d
->n_values
; k
++)
1086 json_variant_unref(d
->values
[k
]);
1093 json_variant_unref_many(array
, n
);
1099 static int output_cat_field(
1104 const size_t highlight
[2]) {
1106 const char *highlight_on
, *highlight_off
;
1111 if (FLAGS_SET(flags
, OUTPUT_COLOR
)) {
1112 highlight_on
= ANSI_HIGHLIGHT_RED
;
1113 highlight_off
= ANSI_NORMAL
;
1115 highlight_on
= highlight_off
= "";
1117 r
= sd_journal_get_data(j
, field
, &data
, &l
);
1118 if (r
== -EBADMSG
) {
1119 log_debug_errno(r
, "Skipping message we can't read: %m");
1122 if (r
== -ENOENT
) /* An entry without the requested field */
1125 return log_error_errno(r
, "Failed to get data: %m");
1128 assert(l
>= fl
+ 1);
1129 assert(((char*) data
)[fl
] == '=');
1131 data
= (const uint8_t*) data
+ fl
+ 1;
1134 if (highlight
&& FLAGS_SET(flags
, OUTPUT_COLOR
)) {
1135 assert(highlight
[0] <= highlight
[1]);
1136 assert(highlight
[1] <= l
);
1138 fwrite((const char*) data
, 1, highlight
[0], f
);
1139 fwrite(highlight_on
, 1, strlen(highlight_on
), f
);
1140 fwrite((const char*) data
+ highlight
[0], 1, highlight
[1] - highlight
[0], f
);
1141 fwrite(highlight_off
, 1, strlen(highlight_off
), f
);
1142 fwrite((const char*) data
+ highlight
[1], 1, l
- highlight
[1], f
);
1144 fwrite((const char*) data
, 1, l
, f
);
1150 static int output_cat(
1156 const Set
*output_fields
,
1157 const size_t highlight
[2]) {
1166 (void) sd_journal_set_data_threshold(j
, 0);
1168 if (set_isempty(output_fields
))
1169 return output_cat_field(f
, j
, flags
, "MESSAGE", highlight
);
1171 SET_FOREACH(field
, output_fields
, iterator
) {
1172 r
= output_cat_field(f
, j
, flags
, field
, streq(field
, "MESSAGE") ? highlight
: NULL
);
1180 static int (*output_funcs
[_OUTPUT_MODE_MAX
])(
1186 const Set
*output_fields
,
1187 const size_t highlight
[2]) = {
1189 [OUTPUT_SHORT
] = output_short
,
1190 [OUTPUT_SHORT_ISO
] = output_short
,
1191 [OUTPUT_SHORT_ISO_PRECISE
] = output_short
,
1192 [OUTPUT_SHORT_PRECISE
] = output_short
,
1193 [OUTPUT_SHORT_MONOTONIC
] = output_short
,
1194 [OUTPUT_SHORT_UNIX
] = output_short
,
1195 [OUTPUT_SHORT_FULL
] = output_short
,
1196 [OUTPUT_VERBOSE
] = output_verbose
,
1197 [OUTPUT_EXPORT
] = output_export
,
1198 [OUTPUT_JSON
] = output_json
,
1199 [OUTPUT_JSON_PRETTY
] = output_json
,
1200 [OUTPUT_JSON_SSE
] = output_json
,
1201 [OUTPUT_JSON_SEQ
] = output_json
,
1202 [OUTPUT_CAT
] = output_cat
,
1203 [OUTPUT_WITH_UNIT
] = output_short
,
1206 int show_journal_entry(
1212 char **output_fields
,
1213 const size_t highlight
[2],
1216 _cleanup_set_free_ Set
*fields
= NULL
;
1220 assert(mode
< _OUTPUT_MODE_MAX
);
1223 n_columns
= columns();
1225 r
= set_put_strdupv(&fields
, output_fields
);
1229 r
= output_funcs
[mode
](f
, j
, mode
, n_columns
, flags
, fields
, highlight
);
1231 if (ellipsized
&& r
> 0)
1237 static int maybe_print_begin_newline(FILE *f
, OutputFlags
*flags
) {
1241 if (!(*flags
& OUTPUT_BEGIN_NEWLINE
))
1244 /* Print a beginning new line if that's request, but only once
1245 * on the first line we print. */
1248 *flags
&= ~OUTPUT_BEGIN_NEWLINE
;
1264 bool need_seek
= false;
1265 int warn_cutoff
= flags
& OUTPUT_WARN_CUTOFF
;
1269 assert(mode
< _OUTPUT_MODE_MAX
);
1271 if (how_many
== (unsigned) -1)
1275 r
= sd_journal_seek_tail(j
);
1277 return log_error_errno(r
, "Failed to seek to tail: %m");
1279 r
= sd_journal_previous_skip(j
, how_many
);
1281 return log_error_errno(r
, "Failed to skip previous: %m");
1288 r
= sd_journal_next(j
);
1290 return log_error_errno(r
, "Failed to iterate through journal: %m");
1298 if (not_before
> 0) {
1299 r
= sd_journal_get_monotonic_usec(j
, &usec
, NULL
);
1301 /* -ESTALE is returned if the timestamp is not from this boot */
1305 return log_error_errno(r
, "Failed to get journal time: %m");
1307 if (usec
< not_before
)
1312 maybe_print_begin_newline(f
, &flags
);
1314 r
= show_journal_entry(f
, j
, mode
, n_columns
, flags
, NULL
, NULL
, ellipsized
);
1319 if (warn_cutoff
&& line
< how_many
&& not_before
> 0) {
1323 /* Check whether the cutoff line is too early */
1325 r
= sd_id128_get_boot(&boot_id
);
1327 return log_error_errno(r
, "Failed to get boot id: %m");
1329 r
= sd_journal_get_cutoff_monotonic_usec(j
, boot_id
, &cutoff
, NULL
);
1331 return log_error_errno(r
, "Failed to get journal cutoff time: %m");
1333 if (r
> 0 && not_before
< cutoff
) {
1334 maybe_print_begin_newline(f
, &flags
);
1336 /* If we logged *something* and no permission error happened, than we can reliably
1337 * emit the warning about rotation. If we didn't log anything and access errors
1338 * happened, emit hint about permissions. Otherwise, give a generic message, since we
1339 * can't diagnose the issue. */
1341 bool noaccess
= journal_access_blocked(j
);
1343 if (line
== 0 && noaccess
)
1344 fprintf(f
, "Warning: some journal files were not opened due to insufficient permissions.");
1346 fprintf(f
, "Warning: journal has been rotated since unit was started, output may be incomplete.\n");
1348 fprintf(f
, "Warning: journal has been rotated since unit was started and some journal "
1349 "files were not opened due to insufficient permissions, output may be incomplete.\n");
1352 warn_cutoff
= false;
1358 int add_matches_for_unit(sd_journal
*j
, const char *unit
) {
1359 const char *m1
, *m2
, *m3
, *m4
;
1365 m1
= strjoina("_SYSTEMD_UNIT=", unit
);
1366 m2
= strjoina("COREDUMP_UNIT=", unit
);
1367 m3
= strjoina("UNIT=", unit
);
1368 m4
= strjoina("OBJECT_SYSTEMD_UNIT=", unit
);
1371 /* Look for messages from the service itself */
1372 (r
= sd_journal_add_match(j
, m1
, 0)) ||
1374 /* Look for coredumps of the service */
1375 (r
= sd_journal_add_disjunction(j
)) ||
1376 (r
= sd_journal_add_match(j
, "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1", 0)) ||
1377 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1378 (r
= sd_journal_add_match(j
, m2
, 0)) ||
1380 /* Look for messages from PID 1 about this service */
1381 (r
= sd_journal_add_disjunction(j
)) ||
1382 (r
= sd_journal_add_match(j
, "_PID=1", 0)) ||
1383 (r
= sd_journal_add_match(j
, m3
, 0)) ||
1385 /* Look for messages from authorized daemons about this service */
1386 (r
= sd_journal_add_disjunction(j
)) ||
1387 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1388 (r
= sd_journal_add_match(j
, m4
, 0))
1391 if (r
== 0 && endswith(unit
, ".slice")) {
1394 m5
= strjoina("_SYSTEMD_SLICE=", unit
);
1396 /* Show all messages belonging to a slice */
1398 (r
= sd_journal_add_disjunction(j
)) ||
1399 (r
= sd_journal_add_match(j
, m5
, 0))
1406 int add_matches_for_user_unit(sd_journal
*j
, const char *unit
, uid_t uid
) {
1408 char *m1
, *m2
, *m3
, *m4
;
1409 char muid
[sizeof("_UID=") + DECIMAL_STR_MAX(uid_t
)];
1414 m1
= strjoina("_SYSTEMD_USER_UNIT=", unit
);
1415 m2
= strjoina("USER_UNIT=", unit
);
1416 m3
= strjoina("COREDUMP_USER_UNIT=", unit
);
1417 m4
= strjoina("OBJECT_SYSTEMD_USER_UNIT=", unit
);
1418 sprintf(muid
, "_UID="UID_FMT
, uid
);
1421 /* Look for messages from the user service itself */
1422 (r
= sd_journal_add_match(j
, m1
, 0)) ||
1423 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1425 /* Look for messages from systemd about this service */
1426 (r
= sd_journal_add_disjunction(j
)) ||
1427 (r
= sd_journal_add_match(j
, m2
, 0)) ||
1428 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1430 /* Look for coredumps of the service */
1431 (r
= sd_journal_add_disjunction(j
)) ||
1432 (r
= sd_journal_add_match(j
, m3
, 0)) ||
1433 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1434 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1436 /* Look for messages from authorized daemons about this service */
1437 (r
= sd_journal_add_disjunction(j
)) ||
1438 (r
= sd_journal_add_match(j
, m4
, 0)) ||
1439 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1440 (r
= sd_journal_add_match(j
, "_UID=0", 0))
1443 if (r
== 0 && endswith(unit
, ".slice")) {
1446 m5
= strjoina("_SYSTEMD_SLICE=", unit
);
1448 /* Show all messages belonging to a slice */
1450 (r
= sd_journal_add_disjunction(j
)) ||
1451 (r
= sd_journal_add_match(j
, m5
, 0)) ||
1452 (r
= sd_journal_add_match(j
, muid
, 0))
1459 static int get_boot_id_for_machine(const char *machine
, sd_id128_t
*boot_id
) {
1460 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1461 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, rootfd
= -1;
1462 char buf
[ID128_UUID_STRING_MAX
];
1470 if (!machine_name_is_valid(machine
))
1473 r
= container_get_leader(machine
, &pid
);
1477 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, NULL
, &rootfd
);
1481 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1484 r
= namespace_fork("(sd-bootidns)", "(sd-bootid)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1485 pidnsfd
, mntnsfd
, -1, -1, rootfd
, &child
);
1491 pair
[0] = safe_close(pair
[0]);
1493 fd
= open("/proc/sys/kernel/random/boot_id", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1495 _exit(EXIT_FAILURE
);
1497 r
= loop_read_exact(fd
, buf
, 36, false);
1500 _exit(EXIT_FAILURE
);
1502 k
= send(pair
[1], buf
, 36, MSG_NOSIGNAL
);
1504 _exit(EXIT_FAILURE
);
1506 _exit(EXIT_SUCCESS
);
1509 pair
[1] = safe_close(pair
[1]);
1511 r
= wait_for_terminate_and_check("(sd-bootidns)", child
, 0);
1514 if (r
!= EXIT_SUCCESS
)
1517 k
= recv(pair
[0], buf
, 36, 0);
1522 r
= sd_id128_from_string(buf
, boot_id
);
1529 int add_match_this_boot(sd_journal
*j
, const char *machine
) {
1530 char match
[9+32+1] = "_BOOT_ID=";
1537 r
= get_boot_id_for_machine(machine
, &boot_id
);
1539 return log_error_errno(r
, "Failed to get boot id of container %s: %m", machine
);
1541 r
= sd_id128_get_boot(&boot_id
);
1543 return log_error_errno(r
, "Failed to get boot id: %m");
1546 sd_id128_to_string(boot_id
, match
+ 9);
1547 r
= sd_journal_add_match(j
, match
, strlen(match
));
1549 return log_error_errno(r
, "Failed to add match: %m");
1551 r
= sd_journal_add_conjunction(j
);
1553 return log_error_errno(r
, "Failed to add conjunction: %m");
1558 int show_journal_by_unit(
1561 const char *log_namespace
,
1568 int journal_open_flags
,
1572 _cleanup_(sd_journal_closep
) sd_journal
*j
= NULL
;
1576 assert(mode
< _OUTPUT_MODE_MAX
);
1582 r
= sd_journal_open_namespace(&j
, log_namespace
, journal_open_flags
| SD_JOURNAL_INCLUDE_DEFAULT_NAMESPACE
);
1584 return log_error_errno(r
, "Failed to open journal: %m");
1586 r
= add_match_this_boot(j
, NULL
);
1591 r
= add_matches_for_unit(j
, unit
);
1593 r
= add_matches_for_user_unit(j
, unit
, uid
);
1595 return log_error_errno(r
, "Failed to add unit matches: %m");
1597 if (DEBUG_LOGGING
) {
1598 _cleanup_free_
char *filter
;
1600 filter
= journal_make_match_string(j
);
1604 log_debug("Journal filter: %s", filter
);
1607 return show_journal(f
, j
, mode
, n_columns
, not_before
, how_many
, flags
, ellipsized
);