• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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         std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
123         bool hasDns = netLinkInfo_.dnsList_.size() ? true : false;
124         if (NetsysController::GetInstance().NetworkCreateVirtual(netId_, hasDns) != NETMANAGER_SUCCESS) {
125             std::string errMsg = std::string(ERROR_MSG_CREATE_VIRTUAL_NETWORK_FAILED).append(std::to_string(netId_));
126             SendSupplierFaultHiSysEvent(FAULT_CREATE_VIRTUAL_NETWORK_FAILED, errMsg);
127         }
128         NetsysController::GetInstance().CreateNetworkCache(netId_, true);
129         isVirtualCreated_ = true;
130     }
131     return true;
132 }
133 
IsIfaceNameInUse()134 bool Network::IsIfaceNameInUse()
135 {
136     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
137     return NetConnServiceIface().IsIfaceNameInUse(netLinkInfo_.ifaceName_, netId_);
138 }
139 
GetNetCapabilitiesAsString(const uint32_t supplierId) const140 std::string Network::GetNetCapabilitiesAsString(const uint32_t supplierId) const
141 {
142     return NetConnServiceIface().GetNetCapabilitiesAsString(supplierId);
143 }
144 
ReleaseBasicNetwork()145 bool Network::ReleaseBasicNetwork()
146 {
147     if (!isPhyNetCreated_) {
148         NETMGR_LOG_E("physical network has not created");
149         return true;
150     }
151     NETMGR_LOG_D("Destroy physical network");
152     StopNetDetection();
153     std::string netCapabilities = GetNetCapabilitiesAsString(supplierId_);
154     NETMGR_LOG_D("ReleaseBasicNetwork supplierId %{public}u, netId %{public}d, netCapabilities %{public}s",
155         supplierId_, netId_, netCapabilities.c_str());
156     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
157     NetLinkInfo netLinkInfoBck = netLinkInfo_;
158     lock.unlock();
159     if (!IsIfaceNameInUse() || isNeedResume_) {
160         for (const auto &inetAddr : netLinkInfoBck.netAddrList_) {
161             int32_t prefixLen = inetAddr.prefixlen_ == 0 ? Ipv4PrefixLen(inetAddr.netMask_) : inetAddr.prefixlen_;
162             NetsysController::GetInstance().DelInterfaceAddress(netLinkInfoBck.ifaceName_, inetAddr.address_,
163                                                                 prefixLen);
164         }
165         for (const auto &route : netLinkInfoBck.routeList_) {
166             if (route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP &&
167                 route.destination_.address_ != LOCAL_ROUTE_IPV6_DESTINATION) {
168                 auto family = GetAddrFamily(route.destination_.address_);
169                 std::string nextHop = (family == AF_INET6) ? "" : LOCAL_ROUTE_NEXT_HOP;
170                 auto destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
171                 NetsysController::GetInstance().NetworkRemoveRoute(LOCAL_NET_ID, route.iface_, destAddress, nextHop);
172             }
173         }
174         isNeedResume_ = false;
175     } else {
176         for (const auto &inetAddr : netLinkInfoBck.netAddrList_) {
177             int32_t prefixLen = inetAddr.prefixlen_ == 0 ? Ipv4PrefixLen(inetAddr.netMask_) : inetAddr.prefixlen_;
178             NetsysController::GetInstance().DelInterfaceAddress(netLinkInfoBck.ifaceName_, inetAddr.address_,
179                                                                 prefixLen, netCapabilities);
180         }
181     }
182     for (const auto &route : netLinkInfoBck.routeList_) {
183         auto destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
184         NetsysController::GetInstance().NetworkRemoveRoute(netId_, route.iface_, destAddress,
185                                                            route.gateway_.address_);
186     }
187     NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfoBck.ifaceName_);
188     NetsysController::GetInstance().NetworkDestroy(netId_);
189     NetsysController::GetInstance().DestroyNetworkCache(netId_);
190     std::unique_lock<std::shared_mutex> wlock(netLinkInfoMutex_);
191     netLinkInfo_.Initialize();
192     isPhyNetCreated_ = false;
193     return true;
194 }
195 
ReleaseVirtualNetwork()196 bool Network::ReleaseVirtualNetwork()
197 {
198     NETMGR_LOG_D("Enter release virtual network");
199     if (isVirtualCreated_) {
200         std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
201         NetLinkInfo netLinkInfoBck = netLinkInfo_;
202         lock.unlock();
203         for (const auto &inetAddr : netLinkInfoBck.netAddrList_) {
204             int32_t prefixLen = inetAddr.prefixlen_;
205             if (prefixLen == 0) {
206                 prefixLen = Ipv4PrefixLen(inetAddr.netMask_);
207             }
208             NetsysController::GetInstance().DelInterfaceAddress(
209                 netLinkInfoBck.ifaceName_, inetAddr.address_, prefixLen);
210         }
211         NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfoBck.ifaceName_);
212         NetsysController::GetInstance().NetworkDestroy(netId_, true);
213         NetsysController::GetInstance().DestroyNetworkCache(netId_, true);
214         std::unique_lock<std::shared_mutex> wlock(netLinkInfoMutex_);
215         netLinkInfo_.Initialize();
216         isVirtualCreated_ = false;
217     }
218     return true;
219 }
220 
UpdateNetLinkInfo(const NetLinkInfo & netLinkInfo)221 bool Network::UpdateNetLinkInfo(const NetLinkInfo &netLinkInfo)
222 {
223     NETMGR_LOG_D("update net link information process");
224     UpdateStatsCached(netLinkInfo);
225     UpdateInterfaces(netLinkInfo);
226     bool isIfaceNameInUse = NetConnServiceIface().IsIfaceNameInUse(netLinkInfo.ifaceName_, netId_);
227     bool flag = false;
228     {
229         std::shared_lock<std::shared_mutex> nlock(netCapsMutex);
230         flag = netCaps_.find(NetCap::NET_CAPABILITY_INTERNET) != netCaps_.end();
231     }
232     if (!isIfaceNameInUse || flag) {
233         UpdateIpAddrs(netLinkInfo);
234     }
235     UpdateRoutes(netLinkInfo);
236     UpdateDns(netLinkInfo);
237     UpdateMtu(netLinkInfo);
238     UpdateTcpBufferSize(netLinkInfo);
239     std::unique_lock<std::shared_mutex> wlock(netLinkInfoMutex_);
240     netLinkInfo_ = netLinkInfo;
241     wlock.unlock();
242     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
243     NetLinkInfo netLinkInfoBck = netLinkInfo_;
244     lock.unlock();
245     if (IsNat464Prefered()) {
246         if (nat464Service_ == nullptr) {
247             nat464Service_ = std::make_unique<Nat464Service>(netId_, netLinkInfoBck.ifaceName_);
248         }
249         nat464Service_->MaybeUpdateV6Iface(netLinkInfoBck.ifaceName_);
250         nat464Service_->UpdateService(NAT464_SERVICE_CONTINUE);
251     } else if (nat464Service_ != nullptr) {
252         nat464Service_->UpdateService(NAT464_SERVICE_STOP);
253     }
254     bool find = false;
255     {
256         std::shared_lock<std::shared_mutex> lock(netCapsMutex);
257         if (netSupplierType_ != BEARER_VPN && netCaps_.find(NetCap::NET_CAPABILITY_INTERNET) != netCaps_.end()) {
258             find = true;
259         }
260     }
261     if (find) {
262         StartNetDetection(false);
263     }
264     return true;
265 }
266 
GetNetLinkInfo() const267 NetLinkInfo Network::GetNetLinkInfo() const
268 {
269     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
270     NetLinkInfo linkInfo = netLinkInfo_;
271     if (netSupplierType_ == BEARER_VPN) {
272         return linkInfo;
273     }
274     for (auto iter = linkInfo.routeList_.begin(); iter != linkInfo.routeList_.end();) {
275         if (iter->destination_.address_ == LOCAL_ROUTE_NEXT_HOP ||
276             iter->destination_.address_ == LOCAL_ROUTE_IPV6_DESTINATION) {
277             ++iter;
278             continue;
279         }
280         iter = linkInfo.routeList_.erase(iter);
281     }
282     return linkInfo;
283 }
284 
GetHttpProxy() const285 HttpProxy Network::GetHttpProxy() const
286 {
287     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
288     return netLinkInfo_.httpProxy_;
289 }
290 
GetIfaceName() const291 std::string Network::GetIfaceName() const
292 {
293     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
294     return netLinkInfo_.ifaceName_;
295 }
296 
GetIdent() const297 std::string Network::GetIdent() const
298 {
299     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
300     return netLinkInfo_.ident_;
301 }
302 
UpdateInterfaces(const NetLinkInfo & newNetLinkInfo)303 void Network::UpdateInterfaces(const NetLinkInfo &newNetLinkInfo)
304 {
305     NETMGR_LOG_D("Network UpdateInterfaces in.");
306     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
307     NetLinkInfo netLinkInfoBck = netLinkInfo_;
308     lock.unlock();
309     if (newNetLinkInfo.ifaceName_ == netLinkInfoBck.ifaceName_) {
310         NETMGR_LOG_D("Network UpdateInterfaces out. same with before.");
311         return;
312     }
313 
314     int32_t ret = NETMANAGER_SUCCESS;
315     // Call netsys to add and remove interface
316     if (!newNetLinkInfo.ifaceName_.empty()) {
317         ret = NetsysController::GetInstance().NetworkAddInterface(netId_, newNetLinkInfo.ifaceName_, netSupplierType_);
318         if (ret != NETMANAGER_SUCCESS) {
319             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_INTERFACE_FAILED);
320         }
321     }
322     if (!netLinkInfoBck.ifaceName_.empty()) {
323         ret = NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfoBck.ifaceName_);
324         if (ret != NETMANAGER_SUCCESS) {
325             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_INTERFACE_FAILED);
326         }
327     }
328     std::unique_lock<std::shared_mutex> wlock(netLinkInfoMutex_);
329     netLinkInfo_.ifaceName_ = newNetLinkInfo.ifaceName_;
330     NETMGR_LOG_D("Network UpdateInterfaces out.");
331 }
332 
UpdateIpAddrs(const NetLinkInfo & newNetLinkInfo)333 void Network::UpdateIpAddrs(const NetLinkInfo &newNetLinkInfo)
334 {
335     // netLinkInfo_ represents the old, netLinkInfo represents the new
336     // Update: remove old Ips first, then add the new Ips
337     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
338     NetLinkInfo netLinkInfoBck = netLinkInfo_;
339     lock.unlock();
340     NETMGR_LOG_I("UpdateIpAddrs, old ip addrs size: [%{public}zu]", netLinkInfoBck.netAddrList_.size());
341     for (const auto &inetAddr : netLinkInfoBck.netAddrList_) {
342         if (newNetLinkInfo.HasNetAddr(inetAddr)) {
343             NETMGR_LOG_W("Same ip address:[%{public}s], there is not need to be deleted",
344                 CommonUtils::ToAnonymousIp(inetAddr.address_).c_str());
345             continue;
346         }
347         auto family = GetAddrFamily(inetAddr.address_);
348         auto prefixLen = inetAddr.prefixlen_ ? static_cast<int32_t>(inetAddr.prefixlen_)
349                                              : ((family == AF_INET6) ? Ipv6PrefixLen(inetAddr.netMask_)
350                                                                      : Ipv4PrefixLen(inetAddr.netMask_));
351         int32_t ret =
352             NetsysController::GetInstance().DelInterfaceAddress(
353                 netLinkInfoBck.ifaceName_, inetAddr.address_, prefixLen);
354         if (NETMANAGER_SUCCESS != ret) {
355             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_DELETE_NET_IP_ADDR_FAILED);
356         }
357 
358         if ((ret == ERRNO_EADDRNOTAVAIL) || (ret == 0)) {
359             NETMGR_LOG_W("remove route info of ip address:[%{public}s]",
360                 CommonUtils::ToAnonymousIp(inetAddr.address_).c_str());
361             std::unique_lock<std::shared_mutex> lock(netLinkInfoMutex_);
362             netLinkInfo_.routeList_.remove_if([family](const Route &route) {
363                 INetAddr::IpType addrFamily = INetAddr::IpType::UNKNOWN;
364                 if (family == AF_INET) {
365                     addrFamily = INetAddr::IpType::IPV4;
366                 } else if (family == AF_INET6) {
367                     addrFamily = INetAddr::IpType::IPV6;
368                 }
369                 return route.destination_.type_ == addrFamily;
370             });
371         }
372     }
373 
374     HandleUpdateIpAddrs(newNetLinkInfo);
375 }
376 
HandleUpdateIpAddrs(const NetLinkInfo & newNetLinkInfo)377 void Network::HandleUpdateIpAddrs(const NetLinkInfo &newNetLinkInfo)
378 {
379     NETMGR_LOG_I("HandleUpdateIpAddrs, new ip addrs size: [%{public}zu]", newNetLinkInfo.netAddrList_.size());
380     for (const auto &inetAddr : newNetLinkInfo.netAddrList_) {
381         std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
382         if (netLinkInfo_.HasNetAddr(inetAddr)) {
383             NETMGR_LOG_W("Same ip address:[%{public}s], there is no need to add it again",
384                          CommonUtils::ToAnonymousIp(inetAddr.address_).c_str());
385             continue;
386         }
387         lock.unlock();
388         auto family = GetAddrFamily(inetAddr.address_);
389         auto prefixLen = inetAddr.prefixlen_ ? static_cast<int32_t>(inetAddr.prefixlen_)
390                                              : ((family == AF_INET6) ? Ipv6PrefixLen(inetAddr.netMask_)
391                                                                      : Ipv4PrefixLen(inetAddr.netMask_));
392         if (NETMANAGER_SUCCESS != NetsysController::GetInstance().AddInterfaceAddress(newNetLinkInfo.ifaceName_,
393                                                                                       inetAddr.address_, prefixLen)) {
394             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_IP_ADDR_FAILED);
395         }
396     }
397 }
398 
UpdateRoutes(const NetLinkInfo & newNetLinkInfo)399 void Network::UpdateRoutes(const NetLinkInfo &newNetLinkInfo)
400 {
401     // netLinkInfo_ contains the old routes info, netLinkInfo contains the new routes info
402     // Update: remove old routes first, then add the new routes
403     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
404     NetLinkInfo netLinkInfoBck = netLinkInfo_;
405     lock.unlock();
406     NETMGR_LOG_D("UpdateRoutes, old routes: [%{public}s]", netLinkInfoBck.ToStringRoute("").c_str());
407     for (const auto &route : netLinkInfoBck.routeList_) {
408         if (newNetLinkInfo.HasRoute(route)) {
409             NETMGR_LOG_W("Same route:[%{public}s]  ifo, there is not need to be deleted",
410                          CommonUtils::ToAnonymousIp(route.destination_.address_).c_str());
411             continue;
412         }
413         std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
414         auto ret = NetsysController::GetInstance().NetworkRemoveRoute(netId_, route.iface_, destAddress,
415                                                                       route.gateway_.address_);
416         int32_t res = NETMANAGER_SUCCESS;
417         if (netSupplierType_ != BEARER_VPN && route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP &&
418             route.destination_.address_ != LOCAL_ROUTE_IPV6_DESTINATION) {
419             auto family = GetAddrFamily(route.destination_.address_);
420             std::string nextHop = (family == AF_INET6) ? "" : LOCAL_ROUTE_NEXT_HOP;
421             res = NetsysController::GetInstance().NetworkRemoveRoute(LOCAL_NET_ID, route.iface_, destAddress, nextHop);
422         }
423         if (ret != NETMANAGER_SUCCESS || res != NETMANAGER_SUCCESS) {
424             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_ROUTES_FAILED);
425         }
426     }
427 
428     NETMGR_LOG_D("UpdateRoutes, new routes: [%{public}s]", newNetLinkInfo.ToStringRoute("").c_str());
429     for (const auto &route : newNetLinkInfo.routeList_) {
430         if (netLinkInfoBck.HasRoute(route)) {
431             NETMGR_LOG_W("Same route:[%{public}s]  ifo, there is no need to add it again",
432                          CommonUtils::ToAnonymousIp(route.destination_.address_).c_str());
433             continue;
434         }
435 
436         std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
437         auto ret =
438             NetsysController::GetInstance().NetworkAddRoute(netId_, route.iface_, destAddress, route.gateway_.address_);
439         int32_t res = NETMANAGER_SUCCESS;
440         if (netSupplierType_ != BEARER_VPN && route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP &&
441             route.destination_.address_ != LOCAL_ROUTE_IPV6_DESTINATION) {
442             auto family = GetAddrFamily(route.destination_.address_);
443             std::string nextHop = (family == AF_INET6) ? "" : LOCAL_ROUTE_NEXT_HOP;
444             res = NetsysController::GetInstance().NetworkAddRoute(LOCAL_NET_ID, route.iface_, destAddress, nextHop);
445         }
446         if (ret != NETMANAGER_SUCCESS || res != NETMANAGER_SUCCESS) {
447             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_ROUTES_FAILED);
448         }
449     }
450     if (newNetLinkInfo.routeList_.empty()) {
451         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_ROUTES_FAILED);
452     }
453 }
454 
UpdateDns(const NetLinkInfo & netLinkInfo)455 void Network::UpdateDns(const NetLinkInfo &netLinkInfo)
456 {
457     NETMGR_LOG_D("Network UpdateDns in.");
458     std::vector<std::string> servers;
459     std::vector<std::string> domains;
460     std::stringstream ss;
461     for (const auto &dns : netLinkInfo.dnsList_) {
462         servers.emplace_back(dns.address_);
463         domains.emplace_back(dns.hostName_);
464         ss << '[' << CommonUtils::ToAnonymousIp(dns.address_).c_str() << ']';
465     }
466     NETMGR_LOG_I("update dns server: %{public}s", ss.str().c_str());
467     // Call netsys to set dns, use default timeout and retry
468     int32_t ret = NetsysController::GetInstance().SetResolverConfig(netId_, 0, 0, servers, domains);
469     if (ret != NETMANAGER_SUCCESS) {
470         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_RESOLVER_FAILED);
471     }
472     NETMGR_LOG_I("SetUserDefinedServerFlag: netId:[%{public}d], flag:[%{public}d]", netId_,
473         netLinkInfo.isUserDefinedDnsServer_);
474     ret = NetsysController::GetInstance().SetUserDefinedServerFlag(netId_, netLinkInfo.isUserDefinedDnsServer_);
475     if (ret != NETMANAGER_SUCCESS) {
476         NETMGR_LOG_E("SetUserDefinedServerFlag failed");
477     }
478     NETMGR_LOG_D("Network UpdateDns out.");
479     if (netLinkInfo.dnsList_.empty()) {
480         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_DNSES_FAILED);
481     }
482 }
483 
UpdateMtu(const NetLinkInfo & netLinkInfo)484 void Network::UpdateMtu(const NetLinkInfo &netLinkInfo)
485 {
486     NETMGR_LOG_D("Network UpdateMtu in.");
487     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
488     if (netLinkInfo.mtu_ == netLinkInfo_.mtu_) {
489         NETMGR_LOG_D("Network UpdateMtu out. same with before.");
490         return;
491     }
492     lock.unlock();
493 
494     int32_t ret = NetsysController::GetInstance().SetInterfaceMtu(netLinkInfo.ifaceName_, netLinkInfo.mtu_);
495     if (ret != NETMANAGER_SUCCESS) {
496         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_MTU_FAILED);
497     }
498     NETMGR_LOG_D("Network UpdateMtu out.");
499 }
500 
UpdateTcpBufferSize(const NetLinkInfo & netLinkInfo)501 void Network::UpdateTcpBufferSize(const NetLinkInfo &netLinkInfo)
502 {
503     NETMGR_LOG_D("Network UpdateTcpBufferSize in.");
504     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
505     if (netLinkInfo.tcpBufferSizes_ == netLinkInfo_.tcpBufferSizes_) {
506         NETMGR_LOG_D("Network UpdateTcpBufferSize out. same with before.");
507         return;
508     }
509     lock.unlock();
510     int32_t ret = NetsysController::GetInstance().SetTcpBufferSizes(netLinkInfo.tcpBufferSizes_);
511     if (ret != NETMANAGER_SUCCESS) {
512         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_TCP_BUFFER_SIZE_FAILED);
513     }
514     NETMGR_LOG_D("Network UpdateTcpBufferSize out.");
515 }
516 
UpdateStatsCached(const NetLinkInfo & netLinkInfo)517 void Network::UpdateStatsCached(const NetLinkInfo &netLinkInfo)
518 {
519     NETMGR_LOG_D("Network UpdateStatsCached in.");
520     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
521     if (netLinkInfo.ifaceName_ == netLinkInfo_.ifaceName_ && netLinkInfo.ident_ == netLinkInfo_.ident_) {
522         NETMGR_LOG_D("Network UpdateStatsCached out. same with before");
523         return;
524     }
525     lock.unlock();
526     int32_t ret = NetStatsClient::GetInstance().UpdateStatsData();
527     if (ret != NETMANAGER_SUCCESS) {
528         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_STATS_CACHED);
529     }
530     NETMGR_LOG_D("Network UpdateStatsCached out.");
531 }
532 
RegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)533 void Network::RegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
534 {
535     NETMGR_LOG_I("Enter RNDCB");
536     if (callback == nullptr) {
537         NETMGR_LOG_E("The parameter callback is null");
538         return;
539     }
540 
541     for (const auto &iter : netDetectionRetCallback_) {
542         if (callback->AsObject().GetRefPtr() == iter->AsObject().GetRefPtr()) {
543             NETMGR_LOG_D("netDetectionRetCallback_ had this callback");
544             return;
545         }
546     }
547 
548     netDetectionRetCallback_.emplace_back(callback);
549 }
550 
UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)551 int32_t Network::UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
552 {
553     NETMGR_LOG_I("Enter URNDCB");
554     if (callback == nullptr) {
555         NETMGR_LOG_E("The parameter of callback is null");
556         return NETMANAGER_ERR_LOCAL_PTR_NULL;
557     }
558 
559     for (auto iter = netDetectionRetCallback_.begin(); iter != netDetectionRetCallback_.end(); ++iter) {
560         if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
561             netDetectionRetCallback_.erase(iter);
562             return NETMANAGER_SUCCESS;
563         }
564     }
565 
566     return NETMANAGER_SUCCESS;
567 }
568 
StartNetDetection(bool needReport)569 void Network::StartNetDetection(bool needReport)
570 {
571     NETMGR_LOG_I("Enter StartNetDetection");
572 #ifdef FEATURE_SUPPORT_POWERMANAGER
573     if (forbidDetectionFlag_) {
574         NETMGR_LOG_W("Sleep status, forbid detection");
575         return;
576     }
577 #endif
578     if (needReport && netMonitor_) {
579         StopNetDetection();
580         InitNetMonitor();
581         return;
582     }
583     if (!netMonitor_) {
584         NETMGR_LOG_I("netMonitor_ is null.");
585         InitNetMonitor();
586         return;
587     } else {
588         netMonitor_->Start();
589     }
590 }
591 
592 #ifdef FEATURE_SUPPORT_POWERMANAGER
UpdateForbidDetectionFlag(bool forbidDetectionFlag)593 void Network::UpdateForbidDetectionFlag(bool forbidDetectionFlag)
594 {
595     forbidDetectionFlag_ = forbidDetectionFlag;
596 }
597 #endif
598 
SetNetCaps(const std::set<NetCap> & netCaps)599 void Network::SetNetCaps(const std::set<NetCap> &netCaps)
600 {
601     std::unique_lock<std::shared_mutex> lock(netCapsMutex);
602     netCaps_ = netCaps;
603 }
604 
NetDetectionForDnsHealth(bool dnsHealthSuccess)605 void Network::NetDetectionForDnsHealth(bool dnsHealthSuccess)
606 {
607     NETMGR_LOG_D("Enter NetDetectionForDnsHealthSync");
608     if (netMonitor_ == nullptr) {
609         NETMGR_LOG_D("netMonitor_ is nullptr");
610         return;
611     }
612     NetDetectionStatus lastDetectResult = detectResult_;
613     {
614         static NetDetectionStatus preStatus = UNKNOWN_STATE;
615         if (preStatus != lastDetectResult) {
616             NETMGR_LOG_I("Last netDetectionState: [%{public}d->%{public}d]", preStatus, lastDetectResult);
617             preStatus = lastDetectResult;
618         }
619     }
620     if (IsDetectionForDnsSuccess(lastDetectResult, dnsHealthSuccess)) {
621         NETMGR_LOG_I("Dns report success, so restart detection.");
622         isDetectingForDns_ = true;
623         netMonitor_->Start();
624     } else if (IsDetectionForDnsFail(lastDetectResult, dnsHealthSuccess)) {
625         NETMGR_LOG_I("Dns report fail, start net detection");
626         netMonitor_->Start();
627     } else {
628         NETMGR_LOG_D("Not match, no need to restart.");
629     }
630 }
631 
StopNetDetection()632 void Network::StopNetDetection()
633 {
634     NETMGR_LOG_D("Enter StopNetDetection");
635     if (netMonitor_ != nullptr) {
636         netMonitor_->Stop();
637         netMonitor_ = nullptr;
638     }
639 }
640 
InitNetMonitor()641 void Network::InitNetMonitor()
642 {
643     NETMGR_LOG_D("Enter InitNetMonitor");
644     std::weak_ptr<INetMonitorCallback> monitorCallback = shared_from_this();
645     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
646     netMonitor_ = std::make_shared<NetMonitor>(netId_, netSupplierType_, netLinkInfo_, monitorCallback, isScreenOn_);
647     if (netMonitor_ == nullptr) {
648         NETMGR_LOG_E("new NetMonitor failed,netMonitor_ is null!");
649         return;
650     }
651     netMonitor_->Start();
652 }
653 
HandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)654 void Network::HandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
655 {
656     NETMGR_LOG_I("HNMR, [%{public}d]", netDetectionState);
657     isDetectingForDns_ = false;
658     NotifyNetDetectionResult(NetDetectionResultConvert(static_cast<int32_t>(netDetectionState)), urlRedirect);
659     if (netCallback_ && (detectResult_ != netDetectionState)) {
660         detectResult_ = netDetectionState;
661         netCallback_(supplierId_, netDetectionState);
662     }
663 }
664 
NotifyNetDetectionResult(NetDetectionResultCode detectionResult,const std::string & urlRedirect)665 void Network::NotifyNetDetectionResult(NetDetectionResultCode detectionResult, const std::string &urlRedirect)
666 {
667     for (const auto &callback : netDetectionRetCallback_) {
668         NETMGR_LOG_D("start callback!");
669         if (callback) {
670             callback->OnNetDetectionResultChanged(detectionResult, urlRedirect);
671         }
672     }
673 }
674 
NetDetectionResultConvert(int32_t internalRet)675 NetDetectionResultCode Network::NetDetectionResultConvert(int32_t internalRet)
676 {
677     switch (internalRet) {
678         case static_cast<int32_t>(INVALID_DETECTION_STATE):
679             return NET_DETECTION_FAIL;
680         case static_cast<int32_t>(VERIFICATION_STATE):
681             return NET_DETECTION_SUCCESS;
682         case static_cast<int32_t>(CAPTIVE_PORTAL_STATE):
683             return NET_DETECTION_CAPTIVE_PORTAL;
684         default:
685             break;
686     }
687     return NET_DETECTION_FAIL;
688 }
689 
SetDefaultNetWork()690 void Network::SetDefaultNetWork()
691 {
692     int32_t ret = NetsysController::GetInstance().SetDefaultNetWork(netId_);
693     if (ret != NETMANAGER_SUCCESS) {
694         SendSupplierFaultHiSysEvent(FAULT_SET_DEFAULT_NETWORK_FAILED, ERROR_MSG_SET_DEFAULT_NETWORK_FAILED);
695     }
696 }
697 
ClearDefaultNetWorkNetId()698 void Network::ClearDefaultNetWorkNetId()
699 {
700     int32_t ret = NetsysController::GetInstance().ClearDefaultNetWorkNetId();
701     if (ret != NETMANAGER_SUCCESS) {
702         SendSupplierFaultHiSysEvent(FAULT_CLEAR_DEFAULT_NETWORK_FAILED, ERROR_MSG_CLEAR_DEFAULT_NETWORK_FAILED);
703     }
704 }
705 
IsConnecting() const706 bool Network::IsConnecting() const
707 {
708     return state_ == NET_CONN_STATE_CONNECTING;
709 }
710 
IsConnected() const711 bool Network::IsConnected() const
712 {
713     return state_ == NET_CONN_STATE_CONNECTED;
714 }
715 
UpdateNetConnState(NetConnState netConnState)716 void Network::UpdateNetConnState(NetConnState netConnState)
717 {
718     if (state_ == netConnState) {
719         NETMGR_LOG_D("Ignore same network state changed.");
720         return;
721     }
722     NetConnState oldState = state_;
723     switch (netConnState) {
724         case NET_CONN_STATE_IDLE:
725         case NET_CONN_STATE_CONNECTING:
726         case NET_CONN_STATE_CONNECTED:
727         case NET_CONN_STATE_DISCONNECTING:
728             state_ = netConnState;
729             break;
730         case NET_CONN_STATE_DISCONNECTED:
731             state_ = netConnState;
732             ResetNetlinkInfo();
733             break;
734         default:
735             state_ = NET_CONN_STATE_UNKNOWN;
736             break;
737     }
738 
739     SendConnectionChangedBroadcast(netConnState);
740     if (IsNat464Prefered()) {
741         std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
742         NetLinkInfo netLinkInfoBck = netLinkInfo_;
743         lock.unlock();
744         if (nat464Service_ == nullptr) {
745             nat464Service_ = std::make_unique<Nat464Service>(netId_, netLinkInfoBck.ifaceName_);
746         }
747         nat464Service_->MaybeUpdateV6Iface(netLinkInfoBck.ifaceName_);
748         nat464Service_->UpdateService(NAT464_SERVICE_CONTINUE);
749     } else if (nat464Service_ != nullptr) {
750         nat464Service_->UpdateService(NAT464_SERVICE_STOP);
751     }
752     NETMGR_LOG_I("Network[%{public}d] state changed, from [%{public}d] to [%{public}d]", netId_, oldState, state_);
753 }
754 
SendConnectionChangedBroadcast(const NetConnState & netConnState) const755 void Network::SendConnectionChangedBroadcast(const NetConnState &netConnState) const
756 {
757     BroadcastInfo info;
758     info.action = EventFwk::CommonEventSupport::COMMON_EVENT_CONNECTIVITY_CHANGE;
759     info.data = "Net Manager Connection State Changed";
760     info.code = static_cast<int32_t>(netConnState);
761     info.ordered = false;
762     std::map<std::string, int32_t> param = {{"NetType", static_cast<int32_t>(netSupplierType_)}};
763     BroadcastManager::GetInstance().SendBroadcast(info, param);
764 }
765 
SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType,const std::string & errMsg)766 void Network::SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType, const std::string &errMsg)
767 {
768     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
769     struct EventInfo eventInfo = {.netlinkInfo = netLinkInfo_.ToString(" "),
770                                   .supplierId = static_cast<int32_t>(supplierId_),
771                                   .errorType = static_cast<int32_t>(errorType),
772                                   .errorMsg = errMsg};
773     EventReport::SendSupplierFaultEvent(eventInfo);
774 }
775 
ResetNetlinkInfo()776 void Network::ResetNetlinkInfo()
777 {
778     std::unique_lock<std::shared_mutex> lock(netLinkInfoMutex_);
779     netLinkInfo_.Initialize();
780     detectResult_ = UNKNOWN_STATE;
781 }
782 
UpdateGlobalHttpProxy(const HttpProxy & httpProxy)783 void Network::UpdateGlobalHttpProxy(const HttpProxy &httpProxy)
784 {
785     if (netMonitor_ == nullptr) {
786         NETMGR_LOG_D("netMonitor_ is nullptr");
787         return;
788     }
789     netMonitor_->UpdateGlobalHttpProxy(httpProxy);
790     StartNetDetection(true);
791 }
792 
OnHandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)793 void Network::OnHandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
794 {
795     if (eventHandler_) {
796         auto network = shared_from_this();
797         eventHandler_->PostAsyncTask([netDetectionState, urlRedirect,
798                                       network]() { network->HandleNetMonitorResult(netDetectionState, urlRedirect); },
799                                      0);
800     }
801 }
802 
ResumeNetworkInfo()803 bool Network::ResumeNetworkInfo()
804 {
805     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
806     NetLinkInfo nli = netLinkInfo_;
807     lock.unlock();
808     {
809         std::shared_lock<std::shared_mutex> lock(netCapsMutex);
810         if (netCaps_.find(NetCap::NET_CAPABILITY_INTERNET) != netCaps_.end()) {
811             isNeedResume_ = true;
812         }
813     }
814     NETMGR_LOG_D("ResumeNetworkInfo UpdateBasicNetwork false");
815     if (!UpdateBasicNetwork(false)) {
816         NETMGR_LOG_E("%s release existed basic network failed", __FUNCTION__);
817         return false;
818     }
819 
820     NETMGR_LOG_D("ResumeNetworkInfo UpdateBasicNetwork true");
821     if (!UpdateBasicNetwork(true)) {
822         NETMGR_LOG_E("%s create basic network failed", __FUNCTION__);
823         return false;
824     }
825 
826     NETMGR_LOG_D("ResumeNetworkInfo UpdateNetLinkInfo");
827     return UpdateNetLinkInfo(nli);
828 }
829 
IsDetectionForDnsSuccess(NetDetectionStatus netDetectionState,bool dnsHealthSuccess)830 bool Network::IsDetectionForDnsSuccess(NetDetectionStatus netDetectionState, bool dnsHealthSuccess)
831 {
832     return ((netDetectionState == INVALID_DETECTION_STATE) && dnsHealthSuccess && !isDetectingForDns_);
833 }
834 
IsDetectionForDnsFail(NetDetectionStatus netDetectionState,bool dnsHealthSuccess)835 bool Network::IsDetectionForDnsFail(NetDetectionStatus netDetectionState, bool dnsHealthSuccess)
836 {
837     return ((netDetectionState == VERIFICATION_STATE) && !dnsHealthSuccess && !(netMonitor_->IsDetecting()));
838 }
839 
IsNat464Prefered()840 bool Network::IsNat464Prefered()
841 {
842     if (netSupplierType_ != BEARER_CELLULAR && netSupplierType_ != BEARER_WIFI && netSupplierType_ != BEARER_ETHERNET) {
843         return false;
844     }
845     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
846     NetLinkInfo netLinkInfoBck = netLinkInfo_;
847     lock.unlock();
848     if (std::any_of(netLinkInfoBck.netAddrList_.begin(), netLinkInfoBck.netAddrList_.end(),
849                     [](const INetAddr &i) { return i.type_ != INetAddr::IPV6; })) {
850         return false;
851     }
852     if (netLinkInfoBck.ifaceName_.empty() || !IsConnected()) {
853         return false;
854     }
855     return true;
856 }
857 
858 
CloseSocketsUid(uint32_t uid)859 void Network::CloseSocketsUid(uint32_t uid)
860 {
861     std::shared_lock<std::shared_mutex> lock(netLinkInfoMutex_);
862     for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
863         NetsysController::GetInstance().CloseSocketsUid(inetAddr.address_, uid);
864     }
865 }
866 
SetScreenState(bool isScreenOn)867 void Network::SetScreenState(bool isScreenOn)
868 {
869     isScreenOn_ = isScreenOn;
870     if (netMonitor_ == nullptr) {
871         NETMGR_LOG_E("netMonitor_ null");
872         return;
873     }
874     netMonitor_->SetScreenState(isScreenOn);
875 }
876 
877 } // namespace NetManagerStandard
878 } // namespace OHOS
879