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