HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/sysext/sysext.c

132,720 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: e31d38d83f0ebe3c4643975d7ec98aa1f9102715

Lines 2001–3000 of 3,321

         * /run/ hierarchy (which our workspace is contained in) MS_SLAVE, see above. */
        r = mount_nofollow_verbose(LOG_ERR, image_class_info[c->image_class].short_identifier, workspace, "tmpfs", 0, "mode=0700");
        if (r < 0)
                return r;
 
        /* Acquire host OS release info, so that we can compare it with the extension's data */
        r = parse_os_release(
                        c->root,
                        "ID", &host_os_release_id,
                        "ID_LIKE", &host_os_release_id_like,
                        "VERSION_ID", &host_os_release_version_id,
                        image_class_info[c->image_class].level_env, &host_os_release_api_level);
        if (r < 0)
                return log_error_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(c->root));
        if (isempty(host_os_release_id))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "'ID' field not found or empty in 'os-release' data of OS tree '%s'.",
                                       empty_to_root(c->root));
 
        /* Let's now mount all images */
        HASHMAP_FOREACH(img, images) {
                _cleanup_free_ char *p = NULL, *path_without_root = NULL;
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *verity_hash = NULL;
 
                p = path_join(workspace, image_class_info[c->image_class].short_identifier_plural, img->name);
                if (!p)
                        return log_oom();
 
                r = mkdir_p(p, 0700);
                if (r < 0)
                        return log_error_errno(r, "Failed to create %s: %m", p);
 
                switch (img->type) {
                case IMAGE_DIRECTORY:
                case IMAGE_SUBVOLUME:
 
                        if (!c->force) {
                                r = extension_has_forbidden_content(p);
                                if (r < 0)
                                        return r;
                                if (r > 0) {
                                        n_ignored++;
                                        continue;
                                }
                        }
 
                        r = mount_nofollow_verbose(LOG_ERR, img->path, p, NULL, MS_BIND, NULL);
                        if (r < 0)
                                return r;
 
                        /* Make this a read-only bind mount */
                        r = bind_remount_recursive(p, MS_RDONLY, MS_RDONLY, NULL);
                        if (r < 0)
                                return log_error_errno(r, "Failed to make bind mount '%s' read-only: %m", p);
 
                        break;
 
                case IMAGE_RAW:
                case IMAGE_BLOCK: {
                        _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
                        _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
                        _cleanup_(verity_settings_done) VeritySettings verity_settings = VERITY_SETTINGS_DEFAULT;
                        DissectImageFlags flags =
                                DISSECT_IMAGE_READ_ONLY |
                                DISSECT_IMAGE_GENERIC_ROOT |
                                DISSECT_IMAGE_REQUIRE_ROOT |
                                DISSECT_IMAGE_MOUNT_ROOT_ONLY |
                                DISSECT_IMAGE_USR_NO_ROOT |
                                DISSECT_IMAGE_ADD_PARTITION_DEVICES |
                                DISSECT_IMAGE_PIN_PARTITION_DEVICES |
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
 
                        r = verity_settings_load(&verity_settings, img->path, NULL, NULL);
                        if (r < 0)
                                return log_error_errno(r, "Failed to read verity artifacts for %s: %m", img->path);
 
                        if (verity_settings.data_path)
                                flags |= DISSECT_IMAGE_NO_PARTITION_TABLE;
 
                        if (!c->force)
                                flags |= DISSECT_IMAGE_VALIDATE_OS_EXT;
 
                        r = loop_device_make_by_path(
                                        img->path,
                                        O_RDONLY,
                                        /* sector_size= */ UINT32_MAX,
                                        FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
                                        LOCK_SH,
                                        &d);
                        if (r < 0)
                                return log_error_errno(r, "Failed to set up loopback device for %s: %m", img->path);
 
                        r = dissect_loop_device_and_warn(
                                        d,
                                        &verity_settings,
                                        /* mount_options= */ NULL,
                                        pick_image_policy(c, img),
                                        /* image_filter= */ NULL,
                                        flags,
                                        &m);
                        if (r < 0)
                                return r;
 
                        /* Do not use the image name derived from the backing file of the loop device */
                        r = free_and_strdup(&m->image_name, img->name);
                        if (r < 0)
                                return r;
 
                        r = dissected_image_load_verity_sig_partition(
                                        m,
                                        d->fd,
                                        &verity_settings);
                        if (r < 0)
                                return r;
 
                        r = dissected_image_guess_verity_roothash(
                                        m,
                                        &verity_settings);
                        if (r < 0)
                                return r;
 
                        if (iovec_is_set(&verity_settings.root_hash)) {
                                r = sd_json_variant_new_hex(&verity_hash, verity_settings.root_hash.iov_base, verity_settings.root_hash.iov_len);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to create origin verity entry for '%s': %m", img->name);
                        }
 
                        r = dissected_image_decrypt(m, c->root, /* passphrase= */ NULL, &verity_settings, pick_image_policy(c, img), flags);
                        if (r < 0)
                                return r;
 
                        r = dissected_image_mount_and_warn(
                                        m,
                                        p,
                                        /* uid_shift= */ UID_INVALID,
                                        /* uid_range= */ UID_INVALID,
                                        /* userns_fd= */ -EBADF,
                                        flags);
                        if (r < 0 && r != -ENOMEDIUM)
                                return r;
                        if (r == -ENOMEDIUM && !c->force) {
                                n_ignored++;
                                continue;
                        }
 
                        r = dissected_image_relinquish(m);
                        if (r < 0)
                                return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
                        break;
                }
                default:
                        assert_not_reached();
                }
 
                if (c->force)
                        log_debug("Force mode enabled, skipping version validation.");
                else {
                        bool is_initrd;
                        r = chase_and_access("/etc/initrd-release", c->root, CHASE_PREFIX_ROOT, F_OK, /* ret_path= */ NULL);
                        if (r < 0 && r != -ENOENT)
                                return log_error_errno(r, "Failed to check for /etc/initrd-release: %m");
                        is_initrd = r >= 0;
 
                        r = extension_release_validate(
                                        img->name,
                                        host_os_release_id,
                                        host_os_release_id_like,
                                        host_os_release_version_id,
                                        host_os_release_api_level,
                                        is_initrd ? "initrd" : "system",
                                        image_extension_release(img, c->image_class),
                                        c->image_class);
                        if (r < 0)
                                return r;
                        if (r == 0) {
                                n_ignored++;
                                continue;
                        }
                }
 
                /* Nice! This one is an extension we want. */
                r = strv_extend(&extensions, img->name);
                if (r < 0)
                        return log_oom();
 
                /* Also get the absolute file name with version info for logging. */
                r = path_extract_filename(img->path, &filename);
                if (r == -ENOMEM)
                        return log_oom();
                if (r < 0)
                        return log_error_errno(r, "Failed to extract filename from '%s': %m", img->path);
 
                r = strv_extend(&extensions_v, filename);
                if (r < 0)
                        return log_oom();
 
                /* Encode extension image origin to check if we can skip the refresh.
                 * It can also be used to provide more detail in "systemd-sysext status". */
 
                if (!isempty(c->root)) {
                        const char *without_root = NULL;
                        without_root = path_startswith(img->path, root_resolved);
                        if (!isempty(without_root)) {
                                path_without_root = strjoin("/", without_root);
                                if (!path_without_root)
                                        return log_oom();
                        }
                }
                if (!path_without_root) {
                        path_without_root = strdup(img->path);
                        if (!path_without_root)
                                return log_oom();
                }
 
                /* The verity hash is not available for all extension types, thus, but only as fallback,
                 * also include data to check for file/directory replacements through a file handle and
                 * unique mount ID (or inode and mount ID as fallback).
                 * A unique mount ID is best because st_dev gets reused too easily, e.g., by a loop dev
                 * mount. For the mount ID to be valid it has to be resolved before we enter the new mount
                 * namespace. Thus, here it wouldn't work and so instead it gets provided by the image
                 * dissect logic and handed over to this subprocess we are in.
                 * Online modification is not well supported with overlay mounts, so we don't do a file
                 * checksum nor do we recurse into a directory to look for touched files. If users want
                 * modifications to be picked up, they need to set the --always-refresh=yes flag (as will be
                 * printed out). */
 
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *origin_entry = NULL;
 
                /* We suppress inclusion of weak identifiers when a strong one is there so that, e.g.,
                 * a confext image stored on /usr gets identified only by the verity hash instead of also
                 * the mount ID because that changes when a sysext overlay mount appears but since the
                 * verity hash is the same for the confext it can actually be reused. */
                r = sd_json_buildo(&origin_entry,
                                   SD_JSON_BUILD_PAIR_STRING("path", path_without_root),
                                   SD_JSON_BUILD_PAIR_CONDITION(!!verity_hash, "verityHash", SD_JSON_BUILD_VARIANT(verity_hash)),
                                   SD_JSON_BUILD_PAIR_CONDITION(!verity_hash, "onMountId", SD_JSON_BUILD_UNSIGNED(img->on_mount_id)),
                                   SD_JSON_BUILD_PAIR_CONDITION(!verity_hash && !!img->fh, "fileHandle",
                                                                SD_JSON_BUILD_OBJECT(SD_JSON_BUILD_PAIR_INTEGER("type", img->fh->handle_type),
                                                                                     SD_JSON_BUILD_PAIR_HEX("handle", img->fh->f_handle,
                                                                                                            img->fh->handle_bytes))),
                                   SD_JSON_BUILD_PAIR_CONDITION(!verity_hash && !img->fh, "inode", SD_JSON_BUILD_UNSIGNED(img->inode)),
                                   SD_JSON_BUILD_PAIR_CONDITION(!verity_hash, "crtime", SD_JSON_BUILD_UNSIGNED(img->crtime)),
                                   SD_JSON_BUILD_PAIR_CONDITION(!verity_hash, "mtime", SD_JSON_BUILD_UNSIGNED(img->mtime)));
                if (r < 0)
                        return log_error_errno(r, "Failed to create origin entry for '%s': %m", img->name);
 
                r = sd_json_variant_set_field(&extensions_origin_entries, img->name, origin_entry);
                if (r < 0)
                        return log_error_errno(r, "Failed to add origin entry for '%s': %m", img->name);
 
                n_extensions++;
        }
 
        /* Nothing left? Then shortcut things */
        if (n_extensions == 0 && c->mutable == MUTABLE_NO) {
                if (n_ignored > 0)
                        log_info("No suitable extensions found (%u ignored due to incompatible image(s)).", n_ignored);
                else
                        log_info("No extensions found.");
                return MERGE_NOTHING_FOUND;
        }
 
        /* Order by version sort with strverscmp_improved() */
        typesafe_qsort(extensions, n_extensions, strverscmp_improvedp);
        typesafe_qsort(extensions_v, n_extensions, strverscmp_improvedp);
 
        STRV_FOREACH(h, c->hierarchies) {
                _cleanup_(overlayfs_paths_freep) OverlayFSPaths *op = NULL;
                _cleanup_free_ char *f = NULL, *buf = NULL, *resolved = NULL, *mutable_directory_without_root = NULL;
 
                /* The origin file includes the backing directories for mutable overlays. */
                r = overlayfs_paths_new(c, *h, workspace, &op);
                if (r < 0)
                        return r;
 
                if (op->resolved_mutable_directory && !isempty(c->root)) {
                        const char *without_root = NULL;
                        without_root = path_startswith(op->resolved_mutable_directory, root_resolved);
                        if (!isempty(without_root)) {
                                mutable_directory_without_root = strjoin("/", without_root);
                                if (!mutable_directory_without_root)
                                        return log_oom();
                        }
                }
                if (!mutable_directory_without_root && op->resolved_mutable_directory) {
                        mutable_directory_without_root = strdup(op->resolved_mutable_directory);
                        if (!mutable_directory_without_root)
                                return log_oom();
                }
 
                if (mutable_directory_without_root) {
                        r = sd_json_variant_set_field_string(&mutable_dir_entries, *h, mutable_directory_without_root);
                        if (r < 0)
                                return log_error_errno(r, "Failed to add mutable directory to origin JSON entry: %m");
                }
 
                /* Find existing origin file for comparison. */
                r = chase(*h, c->root, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &resolved, /* ret_fd= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve hierarchy '%s%s': %m", strempty(c->root), *h);
 
                f = path_join(resolved, image_class_info[c->image_class].dot_directory_name, "origin");
                if (!f)
                        return log_oom();
 
                r = is_our_mount_point(c->image_class, resolved);
                if (r < 0)
                        return r;
                if (r == 0)
                        continue;
 
                if (old_origin_content)
                        continue;
 
                r = read_full_file(f, &buf, /* ret_size */ NULL);
                if (r < 0) {
                        log_debug_errno(r, "Failed to open '%s', continuing search: %m", f);
                        continue;
                }
 
                old_origin_content = TAKE_PTR(buf);
        }
 
        r = sd_json_buildo(&extensions_origin_json,
                           SD_JSON_BUILD_PAIR_OBJECT("mutable",
                                                     SD_JSON_BUILD_PAIR_STRING("mode", mutable_mode_to_string(c->mutable)),
                                                     SD_JSON_BUILD_PAIR_CONDITION(!!mutable_dir_entries,
                                                                                  "mutableDirs",
                                                                                  SD_JSON_BUILD_VARIANT(mutable_dir_entries))),
                           SD_JSON_BUILD_PAIR_CONDITION(!isempty(c->overlayfs_mount_options),
                                                        "mountOptions",
                                                        SD_JSON_BUILD_STRING(c->overlayfs_mount_options)),
                           SD_JSON_BUILD_PAIR_CONDITION(!!extensions_origin_entries,
                                                        "extensions",
                                                        SD_JSON_BUILD_VARIANT(extensions_origin_entries)));
        if (r < 0)
                return log_error_errno(r, "Failed to create extensions origin JSON object: %m");
 
        r = sd_json_variant_format(extensions_origin_json, SD_JSON_FORMAT_PRETTY|SD_JSON_FORMAT_NEWLINE, &extensions_origin_content);
        if (r < 0)
                return log_error_errno(r, "Failed to format extension origin as JSON: %m");
 
        log_debug("New extension origin entry (unordered):\n%s\n", extensions_origin_content);
 
        if (old_origin_content) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *old_origin_json = NULL;
 
                log_debug("Old extension origin entry (unordered):\n%s\n", old_origin_content);
                r = sd_json_parse(old_origin_content, /* flags= */ 0, &old_origin_json, /* reterr_line= */ NULL, /* reterr_column= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse existing extension origin content: %m");
 
                /* This works well with unordered entries. */
                if (sd_json_variant_equal(extensions_origin_json, old_origin_json)) {
                        if (!c->always_refresh) {
                                /* This only happens during refresh, not merge, thus talk about refresh here. */
                                log_info("Skipping extension refresh because no change was found, use --always-refresh=yes to always do a refresh.");
                                return MERGE_SKIP_REFRESH;
                        }
 
                        log_debug("No change found based on origin entry but continuing as requested by --always-refresh=yes.");
                } else
                        log_debug("Found changes based on origin entry, continuing with the refresh.");
        }
 
        if (n_extensions == 0) {
                assert(c->mutable != MUTABLE_NO);
                log_info("No extensions found, proceeding in mutable mode.");
        } else {
                _cleanup_free_ char *buf = strv_join(extensions_v, "', '");
                if (!buf)
                        return log_oom();
 
                log_info("Using extensions '%s'.", buf);
        }
 
        /* Build table of extension paths (in reverse order) */
        paths = new0(char*, n_extensions + 1);
        if (!paths)
                return log_oom();
 
        for (size_t k = 0; k < n_extensions; k++) {
                _cleanup_free_ char *p = NULL;
 
                assert_se(img = hashmap_get(images, extensions[n_extensions - 1 - k]));
 
                p = path_join(workspace, image_class_info[c->image_class].short_identifier_plural, img->name);
                if (!p)
                        return log_oom();
 
                paths[k] = TAKE_PTR(p);
        }
 
        /* Let's now unmerge the status quo ante, since to build the new overlayfs we need a reference to the
         * underlying fs. */
        STRV_FOREACH(h, c->hierarchies) {
                _cleanup_free_ char *submounts_path = NULL, *resolved = NULL;
 
                submounts_path = path_join(workspace, "submounts", *h);
                if (!submounts_path)
                        return log_oom();
 
                r = chase(*h, c->root, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &resolved, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve hierarchy '%s%s': %m", strempty(c->root), *h);
 
                r = unmerge_hierarchy(c, resolved, submounts_path);
                if (r < 0)
                        return r;
                if (r > 0)
                        continue;
 
                /* If we didn't unmerge anything, then we have to move the submounts from the host's
                 * original hierarchy. */
 
                r = move_submounts(resolved, submounts_path);
                if (r < 0)
                        return r;
        }
 
        /* Create overlayfs mounts for all hierarchies */
        STRV_FOREACH(h, c->hierarchies) {
                _cleanup_free_ char *meta_path = NULL, *overlay_path = NULL, *merge_hierarchy_workspace = NULL, *submounts_path = NULL;
 
                meta_path = path_join(workspace, "meta", *h); /* The place where to store metadata about this instance */
                if (!meta_path)
                        return log_oom();
 
                overlay_path = path_join(workspace, "overlay", *h); /* The resulting overlayfs instance */
                if (!overlay_path)
                        return log_oom();
 
                /* Temporary directory for merge_hierarchy needs, like ephemeral directories. */
                merge_hierarchy_workspace = path_join(workspace, "mh_workspace", *h);
                if (!merge_hierarchy_workspace)
                        return log_oom();
 
                submounts_path = path_join(workspace, "submounts", *h);
                if (!submounts_path)
                        return log_oom();
 
                r = merge_hierarchy(
                                c,
                                *h,
                                extensions,
                                paths,
                                extensions_origin_content,
                                meta_path,
                                overlay_path,
                                merge_hierarchy_workspace);
                if (r < 0)
                        return r;
 
                /* After the new hierarchy is set up, move the submounts from the original hierarchy into
                 * place. */
 
                r = move_submounts(submounts_path, overlay_path);
                if (r < 0)
                        return r;
        }
 
        /* And move them all into place. This is where things appear in the host namespace */
        STRV_FOREACH(h, c->hierarchies) {
                _cleanup_free_ char *p = NULL, *resolved = NULL;
 
                p = path_join(workspace, "overlay", *h);
                if (!p)
                        return log_oom();
 
                r = access_nofollow(p, F_OK);
                if (r == -ENOENT) /* Hierarchy apparently was empty in all extensions, and wasn't mounted, ignoring. */
                        continue;
                if (r < 0)
                        return log_error_errno(r, "Failed to check if '%s' exists: %m", p);
 
                r = chase(*h, c->root, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &resolved, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve hierarchy '%s%s': %m", strempty(c->root), *h);
 
                r = mkdir_p(resolved, 0755);
                if (r < 0)
                        return log_error_errno(r, "Failed to create hierarchy mount point '%s': %m", resolved);
 
                /* Using MS_REC to potentially bring in our read-only bind mount of metadata. */
                r = mount_nofollow_verbose(LOG_ERR, p, resolved, NULL, MS_BIND|MS_REC, NULL);
                if (r < 0)
                        return r;
 
                log_info("Merged extensions into '%s'.", resolved);
        }
 
        return MERGE_MOUNTED;
}
 
static int merge(const Context *c, Hashmap *images) {
 
        int r;
 
        assert(c);
 
        (void) dlopen_cryptsetup(LOG_DEBUG);
        (void) dlopen_libblkid(LOG_DEBUG);
        (void) dlopen_libmount(LOG_DEBUG);
 
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        r = pidref_safe_fork("(sd-merge)", FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_NEW_MOUNTNS, &pidref);
        if (r < 0)
                return log_error_errno(r, "Failed to fork off child: %m");
        if (r == 0) {
                /* Child with its own mount namespace */
 
                r = merge_subprocess(c, images, "/run/systemd/sysext");
 
                /* Our namespace ceases to exist here, also implicitly detaching all temporary mounts we
                 * created below /run. Nice! */
 
                if (r < 0)
                        _exit(EXIT_FAILURE);
                if (r == MERGE_NOTHING_FOUND)
                        _exit(MERGE_EXIT_NOTHING_FOUND);
                if (r == MERGE_SKIP_REFRESH)
                        _exit(MERGE_EXIT_SKIP_REFRESH);
 
                _exit(EXIT_SUCCESS);
        }
 
        r = pidref_wait_for_terminate_and_check("(sd-merge)", &pidref, WAIT_LOG_ABNORMAL);
        if (r < 0)
                return r;
        if (r == MERGE_EXIT_NOTHING_FOUND)
                return 0; /* Tell refresh to unmount */
        if (r == MERGE_EXIT_SKIP_REFRESH)
                return 1; /* Same return code as below when we have merged new */
        if (r > 0)
                return log_error_errno(SYNTHETIC_ERRNO(EPROTO), "Failed to merge hierarchies");
 
        _cleanup_set_free_ Set *units_to_restart = NULL, *units_to_reload_or_restart = NULL;
        bool need_to_reload;
        r = get_extension_release_metadata(c, &need_to_reload, &units_to_restart, &units_to_reload_or_restart);
        if (r < 0)
                return r;
        if (need_to_reload) {
                r = daemon_reload();
                if (r < 0)
                        return r;
        }
 
        /* The sets will be empty when opted out */
        r = restart_units(units_to_restart, units_to_reload_or_restart);
        if (r < 0)
                return r;
 
        return 1;
}
 
VERB_DEFAULT_NOARG(verb_status, "status", "Show current merge status (default)");
static int verb_status(int argc, char *argv[], uintptr_t _data, void *userdata) {
        _cleanup_(context_done) Context c = CONTEXT_NULL;
        _cleanup_(table_unrefp) Table *t = NULL;
        int r, ret = 0;
 
        r = context_from_cmdline(&c, arg_image_class);
        if (r < 0)
                return r;
 
        t = table_new("hierarchy", "extensions", "since");
        if (!t)
                return log_oom();
 
        table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
 
        STRV_FOREACH(p, c.hierarchies) {
                _cleanup_free_ char *resolved = NULL, *f = NULL, *buf = NULL;
                _cleanup_strv_free_ char **l = NULL;
                struct stat st;
 
                r = chase(*p, c.root, CHASE_PREFIX_ROOT, &resolved, NULL);
                if (r == -ENOENT) {
                        log_debug_errno(r, "Hierarchy '%s%s' does not exist, ignoring.", strempty(c.root), *p);
                        continue;
                }
                if (r < 0) {
                        log_error_errno(r, "Failed to resolve path to hierarchy '%s%s': %m", strempty(c.root), *p);
                        goto inner_fail;
                }
 
                r = is_our_mount_point(c.image_class, resolved);
                if (r < 0)
                        goto inner_fail;
                if (r == 0) {
                        r = table_add_many(
                                        t,
                                        TABLE_PATH, *p,
                                        TABLE_STRV, STRV_EMPTY,
                                        TABLE_EMPTY);
                        if (r < 0)
                                return table_log_add_error(r);
 
                        continue;
                }
 
                f = path_join(resolved, image_class_info[c.image_class].dot_directory_name, image_class_info[c.image_class].short_identifier_plural);
                if (!f)
                        return log_oom();
 
                r = read_full_file(f, &buf, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to open '%s': %m", f);
 
                l = strv_split_newlines(buf);
                if (!l)
                        return log_oom();
 
                if (stat(*p, &st) < 0)
                        return log_error_errno(errno, "Failed to stat() '%s': %m", *p);
 
                r = table_add_many(
                                t,
                                TABLE_PATH, *p,
                                TABLE_STRV, l,
                                TABLE_TIMESTAMP, timespec_load(&st.st_mtim));
                if (r < 0)
                        return table_log_add_error(r);
 
                continue;
 
        inner_fail:
                if (ret == 0)
                        ret = r;
        }
 
        (void) table_set_sort(t, (size_t) 0);
 
        r = table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
        if (r < 0)
                return r;
 
        return ret;
}
 
static int image_discover_and_read_metadata(const Context *c, Hashmap **ret_images) {
        _cleanup_hashmap_free_ Hashmap *images = NULL;
        Image *img;
        int r;
 
        assert(c);
        assert(ret_images);
 
        r = image_discover(RUNTIME_SCOPE_SYSTEM, c->image_class, c->root, &images);
        if (r < 0)
                return log_error_errno(r, "Failed to discover images: %m");
 
        HASHMAP_FOREACH(img, images) {
                r = image_read_metadata(img, c->root, image_class_info[c->image_class].default_image_policy, RUNTIME_SCOPE_SYSTEM);
                if (r < 0)
                        return log_error_errno(r, "Failed to read metadata for image %s: %m", img->name);
        }
 
        *ret_images = TAKE_PTR(images);
 
        return 0;
}
 
static int look_for_merged_hierarchies(const Context *c, const char **ret_which) {
        int r;
 
        assert(c);
        assert(ret_which);
 
        /* In merge mode fail if things are already merged. (In --refresh mode below we'll unmerge if we find
         * things are already merged...) */
        STRV_FOREACH(p, c->hierarchies) {
                _cleanup_free_ char *resolved = NULL;
 
                r = chase(*p, c->root, CHASE_PREFIX_ROOT, &resolved, NULL);
                if (r == -ENOENT) {
                        log_debug_errno(r, "Hierarchy '%s%s' does not exist, ignoring.", strempty(c->root), *p);
                        continue;
                }
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve path to hierarchy '%s%s': %m", strempty(c->root), *p);
 
                r = is_our_mount_point(c->image_class, resolved);
                if (r < 0)
                        return r;
                if (r > 0) {
                        *ret_which = *p;
                        return 1;
                }
        }
 
        *ret_which = NULL;
        return 0;
}
 
VERB_NOARG(verb_merge, "merge", "Merge extensions into relevant hierarchies");
static int verb_merge(int argc, char *argv[], uintptr_t _data, void *userdata) {
        _cleanup_(context_done) Context c = CONTEXT_NULL;
        _cleanup_hashmap_free_ Hashmap *images = NULL;
        const char *which;
        int r;
 
        r = have_effective_cap(CAP_SYS_ADMIN);
        if (r < 0)
                return log_error_errno(r, "Failed to check if we have enough privileges: %m");
        if (r == 0)
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be privileged.");
 
        r = context_from_cmdline(&c, arg_image_class);
        if (r < 0)
                return r;
 
        r = image_discover_and_read_metadata(&c, &images);
        if (r < 0)
                return r;
 
        r = look_for_merged_hierarchies(&c, &which);
        if (r < 0)
                return r;
        if (r > 0)
                return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Hierarchy '%s' is already merged.", which);
 
        return merge(&c, images);
}
 
typedef struct MethodMergeParameters {
        const char *class;
        int force;
        int no_reload;
        int always_refresh;
        int noexec;
} MethodMergeParameters;
 
static int parse_merge_parameters(sd_varlink *link, sd_json_variant *parameters, MethodMergeParameters *p) {
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "class",         SD_JSON_VARIANT_STRING,  sd_json_dispatch_const_string, offsetof(MethodMergeParameters, class),          0 },
                { "force",         SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate,     offsetof(MethodMergeParameters, force),          0 },
                { "noReload",      SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate,     offsetof(MethodMergeParameters, no_reload),      0 },
                { "alwaysRefresh", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate,     offsetof(MethodMergeParameters, always_refresh), 0 },
                { "noexec",        SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate,     offsetof(MethodMergeParameters, noexec),         0 },
                VARLINK_DISPATCH_POLKIT_FIELD,
                {}
        };
 
        assert(link);
        assert(parameters);
        assert(p);
 
        return sd_varlink_dispatch(link, parameters, dispatch_table, p);
}
 
static int vl_method_merge(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
        _cleanup_(context_done) Context c = CONTEXT_NULL;
        _cleanup_hashmap_free_ Hashmap *images = NULL;
        MethodMergeParameters p = {
                .force = -1,
                .no_reload = -1,
                .always_refresh = -1,
                .noexec = -1,
        };
        ImageClass image_class = arg_image_class;
        int r;
 
        assert(link);
 
        r = parse_merge_parameters(link, parameters, &p);
        if (r != 0)
                return r;
 
        r = parse_image_class_parameter(link, p.class, &image_class);
        if (r < 0)
                return r;
 
        r = context_from_cmdline(&c, image_class);
        if (r < 0)
                return r;
 
        if (p.force >= 0)
                c.force = p.force;
        if (p.no_reload >= 0)
                c.no_reload = p.no_reload;
        if (p.always_refresh >= 0)
                c.always_refresh = p.always_refresh;
        if (p.noexec >= 0)
                c.noexec = p.noexec;
 
        r = varlink_verify_polkit_async(
                        link,
                        /* bus= */ NULL,
                        image_class_info[c.image_class].polkit_rw_action_id,
                        (const char**) STRV_MAKE(
                                "verb", "merge",
                                "force", one_zero(c.force),
                                "noReload", one_zero(c.no_reload),
                                "noexec", one_zero(c.noexec > 0)),
                        polkit_registry);
        if (r <= 0)
                return r;
 
        r = image_discover_and_read_metadata(&c, &images);
        if (r < 0)
                return r;
 
        const char *which;
        r = look_for_merged_hierarchies(&c, &which);
        if (r < 0)
                return r;
        if (r > 0)
                return sd_varlink_errorbo(link, "io.systemd.sysext.AlreadyMerged", SD_JSON_BUILD_PAIR_STRING("hierarchy", which));
 
        r = merge(&c, images);
        if (r < 0)
                return r;
 
        return sd_varlink_reply(link, NULL);
}
 
VERB_NOARG(verb_unmerge, "unmerge", "Unmerge extensions from relevant hierarchies");
static int verb_unmerge(int argc, char *argv[], uintptr_t _data, void *userdata) {
        _cleanup_(context_done) Context c = CONTEXT_NULL;
        int r;
 
        r = have_effective_cap(CAP_SYS_ADMIN);
        if (r < 0)
                return log_error_errno(r, "Failed to check if we have enough privileges: %m");
        if (r == 0)
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be privileged.");
 
        r = context_from_cmdline(&c, arg_image_class);
        if (r < 0)
                return r;
 
        return unmerge(&c);
}
 
typedef struct MethodUnmergeParameters {
        const char *class;
        int no_reload;
} MethodUnmergeParameters;
 
static int vl_method_unmerge(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "class",    SD_JSON_VARIANT_STRING,  sd_json_dispatch_const_string, offsetof(MethodUnmergeParameters, class),     0 },
                { "noReload", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool,      offsetof(MethodUnmergeParameters, no_reload), 0 },
                VARLINK_DISPATCH_POLKIT_FIELD,
                {}
        };
        MethodUnmergeParameters p = {
                .no_reload = -1,
        };
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
        _cleanup_(context_done) Context c = CONTEXT_NULL;
        ImageClass image_class = arg_image_class;
        int r;
 
        assert(link);
 
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
        if (r != 0)
                return r;
 
        r = parse_image_class_parameter(link, p.class, &image_class);
        if (r < 0)
                return r;
 
        r = context_from_cmdline(&c, image_class);
        if (r < 0)
                return r;
 
        if (p.no_reload >= 0)
                c.no_reload = p.no_reload;
 
        r = varlink_verify_polkit_async(
                        link,
                        /* bus= */ NULL,
                        image_class_info[c.image_class].polkit_rw_action_id,
                        (const char**) STRV_MAKE(
                                "verb", "unmerge",
                                "noReload", one_zero(c.no_reload)),
                        polkit_registry);
        if (r <= 0)
                return r;
 
        r = unmerge(&c);
        if (r < 0)
                return r;
 
        return sd_varlink_reply(link, NULL);
}
 
static int refresh(const Context *c) {
 
        _cleanup_hashmap_free_ Hashmap *images = NULL;
        int r;
 
        assert(c);
 
        r = image_discover_and_read_metadata(c, &images);
        if (r < 0)
                return r;
 
        /* Returns > 0 if it did something, i.e. a new overlayfs is mounted now. When it does so it
         * implicitly unmounts any overlayfs placed there before. It also returns == 1 if there were
         * no changes found to apply and the mount stays intact. Returns == 0 if it did nothing, i.e. no
         * extension images found. In this case the old overlayfs remains in place if there was one. */
        r = merge(c, images);
        if (r < 0)
                return r;
        if (r == 0) /* No images found? Then unmerge. The goal of --refresh is after all that after having
                     * called there's a guarantee that the merge status matches the installed extensions. */
                r = unmerge(c);
 
        /* Net result here is that:
         *
         * 1. If an overlayfs was mounted before and no extensions exist anymore, we'll have unmerged things.
         *
         * 2. If an overlayfs was mounted before, and there are still extensions installed' we'll have
         *    unmerged and then merged things again or we have skipped the refresh because no changes
         *    were found.
         *
         * 3. If an overlayfs so far wasn't mounted, and there are extensions installed, we'll have it
         *    mounted now.
         *
         * 4. If there was no overlayfs mount so far, and no extensions installed, we implement a NOP.
         */
 
        return r;
}
 
VERB_NOARG(verb_refresh, "refresh", "Unmerge/merge extensions again");
static int verb_refresh(int argc, char *argv[], uintptr_t _data, void *userdata) {
        _cleanup_(context_done) Context c = CONTEXT_NULL;
        int r;
 
        r = have_effective_cap(CAP_SYS_ADMIN);
        if (r < 0)
                return log_error_errno(r, "Failed to check if we have enough privileges: %m");
        if (r == 0)
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be privileged.");
 
        r = context_from_cmdline(&c, arg_image_class);
        if (r < 0)
                return r;
 
        return refresh(&c);
}
 
static int vl_method_refresh(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
 
        _cleanup_(context_done) Context c = CONTEXT_NULL;
        MethodMergeParameters p = {
                .force = -1,
                .no_reload = -1,
                .always_refresh = -1,
                .noexec = -1,
        };
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
        ImageClass image_class = arg_image_class;
        int r;
 
        assert(link);
 
        r = parse_merge_parameters(link, parameters, &p);
        if (r != 0)
                return r;
 
        r = parse_image_class_parameter(link, p.class, &image_class);
        if (r < 0)
                return r;
 
        r = context_from_cmdline(&c, image_class);
        if (r < 0)
                return r;
 
        if (p.force >= 0)
                c.force = p.force;
        if (p.no_reload >= 0)
                c.no_reload = p.no_reload;
        if (p.always_refresh >= 0)
                c.always_refresh = p.always_refresh;
        if (p.noexec >= 0)
                c.noexec = p.noexec;
 
        r = varlink_verify_polkit_async(
                        link,
                        /* bus= */ NULL,
                        image_class_info[c.image_class].polkit_rw_action_id,
                        (const char**) STRV_MAKE(
                                "verb", "refresh",
                                "force", one_zero(c.force),
                                "noReload", one_zero(c.no_reload),
                                "noexec", one_zero(c.noexec > 0)),
                        polkit_registry);
        if (r <= 0)
                return r;
 
        r = refresh(&c);