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 <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_datashare_utils.h"
27 #include "net_http_proxy_tracker.h"
28 #include "net_manager_center.h"
29 #include "net_manager_constants.h"
30 #include "net_mgr_log_wrapper.h"
31 #include "net_supplier.h"
32 #include "netmanager_base_permission.h"
33 #include "netsys_controller.h"
34
35 namespace OHOS {
36 namespace NetManagerStandard {
37 namespace {
38 constexpr uint32_t MAX_REQUEST_NUM = 2000;
39 // hisysevent error messgae
40 constexpr const char *ERROR_MSG_NULL_SUPPLIER_INFO = "Net supplier info is nullptr";
41 constexpr const char *ERROR_MSG_NULL_NET_LINK_INFO = "Net link info is nullptr";
42 constexpr const char *ERROR_MSG_NULL_NET_SPECIFIER = "The parameter of netSpecifier or callback is null";
43 constexpr const char *ERROR_MSG_CAN_NOT_FIND_SUPPLIER = "Can not find supplier by id:";
44 constexpr const char *ERROR_MSG_UPDATE_NETLINK_INFO_FAILED = "Update net link info failed";
45 constexpr const char *NET_CONN_MANAGER_WORK_THREAD = "NET_CONN_MANAGER_WORK_THREAD";
46 constexpr const char *NET_ACTIVATE_WORK_THREAD = "NET_ACTIVATE_WORK_THREAD";
47 } // namespace
48
49 const bool REGISTER_LOCAL_RESULT =
50 SystemAbility::MakeAndRegisterAbility(NetConnService::GetInstance().get());
51
NetConnService()52 NetConnService::NetConnService()
53 : SystemAbility(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID, true), registerToService_(false), state_(STATE_STOPPED)
54 {
55 netActEventRunner_ = AppExecFwk::EventRunner::Create(NET_ACTIVATE_WORK_THREAD);
56 netActEventHandler_ = std::make_shared<AppExecFwk::EventHandler>(netActEventRunner_);
57 CreateDefaultRequest();
58 }
59
~NetConnService()60 NetConnService::~NetConnService() {}
61
OnStart()62 void NetConnService::OnStart()
63 {
64 struct timeval tv;
65 gettimeofday(&tv, nullptr);
66 NETMGR_LOG_D("NetConnService::OnStart begin");
67 if (state_ == STATE_RUNNING) {
68 NETMGR_LOG_D("the state is already running");
69 return;
70 }
71 if (!Init()) {
72 NETMGR_LOG_E("init failed");
73 return;
74 }
75 state_ = STATE_RUNNING;
76 gettimeofday(&tv, nullptr);
77 NETMGR_LOG_D("NetConnService::OnStart end");
78 }
79
CreateDefaultRequest()80 void NetConnService::CreateDefaultRequest()
81 {
82 if (!defaultNetActivate_) {
83 defaultNetSpecifier_ = (std::make_unique<NetSpecifier>()).release();
84 defaultNetSpecifier_->SetCapability(NET_CAPABILITY_INTERNET);
85 std::weak_ptr<INetActivateCallback> timeoutCb;
86 defaultNetActivate_ =
87 std::make_shared<NetActivate>(defaultNetSpecifier_, nullptr, timeoutCb, 0, netActEventHandler_);
88 defaultNetActivate_->StartTimeOutNetAvailable();
89 defaultNetActivate_->SetRequestId(DEFAULT_REQUEST_ID);
90 netActivates_[DEFAULT_REQUEST_ID] = defaultNetActivate_;
91 }
92 }
93
OnStop()94 void NetConnService::OnStop()
95 {
96 NETMGR_LOG_D("NetConnService::OnStop begin");
97 if (netConnEventRunner_) {
98 netConnEventRunner_->Stop();
99 netConnEventRunner_.reset();
100 }
101 if (netConnEventHandler_) {
102 netConnEventHandler_.reset();
103 }
104 state_ = STATE_STOPPED;
105 registerToService_ = false;
106 NETMGR_LOG_D("NetConnService::OnStop end");
107 }
108
Init()109 bool NetConnService::Init()
110 {
111 if (!REGISTER_LOCAL_RESULT) {
112 NETMGR_LOG_E("Register to local sa manager failed");
113 registerToService_ = false;
114 return false;
115 }
116 if (!registerToService_) {
117 if (!Publish(NetConnService::GetInstance().get())) {
118 NETMGR_LOG_E("Register to sa manager failed");
119 return false;
120 }
121 registerToService_ = true;
122 }
123 netConnEventRunner_ = AppExecFwk::EventRunner::Create(NET_CONN_MANAGER_WORK_THREAD);
124 if (netConnEventRunner_ == nullptr) {
125 NETMGR_LOG_E("Create event runner failed.");
126 return false;
127 }
128 netConnEventHandler_ = std::make_shared<NetConnEventHandler>(netConnEventRunner_);
129 serviceIface_ = std::make_unique<NetConnServiceIface>().release();
130 NetManagerCenter::GetInstance().RegisterConnService(serviceIface_);
131 netScore_ = std::make_unique<NetScore>();
132 if (netScore_ == nullptr) {
133 NETMGR_LOG_E("Make NetScore failed");
134 return false;
135 }
136
137 interfaceStateCallback_ = new (std::nothrow) NetInterfaceStateCallback();
138 if (interfaceStateCallback_) {
139 NetsysController::GetInstance().RegisterCallback(interfaceStateCallback_);
140 }
141 return true;
142 }
143
SystemReady()144 int32_t NetConnService::SystemReady()
145 {
146 NETMGR_LOG_D("System ready.");
147 return NETMANAGER_SUCCESS;
148 }
149
150 // Do not post into event handler, because this interface should have good performance
SetInternetPermission(uint32_t uid,uint8_t allow)151 int32_t NetConnService::SetInternetPermission(uint32_t uid, uint8_t allow)
152 {
153 return NetsysController::GetInstance().SetInternetPermission(uid, allow);
154 }
155
RegisterNetSupplier(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps,uint32_t & supplierId)156 int32_t NetConnService::RegisterNetSupplier(NetBearType bearerType, const std::string &ident,
157 const std::set<NetCap> &netCaps, uint32_t &supplierId)
158 {
159 int32_t result = NETMANAGER_ERROR;
160 if (netConnEventHandler_) {
161 netConnEventHandler_->PostSyncTask([this, bearerType, &ident, &netCaps, &supplierId, &result]() {
162 result = this->RegisterNetSupplierAsync(bearerType, ident, netCaps, supplierId);
163 });
164 }
165 return result;
166 }
167
RegisterNetSupplierCallback(uint32_t supplierId,const sptr<INetSupplierCallback> & callback)168 int32_t NetConnService::RegisterNetSupplierCallback(uint32_t supplierId, const sptr<INetSupplierCallback> &callback)
169 {
170 int32_t result = NETMANAGER_ERROR;
171 if (netConnEventHandler_) {
172 netConnEventHandler_->PostSyncTask([this, supplierId, &callback, &result]() {
173 result = this->RegisterNetSupplierCallbackAsync(supplierId, callback);
174 });
175 }
176 return result;
177 }
178
RegisterNetConnCallback(const sptr<INetConnCallback> & callback)179 int32_t NetConnService::RegisterNetConnCallback(const sptr<INetConnCallback> &callback)
180 {
181 NETMGR_LOG_D("RegisterNetConnCallback service in.");
182 return RegisterNetConnCallback(defaultNetSpecifier_, callback, 0);
183 }
184
RegisterNetConnCallback(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS)185 int32_t NetConnService::RegisterNetConnCallback(const sptr<NetSpecifier> &netSpecifier,
186 const sptr<INetConnCallback> &callback, const uint32_t &timeoutMS)
187 {
188 int32_t result = NETMANAGER_ERROR;
189 if (netConnEventHandler_) {
190 netConnEventHandler_->PostSyncTask([this, &netSpecifier, &callback, timeoutMS, &result]() {
191 result = this->RegisterNetConnCallbackAsync(netSpecifier, callback, timeoutMS);
192 });
193 }
194 return result;
195 }
196
RegisterNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback)197 int32_t NetConnService::RegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback)
198 {
199 NETMGR_LOG_D("Enter NetConnService::RegisterNetDetectionCallback");
200 return RegUnRegNetDetectionCallback(netId, callback, true);
201 }
202
UnregisterNetSupplier(uint32_t supplierId)203 int32_t NetConnService::UnregisterNetSupplier(uint32_t supplierId)
204 {
205 int32_t result = NETMANAGER_ERROR;
206 if (netConnEventHandler_) {
207 netConnEventHandler_->PostSyncTask(
208 [this, supplierId, &result]() { result = this->UnregisterNetSupplierAsync(supplierId); });
209 }
210 return result;
211 }
212
UnregisterNetConnCallback(const sptr<INetConnCallback> & callback)213 int32_t NetConnService::UnregisterNetConnCallback(const sptr<INetConnCallback> &callback)
214 {
215 int32_t result = NETMANAGER_ERROR;
216 if (netConnEventHandler_) {
217 netConnEventHandler_->PostSyncTask(
218 [this, &callback, &result]() { result = this->UnregisterNetConnCallbackAsync(callback); });
219 }
220 return result;
221 }
222
UnRegisterNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback)223 int32_t NetConnService::UnRegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback)
224 {
225 NETMGR_LOG_D("Enter NetConnService::UnRegisterNetDetectionCallback");
226 return RegUnRegNetDetectionCallback(netId, callback, false);
227 }
228
RegUnRegNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback,bool isReg)229 int32_t NetConnService::RegUnRegNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback,
230 bool isReg)
231 {
232 int32_t result = NETMANAGER_ERROR;
233 if (netConnEventHandler_) {
234 netConnEventHandler_->PostSyncTask([this, netId, &callback, isReg, &result]() {
235 result = this->RegUnRegNetDetectionCallbackAsync(netId, callback, isReg);
236 });
237 }
238 return result;
239 }
240
UpdateNetStateForTest(const sptr<NetSpecifier> & netSpecifier,int32_t netState)241 int32_t NetConnService::UpdateNetStateForTest(const sptr<NetSpecifier> &netSpecifier, int32_t netState)
242 {
243 int32_t result = NETMANAGER_ERROR;
244 if (netConnEventHandler_) {
245 netConnEventHandler_->PostSyncTask([this, &netSpecifier, netState, &result]() {
246 result = this->UpdateNetStateForTestAsync(netSpecifier, netState);
247 });
248 }
249 return result;
250 }
251
UpdateNetSupplierInfo(uint32_t supplierId,const sptr<NetSupplierInfo> & netSupplierInfo)252 int32_t NetConnService::UpdateNetSupplierInfo(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo)
253 {
254 int32_t result = NETMANAGER_ERROR;
255 if (netConnEventHandler_) {
256 netConnEventHandler_->PostSyncTask([this, supplierId, &netSupplierInfo, &result]() {
257 result = this->UpdateNetSupplierInfoAsync(supplierId, netSupplierInfo);
258 });
259 }
260 return result;
261 }
262
UpdateNetLinkInfo(uint32_t supplierId,const sptr<NetLinkInfo> & netLinkInfo)263 int32_t NetConnService::UpdateNetLinkInfo(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo)
264 {
265 int32_t result = NETMANAGER_ERROR;
266 if (netConnEventHandler_) {
267 netConnEventHandler_->PostSyncTask([this, supplierId, &netLinkInfo, &result]() {
268 result = this->UpdateNetLinkInfoAsync(supplierId, netLinkInfo);
269 });
270 }
271 return result;
272 }
273
NetDetection(int32_t netId)274 int32_t NetConnService::NetDetection(int32_t netId)
275 {
276 int32_t result = NETMANAGER_ERROR;
277 if (netConnEventHandler_) {
278 netConnEventHandler_->PostSyncTask([this, netId, &result]() { result = this->NetDetectionAsync(netId); });
279 }
280 return result;
281 }
282
RestrictBackgroundChanged(bool restrictBackground)283 int32_t NetConnService::RestrictBackgroundChanged(bool restrictBackground)
284 {
285 int32_t result = NETMANAGER_ERROR;
286 if (netConnEventHandler_) {
287 netConnEventHandler_->PostSyncTask([this, restrictBackground, &result]() {
288 result = this->RestrictBackgroundChangedAsync(restrictBackground);
289 });
290 }
291 return result;
292 }
293
RegisterNetSupplierAsync(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps,uint32_t & supplierId)294 int32_t NetConnService::RegisterNetSupplierAsync(NetBearType bearerType, const std::string &ident,
295 const std::set<NetCap> &netCaps, uint32_t &supplierId)
296 {
297 NETMGR_LOG_I("RegisterNetSupplier service in, bearerType[%{public}u], ident[%{public}s]",
298 static_cast<uint32_t>(bearerType), ident.c_str());
299 // If there is no supplier in the list, create a supplier
300 if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
301 NETMGR_LOG_E("netType parameter invalid");
302 return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
303 }
304 sptr<NetSupplier> supplier = GetNetSupplierFromList(bearerType, ident, netCaps);
305 if (supplier != nullptr) {
306 NETMGR_LOG_E("Supplier[%{public}d %{public}s] already exists.", supplier->GetSupplierId(), ident.c_str());
307 supplierId = supplier->GetSupplierId();
308 return NETMANAGER_SUCCESS;
309 }
310 // If there is no supplier in the list, create a supplier
311 supplier = (std::make_unique<NetSupplier>(bearerType, ident, netCaps)).release();
312 if (supplier == nullptr) {
313 NETMGR_LOG_E("supplier is nullptr");
314 return NET_CONN_ERR_NO_SUPPLIER;
315 }
316 supplierId = supplier->GetSupplierId();
317 if (!netScore_->GetServiceScore(supplier)) {
318 NETMGR_LOG_E("GetServiceScore fail.");
319 }
320 // create network
321 int32_t netId = GenerateNetId();
322 NETMGR_LOG_D("GenerateNetId is: [%{public}d]", netId);
323 if (netId == INVALID_NET_ID) {
324 NETMGR_LOG_E("GenerateNetId fail");
325 return NET_CONN_ERR_INVALID_NETWORK;
326 }
327 std::shared_ptr<Network> network = std::make_shared<Network>(
328 netId, supplierId,
329 std::bind(&NetConnService::HandleDetectionResult, shared_from_this(),
330 std::placeholders::_1, std::placeholders::_2),
331 bearerType, netConnEventHandler_);
332 supplier->SetNetwork(network);
333 supplier->SetNetValid(true);
334 // save supplier
335 std::unique_lock<std::mutex> locker(netManagerMutex_);
336 netSuppliers_[supplierId] = supplier;
337 networks_[netId] = network;
338 locker.unlock();
339 struct EventInfo eventInfo = {.netId = netId, .bearerType = bearerType, .ident = ident, .supplierId = supplierId};
340 EventReport::SendSupplierBehaviorEvent(eventInfo);
341 NETMGR_LOG_I("RegisterNetSupplier service out, supplier[%{public}d %{public}s] netId[%{public}d]", supplierId,
342 ident.c_str(), netId);
343 return NETMANAGER_SUCCESS;
344 }
345
RegisterNetSupplierCallbackAsync(uint32_t supplierId,const sptr<INetSupplierCallback> & callback)346 int32_t NetConnService::RegisterNetSupplierCallbackAsync(uint32_t supplierId,
347 const sptr<INetSupplierCallback> &callback)
348 {
349 NETMGR_LOG_I("RegisterNetSupplierCallback service in, supplierId[%{public}d]", supplierId);
350 if (callback == nullptr) {
351 NETMGR_LOG_E("The parameter callback is null");
352 return NETMANAGER_ERR_LOCAL_PTR_NULL;
353 }
354 auto supplier = FindNetSupplier(supplierId);
355 if (supplier == nullptr) {
356 NETMGR_LOG_E("supplier doesn't exist.");
357 return NET_CONN_ERR_NO_SUPPLIER;
358 }
359 supplier->RegisterSupplierCallback(callback);
360 SendAllRequestToNetwork(supplier);
361 NETMGR_LOG_I("RegisterNetSupplierCallback service out");
362 return NETMANAGER_SUCCESS;
363 }
364
RegisterNetConnCallbackAsync(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS)365 int32_t NetConnService::RegisterNetConnCallbackAsync(const sptr<NetSpecifier> &netSpecifier,
366 const sptr<INetConnCallback> &callback, const uint32_t &timeoutMS)
367 {
368 NETMGR_LOG_I("Register net connect callback async");
369 if (netSpecifier == nullptr || callback == nullptr) {
370 NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
371 struct EventInfo eventInfo = {.errorType = static_cast<int32_t>(FAULT_INVALID_PARAMETER),
372 .errorMsg = ERROR_MSG_NULL_NET_SPECIFIER};
373 EventReport::SendRequestFaultEvent(eventInfo);
374 return NETMANAGER_ERR_LOCAL_PTR_NULL;
375 }
376 if (netActivates_.size() >= MAX_REQUEST_NUM) {
377 NETMGR_LOG_E("Over the max request number");
378 return NET_CONN_ERR_NET_OVER_MAX_REQUEST_NUM;
379 }
380 uint32_t reqId = 0;
381 if (FindSameCallback(callback, reqId)) {
382 NETMGR_LOG_E("RegisterNetConnCallback find same callback");
383 return NET_CONN_ERR_SAME_CALLBACK;
384 }
385 return ActivateNetwork(netSpecifier, callback, timeoutMS);
386 }
387
UnregisterNetSupplierAsync(uint32_t supplierId)388 int32_t NetConnService::UnregisterNetSupplierAsync(uint32_t supplierId)
389 {
390 NETMGR_LOG_I("UnregisterNetSupplier service in, supplierId[%{public}d]", supplierId);
391 // Remove supplier from the list based on supplierId
392 auto supplier = FindNetSupplier(supplierId);
393 if (supplier == nullptr) {
394 NETMGR_LOG_E("supplier doesn't exist.");
395 return NET_CONN_ERR_NO_SUPPLIER;
396 }
397 NETMGR_LOG_I("Unregister supplier[%{public}d, %{public}s], defaultNetSupplier[%{public}d], %{public}s]",
398 supplier->GetSupplierId(), supplier->GetNetSupplierIdent().c_str(),
399 defaultNetSupplier_ ? defaultNetSupplier_->GetSupplierId() : 0,
400 defaultNetSupplier_ ? defaultNetSupplier_->GetNetSupplierIdent().c_str() : "null");
401
402 struct EventInfo eventInfo = {.bearerType = supplier->GetNetSupplierType(),
403 .ident = supplier->GetNetSupplierIdent(),
404 .supplierId = supplier->GetSupplierId()};
405 EventReport::SendSupplierBehaviorEvent(eventInfo);
406
407 int32_t netId = supplier->GetNetId();
408 NET_NETWORK_MAP::iterator iterNetwork = networks_.find(netId);
409 if (iterNetwork != networks_.end()) {
410 std::unique_lock<std::mutex> locker(netManagerMutex_);
411 networks_.erase(iterNetwork);
412 locker.unlock();
413 }
414 if (defaultNetSupplier_ == supplier) {
415 NETMGR_LOG_I("Set default net supplier to nullptr.");
416 sptr<NetSupplier> newSupplier = nullptr;
417 MakeDefaultNetWork(defaultNetSupplier_, newSupplier);
418 }
419 NetSupplierInfo info;
420 supplier->UpdateNetSupplierInfo(info);
421 std::unique_lock<std::mutex> locker(netManagerMutex_);
422 netSuppliers_.erase(supplierId);
423 locker.unlock();
424 FindBestNetworkForAllRequest();
425 NETMGR_LOG_I("UnregisterNetSupplier supplierId[%{public}d] out", supplierId);
426 return NETMANAGER_SUCCESS;
427 }
428
UnregisterNetConnCallbackAsync(const sptr<INetConnCallback> & callback)429 int32_t NetConnService::UnregisterNetConnCallbackAsync(const sptr<INetConnCallback> &callback)
430 {
431 NETMGR_LOG_I("UnregisterNetConnCallback Enter");
432 if (callback == nullptr) {
433 NETMGR_LOG_E("callback is null");
434 return NETMANAGER_ERR_LOCAL_PTR_NULL;
435 }
436 uint32_t reqId = 0;
437 if (!FindSameCallback(callback, reqId)) {
438 NETMGR_LOG_D("UnregisterNetConnCallback can not find same callback");
439 return NET_CONN_ERR_CALLBACK_NOT_FOUND;
440 }
441 NET_ACTIVATE_MAP::iterator iterActive;
442 for (iterActive = netActivates_.begin(); iterActive != netActivates_.end();) {
443 if (!iterActive->second) {
444 ++iterActive;
445 continue;
446 }
447 sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
448 if (saveCallback == nullptr) {
449 ++iterActive;
450 continue;
451 }
452 if (callback->AsObject().GetRefPtr() != saveCallback->AsObject().GetRefPtr()) {
453 ++iterActive;
454 continue;
455 }
456 reqId = iterActive->first;
457 auto netActivate = iterActive->second;
458 if (netActivate) {
459 sptr<NetSupplier> supplier = netActivate->GetServiceSupply();
460 if (supplier) {
461 supplier->CancelRequest(reqId);
462 }
463 }
464 NET_SUPPLIER_MAP::iterator iterSupplier;
465 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
466 if (iterSupplier->second != nullptr) {
467 iterSupplier->second->CancelRequest(reqId);
468 }
469 }
470 iterActive = netActivates_.erase(iterActive);
471 }
472 return NETMANAGER_SUCCESS;
473 }
474
RegUnRegNetDetectionCallbackAsync(int32_t netId,const sptr<INetDetectionCallback> & callback,bool isReg)475 int32_t NetConnService::RegUnRegNetDetectionCallbackAsync(int32_t netId, const sptr<INetDetectionCallback> &callback,
476 bool isReg)
477 {
478 NETMGR_LOG_D("Enter NetConnService::RegUnRegNetDetectionCallback");
479 if (callback == nullptr) {
480 NETMGR_LOG_E("The parameter of callback is null");
481 return NETMANAGER_ERR_LOCAL_PTR_NULL;
482 }
483
484 auto iterNetwork = networks_.find(netId);
485 if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
486 NETMGR_LOG_E("Could not find the corresponding network.");
487 return NET_CONN_ERR_NETID_NOT_FOUND;
488 }
489 if (isReg) {
490 iterNetwork->second->RegisterNetDetectionCallback(callback);
491 return NETMANAGER_SUCCESS;
492 }
493 return iterNetwork->second->UnRegisterNetDetectionCallback(callback);
494 }
495
UpdateNetStateForTestAsync(const sptr<NetSpecifier> & netSpecifier,int32_t netState)496 int32_t NetConnService::UpdateNetStateForTestAsync(const sptr<NetSpecifier> &netSpecifier, int32_t netState)
497 {
498 NETMGR_LOG_D("Test NetConnService::UpdateNetStateForTest(), begin");
499 if (netSpecifier == nullptr) {
500 NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
501 return NETMANAGER_ERR_LOCAL_PTR_NULL;
502 }
503 return NETMANAGER_SUCCESS;
504 }
505
UpdateNetSupplierInfoAsync(uint32_t supplierId,const sptr<NetSupplierInfo> & netSupplierInfo)506 int32_t NetConnService::UpdateNetSupplierInfoAsync(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo)
507 {
508 NETMGR_LOG_I("UpdateNetSupplierInfo service in. supplierId[%{public}d]", supplierId);
509 struct EventInfo eventInfo = {.updateSupplierId = supplierId};
510 if (netSupplierInfo == nullptr) {
511 NETMGR_LOG_E("netSupplierInfo is nullptr");
512 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_SUPPLIERINFO_INV_PARAM);
513 eventInfo.errorMsg = ERROR_MSG_NULL_SUPPLIER_INFO;
514 EventReport::SendSupplierFaultEvent(eventInfo);
515 return NETMANAGER_ERR_PARAMETER_ERROR;
516 }
517 eventInfo.supplierInfo = netSupplierInfo->ToString(" ");
518 EventReport::SendSupplierBehaviorEvent(eventInfo);
519
520 auto supplier = FindNetSupplier(supplierId);
521 if (supplier == nullptr) {
522 NETMGR_LOG_E("Can not find supplier for supplierId[%{public}d]", supplierId);
523 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_SUPPLIERINFO_INV_PARAM);
524 eventInfo.errorMsg = std::string(ERROR_MSG_CAN_NOT_FIND_SUPPLIER).append(std::to_string(supplierId));
525 EventReport::SendSupplierFaultEvent(eventInfo);
526 return NET_CONN_ERR_NO_SUPPLIER;
527 }
528 NETMGR_LOG_I("Update supplier[%{public}d, %{public}s], supplierInfo:[ %{public}s ]", supplierId,
529 supplier->GetNetSupplierIdent().c_str(), netSupplierInfo->ToString(" ").c_str());
530
531 supplier->UpdateNetSupplierInfo(*netSupplierInfo);
532 if (!netSupplierInfo->isAvailable_) {
533 CallbackForSupplier(supplier, CALL_TYPE_LOST);
534 } else {
535 CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
536 }
537 if (!netScore_->GetServiceScore(supplier)) {
538 NETMGR_LOG_E("GetServiceScore fail.");
539 }
540 FindBestNetworkForAllRequest();
541 NETMGR_LOG_I("UpdateNetSupplierInfo service out.");
542 return NETMANAGER_SUCCESS;
543 }
544
UpdateNetLinkInfoAsync(uint32_t supplierId,const sptr<NetLinkInfo> & netLinkInfo)545 int32_t NetConnService::UpdateNetLinkInfoAsync(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo)
546 {
547 NETMGR_LOG_I("UpdateNetLinkInfo service in. supplierId[%{public}d]", supplierId);
548 struct EventInfo eventInfo = {.updateNetlinkId = supplierId};
549
550 if (netLinkInfo == nullptr) {
551 NETMGR_LOG_E("netLinkInfo is nullptr");
552 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_INV_PARAM);
553 eventInfo.errorMsg = ERROR_MSG_NULL_NET_LINK_INFO;
554 EventReport::SendSupplierFaultEvent(eventInfo);
555 return NETMANAGER_ERR_PARAMETER_ERROR;
556 }
557 eventInfo.netlinkInfo = netLinkInfo->ToString(" ");
558 EventReport::SendSupplierBehaviorEvent(eventInfo);
559
560 auto supplier = FindNetSupplier(supplierId);
561 if (supplier == nullptr) {
562 NETMGR_LOG_E("supplier is nullptr");
563 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_INV_PARAM);
564 eventInfo.errorMsg = std::string(ERROR_MSG_CAN_NOT_FIND_SUPPLIER).append(std::to_string(supplierId));
565 EventReport::SendSupplierFaultEvent(eventInfo);
566 return NET_CONN_ERR_NO_SUPPLIER;
567 }
568
569 HttpProxy oldHttpProxy;
570 supplier->GetHttpProxy(oldHttpProxy);
571 // According to supplier id, get network from the list
572 std::unique_lock<std::mutex> locker(netManagerMutex_);
573 if (supplier->UpdateNetLinkInfo(*netLinkInfo) != NETMANAGER_SUCCESS) {
574 NETMGR_LOG_E("UpdateNetLinkInfo fail");
575 eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_FAILED);
576 eventInfo.errorMsg = ERROR_MSG_UPDATE_NETLINK_INFO_FAILED;
577 EventReport::SendSupplierFaultEvent(eventInfo);
578 return NET_CONN_ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL;
579 }
580 locker.unlock();
581 if (oldHttpProxy != netLinkInfo->httpProxy_) {
582 SendHttpProxyChangeBroadcast(netLinkInfo->httpProxy_);
583 }
584
585 CallbackForSupplier(supplier, CALL_TYPE_UPDATE_LINK);
586 if (!netScore_->GetServiceScore(supplier)) {
587 NETMGR_LOG_E("GetServiceScore fail.");
588 }
589 FindBestNetworkForAllRequest();
590 NETMGR_LOG_I("UpdateNetLinkInfo service out.");
591 return NETMANAGER_SUCCESS;
592 }
593
NetDetectionAsync(int32_t netId)594 int32_t NetConnService::NetDetectionAsync(int32_t netId)
595 {
596 NETMGR_LOG_D("Enter NetConnService::NetDetection");
597 auto iterNetwork = networks_.find(netId);
598 if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
599 NETMGR_LOG_E("Could not find the corresponding network.");
600 return NET_CONN_ERR_NETID_NOT_FOUND;
601 }
602 iterNetwork->second->StartNetDetection(true);
603 return NETMANAGER_SUCCESS;
604 }
605
RestrictBackgroundChangedAsync(bool restrictBackground)606 int32_t NetConnService::RestrictBackgroundChangedAsync(bool restrictBackground)
607 {
608 NETMGR_LOG_D("Restrict background changed, background = %{public}d", restrictBackground);
609 for (auto it = netSuppliers_.begin(); it != netSuppliers_.end(); ++it) {
610 if (it->second == nullptr) {
611 continue;
612 }
613
614 if (it->second->GetRestrictBackground() == restrictBackground) {
615 NETMGR_LOG_D("it->second->GetRestrictBackground() == restrictBackground");
616 return NET_CONN_ERR_NET_NO_RESTRICT_BACKGROUND;
617 }
618
619 if (it->second->GetNetSupplierType() == BEARER_VPN) {
620 CallbackForSupplier(it->second, CALL_TYPE_BLOCK_STATUS);
621 }
622 it->second->SetRestrictBackground(restrictBackground);
623 }
624 return NETMANAGER_SUCCESS;
625 }
626
SendHttpProxyChangeBroadcast(const HttpProxy & httpProxy)627 void NetConnService::SendHttpProxyChangeBroadcast(const HttpProxy &httpProxy)
628 {
629 BroadcastInfo info;
630 info.action = EventFwk::CommonEventSupport::COMMON_EVENT_HTTP_PROXY_CHANGE;
631 info.data = "Global HttpProxy Changed";
632 info.ordered = true;
633 std::map<std::string, std::string> param = {{"HttpProxy", httpProxy.ToString()}};
634 BroadcastManager::GetInstance().SendBroadcast(info, param);
635 }
636
ActivateNetwork(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS)637 int32_t NetConnService::ActivateNetwork(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
638 const uint32_t &timeoutMS)
639 {
640 NETMGR_LOG_D("ActivateNetwork Enter");
641 if (netSpecifier == nullptr || callback == nullptr) {
642 NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
643 return NETMANAGER_ERR_PARAMETER_ERROR;
644 }
645 std::weak_ptr<INetActivateCallback> timeoutCb = shared_from_this();
646 std::shared_ptr<NetActivate> request =
647 std::make_shared<NetActivate>(netSpecifier, callback, timeoutCb, timeoutMS, netActEventHandler_);
648 request->StartTimeOutNetAvailable();
649 uint32_t reqId = request->GetRequestId();
650 NETMGR_LOG_I("Make a new request, request id:[%{public}d]", reqId);
651 netActivates_[reqId] = request;
652 sptr<NetSupplier> bestNet = nullptr;
653 int bestScore = static_cast<int>(FindBestNetworkForRequest(bestNet, request));
654 if (bestScore != 0 && bestNet != nullptr) {
655 NETMGR_LOG_I("Match to optimal supplier:[%{public}d %{public}s], netId[%{public}d], score:[%{public}d]",
656 bestNet->GetSupplierId(), bestNet->GetNetSupplierIdent().c_str(), bestNet->GetNetId(), bestScore);
657 bestNet->SelectAsBestNetwork(reqId);
658 request->SetServiceSupply(bestNet);
659 CallbackForAvailable(bestNet, callback);
660 if ((bestNet->GetNetSupplierType() == BEARER_CELLULAR) || (bestNet->GetNetSupplierType() == BEARER_WIFI)) {
661 struct EventInfo eventInfo = {.capabilities = bestNet->GetNetCapabilities().ToString(" "),
662 .supplierIdent = bestNet->GetNetSupplierIdent()};
663 EventReport::SendRequestBehaviorEvent(eventInfo);
664 }
665 return NETMANAGER_SUCCESS;
666 }
667 if (timeoutMS == 0) {
668 callback->NetUnavailable();
669 }
670
671 NETMGR_LOG_I("Not matched to the optimal network, send request to all networks.");
672 SendRequestToAllNetwork(request);
673 return NETMANAGER_SUCCESS;
674 }
675
OnNetActivateTimeOut(uint32_t reqId)676 void NetConnService::OnNetActivateTimeOut(uint32_t reqId)
677 {
678 if (netConnEventHandler_) {
679 netConnEventHandler_->PostSyncTask([reqId, this]() {
680 NETMGR_LOG_D("DeactivateNetwork Enter, reqId is [%{public}d]", reqId);
681 auto iterActivate = netActivates_.find(reqId);
682 if (iterActivate == netActivates_.end()) {
683 NETMGR_LOG_E("not found the reqId: [%{public}d]", reqId);
684 return;
685 }
686 if (iterActivate->second != nullptr) {
687 sptr<NetSupplier> pNetService = iterActivate->second->GetServiceSupply();
688 if (pNetService) {
689 pNetService->CancelRequest(reqId);
690 }
691 }
692
693 NET_SUPPLIER_MAP::iterator iterSupplier;
694 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
695 if (iterSupplier->second == nullptr) {
696 continue;
697 }
698 iterSupplier->second->CancelRequest(reqId);
699 }
700 });
701 }
702 }
703
FindNetSupplier(uint32_t supplierId)704 sptr<NetSupplier> NetConnService::FindNetSupplier(uint32_t supplierId)
705 {
706 auto iterSupplier = netSuppliers_.find(supplierId);
707 if (iterSupplier != netSuppliers_.end()) {
708 return iterSupplier->second;
709 }
710 return nullptr;
711 }
712
FindSameCallback(const sptr<INetConnCallback> & callback,uint32_t & reqId)713 bool NetConnService::FindSameCallback(const sptr<INetConnCallback> &callback, uint32_t &reqId)
714 {
715 if (callback == nullptr) {
716 NETMGR_LOG_E("callback is null");
717 return false;
718 }
719 NET_ACTIVATE_MAP::iterator iterActive;
720 for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
721 if (!iterActive->second) {
722 continue;
723 }
724 sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
725 if (saveCallback == nullptr) {
726 continue;
727 }
728 if (callback->AsObject().GetRefPtr() == saveCallback->AsObject().GetRefPtr()) {
729 reqId = iterActive->first;
730 return true;
731 }
732 }
733 return false;
734 }
735
FindBestNetworkForAllRequest()736 void NetConnService::FindBestNetworkForAllRequest()
737 {
738 NETMGR_LOG_I("FindBestNetworkForAllRequest Enter");
739 NET_ACTIVATE_MAP::iterator iterActive;
740 sptr<NetSupplier> bestSupplier = nullptr;
741 for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
742 if (!iterActive->second) {
743 continue;
744 }
745 int score = static_cast<int>(FindBestNetworkForRequest(bestSupplier, iterActive->second));
746 NETMGR_LOG_D("Find best supplier[%{public}d, %{public}s]for request[%{public}d]",
747 bestSupplier ? bestSupplier->GetSupplierId() : 0,
748 bestSupplier ? bestSupplier->GetNetSupplierIdent().c_str() : "null",
749 iterActive->second->GetRequestId());
750 if (iterActive->second == defaultNetActivate_) {
751 MakeDefaultNetWork(defaultNetSupplier_, bestSupplier);
752 }
753 sptr<NetSupplier> oldSupplier = iterActive->second->GetServiceSupply();
754 sptr<INetConnCallback> callback = iterActive->second->GetNetCallback();
755 if (!bestSupplier) {
756 // not found the bestNetwork
757 NotFindBestSupplier(iterActive->first, iterActive->second, oldSupplier, callback);
758 continue;
759 }
760 SendBestScoreAllNetwork(iterActive->first, score, bestSupplier->GetSupplierId());
761 if (bestSupplier == oldSupplier) {
762 continue;
763 }
764 if (oldSupplier) {
765 oldSupplier->RemoveBestRequest(iterActive->first);
766 }
767 iterActive->second->SetServiceSupply(bestSupplier);
768 CallbackForAvailable(bestSupplier, callback);
769 bestSupplier->SelectAsBestNetwork(iterActive->first);
770 }
771 }
772
FindBestNetworkForRequest(sptr<NetSupplier> & supplier,std::shared_ptr<NetActivate> & netActivateNetwork)773 uint32_t NetConnService::FindBestNetworkForRequest(sptr<NetSupplier> &supplier,
774 std::shared_ptr<NetActivate> &netActivateNetwork)
775 {
776 int bestScore = 0;
777 supplier = nullptr;
778 if (netActivateNetwork == nullptr) {
779 NETMGR_LOG_E("netActivateNetwork is null");
780 return bestScore;
781 }
782 NETMGR_LOG_I(
783 "FindBestNetworkForRequest Enter, request[%{public}d] is [%{public}s]", netActivateNetwork->GetRequestId(),
784 netActivateNetwork->GetNetSpecifier() ? netActivateNetwork->GetNetSpecifier()->ToString(" ").c_str() : "null");
785 NET_SUPPLIER_MAP::iterator iter;
786 for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
787 if (iter->second == nullptr) {
788 continue;
789 }
790 NETMGR_LOG_D("supplier info, supplier[%{public}d, %{public}s], realScore[%{public}d], isConnected[%{public}d]",
791 iter->second->GetSupplierId(), iter->second->GetNetSupplierIdent().c_str(),
792 iter->second->GetRealScore(), iter->second->IsConnected());
793 if ((!iter->second->IsConnected()) || (!netActivateNetwork->MatchRequestAndNetwork(iter->second))) {
794 NETMGR_LOG_D("Supplier[%{public}d] is not connected or not match request.", iter->second->GetSupplierId());
795 continue;
796 }
797 int score = iter->second->GetRealScore();
798 if (score > bestScore) {
799 bestScore = score;
800 supplier = iter->second;
801 }
802 }
803 NETMGR_LOG_I("FindBestNetworkForRequest exit, bestScore[%{public}d], bestSupplier[%{public}d, %{public}s]",
804 bestScore, supplier ? supplier->GetSupplierId() : 0,
805 supplier ? supplier->GetNetSupplierIdent().c_str() : "null");
806 return bestScore;
807 }
808
RequestAllNetworkExceptDefault()809 void NetConnService::RequestAllNetworkExceptDefault()
810 {
811 if ((defaultNetSupplier_ == nullptr) || (defaultNetSupplier_->IsNetValidated())) {
812 return;
813 }
814 NETMGR_LOG_I("Default supplier[%{public}d, %{public}s] is not valid,request to activate another network",
815 defaultNetSupplier_->GetSupplierId(), defaultNetSupplier_->GetNetSupplierIdent().c_str());
816 if (defaultNetActivate_ == nullptr) {
817 NETMGR_LOG_E("Default net request is null");
818 return;
819 }
820 // Request activation of all networks except the default network
821 uint32_t reqId = defaultNetActivate_->GetRequestId();
822 for (const auto &netSupplier : netSuppliers_) {
823 if (netSupplier.second == nullptr || netSupplier.second == defaultNetSupplier_) {
824 continue;
825 }
826 if (netSupplier.second->GetNetScore() >= defaultNetSupplier_->GetNetScore()) {
827 continue;
828 }
829 if (!defaultNetActivate_->MatchRequestAndNetwork(netSupplier.second)) {
830 continue;
831 }
832 if (!netSupplier.second->RequestToConnect(reqId)) {
833 NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed",
834 netSupplier.second->GetSupplierId(), netSupplier.second->GetNetSupplierIdent().c_str());
835 }
836 }
837 }
838
GenerateNetId()839 int32_t NetConnService::GenerateNetId()
840 {
841 for (int32_t i = MIN_NET_ID; i <= MAX_NET_ID; ++i) {
842 netIdLastValue_++;
843 if (netIdLastValue_ > MAX_NET_ID) {
844 netIdLastValue_ = MIN_NET_ID;
845 }
846 if (networks_.find(netIdLastValue_) == networks_.end()) {
847 return netIdLastValue_;
848 }
849 }
850 return INVALID_NET_ID;
851 }
852
NotFindBestSupplier(uint32_t reqId,const std::shared_ptr<NetActivate> & active,const sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)853 void NetConnService::NotFindBestSupplier(uint32_t reqId, const std::shared_ptr<NetActivate> &active,
854 const sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
855 {
856 NETMGR_LOG_I("Could not find best supplier for request:[%{public}d]", reqId);
857 if (supplier != nullptr) {
858 supplier->RemoveBestRequest(reqId);
859 if (callback != nullptr) {
860 sptr<NetHandle> netHandle = supplier->GetNetHandle();
861 callback->NetLost(netHandle);
862 }
863 }
864 if (active != nullptr) {
865 active->SetServiceSupply(nullptr);
866 SendRequestToAllNetwork(active);
867 }
868 }
869
SendAllRequestToNetwork(sptr<NetSupplier> supplier)870 void NetConnService::SendAllRequestToNetwork(sptr<NetSupplier> supplier)
871 {
872 if (supplier == nullptr) {
873 NETMGR_LOG_E("supplier is null");
874 return;
875 }
876 NETMGR_LOG_I("Send all request to supplier[%{public}d, %{public}s]", supplier->GetSupplierId(),
877 supplier->GetNetSupplierIdent().c_str());
878 NET_ACTIVATE_MAP::iterator iter;
879 for (iter = netActivates_.begin(); iter != netActivates_.end(); ++iter) {
880 if (iter->second == nullptr) {
881 continue;
882 }
883 if (!iter->second->MatchRequestAndNetwork(supplier)) {
884 continue;
885 }
886 bool result = supplier->RequestToConnect(iter->first);
887 if (!result) {
888 NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed", supplier->GetSupplierId(),
889 supplier->GetNetSupplierIdent().c_str());
890 }
891 }
892 }
893
SendRequestToAllNetwork(std::shared_ptr<NetActivate> request)894 void NetConnService::SendRequestToAllNetwork(std::shared_ptr<NetActivate> request)
895 {
896 if (request == nullptr) {
897 NETMGR_LOG_E("request is null");
898 return;
899 }
900
901 uint32_t reqId = request->GetRequestId();
902 NETMGR_LOG_I("Send request[%{public}d] to all supplier", request->GetRequestId());
903 NET_SUPPLIER_MAP::iterator iter;
904 for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
905 if (iter->second == nullptr) {
906 continue;
907 }
908 if (!request->MatchRequestAndNetwork(iter->second)) {
909 continue;
910 }
911 bool result = iter->second->RequestToConnect(reqId);
912 if (!result) {
913 NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed", iter->second->GetSupplierId(),
914 iter->second->GetNetSupplierIdent().c_str());
915 }
916 }
917 }
918
SendBestScoreAllNetwork(uint32_t reqId,int32_t bestScore,uint32_t supplierId)919 void NetConnService::SendBestScoreAllNetwork(uint32_t reqId, int32_t bestScore, uint32_t supplierId)
920 {
921 NETMGR_LOG_I("Send best supplier[%{public}d]-score[%{public}d] to all supplier", supplierId, bestScore);
922 NET_SUPPLIER_MAP::iterator iter;
923 for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
924 if (iter->second == nullptr) {
925 continue;
926 }
927 iter->second->ReceiveBestScore(reqId, bestScore, supplierId);
928 }
929 }
930
CallbackForSupplier(sptr<NetSupplier> & supplier,CallbackType type)931 void NetConnService::CallbackForSupplier(sptr<NetSupplier> &supplier, CallbackType type)
932 {
933 if (supplier == nullptr) {
934 NETMGR_LOG_E("supplier is nullptr");
935 return;
936 }
937 std::set<uint32_t> &bestReqList = supplier->GetBestRequestList();
938 NETMGR_LOG_I("Callback type: %{public}d for supplier[%{public}d, %{public}s], best request size: %{public}zd",
939 static_cast<int32_t>(type), supplier->GetSupplierId(), supplier->GetNetSupplierIdent().c_str(),
940 bestReqList.size());
941 for (auto it : bestReqList) {
942 auto reqIt = netActivates_.find(it);
943 if ((reqIt == netActivates_.end()) || (reqIt->second == nullptr)) {
944 continue;
945 }
946 sptr<INetConnCallback> callback = reqIt->second->GetNetCallback();
947 if (!callback) {
948 continue;
949 }
950 sptr<NetHandle> netHandle = supplier->GetNetHandle();
951 switch (type) {
952 case CALL_TYPE_LOST: {
953 callback->NetLost(netHandle);
954 break;
955 }
956 case CALL_TYPE_UPDATE_CAP: {
957 sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
958 *pNetAllCap = supplier->GetNetCapabilities();
959 callback->NetCapabilitiesChange(netHandle, pNetAllCap);
960 break;
961 }
962 case CALL_TYPE_UPDATE_LINK: {
963 sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
964 auto network = supplier->GetNetwork();
965 if (network != nullptr && pInfo != nullptr) {
966 *pInfo = network->GetNetLinkInfo();
967 }
968 callback->NetConnectionPropertiesChange(netHandle, pInfo);
969 break;
970 }
971 case CALL_TYPE_BLOCK_STATUS: {
972 bool Metered = supplier->HasNetCap(NET_CAPABILITY_NOT_METERED);
973 bool newBlocked = NetManagerCenter::GetInstance().IsUidNetAccess(supplier->GetSupplierUid(), Metered);
974 callback->NetBlockStatusChange(netHandle, newBlocked);
975 break;
976 }
977 default:
978 break;
979 }
980 }
981 }
982
CallbackForAvailable(sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)983 void NetConnService::CallbackForAvailable(sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
984 {
985 NETMGR_LOG_I("Callback net available for supplier[%{public}d, %{public}s]",
986 supplier ? supplier->GetSupplierId() : 0,
987 supplier ? supplier->GetNetSupplierIdent().c_str() : "nullptr");
988 if (supplier == nullptr || callback == nullptr) {
989 NETMGR_LOG_E("Input parameter is null.");
990 return;
991 }
992 sptr<NetHandle> netHandle = supplier->GetNetHandle();
993 callback->NetAvailable(netHandle);
994 sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
995 *pNetAllCap = supplier->GetNetCapabilities();
996 callback->NetCapabilitiesChange(netHandle, pNetAllCap);
997 sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
998 auto network = supplier->GetNetwork();
999 if (network != nullptr && pInfo != nullptr) {
1000 *pInfo = network->GetNetLinkInfo();
1001 }
1002 callback->NetConnectionPropertiesChange(netHandle, pInfo);
1003 }
1004
MakeDefaultNetWork(sptr<NetSupplier> & oldSupplier,sptr<NetSupplier> & newSupplier)1005 void NetConnService::MakeDefaultNetWork(sptr<NetSupplier> &oldSupplier, sptr<NetSupplier> &newSupplier)
1006 {
1007 NETMGR_LOG_I("MakeDefaultNetWork in, oldSupplier[%{public}d, %{public}s], newSupplier[%{public}d, %{public}s]",
1008 oldSupplier ? oldSupplier->GetSupplierId() : 0,
1009 oldSupplier ? oldSupplier->GetNetSupplierIdent().c_str() : "null",
1010 newSupplier ? newSupplier->GetSupplierId() : 0,
1011 newSupplier ? newSupplier->GetNetSupplierIdent().c_str() : "null");
1012 if (oldSupplier == newSupplier) {
1013 NETMGR_LOG_D("old supplier equal to new supplier.");
1014 return;
1015 }
1016 if (oldSupplier != nullptr) {
1017 oldSupplier->ClearDefault();
1018 }
1019 if (newSupplier != nullptr) {
1020 newSupplier->SetDefault();
1021 }
1022 std::lock_guard<std::mutex> locker(netManagerMutex_);
1023 oldSupplier = newSupplier;
1024 NETMGR_LOG_I("Default supplier set to: [%{public}d, %{public}s]", oldSupplier ? oldSupplier->GetSupplierId() : 0,
1025 oldSupplier ? oldSupplier->GetNetSupplierIdent().c_str() : "null");
1026 }
1027
HandleDetectionResult(uint32_t supplierId,bool ifValid)1028 void NetConnService::HandleDetectionResult(uint32_t supplierId, bool ifValid)
1029 {
1030 NETMGR_LOG_I("Enter HandleDetectionResult, ifValid[%{public}d]", ifValid);
1031 auto supplier = FindNetSupplier(supplierId);
1032 if (supplier == nullptr) {
1033 NETMGR_LOG_E("supplier doesn't exist.");
1034 return;
1035 }
1036 supplier->SetNetValid(ifValid);
1037 CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
1038 if (!netScore_->GetServiceScore(supplier)) {
1039 NETMGR_LOG_E("GetServiceScore fail.");
1040 return;
1041 }
1042 FindBestNetworkForAllRequest();
1043 if (!ifValid && defaultNetSupplier_ && defaultNetSupplier_->GetSupplierId() == supplierId) {
1044 RequestAllNetworkExceptDefault();
1045 }
1046 }
1047
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident)1048 std::list<sptr<NetSupplier>> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident)
1049 {
1050 std::lock_guard<std::mutex> locker(netManagerMutex_);
1051 std::list<sptr<NetSupplier>> ret;
1052 for (const auto &netSupplier : netSuppliers_) {
1053 if (netSupplier.second == nullptr) {
1054 continue;
1055 }
1056 if ((bearerType != netSupplier.second->GetNetSupplierType())) {
1057 continue;
1058 }
1059 if (!ident.empty() && netSupplier.second->GetNetSupplierIdent() != ident) {
1060 continue;
1061 }
1062 ret.push_back(netSupplier.second);
1063 }
1064 return ret;
1065 }
1066
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps)1067 sptr<NetSupplier> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident,
1068 const std::set<NetCap> &netCaps)
1069 {
1070 std::lock_guard<std::mutex> locker(netManagerMutex_);
1071 for (const auto &netSupplier : netSuppliers_) {
1072 if (netSupplier.second == nullptr) {
1073 continue;
1074 }
1075 if ((bearerType == netSupplier.second->GetNetSupplierType()) &&
1076 (ident == netSupplier.second->GetNetSupplierIdent()) && netSupplier.second->CompareNetCaps(netCaps)) {
1077 return netSupplier.second;
1078 }
1079 }
1080 return nullptr;
1081 }
1082
GetDefaultNet(int32_t & netId)1083 int32_t NetConnService::GetDefaultNet(int32_t &netId)
1084 {
1085 std::lock_guard<std::mutex> locker(netManagerMutex_);
1086 if (!defaultNetSupplier_) {
1087 NETMGR_LOG_E("not found the netId");
1088 return NETMANAGER_SUCCESS;
1089 }
1090
1091 netId = defaultNetSupplier_->GetNetId();
1092 NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
1093 return NETMANAGER_SUCCESS;
1094 }
1095
GetAddressesByName(const std::string & host,int32_t netId,std::vector<INetAddr> & addrList)1096 int32_t NetConnService::GetAddressesByName(const std::string &host, int32_t netId, std::vector<INetAddr> &addrList)
1097 {
1098 return NetManagerCenter::GetInstance().GetAddressesByName(host, static_cast<uint16_t>(netId), addrList);
1099 }
1100
GetAddressByName(const std::string & host,int32_t netId,INetAddr & addr)1101 int32_t NetConnService::GetAddressByName(const std::string &host, int32_t netId, INetAddr &addr)
1102 {
1103 std::vector<INetAddr> addrList;
1104 int ret = GetAddressesByName(host, netId, addrList);
1105 if (ret == NETMANAGER_SUCCESS) {
1106 if (!addrList.empty()) {
1107 addr = addrList[0];
1108 return ret;
1109 }
1110 return NET_CONN_ERR_NO_ADDRESS;
1111 }
1112 return ret;
1113 }
1114
GetSpecificNet(NetBearType bearerType,std::list<int32_t> & netIdList)1115 int32_t NetConnService::GetSpecificNet(NetBearType bearerType, std::list<int32_t> &netIdList)
1116 {
1117 if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1118 NETMGR_LOG_E("netType parameter invalid");
1119 return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1120 }
1121
1122 std::lock_guard<std::mutex> locker(netManagerMutex_);
1123 NET_SUPPLIER_MAP::iterator iterSupplier;
1124 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1125 if (iterSupplier->second == nullptr) {
1126 continue;
1127 }
1128 auto supplierType = iterSupplier->second->GetNetSupplierType();
1129 if (bearerType == supplierType) {
1130 netIdList.push_back(iterSupplier->second->GetNetId());
1131 }
1132 }
1133 NETMGR_LOG_D("netSuppliers_ size[%{public}zd] networks_ size[%{public}zd]", netSuppliers_.size(), networks_.size());
1134 return NETMANAGER_SUCCESS;
1135 }
1136
GetAllNets(std::list<int32_t> & netIdList)1137 int32_t NetConnService::GetAllNets(std::list<int32_t> &netIdList)
1138 {
1139 std::lock_guard<std::mutex> locker(netManagerMutex_);
1140 for (const auto &network : networks_) {
1141 if (network.second != nullptr && network.second->IsConnected()) {
1142 netIdList.push_back(network.second->GetNetId());
1143 }
1144 }
1145 NETMGR_LOG_D("netSuppliers_ size[%{public}zd] netIdList size[%{public}zd]", netSuppliers_.size(), netIdList.size());
1146 return NETMANAGER_SUCCESS;
1147 }
1148
GetSpecificUidNet(int32_t uid,int32_t & netId)1149 int32_t NetConnService::GetSpecificUidNet(int32_t uid, int32_t &netId)
1150 {
1151 NETMGR_LOG_D("Enter GetSpecificUidNet, uid is [%{public}d].", uid);
1152 std::lock_guard<std::mutex> locker(netManagerMutex_);
1153 netId = INVALID_NET_ID;
1154 NET_SUPPLIER_MAP::iterator iterSupplier;
1155 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1156 if ((iterSupplier->second != nullptr) && (uid == iterSupplier->second->GetSupplierUid()) &&
1157 (iterSupplier->second->GetNetSupplierType() == BEARER_VPN)) {
1158 netId = iterSupplier->second->GetNetId();
1159 return NETMANAGER_SUCCESS;
1160 }
1161 }
1162 if (defaultNetSupplier_ != nullptr) {
1163 netId = defaultNetSupplier_->GetNetId();
1164 }
1165 NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
1166 return NETMANAGER_SUCCESS;
1167 }
1168
GetConnectionProperties(int32_t netId,NetLinkInfo & info)1169 int32_t NetConnService::GetConnectionProperties(int32_t netId, NetLinkInfo &info)
1170 {
1171 std::lock_guard<std::mutex> locker(netManagerMutex_);
1172 auto iterNetwork = networks_.find(netId);
1173 if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
1174 return NET_CONN_ERR_INVALID_NETWORK;
1175 }
1176
1177 info = iterNetwork->second->GetNetLinkInfo();
1178 return NETMANAGER_SUCCESS;
1179 }
1180
GetNetCapabilities(int32_t netId,NetAllCapabilities & netAllCap)1181 int32_t NetConnService::GetNetCapabilities(int32_t netId, NetAllCapabilities &netAllCap)
1182 {
1183 std::lock_guard<std::mutex> locker(netManagerMutex_);
1184 NET_SUPPLIER_MAP::iterator iterSupplier;
1185 for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1186 if ((iterSupplier->second != nullptr) && (netId == iterSupplier->second->GetNetId())) {
1187 netAllCap = iterSupplier->second->GetNetCapabilities();
1188 return NETMANAGER_SUCCESS;
1189 }
1190 }
1191 return NET_CONN_ERR_INVALID_NETWORK;
1192 }
1193
GetIfaceNames(NetBearType bearerType,std::list<std::string> & ifaceNames)1194 int32_t NetConnService::GetIfaceNames(NetBearType bearerType, std::list<std::string> &ifaceNames)
1195 {
1196 if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1197 return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1198 }
1199
1200 auto suppliers = GetNetSupplierFromList(bearerType);
1201 for (auto supplier : suppliers) {
1202 if (supplier == nullptr) {
1203 continue;
1204 }
1205 std::shared_ptr<Network> network = supplier->GetNetwork();
1206 if (network == nullptr) {
1207 continue;
1208 }
1209 std::string ifaceName = network->GetNetLinkInfo().ifaceName_;
1210 if (!ifaceName.empty()) {
1211 ifaceNames.push_back(ifaceName);
1212 }
1213 }
1214 return NETMANAGER_SUCCESS;
1215 }
1216
GetIfaceNameByType(NetBearType bearerType,const std::string & ident,std::string & ifaceName)1217 int32_t NetConnService::GetIfaceNameByType(NetBearType bearerType, const std::string &ident, std::string &ifaceName)
1218 {
1219 if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1220 NETMGR_LOG_E("netType parameter invalid");
1221 return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1222 }
1223
1224 auto suppliers = GetNetSupplierFromList(bearerType, ident);
1225 if (suppliers.empty()) {
1226 NETMGR_LOG_D("supplier is nullptr.");
1227 return NET_CONN_ERR_NO_SUPPLIER;
1228 }
1229 auto supplier = suppliers.front();
1230 std::shared_ptr<Network> network = supplier->GetNetwork();
1231 if (network == nullptr) {
1232 NETMGR_LOG_E("network is nullptr");
1233 return NET_CONN_ERR_INVALID_NETWORK;
1234 }
1235
1236 ifaceName = network->GetNetLinkInfo().ifaceName_;
1237
1238 return NETMANAGER_SUCCESS;
1239 }
1240
GetGlobalHttpProxy(HttpProxy & httpProxy)1241 int32_t NetConnService::GetGlobalHttpProxy(HttpProxy &httpProxy)
1242 {
1243 LoadGlobalHttpProxy();
1244 if (globalHttpProxy_.GetHost().empty()) {
1245 httpProxy.SetPort(0);
1246 NETMGR_LOG_E("The http proxy host is empty");
1247 return NETMANAGER_SUCCESS;
1248 }
1249 httpProxy = globalHttpProxy_;
1250 return NETMANAGER_SUCCESS;
1251 }
1252
GetDefaultHttpProxy(int32_t bindNetId,HttpProxy & httpProxy)1253 int32_t NetConnService::GetDefaultHttpProxy(int32_t bindNetId, HttpProxy &httpProxy)
1254 {
1255 LoadGlobalHttpProxy();
1256 if (!globalHttpProxy_.GetHost().empty()) {
1257 httpProxy = globalHttpProxy_;
1258 NETMGR_LOG_D("Return global http proxy as default.");
1259 return NETMANAGER_SUCCESS;
1260 }
1261
1262 std::lock_guard<std::mutex> locker(netManagerMutex_);
1263 auto iter = networks_.find(bindNetId);
1264 if ((iter != networks_.end()) && (iter->second != nullptr)) {
1265 httpProxy = iter->second->GetNetLinkInfo().httpProxy_;
1266 NETMGR_LOG_D("Return bound network's http proxy as default.");
1267 return NETMANAGER_SUCCESS;
1268 }
1269
1270 if (defaultNetSupplier_ != nullptr) {
1271 defaultNetSupplier_->GetHttpProxy(httpProxy);
1272 NETMGR_LOG_D("Return default network's http proxy as default.");
1273 return NETMANAGER_SUCCESS;
1274 }
1275 NETMGR_LOG_E("No default http proxy.");
1276 return NETMANAGER_SUCCESS;
1277 }
1278
GetNetIdByIdentifier(const std::string & ident,std::list<int32_t> & netIdList)1279 int32_t NetConnService::GetNetIdByIdentifier(const std::string &ident, std::list<int32_t> &netIdList)
1280 {
1281 if (ident.empty()) {
1282 NETMGR_LOG_E("The identifier in service is null");
1283 return NETMANAGER_ERR_INVALID_PARAMETER;
1284 }
1285 std::lock_guard<std::mutex> locker(netManagerMutex_);
1286 for (auto iterSupplier : netSuppliers_) {
1287 if (iterSupplier.second == nullptr) {
1288 continue;
1289 }
1290 if (iterSupplier.second->GetNetSupplierIdent() == ident) {
1291 int32_t netId = iterSupplier.second->GetNetId();
1292 netIdList.push_back(netId);
1293 }
1294 }
1295 return NETMANAGER_SUCCESS;
1296 }
1297
GetDumpMessage(std::string & message)1298 void NetConnService::GetDumpMessage(std::string &message)
1299 {
1300 message.append("Net connect Info:\n");
1301 std::lock_guard<std::mutex> locker(netManagerMutex_);
1302 if (defaultNetSupplier_) {
1303 message.append("\tSupplierId: " + std::to_string(defaultNetSupplier_->GetSupplierId()) + "\n");
1304 std::shared_ptr<Network> network = defaultNetSupplier_->GetNetwork();
1305 if (network) {
1306 message.append("\tNetId: " + std::to_string(network->GetNetId()) + "\n");
1307 } else {
1308 message.append("\tNetId: " + std::to_string(INVALID_NET_ID) + "\n");
1309 }
1310 message.append("\tConnStat: " + std::to_string(defaultNetSupplier_->IsConnected()) + "\n");
1311 message.append("\tIsAvailable: " + std::to_string(defaultNetSupplier_->IsNetValidated()) + "\n");
1312 message.append("\tIsRoaming: " + std::to_string(defaultNetSupplier_->GetRoaming()) + "\n");
1313 message.append("\tStrength: " + std::to_string(defaultNetSupplier_->GetStrength()) + "\n");
1314 message.append("\tFrequency: " + std::to_string(defaultNetSupplier_->GetFrequency()) + "\n");
1315 message.append("\tLinkUpBandwidthKbps: " +
1316 std::to_string(defaultNetSupplier_->GetNetCapabilities().linkUpBandwidthKbps_) + "\n");
1317 message.append("\tLinkDownBandwidthKbps: " +
1318 std::to_string(defaultNetSupplier_->GetNetCapabilities().linkDownBandwidthKbps_) + "\n");
1319 message.append("\tUid: " + std::to_string(defaultNetSupplier_->GetSupplierUid()) + "\n");
1320 } else {
1321 message.append("\tdefaultNetSupplier_ is nullptr\n");
1322 message.append("\tSupplierId: \n");
1323 message.append("\tNetId: 0\n");
1324 message.append("\tConnStat: 0\n");
1325 message.append("\tIsAvailable: \n");
1326 message.append("\tIsRoaming: 0\n");
1327 message.append("\tStrength: 0\n");
1328 message.append("\tFrequency: 0\n");
1329 message.append("\tLinkUpBandwidthKbps: 0\n");
1330 message.append("\tLinkDownBandwidthKbps: 0\n");
1331 message.append("\tUid: 0\n");
1332 }
1333 }
1334
HasDefaultNet(bool & flag)1335 int32_t NetConnService::HasDefaultNet(bool &flag)
1336 {
1337 std::lock_guard<std::mutex> locker(netManagerMutex_);
1338 if (!defaultNetSupplier_) {
1339 flag = false;
1340 return NETMANAGER_SUCCESS;
1341 }
1342 flag = true;
1343 return NETMANAGER_SUCCESS;
1344 }
1345
IsDefaultNetMetered(bool & isMetered)1346 int32_t NetConnService::IsDefaultNetMetered(bool &isMetered)
1347 {
1348 std::lock_guard<std::mutex> locker(netManagerMutex_);
1349 if (defaultNetSupplier_) {
1350 isMetered = !defaultNetSupplier_->HasNetCap(NET_CAPABILITY_NOT_METERED);
1351 } else {
1352 isMetered = true;
1353 }
1354 return NETMANAGER_SUCCESS;
1355 }
1356
BindSocket(int32_t socket_fd,int32_t netId)1357 int32_t NetConnService::BindSocket(int32_t socket_fd, int32_t netId)
1358 {
1359 NETMGR_LOG_D("Enter BindSocket.");
1360 return NetsysController::GetInstance().BindSocket(socket_fd, netId);
1361 }
1362
Dump(int32_t fd,const std::vector<std::u16string> & args)1363 int32_t NetConnService::Dump(int32_t fd, const std::vector<std::u16string> &args)
1364 {
1365 NETMGR_LOG_D("Start Dump, fd: %{public}d", fd);
1366 std::string result;
1367 GetDumpMessage(result);
1368 int32_t ret = dprintf(fd, "%s\n", result.c_str());
1369 return (ret < 0) ? static_cast<int32_t>(NET_CONN_ERR_CREATE_DUMP_FAILED) : static_cast<int32_t>(NETMANAGER_SUCCESS);
1370 }
1371
SetAirplaneMode(bool state)1372 int32_t NetConnService::SetAirplaneMode(bool state)
1373 {
1374 auto dataShareHelperUtils = std::make_unique<NetDataShareHelperUtils>();
1375 std::string airplaneMode = std::to_string(state);
1376 Uri uri(AIRPLANE_MODE_URI);
1377 int32_t ret = dataShareHelperUtils->Update(uri, KEY_AIRPLANE_MODE, airplaneMode);
1378 if (ret != NETMANAGER_SUCCESS) {
1379 NETMGR_LOG_E("Update airplane mode:%{public}d to datashare failed.", state);
1380 return NETMANAGER_ERR_INTERNAL;
1381 }
1382
1383 BroadcastInfo info;
1384 info.action = EventFwk::CommonEventSupport::COMMON_EVENT_AIRPLANE_MODE_CHANGED;
1385 info.data = "Net Manager Airplane Mode Changed";
1386 info.code = static_cast<int32_t>(state);
1387 info.ordered = false;
1388 std::map<std::string, int32_t> param;
1389 BroadcastManager::GetInstance().SendBroadcast(info, param);
1390 return NETMANAGER_SUCCESS;
1391 }
1392
SetGlobalHttpProxy(const HttpProxy & httpProxy)1393 int32_t NetConnService::SetGlobalHttpProxy(const HttpProxy &httpProxy)
1394 {
1395 LoadGlobalHttpProxy();
1396 if (globalHttpProxy_ != httpProxy) {
1397 globalHttpProxy_ = httpProxy;
1398 NetHttpProxyTracker httpProxyTracker;
1399 if (!httpProxyTracker.WriteToSettingsData(globalHttpProxy_)) {
1400 return NETMANAGER_ERR_INTERNAL;
1401 }
1402 SendHttpProxyChangeBroadcast(globalHttpProxy_);
1403 }
1404 return NETMANAGER_SUCCESS;
1405 }
1406
SetAppNet(int32_t netId)1407 int32_t NetConnService::SetAppNet(int32_t netId)
1408 {
1409 return NETMANAGER_SUCCESS;
1410 }
1411
RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)1412 int32_t NetConnService::RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback)
1413 {
1414 if (callback == nullptr) {
1415 NETMGR_LOG_E("callback is nullptr");
1416 return NETMANAGER_ERR_LOCAL_PTR_NULL;
1417 }
1418
1419 if (interfaceStateCallback_ == nullptr) {
1420 NETMGR_LOG_E("interfaceStateCallback_ is nullptr");
1421 return NETMANAGER_ERR_LOCAL_PTR_NULL;
1422 }
1423 return interfaceStateCallback_->RegisterInterfaceCallback(callback);
1424 }
1425
GetNetInterfaceConfiguration(const std::string & iface,NetInterfaceConfiguration & config)1426 int32_t NetConnService::GetNetInterfaceConfiguration(const std::string &iface, NetInterfaceConfiguration &config)
1427 {
1428 using namespace OHOS::nmd;
1429 InterfaceConfigurationParcel configParcel;
1430 configParcel.ifName = iface;
1431 if (NetsysController::GetInstance().GetInterfaceConfig(configParcel) != NETMANAGER_SUCCESS) {
1432 return NETMANAGER_ERR_INTERNAL;
1433 }
1434 config.ifName_ = configParcel.ifName;
1435 config.hwAddr_ = configParcel.hwAddr;
1436 config.ipv4Addr_ = configParcel.ipv4Addr;
1437 config.prefixLength_ = configParcel.prefixLength;
1438 config.flags_.assign(configParcel.flags.begin(), configParcel.flags.end());
1439 return NETMANAGER_SUCCESS;
1440 }
1441
LoadGlobalHttpProxy()1442 void NetConnService::LoadGlobalHttpProxy()
1443 {
1444 if (isGlobalProxyLoaded_.load()) {
1445 NETMGR_LOG_D("Global http proxy has been loaded from the SettingsData database.");
1446 return;
1447 }
1448 NetHttpProxyTracker httpProxyTracker;
1449 httpProxyTracker.ReadFromSettingsData(globalHttpProxy_);
1450 isGlobalProxyLoaded_ = true;
1451 }
1452
OnInterfaceAddressUpdated(const std::string & addr,const std::string & ifName,int flags,int scope)1453 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAddressUpdated(const std::string &addr,
1454 const std::string &ifName, int flags,
1455 int scope)
1456 {
1457 std::lock_guard<std::mutex> locker(mutex_);
1458 for (const auto &callback : ifaceStateCallbacks_) {
1459 if (callback == nullptr) {
1460 NETMGR_LOG_E("callback is null");
1461 continue;
1462 }
1463 callback->OnInterfaceAddressUpdated(addr, ifName, flags, scope);
1464 }
1465 return NETMANAGER_SUCCESS;
1466 }
1467
OnInterfaceAddressRemoved(const std::string & addr,const std::string & ifName,int flags,int scope)1468 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAddressRemoved(const std::string &addr,
1469 const std::string &ifName, int flags,
1470 int scope)
1471 {
1472 std::lock_guard<std::mutex> locker(mutex_);
1473 for (const auto &callback : ifaceStateCallbacks_) {
1474 if (callback == nullptr) {
1475 NETMGR_LOG_E("callback is null");
1476 continue;
1477 }
1478 callback->OnInterfaceAddressRemoved(addr, ifName, flags, scope);
1479 }
1480 return NETMANAGER_SUCCESS;
1481 }
1482
OnInterfaceAdded(const std::string & iface)1483 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAdded(const std::string &iface)
1484 {
1485 std::lock_guard<std::mutex> locker(mutex_);
1486 for (const auto &callback : ifaceStateCallbacks_) {
1487 if (callback == nullptr) {
1488 NETMGR_LOG_E("callback is null");
1489 continue;
1490 }
1491 callback->OnInterfaceAdded(iface);
1492 }
1493 return NETMANAGER_SUCCESS;
1494 }
1495
OnInterfaceRemoved(const std::string & iface)1496 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceRemoved(const std::string &iface)
1497 {
1498 std::lock_guard<std::mutex> locker(mutex_);
1499 for (const auto &callback : ifaceStateCallbacks_) {
1500 if (callback == nullptr) {
1501 NETMGR_LOG_E("callback is null");
1502 continue;
1503 }
1504 callback->OnInterfaceRemoved(iface);
1505 }
1506 return NETMANAGER_SUCCESS;
1507 }
1508
OnInterfaceChanged(const std::string & iface,bool up)1509 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceChanged(const std::string &iface, bool up)
1510 {
1511 std::lock_guard<std::mutex> locker(mutex_);
1512 for (const auto &callback : ifaceStateCallbacks_) {
1513 if (callback == nullptr) {
1514 NETMGR_LOG_E("callback is null");
1515 continue;
1516 }
1517 callback->OnInterfaceChanged(iface, up);
1518 }
1519 return NETMANAGER_SUCCESS;
1520 }
1521
OnInterfaceLinkStateChanged(const std::string & iface,bool up)1522 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceLinkStateChanged(const std::string &iface, bool up)
1523 {
1524 std::lock_guard<std::mutex> locker(mutex_);
1525 for (const auto &callback : ifaceStateCallbacks_) {
1526 if (callback == nullptr) {
1527 NETMGR_LOG_E("callback is null");
1528 continue;
1529 }
1530 callback->OnInterfaceLinkStateChanged(iface, up);
1531 }
1532 return NETMANAGER_SUCCESS;
1533 }
1534
OnRouteChanged(bool updated,const std::string & route,const std::string & gateway,const std::string & ifName)1535 int32_t NetConnService::NetInterfaceStateCallback::OnRouteChanged(bool updated, const std::string &route,
1536 const std::string &gateway, const std::string &ifName)
1537 {
1538 return NETMANAGER_SUCCESS;
1539 }
1540
OnDhcpSuccess(NetsysControllerCallback::DhcpResult & dhcpResult)1541 int32_t NetConnService::NetInterfaceStateCallback::OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult)
1542 {
1543 return NETMANAGER_SUCCESS;
1544 }
1545
OnBandwidthReachedLimit(const std::string & limitName,const std::string & iface)1546 int32_t NetConnService::NetInterfaceStateCallback::OnBandwidthReachedLimit(const std::string &limitName,
1547 const std::string &iface)
1548 {
1549 return NETMANAGER_SUCCESS;
1550 }
1551
RegisterInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)1552 int32_t NetConnService::NetInterfaceStateCallback::RegisterInterfaceCallback(
1553 const sptr<INetInterfaceStateCallback> &callback)
1554 {
1555 if (callback == nullptr) {
1556 NETMGR_LOG_E("callback is null");
1557 return NETMANAGER_ERR_LOCAL_PTR_NULL;
1558 }
1559
1560 std::lock_guard<std::mutex> locker(mutex_);
1561 for (const auto &iter : ifaceStateCallbacks_) {
1562 if (!iter) {
1563 continue;
1564 }
1565 if (iter->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
1566 NETMGR_LOG_E("RegisterInterfaceCallback find same callback");
1567 return NET_CONN_ERR_SAME_CALLBACK;
1568 }
1569 }
1570 ifaceStateCallbacks_.push_back(callback);
1571 return NETMANAGER_SUCCESS;
1572 }
1573 } // namespace NetManagerStandard
1574 } // namespace OHOS
1575