1 /*
2 * Copyright (c) 2021-2023 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 StopNetDetection();
109 for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
110 int32_t prefixLen = inetAddr.prefixlen_;
111 if (prefixLen == 0) {
112 prefixLen = Ipv4PrefixLen(inetAddr.netMask_);
113 }
114 NetsysController::GetInstance().InterfaceDelAddress(netLinkInfo_.ifaceName_, inetAddr.address_, prefixLen);
115 }
116 NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfo_.ifaceName_);
117 NetsysController::GetInstance().NetworkDestroy(netId_);
118 NetsysController::GetInstance().DestroyNetworkCache(netId_);
119 netLinkInfo_.Initialize();
120 isPhyNetCreated_ = false;
121 }
122 return true;
123 }
124
UpdateNetLinkInfo(const NetLinkInfo & netLinkInfo)125 bool Network::UpdateNetLinkInfo(const NetLinkInfo &netLinkInfo)
126 {
127 NETMGR_LOG_D("update net link information process");
128 UpdateInterfaces(netLinkInfo);
129 UpdateIpAddrs(netLinkInfo);
130 UpdateRoutes(netLinkInfo);
131 UpdateDns(netLinkInfo);
132 UpdateMtu(netLinkInfo);
133 netLinkInfo_ = netLinkInfo;
134 StartNetDetection(false);
135 return true;
136 }
137
GetNetLinkInfo() const138 NetLinkInfo Network::GetNetLinkInfo() const
139 {
140 return netLinkInfo_;
141 }
142
UpdateInterfaces(const NetLinkInfo & netLinkInfo)143 void Network::UpdateInterfaces(const NetLinkInfo &netLinkInfo)
144 {
145 NETMGR_LOG_D("Network UpdateInterfaces in.");
146 if (netLinkInfo.ifaceName_ == netLinkInfo_.ifaceName_) {
147 NETMGR_LOG_D("Network UpdateInterfaces out. same with before.");
148 return;
149 }
150
151 int32_t ret = NETMANAGER_SUCCESS;
152 // Call netsys to add and remove interface
153 if (!netLinkInfo.ifaceName_.empty()) {
154 ret = NetsysController::GetInstance().NetworkAddInterface(netId_, netLinkInfo.ifaceName_);
155 if (ret != NETMANAGER_SUCCESS) {
156 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_INTERFACE_FAILED);
157 }
158 }
159 if (!netLinkInfo_.ifaceName_.empty()) {
160 ret = NetsysController::GetInstance().NetworkRemoveInterface(netId_, netLinkInfo_.ifaceName_);
161 if (ret != NETMANAGER_SUCCESS) {
162 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_INTERFACE_FAILED);
163 }
164 }
165 netLinkInfo_.ifaceName_ = netLinkInfo.ifaceName_;
166 NETMGR_LOG_D("Network UpdateInterfaces out.");
167 }
168
UpdateIpAddrs(const NetLinkInfo & netLinkInfo)169 void Network::UpdateIpAddrs(const NetLinkInfo &netLinkInfo)
170 {
171 // netLinkInfo_ represents the old, netLinkInfo represents the new
172 // Update: remove old Ips first, then add the new Ips
173 NETMGR_LOG_D("UpdateIpAddrs, old ip addrs: ...");
174 for (const auto &inetAddr : netLinkInfo_.netAddrList_) {
175 int32_t prefixLen = inetAddr.prefixlen_;
176 if (prefixLen == 0) {
177 prefixLen = Ipv4PrefixLen(inetAddr.netMask_);
178 }
179 int32_t ret =
180 NetsysController::GetInstance().InterfaceDelAddress(netLinkInfo_.ifaceName_, inetAddr.address_, prefixLen);
181 if (ret != NETMANAGER_SUCCESS) {
182 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_DELETE_NET_IP_ADDR_FAILED);
183 }
184 }
185
186 NETMGR_LOG_D("UpdateIpAddrs, new ip addrs: ...");
187 for (auto it = netLinkInfo.netAddrList_.begin(); it != netLinkInfo.netAddrList_.end(); ++it) {
188 const struct INetAddr &inetAddr = *it;
189 int32_t prefixLen = inetAddr.prefixlen_;
190 if (prefixLen == 0) {
191 prefixLen = Ipv4PrefixLen(inetAddr.netMask_);
192 }
193 int32_t ret =
194 NetsysController::GetInstance().InterfaceAddAddress(netLinkInfo.ifaceName_, inetAddr.address_, prefixLen);
195 if (ret != NETMANAGER_SUCCESS) {
196 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_IP_ADDR_FAILED);
197 }
198 }
199 NETMGR_LOG_D("Network UpdateIpAddrs out.");
200 }
201
UpdateRoutes(const NetLinkInfo & netLinkInfo)202 void Network::UpdateRoutes(const NetLinkInfo &netLinkInfo)
203 {
204 // netLinkInfo_ contains the old routes info, netLinkInfo contains the new routes info
205 // Update: remove old routes first, then add the new routes
206 NETMGR_LOG_D("UpdateRoutes, old routes: [%{public}s]", netLinkInfo_.ToStringRoute("").c_str());
207 for (const auto &route : netLinkInfo_.routeList_) {
208 std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
209 auto ret = static_cast<uint32_t>(NetsysController::GetInstance().NetworkRemoveRoute(
210 netId_, route.iface_, destAddress, route.gateway_.address_));
211 if (route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP) {
212 ret |= static_cast<uint32_t>(NetsysController::GetInstance().NetworkRemoveRoute(
213 LOCAL_NET_ID, route.iface_, destAddress, LOCAL_ROUTE_NEXT_HOP));
214 }
215 if (ret != NETMANAGER_SUCCESS) {
216 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_REMOVE_NET_ROUTES_FAILED);
217 }
218 }
219
220 NETMGR_LOG_D("UpdateRoutes, new routes: [%{public}s]", netLinkInfo.ToStringRoute("").c_str());
221 for (const auto &route : netLinkInfo.routeList_) {
222 std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
223 int32_t ret =
224 NetsysController::GetInstance().NetworkAddRoute(netId_, route.iface_, destAddress, route.gateway_.address_);
225 int32_t result = 0;
226 if (route.destination_.address_ != LOCAL_ROUTE_NEXT_HOP) {
227 result = NetsysController::GetInstance().NetworkAddRoute(LOCAL_NET_ID, route.iface_, destAddress,
228 LOCAL_ROUTE_NEXT_HOP);
229 }
230 if (ret != NETMANAGER_SUCCESS || result != NETMANAGER_SUCCESS) {
231 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_ADD_NET_ROUTES_FAILED);
232 }
233 }
234 NETMGR_LOG_D("Network UpdateRoutes out.");
235 if (netLinkInfo.routeList_.empty()) {
236 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_ROUTES_FAILED);
237 }
238 }
239
UpdateDns(const NetLinkInfo & netLinkInfo)240 void Network::UpdateDns(const NetLinkInfo &netLinkInfo)
241 {
242 NETMGR_LOG_D("Network UpdateDns in.");
243 std::vector<std::string> servers;
244 std::vector<std::string> domains;
245 for (const auto &dns : netLinkInfo.dnsList_) {
246 servers.emplace_back(dns.address_);
247 domains.emplace_back(dns.hostName_);
248 }
249 // Call netsys to set dns, use default timeout and retry
250 int32_t ret = NetsysController::GetInstance().SetResolverConfig(netId_, 0, 0, servers, domains);
251 if (ret != NETMANAGER_SUCCESS) {
252 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_RESOLVER_FAILED);
253 }
254 NETMGR_LOG_D("Network UpdateDns out.");
255 if (netLinkInfo.dnsList_.empty()) {
256 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_UPDATE_NET_DNSES_FAILED);
257 }
258 }
259
UpdateMtu(const NetLinkInfo & netLinkInfo)260 void Network::UpdateMtu(const NetLinkInfo &netLinkInfo)
261 {
262 NETMGR_LOG_D("Network UpdateMtu in.");
263 if (netLinkInfo.mtu_ == netLinkInfo_.mtu_) {
264 NETMGR_LOG_D("Network UpdateMtu out. same with before.");
265 return;
266 }
267
268 int32_t ret = NetsysController::GetInstance().InterfaceSetMtu(netLinkInfo.ifaceName_, netLinkInfo.mtu_);
269 if (ret != NETMANAGER_SUCCESS) {
270 SendSupplierFaultHiSysEvent(FAULT_UPDATE_NETLINK_INFO_FAILED, ERROR_MSG_SET_NET_MTU_FAILED);
271 }
272 NETMGR_LOG_D("Network UpdateMtu out.");
273 }
274
RegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)275 void Network::RegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
276 {
277 NETMGR_LOG_D("Enter RegisterNetDetectionCallback");
278 if (callback == nullptr) {
279 NETMGR_LOG_E("The parameter callback is null");
280 return;
281 }
282
283 for (const auto &iter : netDetectionRetCallback_) {
284 if (callback->AsObject().GetRefPtr() == iter->AsObject().GetRefPtr()) {
285 NETMGR_LOG_D("netDetectionRetCallback_ had this callback");
286 return;
287 }
288 }
289
290 netDetectionRetCallback_.emplace_back(callback);
291 }
292
UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> & callback)293 int32_t Network::UnRegisterNetDetectionCallback(const sptr<INetDetectionCallback> &callback)
294 {
295 NETMGR_LOG_D("Enter UnRegisterNetDetectionCallback");
296 if (callback == nullptr) {
297 NETMGR_LOG_E("The parameter of callback is null");
298 return NETMANAGER_ERR_LOCAL_PTR_NULL;
299 }
300 for (auto iter = netDetectionRetCallback_.begin(); iter != netDetectionRetCallback_.end(); ++iter) {
301 if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
302 netDetectionRetCallback_.erase(iter);
303 return ERR_NONE;
304 }
305 }
306
307 return NETMANAGER_SUCCESS;
308 }
309
StartNetDetection(bool needReport)310 void Network::StartNetDetection(bool needReport)
311 {
312 NETMGR_LOG_D("Enter Network::StartNetDetection");
313 if (needReport) {
314 StopNetDetection();
315 }
316 InitNetMonitor();
317 }
318
StopNetDetection()319 void Network::StopNetDetection()
320 {
321 NETMGR_LOG_D("Enter Network::StopNetDetection");
322 if (netMonitor_ != nullptr) {
323 netMonitor_->Stop();
324 netMonitor_ = nullptr;
325 }
326 }
327
InitNetMonitor()328 void Network::InitNetMonitor()
329 {
330 if (netMonitor_ == nullptr) {
331 std::weak_ptr<INetMonitorCallback> monitorCallback = shared_from_this();
332 netMonitor_ = std::make_shared<NetMonitor>(netId_, monitorCallback);
333 if (netMonitor_ == nullptr) {
334 NETMGR_LOG_E("new NetMonitor failed,netMonitor_ is null!");
335 return;
336 }
337 }
338 netMonitor_->Start();
339 }
340
HandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)341 void Network::HandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
342 {
343 NETMGR_LOG_D("HandleNetMonitorResult, netDetectionState[%{public}d]", netDetectionState);
344 NotifyNetDetectionResult(NetDetectionResultConvert(static_cast<int32_t>(netDetectionState)), urlRedirect);
345 if (netCallback_ && (detectResult_ != netDetectionState)) {
346 detectResult_ = netDetectionState;
347 netCallback_(supplierId_, netDetectionState == VERIFICATION_STATE);
348 }
349 }
350
NotifyNetDetectionResult(NetDetectionResultCode detectionResult,const std::string & urlRedirect)351 void Network::NotifyNetDetectionResult(NetDetectionResultCode detectionResult, const std::string &urlRedirect)
352 {
353 for (const auto &callback : netDetectionRetCallback_) {
354 NETMGR_LOG_D("start callback!");
355 if (callback) {
356 callback->OnNetDetectionResultChanged(detectionResult, urlRedirect);
357 }
358 }
359 }
360
NetDetectionResultConvert(int32_t internalRet)361 NetDetectionResultCode Network::NetDetectionResultConvert(int32_t internalRet)
362 {
363 switch (internalRet) {
364 case static_cast<int32_t>(INVALID_DETECTION_STATE):
365 return NET_DETECTION_FAIL;
366 case static_cast<int32_t>(VERIFICATION_STATE):
367 return NET_DETECTION_SUCCESS;
368 case static_cast<int32_t>(CAPTIVE_PORTAL_STATE):
369 return NET_DETECTION_CAPTIVE_PORTAL;
370 default:
371 break;
372 }
373 return NET_DETECTION_FAIL;
374 }
375
SetDefaultNetWork()376 void Network::SetDefaultNetWork()
377 {
378 int32_t ret = NetsysController::GetInstance().SetDefaultNetWork(netId_);
379 if (ret != NETMANAGER_SUCCESS) {
380 SendSupplierFaultHiSysEvent(FAULT_SET_DEFAULT_NETWORK_FAILED, ERROR_MSG_SET_DEFAULT_NETWORK_FAILED);
381 }
382 }
383
ClearDefaultNetWorkNetId()384 void Network::ClearDefaultNetWorkNetId()
385 {
386 int32_t ret = NetsysController::GetInstance().ClearDefaultNetWorkNetId();
387 if (ret != NETMANAGER_SUCCESS) {
388 SendSupplierFaultHiSysEvent(FAULT_CLEAR_DEFAULT_NETWORK_FAILED, ERROR_MSG_CLEAR_DEFAULT_NETWORK_FAILED);
389 }
390 }
391
IsConnecting() const392 bool Network::IsConnecting() const
393 {
394 return state_ == NET_CONN_STATE_CONNECTING;
395 }
396
IsConnected() const397 bool Network::IsConnected() const
398 {
399 return state_ == NET_CONN_STATE_CONNECTED;
400 }
401
UpdateNetConnState(NetConnState netConnState)402 void Network::UpdateNetConnState(NetConnState netConnState)
403 {
404 if (state_ == netConnState) {
405 NETMGR_LOG_E("Ignore same network state changed.");
406 return;
407 }
408 NetConnState oldState = state_;
409 switch (netConnState) {
410 case NET_CONN_STATE_IDLE:
411 case NET_CONN_STATE_CONNECTING:
412 case NET_CONN_STATE_CONNECTED:
413 case NET_CONN_STATE_DISCONNECTING:
414 state_ = netConnState;
415 break;
416 case NET_CONN_STATE_DISCONNECTED:
417 state_ = netConnState;
418 ResetNetlinkInfo();
419 break;
420 default:
421 state_ = NET_CONN_STATE_UNKNOWN;
422 break;
423 }
424
425 SendConnectionChangedBroadcast(netConnState);
426 NETMGR_LOG_D("Network[%{public}d] state changed, from [%{public}d] to [%{public}d]", netId_, oldState, state_);
427 }
428
SendConnectionChangedBroadcast(const NetConnState & netConnState) const429 void Network::SendConnectionChangedBroadcast(const NetConnState &netConnState) const
430 {
431 BroadcastInfo info;
432 info.action = EventFwk::CommonEventSupport::COMMON_EVENT_CONNECTIVITY_CHANGE;
433 info.data = "Net Manager Connection State Changed";
434 info.code = static_cast<int32_t>(netConnState);
435 info.ordered = true;
436 std::map<std::string, int32_t> param = {{"NetType", static_cast<int32_t>(netSupplierType_)}};
437 DelayedSingleton<BroadcastManager>::GetInstance()->SendBroadcast(info, param);
438 }
439
SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType,const std::string & errMsg)440 void Network::SendSupplierFaultHiSysEvent(NetConnSupplerFault errorType, const std::string &errMsg)
441 {
442 struct EventInfo eventInfo = {.netlinkInfo = netLinkInfo_.ToString(" "),
443 .supplierId = static_cast<int32_t>(supplierId_),
444 .errorType = static_cast<int32_t>(errorType),
445 .errorMsg = errMsg};
446 EventReport::SendSupplierFaultEvent(eventInfo);
447 }
448
ResetNetlinkInfo()449 void Network::ResetNetlinkInfo()
450 {
451 netLinkInfo_.Initialize();
452 }
453
OnHandleNetMonitorResult(NetDetectionStatus netDetectionState,const std::string & urlRedirect)454 void Network::OnHandleNetMonitorResult(NetDetectionStatus netDetectionState, const std::string &urlRedirect)
455 {
456 if (eventHandler_) {
457 eventHandler_->PostAsyncTask(
458 [netDetectionState, &urlRedirect, this]() { this->HandleNetMonitorResult(netDetectionState, urlRedirect); },
459 0);
460 }
461 }
462 } // namespace NetManagerStandard
463 } // namespace OHOS
464