HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/sysext/sysext.c
Git blob: e31d38d83f0ebe3c4643975d7ec98aa1f9102715
Lines 1–1000 of 3,321
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <linux/loop.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/mount.h>
#include <unistd.h>
#include "sd-json.h"
#include "sd-varlink.h"
#include "argv-util.h"
#include "blkid-util.h"
#include "blockdev-util.h"
#include "build.h"
#include "bus-common-errors.h"
#include "bus-locator.h"
#include "bus-polkit.h"
#include "bus-unit-util.h"
#include "bus-util.h"
#include "bus-wait-for-jobs.h"
#include "capability-util.h"
#include "chase.h"
#include "conf-parser.h"
#include "cryptsetup-util.h"
#include "devnum-util.h"
#include "discover-image.h"
#include "dissect-image.h"
#include "dlopen-note.h"
#include "env-util.h"
#include "errno-util.h"
#include "escape.h"
#include "extension-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-table.h"
#include "fs-util.h"
#include "hashmap.h"
#include "image-policy.h"
#include "initrd-util.h"
#include "label-util.h" /* IWYU pragma: keep */
#include "libmount-util.h"
#include "log.h"
#include "loop-util.h"
#include "main-func.h"
#include "mkdir.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "os-util.h"
#include "pager.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-util.h"
#include "pidref.h"
#include "proc-cmdline.h"
#include "process-util.h"
#include "rm-rf.h"
#include "runtime-scope.h"
#include "selinux-util.h"
#include "set.h"
#include "sort-util.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "time-util.h"
#include "unit-name.h"
#include "varlink-io.systemd.SysUpdate.Notify.h"
#include "varlink-io.systemd.sysext.h"
#include "varlink-util.h"
#include "verbs.h"
typedef enum MutableMode {
MUTABLE_NO,
MUTABLE_YES,
MUTABLE_AUTO,
MUTABLE_IMPORT,
MUTABLE_EPHEMERAL,
MUTABLE_EPHEMERAL_IMPORT,
_MUTABLE_MAX,
_MUTABLE_INVALID = -EINVAL,
} MutableMode;
static const char* const mutable_mode_table[_MUTABLE_MAX] = {
[MUTABLE_NO] = "no",
[MUTABLE_YES] = "yes",
[MUTABLE_AUTO] = "auto",
[MUTABLE_IMPORT] = "import",
[MUTABLE_EPHEMERAL] = "ephemeral",
[MUTABLE_EPHEMERAL_IMPORT] = "ephemeral-import",
};
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(mutable_mode, MutableMode, MUTABLE_YES);
enum {
MERGE_NOTHING_FOUND,
MERGE_MOUNTED,
MERGE_SKIP_REFRESH,
};
enum {
MERGE_EXIT_NOTHING_FOUND = 123,
MERGE_EXIT_SKIP_REFRESH = 124,
};
static char *arg_root = NULL;
static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
static PagerFlags arg_pager_flags = 0;
static bool arg_legend = true;
static bool arg_force = false;
static bool arg_no_reload = false;
static bool arg_always_refresh = false;
static int arg_noexec = -1;
static ImagePolicy *arg_image_policy = NULL;
static bool arg_image_policy_argv_set = false;
static bool arg_varlink = false;
static MutableMode arg_mutable = MUTABLE_NO;
static bool arg_mutable_argv_set = false;
/* Is set to IMAGE_CONFEXT when systemd is called with the confext functionality instead of the default */
static ImageClass arg_image_class = IMAGE_SYSEXT;
#define MUTABLE_EXTENSIONS_BASE_DIR "/var/lib/extensions.mutable"
/* redirect_dir=on and noatime prevent unnecessary upcopies, metacopy=off prevents broken
* files from partial upcopies after umount, index=off allows reuse of the upper/work dirs */
#define MUTABLE_EXTENSIONS_MOUNT_OPTIONS "redirect_dir=on,noatime,metacopy=off,index=off"
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
COMMAND(
"systemd-sysext\0",
"Merge system extension images into /usr/ and /opt/.",
.man_pages = "systemd-sysext(8)\0",
.flags = COMMAND_VERBS_SHARED,
.pager_flags = &arg_pager_flags,
);
COMMAND(
"systemd-confext\0",
"Merge configuration extension images into /etc/.",
.man_pages = "systemd-confext(8)\0",
.flags = COMMAND_VERBS_SHARED,
.pager_flags = &arg_pager_flags,
);
/* Helper struct for naming simplicity and reusability */
static const struct {
const char *short_identifier;
const char *short_identifier_plural;
const char *polkit_rw_action_id;
const char *polkit_ro_action_id;
const char *dot_directory_name;
const char *directory_name;
const char *level_env;
const char *scope_env;
const char *name_env;
const char *mode_env;
const char *opts_env;
const ImagePolicy *default_image_policy;
unsigned long default_mount_flags;
} image_class_info[_IMAGE_CLASS_MAX] = {
[IMAGE_SYSEXT] = {
.short_identifier = "sysext",
.short_identifier_plural = "extensions",
.polkit_rw_action_id = "io.systemd.sysext.manage",
.polkit_ro_action_id = "io.systemd.sysext.read",
.dot_directory_name = ".systemd-sysext",
.level_env = "SYSEXT_LEVEL",
.scope_env = "SYSEXT_SCOPE",
.name_env = "SYSTEMD_SYSEXT_HIERARCHIES",
.mode_env = "SYSTEMD_SYSEXT_MUTABLE_MODE",
.opts_env = "SYSTEMD_SYSEXT_OVERLAYFS_MOUNT_OPTIONS",
.default_image_policy = &image_policy_sysext,
.default_mount_flags = MS_RDONLY|MS_NODEV,
},
[IMAGE_CONFEXT] = {
.short_identifier = "confext",
.short_identifier_plural = "confexts",
.polkit_rw_action_id = "io.systemd.confext.manage",
.polkit_ro_action_id = "io.systemd.confext.read",
.dot_directory_name = ".systemd-confext",
.level_env = "CONFEXT_LEVEL",
.scope_env = "CONFEXT_SCOPE",
.name_env = "SYSTEMD_CONFEXT_HIERARCHIES",
.mode_env = "SYSTEMD_CONFEXT_MUTABLE_MODE",
.opts_env = "SYSTEMD_CONFEXT_OVERLAYFS_MOUNT_OPTIONS",
.default_image_policy = &image_policy_confext,
.default_mount_flags = MS_RDONLY|MS_NODEV|MS_NOSUID|MS_NOEXEC,
}
};
static int parse_mutable_mode(const char *p) {
return mutable_mode_from_string(p);
}
static DEFINE_CONFIG_PARSE_ENUM(config_parse_mutable_mode, mutable_mode, MutableMode);
typedef struct Context {
ImageClass image_class;
char **hierarchies;
char *root;
bool force;
bool no_reload;
bool always_refresh;
int noexec;
MutableMode mutable;
bool mutable_set;
ImagePolicy *image_policy;
bool image_policy_set;
/* image_policy is usually borrowed from arg_image_policy. When parsed from configuration, this
* context owns it and frees it in context_done(). */
bool image_policy_owned;
const char *overlayfs_mount_options;
} Context;
#define CONTEXT_NULL \
(Context) { \
.image_class = IMAGE_SYSEXT, \
.noexec = -1, \
.mutable = MUTABLE_NO, \
}
static void context_done(Context *c) {
assert(c);
c->hierarchies = strv_free(c->hierarchies);
c->root = mfree(c->root);
if (c->image_policy_owned)
c->image_policy = image_policy_free(c->image_policy);
}
static void parse_env_image_class_config(Context *c) {
const char *env_var;
int r;
assert(c);
env_var = secure_getenv(image_class_info[c->image_class].mode_env);
if (env_var) {
r = parse_mutable_mode(env_var);
if (r < 0)
log_warning("Failed to parse %s environment variable value '%s'. Ignoring.",
image_class_info[c->image_class].mode_env, env_var);
else {
c->mutable = r;
c->mutable_set = true;
}
}
env_var = secure_getenv(image_class_info[c->image_class].opts_env);
if (env_var)
c->overlayfs_mount_options = env_var;
}
static int parse_config_file(Context *c) {
_cleanup_(image_policy_freep) ImagePolicy *config_image_policy = NULL;
MutableMode config_mutable = MUTABLE_NO;
const char *section, *sections;
_cleanup_free_ char *config_file = NULL;
int r;
assert(c);
section = c->image_class == IMAGE_SYSEXT ? "SysExt" : "ConfExt";
sections = c->image_class == IMAGE_SYSEXT ? "SysExt\0" : "ConfExt\0";
const ConfigTableItem items[] = {
{ section, "Mutable", config_parse_mutable_mode, 0, &config_mutable },
{ section, "ImagePolicy", config_parse_image_policy, 0, &config_image_policy },
{}
};
config_file = strjoin("systemd/", image_class_info[c->image_class].short_identifier, ".conf");
if (!config_file)
return log_oom();
r = config_parse_standard_file_with_dropins_full(
c->root,
/* root_fd= */ -EBADF,
config_file,
sections,
config_item_table_lookup, items,
CONFIG_PARSE_WARN,
/* userdata= */ NULL,
/* ret_stats_by_path= */ NULL,
/* ret_dropin_files= */ NULL);
if (r < 0)
return r;
/* Configuration has the lowest priority, so only fill in values that neither the environment nor
* argv initialized already. */
if (!c->mutable_set) {
c->mutable = config_mutable;
c->mutable_set = true;
}
if (!c->image_policy_set) {
c->image_policy = TAKE_PTR(config_image_policy);
c->image_policy_set = true;
c->image_policy_owned = true;
}
return 0;
}
static int context_from_cmdline(Context *ret, ImageClass image_class) {
_cleanup_(context_done) Context c = CONTEXT_NULL;
int r;
assert(ret);
/* Start with command-line settings shared by both image classes. Class-specific environment and
* configuration are applied below, with argv values explicitly overriding both. */
c.image_class = image_class;
c.force = arg_force;
c.no_reload = arg_no_reload;
c.always_refresh = arg_always_refresh;
c.noexec = arg_noexec;
if (arg_root && strdup_to(&c.root, arg_root) < 0)
return log_oom();
r = parse_env_extension_hierarchies(&c.hierarchies, image_class_info[image_class].name_env);
if (r < 0)
return log_error_errno(r, "Failed to determine %s hierarchies: %m", image_class_info[image_class].short_identifier);
parse_env_image_class_config(&c);
if (arg_mutable_argv_set) {
c.mutable = arg_mutable;
c.mutable_set = true;
}
if (arg_image_policy_argv_set) {
c.image_policy = arg_image_policy;
c.image_policy_set = true;
c.image_policy_owned = false;
}
r = parse_config_file(&c);
if (r < 0)
log_warning_errno(r, "Failed to parse %s config file, ignoring: %m", image_class_info[image_class].short_identifier);
*ret = TAKE_GENERIC(c, Context, CONTEXT_NULL);
return 0;
}
static int is_our_mount_point(
ImageClass image_class,
const char *p) {
_cleanup_free_ char *buf = NULL, *f = NULL;
struct stat st;
dev_t dev;
int r;
assert(p);
r = path_is_mount_point(p);
if (r == -ENOENT) {
log_debug_errno(r, "Hierarchy '%s' doesn't exist.", p);
return false;
}
if (r < 0)
return log_error_errno(r, "Failed to determine whether '%s' is a mount point: %m", p);
if (r == 0) {
log_debug("Hierarchy '%s' is not a mount point, skipping.", p);
return false;
}
/* So we know now that it's a mount point. Now let's check if it's one of ours, so that we don't
* accidentally unmount the user's own /usr/ but just the mounts we established ourselves. We do this
* check by looking into the metadata directory we place in merged mounts: if the file
* ../dev contains the major/minor device pair of the mount we have a good reason to
* believe this is one of our mounts. This thorough check has the benefit that we aren't easily
* confused if people tar up one of our merged trees and untar them elsewhere where we might mistake
* them for a live sysext tree. */
f = path_join(p, image_class_info[image_class].dot_directory_name, "dev");
if (!f)
return log_oom();
r = read_one_line_file(f, &buf);
if (r == -ENOENT) {
log_debug("Hierarchy '%s' does not carry a %s/dev file, not a merged tree.", p, image_class_info[image_class].dot_directory_name);
return false;
}
if (r < 0)
return log_error_errno(r, "Failed to determine whether hierarchy '%s' contains '%s/dev': %m", p, image_class_info[image_class].dot_directory_name);
r = parse_devnum(buf, &dev);
if (r < 0)
return log_error_errno(r, "Failed to parse device major/minor stored in '%s/dev' file on '%s': %m", image_class_info[image_class].dot_directory_name, p);
if (lstat(p, &st) < 0)
return log_error_errno(errno, "Failed to stat %s: %m", p);
if (st.st_dev != dev) {
log_debug("Hierarchy '%s' reports a different device major/minor than what we are seeing, assuming offline copy.", p);
return false;
}
return true;
}
static int split_unit_string(const char *s, const char *field, const char *extension, Set **units) {
_cleanup_strv_free_ char **split = NULL;
int r;
assert(field);
assert(extension);
assert(units);
if (isempty(s))
return 0;
split = strv_split(s, /* separators= whitespace */ NULL);
if (!split)
return log_oom();
STRV_FOREACH(u, split) {
if (!unit_name_is_valid(*u, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
log_warning("Invalid unit name '%s' in %s= of %s, ignoring.", *u, field, extension);
continue;
}
r = set_put_strdup(units, *u);
if (r < 0)
return log_oom();
}
return 0;
}
static int get_extension_release_metadata(
const Context *c,
bool *ret_need_reload,
Set **ret_restart_units,
Set **ret_reload_or_restart_units) {
/* Parse the mounted images to find out if we need to reload the daemon, and which units to
* restart or reload-or-restart afterwards. */
_cleanup_set_free_ Set *restart_units = NULL, *reload_or_restart_units = NULL;
bool need_to_reload = false;
int r;
assert(c);
if (c->no_reload || !isempty(c->root)) {
/* With --root= we'd be talking to the host service manager about extensions merged
* into a foreign root, which is never what we want. */
if (ret_need_reload)
*ret_need_reload = false;
if (ret_restart_units)
*ret_restart_units = NULL;
if (ret_reload_or_restart_units)
*ret_reload_or_restart_units = NULL;
return 0;
}
STRV_FOREACH(p, c->hierarchies) {
_cleanup_free_ char *f = NULL, *buf = NULL, *resolved = NULL;
_cleanup_strv_free_ char **mounted_extensions = 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) {
log_warning_errno(r, "Failed to resolve path to hierarchy '%s%s': %m, ignoring.", strempty(c->root), *p);
continue;
}
r = is_our_mount_point(c->image_class, resolved);
if (r < 0)
return r;
if (!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);
mounted_extensions = strv_split_newlines(buf);
if (!mounted_extensions)
return log_oom();
STRV_FOREACH(extension, mounted_extensions) {
_cleanup_strv_free_ char **extension_release = NULL;
const char *value;
r = load_extension_release_pairs(c->root, c->image_class, *extension, /* relax_extension_release_check= */ true, &extension_release);
if (r < 0) {
log_debug_errno(r, "Failed to parse extension-release metadata of %s, ignoring: %m", *extension);
continue;
}
value = strv_env_pairs_get(extension_release, "EXTENSION_RELOAD_MANAGER");
if (!isempty(value)) {
int b = parse_boolean(value);
if (b < 0)
log_warning_errno(b, "Failed to parse EXTENSION_RELOAD_MANAGER= of %s, ignoring: %m", *extension);
else if (b)
need_to_reload = true;
}
if (ret_restart_units) {
value = strv_env_pairs_get(extension_release, "EXTENSION_RESTART_UNITS");
r = split_unit_string(value, "EXTENSION_RESTART_UNITS", *extension, &restart_units);
if (r < 0)
return r;
if (!isempty(value))
/* Listing units to restart implies a manager reload because a unit
* shipped (and later removed) by the extension would otherwise not
* be visible to the manager when RestartUnit/StopUnit is issued. */
need_to_reload = true;
}
if (ret_reload_or_restart_units) {
value = strv_env_pairs_get(extension_release, "EXTENSION_RELOAD_OR_RESTART_UNITS");
r = split_unit_string(value, "EXTENSION_RELOAD_OR_RESTART_UNITS", *extension, &reload_or_restart_units);
if (r < 0)
return r;
if (!isempty(value))
need_to_reload = true;
}
}
}
/* If a unit is listed in both, restart takes precedence over reload-or-restart. */
const char *u;
SET_FOREACH(u, restart_units)
free(set_remove(reload_or_restart_units, u));
if (ret_need_reload)
*ret_need_reload = need_to_reload;
if (ret_restart_units)
*ret_restart_units = TAKE_PTR(restart_units);
if (ret_reload_or_restart_units)
*ret_reload_or_restart_units = TAKE_PTR(reload_or_restart_units);
return 0;
}
static int move_submounts(const char *src, const char *dst) {
SubMount *submounts = NULL;
size_t n_submounts = 0;
int r;
assert(src);
assert(dst);
CLEANUP_ARRAY(submounts, n_submounts, sub_mount_array_free);
r = get_sub_mounts(src, &submounts, &n_submounts);
if (r < 0)
return log_error_errno(r, "Failed to get submounts for %s: %m", src);
FOREACH_ARRAY(m, submounts, n_submounts) {
_cleanup_free_ char *t = NULL;
const char *suffix;
struct stat st;
assert_se(suffix = path_startswith(m->path, src));
if (fstat(m->mount_fd, &st) < 0)
return log_error_errno(errno, "Failed to stat %s: %m", m->path);
t = path_join(dst, suffix);
if (!t)
return log_oom();
_cleanup_free_ char *fn = NULL;
_cleanup_close_ int fd = -EBADF;
r = chase(t, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755, &fn, &fd);
if (r < 0)
return log_error_errno(r, "Failed to create and pin parent directory of %s: %m", t);
r = make_mount_point_inode_from_mode(fd, fn, st.st_mode, 0755);
if (r < 0 && r != -EEXIST)
return log_error_errno(r, "Failed to create mountpoint %s: %m", t);
_cleanup_close_ int child_fd = openat(fd, fn, O_PATH|O_CLOEXEC);
if (child_fd < 0)
return log_error_errno(errno, "Failed to pin mountpoint %s: %m", t);
/* Instead of a bind mount we attach the detached clone produced by
* open_tree_attr_with_fallback() from get_sub_mounts() because that has no propagation
* relationship with the original anymore and the MNT_DETACH below won't propagate for
* nested mounts. */
r = RET_NERRNO(move_mount(m->mount_fd, "", child_fd, "", MOVE_MOUNT_F_EMPTY_PATH|MOVE_MOUNT_T_EMPTY_PATH));
if (r < 0)
return log_error_errno(r, "Failed to move mount '%s' to '%s': %m", m->path, t);
(void) umount_verbose(LOG_WARNING, m->path, MNT_DETACH);
}
return 0;
}
static int daemon_reload(void) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
int r;
r = bus_connect_system_systemd(&bus);
if (r < 0)
return log_error_errno(r, "Failed to get D-Bus connection: %m");
return bus_service_manager_reload(bus);
}
static int dispatch_unit_method(sd_bus *bus, BusWaitForJobs *w, Set *units, const char *method) {
const char *unit;
int r;
assert(bus);
assert(w);
assert(method);
/* Issue the given method for each unit and wait for the jobs to complete. Fall back to StopUnit
* when the call reports that the unit's file is gone, e.g., on unmerge when the unit was part of
* the extension, because otherwise the running service is leaked. */
SET_FOREACH(unit, units) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
const char *m = method, *job;
r = bus_call_method(bus, bus_systemd_mgr, m, &error, &reply, "ss", unit, "replace");
if (r < 0 && sd_bus_error_has_names(&error, BUS_ERROR_NO_SUCH_UNIT, BUS_ERROR_LOAD_FAILED)) {
sd_bus_error_free(&error);
m = "StopUnit";
r = bus_call_method(bus, bus_systemd_mgr, m, &error, &reply, "ss", unit, "replace");
if (r < 0 && sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT)) {
log_debug("Unit '%s' is already gone, nothing to stop.", unit);
continue;
}
}
if (r < 0) {
log_warning("Failed to %s unit '%s': %s", m, unit, bus_error_message(&error, r));
continue;
}
r = sd_bus_message_read(reply, "o", &job);
if (r < 0)
return bus_log_parse_error(r);
r = bus_wait_for_jobs_one(w, job, BUS_WAIT_JOBS_LOG_ERROR, /* extra_args= */ NULL);
if (r < 0)
log_warning_errno(r, "Failed to wait for %s job of unit '%s', ignoring: %m", m, unit);
}
return 0;
}
static int restart_units(Set *restart_units, Set *reload_or_restart_units) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
_cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
int r;
if (set_isempty(restart_units) && set_isempty(reload_or_restart_units))
return 0;
r = bus_connect_system_systemd(&bus);
if (r < 0)
return log_error_errno(r, "Failed to get D-Bus connection: %m");
r = bus_wait_for_jobs_new(bus, &w);
if (r < 0)
return log_error_errno(r, "Failed to set up job watcher: %m");
r = dispatch_unit_method(bus, w, restart_units, "RestartUnit");
if (r < 0)
return r;
r = dispatch_unit_method(bus, w, reload_or_restart_units, "ReloadOrRestartUnit");
if (r < 0)
return r;
return 0;
}
static int append_overlayfs_path_option(
char **options,
const char *separator,
const char *option,
const char *path) {
_cleanup_free_ char *escaped = NULL;
assert(options);
assert(separator);
assert(path);
escaped = shell_escape(path, ",:");
if (!escaped)
return log_oom();
if (option) {
if (!strextend(options, separator, option, "=", escaped))
return log_oom();
} else if (!strextend(options, separator, escaped))
return log_oom();
return 0;
}
static int mount_overlayfs(
ImageClass image_class,
int noexec,
const char *where,
char **layers,
const char *upper_dir,
const char *work_dir,
const char *mount_options) {
_cleanup_free_ char *options = NULL;
bool separator = false;
unsigned long flags;
int r;
assert(where);
assert((upper_dir && work_dir) || (!upper_dir && !work_dir));
options = strdup("lowerdir=");
if (!options)
return log_oom();
STRV_FOREACH(l, layers) {
r = append_overlayfs_path_option(&options, separator ? ":" : "", NULL, *l);
if (r < 0)
return r;
separator = true;
}
flags = image_class_info[image_class].default_mount_flags;
if (noexec >= 0)
SET_FLAG(flags, MS_NOEXEC, noexec);
if (upper_dir && work_dir) {
r = append_overlayfs_path_option(&options, ",", "upperdir", upper_dir);
if (r < 0)
return r;
flags &= ~MS_RDONLY;
r = append_overlayfs_path_option(&options, ",", "workdir", work_dir);
if (r < 0)
return r;
if (!mount_options)
mount_options = MUTABLE_EXTENSIONS_MOUNT_OPTIONS;
}
if (!isempty(mount_options) && !strextend(&options, ",", mount_options))
return log_oom();
/* Now mount the actual overlayfs */
r = mount_nofollow_verbose(LOG_ERR, image_class_info[image_class].short_identifier, where, "overlay", flags, options);
if (r < 0)
return r;
return 0;
}
static char *hierarchy_as_single_path_component(const char *hierarchy) {
/* We normally expect hierarchy to be /usr, /opt or /etc, but for debugging purposes the hierarchy
* could very well be like /foo/bar/baz/. So for a given hierarchy we generate a directory name by
* stripping the leading and trailing separators and replacing the rest of separators with dots. This
* makes the generated name to be the same for /foo/bar/baz and for /foo/bar.baz, but, again,
* specifying a different hierarchy is a debugging feature, so non-unique mapping should not be an
* issue in general case. */
const char *stripped = hierarchy;
_cleanup_free_ char *dir_name = NULL;
assert(hierarchy);
stripped += strspn(stripped, "/");
dir_name = strdup(stripped);
if (!dir_name)
return NULL;
delete_trailing_chars(dir_name, "/");
string_replace_char(dir_name, '/', '.');
return TAKE_PTR(dir_name);
}
static int paths_on_same_fs(const char *path1, const char *path2) {
struct stat st1, st2;
assert(path1);
assert(path2);
if (stat(path1, &st1) < 0)
return log_error_errno(errno, "Failed to stat '%s': %m", path1);
if (stat(path2, &st2) < 0)
return log_error_errno(errno, "Failed to stat '%s': %m", path2);
return st1.st_dev == st2.st_dev;
}
static int work_dir_for_hierarchy(
const char *hierarchy,
const char *resolved_upper_dir,
char **ret_work_dir) {
_cleanup_free_ char *parent = NULL;
int r;
assert(hierarchy);
assert(resolved_upper_dir);
assert(ret_work_dir);
r = path_extract_directory(resolved_upper_dir, &parent);
if (r < 0)
return log_error_errno(r, "Failed to get parent directory of upperdir '%s': %m", resolved_upper_dir);
/* TODO: paths_in_same_superblock? partition? device? */
r = paths_on_same_fs(resolved_upper_dir, parent);
if (r < 0)
return r;
if (!r)
return log_error_errno(SYNTHETIC_ERRNO(EXDEV), "Unable to find a suitable workdir location for upperdir '%s' for host hierarchy '%s' - parent directory of the upperdir is in a different filesystem", resolved_upper_dir, hierarchy);
_cleanup_free_ char *f = NULL, *dir_name = NULL;
f = hierarchy_as_single_path_component(hierarchy);
if (!f)
return log_oom();
dir_name = strjoin(".systemd-", f, "-workdir");
if (!dir_name)
return log_oom();
free(f);
f = path_join(parent, dir_name);
if (!f)
return log_oom();
*ret_work_dir = TAKE_PTR(f);
return 0;
}
typedef struct OverlayFSPaths {
char *hierarchy;
mode_t hierarchy_mode;
char *resolved_hierarchy;
char *resolved_mutable_directory;
/* NULL if merged fs is read-only */
char *upper_dir;
/* NULL if merged fs is read-only */
char *work_dir;
/* lowest index is top lowerdir, highest index is bottom lowerdir */
char **lower_dirs;
} OverlayFSPaths;
static OverlayFSPaths *overlayfs_paths_free(OverlayFSPaths *op) {
if (!op)
return NULL;
free(op->hierarchy);
free(op->resolved_hierarchy);
free(op->resolved_mutable_directory);
free(op->upper_dir);
free(op->work_dir);
strv_free(op->lower_dirs);
return mfree(op);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(OverlayFSPaths *, overlayfs_paths_free);
static int parse_image_class_parameter(sd_varlink *link, const char *value, ImageClass *image_class) {
ImageClass c;
assert(link);
assert(image_class);
if (!value)
return 0;
c = image_class_from_string(value);
if (!IN_SET(c, IMAGE_SYSEXT, IMAGE_CONFEXT))
return sd_varlink_error_invalid_parameter_name(link, "class");
*image_class = c;
return 0;
}
static int resolve_hierarchy(const Context *c, const char *hierarchy, char **ret_resolved_hierarchy) {
_cleanup_free_ char *resolved_path = NULL;
int r;
assert(c);
assert(hierarchy);
assert(ret_resolved_hierarchy);
r = chase(hierarchy, c->root, CHASE_PREFIX_ROOT, &resolved_path, NULL);
if (r < 0 && r != -ENOENT)
return log_error_errno(r, "Failed to resolve hierarchy '%s': %m", hierarchy);
*ret_resolved_hierarchy = TAKE_PTR(resolved_path);
return 0;
}
static int mutable_directory_mode_matches_hierarchy(
const char *root_or_null,
const char *path,
mode_t hierarchy_mode) {
_cleanup_free_ char *path_in_root = NULL;
struct stat st;
mode_t actual_mode;
assert(path);
path_in_root = path_join(root_or_null, path);
if (!path_in_root)
return log_oom();
if (stat(path_in_root, &st) < 0) {
if (errno == ENOENT)
return 0;
return log_error_errno(errno, "Failed to stat mutable directory '%s': %m", path_in_root);
}
actual_mode = st.st_mode & 0777;
if (actual_mode != hierarchy_mode)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Mutable directory '%s' has mode %04o, ought to have mode %04o", path_in_root, actual_mode, hierarchy_mode);
return 0;
}
static int resolve_mutable_directory(
const Context *c,
const char *hierarchy,
mode_t hierarchy_mode,
const char *workspace,
char **ret_resolved_mutable_directory) {
_cleanup_free_ char *path = NULL, *resolved_path = NULL, *dir_name = NULL;
const char *root, *base = MUTABLE_EXTENSIONS_BASE_DIR;
int r;
assert(c);
assert(hierarchy);
assert(ret_resolved_mutable_directory);
root = c->root;
if (c->mutable == MUTABLE_NO) {
log_debug("Mutability for hierarchy '%s' is disabled, not resolving mutable directory.", hierarchy);
*ret_resolved_mutable_directory = NULL;
return 0;
}
if (IN_SET(c->mutable, MUTABLE_EPHEMERAL, MUTABLE_EPHEMERAL_IMPORT)) {
/* We create mutable directory inside the temporary tmpfs workspace, which is a fixed
* location that ignores the configured root. */
root = NULL;
base = workspace;
}
dir_name = hierarchy_as_single_path_component(hierarchy);
if (!dir_name)
return log_oom();
path = path_join(base, dir_name);
if (!path)
return log_oom();
if (IN_SET(c->mutable, MUTABLE_YES, MUTABLE_AUTO)) {
/* If there already is a mutable directory, check if its mode matches hierarchy. Merged
* hierarchy will have the same mode as the mutable directory, so we want no surprising mode
* changes here. */
r = mutable_directory_mode_matches_hierarchy(root, path, hierarchy_mode);
if (r < 0)
return r;
}
if (IN_SET(c->mutable, MUTABLE_YES, MUTABLE_EPHEMERAL, MUTABLE_EPHEMERAL_IMPORT)) {
_cleanup_close_ int path_fd = -EBADF, chmod_fd = -EBADF;
/* This also creates, e.g., /var/lib/extensions.mutable/usr if needed and all parent
* directories plus it also works when the last part is a symlink to the real /usr but we
* can't use chase_and_open here because it does not behave the same. */
r = chase(path, root, CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY|CHASE_PREFIX_ROOT, /* ret_path */ NULL, &path_fd);
if (r < 0)
return log_error_errno(r, "Failed to chase/create base directory '%s/%s': %m", strempty(root), skip_leading_slash(path));
chmod_fd = fd_reopen(path_fd, O_CLOEXEC|O_DIRECTORY);