Serenity Operating System
at master 72 lines 2.5 kB view raw
1/* 2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> 3 * Copyright (c) 2022, Undefine <undefine@undefine.pl> 4 * 5 * SPDX-License-Identifier: BSD-2-Clause 6 */ 7 8#include <LibCore/Account.h> 9#include <LibCore/ArgsParser.h> 10#include <LibCore/GetPassword.h> 11#include <LibCore/System.h> 12#include <LibMain/Main.h> 13#include <unistd.h> 14 15ErrorOr<int> serenity_main(Main::Arguments arguments) 16{ 17 TRY(Core::System::pledge("stdio rpath tty exec id")); 18 19 StringView first_positional; 20 StringView second_positional; 21 DeprecatedString command; 22 bool simulate_login = false; 23 24 Core::ArgsParser args_parser; 25 args_parser.add_positional_argument(first_positional, "See --login", "-", Core::ArgsParser::Required::No); 26 args_parser.add_positional_argument(second_positional, "User to switch to (defaults to user with UID 0)", "user", Core::ArgsParser::Required::No); 27 args_parser.add_option(command, "Command to execute", "command", 'c', "command"); 28 args_parser.add_option(simulate_login, "Simulate login", "login", 'l'); 29 args_parser.parse(arguments); 30 31 StringView user = first_positional; 32 33 if (first_positional == '-') { 34 simulate_login = true; 35 user = second_positional; 36 } 37 38 if (geteuid() != 0) 39 return Error::from_string_literal("Not running as root :("); 40 41 auto account = TRY(user.is_empty() ? Core::Account::from_uid(0) : Core::Account::from_name(user)); 42 43 TRY(Core::System::pledge("stdio rpath tty exec id")); 44 45 if (getuid() != 0 && account.has_password()) { 46 if (!TRY(Core::System::isatty(STDIN_FILENO))) 47 return Error::from_string_literal("Standard input is not a terminal"); 48 49 auto password = TRY(Core::get_password()); 50 if (!account.authenticate(password)) 51 return Error::from_string_literal("Incorrect or disabled password."); 52 } 53 54 TRY(Core::System::pledge("stdio rpath exec id")); 55 56 TRY(account.login()); 57 58 if (simulate_login) 59 TRY(Core::System::chdir(account.home_directory())); 60 61 TRY(Core::System::pledge("stdio exec")); 62 63 TRY(Core::System::setenv("HOME"sv, account.home_directory(), true)); 64 65 if (command.is_null()) { 66 TRY(Core::System::exec(account.shell(), Array<StringView, 1> { account.shell().view() }, Core::System::SearchInPath::No)); 67 } else { 68 TRY(Core::System::exec(account.shell(), Array<StringView, 3> { account.shell().view(), "-c"sv, command.view() }, Core::System::SearchInPath::No)); 69 } 70 71 return 1; 72}