HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/portable/portable.c
Git blob: 0d42a3c41aa6ccdbda76b016df825fad2759375e
Lines 2001–2720 of 2,720
}
STRV_FOREACH(e, extension_image_paths) {
_cleanup_free_ char *extension_base_name = NULL;
r = path_extract_filename(*e, &extension_base_name);
if (r < 0) {
log_debug_errno(r, "Failed to extract basename from '%s', ignoring: %m", *e);
continue;
}
r = strv_extendf(&extension_base_names, "PORTABLE_EXTENSION=%s", extension_base_name);
if (r < 0)
log_oom_debug();
if (!strextend_with_separator(&extensions_joined, ", ", *e))
log_oom_debug();
}
LOG_CONTEXT_PUSH_STRV(extension_base_names);
log_struct(LOG_INFO,
LOG_MESSAGE("Successfully %s%s '%s%s%s%s%s'",
verb,
FLAGS_SET(flags, PORTABLE_RUNTIME) ? " ephemeral" : "",
image_path,
isempty(extensions_joined) ? "" : "' and its extension(s) '",
strempty(extensions_joined),
isempty(profile) ? "" : "' using profile '",
strempty(profile)),
message_id,
LOG_ITEM("PORTABLE_ROOT=%s", strna(root_base_name)));
}
int portable_attach(
RuntimeScope scope,
sd_bus *bus,
const char *name_or_path,
char **matches,
const char *profile,
char **extension_image_paths,
const ImagePolicy *image_policy,
PortableFlags flags,
PortableChange **changes,
size_t *n_changes,
sd_bus_error *error) {
_cleanup_(image_policy_freep) ImagePolicy *pinned_root_image_policy = NULL, *pinned_ext_image_policy = NULL;
_cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL, *extension_releases = NULL;
_cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
_cleanup_hashmap_free_ Hashmap *unit_files = NULL;
_cleanup_(lookup_paths_done) LookupPaths paths = {};
_cleanup_strv_free_ char **valid_prefixes = NULL;
_cleanup_(image_unrefp) Image *image = NULL;
PortableMetadata *item;
int r;
assert(scope < _RUNTIME_SCOPE_MAX);
r = portable_profile_validate(scope, profile, error);
if (r < 0)
return r;
r = extract_image_and_extensions(
scope,
name_or_path,
matches,
extension_image_paths,
/* validate_extension= */ true,
/* relax_extension_release_check= */ FLAGS_SET(flags, PORTABLE_FORCE_EXTENSION),
image_policy,
&image,
&extension_images,
&extension_releases,
&os_release,
&unit_files,
&valid_prefixes,
&pinned_root_image_policy,
&pinned_ext_image_policy,
error);
if (r < 0)
return r;
if (valid_prefixes && !prefix_matches_compatible(matches, valid_prefixes)) {
_cleanup_free_ char *matches_joined = NULL, *extensions_joined = NULL, *valid_prefixes_joined = NULL;
matches_joined = strv_join(matches, "', '");
if (!matches_joined)
return -ENOMEM;
extensions_joined = strv_join(extension_image_paths, ", ");
if (!extensions_joined)
return -ENOMEM;
valid_prefixes_joined = strv_join(valid_prefixes, ", ");
if (!valid_prefixes_joined)
return -ENOMEM;
return sd_bus_error_setf(
error,
SD_BUS_ERROR_INVALID_ARGS,
"Selected matches '%s' are not compatible with portable service image '%s%s%s', refusing. (Acceptable prefix matches are: %s)",
matches_joined,
image->path,
isempty(extensions_joined) ? "" : "' or any of its extensions '",
strempty(extensions_joined),
valid_prefixes_joined);
}
if (hashmap_isempty(unit_files)) {
_cleanup_free_ char *extensions_joined = strv_join(extension_image_paths, ", ");
if (!extensions_joined)
return -ENOMEM;
return sd_bus_error_setf(
error,
BUS_ERROR_NO_MATCHING_UNIT_FILES,
"Couldn't find any matching unit files in image '%s%s%s', refusing.",
image->path,
isempty(extensions_joined) ? "" : "' or any of its extensions '",
strempty(extensions_joined));
}
r = lookup_paths_init(&paths, scope, /* flags= */ 0, NULL);
if (r < 0)
return r;
if (!FLAGS_SET(flags, PORTABLE_REATTACH) && !FLAGS_SET(flags, PORTABLE_FORCE_ATTACH))
HASHMAP_FOREACH(item, unit_files) {
r = unit_file_exists_full(scope, &paths, SEARCH_IGNORE_TEMPLATE, item->name, /* ret_path= */ NULL);
if (r < 0)
return sd_bus_error_set_errnof(error, r, "Failed to determine whether unit '%s' exists on the host: %m", item->name);
if (r > 0)
return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' exists on the host already, refusing.", item->name);
r = unit_file_is_active(bus, item->name, error);
if (r < 0)
return r;
if (r > 0)
return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active already, refusing.", item->name);
}
HASHMAP_FOREACH(item, unit_files) {
r = attach_unit_file(
scope,
&paths,
image->path,
image->type,
extension_images,
extension_releases,
pinned_root_image_policy,
pinned_ext_image_policy,
item,
os_release,
profile,
flags,
changes,
n_changes);
if (r < 0)
return sd_bus_error_set_errnof(error, r, "Failed to attach unit '%s': %m", item->name);
}
/* We don't care too much for the image symlink/copy, it's just a convenience thing, it's not necessary for
* proper operation otherwise. */
(void) install_image_and_extensions(scope, image, extension_images, flags, changes, n_changes);
log_portable_verb(
"attached",
"MESSAGE_ID=" SD_MESSAGE_PORTABLE_ATTACHED_STR,
image->path,
profile,
extension_images,
/* extension_image_paths= */ NULL,
flags);
return 0;
}
static int marker_matches_images(const char *marker, const char *name_or_path, char **extension_image_paths, bool match_all) {
_cleanup_strv_free_ char **root_and_extensions = NULL;
int r;
assert(marker);
assert(name_or_path);
/* If extensions were used when attaching, the marker will be a colon-separated
* list of images/paths. We enforce strict 1:1 matching, so that we are sure
* we are detaching exactly what was attached.
* For each image, starting with the root, we look for a token in the marker,
* and return a negative answer on any non-matching combination.
* If a partial match is allowed, then return immediately once it is found, otherwise
* ensure that everything matches. */
root_and_extensions = strv_new(name_or_path);
if (!root_and_extensions)
return -ENOMEM;
r = strv_extend_strv(&root_and_extensions, extension_image_paths, false);
if (r < 0)
return r;
/* Ensure the number of images passed matches the number of images listed in the marker */
while (!isempty(marker))
STRV_FOREACH(image_name_or_path, root_and_extensions) {
_cleanup_free_ char *image = NULL, *base_image = NULL, *base_image_name_or_path = NULL, *base_picked_image = NULL;
_cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
r = extract_first_word(&marker, &image, ":", EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE);
if (r < 0)
return log_debug_errno(r, "Failed to parse marker: %s", marker);
if (r == 0)
return false;
r = path_extract_image_name(image, &base_image);
if (r < 0)
return log_debug_errno(r, "Failed to extract image name from %s, ignoring: %m", image);
r = path_pick(/* root_path= */ NULL,
/* root_fd= */ AT_FDCWD,
/* dir_fd= */ AT_FDCWD,
*image_name_or_path,
pick_filter_image_any,
ELEMENTSOF(pick_filter_image_any),
PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
&result);
if (r < 0 && r != -ENOENT)
return r;
r = path_extract_image_name(*image_name_or_path, &base_image_name_or_path);
if (r < 0)
return log_debug_errno(r, "Failed to extract image name from %s, ignoring: %m", *image_name_or_path);
if (!streq(base_image, base_image_name_or_path) && result.path) {
r = path_extract_image_name(result.path, &base_picked_image);
if (r < 0)
return log_debug_errno(r, "Failed to extract image name from %s, ignoring: %m", result.path);
}
if (!streq(base_image, base_image_name_or_path) &&
!streq_ptr(base_image, base_picked_image)) {
if (match_all)
return false;
} else if (!match_all)
return true;
}
return match_all;
}
static int test_chroot_dropin(
DIR *d,
const char *where,
const char *fname,
const char *name_or_path,
char **extension_image_paths,
char **ret_marker) {
_cleanup_free_ char *line = NULL, *marker = NULL;
_cleanup_fclose_ FILE *f = NULL;
_cleanup_close_ int fd = -EBADF;
const char *p, *e, *k;
int r;
assert(d);
assert(where);
assert(fname);
/* We recognize unis created from portable images via the drop-in we created for them */
p = strjoina(fname, ".d/20-portable.conf");
fd = openat(dirfd(d), p, O_RDONLY|O_CLOEXEC);
if (fd < 0) {
if (errno == ENOENT)
return 0;
return log_debug_errno(errno, "Failed to open %s/%s: %m", where, p);
}
r = take_fdopen_unlocked(&fd, "r", &f);
if (r < 0)
return log_debug_errno(r, "Failed to convert file handle: %m");
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0)
return log_debug_errno(r, "Failed to read from %s/%s: %m", where, p);
e = startswith(line, PORTABLE_DROPIN_MARKER_BEGIN);
if (!e)
return 0;
k = endswith(e, PORTABLE_DROPIN_MARKER_END);
if (!k)
return 0;
marker = strndup(e, k - e);
if (!marker)
return -ENOMEM;
if (!name_or_path)
r = true;
else
/* When detaching we want to match exactly on all images, but when inspecting we only need
* to get the state of one component */
r = marker_matches_images(marker, name_or_path, extension_image_paths, ret_marker != NULL);
if (ret_marker)
*ret_marker = TAKE_PTR(marker);
return r;
}
static int portable_attached_dirent_name(
const struct dirent *de,
char **ret_unit_name,
bool *ret_dropin) {
_cleanup_free_ char *unit_name = NULL;
const char *dropin_suffix;
assert(de);
assert(ret_unit_name);
/* When a portable service is enabled with "portablectl --copy=symlink --enable --now attach",
* and is disabled with "portablectl --enable --now detach", which calls DisableUnitFilesWithFlags
* DBus method, the main unit file is removed, but its drop-ins are not. Hence, we need to list both
* main unit files and drop-in directories (without the main unit files). */
dropin_suffix = endswith(de->d_name, ".d");
if (dropin_suffix)
unit_name = strndup(de->d_name, dropin_suffix - de->d_name);
else
unit_name = strdup(de->d_name);
if (!unit_name)
return -ENOMEM;
if (!unit_name_is_valid(unit_name, UNIT_NAME_ANY))
return 0;
if (dropin_suffix ? !IN_SET(de->d_type, DT_LNK, DT_DIR) : !IN_SET(de->d_type, DT_LNK, DT_REG))
return 0;
*ret_unit_name = TAKE_PTR(unit_name);
if (ret_dropin)
*ret_dropin = dropin_suffix != NULL;
return 1;
}
int portable_detach(
RuntimeScope scope,
sd_bus *bus,
const char *name_or_path,
char **extension_image_paths,
PortableFlags flags,
PortableChange **changes,
size_t *n_changes,
sd_bus_error *error) {
_cleanup_(lookup_paths_done) LookupPaths paths = {};
_cleanup_set_free_ Set *unit_files = NULL, *markers = NULL;
_cleanup_free_ char *extensions = NULL;
_cleanup_closedir_ DIR *d = NULL;
const char *where, *item;
int r, ret = 0;
assert(scope < _RUNTIME_SCOPE_MAX);
assert(name_or_path);
r = lookup_paths_init(&paths, scope, /* flags= */ 0, NULL);
if (r < 0)
return r;
where = attached_path(&paths, flags);
d = opendir(where);
if (!d) {
if (errno == ENOENT)
goto not_found;
return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
}
FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
_cleanup_free_ char *marker = NULL, *unit_name = NULL;
r = portable_attached_dirent_name(de, &unit_name, /* ret_dropin= */ NULL);
if (r < 0)
return r;
if (r == 0)
continue;
/* Filter out duplicates */
if (set_contains(unit_files, unit_name))
continue;
r = test_chroot_dropin(d, where, unit_name, name_or_path, extension_image_paths, &marker);
if (r < 0)
return r;
if (r == 0)
continue;
if (!FLAGS_SET(flags, PORTABLE_REATTACH) && !FLAGS_SET(flags, PORTABLE_FORCE_ATTACH)) {
r = unit_file_is_active(bus, unit_name, error);
if (r < 0)
return r;
if (r > 0)
return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active, can't detach.", unit_name);
}
r = set_ensure_consume(&unit_files, &string_hash_ops_free, TAKE_PTR(unit_name));
if (r < 0)
return log_oom_debug();
for (const char *p = marker;;) {
_cleanup_free_ char *image = NULL;
r = extract_first_word(&p, &image, ":", EXTRACT_UNESCAPE_SEPARATORS|EXTRACT_RETAIN_ESCAPE);
if (r < 0)
return log_debug_errno(r, "Failed to parse marker: %s", p);
if (r == 0)
break;
if (path_is_absolute(image) && !image_in_search_path(scope, IMAGE_PORTABLE, NULL, image)) {
r = set_ensure_consume(&markers, &path_hash_ops_free, TAKE_PTR(image));
if (r < 0)
return r;
}
}
}
if (set_isempty(unit_files))
goto not_found;
SET_FOREACH(item, unit_files) {
_cleanup_free_ char *md = NULL;
if (unlinkat(dirfd(d), item, 0) < 0) {
log_debug_errno(errno, "Can't remove unit file %s/%s: %m", where, item);
if (errno != ENOENT && ret >= 0)
ret = -errno;
} else
portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, item, NULL);
FOREACH_STRING(suffix, ".d/10-profile.conf", ".d/20-portable.conf") {
_cleanup_free_ char *dropin = NULL;
dropin = strjoin(item, suffix);
if (!dropin)
return -ENOMEM;
if (unlinkat(dirfd(d), dropin, 0) < 0) {
log_debug_errno(errno, "Can't remove drop-in %s/%s: %m", where, dropin);
if (errno != ENOENT && ret >= 0)
ret = -errno;
} else
portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, dropin, NULL);
}
md = strjoin(item, ".d");
if (!md)
return -ENOMEM;
if (unlinkat(dirfd(d), md, AT_REMOVEDIR) < 0) {
log_debug_errno(errno, "Can't remove drop-in directory %s/%s: %m", where, md);
if (errno != ENOENT && ret >= 0)
ret = -errno;
} else
portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, md, NULL);
}
/* Now, also drop any image symlink or copy, for images outside of the search path */
SET_FOREACH(item, markers) {
_cleanup_free_ char *target = NULL;
r = image_target_path(scope, item, flags, &target);
if (r < 0) {
log_debug_errno(r, "Failed to determine image path for '%s', ignoring: %m", item);
continue;
}
r = rm_rf(target, REMOVE_ROOT | REMOVE_PHYSICAL | REMOVE_MISSING_OK | REMOVE_SYNCFS);
if (r < 0) {
log_debug_errno(r, "Can't remove image '%s': %m", target);
if (r != -ENOENT)
RET_GATHER(ret, r);
} else
portable_changes_add(changes, n_changes, PORTABLE_UNLINK, target, NULL);
}
/* Try to remove the unit file directory, if we can */
if (rmdir(where) >= 0)
portable_changes_add(changes, n_changes, PORTABLE_UNLINK, where, NULL);
log_portable_verb(
"detached",
"MESSAGE_ID=" SD_MESSAGE_PORTABLE_DETACHED_STR,
name_or_path,
/* profile= */ NULL,
/* extension_images= */ NULL,
extension_image_paths,
flags);
return ret;
not_found:
extensions = strv_join(extension_image_paths, ", ");
if (!extensions)
return -ENOMEM;
r = sd_bus_error_setf(error,
BUS_ERROR_NO_SUCH_UNIT,
"No unit files associated with '%s%s%s' found attached to the system. Image not attached?",
name_or_path,
isempty(extensions) ? "" : "' or any of its extensions '",
isempty(extensions) ? "" : extensions);
return log_debug_errno(r, "%s", error->message);
}
static int portable_get_state_internal(
RuntimeScope scope,
sd_bus *bus,
const char *name_or_path,
char **extension_image_paths,
PortableFlags flags,
PortableState *ret,
sd_bus_error *error) {
_cleanup_(lookup_paths_done) LookupPaths paths = {};
bool found_enabled = false, found_running = false;
_cleanup_set_free_ Set *unit_files = NULL;
_cleanup_closedir_ DIR *d = NULL;
const char *where;
int r;
assert(scope < _RUNTIME_SCOPE_MAX);
assert(name_or_path);
assert(ret);
r = lookup_paths_init(&paths, scope, /* flags= */ 0, NULL);
if (r < 0)
return r;
where = attached_path(&paths, flags);
d = opendir(where);
if (!d) {
if (errno == ENOENT) {
/* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
*ret = PORTABLE_DETACHED;
return 0;
}
return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
}
FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
_cleanup_free_ char *unit_name = NULL;
bool dropin;
r = portable_attached_dirent_name(de, &unit_name, &dropin);
if (r < 0)
return r;
if (r == 0)
continue;
/* Filter out duplicates */
if (set_contains(unit_files, unit_name))
continue;
if (dropin) {
/* If the main unit file still exists, let the regular entry handle it so that
* enabled/running state is determined from the unit file as before. */
r = RET_NERRNO(faccessat(dirfd(d), unit_name, F_OK, AT_SYMLINK_NOFOLLOW));
if (r >= 0)
continue;
if (r != -ENOENT)
return log_debug_errno(r, "Failed to check if '%s/%s' exists: %m", where, unit_name);
}
r = test_chroot_dropin(d, where, unit_name, name_or_path, extension_image_paths, NULL);
if (r < 0)
return r;
if (r == 0)
continue;
if (!dropin) {
UnitFileState state;
r = unit_file_lookup_state(scope, &paths, unit_name, &state);
if (r < 0)
return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", unit_name);
if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_LINKED_RUNTIME))
found_enabled = true;
}
r = unit_file_is_active(bus, unit_name, error);
if (r < 0)
return r;
if (r > 0)
found_running = true;
r = set_ensure_consume(&unit_files, &string_hash_ops_free, TAKE_PTR(unit_name));
if (r < 0)
return log_oom_debug();
}
*ret = found_running ? (!set_isempty(unit_files) && (flags & PORTABLE_RUNTIME) ? PORTABLE_RUNNING_RUNTIME : PORTABLE_RUNNING) :
found_enabled ? (flags & PORTABLE_RUNTIME ? PORTABLE_ENABLED_RUNTIME : PORTABLE_ENABLED) :
!set_isempty(unit_files) ? (flags & PORTABLE_RUNTIME ? PORTABLE_ATTACHED_RUNTIME : PORTABLE_ATTACHED) : PORTABLE_DETACHED;
return 0;
}
int portable_get_state(
RuntimeScope scope,
sd_bus *bus,
const char *name_or_path,
char **extension_image_paths,
PortableFlags flags,
PortableState *ret,
sd_bus_error *error) {
PortableState state;
int r;
assert(name_or_path);
assert(ret);
/* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
* the latter only if we didn't find anything in the former. */
r = portable_get_state_internal(
scope,
bus,
name_or_path,
extension_image_paths,
flags & ~PORTABLE_RUNTIME,
&state,
error);
if (r < 0)
return r;
if (state == PORTABLE_DETACHED) {
r = portable_get_state_internal(scope, bus, name_or_path, extension_image_paths, flags | PORTABLE_RUNTIME, &state, error);
if (r < 0)
return r;
}
*ret = state;
return 0;
}
int portable_get_profiles(RuntimeScope scope, char ***ret) {
_cleanup_strv_free_ char **dirs = NULL;
int r;
assert(ret);
r = portable_profile_dirs(scope, &dirs);
if (r < 0)
return r;
return conf_files_list_strv(ret, NULL, NULL, CONF_FILES_DIRECTORY|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED, (const char* const*) dirs);
}
int portable_profile_validate(RuntimeScope scope, const char *profile, sd_bus_error *reterr_error) {
_cleanup_strv_free_ char **profiles = NULL;
int r;
assert(scope < _RUNTIME_SCOPE_MAX);
if (!filename_is_valid(profile))
return sd_bus_error_setf(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "Profile name '%s' is not valid.", profile);
r = portable_get_profiles(scope, &profiles);
if (r < 0)
return sd_bus_error_set_errnof(reterr_error, r, "Failed to enumerate portable profiles: %m");
if (strv_contains(profiles, profile))
return 0;
_cleanup_free_ char *joined = strv_join(profiles, ", ");
if (!joined)
return -ENOMEM;
return sd_bus_error_setf(
reterr_error,
SD_BUS_ERROR_INVALID_ARGS,
"Profile '%s' does not exist, refusing.%s%s%s",
profile,
isempty(joined) ? "" : " (Available profiles are: ",
strempty(joined),
isempty(joined) ? "" : ")");
}
static const char* const portable_change_type_table[_PORTABLE_CHANGE_TYPE_MAX] = {
[PORTABLE_COPY] = "copy",
[PORTABLE_MKDIR] = "mkdir",
[PORTABLE_SYMLINK] = "symlink",
[PORTABLE_UNLINK] = "unlink",
[PORTABLE_WRITE] = "write",
};
DEFINE_STRING_TABLE_LOOKUP(portable_change_type, int);
static const char* const portable_state_table[_PORTABLE_STATE_MAX] = {
[PORTABLE_DETACHED] = "detached",
[PORTABLE_ATTACHED] = "attached",
[PORTABLE_ATTACHED_RUNTIME] = "attached-runtime",
[PORTABLE_ENABLED] = "enabled",
[PORTABLE_ENABLED_RUNTIME] = "enabled-runtime",
[PORTABLE_RUNNING] = "running",
[PORTABLE_RUNNING_RUNTIME] = "running-runtime",
};
DEFINE_STRING_TABLE_LOOKUP(portable_state, PortableState);