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