1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 21:07:35 +00:00

LibCore: Define and use a fallible, OS-independent getgrent(_r) wrapper

Rather than maintaining a list of #ifdef guards to check systems that do
not provide the reentrant version of getgrent, we can use C++ concepts
to let the compiler perform this check for us.

While we're at it, we can also provide this wrapper as fallible to let
the caller TRY calling it.
This commit is contained in:
Timothy Flynn 2022-12-13 15:08:58 -05:00 committed by Tim Flynn
parent 1ee808fae6
commit d09266237d
3 changed files with 61 additions and 31 deletions

View file

@ -86,6 +86,40 @@ static ErrorOr<Optional<struct passwd>> getpwent_impl(Span<char> buffer)
return Optional<struct passwd> {};
}
// clang-format off
template<typename T>
concept SupportsReentrantGetgrent = requires(T group, T* ptr)
{
getgrent_r(&group, nullptr, 0, &ptr);
};
// clang-format on
// Note: This has to be in the global namespace for the extern declaration to trick the compiler
// into finding a declaration of getgrent_r when it doesn't actually exist.
static ErrorOr<Optional<struct group>> getgrent_impl(Span<char> buffer)
{
if constexpr (SupportsReentrantGetgrent<struct group>) {
struct group group;
struct group* ptr = nullptr;
extern int getgrent_r(struct group*, char*, size_t, struct group**);
auto result = getgrent_r(&group, buffer.data(), buffer.size(), &ptr);
if (result == 0 && ptr)
return group;
if (result != 0 && result != ENOENT)
return Error::from_errno(result);
} else {
errno = 0;
if (auto const* group = ::getgrent())
return *group;
if (errno)
return Error::from_errno(errno);
}
return Optional<struct group> {};
}
namespace Core::System {
#ifndef HOST_NAME_MAX
@ -676,6 +710,11 @@ ErrorOr<Optional<struct passwd>> getpwuid(uid_t uid)
return Optional<struct passwd> {};
}
ErrorOr<Optional<struct group>> getgrent(Span<char> buffer)
{
return getgrent_impl(buffer);
}
ErrorOr<Optional<struct group>> getgrgid(gid_t gid)
{
errno = 0;