Serenity Operating System
at master 101 lines 3.1 kB view raw
1/* 2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/DeprecatedString.h> 8#include <AK/Vector.h> 9#include <LibCore/ArgsParser.h> 10#include <LibCore/DirIterator.h> 11#include <LibCore/System.h> 12#include <LibMain/Main.h> 13#include <grp.h> 14#include <pwd.h> 15#include <stdio.h> 16#include <string.h> 17#include <sys/stat.h> 18#include <unistd.h> 19 20ErrorOr<int> serenity_main(Main::Arguments arguments) 21{ 22 TRY(Core::System::pledge("stdio rpath chown")); 23 24 DeprecatedString spec; 25 Vector<StringView> paths; 26 bool no_dereference = false; 27 bool recursive = false; 28 bool follow_symlinks = false; 29 30 Core::ArgsParser args_parser; 31 args_parser.set_general_help("Change the ownership of a file or directory."); 32 args_parser.add_option(no_dereference, "Don't follow symlinks", "no-dereference", 'h'); 33 args_parser.add_option(recursive, "Change file ownership recursively", "recursive", 'R'); 34 args_parser.add_option(follow_symlinks, "Follow symlinks while recursing into directories", nullptr, 'L'); 35 args_parser.add_positional_argument(spec, "User and group IDs", "USER[:GROUP]"); 36 args_parser.add_positional_argument(paths, "Paths to files", "PATH"); 37 args_parser.parse(arguments); 38 39 uid_t new_uid = -1; 40 gid_t new_gid = -1; 41 42 auto parts = spec.split_view(':', SplitBehavior::KeepEmpty); 43 if (parts[0].is_empty() || (parts.size() == 2 && parts[1].is_empty()) || parts.size() > 2) { 44 warnln("Invalid uid/gid spec"); 45 return 1; 46 } 47 48 auto number = parts[0].to_uint(); 49 if (number.has_value()) { 50 new_uid = number.value(); 51 } else { 52 auto passwd = TRY(Core::System::getpwnam(parts[0])); 53 if (!passwd.has_value()) { 54 warnln("Unknown user '{}'", parts[0]); 55 return 1; 56 } 57 new_uid = passwd->pw_uid; 58 } 59 60 if (parts.size() == 2) { 61 auto number = parts[1].to_uint(); 62 if (number.has_value()) { 63 new_gid = number.value(); 64 } else { 65 auto group = TRY(Core::System::getgrnam(parts[1])); 66 if (!group.has_value()) { 67 warnln("Unknown group '{}'", parts[1]); 68 return 1; 69 } 70 new_gid = group->gr_gid; 71 } 72 } 73 74 Function<ErrorOr<void>(StringView)> update_path_owner = [&](StringView path) -> ErrorOr<void> { 75 auto stat = TRY(Core::System::lstat(path)); 76 77 if (S_ISLNK(stat.st_mode) && !follow_symlinks && !paths.contains_slow(path)) 78 return {}; 79 80 if (no_dereference) { 81 TRY(Core::System::lchown(path, new_uid, new_gid)); 82 } else { 83 TRY(Core::System::chown(path, new_uid, new_gid)); 84 } 85 86 if (recursive && S_ISDIR(stat.st_mode)) { 87 Core::DirIterator it(path, Core::DirIterator::Flags::SkipParentAndBaseDir); 88 89 while (it.has_next()) 90 TRY(update_path_owner(it.next_full_path())); 91 } 92 93 return {}; 94 }; 95 96 for (auto path : paths) { 97 TRY(update_path_owner(path)); 98 } 99 100 return 0; 101}