1 /*
2  * Copyright (c) 2021-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 "common_event_support.h"
17 
18 #include "broadcast_manager.h"
19 #include "event_report.h"
20 #include "net_conn_service_iface.h"
21 #include "net_manager_constants.h"
22 #include "net_mgr_log_wrapper.h"
23 #include "net_stats_client.h"
24 #include "netmanager_base_common_utils.h"
25 #include "netsys_controller.h"
26 #include "network.h"
27 #include "route_utils.h"
28 #include "securec.h"
29 
30 using namespace OHOS::NetManagerStandard::CommonUtils;
31 
32 namespace OHOS {
33 namespace NetManagerStandard {
34 namespace {
35 // hisysevent error messgae
36 constexpr const char *ERROR_MSG_CREATE_PHYSICAL_NETWORK_FAILED = "Create physical network failed, net id:";
37 constexpr const char *ERROR_MSG_CREATE_VIRTUAL_NETWORK_FAILED = "Create virtual network failed, net id:";
38 constexpr const char *ERROR_MSG_ADD_NET_INTERFACE_FAILED = "Add network interface failed";
39 constexpr const char *ERROR_MSG_REMOVE_NET_INTERFACE_FAILED = "Remove network interface failed";
40 constexpr const char *ERROR_MSG_DELETE_NET_IP_ADDR_FAILED = "Delete network ip address failed";
41 constexpr const char *ERROR_MSG_ADD_NET_IP_ADDR_FAILED = "Add network ip address failed";
42 constexpr const char *ERROR_MSG_REMOVE_NET_ROUTES_FAILED = "Remove network routes failed";
43 constexpr const char *ERROR_MSG_ADD_NET_ROUTES_FAILED = "Add network routes failed";
44 constexpr const char *ERROR_MSG_UPDATE_NET_ROUTES_FAILED = "Update netlink routes failed,routes list is empty";
45 constexpr const char *ERROR_MSG_SET_NET_RESOLVER_FAILED = "Set network resolver config failed";
46 constexpr const char *ERROR_MSG_UPDATE_NET_DNSES_FAILED = "Update netlink dns failed,dns list is empty";
47 constexpr const char *ERROR_MSG_SET_NET_MTU_FAILED = "Set netlink interface mtu failed";
48 constexpr const char *ERROR_MSG_SET_NET_TCP_BUFFER_SIZE_FAILED = "Set netlink tcp buffer size failed";
49 constexpr const char *ERROR_MSG_UPDATE_STATS_CACHED = "force update kernel map stats cached failed";
50 constexpr const char *ERROR_MSG_SET_DEFAULT_NETWORK_FAILED = "Set default network failed";
51 constexpr const char *ERROR_MSG_CLEAR_DEFAULT_NETWORK_FAILED = "Clear default network failed";
52 constexpr const char *LOCAL_ROUTE_NEXT_HOP = "0.0.0.0";
53 constexpr const char *LOCAL_ROUTE_IPV6_DESTINATION = "::";
54 constexpr int32_t ERRNO_EADDRNOTAVAIL = -99;
55 } // namespace
56 
Network(int32_t netId,uint32_t supplierId,const NetDetectionHandler & handler,NetBearType bearerType,const std::shared_ptr<NetConnEventHandler> & eventHandler)57 Network::Network(int32_t netId, uint32_t supplierId, const NetDetectionHandler &handler, NetBearType bearerType,
58                  const std::shared_ptr<NetConnEventHandler> &eventHandler)
59     : netId_(netId),
60       supplierId_(supplierId),
61       netCallback_(handler),
62       netSupplierType_(bearerType),
63       eventHandler_(eventHandler)
64 {
65 }
66 
GetNetId() const67 int32_t Network::GetNetId() const
68 {
69     return netId_;
70 }
71 
GetSupplierId() const72 uint32_t Network::GetSupplierId() const
73 {
74     return supplierId_;
75 }
76 
operator ==(const Network & network) const77 bool Network::operator==(const Network &network) const
78 {
79     return netId_ == network.netId_;
80 }
81 
UpdateBasicNetwork(bool isAvailable_)82 bool Network::UpdateBasicNetwork(bool isAvailable_)
83 {
84     NETMGR_LOG_D("Enter UpdateBasicNetwork");
85     if (isAvailable_) {
86         if (netSupplierType_ == BEARER_VPN) {
87             return CreateVirtualNetwork();
88         }
89         return CreateBasicNetwork();
90     } else {
91         if (netSupplierType_ == BEARER_VPN) {
92             return ReleaseVirtualNetwork();
93         }
94         if (nat464Service_ != nullptr) {
95             nat464Service_->UpdateService(NAT464_SERVICE_STOP);
96         }
97         return ReleaseBasicNetwork();
98     }
99 }
100 
CreateBasicNetwork()101 bool Network::CreateBasicNetwork()
102 {
103     NETMGR_LOG_D("Enter CreateBasicNetwork");
104     if (!isPhyNetCreated_) {
105         NETMGR_LOG_D("Create physical network");
106         // Create a physical network
107         if (NetsysController::GetInstance().NetworkCreatePhysical(netId_, 0) != NETMANAGER_SUCCESS) {
108             std::string errMsg = std::string(ERROR_MSG_CREATE_PHYSICAL_NETWORK_FAILED).append(std::to_string(netId_));
109             SendSupplierFaultHiSysEvent(FAULT_CREATE_PHYSICAL_NETWORK_FAILED, errMsg);
110         }
111         NetsysController::GetInstance().CreateNetworkCache(netId_);
112         isPhyNetCreated_ = true;
113     }
114     return true;
115 }
116 
CreateVirtualNetwork()117 bool Network::CreateVirtualNetwork()
118 {
119     NETMGR_LOG_D("Enter create virtual network");
120     if (!isVirtualCreated_) {
121         // Create a virtual network here
122         bool hasDns = netLinkInfo_.dnsList_.size() ? true : false;
123         if (NetsysController::GetInstance().NetworkCreateVirtual(netId_, hasDns) != NETMANAGER_SUCCESS) {
124             std::string errMsg = std::string(ERROR_MSG_CREATE_VIRTUAL_NETWORK_FAILED).append(std::to_string(netId_));
125             SendSupplierFaultHiSysEvent(FAULT_CREATE_VIRTUAL_NETWORK_FAILED, errMsg);
126         }
127         NetsysController::GetInstance().CreateNetworkCache(netId_);
128         isVirtualCreated_ = true;
129     }
130     return true;
131 }
132 
IsAddrInOtherNetwork(const INetAddr & netAddr)133 bool Network::IsAddrInOtherNetwork(const INetAddr &netAddr)
134 {
135     return NetConnServiceIface().IsAddrInOtherNetwork(netLinkInfo_.ifaceName_, netId_, netAddr);
136 }
137 
IsIfaceNameInUse()138 bool Network::IsIfaceNameInUse()
139 {
140     return NetConnServiceIface().IsIfaceNameInUse(netLinkInfo_.ifaceName_, netId_);
141 }
142 
GetNetCapabilitiesAsString(const uint32_t supplierId) const143 std::string Network::GetNetCapabilitiesAsString(const uint32_t supplierId) const
144 {
145     return NetConnServiceIface().GetNetCapabilitiesAsString(supplierId);
146 }
147 
ReleaseBasicNetwork()148 bool Network::ReleaseBasicNetwork()
149 {
150     NETMGR_LOG_D("Enter ReleaseBasicNetwork");
151     if (!isPhyNetCreated_) {
152         return true;
153     }
154     NETMGR_LOG_D("Destroy physical network");
155     StopNetDetection();
156     std::string netCapabilities = GetNetCapabilitiesAsString(supplierId_);
157     NETMGR_LOG_D("ReleaseBasicNetwork supplierId %{public}u, netId %{public}d, netCapabilities %{public}s",
158         supplierId_, netId_, netCapabilities.c_str());
159     if (!IsIfaceNameInUse()) {
160         for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
161             int32_t prefixLen = inetAddr.prefixlen_ == 0 ? Ipv4PrefixLen(inetAddr.netMask_) : inetAddr.prefixlen_;
162             NetsysController::GetInstance().DelInterfaceAddress(netLinkInfo_.ifaceName_, inetAddr.address_,
163                                                                 prefixLen);
164         }
165         for (const auto &route : netLinkInfo_.routeList_) {
166             auto destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
167             NetsysController::GetInstance().NetworkRemoveRoute(netId_, route.iface_, destAddress,
168                                                                route.gateway_.address_);
169             if (route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP &&
170                 route.destination_.address_ != LOCAL_ROUTE_IPV6_DESTINATION) {
171                 auto family = GetAddrFamily(route.destination_.address_);
172                 std::string nextHop = (family == AF_INET6) ? "" : LOCAL_ROUTE_NEXT_HOP;
173                 NetsysController::GetInstance().NetworkRemoveRoute(LOCAL_NET_ID, route.iface_, destAddress, nextHop);
174             }
175         }
176     } else {
177         for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
178             int32_t prefixLen = inetAddr.prefixlen_ == 0 ? Ipv4PrefixLen(inetAddr.netMask_) : inetAddr.prefixlen_;
179             NetsysController::GetInstance().DelInterfaceAddress(netLinkInfo_.ifaceName_, inetAddr.address_,
180                                                                 prefixLen, netCapabilities);
181         }
182     }
183     NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfo_.ifaceName_);
184     NetsysController::GetInstance().NetworkDestroy(netId_);
185     NetsysController::GetInstance().DestroyNetworkCache(netId_);
186     netLinkInfo_.Initialize();
187     isPhyNetCreated_ = false;
188     return true;
189 }
190 
ReleaseVirtualNetwork()191 bool Network::ReleaseVirtualNetwork()
192 {
193     NETMGR_LOG_D("Enter release virtual network");
194     if (isVirtualCreated_) {
195         for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
196             int32_t prefixLen = inetAddr.prefixlen_;
197             if (prefixLen == 0) {
198                 prefixLen = Ipv4PrefixLen(inetAddr.netMask_);
199             }
200             NetsysController::GetInstance().DelInterfaceAddress(netLinkInfo_.ifaceName_, inetAddr.address_, prefixLen);
201         }
202         NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfo_.ifaceName_);
203         NetsysController::GetInstance().NetworkDestroy(netId_);
204         NetsysController::GetInstance().DestroyNetworkCache(netId_);
205         netLinkInfo_.Initialize();
206         isVirtualCreated_ = false;
207     }
208     return true;
209 }
210 
UpdateNetLinkInfo(const NetLinkInfo & netLinkInfo)211 bool Network::UpdateNetLinkInfo(const NetLinkInfo &netLinkInfo)
212 {
213     NETMGR_LOG_D("update net link information process");
214     UpdateStatsCached(netLinkInfo);
215     UpdateInterfaces(netLinkInfo);
216     UpdateIpAddrs(netLinkInfo);
217     UpdateRoutes(netLinkInfo);
218     UpdateDns(netLinkInfo);
219     UpdateMtu(netLinkInfo);
220     UpdateTcpBufferSize(netLinkInfo);
221 
222     netLinkInfo_ = netLinkInfo;
223     if (IsNat464Prefered()) {
224         if (nat464Service_ == nullptr) {
225             nat464Service_ = std::make_unique<Nat464Service>(netId_, netLinkInfo_.ifaceName_);
226         }
227         nat464Service_->MaybeUpdateV6Iface(netLinkInfo_.ifaceName_);
228         nat464Service_->UpdateService(NAT464_SERVICE_CONTINUE);
229     } else if (nat464Service_ != nullptr) {
230         nat464Service_->UpdateService(NAT464_SERVICE_STOP);
231     }
232 
233     if (netSupplierType_ != BEARER_VPN && netCaps_.find(NetCap::NET_CAPABILITY_INTERNET) != netCaps_.end()) {
234         StartNetDetection(false);
235     }
236     return true;
237 }
238 
GetNetLinkInfo() const239 NetLinkInfo Network::GetNetLinkInfo() const
240 {
241     NetLinkInfo linkInfo = netLinkInfo_;
242     for (auto iter = linkInfo.routeList_.begin(); iter != linkInfo.routeList_.end();) {
243         if (iter->destination_.address_ == LOCAL_ROUTE_NEXT_HOP ||
244             iter->destination_.address_ == LOCAL_ROUTE_IPV6_DESTINATION) {
245             ++iter;
246             continue;
247         }
248         iter = linkInfo.routeList_.erase(iter);
249     }
250     return linkInfo;
251 }
252 
GetHttpProxy() const253 HttpProxy Network::GetHttpProxy() const
254 {
255     return netLinkInfo_.httpProxy_;
256 }
257 
GetIfaceName() const258 std::string Network::GetIfaceName() const
259 {
260     return netLinkInfo_.ifaceName_;
261 }
262 
GetIdent() const263 std::string Network::GetIdent() const
264 {
265     return netLinkInfo_.ident_;
266 }
267 
UpdateInterfaces(const NetLinkInfo & newNetLinkInfo)268 void Network::UpdateInterfaces(const NetLinkInfo &newNetLinkInfo)
269 {
270     NETMGR_LOG_D("Network UpdateInterfaces in.");
271     if (newNetLinkInfo.ifaceName_ == netLinkInfo_.ifaceName_) {
272         NETMGR_LOG_D("Network UpdateInterfaces out. same with before.");
273         return;
274     }
275 
276     int32_t ret = NETMANAGER_SUCCESS;
277     // Call netsys to add and remove interface
278     if (!newNetLinkInfo.ifaceName_.empty()) {
279         ret = NetsysController::GetInstance().NetworkAddInterface(netId_, newNetLinkInfo.ifaceName_, netSupplierType_);
280         if (ret != NETMANAGER_SUCCESS) {
281             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_INTERFACE_FAILED);
282         }
283     }
284     if (!netLinkInfo_.ifaceName_.empty()) {
285         ret = NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfo_.ifaceName_);
286         if (ret != NETMANAGER_SUCCESS) {
287             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_INTERFACE_FAILED);
288         }
289     }
290     netLinkInfo_.ifaceName_ = newNetLinkInfo.ifaceName_;
291     NETMGR_LOG_D("Network UpdateInterfaces out.");
292 }
293 
UpdateIpAddrs(const NetLinkInfo & newNetLinkInfo)294 void Network::UpdateIpAddrs(const NetLinkInfo &newNetLinkInfo)
295 {
296     // netLinkInfo_ represents the old, netLinkInfo represents the new
297     // Update: remove old Ips first, then add the new Ips
298     NETMGR_LOG_I("UpdateIpAddrs, old ip addrs size: [%{public}zu]", netLinkInfo_.netAddrList_.size());
299     for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
300         if (IsAddrInOtherNetwork(inetAddr)) {
301             continue;
302         }
303         if (newNetLinkInfo.HasNetAddr(inetAddr)) {
304             NETMGR_LOG_W("Same ip address:[%{public}s], there is not need to be deleted",
305                 CommonUtils::ToAnonymousIp(inetAddr.address_).c_str());
306             continue;
307         }
308         auto family = GetAddrFamily(inetAddr.address_);
309         auto prefixLen = inetAddr.prefixlen_ ? static_cast<int32_t>(inetAddr.prefixlen_)
310                                              : ((family == AF_INET6) ? Ipv6PrefixLen(inetAddr.netMask_)
311                                                                      : Ipv4PrefixLen(inetAddr.netMask_));
312         int32_t ret =
313             NetsysController::GetInstance().DelInterfaceAddress(netLinkInfo_.ifaceName_, inetAddr.address_, prefixLen);
314         if (NETMANAGER_SUCCESS != ret) {
315             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_DELETE_NET_IP_ADDR_FAILED);
316         }
317 
318         if ((ret == ERRNO_EADDRNOTAVAIL) || (ret == 0)) {
319             NETMGR_LOG_W("remove route info of ip address:[%{public}s]",
320                 CommonUtils::ToAnonymousIp(inetAddr.address_).c_str());
321             netLinkInfo_.routeList_.remove_if([family](const Route &route) {
322                 INetAddr::IpType addrFamily = INetAddr::IpType::UNKNOWN;
323                 if (family == AF_INET) {
324                     addrFamily = INetAddr::IpType::IPV4;
325                 } else if (family == AF_INET6) {
326                     addrFamily = INetAddr::IpType::IPV6;
327                 }
328                 return route.destination_.type_ == addrFamily;
329             });
330         }
331     }
332 
333     HandleUpdateIpAddrs(newNetLinkInfo);
334 }
335 
HandleUpdateIpAddrs(const NetLinkInfo & newNetLinkInfo)336 void Network::HandleUpdateIpAddrs(const NetLinkInfo &newNetLinkInfo)
337 {
338     NETMGR_LOG_I("HandleUpdateIpAddrs, new ip addrs size: [%{public}zu]", newNetLinkInfo.netAddrList_.size());
339     for (const auto &inetAddr : newNetLinkInfo.netAddrList_) {
340         if (IsAddrInOtherNetwork(inetAddr)) {
341             continue;
342         }
343         if (netLinkInfo_.HasNetAddr(inetAddr)) {
344             NETMGR_LOG_W("Same ip address:[%{public}s], there is no need to add it again",
345                          CommonUtils::ToAnonymousIp(inetAddr.address_).c_str());
346             continue;
347         }
348         auto family = GetAddrFamily(inetAddr.address_);
349         auto prefixLen = inetAddr.prefixlen_ ? static_cast<int32_t>(inetAddr.prefixlen_)
350                                              : ((family == AF_INET6) ? Ipv6PrefixLen(inetAddr.netMask_)
351                                                                      : Ipv4PrefixLen(inetAddr.netMask_));
352         if (NETMANAGER_SUCCESS != NetsysController::GetInstance().AddInterfaceAddress(newNetLinkInfo.ifaceName_,
353                                                                                       inetAddr.address_, prefixLen)) {
354             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_IP_ADDR_FAILED);
355         }
356     }
357 }
358 
UpdateRoutes(const NetLinkInfo & newNetLinkInfo)359 void Network::UpdateRoutes(const NetLinkInfo &newNetLinkInfo)
360 {
361     // netLinkInfo_ contains the old routes info, netLinkInfo contains the new routes info
362     // Update: remove old routes first, then add the new routes
363     NETMGR_LOG_D("UpdateRoutes, old routes: [%{public}s]", netLinkInfo_.ToStringRoute("").c_str());
364     for (const auto &route : netLinkInfo_.routeList_) {
365         if (newNetLinkInfo.HasRoute(route)) {
366             NETMGR_LOG_W("Same route:[%{public}s]  ifo, there is not need to be deleted",
367                          CommonUtils::ToAnonymousIp(route.destination_.address_).c_str());
368             continue;
369         }
370         std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
371         auto ret = NetsysController::GetInstance().NetworkRemoveRoute(netId_, route.iface_, destAddress,
372                                                                       route.gateway_.address_);
373         int32_t res = NETMANAGER_SUCCESS;
374         if (netSupplierType_ != BEARER_VPN && route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP &&
375             route.destination_.address_ != LOCAL_ROUTE_IPV6_DESTINATION) {
376             auto family = GetAddrFamily(route.destination_.address_);
377             std::string nextHop = (family == AF_INET6) ? "" : LOCAL_ROUTE_NEXT_HOP;
378             res = NetsysController::GetInstance().NetworkRemoveRoute(LOCAL_NET_ID, route.iface_, destAddress, nextHop);
379         }
380         if (ret != NETMANAGER_SUCCESS || res != NETMANAGER_SUCCESS) {
381             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_ROUTES_FAILED);
382         }
383     }
384 
385     NETMGR_LOG_D("UpdateRoutes, new routes: [%{public}s]", newNetLinkInfo.ToStringRoute("").c_str());
386     for (const auto &route : newNetLinkInfo.routeList_) {
387         if (netLinkInfo_.HasRoute(route)) {
388             NETMGR_LOG_W("Same route:[%{public}s]  ifo, there is no need to add it again",
389                          CommonUtils::ToAnonymousIp(route.destination_.address_).c_str());
390             continue;
391         }
392 
393         std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
394         auto ret =
395             NetsysController::GetInstance().NetworkAddRoute(netId_, route.iface_, destAddress, route.gateway_.address_);
396         int32_t res = NETMANAGER_SUCCESS;
397         if (netSupplierType_ != BEARER_VPN && route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP &&
398             route.destination_.address_ != LOCAL_ROUTE_IPV6_DESTINATION) {
399             auto family = GetAddrFamily(route.destination_.address_);
400             std::string nextHop = (family == AF_INET6) ? "" : LOCAL_ROUTE_NEXT_HOP;
401             res = NetsysController::GetInstance().NetworkAddRoute(LOCAL_NET_ID, route.iface_, destAddress, nextHop);
402         }
403         if (ret != NETMANAGER_SUCCESS || res != NETMANAGER_SUCCESS) {
404             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_ROUTES_FAILED);
405         }
406     }
407     NETMGR_LOG_D("Network UpdateRoutes out.");
408     if (newNetLinkInfo.routeList_.empty()) {
409         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_ROUTES_FAILED);
410     }
411 }
412 
UpdateDns(const NetLinkInfo & netLinkInfo)413 void Network::UpdateDns(const NetLinkInfo &netLinkInfo)
414 {
415     NETMGR_LOG_D("Network UpdateDns in.");
416     std::vector<std::string> servers;
417     std::vector<std::string> domains;
418     std::stringstream ss;
419     for (const auto &dns : netLinkInfo.dnsList_) {
420         servers.emplace_back(dns.address_);
421         domains.emplace_back(dns.hostName_);
422         ss << '[' << CommonUtils::ToAnonymousIp(dns.address_).c_str() << ']';
423     }
424     NETMGR_LOG_I("update dns server: %{public}s", ss.str().c_str());
425     // Call netsys to set dns, use default timeout and retry
426     int32_t ret = NetsysController::GetInstance().SetResolverConfig(netId_, 0, 0, servers, domains);
427     if (ret != NETMANAGER_SUCCESS) {
428         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_RESOLVER_FAILED);
429     }
430     NETMGR_LOG_D("Network UpdateDns out.");
431     if (netLinkInfo.dnsList_.empty()) {
432         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_DNSES_FAILED);
433     }
434 }
435 
UpdateMtu(const NetLinkInfo & netLinkInfo)436 void Network::UpdateMtu(const NetLinkInfo &netLinkInfo)
437 {
438     NETMGR_LOG_D("Network UpdateMtu in.");
439     if (netLinkInfo.mtu_ == netLinkInfo_.mtu_) {
440         NETMGR_LOG_D("Network UpdateMtu out. same with before.");
441         return;
442     }
443 
444     int32_t ret = NetsysController::GetInstance().SetInterfaceMtu(netLinkInfo.ifaceName_, netLinkInfo.mtu_);
445     if (ret != NETMANAGER_SUCCESS) {
446         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_MTU_FAILED);
447     }
448     NETMGR_LOG_D("Network UpdateMtu out.");
449 }
450 
UpdateTcpBufferSize(const NetLinkInfo & netLinkInfo)451 void Network::UpdateTcpBufferSize(const NetLinkInfo &netLinkInfo)
452 {
453     NETMGR_LOG_D("Network UpdateTcpBufferSize in.");
454     if (netLinkInfo.tcpBufferSizes_ == netLinkInfo_.tcpBufferSizes_) {
455         NETMGR_LOG_D("Network UpdateTcpBufferSize out. same with before.");
456         return;
457     }
458     int32_t ret = NetsysController::GetInstance().SetTcpBufferSizes(netLinkInfo.tcpBufferSizes_);
459     if (ret != NETMANAGER_SUCCESS) {
460         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_TCP_BUFFER_SIZE_FAILED);
461     }
462     NETMGR_LOG_D("Network UpdateTcpBufferSize out.");
463 }
464 
UpdateStatsCached(const NetLinkInfo & netLinkInfo)465 void Network::UpdateStatsCached(const NetLinkInfo &netLinkInfo)
466 {
467     NETMGR_LOG_D("Network UpdateStatsCached in.");
468     if (netLinkInfo.ifaceName_ == netLinkInfo_.ifaceName_ && netLinkInfo.ident_ == netLinkInfo_.ident_) {
469         NETMGR_LOG_D("Network UpdateStatsCached out. same with before");
470         return;
471     }
472     int32_t ret = NetStatsClient::GetInstance().UpdateStatsData();
473     if (ret != NETMANAGER_SUCCESS) {
474         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_STATS_CACHED);
475     }
476     NETMGR_LOG_D("Network UpdateStatsCached out.");
477 }
478 
RegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)479 void Network::RegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
480 {
481     NETMGR_LOG_I("Enter RNDCB");
482     if (callback == nullptr) {
483         NETMGR_LOG_E("The parameter callback is null");
484         return;
485     }
486 
487     for (const auto &iter : netDetectionRetCallback_) {
488         if (callback->AsObject().GetRefPtr() == iter->AsObject().GetRefPtr()) {
489             NETMGR_LOG_D("netDetectionRetCallback_ had this callback");
490             return;
491         }
492     }
493 
494     netDetectionRetCallback_.emplace_back(callback);
495 }
496 
UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)497 int32_t Network::UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
498 {
499     NETMGR_LOG_I("Enter URNDCB");
500     if (callback == nullptr) {
501         NETMGR_LOG_E("The parameter of callback is null");
502         return NETMANAGER_ERR_LOCAL_PTR_NULL;
503     }
504 
505     for (auto iter = netDetectionRetCallback_.begin(); iter != netDetectionRetCallback_.end(); ++iter) {
506         if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
507             netDetectionRetCallback_.erase(iter);
508             return NETMANAGER_SUCCESS;
509         }
510     }
511 
512     return NETMANAGER_SUCCESS;
513 }
514 
StartNetDetection(bool needReport)515 void Network::StartNetDetection(bool needReport)
516 {
517     NETMGR_LOG_I("Enter StartNetDetection");
518     if (needReport || netMonitor_) {
519         StopNetDetection();
520         InitNetMonitor();
521         return;
522     }
523     if (!netMonitor_) {
524         NETMGR_LOG_I("netMonitor_ is null.");
525         InitNetMonitor();
526         return;
527     }
528 }
529 
SetNetCaps(const std::set<NetCap> & netCaps)530 void Network::SetNetCaps(const std::set<NetCap> &netCaps)
531 {
532     netCaps_ = netCaps;
533 }
534 
NetDetectionForDnsHealth(bool dnsHealthSuccess)535 void Network::NetDetectionForDnsHealth(bool dnsHealthSuccess)
536 {
537     NETMGR_LOG_D("Enter NetDetectionForDnsHealthSync");
538     if (netMonitor_ == nullptr) {
539         NETMGR_LOG_E("netMonitor_ is nullptr");
540         return;
541     }
542     NetDetectionStatus lastDetectResult = detectResult_;
543     {
544         static NetDetectionStatus preStatus = UNKNOWN_STATE;
545         if (preStatus != lastDetectResult) {
546             NETMGR_LOG_I("Last netDetectionState: [%{public}d->%{public}d]", preStatus, lastDetectResult);
547             preStatus = lastDetectResult;
548         }
549     }
550     if (IsDetectionForDnsSuccess(lastDetectResult, dnsHealthSuccess)) {
551         NETMGR_LOG_I("Dns report success, so restart detection.");
552         isDetectingForDns_ = true;
553         StopNetDetection();
554         InitNetMonitor();
555     } else if (IsDetectionForDnsFail(lastDetectResult, dnsHealthSuccess)) {
556         NETMGR_LOG_I("Dns report fail, start net detection");
557         netMonitor_->Start();
558     } else {
559         NETMGR_LOG_D("Not match, no need to restart.");
560     }
561 }
562 
StopNetDetection()563 void Network::StopNetDetection()
564 {
565     NETMGR_LOG_D("Enter StopNetDetection");
566     if (netMonitor_ != nullptr) {
567         netMonitor_->Stop();
568         netMonitor_ = nullptr;
569     }
570 }
571 
InitNetMonitor()572 void Network::InitNetMonitor()
573 {
574     NETMGR_LOG_D("Enter InitNetMonitor");
575     std::weak_ptr<INetMonitorCallback> monitorCallback = shared_from_this();
576     netMonitor_ = std::make_shared<NetMonitor>(netId_, netSupplierType_, netLinkInfo_, monitorCallback);
577     if (netMonitor_ == nullptr) {
578         NETMGR_LOG_E("new NetMonitor failed,netMonitor_ is null!");
579         return;
580     }
581     netMonitor_->Start();
582 }
583 
HandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)584 void Network::HandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
585 {
586     NETMGR_LOG_I("HNMR, [%{public}d]", netDetectionState);
587     isDetectingForDns_ = false;
588     NotifyNetDetectionResult(NetDetectionResultConvert(static_cast<int32_t>(netDetectionState)), urlRedirect);
589     if (netCallback_ && (detectResult_ != netDetectionState)) {
590         detectResult_ = netDetectionState;
591         netCallback_(supplierId_, netDetectionState);
592     }
593 }
594 
NotifyNetDetectionResult(NetDetectionResultCode detectionResult,const std::string & urlRedirect)595 void Network::NotifyNetDetectionResult(NetDetectionResultCode detectionResult, const std::string &urlRedirect)
596 {
597     for (const auto &callback : netDetectionRetCallback_) {
598         NETMGR_LOG_D("start callback!");
599         if (callback) {
600             callback->OnNetDetectionResultChanged(detectionResult, urlRedirect);
601         }
602     }
603 }
604 
NetDetectionResultConvert(int32_t internalRet)605 NetDetectionResultCode Network::NetDetectionResultConvert(int32_t internalRet)
606 {
607     switch (internalRet) {
608         case static_cast<int32_t>(INVALID_DETECTION_STATE):
609             return NET_DETECTION_FAIL;
610         case static_cast<int32_t>(VERIFICATION_STATE):
611             return NET_DETECTION_SUCCESS;
612         case static_cast<int32_t>(CAPTIVE_PORTAL_STATE):
613             return NET_DETECTION_CAPTIVE_PORTAL;
614         default:
615             break;
616     }
617     return NET_DETECTION_FAIL;
618 }
619 
SetDefaultNetWork()620 void Network::SetDefaultNetWork()
621 {
622     int32_t ret = NetsysController::GetInstance().SetDefaultNetWork(netId_);
623     if (ret != NETMANAGER_SUCCESS) {
624         SendSupplierFaultHiSysEvent(FAULT_SET_DEFAULT_NETWORK_FAILED, ERROR_MSG_SET_DEFAULT_NETWORK_FAILED);
625     }
626 }
627 
ClearDefaultNetWorkNetId()628 void Network::ClearDefaultNetWorkNetId()
629 {
630     int32_t ret = NetsysController::GetInstance().ClearDefaultNetWorkNetId();
631     if (ret != NETMANAGER_SUCCESS) {
632         SendSupplierFaultHiSysEvent(FAULT_CLEAR_DEFAULT_NETWORK_FAILED, ERROR_MSG_CLEAR_DEFAULT_NETWORK_FAILED);
633     }
634 }
635 
IsConnecting() const636 bool Network::IsConnecting() const
637 {
638     return state_ == NET_CONN_STATE_CONNECTING;
639 }
640 
IsConnected() const641 bool Network::IsConnected() const
642 {
643     return state_ == NET_CONN_STATE_CONNECTED;
644 }
645 
UpdateNetConnState(NetConnState netConnState)646 void Network::UpdateNetConnState(NetConnState netConnState)
647 {
648     if (state_ == netConnState) {
649         NETMGR_LOG_D("Ignore same network state changed.");
650         return;
651     }
652     NetConnState oldState = state_;
653     switch (netConnState) {
654         case NET_CONN_STATE_IDLE:
655         case NET_CONN_STATE_CONNECTING:
656         case NET_CONN_STATE_CONNECTED:
657         case NET_CONN_STATE_DISCONNECTING:
658             state_ = netConnState;
659             break;
660         case NET_CONN_STATE_DISCONNECTED:
661             state_ = netConnState;
662             ResetNetlinkInfo();
663             break;
664         default:
665             state_ = NET_CONN_STATE_UNKNOWN;
666             break;
667     }
668 
669     SendConnectionChangedBroadcast(netConnState);
670     if (IsNat464Prefered()) {
671         if (nat464Service_ == nullptr) {
672             nat464Service_ = std::make_unique<Nat464Service>(netId_, netLinkInfo_.ifaceName_);
673         }
674         nat464Service_->MaybeUpdateV6Iface(netLinkInfo_.ifaceName_);
675         nat464Service_->UpdateService(NAT464_SERVICE_CONTINUE);
676     } else if (nat464Service_ != nullptr) {
677         nat464Service_->UpdateService(NAT464_SERVICE_STOP);
678     }
679     NETMGR_LOG_I("Network[%{public}d] state changed, from [%{public}d] to [%{public}d]", netId_, oldState, state_);
680 }
681 
SendConnectionChangedBroadcast(const NetConnState & netConnState) const682 void Network::SendConnectionChangedBroadcast(const NetConnState &netConnState) const
683 {
684     BroadcastInfo info;
685     info.action = EventFwk::CommonEventSupport::COMMON_EVENT_CONNECTIVITY_CHANGE;
686     info.data = "Net Manager Connection State Changed";
687     info.code = static_cast<int32_t>(netConnState);
688     info.ordered = false;
689     std::map<std::string, int32_t> param = {{"NetType", static_cast<int32_t>(netSupplierType_)}};
690     BroadcastManager::GetInstance().SendBroadcast(info, param);
691 }
692 
SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType,const std::string & errMsg)693 void Network::SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType, const std::string &errMsg)
694 {
695     struct EventInfo eventInfo = {.netlinkInfo = netLinkInfo_.ToString(" "),
696                                   .supplierId = static_cast<int32_t>(supplierId_),
697                                   .errorType = static_cast<int32_t>(errorType),
698                                   .errorMsg = errMsg};
699     EventReport::SendSupplierFaultEvent(eventInfo);
700 }
701 
ResetNetlinkInfo()702 void Network::ResetNetlinkInfo()
703 {
704     netLinkInfo_.Initialize();
705     detectResult_ = UNKNOWN_STATE;
706 }
707 
UpdateGlobalHttpProxy(const HttpProxy & httpProxy)708 void Network::UpdateGlobalHttpProxy(const HttpProxy &httpProxy)
709 {
710     if (netMonitor_ == nullptr) {
711         NETMGR_LOG_E("netMonitor_ is nullptr");
712         return;
713     }
714     netMonitor_->UpdateGlobalHttpProxy(httpProxy);
715 }
716 
OnHandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)717 void Network::OnHandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
718 {
719     if (eventHandler_) {
720         auto network = shared_from_this();
721         eventHandler_->PostAsyncTask([netDetectionState, urlRedirect,
722                                       network]() { network->HandleNetMonitorResult(netDetectionState, urlRedirect); },
723                                      0);
724     }
725 }
726 
ResumeNetworkInfo()727 bool Network::ResumeNetworkInfo()
728 {
729     NetLinkInfo nli = netLinkInfo_;
730 
731     NETMGR_LOG_D("ResumeNetworkInfo UpdateBasicNetwork false");
732     if (!UpdateBasicNetwork(false)) {
733         NETMGR_LOG_E("%s release existed basic network failed", __FUNCTION__);
734         return false;
735     }
736 
737     NETMGR_LOG_D("ResumeNetworkInfo UpdateBasicNetwork true");
738     if (!UpdateBasicNetwork(true)) {
739         NETMGR_LOG_E("%s create basic network failed", __FUNCTION__);
740         return false;
741     }
742 
743     NETMGR_LOG_D("ResumeNetworkInfo UpdateNetLinkInfo");
744     return UpdateNetLinkInfo(nli);
745 }
746 
IsDetectionForDnsSuccess(NetDetectionStatus netDetectionState,bool dnsHealthSuccess)747 bool Network::IsDetectionForDnsSuccess(NetDetectionStatus netDetectionState, bool dnsHealthSuccess)
748 {
749     return ((netDetectionState == INVALID_DETECTION_STATE) && dnsHealthSuccess && !isDetectingForDns_);
750 }
751 
IsDetectionForDnsFail(NetDetectionStatus netDetectionState,bool dnsHealthSuccess)752 bool Network::IsDetectionForDnsFail(NetDetectionStatus netDetectionState, bool dnsHealthSuccess)
753 {
754     return ((netDetectionState == VERIFICATION_STATE) && !dnsHealthSuccess && !(netMonitor_->IsDetecting()));
755 }
756 
IsNat464Prefered()757 bool Network::IsNat464Prefered()
758 {
759     if (netSupplierType_ != BEARER_CELLULAR && netSupplierType_ != BEARER_WIFI && netSupplierType_ != BEARER_ETHERNET) {
760         return false;
761     }
762     if (std::any_of(netLinkInfo_.netAddrList_.begin(), netLinkInfo_.netAddrList_.end(),
763                     [](const INetAddr &i) { return i.type_ != INetAddr::IPV6; })) {
764         return false;
765     }
766     if (netLinkInfo_.ifaceName_.empty() || !IsConnected()) {
767         return false;
768     }
769     return true;
770 }
771 } // namespace NetManagerStandard
772 } // namespace OHOS
773