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