ladybird/Userland/Utilities/groups.cpp

61 lines
1.7 KiB
C++
Raw Normal View History

2021-05-05 14:33:00 +03:00
/*
* Copyright (c) 2021, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Vector.h>
#include <LibCore/Account.h>
#include <LibCore/ArgsParser.h>
2021-12-03 02:31:50 +03:00
#include <LibCore/System.h>
#include <LibMain/Main.h>
2021-05-05 14:33:00 +03:00
#include <grp.h>
#include <unistd.h>
2022-04-01 20:58:27 +03:00
static void print_account_gids(Core::Account const& account)
2021-05-05 14:33:00 +03:00
{
auto* gr = getgrgid(account.gid());
if (!gr) {
outln();
return;
}
out("{}", gr->gr_name);
for (auto& gid : account.extra_gids()) {
gr = getgrgid(gid);
out(" {}", gr->gr_name);
}
outln();
}
2021-12-03 02:31:50 +03:00
ErrorOr<int> serenity_main(Main::Arguments arguments)
2021-05-05 14:33:00 +03:00
{
2021-12-03 02:31:50 +03:00
TRY(Core::System::unveil("/etc/passwd", "r"));
TRY(Core::System::unveil("/etc/group", "r"));
TRY(Core::System::unveil(nullptr, nullptr));
TRY(Core::System::pledge("stdio rpath"));
2021-05-05 14:33:00 +03:00
Vector<DeprecatedString> usernames;
2021-05-05 14:33:00 +03:00
Core::ArgsParser args_parser;
args_parser.set_general_help("Print group memberships for each username or, if no username is specified, for the current process.");
args_parser.add_positional_argument(usernames, "Usernames to list group memberships for", "usernames", Core::ArgsParser::Required::No);
2021-12-03 02:31:50 +03:00
args_parser.parse(arguments);
2021-05-05 14:33:00 +03:00
if (usernames.is_empty()) {
auto account = TRY(Core::Account::from_uid(geteuid(), Core::Account::Read::PasswdOnly));
2021-12-03 02:31:50 +03:00
print_account_gids(account);
2021-05-05 14:33:00 +03:00
}
for (auto const& username : usernames) {
auto result = Core::Account::from_name(username, Core::Account::Read::PasswdOnly);
2021-05-05 14:33:00 +03:00
if (result.is_error()) {
warnln("{} '{}'", result.error(), username);
continue;
}
out("{} : ", username);
print_account_gids(result.value());
}
return 0;
}