• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 "netmanager_base_common_utils.h"
21 #include "network.h"
22 #include "netsys_controller.h"
23 #include "net_manager_constants.h"
24 #include "net_mgr_log_wrapper.h"
25 #include "route_utils.h"
26 #include "securec.h"
27 
28 using namespace OHOS::NetManagerStandard::CommonUtils;
29 
30 namespace OHOS {
31 namespace NetManagerStandard {
32 namespace {
33 // hisysevent error messgae
34 constexpr const char *ERROR_MSG_CREATE_PHYSICAL_NETWORK_FAILED = "Create physical network failed, net id:";
35 constexpr const char *ERROR_MSG_ADD_NET_INTERFACE_FAILED = "Add network interface failed";
36 constexpr const char *ERROR_MSG_REMOVE_NET_INTERFACE_FAILED = "Remove network interface failed";
37 constexpr const char *ERROR_MSG_DELETE_NET_IP_ADDR_FAILED = "Delete network ip address failed";
38 constexpr const char *ERROR_MSG_ADD_NET_IP_ADDR_FAILED = "Add network ip address failed";
39 constexpr const char *ERROR_MSG_REMOVE_NET_ROUTES_FAILED = "Remove network routes failed";
40 constexpr const char *ERROR_MSG_ADD_NET_ROUTES_FAILED = "Add network routes failed";
41 constexpr const char *ERROR_MSG_UPDATE_NET_ROUTES_FAILED = "Update netlink routes failed,routes list is empty";
42 constexpr const char *ERROR_MSG_SET_NET_RESOLVER_FAILED = "Set network resolver config failed";
43 constexpr const char *ERROR_MSG_UPDATE_NET_DNSES_FAILED = "Update netlink dns failed,dns list is empty";
44 constexpr const char *ERROR_MSG_SET_NET_MTU_FAILED = "Set netlink interface mtu failed";
45 constexpr const char *ERROR_MSG_SET_DEFAULT_NETWORK_FAILED = "Set default network failed";
46 constexpr const char *ERROR_MSG_CLEAR_DEFAULT_NETWORK_FAILED = "Clear default network failed";
47 constexpr const char *LOCAL_ROUTE_NEXT_HOP = "0.0.0.0";
48 } // namespace
49 
Network(int32_t netId,uint32_t supplierId,const NetDetectionHandler & handler,NetBearType bearerType,const std::shared_ptr<NetConnEventHandler> & eventHandler)50 Network::Network(int32_t netId, uint32_t supplierId, const NetDetectionHandler &handler, NetBearType bearerType,
51                  const std::shared_ptr<NetConnEventHandler> &eventHandler)
52     : netId_(netId),
53       supplierId_(supplierId),
54       netCallback_(handler),
55       netSupplierType_(bearerType),
56       eventHandler_(eventHandler)
57 {
58 }
59 
~Network()60 Network::~Network()
61 {
62     if (!ReleaseBasicNetwork()) {
63         NETMGR_LOG_E("ReleaseBasicNetwork fail.");
64     }
65 }
66 
GetNetId() const67 int32_t Network::GetNetId() const
68 {
69     return netId_;
70 }
71 
operator ==(const Network & network) const72 bool Network::operator==(const Network &network) const
73 {
74     return netId_ == network.netId_;
75 }
76 
UpdateBasicNetwork(bool isAvailable_)77 bool Network::UpdateBasicNetwork(bool isAvailable_)
78 {
79     NETMGR_LOG_D("Enter UpdateBasicNetwork");
80     if (isAvailable_) {
81         return CreateBasicNetwork();
82     } else {
83         return ReleaseBasicNetwork();
84     }
85 }
86 
CreateBasicNetwork()87 bool Network::CreateBasicNetwork()
88 {
89     NETMGR_LOG_D("Enter CreateBasicNetwork");
90     if (!isPhyNetCreated_) {
91         NETMGR_LOG_D("Create physical network");
92         // Create a physical network
93         if (NetsysController::GetInstance().NetworkCreatePhysical(netId_, 0) != NETMANAGER_SUCCESS) {
94             std::string errMsg = std::string(ERROR_MSG_CREATE_PHYSICAL_NETWORK_FAILED).append(std::to_string(netId_));
95             SendSupplierFaultHiSysEvent(FAULT_CREATE_PHYSICAL_NETWORK_FAILED, errMsg);
96         }
97         NetsysController::GetInstance().CreateNetworkCache(netId_);
98         isPhyNetCreated_ = true;
99     }
100     return true;
101 }
102 
ReleaseBasicNetwork()103 bool Network::ReleaseBasicNetwork()
104 {
105     NETMGR_LOG_D("Enter ReleaseBasicNetwork");
106     if (isPhyNetCreated_) {
107         NETMGR_LOG_D("Destroy physical network");
108         if (eventHandler_) {
109             eventHandler_->PostAsyncTask([this]() { this->StopNetDetection(); }, 0);
110         }
111         for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
112             int32_t prefixLen = inetAddr.prefixlen_;
113             if (prefixLen == 0) {
114                 prefixLen = Ipv4PrefixLen(inetAddr.netMask_);
115             }
116             NetsysController::GetInstance().InterfaceDelAddress(netLinkInfo_.ifaceName_, inetAddr.address_, prefixLen);
117         }
118         NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfo_.ifaceName_);
119         NetsysController::GetInstance().NetworkDestroy(netId_);
120         NetsysController::GetInstance().DestroyNetworkCache(netId_);
121         netLinkInfo_.Initialize();
122         isPhyNetCreated_ = false;
123     }
124     return true;
125 }
126 
UpdateNetLinkInfo(const NetLinkInfo & netLinkInfo)127 bool Network::UpdateNetLinkInfo(const NetLinkInfo &netLinkInfo)
128 {
129     NETMGR_LOG_D("update net link information process");
130     UpdateInterfaces(netLinkInfo);
131     UpdateIpAddrs(netLinkInfo);
132     UpdateRoutes(netLinkInfo);
133     UpdateDns(netLinkInfo);
134     UpdateMtu(netLinkInfo);
135     netLinkInfo_ = netLinkInfo;
136     StartNetDetection(false);
137     return true;
138 }
139 
GetNetLinkInfo() const140 NetLinkInfo Network::GetNetLinkInfo() const
141 {
142     return netLinkInfo_;
143 }
144 
UpdateInterfaces(const NetLinkInfo & netLinkInfo)145 void Network::UpdateInterfaces(const NetLinkInfo &netLinkInfo)
146 {
147     NETMGR_LOG_D("Network UpdateInterfaces in.");
148     if (netLinkInfo.ifaceName_ == netLinkInfo_.ifaceName_) {
149         NETMGR_LOG_D("Network UpdateInterfaces out. same with before.");
150         return;
151     }
152 
153     int32_t ret = NETMANAGER_SUCCESS;
154     // Call netsys to add and remove interface
155     if (!netLinkInfo.ifaceName_.empty()) {
156         ret = NetsysController::GetInstance().NetworkAddInterface(netId_, netLinkInfo.ifaceName_);
157         if (ret != NETMANAGER_SUCCESS) {
158             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_INTERFACE_FAILED);
159         }
160     }
161     if (!netLinkInfo_.ifaceName_.empty()) {
162         ret = NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfo_.ifaceName_);
163         if (ret != NETMANAGER_SUCCESS) {
164             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_INTERFACE_FAILED);
165         }
166     }
167     netLinkInfo_.ifaceName_ = netLinkInfo.ifaceName_;
168     NETMGR_LOG_D("Network UpdateInterfaces out.");
169 }
170 
UpdateIpAddrs(const NetLinkInfo & netLinkInfo)171 void Network::UpdateIpAddrs(const NetLinkInfo &netLinkInfo)
172 {
173     // netLinkInfo_ represents the old, netLinkInfo represents the new
174     // Update: remove old Ips first, then add the new Ips
175     NETMGR_LOG_D("UpdateIpAddrs, old ip addrs: ...");
176     for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
177         int32_t prefixLen = inetAddr.prefixlen_;
178         if (prefixLen == 0) {
179             prefixLen = Ipv4PrefixLen(inetAddr.netMask_);
180         }
181         int32_t ret =
182             NetsysController::GetInstance().InterfaceDelAddress(netLinkInfo_.ifaceName_, inetAddr.address_, prefixLen);
183         if (ret != NETMANAGER_SUCCESS) {
184             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_DELETE_NET_IP_ADDR_FAILED);
185         }
186     }
187 
188     NETMGR_LOG_D("UpdateIpAddrs, new ip addrs: ...");
189     for (auto it = netLinkInfo.netAddrList_.begin(); it != netLinkInfo.netAddrList_.end(); ++it) {
190         const struct INetAddr &inetAddr = *it;
191         int32_t prefixLen = inetAddr.prefixlen_;
192         if (prefixLen == 0) {
193             prefixLen = Ipv4PrefixLen(inetAddr.netMask_);
194         }
195         int32_t ret =
196             NetsysController::GetInstance().InterfaceAddAddress(netLinkInfo.ifaceName_, inetAddr.address_, prefixLen);
197         if (ret != NETMANAGER_SUCCESS) {
198             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_IP_ADDR_FAILED);
199         }
200     }
201     NETMGR_LOG_D("Network UpdateIpAddrs out.");
202 }
203 
UpdateRoutes(const NetLinkInfo & netLinkInfo)204 void Network::UpdateRoutes(const NetLinkInfo &netLinkInfo)
205 {
206     // netLinkInfo_ contains the old routes info, netLinkInfo contains the new routes info
207     // Update: remove old routes first, then add the new routes
208     NETMGR_LOG_D("UpdateRoutes, old routes: [%{public}s]", netLinkInfo_.ToStringRoute("").c_str());
209     for (const auto &route : netLinkInfo_.routeList_) {
210         std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
211         auto ret = static_cast<uint32_t>(NetsysController::GetInstance().NetworkRemoveRoute(
212                                          netId_, route.iface_, destAddress, route.gateway_.address_));
213         if (route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP) {
214             ret |= static_cast<uint32_t>(NetsysController::GetInstance().NetworkRemoveRoute(
215                                          LOCAL_NET_ID, route.iface_, destAddress, LOCAL_ROUTE_NEXT_HOP));
216         }
217         if (ret != NETMANAGER_SUCCESS) {
218             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_ROUTES_FAILED);
219         }
220     }
221 
222     NETMGR_LOG_D("UpdateRoutes, new routes: [%{public}s]", netLinkInfo.ToStringRoute("").c_str());
223     for (const auto &route : netLinkInfo.routeList_) {
224         std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
225         int32_t ret =
226             NetsysController::GetInstance().NetworkAddRoute(netId_, route.iface_, destAddress, route.gateway_.address_);
227         int32_t result = 0;
228         if (route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP) {
229             result = NetsysController::GetInstance().NetworkAddRoute(LOCAL_NET_ID, route.iface_, destAddress,
230                                                                      LOCAL_ROUTE_NEXT_HOP);
231         }
232         if (ret != NETMANAGER_SUCCESS || result != NETMANAGER_SUCCESS) {
233             SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_ROUTES_FAILED);
234         }
235     }
236     NETMGR_LOG_D("Network UpdateRoutes out.");
237     if (netLinkInfo.routeList_.empty()) {
238         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_ROUTES_FAILED);
239     }
240 }
241 
UpdateDns(const NetLinkInfo & netLinkInfo)242 void Network::UpdateDns(const NetLinkInfo &netLinkInfo)
243 {
244     NETMGR_LOG_D("Network UpdateDns in.");
245     std::vector<std::string> servers;
246     std::vector<std::string> domains;
247     for (const auto &dns : netLinkInfo.dnsList_) {
248         servers.emplace_back(dns.address_);
249         domains.emplace_back(dns.hostName_);
250     }
251     // Call netsys to set dns, use default timeout and retry
252     int32_t ret = NetsysController::GetInstance().SetResolverConfig(netId_, 0, 0, servers, domains);
253     if (ret != NETMANAGER_SUCCESS) {
254         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_RESOLVER_FAILED);
255     }
256     NETMGR_LOG_D("Network UpdateDns out.");
257     if (netLinkInfo.dnsList_.empty()) {
258         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_DNSES_FAILED);
259     }
260 }
261 
UpdateMtu(const NetLinkInfo & netLinkInfo)262 void Network::UpdateMtu(const NetLinkInfo &netLinkInfo)
263 {
264     NETMGR_LOG_D("Network UpdateMtu in.");
265     if (netLinkInfo.mtu_ == netLinkInfo_.mtu_) {
266         NETMGR_LOG_D("Network UpdateMtu out. same with before.");
267         return;
268     }
269 
270     int32_t ret = NetsysController::GetInstance().InterfaceSetMtu(netLinkInfo.ifaceName_, netLinkInfo.mtu_);
271     if (ret != NETMANAGER_SUCCESS) {
272         SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_MTU_FAILED);
273     }
274     NETMGR_LOG_D("Network UpdateMtu out.");
275 }
276 
RegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)277 void Network::RegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
278 {
279     NETMGR_LOG_D("Enter RegisterNetDetectionCallback");
280     if (callback == nullptr) {
281         NETMGR_LOG_E("The parameter callback is null");
282         return;
283     }
284 
285     for (const auto &iter : netDetectionRetCallback_) {
286         if (callback->AsObject().GetRefPtr() == iter->AsObject().GetRefPtr()) {
287             NETMGR_LOG_D("netDetectionRetCallback_ had this callback");
288             return;
289         }
290     }
291 
292     netDetectionRetCallback_.emplace_back(callback);
293 }
294 
UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)295 int32_t Network::UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
296 {
297     NETMGR_LOG_D("Enter UnRegisterNetDetectionCallback");
298     if (callback == nullptr) {
299         NETMGR_LOG_E("The parameter of callback is null");
300         return NETMANAGER_ERR_LOCAL_PTR_NULL;
301     }
302 
303     auto iter = std::find(netDetectionRetCallback_.begin(), netDetectionRetCallback_.end(), callback);
304     if (iter != netDetectionRetCallback_.end()) {
305         netDetectionRetCallback_.erase(iter);
306     }
307 
308     return NETMANAGER_SUCCESS;
309 }
310 
StartNetDetection(bool needReport)311 void Network::StartNetDetection(bool needReport)
312 {
313     NETMGR_LOG_D("Enter Network::StartNetDetection");
314     if (eventHandler_) {
315         eventHandler_->PostAsyncTask(
316             [report = needReport, this]() {
317                 if (report) {
318                     this->StopNetDetection();
319                 }
320                 this->InitNetMonitor();
321             },
322             0);
323     }
324 }
325 
StopNetDetection()326 void Network::StopNetDetection()
327 {
328     NETMGR_LOG_D("Enter Network::StopNetDetection");
329     if (netMonitor_ != nullptr) {
330         netMonitor_->Stop();
331         netMonitor_ = nullptr;
332     }
333 }
334 
InitNetMonitor()335 void Network::InitNetMonitor()
336 {
337     if (netMonitor_ == nullptr) {
338         std::weak_ptr<INetMonitorCallback> monitorCallback = shared_from_this();
339         netMonitor_ = std::make_shared<NetMonitor>(netId_, monitorCallback);
340         if (netMonitor_ == nullptr) {
341             NETMGR_LOG_E("new NetMonitor failed,netMonitor_ is null!");
342             return;
343         }
344     }
345     netMonitor_->Start();
346 }
347 
HandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)348 void Network::HandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
349 {
350     NETMGR_LOG_D("HandleNetMonitorResult, netDetectionState[%{public}d]", netDetectionState);
351     NotifyNetDetectionResult(NetDetectionResultConvert(static_cast<int32_t>(netDetectionState)), urlRedirect);
352     if (netCallback_ && (detectResult_ != netDetectionState)) {
353         detectResult_ = netDetectionState;
354         netCallback_(supplierId_, netDetectionState == VERIFICATION_STATE);
355     }
356 }
357 
NotifyNetDetectionResult(NetDetectionResultCode detectionResult,const std::string & urlRedirect)358 void Network::NotifyNetDetectionResult(NetDetectionResultCode detectionResult, const std::string &urlRedirect)
359 {
360     for (const auto &callback : netDetectionRetCallback_) {
361         NETMGR_LOG_D("start callback!");
362         if (callback) {
363             callback->OnNetDetectionResultChanged(detectionResult, urlRedirect);
364         }
365     }
366 }
367 
NetDetectionResultConvert(int32_t internalRet)368 NetDetectionResultCode Network::NetDetectionResultConvert(int32_t internalRet)
369 {
370     switch (internalRet) {
371         case static_cast<int32_t>(INVALID_DETECTION_STATE):
372             return NET_DETECTION_FAIL;
373         case static_cast<int32_t>(VERIFICATION_STATE):
374             return NET_DETECTION_SUCCESS;
375         case static_cast<int32_t>(CAPTIVE_PORTAL_STATE):
376             return NET_DETECTION_CAPTIVE_PORTAL;
377         default:
378             break;
379     }
380     return NET_DETECTION_FAIL;
381 }
382 
SetDefaultNetWork()383 void Network::SetDefaultNetWork()
384 {
385     int32_t ret = NetsysController::GetInstance().SetDefaultNetWork(netId_);
386     if (ret != NETMANAGER_SUCCESS) {
387         SendSupplierFaultHiSysEvent(FAULT_SET_DEFAULT_NETWORK_FAILED, ERROR_MSG_SET_DEFAULT_NETWORK_FAILED);
388     }
389 }
390 
ClearDefaultNetWorkNetId()391 void Network::ClearDefaultNetWorkNetId()
392 {
393     int32_t ret = NetsysController::GetInstance().ClearDefaultNetWorkNetId();
394     if (ret != NETMANAGER_SUCCESS) {
395         SendSupplierFaultHiSysEvent(FAULT_CLEAR_DEFAULT_NETWORK_FAILED, ERROR_MSG_CLEAR_DEFAULT_NETWORK_FAILED);
396     }
397 }
398 
IsConnecting() const399 bool Network::IsConnecting() const
400 {
401     return state_ == NET_CONN_STATE_CONNECTING;
402 }
403 
IsConnected() const404 bool Network::IsConnected() const
405 {
406     return state_ == NET_CONN_STATE_CONNECTED;
407 }
408 
UpdateNetConnState(NetConnState netConnState)409 void Network::UpdateNetConnState(NetConnState netConnState)
410 {
411     if (state_ == netConnState) {
412         NETMGR_LOG_E("Ignore same network state changed.");
413         return;
414     }
415     NetConnState oldState = state_;
416     switch (netConnState) {
417         case NET_CONN_STATE_IDLE:
418         case NET_CONN_STATE_CONNECTING:
419         case NET_CONN_STATE_CONNECTED:
420         case NET_CONN_STATE_DISCONNECTING:
421             state_ = netConnState;
422             break;
423         case NET_CONN_STATE_DISCONNECTED:
424             state_ = netConnState;
425             ResetNetlinkInfo();
426             break;
427         default:
428             state_ = NET_CONN_STATE_UNKNOWN;
429             break;
430     }
431 
432     SendConnectionChangedBroadcast(netConnState);
433     NETMGR_LOG_D("Network[%{public}d] state changed, from [%{public}d] to [%{public}d]", netId_, oldState, state_);
434 }
435 
SendConnectionChangedBroadcast(const NetConnState & netConnState) const436 void Network::SendConnectionChangedBroadcast(const NetConnState &netConnState) const
437 {
438     BroadcastInfo info;
439     info.action = EventFwk::CommonEventSupport::COMMON_EVENT_CONNECTIVITY_CHANGE;
440     info.data = "Net Manager Connection State Changed";
441     info.code = static_cast<int32_t>(netConnState);
442     info.ordered = true;
443     std::map<std::string, int32_t> param = {{"NetType", static_cast<int32_t>(netSupplierType_)}};
444     DelayedSingleton<BroadcastManager>::GetInstance()->SendBroadcast(info, param);
445 }
446 
SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType,const std::string & errMsg)447 void Network::SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType, const std::string &errMsg)
448 {
449     struct EventInfo eventInfo = {.netlinkInfo = netLinkInfo_.ToString(" "),
450                                   .supplierId = static_cast<int32_t>(supplierId_),
451                                   .errorType = static_cast<int32_t>(errorType),
452                                   .errorMsg = errMsg};
453     EventReport::SendSupplierFaultEvent(eventInfo);
454 }
455 
ResetNetlinkInfo()456 void Network::ResetNetlinkInfo()
457 {
458     netLinkInfo_.Initialize();
459 }
460 
OnHandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)461 void Network::OnHandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
462 {
463     if (eventHandler_) {
464         eventHandler_->PostAsyncTask(
465             [netDetectionState, &urlRedirect, this]() { this->HandleNetMonitorResult(netDetectionState, urlRedirect); },
466             0);
467     }
468 }
469 } // namespace NetManagerStandard
470 } // namespace OHOS
471