• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022-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 #include "ethernet_configuration.h"
16 
17 #include <arpa/inet.h>
18 #include <cerrno>
19 #include <cstdlib>
20 #include <dirent.h>
21 #include <fcntl.h>
22 #include <fstream>
23 #include <limits>
24 #include <regex>
25 #include <sstream>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 
30 #include "net_manager_constants.h"
31 #include "netmanager_base_common_utils.h"
32 #include "netmgr_ext_log_wrapper.h"
33 #include "route.h"
34 #include "securec.h"
35 
36 namespace OHOS {
37 namespace NetManagerStandard {
38 namespace {
39 const std::string IFACE_MATCH = "eth\\d";
40 const std::string CONFIG_KEY_ETH_COMPONENT_FLAG = "config_ethernet_interfaces";
41 const std::string CONFIG_KEY_ETH_IFACE = "iface";
42 const std::string CONFIG_KEY_ETH_LANIFACE = "laniface";
43 const std::string CONFIG_KEY_ETH_CAPS = "caps";
44 const std::string CONFIG_KEY_ETH_IP = "ip";
45 const std::string CONFIG_KEY_ETH_GATEWAY = "gateway";
46 const std::string CONFIG_KEY_ETH_DNS = "dns";
47 const std::string CONFIG_KEY_ETH_NETMASK = "netmask";
48 const std::string CONFIG_KEY_ETH_ROUTE = "route";
49 const std::string CONFIG_KEY_ETH_ROUTE_MASK = "routemask";
50 constexpr int32_t MKDIR_ERR = -1;
51 constexpr int32_t USER_PATH_LEN = 25;
52 constexpr const char *FILE_OBLIQUE_LINE = "/";
53 constexpr const char *KEY_DEVICE = "DEVICE=";
54 constexpr const char *KEY_BOOTPROTO = "BOOTPROTO=";
55 constexpr const char *KEY_STATIC = "STATIC";
56 constexpr const char *KEY_DHCP = "DHCP";
57 constexpr const char *KEY_LAN_STATIC = "LAN_STATIC";
58 constexpr const char *KEY_LAN_DHCP = "LAN_DHCP";
59 constexpr const char *KEY_IPADDR = "IPADDR=";
60 constexpr const char *KEY_NETMASK = "NETMASK=";
61 constexpr const char *KEY_GATEWAY = "GATEWAY=";
62 constexpr const char *KEY_ROUTE = "ROUTE=";
63 constexpr const char *KEY_ROUTE_NETMASK = "ROUTE_NETMASK=";
64 constexpr const char *KEY_DNS = "DNS=";
65 constexpr const char *KEY_PROXY_HOST = "PROXY_HOST=";
66 constexpr const char *KEY_PROXY_PORT = "PROXY_PORT=";
67 constexpr const char *KEY_PROXY_EXCLUSIONS = "PROXY_EXCLUSIONS=";
68 constexpr const char *WRAP = "\n";
69 constexpr const char *DEFAULT_IPV4_ADDR = "0.0.0.0";
70 constexpr const char *DEFAULT_IPV6_ADDR = "::";
71 constexpr const char *DEFAULT_IPV6_MAX_ADDRESS = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
72 constexpr const char *EMPTY_NET_ADDR = "*";
73 constexpr const char *ADDR_SEPARATOR = ",";
74 constexpr const char *EXCLUSIONS_DELIMITER = ",";
75 } // namespace
76 
EthernetConfiguration()77 EthernetConfiguration::EthernetConfiguration()
78 {
79     CreateDir(USER_CONFIG_DIR);
80 }
81 
ReadEthernetInterfaces(std::map<std::string,std::set<NetCap>> & devCaps,std::map<std::string,sptr<InterfaceConfiguration>> & devCfgs,const cJSON * const json)82 bool EthernetConfiguration::ReadEthernetInterfaces(std::map<std::string, std::set<NetCap>> &devCaps,
83                                                    std::map<std::string, sptr<InterfaceConfiguration>> &devCfgs,
84                                                    const cJSON* const json)
85 {
86     for (int32_t i = 0; i < cJSON_GetArraySize(json); i++) {
87         cJSON *item = cJSON_GetArrayItem(json, i);
88         if (item == nullptr) {
89             continue;
90         }
91         std::string iface;
92         bool isLan = false;
93         cJSON *lanIface = cJSON_GetObjectItem(item, CONFIG_KEY_ETH_LANIFACE.c_str());
94         if (lanIface == nullptr) {
95             cJSON *ethIface = cJSON_GetObjectItem(item, CONFIG_KEY_ETH_IFACE.c_str());
96             iface = cJSON_GetStringValue(ethIface);
97             isLan = false;
98         } else {
99             iface = cJSON_GetStringValue(lanIface);
100             isLan = true;
101         }
102         cJSON *capsObj = cJSON_GetObjectItem(item, CONFIG_KEY_ETH_CAPS.c_str());
103         std::set<NetCap> caps;
104         for (int32_t j = 0; j < cJSON_GetArraySize(capsObj); j++) {
105             cJSON *capsItem = cJSON_GetArrayItem(capsObj, j);
106             if (capsItem == nullptr) {
107                 continue;
108             }
109             const auto capsValue = capsItem->valueint;
110             NETMGR_EXT_LOG_D("ReadConfigData capsValue : %{public}d", capsValue);
111             caps.insert(NetCap(capsValue));
112         }
113         if (!caps.empty()) {
114             devCaps[iface] = caps;
115         }
116         const auto &fit = devCfgs.find(iface);
117         if (fit != devCfgs.end()) {
118             NETMGR_EXT_LOG_E("The iface=%{public}s device have set!", fit->first.c_str());
119             continue;
120         }
121         sptr<InterfaceConfiguration> config = ConvertJsonToConfiguration(item, isLan);
122         if (config == nullptr) {
123             NETMGR_EXT_LOG_E("config is nullptr");
124             return false;
125         }
126         std::regex re(IFACE_MATCH);
127         if (cJSON_GetObjectItem(item, CONFIG_KEY_ETH_IP.c_str()) && std::regex_search(iface, re)) {
128             devCfgs[iface] = config;
129         }
130     }
131     return true;
132 }
133 
ReadSystemConfiguration(std::map<std::string,std::set<NetCap>> & devCaps,std::map<std::string,sptr<InterfaceConfiguration>> & devCfgs)134 bool EthernetConfiguration::ReadSystemConfiguration(std::map<std::string, std::set<NetCap>> &devCaps,
135                                                     std::map<std::string, sptr<InterfaceConfiguration>> &devCfgs)
136 {
137     const auto &jsonStr = ReadJsonFile(NETWORK_CONFIG_PATH);
138     if (jsonStr.length() == 0) {
139         NETMGR_EXT_LOG_E("ReadConfigData config file is return empty!");
140         return false;
141     }
142     cJSON *json = cJSON_Parse(jsonStr.c_str());
143     if (json == nullptr) {
144         NETMGR_EXT_LOG_E("json parse failed!");
145         return false;
146     }
147     cJSON *jsonEth = cJSON_GetObjectItem(json, CONFIG_KEY_ETH_COMPONENT_FLAG.c_str());
148     if (jsonEth == nullptr) {
149         NETMGR_EXT_LOG_E("ReadConfigData not find config_ethernet_interfaces!");
150         cJSON_Delete(json);
151         return false;
152     }
153     ReadEthernetInterfaces(devCaps, devCfgs, jsonEth);
154     cJSON_Delete(json);
155     return true;
156 }
157 
ConvertJsonToConfiguration(const cJSON * const jsonData,bool isLan)158 sptr<InterfaceConfiguration> EthernetConfiguration::ConvertJsonToConfiguration(const cJSON* const jsonData, bool isLan)
159 {
160     sptr<InterfaceConfiguration> config = new (std::nothrow) InterfaceConfiguration();
161     if (config == nullptr) {
162         NETMGR_EXT_LOG_E("config is nullptr");
163         return nullptr;
164     }
165 
166     if (isLan) {
167         config->mode_ = LAN_STATIC;
168     } else {
169         config->mode_ = STATIC;
170     }
171     std::string ip = cJSON_GetObjectItem(jsonData, CONFIG_KEY_ETH_IP.c_str())->valuestring;
172     std::string route = cJSON_GetObjectItem(jsonData, CONFIG_KEY_ETH_ROUTE.c_str())->valuestring;
173     std::string gateway = cJSON_GetObjectItem(jsonData, CONFIG_KEY_ETH_GATEWAY.c_str())->valuestring;
174     std::string netmask = cJSON_GetObjectItem(jsonData, CONFIG_KEY_ETH_NETMASK.c_str())->valuestring;
175     std::string dns = cJSON_GetObjectItem(jsonData, CONFIG_KEY_ETH_DNS.c_str())->valuestring;
176     StaticConfiguration::ExtractNetAddrBySeparator(ip, config->ipStatic_.ipAddrList_);
177     StaticConfiguration::ExtractNetAddrBySeparator(route, config->ipStatic_.routeList_);
178     StaticConfiguration::ExtractNetAddrBySeparator(gateway, config->ipStatic_.gatewayList_);
179     StaticConfiguration::ExtractNetAddrBySeparator(netmask, config->ipStatic_.netMaskList_);
180     StaticConfiguration::ExtractNetAddrBySeparator(dns, config->ipStatic_.dnsServers_);
181     std::string routeMask = cJSON_GetObjectItem(jsonData, CONFIG_KEY_ETH_ROUTE_MASK.c_str())->valuestring;
182     ParserIfaceIpAndRoute(config, routeMask);
183     return config;
184 }
185 
ReadUserConfiguration(std::map<std::string,sptr<InterfaceConfiguration>> & devCfgs)186 bool EthernetConfiguration::ReadUserConfiguration(std::map<std::string, sptr<InterfaceConfiguration>> &devCfgs)
187 {
188     DIR *dir = nullptr;
189     dirent *ptr = nullptr;
190     if ((dir = opendir(USER_CONFIG_DIR)) == nullptr) {
191         NETMGR_EXT_LOG_E("Read user configuration open dir error dir=[%{public}s]", USER_CONFIG_DIR);
192         return false;
193     }
194     std::string iface;
195     while ((ptr = readdir(dir)) != nullptr) {
196         if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
197             continue;
198         }
199         if (ptr->d_type == DT_REG) {
200             std::string filePath = std::string(USER_CONFIG_DIR) + FILE_OBLIQUE_LINE + ptr->d_name;
201             std::string fileContent;
202             if (!ReadFile(filePath, fileContent)) {
203                 continue;
204             }
205             std::string().swap(iface);
206             sptr<InterfaceConfiguration> cfg = sptr<InterfaceConfiguration>::MakeSptr();
207             if (cfg == nullptr) {
208                 NETMGR_EXT_LOG_E("cfg new failed for devname[%{public}s]", iface.c_str());
209                 continue;
210             }
211             ParserFileConfig(fileContent, iface, cfg);
212             std::regex re(IFACE_MATCH);
213             if (!iface.empty() && std::regex_search(iface, re)) {
214                 NETMGR_EXT_LOG_D("ReadFileList devname[%{public}s]", iface.c_str());
215                 devCfgs[iface] = cfg;
216             }
217         }
218     }
219     closedir(dir);
220     return true;
221 }
222 
WriteUserConfiguration(const std::string & iface,sptr<InterfaceConfiguration> & cfg)223 bool EthernetConfiguration::WriteUserConfiguration(const std::string &iface, sptr<InterfaceConfiguration> &cfg)
224 {
225     if (cfg == nullptr) {
226         NETMGR_EXT_LOG_E("cfg is nullptr");
227         return false;
228     }
229     if (!CreateDir(USER_CONFIG_DIR)) {
230         NETMGR_EXT_LOG_E("create dir failed");
231         return false;
232     }
233 
234     if (cfg->mode_ == STATIC || cfg->mode_ == LAN_STATIC) {
235         ParserIfaceIpAndRoute(cfg, std::string());
236     }
237 
238     std::string fileContent;
239     GenCfgContent(iface, cfg, fileContent);
240 
241     std::string filePath = std::string(USER_CONFIG_DIR) + FILE_OBLIQUE_LINE + iface;
242     return WriteFile(filePath, fileContent);
243 }
244 
ClearAllUserConfiguration()245 bool EthernetConfiguration::ClearAllUserConfiguration()
246 {
247     return DelDir(USER_CONFIG_DIR);
248 }
249 
ConvertToConfiguration(const EthernetDhcpCallback::DhcpResult & dhcpResult,sptr<StaticConfiguration> & config)250 bool EthernetConfiguration::ConvertToConfiguration(const EthernetDhcpCallback::DhcpResult &dhcpResult,
251                                                    sptr<StaticConfiguration> &config)
252 {
253     if (config == nullptr) {
254         NETMGR_EXT_LOG_E("Error ConvertToIpConfiguration config is null");
255         return false;
256     }
257     if (!IsValidDhcpResult(dhcpResult, config)) {
258         return false;
259     }
260 
261     INetAddr ipAddr;
262     ipAddr.address_ = dhcpResult.ipAddr;
263     ipAddr.family_ = static_cast<uint8_t>(CommonUtils::GetAddrFamily(dhcpResult.ipAddr));
264     ipAddr.prefixlen_ = (ipAddr.family_ == AF_INET6)
265                             ? static_cast<uint8_t>(CommonUtils::Ipv6PrefixLen(dhcpResult.subNet))
266                             : static_cast<uint8_t>(CommonUtils::Ipv4PrefixLen(dhcpResult.subNet));
267     config->ipAddrList_.push_back(ipAddr);
268 
269     INetAddr netMask;
270     netMask.address_ = dhcpResult.subNet;
271     config->netMaskList_.push_back(netMask);
272 
273     INetAddr gateway;
274     gateway.address_ = dhcpResult.gateWay;
275     gateway.family_ = static_cast<uint8_t>(CommonUtils::GetAddrFamily(dhcpResult.gateWay));
276     config->gatewayList_.push_back(gateway);
277 
278     INetAddr route;
279     if (dhcpResult.gateWay != dhcpResult.route1 && dhcpResult.route1 != EMPTY_NET_ADDR) {
280         route.address_ = dhcpResult.route1;
281         route.prefixlen_ = ipAddr.prefixlen_;
282     } else if (dhcpResult.gateWay != dhcpResult.route2 && dhcpResult.route2 != EMPTY_NET_ADDR) {
283         route.address_ = dhcpResult.route2;
284         route.prefixlen_ = ipAddr.prefixlen_;
285     } else {
286         route.address_ = (ipAddr.family_ == AF_INET6) ? DEFAULT_IPV6_ADDR : DEFAULT_IPV4_ADDR;
287         route.prefixlen_ = 0;
288     }
289     route.family_ = static_cast<uint8_t>(CommonUtils::GetAddrFamily(route.address_));
290     config->routeList_.push_back(route);
291 
292     INetAddr dnsNet1;
293     dnsNet1.type_ = (CommonUtils::GetAddrFamily(dhcpResult.dns1)) ? INetAddr::IpType::IPV6 :
294         INetAddr::IpType::IPV4;
295     dnsNet1.address_ = dhcpResult.dns1;
296     INetAddr dnsNet2;
297     dnsNet2.type_ = (CommonUtils::GetAddrFamily(dhcpResult.dns2)) ? INetAddr::IpType::IPV6 :
298         INetAddr::IpType::IPV4;
299     dnsNet2.address_ = dhcpResult.dns2;
300     config->dnsServers_.push_back(dnsNet1);
301     config->dnsServers_.push_back(dnsNet2);
302     return true;
303 }
304 
GetGatewayFromMap(const std::unordered_map<std::string,INetAddr> & temp)305 std::vector<INetAddr> EthernetConfiguration::GetGatewayFromMap(const std::unordered_map<std::string, INetAddr> &temp)
306 {
307     std::vector<INetAddr> t;
308     for (auto [k, v] : temp) {
309         t.push_back(v);
310     }
311     return t;
312 }
313 
GetGatewayFromRouteList(std::list<Route> & routeList)314 std::vector<INetAddr> EthernetConfiguration::GetGatewayFromRouteList(std::list<Route> &routeList)
315 {
316     std::unordered_map<std::string, INetAddr> temp;
317     for (const auto &route : routeList) {
318         temp.emplace(route.gateway_.address_, route.gateway_);
319     }
320     auto temp2 = temp;
321     temp.erase(DEFAULT_IPV4_ADDR);
322     temp.erase(DEFAULT_IPV6_ADDR);
323     if (temp.size() > 0) {
324         return GetGatewayFromMap(temp);
325     }
326     return GetGatewayFromMap(temp2);
327 }
328 
MakeInterfaceConfiguration(const sptr<InterfaceConfiguration> & devCfg,const sptr<NetLinkInfo> & devLinkInfo)329 sptr<InterfaceConfiguration> EthernetConfiguration::MakeInterfaceConfiguration(
330     const sptr<InterfaceConfiguration> &devCfg, const sptr<NetLinkInfo> &devLinkInfo)
331 {
332     if (devCfg == nullptr || devLinkInfo == nullptr) {
333         NETMGR_EXT_LOG_E("param is nullptr");
334         return nullptr;
335     }
336     sptr<InterfaceConfiguration> cfg = new (std::nothrow) InterfaceConfiguration();
337     if (cfg == nullptr) {
338         NETMGR_EXT_LOG_E("cfg new failed");
339         return nullptr;
340     }
341     cfg->mode_ = devCfg->mode_;
342     for (const auto &ipAddr : devLinkInfo->netAddrList_) {
343         cfg->ipStatic_.ipAddrList_.push_back(ipAddr);
344         auto family = CommonUtils::GetAddrFamily(ipAddr.address_);
345         INetAddr netMask;
346         netMask.address_ =
347             ipAddr.netMask_.empty()
348                 ? (((family == AF_INET6) ? CommonUtils::GetIpv6Prefix(DEFAULT_IPV6_MAX_ADDRESS, ipAddr.prefixlen_)
349                                          : CommonUtils::GetMaskByLength(ipAddr.prefixlen_)))
350                 : ipAddr.netMask_;
351         cfg->ipStatic_.netMaskList_.push_back(netMask);
352     }
353     for (const auto &route : devLinkInfo->routeList_) {
354         cfg->ipStatic_.routeList_.push_back(route.destination_);
355     }
356     cfg->ipStatic_.gatewayList_ = GetGatewayFromRouteList(devLinkInfo->routeList_);
357 
358     cfg->ipStatic_.domain_ = devLinkInfo->domain_;
359     for (const auto &addr : devLinkInfo->dnsList_) {
360         cfg->ipStatic_.dnsServers_.push_back(addr);
361     }
362     return cfg;
363 }
364 
ReadJsonFile(const std::string & filePath)365 std::string EthernetConfiguration::ReadJsonFile(const std::string &filePath)
366 {
367     std::ifstream infile;
368     std::string strLine;
369     std::string strAll;
370     infile.open(filePath);
371     if (!infile.is_open()) {
372         NETMGR_EXT_LOG_E("ReadJsonFile filePath failed");
373         return strAll;
374     }
375     while (getline(infile, strLine)) {
376         strAll.append(strLine);
377     }
378     infile.close();
379     return strAll;
380 }
381 
IsDirExist(const std::string & dirPath)382 bool EthernetConfiguration::IsDirExist(const std::string &dirPath)
383 {
384     struct stat status;
385     if (dirPath.empty()) {
386         return false;
387     }
388     return (stat(dirPath.c_str(), &status) == 0);
389 }
390 
CreateDir(const std::string & dirPath)391 bool EthernetConfiguration::CreateDir(const std::string &dirPath)
392 {
393     if (IsDirExist(dirPath)) {
394         return true;
395     }
396     if (mkdir(dirPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == MKDIR_ERR) {
397         NETMGR_EXT_LOG_E("mkdir failed %{public}d: %{public}s", errno, strerror(errno));
398         return false;
399     }
400     return true;
401 }
402 
DelDir(const std::string & dirPath)403 bool EthernetConfiguration::DelDir(const std::string &dirPath)
404 {
405     DIR *dir = nullptr;
406     dirent *entry = nullptr;
407     struct stat statbuf;
408     if ((dir = opendir(dirPath.c_str())) == nullptr) {
409         NETMGR_EXT_LOG_E("EthernetConfiguration DelDir open user dir failed!");
410         return false;
411     }
412     while ((entry = readdir(dir)) != nullptr) {
413         std::string filePath = dirPath + FILE_OBLIQUE_LINE + entry->d_name;
414         lstat(filePath.c_str(), &statbuf);
415         if (S_ISREG(statbuf.st_mode)) {
416             remove(filePath.c_str());
417         }
418     }
419     closedir(dir);
420     sync();
421     return rmdir(dirPath.c_str()) >= 0;
422 }
423 
IsFileExist(const std::string & filePath,std::string & realPath)424 bool EthernetConfiguration::IsFileExist(const std::string &filePath, std::string &realPath)
425 {
426     char tmpPath[PATH_MAX] = {0};
427     if (!realpath(filePath.c_str(), tmpPath)) {
428         NETMGR_EXT_LOG_E("file name is error");
429         return false;
430     }
431     if (strncmp(tmpPath, USER_CONFIG_DIR, USER_PATH_LEN) != 0) {
432         NETMGR_EXT_LOG_E("file path is error");
433         return false;
434     }
435     realPath = tmpPath;
436     return true;
437 }
438 
ReadFile(const std::string & filePath,std::string & fileContent)439 bool EthernetConfiguration::ReadFile(const std::string &filePath, std::string &fileContent)
440 {
441     std::unique_lock<std::mutex> lock(mutex_);
442     if (filePath.empty()) {
443         NETMGR_EXT_LOG_E("filePath empty.");
444         return false;
445     }
446     std::string realPath;
447     if (!IsFileExist(filePath, realPath)) {
448         NETMGR_EXT_LOG_E("[%{public}s] not exist.", filePath.c_str());
449         return false;
450     }
451     std::fstream file(realPath.c_str(), std::fstream::in);
452     if (!file.is_open()) {
453         NETMGR_EXT_LOG_E("EthernetConfiguration read file failed.err %{public}d %{public}s", errno, strerror(errno));
454         return false;
455     }
456     std::stringstream buffer;
457     buffer << file.rdbuf();
458     fileContent = buffer.str();
459     file.close();
460     return true;
461 }
462 
WriteFile(const std::string & filePath,const std::string & fileContent)463 bool EthernetConfiguration::WriteFile(const std::string &filePath, const std::string &fileContent)
464 {
465     std::fstream file(filePath.c_str(), std::fstream::out | std::fstream::trunc);
466     if (!file.is_open()) {
467         NETMGR_EXT_LOG_E("EthernetConfiguration write file=%{public}s fstream failed. err %{public}d %{public}s",
468                          filePath.c_str(), errno, strerror(errno));
469         return false;
470     }
471     file << fileContent.c_str();
472     file.close();
473     sync();
474     return true;
475 }
476 
ParserFileConfig(const std::string & fileContent,std::string & iface,sptr<InterfaceConfiguration> cfg)477 void EthernetConfiguration::ParserFileConfig(const std::string &fileContent, std::string &iface,
478                                              sptr<InterfaceConfiguration> cfg)
479 {
480     ParseDevice(fileContent, iface);
481     ParseBootProto(fileContent, cfg);
482     ParseStaticConfig(fileContent, cfg);
483     ParserFileHttpProxy(fileContent, cfg);
484 }
485 
ParseDevice(const std::string & fileContent,std::string & iface)486 void EthernetConfiguration::ParseDevice(const std::string &fileContent, std::string &iface)
487 {
488     std::string::size_type pos = fileContent.find(KEY_DEVICE);
489     if (pos == std::string::npos) {
490         return;
491     }
492     pos += strlen(KEY_DEVICE);
493     const auto &device = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
494     iface = device;
495 }
496 
ParseBootProto(const std::string & fileContent,sptr<InterfaceConfiguration> cfg)497 void EthernetConfiguration::ParseBootProto(const std::string &fileContent, sptr<InterfaceConfiguration> cfg)
498 {
499     std::string::size_type pos = fileContent.find(KEY_BOOTPROTO);
500     if (pos == std::string::npos) {
501         return;
502     }
503     pos += strlen(KEY_BOOTPROTO);
504     const auto &bootProto = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
505     if (cfg == nullptr) {
506         return;
507     }
508     if (bootProto == KEY_LAN_STATIC) {
509         cfg->mode_ = LAN_STATIC;
510     } else if (bootProto == KEY_LAN_DHCP) {
511         cfg->mode_ = LAN_DHCP;
512     } else if (bootProto == KEY_STATIC) {
513         cfg->mode_ = STATIC;
514     } else {
515         cfg->mode_ = DHCP;
516     }
517 }
518 
ParseStaticConfig(const std::string & fileContent,sptr<InterfaceConfiguration> cfg)519 void EthernetConfiguration::ParseStaticConfig(const std::string &fileContent, sptr<InterfaceConfiguration> cfg)
520 {
521     if (cfg->mode_ != STATIC && cfg->mode_ != LAN_STATIC) {
522         return;
523     }
524     std::string ipAddresses, netMasks, gateways, routes, routeMasks, dnsServers;
525     auto pos = fileContent.find(KEY_IPADDR);
526     if (pos != std::string::npos) {
527         pos += strlen(KEY_IPADDR);
528         ipAddresses = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
529     }
530 
531     pos = fileContent.find(KEY_NETMASK);
532     if (pos != std::string::npos) {
533         pos += strlen(KEY_NETMASK);
534         netMasks = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
535     }
536 
537     pos = fileContent.find(KEY_GATEWAY);
538     if (pos != std::string::npos) {
539         pos += strlen(KEY_GATEWAY);
540         gateways = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
541     }
542 
543     pos = fileContent.find(KEY_ROUTE);
544     if (pos != std::string::npos) {
545         pos += strlen(KEY_ROUTE);
546         routes = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
547     }
548 
549     pos = fileContent.find(KEY_ROUTE_NETMASK);
550     if (pos != std::string::npos) {
551         pos += strlen(KEY_ROUTE_NETMASK);
552         routeMasks = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
553     }
554 
555     pos = fileContent.find(KEY_DNS);
556     if (pos != std::string::npos) {
557         pos += strlen(KEY_DNS);
558         dnsServers = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
559     }
560 
561     StaticConfiguration::ExtractNetAddrBySeparator(ipAddresses, cfg->ipStatic_.ipAddrList_);
562     StaticConfiguration::ExtractNetAddrBySeparator(routes, cfg->ipStatic_.routeList_);
563     StaticConfiguration::ExtractNetAddrBySeparator(gateways, cfg->ipStatic_.gatewayList_);
564     StaticConfiguration::ExtractNetAddrBySeparator(netMasks, cfg->ipStatic_.netMaskList_);
565     StaticConfiguration::ExtractNetAddrBySeparator(dnsServers, cfg->ipStatic_.dnsServers_);
566     ParserIfaceIpAndRoute(cfg, routeMasks);
567 }
568 
ParserFileHttpProxy(const std::string & fileContent,const sptr<InterfaceConfiguration> & cfg)569 void EthernetConfiguration::ParserFileHttpProxy(const std::string &fileContent, const sptr<InterfaceConfiguration> &cfg)
570 {
571     std::string::size_type pos = fileContent.find(KEY_PROXY_HOST);
572     if (pos != std::string::npos) {
573         pos += strlen(KEY_PROXY_HOST);
574         cfg->httpProxy_.SetHost(fileContent.substr(pos, fileContent.find(WRAP, pos) - pos));
575     }
576 
577     pos = fileContent.find(KEY_PROXY_PORT);
578     if (pos != std::string::npos) {
579         pos += strlen(KEY_PROXY_PORT);
580         uint32_t port = CommonUtils::StrToUint(fileContent.substr(pos, fileContent.find(WRAP, pos) - pos));
581         cfg->httpProxy_.SetPort(static_cast<uint16_t>(port));
582     }
583 
584     pos = fileContent.find(KEY_PROXY_EXCLUSIONS);
585     if (pos != std::string::npos) {
586         pos += strlen(KEY_PROXY_EXCLUSIONS);
587         auto exclusions = fileContent.substr(pos, fileContent.find(WRAP, pos) - pos);
588         std::list<std::string> exclusionList;
589         for (const auto &exclusion : CommonUtils::Split(exclusions, EXCLUSIONS_DELIMITER)) {
590             exclusionList.push_back(exclusion);
591         }
592         cfg->httpProxy_.SetExclusionList(exclusionList);
593     }
594 }
595 
ParserIfaceIpAndRoute(sptr<InterfaceConfiguration> & cfg,const std::string & rootNetMask)596 void EthernetConfiguration::ParserIfaceIpAndRoute(sptr<InterfaceConfiguration> &cfg, const std::string &rootNetMask)
597 {
598     if (cfg == nullptr) {
599         NETMGR_EXT_LOG_E("cfg is nullptr");
600         return;
601     }
602 
603     std::for_each(cfg->ipStatic_.netMaskList_.begin(), cfg->ipStatic_.netMaskList_.end(), [&cfg](const auto &netMask) {
604         auto maskFamily = CommonUtils::GetAddrFamily(netMask.address_);
605         for (auto &ipAddr : cfg->ipStatic_.ipAddrList_) {
606             if (maskFamily != CommonUtils::GetAddrFamily(ipAddr.address_)) {
607                 continue;
608             }
609             ipAddr.netMask_ = netMask.address_;
610             ipAddr.prefixlen_ =
611 	    (maskFamily == AF_INET6) ? static_cast<uint32_t>(CommonUtils::Ipv6PrefixLen(netMask.address_))
612                                      : static_cast<uint32_t>(CommonUtils::Ipv4PrefixLen(netMask.address_));
613             break;
614         }
615     });
616 
617     for (const auto &routeMask : CommonUtils::Split(rootNetMask, ADDR_SEPARATOR)) {
618         auto maskFamily = CommonUtils::GetAddrFamily(routeMask);
619         for (auto &route : cfg->ipStatic_.routeList_) {
620             if (maskFamily != CommonUtils::GetAddrFamily(route.address_)) {
621                 continue;
622             }
623             route.prefixlen_ = (maskFamily == AF_INET6) ? static_cast<uint32_t>(CommonUtils::Ipv6PrefixLen(routeMask))
624                                                         : static_cast<uint32_t>(CommonUtils::Ipv4PrefixLen(routeMask));
625             break;
626         }
627     }
628 }
629 
GetIfaceMode(IPSetMode mode)630 std::string EthernetConfiguration::GetIfaceMode(IPSetMode mode)
631 {
632     switch (mode) {
633         case LAN_STATIC:
634             return KEY_LAN_STATIC;
635         case LAN_DHCP:
636             return KEY_LAN_DHCP;
637         case STATIC:
638             return KEY_STATIC;
639         default:
640             return KEY_DHCP;
641     }
642 }
643 
GenCfgContent(const std::string & iface,sptr<InterfaceConfiguration> cfg,std::string & fileContent)644 void EthernetConfiguration::GenCfgContent(const std::string &iface, sptr<InterfaceConfiguration> cfg,
645                                           std::string &fileContent)
646 {
647     if (cfg == nullptr) {
648         NETMGR_EXT_LOG_E("cfg is nullptr");
649         return;
650     }
651     std::string().swap(fileContent);
652     fileContent = fileContent + KEY_DEVICE + iface + WRAP;
653     std::string mode = GetIfaceMode(cfg->mode_);
654     fileContent = fileContent + KEY_BOOTPROTO + mode + WRAP;
655     if (cfg->mode_ == STATIC || cfg->mode_ == LAN_STATIC) {
656         std::string ipAddresses = AccumulateNetAddress(cfg->ipStatic_.ipAddrList_);
657         std::string netMasks = AccumulateNetAddress(cfg->ipStatic_.netMaskList_);
658         std::string gateways = AccumulateNetAddress(cfg->ipStatic_.gatewayList_);
659         std::string routes = AccumulateNetAddress(cfg->ipStatic_.routeList_);
660         std::string routeMasks =
661             std::accumulate(cfg->ipStatic_.routeList_.begin(), cfg->ipStatic_.routeList_.end(), std::string(),
662                             [](const std::string &routeMask, const INetAddr &iter) {
663                                 auto family = CommonUtils::GetAddrFamily(iter.address_);
664                                 std::string mask = (family == AF_INET6) ? DEFAULT_IPV6_ADDR : DEFAULT_IPV4_ADDR;
665                                 return routeMask.empty() ? routeMask + mask : (routeMask + ADDR_SEPARATOR + mask);
666                             });
667         std::string dnsServers = AccumulateNetAddress(cfg->ipStatic_.dnsServers_);
668 
669         fileContent = fileContent + KEY_IPADDR + ipAddresses + WRAP;
670         fileContent = fileContent + KEY_NETMASK + netMasks + WRAP;
671         fileContent = fileContent + KEY_GATEWAY + gateways + WRAP;
672         fileContent = fileContent + KEY_ROUTE + routes + WRAP;
673         fileContent = fileContent + KEY_ROUTE_NETMASK + routeMasks + WRAP;
674         fileContent = fileContent + KEY_DNS + dnsServers + WRAP;
675     }
676     GenHttpProxyContent(cfg, fileContent);
677 }
678 
GenHttpProxyContent(const sptr<InterfaceConfiguration> & cfg,std::string & fileContent)679 void EthernetConfiguration::GenHttpProxyContent(const sptr<InterfaceConfiguration> &cfg, std::string &fileContent)
680 {
681     const auto &exclusionList = cfg->httpProxy_.GetExclusionList();
682     std::string exclusions =
683         std::accumulate(exclusionList.begin(), exclusionList.end(), std::string(),
684                         [](const std::string &exclusion, const std::string &next) {
685                             return exclusion.empty() ? exclusion + next : (exclusion + EXCLUSIONS_DELIMITER + next);
686                         });
687 
688     fileContent = fileContent + KEY_PROXY_HOST + cfg->httpProxy_.GetHost() + WRAP;
689     fileContent = fileContent + KEY_PROXY_PORT + std::to_string(cfg->httpProxy_.GetPort()) + WRAP;
690     fileContent = fileContent + KEY_PROXY_EXCLUSIONS + exclusions + WRAP;
691 }
692 
AccumulateNetAddress(const std::vector<INetAddr> & netAddrList)693 std::string EthernetConfiguration::AccumulateNetAddress(const std::vector<INetAddr> &netAddrList)
694 {
695     return std::accumulate(netAddrList.begin(), netAddrList.end(), std::string(),
696                            [](const std::string &addr, const INetAddr &iter) {
697                                return addr.empty() ? (addr + iter.address_) : (addr + ADDR_SEPARATOR + iter.address_);
698                            });
699 }
700 
IsValidDhcpResult(const EthernetDhcpCallback::DhcpResult & dhcpResult,sptr<StaticConfiguration> & config)701 bool EthernetConfiguration::IsValidDhcpResult(const EthernetDhcpCallback::DhcpResult &dhcpResult,
702                                               sptr<StaticConfiguration> &config)
703 {
704     if (config == nullptr) {
705         NETMGR_EXT_LOG_E("config is nullptr");
706         return false;
707     }
708     if (dhcpResult.ipAddr.empty()) {
709         NETMGR_EXT_LOG_E("DhcpResult ip addr is empty");
710         return false;
711     }
712 
713     bool isSameIp = false;
714     bool isSameGateway = false;
715     if (std::any_of(config->ipAddrList_.begin(), config->ipAddrList_.end(), [&dhcpResult](const auto &ipAddr) {
716         return dhcpResult.ipAddr == ipAddr.address_;
717         })) {
718         NETMGR_EXT_LOG_I("Same ip addr:%{public}s", CommonUtils::ToAnonymousIp(dhcpResult.ipAddr).c_str());
719         isSameIp = true;
720     }
721 
722     if (std::any_of(config->gatewayList_.begin(), config->gatewayList_.end(), [&dhcpResult](const auto &gateway) {
723         return dhcpResult.gateWay == gateway.address_;
724         })) {
725         NETMGR_EXT_LOG_I("Same gateway:%{public}s", CommonUtils::ToAnonymousIp(dhcpResult.gateWay).c_str());
726         isSameGateway = true;
727     }
728     return !(isSameIp && isSameGateway);
729 }
730 } // namespace NetManagerStandard
731 } // namespace OHOS
732