1 /*
2  * Copyright (c) 2023 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 #include "chain_rule.h"
17 
18 #include <sstream>
19 
20 namespace OHOS {
21 namespace EDM {
22 namespace IPTABLES {
23 
ChainRule(const std::string & rule)24 ChainRule::ChainRule(const std::string& rule)
25 {
26     std::istringstream iss(rule);
27     iss >> ruleNo_;
28     uint64_t pkts = 0;
29     iss >> pkts;
30     uint64_t bytes = 0;
31     iss >> bytes;
32     iss >> target_;
33     iss >> prot_;
34     std::string opt;
35     iss >> opt;
36     std::string in;
37     iss >> in;
38     std::string out;
39     iss >> out;
40     std::string defaultIp = "0.0.0.0/0";
41     std::string source;
42     iss >> source;
43     if (source != defaultIp) {
44         srcAddr_ = source;
45     }
46     std::string destination;
47     iss >> destination;
48     if (destination != defaultIp) {
49         destAddr_ = destination;
50     }
51     std::getline(iss, otherOptions_);
52 }
53 
RuleNum()54 uint32_t ChainRule::RuleNum()
55 {
56     return ruleNo_;
57 }
58 
Target()59 std::string ChainRule::Target()
60 {
61     return target_;
62 }
63 
GetOption(const std::string & options,const std::string & key,std::string & value)64 void ChainRule::GetOption(const std::string& options, const std::string& key, std::string& value)
65 {
66     std::string result;
67     TruncateOption(options, key, result);
68     if (!result.empty()) {
69         std::istringstream iss{result};
70         iss >> value;
71     }
72 }
73 
GetOption(const std::string & options,const std::string & key,uint32_t & value)74 void ChainRule::GetOption(const std::string& options, const std::string& key, uint32_t& value)
75 {
76     std::string result;
77     TruncateOption(options, key, result);
78     if (!result.empty()) {
79         std::istringstream iss{result};
80         iss >> value;
81     }
82 }
83 
TruncateOption(const std::string & options,const std::string & key,std::string & result)84 void ChainRule::TruncateOption(const std::string& options, const std::string& key, std::string &result)
85 {
86     auto index = options.find(key);
87     if (index != std::string::npos) {
88         result = options.substr(index + key.length());
89     }
90 }
91 } // namespace IPTABLES
92 } // namespace EDM
93 } // namespace OHOS