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 <sys/time.h>
17
18 #include "common_event_support.h"
19 #include "system_ability_definition.h"
20
21 #include "broadcast_manager.h"
22 #include "event_report.h"
23 #include "net_activate.h"
24 #include "net_conn_service.h"
25 #include "net_conn_types.h"
26 #include "net_manager_center.h"
27 #include "net_manager_constants.h"
28 #include "net_mgr_log_wrapper.h"
29 #include "net_supplier.h"
30 #include "netmanager_base_permission.h"
31 #include "netsys_controller.h"
32 #include "net_http_proxy_tracker.h"
33
34 namespace OHOS {
35 namespace NetManagerStandard {
36 namespace {
37 // hisysevent error messgae
38 constexpr const char *ERROR_MSG_NULL_SUPPLIER_INFO = "Net supplier info is nullptr";
39 constexpr const char *ERROR_MSG_NULL_NET_LINK_INFO = "Net link info is nullptr";
40 constexpr const char *ERROR_MSG_NULL_NET_SPECIFIER = "The parameter of netSpecifier or callback is null";
41 constexpr const char *ERROR_MSG_CAN_NOT_FIND_SUPPLIER = "Can not find supplier by id:";
42 constexpr const char *ERROR_MSG_UPDATE_NETLINK_INFO_FAILED = "Update net link info failed";
43 } // namespace
44
45 const bool REGISTER_LOCAL_RESULT =
46 SystemAbility::MakeAndRegisterAbility(DelayedSingleton<NetConnService>::GetInstance().get());
47
NetConnService()48 NetConnService::NetConnService()
49 : SystemAbility(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID, true), registerToService_(false), state_(STATE_STOPPED)
50 {
51 CreateDefaultRequest();
52 }
53
~NetConnService()54 NetConnService::~NetConnService() {}
55
OnStart()56 void NetConnService::OnStart()
57 {
58 struct timeval tv;
59 gettimeofday(&tv, nullptr);
60 NETMGR_LOG_D("NetConnService::OnStart begin");
61 if (state_ == STATE_RUNNING) {
62 NETMGR_LOG_D("the state is already running");
63 return;
64 }
65 if (!Init()) {
66 NETMGR_LOG_E("init failed");
67 return;
68 }
69 state_ = STATE_RUNNING;
70 gettimeofday(&tv, nullptr);
71 NETMGR_LOG_D("NetConnService::OnStart end");
72 }
73
CreateDefaultRequest()74 void NetConnService::CreateDefaultRequest()
75 {
76 if (!defaultNetActivate_) {
77 defaultNetSpecifier_ = (std::make_unique<NetSpecifier>()).release();
78 defaultNetSpecifier_->SetCapability(NET_CAPABILITY_INTERNET);
79 std::weak_ptr<INetActivateCallback> timeoutCb;
80 defaultNetActivate_ = new (std::nothrow) NetActivate(defaultNetSpecifier_, nullptr, timeoutCb, 0);
81 defaultNetActivate_->SetRequestId(DEFAULT_REQUEST_ID);
82 netActivates_[DEFAULT_REQUEST_ID] = defaultNetActivate_;
83 }
84 }
85
OnStop()86 void NetConnService::OnStop()
87 {
88 state_ = STATE_STOPPED;
89 registerToService_ = false;
90 }
91
Init()92 bool NetConnService::Init()
93 {
94 if (!REGISTER_LOCAL_RESULT) {
95 NETMGR_LOG_E("Register to local sa manager failed");
96 registerToService_ = false;
97 return false;
98 }
99 if (!registerToService_) {
100 if (!Publish(DelayedSingleton<NetConnService>::GetInstance().get())) {
101 NETMGR_LOG_E("Register to sa manager failed");
102 return false;
103 }
104 registerToService_ = true;
105 }
106 serviceIface_ = std::make_unique<NetConnServiceIface>().release();
107 NetManagerCenter::GetInstance().RegisterConnService(serviceIface_);
108 netScore_ = std::make_unique<NetScore>();
109 if (netScore_ == nullptr) {
110 NETMGR_LOG_E("Make NetScore failed");
111 return false;
112 }
113
114 eventRunner_ = AppExecFwk::EventRunner::Create(true);
115 if (eventRunner_ == nullptr) {
116 NETMGR_LOG_E("Create event runner failed.");
117 return false;
118 }
119 netConnEventHandler_ = std::make_shared<NetConnEventHandler>(eventRunner_);
120 NetHttpProxyTracker httpProxyTracker;
121 if (!httpProxyTracker.ReadFromSystemParameter(httpProxy_)) {
122 NETMGR_LOG_E("NetConnService Init: read http proxy failed");
123 }
124 SendGlobalHttpProxyChangeBroadcast();
125 return true;
126 }
127
SystemReady()128 int32_t NetConnService::SystemReady()
129 {
130 NETMGR_LOG_D("System ready.");
131 return NETMANAGER_SUCCESS;
132 }
133
RegisterNetSupplier(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps,uint32_t & supplierId)134 int32_t NetConnService::RegisterNetSupplier(NetBearType bearerType, const std::string &ident,
135 const std::set<NetCap> &netCaps, uint32_t &supplierId)
136 {
137 NETMGR_LOG_D("register supplier, netType[%{public}u], ident[%{public}s]", static_cast<uint32_t>(bearerType),
138 ident.c_str());
139 // According to netType, ident, get the supplier from the list and save the supplierId in the list
140 if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
141 NETMGR_LOG_E("netType parameter invalid");
142 return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
143 }
144
145 sptr<NetSupplier> supplier = GetNetSupplierFromList(bearerType, ident, netCaps);
146 if (supplier != nullptr) {
147 NETMGR_LOG_D("supplier already exists.");
148 supplierId = supplier->GetSupplierId();
149 return NETMANAGER_SUCCESS;
150 }
151
152 // If there is no supplier in the list, create a supplier
153 supplier = (std::make_unique<NetSupplier>(bearerType, ident, netCaps)).release();
154 if (supplier == nullptr) {
155 NETMGR_LOG_E("supplier is nullptr");
156 return NET_CONN_ERR_NO_SUPPLIER;
157 }
158 supplierId = supplier->GetSupplierId();
159 if (!netScore_->GetServiceScore(supplier)) {
160 NETMGR_LOG_E("GetServiceScore fail.");
161 }
162
163 // create network
164 int32_t netId = GenerateNetId();
165 NETMGR_LOG_D("GenerateNetId is: [%{public}d]", netId);
166 if (netId == INVALID_NET_ID) {
167 NETMGR_LOG_E("GenerateNetId fail");
168 return NET_CONN_ERR_INVALID_NETWORK;
169 }
170 using namespace std::placeholders;
171 std::shared_ptr<Network> network =
172 std::make_shared<Network>(netId, supplierId, std::bind(&NetConnService::HandleDetectionResult, this, _1, _2),
173 bearerType, netConnEventHandler_);
174 NETMGR_LOG_D("netId is: [%{public}d], supplierId is: [%{public}d]", network->GetNetId(), supplier->GetSupplierId());
175 supplier->SetNetwork(network);
176 supplier->SetNetValid(true);
177
178 // save supplier
179 std::unique_lock<std::mutex> locker(netManagerMutex_);
180 netSuppliers_[supplierId] = supplier;
181 networks_[netId] = network;
182 locker.unlock();
183
184 NETMGR_LOG_D("RegisterNetSupplier service out. netSuppliers_ size[%{public}zd]", netSuppliers_.size());
185 struct EventInfo eventInfo = {.netId = netId, .bearerType = bearerType, .ident = ident, .supplierId = supplierId};
186 EventReport::SendSupplierBehaviorEvent(eventInfo);
187 return NETMANAGER_SUCCESS;
188 }
189
GenerateNetId()190 int32_t NetConnService::GenerateNetId()
191 {
192 for (int32_t i = MIN_NET_ID; i <= MAX_NET_ID; ++i) {
193 netIdLastValue_++;
194 if (netIdLastValue_ > MAX_NET_ID) {
195 netIdLastValue_ = MIN_NET_ID;
196 }
197 if (networks_.find(netIdLastValue_) == networks_.end()) {
198 return netIdLastValue_;
199 }
200 }
201 return INVALID_NET_ID;
202 }
203
FindNetSupplier(uint32_t supplierId)204 sptr<NetSupplier> NetConnService::FindNetSupplier(uint32_t supplierId)
205 {
206 std::lock_guard<std::mutex> locker(netManagerMutex_);
207 auto iterSupplier = netSuppliers_.find(supplierId);
208 if (iterSupplier != netSuppliers_.end()) {
209 return iterSupplier->second;
210 }
211 return nullptr;
212 }
213
UnregisterNetSupplier(uint32_t supplierId)214 int32_t NetConnService::UnregisterNetSupplier(uint32_t supplierId)
215 {
216 NETMGR_LOG_D("UnregisterNetSupplier supplierId[%{public}d]", supplierId);
217 // Remove supplier from the list based on supplierId
218 auto supplier = FindNetSupplier(supplierId);
219 if (supplier == nullptr) {
220 NETMGR_LOG_E("supplier doesn't exist.");
221 return NET_CONN_ERR_NO_SUPPLIER;
222 }
223 NETMGR_LOG_D("unregister supplier[%{public}d, %{public}s], defaultNetSupplier[%{public}d], %{public}s",
224 supplier->GetSupplierId(), supplier->GetNetSupplierIdent().c_str(),
225 defaultNetSupplier_ ? defaultNetSupplier_->GetSupplierId() : 0,
226 defaultNetSupplier_ ? defaultNetSupplier_->GetNetSupplierIdent().c_str() : "null");
227
228 struct EventInfo eventInfo = {.bearerType = supplier->GetNetSupplierType(),
229 .ident = supplier->GetNetSupplierIdent(),
230 .supplierId = supplier->GetSupplierId()};
231 EventReport::SendSupplierBehaviorEvent(eventInfo);
232
233 int32_t netId = supplier->GetNetId();
234 std::unique_lock<std::mutex> locker(netManagerMutex_);
235 NET_NETWORK_MAP::iterator iterNetwork = networks_.find(netId);
236 if (iterNetwork != networks_.end()) {
237 networks_.erase(iterNetwork);
238 }
239 if (defaultNetSupplier_ == supplier) {
240 NETMGR_LOG_D("set defaultNetSupplier_ to null.");
241 sptr<NetSupplier> newSupplier = nullptr;
242 MakeDefaultNetWork(defaultNetSupplier_, newSupplier);
243 }
244 NetSupplierInfo info;
245 supplier->UpdateNetSupplierInfo(info);
246 netSuppliers_.erase(supplierId);
247 locker.unlock();
248 FindBestNetworkForAllRequest();
249 NETMGR_LOG_D("Destroy supplier network.");
250 return NETMANAGER_SUCCESS;
251 }
252
RegisterNetSupplierCallback(uint32_t supplierId,const sptr<INetSupplierCallback> & callback)253 int32_t NetConnService::RegisterNetSupplierCallback(uint32_t supplierId, const sptr<INetSupplierCallback> &callback)
254 {
255 NETMGR_LOG_D("RegisterNetSupplierCallback service in.");
256 if (callback == nullptr) {
257 NETMGR_LOG_E("The parameter callback is null");
258 return NETMANAGER_ERR_LOCAL_PTR_NULL;
259 }
260 auto supplier = FindNetSupplier(supplierId);
261 if (supplier == nullptr) {
262 NETMGR_LOG_E("supplier doesn't exist.");
263 return NET_CONN_ERR_NO_SUPPLIER;
264 }
265 supplier->RegisterSupplierCallback(callback);
266 SendAllRequestToNetwork(supplier);
267 NETMGR_LOG_D("RegisterNetSupplierCallback service out.");
268 return NETMANAGER_SUCCESS;
269 }
270
RegisterNetConnCallback(const sptr<INetConnCallback> & callback)271 int32_t NetConnService::RegisterNetConnCallback(const sptr<INetConnCallback> &callback)
272 {
273 NETMGR_LOG_D("RegisterNetConnCallback service in.");
274 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
275 return NETMANAGER_ERR_PERMISSION_DENIED;
276 }
277 if (callback == nullptr) {
278 NETMGR_LOG_E("The parameter callback is null");
279 return NETMANAGER_ERR_LOCAL_PTR_NULL;
280 }
281 return RegisterNetConnCallback(defaultNetSpecifier_, callback, 0);
282 }
283
RegisterNetConnCallback(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS)284 int32_t NetConnService::RegisterNetConnCallback(const sptr<NetSpecifier> &netSpecifier,
285 const sptr<INetConnCallback> &callback, const uint32_t &timeoutMS)
286 {
287 NETMGR_LOG_D("RegisterNetConnCallback service in.");
288 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
289 return NETMANAGER_ERR_PERMISSION_DENIED;
290 }
291 if (netSpecifier == nullptr || callback == nullptr) {
292 NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
293 struct EventInfo eventInfo = {.errorType = static_cast<int32_t>(FAULT_INVALID_PARAMETER),
294 .errorMsg = ERROR_MSG_NULL_NET_SPECIFIER};
295 EventReport::SendRequestFaultEvent(eventInfo);
296 return NETMANAGER_ERR_LOCAL_PTR_NULL;
297 }
298 std::lock_guard<std::mutex> locker(netManagerMutex_);
299 if (netActivates_.size() >= MAX_REQUEST_NUM) {
300 NETMGR_LOG_E("Over the max request number");
301 return NET_CONN_ERR_NET_OVER_MAX_REQUEST_NUM;
302 }
303 uint32_t reqId = 0;
304 if (FindSameCallback(callback, reqId)) {
305 NETMGR_LOG_D("RegisterNetConnCallback FindSameCallback(callback, reqId)");
306 return NET_CONN_ERR_CALLBACK_NOT_FOUND;
307 }
308 return ActivateNetwork(netSpecifier, callback, timeoutMS);
309 }
310
UnregisterNetConnCallback(const sptr<INetConnCallback> & callback)311 int32_t NetConnService::UnregisterNetConnCallback(const sptr<INetConnCallback> &callback)
312 {
313 NETMGR_LOG_D("UnregisterNetConnCallback Enter");
314 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
315 return NETMANAGER_ERR_PERMISSION_DENIED;
316 }
317 if (callback == nullptr) {
318 NETMGR_LOG_E("callback is null");
319 return NETMANAGER_ERR_LOCAL_PTR_NULL;
320 }
321 std::lock_guard<std::mutex> locker(netManagerMutex_);
322 uint32_t reqId = 0;
323 if (!FindSameCallback(callback, reqId)) {
324 NETMGR_LOG_D("UnregisterNetConnCallback can not find same callback");
325 return NET_CONN_ERR_SAME_CALLBACK;
326 }
327
328 NET_ACTIVATE_MAP::iterator iterActive;
329 for (iterActive = netActivates_.begin(); iterActive != netActivates_.end();) {
330 if (!iterActive->second) {
331 ++iterActive;
332 continue;
333 }
334 sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
335 if (saveCallback == nullptr) {
336 ++iterActive;
337 continue;
338 }
339 if (callback->AsObject().GetRefPtr() != saveCallback->AsObject().GetRefPtr()) {
340 ++iterActive;
341 continue;
342 }
343 reqId = iterActive->first;
344 sptr<NetActivate> netActivate = iterActive->second;
345 if (netActivate) {
346 sptr<NetSupplier> supplier = netActivate->GetServiceSupply();
347 if (supplier) {
348 supplier->CancelRequest(reqId);
349 }
350 }
351
352 NET_SUPPLIER_MAP::iterator iterSupplier;
353 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
354 if (iterSupplier->second != nullptr) {
355 iterSupplier->second->CancelRequest(reqId);
356 }
357 }
358 iterActive = netActivates_.erase(iterActive);
359 }
360 return NETMANAGER_SUCCESS;
361 }
362
FindSameCallback(const sptr<INetConnCallback> & callback,uint32_t & reqId)363 bool NetConnService::FindSameCallback(const sptr<INetConnCallback> &callback, uint32_t &reqId)
364 {
365 if (callback == nullptr) {
366 NETMGR_LOG_E("callback is null");
367 return false;
368 }
369 NET_ACTIVATE_MAP::iterator iterActive;
370 for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
371 if (!iterActive->second) {
372 continue;
373 }
374 sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
375 if (saveCallback == nullptr) {
376 continue;
377 }
378 if (callback->AsObject().GetRefPtr() == saveCallback->AsObject().GetRefPtr()) {
379 reqId = iterActive->first;
380 return true;
381 }
382 }
383 return false;
384 }
385
UpdateNetStateForTest(const sptr<NetSpecifier> & netSpecifier,int32_t netState)386 int32_t NetConnService::UpdateNetStateForTest(const sptr<NetSpecifier> &netSpecifier, int32_t netState)
387 {
388 NETMGR_LOG_I("Test NetConnService::UpdateNetStateForTest(), begin");
389 if (netSpecifier == nullptr) {
390 NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
391 return NETMANAGER_ERR_LOCAL_PTR_NULL;
392 }
393 return NETMANAGER_SUCCESS;
394 }
395
UpdateNetSupplierInfo(uint32_t supplierId,const sptr<NetSupplierInfo> & netSupplierInfo)396 int32_t NetConnService::UpdateNetSupplierInfo(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo)
397 {
398 struct EventInfo eventInfo = {
399 .updateSupplierId = supplierId
400 };
401 if (netSupplierInfo == nullptr) {
402 NETMGR_LOG_E("netSupplierInfo is nullptr");
403 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_SUPPLIERINFO_INV_PARAM);
404 eventInfo.errorMsg = ERROR_MSG_NULL_SUPPLIER_INFO;
405 EventReport::SendSupplierFaultEvent(eventInfo);
406 return NETMANAGER_ERR_PARAMETER_ERROR;
407 }
408
409 NETMGR_LOG_I("Update supplier info: supplierId[%{public}d], netSupplierInfo[%{public}s]", supplierId,
410 netSupplierInfo->ToString(" ").c_str());
411 eventInfo.supplierInfo = netSupplierInfo->ToString(" ");
412 EventReport::SendSupplierBehaviorEvent(eventInfo);
413
414 // According to supplierId, get the supplier from the list
415 auto supplier = FindNetSupplier(supplierId);
416 if (supplier == nullptr) {
417 NETMGR_LOG_E("supplier is nullptr, netSuppliers_ size[%{public}zd]", netSuppliers_.size());
418 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_SUPPLIERINFO_INV_PARAM);
419 eventInfo.errorMsg = std::string(ERROR_MSG_CAN_NOT_FIND_SUPPLIER).append(std::to_string(supplierId));
420 EventReport::SendSupplierFaultEvent(eventInfo);
421 return NET_CONN_ERR_NO_SUPPLIER;
422 }
423
424 supplier->UpdateNetSupplierInfo(*netSupplierInfo);
425
426 std::unique_lock<std::mutex> locker(netManagerMutex_);
427 if (!netSupplierInfo->isAvailable_) {
428 CallbackForSupplier(supplier, CALL_TYPE_LOST);
429 } else {
430 CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
431 }
432 locker.unlock();
433 if (!netScore_->GetServiceScore(supplier)) {
434 NETMGR_LOG_E("GetServiceScore fail.");
435 }
436 FindBestNetworkForAllRequest();
437 NETMGR_LOG_D("UpdateNetSupplierInfo service out.");
438 return NETMANAGER_SUCCESS;
439 }
440
RestrictBackgroundChanged(bool restrictBackground)441 int32_t NetConnService::RestrictBackgroundChanged(bool restrictBackground)
442 {
443 NETMGR_LOG_D("NetConnService::RestrictBackgroundChanged restrictBackground = %{public}d", restrictBackground);
444 std::lock_guard<std::mutex> locker(netManagerMutex_);
445 for (auto it = netSuppliers_.begin(); it != netSuppliers_.end(); ++it) {
446 if (it->second == nullptr) {
447 continue;
448 }
449
450 if (it->second->GetRestrictBackground() == restrictBackground) {
451 NETMGR_LOG_D("it->second->GetRestrictBackground() == restrictBackground");
452 return NET_CONN_ERR_NET_NO_RESTRICT_BACKGROUND;
453 }
454
455 if (it->second->GetNetSupplierType() == BEARER_VPN) {
456 CallbackForSupplier(it->second, CALL_TYPE_BLOCK_STATUS);
457 }
458 it->second->SetRestrictBackground(restrictBackground);
459 }
460 NETMGR_LOG_D("RestrictBackgroundChanged service out.");
461 return NETMANAGER_SUCCESS;
462 }
463
UpdateNetLinkInfo(uint32_t supplierId,const sptr<NetLinkInfo> & netLinkInfo)464 int32_t NetConnService::UpdateNetLinkInfo(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo)
465 {
466 NETMGR_LOG_D("UpdateNetLinkInfo service in. supplierId[%{public}d]", supplierId);
467 struct EventInfo eventInfo = {
468 .updateNetlinkId = supplierId
469 };
470
471 if (netLinkInfo == nullptr) {
472 NETMGR_LOG_E("netLinkInfo is nullptr");
473 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_INV_PARAM);
474 eventInfo.errorMsg = ERROR_MSG_NULL_NET_LINK_INFO;
475 EventReport::SendSupplierFaultEvent(eventInfo);
476 return NETMANAGER_ERR_PARAMETER_ERROR;
477 }
478
479 eventInfo.netlinkInfo = netLinkInfo->ToString(" ");
480 EventReport::SendSupplierBehaviorEvent(eventInfo);
481
482 auto supplier = FindNetSupplier(supplierId);
483 if (supplier == nullptr) {
484 NETMGR_LOG_E("supplier is nullptr");
485 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_INV_PARAM);
486 eventInfo.errorMsg = std::string(ERROR_MSG_CAN_NOT_FIND_SUPPLIER).append(std::to_string(supplierId));
487 EventReport::SendSupplierFaultEvent(eventInfo);
488 return NET_CONN_ERR_NO_SUPPLIER;
489 }
490 // According to supplier id, get network from the list
491 if (supplier->UpdateNetLinkInfo(*netLinkInfo) != NETMANAGER_SUCCESS) {
492 NETMGR_LOG_E("UpdateNetLinkInfo fail");
493 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_FAILED);
494 eventInfo.errorMsg = ERROR_MSG_UPDATE_NETLINK_INFO_FAILED;
495 EventReport::SendSupplierFaultEvent(eventInfo);
496 return NET_CONN_ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL;
497 }
498 std::unique_lock<std::mutex> locker(netManagerMutex_);
499 CallbackForSupplier(supplier, CALL_TYPE_UPDATE_LINK);
500 locker.unlock();
501 if (!netScore_->GetServiceScore(supplier)) {
502 NETMGR_LOG_E("GetServiceScore fail.");
503 }
504 FindBestNetworkForAllRequest();
505 NETMGR_LOG_D("UpdateNetLinkInfo service out.");
506 return NETMANAGER_SUCCESS;
507 }
508
RegisterNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback)509 int32_t NetConnService::RegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback)
510 {
511 NETMGR_LOG_D("Enter NetConnService::RegisterNetDetectionCallback");
512 return RegUnRegNetDetectionCallback(netId, callback, true);
513 }
514
UnRegisterNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback)515 int32_t NetConnService::UnRegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback)
516 {
517 NETMGR_LOG_D("Enter NetConnService::UnRegisterNetDetectionCallback");
518 return RegUnRegNetDetectionCallback(netId, callback, false);
519 }
520
NetDetection(int32_t netId)521 int32_t NetConnService::NetDetection(int32_t netId)
522 {
523 NETMGR_LOG_D("Enter NetConnService::NetDetection");
524 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO) ||
525 !NetManagerPermission::CheckPermission(Permission::INTERNET)) {
526 return NETMANAGER_ERR_PERMISSION_DENIED;
527 }
528 std::lock_guard<std::mutex> locker(netManagerMutex_);
529 auto iterNetwork = networks_.find(netId);
530 if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
531 NETMGR_LOG_E("Could not find the corresponding network.");
532 return NET_CONN_ERR_NETID_NOT_FOUND;
533 }
534 iterNetwork->second->StartNetDetection(true);
535 return NETMANAGER_SUCCESS;
536 }
537
RegUnRegNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback,bool isReg)538 int32_t NetConnService::RegUnRegNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback,
539 bool isReg)
540 {
541 if (callback == nullptr) {
542 NETMGR_LOG_E("The parameter of callback is null");
543 return NETMANAGER_ERR_LOCAL_PTR_NULL;
544 }
545
546 std::lock_guard<std::mutex> locker(netManagerMutex_);
547 auto iterNetwork = networks_.find(netId);
548 if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
549 NETMGR_LOG_E("Could not find the corresponding network.");
550 return NET_CONN_ERR_NETID_NOT_FOUND;
551 }
552 if (isReg) {
553 iterNetwork->second->RegisterNetDetectionCallback(callback);
554 return NETMANAGER_SUCCESS;
555 }
556 return iterNetwork->second->UnRegisterNetDetectionCallback(callback);
557 }
558
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident)559 std::list<sptr<NetSupplier>> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident)
560 {
561 std::list<sptr<NetSupplier>> ret;
562 std::lock_guard<std::mutex> locker(netManagerMutex_);
563 for (const auto &netSupplier : netSuppliers_) {
564 if (netSupplier.second == nullptr) {
565 continue;
566 }
567 if ((bearerType != netSupplier.second->GetNetSupplierType())) {
568 continue;
569 }
570 if (!ident.empty() && netSupplier.second->GetNetSupplierIdent() != ident) {
571 continue;
572 }
573 ret.push_back(netSupplier.second);
574 }
575 return ret;
576 }
577
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps)578 sptr<NetSupplier> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident,
579 const std::set<NetCap> &netCaps)
580 {
581 std::lock_guard<std::mutex> locker(netManagerMutex_);
582 for (const auto &netSupplier : netSuppliers_) {
583 if (netSupplier.second == nullptr) {
584 continue;
585 }
586 if ((bearerType == netSupplier.second->GetNetSupplierType()) &&
587 (ident == netSupplier.second->GetNetSupplierIdent()) && netSupplier.second->CompareNetCaps(netCaps)) {
588 return netSupplier.second;
589 }
590 }
591 return nullptr;
592 }
593
ActivateNetwork(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS)594 int32_t NetConnService::ActivateNetwork(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
595 const uint32_t &timeoutMS)
596 {
597 NETMGR_LOG_D("ActivateNetwork Enter");
598 if (netSpecifier == nullptr || callback == nullptr) {
599 NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
600 return NETMANAGER_ERR_PARAMETER_ERROR;
601 }
602 std::weak_ptr<INetActivateCallback> timeoutCb = shared_from_this();
603 sptr<NetActivate> request = new (std::nothrow) NetActivate(netSpecifier, callback, timeoutCb, timeoutMS);
604 uint32_t reqId = request->GetRequestId();
605 NETMGR_LOG_D("ActivateNetwork reqId is [%{public}d]", reqId);
606 netActivates_[reqId] = request;
607 sptr<NetSupplier> bestNet = nullptr;
608 int bestScore = static_cast<int>(FindBestNetworkForRequest(bestNet, request));
609 if (bestScore != 0 && bestNet != nullptr) {
610 NETMGR_LOG_I("ActivateNetwork:The bestScore is: [%{public}d], netHandle is [%{public}d]", bestScore,
611 bestNet->GetNetId());
612 bestNet->SelectAsBestNetwork(reqId);
613 request->SetServiceSupply(bestNet);
614 CallbackForAvailable(bestNet, callback);
615 if ((bestNet->GetNetSupplierType() == BEARER_CELLULAR) || (bestNet->GetNetSupplierType() == BEARER_WIFI)) {
616 struct EventInfo eventInfo = {
617 .capabilities = bestNet->GetNetCapabilities().ToString(" "),
618 .supplierIdent = bestNet->GetNetSupplierIdent()
619 };
620 EventReport::SendRequestBehaviorEvent(eventInfo);
621 }
622 return NETMANAGER_SUCCESS;
623 }
624 if (timeoutMS == 0) {
625 callback->NetUnavailable();
626 }
627
628 NETMGR_LOG_I("ActivateNetwork: can't found best network, send request to all networks.");
629 SendRequestToAllNetwork(request);
630 return NETMANAGER_SUCCESS;
631 }
632
OnNetActivateTimeOut(uint32_t reqId)633 void NetConnService::OnNetActivateTimeOut(uint32_t reqId)
634 {
635 NETMGR_LOG_D("OnNetActivateTimeOut Enter, reqId is [%{public}d]", reqId);
636 std::lock_guard<std::mutex> locker(netManagerMutex_);
637 auto iterActivate = netActivates_.find(reqId);
638 if (iterActivate == netActivates_.end()) {
639 NETMGR_LOG_E("not found the reqId: [%{public}d]", reqId);
640 return;
641 }
642 if (iterActivate->second != nullptr) {
643 sptr<NetSupplier> pNetService = iterActivate->second->GetServiceSupply();
644 if (pNetService) {
645 pNetService->CancelRequest(reqId);
646 }
647 }
648
649 NET_SUPPLIER_MAP::iterator iterSupplier;
650 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
651 if (iterSupplier->second == nullptr) {
652 continue;
653 }
654 iterSupplier->second->CancelRequest(reqId);
655 }
656 }
657
GetDefaultNet(int32_t & netId)658 int32_t NetConnService::GetDefaultNet(int32_t &netId)
659 {
660 if (!NetManagerPermission::CheckPermissionWithCache(Permission::GET_NETWORK_INFO)) {
661 return NETMANAGER_ERR_PERMISSION_DENIED;
662 }
663 if (!defaultNetSupplier_) {
664 NETMGR_LOG_E("not found the netId");
665 return NETMANAGER_SUCCESS;
666 }
667
668 netId = defaultNetSupplier_->GetNetId();
669 NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
670 return NETMANAGER_SUCCESS;
671 }
672
HasDefaultNet(bool & flag)673 int32_t NetConnService::HasDefaultNet(bool &flag)
674 {
675 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
676 return NETMANAGER_ERR_PERMISSION_DENIED;
677 }
678 if (!defaultNetSupplier_) {
679 flag = false;
680 return NETMANAGER_SUCCESS;
681 }
682 flag = true;
683 return NETMANAGER_SUCCESS;
684 }
685
IsDefaultNetMetered(bool & isMetered)686 int32_t NetConnService::IsDefaultNetMetered(bool &isMetered)
687 {
688 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
689 return NETMANAGER_ERR_PERMISSION_DENIED;
690 }
691 if (defaultNetSupplier_) {
692 isMetered = !defaultNetSupplier_->HasNetCap(NET_CAPABILITY_NOT_METERED);
693 } else {
694 isMetered = true;
695 }
696 return NETMANAGER_SUCCESS;
697 }
698
MakeDefaultNetWork(sptr<NetSupplier> & oldSupplier,sptr<NetSupplier> & newSupplier)699 void NetConnService::MakeDefaultNetWork(sptr<NetSupplier> &oldSupplier, sptr<NetSupplier> &newSupplier)
700 {
701 NETMGR_LOG_I("MakeDefaultNetWork in, oldSupplier[%{public}d, %{public}s], newSupplier[%{public}d, %{public}s]",
702 oldSupplier ? oldSupplier->GetSupplierId() : 0,
703 oldSupplier ? oldSupplier->GetNetSupplierIdent().c_str() : "null",
704 newSupplier ? newSupplier->GetSupplierId() : 0,
705 newSupplier ? newSupplier->GetNetSupplierIdent().c_str() : "null");
706 if (oldSupplier == newSupplier) {
707 NETMGR_LOG_D("old supplier equal to new supplier.");
708 return;
709 }
710 if (oldSupplier != nullptr) {
711 oldSupplier->ClearDefault();
712 }
713 if (newSupplier != nullptr) {
714 newSupplier->SetDefault();
715 }
716 oldSupplier = newSupplier;
717 NETMGR_LOG_D("default Supplier set to: [%{public}d, %{public}s]", oldSupplier ? oldSupplier->GetSupplierId() : 0,
718 oldSupplier ? oldSupplier->GetNetSupplierIdent().c_str() : "null");
719 }
720
GetAddressesByName(const std::string & host,int32_t netId,std::vector<INetAddr> & addrList)721 int32_t NetConnService::GetAddressesByName(const std::string &host, int32_t netId, std::vector<INetAddr> &addrList)
722 {
723 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
724 return NETMANAGER_ERR_PERMISSION_DENIED;
725 }
726 return NetManagerCenter::GetInstance().GetAddressesByName(host, static_cast<uint16_t>(netId), addrList);
727 }
728
GetAddressByName(const std::string & host,int32_t netId,INetAddr & addr)729 int32_t NetConnService::GetAddressByName(const std::string &host, int32_t netId, INetAddr &addr)
730 {
731 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
732 return NETMANAGER_ERR_PERMISSION_DENIED;
733 }
734 std::vector<INetAddr> addrList;
735 int ret = GetAddressesByName(host, netId, addrList);
736 if (ret == NETMANAGER_SUCCESS) {
737 if (!addrList.empty()) {
738 addr = addrList[0];
739 return ret;
740 }
741 return NET_CONN_ERR_NO_ADDRESS;
742 }
743 return ret;
744 }
745
GetSpecificNet(NetBearType bearerType,std::list<int32_t> & netIdList)746 int32_t NetConnService::GetSpecificNet(NetBearType bearerType, std::list<int32_t> &netIdList)
747 {
748 if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
749 NETMGR_LOG_E("netType parameter invalid");
750 return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
751 }
752
753 NET_SUPPLIER_MAP::iterator iterSupplier;
754 std::lock_guard<std::mutex> locker(netManagerMutex_);
755 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
756 if (iterSupplier->second == nullptr) {
757 continue;
758 }
759 auto supplierType = iterSupplier->second->GetNetSupplierType();
760 if (bearerType == supplierType) {
761 netIdList.push_back(iterSupplier->second->GetNetId());
762 }
763 }
764 NETMGR_LOG_D("netSuppliers_ size[%{public}zd] networks_ size[%{public}zd]", netSuppliers_.size(), networks_.size());
765 return NETMANAGER_SUCCESS;
766 }
767
GetAllNets(std::list<int32_t> & netIdList)768 int32_t NetConnService::GetAllNets(std::list<int32_t> &netIdList)
769 {
770 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
771 return NETMANAGER_ERR_PERMISSION_DENIED;
772 }
773 std::lock_guard<std::mutex> locker(netManagerMutex_);
774 for (const auto &network : networks_) {
775 if (network.second != nullptr && network.second->IsConnected()) {
776 netIdList.push_back(network.second->GetNetId());
777 }
778 }
779 NETMGR_LOG_D("netSuppliers_ size[%{public}zd] netIdList size[%{public}zd]", netSuppliers_.size(), netIdList.size());
780 return NETMANAGER_SUCCESS;
781 }
782
GetSpecificUidNet(int32_t uid,int32_t & netId)783 int32_t NetConnService::GetSpecificUidNet(int32_t uid, int32_t &netId)
784 {
785 NETMGR_LOG_D("Enter GetSpecificUidNet, uid is [%{public}d].", uid);
786 netId = INVALID_NET_ID;
787 NET_SUPPLIER_MAP::iterator iterSupplier;
788 std::lock_guard<std::mutex> locker(netManagerMutex_);
789 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
790 if ((iterSupplier->second != nullptr) && (uid == iterSupplier->second->GetSupplierUid()) &&
791 (iterSupplier->second->GetNetSupplierType() == BEARER_VPN)) {
792 netId = iterSupplier->second->GetNetId();
793 return NETMANAGER_SUCCESS;
794 }
795 }
796 return GetDefaultNet(netId);
797 }
798
GetConnectionProperties(int32_t netId,NetLinkInfo & info)799 int32_t NetConnService::GetConnectionProperties(int32_t netId, NetLinkInfo &info)
800 {
801 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
802 return NETMANAGER_ERR_PERMISSION_DENIED;
803 }
804 std::lock_guard<std::mutex> locker(netManagerMutex_);
805 auto iterNetwork = networks_.find(netId);
806 if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
807 return NET_CONN_ERR_INVALID_NETWORK;
808 }
809
810 info = iterNetwork->second->GetNetLinkInfo();
811 return NETMANAGER_SUCCESS;
812 }
813
GetNetCapabilities(int32_t netId,NetAllCapabilities & netAllCap)814 int32_t NetConnService::GetNetCapabilities(int32_t netId, NetAllCapabilities &netAllCap)
815 {
816 if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
817 return NETMANAGER_ERR_PERMISSION_DENIED;
818 }
819 NET_SUPPLIER_MAP::iterator iterSupplier;
820 std::lock_guard<std::mutex> locker(netManagerMutex_);
821 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
822 if ((iterSupplier->second != nullptr) && (netId == iterSupplier->second->GetNetId())) {
823 netAllCap = iterSupplier->second->GetNetCapabilities();
824 return NETMANAGER_SUCCESS;
825 }
826 }
827 return NET_CONN_ERR_INVALID_NETWORK;
828 }
829
BindSocket(int32_t socket_fd,int32_t netId)830 int32_t NetConnService::BindSocket(int32_t socket_fd, int32_t netId)
831 {
832 NETMGR_LOG_D("Enter BindSocket.");
833 return NetsysController::GetInstance().BindSocket(socket_fd, netId);
834 }
835
RequestAllNetworkExceptDefault()836 void NetConnService::RequestAllNetworkExceptDefault()
837 {
838 if ((defaultNetSupplier_ == nullptr) || (defaultNetSupplier_->IsNetValidated())) {
839 return;
840 }
841 NETMGR_LOG_I("Default supplier[%{public}d, %{public}s] is not valid,request to activate another network",
842 defaultNetSupplier_->GetSupplierId(), defaultNetSupplier_->GetNetSupplierIdent().c_str());
843 if (defaultNetActivate_ == nullptr) {
844 NETMGR_LOG_E("Default net request is null");
845 return;
846 }
847 // Request activation of all networks except the default network
848 uint32_t reqId = defaultNetActivate_->GetRequestId();
849 for (const auto &netSupplier : netSuppliers_) {
850 if (netSupplier.second == nullptr || netSupplier.second == defaultNetSupplier_) {
851 continue;
852 }
853 if (netSupplier.second->GetNetScore() >= defaultNetSupplier_->GetNetScore()) {
854 continue;
855 }
856 if (!defaultNetActivate_->MatchRequestAndNetwork(netSupplier.second)) {
857 continue;
858 }
859 if (!netSupplier.second->RequestToConnect(reqId)) {
860 NETMGR_LOG_E("Request to connect failed");
861 }
862 }
863 }
864
NotFindBestSupplier(uint32_t reqId,const sptr<NetActivate> & active,const sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)865 void NetConnService::NotFindBestSupplier(uint32_t reqId, const sptr<NetActivate> &active,
866 const sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
867 {
868 if (supplier != nullptr) {
869 supplier->RemoveBestRequest(reqId);
870 if (callback != nullptr) {
871 sptr<NetHandle> netHandle = supplier->GetNetHandle();
872 callback->NetLost(netHandle);
873 }
874 }
875 if (active != nullptr) {
876 active->SetServiceSupply(nullptr);
877 SendRequestToAllNetwork(active);
878 }
879 }
880
FindBestNetworkForAllRequest()881 void NetConnService::FindBestNetworkForAllRequest()
882 {
883 NETMGR_LOG_I("FindBestNetworkForAllRequest Enter");
884 std::lock_guard<std::mutex> locker(netManagerMutex_);
885 NET_ACTIVATE_MAP::iterator iterActive;
886 sptr<NetSupplier> bestSupplier = nullptr;
887 for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
888 if (!iterActive->second) {
889 continue;
890 }
891 int score = static_cast<int>(FindBestNetworkForRequest(bestSupplier, iterActive->second));
892 NETMGR_LOG_D("bestSupplier is: [%{public}d, %{public}s]", bestSupplier ? bestSupplier->GetSupplierId() : 0,
893 bestSupplier ? bestSupplier->GetNetSupplierIdent().c_str() : "null");
894 if (iterActive->second == defaultNetActivate_) {
895 MakeDefaultNetWork(defaultNetSupplier_, bestSupplier);
896 }
897 sptr<NetSupplier> oldSupplier = iterActive->second->GetServiceSupply();
898 sptr<INetConnCallback> callback = iterActive->second->GetNetCallback();
899 if (!bestSupplier) {
900 // not found the bestNetwork
901 NotFindBestSupplier(iterActive->first, iterActive->second, oldSupplier, callback);
902 continue;
903 }
904
905 SendBestScoreAllNetwork(iterActive->first, score, bestSupplier->GetSupplierId());
906 if (bestSupplier == oldSupplier) {
907 continue;
908 }
909 if (oldSupplier) {
910 oldSupplier->RemoveBestRequest(iterActive->first);
911 }
912 iterActive->second->SetServiceSupply(bestSupplier);
913 CallbackForAvailable(bestSupplier, callback);
914 bestSupplier->SelectAsBestNetwork(iterActive->first);
915 }
916 }
917
FindBestNetworkForRequest(sptr<NetSupplier> & supplier,sptr<NetActivate> & netActivateNetwork)918 uint32_t NetConnService::FindBestNetworkForRequest(sptr<NetSupplier> &supplier, sptr<NetActivate> &netActivateNetwork)
919 {
920 int bestScore = 0;
921 supplier = nullptr;
922 if (netActivateNetwork == nullptr) {
923 NETMGR_LOG_E("netActivateNetwork is null");
924 return bestScore;
925 }
926 NETMGR_LOG_I("FindBestNetworkForRequest Enter, request is [%{public}s]",
927 netActivateNetwork->GetNetSpecifier() ? netActivateNetwork->GetNetSpecifier()->ToString(" ").c_str()
928 : "null");
929 NET_SUPPLIER_MAP::iterator iter;
930 for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
931 if (iter->second == nullptr) {
932 continue;
933 }
934 NETMGR_LOG_D("supplier info, supplier[%{public}d, %{public}s], realScore[%{public}d], isConnected[%{public}d]",
935 iter->second->GetSupplierId(), iter->second->GetNetSupplierIdent().c_str(),
936 iter->second->GetRealScore(), iter->second->IsConnected());
937 if ((!netActivateNetwork->MatchRequestAndNetwork(iter->second)) || (!iter->second->IsConnected())) {
938 NETMGR_LOG_D("supplier[%{public}d] is not connected or not match request.", iter->second->GetSupplierId());
939 continue;
940 }
941 int score = iter->second->GetRealScore();
942 if (score > bestScore) {
943 bestScore = score;
944 supplier = iter->second;
945 }
946 }
947 NETMGR_LOG_I("FindBestNetworkForRequest exit, bestScore[%{public}d], bestSupplier[%{public}d, %{public}s]",
948 bestScore, supplier ? supplier->GetSupplierId() : 0,
949 supplier ? supplier->GetNetSupplierIdent().c_str() : "null");
950 return bestScore;
951 }
952
SendAllRequestToNetwork(sptr<NetSupplier> supplier)953 void NetConnService::SendAllRequestToNetwork(sptr<NetSupplier> supplier)
954 {
955 NETMGR_LOG_I("SendAllRequestToNetwork.");
956 if (supplier == nullptr) {
957 NETMGR_LOG_E("supplier is null");
958 return;
959 }
960 NET_ACTIVATE_MAP::iterator iter;
961 std::lock_guard<std::mutex> locker(netManagerMutex_);
962 for (iter = netActivates_.begin(); iter != netActivates_.end(); ++iter) {
963 if (iter->second == nullptr) {
964 continue;
965 }
966 if (!iter->second->MatchRequestAndNetwork(supplier)) {
967 continue;
968 }
969 bool result = supplier->RequestToConnect(iter->first);
970 if (!result) {
971 NETMGR_LOG_E("connect supplier failed, result: %{public}d", result);
972 }
973 }
974 }
975
SendRequestToAllNetwork(sptr<NetActivate> request)976 void NetConnService::SendRequestToAllNetwork(sptr<NetActivate> request)
977 {
978 NETMGR_LOG_I("SendRequestToAllNetwork.");
979 if (request == nullptr) {
980 NETMGR_LOG_E("request is null");
981 return;
982 }
983
984 uint32_t reqId = request->GetRequestId();
985 NET_SUPPLIER_MAP::iterator iter;
986 for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
987 if (iter->second == nullptr) {
988 continue;
989 }
990 if (!request->MatchRequestAndNetwork(iter->second)) {
991 continue;
992 }
993 bool result = iter->second->RequestToConnect(reqId);
994 if (!result) {
995 NETMGR_LOG_E("connect service failed, result %{public}d", result);
996 }
997 }
998 }
999
SendBestScoreAllNetwork(uint32_t reqId,int32_t bestScore,uint32_t supplierId)1000 void NetConnService::SendBestScoreAllNetwork(uint32_t reqId, int32_t bestScore, uint32_t supplierId)
1001 {
1002 NETMGR_LOG_I("SendBestScoreAllNetwork Enter");
1003 NET_SUPPLIER_MAP::iterator iter;
1004 for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1005 if (iter->second == nullptr) {
1006 continue;
1007 }
1008 iter->second->ReceiveBestScore(reqId, bestScore, supplierId);
1009 }
1010 }
1011
CallbackForSupplier(sptr<NetSupplier> & supplier,CallbackType type)1012 void NetConnService::CallbackForSupplier(sptr<NetSupplier> &supplier, CallbackType type)
1013 {
1014 NETMGR_LOG_I("CallbackForSupplier Enter");
1015 if (supplier == nullptr) {
1016 return;
1017 }
1018 std::set<uint32_t> &bestReqList = supplier->GetBestRequestList();
1019 NETMGR_LOG_D("bestReqList size = %{public}zd", bestReqList.size());
1020 for (auto it : bestReqList) {
1021 auto reqIt = netActivates_.find(it);
1022 if ((reqIt == netActivates_.end()) || (reqIt->second == nullptr)) {
1023 NETMGR_LOG_D("netActivates_ not find reqId : %{public}d", it);
1024 continue;
1025 }
1026 sptr<INetConnCallback> callback = reqIt->second->GetNetCallback();
1027 if (!callback) {
1028 NETMGR_LOG_D("callback is nullptr");
1029 continue;
1030 }
1031
1032 sptr<NetHandle> netHandle = supplier->GetNetHandle();
1033 switch (type) {
1034 case CALL_TYPE_LOST: {
1035 callback->NetLost(netHandle);
1036 break;
1037 }
1038 case CALL_TYPE_UPDATE_CAP: {
1039 sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
1040 *pNetAllCap = supplier->GetNetCapabilities();
1041 callback->NetCapabilitiesChange(netHandle, pNetAllCap);
1042 break;
1043 }
1044 case CALL_TYPE_UPDATE_LINK: {
1045 sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
1046 auto network = supplier->GetNetwork();
1047 if (network != nullptr && pInfo != nullptr) {
1048 *pInfo = network->GetNetLinkInfo();
1049 }
1050 callback->NetConnectionPropertiesChange(netHandle, pInfo);
1051 break;
1052 }
1053 case CALL_TYPE_BLOCK_STATUS: {
1054 bool Metered = supplier->HasNetCap(NET_CAPABILITY_NOT_METERED);
1055 bool newBlocked = NetManagerCenter::GetInstance().IsUidNetAccess(supplier->GetSupplierUid(), Metered);
1056 callback->NetBlockStatusChange(netHandle, newBlocked);
1057 break;
1058 }
1059 default:
1060 break;
1061 }
1062 }
1063 }
1064
CallbackForAvailable(sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)1065 void NetConnService::CallbackForAvailable(sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
1066 {
1067 if (supplier == nullptr || callback == nullptr) {
1068 NETMGR_LOG_E("Input parameter is null.");
1069 return;
1070 }
1071 sptr<NetHandle> netHandle = supplier->GetNetHandle();
1072 callback->NetAvailable(netHandle);
1073 sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
1074 *pNetAllCap = supplier->GetNetCapabilities();
1075 callback->NetCapabilitiesChange(netHandle, pNetAllCap);
1076 sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
1077 auto network = supplier->GetNetwork();
1078 if (network != nullptr && pInfo != nullptr) {
1079 *pInfo = network->GetNetLinkInfo();
1080 }
1081 callback->NetConnectionPropertiesChange(netHandle, pInfo);
1082 }
1083
GetIfaceNames(NetBearType bearerType,std::list<std::string> & ifaceNames)1084 int32_t NetConnService::GetIfaceNames(NetBearType bearerType, std::list<std::string> &ifaceNames)
1085 {
1086 if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1087 return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1088 }
1089
1090 auto suppliers = GetNetSupplierFromList(bearerType);
1091 for (auto supplier : suppliers) {
1092 if (supplier == nullptr) {
1093 continue;
1094 }
1095 std::shared_ptr<Network> network = supplier->GetNetwork();
1096 if (network == nullptr) {
1097 continue;
1098 }
1099 std::string ifaceName = network->GetNetLinkInfo().ifaceName_;
1100 if (!ifaceName.empty()) {
1101 ifaceNames.push_back(ifaceName);
1102 }
1103 }
1104 return NETMANAGER_SUCCESS;
1105 }
1106
GetIfaceNameByType(NetBearType bearerType,const std::string & ident,std::string & ifaceName)1107 int32_t NetConnService::GetIfaceNameByType(NetBearType bearerType, const std::string &ident, std::string &ifaceName)
1108 {
1109 if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1110 NETMGR_LOG_E("netType parameter invalid");
1111 return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1112 }
1113
1114 auto suppliers = GetNetSupplierFromList(bearerType, ident);
1115 if (suppliers.empty()) {
1116 NETMGR_LOG_D("supplier is nullptr.");
1117 return NET_CONN_ERR_NO_SUPPLIER;
1118 }
1119 auto supplier = suppliers.front();
1120 std::shared_ptr<Network> network = supplier->GetNetwork();
1121 if (network == nullptr) {
1122 NETMGR_LOG_E("network is nullptr");
1123 return NET_CONN_ERR_INVALID_NETWORK;
1124 }
1125
1126 ifaceName = network->GetNetLinkInfo().ifaceName_;
1127
1128 return NETMANAGER_SUCCESS;
1129 }
1130
HandleDetectionResult(uint32_t supplierId,bool ifValid)1131 void NetConnService::HandleDetectionResult(uint32_t supplierId, bool ifValid)
1132 {
1133 NETMGR_LOG_I("Enter HandleDetectionResult, ifValid[%{public}d]", ifValid);
1134 auto supplier = FindNetSupplier(supplierId);
1135 if (supplier == nullptr) {
1136 NETMGR_LOG_E("supplier doesn't exist.");
1137 return;
1138 }
1139 supplier->SetNetValid(ifValid);
1140 std::unique_lock<std::mutex> locker(netManagerMutex_);
1141 CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
1142 locker.unlock();
1143 if (!netScore_->GetServiceScore(supplier)) {
1144 NETMGR_LOG_E("GetServiceScore fail.");
1145 return;
1146 }
1147 FindBestNetworkForAllRequest();
1148 if (!ifValid && defaultNetSupplier_ && defaultNetSupplier_->GetSupplierId() == supplierId) {
1149 RequestAllNetworkExceptDefault();
1150 }
1151 }
1152
SetAirplaneMode(bool state)1153 int32_t NetConnService::SetAirplaneMode(bool state)
1154 {
1155 if (!NetManagerPermission::CheckPermission(Permission::CONNECTIVITY_INTERNAL)) {
1156 return NETMANAGER_ERR_PERMISSION_DENIED;
1157 }
1158 BroadcastInfo info;
1159 info.action = EventFwk::CommonEventSupport::COMMON_EVENT_AIRPLANE_MODE_CHANGED;
1160 info.data = "Net Manager Airplane Mode Changed";
1161 info.code = static_cast<int32_t>(state);
1162 info.ordered = true;
1163 std::map<std::string, int32_t> param;
1164 DelayedSingleton<BroadcastManager>::GetInstance()->SendBroadcast(info, param);
1165 return NETMANAGER_SUCCESS;
1166 }
1167
Dump(int32_t fd,const std::vector<std::u16string> & args)1168 int32_t NetConnService::Dump(int32_t fd, const std::vector<std::u16string> &args)
1169 {
1170 NETMGR_LOG_D("Start Dump, fd: %{public}d", fd);
1171 std::string result;
1172 GetDumpMessage(result);
1173 int32_t ret = dprintf(fd, "%s\n", result.c_str());
1174 return ret < 0 ? static_cast<int32_t>(NET_CONN_ERR_CREATE_DUMP_FAILED)
1175 : static_cast<int32_t>(NETMANAGER_SUCCESS);
1176 }
1177
GetDumpMessage(std::string & message)1178 void NetConnService::GetDumpMessage(std::string &message)
1179 {
1180 message.append("Net connect Info:\n");
1181 if (defaultNetSupplier_) {
1182 message.append("\tSupplierId: " + std::to_string(defaultNetSupplier_->GetSupplierId()) + "\n");
1183 std::shared_ptr<Network> network = defaultNetSupplier_->GetNetwork();
1184 if (network) {
1185 message.append("\tNetId: " + std::to_string(network->GetNetId()) + "\n");
1186 } else {
1187 message.append("\tNetId: " + std::to_string(INVALID_NET_ID) + "\n");
1188 }
1189 message.append("\tConnStat: " + std::to_string(defaultNetSupplier_->IsConnected()) + "\n");
1190 message.append("\tIsAvailable: " + std::to_string(defaultNetSupplier_->IsNetValidated()) + "\n");
1191 message.append("\tIsRoaming: " + std::to_string(defaultNetSupplier_->GetRoaming()) + "\n");
1192 message.append("\tStrength: " + std::to_string(defaultNetSupplier_->GetStrength()) + "\n");
1193 message.append("\tFrequency: " + std::to_string(defaultNetSupplier_->GetFrequency()) + "\n");
1194 message.append("\tLinkUpBandwidthKbps: " +
1195 std::to_string(defaultNetSupplier_->GetNetCapabilities().linkUpBandwidthKbps_) + "\n");
1196 message.append("\tLinkDownBandwidthKbps: " +
1197 std::to_string(defaultNetSupplier_->GetNetCapabilities().linkDownBandwidthKbps_) + "\n");
1198 message.append("\tUid: " + std::to_string(defaultNetSupplier_->GetSupplierUid()) + "\n");
1199 } else {
1200 message.append("\tdefaultNetSupplier_ is nullptr\n");
1201 message.append("\tSupplierId: \n");
1202 message.append("\tNetId: 0\n");
1203 message.append("\tConnStat: 0\n");
1204 message.append("\tIsAvailable: \n");
1205 message.append("\tIsRoaming: 0\n");
1206 message.append("\tStrength: 0\n");
1207 message.append("\tFrequency: 0\n");
1208 message.append("\tLinkUpBandwidthKbps: 0\n");
1209 message.append("\tLinkDownBandwidthKbps: 0\n");
1210 message.append("\tUid: 0\n");
1211 }
1212 }
1213
SetGlobalHttpProxy(const HttpProxy & httpProxy)1214 int32_t NetConnService::SetGlobalHttpProxy(const HttpProxy &httpProxy)
1215 {
1216 if (!NetManagerPermission::CheckPermission(Permission::CONNECTIVITY_INTERNAL)) {
1217 return NETMANAGER_ERR_PERMISSION_DENIED;
1218 }
1219 if (httpProxy_.GetHost() != httpProxy.GetHost() || httpProxy_.GetPort() != httpProxy.GetPort() ||
1220 httpProxy_.GetExclusionList() != httpProxy.GetExclusionList()) {
1221 httpProxy_ = httpProxy;
1222 SendGlobalHttpProxyChangeBroadcast();
1223 std::lock_guard<std::mutex> locker(netManagerMutex_);
1224 NetHttpProxyTracker httpProxyTracker;
1225 if (!httpProxyTracker.WriteToSystemParameter(httpProxy_)) {
1226 NETMGR_LOG_E("Write http proxy to system parameter failed");
1227 }
1228 }
1229 return NETMANAGER_SUCCESS;
1230 }
1231
SendGlobalHttpProxyChangeBroadcast()1232 void NetConnService::SendGlobalHttpProxyChangeBroadcast()
1233 {
1234 BroadcastInfo info;
1235 info.action = EventFwk::CommonEventSupport::COMMON_EVENT_HTTP_PROXY_CHANGE;
1236 info.data = "Global HttpProxy Changed";
1237 info.ordered = true;
1238 std::map<std::string, std::string> param = {{"HttpProxy", httpProxy_.ToString()}};
1239 DelayedSingleton<BroadcastManager>::GetInstance()->SendBroadcast(info, param);
1240 }
1241
GetGlobalHttpProxy(HttpProxy & httpProxy)1242 int32_t NetConnService::GetGlobalHttpProxy(HttpProxy &httpProxy)
1243 {
1244 std::lock_guard<std::mutex> locker(netManagerMutex_);
1245 if (httpProxy_.GetHost().empty()) {
1246 httpProxy.SetPort(0);
1247 NETMGR_LOG_E("The http proxy host is empty");
1248 return NET_CONN_ERR_NO_HTTP_PROXY;
1249 }
1250 httpProxy = httpProxy_;
1251 return NETMANAGER_SUCCESS;
1252 }
1253
GetNetIdByIdentifier(const std::string & ident,int32_t & netId)1254 int32_t NetConnService::GetNetIdByIdentifier(const std::string &ident, int32_t &netId)
1255 {
1256 if (ident.empty()) {
1257 NETMGR_LOG_E("The identifier in service is null");
1258 return NETMANAGER_ERR_INVALID_PARAMETER;
1259 }
1260 for (auto iterSupplier : netSuppliers_) {
1261 if (iterSupplier.second == nullptr) {
1262 continue;
1263 }
1264 if (iterSupplier.second->GetNetSupplierIdent() == ident) {
1265 netId = iterSupplier.second->GetNetId();
1266 break;
1267 }
1268 }
1269 return NETMANAGER_SUCCESS;
1270 }
1271
SetAppNet(int32_t netId)1272 int32_t NetConnService::SetAppNet(int32_t netId)
1273 {
1274 if (!NetManagerPermission::CheckPermission(Permission::INTERNET)) {
1275 return NETMANAGER_ERR_PERMISSION_DENIED;
1276 }
1277
1278 return NETMANAGER_SUCCESS;
1279 }
1280 } // namespace NetManagerStandard
1281 } // namespace OHOS
1282