1 /* 2 * Copyright (c) 2022 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 NETMANAGER_BASE_IPTABLES_WRAPPER_H 17 #define NETMANAGER_BASE_IPTABLES_WRAPPER_H 18 19 #include <condition_variable> 20 #include <cstring> 21 #include <iostream> 22 #include <mutex> 23 #include <queue> 24 #include <thread> 25 26 #include "event_runner.h" 27 #include "event_handler.h" 28 #include "singleton.h" 29 #include "ffrt.h" 30 31 namespace OHOS { 32 namespace nmd { 33 using EventRunner = OHOS::AppExecFwk::EventRunner; 34 using EventHandler = OHOS::AppExecFwk::EventHandler; 35 enum IpType { 36 IPTYPE_IPV4 = 1, 37 IPTYPE_IPV6 = 2, 38 IPTYPE_IPV4V6 = 3, 39 }; 40 class IptablesWrapper : public std::enable_shared_from_this<IptablesWrapper> { 41 public: 42 IptablesWrapper(); 43 ~IptablesWrapper(); GetInstance()44 static std::shared_ptr<IptablesWrapper> &GetInstance() 45 { 46 static std::shared_ptr<IptablesWrapper> instance = std::make_shared<IptablesWrapper>(); 47 return instance; 48 } 49 50 /** 51 * @param ipType ipv4 or ipv6 52 * @param command iptables command 53 * @return NETMANAGER_SUCCESS suceess or NETMANAGER_ERROR failed 54 */ 55 int32_t RunCommand(const IpType &ipType, const std::string &command); 56 57 /** 58 * @brief run iptables exec for result. 59 * 60 * @param ipType ipv4 or ipv6. 61 * @param command iptables command. 62 * @return NETMANAGER_SUCCESS suceess or NETMANAGER_ERROR failed 63 */ 64 std::string RunCommandForRes(const IpType &ipType, const std::string &command); 65 66 /** 67 * @brief run mutiple iptables commands. 68 * 69 * @param ipType ipv4 or ipv6. 70 * @param commands iptables commands. 71 * @return NETMANAGER_SUCCESS suceess or NETMANAGER_ERROR failed 72 */ 73 int32_t RunMutipleCommands(const IpType &ipType, const std::vector<std::string> &commands); 74 75 private: 76 void ExecuteCommand(const std::string &command); 77 void ExecuteCommandForRes(const std::string &command); 78 79 private: 80 std::mutex iptablesMutex_; 81 std::condition_variable conditionVarLock_; 82 bool isRunningFlag_ = false; 83 bool isIptablesSystemAccess_ = false; 84 bool isIp6tablesSystemAccess_ = false; 85 std::string result_; 86 std::thread iptablesWrapperThread_; 87 std::queue<std::string> commandsQueue_; 88 std::shared_ptr<ffrt::queue> iptablesWrapperFfrtQueue_ = nullptr; 89 }; 90 } // namespace nmd 91 } // namespace OHOS 92 #endif /* NETMANAGER_BASE_IPTABLES_WRAPPER_H */ 93