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