• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 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 "ethernet_management.h"
17 
18 #include <fcntl.h>
19 #include <fstream>
20 #include <regex>
21 #include <thread>
22 #include <pthread.h>
23 #include <unistd.h>
24 #include <sys/ioctl.h>
25 #include <vector>
26 
27 #include "net_manager_constants.h"
28 #include "netmanager_base_common_utils.h"
29 #include "netmgr_ext_log_wrapper.h"
30 #include "netsys_controller.h"
31 #include "parameters.h"
32 #include "securec.h"
33 
34 namespace OHOS {
35 namespace NetManagerStandard {
36 const std::string IFACE_MATCH = "eth\\d";
37 constexpr const char *IFACE_LINK_UP = "up";
38 constexpr const char *IFACE_RUNNING = "running";
39 constexpr const char *SYS_CLASS_NET_PATH = "/sys/class/net/";
40 static constexpr const char *MDIO_BUS_DEV_INFO_PATH = "/sys/bus/mdio_bus/devices/bf800000.xge-0:01/dev_info";
41 constexpr const char *ITEM_DEVICE = "/device";
42 constexpr const char *ITEM_USB = "usb";
43 constexpr const char *ITEM_DEVICE_NAME = "/product";
44 constexpr const char *ITEM_SUPPLIER_ID = "/idVendor";
45 constexpr const char *ITEM_SUPPLIER_NAME = "/manufacturer";
46 constexpr const char *ITEM_MAXIMUM_RATE = "/speed";
47 constexpr const char *ITEM_UNIT_MBS = " Mb/s";
48 static constexpr const char *ITEM_COMMA = ",";
49 static constexpr uint32_t INDEX_ZERO = 0;
50 constexpr int SLEEP_TIME_S = 2;
51 constexpr uint32_t INDEX_ONE = 1;
52 constexpr uint32_t INDEX_TWO = 2;
53 constexpr uint32_t INDEX_THREE = 3;
54 constexpr uint32_t INDEX_FOUR = 4;
55 constexpr uint32_t INDEX_FIVE = 5;
56 constexpr uint32_t BUFFER_SIZE = 64;
57 constexpr const char *SYS_PARAM_PERSIST_EDM_SET_ETHERNET_IP_DISABLE = "persist.edm.set_ethernet_ip_disable";
OnDhcpSuccess(EthernetDhcpCallback::DhcpResult & dhcpResult)58 int32_t EthernetManagement::EhternetDhcpNotifyCallback::OnDhcpSuccess(EthernetDhcpCallback::DhcpResult &dhcpResult)
59 {
60     ethernetManagement_.UpdateDevInterfaceLinkInfo(dhcpResult);
61     return 0;
62 }
63 
OnInterfaceAddressUpdated(const std::string &,const std::string &,int,int)64 int32_t EthernetManagement::DevInterfaceStateCallback::OnInterfaceAddressUpdated(const std::string &,
65                                                                                  const std::string &, int, int)
66 {
67     return 0;
68 }
69 
OnInterfaceAddressRemoved(const std::string &,const std::string &,int,int)70 int32_t EthernetManagement::DevInterfaceStateCallback::OnInterfaceAddressRemoved(const std::string &,
71                                                                                  const std::string &, int, int)
72 {
73     return 0;
74 }
75 
OnInterfaceAdded(const std::string & iface)76 int32_t EthernetManagement::DevInterfaceStateCallback::OnInterfaceAdded(const std::string &iface)
77 {
78     std::regex re(IFACE_MATCH);
79     if (std::regex_search(iface, re)) {
80         ethernetManagement_.DevInterfaceAdd(iface);
81         if (NetsysController::GetInstance().SetInterfaceUp(iface) != ERR_NONE) {
82             NETMGR_EXT_LOG_E("Iface[%{public}s] added set up fail!", iface.c_str());
83         }
84     }
85     return 0;
86 }
87 
OnInterfaceRemoved(const std::string & iface)88 int32_t EthernetManagement::DevInterfaceStateCallback::OnInterfaceRemoved(const std::string &iface)
89 {
90     std::regex re(IFACE_MATCH);
91     if (std::regex_search(iface, re)) {
92         ethernetManagement_.DevInterfaceRemove(iface);
93         if (NetsysController::GetInstance().SetInterfaceDown(iface) != ERR_NONE) {
94             NETMGR_EXT_LOG_E("Iface[%{public}s] added set down fail!", iface.c_str());
95         }
96     }
97     return 0;
98 }
99 
OnInterfaceChanged(const std::string &,bool)100 int32_t EthernetManagement::DevInterfaceStateCallback::OnInterfaceChanged(const std::string &, bool)
101 {
102     return 0;
103 }
104 
OnInterfaceLinkStateChanged(const std::string & ifName,bool up)105 int32_t EthernetManagement::DevInterfaceStateCallback::OnInterfaceLinkStateChanged(const std::string &ifName, bool up)
106 {
107     auto startTime = std::chrono::steady_clock::now();
108     std::regex re(IFACE_MATCH);
109     if (std::regex_search(ifName, re)) {
110         ethernetManagement_.UpdateInterfaceState(ifName, up);
111     }
112     auto endTime = std::chrono::steady_clock::now();
113     auto durationNs = std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime);
114     NETMGR_EXT_LOG_I("OnInterfaceLinkStateChanged iface[%{public}s] up[%{public}d], cost=%{public}lld",
115         ifName.c_str(), up, durationNs.count());
116     return 0;
117 }
118 
OnRouteChanged(bool,const std::string &,const std::string &,const std::string &)119 int32_t EthernetManagement::DevInterfaceStateCallback::OnRouteChanged(bool, const std::string &, const std::string &,
120                                                                       const std::string &)
121 {
122     return 0;
123 }
124 
OnDhcpSuccess(NetsysControllerCallback::DhcpResult & dhcpResult)125 int32_t EthernetManagement::DevInterfaceStateCallback::OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult)
126 {
127     return 0;
128 }
129 
OnBandwidthReachedLimit(const std::string & limitName,const std::string & iface)130 int32_t EthernetManagement::DevInterfaceStateCallback::OnBandwidthReachedLimit(const std::string &limitName,
131                                                                                const std::string &iface)
132 {
133     return 0;
134 }
135 
GetInstance()136 EthernetManagement &EthernetManagement::GetInstance()
137 {
138     static EthernetManagement gInstance;
139     return gInstance;
140 }
141 
EthernetManagement()142 EthernetManagement::EthernetManagement()
143 {
144     ethDhcpController_ = std::make_unique<EthernetDhcpController>();
145     ethDhcpNotifyCallback_ = sptr<EhternetDhcpNotifyCallback>::MakeSptr(*this);
146     if (ethDhcpNotifyCallback_ != nullptr) {
147         ethDhcpController_->RegisterDhcpCallback(ethDhcpNotifyCallback_);
148     }
149 
150     ethDevInterfaceStateCallback_ = sptr<DevInterfaceStateCallback>::MakeSptr(*this);
151     ethConfiguration_ = std::make_unique<EthernetConfiguration>();
152     ethConfiguration_->ReadSystemConfiguration(devCaps_, devCfgs_);
153     ethLanManageMent_ = std::make_unique<EthernetLanManagement>();
154 }
155 
156 EthernetManagement::~EthernetManagement() = default;
157 
UpdateInterfaceState(const std::string & dev,bool up)158 void EthernetManagement::UpdateInterfaceState(const std::string &dev, bool up)
159 {
160     NETMGR_EXT_LOG_D("EthernetManagement UpdateInterfaceState dev[%{public}s] up[%{public}d]", dev.c_str(), up);
161     sptr<DevInterfaceState> devState = nullptr;
162     {
163         std::unique_lock<std::mutex> lock(mutex_);
164         auto fit = devs_.find(dev);
165         if (fit == devs_.end()) {
166             return;
167         }
168         devState = fit->second;
169     }
170     if (devState == nullptr) {
171         NETMGR_EXT_LOG_E("devState is nullptr");
172         return;
173     }
174     devState->SetLinkUp(up);
175     IPSetMode mode = devState->GetIPSetMode();
176     bool dhcpReqState = devState->GetDhcpReqState();
177     NETMGR_EXT_LOG_D("EthernetManagement UpdateInterfaceState mode[%{public}d] dhcpReqState[%{public}d]",
178                      static_cast<int32_t>(mode), dhcpReqState);
179     if (up) {
180         if (!devState->IsLanIface()) {
181             devState->RemoteUpdateNetSupplierInfo();
182         }
183         if ((mode == DHCP || mode == LAN_DHCP) && !dhcpReqState) {
184             StartDhcpClient(dev, devState);
185         } else {
186             if (devState->IsLanIface()) {
187                 ethLanManageMent_->UpdateLanLinkInfo(devState);
188             } else {
189                 devState->RemoteUpdateNetLinkInfo();
190             }
191         }
192     } else {
193         if ((mode == DHCP || mode == LAN_DHCP) && dhcpReqState) {
194             StopDhcpClient(dev, devState);
195         }
196         if (devState->IsLanIface()) {
197             ethLanManageMent_->ReleaseLanNetLink(devState);
198         } else {
199             devState->RemoteUpdateNetSupplierInfo();
200         }
201         netLinkConfigs_[dev] = nullptr;
202     }
203 }
204 
GetMacAddress(std::vector<MacAddressInfo> & macAddrList)205 int32_t EthernetManagement::GetMacAddress(std::vector<MacAddressInfo> &macAddrList)
206 {
207     std::regex re(IFACE_MATCH);
208     std::vector<std::string> ifaceLists = NetsysController::GetInstance().InterfaceGetList();
209     if (ifaceLists.empty()) {
210         NETMGR_EXT_LOG_E("EthernetManagement iface list is empty");
211         return ETHERNET_ERR_DEVICE_INFORMATION_NOT_EXIST;
212     }
213     for (const auto &iface : ifaceLists) {
214         if (std::regex_search(iface, re)) {
215             MacAddressInfo macAddressInfo;
216             auto spMacAddr = GetMacAddr(iface);
217             if (spMacAddr.c_str() == nullptr) {
218                 NETMGR_EXT_LOG_E("The iface[%{public}s] device does not find MAC address", iface.c_str());
219                 continue;
220             }
221             macAddressInfo.iface_ = iface;
222             macAddressInfo.macAddress_ = spMacAddr;
223             macAddrList.push_back(macAddressInfo);
224         }
225     }
226     if (macAddrList.size() == 0) {
227         NETMGR_EXT_LOG_E("EthernetManagement mac address list is empty");
228         return ETHERNET_ERR_DEVICE_INFORMATION_NOT_EXIST;
229     }
230     return NETMANAGER_EXT_SUCCESS;
231 }
232 
GetMacAddr(const std::string & iface)233 std::string EthernetManagement::GetMacAddr(const std::string &iface)
234 {
235     NETMGR_EXT_LOG_D("GetMacAddr when iface is [%{public}s]", iface.c_str());
236     std::string macAddr;
237 
238     int fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
239     struct ifreq ifr = {};
240     strncpy_s(ifr.ifr_name, IFNAMSIZ, iface.c_str(), iface.length());
241 
242     if (ioctl(fd, SIOCGIFHWADDR, &ifr) != -1) {
243         macAddr = HwAddrToStr(ifr.ifr_hwaddr.sa_data);
244     }
245     close(fd);
246     return macAddr;
247 }
248 
HwAddrToStr(char * hwaddr)249 std::string EthernetManagement::HwAddrToStr(char *hwaddr)
250 {
251     char buf[BUFFER_SIZE] = {'\0'};
252     if (hwaddr == nullptr) {
253         NETMGR_EXT_LOG_E("hwaddr is nullptr");
254         return "";
255     }
256     errno_t result =
257         sprintf_s(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[INDEX_ONE],
258             hwaddr[INDEX_TWO], hwaddr[INDEX_THREE], hwaddr[INDEX_FOUR],
259             hwaddr[INDEX_FIVE]);
260     if (result < 0) {
261         NETMGR_EXT_LOG_E("[hwAddrToStr] result error : [%{public}d]", result);
262         return "";
263     }
264     return std::string(buf);
265 }
266 
UpdateDevInterfaceCfg(const std::string & iface,sptr<InterfaceConfiguration> cfg)267 int32_t EthernetManagement::UpdateDevInterfaceCfg(const std::string &iface, sptr<InterfaceConfiguration> cfg)
268 {
269     if (cfg == nullptr) {
270         NETMGR_EXT_LOG_E("cfg is nullptr");
271         return NETMANAGER_EXT_ERR_LOCAL_PTR_NULL;
272     }
273     sptr<DevInterfaceState> devState = nullptr;
274     {
275         std::unique_lock<std::mutex> lock(mutex_);
276         auto fit = devs_.find(iface);
277         if (fit == devs_.end() || fit->second == nullptr) {
278             NETMGR_EXT_LOG_E("The iface[%{public}s] device or device information does not exist", iface.c_str());
279             return ETHERNET_ERR_DEVICE_INFORMATION_NOT_EXIST;
280         }
281         devState = fit->second;
282     }
283     if (!devState->GetLinkUp()) {
284         NETMGR_EXT_LOG_E("The iface[%{public}s] device is unlink", iface.c_str());
285         return ETHERNET_ERR_DEVICE_NOT_LINK;
286     }
287     if (!ModeInputCheck(devState->GetIfcfg()->mode_, cfg->mode_)) {
288         NETMGR_EXT_LOG_E("The iface[%{public}s] device can not exchange between WAN and LAN", iface.c_str());
289         return NETMANAGER_ERR_INVALID_PARAMETER;
290     }
291     if (!CanModifyCheck(devState->GetIfcfg()->mode_, cfg->mode_)) {
292         NETMGR_EXT_LOG_E("The iface[%{public}s] device is not allowed to update", iface.c_str());
293         return NETMANAGER_ERR_PERMISSION_DENIED;
294     }
295     if (!ethConfiguration_->WriteUserConfiguration(iface, cfg)) {
296         NETMGR_EXT_LOG_E("EthernetManagement write user configurations error!");
297         return ETHERNET_ERR_USER_CONIFGURATION_WRITE_FAIL;
298     }
299     if (devState->GetIfcfg()->mode_ != cfg->mode_) {
300         ProcessChangeMode(iface, devState, cfg);
301     } else if (cfg->mode_ == DHCP) {
302         devState->UpdateNetHttpProxy(cfg->httpProxy_);
303     }
304     if (devState->IsLanIface()) {
305         ethLanManageMent_->GetOldLinkInfo(devState);
306         devState->SetLancfg(cfg);
307         ethLanManageMent_->UpdateLanLinkInfo(devState);
308     } else {
309         devState->SetIfcfg(cfg);
310     }
311     devCfgs_[iface] = cfg;
312     return NETMANAGER_EXT_SUCCESS;
313 }
314 
CanModifyCheck(IPSetMode origin,IPSetMode input)315 bool EthernetManagement::CanModifyCheck(IPSetMode origin, IPSetMode input)
316 {
317     std::string param(SYS_PARAM_PERSIST_EDM_SET_ETHERNET_IP_DISABLE);
318     bool isSetEthernetIpDisabled = OHOS::system::GetBoolParameter(param, false);
319     NETMGR_EXT_LOG_D("Set ethernet ip is disabled: %{public}d, origin mode: %{public}d, input mode: %{public}d",
320         isSetEthernetIpDisabled, origin, input);
321     if (isSetEthernetIpDisabled && origin == STATIC && (input == DHCP || input == STATIC)) {
322         return false;
323     }
324     return true;
325 }
326 
ProcessChangeMode(const std::string & iface,sptr<DevInterfaceState> devState,sptr<InterfaceConfiguration> cfg)327 void EthernetManagement::ProcessChangeMode(
328     const std::string &iface, sptr<DevInterfaceState> devState, sptr<InterfaceConfiguration> cfg)
329 {
330     if (cfg->mode_ == DHCP || cfg->mode_ == LAN_DHCP) {
331         StartDhcpClient(iface, devState);
332     } else {
333         StopDhcpClient(iface, devState);
334         netLinkConfigs_[iface] = nullptr;
335     }
336 }
337 
UpdateDevInterfaceLinkInfo(EthernetDhcpCallback::DhcpResult & dhcpResult)338 int32_t EthernetManagement::UpdateDevInterfaceLinkInfo(EthernetDhcpCallback::DhcpResult &dhcpResult)
339 {
340     NETMGR_EXT_LOG_D("EthernetManagement::UpdateDevInterfaceLinkInfo");
341     std::lock_guard<std::mutex> locker(mutex_);
342     auto fit = devs_.find(dhcpResult.iface);
343     if (fit == devs_.end() || fit->second == nullptr) {
344         NETMGR_EXT_LOG_E("The iface[%{public}s] device or device information does not exist", dhcpResult.iface.c_str());
345         return ETHERNET_ERR_DEVICE_INFORMATION_NOT_EXIST;
346     }
347     if (!fit->second->GetLinkUp()) {
348         NETMGR_EXT_LOG_E("The iface[%{public}s] The device is not turned on", dhcpResult.iface.c_str());
349         return ETHERNET_ERR_DEVICE_NOT_LINK;
350     }
351 
352     IPSetMode mode = fit->second->GetIPSetMode();
353     if (mode == IPSetMode::STATIC || mode == IPSetMode::LAN_STATIC) {
354         NETMGR_EXT_LOG_E("The iface[%{public}s] set mode is STATIC now", dhcpResult.iface.c_str());
355         return ETHERNET_ERR_DEVICE_NOT_LINK;
356     }
357 
358     auto &config = netLinkConfigs_[dhcpResult.iface];
359     if (config == nullptr) {
360         config = new (std::nothrow) StaticConfiguration();
361         if (config == nullptr) {
362             NETMGR_EXT_LOG_E("Iface:%{public}s's link info config is nullptr", dhcpResult.iface.c_str());
363             return ETHERNET_ERR_CONVERT_CONFIGURATINO_FAIL;
364         }
365     }
366 
367     if (!ethConfiguration_->ConvertToConfiguration(dhcpResult, config)) {
368         NETMGR_EXT_LOG_E("EthernetManagement dhcp convert to configurations error!");
369         return ETHERNET_ERR_CONVERT_CONFIGURATINO_FAIL;
370     }
371     if (fit->second->IsLanIface()) {
372         ethLanManageMent_->GetOldLinkInfo(fit->second);
373         fit->second->UpdateLanLinkInfo(config);
374         ethLanManageMent_->UpdateLanLinkInfo(fit->second);
375     } else {
376         fit->second->UpdateLinkInfo(config);
377         fit->second->RemoteUpdateNetLinkInfo();
378     }
379     return NETMANAGER_EXT_SUCCESS;
380 }
381 
GetDevInterfaceCfg(const std::string & iface,sptr<InterfaceConfiguration> & ifaceConfig)382 int32_t EthernetManagement::GetDevInterfaceCfg(const std::string &iface, sptr<InterfaceConfiguration> &ifaceConfig)
383 {
384     std::unique_lock<std::mutex> lock(mutex_);
385     auto fit = devs_.find(iface);
386     if (fit == devs_.end() || fit->second == nullptr) {
387         NETMGR_EXT_LOG_E("The iface[%{public}s] device does not exist", iface.c_str());
388         return ETHERNET_ERR_DEVICE_INFORMATION_NOT_EXIST;
389     }
390     if (!fit->second->GetLinkUp()) {
391         ifaceConfig = fit->second->GetIfcfg();
392         return NETMANAGER_EXT_SUCCESS;
393     }
394     auto temp = ethConfiguration_->MakeInterfaceConfiguration(fit->second->GetIfcfg(), fit->second->GetLinkInfo());
395     if (temp == nullptr) {
396         return ETHERNET_ERR_DEVICE_INFORMATION_NOT_EXIST;
397     }
398     ifaceConfig = temp;
399     return NETMANAGER_EXT_SUCCESS;
400 }
401 
IsIfaceActive(const std::string & iface,int32_t & activeStatus)402 int32_t EthernetManagement::IsIfaceActive(const std::string &iface, int32_t &activeStatus)
403 {
404     std::unique_lock<std::mutex> lock(mutex_);
405     auto fit = devs_.find(iface);
406     if (fit == devs_.end() || fit->second == nullptr) {
407         NETMGR_EXT_LOG_E("The iface[%{public}s] device does not exist", iface.c_str());
408         return ETHERNET_ERR_DEVICE_INFORMATION_NOT_EXIST;
409     }
410     activeStatus = static_cast<int32_t>(fit->second->GetLinkUp());
411     return NETMANAGER_EXT_SUCCESS;
412 }
413 
GetAllActiveIfaces(std::vector<std::string> & activeIfaces)414 int32_t EthernetManagement::GetAllActiveIfaces(std::vector<std::string> &activeIfaces)
415 {
416     std::unique_lock<std::mutex> lock(mutex_);
417     for (auto it = devs_.begin(); it != devs_.end(); ++it) {
418         if (it->second->GetLinkUp()) {
419             activeIfaces.push_back(it->first);
420         }
421     }
422     return NETMANAGER_EXT_SUCCESS;
423 }
424 
ResetFactory()425 int32_t EthernetManagement::ResetFactory()
426 {
427     if (!ethConfiguration_->ClearAllUserConfiguration()) {
428         NETMGR_EXT_LOG_E("Failed to ResetFactory!");
429         return ETHERNET_ERR_USER_CONIFGURATION_CLEAR_FAIL;
430     }
431     NETMGR_EXT_LOG_I("Success to ResetFactory!");
432     return NETMANAGER_EXT_SUCCESS;
433 }
434 
Init()435 void EthernetManagement::Init()
436 {
437     static const unsigned int SLEEP_TIME = 4;
438     std::this_thread::sleep_for(std::chrono::seconds(SLEEP_TIME));
439     if (ethDevInterfaceStateCallback_ != nullptr) {
440         NetsysController::GetInstance().RegisterCallback(ethDevInterfaceStateCallback_);
441     }
442     std::regex re(IFACE_MATCH);
443     std::vector<std::string> ifaces = NetsysController::GetInstance().InterfaceGetList();
444     if (ifaces.empty()) {
445         NETMGR_EXT_LOG_E("EthernetManagement link list is empty");
446         return;
447     }
448     NETMGR_EXT_LOG_D("EthernetManagement devs size[%{public}zd]", ifaces.size());
449     if (!ethConfiguration_->ReadUserConfiguration(devCfgs_)) {
450         NETMGR_EXT_LOG_E("EthernetManagement read user configurations error! ");
451         return;
452     }
453     for (const auto &devName : ifaces) {
454         NETMGR_EXT_LOG_D("EthernetManagement devName[%{public}s]", devName.c_str());
455         if (!std::regex_search(devName, re)) {
456             continue;
457         }
458         DevInterfaceAdd(devName);
459     }
460     std::thread t(&EthernetManagement::StartSetDevUpThd, &EthernetManagement::GetInstance());
461     std::string threadName = "SetDevUpThd";
462     pthread_setname_np(t.native_handle(), threadName.c_str());
463     t.detach();
464     NETMGR_EXT_LOG_D("EthernetManagement devs_ size[%{public}zd", devs_.size());
465 }
466 
StartSetDevUpThd()467 void EthernetManagement::StartSetDevUpThd()
468 {
469     NETMGR_EXT_LOG_D("EthernetManagement StartSetDevUpThd in.");
470     std::map<std::string, sptr<DevInterfaceState>> tempDevMap;
471     {
472         std::unique_lock<std::mutex> lock(mutex_);
473         tempDevMap = devs_;
474     }
475 
476     for (auto &dev : tempDevMap) {
477         std::string devName = dev.first;
478         if (IsIfaceLinkUp(devName)) {
479             continue;
480         }
481         while (true) {
482             if (NetsysController::GetInstance().SetInterfaceUp(devName) != ERR_NONE) {
483                 sleep(SLEEP_TIME_S);
484                 continue;
485             }
486             break;
487         }
488     }
489 }
490 
IsIfaceLinkUp(const std::string & iface)491 bool EthernetManagement::IsIfaceLinkUp(const std::string &iface)
492 {
493     OHOS::nmd::InterfaceConfigurationParcel config;
494     config.ifName = iface;
495     if (NetsysController::GetInstance().GetInterfaceConfig(config) != ERR_NONE) {
496         return false;
497     }
498     if (std::find(config.flags.begin(), config.flags.end(), IFACE_LINK_UP) == config.flags.end() ||
499         std::find(config.flags.begin(), config.flags.end(), IFACE_RUNNING) == config.flags.end()) {
500         return false;
501     }
502     UpdateInterfaceState(iface, true);
503     return true;
504 }
505 
StartDhcpClient(const std::string & dev,sptr<DevInterfaceState> & devState)506 void EthernetManagement::StartDhcpClient(const std::string &dev, sptr<DevInterfaceState> &devState)
507 {
508     NETMGR_EXT_LOG_D("EthernetManagement StartDhcpClient[%{public}s]", dev.c_str());
509     ethDhcpController_->StartClient(dev, true);
510     devState->SetDhcpReqState(true);
511 }
512 
StopDhcpClient(const std::string & dev,sptr<DevInterfaceState> & devState)513 void EthernetManagement::StopDhcpClient(const std::string &dev, sptr<DevInterfaceState> &devState)
514 {
515     NETMGR_EXT_LOG_D("EthernetManagement StopDhcpClient[%{public}s]", dev.c_str());
516     ethDhcpController_->StopClient(dev, true);
517     devState->SetDhcpReqState(false);
518 }
519 
DevInterfaceAdd(const std::string & devName)520 void EthernetManagement::DevInterfaceAdd(const std::string &devName)
521 {
522     NETMGR_EXT_LOG_D("Interface name:[%{public}s] add.", devName.c_str());
523     std::unique_lock<std::mutex> lock(mutex_);
524     auto fitDev = devs_.find(devName);
525     if (fitDev != devs_.end()) {
526         NETMGR_EXT_LOG_E("Interface name:[%{public}s] has added.", devName.c_str());
527         return;
528     }
529     sptr<DevInterfaceState> devState = new (std::nothrow) DevInterfaceState();
530     if (devState == nullptr) {
531         NETMGR_EXT_LOG_E("devState is nullptr");
532         return;
533     }
534     ethConfiguration_->ReadSystemConfiguration(devCaps_, devCfgs_);
535     devs_.insert(std::make_pair(devName, devState));
536     devState->SetDevName(devName);
537     auto fitCfg = devCfgs_.find(devName);
538     if (fitCfg != devCfgs_.end()) {
539         if (fitCfg->second->mode_ == LAN_STATIC || fitCfg->second->mode_ == LAN_DHCP) {
540             NETMGR_EXT_LOG_D("Lan Interface name:[%{public}s] add, mode [%{public}d]",
541                              devName.c_str(), fitCfg->second->mode_);
542             devState->SetLancfg(fitCfg->second);
543             ethLanManageMent_->UpdateLanLinkInfo(devState);
544             return;
545         }
546         devState->RemoteRegisterNetSupplier();
547         devState->SetIfcfg(fitCfg->second);
548     } else {
549         sptr<InterfaceConfiguration> ifCfg = new (std::nothrow) InterfaceConfiguration();
550         if (ifCfg == nullptr) {
551             NETMGR_EXT_LOG_E("ifCfg is nullptr");
552             return;
553         }
554         ifCfg->mode_ = DHCP;
555         devState->RemoteRegisterNetSupplier();
556         devState->SetIfcfg(ifCfg);
557     }
558     auto fitCap = devCaps_.find(devName);
559     if (fitCap != devCaps_.end()) {
560         devState->SetNetCaps(fitCap->second);
561     }
562 }
563 
DevInterfaceRemove(const std::string & devName)564 void EthernetManagement::DevInterfaceRemove(const std::string &devName)
565 {
566     NETMGR_EXT_LOG_D("Interface name:[%{public}s] remove.", devName.c_str());
567     std::unique_lock<std::mutex> lock(mutex_);
568     auto fitDev = devs_.find(devName);
569     if (fitDev != devs_.end()) {
570         if (fitDev->second != nullptr) {
571             fitDev->second->RemoteUnregisterNetSupplier();
572         }
573         devs_.erase(fitDev);
574     }
575 }
576 
GetDumpInfo(std::string & info)577 void EthernetManagement::GetDumpInfo(std::string &info)
578 {
579     std::for_each(devs_.begin(), devs_.end(), [&info](const auto &dev) { dev.second->GetDumpInfo(info); });
580 }
581 
ModeInputCheck(IPSetMode origin,IPSetMode input)582 bool EthernetManagement::ModeInputCheck(IPSetMode origin, IPSetMode input)
583 {
584     if (origin == STATIC || origin == DHCP) {
585         if (input == LAN_STATIC || input == LAN_DHCP) {
586             return false;
587         }
588     } else if (origin == LAN_STATIC || origin == LAN_DHCP) {
589         if (input == STATIC || input == DHCP) {
590             return false;
591         }
592     }
593     return true;
594 }
595 
GetSysNodeValue(const std::string & nodePath,std::string & nodeVal)596 bool EthernetManagement::GetSysNodeValue(const std::string &nodePath, std::string &nodeVal)
597 {
598     std::ifstream infile;
599     std::string strLine;
600     std::error_code ec;
601 
602     std::filesystem::path filePath(nodePath);
603     if (!std::filesystem::exists(filePath)) {
604         NETMGR_EXT_LOG_E("GetSysNodeValue nodePath not exist");
605         return false;
606     }
607     auto truePath = std::filesystem::canonical(filePath, ec);
608     if (ec) {
609         NETMGR_EXT_LOG_E("GetSysNodeValue canonical failed:%{public}s", ec.message().c_str());
610         return false;
611     }
612     std::string truePathStr = truePath.string();
613     infile.open(truePathStr);
614     if (!infile.is_open()) {
615         NETMGR_EXT_LOG_E("GetSysNodeValue open failed");
616         return false;
617     }
618     while (getline(infile, strLine)) {
619         nodeVal.append(strLine);
620     }
621     infile.close();
622     return true;
623 }
624 
GetUsbEthDeviceInfo(const std::string & iface,std::string & nodePath,std::vector<EthernetDeviceInfo> & deviceInfoList)625 void EthernetManagement::GetUsbEthDeviceInfo(const std::string &iface, std::string &nodePath,
626     std::vector<EthernetDeviceInfo> &deviceInfoList)
627 {
628     size_t pos = nodePath.find_last_of('/');
629     if (pos != std::string::npos) {
630         nodePath.erase(pos);
631     }
632     EthernetDeviceInfo tempDeviceInfo;
633     tempDeviceInfo.ifaceName_ = iface;
634     tempDeviceInfo.connectionMode_ = EXTERNAL;
635     bool ret = true;
636     ret &= GetSysNodeValue(nodePath + ITEM_DEVICE_NAME, tempDeviceInfo.deviceName_);
637     ret &= GetSysNodeValue(nodePath + ITEM_SUPPLIER_NAME, tempDeviceInfo.supplierName_);
638     ret &= GetSysNodeValue(nodePath + ITEM_SUPPLIER_ID, tempDeviceInfo.supplierId_);
639     ret &= GetSysNodeValue(nodePath + ITEM_MAXIMUM_RATE, tempDeviceInfo.maximumRate_);
640     tempDeviceInfo.productName_ = tempDeviceInfo.deviceName_;
641     tempDeviceInfo.maximumRate_ += ITEM_UNIT_MBS;
642     if (ret) {
643         deviceInfoList.push_back(tempDeviceInfo);
644     }
645 }
646 
GetPciEthDeviceInfo(const std::string & iface,std::string nodePath,std::vector<EthernetDeviceInfo> & deviceInfoList)647 void EthernetManagement::GetPciEthDeviceInfo(const std::string &iface, std::string nodePath,
648     std::vector<EthernetDeviceInfo> &deviceInfoList)
649 {
650     std::string value;
651     if (!GetSysNodeValue(nodePath, value)) {
652         return;
653     }
654     auto valVec = CommonUtils::Split(value, ITEM_COMMA);
655     if (valVec.size() != INDEX_FOUR) {
656         return;
657     }
658     EthernetDeviceInfo tempDeviceInfo;
659     tempDeviceInfo.ifaceName_ = iface;
660     tempDeviceInfo.connectionMode_ = BUILT_IN;
661     tempDeviceInfo.deviceName_ = valVec[INDEX_ZERO];
662     tempDeviceInfo.supplierId_ = valVec[INDEX_ONE];
663     tempDeviceInfo.supplierName_ = valVec[INDEX_TWO];
664     tempDeviceInfo.maximumRate_ = valVec[INDEX_THREE] + ITEM_UNIT_MBS;
665     tempDeviceInfo.productName_ = tempDeviceInfo.deviceName_;
666     deviceInfoList.push_back(tempDeviceInfo);
667 }
668 
GetDeviceInformation(std::vector<EthernetDeviceInfo> & deviceInfoList)669 int32_t EthernetManagement::GetDeviceInformation(std::vector<EthernetDeviceInfo> &deviceInfoList)
670 {
671     deviceInfoList.clear();
672     std::vector<std::string> ifaces;
673     std::unique_lock<std::mutex> lock(mutex_);
674     for (auto it = devs_.begin(); it != devs_.end(); ++it) {
675         ifaces.emplace_back(it->first);
676     }
677     lock.unlock();
678     for (std::string &iface : ifaces) {
679         std::string netDevicePath = SYS_CLASS_NET_PATH + iface + ITEM_DEVICE;
680         std::filesystem::path filePath(netDevicePath);
681         auto truePath = std::filesystem::canonical(filePath);
682         if (!std::filesystem::exists(truePath)) {
683             NETMGR_EXT_LOG_E("GetDeviceInformation truePath %{public}s not exist", truePath.string().c_str());
684             continue;
685         }
686         std::string netDevNodePath = truePath.string();
687         if (netDevNodePath.find(ITEM_USB) != std::string::npos) {
688             GetUsbEthDeviceInfo(iface, netDevNodePath, deviceInfoList);
689         } else {
690             GetPciEthDeviceInfo(iface, MDIO_BUS_DEV_INFO_PATH, deviceInfoList);
691         }
692     }
693     if (deviceInfoList.size() == 0) {
694         NETMGR_EXT_LOG_E("GetDeviceInformation list empty");
695         return ETHERNET_ERR_DEVICE_INFORMATION_NOT_EXIST;
696     }
697     return NETMANAGER_EXT_SUCCESS;
698 }
699 } // namespace NetManagerStandard
700 } // namespace OHOS
701