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