• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 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 #include <atomic>
16 #include <fstream>
17 #include <functional>
18 #include <memory>
19 #include <sys/time.h>
20 #include <utility>
21 #include <regex>
22 #include <condition_variable>
23 
24 #include "common_event_data.h"
25 #include "common_event_manager.h"
26 #include "common_event_subscriber.h"
27 #include "common_event_support.h"
28 #include "netmanager_base_common_utils.h"
29 #include "network.h"
30 #include "system_ability_definition.h"
31 #include "want.h"
32 
33 #include "broadcast_manager.h"
34 #include "event_report.h"
35 #include "net_activate.h"
36 #include "net_conn_service.h"
37 #include "net_conn_callback_proxy_wrapper.h"
38 #include "net_conn_types.h"
39 #include "net_policy_client.h"
40 #include "net_datashare_utils.h"
41 #include "net_http_proxy_tracker.h"
42 #include "net_manager_center.h"
43 #include "net_manager_constants.h"
44 #include "net_mgr_log_wrapper.h"
45 #include "net_supplier.h"
46 #include "netmanager_base_permission.h"
47 #include "netsys_controller.h"
48 #include "ipc_skeleton.h"
49 #include "parameter.h"
50 #include "parameters.h"
51 
52 namespace OHOS {
53 namespace NetManagerStandard {
54 namespace {
55 constexpr uint32_t MAX_ALLOW_UID_NUM = 2000;
56 constexpr uint32_t INVALID_SUPPLIER_ID = 0;
57 // hisysevent error messgae
58 constexpr const char *ERROR_MSG_NULL_SUPPLIER_INFO = "Net supplier info is nullptr";
59 constexpr const char *ERROR_MSG_NULL_NET_LINK_INFO = "Net link info is nullptr";
60 constexpr const char *ERROR_MSG_NULL_NET_SPECIFIER = "The parameter of netSpecifier or callback is null";
61 constexpr const char *ERROR_MSG_CAN_NOT_FIND_SUPPLIER = "Can not find supplier by id:";
62 constexpr const char *ERROR_MSG_UPDATE_NETLINK_INFO_FAILED = "Update net link info failed";
63 constexpr const char *ERROR_MSG_UPDATE_ERROR_UID = "Update net link info by error uid";
64 constexpr const char *NET_CONN_MANAGER_WORK_THREAD = "NET_CONN_MANAGER_WORK_THREAD";
65 constexpr const char *URL_CFG_FILE = "/system/etc/netdetectionurl.conf";
66 constexpr const char *HTTP_URL_HEADER = "HttpProbeUrl:";
67 constexpr const char NEW_LINE_STR = '\n';
68 const uint32_t SYS_PARAMETER_SIZE = 256;
69 constexpr const char *CFG_NETWORK_PRE_AIRPLANE_MODE_WAIT_TIMES = "persist.network.pre_airplane_mode_wait_times";
70 constexpr const char *NO_DELAY_TIME_CONFIG = "100";
71 constexpr const char *SETTINGS_DATASHARE_URI =
72         "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true";
73 constexpr const char *SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility";
74 constexpr uint32_t INPUT_VALUE_LENGTH = 10;
75 constexpr uint32_t MAX_DELAY_TIME = 200;
76 constexpr uint16_t DEFAULT_MTU = 1500;
77 constexpr int32_t SUCCESS_CODE = 204;
78 constexpr int32_t RETRY_TIMES = 3;
79 constexpr long AUTH_TIME_OUT = 5L;
80 constexpr const char *BOOTEVENT_NETMANAGER_SERVICE_READY = "bootevent.netmanager.ready";
81 constexpr const char *BOOTEVENT_NETSYSNATIVE_SERVICE_READY = "bootevent.netsysnative.ready";
82 } // namespace
83 
84 const bool REGISTER_LOCAL_RESULT =
85     SystemAbility::MakeAndRegisterAbility(NetConnService::GetInstance().get());
86 
NetConnService()87 NetConnService::NetConnService()
88     : SystemAbility(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID, true), registerToService_(false), state_(STATE_STOPPED)
89 {
90 }
91 
~NetConnService()92 NetConnService::~NetConnService()
93 {
94     RemoveALLClientDeathRecipient();
95 }
96 
OnStart()97 void NetConnService::OnStart()
98 {
99     struct timeval tv;
100     gettimeofday(&tv, nullptr);
101     NETMGR_LOG_D("OnStart begin");
102     if (state_ == STATE_RUNNING) {
103         NETMGR_LOG_D("the state is already running");
104         return;
105     }
106     if (!Init()) {
107         NETMGR_LOG_E("init failed");
108         return;
109     }
110     state_ = STATE_RUNNING;
111     gettimeofday(&tv, nullptr);
112     if (!system::GetBoolParameter(BOOTEVENT_NETMANAGER_SERVICE_READY, false)) {
113         system::SetParameter(BOOTEVENT_NETMANAGER_SERVICE_READY, "true");
114         NETMGR_LOG_I("set netmanager service start true");
115     }
116     NETMGR_LOG_D("OnStart end");
117 }
118 
CreateDefaultRequest()119 void NetConnService::CreateDefaultRequest()
120 {
121     if (!defaultNetActivate_) {
122         defaultNetSpecifier_ = (std::make_unique<NetSpecifier>()).release();
123         defaultNetSpecifier_->SetCapabilities({NET_CAPABILITY_INTERNET, NET_CAPABILITY_NOT_VPN});
124         std::weak_ptr<INetActivateCallback> timeoutCb;
125         defaultNetActivate_ = std::make_shared<NetActivate>(defaultNetSpecifier_, nullptr, timeoutCb, 0,
126                                                             netConnEventHandler_, 0, REQUEST);
127         defaultNetActivate_->StartTimeOutNetAvailable();
128         defaultNetActivate_->SetRequestId(DEFAULT_REQUEST_ID);
129         {
130             std::unique_lock<std::shared_mutex> lock(netActivatesMutex_);
131             netActivates_[DEFAULT_REQUEST_ID] = defaultNetActivate_;
132         }
133         NETMGR_LOG_D("defaultnetcap size = [%{public}zu]", defaultNetSpecifier_->netCapabilities_.netCaps_.size());
134     }
135 }
136 
OnStop()137 void NetConnService::OnStop()
138 {
139     NETMGR_LOG_D("OnStop begin");
140     if (netConnEventRunner_) {
141         netConnEventRunner_->Stop();
142         netConnEventRunner_.reset();
143     }
144     if (netConnEventHandler_) {
145         netConnEventHandler_.reset();
146     }
147     state_ = STATE_STOPPED;
148     registerToService_ = false;
149     NETMGR_LOG_D("OnStop end");
150 }
151 
Init()152 bool NetConnService::Init()
153 {
154     if (!REGISTER_LOCAL_RESULT) {
155         NETMGR_LOG_E("Register to local sa manager failed");
156         registerToService_ = false;
157         return false;
158     }
159 
160     AddSystemAbilityListener(COMM_NETSYS_NATIVE_SYS_ABILITY_ID);
161 
162     netConnEventRunner_ = AppExecFwk::EventRunner::Create(NET_CONN_MANAGER_WORK_THREAD);
163     if (netConnEventRunner_ == nullptr) {
164         NETMGR_LOG_E("Create event runner failed.");
165         return false;
166     }
167     netConnEventHandler_ = std::make_shared<NetConnEventHandler>(netConnEventRunner_);
168     CreateDefaultRequest();
169     serviceIface_ = std::make_unique<NetConnServiceIface>().release();
170     NetManagerCenter::GetInstance().RegisterConnService(serviceIface_);
171 
172     interfaceStateCallback_ = new (std::nothrow) NetInterfaceStateCallback();
173     if (interfaceStateCallback_) {
174         NetsysController::GetInstance().RegisterCallback(interfaceStateCallback_);
175     }
176     dnsResultCallback_ = std::make_unique<NetDnsResultCallback>().release();
177     int32_t regDnsResult = NetsysController::GetInstance().RegisterDnsResultCallback(dnsResultCallback_, 0);
178     NETMGR_LOG_I("Register Dns Result callback result: [%{public}d]", regDnsResult);
179 
180     netFactoryResetCallback_ = std::make_unique<NetFactoryResetCallback>().release();
181     if (netFactoryResetCallback_ == nullptr) {
182         NETMGR_LOG_E("netFactoryResetCallback_ is nullptr");
183     }
184     AddSystemAbilityListener(ACCESS_TOKEN_MANAGER_SERVICE_ID);
185     AddSystemAbilityListener(COMM_NET_POLICY_MANAGER_SYS_ABILITY_ID);
186     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
187 
188 #ifdef ENABLE_SET_APP_FROZENED
189     if (netConnEventHandler_) {
190         int64_t delayTime = 3000;
191         appStateAwareCallback_.OnForegroundAppChanged = [] (const uint32_t uid) {
192             std::shared_ptr<NetConnService> netConnService = NetConnService::GetInstance();
193             if (netConnService) {
194                 netConnService ->SetAppIsFrozened(uid, false);
195             }
196         };
197         netConnEventHandler_->PostAsyncTask([this]() {
198             AppStateAwareManager::GetInstance().RegisterAppStateAwareCallback(appStateAwareCallback_);
199         },
200             delayTime);
201     }
202 #endif
203     NETMGR_LOG_I("Init end");
204     return true;
205 }
206 
CheckIfSettingsDataReady()207 bool NetConnService::CheckIfSettingsDataReady()
208 {
209     if (isDataShareReady_.load()) {
210         return true;
211     }
212     sptr<ISystemAbilityManager> saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
213     if (saManager == nullptr) {
214         NETMGR_LOG_E("GetSystemAbilityManager failed.");
215         return false;
216     }
217     sptr<IRemoteObject> dataShareSa = saManager->GetSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
218     if (dataShareSa == nullptr) {
219         NETMGR_LOG_E("Get dataShare SA Failed.");
220         return false;
221     }
222     sptr<IRemoteObject> remoteObj = saManager->GetSystemAbility(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID);
223     if (remoteObj == nullptr) {
224         NETMGR_LOG_E("NetDataShareHelperUtils GetSystemAbility Service Failed.");
225         return false;
226     }
227     std::pair<int, std::shared_ptr<DataShare::DataShareHelper>> ret =
228             DataShare::DataShareHelper::Create(remoteObj, SETTINGS_DATASHARE_URI, SETTINGS_DATA_EXT_URI);
229     NETMGR_LOG_I("create data_share helper, ret=%{public}d", ret.first);
230     if (ret.first == DataShare::E_OK) {
231         NETMGR_LOG_I("create data_share helper success");
232         auto helper = ret.second;
233         if (helper != nullptr) {
234             bool releaseRet = helper->Release();
235             NETMGR_LOG_I("release data_share helper, releaseRet=%{public}d", releaseRet);
236         }
237         isDataShareReady_ = true;
238         return true;
239     } else if (ret.first == DataShare::E_DATA_SHARE_NOT_READY) {
240         NETMGR_LOG_E("create data_share helper failed");
241         isDataShareReady_ = false;
242         return false;
243     }
244     NETMGR_LOG_E("data_share unknown.");
245     return true;
246 }
247 
SystemReady()248 int32_t NetConnService::SystemReady()
249 {
250     if (state_ == STATE_RUNNING) {
251         NETMGR_LOG_D("System ready.");
252         return NETMANAGER_SUCCESS;
253     } else {
254         return NETMANAGER_ERROR;
255     }
256 }
257 
258 // Do not post into event handler, because this interface should have good performance
SetInternetPermission(uint32_t uid,uint8_t allow)259 int32_t NetConnService::SetInternetPermission(uint32_t uid, uint8_t allow)
260 {
261     return NetsysController::GetInstance().SetInternetPermission(uid, allow);
262 }
263 
RegisterNetSupplier(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps,uint32_t & supplierId)264 int32_t NetConnService::RegisterNetSupplier(NetBearType bearerType, const std::string &ident,
265                                             const std::set<NetCap> &netCaps, uint32_t &supplierId)
266 {
267     std::set<NetCap> tmp = netCaps;
268     int32_t callingUid = IPCSkeleton::GetCallingUid();
269     NETMGR_LOG_D("RegisterNetSupplier in netcaps size = %{public}zu.", tmp.size());
270     if (bearerType != BEARER_VPN) {
271         tmp.insert(NET_CAPABILITY_NOT_VPN);
272     }
273     NETMGR_LOG_D("RegisterNetSupplier out netcaps size = %{public}zu.", tmp.size());
274     int32_t result = NETMANAGER_ERROR;
275     if (netConnEventHandler_) {
276         netConnEventHandler_->PostSyncTask([this, bearerType, &ident, tmp, &supplierId, callingUid, &result]() {
277             result = this->RegisterNetSupplierAsync(bearerType, ident, tmp, supplierId, callingUid);
278         });
279     }
280     return result;
281 }
282 
RegisterNetSupplierCallback(uint32_t supplierId,const sptr<INetSupplierCallback> & callback)283 int32_t NetConnService::RegisterNetSupplierCallback(uint32_t supplierId, const sptr<INetSupplierCallback> &callback)
284 {
285     int32_t result = NETMANAGER_ERROR;
286     if (netConnEventHandler_) {
287         netConnEventHandler_->PostSyncTask([this, supplierId, &callback, &result]() {
288             result = this->RegisterNetSupplierCallbackAsync(supplierId, callback);
289         });
290     }
291     return result;
292 }
293 
RegisterNetConnCallback(const sptr<INetConnCallback> callback)294 int32_t NetConnService::RegisterNetConnCallback(const sptr<INetConnCallback> callback)
295 {
296     NETMGR_LOG_D("RegisterNetConnCallback service in.");
297     return RegisterNetConnCallback(defaultNetSpecifier_, callback, 0);
298 }
299 
RegisterNetConnCallback(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> callback,const uint32_t & timeoutMS)300 int32_t NetConnService::RegisterNetConnCallback(const sptr<NetSpecifier> &netSpecifier,
301                                                 const sptr<INetConnCallback> callback, const uint32_t &timeoutMS)
302 {
303     uint32_t callingUid = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
304 
305     int32_t result = NETMANAGER_ERROR;
306     if (netConnEventHandler_) {
307         netConnEventHandler_->PostSyncTask([this, &netSpecifier, &callback, timeoutMS, callingUid, &result]() {
308             result = this->RegisterNetConnCallbackAsync(netSpecifier, callback, timeoutMS, callingUid);
309         });
310     }
311     return result;
312 }
313 
RequestNetConnection(const sptr<NetSpecifier> netSpecifier,const sptr<INetConnCallback> callback,const uint32_t timeoutMS)314 int32_t NetConnService::RequestNetConnection(const sptr<NetSpecifier> netSpecifier,
315                                              const sptr<INetConnCallback> callback, const uint32_t timeoutMS)
316 {
317     uint32_t callingUid = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
318 
319     int32_t result = NETMANAGER_ERROR;
320     if (netSpecifier == nullptr) {
321         return NETMANAGER_ERR_LOCAL_PTR_NULL;
322     }
323     std::set<NetCap> &netCaps = netSpecifier->netCapabilities_.netCaps_;
324     if (netCaps.find(NetCap::NET_CAPABILITY_INTERNAL_DEFAULT) != netCaps.end()) {
325         if (!NetManagerPermission::CheckPermission(Permission::CONNECTIVITY_INTERNAL)) {
326                 NETMGR_LOG_I("Permission deny: Request with INTERNAL_DEFAULT But not has CONNECTIVITY_INTERNAL");
327                 return NETMANAGER_ERR_PERMISSION_DENIED;
328         }
329     } else {
330         if (!NetManagerPermission::CheckPermission(Permission::GET_NETWORK_INFO)) {
331                 NETMGR_LOG_I("Permission deny: request need GET_NETWORK_INFO permission");
332                 return NETMANAGER_ERR_PERMISSION_DENIED;
333         }
334     }
335     if (netConnEventHandler_) {
336         netConnEventHandler_->PostSyncTask([this, netSpecifier, callback, timeoutMS, &callingUid, &result]() {
337             result = this->RequestNetConnectionAsync(netSpecifier, callback, timeoutMS, callingUid);
338         });
339     }
340     return result;
341 }
342 
RegisterNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback)343 int32_t NetConnService::RegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback)
344 {
345     NETMGR_LOG_D("Enter RegisterNetDetectionCallback");
346     return RegUnRegNetDetectionCallback(netId, callback, true);
347 }
348 
UnregisterNetSupplier(uint32_t supplierId)349 int32_t NetConnService::UnregisterNetSupplier(uint32_t supplierId)
350 {
351     int32_t result = NETMANAGER_ERROR;
352     int32_t callingUid = IPCSkeleton::GetCallingUid();
353     if (netConnEventHandler_) {
354         netConnEventHandler_->PostSyncTask([this, supplierId, &callingUid, &result]() {
355             result = this->UnregisterNetSupplierAsync(supplierId, false, callingUid);
356         });
357     }
358     return result;
359 }
360 
UnregisterNetConnCallback(const sptr<INetConnCallback> & callback)361 int32_t NetConnService::UnregisterNetConnCallback(const sptr<INetConnCallback> &callback)
362 {
363     uint32_t callingUid = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
364     int32_t result = NETMANAGER_ERROR;
365     if (netConnEventHandler_) {
366         netConnEventHandler_->PostSyncTask([this, &callback, callingUid, &result]() {
367             result = this->UnregisterNetConnCallbackAsync(callback, callingUid);
368         });
369     }
370     return result;
371 }
372 
UnRegisterNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback)373 int32_t NetConnService::UnRegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback)
374 {
375     NETMGR_LOG_D("Enter UnRegisterNetDetectionCallback");
376     return RegUnRegNetDetectionCallback(netId, callback, false);
377 }
378 
RegUnRegNetDetectionCallback(int32_t netId,const sptr<INetDetectionCallback> & callback,bool isReg)379 int32_t NetConnService::RegUnRegNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback,
380                                                      bool isReg)
381 {
382     int32_t result = NETMANAGER_ERROR;
383     if (netConnEventHandler_) {
384         netConnEventHandler_->PostSyncTask([this, netId, &callback, isReg, &result]() {
385             result = this->RegUnRegNetDetectionCallbackAsync(netId, callback, isReg);
386         });
387     }
388     return result;
389 }
390 
UpdateNetCaps(const std::set<NetCap> & netCaps,const uint32_t supplierId)391 int32_t NetConnService::UpdateNetCaps(const std::set<NetCap> &netCaps, const uint32_t supplierId)
392 {
393     int32_t result = NETMANAGER_ERROR;
394     if (netConnEventHandler_) {
395         netConnEventHandler_->PostSyncTask([this, &netCaps, supplierId, &result]() {
396             result = this->UpdateNetCapsAsync(netCaps, supplierId);
397         });
398     }
399     return result;
400 }
401 
UpdateNetStateForTest(const sptr<NetSpecifier> & netSpecifier,int32_t netState)402 int32_t NetConnService::UpdateNetStateForTest(const sptr<NetSpecifier> &netSpecifier, int32_t netState)
403 {
404     int32_t result = NETMANAGER_ERROR;
405     if (netConnEventHandler_) {
406         netConnEventHandler_->PostSyncTask([this, &netSpecifier, netState, &result]() {
407             result = this->UpdateNetStateForTestAsync(netSpecifier, netState);
408         });
409     }
410     return result;
411 }
412 
UpdateNetSupplierInfo(uint32_t supplierId,const sptr<NetSupplierInfo> & netSupplierInfo)413 int32_t NetConnService::UpdateNetSupplierInfo(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo)
414 {
415     int32_t result = NETMANAGER_ERROR;
416     int32_t callingUid = IPCSkeleton::GetCallingUid();
417     if (netConnEventHandler_) {
418         netConnEventHandler_->PostSyncTask([this, supplierId, &netSupplierInfo, callingUid, &result]() {
419             result = this->UpdateNetSupplierInfoAsync(supplierId, netSupplierInfo, callingUid);
420         });
421     }
422     return result;
423 }
424 
UpdateNetLinkInfo(uint32_t supplierId,const sptr<NetLinkInfo> & netLinkInfo)425 int32_t NetConnService::UpdateNetLinkInfo(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo)
426 {
427     int32_t result = NETMANAGER_ERROR;
428     int32_t callingUid = IPCSkeleton::GetCallingUid();
429     httpProxyThreadCv_.notify_all();
430     if (netConnEventHandler_) {
431         netConnEventHandler_->PostSyncTask([this, supplierId, &netLinkInfo, callingUid, &result]() {
432             result = this->UpdateNetLinkInfoAsync(supplierId, netLinkInfo, callingUid);
433         });
434     }
435     return result;
436 }
437 
NetDetection(int32_t netId)438 int32_t NetConnService::NetDetection(int32_t netId)
439 {
440     int32_t callingUid = IPCSkeleton::GetCallingUid();
441     NETMGR_LOG_I("NetDetection, call uid [%{public}d]", callingUid);
442     httpProxyThreadCv_.notify_all();
443     int32_t result = NETMANAGER_ERROR;
444     if (netConnEventHandler_) {
445         netConnEventHandler_->PostSyncTask([this, netId, &result]() { result = this->NetDetectionAsync(netId); });
446     }
447     return result;
448 }
449 
RestrictBackgroundChanged(bool restrictBackground)450 int32_t NetConnService::RestrictBackgroundChanged(bool restrictBackground)
451 {
452     int32_t result = NETMANAGER_ERROR;
453     if (netConnEventHandler_) {
454         netConnEventHandler_->PostSyncTask([this, restrictBackground, &result]() {
455             result = this->RestrictBackgroundChangedAsync(restrictBackground);
456         });
457     }
458     return result;
459 }
460 
RegisterNetSupplierAsync(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps,uint32_t & supplierId,int32_t callingUid)461 int32_t NetConnService::RegisterNetSupplierAsync(NetBearType bearerType, const std::string &ident,
462                                                  const std::set<NetCap> &netCaps, uint32_t &supplierId,
463                                                  int32_t callingUid)
464 {
465     NETMGR_LOG_I("RegisterNetSupplier service in, bearerType[%{public}u], ident[%{public}s]",
466                  static_cast<uint32_t>(bearerType), ident.c_str());
467     // If there is no supplier in the list, create a supplier
468     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
469         NETMGR_LOG_E("netType parameter invalid");
470         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
471     }
472     sptr<NetSupplier> supplier = GetNetSupplierFromList(bearerType, ident, netCaps);
473     if (supplier != nullptr) {
474         NETMGR_LOG_E("Supplier[%{public}d %{public}s] already exists.", supplier->GetSupplierId(), ident.c_str());
475         supplierId = supplier->GetSupplierId();
476         return NETMANAGER_SUCCESS;
477     }
478     // If there is no supplier in the list, create a supplier
479     supplier = (std::make_unique<NetSupplier>(bearerType, ident, netCaps)).release();
480     if (supplier == nullptr) {
481         NETMGR_LOG_E("supplier is nullptr");
482         return NET_CONN_ERR_NO_SUPPLIER;
483     }
484     supplierId = supplier->GetSupplierId();
485     // create network
486     bool isContainInternal = netCaps.find(NetCap::NET_CAPABILITY_INTERNAL_DEFAULT) != netCaps.end();
487     int32_t netId = isContainInternal ? GenerateInternalNetId() : GenerateNetId();
488     NETMGR_LOG_D("GenerateNetId is: [%{public}d], bearerType: %{public}d, supplierId: %{public}d",
489         netId, bearerType, supplierId);
490     if (netId == INVALID_NET_ID) {
491         NETMGR_LOG_E("GenerateNetId fail");
492         return NET_CONN_ERR_INVALID_NETWORK;
493     }
494     std::shared_ptr<Network> network = std::make_shared<Network>(
495         netId, supplierId,
496         std::bind(&NetConnService::HandleDetectionResult, shared_from_this(),
497             std::placeholders::_1, std::placeholders::_2),
498         bearerType, netConnEventHandler_);
499     network->SetNetCaps(netCaps);
500     supplier->SetNetwork(network);
501     supplier->SetUid(callingUid);
502     // save supplier
503     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
504     netSuppliers_[supplierId] = supplier;
505     networks_[netId] = network;
506     locker.unlock();
507     struct EventInfo eventInfo = {.netId = netId, .bearerType = bearerType, .ident = ident, .supplierId = supplierId};
508     EventReport::SendSupplierBehaviorEvent(eventInfo);
509     NETMGR_LOG_I("RegisterNetSupplier service out, supplier[%{public}d %{public}s] netId[%{public}d]", supplierId,
510                  ident.c_str(), netId);
511     return NETMANAGER_SUCCESS;
512 }
513 
OnNetSupplierRemoteDied(const wptr<IRemoteObject> & remoteObject)514 void NetConnService::OnNetSupplierRemoteDied(const wptr<IRemoteObject> &remoteObject)
515 {
516     sptr<IRemoteObject> diedRemoted = remoteObject.promote();
517     if (diedRemoted == nullptr || netConnEventHandler_ == nullptr) {
518         NETMGR_LOG_E("diedRemoted or netConnEventHandler_ is null");
519         return;
520     }
521     uint32_t callingUid = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
522     uint32_t tmpSupplierId = INVALID_SUPPLIER_ID;
523     NETMGR_LOG_I("OnNetSupplierRemoteDied, callingUid=%{public}u", callingUid);
524     sptr<INetSupplierCallback> callback = iface_cast<INetSupplierCallback>(diedRemoted);
525 
526     netConnEventHandler_->PostSyncTask([this, &tmpSupplierId, callingUid, &callback]() {
527         for (const auto &supplier : netSuppliers_) {
528             if (supplier.second == nullptr || supplier.second->GetSupplierCallback() == nullptr) {
529                 continue;
530             }
531             if (supplier.second->GetSupplierCallback()->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
532                 tmpSupplierId = supplier.second->GetSupplierId();
533                 break;
534             }
535         }
536         if (tmpSupplierId != INVALID_SUPPLIER_ID) {
537             NETMGR_LOG_I("OnNetSupplierRemoteDied UnregisterNetSupplier SupplierId %{public}u", tmpSupplierId);
538             UnregisterNetSupplierAsync(tmpSupplierId, true, callingUid);
539         }
540     });
541 }
542 
RemoveNetSupplierDeathRecipient(const sptr<INetSupplierCallback> & callback)543 void NetConnService::RemoveNetSupplierDeathRecipient(const sptr<INetSupplierCallback> &callback)
544 {
545     if (callback == nullptr) {
546         NETMGR_LOG_E("RemoveNetSupplierDeathRecipient is null");
547         return;
548     }
549     callback->AsObject()->RemoveDeathRecipient(netSuplierDeathRecipient_);
550 }
551 
AddNetSupplierDeathRecipient(const sptr<INetSupplierCallback> & callback)552 void NetConnService::AddNetSupplierDeathRecipient(const sptr<INetSupplierCallback> &callback)
553 {
554     if (netSuplierDeathRecipient_ == nullptr) {
555         netSuplierDeathRecipient_ = new (std::nothrow) NetSupplierCallbackDeathRecipient(*this);
556     }
557     if (netSuplierDeathRecipient_ == nullptr) {
558         NETMGR_LOG_E("netSuplierDeathRecipient_ is null");
559         return;
560     }
561     if (!callback->AsObject()->AddDeathRecipient(netSuplierDeathRecipient_)) {
562         NETMGR_LOG_E("AddNetSupplierDeathRecipient failed");
563         return;
564     }
565 }
566 
RegisterNetSupplierCallbackAsync(uint32_t supplierId,const sptr<INetSupplierCallback> & callback)567 int32_t NetConnService::RegisterNetSupplierCallbackAsync(uint32_t supplierId,
568                                                          const sptr<INetSupplierCallback> &callback)
569 {
570     NETMGR_LOG_I("RegisterNetSupplierCallback service in, supplierId[%{public}d]", supplierId);
571     if (callback == nullptr) {
572         NETMGR_LOG_E("The parameter callback is null");
573         return NETMANAGER_ERR_LOCAL_PTR_NULL;
574     }
575     auto supplier = FindNetSupplier(supplierId);
576     if (supplier == nullptr) {
577         NETMGR_LOG_E("supplier doesn't exist.");
578         return NET_CONN_ERR_NO_SUPPLIER;
579     }
580     supplier->RegisterSupplierCallback(callback);
581     SendAllRequestToNetwork(supplier);
582     AddNetSupplierDeathRecipient(callback);
583     NETMGR_LOG_I("RegisterNetSupplierCallback service out");
584     return NETMANAGER_SUCCESS;
585 }
586 
RegisterNetConnCallbackAsync(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS,const uint32_t callingUid)587 int32_t NetConnService::RegisterNetConnCallbackAsync(const sptr<NetSpecifier> &netSpecifier,
588                                                      const sptr<INetConnCallback> &callback, const uint32_t &timeoutMS,
589                                                      const uint32_t callingUid)
590 {
591     if (netSpecifier == nullptr || callback == nullptr) {
592         NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
593         struct EventInfo eventInfo = {.errorType = static_cast<int32_t>(FAULT_INVALID_PARAMETER),
594                                       .errorMsg = ERROR_MSG_NULL_NET_SPECIFIER};
595         EventReport::SendRequestFaultEvent(eventInfo);
596         return NETMANAGER_ERR_LOCAL_PTR_NULL;
597     }
598     uint32_t reqId = 0;
599     if (FindSameCallback(callback, reqId)) {
600         NETMGR_LOG_E("FindSameCallback callUid:%{public}u reqId:%{public}u", callingUid,
601                      reqId);
602         return NET_CONN_ERR_SAME_CALLBACK;
603     }
604     auto registerType = (netSpecifier != nullptr && ((netSpecifier->netCapabilities_.netCaps_.count(
605         NetManagerStandard::NET_CAPABILITY_INTERNAL_DEFAULT) > 0) ||
606         (netSpecifier->netCapabilities_.bearerTypes_.count(NetManagerStandard::BEARER_CELLULAR) > 0))) ?
607         REQUEST : REGISTER;
608     NETMGR_LOG_I("Register net connect callback async, callUid[%{public}u], reqId[%{public}u], regType[%{public}u]",
609                  callingUid, reqId, registerType);
610     int32_t ret = IncreaseNetConnCallbackCntForUid(callingUid, registerType);
611     if (ret != NETMANAGER_SUCCESS) {
612         return ret;
613     }
614     AddClientDeathRecipient(callback);
615     return ActivateNetwork(netSpecifier, callback, timeoutMS, REGISTER, callingUid);
616 }
617 
RequestNetConnectionAsync(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS,const uint32_t callingUid)618 int32_t NetConnService::RequestNetConnectionAsync(const sptr<NetSpecifier> &netSpecifier,
619                                                   const sptr<INetConnCallback> &callback, const uint32_t &timeoutMS,
620                                                   const uint32_t callingUid)
621 {
622     NETMGR_LOG_I("Request net connect callback async, call uid [%{public}u]", callingUid);
623     if (netSpecifier == nullptr || callback == nullptr) {
624         NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
625         struct EventInfo eventInfo = {.errorType = static_cast<int32_t>(FAULT_INVALID_PARAMETER),
626                                       .errorMsg = ERROR_MSG_NULL_NET_SPECIFIER};
627         EventReport::SendRequestFaultEvent(eventInfo);
628         return NETMANAGER_ERR_LOCAL_PTR_NULL;
629     }
630     uint32_t reqId = 0;
631     if (FindSameCallback(callback, reqId)) {
632         NETMGR_LOG_E("RequestNetConnection found same callback");
633         return NET_CONN_ERR_SAME_CALLBACK;
634     }
635     int32_t ret = IncreaseNetConnCallbackCntForUid(callingUid, REQUEST);
636     if (ret != NETMANAGER_SUCCESS) {
637         return ret;
638     }
639     AddClientDeathRecipient(callback);
640     return ActivateNetwork(netSpecifier, callback, timeoutMS, REQUEST, callingUid);
641 }
642 
UnregisterNetSupplierAsync(uint32_t supplierId,bool ignoreUid,int32_t callingUid)643 int32_t NetConnService::UnregisterNetSupplierAsync(uint32_t supplierId, bool ignoreUid, int32_t callingUid)
644 {
645     NETMGR_LOG_I("UnregisterNetSupplier service in, supplierId[%{public}d]", supplierId);
646     // Remove supplier from the list based on supplierId
647     auto supplier = FindNetSupplier(supplierId);
648     if (supplier == nullptr) {
649         NETMGR_LOG_E("supplier doesn't exist.");
650         return NET_CONN_ERR_NO_SUPPLIER;
651     }
652     if (!ignoreUid && CheckAndCompareUid(supplier, callingUid) != NETMANAGER_SUCCESS) {
653         NETMGR_LOG_E("UnregisterNetSupplierAsync uid[%{public}d] is not equal to callingUid[%{public}d].",
654                      supplier->GetUid(), callingUid);
655         return NETMANAGER_ERR_INVALID_PARAMETER;
656     }
657     NETMGR_LOG_I("Unregister supplier[%{public}d, %{public}d, %{public}s], defaultNetSupplier[%{public}d], %{public}s]",
658                  supplier->GetSupplierId(), supplier->GetUid(), supplier->GetNetSupplierIdent().c_str(),
659                  defaultNetSupplier_ ? defaultNetSupplier_->GetSupplierId() : 0,
660                  defaultNetSupplier_ ? defaultNetSupplier_->GetNetSupplierIdent().c_str() : "null");
661 
662     struct EventInfo eventInfo = {.bearerType = supplier->GetNetSupplierType(),
663                                   .ident = supplier->GetNetSupplierIdent(),
664                                   .supplierId = supplier->GetSupplierId()};
665     EventReport::SendSupplierBehaviorEvent(eventInfo);
666 
667     int32_t netId = supplier->GetNetId();
668     NET_NETWORK_MAP::iterator iterNetwork = networks_.find(netId);
669     if (iterNetwork != networks_.end()) {
670         NETMGR_LOG_I("the iterNetwork already exists.");
671         std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
672         networks_.erase(iterNetwork);
673         locker.unlock();
674     }
675     if (defaultNetSupplier_ == supplier) {
676         NETMGR_LOG_I("Set default net supplier to nullptr.");
677         sptr<NetSupplier> newSupplier = nullptr;
678         MakeDefaultNetWork(defaultNetSupplier_, newSupplier);
679     }
680     NetSupplierInfo info;
681     supplier->UpdateNetSupplierInfo(info);
682     RemoveNetSupplierDeathRecipient(supplier->GetSupplierCallback());
683     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
684     netSuppliers_.erase(supplierId);
685     locker.unlock();
686     FindBestNetworkForAllRequest();
687     NETMGR_LOG_I("UnregisterNetSupplier supplierId[%{public}d] out", supplierId);
688     return NETMANAGER_SUCCESS;
689 }
690 
CheckAndCompareUid(sptr<NetSupplier> & supplier,int32_t callingUid)691 int32_t NetConnService::CheckAndCompareUid(sptr<NetSupplier> &supplier, int32_t callingUid)
692 {
693     int32_t uid = supplier->GetUid();
694     if (uid != callingUid) {
695         struct EventInfo eventInfo = {
696             .errorType = static_cast<int32_t>(NETMANAGER_ERR_INVALID_PARAMETER),
697             .errorMsg = std::string(ERROR_MSG_UPDATE_ERROR_UID) +
698                         std::to_string(callingUid)
699         };
700         EventReport::SendSupplierFaultEvent(eventInfo);
701     }
702     return NETMANAGER_SUCCESS;
703 }
704 
705 #ifdef FEATURE_SUPPORT_POWERMANAGER
StopAllNetDetection()706 void NetConnService::StopAllNetDetection()
707 {
708     netConnEventHandler_->PostSyncTask([this]() {
709         for (const auto& pNetSupplier : netSuppliers_) {
710             if (pNetSupplier.second == nullptr) {
711                 continue;
712             }
713             std::shared_ptr<Network> pNetwork = pNetSupplier.second->GetNetwork();
714             if (pNetwork == nullptr) {
715                 NETMGR_LOG_E("pNetwork is null, id:%{public}d", pNetSupplier.first);
716                 continue;
717             }
718             pNetwork->StopNetDetection();
719             pNetwork->UpdateForbidDetectionFlag(true);
720         }
721     });
722 }
723 
StartAllNetDetection()724 void NetConnService::StartAllNetDetection()
725 {
726     netConnEventHandler_->PostSyncTask([this]() {
727         for (const auto& pNetSupplier : netSuppliers_) {
728             if (pNetSupplier.second == nullptr) {
729                 continue;
730             }
731             std::shared_ptr<Network> pNetwork = pNetSupplier.second->GetNetwork();
732             if (pNetwork == nullptr) {
733                 NETMGR_LOG_E("pNetwork is null, id:%{public}d", pNetSupplier.first);
734                 continue;
735             }
736             pNetwork->UpdateForbidDetectionFlag(false);
737         }
738         if ((defaultNetSupplier_ == nullptr)) {
739             NETMGR_LOG_W("defaultNetSupplier_ is  null");
740             return;
741         }
742         std::shared_ptr<Network> pDefaultNetwork = defaultNetSupplier_->GetNetwork();
743         if (pDefaultNetwork == nullptr) {
744             NETMGR_LOG_E("pDefaultNetwork is null");
745             return;
746         }
747         httpProxyThreadCv_.notify_all();
748         pDefaultNetwork->StartNetDetection(false);
749     });
750 }
751 
HandlePowerMgrEvent(int code)752 void NetConnService::HandlePowerMgrEvent(int code)
753 {
754     if (code == STATE_ENTER_FORCESLEEP || code == STATE_ENTER_SLEEP_NOT_FORCE) {
755         NETMGR_LOG_I("on receive enter sleep, code %{public}d.", code);
756         if (netConnEventHandler_) {
757             netConnEventHandler_->PostSyncTask([this]() {
758                 this->StopAllNetDetection();
759             });
760         }
761         isInSleep_.store(true);
762     } else if (code == STATE_EXIT_FORCESLEEP || code == STATE_EXIT_SLEEP_NOT_FORCE) {
763         NETMGR_LOG_I("on receive exit sleep, code %{public}d.", code);
764         if (netConnEventHandler_) {
765             netConnEventHandler_->PostSyncTask([this]() {
766                 this->StartAllNetDetection();
767             });
768         }
769         isInSleep_.store(false);
770     }
771 }
772 #endif
773 
HandleScreenEvent(bool isScreenOn)774 void NetConnService::HandleScreenEvent(bool isScreenOn)
775 {
776     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
777     for (const auto& pNetSupplier : netSuppliers_) {
778         if (pNetSupplier.second == nullptr) {
779             continue;
780         }
781         std::shared_ptr<Network> pNetwork = pNetSupplier.second->GetNetwork();
782         if (pNetwork == nullptr) {
783             NETMGR_LOG_E("pNetwork is null, id:%{public}d", pNetSupplier.first);
784             continue;
785         }
786         int delayTime = 0;
787         if (netConnEventHandler_) {
788             netConnEventHandler_->PostAsyncTask([pNetwork, isScreenOn]() { pNetwork->SetScreenState(isScreenOn); },
789                                                 delayTime);
790         }
791         if (!isScreenOn || pNetSupplier.second->GetNetSupplierType() != BEARER_WIFI ||
792             !pNetSupplier.second->HasNetCap(NET_CAPABILITY_PORTAL)) {
793             continue;
794         }
795         if (netConnEventHandler_) {
796             netConnEventHandler_->PostAsyncTask([pNetwork]() { pNetwork->StartNetDetection(false); }, delayTime);
797         }
798     }
799 }
800 
UnregisterNetConnCallbackAsync(const sptr<INetConnCallback> & callback,const uint32_t callingUid)801 int32_t NetConnService::UnregisterNetConnCallbackAsync(const sptr<INetConnCallback> &callback,
802                                                        const uint32_t callingUid)
803 {
804     if (callback == nullptr) {
805         NETMGR_LOG_E("callback is null, callUid[%{public}u]", callingUid);
806         return NETMANAGER_ERR_LOCAL_PTR_NULL;
807     }
808     RegisterType registerType = INVALIDTYPE;
809     uint32_t reqId = 0;
810     uint32_t uid = 0;
811     if (!FindSameCallback(callback, reqId, registerType, uid) || registerType == INVALIDTYPE) {
812         NETMGR_LOG_E("NotFindSameCallback callUid:%{public}u reqId:%{public}u, uid:%{public}d",
813                      callingUid, reqId, uid);
814         return NET_CONN_ERR_CALLBACK_NOT_FOUND;
815     }
816     NETMGR_LOG_I("start, callUid:%{public}u, reqId:%{public}u, uid:%{public}d", callingUid, reqId, uid);
817     DecreaseNetConnCallbackCntForUid(uid, registerType);
818     DecreaseNetActivatesForUid(uid, callback);
819     DecreaseNetActivates(uid, callback, reqId);
820 
821     return NETMANAGER_SUCCESS;
822 }
823 
IncreaseNetConnCallbackCntForUid(const uint32_t callingUid,const RegisterType registerType)824 int32_t NetConnService::IncreaseNetConnCallbackCntForUid(const uint32_t callingUid, const RegisterType registerType)
825 {
826     std::lock_guard guard(netUidRequestMutex_);
827     auto &netUidRequest = registerType == REGISTER ?
828         netUidRequest_ : internalDefaultUidRequest_;
829     auto requestNetwork = netUidRequest.find(callingUid);
830     if (requestNetwork == netUidRequest.end()) {
831         netUidRequest.insert(std::make_pair(callingUid, 1));
832     } else {
833         if (requestNetwork->second >= MAX_ALLOW_UID_NUM) {
834             NETMGR_LOG_E("return falied for UID [%{public}d] has registered over [%{public}d] callback",
835                          callingUid, MAX_ALLOW_UID_NUM);
836             return NET_CONN_ERR_NET_OVER_MAX_REQUEST_NUM;
837         } else {
838             requestNetwork->second++;
839         }
840     }
841     return NETMANAGER_SUCCESS;
842 }
843 
DecreaseNetConnCallbackCntForUid(const uint32_t callingUid,const RegisterType registerType)844 void NetConnService::DecreaseNetConnCallbackCntForUid(const uint32_t callingUid, const RegisterType registerType)
845 {
846     std::lock_guard guard(netUidRequestMutex_);
847     auto &netUidRequest = registerType == REGISTER ?
848         netUidRequest_ : internalDefaultUidRequest_;
849     auto requestNetwork = netUidRequest.find(callingUid);
850     if (requestNetwork == netUidRequest.end()) {
851         NETMGR_LOG_E("Could not find the request calling uid");
852     } else {
853         if (requestNetwork->second >= 1) {
854             requestNetwork->second--;
855         }
856         if (requestNetwork->second == 0) {
857             netUidRequest.erase(requestNetwork);
858         }
859     }
860 }
861 
DecreaseNetActivatesForUid(const uint32_t callingUid,const sptr<INetConnCallback> & callback)862 void NetConnService::DecreaseNetActivatesForUid(const uint32_t callingUid, const sptr<INetConnCallback> &callback)
863 {
864     std::lock_guard guard(uidActivateMutex_);
865     auto it = netUidActivates_.find(callingUid);
866     if (it != netUidActivates_.end()) {
867         std::vector<std::shared_ptr<NetActivate>> &activates = it->second;
868         for (auto iter = activates.begin(); iter != activates.end();) {
869             if ((*iter)->GetNetCallback() == callback) {
870                 iter = activates.erase(iter);
871                 break;
872             } else {
873                 ++iter;
874             }
875         }
876         if (activates.empty()) {
877             netUidActivates_.erase(it);
878         }
879     }
880 }
881 
DecreaseNetActivates(const uint32_t callingUid,const sptr<INetConnCallback> & callback,uint32_t reqId)882 void NetConnService::DecreaseNetActivates(const uint32_t callingUid, const sptr<INetConnCallback> &callback,
883                                           uint32_t reqId)
884 {
885     std::lock_guard<std::shared_mutex> lock(netActivatesMutex_);
886     for (auto iterActive = netActivates_.begin(); iterActive != netActivates_.end();) {
887         if (!iterActive->second) {
888             ++iterActive;
889             continue;
890         }
891         sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
892         if (saveCallback == nullptr) {
893             ++iterActive;
894             continue;
895         }
896         if (callback->AsObject().GetRefPtr() != saveCallback->AsObject().GetRefPtr()) {
897             ++iterActive;
898             continue;
899         }
900         reqId = iterActive->first;
901         auto netActivate = iterActive->second;
902         NetRequest netRequest(netActivate->GetUid(), reqId);
903         if (netActivate) {
904             sptr<NetSupplier> supplier = netActivate->GetServiceSupply();
905             if (supplier) {
906                 supplier->CancelRequest(netRequest);
907             }
908         }
909         NET_SUPPLIER_MAP::iterator iterSupplier;
910         for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
911             if (iterSupplier->second != nullptr) {
912                 iterSupplier->second->CancelRequest(netRequest);
913             }
914         }
915         iterActive = netActivates_.erase(iterActive);
916         RemoveClientDeathRecipient(callback);
917     }
918     NETMGR_LOG_I("end, callUid:%{public}u, reqId:%{public}u", callingUid, reqId);
919 }
920 
RegUnRegNetDetectionCallbackAsync(int32_t netId,const sptr<INetDetectionCallback> & callback,bool isReg)921 int32_t NetConnService::RegUnRegNetDetectionCallbackAsync(int32_t netId, const sptr<INetDetectionCallback> &callback,
922                                                           bool isReg)
923 {
924     NETMGR_LOG_I("Enter Async");
925     if (callback == nullptr) {
926         NETMGR_LOG_E("The parameter of callback is null");
927         return NETMANAGER_ERR_LOCAL_PTR_NULL;
928     }
929 
930     auto iterNetwork = networks_.find(netId);
931     if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
932         NETMGR_LOG_E("Could not find the corresponding network.");
933         return NET_CONN_ERR_NETID_NOT_FOUND;
934     }
935     if (isReg) {
936         iterNetwork->second->RegisterNetDetectionCallback(callback);
937         return NETMANAGER_SUCCESS;
938     }
939     return iterNetwork->second->UnRegisterNetDetectionCallback(callback);
940 }
941 
UpdateNetCapsAsync(const std::set<NetCap> & netCaps,const uint32_t supplierId)942 int32_t NetConnService::UpdateNetCapsAsync(const std::set<NetCap> &netCaps, const uint32_t supplierId)
943 {
944     NETMGR_LOG_I("Update net caps async.");
945     auto supplier = FindNetSupplier(supplierId);
946     if (supplier == nullptr) {
947         NETMGR_LOG_E("supplier is not exists.");
948         return NET_CONN_ERR_NO_SUPPLIER;
949     }
950 
951     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
952     auto network = supplier->GetNetwork();
953     if (network == nullptr) {
954         NETMGR_LOG_E("network is null");
955         return NETMANAGER_ERR_LOCAL_PTR_NULL;
956     }
957     network->SetNetCaps(netCaps);
958     supplier->SetNetwork(network);
959     CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
960     FindBestNetworkForAllRequest();
961     return NETMANAGER_SUCCESS;
962 }
963 
UpdateNetStateForTestAsync(const sptr<NetSpecifier> & netSpecifier,int32_t netState)964 int32_t NetConnService::UpdateNetStateForTestAsync(const sptr<NetSpecifier> &netSpecifier, int32_t netState)
965 {
966     NETMGR_LOG_D("Test NetConnService::UpdateNetStateForTest(), begin");
967     if (netSpecifier == nullptr) {
968         NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
969         return NETMANAGER_ERR_LOCAL_PTR_NULL;
970     }
971     return NETMANAGER_SUCCESS;
972 }
973 
UpdateNetSupplierInfoAsync(uint32_t supplierId,const sptr<NetSupplierInfo> & netSupplierInfo,int32_t callingUid)974 int32_t NetConnService::UpdateNetSupplierInfoAsync(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo,
975                                                    int32_t callingUid)
976 {
977     NETMGR_LOG_I("UpdateNetSupplierInfo service in. supplierId[%{public}d]", supplierId);
978     struct EventInfo eventInfo = {.updateSupplierId = supplierId};
979     if (netSupplierInfo == nullptr) {
980         NETMGR_LOG_E("netSupplierInfo is nullptr");
981         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_SUPPLIERINFO_INV_PARAM);
982         eventInfo.errorMsg = ERROR_MSG_NULL_SUPPLIER_INFO;
983         EventReport::SendSupplierFaultEvent(eventInfo);
984         return NETMANAGER_ERR_PARAMETER_ERROR;
985     }
986     eventInfo.supplierInfo = netSupplierInfo->ToString("\"");
987 
988     auto supplier = FindNetSupplier(supplierId);
989     if (supplier == nullptr) {
990         NETMGR_LOG_E("Can not find supplier for supplierId[%{public}d]", supplierId);
991         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_SUPPLIERINFO_INV_PARAM);
992         eventInfo.errorMsg = std::string(ERROR_MSG_CAN_NOT_FIND_SUPPLIER).append(std::to_string(supplierId));
993         EventReport::SendSupplierFaultEvent(eventInfo);
994         return NET_CONN_ERR_NO_SUPPLIER;
995     }
996 
997     if (CheckAndCompareUid(supplier, callingUid) != NETMANAGER_SUCCESS) {
998         NETMGR_LOG_E("UpdateNetSupplierInfoAsync uid[%{public}d] is not equal to callingUid[%{public}d].",
999                      supplier->GetUid(), callingUid);
1000         return NETMANAGER_ERR_INVALID_PARAMETER;
1001     }
1002     eventInfo.bearerType = supplier->GetNetSupplierType();
1003     eventInfo.netId = supplier->GetNetId();
1004     EventReport::SendSupplierBehaviorEvent(eventInfo);
1005     NETMGR_LOG_I("Update supplier[%{public}d, %{public}d, %{public}s], supplierInfo:[ %{public}s ]", supplierId,
1006                  supplier->GetUid(), supplier->GetNetSupplierIdent().c_str(), netSupplierInfo->ToString(" ").c_str());
1007     supplier->UpdateNetSupplierInfo(*netSupplierInfo);
1008     if (!netSupplierInfo->isAvailable_) {
1009         CallbackForSupplier(supplier, CALL_TYPE_LOST);
1010         std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
1011         supplier->ResetNetSupplier();
1012         locker.unlock();
1013     } else {
1014         CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
1015     }
1016     // Init score again here in case of net supplier type changed.
1017     std::unique_lock<std::recursive_mutex> initLocker(netManagerMutex_);
1018     if (netSupplierInfo->score_ == 0) {
1019         supplier->InitNetScore();
1020     }
1021     initLocker.unlock();
1022     FindBestNetworkForAllRequest();
1023     NETMGR_LOG_I("UpdateNetSupplierInfo service out.");
1024     return NETMANAGER_SUCCESS;
1025 }
1026 
UpdateNetLinkInfoAsync(uint32_t supplierId,const sptr<NetLinkInfo> & netLinkInfo,int32_t callingUid)1027 int32_t NetConnService::UpdateNetLinkInfoAsync(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo,
1028                                                int32_t callingUid)
1029 {
1030     NETMGR_LOG_I("UpdateNetLinkInfo service in. supplierId[%{public}d]", supplierId);
1031     struct EventInfo eventInfo = {.updateNetlinkId = supplierId};
1032 
1033     if (netLinkInfo == nullptr) {
1034         NETMGR_LOG_E("netLinkInfo is nullptr");
1035         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_INV_PARAM);
1036         eventInfo.errorMsg = ERROR_MSG_NULL_NET_LINK_INFO;
1037         EventReport::SendSupplierFaultEvent(eventInfo);
1038         return NETMANAGER_ERR_PARAMETER_ERROR;
1039     }
1040     eventInfo.netlinkInfo = netLinkInfo->ToString(" ");
1041 
1042     auto supplier = FindNetSupplier(supplierId);
1043     if (supplier == nullptr) {
1044         NETMGR_LOG_E("supplier is nullptr");
1045         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_INV_PARAM);
1046         eventInfo.errorMsg = std::string(ERROR_MSG_CAN_NOT_FIND_SUPPLIER).append(std::to_string(supplierId));
1047         EventReport::SendSupplierFaultEvent(eventInfo);
1048         return NET_CONN_ERR_NO_SUPPLIER;
1049     }
1050 
1051     if (CheckAndCompareUid(supplier, callingUid) != NETMANAGER_SUCCESS) {
1052         NETMGR_LOG_E("UpdateNetLinkInfoAsync uid[%{public}d] is not equal to callingUid[%{public}d].",
1053                      supplier->GetUid(), callingUid);
1054         return NETMANAGER_ERR_INVALID_PARAMETER;
1055     }
1056     eventInfo.bearerType = supplier->GetNetSupplierType();
1057     eventInfo.netId = supplier->GetNetId();
1058     EventReport::SendSupplierBehaviorEvent(eventInfo);
1059     HttpProxy oldHttpProxy;
1060     supplier->GetHttpProxy(oldHttpProxy);
1061     // According to supplier id, get network from the list
1062     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
1063     if (supplier->UpdateNetLinkInfo(*netLinkInfo) != NETMANAGER_SUCCESS) {
1064         NETMGR_LOG_E("UpdateNetLinkInfo fail");
1065         eventInfo.errorType = static_cast<int32_t>(FAULT_UPDATE_NETLINK_INFO_FAILED);
1066         eventInfo.errorMsg = ERROR_MSG_UPDATE_NETLINK_INFO_FAILED;
1067         EventReport::SendSupplierFaultEvent(eventInfo);
1068         return NET_CONN_ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL;
1069     }
1070     locker.unlock();
1071     CallbackForSupplier(supplier, CALL_TYPE_UPDATE_LINK);
1072     FindBestNetworkForAllRequest();
1073 
1074     if (oldHttpProxy != netLinkInfo->httpProxy_) {
1075         SendHttpProxyChangeBroadcast(netLinkInfo->httpProxy_);
1076     }
1077     NETMGR_LOG_I("UpdateNetLinkInfo service out.");
1078     return NETMANAGER_SUCCESS;
1079 }
1080 
NetDetectionAsync(int32_t netId)1081 int32_t NetConnService::NetDetectionAsync(int32_t netId)
1082 {
1083     NETMGR_LOG_I("Enter NetDetection, netId=[%{public}d]", netId);
1084     auto iterNetwork = networks_.find(netId);
1085     if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr) || !iterNetwork->second->IsConnected()) {
1086         NETMGR_LOG_E("Could not find the corresponding network or network is not connected.");
1087         return NET_CONN_ERR_NETID_NOT_FOUND;
1088     }
1089     iterNetwork->second->StartNetDetection(false);
1090     NETMGR_LOG_I("End NetDetection");
1091     return NETMANAGER_SUCCESS;
1092 }
1093 
NetDetectionForDnsHealthSync(int32_t netId,bool dnsHealthSuccess)1094 int32_t NetConnService::NetDetectionForDnsHealthSync(int32_t netId, bool dnsHealthSuccess)
1095 {
1096     NETMGR_LOG_D("Enter NetDetectionForDnsHealthSync");
1097     auto iterNetwork = networks_.find(netId);
1098     if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
1099         NETMGR_LOG_E("Could not find the corresponding network");
1100         return NET_CONN_ERR_NETID_NOT_FOUND;
1101     }
1102     iterNetwork->second->NetDetectionForDnsHealth(dnsHealthSuccess);
1103     return NETMANAGER_SUCCESS;
1104 }
1105 
RestrictBackgroundChangedAsync(bool restrictBackground)1106 int32_t NetConnService::RestrictBackgroundChangedAsync(bool restrictBackground)
1107 {
1108     NETMGR_LOG_I("Restrict background changed, background = %{public}d", restrictBackground);
1109     for (auto it = netSuppliers_.begin(); it != netSuppliers_.end(); ++it) {
1110         if (it->second == nullptr) {
1111             continue;
1112         }
1113 
1114         if (it->second->GetRestrictBackground() == restrictBackground) {
1115             NETMGR_LOG_D("it->second->GetRestrictBackground() == restrictBackground");
1116             return NET_CONN_ERR_NET_NO_RESTRICT_BACKGROUND;
1117         }
1118 
1119         if (it->second->GetNetSupplierType() == BEARER_VPN) {
1120             CallbackForSupplier(it->second, CALL_TYPE_BLOCK_STATUS);
1121         }
1122         it->second->SetRestrictBackground(restrictBackground);
1123     }
1124     NETMGR_LOG_I("End RestrictBackgroundChangedAsync");
1125     return NETMANAGER_SUCCESS;
1126 }
1127 
SendHttpProxyChangeBroadcast(const HttpProxy & httpProxy)1128 void NetConnService::SendHttpProxyChangeBroadcast(const HttpProxy &httpProxy)
1129 {
1130     BroadcastInfo info;
1131     info.action = EventFwk::CommonEventSupport::COMMON_EVENT_HTTP_PROXY_CHANGE;
1132     info.data = "Global HttpProxy Changed";
1133     info.ordered = false;
1134     std::map<std::string, std::string> param = {{"HttpProxy", httpProxy.ToString()}};
1135     int32_t userId = GetValidUserIdFromProxy(httpProxy);
1136     if (userId == INVALID_USER_ID) {
1137         return;
1138     }
1139     param.emplace("UserId", std::to_string(userId));
1140     BroadcastManager::GetInstance().SendBroadcast(info, param);
1141 }
1142 
ActivateNetwork(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS,const int32_t registerType,const uint32_t callingUid)1143 int32_t NetConnService::ActivateNetwork(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
1144                                         const uint32_t &timeoutMS, const int32_t registerType,
1145                                         const uint32_t callingUid)
1146 {
1147     NETMGR_LOG_D("ActivateNetwork Enter");
1148     if (netSpecifier == nullptr || callback == nullptr) {
1149         NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
1150         return NETMANAGER_ERR_PARAMETER_ERROR;
1151     }
1152     std::weak_ptr<INetActivateCallback> timeoutCb = shared_from_this();
1153 
1154     std::shared_ptr<NetActivate> request = CreateNetActivateRequest(netSpecifier, callback,
1155         timeoutMS, REQUEST, callingUid);
1156 
1157     request->StartTimeOutNetAvailable();
1158     uint32_t reqId = request->GetRequestId();
1159     NETMGR_LOG_I("New request [id:%{public}u]", reqId);
1160     NetRequest netrequest(request->GetUid(), reqId);
1161     {
1162         std::lock_guard<std::shared_mutex> guard(netActivatesMutex_);
1163         netActivates_[reqId] = request;
1164     }
1165     {
1166         std::lock_guard guard(uidActivateMutex_);
1167         netUidActivates_[callingUid].push_back(request);
1168     }
1169     sptr<NetSupplier> bestNet = nullptr;
1170     int bestScore = static_cast<int>(FindBestNetworkForRequest(bestNet, request));
1171     if (bestScore != 0 && bestNet != nullptr) {
1172         NETMGR_LOG_I(
1173             "Match to optimal supplier:[%{public}d %{public}s] netId[%{public}d] score[%{public}d] "
1174             "reqId[%{public}u]",
1175             bestNet->GetSupplierId(), bestNet->GetNetSupplierIdent().c_str(), bestNet->GetNetId(), bestScore, reqId);
1176         bestNet->SelectAsBestNetwork(netrequest);
1177         request->SetServiceSupply(bestNet);
1178         CallbackForAvailable(bestNet, callback);
1179         if ((bestNet->GetNetSupplierType() == BEARER_CELLULAR) || (bestNet->GetNetSupplierType() == BEARER_WIFI)) {
1180             std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
1181             struct EventInfo eventInfo = {.capabilities = bestNet->GetNetCapabilities().ToString(" "),
1182                                           .supplierIdent = bestNet->GetNetSupplierIdent()};
1183             locker.unlock();
1184             EventReport::SendRequestBehaviorEvent(eventInfo);
1185         }
1186         return NETMANAGER_SUCCESS;
1187     }
1188     if (timeoutMS == 0) {
1189         callback->NetUnavailable();
1190     }
1191 
1192     NETMGR_LOG_D("Not matched to the optimal network, send request to all networks.");
1193     SendRequestToAllNetwork(request);
1194     return NETMANAGER_SUCCESS;
1195 }
1196 
CreateNetActivateRequest(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS,const int32_t registerType,const uint32_t callingUid)1197 std::shared_ptr<NetActivate> NetConnService::CreateNetActivateRequest(const sptr<NetSpecifier> &netSpecifier,
1198                                                                       const sptr<INetConnCallback> &callback,
1199                                                                       const uint32_t &timeoutMS,
1200                                                                       const int32_t registerType,
1201                                                                       const uint32_t callingUid)
1202 {
1203     std::weak_ptr<INetActivateCallback> timeoutCb = shared_from_this();
1204     std::shared_ptr<NetActivate> request = nullptr;
1205 #ifdef ENABLE_SET_APP_FROZENED
1206     sptr<NetConnCallbackProxyWrapper> callbakWrapper = new (std::nothrow) NetConnCallbackProxyWrapper(callback);
1207     if (callbakWrapper == nullptr) {
1208         NETMGR_LOG_E("NetConnCallbackProxyWrapper ptr is null");
1209         request = std::make_shared<NetActivate>(
1210             netSpecifier, callback, timeoutCb, timeoutMS, netConnEventHandler_, callingUid, registerType);
1211     } else {
1212         request = std::make_shared<NetActivate>(
1213         netSpecifier, callbakWrapper, timeoutCb, timeoutMS, netConnEventHandler_, callingUid, registerType);
1214         callbakWrapper->SetNetActivate(request);
1215     }
1216 #else
1217     request = std::make_shared<NetActivate>(
1218         netSpecifier, callback, timeoutCb, timeoutMS, netConnEventHandler_, callingUid, registerType);
1219 #endif
1220     return request;
1221 }
1222 
OnNetActivateTimeOut(uint32_t reqId)1223 void NetConnService::OnNetActivateTimeOut(uint32_t reqId)
1224 {
1225     if (netConnEventHandler_) {
1226         netConnEventHandler_->PostSyncTask([reqId, this]() {
1227             NETMGR_LOG_I("DeactivateNetwork Enter, reqId is [%{public}d]", reqId);
1228             std::shared_lock<std::shared_mutex> lock(netActivatesMutex_);
1229             auto iterActivate = netActivates_.find(reqId);
1230             if (iterActivate == netActivates_.end()) {
1231                 NETMGR_LOG_E("not found the reqId: [%{public}d]", reqId);
1232                 return;
1233             }
1234             NetRequest netrequest;
1235             netrequest.requestId = reqId;
1236             if (iterActivate->second != nullptr) {
1237                 sptr<NetSupplier> pNetService = iterActivate->second->GetServiceSupply();
1238                 netrequest.uid = iterActivate->second->GetUid();
1239                 if (pNetService) {
1240                     pNetService->CancelRequest(netrequest);
1241                 }
1242             }
1243             lock.unlock();
1244 
1245             NET_SUPPLIER_MAP::iterator iterSupplier;
1246             for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1247                 if (iterSupplier->second == nullptr) {
1248                     continue;
1249                 }
1250                 iterSupplier->second->CancelRequest(netrequest);
1251             }
1252         });
1253     }
1254 }
1255 
FindNetSupplier(uint32_t supplierId)1256 sptr<NetSupplier> NetConnService::FindNetSupplier(uint32_t supplierId)
1257 {
1258     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1259     auto iterSupplier = netSuppliers_.find(supplierId);
1260     if (iterSupplier != netSuppliers_.end()) {
1261         return iterSupplier->second;
1262     }
1263     return nullptr;
1264 }
1265 
FindSameCallback(const sptr<INetConnCallback> & callback,uint32_t & reqId,RegisterType & registerType,uint32_t & uid)1266 bool NetConnService::FindSameCallback(const sptr<INetConnCallback> &callback,
1267                                       uint32_t &reqId, RegisterType &registerType, uint32_t &uid)
1268 {
1269     if (callback == nullptr) {
1270         NETMGR_LOG_E("callback is null");
1271         return false;
1272     }
1273     NET_ACTIVATE_MAP::iterator iterActive;
1274     NET_ACTIVATE_MAP netActivatesBck;
1275     {
1276         std::shared_lock<std::shared_mutex> lock(netActivatesMutex_);
1277         netActivatesBck = netActivates_;
1278     }
1279     for (iterActive = netActivatesBck.begin(); iterActive != netActivatesBck.end(); ++iterActive) {
1280         if (!iterActive->second) {
1281             continue;
1282         }
1283         sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
1284         if (saveCallback == nullptr) {
1285             continue;
1286         }
1287         if (callback->AsObject().GetRefPtr() == saveCallback->AsObject().GetRefPtr()) {
1288             reqId = iterActive->first;
1289             if (iterActive->second) {
1290                 auto specifier = iterActive->second->GetNetSpecifier();
1291                 registerType = (specifier != nullptr && ((specifier->netCapabilities_.netCaps_.count(
1292                     NetManagerStandard::NET_CAPABILITY_INTERNAL_DEFAULT) > 0) ||
1293                     (specifier->netCapabilities_.bearerTypes_.count(NetManagerStandard::BEARER_CELLULAR) > 0))) ?
1294                     REQUEST : REGISTER;
1295                 uid = iterActive->second->GetUid();
1296             }
1297             return true;
1298         }
1299     }
1300     return false;
1301 }
1302 
FindSameCallback(const sptr<INetConnCallback> & callback,uint32_t & reqId)1303 bool NetConnService::FindSameCallback(const sptr<INetConnCallback> &callback, uint32_t &reqId)
1304 {
1305     RegisterType registerType = INVALIDTYPE;
1306     uint32_t uid = 0;
1307     return FindSameCallback(callback, reqId, registerType, uid);
1308 }
1309 
FindBestNetworkForAllRequest()1310 void NetConnService::FindBestNetworkForAllRequest()
1311 {
1312     NET_ACTIVATE_MAP netActivatesBck;
1313     {
1314         std::shared_lock<std::shared_mutex> lock(netActivatesMutex_);
1315         netActivatesBck = netActivates_;
1316     }
1317     NETMGR_LOG_I("FindBestNetworkForAllRequest Enter. netActivates_ size: [%{public}zu]", netActivatesBck.size());
1318     NET_ACTIVATE_MAP::iterator iterActive;
1319     sptr<NetSupplier> bestSupplier = nullptr;
1320     for (iterActive = netActivatesBck.begin(); iterActive != netActivatesBck.end(); ++iterActive) {
1321         if (!iterActive->second) {
1322             continue;
1323         }
1324         int score = static_cast<int>(FindBestNetworkForRequest(bestSupplier, iterActive->second));
1325         NETMGR_LOG_D("Find best supplier[%{public}d, %{public}s]for request[%{public}d]",
1326                      bestSupplier ? bestSupplier->GetSupplierId() : 0,
1327                      bestSupplier ? bestSupplier->GetNetSupplierIdent().c_str() : "null",
1328                      iterActive->second->GetRequestId());
1329         if (iterActive->second == defaultNetActivate_) {
1330             MakeDefaultNetWork(defaultNetSupplier_, bestSupplier);
1331         }
1332         sptr<NetSupplier> oldSupplier = iterActive->second->GetServiceSupply();
1333         sptr<INetConnCallback> callback = iterActive->second->GetNetCallback();
1334         if (!bestSupplier) {
1335             // not found the bestNetwork
1336             NotFindBestSupplier(iterActive->first, iterActive->second, oldSupplier, callback);
1337             continue;
1338         }
1339         SendBestScoreAllNetwork(iterActive->first, score, bestSupplier->GetSupplierId(), iterActive->second->GetUid());
1340         if (bestSupplier == oldSupplier) {
1341             NETMGR_LOG_D("bestSupplier is equal with oldSupplier.");
1342             continue;
1343         }
1344         if (oldSupplier) {
1345             oldSupplier->RemoveBestRequest(iterActive->first);
1346         }
1347         iterActive->second->SetServiceSupply(bestSupplier);
1348         CallbackForAvailable(bestSupplier, callback);
1349         NetRequest netRequest(iterActive->second->GetUid(), iterActive->first);
1350         bestSupplier->SelectAsBestNetwork(netRequest);
1351     }
1352     NETMGR_LOG_I("FindBestNetworkForAllRequest end");
1353 }
1354 
FindBestNetworkForRequest(sptr<NetSupplier> & supplier,std::shared_ptr<NetActivate> & netActivateNetwork)1355 uint32_t NetConnService::FindBestNetworkForRequest(sptr<NetSupplier> &supplier,
1356                                                    std::shared_ptr<NetActivate> &netActivateNetwork)
1357 {
1358     int bestScore = 0;
1359     supplier = nullptr;
1360     if (netActivateNetwork == nullptr) {
1361         NETMGR_LOG_E("netActivateNetwork is null");
1362         return bestScore;
1363     }
1364     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1365     NET_SUPPLIER_MAP::iterator iter;
1366     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1367         if (iter->second == nullptr) {
1368             continue;
1369         }
1370         NETMGR_LOG_D("supplier info, supplier[%{public}d, %{public}s], realScore[%{public}d], isConnected[%{public}d]",
1371                      iter->second->GetSupplierId(), iter->second->GetNetSupplierIdent().c_str(),
1372                      iter->second->GetRealScore(), iter->second->IsConnected());
1373         if ((!iter->second->IsConnected()) || (!netActivateNetwork->MatchRequestAndNetwork(iter->second))) {
1374             NETMGR_LOG_D("Supplier[%{public}d] is not connected or not match request.", iter->second->GetSupplierId());
1375             continue;
1376         }
1377         int score = iter->second->GetRealScore();
1378         if (score > bestScore) {
1379             bestScore = score;
1380             supplier = iter->second;
1381         }
1382     }
1383     NETMGR_LOG_D(
1384         "bestScore[%{public}d], bestSupplier[%{public}d, %{public}s], "
1385         "request[%{public}d] is [%{public}s],",
1386         bestScore, supplier ? supplier->GetSupplierId() : 0,
1387         supplier ? supplier->GetNetSupplierIdent().c_str() : "null", netActivateNetwork->GetRequestId(),
1388         netActivateNetwork->GetNetSpecifier() ? netActivateNetwork->GetNetSpecifier()->ToString(" ").c_str() : "null");
1389     return bestScore;
1390 }
1391 
RequestAllNetworkExceptDefault()1392 void NetConnService::RequestAllNetworkExceptDefault()
1393 {
1394     if ((defaultNetSupplier_ == nullptr) || (defaultNetSupplier_->IsNetValidated())
1395         || (defaultNetSupplier_->IsNetAcceptUnavalidate())) {
1396         NETMGR_LOG_E("defaultNetSupplier_ is  null or IsNetValidated or AcceptUnavalidate");
1397         return;
1398     }
1399     NETMGR_LOG_I("Default supplier[%{public}d, %{public}s] is not valid,request to activate another network",
1400                  defaultNetSupplier_->GetSupplierId(), defaultNetSupplier_->GetNetSupplierIdent().c_str());
1401     if (defaultNetActivate_ == nullptr) {
1402         NETMGR_LOG_E("Default net request is null");
1403         return;
1404     }
1405     // Request activation of all networks except the default network
1406     NetRequest netrequest(
1407         defaultNetActivate_->GetUid(), defaultNetActivate_->GetRequestId(), defaultNetActivate_->GetRegisterType());
1408     for (const auto &netSupplier : netSuppliers_) {
1409         if (netSupplier.second == nullptr || netSupplier.second == defaultNetSupplier_) {
1410             NETMGR_LOG_E("netSupplier is null or is defaultNetSupplier_");
1411             continue;
1412         }
1413         if (netSupplier.second->GetNetScore() >= defaultNetSupplier_->GetNetScore()) {
1414             continue;
1415         }
1416         if (netSupplier.second->HasNetCap(NetCap::NET_CAPABILITY_INTERNAL_DEFAULT)) {
1417             NETMGR_LOG_I("Supplier[%{public}d] is internal, skip.", netSupplier.second->GetSupplierId());
1418             continue;
1419         }
1420         if (!defaultNetActivate_->MatchRequestAndNetwork(netSupplier.second, true)) {
1421             continue;
1422         }
1423         if (!netSupplier.second->RequestToConnect(netrequest)) {
1424             NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed",
1425                          netSupplier.second->GetSupplierId(), netSupplier.second->GetNetSupplierIdent().c_str());
1426         }
1427     }
1428 }
1429 
GenerateNetId()1430 int32_t NetConnService::GenerateNetId()
1431 {
1432     for (int32_t i = MIN_NET_ID; i <= MAX_NET_ID; ++i) {
1433         netIdLastValue_++;
1434         if (netIdLastValue_ > MAX_NET_ID) {
1435             netIdLastValue_ = MIN_NET_ID;
1436         }
1437         if (networks_.find(netIdLastValue_) == networks_.end()) {
1438             return netIdLastValue_;
1439         }
1440     }
1441     return INVALID_NET_ID;
1442 }
1443 
GenerateInternalNetId()1444 int32_t NetConnService::GenerateInternalNetId()
1445 {
1446     for (int32_t i = MIN_INTERNAL_NET_ID; i <= MAX_INTERNAL_NET_ID; ++i) {
1447         int32_t value = internalNetIdLastValue_++;
1448         if (value > MAX_INTERNAL_NET_ID) {
1449             internalNetIdLastValue_ = MIN_INTERNAL_NET_ID;
1450             value = MIN_INTERNAL_NET_ID;
1451         }
1452         if (networks_.find(value) == networks_.end()) {
1453             return value;
1454         }
1455     }
1456     return INVALID_NET_ID;
1457 }
1458 
NotFindBestSupplier(uint32_t reqId,const std::shared_ptr<NetActivate> & active,const sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)1459 void NetConnService::NotFindBestSupplier(uint32_t reqId, const std::shared_ptr<NetActivate> &active,
1460                                          const sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
1461 {
1462     NETMGR_LOG_I("Could not find best supplier for request:[%{public}d]", reqId);
1463     if (supplier != nullptr) {
1464         supplier->RemoveBestRequest(reqId);
1465         if (callback != nullptr) {
1466             sptr<NetHandle> netHandle = supplier->GetNetHandle();
1467             callback->NetLost(netHandle);
1468         }
1469     }
1470     if (active != nullptr) {
1471         active->SetServiceSupply(nullptr);
1472         SendRequestToAllNetwork(active);
1473     }
1474 }
1475 
SendAllRequestToNetwork(sptr<NetSupplier> supplier)1476 void NetConnService::SendAllRequestToNetwork(sptr<NetSupplier> supplier)
1477 {
1478     if (supplier == nullptr) {
1479         NETMGR_LOG_E("supplier is null");
1480         return;
1481     }
1482     NETMGR_LOG_I("Send all request to supplier[%{public}d, %{public}s]", supplier->GetSupplierId(),
1483                  supplier->GetNetSupplierIdent().c_str());
1484     NET_ACTIVATE_MAP::iterator iter;
1485     std::shared_lock<std::shared_mutex> lock(netActivatesMutex_);
1486     for (iter = netActivates_.begin(); iter != netActivates_.end(); ++iter) {
1487         if (iter->second == nullptr) {
1488             continue;
1489         }
1490         if (!iter->second->MatchRequestAndNetwork(supplier, true)) {
1491             continue;
1492         }
1493         NetRequest netrequest(iter->second->GetUid(), iter->first, iter->second->GetRegisterType());
1494         netrequest.bearTypes = iter->second->GetBearType();
1495         bool result = supplier->RequestToConnect(netrequest);
1496         if (!result) {
1497             NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed", supplier->GetSupplierId(),
1498                          supplier->GetNetSupplierIdent().c_str());
1499         }
1500     }
1501 }
1502 
SendRequestToAllNetwork(std::shared_ptr<NetActivate> request)1503 void NetConnService::SendRequestToAllNetwork(std::shared_ptr<NetActivate> request)
1504 {
1505     if (request == nullptr) {
1506         NETMGR_LOG_E("request is null");
1507         return;
1508     }
1509 
1510     NetRequest netrequest(request->GetUid(),
1511             request->GetRequestId(),
1512             request->GetRegisterType(),
1513             request->GetNetSpecifier()->ident_,
1514             request->GetBearType());
1515     NETMGR_LOG_I("Send request[%{public}d] to all supplier", netrequest.requestId);
1516     NET_SUPPLIER_MAP::iterator iter;
1517     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
1518     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1519         if (iter->second == nullptr) {
1520             continue;
1521         }
1522         if (!request->MatchRequestAndNetwork(iter->second, true)) {
1523             continue;
1524         }
1525 
1526         bool result = iter->second->RequestToConnect(netrequest);
1527         if (!result) {
1528             NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed", iter->second->GetSupplierId(),
1529                          iter->second->GetNetSupplierIdent().c_str());
1530         }
1531     }
1532 }
1533 
SendBestScoreAllNetwork(uint32_t reqId,int32_t bestScore,uint32_t supplierId,uint32_t uid)1534 void NetConnService::SendBestScoreAllNetwork(uint32_t reqId, int32_t bestScore, uint32_t supplierId, uint32_t uid)
1535 {
1536     NETMGR_LOG_D("Send best supplier[%{public}d]-score[%{public}d] to all supplier", supplierId, bestScore);
1537     NET_SUPPLIER_MAP::iterator iter;
1538     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1539     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1540         if (iter->second == nullptr) {
1541             continue;
1542         }
1543         if (iter->second->HasNetCap(NetCap::NET_CAPABILITY_INTERNAL_DEFAULT)) {
1544             continue;
1545         }
1546         NetRequest netrequest;
1547         netrequest.uid = uid;
1548         netrequest.requestId = reqId;
1549         iter->second->ReceiveBestScore(bestScore, supplierId, netrequest);
1550     }
1551 }
1552 
CallbackForSupplier(sptr<NetSupplier> & supplier,CallbackType type)1553 void NetConnService::CallbackForSupplier(sptr<NetSupplier> &supplier, CallbackType type)
1554 {
1555     if (supplier == nullptr) {
1556         NETMGR_LOG_E("supplier is nullptr");
1557         return;
1558     }
1559     std::set<uint32_t> &bestReqList = supplier->GetBestRequestList();
1560     NETMGR_LOG_I("Callback type: %{public}d for supplier[%{public}d, %{public}s], best request size: %{public}zd",
1561                  static_cast<int32_t>(type), supplier->GetSupplierId(), supplier->GetNetSupplierIdent().c_str(),
1562                  bestReqList.size());
1563     NET_ACTIVATE_MAP netActivatesBck;
1564     {
1565         std::shared_lock<std::shared_mutex> lock(netActivatesMutex_);
1566         netActivatesBck = netActivates_;
1567     }
1568     for (auto it : bestReqList) {
1569         auto reqIt = netActivatesBck.find(it);
1570         if (reqIt == netActivatesBck.end() || reqIt->second == nullptr || reqIt->second->GetNetCallback() == nullptr) {
1571             continue;
1572         }
1573         sptr<INetConnCallback> callback = reqIt->second->GetNetCallback();
1574         sptr<NetHandle> netHandle = supplier->GetNetHandle();
1575         HandleCallback(supplier, netHandle, callback, type);
1576     }
1577 }
1578 
HandleCallback(sptr<NetSupplier> & supplier,sptr<NetHandle> & netHandle,sptr<INetConnCallback> callback,CallbackType type)1579 void NetConnService::HandleCallback(sptr<NetSupplier> &supplier, sptr<NetHandle> &netHandle,
1580     sptr<INetConnCallback> callback, CallbackType type)
1581 {
1582     switch (type) {
1583         case CALL_TYPE_LOST: {
1584             callback->NetLost(netHandle);
1585             break;
1586         }
1587         case CALL_TYPE_UPDATE_CAP: {
1588             sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
1589             std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1590             *pNetAllCap = supplier->GetNetCapabilities();
1591             callback->NetCapabilitiesChange(netHandle, pNetAllCap);
1592             break;
1593         }
1594         case CALL_TYPE_UPDATE_LINK: {
1595             sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
1596             auto network = supplier->GetNetwork();
1597             if (network != nullptr && pInfo != nullptr) {
1598                 *pInfo = network->GetNetLinkInfo();
1599             }
1600             callback->NetConnectionPropertiesChange(netHandle, pInfo);
1601             break;
1602         }
1603         case CALL_TYPE_BLOCK_STATUS: {
1604             callback->NetBlockStatusChange(netHandle, NetManagerCenter::GetInstance().IsUidNetAccess(
1605                 supplier->GetSupplierUid(), supplier->HasNetCap(NET_CAPABILITY_NOT_METERED)));
1606             break;
1607         }
1608         case CALL_TYPE_UNAVAILABLE: {
1609             callback->NetUnavailable();
1610             break;
1611         }
1612         default:
1613             break;
1614     }
1615 }
1616 
CallbackForAvailable(sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)1617 void NetConnService::CallbackForAvailable(sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
1618 {
1619     if (supplier == nullptr || callback == nullptr) {
1620         NETMGR_LOG_E("Input parameter is null.");
1621         return;
1622     }
1623     NETMGR_LOG_I("CallbackForAvailable supplier[%{public}d, %{public}s]", supplier->GetSupplierId(),
1624                  supplier->GetNetSupplierIdent().c_str());
1625     sptr<NetHandle> netHandle = supplier->GetNetHandle();
1626     callback->NetAvailable(netHandle);
1627     sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
1628     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
1629     *pNetAllCap = supplier->GetNetCapabilities();
1630     locker.unlock();
1631     callback->NetCapabilitiesChange(netHandle, pNetAllCap);
1632     sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
1633     auto network = supplier->GetNetwork();
1634     if (network != nullptr && pInfo != nullptr) {
1635         *pInfo = network->GetNetLinkInfo();
1636     }
1637     callback->NetConnectionPropertiesChange(netHandle, pInfo);
1638     NetsysController::GetInstance().NotifyNetBearerTypeChange(pNetAllCap->bearerTypes_);
1639 }
1640 
MakeDefaultNetWork(sptr<NetSupplier> & oldSupplier,sptr<NetSupplier> & newSupplier)1641 void NetConnService::MakeDefaultNetWork(sptr<NetSupplier> &oldSupplier, sptr<NetSupplier> &newSupplier)
1642 {
1643     NETMGR_LOG_I(
1644         "oldSupplier[%{public}d, %{public}s], newSupplier[%{public}d, %{public}s], old equals "
1645         "new is [%{public}d]", oldSupplier ? oldSupplier->GetSupplierId() : 0,
1646         oldSupplier ? oldSupplier->GetNetSupplierIdent().c_str() : "null",
1647         newSupplier ? newSupplier->GetSupplierId() : 0,
1648         newSupplier ? newSupplier->GetNetSupplierIdent().c_str() : "null", oldSupplier == newSupplier);
1649     if (oldSupplier == newSupplier) {
1650         NETMGR_LOG_D("old supplier equal to new supplier.");
1651         return;
1652     }
1653     if (oldSupplier != nullptr) {
1654         oldSupplier->ClearDefault();
1655     }
1656     if (newSupplier != nullptr) {
1657         newSupplier->SetDefault();
1658     }
1659     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1660     oldSupplier = newSupplier;
1661 }
1662 
HandleDetectionResult(uint32_t supplierId,NetDetectionStatus netState)1663 void NetConnService::HandleDetectionResult(uint32_t supplierId, NetDetectionStatus netState)
1664 {
1665     NETMGR_LOG_I("Enter HandleDetectionResult, ifValid[%{public}d]", netState);
1666     auto supplier = FindNetSupplier(supplierId);
1667     if (supplier == nullptr) {
1668         NETMGR_LOG_E("supplier doesn't exist.");
1669         return;
1670     }
1671     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
1672     supplier->SetNetValid(netState);
1673     supplier->SetDetectionDone();
1674     locker.unlock();
1675     CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
1676     FindBestNetworkForAllRequest();
1677     bool ifValid = netState == VERIFICATION_STATE;
1678     if (!ifValid && defaultNetSupplier_ && defaultNetSupplier_->GetSupplierId() == supplierId) {
1679         RequestAllNetworkExceptDefault();
1680     }
1681     NETMGR_LOG_I("Enter HandleDetectionResult end");
1682 }
1683 
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident)1684 std::list<sptr<NetSupplier>> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident)
1685 {
1686     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1687     std::list<sptr<NetSupplier>> ret;
1688     for (const auto &netSupplier : netSuppliers_) {
1689         if (netSupplier.second == nullptr) {
1690             continue;
1691         }
1692         if ((bearerType != netSupplier.second->GetNetSupplierType())) {
1693             continue;
1694         }
1695         if (!ident.empty() && netSupplier.second->GetNetSupplierIdent() != ident) {
1696             continue;
1697         }
1698         ret.push_back(netSupplier.second);
1699     }
1700     return ret;
1701 }
1702 
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps)1703 sptr<NetSupplier> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident,
1704                                                          const std::set<NetCap> &netCaps)
1705 {
1706     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1707     for (const auto &netSupplier : netSuppliers_) {
1708         if (netSupplier.second == nullptr) {
1709             continue;
1710         }
1711         if ((bearerType == netSupplier.second->GetNetSupplierType()) &&
1712             (ident == netSupplier.second->GetNetSupplierIdent()) && netSupplier.second->CompareNetCaps(netCaps)) {
1713             return netSupplier.second;
1714         }
1715     }
1716     return nullptr;
1717 }
1718 
GetDefaultNet(int32_t & netId)1719 int32_t NetConnService::GetDefaultNet(int32_t &netId)
1720 {
1721     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1722     if (!defaultNetSupplier_) {
1723         NETMGR_LOG_D("not found the netId");
1724         return NETMANAGER_SUCCESS;
1725     }
1726 
1727     netId = defaultNetSupplier_->GetNetId();
1728     NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
1729     return NETMANAGER_SUCCESS;
1730 }
1731 
GetAddressesByName(const std::string & host,int32_t netId,std::vector<INetAddr> & addrList)1732 int32_t NetConnService::GetAddressesByName(const std::string &host, int32_t netId, std::vector<INetAddr> &addrList)
1733 {
1734     return NetManagerCenter::GetInstance().GetAddressesByName(host, static_cast<uint16_t>(netId), addrList);
1735 }
1736 
GetAddressByName(const std::string & host,int32_t netId,INetAddr & addr)1737 int32_t NetConnService::GetAddressByName(const std::string &host, int32_t netId, INetAddr &addr)
1738 {
1739     std::vector<INetAddr> addrList;
1740     int ret = GetAddressesByName(host, netId, addrList);
1741     if (ret == NETMANAGER_SUCCESS) {
1742         if (!addrList.empty()) {
1743             addr = addrList[0];
1744             return ret;
1745         }
1746         return NET_CONN_ERR_NO_ADDRESS;
1747     }
1748     return ret;
1749 }
1750 
GetSpecificNet(NetBearType bearerType,std::list<int32_t> & netIdList)1751 int32_t NetConnService::GetSpecificNet(NetBearType bearerType, std::list<int32_t> &netIdList)
1752 {
1753     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1754         NETMGR_LOG_E("netType parameter invalid");
1755         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1756     }
1757 
1758     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1759     NET_SUPPLIER_MAP::iterator iterSupplier;
1760     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1761         if (iterSupplier->second == nullptr) {
1762             continue;
1763         }
1764         auto supplierType = iterSupplier->second->GetNetSupplierType();
1765         if (bearerType == supplierType) {
1766             netIdList.push_back(iterSupplier->second->GetNetId());
1767         }
1768     }
1769     NETMGR_LOG_D("netSuppliers_ size[%{public}zd] networks_ size[%{public}zd]", netSuppliers_.size(), networks_.size());
1770     return NETMANAGER_SUCCESS;
1771 }
1772 
GetSpecificNetByIdent(NetBearType bearerType,const std::string & ident,std::list<int32_t> & netIdList)1773 int32_t NetConnService::GetSpecificNetByIdent(NetBearType bearerType, const std::string &ident,
1774                                               std::list<int32_t> &netIdList)
1775 {
1776     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1777         NETMGR_LOG_E("netType parameter invalid");
1778         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1779     }
1780 
1781     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1782     NET_SUPPLIER_MAP::iterator iterSupplier;
1783     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1784         if (iterSupplier->second == nullptr) {
1785             continue;
1786         }
1787         auto supplierType = iterSupplier->second->GetNetSupplierType();
1788         std::string supplierIdent = iterSupplier->second->GetNetSupplierIdent();
1789         if (bearerType == supplierType && ident == supplierIdent) {
1790             netIdList.push_back(iterSupplier->second->GetNetId());
1791         }
1792     }
1793     NETMGR_LOG_D("netSuppliers_ size[%{public}zd] networks_ size[%{public}zd]", netSuppliers_.size(), networks_.size());
1794     return NETMANAGER_SUCCESS;
1795 }
1796 
GetAllNetsAsync(std::list<int32_t> & netIdList)1797 int32_t NetConnService::GetAllNetsAsync(std::list<int32_t> &netIdList)
1798 {
1799     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1800     auto currentUid = IPCSkeleton::GetCallingUid();
1801     for (const auto &network : networks_) {
1802         if (network.second != nullptr && network.second->IsConnected()) {
1803             auto netId = network.second->GetNetId();
1804             sptr<NetSupplier> curSupplier = FindNetSupplier(network.second->GetSupplierId());
1805             // inner virtual interface and uid is not trusted, skip
1806             if (curSupplier != nullptr &&
1807                 curSupplier->HasNetCap(NetCap::NET_CAPABILITY_INTERNAL_DEFAULT) &&
1808                 !IsInRequestNetUids(currentUid)) {
1809                 NETMGR_LOG_D("Network [%{public}d] is internal, uid [%{public}d] skips.", netId, currentUid);
1810                 continue;
1811             }
1812             netIdList.push_back(netId);
1813         }
1814     }
1815     NETMGR_LOG_D("netSuppliers_ size[%{public}zd] netIdList size[%{public}zd]", netSuppliers_.size(), netIdList.size());
1816     return NETMANAGER_SUCCESS;
1817 }
1818 
GetAllNets(std::list<int32_t> & netIdList)1819 int32_t NetConnService::GetAllNets(std::list<int32_t> &netIdList)
1820 {
1821     int32_t result = NETMANAGER_ERROR;
1822     if (netConnEventHandler_) {
1823         netConnEventHandler_->PostSyncTask([this, &netIdList, &result]() {
1824             result = this->GetAllNetsAsync(netIdList);
1825         });
1826     }
1827     return result;
1828 }
1829 
IsInRequestNetUids(int32_t uid)1830 bool NetConnService::IsInRequestNetUids(int32_t uid)
1831 {
1832     return internalDefaultUidRequest_.count(uid) > 0;
1833 }
1834 
GetSpecificUidNet(int32_t uid,int32_t & netId)1835 int32_t NetConnService::GetSpecificUidNet(int32_t uid, int32_t &netId)
1836 {
1837     NETMGR_LOG_D("Enter GetSpecificUidNet, uid is [%{public}d].", uid);
1838     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1839     netId = INVALID_NET_ID;
1840     NET_SUPPLIER_MAP::iterator iterSupplier;
1841     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1842         if ((iterSupplier->second != nullptr) && (uid == iterSupplier->second->GetSupplierUid()) &&
1843             (iterSupplier->second->GetNetSupplierType() == BEARER_VPN)) {
1844             netId = iterSupplier->second->GetNetId();
1845             return NETMANAGER_SUCCESS;
1846         }
1847     }
1848     if (defaultNetSupplier_ != nullptr) {
1849         netId = defaultNetSupplier_->GetNetId();
1850     }
1851     NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
1852     return NETMANAGER_SUCCESS;
1853 }
1854 
GetConnectionProperties(int32_t netId,NetLinkInfo & info)1855 int32_t NetConnService::GetConnectionProperties(int32_t netId, NetLinkInfo &info)
1856 {
1857     if (netConnEventHandler_ == nullptr) {
1858         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1859         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1860     }
1861     int32_t result = NETMANAGER_SUCCESS;
1862     netConnEventHandler_->PostSyncTask([netId, &info, &result, this]() {
1863         auto iterNetwork = networks_.find(netId);
1864         if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
1865             result = NET_CONN_ERR_INVALID_NETWORK;
1866             return;
1867         }
1868         info = iterNetwork->second->GetNetLinkInfo();
1869         if (info.mtu_ == 0) {
1870             info.mtu_ = DEFAULT_MTU;
1871         }
1872     });
1873     return result;
1874 }
1875 
GetNetCapabilities(int32_t netId,NetAllCapabilities & netAllCap)1876 int32_t NetConnService::GetNetCapabilities(int32_t netId, NetAllCapabilities &netAllCap)
1877 {
1878     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1879     NET_SUPPLIER_MAP::iterator iterSupplier;
1880     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1881         if ((iterSupplier->second != nullptr) && (netId == iterSupplier->second->GetNetId())) {
1882             netAllCap = iterSupplier->second->GetNetCapabilities();
1883             return NETMANAGER_SUCCESS;
1884         }
1885     }
1886     return NET_CONN_ERR_INVALID_NETWORK;
1887 }
1888 
GetIfaceNames(NetBearType bearerType,std::list<std::string> & ifaceNames)1889 int32_t NetConnService::GetIfaceNames(NetBearType bearerType, std::list<std::string> &ifaceNames)
1890 {
1891     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1892         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1893     }
1894 
1895     if (netConnEventHandler_ == nullptr) {
1896         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1897         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1898     }
1899     netConnEventHandler_->PostSyncTask([bearerType, &ifaceNames, this]() {
1900         auto suppliers = GetNetSupplierFromList(bearerType);
1901         for (auto supplier : suppliers) {
1902             if (supplier == nullptr) {
1903                 continue;
1904             }
1905             std::shared_ptr<Network> network = supplier->GetNetwork();
1906             if (network == nullptr) {
1907                 continue;
1908             }
1909             std::string ifaceName = network->GetIfaceName();
1910             if (!ifaceName.empty()) {
1911                 ifaceNames.push_back(ifaceName);
1912             }
1913         }
1914     });
1915     return NETMANAGER_SUCCESS;
1916 }
1917 
GetIfaceNameByType(NetBearType bearerType,const std::string & ident,std::string & ifaceName)1918 int32_t NetConnService::GetIfaceNameByType(NetBearType bearerType, const std::string &ident, std::string &ifaceName)
1919 {
1920     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1921         NETMGR_LOG_E("netType parameter invalid");
1922         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1923     }
1924     if (netConnEventHandler_ == nullptr) {
1925         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1926         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1927     }
1928     int32_t result = NETMANAGER_SUCCESS;
1929     netConnEventHandler_->PostSyncTask([bearerType, &ifaceName, &ident, &result, this]() {
1930         auto suppliers = GetNetSupplierFromList(bearerType, ident);
1931         if (suppliers.empty()) {
1932             NETMGR_LOG_D("supplier is nullptr.");
1933             result = NET_CONN_ERR_NO_SUPPLIER;
1934             return;
1935         }
1936         auto supplier = suppliers.front();
1937         if (supplier == nullptr) {
1938             NETMGR_LOG_E("supplier is nullptr");
1939             result = NETMANAGER_ERR_LOCAL_PTR_NULL;
1940             return;
1941         }
1942         std::shared_ptr<Network> network = supplier->GetNetwork();
1943         if (network == nullptr) {
1944             NETMGR_LOG_E("network is nullptr");
1945             result = NET_CONN_ERR_INVALID_NETWORK;
1946             return;
1947         }
1948         ifaceName = network->GetIfaceName();
1949     });
1950     return result;
1951 }
1952 
GetIfaceNameIdentMaps(NetBearType bearerType,SafeMap<std::string,std::string> & ifaceNameIdentMaps)1953 int32_t NetConnService::GetIfaceNameIdentMaps(NetBearType bearerType,
1954                                               SafeMap<std::string, std::string> &ifaceNameIdentMaps)
1955 {
1956     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1957         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1958     }
1959 
1960     if (netConnEventHandler_ == nullptr) {
1961         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1962         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1963     }
1964     netConnEventHandler_->PostSyncTask([bearerType, &ifaceNameIdentMaps, this]() {
1965         NETMGR_LOG_I("Enter GetIfaceNameIdentMaps, netBearType=%{public}d", bearerType);
1966         ifaceNameIdentMaps.Clear();
1967         auto suppliers = GetNetSupplierFromList(bearerType);
1968         for (auto supplier: suppliers) {
1969             if (supplier == nullptr || !supplier->HasNetCap(NET_CAPABILITY_INTERNET)) {
1970                 continue;
1971             }
1972             std::shared_ptr <Network> network = supplier->GetNetwork();
1973             if (network == nullptr || !network->IsConnected()) {
1974                 continue;
1975             }
1976             std::string ifaceName = network->GetIfaceName();
1977             if (ifaceName.empty()) {
1978                 continue;
1979             }
1980             std::string ident = network->GetIdent();
1981             ifaceNameIdentMaps.EnsureInsert(std::move(ifaceName), std::move(ident));
1982         }
1983     });
1984     return NETMANAGER_SUCCESS;
1985 }
1986 
GetGlobalHttpProxy(HttpProxy & httpProxy)1987 int32_t NetConnService::GetGlobalHttpProxy(HttpProxy &httpProxy)
1988 {
1989     NETMGR_LOG_I("GetGlobalHttpProxy userId[%{public}d]", httpProxy.GetUserId());
1990     if (httpProxy.GetUserId() == ROOT_USER_ID || httpProxy.GetUserId() == INVALID_USER_ID) {
1991         LoadGlobalHttpProxy(ACTIVE, httpProxy);
1992     }
1993     if (httpProxy.GetUserId() > 0) {
1994         // if the valid userId is given. so load http proxy from specified user.
1995         LoadGlobalHttpProxy(SPECIFY, httpProxy);
1996     } else {
1997         // executed in the caller process, so load http proxy from local user which the process belongs.
1998         LoadGlobalHttpProxy(LOCAL, httpProxy);
1999     }
2000     if (httpProxy.GetHost().empty()) {
2001         httpProxy.SetPort(0);
2002         NETMGR_LOG_E("The http proxy host is empty");
2003         return NETMANAGER_SUCCESS;
2004     }
2005     return NETMANAGER_SUCCESS;
2006 }
2007 
GetDefaultHttpProxy(int32_t bindNetId,HttpProxy & httpProxy)2008 int32_t NetConnService::GetDefaultHttpProxy(int32_t bindNetId, HttpProxy &httpProxy)
2009 {
2010     NETMGR_LOG_I("GetDefaultHttpProxy userId[%{public}d]", httpProxy.GetUserId());
2011     if (httpProxy.GetUserId() == ROOT_USER_ID || httpProxy.GetUserId() == INVALID_USER_ID) {
2012         LoadGlobalHttpProxy(ACTIVE, httpProxy);
2013     }
2014     auto startTime = std::chrono::steady_clock::now();
2015     if (httpProxy.GetUserId() > 0) {
2016         // if the valid userId is given. so load http proxy from specified user.
2017         LoadGlobalHttpProxy(SPECIFY, httpProxy);
2018     } else {
2019         // executed in the caller process, so load http proxy from local user which the process belongs.
2020         LoadGlobalHttpProxy(LOCAL, httpProxy);
2021     }
2022     if (!httpProxy.GetHost().empty()) {
2023         NETMGR_LOG_D("Return global http proxy as default.");
2024         return NETMANAGER_SUCCESS;
2025     }
2026 
2027     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2028     auto iter = networks_.find(bindNetId);
2029     if ((iter != networks_.end()) && (iter->second != nullptr)) {
2030         httpProxy = iter->second->GetHttpProxy();
2031         NETMGR_LOG_I("Return bound network's http proxy as default.");
2032         return NETMANAGER_SUCCESS;
2033     }
2034 
2035     if (defaultNetSupplier_ != nullptr) {
2036         defaultNetSupplier_->GetHttpProxy(httpProxy);
2037         auto endTime = std::chrono::steady_clock::now();
2038         auto durationNs = std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime);
2039         NETMGR_LOG_D("Use default http proxy, cost=%{public}lld",  durationNs.count());
2040         return NETMANAGER_SUCCESS;
2041     }
2042     auto endTime = std::chrono::steady_clock::now();
2043     auto durationNs = std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime);
2044     NETMGR_LOG_I("No default http proxy, durationNs=%{public}lld", durationNs.count());
2045     return NETMANAGER_SUCCESS;
2046 }
2047 
GetNetIdByIdentifier(const std::string & ident,std::list<int32_t> & netIdList)2048 int32_t NetConnService::GetNetIdByIdentifier(const std::string &ident, std::list<int32_t> &netIdList)
2049 {
2050     if (ident.empty()) {
2051         NETMGR_LOG_E("The identifier in service is null");
2052         return NETMANAGER_ERR_INVALID_PARAMETER;
2053     }
2054     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2055     for (auto iterSupplier : netSuppliers_) {
2056         if (iterSupplier.second == nullptr) {
2057             continue;
2058         }
2059         if (iterSupplier.second->GetNetSupplierIdent() == ident) {
2060             int32_t netId = iterSupplier.second->GetNetId();
2061             netIdList.push_back(netId);
2062         }
2063     }
2064     return NETMANAGER_SUCCESS;
2065 }
2066 
GetDumpMessage(std::string & message)2067 void NetConnService::GetDumpMessage(std::string &message)
2068 {
2069     message.append("Net connect Info:\n");
2070     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2071     if (defaultNetSupplier_) {
2072         message.append("\tSupplierId: " + std::to_string(defaultNetSupplier_->GetSupplierId()) + "\n");
2073         std::shared_ptr<Network> network = defaultNetSupplier_->GetNetwork();
2074         if (network) {
2075             message.append("\tNetId: " + std::to_string(network->GetNetId()) + "\n");
2076         } else {
2077             message.append("\tNetId: " + std::to_string(INVALID_NET_ID) + "\n");
2078         }
2079         message.append("\tConnStat: " + std::to_string(defaultNetSupplier_->IsConnected()) + "\n");
2080         message.append("\tIsAvailable: " + std::to_string(defaultNetSupplier_->IsNetValidated()) + "\n");
2081         message.append("\tIsRoaming: " + std::to_string(defaultNetSupplier_->GetRoaming()) + "\n");
2082         message.append("\tStrength: " + std::to_string(defaultNetSupplier_->GetStrength()) + "\n");
2083         message.append("\tFrequency: " + std::to_string(defaultNetSupplier_->GetFrequency()) + "\n");
2084         message.append("\tLinkUpBandwidthKbps: " +
2085                        std::to_string(defaultNetSupplier_->GetNetCapabilities().linkUpBandwidthKbps_) + "\n");
2086         message.append("\tLinkDownBandwidthKbps: " +
2087                        std::to_string(defaultNetSupplier_->GetNetCapabilities().linkDownBandwidthKbps_) + "\n");
2088         message.append("\tUid: " + std::to_string(defaultNetSupplier_->GetSupplierUid()) + "\n");
2089     } else {
2090         message.append("\tdefaultNetSupplier_ is nullptr\n");
2091         message.append("\tSupplierId: \n");
2092         message.append("\tNetId: 0\n");
2093         message.append("\tConnStat: 0\n");
2094         message.append("\tIsAvailable: \n");
2095         message.append("\tIsRoaming: 0\n");
2096         message.append("\tStrength: 0\n");
2097         message.append("\tFrequency: 0\n");
2098         message.append("\tLinkUpBandwidthKbps: 0\n");
2099         message.append("\tLinkDownBandwidthKbps: 0\n");
2100         message.append("\tUid: 0\n");
2101     }
2102     if (dnsResultCallback_ != nullptr) {
2103         dnsResultCallback_->GetDumpMessageForDnsResult(message);
2104     }
2105 }
2106 
HasDefaultNet(bool & flag)2107 int32_t NetConnService::HasDefaultNet(bool &flag)
2108 {
2109     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2110     if (!defaultNetSupplier_) {
2111         flag = false;
2112         return NETMANAGER_SUCCESS;
2113     }
2114     flag = true;
2115     return NETMANAGER_SUCCESS;
2116 }
2117 
IsDefaultNetMetered(bool & isMetered)2118 int32_t NetConnService::IsDefaultNetMetered(bool &isMetered)
2119 {
2120     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2121     if (defaultNetSupplier_) {
2122         isMetered = !defaultNetSupplier_->HasNetCap(NET_CAPABILITY_NOT_METERED);
2123     } else {
2124         isMetered = true;
2125     }
2126     return NETMANAGER_SUCCESS;
2127 }
2128 
BindSocket(int32_t socketFd,int32_t netId)2129 int32_t NetConnService::BindSocket(int32_t socketFd, int32_t netId)
2130 {
2131     NETMGR_LOG_D("Enter BindSocket.");
2132     return NetsysController::GetInstance().BindSocket(socketFd, netId);
2133 }
2134 
Dump(int32_t fd,const std::vector<std::u16string> & args)2135 int32_t NetConnService::Dump(int32_t fd, const std::vector<std::u16string> &args)
2136 {
2137     NETMGR_LOG_D("Start Dump, fd: %{public}d", fd);
2138     std::string result;
2139     GetDumpMessage(result);
2140     int32_t ret = dprintf(fd, "%s\n", result.c_str());
2141     return (ret < 0) ? static_cast<int32_t>(NET_CONN_ERR_CREATE_DUMP_FAILED) : static_cast<int32_t>(NETMANAGER_SUCCESS);
2142 }
2143 
IsValidDecValue(const std::string & inputValue)2144 bool NetConnService::IsValidDecValue(const std::string &inputValue)
2145 {
2146     if (inputValue.length() > INPUT_VALUE_LENGTH) {
2147         NETMGR_LOG_E("The value entered is out of range, value:%{public}s", inputValue.c_str());
2148         return false;
2149     }
2150     bool isValueNumber = regex_match(inputValue, std::regex("(-[\\d+]+)|(\\d+)"));
2151     if (isValueNumber) {
2152         int64_t numberValue = std::stoll(inputValue);
2153         if ((numberValue >= INT32_MIN) && (numberValue <= INT32_MAX)) {
2154             return true;
2155         }
2156     }
2157     NETMGR_LOG_I("InputValue is not a decimal number");
2158     return false;
2159 }
2160 
GetDelayNotifyTime()2161 int32_t NetConnService::GetDelayNotifyTime()
2162 {
2163     char param[SYS_PARAMETER_SIZE] = { 0 };
2164     int32_t delayTime = 0;
2165     int32_t code = GetParameter(CFG_NETWORK_PRE_AIRPLANE_MODE_WAIT_TIMES, NO_DELAY_TIME_CONFIG,
2166                                 param, SYS_PARAMETER_SIZE);
2167     std::string time = param;
2168     if (code <= 0 || !IsValidDecValue(time)) {
2169         try {
2170             delayTime = std::stoi(NO_DELAY_TIME_CONFIG);
2171         } catch (const std::invalid_argument& e) {
2172             NETMGR_LOG_E("invalid_argument");
2173             return delayTime;
2174         } catch (const std::out_of_range& e) {
2175             NETMGR_LOG_E("out_of_range");
2176             return delayTime;
2177         }
2178     } else {
2179         try {
2180             auto tmp = std::stoi(time);
2181             delayTime = tmp > static_cast<int32_t>(MAX_DELAY_TIME) ? std::stoi(NO_DELAY_TIME_CONFIG) : tmp;
2182         } catch (const std::invalid_argument& e) {
2183             NETMGR_LOG_E("invalid_argument");
2184             return delayTime;
2185         } catch (const std::out_of_range& e) {
2186             NETMGR_LOG_E("out_of_range");
2187             return delayTime;
2188         }
2189     }
2190     NETMGR_LOG_D("delay time is %{public}d", delayTime);
2191     return delayTime;
2192 }
2193 
RegisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback)2194 int32_t NetConnService::RegisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback)
2195 {
2196     int32_t callingUid = static_cast<int32_t>(IPCSkeleton::GetCallingUid());
2197     NETMGR_LOG_D("RegisterPreAirplaneCallback, calllinguid [%{public}d]", callingUid);
2198     std::lock_guard guard(preAirplaneCbsMutex_);
2199     preAirplaneCallbacks_[callingUid] = callback;
2200     return NETMANAGER_SUCCESS;
2201 }
2202 
UnregisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback)2203 int32_t NetConnService::UnregisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback)
2204 {
2205     int32_t callingUid = static_cast<int32_t>(IPCSkeleton::GetCallingUid());
2206     NETMGR_LOG_D("UnregisterPreAirplaneCallback, calllinguid [%{public}d]", callingUid);
2207     std::lock_guard guard(preAirplaneCbsMutex_);
2208     preAirplaneCallbacks_.erase(callingUid);
2209     return NETMANAGER_SUCCESS;
2210 }
2211 
SetAirplaneMode(bool state)2212 int32_t NetConnService::SetAirplaneMode(bool state)
2213 {
2214     NETMGR_LOG_I("Enter SetAirplaneMode, AirplaneMode is %{public}d", state);
2215     if (state) {
2216         std::lock_guard guard(preAirplaneCbsMutex_);
2217         for (const auto& mem : preAirplaneCallbacks_) {
2218             if (mem.second != nullptr) {
2219                 int32_t ret = mem.second->PreAirplaneStart();
2220                 NETMGR_LOG_D("PreAirplaneStart result %{public}d", ret);
2221             }
2222         }
2223     }
2224     if (netConnEventHandler_ == nullptr) {
2225         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
2226         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2227     }
2228     netConnEventHandler_->RemoveAsyncTask("delay airplane mode");
2229     auto delayTime = GetDelayNotifyTime();
2230 
2231     bool ret = netConnEventHandler_->PostAsyncTask(
2232         [state]() {
2233             NETMGR_LOG_I("Enter delay");
2234             auto dataShareHelperUtils = std::make_unique<NetDataShareHelperUtils>();
2235             std::string airplaneMode = std::to_string(state);
2236             Uri uri(AIRPLANE_MODE_URI);
2237             int32_t ret = dataShareHelperUtils->Update(uri, KEY_AIRPLANE_MODE, airplaneMode);
2238             if (ret != NETMANAGER_SUCCESS) {
2239                 NETMGR_LOG_E("Update airplane mode:%{public}d to datashare failed.", state);
2240                 return;
2241             }
2242             BroadcastInfo info;
2243             info.action = EventFwk::CommonEventSupport::COMMON_EVENT_AIRPLANE_MODE_CHANGED;
2244             info.data = "Net Manager Airplane Mode Changed";
2245             info.code = static_cast<int32_t>(state);
2246             info.ordered = false;
2247             std::map<std::string, int32_t> param;
2248             BroadcastManager::GetInstance().SendBroadcast(info, param);
2249         },
2250         "delay airplane mode", delayTime);
2251     NETMGR_LOG_I("SetAirplaneMode out [%{public}d]", ret);
2252 
2253     return NETMANAGER_SUCCESS;
2254 }
2255 
ActiveHttpProxy()2256 void NetConnService::ActiveHttpProxy()
2257 {
2258     NETMGR_LOG_D("ActiveHttpProxy thread start");
2259     uint32_t retryTimes = RETRY_TIMES;
2260     while (httpProxyThreadNeedRun_.load()) {
2261         NETMGR_LOG_D("Keep global http-proxy active every 2 minutes");
2262         CURL *curl = nullptr;
2263         HttpProxy tempProxy;
2264         {
2265             auto userInfoHelp = NetProxyUserinfo::GetInstance();
2266             // executed in the SA process, so load http proxy from current active user.
2267             LoadGlobalHttpProxy(ACTIVE, tempProxy);
2268             userInfoHelp.GetHttpProxyHostPass(tempProxy);
2269         }
2270         if (!tempProxy.host_.empty() && !tempProxy.username_.empty()) {
2271             curl = curl_easy_init();
2272             SetCurlOptions(curl, tempProxy);
2273         }
2274         if (curl) {
2275             long response_code;
2276             auto ret = curl_easy_perform(curl);
2277             curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
2278             NETMGR_LOG_D("SetGlobalHttpProxy ActiveHttpProxy ret: %{public}d, code: %{public}d", static_cast<int>(ret),
2279                          static_cast<int32_t>(response_code));
2280             if (response_code != SUCCESS_CODE && retryTimes == 0 && !isInSleep_.load()) {
2281                 retryTimes = RETRY_TIMES;
2282             }
2283             curl_easy_cleanup(curl);
2284         }
2285         if (httpProxyThreadNeedRun_.load()) {
2286             if (retryTimes == 0) {
2287                 std::unique_lock lock(httpProxyThreadMutex_);
2288                 auto notifyRet = httpProxyThreadCv_.wait_for(lock, std::chrono::seconds(isInSleep_.load() ?
2289                     HTTP_PROXY_ACTIVE_PERIOD_IN_SLEEP_S : HTTP_PROXY_ACTIVE_PERIOD_S));
2290                 retryTimes = (notifyRet == std::cv_status::timeout) ? 0 : RETRY_TIMES;
2291             } else {
2292                 retryTimes--;
2293             }
2294         } else {
2295             NETMGR_LOG_W("ActiveHttpProxy has been clear.");
2296         }
2297     }
2298 }
2299 
SetCurlOptions(CURL * curl,HttpProxy tempProxy)2300 void NetConnService::SetCurlOptions(CURL *curl, HttpProxy tempProxy)
2301 {
2302     std::string httpUrl;
2303     GetHttpUrlFromConfig(httpUrl);
2304     if (httpUrl.empty()) {
2305         NETMGR_LOG_E("ActiveHttpProxy thread get url failed!");
2306         return;
2307     }
2308     auto proxyType = (tempProxy.host_.find("https://") != std::string::npos) ? CURLPROXY_HTTPS : CURLPROXY_HTTP;
2309     curl_easy_setopt(curl, CURLOPT_URL, httpUrl.c_str());
2310     curl_easy_setopt(curl, CURLOPT_TIMEOUT, AUTH_TIME_OUT);
2311     curl_easy_setopt(curl, CURLOPT_PROXY, tempProxy.host_.c_str());
2312     curl_easy_setopt(curl, CURLOPT_PROXYPORT, tempProxy.port_);
2313     curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxyType);
2314     curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, tempProxy.username_.c_str());
2315     if (!tempProxy.password_.empty()) {
2316         curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
2317         curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
2318         curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, tempProxy.password_.c_str());
2319     } else {
2320         curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
2321     }
2322 }
2323 
GetHttpUrlFromConfig(std::string & httpUrl)2324 void NetConnService::GetHttpUrlFromConfig(std::string &httpUrl)
2325 {
2326     if (!std::filesystem::exists(URL_CFG_FILE)) {
2327         NETMGR_LOG_E("File not exist (%{public}s)", URL_CFG_FILE);
2328         return;
2329     }
2330 
2331     std::ifstream file(URL_CFG_FILE);
2332     if (!file.is_open()) {
2333         NETMGR_LOG_E("Open file failed (%{public}s)", strerror(errno));
2334         return;
2335     }
2336 
2337     std::ostringstream oss;
2338     oss << file.rdbuf();
2339     std::string content = oss.str();
2340     auto pos = content.find(HTTP_URL_HEADER);
2341     if (pos != std::string::npos) {
2342         pos += strlen(HTTP_URL_HEADER);
2343         httpUrl = content.substr(pos, content.find(NEW_LINE_STR, pos) - pos);
2344     }
2345     NETMGR_LOG_D("Get net detection http url:[%{public}s]", httpUrl.c_str());
2346 }
2347 
SetGlobalHttpProxyInner(const HttpProxy & httpProxy)2348 int32_t NetConnService::SetGlobalHttpProxyInner(const HttpProxy &httpProxy)
2349 {
2350     NetHttpProxyTracker httpProxyTracker;
2351     HttpProxy newHttpProxy = httpProxy;
2352     int32_t userId = GetValidUserIdFromProxy(httpProxy);
2353     if (userId == INVALID_USER_ID) {
2354         return NETMANAGER_ERR_INTERNAL;
2355     }
2356     if (IsPrimaryUserId(userId)) {
2357         if (!httpProxyTracker.WriteToSettingsData(newHttpProxy)) {
2358             NETMGR_LOG_E("SetGlobalHttpProxyInner write settingDate fail.");
2359             return NETMANAGER_ERR_INTERNAL;
2360         }
2361     }
2362     if (!httpProxyTracker.WriteToSettingsDataUser(newHttpProxy, userId)) {
2363         NETMGR_LOG_E("SetGlobalHttpProxyInner write settingDateUser fail. userId=%{public}d", userId);
2364         return NETMANAGER_ERR_INTERNAL;
2365     }
2366     globalHttpProxyCache_.EnsureInsert(userId, httpProxy);
2367     SendHttpProxyChangeBroadcast(httpProxy);
2368     UpdateGlobalHttpProxy(httpProxy);
2369     return NETMANAGER_SUCCESS;
2370 }
2371 
SetGlobalHttpProxyOld(HttpProxy httpProxy,int32_t activeUserId)2372 int32_t NetConnService::SetGlobalHttpProxyOld(HttpProxy httpProxy, int32_t activeUserId)
2373 {
2374     if (currentUserId_ == INVALID_USER_ID) {
2375         if (!httpProxy.GetHost().empty()) {
2376             currentUserId_ = activeUserId;
2377         }
2378         httpProxy.SetUserId(currentUserId_);
2379     } else if (currentUserId_ == activeUserId) {
2380         httpProxy.SetUserId(currentUserId_);
2381     } else {
2382         if (httpProxy.GetHost().empty()) {
2383             httpProxy.SetUserId(currentUserId_);
2384             currentUserId_ = INVALID_USER_ID;
2385         } else {
2386             HttpProxy emptyHttpProxy;
2387             emptyHttpProxy.SetUserId(currentUserId_);
2388             if (SetGlobalHttpProxyInner(emptyHttpProxy) != NETMANAGER_SUCCESS) {
2389                 return NETMANAGER_ERR_INTERNAL;
2390             }
2391             currentUserId_ = activeUserId;
2392             httpProxy.SetUserId(currentUserId_);
2393         }
2394     }
2395     SetGlobalHttpProxyInner(httpProxy);
2396     if (!httpProxy.GetHost().empty()) {
2397         httpProxyThreadCv_.notify_all();
2398     }
2399     if (!httpProxyThreadNeedRun_ && !httpProxy.GetUsername().empty()) {
2400         CreateActiveHttpProxyThread();
2401     } else if (httpProxyThreadNeedRun_ && httpProxy.GetHost().empty()) {
2402         httpProxyThreadNeedRun_ = false;
2403     }
2404     NETMGR_LOG_I("End SetGlobalHttpProxyOld.");
2405     return NETMANAGER_SUCCESS;
2406 }
2407 
SetGlobalHttpProxy(const HttpProxy & httpProxy)2408 int32_t NetConnService::SetGlobalHttpProxy(const HttpProxy &httpProxy)
2409 {
2410     int32_t activeUserId;
2411     int32_t ret = GetActiveUserId(activeUserId);
2412     if (ret != NETMANAGER_SUCCESS) {
2413         NETMGR_LOG_E("SetGlobalHttpProxy failed to get active userId.");
2414         return INVALID_USER_ID;
2415     }
2416     NETMGR_LOG_I(
2417         "Enter SetGlobalHttpProxy. httpproxy = %{public}zu, currentUserId_=%{public}d, activeUserId=%{public}d",
2418         httpProxy.GetHost().length(), currentUserId_, activeUserId);
2419     if (httpProxy.GetUserId() == INVALID_USER_ID) {
2420         return SetGlobalHttpProxyOld(httpProxy, activeUserId);
2421     }
2422     HttpProxy oldHttpProxy;
2423     oldHttpProxy.SetUserId(httpProxy.GetUserId());
2424     GetGlobalHttpProxy(oldHttpProxy);
2425     if (oldHttpProxy != httpProxy) {
2426         HttpProxy newHttpProxy = httpProxy;
2427         int32_t userId = GetValidUserIdFromProxy(httpProxy);
2428         if (userId == INVALID_USER_ID) {
2429             return NETMANAGER_ERR_INTERNAL;
2430         }
2431         NETMGR_LOG_I("GlobalHttpProxy userId is %{public}d", userId);
2432         NetHttpProxyTracker httpProxyTracker;
2433         if (IsPrimaryUserId(userId)) {
2434             if (!httpProxyTracker.WriteToSettingsData(newHttpProxy)) {
2435                 NETMGR_LOG_E("GlobalHttpProxy write settingDate fail.");
2436                 return NETMANAGER_ERR_INTERNAL;
2437             }
2438         }
2439         if (!httpProxyTracker.WriteToSettingsDataUser(newHttpProxy, userId)) {
2440             NETMGR_LOG_E("GlobalHttpProxy write settingDateUser fail. userId=%{public}d", userId);
2441             return NETMANAGER_ERR_INTERNAL;
2442         }
2443         globalHttpProxyCache_.EnsureInsert(userId, newHttpProxy);
2444         SendHttpProxyChangeBroadcast(newHttpProxy);
2445         UpdateGlobalHttpProxy(newHttpProxy);
2446     }
2447     if (!httpProxy.GetHost().empty()) {
2448         httpProxyThreadCv_.notify_all();
2449     }
2450     if (!httpProxyThreadNeedRun_ && !httpProxy.GetUsername().empty()) {
2451         NETMGR_LOG_I("ActiveHttpProxy  user.len[%{public}zu], pwd.len[%{public}zu]", httpProxy.username_.length(),
2452                      httpProxy.password_.length());
2453         CreateActiveHttpProxyThread();
2454     } else if (httpProxyThreadNeedRun_ && httpProxy.GetHost().empty()) {
2455         httpProxyThreadNeedRun_ = false;
2456     }
2457     NETMGR_LOG_I("End SetGlobalHttpProxy.");
2458     return NETMANAGER_SUCCESS;
2459 }
2460 
GetPacUrl(std::string & pacUrl)2461 int32_t NetConnService::GetPacUrl(std::string &pacUrl)
2462 {
2463     auto dataShareHelperUtils = std::make_unique<NetDataShareHelperUtils>();
2464     Uri uri(PAC_URL_URI);
2465     int32_t ret = dataShareHelperUtils->Query(uri, KEY_PAC_URL, pacUrl);
2466     if (ret != NETMANAGER_SUCCESS) {
2467         NETMGR_LOG_E("Query pac url failed.");
2468         return NETMANAGER_ERR_INTERNAL;
2469     }
2470     return NETMANAGER_SUCCESS;
2471 }
2472 
SetPacUrl(const std::string & pacUrl)2473 int32_t NetConnService::SetPacUrl(const std::string &pacUrl)
2474 {
2475     auto dataShareHelperUtils = std::make_unique<NetDataShareHelperUtils>();
2476     Uri uri(PAC_URL_URI);
2477     int32_t ret = dataShareHelperUtils->Update(uri, KEY_PAC_URL, pacUrl);
2478     if (ret != NETMANAGER_SUCCESS) {
2479         NETMGR_LOG_E("Update pacUrl to datashare failed.");
2480         return NETMANAGER_ERR_INTERNAL;
2481     }
2482     return NETMANAGER_SUCCESS;
2483 }
2484 
CreateActiveHttpProxyThread()2485 void NetConnService::CreateActiveHttpProxyThread()
2486 {
2487     httpProxyThreadNeedRun_ = true;
2488     std::thread t([sp = shared_from_this()]() { sp->ActiveHttpProxy(); });
2489     std::string threadName = "ActiveHttpProxy";
2490     pthread_setname_np(t.native_handle(), threadName.c_str());
2491     t.detach();
2492 }
2493 
GetLocalUserId(int32_t & userId)2494 int32_t NetConnService::GetLocalUserId(int32_t &userId)
2495 {
2496     int32_t uid = IPCSkeleton::GetCallingUid();
2497     int ret = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
2498     if (ret != 0) {
2499         NETMGR_LOG_E("GetOsAccountLocalIdFromUid failed. uid is %{public}d, ret is %{public}d", uid, ret);
2500         return NETMANAGER_ERR_INTERNAL;
2501     }
2502     return NETMANAGER_SUCCESS;
2503 }
2504 
GetActiveUserId(int32_t & userId)2505 int32_t NetConnService::GetActiveUserId(int32_t &userId)
2506 {
2507     std::vector<int> activeIds;
2508     int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds);
2509     if (ret != 0) {
2510         NETMGR_LOG_E("QueryActiveOsAccountIds failed. ret is %{public}d", ret);
2511         return NETMANAGER_ERR_INTERNAL;
2512     }
2513     if (activeIds.empty()) {
2514         NETMGR_LOG_E("QueryActiveOsAccountIds is empty");
2515         return NETMANAGER_ERR_INTERNAL;
2516     }
2517     userId = activeIds[0];
2518     return NETMANAGER_SUCCESS;
2519 }
2520 
IsValidUserId(int32_t userId)2521 bool NetConnService::IsValidUserId(int32_t userId)
2522 {
2523     if (userId < 0) {
2524         return false;
2525     }
2526     bool isValid = false;
2527     auto ret = AccountSA::OsAccountManager::IsOsAccountExists(userId, isValid);
2528     if (ret != NETMANAGER_SUCCESS) {
2529         NETMGR_LOG_E("IsOsAccountExists is failed. ret[%{public}d], userId[%{public}d]", ret, userId);
2530         return false;
2531     }
2532     return isValid;
2533 }
2534 
GetValidUserIdFromProxy(const HttpProxy & httpProxy)2535 int32_t NetConnService::GetValidUserIdFromProxy(const HttpProxy &httpProxy)
2536 {
2537     int32_t userId;
2538     if (httpProxy.GetUserId() == ROOT_USER_ID || httpProxy.GetUserId() == INVALID_USER_ID) {
2539         int32_t ret = GetActiveUserId(userId);
2540         if (ret != NETMANAGER_SUCCESS) {
2541             NETMGR_LOG_E("GetValidUserIdFromProxy failed to get active userId.");
2542             return INVALID_USER_ID;
2543         }
2544     } else {
2545         userId = httpProxy.GetUserId();
2546     }
2547     return userId;
2548 }
2549 
SetAppNet(int32_t netId)2550 int32_t NetConnService::SetAppNet(int32_t netId)
2551 {
2552     return NETMANAGER_SUCCESS;
2553 }
2554 
RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)2555 int32_t NetConnService::RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback)
2556 {
2557     if (callback == nullptr) {
2558         NETMGR_LOG_E("callback is nullptr");
2559         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2560     }
2561     NETMGR_LOG_I("Enter RegisterNetInterfaceCallback.");
2562     if (interfaceStateCallback_ == nullptr) {
2563         NETMGR_LOG_E("interfaceStateCallback_ is nullptr");
2564         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2565     }
2566     return interfaceStateCallback_->RegisterInterfaceCallback(callback);
2567 }
2568 
UnregisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)2569 int32_t NetConnService::UnregisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback)
2570 {
2571     if (callback == nullptr) {
2572         NETMGR_LOG_E("callback is nullptr");
2573         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2574     }
2575     NETMGR_LOG_I("Enter UnregisterNetInterfaceCallback.");
2576     if (interfaceStateCallback_ == nullptr) {
2577         NETMGR_LOG_E("interfaceStateCallback_ is nullptr");
2578         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2579     }
2580     return interfaceStateCallback_->UnregisterInterfaceCallback(callback);
2581 }
2582 
GetNetInterfaceConfiguration(const std::string & iface,NetInterfaceConfiguration & config)2583 int32_t NetConnService::GetNetInterfaceConfiguration(const std::string &iface, NetInterfaceConfiguration &config)
2584 {
2585     using namespace OHOS::nmd;
2586     InterfaceConfigurationParcel configParcel;
2587     configParcel.ifName = iface;
2588     if (NetsysController::GetInstance().GetInterfaceConfig(configParcel) != NETMANAGER_SUCCESS) {
2589         return NETMANAGER_ERR_INTERNAL;
2590     }
2591     config.ifName_ = configParcel.ifName;
2592     config.hwAddr_ = configParcel.hwAddr;
2593     config.ipv4Addr_ = configParcel.ipv4Addr;
2594     config.prefixLength_ = configParcel.prefixLength;
2595     config.flags_.assign(configParcel.flags.begin(), configParcel.flags.end());
2596     return NETMANAGER_SUCCESS;
2597 }
2598 
SetNetInterfaceIpAddress(const std::string & iface,const std::string & ipAddress)2599 int32_t NetConnService::SetNetInterfaceIpAddress(const std::string &iface, const std::string &ipAddress)
2600 {
2601     return NetsysController::GetInstance().InterfaceSetIpAddress(iface, ipAddress);
2602 }
2603 
SetInterfaceUp(const std::string & iface)2604 int32_t NetConnService::SetInterfaceUp(const std::string &iface)
2605 {
2606     return NetsysController::GetInstance().SetInterfaceUp(iface);
2607 }
2608 
SetInterfaceDown(const std::string & iface)2609 int32_t NetConnService::SetInterfaceDown(const std::string &iface)
2610 {
2611     return NetsysController::GetInstance().SetInterfaceDown(iface);
2612 }
2613 
NetDetectionForDnsHealth(int32_t netId,bool dnsHealthSuccess)2614 int32_t NetConnService::NetDetectionForDnsHealth(int32_t netId, bool dnsHealthSuccess)
2615 {
2616     int32_t result = NETMANAGER_ERROR;
2617     if (netConnEventHandler_) {
2618         netConnEventHandler_->PostSyncTask([netId, dnsHealthSuccess, &result, this]() {
2619             result = this->NetDetectionForDnsHealthSync(netId, dnsHealthSuccess);
2620         });
2621     }
2622     return result;
2623 }
2624 
2625 // Query the global http proxy of a specified user type.
2626 // The user type can be ACTIVE or LOCAL.
2627 // The ACTIVE is the user in active state on the foreground.
2628 // The LOCAL is the user to which the application process belongs.
LoadGlobalHttpProxy(UserIdType userIdType,HttpProxy & httpProxy)2629 void NetConnService::LoadGlobalHttpProxy(UserIdType userIdType, HttpProxy &httpProxy)
2630 {
2631     int32_t userId = -1;
2632     int32_t ret = NETMANAGER_SUCCESS;
2633     if (userIdType == ACTIVE) {
2634         ret = GetActiveUserId(userId);
2635     } else if (userIdType == LOCAL) {
2636         ret = GetLocalUserId(userId);
2637         if (userId == ROOT_USER_ID) {
2638             ret = GetActiveUserId(userId);
2639         }
2640     } else if (userIdType == SPECIFY) {
2641         userId = httpProxy.GetUserId();
2642     } else {
2643         NETMGR_LOG_E("LoadGlobalHttpProxy invalid userIdType.");
2644         return;
2645     }
2646     if (ret != NETMANAGER_SUCCESS) {
2647         NETMGR_LOG_E("LoadGlobalHttpProxy get userId fail.");
2648         return;
2649     }
2650     if (!IsValidUserId(userId)) {
2651         NETMGR_LOG_E("LoadGlobalHttpProxy userId is not exist. userId[%{public}d]", httpProxy.GetUserId());
2652         return;
2653     }
2654     NETMGR_LOG_I("LoadGlobalHttpProxy userId = %{public}d", userId);
2655     if (globalHttpProxyCache_.Find(userId, httpProxy)) {
2656         NETMGR_LOG_D("Global http proxy has been loaded from the SettingsData database. userId=%{public}d", userId);
2657         return;
2658     }
2659     if (!isDataShareReady_.load() && !CheckIfSettingsDataReady()) {
2660         NETMGR_LOG_E("data share is not ready.");
2661         return;
2662     }
2663     NetHttpProxyTracker httpProxyTracker;
2664     HttpProxy tmpHttpProxy;
2665     if (IsPrimaryUserId(userId)) {
2666         httpProxyTracker.ReadFromSettingsData(tmpHttpProxy);
2667     } else {
2668         httpProxyTracker.ReadFromSettingsDataUser(tmpHttpProxy, userId);
2669     }
2670     tmpHttpProxy.SetUserId(userId);
2671 
2672     httpProxy = tmpHttpProxy;
2673     globalHttpProxyCache_.EnsureInsert(userId, tmpHttpProxy);
2674 }
2675 
UpdateGlobalHttpProxy(const HttpProxy & httpProxy)2676 void NetConnService::UpdateGlobalHttpProxy(const HttpProxy &httpProxy)
2677 {
2678     if (netConnEventHandler_ == nullptr) {
2679         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
2680         return;
2681     }
2682     NETMGR_LOG_I("UpdateGlobalHttpProxy start");
2683     netConnEventHandler_->PostAsyncTask([this, httpProxy]() {
2684         for (const auto &supplier : netSuppliers_) {
2685             if (supplier.second == nullptr) {
2686                 continue;
2687             }
2688             supplier.second->UpdateGlobalHttpProxy(httpProxy);
2689         }
2690         NETMGR_LOG_I("UpdateGlobalHttpProxy end");
2691     });
2692 }
2693 
OnInterfaceAddressUpdated(const std::string & addr,const std::string & ifName,int flags,int scope)2694 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAddressUpdated(const std::string &addr,
2695                                                                              const std::string &ifName, int flags,
2696                                                                              int scope)
2697 {
2698     std::lock_guard<std::mutex> locker(mutex_);
2699     for (const auto &callback : ifaceStateCallbacks_) {
2700         if (callback == nullptr) {
2701             NETMGR_LOG_E("callback is null");
2702             continue;
2703         }
2704         callback->OnInterfaceAddressUpdated(addr, ifName, flags, scope);
2705     }
2706     return NETMANAGER_SUCCESS;
2707 }
2708 
OnInterfaceAddressRemoved(const std::string & addr,const std::string & ifName,int flags,int scope)2709 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAddressRemoved(const std::string &addr,
2710                                                                              const std::string &ifName, int flags,
2711                                                                              int scope)
2712 {
2713     std::lock_guard<std::mutex> locker(mutex_);
2714     for (const auto &callback : ifaceStateCallbacks_) {
2715         if (callback == nullptr) {
2716             NETMGR_LOG_E("callback is null");
2717             continue;
2718         }
2719         callback->OnInterfaceAddressRemoved(addr, ifName, flags, scope);
2720     }
2721     return NETMANAGER_SUCCESS;
2722 }
2723 
OnInterfaceAdded(const std::string & iface)2724 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAdded(const std::string &iface)
2725 {
2726     std::lock_guard<std::mutex> locker(mutex_);
2727     for (const auto &callback : ifaceStateCallbacks_) {
2728         if (callback == nullptr) {
2729             NETMGR_LOG_E("callback is null");
2730             continue;
2731         }
2732         callback->OnInterfaceAdded(iface);
2733     }
2734     return NETMANAGER_SUCCESS;
2735 }
2736 
OnInterfaceRemoved(const std::string & iface)2737 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceRemoved(const std::string &iface)
2738 {
2739     std::lock_guard<std::mutex> locker(mutex_);
2740     for (const auto &callback : ifaceStateCallbacks_) {
2741         if (callback == nullptr) {
2742             NETMGR_LOG_E("callback is null");
2743             continue;
2744         }
2745         callback->OnInterfaceRemoved(iface);
2746     }
2747     return NETMANAGER_SUCCESS;
2748 }
2749 
OnInterfaceChanged(const std::string & iface,bool up)2750 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceChanged(const std::string &iface, bool up)
2751 {
2752     std::lock_guard<std::mutex> locker(mutex_);
2753     for (const auto &callback : ifaceStateCallbacks_) {
2754         if (callback == nullptr) {
2755             NETMGR_LOG_E("callback is null");
2756             continue;
2757         }
2758         callback->OnInterfaceChanged(iface, up);
2759     }
2760     return NETMANAGER_SUCCESS;
2761 }
2762 
OnInterfaceLinkStateChanged(const std::string & iface,bool up)2763 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceLinkStateChanged(const std::string &iface, bool up)
2764 {
2765     std::lock_guard<std::mutex> locker(mutex_);
2766     for (const auto &callback : ifaceStateCallbacks_) {
2767         if (callback == nullptr) {
2768             NETMGR_LOG_E("callback is null");
2769             continue;
2770         }
2771         callback->OnInterfaceLinkStateChanged(iface, up);
2772     }
2773     return NETMANAGER_SUCCESS;
2774 }
2775 
OnRouteChanged(bool updated,const std::string & route,const std::string & gateway,const std::string & ifName)2776 int32_t NetConnService::NetInterfaceStateCallback::OnRouteChanged(bool updated, const std::string &route,
2777                                                                   const std::string &gateway, const std::string &ifName)
2778 {
2779     std::lock_guard<std::mutex> locker(mutex_);
2780     for (const auto &callback : ifaceStateCallbacks_) {
2781         if (callback == nullptr) {
2782             NETMGR_LOG_E("callback is null");
2783             continue;
2784         }
2785         callback->OnRouteChanged(updated, route, gateway, ifName);
2786     }
2787     return NETMANAGER_SUCCESS;
2788 }
2789 
OnDhcpSuccess(NetsysControllerCallback::DhcpResult & dhcpResult)2790 int32_t NetConnService::NetInterfaceStateCallback::OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult)
2791 {
2792     return NETMANAGER_SUCCESS;
2793 }
2794 
OnBandwidthReachedLimit(const std::string & limitName,const std::string & iface)2795 int32_t NetConnService::NetInterfaceStateCallback::OnBandwidthReachedLimit(const std::string &limitName,
2796                                                                            const std::string &iface)
2797 {
2798     return NETMANAGER_SUCCESS;
2799 }
2800 
RegisterInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)2801 int32_t NetConnService::NetInterfaceStateCallback::RegisterInterfaceCallback(
2802     const sptr<INetInterfaceStateCallback> &callback)
2803 {
2804     if (callback == nullptr) {
2805         NETMGR_LOG_E("callback is null");
2806         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2807     }
2808 
2809     std::lock_guard<std::mutex> locker(mutex_);
2810     for (const auto &iter : ifaceStateCallbacks_) {
2811         if (!iter) {
2812             continue;
2813         }
2814         if (iter->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
2815             NETMGR_LOG_E("RegisterInterfaceCallback find same callback");
2816             return NET_CONN_ERR_SAME_CALLBACK;
2817         }
2818     }
2819     ifaceStateCallbacks_.push_back(callback);
2820     NETMGR_LOG_I("Register interface callback successful");
2821 
2822     AddIfaceDeathRecipient(callback);
2823     return NETMANAGER_SUCCESS;
2824 }
2825 
UnregisterInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)2826 int32_t NetConnService::NetInterfaceStateCallback::UnregisterInterfaceCallback(
2827     const sptr<INetInterfaceStateCallback> &callback)
2828 {
2829     NETMGR_LOG_I("UnregisterInterfaceCallback, callingPid=%{public}d, callingUid=%{public}d",
2830                  IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid());
2831 
2832     std::lock_guard<std::mutex> locker(mutex_);
2833     auto isSameCallback = [&callback](const sptr<INetInterfaceStateCallback> &item) {
2834         return item->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr();
2835     };
2836     auto iter = std::find_if(ifaceStateCallbacks_.cbegin(), ifaceStateCallbacks_.cend(), isSameCallback);
2837     if (iter == ifaceStateCallbacks_.cend()) {
2838         NETMGR_LOG_E("UnregisterInterfaceCallback callback not found.");
2839         return NET_CONN_ERR_CALLBACK_NOT_FOUND;
2840     }
2841 
2842     callback->AsObject()->RemoveDeathRecipient(netIfaceStateDeathRecipient_);
2843     ifaceStateCallbacks_.erase(iter);
2844     return NETMANAGER_SUCCESS;
2845 }
2846 
OnNetIfaceStateRemoteDied(const wptr<IRemoteObject> & remoteObject)2847 void NetConnService::NetInterfaceStateCallback::OnNetIfaceStateRemoteDied(const wptr<IRemoteObject> &remoteObject)
2848 {
2849     sptr<IRemoteObject> diedRemoted = remoteObject.promote();
2850     if (diedRemoted == nullptr) {
2851         NETMGR_LOG_E("diedRemoted is null");
2852         return;
2853     }
2854     sptr<INetInterfaceStateCallback> callback = iface_cast<INetInterfaceStateCallback>(diedRemoted);
2855 
2856     int32_t ret = UnregisterInterfaceCallback(callback);
2857     if (ret != NETMANAGER_SUCCESS) {
2858         NETMGR_LOG_E("UnregisterInterfaceCallback failed with code %{public}d", ret);
2859     }
2860 }
2861 
AddIfaceDeathRecipient(const sptr<INetInterfaceStateCallback> & callback)2862 void NetConnService::NetInterfaceStateCallback::AddIfaceDeathRecipient(const sptr<INetInterfaceStateCallback> &callback)
2863 {
2864     if (netIfaceStateDeathRecipient_ == nullptr) {
2865         netIfaceStateDeathRecipient_ = new (std::nothrow) NetIfaceStateCallbackDeathRecipient(*this);
2866     }
2867     if (netIfaceStateDeathRecipient_ == nullptr) {
2868         NETMGR_LOG_E("netIfaceStateDeathRecipient_ is null");
2869         return;
2870     }
2871     if (!callback->AsObject()->AddDeathRecipient(netIfaceStateDeathRecipient_)) {
2872         NETMGR_LOG_E("AddNetIfaceStateCallbackDeathRecipient failed");
2873         return;
2874     }
2875 }
2876 
NetUidPolicyChange(uint32_t uid,uint32_t policy)2877 int32_t NetConnService::NetPolicyCallback::NetUidPolicyChange(uint32_t uid, uint32_t policy)
2878 {
2879     NETMGR_LOG_D("NetUidPolicyChange Uid=%{public}d, policy=%{public}d", uid, policy);
2880     auto netConnService = netConnService_.lock();
2881     if (netConnService == nullptr) {
2882         NETMGR_LOG_E("netConnService_ has destory");
2883         return NETMANAGER_ERROR;
2884     }
2885     if (netConnService->defaultNetSupplier_ == nullptr) {
2886         NETMGR_LOG_E("defaultNetSupplier_ is nullptr");
2887         return NETMANAGER_ERROR;
2888     }
2889     if (netConnService->netConnEventHandler_) {
2890         netConnService->netConnEventHandler_->PostSyncTask([this, uid, policy]() { SendNetPolicyChange(uid, policy); });
2891         return NETMANAGER_SUCCESS;
2892     }
2893     return NETMANAGER_ERROR;
2894 }
2895 
SendNetPolicyChange(uint32_t uid,uint32_t policy)2896 void NetConnService::NetPolicyCallback::SendNetPolicyChange(uint32_t uid, uint32_t policy)
2897 {
2898     auto netConnService = netConnService_.lock();
2899     if (netConnService == nullptr) {
2900         NETMGR_LOG_E("netConnService_ has destory");
2901         return;
2902     }
2903     sptr<NetHandle> defaultNetHandle = nullptr;
2904     bool metered = false;
2905     bool newBlocked = false;
2906     {
2907         std::lock_guard<std::recursive_mutex> locker(netConnService->netManagerMutex_);
2908         if (netConnService->defaultNetSupplier_ == nullptr) {
2909             NETMGR_LOG_E("SendNetPolicyChange defaultNetSupplier_ is nullptr");
2910             return;
2911         }
2912         defaultNetHandle = netConnService->defaultNetSupplier_->GetNetHandle();
2913         metered = netConnService->defaultNetSupplier_->HasNetCap(NET_CAPABILITY_NOT_METERED);
2914     }
2915     newBlocked = NetManagerCenter::GetInstance().IsUidNetAccess(uid, metered);
2916     std::vector<std::shared_ptr<NetActivate>> activates;
2917     {
2918         std::lock_guard guard(netConnService->uidActivateMutex_);
2919         auto it = netConnService->netUidActivates_.find(uid);
2920         if (it != netConnService->netUidActivates_.end()) {
2921             activates = it->second;
2922         }
2923     }
2924     for (auto &activate : activates) {
2925         if (activate->GetNetCallback() && activate->MatchRequestAndNetwork(netConnService->defaultNetSupplier_)) {
2926             NETMGR_LOG_D("NetUidPolicyChange Uid=%{public}d, policy=%{public}d", uid, policy);
2927             activate->GetNetCallback()->NetBlockStatusChange(defaultNetHandle, newBlocked);
2928         }
2929     }
2930 }
2931 
AddNetworkRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)2932 int32_t NetConnService::AddNetworkRoute(int32_t netId, const std::string &ifName,
2933                                         const std::string &destination, const std::string &nextHop)
2934 {
2935     return NetsysController::GetInstance().NetworkAddRoute(netId, ifName, destination, nextHop);
2936 }
2937 
RemoveNetworkRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)2938 int32_t NetConnService::RemoveNetworkRoute(int32_t netId, const std::string &ifName,
2939                                            const std::string &destination, const std::string &nextHop)
2940 {
2941     return NetsysController::GetInstance().NetworkRemoveRoute(netId, ifName, destination, nextHop);
2942 }
2943 
AddInterfaceAddress(const std::string & ifName,const std::string & ipAddr,int32_t prefixLength)2944 int32_t NetConnService::AddInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
2945                                             int32_t prefixLength)
2946 {
2947     return NetsysController::GetInstance().AddInterfaceAddress(ifName, ipAddr, prefixLength);
2948 }
2949 
DelInterfaceAddress(const std::string & ifName,const std::string & ipAddr,int32_t prefixLength)2950 int32_t NetConnService::DelInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
2951                                             int32_t prefixLength)
2952 {
2953     return NetsysController::GetInstance().DelInterfaceAddress(ifName, ipAddr, prefixLength);
2954 }
2955 
AddStaticArp(const std::string & ipAddr,const std::string & macAddr,const std::string & ifName)2956 int32_t NetConnService::AddStaticArp(const std::string &ipAddr, const std::string &macAddr,
2957                                      const std::string &ifName)
2958 {
2959     return NetsysController::GetInstance().AddStaticArp(ipAddr, macAddr, ifName);
2960 }
2961 
DelStaticArp(const std::string & ipAddr,const std::string & macAddr,const std::string & ifName)2962 int32_t NetConnService::DelStaticArp(const std::string &ipAddr, const std::string &macAddr,
2963                                      const std::string &ifName)
2964 {
2965     return NetsysController::GetInstance().DelStaticArp(ipAddr, macAddr, ifName);
2966 }
2967 
RegisterSlotType(uint32_t supplierId,int32_t type)2968 int32_t NetConnService::RegisterSlotType(uint32_t supplierId, int32_t type)
2969 {
2970     int32_t result = NETMANAGER_SUCCESS;
2971     if (netConnEventHandler_) {
2972         netConnEventHandler_->PostSyncTask([this, supplierId, type, &result]() {
2973             if (netSuppliers_.find(supplierId) == netSuppliers_.end()) {
2974                 NETMGR_LOG_E("supplierId[%{public}d] is not exits", supplierId);
2975                 result =  NETMANAGER_ERR_INVALID_PARAMETER;
2976             } else {
2977                 NETMGR_LOG_I("supplierId[%{public}d] update type[%{public}d].", supplierId, type);
2978                 sptr<NetSupplier> supplier = netSuppliers_[supplierId];
2979                 supplier->SetSupplierType(type);
2980                 result =  NETMANAGER_SUCCESS;
2981             }
2982         });
2983     }
2984     return result;
2985 }
2986 
GetSlotType(std::string & type)2987 int32_t NetConnService::GetSlotType(std::string &type)
2988 {
2989     int32_t result = NETMANAGER_SUCCESS;
2990     if (netConnEventHandler_) {
2991         netConnEventHandler_->PostSyncTask([this, &type, &result]() {
2992             if (defaultNetSupplier_ == nullptr) {
2993                 NETMGR_LOG_E("supplier is nullptr");
2994                 result =  NETMANAGER_ERR_LOCAL_PTR_NULL;
2995             } else {
2996                 type = defaultNetSupplier_->GetSupplierType();
2997                 result =  NETMANAGER_SUCCESS;
2998             }
2999         });
3000     }
3001     return result;
3002 }
3003 
FactoryResetNetwork()3004 int32_t NetConnService::FactoryResetNetwork()
3005 {
3006     NETMGR_LOG_I("Enter FactoryResetNetwork.");
3007 
3008     SetAirplaneMode(false);
3009 
3010     if (netFactoryResetCallback_ == nullptr) {
3011         NETMGR_LOG_E("netFactoryResetCallback_ is nullptr");
3012         return NETMANAGER_ERR_LOCAL_PTR_NULL;
3013     }
3014     netFactoryResetCallback_->NotifyNetFactoryResetAsync();
3015 
3016     NETMGR_LOG_I("End FactoryResetNetwork.");
3017     return NETMANAGER_SUCCESS;
3018 }
3019 
RegisterNetFactoryResetCallback(const sptr<INetFactoryResetCallback> & callback)3020 int32_t NetConnService::RegisterNetFactoryResetCallback(const sptr<INetFactoryResetCallback> &callback)
3021 {
3022     if (callback == nullptr) {
3023         NETMGR_LOG_E("callback is nullptr");
3024         return NETMANAGER_ERR_LOCAL_PTR_NULL;
3025     }
3026     NETMGR_LOG_I("Enter RegisterNetFactoryResetCallback.");
3027     if (netFactoryResetCallback_ == nullptr) {
3028         NETMGR_LOG_E("netFactoryResetCallback_ is nullptr");
3029         return NETMANAGER_ERR_LOCAL_PTR_NULL;
3030     }
3031     return netFactoryResetCallback_->RegisterNetFactoryResetCallbackAsync(callback);
3032 }
3033 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)3034 void NetConnService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
3035 {
3036     NETMGR_LOG_I("OnAddSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
3037     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
3038         if (hasSARemoved_) {
3039             OnNetSysRestart();
3040             hasSARemoved_ = false;
3041         }
3042         if (!system::GetBoolParameter(BOOTEVENT_NETSYSNATIVE_SERVICE_READY, false)) {
3043             system::SetParameter(BOOTEVENT_NETSYSNATIVE_SERVICE_READY, "true");
3044             NETMGR_LOG_I("set netsysnative service start true");
3045         }
3046     } else if (systemAbilityId == ACCESS_TOKEN_MANAGER_SERVICE_ID) {
3047         if (!registerToService_) {
3048             if (!Publish(NetConnService::GetInstance().get())) {
3049                 NETMGR_LOG_E("Register to sa manager failed");
3050             }
3051             registerToService_ = true;
3052         }
3053     } else if (systemAbilityId == COMM_NET_POLICY_MANAGER_SYS_ABILITY_ID) {
3054         policyCallback_ = sptr<NetPolicyCallback>::MakeSptr(shared_from_this());
3055         int32_t registerRet = NetPolicyClient::GetInstance().RegisterNetPolicyCallback(policyCallback_);
3056         if (registerRet != NETMANAGER_SUCCESS) {
3057             NETMGR_LOG_E("Register NetPolicyCallback failed, ret =%{public}d", registerRet);
3058         }
3059     } else if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
3060         SubscribeCommonEvent("usual.event.DATA_SHARE_READY",
3061             [this](auto && PH1) { OnReceiveEvent(std::forward<decltype(PH1)>(PH1)); });
3062 #ifdef FEATURE_SUPPORT_POWERMANAGER
3063         SubscribeCommonEvent("usual.event.POWER_MANAGER_STATE_CHANGED",
3064             [this](auto && PH1) { OnReceiveEvent(std::forward<decltype(PH1)>(PH1)); });
3065 #endif
3066         SubscribeCommonEvent("usual.event.SCREEN_ON",
3067             [this](auto && PH1) { OnReceiveEvent(std::forward<decltype(PH1)>(PH1)); });
3068         SubscribeCommonEvent("usual.event.SCREEN_OFF",
3069             [this](auto && PH1) { OnReceiveEvent(std::forward<decltype(PH1)>(PH1)); });
3070     }
3071 }
3072 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)3073 void NetConnService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
3074 {
3075     NETMGR_LOG_I("OnRemoveSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
3076     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
3077         hasSARemoved_ = true;
3078     }
3079 }
3080 
SubscribeCommonEvent(const std::string & eventName,EventReceiver receiver)3081 void NetConnService::SubscribeCommonEvent(const std::string &eventName, EventReceiver receiver)
3082 {
3083     NETMGR_LOG_I("eventName=%{public}s", eventName.c_str());
3084     EventFwk::MatchingSkills matchingSkills;
3085     matchingSkills.AddEvent(eventName);
3086     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
3087 
3088     auto subscriberPtr = std::make_shared<NetConnListener>(subscribeInfo, receiver);
3089     if (subscriberPtr == nullptr) {
3090         NETMGR_LOG_E("subscriberPtr is nullptr");
3091         return;
3092     }
3093     EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberPtr);
3094 }
3095 
OnReceiveEvent(const EventFwk::CommonEventData & data)3096 void NetConnService::OnReceiveEvent(const EventFwk::CommonEventData &data)
3097 {
3098     auto const &want = data.GetWant();
3099     std::string action = want.GetAction();
3100     if (action == "usual.event.DATA_SHARE_READY") {
3101         NETMGR_LOG_I("on receive data_share ready.");
3102         isDataShareReady_ = true;
3103         HttpProxy httpProxy;
3104         // executed in the SA process, so load http proxy from current active user.
3105         LoadGlobalHttpProxy(ACTIVE, httpProxy);
3106         UpdateGlobalHttpProxy(httpProxy);
3107     }
3108 #ifdef FEATURE_SUPPORT_POWERMANAGER
3109     if (action == "usual.event.POWER_MANAGER_STATE_CHANGED") {
3110         int code = data.GetCode();
3111         HandlePowerMgrEvent(code);
3112     }
3113 #endif
3114     if (action == "usual.event.SCREEN_ON") {
3115         HandleScreenEvent(true);
3116     } else if (action == "usual.event.SCREEN_OFF") {
3117         HandleScreenEvent(false);
3118     }
3119 }
3120 
IsSupplierMatchRequestAndNetwork(sptr<NetSupplier> ns)3121 bool NetConnService::IsSupplierMatchRequestAndNetwork(sptr<NetSupplier> ns)
3122 {
3123     if (ns == nullptr) {
3124         NETMGR_LOG_E("supplier is nullptr");
3125         return false;
3126     }
3127     NET_ACTIVATE_MAP::iterator iterActive;
3128     std::shared_lock<std::shared_mutex> lock(netActivatesMutex_);
3129     for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
3130         if (!iterActive->second) {
3131             continue;
3132         }
3133         if (iterActive->second->MatchRequestAndNetwork(ns)) {
3134             return true;
3135         }
3136     }
3137 
3138     return false;
3139 }
3140 
RecoverNetSys()3141 void NetConnService::RecoverNetSys()
3142 {
3143     NETMGR_LOG_I("RecoverNetSys");
3144 
3145     NET_SUPPLIER_MAP::iterator iter;
3146     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
3147         if (iter->second == nullptr) {
3148             continue;
3149         }
3150         NETMGR_LOG_D("supplier info, supplier[%{public}d, %{public}s], realScore[%{public}d], isConnected[%{public}d]",
3151             iter->second->GetSupplierId(), iter->second->GetNetSupplierIdent().c_str(),
3152             iter->second->GetRealScore(), iter->second->IsConnected());
3153 
3154         if ((!iter->second->IsConnected()) || (!IsSupplierMatchRequestAndNetwork(iter->second))) {
3155             NETMGR_LOG_D("Supplier[%{public}d] is not connected or not match request.", iter->second->GetSupplierId());
3156             continue;
3157         }
3158         iter->second->ResumeNetworkInfo();
3159     }
3160     if (defaultNetSupplier_ != nullptr) {
3161         defaultNetSupplier_->ClearDefault();
3162         defaultNetSupplier_ = nullptr;
3163     }
3164     FindBestNetworkForAllRequest();
3165 }
3166 
OnNetSysRestart()3167 void NetConnService::OnNetSysRestart()
3168 {
3169     if (netConnEventHandler_) {
3170         netConnEventHandler_->PostSyncTask([this]() {
3171             NETMGR_LOG_I("OnNetSysRestart");
3172             this->RecoverNetSys();
3173         });
3174     }
3175 }
3176 
IsPreferCellularUrl(const std::string & url,bool & preferCellular)3177 int32_t NetConnService::IsPreferCellularUrl(const std::string& url, bool& preferCellular)
3178 {
3179     std::string hostName = CommonUtils::GetHostnameFromURL(url);
3180     static std::vector<std::string> preferredRegexList = GetPreferredRegex();
3181     preferCellular = std::any_of(preferredRegexList.begin(), preferredRegexList.end(),
3182         [&hostName](const std::string &str) -> bool {
3183             try {
3184                 return std::regex_match(hostName, std::regex(str));
3185             } catch (const std::regex_error& e) {
3186                 NETMGR_LOG_E("regex_match exception!");
3187                 return false;
3188             }
3189         });
3190     NETMGR_LOG_I("preferCellular:%{public}d", preferCellular);
3191     return 0;
3192 }
3193 
IsIfaceNameInUse(const std::string & ifaceName,int32_t netId)3194 bool NetConnService::IsIfaceNameInUse(const std::string &ifaceName, int32_t netId)
3195 {
3196     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
3197     for (const auto &netSupplier : netSuppliers_) {
3198         if (netSupplier.second->GetNetwork()->GetNetId() == netId) {
3199             continue;
3200         }
3201         if (!netSupplier.second->IsAvailable()) {
3202             continue;
3203         }
3204         if (netSupplier.second->GetNetwork()->GetIfaceName() == ifaceName) {
3205             return true;
3206         }
3207     }
3208     return false;
3209 }
3210 
GetNetCapabilitiesAsString(const uint32_t supplierId)3211 std::string NetConnService::GetNetCapabilitiesAsString(const uint32_t supplierId)
3212 {
3213     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
3214     const auto iterNetSuppliers = netSuppliers_.find(supplierId);
3215     if (iterNetSuppliers != netSuppliers_.end() && iterNetSuppliers->second != nullptr) {
3216         return iterNetSuppliers->second->GetNetCapabilities().ToString(" ");
3217     }
3218     return {};
3219 }
3220 
GetPreferredRegex()3221 std::vector<std::string> NetConnService::GetPreferredRegex()
3222 {
3223     std::vector<std::string> preferCellularRegexList;
3224     const std::string preferCellularRegexPath = "/system/etc/prefer_cellular_regex_list.txt";
3225     std::ifstream preferCellularFile(preferCellularRegexPath);
3226     if (preferCellularFile.is_open()) {
3227         std::string line;
3228         while (getline(preferCellularFile, line)) {
3229             line.erase(std::remove(line.begin(), line.end(), '\r'), line.end());
3230             line.erase(std::remove(line.begin(), line.end(), '\t'), line.end());
3231             preferCellularRegexList.push_back(line);
3232         }
3233         preferCellularFile.close();
3234     } else {
3235         NETMGR_LOG_E("open prefer cellular url file failure.");
3236     }
3237     return preferCellularRegexList;
3238 }
3239 
OnRemoteDied(const wptr<IRemoteObject> & remoteObject)3240 void NetConnService::OnRemoteDied(const wptr<IRemoteObject> &remoteObject)
3241 {
3242     sptr<IRemoteObject> diedRemoted = remoteObject.promote();
3243     if (diedRemoted == nullptr) {
3244         NETMGR_LOG_E("diedRemoted is null");
3245         return;
3246     }
3247     uint32_t callingUid = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
3248     NETMGR_LOG_I("OnRemoteDied, callingUid=%{public}u", callingUid);
3249     sptr<INetConnCallback> callback = iface_cast<INetConnCallback>(diedRemoted);
3250     UnregisterNetConnCallback(callback);
3251 }
3252 
RemoveClientDeathRecipient(const sptr<INetConnCallback> & callback)3253 void NetConnService::RemoveClientDeathRecipient(const sptr<INetConnCallback> &callback)
3254 {
3255     std::lock_guard<std::mutex> autoLock(remoteMutex_);
3256     auto iter =
3257         std::find_if(remoteCallback_.cbegin(), remoteCallback_.cend(), [&callback](const sptr<INetConnCallback> &item) {
3258             return item->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr();
3259         });
3260     if (iter == remoteCallback_.cend()) {
3261         return;
3262     }
3263     callback->AsObject()->RemoveDeathRecipient(deathRecipient_);
3264     remoteCallback_.erase(iter);
3265 }
3266 
AddClientDeathRecipient(const sptr<INetConnCallback> & callback)3267 void NetConnService::AddClientDeathRecipient(const sptr<INetConnCallback> &callback)
3268 {
3269     std::lock_guard<std::mutex> autoLock(remoteMutex_);
3270     if (deathRecipient_ == nullptr) {
3271         deathRecipient_ = new (std::nothrow) ConnCallbackDeathRecipient(*this);
3272     }
3273     if (deathRecipient_ == nullptr) {
3274         NETMGR_LOG_E("deathRecipient is null");
3275         return;
3276     }
3277     if (!callback->AsObject()->AddDeathRecipient(deathRecipient_)) {
3278         NETMGR_LOG_E("AddClientDeathRecipient failed");
3279         return;
3280     }
3281     auto iter =
3282         std::find_if(remoteCallback_.cbegin(), remoteCallback_.cend(), [&callback](const sptr<INetConnCallback> &item) {
3283             return item->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr();
3284         });
3285     if (iter == remoteCallback_.cend()) {
3286         remoteCallback_.emplace_back(callback);
3287     }
3288 }
3289 
RemoveALLClientDeathRecipient()3290 void NetConnService::RemoveALLClientDeathRecipient()
3291 {
3292     std::lock_guard<std::mutex> autoLock(remoteMutex_);
3293     for (auto &item : remoteCallback_) {
3294         item->AsObject()->RemoveDeathRecipient(deathRecipient_);
3295     }
3296     remoteCallback_.clear();
3297     appStateAwareCallback_.OnForegroundAppChanged = nullptr;
3298     deathRecipient_ = nullptr;
3299 }
3300 
FindSupplierWithInternetByBearerType(NetBearType bearerType,const std::string & ident)3301 std::vector<sptr<NetSupplier>> NetConnService::FindSupplierWithInternetByBearerType(
3302     NetBearType bearerType, const std::string &ident)
3303 {
3304     std::vector<sptr<NetSupplier>> result;
3305     NET_SUPPLIER_MAP::iterator iterSupplier;
3306     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
3307     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
3308         if (iterSupplier->second == nullptr) {
3309             continue;
3310         }
3311         if (!iterSupplier->second->GetNetCaps().HasNetCap(NET_CAPABILITY_INTERNET)) {
3312             continue;
3313         }
3314         if (iterSupplier->second->GetNetSupplierIdent() != ident) {
3315             continue;
3316         }
3317         std::set<NetBearType>::iterator iter = iterSupplier->second->GetNetCapabilities().bearerTypes_.find(bearerType);
3318         if (iter != iterSupplier->second->GetNetCapabilities().bearerTypes_.end()) {
3319             NETMGR_LOG_I("found supplierId[%{public}d] by bearertype[%{public}d].", iterSupplier->first, bearerType);
3320             result.push_back(iterSupplier->second);
3321         }
3322     }
3323     return result;
3324 }
3325 
DecreaseSupplierScore(NetBearType bearerType,const std::string & ident,uint32_t & supplierId)3326 int32_t NetConnService::DecreaseSupplierScore(NetBearType bearerType, const std::string &ident, uint32_t& supplierId)
3327 {
3328     int32_t result = NETMANAGER_ERROR;
3329     if (netConnEventHandler_) {
3330         netConnEventHandler_->PostSyncTask([this, bearerType, ident, &supplierId, &result]() {
3331             result = this->DecreaseSupplierScoreAsync(bearerType, ident, supplierId);
3332         });
3333     }
3334     return result;
3335 }
3336 
IncreaseSupplierScore(uint32_t supplierId)3337 int32_t NetConnService::IncreaseSupplierScore(uint32_t supplierId)
3338 {
3339     int32_t result = NETMANAGER_ERROR;
3340     if (netConnEventHandler_) {
3341         netConnEventHandler_->PostSyncTask([this, supplierId, &result]() {
3342             result = this->IncreaseSupplierScoreAsync(supplierId);
3343         });
3344     }
3345     return result;
3346 }
3347 
DecreaseSupplierScoreAsync(NetBearType bearerType,const std::string & ident,uint32_t & supplierId)3348 int32_t NetConnService::DecreaseSupplierScoreAsync(
3349     NetBearType bearerType, const std::string &ident, uint32_t& supplierId)
3350 {
3351     NETMGR_LOG_I("decrease supplier score by type[%{public}d], ident[%{public}s]", bearerType, ident.c_str());
3352     std::vector<sptr<NetSupplier>> suppliers = FindSupplierWithInternetByBearerType(bearerType, ident);
3353     if (suppliers.empty()) {
3354         NETMGR_LOG_E("not found supplierId by bearertype[%{public}d].", bearerType);
3355         return NETMANAGER_ERR_INVALID_PARAMETER;
3356     }
3357     uint32_t tmpSupplierId = FindSupplierToReduceScore(suppliers, supplierId);
3358     if (tmpSupplierId == INVALID_SUPPLIER_ID) {
3359         if (bearerType == BEARER_WIFI) {
3360             tmpSupplierId = FindSupplierForConnected(suppliers);
3361             supplierId = tmpSupplierId;
3362             NETMGR_LOG_I("FindSupplierForInterface supplierId by supplierId[%{public}d].", supplierId);
3363         }
3364         if (tmpSupplierId == INVALID_SUPPLIER_ID) {
3365             NETMGR_LOG_E("not found supplierId");
3366             return NETMANAGER_ERR_INVALID_PARAMETER;
3367         }
3368     }
3369     // Check supplier exist by supplierId, and check supplier's type equals to bearerType.
3370     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
3371     auto supplier = FindNetSupplier(supplierId);
3372     if (supplier == nullptr || supplier->GetNetSupplierType() != bearerType) {
3373         locker.unlock();
3374         NETMGR_LOG_E("supplier doesn't exist.");
3375         return NETMANAGER_ERR_INVALID_PARAMETER;
3376     }
3377     supplier->SetNetValid(QUALITY_POOR_STATE);
3378     locker.unlock();
3379     // Find best network because supplier score changed.
3380     FindBestNetworkForAllRequest();
3381     // Tell other suppliers to enable if current default supplier is not better than others.
3382     if (defaultNetSupplier_ && defaultNetSupplier_->GetSupplierId() == supplierId) {
3383         RequestAllNetworkExceptDefault();
3384     }
3385     return NETMANAGER_SUCCESS;
3386 }
3387 
IncreaseSupplierScoreAsync(uint32_t supplierId)3388 int32_t NetConnService::IncreaseSupplierScoreAsync(uint32_t supplierId)
3389 {
3390     NETMGR_LOG_I("Increase supplier score by supplierId[%{public}d]", supplierId);
3391     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
3392     auto supplier = FindNetSupplier(supplierId);
3393     if (supplier == nullptr) {
3394         locker.unlock();
3395         NETMGR_LOG_E("supplier doesn't exist.");
3396         return NETMANAGER_ERR_INVALID_PARAMETER;
3397     }
3398     supplier->SetNetValid(QUALITY_GOOD_STATE);
3399     locker.unlock();
3400     // Find best network because supplier score changed.
3401     FindBestNetworkForAllRequest();
3402     // Tell other suppliers to enable if current default supplier is not better than others.
3403     if (defaultNetSupplier_ && defaultNetSupplier_->GetSupplierId() == supplierId) {
3404         RequestAllNetworkExceptDefault();
3405     }
3406     return NETMANAGER_SUCCESS;
3407 }
3408 
FindSupplierToReduceScore(std::vector<sptr<NetSupplier>> & suppliers,uint32_t & supplierId)3409 uint32_t NetConnService::FindSupplierToReduceScore(std::vector<sptr<NetSupplier>>& suppliers, uint32_t& supplierId)
3410 {
3411     uint32_t ret = INVALID_SUPPLIER_ID;
3412     if (!defaultNetSupplier_) {
3413         NETMGR_LOG_E("default net supplier nullptr");
3414         return ret;
3415     }
3416     std::vector<sptr<NetSupplier>>::iterator iter;
3417     for (iter = suppliers.begin(); iter != suppliers.end(); ++iter) {
3418         if (defaultNetSupplier_->GetNetId() == (*iter)->GetNetId()) {
3419             ret = (*iter)->GetSupplierId();
3420             supplierId = ret;
3421             break;
3422         }
3423     }
3424     return ret;
3425 }
3426 
FindSupplierForConnected(std::vector<sptr<NetSupplier>> & suppliers)3427 uint32_t NetConnService::FindSupplierForConnected(std::vector<sptr<NetSupplier>> &suppliers)
3428 {
3429     uint32_t ret = INVALID_SUPPLIER_ID;
3430     std::vector<sptr<NetSupplier>>::iterator iter;
3431     for (iter = suppliers.begin(); iter != suppliers.end(); ++iter) {
3432         if (*iter == nullptr) {
3433             continue;
3434         }
3435         if ((*iter)->IsConnected()) {
3436             ret = (*iter)->GetSupplierId();
3437             break;
3438         }
3439     }
3440     return ret;
3441 }
3442 
NetConnListener(const EventFwk::CommonEventSubscribeInfo & subscribeInfo,EventReceiver receiver)3443 NetConnService::NetConnListener::NetConnListener(const EventFwk::CommonEventSubscribeInfo &subscribeInfo,
3444     EventReceiver receiver) : EventFwk::CommonEventSubscriber(subscribeInfo), eventReceiver_(receiver) {}
3445 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)3446 void NetConnService::NetConnListener::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
3447 {
3448     if (eventReceiver_ == nullptr) {
3449         NETMGR_LOG_E("eventReceiver is nullptr");
3450         return;
3451     }
3452     NETMGR_LOG_I("NetConnListener::OnReceiveEvent(), event:[%{public}s], data:[%{public}s], code:[%{public}d]",
3453                  eventData.GetWant().GetAction().c_str(), eventData.GetData().c_str(), eventData.GetCode());
3454     eventReceiver_(eventData);
3455 }
3456 
EnableVnicNetwork(const sptr<NetLinkInfo> & netLinkInfo,const std::set<int32_t> & uids)3457 int32_t NetConnService::EnableVnicNetwork(const sptr<NetLinkInfo> &netLinkInfo, const std::set<int32_t> &uids)
3458 {
3459     int32_t result = NETMANAGER_ERROR;
3460     if (netConnEventHandler_) {
3461         netConnEventHandler_->PostSyncTask(
3462             [this, &netLinkInfo, &uids, &result]() { result = this->EnableVnicNetworkAsync(netLinkInfo, uids); });
3463     }
3464     return result;
3465 }
3466 
EnableVnicNetworkAsync(const sptr<NetLinkInfo> & netLinkInfo,const std::set<int32_t> & uids)3467 int32_t NetConnService::EnableVnicNetworkAsync(const sptr<NetLinkInfo> &netLinkInfo, const std::set<int32_t> &uids)
3468 {
3469     NETMGR_LOG_I("enable vnic network");
3470 
3471     if (vnicCreated.load()) {
3472         NETMGR_LOG_E("Enable Vnic Network already");
3473         return NETWORKVPN_ERROR_VNIC_EXIST;
3474     }
3475 
3476     uint16_t mtu = netLinkInfo->mtu_;
3477     if (netLinkInfo->netAddrList_.empty()) {
3478         NETMGR_LOG_E("the netLinkInfo netAddrList is empty");
3479         return NET_CONN_ERR_INVALID_NETWORK;
3480     }
3481 
3482     const std::string &tunAddr = netLinkInfo->netAddrList_.front().address_;
3483     int32_t prefix = netLinkInfo->netAddrList_.front().prefixlen_;
3484     if (!CommonUtils::IsValidIPV4(tunAddr)) {
3485         NETMGR_LOG_E("the netLinkInfo tunAddr is not valid");
3486         return NET_CONN_ERR_INVALID_NETWORK;
3487     }
3488 
3489     NETMGR_LOG_I("EnableVnicNetwork tunAddr:[%{public}s], prefix:[%{public}d]", tunAddr.c_str(), prefix);
3490     if (NetsysController::GetInstance().CreateVnic(mtu, tunAddr, prefix, uids) != NETMANAGER_SUCCESS) {
3491         NETMGR_LOG_E("EnableVnicNetwork CreateVnic failed");
3492         return NETMANAGER_ERR_OPERATION_FAILED;
3493     }
3494 
3495     vnicCreated = true;
3496     return NETMANAGER_SUCCESS;
3497 }
3498 
DisableVnicNetwork()3499 int32_t NetConnService::DisableVnicNetwork()
3500 {
3501     int32_t result = NETMANAGER_ERROR;
3502     if (netConnEventHandler_) {
3503         netConnEventHandler_->PostSyncTask(
3504             [this, &result]() { result = this->DisableVnicNetworkAsync(); });
3505     }
3506     return result;
3507 }
3508 
DisableVnicNetworkAsync()3509 int32_t NetConnService::DisableVnicNetworkAsync()
3510 {
3511     NETMGR_LOG_I("del internal virtual network");
3512 
3513     if (!vnicCreated.load()) {
3514         NETMGR_LOG_E("cannot find vnic network");
3515         return NET_CONN_ERR_INVALID_NETWORK;
3516     }
3517 
3518     if (NetsysController::GetInstance().DestroyVnic() != NETMANAGER_SUCCESS) {
3519         return NETMANAGER_ERR_OPERATION_FAILED;
3520     }
3521     vnicCreated = false;
3522     return NETMANAGER_SUCCESS;
3523 }
3524 
EnableDistributedClientNet(const std::string & virnicAddr,const std::string & iif)3525 int32_t NetConnService::EnableDistributedClientNet(const std::string &virnicAddr, const std::string &iif)
3526 {
3527     int32_t result = NETMANAGER_ERROR;
3528     if (netConnEventHandler_) {
3529         netConnEventHandler_->PostSyncTask(
3530             [this, &virnicAddr, &iif, &result]() { result = this->EnableDistributedClientNetAsync(virnicAddr, iif); });
3531     }
3532     return result;
3533 }
3534 
EnableDistributedClientNetAsync(const std::string & virnicAddr,const std::string & iif)3535 int32_t NetConnService::EnableDistributedClientNetAsync(const std::string &virnicAddr, const std::string &iif)
3536 {
3537     if (iif.empty()) {
3538         NETMGR_LOG_E("iif is empty");
3539         return NET_CONN_ERR_INVALID_NETWORK;
3540     }
3541 
3542     if (!CommonUtils::IsValidIPV4(virnicAddr)) {
3543         NETMGR_LOG_E("the virnicAddr is not valid");
3544         return NET_CONN_ERR_INVALID_NETWORK;
3545     }
3546 
3547     if (NetsysController::GetInstance().EnableDistributedClientNet(virnicAddr, iif) != NETMANAGER_SUCCESS) {
3548         NETMGR_LOG_E("EnableDistributedClientNet failed");
3549         return NETMANAGER_ERR_OPERATION_FAILED;
3550     }
3551 
3552     return NETMANAGER_SUCCESS;
3553 }
3554 
EnableDistributedServerNet(const std::string & iif,const std::string & devIface,const std::string & dstAddr)3555 int32_t NetConnService::EnableDistributedServerNet(const std::string &iif, const std::string &devIface,
3556                                                    const std::string &dstAddr)
3557 {
3558     int32_t result = NETMANAGER_ERROR;
3559     if (netConnEventHandler_) {
3560         netConnEventHandler_->PostSyncTask([this, &iif, &devIface, &dstAddr, &result]() {
3561             result = this->EnableDistributedServerNetAsync(iif, devIface, dstAddr);
3562         });
3563     }
3564     return result;
3565 }
3566 
EnableDistributedServerNetAsync(const std::string & iif,const std::string & devIface,const std::string & dstAddr)3567 int32_t NetConnService::EnableDistributedServerNetAsync(const std::string &iif, const std::string &devIface,
3568                                                         const std::string &dstAddr)
3569 {
3570     if (iif.empty() || devIface.empty()) {
3571         NETMGR_LOG_E("iif || devIface is empty");
3572         return NET_CONN_ERR_INVALID_NETWORK;
3573     }
3574 
3575     if (!CommonUtils::IsValidIPV4(dstAddr)) {
3576         NETMGR_LOG_E("the dstAddr is not valid");
3577         return NET_CONN_ERR_INVALID_NETWORK;
3578     }
3579 
3580     if (NetsysController::GetInstance().EnableDistributedServerNet(iif, devIface, dstAddr) != NETMANAGER_SUCCESS) {
3581         NETMGR_LOG_E("EnableDistributedServerNet failed");
3582         return NETMANAGER_ERR_OPERATION_FAILED;
3583     }
3584 
3585     return NETMANAGER_SUCCESS;
3586 }
3587 
DisableDistributedNet(bool isServer)3588 int32_t NetConnService::DisableDistributedNet(bool isServer)
3589 {
3590     int32_t result = NETMANAGER_ERROR;
3591     if (netConnEventHandler_) {
3592         netConnEventHandler_->PostSyncTask(
3593             [this, isServer, &result]() { result = this->DisableDistributedNetAsync(isServer); });
3594     }
3595     return result;
3596 }
3597 
DisableDistributedNetAsync(bool isServer)3598 int32_t NetConnService::DisableDistributedNetAsync(bool isServer)
3599 {
3600     if (NetsysController::GetInstance().DisableDistributedNet(isServer) != NETMANAGER_SUCCESS) {
3601         NETMGR_LOG_E("DisableDistributedNet");
3602         return NETMANAGER_ERR_OPERATION_FAILED;
3603     }
3604 
3605     return NETMANAGER_SUCCESS;
3606 }
3607 
CloseSocketsUid(int32_t netId,uint32_t uid)3608 int32_t NetConnService::CloseSocketsUid(int32_t netId, uint32_t uid)
3609 {
3610     int32_t result = NETMANAGER_ERROR;
3611     if (netConnEventHandler_) {
3612         netConnEventHandler_->PostSyncTask(
3613             [this, netId, uid, &result]() { result = this->CloseSocketsUidAsync(netId, uid); });
3614     }
3615     return result;
3616 }
3617 
CloseSocketsUidAsync(int32_t netId,uint32_t uid)3618 int32_t NetConnService::CloseSocketsUidAsync(int32_t netId, uint32_t uid)
3619 {
3620     auto iterNetwork = networks_.find(netId);
3621     if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
3622         NETMGR_LOG_E("Could not find the corresponding network.");
3623         return NET_CONN_ERR_NETID_NOT_FOUND;
3624     }
3625     iterNetwork->second->CloseSocketsUid(uid);
3626     return NETMANAGER_SUCCESS;
3627 }
3628 
SetAppIsFrozened(uint32_t uid,bool isFrozened)3629 int32_t NetConnService::SetAppIsFrozened(uint32_t uid, bool isFrozened)
3630 {
3631     int32_t result = NETMANAGER_SUCCESS;
3632 #ifdef ENABLE_SET_APP_FROZENED
3633     if (netConnEventHandler_ && enableAppFrozenedCallbackLimitation_.load()) {
3634         netConnEventHandler_->PostSyncTask(
3635             [this, uid, isFrozened, &result]() { result = this->SetAppIsFrozenedAsync(uid, isFrozened); });
3636     }
3637 #endif
3638     return result;
3639 }
3640 
SetAppIsFrozenedAsync(uint32_t uid,bool isFrozened)3641 int32_t NetConnService::SetAppIsFrozenedAsync(uint32_t uid, bool isFrozened)
3642 {
3643     std::lock_guard guard(uidActivateMutex_);
3644     auto it = netUidActivates_.find(uid);
3645     if ((it == netUidActivates_.end())) {
3646         return NETMANAGER_SUCCESS;
3647     }
3648     std::vector<std::shared_ptr<NetActivate>> activates = it->second;
3649     NETMGR_LOG_I("SetAppIsFrozenedAsync uid[%{public}d], isFrozened=[%{public}d].", uid, isFrozened);
3650     for (auto iter = activates.begin(); iter != activates.end();++iter) {
3651         auto curNetAct = (*iter);
3652         if (curNetAct->IsAppFrozened() == isFrozened) {
3653             continue;
3654         }
3655         curNetAct->SetIsAppFrozened(isFrozened);
3656         if (isFrozened) {
3657             continue;
3658         }
3659         sptr<NetSupplier> netSupplier = curNetAct->GetServiceSupply();
3660         sptr<INetConnCallback> callback = curNetAct->GetNetCallback();
3661         CallbackType callbackType = curNetAct->GetLastCallbackType();
3662         if (callbackType == CALL_TYPE_UNKNOWN) {
3663             continue;
3664         }
3665         if (netSupplier == nullptr) {
3666             if (callbackType != CALL_TYPE_LOST) {
3667                 continue;
3668             }
3669             netSupplier = curNetAct->GetLastServiceSupply();
3670             if (netSupplier && callback) {
3671                 sptr<NetHandle> netHandle = netSupplier->GetNetHandle();
3672                 callback->NetLost(netHandle);
3673             }
3674         } else if (callbackType == CALL_TYPE_AVAILABLE) {
3675             CallbackForAvailable(netSupplier, curNetAct->GetNetCallback());
3676         } else {
3677             sptr<NetHandle> netHandle = netSupplier->GetNetHandle();
3678             HandleCallback(netSupplier, netHandle, callback, callbackType);
3679         }
3680         curNetAct->SetLastServiceSupply(nullptr);
3681         curNetAct->SetLastCallbackType(CALL_TYPE_UNKNOWN);
3682     }
3683     return NETMANAGER_SUCCESS;
3684 }
3685 
EnableAppFrozenedCallbackLimitation(bool flag)3686 int32_t NetConnService::EnableAppFrozenedCallbackLimitation(bool flag)
3687 {
3688     int32_t result = NETMANAGER_SUCCESS;
3689     if (netConnEventHandler_) {
3690         netConnEventHandler_->PostSyncTask([this, flag, &result]() {
3691             result = this->EnableAppFrozenedCallbackLimitationAsync(flag);
3692     });
3693     }
3694     return result;
3695 }
3696 
EnableAppFrozenedCallbackLimitationAsync(bool flag)3697 int32_t NetConnService::EnableAppFrozenedCallbackLimitationAsync(bool flag)
3698 {
3699     enableAppFrozenedCallbackLimitation_ = flag;
3700     NETMGR_LOG_I("enableAppFrozenedCallbackLimitation_ = %{public}d", enableAppFrozenedCallbackLimitation_.load());
3701     return NETMANAGER_SUCCESS;
3702 }
3703 
IsAppFrozenedCallbackLimitation()3704 bool NetConnService::IsAppFrozenedCallbackLimitation()
3705 {
3706     bool ret = enableAppFrozenedCallbackLimitation_.load();
3707     return ret;
3708 }
3709 
3710 } // namespace NetManagerStandard
3711 } // namespace OHOS
3712