1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_FILE_FS_WATCHER_IMPL_H 17 #define OHOS_FILE_FS_WATCHER_IMPL_H 18 19 #include <mutex> 20 #include <sys/inotify.h> 21 #include <unordered_map> 22 #include <unordered_set> 23 24 #include "uni_error.h" 25 #include "ffi_remote_data.h" 26 #include "cj_common_ffi.h" 27 #include "cj_lambda.h" 28 #include "singleton.h" 29 30 namespace OHOS { 31 namespace CJSystemapi { 32 constexpr int BUF_SIZE = 1024; 33 34 struct CWatchEvent { 35 const char* fileName; 36 uint32_t event; 37 uint32_t cookie; 38 }; 39 struct WatcherInfoArg { 40 std::string fileName = ""; 41 uint32_t events = 0; 42 int wd = -1; 43 std::function<void(CWatchEvent)> watchCallback_; WatcherInfoArgWatcherInfoArg44 explicit WatcherInfoArg(void (*callback)(CWatchEvent)) 45 { 46 watchCallback_ = CJLambda::Create(callback); 47 } 48 ~WatcherInfoArg() = default; 49 }; 50 51 class WatcherImpl : public OHOS::FFI::FFIData, public Singleton<WatcherImpl> { 52 public: 53 std::shared_ptr<WatcherInfoArg> data_; 54 WatcherImpl(); 55 int32_t GetNotifyId(); 56 bool InitNotify(); 57 bool AddWatcherInfo(const std::string &fileName, std::shared_ptr<WatcherInfoArg> arg); 58 bool CheckEventValid(const uint32_t &event); 59 int32_t StartNotify(); 60 void GetNotifyEvent(); 61 int32_t StopNotify(); 62 GetRuntimeType()63 OHOS::FFI::RuntimeType* GetRuntimeType() override { return GetClassType(); } 64 private: 65 uint32_t RemoveWatcherInfo(std::shared_ptr<WatcherInfoArg> arg); 66 std::tuple<bool, int> CheckEventWatched(const std::string &fileName, const uint32_t &event); 67 void NotifyEvent(const struct inotify_event *event); 68 int CloseNotifyFd(); 69 int NotifyToWatchNewEvents(const std::string &fileName, const int &wd, const uint32_t &watchEvents); 70 71 private: 72 static std::mutex watchMutex_; 73 bool run_ = false; 74 int32_t notifyFd_ = -1; 75 std::unordered_set<std::shared_ptr<WatcherInfoArg>> watcherInfoSet_; 76 std::unordered_map<std::string, std::pair<int, uint32_t>> wdFileNameMap_; 77 78 friend class OHOS::FFI::RuntimeType; 79 friend class OHOS::FFI::TypeBase; GetClassType()80 static OHOS::FFI::RuntimeType* GetClassType() 81 { 82 static OHOS::FFI::RuntimeType runtimeType = OHOS::FFI::RuntimeType::Create<OHOS::FFI::FFIData>("WatcherImpl"); 83 return &runtimeType; 84 } 85 }; 86 } // OHOS::FileManagement::ModuleFileIO 87 } 88 89 #endif // OHOS_FILE_FS_IMPL_H