1
0
mirror of https://github.com/systemd/systemd.git synced 2024-12-22 17:35:35 +03:00

Merge pull request #24813 from DaanDeMeyer/at-all-the-things

Add more openat() style variants for existing stuff
This commit is contained in:
Luca Boccassi 2022-11-10 10:57:14 +01:00 committed by GitHub
commit 741504aa17
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 425 additions and 240 deletions

View File

@ -57,15 +57,15 @@ static int log_autofs_mount_point(int fd, const char *path, ChaseSymlinksFlags f
strna(n1), path);
}
int chase_symlinks(
int chase_symlinks_at(
int dir_fd,
const char *path,
const char *original_root,
ChaseSymlinksFlags flags,
char **ret_path,
int *ret_fd) {
_cleanup_free_ char *buffer = NULL, *done = NULL, *root = NULL;
_cleanup_close_ int fd = -1;
_cleanup_free_ char *buffer = NULL, *done = NULL;
_cleanup_close_ int fd = -1, root_fd = -1;
unsigned max_follow = CHASE_SYMLINKS_MAX; /* how many symlinks to follow before giving up and returning ELOOP */
bool exists = true, append_trail_slash = false;
struct stat previous_stat;
@ -73,6 +73,8 @@ int chase_symlinks(
int r;
assert(path);
assert(!FLAGS_SET(flags, CHASE_PREFIX_ROOT));
assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
/* Either the file may be missing, or we return an fd to the final object, but both make no sense */
if ((flags & CHASE_NONEXISTENT) && ret_fd)
@ -82,27 +84,36 @@ int chase_symlinks(
return -EINVAL;
if (isempty(path))
return -EINVAL;
path = ".";
/* This is a lot like canonicalize_file_name(), but takes an additional "root" parameter, that allows following
* symlinks relative to a root directory, instead of the root of the host.
/* This function resolves symlinks of the path relative to the given directory file descriptor. If
* CHASE_SYMLINKS_RESOLVE_IN_ROOT is specified, symlinks are resolved relative to the given directory
* file descriptor. Otherwise, they are resolved relative to the root directory of the host.
*
* Note that "root" primarily matters if we encounter an absolute symlink. It is also used when following
* relative symlinks to ensure they cannot be used to "escape" the root directory. The path parameter passed is
* assumed to be already prefixed by it, except if the CHASE_PREFIX_ROOT flag is set, in which case it is first
* prefixed accordingly.
* Note that when CHASE_SYMLINKS_RESOLVE_IN_ROOT is specified and we find an absolute symlink, it is
* resolved relative to given directory file descriptor and not the root of the host. Also, when
* following relative symlinks, this functions ensure they cannot be used to "escape" the given
* directory file descriptor. The "path" parameter is always interpreted relative to the given
* directory file descriptor. If the given directory file descriptor is AT_FDCWD and "path" is
* absolute, it is interpreted relative to the root directory of the host.
*
* Algorithmically this operates on two path buffers: "done" are the components of the path we already
* processed and resolved symlinks, "." and ".." of. "todo" are the components of the path we still need to
* process. On each iteration, we move one component from "todo" to "done", processing it's special meaning
* each time. The "todo" path always starts with at least one slash, the "done" path always ends in no
* slash. We always keep an O_PATH fd to the component we are currently processing, thus keeping lookup races
* to a minimum.
* If "dir_fd" is a valid directory fd, "path" is an absolute path and "ret_path" is not NULL, this
* functions returns a relative path in "ret_path" because openat() like functions generally ignore
* the directory fd if they are provided with an absolute path. On the other hand, if "dir_fd" is
* AT_FDCWD and "path" is an absolute path, we need to return an absolute path in "ret_path" because
* otherwise, if the caller passes the returned relative path to another openat() like function, it
* would be resolved relative to the current working directory instead of to "/".
*
* Suggested usage: whenever you want to canonicalize a path, use this function. Pass the absolute path you got
* as-is: fully qualified and relative to your host's root. Optionally, specify the root parameter to tell this
* function what to do when encountering a symlink with an absolute path as directory: prefix it by the
* specified path.
* Algorithmically this operates on two path buffers: "done" are the components of the path we
* already processed and resolved symlinks, "." and ".." of. "todo" are the components of the path we
* still need to process. On each iteration, we move one component from "todo" to "done", processing
* it's special meaning each time. We always keep an O_PATH fd to the component we are currently
* processing, thus keeping lookup races to a minimum.
*
* Suggested usage: whenever you want to canonicalize a path, use this function. Pass the absolute
* path you got as-is: fully qualified and relative to your host's root. Optionally, specify the
* "dir_fd" parameter to tell this function what to do when encountering a symlink with an absolute
* path as directory: resolve it relative to the given directory file descriptor.
*
* There are five ways to invoke this function:
*
@ -113,34 +124,33 @@ int chase_symlinks(
*
* 2. With ret_fd: in this case the destination is opened after chasing it as O_PATH and this file
* descriptor is returned as return value. This is useful to open files relative to some root
* directory. Note that the returned O_PATH file descriptors must be converted into a regular one (using
* fd_reopen() or such) before it can be used for reading/writing. ret_fd may not be combined with
* CHASE_NONEXISTENT.
* directory. Note that the returned O_PATH file descriptors must be converted into a regular one
* (using fd_reopen() or such) before it can be used for reading/writing. ret_fd may not be
* combined with CHASE_NONEXISTENT.
*
* 3. With CHASE_STEP: in this case only a single step of the normalization is executed, i.e. only the first
* symlink or ".." component of the path is resolved, and the resulting path is returned. This is useful if
* a caller wants to trace the path through the file system verbosely. Returns < 0 on error, > 0 if the
* path is fully normalized, and == 0 for each normalization step. This may be combined with
* CHASE_NONEXISTENT, in which case 1 is returned when a component is not found.
* 3. With CHASE_STEP: in this case only a single step of the normalization is executed, i.e. only
* the first symlink or ".." component of the path is resolved, and the resulting path is
* returned. This is useful if a caller wants to trace the path through the file system verbosely.
* Returns < 0 on error, > 0 if the path is fully normalized, and == 0 for each normalization
* step. This may be combined with CHASE_NONEXISTENT, in which case 1 is returned when a component
* is not found.
*
* 4. With CHASE_SAFE: in this case the path must not contain unsafe transitions, i.e. transitions from
* unprivileged to privileged files or directories. In such cases the return value is -ENOLINK. If
* CHASE_WARN is also set, a warning describing the unsafe transition is emitted. CHASE_WARN cannot
* be used in PID 1.
* 4. With CHASE_SAFE: in this case the path must not contain unsafe transitions, i.e. transitions
* from unprivileged to privileged files or directories. In such cases the return value is
* -ENOLINK. If CHASE_WARN is also set, a warning describing the unsafe transition is emitted.
* CHASE_WARN cannot be used in PID 1.
*
* 5. With CHASE_NO_AUTOFS: in this case if an autofs mount point is encountered, path normalization
* is aborted and -EREMOTE is returned. If CHASE_WARN is also set, a warning showing the path of
* the mount point is emitted. CHASE_WARN cannot be used in PID 1.
*/
/* A root directory of "/" or "" is identical to none */
if (empty_or_root(original_root))
original_root = NULL;
if (!(flags & (CHASE_AT_RESOLVE_IN_ROOT|CHASE_NONEXISTENT|CHASE_NO_AUTOFS|CHASE_SAFE|CHASE_STEP)) &&
!ret_path && ret_fd) {
if (!original_root && !ret_path && !(flags & (CHASE_NONEXISTENT|CHASE_NO_AUTOFS|CHASE_SAFE|CHASE_STEP)) && ret_fd) {
/* Shortcut the ret_fd case if the caller isn't interested in the actual path and has no root set
* and doesn't care about any of the other special features we provide either. */
r = open(path, O_PATH|O_CLOEXEC|((flags & CHASE_NOFOLLOW) ? O_NOFOLLOW : 0));
/* Shortcut the ret_fd case if the caller isn't interested in the actual path and has no root
* set and doesn't care about any of the other special features we provide either. */
r = openat(dir_fd, path, O_PATH|O_CLOEXEC|((flags & CHASE_NOFOLLOW) ? O_NOFOLLOW : 0));
if (r < 0)
return -errno;
@ -148,62 +158,38 @@ int chase_symlinks(
return 0;
}
if (original_root) {
r = path_make_absolute_cwd(original_root, &root);
if (r < 0)
return r;
/* Simplify the root directory, so that it has no duplicate slashes and nothing at the
* end. While we won't resolve the root path we still simplify it. Note that dropping the
* trailing slash should not change behaviour, since when opening it we specify O_DIRECTORY
* anyway. Moreover at the end of this function after processing everything we'll always turn
* the empty string back to "/". */
delete_trailing_chars(root, "/");
path_simplify(root);
if (flags & CHASE_PREFIX_ROOT) {
buffer = path_join(root, path);
buffer = strdup(path);
if (!buffer)
return -ENOMEM;
}
bool need_absolute = !FLAGS_SET(flags, CHASE_AT_RESOLVE_IN_ROOT) && path_is_absolute(path);
if (need_absolute) {
done = strdup("/");
if (!done)
return -ENOMEM;
}
if (!buffer) {
r = path_make_absolute_cwd(path, &buffer);
if (r < 0)
return r;
}
if (FLAGS_SET(flags, CHASE_AT_RESOLVE_IN_ROOT))
root_fd = openat(dir_fd, ".", O_CLOEXEC|O_DIRECTORY|O_PATH);
else
root_fd = open("/", O_CLOEXEC|O_DIRECTORY|O_PATH);
if (root_fd < 0)
return -errno;
fd = open(empty_to_root(root), O_CLOEXEC|O_DIRECTORY|O_PATH);
if (FLAGS_SET(flags, CHASE_AT_RESOLVE_IN_ROOT) || !path_is_absolute(path))
fd = openat(dir_fd, ".", O_CLOEXEC|O_DIRECTORY|O_PATH);
else
fd = open("/", O_CLOEXEC|O_DIRECTORY|O_PATH);
if (fd < 0)
return -errno;
if (flags & CHASE_SAFE)
if (fstat(fd, &previous_stat) < 0)
return -errno;
if (flags & CHASE_TRAIL_SLASH)
append_trail_slash = endswith(buffer, "/") || endswith(buffer, "/.");
if (root) {
/* If we are operating on a root directory, let's take the root directory as it is. */
todo = path_startswith(buffer, root);
if (!todo)
return log_full_errno(flags & CHASE_WARN ? LOG_WARNING : LOG_DEBUG,
SYNTHETIC_ERRNO(ECHRNG),
"Specified path '%s' is outside of specified root directory '%s', refusing to resolve.",
path, root);
done = strdup(root);
} else {
todo = buffer;
done = strdup("/");
}
if (!done)
return -ENOMEM;
for (;;) {
for (todo = buffer;;) {
_cleanup_free_ char *first = NULL;
_cleanup_close_ int child = -1;
struct stat st;
@ -228,34 +214,37 @@ int chase_symlinks(
_cleanup_free_ char *parent = NULL;
_cleanup_close_ int fd_parent = -1;
/* If we already are at the top, then going up will not change anything. This is in-line with
* how the kernel handles this. */
if (empty_or_root(done))
/* If we already are at the top, then going up will not change anything. This is
* in-line with how the kernel handles this. */
if (empty_or_root(done) && FLAGS_SET(flags, CHASE_AT_RESOLVE_IN_ROOT))
continue;
fd_parent = openat(fd, "..", O_CLOEXEC|O_NOFOLLOW|O_PATH|O_DIRECTORY);
if (fd_parent < 0)
return -errno;
if (fstat(fd_parent, &st) < 0)
return -errno;
/* If we opened the same directory, that means we're at the host root directory, so
* going up won't change anything. */
if (st.st_dev == previous_stat.st_dev && st.st_ino == previous_stat.st_ino)
continue;
r = path_extract_directory(done, &parent);
if (r < 0)
return r;
/* Don't allow this to leave the root dir. */
if (root &&
path_startswith(done, root) &&
!path_startswith(parent, root))
continue;
if (r >= 0 || r == -EDESTADDRREQ)
free_and_replace(done, parent);
else if (IN_SET(r, -EINVAL, -EADDRNOTAVAIL)) {
/* If we're at the top of "dir_fd", start appending ".." to "done". */
if (!path_extend(&done, ".."))
return -ENOMEM;
} else
return r;
if (flags & CHASE_STEP)
goto chased_one;
fd_parent = openat(fd, "..", O_CLOEXEC|O_NOFOLLOW|O_PATH);
if (fd_parent < 0)
return -errno;
if (flags & CHASE_SAFE) {
if (fstat(fd_parent, &st) < 0)
return -errno;
if (unsafe_transition(&previous_stat, &st))
return log_unsafe_transition(fd, fd_parent, path, flags);
@ -315,13 +304,13 @@ int chase_symlinks(
if (path_is_absolute(destination)) {
/* An absolute destination. Start the loop from the beginning, but use the root
* directory as base. */
/* An absolute destination. Start the loop from the beginning, but use the
* root file descriptor as base. */
safe_close(fd);
fd = open(empty_to_root(root), O_CLOEXEC|O_DIRECTORY|O_PATH);
fd = fd_reopen(root_fd, O_CLOEXEC|O_PATH|O_DIRECTORY);
if (fd < 0)
return -errno;
return fd;
if (flags & CHASE_SAFE) {
if (fstat(fd, &st) < 0)
@ -333,8 +322,7 @@ int chase_symlinks(
previous_stat = st;
}
/* Note that we do not revalidate the root, we take it as is. */
r = free_and_strdup(&done, empty_to_root(root));
r = free_and_strdup(&done, need_absolute ? "/" : NULL);
if (r < 0)
return r;
}
@ -401,6 +389,88 @@ chased_one:
return 0;
}
int chase_symlinks(
const char *path,
const char *original_root,
ChaseSymlinksFlags flags,
char **ret_path,
int *ret_fd) {
_cleanup_free_ char *root = NULL, *absolute = NULL, *p = NULL;
_cleanup_close_ int fd = -1, pfd = -1;
int r;
assert(path);
if (isempty(path))
return -EINVAL;
/* A root directory of "/" or "" is identical to none */
if (empty_or_root(original_root))
original_root = NULL;
if (original_root) {
r = path_make_absolute_cwd(original_root, &root);
if (r < 0)
return r;
/* Simplify the root directory, so that it has no duplicate slashes and nothing at the
* end. While we won't resolve the root path we still simplify it. Note that dropping the
* trailing slash should not change behaviour, since when opening it we specify O_DIRECTORY
* anyway. Moreover at the end of this function after processing everything we'll always turn
* the empty string back to "/". */
delete_trailing_chars(root, "/");
path_simplify(root);
if (flags & CHASE_PREFIX_ROOT) {
absolute = path_join(root, path);
if (!absolute)
return -ENOMEM;
}
}
if (!absolute) {
r = path_make_absolute_cwd(path, &absolute);
if (r < 0)
return r;
}
if (root) {
path = path_startswith(absolute, root);
if (!path)
return log_full_errno(flags & CHASE_WARN ? LOG_WARNING : LOG_DEBUG,
SYNTHETIC_ERRNO(ECHRNG),
"Specified path '%s' is outside of specified root directory '%s', refusing to resolve.",
absolute, root);
}
if (root) {
fd = open(root, O_CLOEXEC|O_DIRECTORY|O_PATH);
if (fd < 0)
return -errno;
flags |= CHASE_AT_RESOLVE_IN_ROOT;
} else
fd = AT_FDCWD;
r = chase_symlinks_at(fd, path, flags & ~CHASE_PREFIX_ROOT, ret_path ? &p : NULL, ret_fd ? &pfd : NULL);
if (r < 0)
return r;
if (ret_path) {
char *q = path_join(root, p);
if (!q)
return -ENOMEM;
*ret_path = TAKE_PTR(q);
}
if (ret_fd)
*ret_fd = TAKE_FD(pfd);
return r;
}
int chase_symlinks_and_open(
const char *path,
const char *root,

View File

@ -17,6 +17,8 @@ typedef enum ChaseSymlinksFlags {
* right-most component refers to symlink, return O_PATH fd of the symlink. */
CHASE_WARN = 1 << 7, /* Emit an appropriate warning when an error is encountered.
* Note: this may do an NSS lookup, hence this flag cannot be used in PID 1. */
CHASE_AT_RESOLVE_IN_ROOT = 1 << 8, /* Same as openat2()'s RESOLVE_IN_ROOT flag, symlinks are resolved
* relative to the given directory fd instead of root. */
} ChaseSymlinksFlags;
bool unsafe_transition(const struct stat *a, const struct stat *b);
@ -31,3 +33,5 @@ int chase_symlinks_and_opendir(const char *path, const char *root, ChaseSymlinks
int chase_symlinks_and_stat(const char *path, const char *root, ChaseSymlinksFlags chase_flags, char **ret_path, struct stat *ret_stat, int *ret_fd);
int chase_symlinks_and_access(const char *path, const char *root, ChaseSymlinksFlags chase_flags, int access_mode, char **ret_path, int *ret_fd);
int chase_symlinks_and_fopen_unlocked(const char *path, const char *root, ChaseSymlinksFlags chase_flags, const char *open_flags, char **ret_path, FILE **ret_file);
int chase_symlinks_at(int dir_fd, const char *path, ChaseSymlinksFlags flags, char **ret_path, int *ret_fd);

View File

@ -43,16 +43,17 @@
* can detect EOFs. */
#define READ_VIRTUAL_BYTES_MAX (4U*1024U*1024U - 2U)
int fopen_unlocked(const char *path, const char *options, FILE **ret) {
int fopen_unlocked_at(int dir_fd, const char *path, const char *options, int flags, FILE **ret) {
int r;
assert(ret);
FILE *f = fopen(path, options);
if (!f)
return -errno;
r = xfopenat(dir_fd, path, options, flags, ret);
if (r < 0)
return r;
(void) __fsetlocking(f, FSETLOCKING_BYCALLER);
(void) __fsetlocking(*ret, FSETLOCKING_BYCALLER);
*ret = f;
return 0;
}
@ -209,7 +210,8 @@ int write_string_stream_ts(
return 0;
}
static int write_string_file_atomic(
static int write_string_file_atomic_at(
int dir_fd,
const char *fn,
const char *line,
WriteStringFileFlags flags,
@ -225,7 +227,7 @@ static int write_string_file_atomic(
/* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
* semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
r = fopen_temporary(fn, &f, &p);
r = fopen_temporary_at(dir_fd, fn, &f, &p);
if (r < 0)
return r;
@ -237,7 +239,7 @@ static int write_string_file_atomic(
if (r < 0)
goto fail;
if (rename(p, fn) < 0) {
if (renameat(dir_fd, p, dir_fd, fn) < 0) {
r = -errno;
goto fail;
}
@ -252,11 +254,12 @@ static int write_string_file_atomic(
return 0;
fail:
(void) unlink(p);
(void) unlinkat(dir_fd, p, 0);
return r;
}
int write_string_file_ts(
int write_string_file_ts_at(
int dir_fd,
const char *fn,
const char *line,
WriteStringFileFlags flags,
@ -272,7 +275,7 @@ int write_string_file_ts(
assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
if (flags & WRITE_STRING_FILE_MKDIR_0755) {
r = mkdir_parents(fn, 0755);
r = mkdirat_parents(dir_fd, fn, 0755);
if (r < 0)
return r;
}
@ -280,7 +283,7 @@ int write_string_file_ts(
if (flags & WRITE_STRING_FILE_ATOMIC) {
assert(flags & WRITE_STRING_FILE_CREATE);
r = write_string_file_atomic(fn, line, flags, ts);
r = write_string_file_atomic_at(dir_fd, fn, line, flags, ts);
if (r < 0)
goto fail;
@ -289,7 +292,7 @@ int write_string_file_ts(
assert(!ts);
/* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
fd = open(fn, O_CLOEXEC|O_NOCTTY |
fd = openat(dir_fd, fn, O_CLOEXEC|O_NOCTTY |
(FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) |
(FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) |
(FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
@ -364,7 +367,7 @@ int read_one_line_file(const char *fn, char **line) {
return read_line(f, LONG_LINE_MAX, line);
}
int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
int verify_file_at(int dir_fd, const char *fn, const char *blob, bool accept_extra_nl) {
_cleanup_fclose_ FILE *f = NULL;
_cleanup_free_ char *buf = NULL;
size_t l, k;
@ -382,7 +385,7 @@ int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
if (!buf)
return -ENOMEM;
r = fopen_unlocked(fn, "re", &f);
r = fopen_unlocked_at(dir_fd, fn, "re", 0, &f);
if (r < 0)
return r;

View File

@ -43,7 +43,10 @@ typedef enum {
READ_FULL_FILE_FAIL_WHEN_LARGER = 1 << 5, /* fail loading if file is larger than specified size */
} ReadFullFileFlags;
int fopen_unlocked(const char *path, const char *options, FILE **ret);
int fopen_unlocked_at(int dir_fd, const char *path, const char *options, int flags, FILE **ret);
static inline int fopen_unlocked(const char *path, const char *options, FILE **ret) {
return fopen_unlocked_at(AT_FDCWD, path, options, 0, ret);
}
int fdopen_unlocked(int fd, const char *options, FILE **ret);
int take_fdopen_unlocked(int *fd, const char *options, FILE **ret);
FILE* take_fdopen(int *fd, const char *options);
@ -55,7 +58,13 @@ int write_string_stream_ts(FILE *f, const char *line, WriteStringFileFlags flags
static inline int write_string_stream(FILE *f, const char *line, WriteStringFileFlags flags) {
return write_string_stream_ts(f, line, flags, NULL);
}
int write_string_file_ts(const char *fn, const char *line, WriteStringFileFlags flags, const struct timespec *ts);
int write_string_file_ts_at(int dir_fd, const char *fn, const char *line, WriteStringFileFlags flags, const struct timespec *ts);
static inline int write_string_file_ts(const char *fn, const char *line, WriteStringFileFlags flags, const struct timespec *ts) {
return write_string_file_ts_at(AT_FDCWD, fn, line, flags, ts);
}
static inline int write_string_file_at(int dir_fd, const char *fn, const char *line, WriteStringFileFlags flags) {
return write_string_file_ts_at(dir_fd, fn, line, flags, NULL);
}
static inline int write_string_file(const char *fn, const char *line, WriteStringFileFlags flags) {
return write_string_file_ts(fn, line, flags, NULL);
}
@ -64,6 +73,9 @@ int write_string_filef(const char *fn, WriteStringFileFlags flags, const char *f
int read_one_line_file(const char *filename, char **line);
int read_full_file_full(int dir_fd, const char *filename, uint64_t offset, size_t size, ReadFullFileFlags flags, const char *bind_name, char **ret_contents, size_t *ret_size);
static inline int read_full_file_at(int dir_fd, const char *filename, char **ret_contents, size_t *ret_size) {
return read_full_file_full(dir_fd, filename, UINT64_MAX, SIZE_MAX, 0, NULL, ret_contents, ret_size);
}
static inline int read_full_file(const char *filename, char **ret_contents, size_t *ret_size) {
return read_full_file_full(AT_FDCWD, filename, UINT64_MAX, SIZE_MAX, 0, NULL, ret_contents, ret_size);
}
@ -82,7 +94,10 @@ static inline int read_full_stream(FILE *f, char **ret_contents, size_t *ret_siz
return read_full_stream_full(f, NULL, UINT64_MAX, SIZE_MAX, 0, ret_contents, ret_size);
}
int verify_file(const char *fn, const char *blob, bool accept_extra_nl);
int verify_file_at(int dir_fd, const char *fn, const char *blob, bool accept_extra_nl);
static inline int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
return verify_file_at(AT_FDCWD, fn, blob, accept_extra_nl);
}
int executable_is_script(const char *path, char **interpreter);

View File

@ -194,17 +194,17 @@ int readlink_and_make_absolute(const char *p, char **r) {
return 0;
}
int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
int chmod_and_chown_at(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid) {
_cleanup_close_ int fd = -1;
assert(path);
fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW); /* Let's acquire an O_PATH fd, as precaution to change
* mode/owner on the same file */
if (path) {
/* Let's acquire an O_PATH fd, as precaution to change mode/owner on the same file */
fd = openat(dir_fd, path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
if (fd < 0)
return -errno;
}
return fchmod_and_chown(fd, mode, uid, gid);
return fchmod_and_chown(path ? fd : dir_fd, mode, uid, gid);
}
int fchmod_and_chown_with_fallback(int fd, const char *path, mode_t mode, uid_t uid, gid_t gid) {

View File

@ -33,7 +33,10 @@ int readlink_malloc(const char *p, char **r);
int readlink_value(const char *p, char **ret);
int readlink_and_make_absolute(const char *p, char **r);
int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid);
int chmod_and_chown_at(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid);
static inline int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
return chmod_and_chown_at(AT_FDCWD, path, mode, uid, gid);
}
int fchmod_and_chown_with_fallback(int fd, const char *path, mode_t mode, uid_t uid, gid_t gid);
static inline int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
return fchmod_and_chown_with_fallback(fd, NULL, mode, uid, gid); /* no fallback */

View File

@ -16,7 +16,8 @@
#include "stdio-util.h"
#include "user-util.h"
int mkdir_safe_internal(
int mkdirat_safe_internal(
int dir_fd,
const char *path,
mode_t mode,
uid_t uid,
@ -31,27 +32,27 @@ int mkdir_safe_internal(
assert(mode != MODE_INVALID);
assert(_mkdirat && _mkdirat != mkdirat);
if (_mkdirat(AT_FDCWD, path, mode) >= 0) {
r = chmod_and_chown(path, mode, uid, gid);
if (_mkdirat(dir_fd, path, mode) >= 0) {
r = chmod_and_chown_at(dir_fd, path, mode, uid, gid);
if (r < 0)
return r;
}
if (lstat(path, &st) < 0)
if (fstatat(dir_fd, path, &st, AT_SYMLINK_NOFOLLOW) < 0)
return -errno;
if ((flags & MKDIR_FOLLOW_SYMLINK) && S_ISLNK(st.st_mode)) {
_cleanup_free_ char *p = NULL;
r = chase_symlinks(path, NULL, CHASE_NONEXISTENT, &p, NULL);
r = chase_symlinks_at(dir_fd, path, CHASE_NONEXISTENT, &p, NULL);
if (r < 0)
return r;
if (r == 0)
return mkdir_safe_internal(p, mode, uid, gid,
return mkdirat_safe_internal(dir_fd, p, mode, uid, gid,
flags & ~MKDIR_FOLLOW_SYMLINK,
_mkdirat);
if (lstat(p, &st) < 0)
if (fstatat(dir_fd, p, &st, AT_SYMLINK_NOFOLLOW) < 0)
return -errno;
}
@ -87,50 +88,43 @@ int mkdirat_errno_wrapper(int dirfd, const char *pathname, mode_t mode) {
return RET_NERRNO(mkdirat(dirfd, pathname, mode));
}
int mkdir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdir_safe_internal(path, mode, uid, gid, flags, mkdirat_errno_wrapper);
int mkdirat_safe(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdirat_safe_internal(dir_fd, path, mode, uid, gid, flags, mkdirat_errno_wrapper);
}
int mkdir_parents_internal(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdirat) {
const char *p, *e = NULL;
int mkdirat_parents_internal(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdirat) {
const char *e = NULL;
int r;
assert(path);
assert(_mkdirat != mkdirat);
if (prefix) {
p = path_startswith_full(path, prefix, /* accept_dot_dot= */ false);
if (!p)
return -ENOTDIR;
} else
p = path;
if (isempty(p))
if (isempty(path))
return 0;
if (!path_is_safe(p))
if (!path_is_safe(path))
return -ENOTDIR;
/* return immediately if directory exists */
r = path_find_last_component(p, /* accept_dot_dot= */ false, &e, NULL);
r = path_find_last_component(path, /* accept_dot_dot= */ false, &e, NULL);
if (r <= 0) /* r == 0 means path is equivalent to prefix. */
return r;
if (e == p)
if (e == path)
return 0;
assert(e > p);
assert(e > path);
assert(*e == '/');
/* drop the last component */
path = strndupa_safe(path, e - path);
r = is_dir(path, true);
r = is_dir_full(dir_fd, path, true);
if (r > 0)
return 0;
if (r == 0)
return -ENOTDIR;
/* create every parent directory in the path, except the last component */
for (p = path;;) {
for (const char *p = path;;) {
char *s;
int n;
@ -144,18 +138,39 @@ int mkdir_parents_internal(const char *prefix, const char *path, mode_t mode, ui
s[n] = '\0';
if (!prefix || !path_startswith_full(prefix, path, /* accept_dot_dot= */ false)) {
r = mkdir_safe_internal(path, mode, uid, gid, flags | MKDIR_IGNORE_EXISTING, _mkdirat);
r = mkdirat_safe_internal(dir_fd, path, mode, uid, gid, flags | MKDIR_IGNORE_EXISTING, _mkdirat);
if (r < 0 && r != -EEXIST)
return r;
}
s[n] = *p == '\0' ? '\0' : '/';
}
}
int mkdir_parents(const char *path, mode_t mode) {
return mkdir_parents_internal(NULL, path, mode, UID_INVALID, UID_INVALID, 0, mkdirat_errno_wrapper);
int mkdir_parents_internal(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdirat) {
_cleanup_close_ int fd = AT_FDCWD;
const char *p;
assert(path);
assert(_mkdirat != mkdirat);
if (prefix) {
p = path_startswith_full(path, prefix, /* accept_dot_dot= */ false);
if (!p)
return -ENOTDIR;
} else
p = path;
if (prefix) {
fd = open(prefix, O_PATH|O_DIRECTORY|O_CLOEXEC);
if (fd < 0)
return -errno;
}
return mkdirat_parents_internal(fd, p, mode, uid, gid, flags, _mkdirat);
}
int mkdirat_parents(int dir_fd, const char *path, mode_t mode) {
return mkdirat_parents_internal(dir_fd, path, mode, UID_INVALID, UID_INVALID, 0, mkdirat_errno_wrapper);
}
int mkdir_parents_safe(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {

View File

@ -1,6 +1,7 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <fcntl.h>
#include <sys/types.h>
typedef enum MkdirFlags {
@ -11,8 +12,14 @@ typedef enum MkdirFlags {
int mkdirat_errno_wrapper(int dirfd, const char *pathname, mode_t mode);
int mkdir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags);
int mkdir_parents(const char *path, mode_t mode);
int mkdirat_safe(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags);
static inline int mkdir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdirat_safe(AT_FDCWD, path, mode, uid, gid, flags);
}
int mkdirat_parents(int dir_fd, const char *path, mode_t mode);
static inline int mkdir_parents(const char *path, mode_t mode) {
return mkdirat_parents(AT_FDCWD, path, mode);
}
int mkdir_parents_safe(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags);
int mkdir_p(const char *path, mode_t mode);
int mkdir_p_safe(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags);
@ -20,6 +27,10 @@ int mkdir_p_root(const char *root, const char *p, uid_t uid, gid_t gid, mode_t m
/* The following are used to implement the mkdir_xyz_label() calls, don't use otherwise. */
typedef int (*mkdirat_func_t)(int dir_fd, const char *pathname, mode_t mode);
int mkdir_safe_internal(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdir);
int mkdirat_safe_internal(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdir);
static inline int mkdir_safe_internal(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdir) {
return mkdirat_safe_internal(AT_FDCWD, path, mode, uid, gid, flags, _mkdir);
}
int mkdirat_parents_internal(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdirat);
int mkdir_parents_internal(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdir);
int mkdir_p_internal(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags, mkdirat_func_t _mkdir);

View File

@ -221,6 +221,33 @@ int path_make_relative_parent(const char *from_child, const char *to, char **ret
return path_make_relative(from, to, ret);
}
int path_make_relative_cwd(const char *p, char **ret) {
char *c;
int r;
assert(p);
assert(ret);
if (path_is_absolute(p)) {
_cleanup_free_ char *cwd = NULL;
r = safe_getcwd(&cwd);
if (r < 0)
return r;
r = path_make_relative(cwd, p, &c);
if (r < 0)
return r;
} else {
c = strdup(p);
if (!c)
return -ENOMEM;
}
*ret = TAKE_PTR(c);
return 0;
}
char* path_startswith_strv(const char *p, char **set) {
STRV_FOREACH(s, set) {
char *t;

View File

@ -62,6 +62,7 @@ int safe_getcwd(char **ret);
int path_make_absolute_cwd(const char *p, char **ret);
int path_make_relative(const char *from, const char *to, char **ret);
int path_make_relative_parent(const char *from_child, const char *to, char **ret);
int path_make_relative_cwd(const char *from, char **ret);
char *path_startswith_full(const char *path, const char *prefix, bool accept_dot_dot) _pure_;
static inline char* path_startswith(const char *path, const char *prefix) {
return path_startswith_full(path, prefix, true);

View File

@ -19,14 +19,14 @@
#include "tmpfile-util.h"
#include "umask-util.h"
int fopen_temporary(const char *path, FILE **ret_f, char **ret_temp_path) {
int fopen_temporary_at(int dir_fd, const char *path, FILE **ret_file, char **ret_temp_path) {
_cleanup_fclose_ FILE *f = NULL;
_cleanup_free_ char *t = NULL;
_cleanup_close_ int fd = -1;
int r;
if (path) {
r = tempfn_xxxxxx(path, NULL, &t);
r = tempfn_random(path, NULL, &t);
if (r < 0)
return r;
} else {
@ -36,12 +36,12 @@ int fopen_temporary(const char *path, FILE **ret_f, char **ret_temp_path) {
if (r < 0)
return r;
t = path_join(d, "XXXXXX");
if (!t)
return -ENOMEM;
r = tempfn_random_child(d, NULL, &t);
if (r < 0)
return r;
}
fd = mkostemp_safe(t);
fd = openat(dir_fd, t, O_CLOEXEC|O_NOCTTY|O_RDWR|O_CREAT|O_EXCL, 0600);
if (fd < 0)
return -errno;
@ -50,12 +50,12 @@ int fopen_temporary(const char *path, FILE **ret_f, char **ret_temp_path) {
r = take_fdopen_unlocked(&fd, "w", &f);
if (r < 0) {
(void) unlink(t);
(void) unlinkat(dir_fd, t, 0);
return r;
}
if (ret_f)
*ret_f = TAKE_PTR(f);
if (ret_file)
*ret_file = TAKE_PTR(f);
if (ret_temp_path)
*ret_temp_path = TAKE_PTR(t);
@ -358,3 +358,23 @@ int mkdtemp_malloc(const char *template, char **ret) {
*ret = TAKE_PTR(p);
return 0;
}
int mkdtemp_open(const char *template, int flags, char **ret) {
_cleanup_free_ char *p = NULL;
int fd, r;
r = mkdtemp_malloc(template, &p);
if (r < 0)
return r;
fd = RET_NERRNO(open(p, O_DIRECTORY|O_CLOEXEC|flags));
if (fd < 0) {
(void) rmdir(p);
return fd;
}
if (ret)
*ret = TAKE_PTR(p);
return fd;
}

View File

@ -1,9 +1,13 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <fcntl.h>
#include <stdio.h>
int fopen_temporary(const char *path, FILE **_f, char **_temp_path);
int fopen_temporary_at(int dir_fd, const char *path, FILE **ret_file, char **ret_path);
static inline int fopen_temporary(const char *path, FILE **ret_file, char **ret_path) {
return fopen_temporary_at(AT_FDCWD, path, ret_file, ret_path);
}
int mkostemp_safe(char *pattern);
int fmkostemp_safe(char *pattern, const char *mode, FILE**_f);
@ -19,3 +23,4 @@ int link_tmpfile(int fd, const char *path, const char *target);
int flink_tmpfile(FILE *f, const char *path, const char *target);
int mkdtemp_malloc(const char *template, char **ret);
int mkdtemp_open(const char *template, int flags, char **ret);

View File

@ -25,12 +25,12 @@ int mkdirat_label(int dirfd, const char *path, mode_t mode) {
return mac_smack_fix_full(dirfd, path, NULL, 0);
}
int mkdir_safe_label(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdir_safe_internal(path, mode, uid, gid, flags, mkdirat_label);
int mkdirat_safe_label(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdirat_safe_internal(dir_fd, path, mode, uid, gid, flags, mkdirat_label);
}
int mkdir_parents_label(const char *path, mode_t mode) {
return mkdir_parents_internal(NULL, path, mode, UID_INVALID, UID_INVALID, 0, mkdirat_label);
int mkdirat_parents_label(int dir_fd, const char *path, mode_t mode) {
return mkdirat_parents_internal(dir_fd, path, mode, UID_INVALID, UID_INVALID, 0, mkdirat_label);
}
int mkdir_p_label(const char *path, mode_t mode) {

View File

@ -12,6 +12,12 @@ static inline int mkdir_label(const char *path, mode_t mode) {
return mkdirat_label(AT_FDCWD, path, mode);
}
int mkdir_safe_label(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags);
int mkdir_parents_label(const char *path, mode_t mod);
int mkdirat_safe_label(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags);
static inline int mkdir_safe_label(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdirat_safe_label(AT_FDCWD, path, mode, uid, gid, flags);
}
int mkdirat_parents_label(int dir_fd, const char *path, mode_t mod);
static inline int mkdir_parents_label(const char *path, mode_t mod) {
return mkdirat_parents_label(AT_FDCWD, path, mod);
}
int mkdir_p_label(const char *path, mode_t mode);

View File

@ -5,6 +5,7 @@
#include "alloc-util.h"
#include "errno-util.h"
#include "fd-util.h"
typedef enum RemoveFlags {
REMOVE_ONLY_DIRECTORIES = 1 << 0, /* Only remove empty directories, no files */
@ -51,3 +52,19 @@ static inline char *rm_rf_subvolume_and_free(char *p) {
return mfree(p);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(char*, rm_rf_subvolume_and_free);
static inline int rm_rf_physical_and_close(int fd) {
_cleanup_free_ char *p = NULL;
if (fd < 0)
return -1;
if (fd_get_path(fd, &p) < 0)
return safe_close(fd);
safe_close(fd);
(void) rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK|REMOVE_CHMOD);
return -1;
}
DEFINE_TRIVIAL_CLEANUP_FUNC(int, rm_rf_physical_and_close);

View File

@ -49,11 +49,11 @@ TEST(copy_file) {
unlink(fn_copy);
}
static bool read_file_and_streq(const char* filepath, const char* expected_contents) {
static bool read_file_at_and_streq(int dir_fd, const char *path, const char *expected) {
_cleanup_free_ char *buf = NULL;
assert_se(read_full_file(filepath, &buf, NULL) == 0);
return streq(buf, expected_contents);
assert_se(read_full_file_at(dir_fd, path, &buf, NULL) == 0);
return streq(buf, expected);
}
TEST(copy_tree_replace_file) {
@ -69,53 +69,41 @@ TEST(copy_tree_replace_file) {
assert_se(copy_tree(src, dst, UID_INVALID, GID_INVALID, COPY_REFLINK) == -EEXIST);
assert_se(read_file_and_streq(dst, "foo foo foo\n"));
assert_se(read_file_at_and_streq(AT_FDCWD, dst, "foo foo foo\n"));
assert_se(copy_tree(src, dst, UID_INVALID, GID_INVALID, COPY_REFLINK|COPY_REPLACE) == 0);
assert_se(read_file_and_streq(dst, "bar bar\n"));
assert_se(read_file_at_and_streq(AT_FDCWD, dst, "bar bar\n"));
}
TEST(copy_tree_replace_dirs) {
_cleanup_free_ char *src_path1 = NULL, *src_path2 = NULL, *dst_path1 = NULL, *dst_path2 = NULL;
_cleanup_(rm_rf_physical_and_freep) char *src_directory = NULL, *dst_directory = NULL;
const char *file1 = "foo_file", *file2 = "bar_file";
_cleanup_(rm_rf_physical_and_closep) int src = -1, dst = -1;
/* Create the random source/destination directories */
assert_se(mkdtemp_malloc("/tmp/dirXXXXXX", &src_directory) >= 0);
assert_se(mkdtemp_malloc("/tmp/dirXXXXXX", &dst_directory) >= 0);
/* Construct the source/destination filepaths (should have different dir name, but same file names within) */
assert_se(src_path1 = path_join(src_directory, file1));
assert_se(src_path2 = path_join(src_directory, file2));
assert_se(dst_path1 = path_join(dst_directory, file1));
assert_se(dst_path2 = path_join(dst_directory, file2));
assert_se((src = mkdtemp_open(NULL, 0, NULL)) >= 0);
assert_se((dst = mkdtemp_open(NULL, 0, NULL)) >= 0);
/* Populate some data to differentiate the files. */
assert_se(write_string_file(src_path1, "src file 1", WRITE_STRING_FILE_CREATE) == 0);
assert_se(write_string_file(src_path2, "src file 2", WRITE_STRING_FILE_CREATE) == 0);
assert_se(write_string_file_at(src, "foo", "src file 1", WRITE_STRING_FILE_CREATE) >= 0);
assert_se(write_string_file_at(src, "bar", "src file 2", WRITE_STRING_FILE_CREATE) == 0);
assert_se(write_string_file(dst_path1, "dest file 1", WRITE_STRING_FILE_CREATE) == 0);
assert_se(write_string_file(dst_path2, "dest file 2", WRITE_STRING_FILE_CREATE) == 0);
assert_se(write_string_file_at(dst, "foo", "dest file 1", WRITE_STRING_FILE_CREATE) == 0);
assert_se(write_string_file_at(dst, "bar", "dest file 2", WRITE_STRING_FILE_CREATE) == 0);
/* Copying without COPY_REPLACE should fail because the destination file already exists. */
assert_se(copy_tree(src_directory, dst_directory, UID_INVALID, GID_INVALID, COPY_REFLINK) == -EEXIST);
assert_se(copy_tree_at(src, ".", dst, ".", UID_INVALID, GID_INVALID, COPY_REFLINK) == -EEXIST);
{
assert_se(read_file_and_streq(src_path1, "src file 1\n"));
assert_se(read_file_and_streq(src_path2, "src file 2\n"));
assert_se(read_file_and_streq(dst_path1, "dest file 1\n"));
assert_se(read_file_and_streq(dst_path2, "dest file 2\n"));
}
assert_se(read_file_at_and_streq(src, "foo", "src file 1\n"));
assert_se(read_file_at_and_streq(src, "bar", "src file 2\n"));
assert_se(read_file_at_and_streq(dst, "foo", "dest file 1\n"));
assert_se(read_file_at_and_streq(dst, "bar", "dest file 2\n"));
assert_se(copy_tree(src_directory, dst_directory, UID_INVALID, GID_INVALID, COPY_REFLINK|COPY_REPLACE|COPY_MERGE) == 0);
assert_se(copy_tree_at(src, ".", dst, ".", UID_INVALID, GID_INVALID, COPY_REFLINK|COPY_REPLACE|COPY_MERGE) == 0);
{
assert_se(read_file_and_streq(src_path1, "src file 1\n"));
assert_se(read_file_and_streq(src_path2, "src file 2\n"));
assert_se(read_file_and_streq(dst_path1, "src file 1\n"));
assert_se(read_file_and_streq(dst_path2, "src file 2\n"));
}
assert_se(read_file_at_and_streq(src, "foo", "src file 1\n"));
assert_se(read_file_at_and_streq(src, "bar", "src file 2\n"));
assert_se(read_file_at_and_streq(dst, "foo", "src file 1\n"));
assert_se(read_file_at_and_streq(dst, "bar", "src file 2\n"));
}
TEST(copy_file_fd) {