HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/sysupdate/sysupdate-transfer.c

80,120 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 930e453737dc04cdb2dcf4749faaa2d96460f7af

Lines 1001–1862 of 1,862

                         glyph(GLYPH_RECYCLING),
                         space == UINT64_MAX ? "disabled" : "old",
                         oldest->path,
                         resource_type_to_string(oldest->resource->type));
 
                r = transfer_instance_vacuum(t, oldest);
                if (r < 0)
                        return r;
 
                instance_free(oldest);
                memmove(t->target.instances + p, t->target.instances + p + 1, (t->target.n_instances - p - 1) * sizeof(Instance*));
                t->target.n_instances--;
 
                count++;
        }
 
        return count;
}
 
static void compile_pattern_fields(
                const Transfer *t,
                const Instance *i,
                InstanceMetadata *ret) {
 
        assert(t);
        assert(i);
        assert(ret);
 
        *ret = (InstanceMetadata) {
                .version = i->metadata.version,
 
                /* We generally prefer explicitly configured values for the transfer over those automatically
                 * derived from the source instance. Also, if the source is a tar archive, then let's not
                 * patch mtime/mode and use the one embedded in the tar file */
                .partition_uuid = t->partition_uuid_set ? t->partition_uuid : i->metadata.partition_uuid,
                .partition_uuid_set = t->partition_uuid_set || i->metadata.partition_uuid_set,
                .partition_flags = t->partition_flags_set ? t->partition_flags : i->metadata.partition_flags,
                .partition_flags_set = t->partition_flags_set || i->metadata.partition_flags_set,
                .mtime = RESOURCE_IS_TAR(i->resource->type) ? USEC_INFINITY : i->metadata.mtime,
                .mode = t->mode != MODE_INVALID ? t->mode : (RESOURCE_IS_TAR(i->resource->type) ? MODE_INVALID : i->metadata.mode),
                .size = i->metadata.size,
                .tries_done = t->tries_done != UINT64_MAX ? t->tries_done :
                              i->metadata.tries_done != UINT64_MAX ? i->metadata.tries_done : 0,
                .tries_left = t->tries_left != UINT64_MAX ? t->tries_left :
                              i->metadata.tries_left != UINT64_MAX ? i->metadata.tries_left : 3,
                .no_auto = t->no_auto >= 0 ? t->no_auto : i->metadata.no_auto,
                .read_only = t->read_only >= 0 ? t->read_only : i->metadata.read_only,
                .growfs = t->growfs >= 0 ? t->growfs : i->metadata.growfs,
                .sha256sum_set = i->metadata.sha256sum_set,
        };
 
        memcpy(ret->sha256sum, i->metadata.sha256sum, sizeof(ret->sha256sum));
}
 
typedef struct CalloutContext {
        const Transfer *transfer;
        const Instance *instance;
        TransferProgress callback;
        PidRef pid;
        const char *name;
        int helper_errno;
        void* userdata;
} CalloutContext;
 
static CalloutContext *callout_context_free(CalloutContext *ctx) {
        if (!ctx)
                return NULL;
 
        /* We don't own any data but need to clean up the job pid */
        pidref_done(&ctx->pid);
 
        return mfree(ctx);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(CalloutContext*, callout_context_free);
 
static int callout_context_new(const Transfer *t, const Instance *i, TransferProgress cb,
                               const char *name, void* userdata, CalloutContext **ret) {
        _cleanup_(callout_context_freep) CalloutContext *ctx = NULL;
 
        assert(t);
        assert(i);
        assert(cb);
        assert(ret);
 
        ctx = new(CalloutContext, 1);
        if (!ctx)
                return -ENOMEM;
 
        *ctx = (CalloutContext) {
                .transfer = t,
                .instance = i,
                .callback = cb,
                .pid = PIDREF_NULL,
                .name = name,
                .userdata = userdata,
        };
 
        *ret = TAKE_PTR(ctx);
        return 0;
}
 
static int helper_on_exit(sd_event_source *s, const siginfo_t *si, void *userdata) {
        CalloutContext *ctx = ASSERT_PTR(userdata);
        int r;
 
        assert(s);
        assert(si);
        assert(ctx);
 
        if (si->si_code == CLD_EXITED) {
                if (si->si_status == EXIT_SUCCESS) {
                        r = 0;
                        log_debug("%s succeeded.", ctx->name);
                } else if (ctx->helper_errno != 0) {
                        r = -ctx->helper_errno;
                        log_error_errno(r, "%s failed with exit status %i: %m", ctx->name, si->si_status);
                } else {
                        r = -EPROTO;
                        log_error("%s failed with exit status %i.", ctx->name, si->si_status);
                }
        } else {
                r = -EPROTO;
                if (IN_SET(si->si_code, CLD_KILLED, CLD_DUMPED))
                        log_error("%s terminated by signal %s.", ctx->name, signal_to_string(si->si_status));
                else
                        log_error("%s failed due to unknown reason.", ctx->name);
        }
 
        return sd_event_exit(sd_event_source_get_event(s), r);
}
 
static int helper_on_notify(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        CalloutContext *ctx = ASSERT_PTR(userdata);
        int r;
 
        assert(fd >= 0);
 
        _cleanup_free_ char *buf = NULL;
        _cleanup_(pidref_done) PidRef sender_pid = PIDREF_NULL;
        r = notify_recv(fd, &buf, /* ret_ucred= */ NULL, &sender_pid);
        if (r == -EAGAIN)
                return 0;
        if (r < 0)
                return r;
 
        if (!pidref_equal(&ctx->pid, &sender_pid)) {
                log_warning("Got notification datagram from unexpected peer, ignoring.");
                return 0;
        }
 
        char *errno_str = find_line_startswith(buf, "ERRNO=");
        if (errno_str) {
                truncate_nl(errno_str);
                r = parse_errno(errno_str);
                if (r < 0)
                        log_warning_errno(r, "Got invalid errno value '%s', ignoring: %m", errno_str);
                else {
                        ctx->helper_errno = r;
                        log_debug_errno(r, "Got errno from callout: %i (%m)", r);
                }
        }
 
        char *progress_str = find_line_startswith(buf, "X_IMPORT_PROGRESS=");
        if (progress_str) {
                truncate_nl(progress_str);
 
                int progress = parse_percent(progress_str);
                if (progress < 0)
                        log_warning("Got invalid percent value '%s', ignoring.", progress_str);
                else {
                        r = ctx->callback(ctx->transfer, ctx->instance, progress);
                        if (r < 0)
                                return r;
                }
        }
 
        return 0;
}
 
static int run_callout(
                const char *name,
                char *cmdline[],
                const Transfer *transfer,
                const Instance *instance,
                TransferProgress callback,
                void *userdata) {
 
        int r;
 
        assert(name);
        assert(cmdline);
        assert(cmdline[0]);
 
        _cleanup_(callout_context_freep) CalloutContext *ctx = NULL;
        r = callout_context_new(transfer, instance, callback, name, userdata, &ctx);
        if (r < 0)
                return log_oom();
 
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
        r = sd_event_new(&event);
        if (r < 0)
                return log_error_errno(r, "Failed to create event: %m");
 
        /* Kill the helper & return an error if we get interrupted by a signal */
        r = sd_event_add_signal(event, NULL, SIGINT | SD_EVENT_SIGNAL_PROCMASK, NULL, INT_TO_PTR(-ECANCELED));
        if (r < 0)
                return log_error_errno(r, "Failed to register signal to event: %m");
        r = sd_event_add_signal(event, NULL, SIGTERM | SD_EVENT_SIGNAL_PROCMASK, NULL, INT_TO_PTR(-ECANCELED));
        if (r < 0)
                return log_error_errno(r, "Failed to register signal to event: %m");
 
        _cleanup_free_ char *bind_name = NULL;
        r = notify_socket_prepare(
                        event,
                        SD_EVENT_PRIORITY_NORMAL - 5,
                        helper_on_notify,
                        ctx,
                        &bind_name);
        if (r < 0)
                return log_error_errno(r, "Failed to prepare notify socket: %m");
 
        r = pidref_safe_fork(ctx->name, FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_LOG, &ctx->pid);
        if (r < 0)
                return log_error_errno(r, "Failed to fork process %s: %m", ctx->name);
        if (r == 0) {
                /* Child */
                if (setenv("NOTIFY_SOCKET", bind_name, 1) < 0) {
                        log_error_errno(errno, "setenv() failed: %m");
                        _exit(EXIT_FAILURE);
                }
                r = invoke_callout_binary(cmdline[0], (char *const*) cmdline);
                log_error_errno(r, "Failed to execute %s tool: %m", cmdline[0]);
                _exit(EXIT_FAILURE);
        }
 
        /* Quit the loop w/ when child process exits */
        _cleanup_(sd_event_source_unrefp) sd_event_source *exit_source = NULL;
        r = event_add_child_pidref(event, &exit_source, &ctx->pid, WEXITED, helper_on_exit, ctx);
        if (r < 0)
                return log_error_errno(r, "Failed to add child process to event loop: %m");
 
        r = sd_event_source_set_child_process_own(exit_source, true);
        if (r < 0)
                return log_error_errno(r, "Failed to take ownership of child process: %m");
 
        /* Process events until the helper quits */
        return sd_event_loop(event);
}
 
/* Build the filenames and paths which is normally done by transfer_acquire_instance(), but for partial
 * and pending instances which are about to be installed (in which case, transfer_acquire_instance() is
 * skipped). */
int transfer_compute_temporary_paths(Transfer *t, Instance *i, InstanceMetadata *f) {
        _cleanup_free_ char *formatted_pattern = NULL;
        int r;
 
        assert(t);
        assert(i);
 
        assert(!t->final_path);
        assert(!t->temporary_partial_path);
        assert(!t->temporary_pending_path);
        assert(!t->final_partition_label);
        assert(!strv_isempty(t->target.patterns));
 
        /* Format the target name using the first pattern specified */
        compile_pattern_fields(t, i, f);
        r = pattern_format(t->target.patterns[0], f, &formatted_pattern);
        if (r < 0)
                return log_error_errno(r, "Failed to format target pattern: %m");
 
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
                _cleanup_free_ char *final_dir = NULL, *final_filename = NULL, *partial_filename = NULL, *pending_filename = NULL;
 
                if (!path_is_safe(formatted_pattern))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Formatted pattern is not suitable as file name, refusing: %s", formatted_pattern);
 
                t->final_path = path_join(t->target.path, formatted_pattern);
                if (!t->final_path)
                        return log_oom();
 
                /* Build the paths for the partial and pending files, which hold the resource while it’s
                 * being acquired and after it’s been acquired (but before it’s moved to the final_path
                 * when it’s installed).
                 *
                 * Split the filename off the `final_path`, then add a prefix to it for each of partial and
                 * pending, then join them back on to the same directory. */
                r = path_split_prefix_filename(t->final_path, &final_dir, &final_filename);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse path: %m");
 
                if (!strprepend(&partial_filename, ".sysupdate.partial.", final_filename))
                        return log_oom();
 
                if (!strprepend(&pending_filename, ".sysupdate.pending.", final_filename))
                        return log_oom();
 
                t->temporary_partial_path = path_join(final_dir, partial_filename);
                if (!t->temporary_partial_path)
                        return log_oom();
 
                t->temporary_pending_path = path_join(final_dir, pending_filename);
                if (!t->temporary_pending_path)
                        return log_oom();
        }
 
        if (t->target.type == RESOURCE_PARTITION) {
                r = gpt_partition_label_valid(formatted_pattern);
                if (r < 0)
                        return log_error_errno(r, "Failed to determine if formatted pattern is suitable as GPT partition label: %s", formatted_pattern);
                if (!r)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Formatted pattern is not suitable as GPT partition label, refusing: %s", formatted_pattern);
 
                assert(t->target.partition_type_set);
 
                /* Derive temporary partition type UUIDs for partial/pending states from the configured
                 * partition type. This avoids the need for label prefixes. */
                r = gpt_partition_type_uuid_for_sysupdate_partial(t->target.partition_type.uuid, &t->partition_type_partial);
                if (r < 0)
                        return log_error_errno(r, "Failed to derive partial partition type UUID: %m");
 
                r = gpt_partition_type_uuid_for_sysupdate_pending(t->target.partition_type.uuid, &t->partition_type_pending);
                if (r < 0)
                        return log_error_errno(r, "Failed to derive pending partition type UUID: %m");
 
                t->final_partition_label = TAKE_PTR(formatted_pattern);
        }
 
        return 0;
}
 
static bool transfer_zero_fill(const Transfer *t) {
        assert(t);
        assert(t->target.type == RESOURCE_PARTITION);
        assert(t->target.partition_type_set);
 
        /* Returns whether to fill up the rest of the partition with zeroes after writing the payload. If
         * configured explicitly, use that. Otherwise, do so for verity signature partitions only: they carry
         * a JSON object that must be followed by NUL bytes only, up to the end of the partition. The
         * artifacts we install there generally come without that padding though (repart's --split= mode
         * trims it, so that the file is a plain JSON text file), hence without zero filling the tail of a
         * previous, longer signature would survive right after the new one. These partitions are tiny, hence
         * this is cheap. */
 
        if (t->zero_fill >= 0)
                return t->zero_fill;
 
        return partition_designator_is_verity_sig(t->target.partition_type.designator);
}
 
int transfer_acquire_instance(Transfer *t, Instance *i, InstanceMetadata *f, TransferProgress cb, void *userdata) {
        _cleanup_free_ char *digest = NULL;
        char offset[DECIMAL_STR_MAX(uint64_t)+1], max_size[DECIMAL_STR_MAX(uint64_t)+1];
        const char *where = NULL;
        Instance *existing;
        int r;
 
        assert(t);
        assert(i);
        assert(f);
        assert(i->resource == &t->source);
        assert(cb);
 
        /* Does this instance already exist in the target? Then we don't need to acquire anything */
        existing = resource_find_instance(&t->target, i->metadata.version);
        if (existing && (existing->is_partial || existing->is_pending))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to acquire '%s', instance is already partial or pending in the target.", i->path);
        if (existing) {
                log_info("No need to acquire '%s', already installed.", i->path);
                return 0;
        }
 
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
                r = mkdir_parents(t->temporary_partial_path, 0755);
                if (r < 0)
                        return log_error_errno(r, "Cannot create target directory: %m");
 
                r = mkdir_parents(t->temporary_pending_path, 0755);
                if (r < 0)
                        return log_error_errno(r, "Cannot create target directory: %m");
 
                r = mkdir_parents(t->final_path, 0755);
                if (r < 0)
                        return log_error_errno(r, "Cannot create target directory: %m");
 
                where = t->final_path;
        }
 
        if (t->target.type == RESOURCE_PARTITION) {
                r = find_suitable_partition(
                                t->target.path,
                                i->metadata.size,
                                t->target.partition_type_set ? &t->target.partition_type.uuid : NULL,
                                &t->partition_info);
                if (r < 0)
                        return r;
 
                xsprintf(offset, "%" PRIu64, t->partition_info.start);
                xsprintf(max_size, "%" PRIu64, t->partition_info.size);
 
                where = t->partition_info.device;
 
                /* Set the partition label and change the partition type to the derived "partial" type UUID
                 * to indicate that a transfer to it is in progress. */
                r = free_and_strdup_warn(&t->partition_info.label, t->final_partition_label);
                if (r < 0)
                        return r;
                t->partition_info.type = t->partition_type_partial;
                t->partition_change = PARTITION_LABEL | PARTITION_TYPE;
 
                log_debug("Marking partition '%s' as partial (label='%s', type=%s).",
                          t->partition_info.device,
                          t->partition_info.label,
                          SD_ID128_TO_UUID_STRING(t->partition_info.type));
                r = patch_partition(
                                t->target.path,
                                &t->partition_info,
                                t->partition_change);
                if (r < 0)
                        return r;
        }
 
        assert(where);
 
        log_info("%s Acquiring %s %s %s...", glyph(GLYPH_DOWNLOAD), i->path, glyph(GLYPH_ARROW_RIGHT), where);
 
        if (RESOURCE_IS_URL(i->resource->type)) {
                /* For URL sources we require the SHA256 sum to be known so that we can validate the
                 * download. */
 
                if (!i->metadata.sha256sum_set)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "SHA256 checksum not known for download '%s', refusing.", i->path);
 
                digest = hexmem(i->metadata.sha256sum, sizeof(i->metadata.sha256sum));
                if (!digest)
                        return log_oom();
        }
 
        switch (i->resource->type) { /* Source */
 
        case RESOURCE_REGULAR_FILE:
 
                switch (t->target.type) { /* Target */
 
                case RESOURCE_REGULAR_FILE:
 
                        /* regular file → regular file (why fork off systemd-import for such a simple file
                         * copy case? implicit decompression mostly, and thus also sandboxing. Also, the
                         * importer has some tricks up its sleeve, such as sparse file generation, which we
                         * want to take benefit of, too.) */
 
                        r = run_callout("(sd-import-raw)",
                                        STRV_MAKE(
                                               SYSTEMD_IMPORT_PATH,
                                               "raw",
                                               "--direct",          /* just copy/unpack the specified file, don't do anything else */
                                               t->context->sync ? "--sync=yes" : "--sync=no",
                                               i->path,
                                               t->temporary_partial_path),
                                        t, i, cb, userdata);
                        break;
 
                case RESOURCE_PARTITION:
 
                        /* regular file → partition */
 
                        r = run_callout("(sd-import-raw)",
                                        STRV_MAKE(
                                               SYSTEMD_IMPORT_PATH,
                                               "raw",
                                               "--direct",          /* just copy/unpack the specified file, don't do anything else */
                                               "--offset", offset,
                                               "--size-max", max_size,
                                               transfer_zero_fill(t) ? "--zero-fill=yes" : "--zero-fill=no",
                                               t->context->sync ? "--sync=yes" : "--sync=no",
                                               i->path,
                                               t->target.path),
                                        t, i, cb, userdata);
                        break;
 
                default:
                        assert_not_reached();
                }
 
                break;
 
        case RESOURCE_DIRECTORY:
        case RESOURCE_SUBVOLUME:
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
 
                /* directory/subvolume → directory/subvolume */
 
                r = run_callout("(sd-import-fs)",
                                STRV_MAKE(
                                       SYSTEMD_IMPORT_FS_PATH,
                                       "run",
                                       "--direct",          /* just untar the specified file, don't do anything else */
                                       t->context->sync ? "--sync=yes" : "--sync=no",
                                       t->target.type == RESOURCE_SUBVOLUME ? "--btrfs-subvol=yes" : "--btrfs-subvol=no",
                                       i->path,
                                       t->temporary_partial_path),
                                t, i, cb, userdata);
                break;
 
        case RESOURCE_TAR:
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
 
                /* tar → directory/subvolume */
 
                r = run_callout("(sd-import-tar)",
                                STRV_MAKE(
                                       SYSTEMD_IMPORT_PATH,
                                       "tar",
                                       "--direct",          /* just untar the specified file, don't do anything else */
                                       t->context->sync ? "--sync=yes" : "--sync=no",
                                       t->target.type == RESOURCE_SUBVOLUME ? "--btrfs-subvol=yes" : "--btrfs-subvol=no",
                                       i->path,
                                       t->temporary_partial_path),
                                t, i, cb, userdata);
                break;
 
        case RESOURCE_URL_FILE:
 
                switch (t->target.type) {
 
                case RESOURCE_REGULAR_FILE:
 
                        /* url file → regular file */
 
                        r = run_callout("(sd-pull-raw)",
                                       STRV_MAKE(
                                               SYSTEMD_PULL_PATH,
                                               "raw",
                                               "--direct",          /* just download the specified URL, don't download anything else */
                                               "--verify", digest,  /* validate by explicit SHA256 sum */
                                               t->context->sync ? "--sync=yes" : "--sync=no",
                                               i->path,
                                               t->temporary_partial_path),
                                        t, i, cb, userdata);
                        break;
 
                case RESOURCE_PARTITION:
 
                        /* url file → partition */
 
                        r = run_callout("(sd-pull-raw)",
                                        STRV_MAKE(
                                               SYSTEMD_PULL_PATH,
                                               "raw",
                                               "--direct",              /* just download the specified URL, don't download anything else */
                                               "--verify", digest,      /* validate by explicit SHA256 sum */
                                               "--offset", offset,
                                               "--size-max", max_size,
                                               transfer_zero_fill(t) ? "--zero-fill=yes" : "--zero-fill=no",
                                               t->context->sync ? "--sync=yes" : "--sync=no",
                                               i->path,
                                               t->target.path),
                                        t, i, cb, userdata);
                        break;
 
                default:
                        assert_not_reached();
                }
 
                break;
 
        case RESOURCE_URL_TAR:
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
 
                r = run_callout("(sd-pull-tar)",
                                STRV_MAKE(
                                       SYSTEMD_PULL_PATH,
                                       "tar",
                                       "--direct",          /* just download the specified URL, don't download anything else */
                                       "--verify", digest,  /* validate by explicit SHA256 sum */
                                       t->target.type == RESOURCE_SUBVOLUME ? "--btrfs-subvol=yes" : "--btrfs-subvol=no",
                                       t->context->sync ? "--sync=yes" : "--sync=no",
                                       i->path,
                                       t->temporary_partial_path),
                                t, i, cb, userdata);
                break;
 
        default:
                assert_not_reached();
        }
        if (r < 0)
                return r;
 
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
                bool need_sync = false;
                assert(t->temporary_partial_path);
                assert(t->temporary_pending_path);
 
                /* Apply file attributes if set */
                if (f->mtime != USEC_INFINITY) {
                        struct timespec ts;
 
                        timespec_store(&ts, f->mtime);
 
                        if (utimensat(AT_FDCWD, t->temporary_partial_path, (struct timespec[2]) { ts, ts }, AT_SYMLINK_NOFOLLOW) < 0)
                                return log_error_errno(errno, "Failed to adjust mtime of '%s': %m", t->temporary_partial_path);
 
                        need_sync = true;
                }
 
                if (f->mode != MODE_INVALID) {
                        /* Try with AT_SYMLINK_NOFOLLOW first, because it's the safe thing to do. Older
                         * kernels don't support that however, in that case we fall back to chmod(). Not as
                         * safe, but shouldn't be a problem, given that we don't create symlinks here. */
                        if (fchmodat(AT_FDCWD, t->temporary_partial_path, f->mode, AT_SYMLINK_NOFOLLOW) < 0 &&
                            (!ERRNO_IS_NOT_SUPPORTED(errno) || chmod(t->temporary_partial_path, f->mode) < 0))
                                return log_error_errno(errno, "Failed to adjust mode of '%s': %m", t->temporary_partial_path);
 
                        need_sync = true;
                }
 
                /* Synchronize */
                if (t->context->sync && need_sync) {
                        if (t->target.type == RESOURCE_REGULAR_FILE)
                                r = fsync_path_and_parent_at(AT_FDCWD, t->temporary_partial_path);
                        else {
                                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
                                r = syncfs_path(AT_FDCWD, t->temporary_partial_path);
                        }
                        if (r < 0)
                                return log_error_errno(r, "Failed to synchronize file system backing '%s': %m", t->temporary_partial_path);
                }
 
                t->install_read_only = f->read_only;
 
                /* Rename the file from `.sysupdate.partial.<VERSION>` to `.sysupdate.pending.<VERSION>` to indicate it’s ready to install. */
                log_debug("Renaming resource instance '%s' to '%s'.", t->temporary_partial_path, t->temporary_pending_path);
                r = install_file(AT_FDCWD, t->temporary_partial_path,
                                 AT_FDCWD, t->temporary_pending_path,
                                 INSTALL_REPLACE|
                                 (t->install_read_only > 0 ? INSTALL_READ_ONLY : 0)|
                                 (t->target.type == RESOURCE_REGULAR_FILE ? INSTALL_FSYNC_FULL : INSTALL_SYNCFS));
                if (r < 0)
                        return log_error_errno(r, "Failed to move '%s' into pending place: %m", t->temporary_pending_path);
        }
 
        if (t->target.type == RESOURCE_PARTITION) {
                /* Now change the partition type to the derived "pending" type UUID to indicate that the
                 * acquire is complete and the partition is ready for install. */
                t->partition_info.type = t->partition_type_pending;
                t->partition_change = PARTITION_TYPE;
 
                if (f->partition_uuid_set) {
                        t->partition_info.uuid = f->partition_uuid;
                        t->partition_change |= PARTITION_UUID;
                }
 
                if (f->partition_flags_set) {
                        t->partition_info.flags = f->partition_flags;
                        t->partition_change |= PARTITION_FLAGS;
                }
 
                if (f->no_auto >= 0) {
                        t->partition_info.no_auto = f->no_auto;
                        t->partition_change |= PARTITION_NO_AUTO;
                }
 
                if (f->read_only >= 0) {
                        t->partition_info.read_only = f->read_only;
                        t->partition_change |= PARTITION_READ_ONLY;
                }
 
                if (f->growfs >= 0) {
                        t->partition_info.growfs = f->growfs;
                        t->partition_change |= PARTITION_GROWFS;
                }
 
                log_debug("Marking partition '%s' as pending (type=%s).",
                          t->partition_info.device,
                          SD_ID128_TO_UUID_STRING(t->partition_info.type));
                r = patch_partition(
                                t->target.path,
                                &t->partition_info,
                                t->partition_change);
                if (r < 0)
                        return r;
        }
 
        /* For regular file cases the only step left is to install the file in place, which install_file()
         * will do via rename(). For partition cases the only step left is to update the partition table,
         * which is done at the same place. */
 
        log_info("Successfully acquired '%s'.", i->path);
        return 0;
}
 
int transfer_process_partial_and_pending_instance(Transfer *t, Instance *i) {
        InstanceMetadata f;
        Instance *existing;
        int r;
 
        assert(t);
        assert(i);
 
        log_debug("transfer_process_partial_and_pending_instance %s", i->path);
 
        /* Does this instance already exist in the target but isn’t pending? */
        existing = resource_find_instance(&t->target, i->metadata.version);
        if (existing && !existing->is_pending) {
                log_info("Resource '%s' instance is already in the target but is not pending.", i->path);
                return 0;
        }
 
        /* All we need to do is compute the temporary paths. We don’t need to do any of the other work in
         * transfer_acquire_instance(). */
        r = transfer_compute_temporary_paths(t, i, &f);
        if (r < 0)
                return r;
 
        /* This is the analogue of find_suitable_partition(), but since finding the suitable partition has
         * already happened in the acquire phase, the target should already have that information and it
         * should already have been claimed with the pending partition type UUID. */
        if (t->target.type == RESOURCE_PARTITION) {
                assert(i->resource == &t->target);
                assert(i->is_pending);
 
                r = partition_info_copy(&t->partition_info, &i->partition_info);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
int transfer_install_instance(
                Transfer *t,
                Instance *i,
                const char *root) {
 
        int r;
 
        assert(t);
        assert(i);
        assert(i->resource);
        assert(i->is_pending || t == container_of(i->resource, Transfer, source));
 
        log_debug("transfer_install_instance %s %s %s %d", i->path, t->temporary_pending_path, t->final_partition_label, t->partition_change);
 
        if (t->temporary_pending_path) {
                assert(RESOURCE_IS_FILESYSTEM(t->target.type));
                assert(t->final_path);
 
                r = install_file(AT_FDCWD, t->temporary_pending_path,
                                 AT_FDCWD, t->final_path,
                                 INSTALL_REPLACE|
                                 (t->install_read_only > 0 ? INSTALL_READ_ONLY : 0)|
                                 (t->target.type == RESOURCE_REGULAR_FILE ? INSTALL_FSYNC_FULL : INSTALL_SYNCFS));
                if (r < 0)
                        return log_error_errno(r, "Failed to move '%s' into place: %m", t->final_path);
 
                log_info("Successfully installed '%s' (%s) as '%s' (%s).",
                         i->path,
                         resource_type_to_string(i->resource->type),
                         t->final_path,
                         resource_type_to_string(t->target.type));
 
                t->temporary_pending_path = mfree(t->temporary_pending_path);
 
                (void) context_installdb_record(t->context, t->target.path, t->target.patterns);
        }
 
        if (t->final_partition_label) {
                assert(t->target.type == RESOURCE_PARTITION);
                assert(t->target.partition_type_set);
 
                r = free_and_strdup_warn(&t->partition_info.label, t->final_partition_label);
                if (r < 0)
                        return r;
 
                /* Restore the original partition type UUID now that the partition is fully installed. */
                t->partition_info.type = t->target.partition_type.uuid;
                t->partition_change = PARTITION_LABEL | PARTITION_TYPE;
 
                r = patch_partition(
                                t->target.path,
                                &t->partition_info,
                                t->partition_change);
                if (r < 0)
                        return r;
 
                log_info("Successfully installed '%s' (%s) as '%s' (%s).",
                         i->path,
                         resource_type_to_string(i->resource->type),
                         t->partition_info.device,
                         resource_type_to_string(t->target.type));
        }
 
        if (t->current_symlink) {
                _cleanup_free_ char *buf = NULL, *parent = NULL, *relative = NULL, *resolved = NULL;
                const char *link_path, *link_target;
                bool resolve_link_path = false;
 
                if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
 
                        assert(t->target.path);
 
                        if (path_is_absolute(t->current_symlink)) {
                                link_path = t->current_symlink;
                                resolve_link_path = true;
                        } else {
                                buf = path_make_absolute(t->current_symlink, t->target.path);
                                if (!buf)
                                        return log_oom();
 
                                link_path = buf;
                        }
 
                        link_target = t->final_path;
 
                } else if (t->target.type == RESOURCE_PARTITION) {
 
                        assert(path_is_absolute(t->current_symlink));
 
                        link_path = t->current_symlink;
                        link_target = t->partition_info.device;
 
                        resolve_link_path = true;
                } else
                        assert_not_reached();
 
                if (resolve_link_path && root) {
                        r = chase(link_path, root, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT|CHASE_TRIGGER_AUTOFS, &resolved, NULL);
                        if (r < 0)
                                return log_error_errno(r, "Failed to resolve current symlink path '%s': %m", link_path);
 
                        link_path = resolved;
                }
 
                if (link_target) {
                        r = path_extract_directory(link_path, &parent);
                        if (r < 0)
                                return log_error_errno(r, "Failed to extract directory of target path '%s': %m", link_path);
 
                        r = path_make_relative(parent, link_target, &relative);
                        if (r < 0)
                                return log_error_errno(r, "Failed to make symlink path '%s' relative to '%s': %m", link_target, parent);
 
                        r = mkdir_parents(link_path, 0755);
                        if (r < 0)
                                return log_error_errno(r, "Failed to create directory for current symlink '%s': %m", link_path);
 
                        r = symlink_atomic(relative, link_path);
                        if (r < 0)
                                return log_error_errno(r, "Failed to update current symlink '%s' %s '%s': %m",
                                                       link_path,
                                                       glyph(GLYPH_ARROW_RIGHT),
                                                       relative);
 
                        log_info("Updated symlink '%s' %s '%s'.",
                                 link_path, glyph(GLYPH_ARROW_RIGHT), relative);
                }
        }
 
        return 0;
}