From cfbe01ffbe981f48072b16e0fc6225a00138db6d Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Mon, 27 Nov 2023 18:18:23 +0100 Subject: [PATCH] io/Beneath: add OpenDirectoryBeneath() --- src/io/Beneath.cxx | 25 +++++++++++++++++++++++++ src/io/Beneath.hxx | 6 ++++++ 2 files changed, 31 insertions(+) diff --git a/src/io/Beneath.cxx b/src/io/Beneath.cxx index 1e164f529..577c082b8 100644 --- a/src/io/Beneath.cxx +++ b/src/io/Beneath.cxx @@ -35,3 +35,28 @@ OpenReadOnlyBeneath(FileAt file) return fd; } + +static constexpr struct open_how directory_beneath{ + .flags = O_DIRECTORY|O_RDONLY|O_NOCTTY|O_CLOEXEC, + .resolve = RESOLVE_BENEATH|RESOLVE_NO_MAGICLINKS, +}; + +UniqueFileDescriptor +TryOpenDirectoryBeneath(FileAt file) noexcept +{ + assert(file.directory.IsDefined()); + + int fd = openat2(file.directory.Get(), file.name, + &directory_beneath, sizeof(directory_beneath)); + return UniqueFileDescriptor{fd}; +} + +UniqueFileDescriptor +OpenDirectoryBeneath(FileAt file) +{ + auto fd = TryOpenDirectoryBeneath(file); + if (!fd.IsDefined()) + throw FmtErrno("Failed to open '{}'", file.name); + + return fd; +} diff --git a/src/io/Beneath.hxx b/src/io/Beneath.hxx index 09fcf3369..75c2a3676 100644 --- a/src/io/Beneath.hxx +++ b/src/io/Beneath.hxx @@ -11,3 +11,9 @@ TryOpenReadOnlyBeneath(FileAt file) noexcept; UniqueFileDescriptor OpenReadOnlyBeneath(FileAt file); + +UniqueFileDescriptor +TryOpenDirectoryBeneath(FileAt file) noexcept; + +UniqueFileDescriptor +OpenDirectoryBeneath(FileAt file);