1 // 2 // 3 // Copyright 2023 gRPC authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 // 17 // 18 19 #include <grpc/support/port_platform.h> 20 21 #include <memory> 22 23 #include "absl/functional/function_ref.h" 24 #include "absl/status/status.h" 25 #include "absl/strings/string_view.h" 26 27 #if defined(GPR_LINUX) || defined(GPR_ANDROID) || defined(GPR_FREEBSD) || \ 28 defined(GPR_APPLE) 29 30 #include <dirent.h> 31 32 #include <string> 33 34 #include "src/core/lib/gprpp/directory_reader.h" 35 36 namespace grpc_core { 37 38 namespace { 39 const char kSkipEntriesSelf[] = "."; 40 const char kSkipEntriesParent[] = ".."; 41 } // namespace 42 43 class DirectoryReaderImpl : public DirectoryReader { 44 public: DirectoryReaderImpl(absl::string_view directory_path)45 explicit DirectoryReaderImpl(absl::string_view directory_path) 46 : directory_path_(directory_path) {} Name() const47 absl::string_view Name() const override { return directory_path_; } 48 absl::Status ForEach(absl::FunctionRef<void(absl::string_view)>) override; 49 50 private: 51 const std::string directory_path_; 52 }; 53 MakeDirectoryReader(absl::string_view filename)54std::unique_ptr<DirectoryReader> MakeDirectoryReader( 55 absl::string_view filename) { 56 return std::make_unique<DirectoryReaderImpl>(filename); 57 } 58 ForEach(absl::FunctionRef<void (absl::string_view)> callback)59absl::Status DirectoryReaderImpl::ForEach( 60 absl::FunctionRef<void(absl::string_view)> callback) { 61 // Open the dir for reading 62 DIR* directory = opendir(directory_path_.c_str()); 63 if (directory == nullptr) { 64 return absl::InternalError("Could not read crl directory."); 65 } 66 struct dirent* directory_entry; 67 // Iterate over everything in the directory 68 while ((directory_entry = readdir(directory)) != nullptr) { 69 const absl::string_view file_name = directory_entry->d_name; 70 // Skip "." and ".." 71 if (file_name == kSkipEntriesParent || file_name == kSkipEntriesSelf) { 72 continue; 73 } 74 // Call the callback with this filename 75 callback(file_name); 76 } 77 closedir(directory); 78 return absl::OkStatus(); 79 } 80 } // namespace grpc_core 81 82 #endif // GPR_LINUX || GPR_ANDROID || GPR_FREEBSD || GPR_APPLE 83