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, there is not need to be deleted");
305 continue;
306 }
307 auto family = GetAddrFamily(inetAddr.address_);
308 auto prefixLen = inetAddr.prefixlen_ ? static_cast<int32_t>(inetAddr.prefixlen_)
309 : ((family == AF_INET6) ? Ipv6PrefixLen(inetAddr.netMask_)
310 : Ipv4PrefixLen(inetAddr.netMask_));
311 int32_t ret =
312 NetsysController::GetInstance().DelInterfaceAddress(netLinkInfo_.ifaceName_, inetAddr.address_, prefixLen);
313 if (NETMANAGER_SUCCESS != ret) {
314 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_DELETE_NET_IP_ADDR_FAILED);
315 }
316
317 if ((ret == ERRNO_EADDRNOTAVAIL) || (ret == 0)) {
318 NETMGR_LOG_W("remove route info of ip address");
319 netLinkInfo_.routeList_.remove_if([family](const Route &route) {
320 INetAddr::IpType addrFamily = INetAddr::IpType::UNKNOWN;
321 if (family == AF_INET) {
322 addrFamily = INetAddr::IpType::IPV4;
323 } else if (family == AF_INET6) {
324 addrFamily = INetAddr::IpType::IPV6;
325 }
326 return route.destination_.type_ == addrFamily;
327 });
328 }
329 }
330
331 HandleUpdateIpAddrs(newNetLinkInfo);
332 }
333
HandleUpdateIpAddrs(const NetLinkInfo & newNetLinkInfo)334 void Network::HandleUpdateIpAddrs(const NetLinkInfo &newNetLinkInfo)
335 {
336 NETMGR_LOG_I("HandleUpdateIpAddrs, new ip addrs size: [%{public}zu]", newNetLinkInfo.netAddrList_.size());
337 for (const auto &inetAddr : newNetLinkInfo.netAddrList_) {
338 if (IsAddrInOtherNetwork(inetAddr)) {
339 continue;
340 }
341 if (netLinkInfo_.HasNetAddr(inetAddr)) {
342 NETMGR_LOG_W("Same ip address:[%{public}s], there is no need to add it again",
343 CommonUtils::ToAnonymousIp(inetAddr.address_).c_str());
344 continue;
345 }
346 auto family = GetAddrFamily(inetAddr.address_);
347 auto prefixLen = inetAddr.prefixlen_ ? static_cast<int32_t>(inetAddr.prefixlen_)
348 : ((family == AF_INET6) ? Ipv6PrefixLen(inetAddr.netMask_)
349 : Ipv4PrefixLen(inetAddr.netMask_));
350 if (NETMANAGER_SUCCESS != NetsysController::GetInstance().AddInterfaceAddress(newNetLinkInfo.ifaceName_,
351 inetAddr.address_, prefixLen)) {
352 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_IP_ADDR_FAILED);
353 }
354 }
355 }
356
UpdateRoutes(const NetLinkInfo & newNetLinkInfo)357 void Network::UpdateRoutes(const NetLinkInfo &newNetLinkInfo)
358 {
359 // netLinkInfo_ contains the old routes info, netLinkInfo contains the new routes info
360 // Update: remove old routes first, then add the new routes
361 NETMGR_LOG_D("UpdateRoutes, old routes: [%{public}s]", netLinkInfo_.ToStringRoute("").c_str());
362 for (const auto &route : netLinkInfo_.routeList_) {
363 if (newNetLinkInfo.HasRoute(route)) {
364 NETMGR_LOG_W("Same route:[%{public}s] ifo, there is not need to be deleted",
365 CommonUtils::ToAnonymousIp(route.destination_.address_).c_str());
366 continue;
367 }
368 std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
369 auto ret = NetsysController::GetInstance().NetworkRemoveRoute(netId_, route.iface_, destAddress,
370 route.gateway_.address_);
371 int32_t res = NETMANAGER_SUCCESS;
372 if (netSupplierType_ != BEARER_VPN && route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP &&
373 route.destination_.address_ != LOCAL_ROUTE_IPV6_DESTINATION) {
374 auto family = GetAddrFamily(route.destination_.address_);
375 std::string nextHop = (family == AF_INET6) ? "" : LOCAL_ROUTE_NEXT_HOP;
376 res = NetsysController::GetInstance().NetworkRemoveRoute(LOCAL_NET_ID, route.iface_, destAddress, nextHop);
377 }
378 if (ret != NETMANAGER_SUCCESS || res != NETMANAGER_SUCCESS) {
379 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_ROUTES_FAILED);
380 }
381 }
382
383 NETMGR_LOG_D("UpdateRoutes, new routes: [%{public}s]", newNetLinkInfo.ToStringRoute("").c_str());
384 for (const auto &route : newNetLinkInfo.routeList_) {
385 if (netLinkInfo_.HasRoute(route)) {
386 NETMGR_LOG_W("Same route:[%{public}s] ifo, there is no need to add it again",
387 CommonUtils::ToAnonymousIp(route.destination_.address_).c_str());
388 continue;
389 }
390
391 std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
392 auto ret =
393 NetsysController::GetInstance().NetworkAddRoute(netId_, route.iface_, destAddress, route.gateway_.address_);
394 int32_t res = NETMANAGER_SUCCESS;
395 if (netSupplierType_ != BEARER_VPN && route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP &&
396 route.destination_.address_ != LOCAL_ROUTE_IPV6_DESTINATION) {
397 auto family = GetAddrFamily(route.destination_.address_);
398 std::string nextHop = (family == AF_INET6) ? "" : LOCAL_ROUTE_NEXT_HOP;
399 res = NetsysController::GetInstance().NetworkAddRoute(LOCAL_NET_ID, route.iface_, destAddress, nextHop);
400 }
401 if (ret != NETMANAGER_SUCCESS || res != NETMANAGER_SUCCESS) {
402 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_ROUTES_FAILED);
403 }
404 }
405 NETMGR_LOG_D("Network UpdateRoutes out.");
406 if (newNetLinkInfo.routeList_.empty()) {
407 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_ROUTES_FAILED);
408 }
409 }
410
UpdateDns(const NetLinkInfo & netLinkInfo)411 void Network::UpdateDns(const NetLinkInfo &netLinkInfo)
412 {
413 NETMGR_LOG_D("Network UpdateDns in.");
414 std::vector<std::string> servers;
415 std::vector<std::string> domains;
416 std::stringstream ss;
417 for (const auto &dns : netLinkInfo.dnsList_) {
418 servers.emplace_back(dns.address_);
419 domains.emplace_back(dns.hostName_);
420 ss << '[' << CommonUtils::ToAnonymousIp(dns.address_).c_str() << ']';
421 }
422 NETMGR_LOG_I("update dns server: %{public}s", ss.str().c_str());
423 // Call netsys to set dns, use default timeout and retry
424 int32_t ret = NetsysController::GetInstance().SetResolverConfig(netId_, 0, 0, servers, domains);
425 if (ret != NETMANAGER_SUCCESS) {
426 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_RESOLVER_FAILED);
427 }
428 NETMGR_LOG_D("Network UpdateDns out.");
429 if (netLinkInfo.dnsList_.empty()) {
430 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_DNSES_FAILED);
431 }
432 }
433
UpdateMtu(const NetLinkInfo & netLinkInfo)434 void Network::UpdateMtu(const NetLinkInfo &netLinkInfo)
435 {
436 NETMGR_LOG_D("Network UpdateMtu in.");
437 if (netLinkInfo.mtu_ == netLinkInfo_.mtu_) {
438 NETMGR_LOG_D("Network UpdateMtu out. same with before.");
439 return;
440 }
441
442 int32_t ret = NetsysController::GetInstance().SetInterfaceMtu(netLinkInfo.ifaceName_, netLinkInfo.mtu_);
443 if (ret != NETMANAGER_SUCCESS) {
444 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_MTU_FAILED);
445 }
446 NETMGR_LOG_D("Network UpdateMtu out.");
447 }
448
UpdateTcpBufferSize(const NetLinkInfo & netLinkInfo)449 void Network::UpdateTcpBufferSize(const NetLinkInfo &netLinkInfo)
450 {
451 NETMGR_LOG_D("Network UpdateTcpBufferSize in.");
452 if (netLinkInfo.tcpBufferSizes_ == netLinkInfo_.tcpBufferSizes_) {
453 NETMGR_LOG_D("Network UpdateTcpBufferSize out. same with before.");
454 return;
455 }
456 int32_t ret = NetsysController::GetInstance().SetTcpBufferSizes(netLinkInfo.tcpBufferSizes_);
457 if (ret != NETMANAGER_SUCCESS) {
458 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_TCP_BUFFER_SIZE_FAILED);
459 }
460 NETMGR_LOG_D("Network UpdateTcpBufferSize out.");
461 }
462
UpdateStatsCached(const NetLinkInfo & netLinkInfo)463 void Network::UpdateStatsCached(const NetLinkInfo &netLinkInfo)
464 {
465 NETMGR_LOG_D("Network UpdateStatsCached in.");
466 if (netLinkInfo.ifaceName_ == netLinkInfo_.ifaceName_ && netLinkInfo.ident_ == netLinkInfo_.ident_) {
467 NETMGR_LOG_D("Network UpdateStatsCached out. same with before");
468 return;
469 }
470 int32_t ret = NetStatsClient::GetInstance().UpdateStatsData();
471 if (ret != NETMANAGER_SUCCESS) {
472 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_STATS_CACHED);
473 }
474 NETMGR_LOG_D("Network UpdateStatsCached out.");
475 }
476
RegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)477 void Network::RegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
478 {
479 NETMGR_LOG_I("Enter RNDCB");
480 if (callback == nullptr) {
481 NETMGR_LOG_E("The parameter callback is null");
482 return;
483 }
484
485 for (const auto &iter : netDetectionRetCallback_) {
486 if (callback->AsObject().GetRefPtr() == iter->AsObject().GetRefPtr()) {
487 NETMGR_LOG_D("netDetectionRetCallback_ had this callback");
488 return;
489 }
490 }
491
492 netDetectionRetCallback_.emplace_back(callback);
493 }
494
UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)495 int32_t Network::UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
496 {
497 NETMGR_LOG_I("Enter URNDCB");
498 if (callback == nullptr) {
499 NETMGR_LOG_E("The parameter of callback is null");
500 return NETMANAGER_ERR_LOCAL_PTR_NULL;
501 }
502
503 for (auto iter = netDetectionRetCallback_.begin(); iter != netDetectionRetCallback_.end(); ++iter) {
504 if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
505 netDetectionRetCallback_.erase(iter);
506 return NETMANAGER_SUCCESS;
507 }
508 }
509
510 return NETMANAGER_SUCCESS;
511 }
512
StartNetDetection(bool needReport)513 void Network::StartNetDetection(bool needReport)
514 {
515 NETMGR_LOG_I("Enter StartNetDetection");
516 if (needReport || netMonitor_) {
517 StopNetDetection();
518 InitNetMonitor();
519 return;
520 }
521 if (!netMonitor_) {
522 NETMGR_LOG_I("netMonitor_ is null.");
523 InitNetMonitor();
524 return;
525 }
526 }
527
SetNetCaps(const std::set<NetCap> & netCaps)528 void Network::SetNetCaps(const std::set<NetCap> &netCaps)
529 {
530 netCaps_ = netCaps;
531 }
532
NetDetectionForDnsHealth(bool dnsHealthSuccess)533 void Network::NetDetectionForDnsHealth(bool dnsHealthSuccess)
534 {
535 NETMGR_LOG_D("Enter NetDetectionForDnsHealthSync");
536 if (netMonitor_ == nullptr) {
537 NETMGR_LOG_E("netMonitor_ is nullptr");
538 return;
539 }
540 NetDetectionStatus lastDetectResult = detectResult_;
541 {
542 static NetDetectionStatus preStatus = UNKNOWN_STATE;
543 if (preStatus != lastDetectResult) {
544 NETMGR_LOG_I("Last netDetectionState: [%{public}d->%{public}d]", preStatus, lastDetectResult);
545 preStatus = lastDetectResult;
546 }
547 }
548 if (IsDetectionForDnsSuccess(lastDetectResult, dnsHealthSuccess)) {
549 NETMGR_LOG_I("Dns report success, so restart detection.");
550 isDetectingForDns_ = true;
551 StopNetDetection();
552 InitNetMonitor();
553 } else if (IsDetectionForDnsFail(lastDetectResult, dnsHealthSuccess)) {
554 NETMGR_LOG_I("Dns report fail, start net detection");
555 netMonitor_->Start();
556 } else {
557 NETMGR_LOG_D("Not match, no need to restart.");
558 }
559 }
560
StopNetDetection()561 void Network::StopNetDetection()
562 {
563 NETMGR_LOG_D("Enter StopNetDetection");
564 if (netMonitor_ != nullptr) {
565 netMonitor_->Stop();
566 netMonitor_ = nullptr;
567 }
568 }
569
InitNetMonitor()570 void Network::InitNetMonitor()
571 {
572 NETMGR_LOG_D("Enter InitNetMonitor");
573 std::weak_ptr<INetMonitorCallback> monitorCallback = shared_from_this();
574 netMonitor_ = std::make_shared<NetMonitor>(netId_, netSupplierType_, netLinkInfo_, monitorCallback);
575 if (netMonitor_ == nullptr) {
576 NETMGR_LOG_E("new NetMonitor failed,netMonitor_ is null!");
577 return;
578 }
579 netMonitor_->Start();
580 }
581
HandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)582 void Network::HandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
583 {
584 NETMGR_LOG_I("HNMR, [%{public}d]", netDetectionState);
585 isDetectingForDns_ = false;
586 NotifyNetDetectionResult(NetDetectionResultConvert(static_cast<int32_t>(netDetectionState)), urlRedirect);
587 if (netCallback_ && (detectResult_ != netDetectionState)) {
588 detectResult_ = netDetectionState;
589 netCallback_(supplierId_, netDetectionState);
590 }
591 }
592
NotifyNetDetectionResult(NetDetectionResultCode detectionResult,const std::string & urlRedirect)593 void Network::NotifyNetDetectionResult(NetDetectionResultCode detectionResult, const std::string &urlRedirect)
594 {
595 for (const auto &callback : netDetectionRetCallback_) {
596 NETMGR_LOG_D("start callback!");
597 if (callback) {
598 callback->OnNetDetectionResultChanged(detectionResult, urlRedirect);
599 }
600 }
601 }
602
NetDetectionResultConvert(int32_t internalRet)603 NetDetectionResultCode Network::NetDetectionResultConvert(int32_t internalRet)
604 {
605 switch (internalRet) {
606 case static_cast<int32_t>(INVALID_DETECTION_STATE):
607 return NET_DETECTION_FAIL;
608 case static_cast<int32_t>(VERIFICATION_STATE):
609 return NET_DETECTION_SUCCESS;
610 case static_cast<int32_t>(CAPTIVE_PORTAL_STATE):
611 return NET_DETECTION_CAPTIVE_PORTAL;
612 default:
613 break;
614 }
615 return NET_DETECTION_FAIL;
616 }
617
SetDefaultNetWork()618 void Network::SetDefaultNetWork()
619 {
620 int32_t ret = NetsysController::GetInstance().SetDefaultNetWork(netId_);
621 if (ret != NETMANAGER_SUCCESS) {
622 SendSupplierFaultHiSysEvent(FAULT_SET_DEFAULT_NETWORK_FAILED, ERROR_MSG_SET_DEFAULT_NETWORK_FAILED);
623 }
624 }
625
ClearDefaultNetWorkNetId()626 void Network::ClearDefaultNetWorkNetId()
627 {
628 int32_t ret = NetsysController::GetInstance().ClearDefaultNetWorkNetId();
629 if (ret != NETMANAGER_SUCCESS) {
630 SendSupplierFaultHiSysEvent(FAULT_CLEAR_DEFAULT_NETWORK_FAILED, ERROR_MSG_CLEAR_DEFAULT_NETWORK_FAILED);
631 }
632 }
633
IsConnecting() const634 bool Network::IsConnecting() const
635 {
636 return state_ == NET_CONN_STATE_CONNECTING;
637 }
638
IsConnected() const639 bool Network::IsConnected() const
640 {
641 return state_ == NET_CONN_STATE_CONNECTED;
642 }
643
UpdateNetConnState(NetConnState netConnState)644 void Network::UpdateNetConnState(NetConnState netConnState)
645 {
646 if (state_ == netConnState) {
647 NETMGR_LOG_D("Ignore same network state changed.");
648 return;
649 }
650 NetConnState oldState = state_;
651 switch (netConnState) {
652 case NET_CONN_STATE_IDLE:
653 case NET_CONN_STATE_CONNECTING:
654 case NET_CONN_STATE_CONNECTED:
655 case NET_CONN_STATE_DISCONNECTING:
656 state_ = netConnState;
657 break;
658 case NET_CONN_STATE_DISCONNECTED:
659 state_ = netConnState;
660 ResetNetlinkInfo();
661 break;
662 default:
663 state_ = NET_CONN_STATE_UNKNOWN;
664 break;
665 }
666
667 SendConnectionChangedBroadcast(netConnState);
668 if (IsNat464Prefered()) {
669 if (nat464Service_ == nullptr) {
670 nat464Service_ = std::make_unique<Nat464Service>(netId_, netLinkInfo_.ifaceName_);
671 }
672 nat464Service_->MaybeUpdateV6Iface(netLinkInfo_.ifaceName_);
673 nat464Service_->UpdateService(NAT464_SERVICE_CONTINUE);
674 } else if (nat464Service_ != nullptr) {
675 nat464Service_->UpdateService(NAT464_SERVICE_STOP);
676 }
677 NETMGR_LOG_I("Network[%{public}d] state changed, from [%{public}d] to [%{public}d]", netId_, oldState, state_);
678 }
679
SendConnectionChangedBroadcast(const NetConnState & netConnState) const680 void Network::SendConnectionChangedBroadcast(const NetConnState &netConnState) const
681 {
682 BroadcastInfo info;
683 info.action = EventFwk::CommonEventSupport::COMMON_EVENT_CONNECTIVITY_CHANGE;
684 info.data = "Net Manager Connection State Changed";
685 info.code = static_cast<int32_t>(netConnState);
686 info.ordered = false;
687 std::map<std::string, int32_t> param = {{"NetType", static_cast<int32_t>(netSupplierType_)}};
688 BroadcastManager::GetInstance().SendBroadcast(info, param);
689 }
690
SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType,const std::string & errMsg)691 void Network::SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType, const std::string &errMsg)
692 {
693 struct EventInfo eventInfo = {.netlinkInfo = netLinkInfo_.ToString(" "),
694 .supplierId = static_cast<int32_t>(supplierId_),
695 .errorType = static_cast<int32_t>(errorType),
696 .errorMsg = errMsg};
697 EventReport::SendSupplierFaultEvent(eventInfo);
698 }
699
ResetNetlinkInfo()700 void Network::ResetNetlinkInfo()
701 {
702 netLinkInfo_.Initialize();
703 detectResult_ = UNKNOWN_STATE;
704 }
705
UpdateGlobalHttpProxy(const HttpProxy & httpProxy)706 void Network::UpdateGlobalHttpProxy(const HttpProxy &httpProxy)
707 {
708 if (netMonitor_ == nullptr) {
709 NETMGR_LOG_E("netMonitor_ is nullptr");
710 return;
711 }
712 netMonitor_->UpdateGlobalHttpProxy(httpProxy);
713 }
714
OnHandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)715 void Network::OnHandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
716 {
717 if (eventHandler_) {
718 auto network = shared_from_this();
719 eventHandler_->PostAsyncTask([netDetectionState, urlRedirect,
720 network]() { network->HandleNetMonitorResult(netDetectionState, urlRedirect); },
721 0);
722 }
723 }
724
ResumeNetworkInfo()725 bool Network::ResumeNetworkInfo()
726 {
727 NetLinkInfo nli = netLinkInfo_;
728
729 NETMGR_LOG_D("ResumeNetworkInfo UpdateBasicNetwork false");
730 if (!UpdateBasicNetwork(false)) {
731 NETMGR_LOG_E("%s release existed basic network failed", __FUNCTION__);
732 return false;
733 }
734
735 NETMGR_LOG_D("ResumeNetworkInfo UpdateBasicNetwork true");
736 if (!UpdateBasicNetwork(true)) {
737 NETMGR_LOG_E("%s create basic network failed", __FUNCTION__);
738 return false;
739 }
740
741 NETMGR_LOG_D("ResumeNetworkInfo UpdateNetLinkInfo");
742 return UpdateNetLinkInfo(nli);
743 }
744
IsDetectionForDnsSuccess(NetDetectionStatus netDetectionState,bool dnsHealthSuccess)745 bool Network::IsDetectionForDnsSuccess(NetDetectionStatus netDetectionState, bool dnsHealthSuccess)
746 {
747 return ((netDetectionState == INVALID_DETECTION_STATE) && dnsHealthSuccess && !isDetectingForDns_);
748 }
749
IsDetectionForDnsFail(NetDetectionStatus netDetectionState,bool dnsHealthSuccess)750 bool Network::IsDetectionForDnsFail(NetDetectionStatus netDetectionState, bool dnsHealthSuccess)
751 {
752 return ((netDetectionState == VERIFICATION_STATE) && !dnsHealthSuccess && !(netMonitor_->IsDetecting()));
753 }
754
IsNat464Prefered()755 bool Network::IsNat464Prefered()
756 {
757 if (netSupplierType_ != BEARER_CELLULAR && netSupplierType_ != BEARER_WIFI && netSupplierType_ != BEARER_ETHERNET) {
758 return false;
759 }
760 if (std::any_of(netLinkInfo_.netAddrList_.begin(), netLinkInfo_.netAddrList_.end(),
761 [](const INetAddr &i) { return i.type_ != INetAddr::IPV6; })) {
762 return false;
763 }
764 if (netLinkInfo_.ifaceName_.empty() || !IsConnected()) {
765 return false;
766 }
767 return true;
768 }
769 } // namespace NetManagerStandard
770 } // namespace OHOS
771