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 DECLARE_DELAYED_SINGLETON(IptablesWrapper) 41 public: 42 /** 43 * @param ipType ipv4 or ipv6 44 * @param command iptables command 45 * @return NETMANAGER_SUCCESS suceess or NETMANAGER_ERROR failed 46 */ 47 int32_t RunCommand(const IpType &ipType, const std::string &command); 48 49 /** 50 * @brief run iptables exec for result. 51 * 52 * @param ipType ipv4 or ipv6. 53 * @param command iptables command. 54 * @return NETMANAGER_SUCCESS suceess or NETMANAGER_ERROR failed 55 */ 56 std::string RunCommandForRes(const IpType &ipType, const std::string &command); 57 58 private: 59 void ExecuteCommand(const std::string &command); 60 void ExecuteCommandForRes(const std::string &command); 61 62 private: 63 std::mutex iptablesMutex_; 64 std::condition_variable conditionVarLock_; 65 bool isRunningFlag_ = false; 66 bool isIptablesSystemAccess_ = false; 67 bool forRes_ = false; 68 std::string result_; 69 std::thread iptablesWrapperThread_; 70 std::queue<std::string> commandsQueue_; 71 std::shared_ptr<EventHandler> handler_ = nullptr; 72 }; 73 } // namespace nmd 74 } // namespace OHOS 75 #endif /* NETMANAGER_BASE_IPTABLES_WRAPPER_H */ 76