Serenity Operating System
at master 62 lines 2.1 kB view raw
1/* 2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> 3 * Copyright (c) 2021, Kenneth Myhra <kennethmyhra@serenityos.org> 4 * Copyright (c) 2021, Xavier Defrang <xavier.defrang@gmail.com> 5 * 6 * SPDX-License-Identifier: BSD-2-Clause 7 */ 8 9#include <AK/Vector.h> 10#include <LibCore/ArgsParser.h> 11#include <LibCore/DirIterator.h> 12#include <LibCore/FilePermissionsMask.h> 13#include <LibCore/System.h> 14#include <LibMain/Main.h> 15 16ErrorOr<int> serenity_main(Main::Arguments arguments) 17{ 18 TRY(Core::System::pledge("stdio rpath fattr")); 19 20 StringView mode; 21 Vector<StringView> paths; 22 bool recursive = false; 23 24 Core::ArgsParser args_parser; 25 args_parser.add_option(recursive, "Change file modes recursively", "recursive", 'R'); 26 args_parser.add_positional_argument(mode, "File mode in octal or symbolic notation", "mode"); 27 args_parser.add_positional_argument(paths, "Paths to file", "paths"); 28 args_parser.parse(arguments); 29 30 auto mask = TRY(Core::FilePermissionsMask::parse(mode)); 31 32 Function<ErrorOr<void>(StringView const&)> update_path_permissions = [&](StringView const& path) -> ErrorOr<void> { 33 auto stat = TRY(Core::System::lstat(path)); 34 35 if (S_ISLNK(stat.st_mode)) { 36 // Symlinks don't get processed unless they are explicitly listed on the command line. 37 if (!paths.contains_slow(path)) 38 return {}; 39 40 // The chmod syscall changes the file that a link points to, so we will have to get 41 // the correct mode to base our modifications on. 42 stat = TRY(Core::System::stat(path)); 43 } 44 45 TRY(Core::System::chmod(path, mask.apply(stat.st_mode))); 46 47 if (recursive && S_ISDIR(stat.st_mode)) { 48 Core::DirIterator it(path, Core::DirIterator::Flags::SkipParentAndBaseDir); 49 50 while (it.has_next()) 51 TRY(update_path_permissions(it.next_full_path())); 52 } 53 54 return {}; 55 }; 56 57 for (auto const& path : paths) { 58 TRY(update_path_permissions(path)); 59 } 60 61 return 0; 62}