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