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 2001–3000 of 5,453

        assert(path);
        assert(i->type == WRITE_FILE);
 
        r = path_extract_filename(path, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
        if (r == O_DIRECTORY)
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
 
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
         * can't be changed behind our back. */
        dir_fd = path_open_parent_safe(path, i->allow_failure);
        if (dir_fd < 0)
                return dir_fd;
 
        /* Follow symlinks. Open with O_PATH in dry-run mode to make sure we don't use the path inadvertently. */
        int flags = O_NONBLOCK | O_CLOEXEC | O_WRONLY | O_NOCTTY | i->append_or_force * O_APPEND | arg_dry_run * O_PATH;
        fd = openat(dir_fd, bn, flags, i->mode);
        if (fd < 0) {
                if (errno == ENOENT) {
                        log_debug_errno(errno, "Not writing missing file \"%s\": %m", path);
                        return 0;
                }
 
                if (i->allow_failure)
                        return log_debug_errno(errno, "Failed to open file \"%s\", ignoring: %m", path);
 
                return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
        }
 
        /* 'w' is allowed to write into any kind of files. */
 
        r = write_argument_data(i, fd, path);
        if (r < 0)
                return r;
 
        return fd_set_perms(c, i, fd, path, NULL, creation);
}
 
static int create_file(
                Context *c,
                Item *i,
                const char *path) {
 
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
        _cleanup_free_ char *bn = NULL;
        struct stat stbuf, *st = NULL;
        CreationMode creation;
        int r = 0;
 
        assert(c);
        assert(i);
        assert(path);
        assert(i->type == CREATE_FILE);
 
        /* 'f' operates on regular files exclusively. */
 
        r = path_extract_filename(path, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
        if (r == O_DIRECTORY)
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
 
        if (arg_dry_run) {
                log_info("Would create file %s", path);
                return 0;
 
                /* The opening of the directory below would fail if it doesn't exist,
                 * so log and exit before even trying to do that. */
        }
 
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
         * can't be changed behind our back. */
        dir_fd = path_open_parent_safe(path, i->allow_failure);
        if (dir_fd < 0)
                return dir_fd;
 
        WITH_UMASK(0000) {
                mac_selinux_create_file_prepare(path, S_IFREG, arg_label_context);
                fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
                mac_selinux_create_file_clear();
        }
 
        if (fd < 0) {
                /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
                 * returns EROFS only if it needs to create the file. */
                if (fd != -EEXIST)
                        return log_error_errno(fd, "Failed to create file %s: %m", path);
 
                /* Re-open the file. At that point it must exist since open(2) failed with EEXIST. We still
                 * need to check if the perms/mode need to be changed. For read-only filesystems, we let
                 * fd_set_perms() report the error if the perms need to be modified. */
                fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
                if (fd < 0)
                        return log_error_errno(errno, "Failed to reopen file %s: %m", path);
 
                if (fstat(fd, &stbuf) < 0)
                        return log_error_errno(errno, "stat(%s) failed: %m", path);
 
                if (!S_ISREG(stbuf.st_mode))
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
                                               "%s exists and is not a regular file.",
                                               path);
 
                st = &stbuf;
                creation = CREATION_EXISTING;
        } else {
                r = write_argument_data(i, fd, path);
                if (r < 0)
                        return r;
 
                creation = CREATION_NORMAL;
        }
 
        return fd_set_perms(c, i, fd, path, st, creation);
}
 
static int truncate_file(
                Context *c,
                Item *i,
                const char *path) {
 
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
        _cleanup_free_ char *bn = NULL;
        struct stat stbuf, *st = NULL;
        CreationMode creation;
        bool erofs = false;
        int r = 0;
 
        assert(c);
        assert(i);
        assert(path);
        assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
 
        /* We want to operate on regular file exclusively especially since O_TRUNC is unspecified if the file
         * is neither a regular file nor a fifo nor a terminal device. Therefore we first open the file and
         * make sure it's a regular one before truncating it. */
 
        r = path_extract_filename(path, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
        if (r == O_DIRECTORY)
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for truncation, is a directory.", path);
 
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
         * can't be changed behind our back. */
        dir_fd = path_open_parent_safe(path, i->allow_failure);
        if (dir_fd < 0)
                return dir_fd;
 
        if (arg_dry_run) {
                log_info("Would truncate %s", path);
                return 0;
        }
 
        creation = CREATION_EXISTING;
        fd = RET_NERRNO(openat(dir_fd, bn, O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
        if (fd == -ENOENT) {
                creation = CREATION_NORMAL; /* Didn't work without O_CREATE, try again with */
 
                WITH_UMASK(0000) {
                        mac_selinux_create_file_prepare(path, S_IFREG, arg_label_context);
                        fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
                        mac_selinux_create_file_clear();
                }
        }
 
        if (fd < 0) {
                if (fd != -EROFS)
                        return log_error_errno(fd, "Failed to open/create file %s: %m", path);
 
                /* On a read-only filesystem, we don't want to fail if the target is already empty and the
                 * perms are set. So we still proceed with the sanity checks and let the remaining operations
                 * fail with EROFS if they try to modify the target file. */
 
                fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
                if (fd < 0) {
                        if (errno == ENOENT)
                                return log_error_errno(SYNTHETIC_ERRNO(EROFS),
                                                       "Cannot create file %s on a read-only file system.",
                                                       path);
 
                        return log_error_errno(errno, "Failed to reopen file %s: %m", path);
                }
 
                erofs = true;
                creation = CREATION_EXISTING;
        }
 
        if (fstat(fd, &stbuf) < 0)
                return log_error_errno(errno, "stat(%s) failed: %m", path);
 
        if (!S_ISREG(stbuf.st_mode))
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
                                       "%s exists and is not a regular file.",
                                       path);
 
        if (stbuf.st_size > 0) {
                if (ftruncate(fd, 0) < 0) {
                        r = erofs ? -EROFS : -errno;
                        return log_error_errno(r, "Failed to truncate file %s: %m", path);
                }
        } else
                st = &stbuf;
 
        log_debug("\"%s\" has been created.", path);
 
        if (item_binary_argument(i)) {
                r = write_argument_data(i, fd, path);
                if (r < 0)
                        return r;
        }
 
        return fd_set_perms(c, i, fd, path, st, creation);
}
 
static int copy_files(Context *c, Item *i) {
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
        _cleanup_free_ char *bn = NULL;
        struct stat st, a;
        int r;
 
        log_action("Would copy", "Copying", "%s tree \"%s\" to \"%s\"", i->argument, i->path);
        if (arg_dry_run)
                return 0;
 
        r = path_extract_filename(i->path, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
 
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
         * path can't be changed behind our back. */
        dfd = path_open_parent_safe(i->path, i->allow_failure);
        if (dfd < 0)
                return dfd;
 
        r = copy_tree_at(AT_FDCWD, i->argument,
                         dfd, bn,
                         i->uid_set ? i->uid : UID_INVALID,
                         i->gid_set ? i->gid : GID_INVALID,
                         ((i->append_or_force) ? COPY_MERGE : COPY_MERGE_EMPTY) | COPY_MAC_CREATE | COPY_HARDLINKS,
                         NULL, NULL);
 
        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
        if (fd < 0) {
                if (r < 0) /* Look at original error first */
                        return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
 
                return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
        }
 
        if (r < 0 && !IN_SET(r, -EEXIST, -EROFS))
                return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
 
        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
 
        if (lstat(i->argument, &a) < 0)
                return log_error_errno(errno, "Failed to lstat(%s): %m", i->argument);
 
        if (((st.st_mode ^ a.st_mode) & S_IFMT) != 0) {
                log_debug("Can't copy to %s, file exists already and is of different type", i->path);
                return 0;
        }
 
        return fd_set_perms(c, i, fd, i->path, &st, _CREATION_MODE_INVALID);
}
 
static int create_directory_or_subvolume(
                const char *path,
                mode_t mode,
                bool subvol,
                bool allow_failure,
                struct stat *ret_st,
                CreationMode *ret_creation) {
 
        _cleanup_free_ char *bn = NULL;
        _cleanup_close_ int pfd = -EBADF;
        CreationMode creation;
        struct stat st;
        int r, fd;
 
        assert(path);
 
        r = path_extract_filename(path, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
 
        pfd = path_open_parent_safe(path, allow_failure);
        if (pfd < 0)
                return pfd;
 
        if (subvol) {
                r = getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
                if (r < 0) {
                        if (r != -ENXIO) /* env var is unset */
                                log_warning_errno(r, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
                        r = btrfs_is_subvol(empty_to_root(arg_root)) > 0;
                }
                if (r == 0)
                        /* Don't create a subvolume unless the root directory is one, too. We do this under
                         * the assumption that if the root directory is just a plain directory (i.e. very
                         * lightweight), we shouldn't try to split it up into subvolumes (i.e. more
                         * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
                         * subvolume set up below their tree only if they specifically set up a btrfs
                         * subvolume for the root dir too. */
                        subvol = false;
                else {
                        log_action("Would create", "Creating", "%s btrfs subvolume %s", path);
                        if (!arg_dry_run)
                                WITH_UMASK((~mode) & 0777)
                                        r = btrfs_subvol_make(pfd, bn);
                        else
                                r = 0;
                }
        } else
                r = 0;
 
        if (!subvol || ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
                log_action("Would create", "Creating", "%s directory \"%s\"", path);
                if (!arg_dry_run)
                        WITH_UMASK(0000)
                                r = mkdirat_label(pfd, bn, mode, arg_label_context);
        }
 
        if (arg_dry_run)
                return 0;
 
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
 
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY|O_PATH);
        if (fd < 0) {
                /* We couldn't open it because it is not actually a directory? */
                if (errno == ENOTDIR)
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "\"%s\" already exists and is not a directory.", path);
 
                /* Then look at the original error */
                if (r < 0)
                        return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
                                              r,
                                              "Failed to create directory or subvolume \"%s\"%s: %m",
                                              path,
                                              allow_failure ? ", ignoring" : "");
 
                return log_error_errno(errno, "Failed to open directory/subvolume we just created '%s': %m", path);
        }
 
        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
 
        assert(S_ISDIR(st.st_mode)); /* we used O_DIRECTORY above */
 
        log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), path);
 
        if (ret_st)
                *ret_st = st;
        if (ret_creation)
                *ret_creation = creation;
 
        return fd;
}
 
static int create_directory(
                Context *c,
                Item *i,
                const char *path) {
 
        _cleanup_close_ int fd = -EBADF;
        CreationMode creation;
        struct stat st;
 
        assert(c);
        assert(i);
        assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
 
        if (arg_dry_run) {
                log_info("Would create directory %s", path);
                return 0;
        }
 
        fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ false, i->allow_failure, &st, &creation);
        if (fd == -EEXIST)
                return 0;
        if (fd < 0)
                return fd;
 
        return fd_set_perms(c, i, fd, path, &st, creation);
}
 
static int create_subvolume(
                Context *c,
                Item *i,
                const char *path) {
 
        _cleanup_close_ int fd = -EBADF;
        CreationMode creation;
        struct stat st;
        int r, q = 0;
 
        assert(c);
        assert(i);
        assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
 
        if (arg_dry_run) {
                log_info("Would create subvolume %s", path);
                return 0;
        }
 
        fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ true, i->allow_failure, &st, &creation);
        if (fd == -EEXIST)
                return 0;
        if (fd < 0)
                return fd;
 
        if (creation == CREATION_NORMAL &&
            IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
                r = btrfs_subvol_auto_qgroup_fd(fd, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
                if (r == -ENOTTY)
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
                else if (r == -EROFS)
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
                else if (r == -ENOTCONN)
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
                else if (r < 0)
                        q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
                else if (r > 0)
                        log_debug("Adjusted quota for subvolume \"%s\".", i->path);
                else if (r == 0)
                        log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
        }
 
        r = fd_set_perms(c, i, fd, path, &st, creation);
        if (q < 0) /* prefer the quota change error from above */
                return q;
 
        return r;
}
 
static int empty_directory(
                Context *c,
                Item *i,
                const char *path,
                CreationMode creation) {
 
        _cleanup_close_ int fd = -EBADF;
        struct stat st;
        int r;
 
        assert(c);
        assert(i);
        assert(i->type == EMPTY_DIRECTORY);
 
        r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN, NULL, &fd);
        if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
                return r;
        if (r == -ENOENT) {
                /* Option "e" operates only on existing objects. Do not print errors about non-existent files
                 * or directories */
                log_debug_errno(r, "Skipping missing directory: %s", path);
                return 0;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to open directory '%s': %m", path);
 
        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
        if (!S_ISDIR(st.st_mode)) {
                log_warning("'%s' already exists and is not a directory.", path);
                return 0;
        }
 
        return fd_set_perms(c, i, fd, path, &st, creation);
}
 
static int create_device(
                Context *c,
                Item *i,
                mode_t file_type) {
 
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
        _cleanup_free_ char *bn = NULL;
        CreationMode creation;
        struct stat st;
        int r;
 
        assert(c);
        assert(i);
        assert(IN_SET(i->type, CREATE_BLOCK_DEVICE, CREATE_CHAR_DEVICE));
        assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
 
        r = path_extract_filename(i->path, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
        if (r == O_DIRECTORY)
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
                                       "Cannot open path '%s' for creating device node, is a directory.", i->path);
 
        if (arg_dry_run) {
                log_info("Would create device node %s", i->path);
                return 0;
        }
 
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
         * path can't be changed behind our back. */
        dfd = path_open_parent_safe(i->path, i->allow_failure);
        if (dfd < 0)
                return dfd;
 
        WITH_UMASK(0000) {
                mac_selinux_create_file_prepare(i->path, file_type, arg_label_context);
                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
                mac_selinux_create_file_clear();
        }
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
 
        /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
         * order anyway and we hence can ignore the error to create the device node */
        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
        if (fd < 0) {
                /* OK, so opening the inode failed, let's look at the original error then. */
 
                if (r < 0) {
                        if (ERRNO_IS_PRIVILEGE(r))
                                goto handle_privilege;
 
                        return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
                }
 
                return log_error_errno(errno, "Failed to open device node '%s' we just created: %m", i->path);
        }
 
        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
 
        if (((st.st_mode ^ file_type) & S_IFMT) != 0) {
 
                if (i->append_or_force) {
                        fd = safe_close(fd);
 
                        WITH_UMASK(0000) {
                                mac_selinux_create_file_prepare(i->path, file_type, arg_label_context);
                                r = mknodat_atomic(dfd, bn, i->mode | file_type, i->major_minor);
                                mac_selinux_create_file_clear();
                        }
                        if (ERRNO_IS_PRIVILEGE(r))
                                goto handle_privilege;
                        if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
                                r = rm_rf_child(dfd, bn, REMOVE_PHYSICAL);
                                if (r < 0)
                                        return log_error_errno(r, "rm -rf %s failed: %m", i->path);
 
                                mac_selinux_create_file_prepare(i->path, file_type, arg_label_context);
                                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
                                mac_selinux_create_file_clear();
                        }
                        if (r < 0)
                                return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
 
                        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
                        if (fd < 0)
                                return log_error_errno(errno, "Failed to open device node we just created '%s': %m", i->path);
 
                        /* Validate type before change ownership below */
                        if (fstat(fd, &st) < 0)
                                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
 
                        if (((st.st_mode ^ file_type) & S_IFMT) != 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
                                                       "Device node we just created is not a device node, refusing.");
 
                        creation = CREATION_FORCE;
                } else {
                        log_warning("\"%s\" already exists and is not a device node.", i->path);
                        return 0;
                }
        }
 
        log_debug("%s %s device node \"%s\" " DEVNUM_FORMAT_STR ".",
                  creation_mode_verb_to_string(creation),
                  i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
                  i->path, DEVNUM_FORMAT_VAL(i->major_minor));
 
        return fd_set_perms(c, i, fd, i->path, &st, creation);
 
handle_privilege:
        log_debug_errno(r,
                        "We lack permissions, possibly because of cgroup configuration; "
                        "skipping creation of device node '%s'.", i->path);
        return 0;
}
 
static int create_fifo(Context *c, Item *i) {
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
        _cleanup_free_ char *bn = NULL;
        CreationMode creation;
        struct stat st;
        int r;
 
        assert(c);
        assert(i);
        assert(i->type == CREATE_FIFO);
 
        r = path_extract_filename(i->path, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
        if (r == O_DIRECTORY)
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
                                       "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
 
        if (arg_dry_run) {
                log_info("Would create fifo %s", i->path);
                return 0;
        }
 
        pfd = path_open_parent_safe(i->path, i->allow_failure);
        if (pfd < 0)
                return pfd;
 
        WITH_UMASK(0000) {
                mac_selinux_create_file_prepare(i->path, S_IFIFO, arg_label_context);
                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
                mac_selinux_create_file_clear();
        }
 
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
 
        /* Open the inode via O_PATH, regardless if we managed to create it or not. Maybe it is already the FIFO we want */
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
        if (fd < 0) {
                if (r < 0)
                        return log_error_errno(r, "Failed to create FIFO %s: %m", i->path); /* original error! */
 
                return log_error_errno(errno, "Failed to open FIFO we just created %s: %m", i->path);
        }
 
        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
 
        if (!S_ISFIFO(st.st_mode)) {
 
                if (i->append_or_force) {
                        fd = safe_close(fd);
 
                        WITH_UMASK(0000) {
                                mac_selinux_create_file_prepare(i->path, S_IFIFO, arg_label_context);
                                r = mkfifoat_atomic(pfd, bn, i->mode);
                                mac_selinux_create_file_clear();
                        }
                        if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
                                r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
                                if (r < 0)
                                        return log_error_errno(r, "rm -rf %s failed: %m", i->path);
 
                                mac_selinux_create_file_prepare(i->path, S_IFIFO, arg_label_context);
                                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
                                mac_selinux_create_file_clear();
                        }
                        if (r < 0)
                                return log_error_errno(r, "Failed to create FIFO %s: %m", i->path);
 
                        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
                        if (fd < 0)
                                return log_error_errno(errno, "Failed to open FIFO we just created '%s': %m", i->path);
 
                        /* Validate type before change ownership below */
                        if (fstat(fd, &st) < 0)
                                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
 
                        if (!S_ISFIFO(st.st_mode))
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
                                                       "FIFO inode we just created is not a FIFO, refusing.");
 
                        creation = CREATION_FORCE;
                } else {
                        log_warning("\"%s\" already exists and is not a FIFO.", i->path);
                        return 0;
                }
        }
 
        log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), i->path);
 
        return fd_set_perms(c, i, fd, i->path, &st, creation);
}
 
static int create_symlink(Context *c, Item *i) {
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
        _cleanup_free_ char *bn = NULL;
        CreationMode creation;
        struct stat st;
        bool good = false;
        int r;
 
        assert(c);
        assert(i);
 
        if (i->ignore_if_target_missing) {
                _cleanup_free_ char *target = NULL;
                ChaseFlags chase_flags = CHASE_SAFE|CHASE_NOFOLLOW;
 
                if (!path_is_absolute(i->argument)) {
                        _cleanup_free_ char *dn = NULL;
 
                        r = path_extract_directory(i->path, &dn);
                        if (r < 0)
                                return log_error_errno(r, "Failed to extract directory from path '%s': %m", i->path);
 
                        target = path_join(dn, i->argument);
                        if (!target)
                                return log_oom();
                } else
                        chase_flags |= CHASE_PREFIX_ROOT;
 
                r = chase(target ?: i->argument, arg_root, chase_flags, /* ret_path= */ NULL, /* ret_fd= */ NULL);
                if (r == -ENOENT) {
                        /* Silently skip over lines where the source file is missing. */
                        log_debug_errno(r, "Symlink source path '%s' does not exist, skipping line.", i->argument);
                        return 0;
                }
                if (r < 0)
                        return log_error_errno(r, "Failed to check if symlink source path '%s' exists: %m", i->argument);
        }
 
        r = path_extract_filename(i->path, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
        if (r == O_DIRECTORY)
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
                                       "Cannot open path '%s' for creating symlink, is a directory.", i->path);
 
        if (arg_dry_run) {
                log_info("Would create symlink %s -> %s", i->path, i->argument);
                return 0;
        }
 
        pfd = path_open_parent_safe(i->path, i->allow_failure);
        if (pfd < 0)
                return pfd;
 
        mac_selinux_create_file_prepare(i->path, S_IFLNK, arg_label_context);
        r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
        mac_selinux_create_file_clear();
 
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
 
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
        if (fd < 0) {
                if (r < 0)
                        return log_error_errno(r, "Failed to create symlink '%s': %m", i->path); /* original error! */
 
                return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
        }
 
        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
 
        if (S_ISLNK(st.st_mode)) {
                _cleanup_free_ char *x = NULL;
 
                r = readlinkat_malloc(fd, "", &x);
                if (r < 0)
                        return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
 
                good = streq(x, i->argument);
        } else
                good = false;
 
        if (!good) {
                if (!i->append_or_force) {
                        log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
                        return 0;
                }
 
                fd = safe_close(fd);
 
                r = symlinkat_atomic_full_label(i->argument, pfd, bn, SYMLINK_LABEL, arg_label_context);
                if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
                        r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
                        if (r < 0)
                                return log_error_errno(r, "rm -rf %s failed: %m", i->path);
 
                        r = symlinkat_atomic_full_label(i->argument, pfd, bn, SYMLINK_LABEL, arg_label_context);
                }
                if (r < 0)
                        return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
 
                fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
                if (fd < 0)
                        return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
 
                /* Validate type before change ownership below */
                if (fstat(fd, &st) < 0)
                        return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
 
                if (!S_ISLNK(st.st_mode))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Symlink we just created is not a symlink, refusing.");
 
                creation = CREATION_FORCE;
        }
 
        log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
        return fd_set_perms(c, i, fd, i->path, &st, creation);
}
 
typedef int (*action_t)(Context *c, Item *i, const char *path, CreationMode creation);
typedef int (*fdaction_t)(Context *c, Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
 
static int item_do(
                Context *c,
                Item *i,
                int fd,
                const char *path,
                CreationMode creation,
                fdaction_t action) {
 
        struct stat st;
        int r;
 
        assert(c);
        assert(i);
        assert(fd >= 0);
        assert(path);
        assert(action);
 
        if (fstat(fd, &st) < 0) {
                r = log_error_errno(errno, "fstat() on file failed: %m");
                goto finish;
        }
 
        /* This returns the first error we run into, but nevertheless tries to go on */
        r = action(c, i, fd, path, &st, creation);
 
        if (S_ISDIR(st.st_mode)) {
                _cleanup_closedir_ DIR *d = NULL;
 
                /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
                 * reading the directory content. */
                d = opendir(FORMAT_PROC_FD_PATH(fd));
                if (!d) {
                        RET_GATHER(r, log_error_errno(errno, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd)));
                        goto finish;
                }
 
                FOREACH_DIRENT_ALL(de, d, RET_GATHER(r, -errno); goto finish) {
                        _cleanup_close_ int de_fd = -EBADF;
                        _cleanup_free_ char *de_path = NULL;
 
                        if (dot_or_dot_dot(de->d_name))
                                continue;
 
                        de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
                        if (de_fd < 0) {
                                if (errno != ENOENT)
                                        RET_GATHER(r, log_error_errno(errno, "Failed to open file '%s': %m", de->d_name));
                                continue;
                        }
 
                        de_path = path_join(path, de->d_name);
                        if (!de_path) {
                                r = log_oom();
                                goto finish;
                        }
 
                        /* Pass ownership of dirent fd over */
                        RET_GATHER(r, item_do(c, i, TAKE_FD(de_fd), de_path, CREATION_EXISTING, action));
                }
        }
 
finish:
        safe_close(fd);
        return r;
}
 
static int glob_item(Context *c, Item *i, action_t action) {
        _cleanup_strv_free_ char **paths = NULL;
        int r;
 
        assert(c);
        assert(i);
        assert(action);
 
        r = safe_glob_full(i->path, GLOB_NOSORT|GLOB_BRACE, opendir_nomod, &paths);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
 
        r = 0;
        STRV_FOREACH(fn, paths)
                /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
                RET_GATHER(r, action(c, i, *fn, CREATION_EXISTING));
 
        return r;
}
 
static int glob_item_recursively(
                Context *c,
                Item *i,
                fdaction_t action) {
 
        _cleanup_strv_free_ char **paths = NULL;
        int r;
 
        assert(c);
        assert(i);
        assert(action);
 
        r = safe_glob_full(i->path, GLOB_NOSORT|GLOB_BRACE, opendir_nomod, &paths);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
 
        r = 0;
        STRV_FOREACH(fn, paths) {
                _cleanup_close_ int fd = -EBADF;
 
                /* Make sure we won't trigger/follow file object (such as device nodes, automounts, ...)
                 * pointed out by 'fn' with O_PATH. Note, when O_PATH is used, flags other than
                 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
                fd = path_open_safe(*fn);
                if (fd < 0) {
                        RET_GATHER(r, fd);
                        continue;
                }
 
                RET_GATHER(r, item_do(c, i, TAKE_FD(fd), *fn, CREATION_EXISTING, action));
        }
 
        return r;
}
 
static int rm_if_wrong_type_safe(
                mode_t mode,
                int parent_fd,
                const struct stat *parent_st, /* Only used if follow_links below is true. */
                const char *name,
                int flags) {
        _cleanup_free_ char *parent_name = NULL;
        bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
        struct stat st;
        int r;
 
        assert(name);
        assert((mode & ~S_IFMT) == 0);
        assert(!follow_links || parent_st);
        assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
 
        if (mode == 0)
                return 0;
 
        if (!filename_is_valid(name))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
 
        r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
        if (r < 0) {
                (void) fd_get_path(parent_fd, &parent_name);
                return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_ERR, r,
                                      "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
        }
 
        /* Fail before removing anything if this is an unsafe transition. */
        if (follow_links && stat_unsafe_transition(parent_st, &st)) {
                (void) fd_get_path(parent_fd, &parent_name);
                return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
                                       "Unsafe transition from \"%s\" to \"%s\".", parent_name ?: "...", name);
        }
 
        if ((st.st_mode & S_IFMT) == mode)
                return 0;
 
        (void) fd_get_path(parent_fd, &parent_name);
        log_notice("Wrong file type 0o%o; rm -rf \"%s/%s\"", st.st_mode & S_IFMT, parent_name ?: "...", name);
 
        /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
         * target, so make sure it is identified as a link and not a directory. */
        if (follow_links) {
                r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
                if (r < 0)
                        return log_error_errno(r, "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
        }
 
        /* Do not remove mount points. */
        r = is_mount_point_at(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
        if (r < 0)
                (void) log_warning_errno(r, "Failed to check if  \"%s/%s\" is a mount point: %m; continuing.",
                                         parent_name ?: "...", name);
        else if (r > 0)
                return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
                                "Not removing  \"%s/%s\" because it is a mount point.", parent_name ?: "...", name);
 
        log_action("Would remove", "Removing", "%s %s/%s", parent_name ?: "...", name);
        if (!arg_dry_run) {
                if ((st.st_mode & S_IFMT) == S_IFDIR) {
                        _cleanup_close_ int child_fd = -EBADF;
 
                        child_fd = openat(parent_fd, name, O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
                        if (child_fd < 0)
                                return log_error_errno(errno, "Failed to open \"%s/%s\": %m", parent_name ?: "...", name);
 
                        r = rm_rf_children(TAKE_FD(child_fd), REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL, &st);