HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/tmpfiles/tmpfiles.c

203,319 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: c4caa0b857918b2141bedc1762e40c4e54e030a4

Lines 5001–5453 of 5,453

                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("image", "PATH", "Operate on disk image as filesystem root"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_image);
                        if (r < 0)
                                return r;
 
                        /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
                        r = exclude_default_prefixes();
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("image-policy", "POLICY", "Specify disk image dissection policy"):
                        r = parse_image_policy_argument(opts.arg, &arg_image_policy);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("replace", "PATH", "Treat arguments as replacement for PATH"):
                        if (!path_is_absolute(opts.arg))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "The argument to --replace= must be an absolute path.");
                        if (!endswith(opts.arg, ".conf"))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "The argument to --replace= must have the extension '.conf'.");
 
                        arg_replace = opts.arg;
                        break;
 
                OPTION('n', "dry-run", NULL, "Just print what would be done"):
                        arg_dry_run = true;
                        break;
 
                OPTION_LONG("inline", NULL, "Treat arguments as configuration lines"):
                        arg_inline = true;
                        break;
 
                OPTION_COMMON_NO_PAGER:
                        arg_pager_flags |= PAGER_DISABLE;
                        break;
 
                OPTION_COMMON_INTROSPECT_CLI:
                        return introspect_cli(SD_JSON_FORMAT_OFF);
                }
 
        char **args = option_parser_get_args(&opts);
        size_t n_args = option_parser_get_n_args(&opts);
 
        if (arg_operation == 0 && arg_cat_flags == CAT_CONFIG_OFF)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "You need to specify at least one of --clean, --create, --remove, or --purge.");
 
        if (FLAGS_SET(arg_operation, OPERATION_PURGE) && n_args == 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Refusing --purge without specification of a configuration file.");
 
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Option --replace= is not supported with --cat-config/--tldr.");
 
        if (arg_inline && arg_cat_flags != CAT_CONFIG_OFF)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Option --inline is not supported with --cat-config/--tldr.");
 
        if (arg_replace && n_args == 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "When --replace= is given, some configuration items must be specified.");
 
        if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Combination of --user and --root= is not supported.");
 
        if (arg_image && arg_root)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Please specify either --root= or --image=, the combination of both is not supported.");
 
        *ret_args = args;
        return 1;
}
 
static int read_config_file(
                Context *c,
                char **config_dirs,
                const char *fn,
                bool ignore_enoent,
                bool *invalid_config) {
 
        ItemArray *ia;
        int r = 0;
 
        assert(c);
        assert(fn);
 
        r = conf_file_read(arg_root, (const char**) config_dirs, fn,
                           parse_line, c, ignore_enoent, invalid_config);
        if (r <= 0)
                return r;
 
        /* we have to determine age parameter for each entry of type X */
        ORDERED_HASHMAP_FOREACH(ia, c->globs)
                FOREACH_ARRAY(i, ia->items, ia->n_items) {
                        ItemArray *ja;
                        Item *candidate_item = NULL;
 
                        if (i->type != IGNORE_DIRECTORY_PATH)
                                continue;
 
                        ORDERED_HASHMAP_FOREACH(ja, c->items)
                                FOREACH_ARRAY(j, ja->items, ja->n_items) {
                                        if (!IN_SET(j->type, CREATE_DIRECTORY,
                                                             TRUNCATE_DIRECTORY,
                                                             CREATE_SUBVOLUME,
                                                             CREATE_SUBVOLUME_INHERIT_QUOTA,
                                                             CREATE_SUBVOLUME_NEW_QUOTA))
                                                continue;
 
                                        if (path_equal(j->path, i->path)) {
                                                candidate_item = j;
                                                break;
                                        }
 
                                        if (candidate_item
                                            ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
                                            : path_startswith(i->path, j->path) != NULL)
                                                candidate_item = j;
                                }
 
                        if (candidate_item && candidate_item->age_set) {
                                i->age = candidate_item->age;
                                i->age_set = true;
                                i->age_by_file = candidate_item->age_by_file;
                                i->age_by_dir = candidate_item->age_by_dir;
                        }
                }
 
        return r;
}
 
static int parse_arguments(
                Context *c,
                char **config_dirs,
                char **args,
                bool *invalid_config) {
 
        unsigned pos = 1;
        int r;
 
        assert(c);
        assert(invalid_config);
 
        STRV_FOREACH(arg, args) {
                if (arg_inline) {
                        bool invalid_arg = false;
 
                        /* Use (argument):n, where n==1 for the first positional arg */
                        r = parse_line("(argument)", pos, *arg, &invalid_arg, c);
                        if (invalid_arg)
                                *invalid_config = true;
                        else if (r < 0)
                                return r;
                } else {
                        r = read_config_file(c, config_dirs, *arg, /* ignore_enoent= */ false, invalid_config);
                        if (r < 0)
                                return r;
                }
 
                pos++;
        }
 
        return 0;
}
 
static int read_config_files(
                Context *c,
                char **config_dirs,
                char **args,
                bool *invalid_config) {
 
        _cleanup_strv_free_ char **files = NULL;
        _cleanup_free_ char *p = NULL;
        int r;
 
        assert(c);
 
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
        if (r < 0)
                return r;
 
        STRV_FOREACH(f, files)
                if (p && path_equal(*f, p)) {
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
 
                        r = parse_arguments(c, config_dirs, args, invalid_config);
                        if (r < 0)
                                return r;
                } else
                        /* Just warn, ignore result otherwise.
                         * read_config_file() has some debug output, so no need to print anything. */
                        (void) read_config_file(c, config_dirs, *f, true, invalid_config);
 
        return 0;
}
 
static int read_credential_lines(Context *c, bool *invalid_config) {
        _cleanup_free_ char *j = NULL;
        const char *d;
        int r;
 
        assert(c);
 
        r = get_credentials_dir(&d);
        if (r == -ENXIO)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to get credentials directory: %m");
 
        j = path_join(d, "tmpfiles.extra");
        if (!j)
                return log_oom();
 
        (void) read_config_file(c, /* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
        return 0;
}
 
static int link_parent(Context *c, ItemArray *a) {
        const char *path;
        char *prefix;
        int r;
 
        assert(c);
        assert(a);
 
        /* Finds the closest "parent" item array for the specified item array. Then registers the specified
         * item array as child of it, and fills the parent in, linking them both ways. This allows us to
         * later create parents before their children, and clean up/remove children before their parents.
         */
 
        if (a->n_items <= 0)
                return 0;
 
        path = a->items[0].path;
        prefix = newa(char, strlen(path) + 1);
        PATH_FOREACH_PREFIX(prefix, path) {
                ItemArray *j;
 
                j = ordered_hashmap_get(c->items, prefix);
                if (!j)
                        j = ordered_hashmap_get(c->globs, prefix);
                if (j) {
                        r = set_ensure_put(&j->children, NULL, a);
                        if (r < 0)
                                return log_oom();
 
                        a->parent = j;
                        return 1;
                }
        }
 
        return 0;
}
 
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
                                              ItemArray, item_array_free);
 
static int run(int argc, char *argv[]) {
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
        _cleanup_strv_free_ char **config_dirs = NULL;
        _cleanup_(context_done) Context c = {};
        bool invalid_config = false;
        ItemArray *a;
        enum {
                PHASE_PURGE,
                PHASE_REMOVE_AND_CLEAN,
                PHASE_CREATE,
                _PHASE_MAX
        } phase;
        int r;
 
        LIBACL_NOTE(recommended);
        LIBBLKID_NOTE(recommended);
        LIBCRYPTSETUP_NOTE(suggested);
        LIBCRYPTO_NOTE(suggested);
        LIBMOUNT_NOTE(recommended);
        LIBSELINUX_NOTE(recommended);
 
        char **args = NULL;
        r = parse_argv(argc, argv, &args);
        if (r <= 0)
                return r;
 
        log_setup();
 
        /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
         * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
         * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
         * apparently invoke it without anyway and are surprised about the failures, let's catch this early
         * and output a nice and friendly warning. */
        if (proc_mounted() == 0)
                return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
                                       "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
                                       "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
 
        /* Descending down file system trees might take a lot of fds */
        (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
 
        switch (arg_runtime_scope) {
 
        case RUNTIME_SCOPE_USER:
                r = user_config_paths(&config_dirs);
                if (r < 0)
                        return log_error_errno(r, "Failed to initialize configuration directory list: %m");
                break;
 
        case RUNTIME_SCOPE_SYSTEM:
                config_dirs = strv_new(CONF_PATHS("tmpfiles.d"));
                if (!config_dirs)
                        return log_oom();
                break;
 
        default:
                assert_not_reached();
        }
 
        if (DEBUG_LOGGING) {
                _cleanup_free_ char *t = NULL;
 
                STRV_FOREACH(i, config_dirs) {
                        _cleanup_free_ char *j = NULL;
 
                        j = path_join(arg_root, *i);
                        if (!j)
                                return log_oom();
 
                        if (!strextend(&t, "\n\t", j))
                                return log_oom();
                }
 
                log_debug("Looking for configuration files in (higher priority first):%s", t);
        }
 
        if (arg_cat_flags != CAT_CONFIG_OFF)
                return cat_config(config_dirs, args);
 
        if (should_bypass("SYSTEMD_TMPFILES"))
                return 0;
 
        umask(0022);
 
        r = mac_init();
        if (r < 0)
                return r;
 
        if (arg_image) {
                assert(!arg_root);
 
                r = mount_image_privately_interactively(
                                arg_image,
                                arg_image_policy,
                                DISSECT_IMAGE_GENERIC_ROOT |
                                DISSECT_IMAGE_REQUIRE_ROOT |
                                DISSECT_IMAGE_VALIDATE_OS |
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
                                DISSECT_IMAGE_FSCK |
                                DISSECT_IMAGE_GROWFS |
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
                                &mounted_dir,
                                /* ret_dir_fd= */ NULL,
                                &loop_device);
                if (r < 0)
                        return r;
 
                arg_root = strdup(mounted_dir);
                if (!arg_root)
                        return log_oom();
        }
 
        r = mac_label_context_new(arg_root, &arg_label_context);
        if (r < 0)
                return log_error_errno(r, "Failed to initialize label context for root '%s': %m", arg_root);
 
        c.items = ordered_hashmap_new(&item_array_hash_ops);
        c.globs = ordered_hashmap_new(&item_array_hash_ops);
        if (!c.items || !c.globs)
                return log_oom();
 
        /* If command line arguments are specified along with --replace=, read all configuration files and
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
         * read configuration and execute it. */
        if (arg_replace || strv_isempty(args))
                r = read_config_files(&c, config_dirs, args, &invalid_config);
        else
                r = parse_arguments(&c, config_dirs, args, &invalid_config);
        if (r < 0)
                return r;
 
        r = read_credential_lines(&c, &invalid_config);
        if (r < 0)
                return r;
 
        /* Let's now link up all child/parent relationships */
        ORDERED_HASHMAP_FOREACH(a, c.items) {
                r = link_parent(&c, a);
                if (r < 0)
                        return r;
        }
        ORDERED_HASHMAP_FOREACH(a, c.globs) {
                r = link_parent(&c, a);
                if (r < 0)
                        return r;
        }
 
        /* If multiple operations are requested, let's first run the remove/clean operations, and only then
         * the create operations. i.e. that we first clean out the platform we then build on. */
        for (phase = 0; phase < _PHASE_MAX; phase++) {
                OperationMask op;
 
                if (phase == PHASE_PURGE)
                        op = arg_operation & OPERATION_PURGE;
                else if (phase == PHASE_REMOVE_AND_CLEAN)
                        op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
                else if (phase == PHASE_CREATE)
                        op = arg_operation & OPERATION_CREATE;
                else
                        assert_not_reached();
 
                if (op == 0) /* Nothing requested in this phase */
                        continue;
 
                /* The non-globbing ones usually create things, hence we apply them first */
                ORDERED_HASHMAP_FOREACH(a, c.items)
                        RET_GATHER(r, process_item_array(&c, a, op));
 
                /* The globbing ones usually alter things, hence we apply them second. */
                ORDERED_HASHMAP_FOREACH(a, c.globs)
                        RET_GATHER(r, process_item_array(&c, a, op));
        }
 
        if (ERRNO_IS_NEG_RESOURCE(r))
                return r;
        if (invalid_config)
                return EX_DATAERR;
        if (r < 0)
                return EX_CANTCREAT;
        return 0;
}
 
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);