LibCore: Implement Account::self()

This commit is contained in:
Jean-Baptiste Boric 2021-07-08 19:31:22 +02:00 committed by Andreas Kling
parent 3db1681214
commit fdf638dde0
Notes: sideshowbarker 2024-07-18 09:59:20 +09:00
2 changed files with 40 additions and 0 deletions

View File

@ -66,6 +66,45 @@ Result<Account, String> Account::from_passwd(const passwd& pwd, const spwd& spwd
return account;
}
Account Account::self()
{
struct passwd fallback;
fallback.pw_name = const_cast<char*>("(unknown)");
fallback.pw_uid = getuid();
fallback.pw_gid = getgid();
fallback.pw_gecos = const_cast<char*>("");
fallback.pw_dir = const_cast<char*>("(unknown)");
fallback.pw_shell = const_cast<char*>("(unknown)");
Vector<gid_t> extra_gids;
int extra_gid_count = getgroups(0, nullptr);
if (extra_gid_count) {
extra_gids.resize(extra_gid_count);
int rc = getgroups(extra_gid_count, extra_gids.data());
if (rc < 0)
extra_gids.resize(0);
}
struct passwd* pwd = getpwuid(fallback.pw_uid);
if (!pwd)
pwd = &fallback;
else
pwd->pw_gid = fallback.pw_gid;
spwd spwd_dummy = {};
spwd_dummy.sp_namp = pwd->pw_name;
spwd_dummy.sp_pwdp = const_cast<char*>("");
#ifndef AK_OS_BSD_GENERIC
auto* spwd = getspnam(pwd->pw_name);
if (!spwd)
spwd = &spwd_dummy;
#else
auto* spwd = &spwd_dummy;
#endif
return Account(*pwd, *spwd, extra_gids);
}
Result<Account, String> Account::from_name(const char* username)
{
errno = 0;

View File

@ -27,6 +27,7 @@ struct spwd {
class Account {
public:
static Account self();
static Result<Account, String> from_name(const char* username);
static Result<Account, String> from_uid(uid_t uid);