HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/basic/fs-util.c
Git blob: d68a09814f394ec38189bf992e0629f63c6a418e
Lines 1001–1603 of 1,603
d = strchrnul(e, delimiter);
ss = strndup(e, d - e);
if (!ss)
return -ENOMEM;
if (!filename_is_valid(ss))
return -EINVAL;
if (!isempty(d)) {
x = strdup(skip_leading_chars(d, CHAR_TO_STR(delimiter)));
if (!x)
return -EINVAL;
/* Make sure to convert Windows-style "\" → Unix-style / */
for (char *i = x; *i; i++)
if (*i == delimiter)
*i = '/';
if (!path_is_valid(x))
return -EINVAL;
path_simplify(x);
if (!path_is_normalized(x))
return -EINVAL;
}
if (ret_host)
*ret_host = TAKE_PTR(h);
if (ret_service)
*ret_service = TAKE_PTR(ss);
if (ret_path)
*ret_path = TAKE_PTR(x);
return 0;
}
int open_mkdir_at_full_label(int dirfd, const char *path, int flags, XOpenFlags xopen_flags, mode_t mode, LabelContext *label_context) {
_cleanup_close_ int fd = -EBADF, parent_fd = -EBADF;
_cleanup_free_ char *fname = NULL, *parent = NULL;
int r;
/* Creates a directory with mkdirat() and then opens it, in the "most atomic" fashion we can
* do. Guarantees that the returned fd refers to a directory. If O_EXCL is specified will fail if the
* dir already exists. Otherwise will open an existing dir, but only if it is one. */
if (flags & ~(O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_EXCL|O_NOATIME|O_NOFOLLOW|O_PATH))
return -EINVAL;
if ((flags & O_ACCMODE_STRICT) != O_RDONLY)
return -EINVAL;
/* Note that O_DIRECTORY|O_NOFOLLOW is implied, but we allow specifying it anyway. The following
* flags actually make sense to specify: O_CLOEXEC, O_EXCL, O_NOATIME, O_PATH */
/* If this is not a valid filename, it's a path. Let's open the parent directory then, so
* that we can pin it, and operate below it. */
r = path_extract_directory(path, &parent);
if (r < 0) {
if (!IN_SET(r, -EDESTADDRREQ, -EADDRNOTAVAIL))
return r;
} else {
r = path_extract_filename(path, &fname);
if (r < 0)
return r;
parent_fd = openat(dirfd, parent, O_PATH|O_DIRECTORY|O_CLOEXEC);
if (parent_fd < 0)
return -errno;
dirfd = parent_fd;
path = fname;
}
fd = xopenat_full_label(dirfd, path, flags|O_CREAT|O_DIRECTORY|O_NOFOLLOW, xopen_flags, mode, label_context);
if (IN_SET(fd, -ELOOP, -ENOTDIR))
return -EEXIST;
if (fd < 0)
return fd;
return TAKE_FD(fd);
}
int openat_report_new(int dirfd, const char *pathname, int flags, mode_t mode, bool *ret_newly_created) {
int fd;
/* Just like openat(), but adds one thing: optionally returns whether we created the file anew or if
* it already existed before. This is only relevant if O_CREAT is set without O_EXCL, and thus will
* shortcut to openat() otherwise.
*
* Note that this routine is a bit more strict with symlinks than regular openat() is. If O_NOFOLLOW
* is not specified, then we'll follow the symlink when opening an existing file but we will *not*
* follow it when creating a new one (because that's a terrible UNIX misfeature and generally a
* security hole). */
if (!FLAGS_SET(flags, O_CREAT) || FLAGS_SET(flags, O_EXCL)) {
fd = openat(dirfd, pathname, flags, mode);
if (fd < 0)
return -errno;
if (ret_newly_created)
*ret_newly_created = FLAGS_SET(flags, O_CREAT);
return fd;
}
for (unsigned attempts = 7;;) {
/* First, attempt to open without O_CREAT/O_EXCL, i.e. open existing file */
fd = openat(dirfd, pathname, flags & ~(O_CREAT | O_EXCL), mode);
if (fd >= 0) {
if (ret_newly_created)
*ret_newly_created = false;
return fd;
}
if (errno != ENOENT)
return -errno;
/* So the file didn't exist yet, hence create it with O_CREAT/O_EXCL/O_NOFOLLOW. */
fd = openat(dirfd, pathname, flags | O_CREAT | O_EXCL | O_NOFOLLOW, mode);
if (fd >= 0) {
if (ret_newly_created)
*ret_newly_created = true;
return fd;
}
if (errno != EEXIST)
return -errno;
/* Hmm, so now we got EEXIST? Then someone might have created the file between the first and
* second call to openat(). Let's try again but with a limit so we don't spin forever. */
if (--attempts == 0) /* Give up eventually, somebody is playing with us */
return -EEXIST;
}
}
static int openat_with_automount(int dir_fd, const char *path, int open_flags, mode_t mode) {
/* When XO_TRIGGER_AUTOMOUNT is set we want to trigger automounts on the path. open() with O_PATH
* does not do that, so we use open_tree() without OPEN_TREE_CLONE which is equivalent to open() with
* O_PATH except that it does trigger automounts. Some sandboxes reject open_tree() with EPERM or
* ENOSYS, in which case we fall back to plain openat(): autofs wouldn't work inside a restricted
* mount namespace anyway. open_tree() only ever returns O_PATH fds, so this helper is for O_PATH
* acquisition only. */
static bool can_open_tree = true;
assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
assert(path);
assert(FLAGS_SET(open_flags, O_PATH));
if (can_open_tree) {
int fd = RET_NERRNO(open_tree(dir_fd, path,
OPEN_TREE_CLOEXEC |
(FLAGS_SET(open_flags, O_NOFOLLOW) ? AT_SYMLINK_NOFOLLOW : 0)));
if (fd >= 0) {
/* open_tree() doesn't honor O_DIRECTORY, so enforce it ourselves to match
* the openat() fallback's behavior. */
if (FLAGS_SET(open_flags, O_DIRECTORY)) {
int q = fd_verify_directory(fd);
if (q < 0) {
safe_close(fd);
return q;
}
}
return fd;
}
if (fd != -EPERM && !ERRNO_IS_NEG_NOT_SUPPORTED(fd))
return fd;
can_open_tree = false;
}
return RET_NERRNO(openat(dir_fd, path, open_flags, mode));
}
int xopenat_full_label(int dir_fd, const char *path, int open_flags, XOpenFlags xopen_flags, mode_t mode, LabelContext *label_context) {
_cleanup_close_ int fd = -EBADF;
bool made_dir = false, made_file = false;
int r;
assert(wildcard_fd_is_valid(dir_fd));
/* An inode can only be one of a directory, a regular file or a socket at the same time. */
assert(FLAGS_SET(open_flags, O_DIRECTORY) + FLAGS_SET(xopen_flags, XO_REGULAR) + FLAGS_SET(xopen_flags, XO_SOCKET) <= 1);
/* Sockets cannot be open()ed, only pinned via O_PATH. */
assert(!FLAGS_SET(xopen_flags, XO_SOCKET) || FLAGS_SET(open_flags, O_PATH));
/* XO_TRIGGER_AUTOMOUNT requires O_PATH and does not support creating inodes. XO_SUBVOLUME
* requires O_CREAT, and XO_COW/XO_NOCOW need a writable fd for their chattr ioctl, so none are
* compatible with XO_TRIGGER_AUTOMOUNT. */
assert(!FLAGS_SET(xopen_flags, XO_TRIGGER_AUTOMOUNT) ||
(FLAGS_SET(open_flags, O_PATH) && !FLAGS_SET(open_flags, O_CREAT)));
assert(!(FLAGS_SET(xopen_flags, XO_TRIGGER_AUTOMOUNT) && FLAGS_SET(xopen_flags, XO_SUBVOLUME)));
assert(!(FLAGS_SET(xopen_flags, XO_TRIGGER_AUTOMOUNT) && (xopen_flags & (XO_COW|XO_NOCOW))));
assert((xopen_flags & (XO_COW|XO_NOCOW)) != (XO_COW|XO_NOCOW));
/* Don't specify an access mode if you want auto mode. */
assert(!FLAGS_SET(xopen_flags, XO_AUTO_RW_RO) || (open_flags & O_ACCMODE_STRICT) == 0);
/* This is like openat(), but has a few tricks up its sleeves, extending behaviour:
*
* • O_DIRECTORY|O_CREAT is supported, which causes a directory to be created, and immediately
* opened. When used with the XO_SUBVOLUME flag this will even create a btrfs subvolume.
*
* • If O_CREAT is used with XO_LABEL, any created file will be immediately relabelled.
*
* • If the path is specified NULL or empty, behaves like fd_reopen().
*
* • If XO_COW or XO_NOCOW is specified will turn off or on the NOCOW btrfs flag on the file, if
* available.
*
* • if XO_REGULAR is specified will return an error if inode is not a regular file.
*
* • if XO_SOCKET is specified will return an error if inode is not a socket.
*
* • if XO_TRIGGER_AUTOMOUNT is specified O_PATH fds will trigger automounts.
*
* • If mode is specified as MODE_INVALID, we'll use 0755 for dirs, and 0644 for regular files.
*
* • The dir fd can be passed as XAT_FDROOT, in which case any relative paths will be taken relative to the root fs.
*
* • If XO_AUTO_RW_RO is specified and the file cannot be opened in O_RDWR mode due to EACCES/EROFS or similar, retry in O_RDONLY mode.
*/
if (mode == MODE_INVALID)
mode = (open_flags & O_DIRECTORY) ? 0755 : 0644;
if (FLAGS_SET(xopen_flags, XO_AUTO_RW_RO)) {
if (open_flags & O_DIRECTORY) {
/* Directories can only be opened in read-only mode */
xopen_flags &= ~XO_AUTO_RW_RO;
open_flags |= O_RDONLY;
} else if (open_flags & O_PATH)
/* O_PATH is incompatible with O_RDONLY/O_RDWR → fail */
return -EINVAL;
}
if (isempty(path)) {
assert(!FLAGS_SET(open_flags, O_CREAT|O_EXCL));
open_flags &= ~O_NOFOLLOW;
if (FLAGS_SET(xopen_flags, XO_REGULAR)) {
r = fd_verify_regular(dir_fd);
if (r < 0)
return r;
}
if (FLAGS_SET(xopen_flags, XO_SOCKET)) {
r = fd_verify_socket(dir_fd);
if (r < 0)
return r;
}
if (FLAGS_SET(xopen_flags, XO_AUTO_RW_RO)) {
/* First try: in r/w mode */
fd = fd_reopen(dir_fd, open_flags|O_RDWR);
if (!ERRNO_IS_NEG_FS_WRITE_REFUSED(fd) && fd != -EISDIR)
return TAKE_FD(fd);
open_flags |= O_RDONLY;
}
return fd_reopen(dir_fd, open_flags);
}
_cleanup_close_ int _dir_fd = -EBADF;
if (dir_fd == XAT_FDROOT) {
if (path_is_absolute(path))
dir_fd = AT_FDCWD;
else {
_dir_fd = open("/", O_CLOEXEC|O_DIRECTORY|O_PATH);
if (_dir_fd < 0)
return -errno;
dir_fd = _dir_fd;
}
}
bool call_label_ops_post = false;
if (FLAGS_SET(open_flags, O_CREAT) && FLAGS_SET(xopen_flags, XO_LABEL)) {
r = label_ops_pre(dir_fd, path, FLAGS_SET(open_flags, O_DIRECTORY) ? S_IFDIR : S_IFREG, label_context);
if (r < 0)
return r;
call_label_ops_post = true;
}
if (FLAGS_SET(open_flags, O_DIRECTORY|O_CREAT)) {
if (FLAGS_SET(xopen_flags, XO_SUBVOLUME))
r = btrfs_subvol_make_fallback(dir_fd, path, mode);
else
r = RET_NERRNO(mkdirat(dir_fd, path, mode));
if (r == -EEXIST) {
if (FLAGS_SET(open_flags, O_EXCL))
return -EEXIST;
} else if (r < 0)
return r;
else
made_dir = true;
open_flags &= ~(O_EXCL|O_CREAT);
}
if (FLAGS_SET(xopen_flags, XO_REGULAR)) {
/* Guarantee we return a regular fd only, and don't open the file unless we verified it
* first */
if (FLAGS_SET(open_flags, O_PATH)) {
fd = FLAGS_SET(xopen_flags, XO_TRIGGER_AUTOMOUNT) ?
openat_with_automount(dir_fd, path, open_flags, mode) :
RET_NERRNO(openat(dir_fd, path, open_flags, mode));
if (fd < 0) {
r = fd;
goto error;
}
r = fd_verify_regular(fd);
if (r < 0)
goto error;
} else if (FLAGS_SET(open_flags, O_CREAT|O_EXCL)) {
/* In O_EXCL mode we can just create the thing, everything is dealt with for us */
if (FLAGS_SET(xopen_flags, XO_AUTO_RW_RO)) {
fd = RET_NERRNO(openat(dir_fd, path, open_flags|O_RDWR, mode));
if (ERRNO_IS_NEG_FS_WRITE_REFUSED(fd))
open_flags |= O_RDONLY;
else if (fd < 0) {
r = fd;
goto error;
}
}
if (fd < 0) {
fd = openat(dir_fd, path, open_flags, mode);
if (fd < 0) {
r = -errno;
goto error;
}
}
made_file = true;
} else {
/* Otherwise pin the inode first via O_PATH */
_cleanup_close_ int inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC|(open_flags & O_NOFOLLOW));
if (inode_fd < 0) {
if (errno != ENOENT || !FLAGS_SET(open_flags, O_CREAT)) {
r = -errno;
goto error;
}
/* Doesn't exist yet, then try to create it */
open_flags |= O_EXCL;
if (FLAGS_SET(xopen_flags, XO_AUTO_RW_RO)) {
fd = RET_NERRNO(openat(dir_fd, path, open_flags|O_RDWR, mode));
if (ERRNO_IS_NEG_FS_WRITE_REFUSED(fd))
open_flags |= O_RDONLY;
else if (fd < 0) {
r = fd;
goto error;
}
}
if (fd < 0) {
fd = openat(dir_fd, path, open_flags, mode);
if (fd < 0) {
r = -errno;
goto error;
}
}
made_file = true;
} else {
/* OK, we pinned it. Now verify it's actually a regular file, and then reopen it */
r = fd_verify_regular(inode_fd);
if (r < 0)
goto error;
open_flags &= ~(O_NOFOLLOW|O_CREAT);
if (FLAGS_SET(xopen_flags, XO_AUTO_RW_RO)) {
fd = fd_reopen(inode_fd, open_flags|O_RDWR);
if (ERRNO_IS_NEG_FS_WRITE_REFUSED(fd))
open_flags |= O_RDONLY;
else if (fd < 0) {
r = fd;
goto error;
}
}
if (fd < 0) {
fd = fd_reopen(inode_fd, open_flags);
if (fd < 0) {
r = fd;
goto error;
}
}
}
}
} else if (FLAGS_SET(xopen_flags, XO_TRIGGER_AUTOMOUNT)) {
fd = openat_with_automount(dir_fd, path, open_flags, mode);
if (fd < 0) {
r = fd;
goto error;
}
} else {
/* XO_SOCKET also lands here: it requires O_PATH (see asserts above) so openat() pins
* the inode without connecting, and fd_verify_socket() below enforces the type. */
if (FLAGS_SET(xopen_flags, XO_AUTO_RW_RO)) {
fd = openat_report_new(dir_fd, path, O_RDWR|open_flags, mode, &made_file);
if (ERRNO_IS_NEG_FS_WRITE_REFUSED(fd) || fd == -EISDIR)
open_flags |= O_RDONLY;
else if (fd < 0) {
r = fd;
goto error;
}
}
if (fd < 0) {
fd = openat_report_new(dir_fd, path, open_flags, mode, &made_file);
if (fd < 0) {
r = fd;
goto error;
}
}
}
if (FLAGS_SET(xopen_flags, XO_SOCKET)) {
r = fd_verify_socket(fd);
if (r < 0)
goto error;
}
if (call_label_ops_post) {
call_label_ops_post = false;
r = label_ops_post(fd, /* path= */ NULL, made_file || made_dir, label_context);
if (r < 0)
goto error;
}
if (xopen_flags & (XO_COW|XO_NOCOW)) {
r = chattr_fd(fd, FLAGS_SET(xopen_flags, XO_NOCOW) ? FS_NOCOW_FL : 0, FS_NOCOW_FL);
if (r < 0 && !ERRNO_IS_IOCTL_NOT_SUPPORTED(r))
goto error;
}
return TAKE_FD(fd);
error:
if (call_label_ops_post)
(void) label_ops_post(fd >= 0 ? fd : dir_fd, fd >= 0 ? NULL : path, made_dir || made_file, label_context);
if (made_dir || made_file)
(void) unlinkat(dir_fd, path, made_dir ? AT_REMOVEDIR : 0);
return r;
}
int xopenat_lock_full_label(
int dir_fd,
const char *path,
int open_flags,
XOpenFlags xopen_flags,
mode_t mode,
LockType locktype,
int operation,
LabelContext *label_context) {
_cleanup_close_ int fd = -EBADF;
int r;
assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
assert(IN_SET(operation & ~LOCK_NB, LOCK_EX, LOCK_SH));
/* POSIX/UNPOSIX locks don't work on directories (errno is set to -EBADF so let's return early with
* the same error here). */
if (FLAGS_SET(open_flags, O_DIRECTORY) && !IN_SET(locktype, LOCK_BSD, LOCK_NONE))
return -EBADF;
for (;;) {
struct stat st;
fd = xopenat_full_label(dir_fd, path, open_flags, xopen_flags, mode, label_context);
if (fd < 0)
return fd;
r = lock_generic(fd, locktype, operation);
if (r < 0)
return r;
/* If we acquired the lock, let's check if the file/directory still exists in the file
* system. If not, then the previous exclusive owner removed it and then closed it. In such a
* case our acquired lock is worthless, hence try again. */
if (fstat(fd, &st) < 0)
return -errno;
if (st.st_nlink > 0)
break;
fd = safe_close(fd);
}
return TAKE_FD(fd);
}
int link_fd(int fd, int newdirfd, const char *newpath) {
int r;
assert(fd >= 0);
assert(newdirfd >= 0 || newdirfd == AT_FDCWD);
assert(newpath);
/* Try to link via AT_EMPTY_PATH first. This fails with ENOENT if we don't have CAP_DAC_READ_SEARCH
* on kernels < 6.10, in which case we'd then resort to /proc/self/fd/ dance.
*
* See also: https://github.com/torvalds/linux/commit/42bd2af5950456d46fdaa91c3a8fb02e680f19f5 */
r = RET_NERRNO(linkat(fd, "", newdirfd, newpath, AT_EMPTY_PATH));
if (r == -ENOENT) {
r = RET_NERRNO(linkat(AT_FDCWD, FORMAT_PROC_FD_PATH(fd), newdirfd, newpath, AT_SYMLINK_FOLLOW));
if (r == -ENOENT && proc_mounted() == 0) /* No proc_fd_enoent_errno() here because we don't
know if it's the target path that's missing. */
return -ENOSYS;
}
return r;
}
int linkat_replace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
_cleanup_close_ int old_fd = -EBADF;
int r;
assert(olddirfd >= 0 || olddirfd == AT_FDCWD);
assert(newdirfd >= 0 || newdirfd == AT_FDCWD);
assert(!isempty(newpath)); /* source path is optional, but the target path is not */
/* Like linkat() but replaces the target if needed. Is a NOP if source and target already share the
* same inode. */
if (olddirfd == AT_FDCWD && isempty(oldpath)) /* Refuse operating on the cwd (which is a dir, and dirs can't be hardlinked) */
return -EISDIR;
if (path_implies_directory(oldpath)) /* Refuse these definite directories early */
return -EISDIR;
if (path_implies_directory(newpath))
return -EISDIR;
/* First, try to link this directly */
if (oldpath)
r = RET_NERRNO(linkat(olddirfd, oldpath, newdirfd, newpath, 0));
else
r = link_fd(olddirfd, newdirfd, newpath);
if (r >= 0)
return 0;
if (r != -EEXIST)
return r;
old_fd = xopenat(olddirfd, oldpath, O_PATH|O_CLOEXEC);
if (old_fd < 0)
return old_fd;
struct stat old_st;
if (fstat(old_fd, &old_st) < 0)
return -errno;
if (S_ISDIR(old_st.st_mode)) /* Don't bother if we are operating on a directory */
return -EISDIR;
struct stat new_st;
if (fstatat(newdirfd, newpath, &new_st, AT_SYMLINK_NOFOLLOW) < 0)
return -errno;
if (S_ISDIR(new_st.st_mode)) /* Refuse replacing directories */
return -EEXIST;
if (stat_inode_same(&old_st, &new_st)) /* Already the same inode? Then shortcut this */
return 0;
_cleanup_free_ char *tmp_path = NULL;
r = tempfn_random(newpath, /* extra= */ NULL, &tmp_path);
if (r < 0)
return r;
r = link_fd(old_fd, newdirfd, tmp_path);
if (r < 0) {
if (!ERRNO_IS_PRIVILEGE(r))
return r;
/* If that didn't work due to permissions then go via the path of the dentry */
r = RET_NERRNO(linkat(olddirfd, oldpath, newdirfd, tmp_path, 0));
if (r < 0)
return r;
}
r = RET_NERRNO(renameat(newdirfd, tmp_path, newdirfd, newpath));
if (r < 0) {
(void) unlinkat(newdirfd, tmp_path, /* flags= */ 0);
return r;
}
return 0;
}