HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/logs-show.c

87,278 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 513d76558e31319a9b649382f7cde8d9726f9564

Lines 1001–2000 of 2,347

                if (r < 0)
                        return r;
                if (!r)
                        continue;
 
                if (utf8_is_printable_newline(data, length, false))
                        fwrite(data, length, 1, f);
                else {
                        uint64_t le64;
 
                        fwrite(data, fieldlen, 1, f);
                        fputc('\n', f);
                        le64 = htole64(length - fieldlen - 1);
                        fwrite(&le64, sizeof(le64), 1, f);
                        fwrite(c + 1, length - fieldlen - 1, 1, f);
                }
 
                fputc('\n', f);
        }
        if (IN_SET(r, -EADDRNOTAVAIL, -EBADMSG)) {
                log_debug_errno(r, "Skipping message we can't read: %m");
                return 0;
        }
 
        if (r < 0)
                return r;
 
        fputc('\n', f);
 
        return 0;
}
 
void json_escape(
                FILE *f,
                const char* p,
                size_t l,
                OutputFlags flags) {
 
        assert(f);
        assert(p);
 
        if (((flags & OUTPUT_SKIP_UNPRINTABLE) && !utf8_is_printable(p, l)) ||
            (!(flags & OUTPUT_SHOW_ALL) && l >= JSON_THRESHOLD))
                fputs("null", f);
 
        else if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(p, l)) {
                bool not_first = false;
 
                fputs("[ ", f);
 
                while (l > 0) {
                        if (not_first)
                                fprintf(f, ", %u", (uint8_t) *p);
                        else {
                                not_first = true;
                                fprintf(f, "%u", (uint8_t) *p);
                        }
 
                        p++;
                        l--;
                }
 
                fputs(" ]", f);
        } else {
                fputc('"', f);
 
                while (l > 0) {
                        if (IN_SET(*p, '"', '\\')) {
                                fputc('\\', f);
                                fputc(*p, f);
                        } else if (*p == '\n')
                                fputs("\\n", f);
                        else if ((uint8_t) *p < ' ')
                                fprintf(f, "\\u%04x", (uint8_t) *p);
                        else
                                fputc(*p, f);
 
                        p++;
                        l--;
                }
 
                fputc('"', f);
        }
}
 
typedef struct JsonData {
        sd_json_variant* name;
        sd_json_variant* values;
} JsonData;
 
static JsonData* json_data_free(JsonData *d) {
        if (!d)
                return NULL;
 
        sd_json_variant_unref(d->name);
        sd_json_variant_unref(d->values);
 
        return mfree(d);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(JsonData*, json_data_free);
 
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(json_data_hash_ops_free,
                                              char, string_hash_func, string_compare_func,
                                              JsonData, json_data_free);
 
static int update_json_data(
                Hashmap *h,
                OutputFlags flags,
                const char *name,
                const void *value,
                size_t size) {
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        JsonData *d;
        int r;
 
        assert(name);
        assert(value);
 
        if (size == SIZE_MAX)
                size = strlen(value);
 
        if (!(flags & OUTPUT_SHOW_ALL) && strlen(name) + 1 + size >= JSON_THRESHOLD)
                r = sd_json_variant_new_null(&v);
        else if (utf8_is_printable(value, size))
                r = sd_json_variant_new_stringn(&v, value, size);
        else if (flags & OUTPUT_SKIP_UNPRINTABLE)
                r = sd_json_variant_new_null(&v);
        else
                r = sd_json_variant_new_array_bytes(&v, value, size);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate JSON data: %m");
 
        d = hashmap_get(h, name);
        if (d) {
                r = sd_json_variant_append_array(&d->values, v);
                if (r < 0)
                        return log_error_errno(r, "Failed to append JSON value into array: %m");
        } else {
                _cleanup_(json_data_freep) JsonData *e = NULL;
 
                e = new0(JsonData, 1);
                if (!e)
                        return log_oom();
 
                r = sd_json_variant_new_string(&e->name, name);
                if (r < 0)
                        return log_error_errno(r, "Failed to allocate JSON name variant: %m");
 
                r = sd_json_variant_append_array(&e->values, v);
                if (r < 0)
                        return log_error_errno(r, "Failed to create JSON value array: %m");
 
                r = hashmap_put(h, sd_json_variant_string(e->name), e);
                if (r < 0)
                        return log_error_errno(r, "Failed to insert JSON data into hashmap: %m");
 
                TAKE_PTR(e);
        }
 
        return 0;
}
 
static int update_json_data_split(
                Hashmap *h,
                OutputFlags flags,
                const Set *output_fields,
                const void *data,
                size_t size) {
 
        size_t fieldlen;
        const char *eq;
        char *name;
 
        assert(h);
        assert(data || size == 0);
 
        if (memory_startswith(data, size, "_BOOT_ID="))
                return 0;
 
        eq = memchr(data, '=', MIN(size, JSON_THRESHOLD));
        if (!eq)
                return 0;
 
        fieldlen = eq - (const char*) data;
        if (!journal_field_valid(data, fieldlen, /* allow_protected= */ true)) {
                log_debug("Encountered invalid field, assuming bad or incompletely written field, leaving.");
                return 0;
        }
 
        name = strndupa_safe(data, fieldlen);
        if (output_fields && !set_contains(output_fields, name))
                return 0;
 
        return update_json_data(h, flags, name, eq + 1, size - fieldlen - 1);
}
 
int journal_entry_to_json(
                sd_journal *j,
                OutputFlags flags,
                const Set *output_fields,
                sd_json_variant **ret) {
 
        char usecbuf[CONST_MAX(DECIMAL_STR_MAX(usec_t), DECIMAL_STR_MAX(uint64_t))];
        sd_id128_t journal_boot_id, seqnum_id;
        _cleanup_free_ char *cursor = NULL;
        usec_t realtime, monotonic;
        uint64_t seqnum;
        const char *corrupted_what = NULL;
        _cleanup_hashmap_free_ Hashmap *h = NULL;
        _cleanup_free_ sd_json_variant **array = NULL;
        size_t n = 0;
        int r;
 
        assert(j);
        assert(ret);
 
        (void) sd_journal_set_data_threshold(j, flags & OUTPUT_SHOW_ALL ? 0 : JSON_THRESHOLD);
 
        r = sd_journal_get_cursor(j, &cursor);
        if (IN_SET(r, -EBADMSG, -EADDRNOTAVAIL)) {
                corrupted_what = "cursor";
                goto corrupted_skip;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to get cursor: %m");
 
        r = sd_journal_get_realtime_usec(j, &realtime);
        if (r == -EBADMSG) {
                corrupted_what = "realtime timestamp";
                goto corrupted_skip;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to get realtime timestamp: %m");
 
        r = sd_journal_get_monotonic_usec(j, &monotonic, &journal_boot_id);
        if (r == -EBADMSG) {
                corrupted_what = "monotonic timestamp";
                goto corrupted_skip;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to get monotonic timestamp: %m");
 
        r = sd_journal_get_seqnum(j, &seqnum, &seqnum_id);
        if (r == -EBADMSG) {
                corrupted_what = "sequence number";
                goto corrupted_skip;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to get seqnum: %m");
 
        h = hashmap_new(&json_data_hash_ops_free);
        if (!h)
                return log_oom();
 
        r = update_json_data(h, flags, "__CURSOR", cursor, SIZE_MAX);
        if (r < 0)
                return r;
 
        xsprintf(usecbuf, USEC_FMT, realtime);
        r = update_json_data(h, flags, "__REALTIME_TIMESTAMP", usecbuf, SIZE_MAX);
        if (r < 0)
                return r;
 
        xsprintf(usecbuf, USEC_FMT, monotonic);
        r = update_json_data(h, flags, "__MONOTONIC_TIMESTAMP", usecbuf, SIZE_MAX);
        if (r < 0)
                return r;
 
        r = update_json_data(h, flags, "_BOOT_ID", SD_ID128_TO_STRING(journal_boot_id), SIZE_MAX);
        if (r < 0)
                return r;
 
        xsprintf(usecbuf, USEC_FMT, seqnum);
        r = update_json_data(h, flags, "__SEQNUM", usecbuf, SIZE_MAX);
        if (r < 0)
                return r;
 
        r = update_json_data(h, flags, "__SEQNUM_ID", SD_ID128_TO_STRING(seqnum_id), SIZE_MAX);
        if (r < 0)
                return r;
 
        for (;;) {
                const void *data;
                size_t size;
 
                r = sd_journal_enumerate_data(j, &data, &size);
                if (IN_SET(r, -EBADMSG, -EADDRNOTAVAIL)) {
                        log_debug_errno(r, "Skipping message we can't read: %m");
                        return 0;
                }
                if (r < 0)
                        return log_error_errno(r, "Failed to read journal: %m");
                if (r == 0)
                        break;
 
                r = update_json_data_split(h, flags, output_fields, data, size);
                if (r < 0)
                        return r;
        }
 
        array = new(sd_json_variant*, hashmap_size(h) * 2);
        if (!array)
                return log_oom();
 
        JsonData *d;
        HASHMAP_FOREACH(d, h) {
                assert(sd_json_variant_elements(d->values) > 0);
 
                array[n++] = d->name;
 
                if (sd_json_variant_elements(d->values) == 1)
                        array[n++] = sd_json_variant_by_index(d->values, 0);
                else
                        array[n++] = d->values;
        }
 
        r = sd_json_variant_new_object(ret, array, n);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate JSON object: %m");
 
        return 1;
 
corrupted_skip:
        log_debug_errno(r, "Unable to determine %s of entry, assuming bad or partially written entry: %m", ASSERT_PTR(corrupted_what));
        *ret = NULL;
        return 0;
}
 
static int output_json(
                FILE *f,
                sd_journal *j,
                OutputMode mode,
                unsigned n_columns,
                OutputFlags flags,
                const Set *output_fields,
                const size_t highlight[2],
                dual_timestamp *previous_display_ts, /* unused */
                sd_id128_t *previous_boot_id) {      /* unused */
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *object = NULL;
        int r;
 
        r = journal_entry_to_json(j, flags, output_fields, &object);
        if (r <= 0)
                return r;
 
        return sd_json_variant_dump(object,
                                    output_mode_to_json_format_flags(mode) |
                                    (FLAGS_SET(flags, OUTPUT_COLOR) ? SD_JSON_FORMAT_COLOR : 0),
                                    f, NULL);
}
 
static int output_cat_field(
                FILE *f,
                sd_journal *j,
                OutputFlags flags,
                int prio,
                const char *field,
                const size_t highlight[2]) {
 
        const char *color_on = "", *color_off = "", *highlight_on = "";
        const void *data;
        size_t l, fl;
        int r;
 
        if (FLAGS_SET(flags, OUTPUT_COLOR))
                get_log_colors(prio, &color_on, &color_off, &highlight_on);
 
        r = sd_journal_get_data(j, field, &data, &l);
        if (IN_SET(r, -EBADMSG, -EADDRNOTAVAIL)) {
                log_debug_errno(r, "Skipping message we can't read: %m");
                return 0;
        }
        if (r == -ENOENT) /* An entry without the requested field */
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to get data: %m");
 
        fl = strlen(field);
        assert(l >= fl + 1);
        assert(((char*) data)[fl] == '=');
 
        data = (const uint8_t*) data + fl + 1;
        l -= fl + 1;
 
        if (FLAGS_SET(flags, OUTPUT_COLOR)) {
                if (highlight) {
                        assert(highlight[0] <= highlight[1]);
                        assert(highlight[1] <= l);
 
                        fputs(color_on, f);
                        fwrite((const char*) data, 1, highlight[0], f);
                        fputs(highlight_on, f);
                        fwrite((const char*) data + highlight[0], 1, highlight[1] - highlight[0], f);
                        fputs(color_on, f);
                        fwrite((const char*) data + highlight[1], 1, l - highlight[1], f);
                        fputs(color_off, f);
                } else {
                        fputs(color_on, f);
                        fwrite((const char*) data, 1, l, f);
                        fputs(color_off, f);
                }
        } else
                fwrite((const char*) data, 1, l, f);
 
        fputc('\n', f);
        return 0;
}
 
static int output_cat(
                FILE *f,
                sd_journal *j,
                OutputMode mode,
                unsigned n_columns,
                OutputFlags flags,
                const Set *output_fields,
                const size_t highlight[2],
                dual_timestamp *previous_display_ts, /* unused */
                sd_id128_t *previous_boot_id) {      /* unused */
 
        int r, prio = LOG_INFO;
        const char *field;
 
        assert(j);
        assert(f);
 
        (void) sd_journal_set_data_threshold(j, 0);
 
        if (FLAGS_SET(flags, OUTPUT_COLOR)) {
                const void *data;
                size_t l;
 
                /* Determine priority of this entry, so that we can color it nicely */
 
                r = sd_journal_get_data(j, "PRIORITY", &data, &l);
                if (IN_SET(r, -EBADMSG, -EADDRNOTAVAIL)) {
                        log_debug_errno(r, "Skipping message we can't read: %m");
                        return 0;
                }
                if (r < 0) {
                        if (r != -ENOENT)
                                return log_error_errno(r, "Failed to get data: %m");
 
                        /* An entry without PRIORITY */
                } else if (l == 10 && memcmp(data, "PRIORITY=", 9) == 0) {
                        char c = ((char*) data)[9];
 
                        if (c >= '0' && c <= '7')
                                prio = c - '0';
                }
        }
 
        if (set_isempty(output_fields))
                return output_cat_field(f, j, flags, prio, "MESSAGE", highlight);
 
        SET_FOREACH(field, output_fields) {
                r = output_cat_field(f, j, flags, prio, field, streq(field, "MESSAGE") ? highlight : NULL);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
typedef int (*output_func_t)(
                FILE *f,
                sd_journal *j,
                OutputMode mode,
                unsigned n_columns,
                OutputFlags flags,
                const Set *output_fields,
                const size_t highlight[2],
                dual_timestamp *previous_display_ts,
                sd_id128_t *previous_boot_id);
 
static output_func_t output_funcs[_OUTPUT_MODE_MAX] = {
        [OUTPUT_SHORT]             = output_short,
        [OUTPUT_SHORT_ISO]         = output_short,
        [OUTPUT_SHORT_ISO_PRECISE] = output_short,
        [OUTPUT_SHORT_PRECISE]     = output_short,
        [OUTPUT_SHORT_MONOTONIC]   = output_short,
        [OUTPUT_SHORT_DELTA]       = output_short,
        [OUTPUT_SHORT_UNIX]        = output_short,
        [OUTPUT_SHORT_FULL]        = output_short,
        [OUTPUT_VERBOSE]           = output_verbose,
        [OUTPUT_EXPORT]            = output_export,
        [OUTPUT_JSON]              = output_json,
        [OUTPUT_JSON_PRETTY]       = output_json,
        [OUTPUT_JSON_SSE]          = output_json,
        [OUTPUT_JSON_SEQ]          = output_json,
        [OUTPUT_CAT]               = output_cat,
        [OUTPUT_WITH_UNIT]         = output_short,
};
 
int show_journal_entry(
                FILE *f,
                sd_journal *j,
                OutputMode mode,
                unsigned n_columns,
                OutputFlags flags,
                Set *output_fields,
                const size_t highlight[2],
                bool *ellipsized,
                dual_timestamp *previous_display_ts,
                sd_id128_t *previous_boot_id) {
 
        int r;
 
        assert(mode >= 0);
        assert(mode < _OUTPUT_MODE_MAX);
        assert(previous_display_ts);
        assert(previous_boot_id);
 
        if (n_columns <= 0)
                n_columns = columns();
 
        r = output_funcs[mode](
                        f,
                        j,
                        mode,
                        n_columns,
                        flags,
                        output_fields,
                        highlight,
                        previous_display_ts,
                        previous_boot_id);
 
        if (ellipsized && r > 0)
                *ellipsized = true;
 
        return r;
}
 
static int maybe_print_begin_newline(FILE *f, OutputFlags *flags) {
        assert(f);
        assert(flags);
 
        if (!(*flags & OUTPUT_BEGIN_NEWLINE))
                return 0;
 
        /* Print a beginning new line if that's request, but only once
         * on the first line we print. */
 
        fputc('\n', f);
        *flags &= ~OUTPUT_BEGIN_NEWLINE;
        return 0;
}
 
int show_journal(
                FILE *f,
                sd_journal *j,
                OutputMode mode,
                unsigned n_columns,
                usec_t not_before,
                unsigned how_many,
                OutputFlags flags,
                bool *ellipsized) {
 
        int r;
        unsigned line = 0;
        bool need_seek = false;
        int warn_cutoff = flags & OUTPUT_WARN_CUTOFF;
        dual_timestamp previous_display_ts = DUAL_TIMESTAMP_NULL;
        sd_id128_t previous_boot_id = SD_ID128_NULL;
 
        assert(j);
        assert(mode >= 0);
        assert(mode < _OUTPUT_MODE_MAX);
 
        if (how_many == UINT_MAX)
                need_seek = true;
        else {
                /* Seek to end */
                r = sd_journal_seek_tail(j);
                if (r < 0)
                        return log_error_errno(r, "Failed to seek to tail: %m");
 
                r = sd_journal_previous_skip(j, how_many);
                if (r < 0)
                        return log_error_errno(r, "Failed to skip previous: %m");
        }
 
        for (;;) {
                usec_t usec;
 
                if (need_seek) {
                        r = sd_journal_next(j);
                        if (r == -EBADMSG) {
                                log_debug_errno(r, "Bad or partially written entry, leaving.");
                                break;
                        }
                        if (r < 0)
                                return log_error_errno(r, "Failed to iterate through journal: %m");
                }
 
                if (r == 0)
                        break;
 
                need_seek = true;
 
                if (not_before > 0) {
                        r = sd_journal_get_monotonic_usec(j, &usec, NULL);
 
                        /* -ESTALE is returned if the timestamp is not from this boot */
                        if (r == -ESTALE)
                                continue;
                        if (r < 0)
                                return log_error_errno(r, "Failed to get journal time: %m");
 
                        if (usec < not_before)
                                continue;
                }
 
                line++;
                maybe_print_begin_newline(f, &flags);
 
                r = show_journal_entry(
                                f,
                                j,
                                mode,
                                n_columns,
                                flags,
                                /* output_fields= */ NULL,
                                /* highlight= */ NULL,
                                ellipsized,
                                &previous_display_ts,
                                &previous_boot_id);
                if (r < 0)
                        return r;
        }
 
        if (warn_cutoff && line < how_many && not_before > 0) {
                sd_id128_t boot_id;
                usec_t cutoff = 0;
 
                /* Check whether the cutoff line is too early */
 
                r = sd_id128_get_boot(&boot_id);
                if (r < 0)
                        return log_error_errno(r, "Failed to get boot id: %m");
 
                r = sd_journal_get_cutoff_monotonic_usec(j, boot_id, &cutoff, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to get journal cutoff time: %m");
 
                if (r > 0 && not_before < cutoff) {
                        maybe_print_begin_newline(f, &flags);
 
                        /* If we logged *something* and no permission error happened, than we can reliably
                         * emit the warning about rotation. If we didn't log anything and access errors
                         * happened, emit hint about permissions. Otherwise, give a generic message, since we
                         * can't diagnose the issue. */
 
                        bool noaccess = journal_access_blocked(j);
 
                        if (line == 0 && noaccess)
                                fprintf(f, "Warning: some journal files were not opened due to insufficient permissions.\n");
                        else if (!noaccess)
                                fprintf(f, "Notice: journal has been rotated since unit was started, output may be incomplete.\n");
                        else
                                fprintf(f, "Warning: journal has been rotated since unit was started and some journal "
                                        "files were not opened due to insufficient permissions, output may be incomplete.\n");
                }
 
                warn_cutoff = false;
        }
 
        return 0;
}
 
int add_matches_for_invocation_id(sd_journal *j, sd_id128_t id) {
        int r;
 
        assert(j);
        assert(!sd_id128_is_null(id));
 
        (void) (
                /* Look for messages from the service itself. */
                (r = journal_add_match_pair(j, "_SYSTEMD_INVOCATION_ID", SD_ID128_TO_STRING(id))) ||
 
                /* Look for messages from authorized daemons about this service. */
                (r = sd_journal_add_disjunction(j)) ||
                (r = journal_add_match_pair(j, "OBJECT_SYSTEMD_INVOCATION_ID", SD_ID128_TO_STRING(id))) ||
 
                /* Look for messages from system service manager (PID 1) about this service. */
                (r = sd_journal_add_disjunction(j)) ||
                (r = journal_add_match_pair(j, "INVOCATION_ID", SD_ID128_TO_STRING(id))) ||
 
                /* Look for messages from user-session service manager about this service. */
                (r = sd_journal_add_disjunction(j)) ||
                (r = journal_add_match_pair(j, "USER_INVOCATION_ID", SD_ID128_TO_STRING(id)))
        );
 
        return r;
}
 
static int add_matches_for_coredump_uid(sd_journal *j, MatchUnitFlag flags, const char *unit) {
        static uid_t cached_uid = 0;
        int r;
 
        assert(j);
        assert(unit);
 
        if (!FLAGS_SET(flags, MATCH_UNIT_COREDUMP_UID))
                return 0;
 
        if (cached_uid == 0) {
                r = get_user_creds("systemd-coredump", /* flags= */ 0, NULL, &cached_uid, NULL, NULL, NULL);
                if (r < 0) {
                        log_debug_errno(r, "Failed to resolve systemd-coredump user, ignoring: %m");
                        cached_uid = UID_INVALID;
                } else if (cached_uid == 0) /* Huh? Let's handle that gracefully. */
                        cached_uid = UID_INVALID;
        }
 
        if (!uid_is_valid(cached_uid))
                return 0;
 
        r = journal_add_matchf(j, "_UID="UID_FMT, cached_uid);
        if (r < 0)
                return r;
 
        /* for systemd-coredump older than 888e378da2dbf4520e68a9d7e59712a3cd5a830f */
        return sd_journal_add_match(j, "_UID=0", SIZE_MAX);
}
 
int add_matches_for_unit_full(sd_journal *j, MatchUnitFlag flags, const char *unit) {
        int r;
 
        assert(j);
        assert(unit);
 
        (void) (
                /* Look for messages from the service itself */
                (r = journal_add_match_pair(j, "_SYSTEMD_UNIT", unit)) ||
 
                /* Look for messages from PID 1 about this service. Note that the actual match is placed
                 * on init.scope rather than _PID=1, as we want to match messages from helper processes
                 * forked off by init too. */
                (r = sd_journal_add_disjunction(j)) ||
                (r = sd_journal_add_match(j, "_SYSTEMD_CGROUP=/init.scope", SIZE_MAX)) ||
                (r = journal_add_match_pair(j, "UNIT", unit)) ||
 
                /* Look for messages from authorized daemons about this service */
                (r = sd_journal_add_disjunction(j)) ||
                (r = sd_journal_add_match(j, "_UID=0", SIZE_MAX)) ||
                (r = journal_add_match_pair(j, "OBJECT_SYSTEMD_UNIT", unit))
        );
 
        if (r == 0 && FLAGS_SET(flags, MATCH_UNIT_COREDUMP))
                (void) (
                        /* Look for coredumps of the service */
                        (r = sd_journal_add_disjunction(j)) ||
                        (r = sd_journal_add_match(j, "MESSAGE_ID=" SD_MESSAGE_COREDUMP_STR, SIZE_MAX)) ||
                        (r = add_matches_for_coredump_uid(j, flags, unit)) ||
                        (r = journal_add_match_pair(j, "COREDUMP_UNIT", unit))
                );
 
        if (r == 0 && FLAGS_SET(flags, MATCH_UNIT_SLICE) && endswith(unit, ".slice"))
                /* Show all messages belonging to a slice */
                (void) (
                        (r = sd_journal_add_disjunction(j)) ||
                        (r = journal_add_match_pair(j, "_SYSTEMD_SLICE", unit))
                );
 
        return r;
}
 
int add_matches_for_user_unit_full(sd_journal *j, MatchUnitFlag flags, uid_t uid, const char *unit) {
        int r;
 
        assert(j);
        assert(unit);
 
        if (uid == UID_INVALID)
                uid = getuid();
 
        (void) (
                /* Look for messages from the user service itself */
                (r = journal_add_match_pair(j, "_SYSTEMD_USER_UNIT", unit)) ||
                (r = journal_add_matchf(j, "_UID="UID_FMT, uid)) ||
 
                /* Look for messages from systemd about this service */
                (r = sd_journal_add_disjunction(j)) ||
                (r = journal_add_match_pair(j, "USER_UNIT", unit)) ||
                (r = journal_add_matchf(j, "_UID="UID_FMT, uid)) ||
 
                /* Look for messages from authorized daemons about this service */
                (r = sd_journal_add_disjunction(j)) ||
                (r = journal_add_match_pair(j, "OBJECT_SYSTEMD_USER_UNIT", unit)) ||
                (r = journal_add_matchf(j, "_UID="UID_FMT, uid)) ||
                (r = sd_journal_add_match(j, "_UID=0", SIZE_MAX))
        );
 
        if (r == 0 && FLAGS_SET(flags, MATCH_UNIT_COREDUMP))
                (void) (
                        /* Look for coredumps of the service */
                        (r = sd_journal_add_disjunction(j)) ||
                        (r = journal_add_match_pair(j, "COREDUMP_USER_UNIT", unit)) ||
                        (r = journal_add_matchf(j, "_UID="UID_FMT, uid)) ||
                        (r = sd_journal_add_match(j, "_UID=0", SIZE_MAX))
                );
 
        if (r == 0 && FLAGS_SET(flags, MATCH_UNIT_SLICE) && endswith(unit, ".slice"))
                /* Show all messages belonging to a slice */
                (void) (
                        (r = sd_journal_add_disjunction(j)) ||
                        (r = journal_add_match_pair(j, "_SYSTEMD_USER_SLICE", unit)) ||
                        (r = journal_add_matchf(j, "_UID="UID_FMT, uid))
                );
 
        return r;
}
 
int add_match_boot_id(sd_journal *j, sd_id128_t id) {
        int r;
 
        assert(j);
 
        if (sd_id128_is_null(id)) {
                r = sd_id128_get_boot(&id);
                if (r < 0)
                        return log_error_errno(r, "Failed to get boot ID: %m");
        }
 
        r = journal_add_match_pair(j, "_BOOT_ID", SD_ID128_TO_STRING(id));
        if (r < 0)
                return log_error_errno(r, "Failed to add match: %m");
 
        return 0;
}
 
int add_match_this_boot(sd_journal *j, const char *machine) {
        sd_id128_t boot_id;
        int r;
 
        assert(j);
 
        r = id128_get_boot_for_machine(machine, &boot_id);
        if (r < 0)
                return log_error_errno(r, "Failed to get boot ID%s%s: %m",
                                       isempty(machine) ? "" : " of container ", strempty(machine));
 
        r = add_match_boot_id(j, boot_id);
        if (r < 0)
                return r;
 
        r = sd_journal_add_conjunction(j);
        if (r < 0)
                return log_error_errno(r, "Failed to add conjunction: %m");
 
        return 0;
}
 
int show_journal_by_unit(
                FILE *f,
                const char *unit,
                const char *log_namespace,
                OutputMode mode,
                unsigned n_columns,
                usec_t not_before,
                unsigned how_many,
                OutputFlags flags,
                int journal_open_flags,
                bool system_unit,
                bool *ellipsized) {
 
        _cleanup_(sd_journal_closep) sd_journal *j = NULL;
        int r;
 
        assert(mode >= 0);
        assert(mode < _OUTPUT_MODE_MAX);
        assert(unit);
 
        if (how_many <= 0)
                return 0;
 
        r = sd_journal_open_namespace(&j, log_namespace,
                                      journal_open_flags |
                                      SD_JOURNAL_INCLUDE_DEFAULT_NAMESPACE |
                                      SD_JOURNAL_ASSUME_IMMUTABLE);
        if (r < 0)
                return log_error_errno(r, "Failed to open journal: %m");
 
        if (system_unit)
                r = add_matches_for_unit(j, unit);
        else
                r = add_matches_for_user_unit(j, unit);
        if (r < 0)
                return log_error_errno(r, "Failed to add unit matches: %m");
 
        r = sd_journal_add_conjunction(j);
        if (r < 0)
                return log_error_errno(r, "Failed to add conjunction: %m");
 
        r = add_match_this_boot(j, NULL);
        if (r < 0)
                return r;
 
        if (DEBUG_LOGGING) {
                _cleanup_free_ char *filter = NULL;
 
                filter = journal_make_match_string(j);
                if (!filter)
                        return log_oom();
 
                log_debug("Journal filter: %s", filter);
        }
 
        return show_journal(f, j, mode, n_columns, not_before, how_many, flags, ellipsized);
}
 
static int journal_get_id128(sd_journal *j, const char *field, sd_id128_t *ret) {
        const char *data, *str;
        size_t len, fl;
        sd_id128_t v;
        int r;
 
        assert(j);
        assert(field);
 
        /* This returns 1 when non-null ID is found, 0 when null ID is found, -ENOENT when the field not
         * found, -EINVAL when the field found but not a valid ID, -EBADMSG or -EADDRNOTAVAIL when journal
         * corruption detected. On a critical issue, other negative errno may be returned. */
 
        r = sd_journal_get_data(j, field, (const void**) &data, &len);
        if (r < 0)
                return r;
 
        fl = strlen(field);
        assert(len > fl);
        assert(data[fl] == '=');
 
        if (len > fl + 1 + SD_ID128_UUID_STRING_MAX)
                return -EINVAL;
 
        str = memdupa_suffix0(data + fl + 1, len - fl - 1);
 
        r = sd_id128_from_string(str, ret ?: &v);
        if (r < 0)
                return r;
 
        return !sd_id128_is_null(ret ? *ret : v);
}
 
static int journal_get_invocation_id(sd_journal *j, sd_id128_t *ret) {
        int r;
 
        assert(j);
 
        FOREACH_STRING(s,
                       "_SYSTEMD_INVOCATION_ID",       /* By the systemd unit. */
                       "OBJECT_SYSTEMD_INVOCATION_ID", /* Added by journald. */
                       "INVOCATION_ID",                /* By the system service manager (PID 1). */
                       "USER_INVOCATION_ID") {         /* By the user session service manager. */
 
                r = journal_get_id128(j, s, ret);
                if (!IN_SET(r, 0, -ENOENT, -EINVAL, -EBADMSG, -EADDRNOTAVAIL))
                        return r;
        }
 
        /* No invocation ID found in the entry. */
        if (ret)
                *ret = SD_ID128_NULL;
        return 0;
}
 
static const char* const log_id_type_table[_LOG_ID_TYPE_MAX] = {
        [LOG_BOOT_ID]                   = "boot ID",
        [LOG_SYSTEM_UNIT_INVOCATION_ID] = "system unit invocation ID",
        [LOG_USER_UNIT_INVOCATION_ID]   = "user unit invocation ID",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(log_id_type, LogIdType);
 
static int set_matches_for_discover_id(
                sd_journal *j,
                LogIdType type,
                sd_id128_t boot_id,
                const char *unit,
                sd_id128_t id) {
 
        int r;
 
        assert(j);
        assert(type >= 0 && type < _LOG_ID_TYPE_MAX);
 
        sd_journal_flush_matches(j);
 
        if (type == LOG_BOOT_ID) {
                if (sd_id128_is_null(id))
                        return 0;
 
                return add_match_boot_id(j, id);
        }
 
        if (!sd_id128_is_null(boot_id)) {
                r = add_match_boot_id(j, boot_id);