• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <fstream>
17 #include <sys/time.h>
18 
19 #include "common_event_support.h"
20 #include "system_ability_definition.h"
21 
22 #include "broadcast_manager.h"
23 #include "event_report.h"
24 #include "net_activate.h"
25 #include "net_conn_service.h"
26 #include "net_conn_types.h"
27 #include "net_datashare_utils.h"
28 #include "net_http_proxy_tracker.h"
29 #include "net_manager_center.h"
30 #include "net_manager_constants.h"
31 #include "net_mgr_log_wrapper.h"
32 #include "net_supplier.h"
33 #include "netmanager_base_permission.h"
34 #include "netsys_controller.h"
35 #include "ipc_skeleton.h"
36 
37 namespace OHOS {
38 namespace NetManagerStandard {
39 namespace {
40 constexpr uint32_t MAX_ALLOW_UID_NUM = 2000;
41 // hisysevent error messgae
42 constexpr const char *ERROR_MSG_NULL_SUPPLIER_INFO = "Net supplier info is nullptr";
43 constexpr const char *ERROR_MSG_NULL_NET_LINK_INFO = "Net link info is nullptr";
44 constexpr const char *ERROR_MSG_NULL_NET_SPECIFIER = "The parameter of netSpecifier or callback is null";
45 constexpr const char *ERROR_MSG_CAN_NOT_FIND_SUPPLIER = "Can not find supplier by id:";
46 constexpr const char *ERROR_MSG_UPDATE_NETLINK_INFO_FAILED = "Update net link info failed";
47 constexpr const char *NET_CONN_MANAGER_WORK_THREAD = "NET_CONN_MANAGER_WORK_THREAD";
48 constexpr const char *NET_ACTIVATE_WORK_THREAD = "NET_ACTIVATE_WORK_THREAD";
49 constexpr const char *NET_HTTP_PROBE_URL = "http://connectivitycheck.platform.hicloud.com/generate_204";
50 } // namespace
51 
52 const bool REGISTER_LOCAL_RESULT =
53     SystemAbility::MakeAndRegisterAbility(NetConnService::GetInstance().get());
54 
NetConnService()55 NetConnService::NetConnService()
56     : SystemAbility(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID, true), registerToService_(false), state_(STATE_STOPPED)
57 {
58     netActEventRunner_ = AppExecFwk::EventRunner::Create(NET_ACTIVATE_WORK_THREAD);
59     netActEventHandler_ = std::make_shared<AppExecFwk::EventHandler>(netActEventRunner_);
60     CreateDefaultRequest();
61 }
62 
~NetConnService()63 NetConnService::~NetConnService() {}
64 
OnStart()65 void NetConnService::OnStart()
66 {
67     struct timeval tv;
68     gettimeofday(&tv, nullptr);
69     NETMGR_LOG_D("NetConnService::OnStart begin");
70     if (state_ == STATE_RUNNING) {
71         NETMGR_LOG_D("the state is already running");
72         return;
73     }
74     if (!Init()) {
75         NETMGR_LOG_E("init failed");
76         return;
77     }
78     state_ = STATE_RUNNING;
79     gettimeofday(&tv, nullptr);
80     NETMGR_LOG_D("NetConnService::OnStart end");
81 }
82 
CreateDefaultRequest()83 void NetConnService::CreateDefaultRequest()
84 {
85     if (!defaultNetActivate_) {
86         defaultNetSpecifier_ = (std::make_unique<NetSpecifier>()).release();
87         defaultNetSpecifier_->SetCapability(NET_CAPABILITY_INTERNET);
88         std::weak_ptr<INetActivateCallback> timeoutCb;
89         defaultNetActivate_ =
90             std::make_shared<NetActivate>(defaultNetSpecifier_, nullptr, timeoutCb, 0, netActEventHandler_);
91         defaultNetActivate_->StartTimeOutNetAvailable();
92         defaultNetActivate_->SetRequestId(DEFAULT_REQUEST_ID);
93         netActivates_[DEFAULT_REQUEST_ID] = defaultNetActivate_;
94     }
95 }
96 
OnStop()97 void NetConnService::OnStop()
98 {
99     NETMGR_LOG_D("NetConnService::OnStop begin");
100     if (netConnEventRunner_) {
101         netConnEventRunner_->Stop();
102         netConnEventRunner_.reset();
103     }
104     if (netConnEventHandler_) {
105         netConnEventHandler_.reset();
106     }
107     state_ = STATE_STOPPED;
108     registerToService_ = false;
109     NETMGR_LOG_D("NetConnService::OnStop end");
110 }
111 
Init()112 bool NetConnService::Init()
113 {
114     if (!REGISTER_LOCAL_RESULT) {
115         NETMGR_LOG_E("Register to local sa manager failed");
116         registerToService_ = false;
117         return false;
118     }
119     if (!registerToService_) {
120         if (!Publish(NetConnService::GetInstance().get())) {
121             NETMGR_LOG_E("Register to sa manager failed");
122             return false;
123         }
124         registerToService_ = true;
125     }
126 
127     AddSystemAbilityListener(COMM_NETSYS_NATIVE_SYS_ABILITY_ID);
128 
129     netConnEventRunner_ = AppExecFwk::EventRunner::Create(NET_CONN_MANAGER_WORK_THREAD);
130     if (netConnEventRunner_ == nullptr) {
131         NETMGR_LOG_E("Create event runner failed.");
132         return false;
133     }
134     netConnEventHandler_ = std::make_shared<NetConnEventHandler>(netConnEventRunner_);
135     serviceIface_ = std::make_unique<NetConnServiceIface>().release();
136     NetManagerCenter::GetInstance().RegisterConnService(serviceIface_);
137     netScore_ = std::make_unique<NetScore>();
138     if (netScore_ == nullptr) {
139         NETMGR_LOG_E("Make NetScore failed");
140         return false;
141     }
142 
143     interfaceStateCallback_ = new (std::nothrow) NetInterfaceStateCallback();
144     if (interfaceStateCallback_) {
145         NetsysController::GetInstance().RegisterCallback(interfaceStateCallback_);
146     }
147     dnsResultCallback_ = std::make_unique<NetDnsResultCallback>().release();
148     int32_t regDnsResult = NetsysController::GetInstance().RegisterDnsResultCallback(dnsResultCallback_, 0);
149     NETMGR_LOG_I("Register Dns Result callback result: [%{public}d]", regDnsResult);
150 
151     netFactoryResetCallback_ = std::make_unique<NetFactoryResetCallback>().release();
152     if (netFactoryResetCallback_ == nullptr) {
153         NETMGR_LOG_E("netFactoryResetCallback_ is nullptr");
154     }
155 
156     RecoverInfo();
157     NETMGR_LOG_I("NetConnService::Init end");
158     return true;
159 }
160 
RecoverInfo()161 void NetConnService::RecoverInfo()
162 {
163     // recover httpproxy
164     LoadGlobalHttpProxy();
165     if (!globalHttpProxy_.GetHost().empty()) {
166         NETMGR_LOG_D("globalHttpProxy_ not empty, send broadcast");
167         SendHttpProxyChangeBroadcast(globalHttpProxy_);
168         UpdateGlobalHttpProxy(globalHttpProxy_);
169     }
170 }
171 
SystemReady()172 int32_t NetConnService::SystemReady()
173 {
174     if (state_ == STATE_RUNNING) {
175         NETMGR_LOG_D("System ready.");
176         return NETMANAGER_SUCCESS;
177     } else {
178         return NETMANAGER_ERROR;
179     }
180 }
181 
182 // Do not post into event handler, because this interface should have good performance
SetInternetPermission(uint32_t uid,uint8_t allow)183 int32_t NetConnService::SetInternetPermission(uint32_t uid, uint8_t allow)
184 {
185     return NetsysController::GetInstance().SetInternetPermission(uid, allow);
186 }
187 
RegisterNetSupplier(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps,uint32_t & supplierId)188 int32_t NetConnService::RegisterNetSupplier(NetBearType bearerType, const std::string &ident,
189                                             const std::set<NetCap> &netCaps, uint32_t &supplierId)
190 {
191     int32_t result = NETMANAGER_ERROR;
192     if (netConnEventHandler_) {
193         netConnEventHandler_->PostSyncTask([this, bearerType, &ident, &netCaps, &supplierId, &result]() {
194             result = this->RegisterNetSupplierAsync(bearerType, ident, netCaps, supplierId);
195         });
196     }
197     return result;
198 }
199 
RegisterNetSupplierCallback(uint32_t supplierId,const sptr<INetSupplierCallback> & callback)200 int32_t NetConnService::RegisterNetSupplierCallback(uint32_t supplierId, const sptr<INetSupplierCallback> &callback)
201 {
202     int32_t result = NETMANAGER_ERROR;
203     if (netConnEventHandler_) {
204         netConnEventHandler_->PostSyncTask([this, supplierId, &callback, &result]() {
205             result = this->RegisterNetSupplierCallbackAsync(supplierId, callback);
206         });
207     }
208     return result;
209 }
210 
RegisterNetConnCallback(const sptr<INetConnCallback> & callback)211 int32_t NetConnService::RegisterNetConnCallback(const sptr<INetConnCallback> &callback)
212 {
213     NETMGR_LOG_D("RegisterNetConnCallback service in.");
214     return RegisterNetConnCallback(defaultNetSpecifier_, callback, 0);
215 }
216 
RegisterNetConnCallback(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS)217 int32_t NetConnService::RegisterNetConnCallback(const sptr<NetSpecifier> &netSpecifier,
218                                                 const sptr<INetConnCallback> &callback, const uint32_t &timeoutMS)
219 {
220     int32_t callingUid = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
221 
222     int32_t result = NETMANAGER_ERROR;
223     if (netConnEventHandler_) {
224         netConnEventHandler_->PostSyncTask([this, &netSpecifier, &callback, timeoutMS, callingUid, &result]() {
225             result = this->RegisterNetConnCallbackAsync(netSpecifier, callback, timeoutMS, callingUid);
226         });
227     }
228     return result;
229 }
230 
RegisterNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback)231 int32_t NetConnService::RegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback)
232 {
233     NETMGR_LOG_D("Enter NetConnService::RegisterNetDetectionCallback");
234     return RegUnRegNetDetectionCallback(netId, callback, true);
235 }
236 
UnregisterNetSupplier(uint32_t supplierId)237 int32_t NetConnService::UnregisterNetSupplier(uint32_t supplierId)
238 {
239     int32_t result = NETMANAGER_ERROR;
240     if (netConnEventHandler_) {
241         netConnEventHandler_->PostSyncTask(
242             [this, supplierId, &result]() { result = this->UnregisterNetSupplierAsync(supplierId); });
243     }
244     return result;
245 }
246 
UnregisterNetConnCallback(const sptr<INetConnCallback> & callback)247 int32_t NetConnService::UnregisterNetConnCallback(const sptr<INetConnCallback> &callback)
248 {
249     int32_t callingUid = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
250     int32_t result = NETMANAGER_ERROR;
251     if (netConnEventHandler_) {
252         netConnEventHandler_->PostSyncTask(
253             [this, &callback, callingUid, &result]() {
254                 result = this->UnregisterNetConnCallbackAsync(callback, callingUid);
255             });
256     }
257     return result;
258 }
259 
UnRegisterNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback)260 int32_t NetConnService::UnRegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback)
261 {
262     NETMGR_LOG_D("Enter NetConnService::UnRegisterNetDetectionCallback");
263     return RegUnRegNetDetectionCallback(netId, callback, false);
264 }
265 
RegUnRegNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback,bool isReg)266 int32_t NetConnService::RegUnRegNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback,
267                                                      bool isReg)
268 {
269     int32_t result = NETMANAGER_ERROR;
270     if (netConnEventHandler_) {
271         netConnEventHandler_->PostSyncTask([this, netId, &callback, isReg, &result]() {
272             result = this->RegUnRegNetDetectionCallbackAsync(netId, callback, isReg);
273         });
274     }
275     return result;
276 }
277 
UpdateNetStateForTest(const sptr<NetSpecifier> & netSpecifier,int32_t netState)278 int32_t NetConnService::UpdateNetStateForTest(const sptr<NetSpecifier> &netSpecifier, int32_t netState)
279 {
280     int32_t result = NETMANAGER_ERROR;
281     if (netConnEventHandler_) {
282         netConnEventHandler_->PostSyncTask([this, &netSpecifier, netState, &result]() {
283             result = this->UpdateNetStateForTestAsync(netSpecifier, netState);
284         });
285     }
286     return result;
287 }
288 
UpdateNetSupplierInfo(uint32_t supplierId,const sptr<NetSupplierInfo> & netSupplierInfo)289 int32_t NetConnService::UpdateNetSupplierInfo(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo)
290 {
291     int32_t result = NETMANAGER_ERROR;
292     if (netConnEventHandler_) {
293         netConnEventHandler_->PostSyncTask([this, supplierId, &netSupplierInfo, &result]() {
294             result = this->UpdateNetSupplierInfoAsync(supplierId, netSupplierInfo);
295         });
296     }
297     return result;
298 }
299 
UpdateNetLinkInfo(uint32_t supplierId,const sptr<NetLinkInfo> & netLinkInfo)300 int32_t NetConnService::UpdateNetLinkInfo(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo)
301 {
302     int32_t result = NETMANAGER_ERROR;
303     if (netConnEventHandler_) {
304         netConnEventHandler_->PostSyncTask([this, supplierId, &netLinkInfo, &result]() {
305             result = this->UpdateNetLinkInfoAsync(supplierId, netLinkInfo);
306         });
307     }
308     return result;
309 }
310 
NetDetection(int32_t netId)311 int32_t NetConnService::NetDetection(int32_t netId)
312 {
313     int32_t result = NETMANAGER_ERROR;
314     if (netConnEventHandler_) {
315         netConnEventHandler_->PostSyncTask([this, netId, &result]() { result = this->NetDetectionAsync(netId); });
316     }
317     return result;
318 }
319 
RestrictBackgroundChanged(bool restrictBackground)320 int32_t NetConnService::RestrictBackgroundChanged(bool restrictBackground)
321 {
322     int32_t result = NETMANAGER_ERROR;
323     if (netConnEventHandler_) {
324         netConnEventHandler_->PostSyncTask([this, restrictBackground, &result]() {
325             result = this->RestrictBackgroundChangedAsync(restrictBackground);
326         });
327     }
328     return result;
329 }
330 
RegisterNetSupplierAsync(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps,uint32_t & supplierId)331 int32_t NetConnService::RegisterNetSupplierAsync(NetBearType bearerType, const std::string &ident,
332                                                  const std::set<NetCap> &netCaps, uint32_t &supplierId)
333 {
334     NETMGR_LOG_I("RegisterNetSupplier service in, bearerType[%{public}u], ident[%{public}s]",
335                  static_cast<uint32_t>(bearerType), ident.c_str());
336     // If there is no supplier in the list, create a supplier
337     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
338         NETMGR_LOG_E("netType parameter invalid");
339         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
340     }
341     sptr<NetSupplier> supplier = GetNetSupplierFromList(bearerType, ident, netCaps);
342     if (supplier != nullptr) {
343         NETMGR_LOG_E("Supplier[%{public}d %{public}s] already exists.", supplier->GetSupplierId(), ident.c_str());
344         supplierId = supplier->GetSupplierId();
345         return NETMANAGER_SUCCESS;
346     }
347     // If there is no supplier in the list, create a supplier
348     supplier = (std::make_unique<NetSupplier>(bearerType, ident, netCaps)).release();
349     if (supplier == nullptr) {
350         NETMGR_LOG_E("supplier is nullptr");
351         return NET_CONN_ERR_NO_SUPPLIER;
352     }
353     supplierId = supplier->GetSupplierId();
354     if (!netScore_->GetServiceScore(supplier)) {
355         NETMGR_LOG_E("GetServiceScore fail.");
356     }
357     // create network
358     int32_t netId = GenerateNetId();
359     NETMGR_LOG_D("GenerateNetId is: [%{public}d]", netId);
360     if (netId == INVALID_NET_ID) {
361         NETMGR_LOG_E("GenerateNetId fail");
362         return NET_CONN_ERR_INVALID_NETWORK;
363     }
364     std::shared_ptr<Network> network = std::make_shared<Network>(
365         netId, supplierId,
366         std::bind(&NetConnService::HandleDetectionResult, shared_from_this(),
367             std::placeholders::_1, std::placeholders::_2),
368         bearerType, netConnEventHandler_);
369     supplier->SetNetwork(network);
370     supplier->SetNetValid(true);
371     // save supplier
372     std::unique_lock<std::mutex> locker(netManagerMutex_);
373     netSuppliers_[supplierId] = supplier;
374     networks_[netId] = network;
375     locker.unlock();
376     struct EventInfo eventInfo = {.netId = netId, .bearerType = bearerType, .ident = ident, .supplierId = supplierId};
377     EventReport::SendSupplierBehaviorEvent(eventInfo);
378     NETMGR_LOG_I("RegisterNetSupplier service out, supplier[%{public}d %{public}s] netId[%{public}d]", supplierId,
379                  ident.c_str(), netId);
380     return NETMANAGER_SUCCESS;
381 }
382 
RegisterNetSupplierCallbackAsync(uint32_t supplierId,const sptr<INetSupplierCallback> & callback)383 int32_t NetConnService::RegisterNetSupplierCallbackAsync(uint32_t supplierId,
384                                                          const sptr<INetSupplierCallback> &callback)
385 {
386     NETMGR_LOG_I("RegisterNetSupplierCallback service in, supplierId[%{public}d]", supplierId);
387     if (callback == nullptr) {
388         NETMGR_LOG_E("The parameter callback is null");
389         return NETMANAGER_ERR_LOCAL_PTR_NULL;
390     }
391     auto supplier = FindNetSupplier(supplierId);
392     if (supplier == nullptr) {
393         NETMGR_LOG_E("supplier doesn't exist.");
394         return NET_CONN_ERR_NO_SUPPLIER;
395     }
396     supplier->RegisterSupplierCallback(callback);
397     SendAllRequestToNetwork(supplier);
398     NETMGR_LOG_I("RegisterNetSupplierCallback service out");
399     return NETMANAGER_SUCCESS;
400 }
401 
RegisterNetConnCallbackAsync(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS,const uint32_t callingUid)402 int32_t NetConnService::RegisterNetConnCallbackAsync(const sptr<NetSpecifier> &netSpecifier,
403                                                      const sptr<INetConnCallback> &callback, const uint32_t &timeoutMS,
404                                                      const uint32_t callingUid)
405 {
406     NETMGR_LOG_I("Register net connect callback async, call uid [%{public}u]", callingUid);
407     if (netSpecifier == nullptr || callback == nullptr) {
408         NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
409         struct EventInfo eventInfo = {.errorType = static_cast<int32_t>(FAULT_INVALID_PARAMETER),
410                                       .errorMsg = ERROR_MSG_NULL_NET_SPECIFIER};
411         EventReport::SendRequestFaultEvent(eventInfo);
412         return NETMANAGER_ERR_LOCAL_PTR_NULL;
413     }
414     uint32_t reqId = 0;
415     if (FindSameCallback(callback, reqId)) {
416         NETMGR_LOG_E("RegisterNetConnCallback find same callback");
417         return NET_CONN_ERR_SAME_CALLBACK;
418     }
419     int32_t ret = IncreaseNetConnCallbackCntForUid(callingUid);
420     if (ret != NETMANAGER_SUCCESS) {
421         return ret;
422     }
423     return ActivateNetwork(netSpecifier, callback, timeoutMS);
424 }
425 
UnregisterNetSupplierAsync(uint32_t supplierId)426 int32_t NetConnService::UnregisterNetSupplierAsync(uint32_t supplierId)
427 {
428     NETMGR_LOG_I("UnregisterNetSupplier service in, supplierId[%{public}d]", supplierId);
429     // Remove supplier from the list based on supplierId
430     auto supplier = FindNetSupplier(supplierId);
431     if (supplier == nullptr) {
432         NETMGR_LOG_E("supplier doesn't exist.");
433         return NET_CONN_ERR_NO_SUPPLIER;
434     }
435     NETMGR_LOG_I("Unregister supplier[%{public}d, %{public}s], defaultNetSupplier[%{public}d], %{public}s]",
436                  supplier->GetSupplierId(), supplier->GetNetSupplierIdent().c_str(),
437                  defaultNetSupplier_ ? defaultNetSupplier_->GetSupplierId() : 0,
438                  defaultNetSupplier_ ? defaultNetSupplier_->GetNetSupplierIdent().c_str() : "null");
439 
440     struct EventInfo eventInfo = {.bearerType = supplier->GetNetSupplierType(),
441                                   .ident = supplier->GetNetSupplierIdent(),
442                                   .supplierId = supplier->GetSupplierId()};
443     EventReport::SendSupplierBehaviorEvent(eventInfo);
444 
445     int32_t netId = supplier->GetNetId();
446     NET_NETWORK_MAP::iterator iterNetwork = networks_.find(netId);
447     if (iterNetwork != networks_.end()) {
448         NETMGR_LOG_I("the iterNetwork already exists.");
449         std::unique_lock<std::mutex> locker(netManagerMutex_);
450         networks_.erase(iterNetwork);
451         locker.unlock();
452     }
453     if (defaultNetSupplier_ == supplier) {
454         NETMGR_LOG_I("Set default net supplier to nullptr.");
455         sptr<NetSupplier> newSupplier = nullptr;
456         MakeDefaultNetWork(defaultNetSupplier_, newSupplier);
457     }
458     NetSupplierInfo info;
459     supplier->UpdateNetSupplierInfo(info);
460     std::unique_lock<std::mutex> locker(netManagerMutex_);
461     netSuppliers_.erase(supplierId);
462     locker.unlock();
463     FindBestNetworkForAllRequest();
464     NETMGR_LOG_I("UnregisterNetSupplier supplierId[%{public}d] out", supplierId);
465     return NETMANAGER_SUCCESS;
466 }
467 
UnregisterNetConnCallbackAsync(const sptr<INetConnCallback> & callback,const uint32_t callingUid)468 int32_t NetConnService::UnregisterNetConnCallbackAsync(const sptr<INetConnCallback> &callback,
469                                                        const uint32_t callingUid)
470 {
471     NETMGR_LOG_I("UnregisterNetConnCallback Enter, call uid [%{public}u]", callingUid);
472     if (callback == nullptr) {
473         NETMGR_LOG_E("callback is null");
474         return NETMANAGER_ERR_LOCAL_PTR_NULL;
475     }
476     DecreaseNetConnCallbackCntForUid(callingUid);
477     uint32_t reqId = 0;
478     if (!FindSameCallback(callback, reqId)) {
479         NETMGR_LOG_E("UnregisterNetConnCallback can not find same callback");
480         return NET_CONN_ERR_CALLBACK_NOT_FOUND;
481     }
482     NET_ACTIVATE_MAP::iterator iterActive;
483     for (iterActive = netActivates_.begin(); iterActive != netActivates_.end();) {
484         if (!iterActive->second) {
485             ++iterActive;
486             continue;
487         }
488         sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
489         if (saveCallback == nullptr) {
490             ++iterActive;
491             continue;
492         }
493         if (callback->AsObject().GetRefPtr() != saveCallback->AsObject().GetRefPtr()) {
494             ++iterActive;
495             continue;
496         }
497         reqId = iterActive->first;
498         auto netActivate = iterActive->second;
499         if (netActivate) {
500             sptr<NetSupplier> supplier = netActivate->GetServiceSupply();
501             if (supplier) {
502                 supplier->CancelRequest(reqId);
503             }
504         }
505         NET_SUPPLIER_MAP::iterator iterSupplier;
506         for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
507             if (iterSupplier->second != nullptr) {
508                 iterSupplier->second->CancelRequest(reqId);
509             }
510         }
511         iterActive = netActivates_.erase(iterActive);
512     }
513     NETMGR_LOG_I("UnregisterNetConnCallback End.");
514     return NETMANAGER_SUCCESS;
515 }
516 
IncreaseNetConnCallbackCntForUid(const uint32_t callingUid)517 int32_t NetConnService::IncreaseNetConnCallbackCntForUid(const uint32_t callingUid)
518 {
519     auto requestNetwork = netUidRequest_.find(callingUid);
520     if (requestNetwork == netUidRequest_.end()) {
521         netUidRequest_.insert(std::make_pair(callingUid, 1));
522     } else {
523         if (requestNetwork->second >= MAX_ALLOW_UID_NUM) {
524             NETMGR_LOG_E("return falied for UID [%{public}d] has registered over [%{public}d] callback",
525                          callingUid, MAX_ALLOW_UID_NUM);
526             return NET_CONN_ERR_NET_OVER_MAX_REQUEST_NUM;
527         } else {
528             requestNetwork->second++;
529         }
530     }
531     return NETMANAGER_SUCCESS;
532 }
533 
DecreaseNetConnCallbackCntForUid(const uint32_t callingUid)534 void NetConnService::DecreaseNetConnCallbackCntForUid(const uint32_t callingUid)
535 {
536     auto requestNetwork = netUidRequest_.find(callingUid);
537     if (requestNetwork == netUidRequest_.end()) {
538         NETMGR_LOG_E("Could not find the request calling uid");
539     } else {
540         if (requestNetwork->second >= 1) {
541             requestNetwork->second--;
542         }
543         if (requestNetwork->second == 0) {
544             netUidRequest_.erase(requestNetwork);
545         }
546     }
547 }
548 
RegUnRegNetDetectionCallbackAsync(int32_t netId,const sptr<INetDetectionCallback> & callback,bool isReg)549 int32_t NetConnService::RegUnRegNetDetectionCallbackAsync(int32_t netId, const sptr<INetDetectionCallback> &callback,
550                                                           bool isReg)
551 {
552     NETMGR_LOG_D("Enter NetConnService::RegUnRegNetDetectionCallback");
553     if (callback == nullptr) {
554         NETMGR_LOG_E("The parameter of callback is null");
555         return NETMANAGER_ERR_LOCAL_PTR_NULL;
556     }
557 
558     auto iterNetwork = networks_.find(netId);
559     if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
560         NETMGR_LOG_E("Could not find the corresponding network.");
561         return NET_CONN_ERR_NETID_NOT_FOUND;
562     }
563     if (isReg) {
564         iterNetwork->second->RegisterNetDetectionCallback(callback);
565         return NETMANAGER_SUCCESS;
566     }
567     return iterNetwork->second->UnRegisterNetDetectionCallback(callback);
568 }
569 
UpdateNetStateForTestAsync(const sptr<NetSpecifier> & netSpecifier,int32_t netState)570 int32_t NetConnService::UpdateNetStateForTestAsync(const sptr<NetSpecifier> &netSpecifier, int32_t netState)
571 {
572     NETMGR_LOG_D("Test NetConnService::UpdateNetStateForTest(), begin");
573     if (netSpecifier == nullptr) {
574         NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
575         return NETMANAGER_ERR_LOCAL_PTR_NULL;
576     }
577     return NETMANAGER_SUCCESS;
578 }
579 
UpdateNetSupplierInfoAsync(uint32_t supplierId,const sptr<NetSupplierInfo> & netSupplierInfo)580 int32_t NetConnService::UpdateNetSupplierInfoAsync(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo)
581 {
582     NETMGR_LOG_I("UpdateNetSupplierInfo service in. supplierId[%{public}d]", supplierId);
583     struct EventInfo eventInfo = {.updateSupplierId = supplierId};
584     if (netSupplierInfo == nullptr) {
585         NETMGR_LOG_E("netSupplierInfo is nullptr");
586         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_SUPPLIERINFO_INV_PARAM);
587         eventInfo.errorMsg = ERROR_MSG_NULL_SUPPLIER_INFO;
588         EventReport::SendSupplierFaultEvent(eventInfo);
589         return NETMANAGER_ERR_PARAMETER_ERROR;
590     }
591     eventInfo.supplierInfo = netSupplierInfo->ToString(" ");
592     EventReport::SendSupplierBehaviorEvent(eventInfo);
593 
594     auto supplier = FindNetSupplier(supplierId);
595     if (supplier == nullptr) {
596         NETMGR_LOG_E("Can not find supplier for supplierId[%{public}d]", supplierId);
597         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_SUPPLIERINFO_INV_PARAM);
598         eventInfo.errorMsg = std::string(ERROR_MSG_CAN_NOT_FIND_SUPPLIER).append(std::to_string(supplierId));
599         EventReport::SendSupplierFaultEvent(eventInfo);
600         return NET_CONN_ERR_NO_SUPPLIER;
601     }
602     NETMGR_LOG_I("Update supplier[%{public}d, %{public}s], supplierInfo:[ %{public}s ]", supplierId,
603                  supplier->GetNetSupplierIdent().c_str(), netSupplierInfo->ToString(" ").c_str());
604 
605     supplier->UpdateNetSupplierInfo(*netSupplierInfo);
606     if (!netSupplierInfo->isAvailable_) {
607         CallbackForSupplier(supplier, CALL_TYPE_LOST);
608     } else {
609         CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
610     }
611     if (!netScore_->GetServiceScore(supplier)) {
612         NETMGR_LOG_E("GetServiceScore fail.");
613     }
614     FindBestNetworkForAllRequest();
615     NETMGR_LOG_I("UpdateNetSupplierInfo service out.");
616     return NETMANAGER_SUCCESS;
617 }
618 
UpdateNetLinkInfoAsync(uint32_t supplierId,const sptr<NetLinkInfo> & netLinkInfo)619 int32_t NetConnService::UpdateNetLinkInfoAsync(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo)
620 {
621     NETMGR_LOG_I("UpdateNetLinkInfo service in. supplierId[%{public}d]", supplierId);
622     struct EventInfo eventInfo = {.updateNetlinkId = supplierId};
623 
624     if (netLinkInfo == nullptr) {
625         NETMGR_LOG_E("netLinkInfo is nullptr");
626         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_INV_PARAM);
627         eventInfo.errorMsg = ERROR_MSG_NULL_NET_LINK_INFO;
628         EventReport::SendSupplierFaultEvent(eventInfo);
629         return NETMANAGER_ERR_PARAMETER_ERROR;
630     }
631     eventInfo.netlinkInfo = netLinkInfo->ToString(" ");
632     EventReport::SendSupplierBehaviorEvent(eventInfo);
633 
634     auto supplier = FindNetSupplier(supplierId);
635     if (supplier == nullptr) {
636         NETMGR_LOG_E("supplier is nullptr");
637         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_INV_PARAM);
638         eventInfo.errorMsg = std::string(ERROR_MSG_CAN_NOT_FIND_SUPPLIER).append(std::to_string(supplierId));
639         EventReport::SendSupplierFaultEvent(eventInfo);
640         return NET_CONN_ERR_NO_SUPPLIER;
641     }
642 
643     HttpProxy oldHttpProxy;
644     supplier->GetHttpProxy(oldHttpProxy);
645     // According to supplier id, get network from the list
646     std::unique_lock<std::mutex> locker(netManagerMutex_);
647     if (supplier->UpdateNetLinkInfo(*netLinkInfo) != NETMANAGER_SUCCESS) {
648         NETMGR_LOG_E("UpdateNetLinkInfo fail");
649         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_FAILED);
650         eventInfo.errorMsg = ERROR_MSG_UPDATE_NETLINK_INFO_FAILED;
651         EventReport::SendSupplierFaultEvent(eventInfo);
652         return NET_CONN_ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL;
653     }
654     locker.unlock();
655     if (oldHttpProxy != netLinkInfo->httpProxy_) {
656         NETMGR_LOG_I("new httpProxy is %{public}s.", netLinkInfo->httpProxy_.ToString().c_str());
657         SendHttpProxyChangeBroadcast(netLinkInfo->httpProxy_);
658     }
659 
660     CallbackForSupplier(supplier, CALL_TYPE_UPDATE_LINK);
661     if (!netScore_->GetServiceScore(supplier)) {
662         NETMGR_LOG_E("GetServiceScore fail.");
663     }
664     FindBestNetworkForAllRequest();
665     NETMGR_LOG_I("UpdateNetLinkInfo service out.");
666     return NETMANAGER_SUCCESS;
667 }
668 
NetDetectionAsync(int32_t netId)669 int32_t NetConnService::NetDetectionAsync(int32_t netId)
670 {
671     NETMGR_LOG_I("Enter NetConnService::NetDetection, netId=[%{public}d]", netId);
672     auto iterNetwork = networks_.find(netId);
673     if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
674         NETMGR_LOG_E("Could not find the corresponding network.");
675         return NET_CONN_ERR_NETID_NOT_FOUND;
676     }
677     iterNetwork->second->StartNetDetection(true);
678     NETMGR_LOG_I("End NetConnService::NetDetection");
679     return NETMANAGER_SUCCESS;
680 }
681 
RestrictBackgroundChangedAsync(bool restrictBackground)682 int32_t NetConnService::RestrictBackgroundChangedAsync(bool restrictBackground)
683 {
684     NETMGR_LOG_I("Restrict background changed, background = %{public}d", restrictBackground);
685     for (auto it = netSuppliers_.begin(); it != netSuppliers_.end(); ++it) {
686         if (it->second == nullptr) {
687             continue;
688         }
689 
690         if (it->second->GetRestrictBackground() == restrictBackground) {
691             NETMGR_LOG_D("it->second->GetRestrictBackground() == restrictBackground");
692             return NET_CONN_ERR_NET_NO_RESTRICT_BACKGROUND;
693         }
694 
695         if (it->second->GetNetSupplierType() == BEARER_VPN) {
696             CallbackForSupplier(it->second, CALL_TYPE_BLOCK_STATUS);
697         }
698         it->second->SetRestrictBackground(restrictBackground);
699     }
700     NETMGR_LOG_I("End NetConnService::RestrictBackgroundChangedAsync");
701     return NETMANAGER_SUCCESS;
702 }
703 
SendHttpProxyChangeBroadcast(const HttpProxy & httpProxy)704 void NetConnService::SendHttpProxyChangeBroadcast(const HttpProxy &httpProxy)
705 {
706     BroadcastInfo info;
707     info.action = EventFwk::CommonEventSupport::COMMON_EVENT_HTTP_PROXY_CHANGE;
708     info.data = "Global HttpProxy Changed";
709     info.ordered = true;
710     std::map<std::string, std::string> param = {{"HttpProxy", httpProxy.ToString()}};
711     BroadcastManager::GetInstance().SendBroadcast(info, param);
712 }
713 
ActivateNetwork(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS)714 int32_t NetConnService::ActivateNetwork(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
715                                         const uint32_t &timeoutMS)
716 {
717     NETMGR_LOG_D("ActivateNetwork Enter");
718     if (netSpecifier == nullptr || callback == nullptr) {
719         NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
720         return NETMANAGER_ERR_PARAMETER_ERROR;
721     }
722     std::weak_ptr<INetActivateCallback> timeoutCb = shared_from_this();
723     std::shared_ptr<NetActivate> request =
724         std::make_shared<NetActivate>(netSpecifier, callback, timeoutCb, timeoutMS, netActEventHandler_);
725     request->StartTimeOutNetAvailable();
726     uint32_t reqId = request->GetRequestId();
727     NETMGR_LOG_I("Make a new request, request id:[%{public}d]", reqId);
728     netActivates_[reqId] = request;
729     sptr<NetSupplier> bestNet = nullptr;
730     int bestScore = static_cast<int>(FindBestNetworkForRequest(bestNet, request));
731     if (bestScore != 0 && bestNet != nullptr) {
732         NETMGR_LOG_I("Match to optimal supplier:[%{public}d %{public}s], netId[%{public}d], score:[%{public}d]",
733                      bestNet->GetSupplierId(), bestNet->GetNetSupplierIdent().c_str(), bestNet->GetNetId(), bestScore);
734         bestNet->SelectAsBestNetwork(reqId);
735         request->SetServiceSupply(bestNet);
736         CallbackForAvailable(bestNet, callback);
737         if ((bestNet->GetNetSupplierType() == BEARER_CELLULAR) || (bestNet->GetNetSupplierType() == BEARER_WIFI)) {
738             struct EventInfo eventInfo = {.capabilities = bestNet->GetNetCapabilities().ToString(" "),
739                                           .supplierIdent = bestNet->GetNetSupplierIdent()};
740             EventReport::SendRequestBehaviorEvent(eventInfo);
741         }
742         return NETMANAGER_SUCCESS;
743     }
744     if (timeoutMS == 0) {
745         callback->NetUnavailable();
746     }
747 
748     NETMGR_LOG_I("Not matched to the optimal network, send request to all networks.");
749     SendRequestToAllNetwork(request);
750     return NETMANAGER_SUCCESS;
751 }
752 
OnNetActivateTimeOut(uint32_t reqId)753 void NetConnService::OnNetActivateTimeOut(uint32_t reqId)
754 {
755     if (netConnEventHandler_) {
756         netConnEventHandler_->PostSyncTask([reqId, this]() {
757             NETMGR_LOG_I("DeactivateNetwork Enter, reqId is [%{public}d]", reqId);
758             auto iterActivate = netActivates_.find(reqId);
759             if (iterActivate == netActivates_.end()) {
760                 NETMGR_LOG_E("not found the reqId: [%{public}d]", reqId);
761                 return;
762             }
763             if (iterActivate->second != nullptr) {
764                 sptr<NetSupplier> pNetService = iterActivate->second->GetServiceSupply();
765                 if (pNetService) {
766                     pNetService->CancelRequest(reqId);
767                 }
768             }
769 
770             NET_SUPPLIER_MAP::iterator iterSupplier;
771             for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
772                 if (iterSupplier->second == nullptr) {
773                     continue;
774                 }
775                 iterSupplier->second->CancelRequest(reqId);
776             }
777         });
778     }
779 }
780 
FindNetSupplier(uint32_t supplierId)781 sptr<NetSupplier> NetConnService::FindNetSupplier(uint32_t supplierId)
782 {
783     auto iterSupplier = netSuppliers_.find(supplierId);
784     if (iterSupplier != netSuppliers_.end()) {
785         return iterSupplier->second;
786     }
787     return nullptr;
788 }
789 
FindSameCallback(const sptr<INetConnCallback> & callback,uint32_t & reqId)790 bool NetConnService::FindSameCallback(const sptr<INetConnCallback> &callback, uint32_t &reqId)
791 {
792     if (callback == nullptr) {
793         NETMGR_LOG_E("callback is null");
794         return false;
795     }
796     NET_ACTIVATE_MAP::iterator iterActive;
797     for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
798         if (!iterActive->second) {
799             continue;
800         }
801         sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
802         if (saveCallback == nullptr) {
803             continue;
804         }
805         if (callback->AsObject().GetRefPtr() == saveCallback->AsObject().GetRefPtr()) {
806             reqId = iterActive->first;
807             return true;
808         }
809     }
810     return false;
811 }
812 
FindBestNetworkForAllRequest()813 void NetConnService::FindBestNetworkForAllRequest()
814 {
815     NETMGR_LOG_I("FindBestNetworkForAllRequest Enter");
816     NET_ACTIVATE_MAP::iterator iterActive;
817     sptr<NetSupplier> bestSupplier = nullptr;
818     for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
819         if (!iterActive->second) {
820             continue;
821         }
822         int score = static_cast<int>(FindBestNetworkForRequest(bestSupplier, iterActive->second));
823         NETMGR_LOG_D("Find best supplier[%{public}d, %{public}s]for request[%{public}d]",
824                      bestSupplier ? bestSupplier->GetSupplierId() : 0,
825                      bestSupplier ? bestSupplier->GetNetSupplierIdent().c_str() : "null",
826                      iterActive->second->GetRequestId());
827         if (iterActive->second == defaultNetActivate_) {
828             MakeDefaultNetWork(defaultNetSupplier_, bestSupplier);
829         }
830         sptr<NetSupplier> oldSupplier = iterActive->second->GetServiceSupply();
831         sptr<INetConnCallback> callback = iterActive->second->GetNetCallback();
832         if (!bestSupplier) {
833             // not found the bestNetwork
834             NotFindBestSupplier(iterActive->first, iterActive->second, oldSupplier, callback);
835             continue;
836         }
837         SendBestScoreAllNetwork(iterActive->first, score, bestSupplier->GetSupplierId());
838         if (bestSupplier == oldSupplier) {
839             NETMGR_LOG_D("bestSupplier is equal with oldSupplier.");
840             continue;
841         }
842         if (oldSupplier) {
843             oldSupplier->RemoveBestRequest(iterActive->first);
844         }
845         iterActive->second->SetServiceSupply(bestSupplier);
846         CallbackForAvailable(bestSupplier, callback);
847         bestSupplier->SelectAsBestNetwork(iterActive->first);
848     }
849     NETMGR_LOG_I("FindBestNetworkForAllRequest end");
850 }
851 
FindBestNetworkForRequest(sptr<NetSupplier> & supplier,std::shared_ptr<NetActivate> & netActivateNetwork)852 uint32_t NetConnService::FindBestNetworkForRequest(sptr<NetSupplier> &supplier,
853                                                    std::shared_ptr<NetActivate> &netActivateNetwork)
854 {
855     int bestScore = 0;
856     supplier = nullptr;
857     if (netActivateNetwork == nullptr) {
858         NETMGR_LOG_E("netActivateNetwork is null");
859         return bestScore;
860     }
861 
862     NET_SUPPLIER_MAP::iterator iter;
863     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
864         if (iter->second == nullptr) {
865             continue;
866         }
867         NETMGR_LOG_D("supplier info, supplier[%{public}d, %{public}s], realScore[%{public}d], isConnected[%{public}d]",
868                      iter->second->GetSupplierId(), iter->second->GetNetSupplierIdent().c_str(),
869                      iter->second->GetRealScore(), iter->second->IsConnected());
870         if ((!iter->second->IsConnected()) || (!netActivateNetwork->MatchRequestAndNetwork(iter->second))) {
871             NETMGR_LOG_D("Supplier[%{public}d] is not connected or not match request.", iter->second->GetSupplierId());
872             continue;
873         }
874         int score = iter->second->GetRealScore();
875         if (score > bestScore) {
876             bestScore = score;
877             supplier = iter->second;
878         }
879     }
880     NETMGR_LOG_I(
881         "FindBestNetworkForRequest exit, bestScore[%{public}d], bestSupplier[%{public}d, %{public}s], "
882         "request[%{public}d] is [%{public}s],",
883         bestScore, supplier ? supplier->GetSupplierId() : 0,
884         supplier ? supplier->GetNetSupplierIdent().c_str() : "null", netActivateNetwork->GetRequestId(),
885         netActivateNetwork->GetNetSpecifier() ? netActivateNetwork->GetNetSpecifier()->ToString(" ").c_str() : "null");
886     return bestScore;
887 }
888 
RequestAllNetworkExceptDefault()889 void NetConnService::RequestAllNetworkExceptDefault()
890 {
891     if ((defaultNetSupplier_ == nullptr) || (defaultNetSupplier_->IsNetValidated())) {
892         NETMGR_LOG_E("defaultNetSupplier_ is  null or IsNetValidated");
893         return;
894     }
895     NETMGR_LOG_I("Default supplier[%{public}d, %{public}s] is not valid,request to activate another network",
896                  defaultNetSupplier_->GetSupplierId(), defaultNetSupplier_->GetNetSupplierIdent().c_str());
897     if (defaultNetActivate_ == nullptr) {
898         NETMGR_LOG_E("Default net request is null");
899         return;
900     }
901     // Request activation of all networks except the default network
902     uint32_t reqId = defaultNetActivate_->GetRequestId();
903     for (const auto &netSupplier : netSuppliers_) {
904         if (netSupplier.second == nullptr || netSupplier.second == defaultNetSupplier_) {
905             NETMGR_LOG_E("netSupplier is null or is defaultNetSupplier_");
906             continue;
907         }
908         if (netSupplier.second->GetNetScore() >= defaultNetSupplier_->GetNetScore()) {
909             continue;
910         }
911         if (!defaultNetActivate_->MatchRequestAndNetwork(netSupplier.second)) {
912             continue;
913         }
914         if (!netSupplier.second->RequestToConnect(reqId)) {
915             NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed",
916                          netSupplier.second->GetSupplierId(), netSupplier.second->GetNetSupplierIdent().c_str());
917         }
918     }
919 }
920 
GenerateNetId()921 int32_t NetConnService::GenerateNetId()
922 {
923     for (int32_t i = MIN_NET_ID; i <= MAX_NET_ID; ++i) {
924         netIdLastValue_++;
925         if (netIdLastValue_ > MAX_NET_ID) {
926             netIdLastValue_ = MIN_NET_ID;
927         }
928         if (networks_.find(netIdLastValue_) == networks_.end()) {
929             return netIdLastValue_;
930         }
931     }
932     return INVALID_NET_ID;
933 }
934 
NotFindBestSupplier(uint32_t reqId,const std::shared_ptr<NetActivate> & active,const sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)935 void NetConnService::NotFindBestSupplier(uint32_t reqId, const std::shared_ptr<NetActivate> &active,
936                                          const sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
937 {
938     NETMGR_LOG_I("Could not find best supplier for request:[%{public}d]", reqId);
939     if (supplier != nullptr) {
940         supplier->RemoveBestRequest(reqId);
941         if (callback != nullptr) {
942             sptr<NetHandle> netHandle = supplier->GetNetHandle();
943             callback->NetLost(netHandle);
944         }
945     }
946     if (active != nullptr) {
947         active->SetServiceSupply(nullptr);
948         SendRequestToAllNetwork(active);
949     }
950 }
951 
SendAllRequestToNetwork(sptr<NetSupplier> supplier)952 void NetConnService::SendAllRequestToNetwork(sptr<NetSupplier> supplier)
953 {
954     if (supplier == nullptr) {
955         NETMGR_LOG_E("supplier is null");
956         return;
957     }
958     NETMGR_LOG_I("Send all request to supplier[%{public}d, %{public}s]", supplier->GetSupplierId(),
959                  supplier->GetNetSupplierIdent().c_str());
960     NET_ACTIVATE_MAP::iterator iter;
961     for (iter = netActivates_.begin(); iter != netActivates_.end(); ++iter) {
962         if (iter->second == nullptr) {
963             continue;
964         }
965         if (!iter->second->MatchRequestAndNetwork(supplier)) {
966             continue;
967         }
968         bool result = supplier->RequestToConnect(iter->first);
969         if (!result) {
970             NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed", supplier->GetSupplierId(),
971                          supplier->GetNetSupplierIdent().c_str());
972         }
973     }
974 }
975 
SendRequestToAllNetwork(std::shared_ptr<NetActivate> request)976 void NetConnService::SendRequestToAllNetwork(std::shared_ptr<NetActivate> request)
977 {
978     if (request == nullptr) {
979         NETMGR_LOG_E("request is null");
980         return;
981     }
982 
983     uint32_t reqId = request->GetRequestId();
984     NETMGR_LOG_I("Send request[%{public}d] to all supplier", 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("Request network for supplier[%{public}d, %{public}s] failed", iter->second->GetSupplierId(),
996                          iter->second->GetNetSupplierIdent().c_str());
997         }
998     }
999 }
1000 
SendBestScoreAllNetwork(uint32_t reqId,int32_t bestScore,uint32_t supplierId)1001 void NetConnService::SendBestScoreAllNetwork(uint32_t reqId, int32_t bestScore, uint32_t supplierId)
1002 {
1003     NETMGR_LOG_I("Send best supplier[%{public}d]-score[%{public}d] to all supplier", supplierId, bestScore);
1004     NET_SUPPLIER_MAP::iterator iter;
1005     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1006         if (iter->second == nullptr) {
1007             continue;
1008         }
1009         iter->second->ReceiveBestScore(reqId, bestScore, supplierId);
1010     }
1011 }
1012 
CallbackForSupplier(sptr<NetSupplier> & supplier,CallbackType type)1013 void NetConnService::CallbackForSupplier(sptr<NetSupplier> &supplier, CallbackType type)
1014 {
1015     if (supplier == nullptr) {
1016         NETMGR_LOG_E("supplier is nullptr");
1017         return;
1018     }
1019     std::set<uint32_t> &bestReqList = supplier->GetBestRequestList();
1020     NETMGR_LOG_I("Callback type: %{public}d for supplier[%{public}d, %{public}s], best request size: %{public}zd",
1021                  static_cast<int32_t>(type), supplier->GetSupplierId(), supplier->GetNetSupplierIdent().c_str(),
1022                  bestReqList.size());
1023     for (auto it : bestReqList) {
1024         auto reqIt = netActivates_.find(it);
1025         if ((reqIt == netActivates_.end()) || (reqIt->second == nullptr)) {
1026             continue;
1027         }
1028         sptr<INetConnCallback> callback = reqIt->second->GetNetCallback();
1029         if (!callback) {
1030             continue;
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     NETMGR_LOG_I("Callback net available for supplier[%{public}d, %{public}s]",
1068                  supplier ? supplier->GetSupplierId() : 0,
1069                  supplier ? supplier->GetNetSupplierIdent().c_str() : "nullptr");
1070     if (supplier == nullptr || callback == nullptr) {
1071         NETMGR_LOG_E("Input parameter is null.");
1072         return;
1073     }
1074     sptr<NetHandle> netHandle = supplier->GetNetHandle();
1075     callback->NetAvailable(netHandle);
1076     sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
1077     *pNetAllCap = supplier->GetNetCapabilities();
1078     callback->NetCapabilitiesChange(netHandle, pNetAllCap);
1079     sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
1080     auto network = supplier->GetNetwork();
1081     if (network != nullptr && pInfo != nullptr) {
1082         *pInfo = network->GetNetLinkInfo();
1083     }
1084     callback->NetConnectionPropertiesChange(netHandle, pInfo);
1085 }
1086 
MakeDefaultNetWork(sptr<NetSupplier> & oldSupplier,sptr<NetSupplier> & newSupplier)1087 void NetConnService::MakeDefaultNetWork(sptr<NetSupplier> &oldSupplier, sptr<NetSupplier> &newSupplier)
1088 {
1089     NETMGR_LOG_I(
1090         "MakeDefaultNetWork in, oldSupplier[%{public}d, %{public}s], newSupplier[%{public}d, %{public}s], old equals "
1091         "new is [%{public}d]", oldSupplier ? oldSupplier->GetSupplierId() : 0,
1092         oldSupplier ? oldSupplier->GetNetSupplierIdent().c_str() : "null",
1093         newSupplier ? newSupplier->GetSupplierId() : 0,
1094         newSupplier ? newSupplier->GetNetSupplierIdent().c_str() : "null", oldSupplier == newSupplier);
1095     if (oldSupplier == newSupplier) {
1096         NETMGR_LOG_D("old supplier equal to new supplier.");
1097         return;
1098     }
1099     if (oldSupplier != nullptr) {
1100         oldSupplier->ClearDefault();
1101     }
1102     if (newSupplier != nullptr) {
1103         newSupplier->SetDefault();
1104     }
1105     std::lock_guard<std::mutex> locker(netManagerMutex_);
1106     oldSupplier = newSupplier;
1107 }
1108 
HandleDetectionResult(uint32_t supplierId,bool ifValid)1109 void NetConnService::HandleDetectionResult(uint32_t supplierId, bool ifValid)
1110 {
1111     NETMGR_LOG_I("Enter HandleDetectionResult, ifValid[%{public}d]", ifValid);
1112     auto supplier = FindNetSupplier(supplierId);
1113     if (supplier == nullptr) {
1114         NETMGR_LOG_E("supplier doesn't exist.");
1115         return;
1116     }
1117     supplier->SetNetValid(ifValid);
1118     CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
1119     if (!netScore_->GetServiceScore(supplier)) {
1120         NETMGR_LOG_E("GetServiceScore fail.");
1121         return;
1122     }
1123     FindBestNetworkForAllRequest();
1124     if (!ifValid && defaultNetSupplier_ && defaultNetSupplier_->GetSupplierId() == supplierId) {
1125         RequestAllNetworkExceptDefault();
1126     }
1127     NETMGR_LOG_I("Enter HandleDetectionResult end");
1128 }
1129 
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident)1130 std::list<sptr<NetSupplier>> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident)
1131 {
1132     std::lock_guard<std::mutex> locker(netManagerMutex_);
1133     std::list<sptr<NetSupplier>> ret;
1134     for (const auto &netSupplier : netSuppliers_) {
1135         if (netSupplier.second == nullptr) {
1136             continue;
1137         }
1138         if ((bearerType != netSupplier.second->GetNetSupplierType())) {
1139             continue;
1140         }
1141         if (!ident.empty() && netSupplier.second->GetNetSupplierIdent() != ident) {
1142             continue;
1143         }
1144         ret.push_back(netSupplier.second);
1145     }
1146     return ret;
1147 }
1148 
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps)1149 sptr<NetSupplier> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident,
1150                                                          const std::set<NetCap> &netCaps)
1151 {
1152     std::lock_guard<std::mutex> locker(netManagerMutex_);
1153     for (const auto &netSupplier : netSuppliers_) {
1154         if (netSupplier.second == nullptr) {
1155             continue;
1156         }
1157         if ((bearerType == netSupplier.second->GetNetSupplierType()) &&
1158             (ident == netSupplier.second->GetNetSupplierIdent()) && netSupplier.second->CompareNetCaps(netCaps)) {
1159             return netSupplier.second;
1160         }
1161     }
1162     return nullptr;
1163 }
1164 
GetDefaultNet(int32_t & netId)1165 int32_t NetConnService::GetDefaultNet(int32_t &netId)
1166 {
1167     std::lock_guard<std::mutex> locker(netManagerMutex_);
1168     if (!defaultNetSupplier_) {
1169         NETMGR_LOG_E("not found the netId");
1170         return NETMANAGER_SUCCESS;
1171     }
1172 
1173     netId = defaultNetSupplier_->GetNetId();
1174     NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
1175     return NETMANAGER_SUCCESS;
1176 }
1177 
GetAddressesByName(const std::string & host,int32_t netId,std::vector<INetAddr> & addrList)1178 int32_t NetConnService::GetAddressesByName(const std::string &host, int32_t netId, std::vector<INetAddr> &addrList)
1179 {
1180     return NetManagerCenter::GetInstance().GetAddressesByName(host, static_cast<uint16_t>(netId), addrList);
1181 }
1182 
GetAddressByName(const std::string & host,int32_t netId,INetAddr & addr)1183 int32_t NetConnService::GetAddressByName(const std::string &host, int32_t netId, INetAddr &addr)
1184 {
1185     std::vector<INetAddr> addrList;
1186     int ret = GetAddressesByName(host, netId, addrList);
1187     if (ret == NETMANAGER_SUCCESS) {
1188         if (!addrList.empty()) {
1189             addr = addrList[0];
1190             return ret;
1191         }
1192         return NET_CONN_ERR_NO_ADDRESS;
1193     }
1194     return ret;
1195 }
1196 
GetSpecificNet(NetBearType bearerType,std::list<int32_t> & netIdList)1197 int32_t NetConnService::GetSpecificNet(NetBearType bearerType, std::list<int32_t> &netIdList)
1198 {
1199     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1200         NETMGR_LOG_E("netType parameter invalid");
1201         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1202     }
1203 
1204     std::lock_guard<std::mutex> locker(netManagerMutex_);
1205     NET_SUPPLIER_MAP::iterator iterSupplier;
1206     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1207         if (iterSupplier->second == nullptr) {
1208             continue;
1209         }
1210         auto supplierType = iterSupplier->second->GetNetSupplierType();
1211         if (bearerType == supplierType) {
1212             netIdList.push_back(iterSupplier->second->GetNetId());
1213         }
1214     }
1215     NETMGR_LOG_D("netSuppliers_ size[%{public}zd] networks_ size[%{public}zd]", netSuppliers_.size(), networks_.size());
1216     return NETMANAGER_SUCCESS;
1217 }
1218 
GetAllNets(std::list<int32_t> & netIdList)1219 int32_t NetConnService::GetAllNets(std::list<int32_t> &netIdList)
1220 {
1221     std::lock_guard<std::mutex> locker(netManagerMutex_);
1222     for (const auto &network : networks_) {
1223         if (network.second != nullptr && network.second->IsConnected()) {
1224             netIdList.push_back(network.second->GetNetId());
1225         }
1226     }
1227     NETMGR_LOG_D("netSuppliers_ size[%{public}zd] netIdList size[%{public}zd]", netSuppliers_.size(), netIdList.size());
1228     return NETMANAGER_SUCCESS;
1229 }
1230 
GetSpecificUidNet(int32_t uid,int32_t & netId)1231 int32_t NetConnService::GetSpecificUidNet(int32_t uid, int32_t &netId)
1232 {
1233     NETMGR_LOG_D("Enter GetSpecificUidNet, uid is [%{public}d].", uid);
1234     std::lock_guard<std::mutex> locker(netManagerMutex_);
1235     netId = INVALID_NET_ID;
1236     NET_SUPPLIER_MAP::iterator iterSupplier;
1237     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1238         if ((iterSupplier->second != nullptr) && (uid == iterSupplier->second->GetSupplierUid()) &&
1239             (iterSupplier->second->GetNetSupplierType() == BEARER_VPN)) {
1240             netId = iterSupplier->second->GetNetId();
1241             return NETMANAGER_SUCCESS;
1242         }
1243     }
1244     if (defaultNetSupplier_ != nullptr) {
1245         netId = defaultNetSupplier_->GetNetId();
1246     }
1247     NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
1248     return NETMANAGER_SUCCESS;
1249 }
1250 
GetConnectionProperties(int32_t netId,NetLinkInfo & info)1251 int32_t NetConnService::GetConnectionProperties(int32_t netId, NetLinkInfo &info)
1252 {
1253     std::lock_guard<std::mutex> locker(netManagerMutex_);
1254     auto iterNetwork = networks_.find(netId);
1255     if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
1256         return NET_CONN_ERR_INVALID_NETWORK;
1257     }
1258 
1259     info = iterNetwork->second->GetNetLinkInfo();
1260     return NETMANAGER_SUCCESS;
1261 }
1262 
GetNetCapabilities(int32_t netId,NetAllCapabilities & netAllCap)1263 int32_t NetConnService::GetNetCapabilities(int32_t netId, NetAllCapabilities &netAllCap)
1264 {
1265     std::lock_guard<std::mutex> locker(netManagerMutex_);
1266     NET_SUPPLIER_MAP::iterator iterSupplier;
1267     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1268         if ((iterSupplier->second != nullptr) && (netId == iterSupplier->second->GetNetId())) {
1269             netAllCap = iterSupplier->second->GetNetCapabilities();
1270             return NETMANAGER_SUCCESS;
1271         }
1272     }
1273     return NET_CONN_ERR_INVALID_NETWORK;
1274 }
1275 
GetIfaceNames(NetBearType bearerType,std::list<std::string> & ifaceNames)1276 int32_t NetConnService::GetIfaceNames(NetBearType bearerType, std::list<std::string> &ifaceNames)
1277 {
1278     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1279         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1280     }
1281 
1282     auto suppliers = GetNetSupplierFromList(bearerType);
1283     for (auto supplier : suppliers) {
1284         if (supplier == nullptr) {
1285             continue;
1286         }
1287         std::shared_ptr<Network> network = supplier->GetNetwork();
1288         if (network == nullptr) {
1289             continue;
1290         }
1291         std::string ifaceName = network->GetNetLinkInfo().ifaceName_;
1292         if (!ifaceName.empty()) {
1293             ifaceNames.push_back(ifaceName);
1294         }
1295     }
1296     return NETMANAGER_SUCCESS;
1297 }
1298 
GetIfaceNameByType(NetBearType bearerType,const std::string & ident,std::string & ifaceName)1299 int32_t NetConnService::GetIfaceNameByType(NetBearType bearerType, const std::string &ident, std::string &ifaceName)
1300 {
1301     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1302         NETMGR_LOG_E("netType parameter invalid");
1303         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1304     }
1305 
1306     auto suppliers = GetNetSupplierFromList(bearerType, ident);
1307     if (suppliers.empty()) {
1308         NETMGR_LOG_D("supplier is nullptr.");
1309         return NET_CONN_ERR_NO_SUPPLIER;
1310     }
1311     auto supplier = suppliers.front();
1312     std::shared_ptr<Network> network = supplier->GetNetwork();
1313     if (network == nullptr) {
1314         NETMGR_LOG_E("network is nullptr");
1315         return NET_CONN_ERR_INVALID_NETWORK;
1316     }
1317 
1318     ifaceName = network->GetNetLinkInfo().ifaceName_;
1319 
1320     return NETMANAGER_SUCCESS;
1321 }
1322 
GetGlobalHttpProxy(HttpProxy & httpProxy)1323 int32_t NetConnService::GetGlobalHttpProxy(HttpProxy &httpProxy)
1324 {
1325     LoadGlobalHttpProxy();
1326     if (globalHttpProxy_.GetHost().empty()) {
1327         httpProxy.SetPort(0);
1328         NETMGR_LOG_E("The http proxy host is empty");
1329         return NETMANAGER_SUCCESS;
1330     }
1331     httpProxy = globalHttpProxy_;
1332     return NETMANAGER_SUCCESS;
1333 }
1334 
GetDefaultHttpProxy(int32_t bindNetId,HttpProxy & httpProxy)1335 int32_t NetConnService::GetDefaultHttpProxy(int32_t bindNetId, HttpProxy &httpProxy)
1336 {
1337     LoadGlobalHttpProxy();
1338     if (!globalHttpProxy_.GetHost().empty()) {
1339         httpProxy = globalHttpProxy_;
1340         NETMGR_LOG_D("Return global http proxy as default.");
1341         return NETMANAGER_SUCCESS;
1342     }
1343 
1344     std::lock_guard<std::mutex> locker(netManagerMutex_);
1345     auto iter = networks_.find(bindNetId);
1346     if ((iter != networks_.end()) && (iter->second != nullptr)) {
1347         httpProxy = iter->second->GetNetLinkInfo().httpProxy_;
1348         NETMGR_LOG_D("Return bound network's http proxy as default.");
1349         return NETMANAGER_SUCCESS;
1350     }
1351 
1352     if (defaultNetSupplier_ != nullptr) {
1353         defaultNetSupplier_->GetHttpProxy(httpProxy);
1354         NETMGR_LOG_D("Return default network's http proxy as default.");
1355         return NETMANAGER_SUCCESS;
1356     }
1357     NETMGR_LOG_E("No default http proxy.");
1358     return NETMANAGER_SUCCESS;
1359 }
1360 
GetNetIdByIdentifier(const std::string & ident,std::list<int32_t> & netIdList)1361 int32_t NetConnService::GetNetIdByIdentifier(const std::string &ident, std::list<int32_t> &netIdList)
1362 {
1363     if (ident.empty()) {
1364         NETMGR_LOG_E("The identifier in service is null");
1365         return NETMANAGER_ERR_INVALID_PARAMETER;
1366     }
1367     std::lock_guard<std::mutex> locker(netManagerMutex_);
1368     for (auto iterSupplier : netSuppliers_) {
1369         if (iterSupplier.second == nullptr) {
1370             continue;
1371         }
1372         if (iterSupplier.second->GetNetSupplierIdent() == ident) {
1373             int32_t netId = iterSupplier.second->GetNetId();
1374             netIdList.push_back(netId);
1375         }
1376     }
1377     return NETMANAGER_SUCCESS;
1378 }
1379 
GetDumpMessage(std::string & message)1380 void NetConnService::GetDumpMessage(std::string &message)
1381 {
1382     message.append("Net connect Info:\n");
1383     std::lock_guard<std::mutex> locker(netManagerMutex_);
1384     if (defaultNetSupplier_) {
1385         message.append("\tSupplierId: " + std::to_string(defaultNetSupplier_->GetSupplierId()) + "\n");
1386         std::shared_ptr<Network> network = defaultNetSupplier_->GetNetwork();
1387         if (network) {
1388             message.append("\tNetId: " + std::to_string(network->GetNetId()) + "\n");
1389         } else {
1390             message.append("\tNetId: " + std::to_string(INVALID_NET_ID) + "\n");
1391         }
1392         message.append("\tConnStat: " + std::to_string(defaultNetSupplier_->IsConnected()) + "\n");
1393         message.append("\tIsAvailable: " + std::to_string(defaultNetSupplier_->IsNetValidated()) + "\n");
1394         message.append("\tIsRoaming: " + std::to_string(defaultNetSupplier_->GetRoaming()) + "\n");
1395         message.append("\tStrength: " + std::to_string(defaultNetSupplier_->GetStrength()) + "\n");
1396         message.append("\tFrequency: " + std::to_string(defaultNetSupplier_->GetFrequency()) + "\n");
1397         message.append("\tLinkUpBandwidthKbps: " +
1398                        std::to_string(defaultNetSupplier_->GetNetCapabilities().linkUpBandwidthKbps_) + "\n");
1399         message.append("\tLinkDownBandwidthKbps: " +
1400                        std::to_string(defaultNetSupplier_->GetNetCapabilities().linkDownBandwidthKbps_) + "\n");
1401         message.append("\tUid: " + std::to_string(defaultNetSupplier_->GetSupplierUid()) + "\n");
1402     } else {
1403         message.append("\tdefaultNetSupplier_ is nullptr\n");
1404         message.append("\tSupplierId: \n");
1405         message.append("\tNetId: 0\n");
1406         message.append("\tConnStat: 0\n");
1407         message.append("\tIsAvailable: \n");
1408         message.append("\tIsRoaming: 0\n");
1409         message.append("\tStrength: 0\n");
1410         message.append("\tFrequency: 0\n");
1411         message.append("\tLinkUpBandwidthKbps: 0\n");
1412         message.append("\tLinkDownBandwidthKbps: 0\n");
1413         message.append("\tUid: 0\n");
1414     }
1415     if (dnsResultCallback_ != nullptr) {
1416         dnsResultCallback_->GetDumpMessageForDnsResult(message);
1417     }
1418 }
1419 
HasDefaultNet(bool & flag)1420 int32_t NetConnService::HasDefaultNet(bool &flag)
1421 {
1422     std::lock_guard<std::mutex> locker(netManagerMutex_);
1423     if (!defaultNetSupplier_) {
1424         flag = false;
1425         return NETMANAGER_SUCCESS;
1426     }
1427     flag = true;
1428     return NETMANAGER_SUCCESS;
1429 }
1430 
IsDefaultNetMetered(bool & isMetered)1431 int32_t NetConnService::IsDefaultNetMetered(bool &isMetered)
1432 {
1433     std::lock_guard<std::mutex> locker(netManagerMutex_);
1434     if (defaultNetSupplier_) {
1435         isMetered = !defaultNetSupplier_->HasNetCap(NET_CAPABILITY_NOT_METERED);
1436     } else {
1437         isMetered = true;
1438     }
1439     return NETMANAGER_SUCCESS;
1440 }
1441 
BindSocket(int32_t socketFd,int32_t netId)1442 int32_t NetConnService::BindSocket(int32_t socketFd, int32_t netId)
1443 {
1444     NETMGR_LOG_D("Enter BindSocket.");
1445     return NetsysController::GetInstance().BindSocket(socketFd, netId);
1446 }
1447 
Dump(int32_t fd,const std::vector<std::u16string> & args)1448 int32_t NetConnService::Dump(int32_t fd, const std::vector<std::u16string> &args)
1449 {
1450     NETMGR_LOG_D("Start Dump, fd: %{public}d", fd);
1451     std::string result;
1452     GetDumpMessage(result);
1453     int32_t ret = dprintf(fd, "%s\n", result.c_str());
1454     return (ret < 0) ? static_cast<int32_t>(NET_CONN_ERR_CREATE_DUMP_FAILED) : static_cast<int32_t>(NETMANAGER_SUCCESS);
1455 }
1456 
SetAirplaneMode(bool state)1457 int32_t NetConnService::SetAirplaneMode(bool state)
1458 {
1459     NETMGR_LOG_I("Enter SetAirplaneMode, AirplaneMode is %{public}d", state);
1460     auto dataShareHelperUtils = std::make_unique<NetDataShareHelperUtils>();
1461     std::string airplaneMode = std::to_string(state);
1462     Uri uri(AIRPLANE_MODE_URI);
1463     int32_t ret = dataShareHelperUtils->Update(uri, KEY_AIRPLANE_MODE, airplaneMode);
1464     if (ret != NETMANAGER_SUCCESS) {
1465         NETMGR_LOG_E("Update airplane mode:%{public}d to datashare failed.", state);
1466         return NETMANAGER_ERR_INTERNAL;
1467     }
1468 
1469     BroadcastInfo info;
1470     info.action = EventFwk::CommonEventSupport::COMMON_EVENT_AIRPLANE_MODE_CHANGED;
1471     info.data = "Net Manager Airplane Mode Changed";
1472     info.code = static_cast<int32_t>(state);
1473     info.ordered = false;
1474     std::map<std::string, int32_t> param;
1475     BroadcastManager::GetInstance().SendBroadcast(info, param);
1476     NETMGR_LOG_I("End SetAirplaneMode.");
1477     return NETMANAGER_SUCCESS;
1478 }
1479 
ActiveHttpProxy()1480 void NetConnService::ActiveHttpProxy()
1481 {
1482     while (httpProxyThreadNeedRun_.load()) {
1483         CURL *curl = nullptr;
1484         HttpProxy tempProxy;
1485         {
1486             std::lock_guard guard(globalHttpProxyMutex_);
1487             tempProxy = globalHttpProxy_;
1488         }
1489         auto proxyType = (tempProxy.host_.find("https://") != std::string::npos) ? CURLPROXY_HTTPS : CURLPROXY_HTTP;
1490         if (!tempProxy.host_.empty() && !tempProxy.username_.empty()) {
1491             curl = curl_easy_init();
1492             curl_easy_setopt(curl, CURLOPT_URL, NET_HTTP_PROBE_URL);
1493             curl_easy_setopt(curl, CURLOPT_PROXY, tempProxy.host_.c_str());
1494             curl_easy_setopt(curl, CURLOPT_PROXYPORT, tempProxy.port_);
1495             curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxyType);
1496             curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, tempProxy.username_.c_str());
1497             curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
1498             if (!tempProxy.password_.empty()) {
1499                 curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, tempProxy.password_.c_str());
1500             }
1501         }
1502         if (curl) {
1503             auto ret = curl_easy_perform(curl);
1504             NETMGR_LOG_I("SetGlobalHttpProxy ActiveHttpProxy %{public}d", static_cast<int>(ret));
1505             curl_easy_cleanup(curl);
1506         }
1507         std::unique_lock lock(httpProxyThreadMutex_);
1508         httpProxyThreadCv_.wait_for(lock, std::chrono::seconds(HTTP_PROXY_ACTIVE_PERIOD_S));
1509     }
1510 }
1511 
SetGlobalHttpProxy(const HttpProxy & httpProxy)1512 int32_t NetConnService::SetGlobalHttpProxy(const HttpProxy &httpProxy)
1513 {
1514     NETMGR_LOG_I("Enter SetGlobalHttpProxy.");
1515     if (!httpProxyThreadNeedRun_) {
1516         httpProxyThreadNeedRun_ = true;
1517         std::thread([this]() { ActiveHttpProxy(); }).detach();
1518     }
1519     LoadGlobalHttpProxy();
1520     if (globalHttpProxy_ != httpProxy) {
1521         {
1522             std::lock_guard guard(globalHttpProxyMutex_);
1523             globalHttpProxy_ = httpProxy;
1524         }
1525         httpProxyThreadCv_.notify_all();
1526         NetHttpProxyTracker httpProxyTracker;
1527         if (!httpProxyTracker.WriteToSettingsData(globalHttpProxy_)) {
1528             NETMGR_LOG_E("GlobalHttpProxy write settingDate fail.");
1529             return NETMANAGER_ERR_INTERNAL;
1530         }
1531         SendHttpProxyChangeBroadcast(globalHttpProxy_);
1532         UpdateGlobalHttpProxy(globalHttpProxy_);
1533     }
1534     NETMGR_LOG_I("End SetGlobalHttpProxy.");
1535     return NETMANAGER_SUCCESS;
1536 }
1537 
SetAppNet(int32_t netId)1538 int32_t NetConnService::SetAppNet(int32_t netId)
1539 {
1540     return NETMANAGER_SUCCESS;
1541 }
1542 
RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)1543 int32_t NetConnService::RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback)
1544 {
1545     if (callback == nullptr) {
1546         NETMGR_LOG_E("callback is nullptr");
1547         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1548     }
1549     NETMGR_LOG_I("Enter RegisterNetInterfaceCallback.");
1550     if (interfaceStateCallback_ == nullptr) {
1551         NETMGR_LOG_E("interfaceStateCallback_ is nullptr");
1552         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1553     }
1554     return interfaceStateCallback_->RegisterInterfaceCallback(callback);
1555 }
1556 
GetNetInterfaceConfiguration(const std::string & iface,NetInterfaceConfiguration & config)1557 int32_t NetConnService::GetNetInterfaceConfiguration(const std::string &iface, NetInterfaceConfiguration &config)
1558 {
1559     using namespace OHOS::nmd;
1560     InterfaceConfigurationParcel configParcel;
1561     configParcel.ifName = iface;
1562     if (NetsysController::GetInstance().GetInterfaceConfig(configParcel) != NETMANAGER_SUCCESS) {
1563         return NETMANAGER_ERR_INTERNAL;
1564     }
1565     config.ifName_ = configParcel.ifName;
1566     config.hwAddr_ = configParcel.hwAddr;
1567     config.ipv4Addr_ = configParcel.ipv4Addr;
1568     config.prefixLength_ = configParcel.prefixLength;
1569     config.flags_.assign(configParcel.flags.begin(), configParcel.flags.end());
1570     return NETMANAGER_SUCCESS;
1571 }
1572 
NetDetectionForDnsHealth(int32_t netId,bool dnsHealthSuccess)1573 int32_t NetConnService::NetDetectionForDnsHealth(int32_t netId, bool dnsHealthSuccess)
1574 {
1575     NETMGR_LOG_D("Enter NetConnService::NetDetectionForDnsHealth");
1576     auto iterNetwork = networks_.find(netId);
1577     if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
1578         NETMGR_LOG_E("Could not find the corresponding network");
1579         return NET_CONN_ERR_NETID_NOT_FOUND;
1580     }
1581     iterNetwork->second->NetDetectionForDnsHealth(dnsHealthSuccess);
1582     return NETMANAGER_SUCCESS;
1583 }
1584 
LoadGlobalHttpProxy()1585 void NetConnService::LoadGlobalHttpProxy()
1586 {
1587     if (isGlobalProxyLoaded_.load()) {
1588         NETMGR_LOG_D("Global http proxy has been loaded from the SettingsData database.");
1589         return;
1590     }
1591     NetHttpProxyTracker httpProxyTracker;
1592     httpProxyTracker.ReadFromSettingsData(globalHttpProxy_);
1593     isGlobalProxyLoaded_ = true;
1594 }
1595 
UpdateGlobalHttpProxy(const HttpProxy & httpProxy)1596 void NetConnService::UpdateGlobalHttpProxy(const HttpProxy &httpProxy)
1597 {
1598     if (netConnEventHandler_ == nullptr) {
1599         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1600         return;
1601     }
1602     NETMGR_LOG_I("UpdateGlobalHttpProxy start");
1603     netConnEventHandler_->PostAsyncTask([this, httpProxy]() {
1604         for (const auto &supplier : netSuppliers_) {
1605             if (supplier.second == nullptr) {
1606                 continue;
1607             }
1608             supplier.second->UpdateGlobalHttpProxy(httpProxy);
1609         }
1610         NETMGR_LOG_I("UpdateGlobalHttpProxy end");
1611     });
1612 }
1613 
OnInterfaceAddressUpdated(const std::string & addr,const std::string & ifName,int flags,int scope)1614 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAddressUpdated(const std::string &addr,
1615                                                                              const std::string &ifName, int flags,
1616                                                                              int scope)
1617 {
1618     std::lock_guard<std::mutex> locker(mutex_);
1619     for (const auto &callback : ifaceStateCallbacks_) {
1620         if (callback == nullptr) {
1621             NETMGR_LOG_E("callback is null");
1622             continue;
1623         }
1624         callback->OnInterfaceAddressUpdated(addr, ifName, flags, scope);
1625     }
1626     return NETMANAGER_SUCCESS;
1627 }
1628 
OnInterfaceAddressRemoved(const std::string & addr,const std::string & ifName,int flags,int scope)1629 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAddressRemoved(const std::string &addr,
1630                                                                              const std::string &ifName, int flags,
1631                                                                              int scope)
1632 {
1633     std::lock_guard<std::mutex> locker(mutex_);
1634     for (const auto &callback : ifaceStateCallbacks_) {
1635         if (callback == nullptr) {
1636             NETMGR_LOG_E("callback is null");
1637             continue;
1638         }
1639         callback->OnInterfaceAddressRemoved(addr, ifName, flags, scope);
1640     }
1641     return NETMANAGER_SUCCESS;
1642 }
1643 
OnInterfaceAdded(const std::string & iface)1644 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAdded(const std::string &iface)
1645 {
1646     std::lock_guard<std::mutex> locker(mutex_);
1647     for (const auto &callback : ifaceStateCallbacks_) {
1648         if (callback == nullptr) {
1649             NETMGR_LOG_E("callback is null");
1650             continue;
1651         }
1652         callback->OnInterfaceAdded(iface);
1653     }
1654     return NETMANAGER_SUCCESS;
1655 }
1656 
OnInterfaceRemoved(const std::string & iface)1657 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceRemoved(const std::string &iface)
1658 {
1659     std::lock_guard<std::mutex> locker(mutex_);
1660     for (const auto &callback : ifaceStateCallbacks_) {
1661         if (callback == nullptr) {
1662             NETMGR_LOG_E("callback is null");
1663             continue;
1664         }
1665         callback->OnInterfaceRemoved(iface);
1666     }
1667     return NETMANAGER_SUCCESS;
1668 }
1669 
OnInterfaceChanged(const std::string & iface,bool up)1670 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceChanged(const std::string &iface, bool up)
1671 {
1672     std::lock_guard<std::mutex> locker(mutex_);
1673     for (const auto &callback : ifaceStateCallbacks_) {
1674         if (callback == nullptr) {
1675             NETMGR_LOG_E("callback is null");
1676             continue;
1677         }
1678         callback->OnInterfaceChanged(iface, up);
1679     }
1680     return NETMANAGER_SUCCESS;
1681 }
1682 
OnInterfaceLinkStateChanged(const std::string & iface,bool up)1683 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceLinkStateChanged(const std::string &iface, bool up)
1684 {
1685     std::lock_guard<std::mutex> locker(mutex_);
1686     for (const auto &callback : ifaceStateCallbacks_) {
1687         if (callback == nullptr) {
1688             NETMGR_LOG_E("callback is null");
1689             continue;
1690         }
1691         callback->OnInterfaceLinkStateChanged(iface, up);
1692     }
1693     return NETMANAGER_SUCCESS;
1694 }
1695 
OnRouteChanged(bool updated,const std::string & route,const std::string & gateway,const std::string & ifName)1696 int32_t NetConnService::NetInterfaceStateCallback::OnRouteChanged(bool updated, const std::string &route,
1697                                                                   const std::string &gateway, const std::string &ifName)
1698 {
1699     return NETMANAGER_SUCCESS;
1700 }
1701 
OnDhcpSuccess(NetsysControllerCallback::DhcpResult & dhcpResult)1702 int32_t NetConnService::NetInterfaceStateCallback::OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult)
1703 {
1704     return NETMANAGER_SUCCESS;
1705 }
1706 
OnBandwidthReachedLimit(const std::string & limitName,const std::string & iface)1707 int32_t NetConnService::NetInterfaceStateCallback::OnBandwidthReachedLimit(const std::string &limitName,
1708                                                                            const std::string &iface)
1709 {
1710     return NETMANAGER_SUCCESS;
1711 }
1712 
RegisterInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)1713 int32_t NetConnService::NetInterfaceStateCallback::RegisterInterfaceCallback(
1714     const sptr<INetInterfaceStateCallback> &callback)
1715 {
1716     if (callback == nullptr) {
1717         NETMGR_LOG_E("callback is null");
1718         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1719     }
1720 
1721     std::lock_guard<std::mutex> locker(mutex_);
1722     for (const auto &iter : ifaceStateCallbacks_) {
1723         if (!iter) {
1724             continue;
1725         }
1726         if (iter->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
1727             NETMGR_LOG_E("RegisterInterfaceCallback find same callback");
1728             return NET_CONN_ERR_SAME_CALLBACK;
1729         }
1730     }
1731     ifaceStateCallbacks_.push_back(callback);
1732     return NETMANAGER_SUCCESS;
1733 }
1734 
AddNetworkRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)1735 int32_t NetConnService::AddNetworkRoute(int32_t netId, const std::string &ifName,
1736                                         const std::string &destination, const std::string &nextHop)
1737 {
1738     return NetsysController::GetInstance().NetworkAddRoute(netId, ifName, destination, nextHop);
1739 }
1740 
RemoveNetworkRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)1741 int32_t NetConnService::RemoveNetworkRoute(int32_t netId, const std::string &ifName,
1742                                            const std::string &destination, const std::string &nextHop)
1743 {
1744     return NetsysController::GetInstance().NetworkRemoveRoute(netId, ifName, destination, nextHop);
1745 }
1746 
AddInterfaceAddress(const std::string & ifName,const std::string & ipAddr,int32_t prefixLength)1747 int32_t NetConnService::AddInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
1748                                             int32_t prefixLength)
1749 {
1750     return NetsysController::GetInstance().AddInterfaceAddress(ifName, ipAddr, prefixLength);
1751 }
1752 
DelInterfaceAddress(const std::string & ifName,const std::string & ipAddr,int32_t prefixLength)1753 int32_t NetConnService::DelInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
1754                                             int32_t prefixLength)
1755 {
1756     return NetsysController::GetInstance().DelInterfaceAddress(ifName, ipAddr, prefixLength);
1757 }
1758 
AddStaticArp(const std::string & ipAddr,const std::string & macAddr,const std::string & ifName)1759 int32_t NetConnService::AddStaticArp(const std::string &ipAddr, const std::string &macAddr,
1760                                      const std::string &ifName)
1761 {
1762     return NetsysController::GetInstance().AddStaticArp(ipAddr, macAddr, ifName);
1763 }
1764 
DelStaticArp(const std::string & ipAddr,const std::string & macAddr,const std::string & ifName)1765 int32_t NetConnService::DelStaticArp(const std::string &ipAddr, const std::string &macAddr,
1766                                      const std::string &ifName)
1767 {
1768     return NetsysController::GetInstance().DelStaticArp(ipAddr, macAddr, ifName);
1769 }
1770 
RegisterSlotType(uint32_t supplierId,int32_t type)1771 int32_t NetConnService::RegisterSlotType(uint32_t supplierId, int32_t type)
1772 {
1773     int32_t result = NETMANAGER_SUCCESS;
1774     if (netConnEventHandler_) {
1775         netConnEventHandler_->PostSyncTask([this, supplierId, type, &result]() {
1776             if (netSuppliers_.find(supplierId) == netSuppliers_.end()) {
1777                 NETMGR_LOG_E("supplierId[%{public}d] is not exits", supplierId);
1778                 result =  NETMANAGER_ERR_INVALID_PARAMETER;
1779             } else {
1780                 NETMGR_LOG_I("supplierId[%{public}d] update type[%{public}d].", supplierId, type);
1781                 sptr<NetSupplier> supplier = netSuppliers_[supplierId];
1782                 supplier->SetSupplierType(type);
1783                 result =  NETMANAGER_SUCCESS;
1784             }
1785         });
1786     }
1787     return result;
1788 }
1789 
GetSlotType(std::string & type)1790 int32_t NetConnService::GetSlotType(std::string &type)
1791 {
1792     int32_t result = NETMANAGER_SUCCESS;
1793     if (netConnEventHandler_) {
1794         netConnEventHandler_->PostSyncTask([this, &type, &result]() {
1795             if (defaultNetSupplier_ == nullptr) {
1796                 NETMGR_LOG_E("supplier is nullptr");
1797                 result =  NETMANAGER_ERR_LOCAL_PTR_NULL;
1798             } else {
1799                 type = defaultNetSupplier_->GetSupplierType();
1800                 result =  NETMANAGER_SUCCESS;
1801             }
1802         });
1803     }
1804     return result;
1805 }
1806 
FactoryResetNetwork()1807 int32_t NetConnService::FactoryResetNetwork()
1808 {
1809     NETMGR_LOG_I("Enter FactoryResetNetwork.");
1810 
1811     SetAirplaneMode(false);
1812 
1813     if (netFactoryResetCallback_ == nullptr) {
1814         NETMGR_LOG_E("netFactoryResetCallback_ is nullptr");
1815         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1816     }
1817     netFactoryResetCallback_->NotifyNetFactoryResetAsync();
1818 
1819     NETMGR_LOG_I("End FactoryResetNetwork.");
1820     return NETMANAGER_SUCCESS;
1821 }
1822 
RegisterNetFactoryResetCallback(const sptr<INetFactoryResetCallback> & callback)1823 int32_t NetConnService::RegisterNetFactoryResetCallback(const sptr<INetFactoryResetCallback> &callback)
1824 {
1825     if (callback == nullptr) {
1826         NETMGR_LOG_E("callback is nullptr");
1827         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1828     }
1829     NETMGR_LOG_I("Enter RegisterNetFactoryResetCallback.");
1830     if (netFactoryResetCallback_ == nullptr) {
1831         NETMGR_LOG_E("netFactoryResetCallback_ is nullptr");
1832         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1833     }
1834     return netFactoryResetCallback_->RegisterNetFactoryResetCallbackAsync(callback);
1835 }
1836 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)1837 void NetConnService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
1838 {
1839     NETMGR_LOG_I("NetConnService::OnAddSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
1840     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
1841         if (hasSARemoved_) {
1842             OnNetSysRestart();
1843             hasSARemoved_ = false;
1844         }
1845     }
1846 }
1847 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)1848 void NetConnService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
1849 {
1850     NETMGR_LOG_I("NetConnService::OnRemoveSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
1851     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
1852         hasSARemoved_ = true;
1853     }
1854 }
1855 
IsSupplierMatchRequestAndNetwork(sptr<NetSupplier> ns)1856 bool NetConnService::IsSupplierMatchRequestAndNetwork(sptr<NetSupplier> ns)
1857 {
1858     NET_ACTIVATE_MAP::iterator iterActive;
1859     for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
1860         if (!iterActive->second) {
1861             continue;
1862         }
1863         if (iterActive->second->MatchRequestAndNetwork(ns)) {
1864             return true;
1865         }
1866     }
1867 
1868     return false;
1869 }
1870 
OnNetSysRestart()1871 void NetConnService::OnNetSysRestart()
1872 {
1873     NETMGR_LOG_I("NetConnService::OnNetSysRestart");
1874 
1875     NET_SUPPLIER_MAP::iterator iter;
1876     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1877         if (iter->second == nullptr) {
1878             continue;
1879         }
1880 
1881         NETMGR_LOG_D("supplier info, supplier[%{public}d, %{public}s], realScore[%{public}d], isConnected[%{public}d]",
1882             iter->second->GetSupplierId(), iter->second->GetNetSupplierIdent().c_str(),
1883             iter->second->GetRealScore(), iter->second->IsConnected());
1884 
1885         if ((!iter->second->IsConnected()) || (!IsSupplierMatchRequestAndNetwork(iter->second))) {
1886             NETMGR_LOG_D("Supplier[%{public}d] is not connected or not match request.", iter->second->GetSupplierId());
1887             continue;
1888         }
1889 
1890         iter->second->ResumeNetworkInfo();
1891     }
1892 
1893     if (defaultNetSupplier_ != nullptr) {
1894         defaultNetSupplier_->ClearDefault();
1895         defaultNetSupplier_ = nullptr;
1896     }
1897 
1898     FindBestNetworkForAllRequest();
1899 }
1900 
IsPreferCellularUrl(const std::string & url,bool & preferCellular)1901 int32_t NetConnService::IsPreferCellularUrl(const std::string& url, bool& preferCellular)
1902 {
1903     static std::vector<std::string> preferredUrlList = GetPreferredUrl();
1904     preferCellular = std::any_of(preferredUrlList.begin(), preferredUrlList.end(),
1905                                  [&url](const std::string &str) { return url.find(str) != std::string::npos; });
1906     return 0;
1907 }
1908 
GetPreferredUrl()1909 std::vector<std::string> NetConnService::GetPreferredUrl()
1910 {
1911     std::vector<std::string> preferCellularUrlList;
1912     const std::string preferCellularUrlPath = "/system/etc/prefer_cellular_url_list.txt";
1913     std::ifstream preferCellularFile(preferCellularUrlPath);
1914     if (preferCellularFile.is_open()) {
1915         std::string line;
1916         while (getline(preferCellularFile, line)) {
1917             preferCellularUrlList.push_back(line);
1918         }
1919         preferCellularFile.close();
1920     } else {
1921         NETMGR_LOG_E("open prefer cellular url file failure.");
1922     }
1923     return preferCellularUrlList;
1924 }
1925 } // namespace NetManagerStandard
1926 } // namespace OHOS
1927