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 30 namespace OHOS { 31 namespace nmd { 32 using EventRunner = OHOS::AppExecFwk::EventRunner; 33 using EventHandler = OHOS::AppExecFwk::EventHandler; 34 enum IpType { 35 IPTYPE_IPV4 = 1, 36 IPTYPE_IPV6 = 2, 37 IPTYPE_IPV4V6 = 3, 38 }; 39 class IptablesWrapper : public std::enable_shared_from_this<IptablesWrapper> { 40 public: 41 IptablesWrapper(); 42 ~IptablesWrapper(); GetInstance()43 static std::shared_ptr<IptablesWrapper> &GetInstance() 44 { 45 static std::shared_ptr<IptablesWrapper> instance = std::make_shared<IptablesWrapper>(); 46 return instance; 47 } 48 49 /** 50 * @param ipType ipv4 or ipv6 51 * @param command iptables command 52 * @return NETMANAGER_SUCCESS suceess or NETMANAGER_ERROR failed 53 */ 54 int32_t RunCommand(const IpType &ipType, const std::string &command); 55 56 /** 57 * @brief run iptables exec for result. 58 * 59 * @param ipType ipv4 or ipv6. 60 * @param command iptables command. 61 * @return NETMANAGER_SUCCESS suceess or NETMANAGER_ERROR failed 62 */ 63 std::string RunCommandForRes(const IpType &ipType, const std::string &command); 64 65 private: 66 void ExecuteCommand(const std::string &command); 67 void ExecuteCommandForRes(const std::string &command); 68 69 private: 70 std::mutex iptablesMutex_; 71 std::condition_variable conditionVarLock_; 72 bool isRunningFlag_ = false; 73 bool isIptablesSystemAccess_ = false; 74 std::string result_; 75 std::thread iptablesWrapperThread_; 76 std::queue<std::string> commandsQueue_; 77 std::shared_ptr<EventHandler> handler_ = nullptr; 78 }; 79 } // namespace nmd 80 } // namespace OHOS 81 #endif /* NETMANAGER_BASE_IPTABLES_WRAPPER_H */ 82