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;
892     int32_t ret = GetCallingUserId(userId);
893     if (ret == NETMANAGER_SUCCESS) {
894         param.emplace("UserId", std::to_string(userId));
895     } else {
896         NETMGR_LOG_E("SendHttpProxyChangeBroadcast get calling userId fail.");
897     }
898     BroadcastManager::GetInstance().SendBroadcast(info, param);
899 }
900 
ActivateNetwork(const sptr<NetSpecifier> & netSpecifier,const sptr<INetConnCallback> & callback,const uint32_t & timeoutMS,const int32_t registerType,const uint32_t callingUid)901 int32_t NetConnService::ActivateNetwork(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
902                                         const uint32_t &timeoutMS, const int32_t registerType,
903                                         const uint32_t callingUid)
904 {
905     NETMGR_LOG_D("ActivateNetwork Enter");
906     if (netSpecifier == nullptr || callback == nullptr) {
907         NETMGR_LOG_E("The parameter of netSpecifier or callback is null");
908         return NETMANAGER_ERR_PARAMETER_ERROR;
909     }
910     std::weak_ptr<INetActivateCallback> timeoutCb = shared_from_this();
911     std::shared_ptr<NetActivate> request =
912         std::make_shared<NetActivate>(netSpecifier, callback, timeoutCb, timeoutMS, netConnEventHandler_, registerType);
913     request->StartTimeOutNetAvailable();
914     uint32_t reqId = request->GetRequestId();
915     NETMGR_LOG_I("New request [id:%{public}u]", reqId);
916     netActivates_[reqId] = request;
917     sptr<NetSupplier> bestNet = nullptr;
918     int bestScore = static_cast<int>(FindBestNetworkForRequest(bestNet, request));
919     if (bestScore != 0 && bestNet != nullptr) {
920         NETMGR_LOG_I(
921             "Match to optimal supplier:[%{public}d %{public}s] netId[%{public}d] score[%{public}d] "
922             "reqId[%{public}u]",
923             bestNet->GetSupplierId(), bestNet->GetNetSupplierIdent().c_str(), bestNet->GetNetId(), bestScore, reqId);
924         bestNet->SelectAsBestNetwork(reqId);
925         request->SetServiceSupply(bestNet);
926         CallbackForAvailable(bestNet, callback);
927         if ((bestNet->GetNetSupplierType() == BEARER_CELLULAR) || (bestNet->GetNetSupplierType() == BEARER_WIFI)) {
928             struct EventInfo eventInfo = {.capabilities = bestNet->GetNetCapabilities().ToString(" "),
929                                           .supplierIdent = bestNet->GetNetSupplierIdent()};
930             EventReport::SendRequestBehaviorEvent(eventInfo);
931         }
932         return NETMANAGER_SUCCESS;
933     }
934     if (timeoutMS == 0) {
935         callback->NetUnavailable();
936     }
937 
938     NETMGR_LOG_D("Not matched to the optimal network, send request to all networks.");
939     SendRequestToAllNetwork(request, callingUid);
940     return NETMANAGER_SUCCESS;
941 }
942 
OnNetActivateTimeOut(uint32_t reqId)943 void NetConnService::OnNetActivateTimeOut(uint32_t reqId)
944 {
945     if (netConnEventHandler_) {
946         netConnEventHandler_->PostSyncTask([reqId, this]() {
947             NETMGR_LOG_I("DeactivateNetwork Enter, reqId is [%{public}d]", reqId);
948             auto iterActivate = netActivates_.find(reqId);
949             if (iterActivate == netActivates_.end()) {
950                 NETMGR_LOG_E("not found the reqId: [%{public}d]", reqId);
951                 return;
952             }
953             if (iterActivate->second != nullptr) {
954                 sptr<NetSupplier> pNetService = iterActivate->second->GetServiceSupply();
955                 if (pNetService) {
956                     pNetService->CancelRequest(reqId);
957                 }
958             }
959 
960             NET_SUPPLIER_MAP::iterator iterSupplier;
961             for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
962                 if (iterSupplier->second == nullptr) {
963                     continue;
964                 }
965                 iterSupplier->second->CancelRequest(reqId);
966             }
967         });
968     }
969 }
970 
FindNetSupplier(uint32_t supplierId)971 sptr<NetSupplier> NetConnService::FindNetSupplier(uint32_t supplierId)
972 {
973     auto iterSupplier = netSuppliers_.find(supplierId);
974     if (iterSupplier != netSuppliers_.end()) {
975         return iterSupplier->second;
976     }
977     return nullptr;
978 }
979 
FindSameCallback(const sptr<INetConnCallback> & callback,uint32_t & reqId,RegisterType & registerType)980 bool NetConnService::FindSameCallback(const sptr<INetConnCallback> &callback,
981                                       uint32_t &reqId, RegisterType &registerType)
982 {
983     if (callback == nullptr) {
984         NETMGR_LOG_E("callback is null");
985         return false;
986     }
987     NET_ACTIVATE_MAP::iterator iterActive;
988     for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
989         if (!iterActive->second) {
990             continue;
991         }
992         sptr<INetConnCallback> saveCallback = iterActive->second->GetNetCallback();
993         if (saveCallback == nullptr) {
994             continue;
995         }
996         if (callback->AsObject().GetRefPtr() == saveCallback->AsObject().GetRefPtr()) {
997             reqId = iterActive->first;
998             if (iterActive->second) {
999                 auto specifier = iterActive->second->GetNetSpecifier();
1000                 registerType = (specifier != nullptr &&
1001                     specifier->netCapabilities_.netCaps_.count(
1002                         NetManagerStandard::NET_CAPABILITY_INTERNAL_DEFAULT) > 0) ?
1003                         REQUEST : REGISTER;
1004             }
1005             return true;
1006         }
1007     }
1008     return false;
1009 }
1010 
FindSameCallback(const sptr<INetConnCallback> & callback,uint32_t & reqId)1011 bool NetConnService::FindSameCallback(const sptr<INetConnCallback> &callback, uint32_t &reqId)
1012 {
1013     RegisterType registerType = INVALIDTYPE;
1014     return FindSameCallback(callback, reqId, registerType);
1015 }
1016 
FindBestNetworkForAllRequest()1017 void NetConnService::FindBestNetworkForAllRequest()
1018 {
1019     NETMGR_LOG_I("FindBestNetworkForAllRequest Enter. netActivates_ size: [%{public}zu]", netActivates_.size());
1020     NET_ACTIVATE_MAP::iterator iterActive;
1021     sptr<NetSupplier> bestSupplier = nullptr;
1022     for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
1023         if (!iterActive->second) {
1024             continue;
1025         }
1026         int score = static_cast<int>(FindBestNetworkForRequest(bestSupplier, iterActive->second));
1027         NETMGR_LOG_D("Find best supplier[%{public}d, %{public}s]for request[%{public}d]",
1028                      bestSupplier ? bestSupplier->GetSupplierId() : 0,
1029                      bestSupplier ? bestSupplier->GetNetSupplierIdent().c_str() : "null",
1030                      iterActive->second->GetRequestId());
1031         if (iterActive->second == defaultNetActivate_) {
1032             MakeDefaultNetWork(defaultNetSupplier_, bestSupplier);
1033         }
1034         sptr<NetSupplier> oldSupplier = iterActive->second->GetServiceSupply();
1035         sptr<INetConnCallback> callback = iterActive->second->GetNetCallback();
1036         if (!bestSupplier) {
1037             // not found the bestNetwork
1038             NotFindBestSupplier(iterActive->first, iterActive->second, oldSupplier, callback);
1039             continue;
1040         }
1041         SendBestScoreAllNetwork(iterActive->first, score, bestSupplier->GetSupplierId());
1042         if (bestSupplier == oldSupplier) {
1043             NETMGR_LOG_D("bestSupplier is equal with oldSupplier.");
1044             continue;
1045         }
1046         if (oldSupplier) {
1047             oldSupplier->RemoveBestRequest(iterActive->first);
1048         }
1049         iterActive->second->SetServiceSupply(bestSupplier);
1050         CallbackForAvailable(bestSupplier, callback);
1051         bestSupplier->SelectAsBestNetwork(iterActive->first);
1052     }
1053     NETMGR_LOG_I("FindBestNetworkForAllRequest end");
1054 }
1055 
FindBestNetworkForRequest(sptr<NetSupplier> & supplier,std::shared_ptr<NetActivate> & netActivateNetwork)1056 uint32_t NetConnService::FindBestNetworkForRequest(sptr<NetSupplier> &supplier,
1057                                                    std::shared_ptr<NetActivate> &netActivateNetwork)
1058 {
1059     int bestScore = 0;
1060     supplier = nullptr;
1061     if (netActivateNetwork == nullptr) {
1062         NETMGR_LOG_E("netActivateNetwork is null");
1063         return bestScore;
1064     }
1065 
1066     NET_SUPPLIER_MAP::iterator iter;
1067     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1068         if (iter->second == nullptr) {
1069             continue;
1070         }
1071         NETMGR_LOG_D("supplier info, supplier[%{public}d, %{public}s], realScore[%{public}d], isConnected[%{public}d]",
1072                      iter->second->GetSupplierId(), iter->second->GetNetSupplierIdent().c_str(),
1073                      iter->second->GetRealScore(), iter->second->IsConnected());
1074         if ((!iter->second->IsConnected()) || (!netActivateNetwork->MatchRequestAndNetwork(iter->second))) {
1075             NETMGR_LOG_D("Supplier[%{public}d] is not connected or not match request.", iter->second->GetSupplierId());
1076             continue;
1077         }
1078         int score = iter->second->GetRealScore();
1079         if (score > bestScore) {
1080             bestScore = score;
1081             supplier = iter->second;
1082         }
1083     }
1084     NETMGR_LOG_D(
1085         "bestScore[%{public}d], bestSupplier[%{public}d, %{public}s], "
1086         "request[%{public}d] is [%{public}s],",
1087         bestScore, supplier ? supplier->GetSupplierId() : 0,
1088         supplier ? supplier->GetNetSupplierIdent().c_str() : "null", netActivateNetwork->GetRequestId(),
1089         netActivateNetwork->GetNetSpecifier() ? netActivateNetwork->GetNetSpecifier()->ToString(" ").c_str() : "null");
1090     return bestScore;
1091 }
1092 
RequestAllNetworkExceptDefault()1093 void NetConnService::RequestAllNetworkExceptDefault()
1094 {
1095     if ((defaultNetSupplier_ == nullptr) || (defaultNetSupplier_->IsNetValidated())) {
1096         NETMGR_LOG_E("defaultNetSupplier_ is  null or IsNetValidated");
1097         return;
1098     }
1099     NETMGR_LOG_I("Default supplier[%{public}d, %{public}s] is not valid,request to activate another network",
1100                  defaultNetSupplier_->GetSupplierId(), defaultNetSupplier_->GetNetSupplierIdent().c_str());
1101     if (defaultNetActivate_ == nullptr) {
1102         NETMGR_LOG_E("Default net request is null");
1103         return;
1104     }
1105     // Request activation of all networks except the default network
1106     uint32_t reqId = defaultNetActivate_->GetRequestId();
1107     for (const auto &netSupplier : netSuppliers_) {
1108         if (netSupplier.second == nullptr || netSupplier.second == defaultNetSupplier_) {
1109             NETMGR_LOG_E("netSupplier is null or is defaultNetSupplier_");
1110             continue;
1111         }
1112         if (netSupplier.second->GetNetScore() >= defaultNetSupplier_->GetNetScore()) {
1113             continue;
1114         }
1115         if (netSupplier.second->HasNetCap(NetCap::NET_CAPABILITY_INTERNAL_DEFAULT)) {
1116             NETMGR_LOG_I("Supplier[%{public}d] is internal, skip.", netSupplier.second->GetSupplierId());
1117             continue;
1118         }
1119         if (!defaultNetActivate_->MatchRequestAndNetwork(netSupplier.second, true)) {
1120             continue;
1121         }
1122         if (!netSupplier.second->RequestToConnect(reqId)) {
1123             NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed",
1124                          netSupplier.second->GetSupplierId(), netSupplier.second->GetNetSupplierIdent().c_str());
1125         }
1126     }
1127 }
1128 
GenerateNetId()1129 int32_t NetConnService::GenerateNetId()
1130 {
1131     for (int32_t i = MIN_NET_ID; i <= MAX_NET_ID; ++i) {
1132         netIdLastValue_++;
1133         if (netIdLastValue_ > MAX_NET_ID) {
1134             netIdLastValue_ = MIN_NET_ID;
1135         }
1136         if (networks_.find(netIdLastValue_) == networks_.end()) {
1137             return netIdLastValue_;
1138         }
1139     }
1140     return INVALID_NET_ID;
1141 }
1142 
GenerateInternalNetId()1143 int32_t NetConnService::GenerateInternalNetId()
1144 {
1145     for (int32_t i = MIN_INTERNAL_NET_ID; i <= MAX_INTERNAL_NET_ID; ++i) {
1146         int32_t value = internalNetIdLastValue_++;
1147         if (value > MAX_INTERNAL_NET_ID) {
1148             internalNetIdLastValue_ = MIN_INTERNAL_NET_ID;
1149             value = MIN_INTERNAL_NET_ID;
1150         }
1151         if (networks_.find(value) == networks_.end()) {
1152             return value;
1153         }
1154     }
1155     return INVALID_NET_ID;
1156 }
1157 
NotFindBestSupplier(uint32_t reqId,const std::shared_ptr<NetActivate> & active,const sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)1158 void NetConnService::NotFindBestSupplier(uint32_t reqId, const std::shared_ptr<NetActivate> &active,
1159                                          const sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
1160 {
1161     NETMGR_LOG_I("Could not find best supplier for request:[%{public}d]", reqId);
1162     if (supplier != nullptr) {
1163         supplier->RemoveBestRequest(reqId);
1164         if (callback != nullptr) {
1165             sptr<NetHandle> netHandle = supplier->GetNetHandle();
1166             callback->NetLost(netHandle);
1167         }
1168     }
1169     if (active != nullptr) {
1170         active->SetServiceSupply(nullptr);
1171         SendRequestToAllNetwork(active);
1172     }
1173 }
1174 
SendAllRequestToNetwork(sptr<NetSupplier> supplier)1175 void NetConnService::SendAllRequestToNetwork(sptr<NetSupplier> supplier)
1176 {
1177     if (supplier == nullptr) {
1178         NETMGR_LOG_E("supplier is null");
1179         return;
1180     }
1181     NETMGR_LOG_I("Send all request to supplier[%{public}d, %{public}s]", supplier->GetSupplierId(),
1182                  supplier->GetNetSupplierIdent().c_str());
1183     NET_ACTIVATE_MAP::iterator iter;
1184     for (iter = netActivates_.begin(); iter != netActivates_.end(); ++iter) {
1185         if (iter->second == nullptr) {
1186             continue;
1187         }
1188         if (!iter->second->MatchRequestAndNetwork(supplier, true)) {
1189             continue;
1190         }
1191         NetRequest netrequest(iter->second->GetRegisterType(), iter->second->GetBearType());
1192         bool result = supplier->RequestToConnect(iter->first, netrequest);
1193         if (!result) {
1194             NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed", supplier->GetSupplierId(),
1195                          supplier->GetNetSupplierIdent().c_str());
1196         }
1197     }
1198 }
1199 
SendRequestToAllNetwork(std::shared_ptr<NetActivate> request,uint32_t callingUid)1200 void NetConnService::SendRequestToAllNetwork(std::shared_ptr<NetActivate> request, uint32_t callingUid)
1201 {
1202     if (request == nullptr) {
1203         NETMGR_LOG_E("request is null");
1204         return;
1205     }
1206 
1207     uint32_t reqId = request->GetRequestId();
1208     NETMGR_LOG_I("Send request[%{public}d] to all supplier", request->GetRequestId());
1209     NET_SUPPLIER_MAP::iterator iter;
1210     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1211         if (iter->second == nullptr) {
1212             continue;
1213         }
1214         if (!request->MatchRequestAndNetwork(iter->second, true)) {
1215             continue;
1216         }
1217         NetRequest netrequest(request->GetRegisterType(), request->GetBearType(), callingUid, request->GetRequestId(),
1218             request->GetNetSpecifier()->ident_);
1219         bool result = iter->second->RequestToConnect(reqId, netrequest);
1220         if (!result) {
1221             NETMGR_LOG_E("Request network for supplier[%{public}d, %{public}s] failed", iter->second->GetSupplierId(),
1222                          iter->second->GetNetSupplierIdent().c_str());
1223         }
1224     }
1225 }
1226 
SendBestScoreAllNetwork(uint32_t reqId,int32_t bestScore,uint32_t supplierId)1227 void NetConnService::SendBestScoreAllNetwork(uint32_t reqId, int32_t bestScore, uint32_t supplierId)
1228 {
1229     NETMGR_LOG_D("Send best supplier[%{public}d]-score[%{public}d] to all supplier", supplierId, bestScore);
1230     NET_SUPPLIER_MAP::iterator iter;
1231     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
1232         if (iter->second == nullptr) {
1233             continue;
1234         }
1235         if (iter->second->HasNetCap(NetCap::NET_CAPABILITY_INTERNAL_DEFAULT)) {
1236             continue;
1237         }
1238         iter->second->ReceiveBestScore(reqId, bestScore, supplierId);
1239     }
1240 }
1241 
CallbackForSupplier(sptr<NetSupplier> & supplier,CallbackType type)1242 void NetConnService::CallbackForSupplier(sptr<NetSupplier> &supplier, CallbackType type)
1243 {
1244     if (supplier == nullptr) {
1245         NETMGR_LOG_E("supplier is nullptr");
1246         return;
1247     }
1248     std::set<uint32_t> &bestReqList = supplier->GetBestRequestList();
1249     NETMGR_LOG_I("Callback type: %{public}d for supplier[%{public}d, %{public}s], best request size: %{public}zd",
1250                  static_cast<int32_t>(type), supplier->GetSupplierId(), supplier->GetNetSupplierIdent().c_str(),
1251                  bestReqList.size());
1252     for (auto it : bestReqList) {
1253         auto reqIt = netActivates_.find(it);
1254         if ((reqIt == netActivates_.end()) || (reqIt->second == nullptr)) {
1255             continue;
1256         }
1257         sptr<INetConnCallback> callback = reqIt->second->GetNetCallback();
1258         if (!callback) {
1259             continue;
1260         }
1261         sptr<NetHandle> netHandle = supplier->GetNetHandle();
1262         switch (type) {
1263             case CALL_TYPE_LOST: {
1264                 callback->NetLost(netHandle);
1265                 break;
1266             }
1267             case CALL_TYPE_UPDATE_CAP: {
1268                 sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
1269                 *pNetAllCap = supplier->GetNetCapabilities();
1270                 callback->NetCapabilitiesChange(netHandle, pNetAllCap);
1271                 break;
1272             }
1273             case CALL_TYPE_UPDATE_LINK: {
1274                 sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
1275                 auto network = supplier->GetNetwork();
1276                 if (network != nullptr && pInfo != nullptr) {
1277                     *pInfo = network->GetNetLinkInfo();
1278                 }
1279                 callback->NetConnectionPropertiesChange(netHandle, pInfo);
1280                 break;
1281             }
1282             case CALL_TYPE_BLOCK_STATUS: {
1283                 bool Metered = supplier->HasNetCap(NET_CAPABILITY_NOT_METERED);
1284                 bool newBlocked = NetManagerCenter::GetInstance().IsUidNetAccess(supplier->GetSupplierUid(), Metered);
1285                 callback->NetBlockStatusChange(netHandle, newBlocked);
1286                 break;
1287             }
1288             default:
1289                 break;
1290         }
1291     }
1292 }
1293 
CallbackForAvailable(sptr<NetSupplier> & supplier,const sptr<INetConnCallback> & callback)1294 void NetConnService::CallbackForAvailable(sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback)
1295 {
1296     if (supplier == nullptr || callback == nullptr) {
1297         NETMGR_LOG_E("Input parameter is null.");
1298         return;
1299     }
1300     NETMGR_LOG_I("CallbackForAvailable supplier[%{public}d, %{public}s]", supplier->GetSupplierId(),
1301                  supplier->GetNetSupplierIdent().c_str());
1302     sptr<NetHandle> netHandle = supplier->GetNetHandle();
1303     callback->NetAvailable(netHandle);
1304     sptr<NetAllCapabilities> pNetAllCap = std::make_unique<NetAllCapabilities>().release();
1305     *pNetAllCap = supplier->GetNetCapabilities();
1306     callback->NetCapabilitiesChange(netHandle, pNetAllCap);
1307     sptr<NetLinkInfo> pInfo = std::make_unique<NetLinkInfo>().release();
1308     auto network = supplier->GetNetwork();
1309     if (network != nullptr && pInfo != nullptr) {
1310         *pInfo = network->GetNetLinkInfo();
1311     }
1312     callback->NetConnectionPropertiesChange(netHandle, pInfo);
1313     NetsysController::GetInstance().NotifyNetBearerTypeChange(pNetAllCap->bearerTypes_);
1314 }
1315 
MakeDefaultNetWork(sptr<NetSupplier> & oldSupplier,sptr<NetSupplier> & newSupplier)1316 void NetConnService::MakeDefaultNetWork(sptr<NetSupplier> &oldSupplier, sptr<NetSupplier> &newSupplier)
1317 {
1318     NETMGR_LOG_I(
1319         "oldSupplier[%{public}d, %{public}s], newSupplier[%{public}d, %{public}s], old equals "
1320         "new is [%{public}d]", oldSupplier ? oldSupplier->GetSupplierId() : 0,
1321         oldSupplier ? oldSupplier->GetNetSupplierIdent().c_str() : "null",
1322         newSupplier ? newSupplier->GetSupplierId() : 0,
1323         newSupplier ? newSupplier->GetNetSupplierIdent().c_str() : "null", oldSupplier == newSupplier);
1324     if (oldSupplier == newSupplier) {
1325         NETMGR_LOG_D("old supplier equal to new supplier.");
1326         return;
1327     }
1328     if (oldSupplier != nullptr) {
1329         oldSupplier->ClearDefault();
1330     }
1331     if (newSupplier != nullptr) {
1332         newSupplier->SetDefault();
1333     }
1334     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1335     oldSupplier = newSupplier;
1336 }
1337 
HandleDetectionResult(uint32_t supplierId,NetDetectionStatus netState)1338 void NetConnService::HandleDetectionResult(uint32_t supplierId, NetDetectionStatus netState)
1339 {
1340     NETMGR_LOG_I("Enter HandleDetectionResult, ifValid[%{public}d]", netState);
1341     auto supplier = FindNetSupplier(supplierId);
1342     if (supplier == nullptr) {
1343         NETMGR_LOG_E("supplier doesn't exist.");
1344         return;
1345     }
1346     supplier->SetNetValid(netState);
1347     supplier->SetDetectionDone();
1348     CallbackForSupplier(supplier, CALL_TYPE_UPDATE_CAP);
1349     FindBestNetworkForAllRequest();
1350     bool ifValid = netState == VERIFICATION_STATE;
1351     if (!ifValid && defaultNetSupplier_ && defaultNetSupplier_->GetSupplierId() == supplierId) {
1352         RequestAllNetworkExceptDefault();
1353     }
1354     NETMGR_LOG_I("Enter HandleDetectionResult end");
1355 }
1356 
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident)1357 std::list<sptr<NetSupplier>> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident)
1358 {
1359     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1360     std::list<sptr<NetSupplier>> ret;
1361     for (const auto &netSupplier : netSuppliers_) {
1362         if (netSupplier.second == nullptr) {
1363             continue;
1364         }
1365         if ((bearerType != netSupplier.second->GetNetSupplierType())) {
1366             continue;
1367         }
1368         if (!ident.empty() && netSupplier.second->GetNetSupplierIdent() != ident) {
1369             continue;
1370         }
1371         ret.push_back(netSupplier.second);
1372     }
1373     return ret;
1374 }
1375 
GetNetSupplierFromList(NetBearType bearerType,const std::string & ident,const std::set<NetCap> & netCaps)1376 sptr<NetSupplier> NetConnService::GetNetSupplierFromList(NetBearType bearerType, const std::string &ident,
1377                                                          const std::set<NetCap> &netCaps)
1378 {
1379     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1380     for (const auto &netSupplier : netSuppliers_) {
1381         if (netSupplier.second == nullptr) {
1382             continue;
1383         }
1384         if ((bearerType == netSupplier.second->GetNetSupplierType()) &&
1385             (ident == netSupplier.second->GetNetSupplierIdent()) && netSupplier.second->CompareNetCaps(netCaps)) {
1386             return netSupplier.second;
1387         }
1388     }
1389     return nullptr;
1390 }
1391 
GetDefaultNet(int32_t & netId)1392 int32_t NetConnService::GetDefaultNet(int32_t &netId)
1393 {
1394     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1395     if (!defaultNetSupplier_) {
1396         NETMGR_LOG_E("not found the netId");
1397         return NETMANAGER_SUCCESS;
1398     }
1399 
1400     netId = defaultNetSupplier_->GetNetId();
1401     NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
1402     return NETMANAGER_SUCCESS;
1403 }
1404 
GetAddressesByName(const std::string & host,int32_t netId,std::vector<INetAddr> & addrList)1405 int32_t NetConnService::GetAddressesByName(const std::string &host, int32_t netId, std::vector<INetAddr> &addrList)
1406 {
1407     return NetManagerCenter::GetInstance().GetAddressesByName(host, static_cast<uint16_t>(netId), addrList);
1408 }
1409 
GetAddressByName(const std::string & host,int32_t netId,INetAddr & addr)1410 int32_t NetConnService::GetAddressByName(const std::string &host, int32_t netId, INetAddr &addr)
1411 {
1412     std::vector<INetAddr> addrList;
1413     int ret = GetAddressesByName(host, netId, addrList);
1414     if (ret == NETMANAGER_SUCCESS) {
1415         if (!addrList.empty()) {
1416             addr = addrList[0];
1417             return ret;
1418         }
1419         return NET_CONN_ERR_NO_ADDRESS;
1420     }
1421     return ret;
1422 }
1423 
GetSpecificNet(NetBearType bearerType,std::list<int32_t> & netIdList)1424 int32_t NetConnService::GetSpecificNet(NetBearType bearerType, std::list<int32_t> &netIdList)
1425 {
1426     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1427         NETMGR_LOG_E("netType parameter invalid");
1428         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1429     }
1430 
1431     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1432     NET_SUPPLIER_MAP::iterator iterSupplier;
1433     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1434         if (iterSupplier->second == nullptr) {
1435             continue;
1436         }
1437         auto supplierType = iterSupplier->second->GetNetSupplierType();
1438         if (bearerType == supplierType) {
1439             netIdList.push_back(iterSupplier->second->GetNetId());
1440         }
1441     }
1442     NETMGR_LOG_D("netSuppliers_ size[%{public}zd] networks_ size[%{public}zd]", netSuppliers_.size(), networks_.size());
1443     return NETMANAGER_SUCCESS;
1444 }
1445 
GetAllNets(std::list<int32_t> & netIdList)1446 int32_t NetConnService::GetAllNets(std::list<int32_t> &netIdList)
1447 {
1448     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1449     auto currentUid = IPCSkeleton::GetCallingUid();
1450     for (const auto &network : networks_) {
1451         if (network.second != nullptr && network.second->IsConnected()) {
1452             auto netId = network.second->GetNetId();
1453             sptr<NetSupplier> curSupplier = FindNetSupplier(network.second->GetSupplierId());
1454             // inner virtual interface and uid is not trusted, skip
1455             if (curSupplier != nullptr &&
1456                 curSupplier->HasNetCap(NetCap::NET_CAPABILITY_INTERNAL_DEFAULT) &&
1457                 !IsInRequestNetUids(currentUid)) {
1458                 NETMGR_LOG_D("Network [%{public}d] is internal, uid [%{public}d] skips.", netId, currentUid);
1459                 continue;
1460             }
1461             netIdList.push_back(netId);
1462         }
1463     }
1464     NETMGR_LOG_D("netSuppliers_ size[%{public}zd] netIdList size[%{public}zd]", netSuppliers_.size(), netIdList.size());
1465     return NETMANAGER_SUCCESS;
1466 }
1467 
IsInRequestNetUids(int32_t uid)1468 bool NetConnService::IsInRequestNetUids(int32_t uid)
1469 {
1470     return internalDefaultUidRequest_.count(uid) > 0;
1471 }
1472 
GetSpecificUidNet(int32_t uid,int32_t & netId)1473 int32_t NetConnService::GetSpecificUidNet(int32_t uid, int32_t &netId)
1474 {
1475     NETMGR_LOG_D("Enter GetSpecificUidNet, uid is [%{public}d].", uid);
1476     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1477     netId = INVALID_NET_ID;
1478     NET_SUPPLIER_MAP::iterator iterSupplier;
1479     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1480         if ((iterSupplier->second != nullptr) && (uid == iterSupplier->second->GetSupplierUid()) &&
1481             (iterSupplier->second->GetNetSupplierType() == BEARER_VPN)) {
1482             netId = iterSupplier->second->GetNetId();
1483             return NETMANAGER_SUCCESS;
1484         }
1485     }
1486     if (defaultNetSupplier_ != nullptr) {
1487         netId = defaultNetSupplier_->GetNetId();
1488     }
1489     NETMGR_LOG_D("GetDefaultNet found the netId: [%{public}d]", netId);
1490     return NETMANAGER_SUCCESS;
1491 }
1492 
GetConnectionProperties(int32_t netId,NetLinkInfo & info)1493 int32_t NetConnService::GetConnectionProperties(int32_t netId, NetLinkInfo &info)
1494 {
1495     if (netConnEventHandler_ == nullptr) {
1496         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1497         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1498     }
1499     int32_t result = NETMANAGER_SUCCESS;
1500     netConnEventHandler_->PostSyncTask([netId, &info, &result, this]() {
1501         auto iterNetwork = networks_.find(netId);
1502         if ((iterNetwork == networks_.end()) || (iterNetwork->second == nullptr)) {
1503             result = NET_CONN_ERR_INVALID_NETWORK;
1504             return;
1505         }
1506         info = iterNetwork->second->GetNetLinkInfo();
1507         if (info.mtu_ == 0) {
1508             info.mtu_ = DEFAULT_MTU;
1509         }
1510     });
1511     return result;
1512 }
1513 
GetNetCapabilities(int32_t netId,NetAllCapabilities & netAllCap)1514 int32_t NetConnService::GetNetCapabilities(int32_t netId, NetAllCapabilities &netAllCap)
1515 {
1516     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1517     NET_SUPPLIER_MAP::iterator iterSupplier;
1518     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
1519         if ((iterSupplier->second != nullptr) && (netId == iterSupplier->second->GetNetId())) {
1520             netAllCap = iterSupplier->second->GetNetCapabilities();
1521             return NETMANAGER_SUCCESS;
1522         }
1523     }
1524     return NET_CONN_ERR_INVALID_NETWORK;
1525 }
1526 
GetIfaceNames(NetBearType bearerType,std::list<std::string> & ifaceNames)1527 int32_t NetConnService::GetIfaceNames(NetBearType bearerType, std::list<std::string> &ifaceNames)
1528 {
1529     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1530         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1531     }
1532 
1533     if (netConnEventHandler_ == nullptr) {
1534         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1535         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1536     }
1537     netConnEventHandler_->PostSyncTask([bearerType, &ifaceNames, this]() {
1538         auto suppliers = GetNetSupplierFromList(bearerType);
1539         for (auto supplier : suppliers) {
1540             if (supplier == nullptr) {
1541                 continue;
1542             }
1543             std::shared_ptr<Network> network = supplier->GetNetwork();
1544             if (network == nullptr) {
1545                 continue;
1546             }
1547             std::string ifaceName = network->GetIfaceName();
1548             if (!ifaceName.empty()) {
1549                 ifaceNames.push_back(ifaceName);
1550             }
1551         }
1552     });
1553     return NETMANAGER_SUCCESS;
1554 }
1555 
GetIfaceNameByType(NetBearType bearerType,const std::string & ident,std::string & ifaceName)1556 int32_t NetConnService::GetIfaceNameByType(NetBearType bearerType, const std::string &ident, std::string &ifaceName)
1557 {
1558     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1559         NETMGR_LOG_E("netType parameter invalid");
1560         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1561     }
1562     if (netConnEventHandler_ == nullptr) {
1563         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1564         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1565     }
1566     int32_t result = NETMANAGER_SUCCESS;
1567     netConnEventHandler_->PostSyncTask([bearerType, &ifaceName, &ident, &result, this]() {
1568         auto suppliers = GetNetSupplierFromList(bearerType, ident);
1569         if (suppliers.empty()) {
1570             NETMGR_LOG_D("supplier is nullptr.");
1571             result = NET_CONN_ERR_NO_SUPPLIER;
1572             return;
1573         }
1574         auto supplier = suppliers.front();
1575         std::shared_ptr<Network> network = supplier->GetNetwork();
1576         if (network == nullptr) {
1577             NETMGR_LOG_E("network is nullptr");
1578             result = NET_CONN_ERR_INVALID_NETWORK;
1579             return;
1580         }
1581         ifaceName = network->GetIfaceName();
1582     });
1583     return result;
1584 }
1585 
GetIfaceNameIdentMaps(NetBearType bearerType,SafeMap<std::string,std::string> & ifaceNameIdentMaps)1586 int32_t NetConnService::GetIfaceNameIdentMaps(NetBearType bearerType,
1587                                               SafeMap<std::string, std::string> &ifaceNameIdentMaps)
1588 {
1589     if (bearerType < BEARER_CELLULAR || bearerType >= BEARER_DEFAULT) {
1590         return NET_CONN_ERR_NET_TYPE_NOT_FOUND;
1591     }
1592 
1593     if (netConnEventHandler_ == nullptr) {
1594         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1595         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1596     }
1597     netConnEventHandler_->PostSyncTask([bearerType, &ifaceNameIdentMaps, this]() {
1598         NETMGR_LOG_I("Enter GetIfaceNameIdentMaps, netBearType=%{public}d", bearerType);
1599         ifaceNameIdentMaps.Clear();
1600         auto suppliers = GetNetSupplierFromList(bearerType);
1601         for (auto supplier: suppliers) {
1602             if (supplier == nullptr || !supplier->HasNetCap(NET_CAPABILITY_INTERNET)) {
1603                 continue;
1604             }
1605             std::shared_ptr <Network> network = supplier->GetNetwork();
1606             if (network == nullptr || !network->IsConnected()) {
1607                 continue;
1608             }
1609             std::string ifaceName = network->GetIfaceName();
1610             if (ifaceName.empty()) {
1611                 continue;
1612             }
1613             std::string ident = network->GetIdent();
1614             ifaceNameIdentMaps.EnsureInsert(std::move(ifaceName), std::move(ident));
1615         }
1616     });
1617     return NETMANAGER_SUCCESS;
1618 }
1619 
GetGlobalHttpProxy(HttpProxy & httpProxy)1620 int32_t NetConnService::GetGlobalHttpProxy(HttpProxy &httpProxy)
1621 {
1622     LoadGlobalHttpProxy(httpProxy);
1623     if (httpProxy.GetHost().empty()) {
1624         httpProxy.SetPort(0);
1625         NETMGR_LOG_E("The http proxy host is empty");
1626         return NETMANAGER_SUCCESS;
1627     }
1628     return NETMANAGER_SUCCESS;
1629 }
1630 
GetDefaultHttpProxy(int32_t bindNetId,HttpProxy & httpProxy)1631 int32_t NetConnService::GetDefaultHttpProxy(int32_t bindNetId, HttpProxy &httpProxy)
1632 {
1633     auto startTime = std::chrono::steady_clock::now();
1634     LoadGlobalHttpProxy(httpProxy);
1635     if (!httpProxy.GetHost().empty()) {
1636         NETMGR_LOG_I("Return global http proxy as default.");
1637         return NETMANAGER_SUCCESS;
1638     }
1639 
1640     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1641     auto iter = networks_.find(bindNetId);
1642     if ((iter != networks_.end()) && (iter->second != nullptr)) {
1643         httpProxy = iter->second->GetHttpProxy();
1644         NETMGR_LOG_I("Return bound network's http proxy as default.");
1645         return NETMANAGER_SUCCESS;
1646     }
1647 
1648     if (defaultNetSupplier_ != nullptr) {
1649         defaultNetSupplier_->GetHttpProxy(httpProxy);
1650         auto endTime = std::chrono::steady_clock::now();
1651         auto durationNs = std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime);
1652         NETMGR_LOG_D("Use default http proxy, cost=%{public}lld",  durationNs.count());
1653         return NETMANAGER_SUCCESS;
1654     }
1655     NETMGR_LOG_I("No default http proxy.");
1656     return NETMANAGER_SUCCESS;
1657 }
1658 
GetNetIdByIdentifier(const std::string & ident,std::list<int32_t> & netIdList)1659 int32_t NetConnService::GetNetIdByIdentifier(const std::string &ident, std::list<int32_t> &netIdList)
1660 {
1661     if (ident.empty()) {
1662         NETMGR_LOG_E("The identifier in service is null");
1663         return NETMANAGER_ERR_INVALID_PARAMETER;
1664     }
1665     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1666     for (auto iterSupplier : netSuppliers_) {
1667         if (iterSupplier.second == nullptr) {
1668             continue;
1669         }
1670         if (iterSupplier.second->GetNetSupplierIdent() == ident) {
1671             int32_t netId = iterSupplier.second->GetNetId();
1672             netIdList.push_back(netId);
1673         }
1674     }
1675     return NETMANAGER_SUCCESS;
1676 }
1677 
GetDumpMessage(std::string & message)1678 void NetConnService::GetDumpMessage(std::string &message)
1679 {
1680     message.append("Net connect Info:\n");
1681     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1682     if (defaultNetSupplier_) {
1683         message.append("\tSupplierId: " + std::to_string(defaultNetSupplier_->GetSupplierId()) + "\n");
1684         std::shared_ptr<Network> network = defaultNetSupplier_->GetNetwork();
1685         if (network) {
1686             message.append("\tNetId: " + std::to_string(network->GetNetId()) + "\n");
1687         } else {
1688             message.append("\tNetId: " + std::to_string(INVALID_NET_ID) + "\n");
1689         }
1690         message.append("\tConnStat: " + std::to_string(defaultNetSupplier_->IsConnected()) + "\n");
1691         message.append("\tIsAvailable: " + std::to_string(defaultNetSupplier_->IsNetValidated()) + "\n");
1692         message.append("\tIsRoaming: " + std::to_string(defaultNetSupplier_->GetRoaming()) + "\n");
1693         message.append("\tStrength: " + std::to_string(defaultNetSupplier_->GetStrength()) + "\n");
1694         message.append("\tFrequency: " + std::to_string(defaultNetSupplier_->GetFrequency()) + "\n");
1695         message.append("\tLinkUpBandwidthKbps: " +
1696                        std::to_string(defaultNetSupplier_->GetNetCapabilities().linkUpBandwidthKbps_) + "\n");
1697         message.append("\tLinkDownBandwidthKbps: " +
1698                        std::to_string(defaultNetSupplier_->GetNetCapabilities().linkDownBandwidthKbps_) + "\n");
1699         message.append("\tUid: " + std::to_string(defaultNetSupplier_->GetSupplierUid()) + "\n");
1700     } else {
1701         message.append("\tdefaultNetSupplier_ is nullptr\n");
1702         message.append("\tSupplierId: \n");
1703         message.append("\tNetId: 0\n");
1704         message.append("\tConnStat: 0\n");
1705         message.append("\tIsAvailable: \n");
1706         message.append("\tIsRoaming: 0\n");
1707         message.append("\tStrength: 0\n");
1708         message.append("\tFrequency: 0\n");
1709         message.append("\tLinkUpBandwidthKbps: 0\n");
1710         message.append("\tLinkDownBandwidthKbps: 0\n");
1711         message.append("\tUid: 0\n");
1712     }
1713     if (dnsResultCallback_ != nullptr) {
1714         dnsResultCallback_->GetDumpMessageForDnsResult(message);
1715     }
1716 }
1717 
HasDefaultNet(bool & flag)1718 int32_t NetConnService::HasDefaultNet(bool &flag)
1719 {
1720     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1721     if (!defaultNetSupplier_) {
1722         flag = false;
1723         return NETMANAGER_SUCCESS;
1724     }
1725     flag = true;
1726     return NETMANAGER_SUCCESS;
1727 }
1728 
IsDefaultNetMetered(bool & isMetered)1729 int32_t NetConnService::IsDefaultNetMetered(bool &isMetered)
1730 {
1731     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
1732     if (defaultNetSupplier_) {
1733         isMetered = !defaultNetSupplier_->HasNetCap(NET_CAPABILITY_NOT_METERED);
1734     } else {
1735         isMetered = true;
1736     }
1737     return NETMANAGER_SUCCESS;
1738 }
1739 
BindSocket(int32_t socketFd,int32_t netId)1740 int32_t NetConnService::BindSocket(int32_t socketFd, int32_t netId)
1741 {
1742     NETMGR_LOG_D("Enter BindSocket.");
1743     return NetsysController::GetInstance().BindSocket(socketFd, netId);
1744 }
1745 
Dump(int32_t fd,const std::vector<std::u16string> & args)1746 int32_t NetConnService::Dump(int32_t fd, const std::vector<std::u16string> &args)
1747 {
1748     NETMGR_LOG_D("Start Dump, fd: %{public}d", fd);
1749     std::string result;
1750     GetDumpMessage(result);
1751     int32_t ret = dprintf(fd, "%s\n", result.c_str());
1752     return (ret < 0) ? static_cast<int32_t>(NET_CONN_ERR_CREATE_DUMP_FAILED) : static_cast<int32_t>(NETMANAGER_SUCCESS);
1753 }
1754 
IsValidDecValue(const std::string & inputValue)1755 bool NetConnService::IsValidDecValue(const std::string &inputValue)
1756 {
1757     if (inputValue.length() > INPUT_VALUE_LENGTH) {
1758         NETMGR_LOG_E("The value entered is out of range, value:%{public}s", inputValue.c_str());
1759         return false;
1760     }
1761     bool isValueNumber = regex_match(inputValue, std::regex("(-[\\d+]+)|(\\d+)"));
1762     if (isValueNumber) {
1763         int64_t numberValue = std::stoll(inputValue);
1764         if ((numberValue >= INT32_MIN) && (numberValue <= INT32_MAX)) {
1765             return true;
1766         }
1767     }
1768     NETMGR_LOG_I("InputValue is not a decimal number");
1769     return false;
1770 }
1771 
GetDelayNotifyTime()1772 int32_t NetConnService::GetDelayNotifyTime()
1773 {
1774     char param[SYS_PARAMETER_SIZE] = { 0 };
1775     int32_t delayTime = 0;
1776     int32_t code = GetParameter(CFG_NETWORK_PRE_AIRPLANE_MODE_WAIT_TIMES, NO_DELAY_TIME_CONFIG,
1777                                 param, SYS_PARAMETER_SIZE);
1778     std::string time = param;
1779     if (code <= 0 || !IsValidDecValue(time)) {
1780         try {
1781             delayTime = std::stoi(NO_DELAY_TIME_CONFIG);
1782         } catch (const std::invalid_argument& e) {
1783             NETMGR_LOG_E("invalid_argument");
1784             return delayTime;
1785         } catch (const std::out_of_range& e) {
1786             NETMGR_LOG_E("out_of_range");
1787             return delayTime;
1788         }
1789     } else {
1790         try {
1791             auto tmp = std::stoi(time);
1792             delayTime = tmp > static_cast<int32_t>(MAX_DELAY_TIME) ? std::stoi(NO_DELAY_TIME_CONFIG) : tmp;
1793         } catch (const std::invalid_argument& e) {
1794             NETMGR_LOG_E("invalid_argument");
1795             return delayTime;
1796         } catch (const std::out_of_range& e) {
1797             NETMGR_LOG_E("out_of_range");
1798             return delayTime;
1799         }
1800     }
1801     NETMGR_LOG_D("delay time is %{public}d", delayTime);
1802     return delayTime;
1803 }
1804 
RegisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback)1805 int32_t NetConnService::RegisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback)
1806 {
1807     int32_t callingUid = static_cast<int32_t>(IPCSkeleton::GetCallingUid());
1808     NETMGR_LOG_D("RegisterPreAirplaneCallback, calllinguid [%{public}d]", callingUid);
1809     std::lock_guard guard(preAirplaneCbsMutex_);
1810     preAirplaneCallbacks_[callingUid] = callback;
1811     return NETMANAGER_SUCCESS;
1812 }
1813 
UnregisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback)1814 int32_t NetConnService::UnregisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback)
1815 {
1816     int32_t callingUid = static_cast<int32_t>(IPCSkeleton::GetCallingUid());
1817     NETMGR_LOG_D("UnregisterPreAirplaneCallback, calllinguid [%{public}d]", callingUid);
1818     std::lock_guard guard(preAirplaneCbsMutex_);
1819     preAirplaneCallbacks_.erase(callingUid);
1820     return NETMANAGER_SUCCESS;
1821 }
1822 
SetAirplaneMode(bool state)1823 int32_t NetConnService::SetAirplaneMode(bool state)
1824 {
1825     NETMGR_LOG_I("Enter SetAirplaneMode, AirplaneMode is %{public}d", state);
1826     if (state) {
1827         std::lock_guard guard(preAirplaneCbsMutex_);
1828         for (const auto& mem : preAirplaneCallbacks_) {
1829             if (mem.second != nullptr) {
1830                 int32_t ret = mem.second->PreAirplaneStart();
1831                 NETMGR_LOG_D("PreAirplaneStart result %{public}d", ret);
1832             }
1833         }
1834     }
1835     if (netConnEventHandler_ == nullptr) {
1836         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
1837         return NETMANAGER_ERR_LOCAL_PTR_NULL;
1838     }
1839     netConnEventHandler_->RemoveAsyncTask("delay airplane mode");
1840     auto delayTime = GetDelayNotifyTime();
1841 
1842     netConnEventHandler_->PostAsyncTask(
1843         [state]() {
1844             NETMGR_LOG_I("Enter delay");
1845             auto dataShareHelperUtils = std::make_unique<NetDataShareHelperUtils>();
1846             std::string airplaneMode = std::to_string(state);
1847             Uri uri(AIRPLANE_MODE_URI);
1848             int32_t ret = dataShareHelperUtils->Update(uri, KEY_AIRPLANE_MODE, airplaneMode);
1849             if (ret != NETMANAGER_SUCCESS) {
1850                 NETMGR_LOG_E("Update airplane mode:%{public}d to datashare failed.", state);
1851                 return;
1852             }
1853             BroadcastInfo info;
1854             info.action = EventFwk::CommonEventSupport::COMMON_EVENT_AIRPLANE_MODE_CHANGED;
1855             info.data = "Net Manager Airplane Mode Changed";
1856             info.code = static_cast<int32_t>(state);
1857             info.ordered = false;
1858             std::map<std::string, int32_t> param;
1859             BroadcastManager::GetInstance().SendBroadcast(info, param);
1860         },
1861         "delay airplane mode", delayTime);
1862     NETMGR_LOG_I("SetAirplaneMode out");
1863 
1864     return NETMANAGER_SUCCESS;
1865 }
1866 
ActiveHttpProxy()1867 void NetConnService::ActiveHttpProxy()
1868 {
1869     NETMGR_LOG_D("ActiveHttpProxy thread start");
1870     while (httpProxyThreadNeedRun_.load()) {
1871         NETMGR_LOG_D("Keep global http-proxy active every 2 minutes");
1872         CURL *curl = nullptr;
1873         HttpProxy tempProxy;
1874         {
1875             auto userInfoHelp = NetProxyUserinfo::GetInstance();
1876             LoadGlobalHttpProxy(tempProxy);
1877             userInfoHelp.GetHttpProxyHostPass(tempProxy);
1878         }
1879         auto proxyType = (tempProxy.host_.find("https://") != std::string::npos) ? CURLPROXY_HTTPS : CURLPROXY_HTTP;
1880         if (!tempProxy.host_.empty() && !tempProxy.username_.empty()) {
1881             std::string httpUrl;
1882             GetHttpUrlFromConfig(httpUrl);
1883             if (httpUrl.empty()) {
1884                 NETMGR_LOG_E("ActiveHttpProxy thread get url failed!");
1885                 continue;
1886             }
1887             curl = curl_easy_init();
1888             curl_easy_setopt(curl, CURLOPT_URL, httpUrl.c_str());
1889             curl_easy_setopt(curl, CURLOPT_PROXY, tempProxy.host_.c_str());
1890             curl_easy_setopt(curl, CURLOPT_PROXYPORT, tempProxy.port_);
1891             curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxyType);
1892             curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, tempProxy.username_.c_str());
1893             curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
1894             if (!tempProxy.password_.empty()) {
1895                 curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, tempProxy.password_.c_str());
1896             }
1897         }
1898         if (curl) {
1899             auto ret = curl_easy_perform(curl);
1900             NETMGR_LOG_I("SetGlobalHttpProxy ActiveHttpProxy %{public}d", static_cast<int>(ret));
1901             curl_easy_cleanup(curl);
1902         }
1903         if (httpProxyThreadNeedRun_.load()) {
1904             std::unique_lock lock(httpProxyThreadMutex_);
1905             httpProxyThreadCv_.wait_for(lock, std::chrono::seconds(HTTP_PROXY_ACTIVE_PERIOD_S));
1906         } else {
1907             NETMGR_LOG_W("ActiveHttpProxy has been clear.");
1908         }
1909     }
1910 }
1911 
GetHttpUrlFromConfig(std::string & httpUrl)1912 void NetConnService::GetHttpUrlFromConfig(std::string &httpUrl)
1913 {
1914     if (!std::filesystem::exists(URL_CFG_FILE)) {
1915         NETMGR_LOG_E("File not exist (%{public}s)", URL_CFG_FILE);
1916         return;
1917     }
1918 
1919     std::ifstream file(URL_CFG_FILE);
1920     if (!file.is_open()) {
1921         NETMGR_LOG_E("Open file failed (%{public}s)", strerror(errno));
1922         return;
1923     }
1924 
1925     std::ostringstream oss;
1926     oss << file.rdbuf();
1927     std::string content = oss.str();
1928     auto pos = content.find(HTTP_URL_HEADER);
1929     if (pos != std::string::npos) {
1930         pos += strlen(HTTP_URL_HEADER);
1931         httpUrl = content.substr(pos, content.find(NEW_LINE_STR, pos) - pos);
1932     }
1933     NETMGR_LOG_D("Get net detection http url:[%{public}s]", httpUrl.c_str());
1934 }
1935 
SetGlobalHttpProxy(const HttpProxy & httpProxy)1936 int32_t NetConnService::SetGlobalHttpProxy(const HttpProxy &httpProxy)
1937 {
1938     NETMGR_LOG_I("Enter SetGlobalHttpProxy. httpproxy = %{public}zu", httpProxy.GetHost().length());
1939     HttpProxy oldHttpProxy;
1940     LoadGlobalHttpProxy(oldHttpProxy);
1941     if (oldHttpProxy != httpProxy) {
1942         HttpProxy newHttpProxy = httpProxy;
1943         httpProxyThreadCv_.notify_all();
1944         int32_t userId;
1945         int32_t ret = GetCallingUserId(userId);
1946         if (ret != NETMANAGER_SUCCESS) {
1947             NETMGR_LOG_E("GlobalHttpProxy get calling userId fail.");
1948             return ret;
1949         }
1950         NETMGR_LOG_I("GlobalHttpProxy userId is %{public}d", userId);
1951         NetHttpProxyTracker httpProxyTracker;
1952         if (IsPrimaryUserId(userId)) {
1953             if (!httpProxyTracker.WriteToSettingsData(newHttpProxy)) {
1954                 NETMGR_LOG_E("GlobalHttpProxy write settingDate fail.");
1955                 return NETMANAGER_ERR_INTERNAL;
1956             }
1957         }
1958         if (!httpProxyTracker.WriteToSettingsDataUser(newHttpProxy, userId)) {
1959             NETMGR_LOG_E("GlobalHttpProxy write settingDateUser fail. userId=%{public}d", userId);
1960             return NETMANAGER_ERR_INTERNAL;
1961         }
1962         globalHttpProxyCache_.EnsureInsert(userId, newHttpProxy);
1963         SendHttpProxyChangeBroadcast(newHttpProxy);
1964         UpdateGlobalHttpProxy(newHttpProxy);
1965     }
1966     if (!httpProxyThreadNeedRun_ && !httpProxy.GetUsername().empty()) {
1967         NETMGR_LOG_I("ActiveHttpProxy  user.len[%{public}zu], pwd.len[%{public}zu]", httpProxy.username_.length(),
1968                      httpProxy.password_.length());
1969         httpProxyThreadNeedRun_ = true;
1970         std::thread t([this]() { ActiveHttpProxy(); });
1971         std::string threadName = "ActiveHttpProxy";
1972         pthread_setname_np(t.native_handle(), threadName.c_str());
1973         t.detach();
1974     } else if (httpProxyThreadNeedRun_ && httpProxy.GetHost().empty()) {
1975         httpProxyThreadNeedRun_ = false;
1976     }
1977     NETMGR_LOG_I("End SetGlobalHttpProxy.");
1978     return NETMANAGER_SUCCESS;
1979 }
1980 
GetCallingUserId(int32_t & userId)1981 int32_t NetConnService::GetCallingUserId(int32_t &userId)
1982 {
1983     std::vector<int> activeIds;
1984     int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds);
1985     if (ret != 0) {
1986         NETMGR_LOG_E("QueryActiveOsAccountIds failed. ret is %{public}d", ret);
1987         return NETMANAGER_ERR_INTERNAL;
1988     }
1989     if (activeIds.empty()) {
1990         NETMGR_LOG_E("QueryActiveOsAccountIds is empty");
1991         return NETMANAGER_ERR_INTERNAL;
1992     }
1993     userId = activeIds[0];
1994     return NETMANAGER_SUCCESS;
1995 }
1996 
SetAppNet(int32_t netId)1997 int32_t NetConnService::SetAppNet(int32_t netId)
1998 {
1999     return NETMANAGER_SUCCESS;
2000 }
2001 
RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)2002 int32_t NetConnService::RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback)
2003 {
2004     if (callback == nullptr) {
2005         NETMGR_LOG_E("callback is nullptr");
2006         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2007     }
2008     NETMGR_LOG_I("Enter RegisterNetInterfaceCallback.");
2009     if (interfaceStateCallback_ == nullptr) {
2010         NETMGR_LOG_E("interfaceStateCallback_ is nullptr");
2011         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2012     }
2013     return interfaceStateCallback_->RegisterInterfaceCallback(callback);
2014 }
2015 
GetNetInterfaceConfiguration(const std::string & iface,NetInterfaceConfiguration & config)2016 int32_t NetConnService::GetNetInterfaceConfiguration(const std::string &iface, NetInterfaceConfiguration &config)
2017 {
2018     using namespace OHOS::nmd;
2019     InterfaceConfigurationParcel configParcel;
2020     configParcel.ifName = iface;
2021     if (NetsysController::GetInstance().GetInterfaceConfig(configParcel) != NETMANAGER_SUCCESS) {
2022         return NETMANAGER_ERR_INTERNAL;
2023     }
2024     config.ifName_ = configParcel.ifName;
2025     config.hwAddr_ = configParcel.hwAddr;
2026     config.ipv4Addr_ = configParcel.ipv4Addr;
2027     config.prefixLength_ = configParcel.prefixLength;
2028     config.flags_.assign(configParcel.flags.begin(), configParcel.flags.end());
2029     return NETMANAGER_SUCCESS;
2030 }
2031 
NetDetectionForDnsHealth(int32_t netId,bool dnsHealthSuccess)2032 int32_t NetConnService::NetDetectionForDnsHealth(int32_t netId, bool dnsHealthSuccess)
2033 {
2034     int32_t result = NETMANAGER_ERROR;
2035     if (netConnEventHandler_) {
2036         netConnEventHandler_->PostSyncTask([netId, dnsHealthSuccess, &result, this]() {
2037             result = this->NetDetectionForDnsHealthSync(netId, dnsHealthSuccess);
2038         });
2039     }
2040     return result;
2041 }
2042 
LoadGlobalHttpProxy(HttpProxy & httpProxy)2043 void NetConnService::LoadGlobalHttpProxy(HttpProxy &httpProxy)
2044 {
2045     int32_t userId;
2046     int32_t ret = GetCallingUserId(userId);
2047     if (ret != NETMANAGER_SUCCESS) {
2048         NETMGR_LOG_E("LoadGlobalHttpProxy get calling userId fail.");
2049         return;
2050     }
2051     if (globalHttpProxyCache_.Find(userId, httpProxy)) {
2052         NETMGR_LOG_D("Global http proxy has been loaded from the SettingsData database. userId=%{public}d", userId);
2053         return;
2054     }
2055     if (!isDataShareReady_.load() && !CheckIfSettingsDataReady()) {
2056         NETMGR_LOG_E("data share is not ready.");
2057         return;
2058     }
2059     NetHttpProxyTracker httpProxyTracker;
2060     HttpProxy tmpHttpProxy;
2061     if (IsPrimaryUserId(userId)) {
2062         httpProxyTracker.ReadFromSettingsData(tmpHttpProxy);
2063     } else {
2064         httpProxyTracker.ReadFromSettingsDataUser(tmpHttpProxy, userId);
2065     }
2066     {
2067         std::lock_guard guard(globalHttpProxyMutex_);
2068         httpProxy = tmpHttpProxy;
2069     }
2070     globalHttpProxyCache_.EnsureInsert(userId, tmpHttpProxy);
2071 }
2072 
UpdateGlobalHttpProxy(const HttpProxy & httpProxy)2073 void NetConnService::UpdateGlobalHttpProxy(const HttpProxy &httpProxy)
2074 {
2075     if (netConnEventHandler_ == nullptr) {
2076         NETMGR_LOG_E("netConnEventHandler_ is nullptr.");
2077         return;
2078     }
2079     NETMGR_LOG_I("UpdateGlobalHttpProxy start");
2080     netConnEventHandler_->PostAsyncTask([this, httpProxy]() {
2081         for (const auto &supplier : netSuppliers_) {
2082             if (supplier.second == nullptr) {
2083                 continue;
2084             }
2085             supplier.second->UpdateGlobalHttpProxy(httpProxy);
2086         }
2087         NETMGR_LOG_I("UpdateGlobalHttpProxy end");
2088     });
2089 }
2090 
OnInterfaceAddressUpdated(const std::string & addr,const std::string & ifName,int flags,int scope)2091 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAddressUpdated(const std::string &addr,
2092                                                                              const std::string &ifName, int flags,
2093                                                                              int scope)
2094 {
2095     std::lock_guard<std::mutex> locker(mutex_);
2096     for (const auto &callback : ifaceStateCallbacks_) {
2097         if (callback == nullptr) {
2098             NETMGR_LOG_E("callback is null");
2099             continue;
2100         }
2101         callback->OnInterfaceAddressUpdated(addr, ifName, flags, scope);
2102     }
2103     return NETMANAGER_SUCCESS;
2104 }
2105 
OnInterfaceAddressRemoved(const std::string & addr,const std::string & ifName,int flags,int scope)2106 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAddressRemoved(const std::string &addr,
2107                                                                              const std::string &ifName, int flags,
2108                                                                              int scope)
2109 {
2110     std::lock_guard<std::mutex> locker(mutex_);
2111     for (const auto &callback : ifaceStateCallbacks_) {
2112         if (callback == nullptr) {
2113             NETMGR_LOG_E("callback is null");
2114             continue;
2115         }
2116         callback->OnInterfaceAddressRemoved(addr, ifName, flags, scope);
2117     }
2118     return NETMANAGER_SUCCESS;
2119 }
2120 
OnInterfaceAdded(const std::string & iface)2121 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceAdded(const std::string &iface)
2122 {
2123     std::lock_guard<std::mutex> locker(mutex_);
2124     for (const auto &callback : ifaceStateCallbacks_) {
2125         if (callback == nullptr) {
2126             NETMGR_LOG_E("callback is null");
2127             continue;
2128         }
2129         callback->OnInterfaceAdded(iface);
2130     }
2131     return NETMANAGER_SUCCESS;
2132 }
2133 
OnInterfaceRemoved(const std::string & iface)2134 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceRemoved(const std::string &iface)
2135 {
2136     std::lock_guard<std::mutex> locker(mutex_);
2137     for (const auto &callback : ifaceStateCallbacks_) {
2138         if (callback == nullptr) {
2139             NETMGR_LOG_E("callback is null");
2140             continue;
2141         }
2142         callback->OnInterfaceRemoved(iface);
2143     }
2144     return NETMANAGER_SUCCESS;
2145 }
2146 
OnInterfaceChanged(const std::string & iface,bool up)2147 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceChanged(const std::string &iface, bool up)
2148 {
2149     std::lock_guard<std::mutex> locker(mutex_);
2150     for (const auto &callback : ifaceStateCallbacks_) {
2151         if (callback == nullptr) {
2152             NETMGR_LOG_E("callback is null");
2153             continue;
2154         }
2155         callback->OnInterfaceChanged(iface, up);
2156     }
2157     return NETMANAGER_SUCCESS;
2158 }
2159 
OnInterfaceLinkStateChanged(const std::string & iface,bool up)2160 int32_t NetConnService::NetInterfaceStateCallback::OnInterfaceLinkStateChanged(const std::string &iface, bool up)
2161 {
2162     std::lock_guard<std::mutex> locker(mutex_);
2163     for (const auto &callback : ifaceStateCallbacks_) {
2164         if (callback == nullptr) {
2165             NETMGR_LOG_E("callback is null");
2166             continue;
2167         }
2168         callback->OnInterfaceLinkStateChanged(iface, up);
2169     }
2170     return NETMANAGER_SUCCESS;
2171 }
2172 
OnRouteChanged(bool updated,const std::string & route,const std::string & gateway,const std::string & ifName)2173 int32_t NetConnService::NetInterfaceStateCallback::OnRouteChanged(bool updated, const std::string &route,
2174                                                                   const std::string &gateway, const std::string &ifName)
2175 {
2176     return NETMANAGER_SUCCESS;
2177 }
2178 
OnDhcpSuccess(NetsysControllerCallback::DhcpResult & dhcpResult)2179 int32_t NetConnService::NetInterfaceStateCallback::OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult)
2180 {
2181     return NETMANAGER_SUCCESS;
2182 }
2183 
OnBandwidthReachedLimit(const std::string & limitName,const std::string & iface)2184 int32_t NetConnService::NetInterfaceStateCallback::OnBandwidthReachedLimit(const std::string &limitName,
2185                                                                            const std::string &iface)
2186 {
2187     return NETMANAGER_SUCCESS;
2188 }
2189 
RegisterInterfaceCallback(const sptr<INetInterfaceStateCallback> & callback)2190 int32_t NetConnService::NetInterfaceStateCallback::RegisterInterfaceCallback(
2191     const sptr<INetInterfaceStateCallback> &callback)
2192 {
2193     if (callback == nullptr) {
2194         NETMGR_LOG_E("callback is null");
2195         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2196     }
2197 
2198     std::lock_guard<std::mutex> locker(mutex_);
2199     for (const auto &iter : ifaceStateCallbacks_) {
2200         if (!iter) {
2201             continue;
2202         }
2203         if (iter->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
2204             NETMGR_LOG_E("RegisterInterfaceCallback find same callback");
2205             return NET_CONN_ERR_SAME_CALLBACK;
2206         }
2207     }
2208     ifaceStateCallbacks_.push_back(callback);
2209     return NETMANAGER_SUCCESS;
2210 }
2211 
AddNetworkRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)2212 int32_t NetConnService::AddNetworkRoute(int32_t netId, const std::string &ifName,
2213                                         const std::string &destination, const std::string &nextHop)
2214 {
2215     return NetsysController::GetInstance().NetworkAddRoute(netId, ifName, destination, nextHop);
2216 }
2217 
RemoveNetworkRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)2218 int32_t NetConnService::RemoveNetworkRoute(int32_t netId, const std::string &ifName,
2219                                            const std::string &destination, const std::string &nextHop)
2220 {
2221     return NetsysController::GetInstance().NetworkRemoveRoute(netId, ifName, destination, nextHop);
2222 }
2223 
AddInterfaceAddress(const std::string & ifName,const std::string & ipAddr,int32_t prefixLength)2224 int32_t NetConnService::AddInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
2225                                             int32_t prefixLength)
2226 {
2227     return NetsysController::GetInstance().AddInterfaceAddress(ifName, ipAddr, prefixLength);
2228 }
2229 
DelInterfaceAddress(const std::string & ifName,const std::string & ipAddr,int32_t prefixLength)2230 int32_t NetConnService::DelInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
2231                                             int32_t prefixLength)
2232 {
2233     return NetsysController::GetInstance().DelInterfaceAddress(ifName, ipAddr, prefixLength);
2234 }
2235 
AddStaticArp(const std::string & ipAddr,const std::string & macAddr,const std::string & ifName)2236 int32_t NetConnService::AddStaticArp(const std::string &ipAddr, const std::string &macAddr,
2237                                      const std::string &ifName)
2238 {
2239     return NetsysController::GetInstance().AddStaticArp(ipAddr, macAddr, ifName);
2240 }
2241 
DelStaticArp(const std::string & ipAddr,const std::string & macAddr,const std::string & ifName)2242 int32_t NetConnService::DelStaticArp(const std::string &ipAddr, const std::string &macAddr,
2243                                      const std::string &ifName)
2244 {
2245     return NetsysController::GetInstance().DelStaticArp(ipAddr, macAddr, ifName);
2246 }
2247 
RegisterSlotType(uint32_t supplierId,int32_t type)2248 int32_t NetConnService::RegisterSlotType(uint32_t supplierId, int32_t type)
2249 {
2250     int32_t result = NETMANAGER_SUCCESS;
2251     if (netConnEventHandler_) {
2252         netConnEventHandler_->PostSyncTask([this, supplierId, type, &result]() {
2253             if (netSuppliers_.find(supplierId) == netSuppliers_.end()) {
2254                 NETMGR_LOG_E("supplierId[%{public}d] is not exits", supplierId);
2255                 result =  NETMANAGER_ERR_INVALID_PARAMETER;
2256             } else {
2257                 NETMGR_LOG_I("supplierId[%{public}d] update type[%{public}d].", supplierId, type);
2258                 sptr<NetSupplier> supplier = netSuppliers_[supplierId];
2259                 supplier->SetSupplierType(type);
2260                 result =  NETMANAGER_SUCCESS;
2261             }
2262         });
2263     }
2264     return result;
2265 }
2266 
GetSlotType(std::string & type)2267 int32_t NetConnService::GetSlotType(std::string &type)
2268 {
2269     int32_t result = NETMANAGER_SUCCESS;
2270     if (netConnEventHandler_) {
2271         netConnEventHandler_->PostSyncTask([this, &type, &result]() {
2272             if (defaultNetSupplier_ == nullptr) {
2273                 NETMGR_LOG_E("supplier is nullptr");
2274                 result =  NETMANAGER_ERR_LOCAL_PTR_NULL;
2275             } else {
2276                 type = defaultNetSupplier_->GetSupplierType();
2277                 result =  NETMANAGER_SUCCESS;
2278             }
2279         });
2280     }
2281     return result;
2282 }
2283 
FactoryResetNetwork()2284 int32_t NetConnService::FactoryResetNetwork()
2285 {
2286     NETMGR_LOG_I("Enter FactoryResetNetwork.");
2287 
2288     SetAirplaneMode(false);
2289 
2290     if (netFactoryResetCallback_ == nullptr) {
2291         NETMGR_LOG_E("netFactoryResetCallback_ is nullptr");
2292         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2293     }
2294     netFactoryResetCallback_->NotifyNetFactoryResetAsync();
2295 
2296     NETMGR_LOG_I("End FactoryResetNetwork.");
2297     return NETMANAGER_SUCCESS;
2298 }
2299 
RegisterNetFactoryResetCallback(const sptr<INetFactoryResetCallback> & callback)2300 int32_t NetConnService::RegisterNetFactoryResetCallback(const sptr<INetFactoryResetCallback> &callback)
2301 {
2302     if (callback == nullptr) {
2303         NETMGR_LOG_E("callback is nullptr");
2304         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2305     }
2306     NETMGR_LOG_I("Enter RegisterNetFactoryResetCallback.");
2307     if (netFactoryResetCallback_ == nullptr) {
2308         NETMGR_LOG_E("netFactoryResetCallback_ is nullptr");
2309         return NETMANAGER_ERR_LOCAL_PTR_NULL;
2310     }
2311     return netFactoryResetCallback_->RegisterNetFactoryResetCallbackAsync(callback);
2312 }
2313 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2314 void NetConnService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
2315 {
2316     NETMGR_LOG_I("OnAddSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
2317     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
2318         if (hasSARemoved_) {
2319             OnNetSysRestart();
2320             hasSARemoved_ = false;
2321         }
2322     } else if (systemAbilityId == ACCESS_TOKEN_MANAGER_SERVICE_ID) {
2323         if (!registerToService_) {
2324             if (!Publish(NetConnService::GetInstance().get())) {
2325                 NETMGR_LOG_E("Register to sa manager failed");
2326             }
2327             registerToService_ = true;
2328         }
2329     }
2330 }
2331 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2332 void NetConnService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
2333 {
2334     NETMGR_LOG_I("OnRemoveSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
2335     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
2336         hasSARemoved_ = true;
2337     }
2338 }
2339 
SubscribeCommonEvent(const std::string & eventName,EventReceiver receiver)2340 void NetConnService::SubscribeCommonEvent(const std::string &eventName, EventReceiver receiver)
2341 {
2342     NETMGR_LOG_I("eventName=%{public}s", eventName.c_str());
2343     EventFwk::MatchingSkills matchingSkills;
2344     matchingSkills.AddEvent(eventName);
2345     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
2346 
2347     auto subscriberPtr = std::make_shared<NetConnListener>(subscribeInfo, receiver);
2348     if (subscriberPtr == nullptr) {
2349         NETMGR_LOG_E("subscriberPtr is nullptr");
2350         return;
2351     }
2352     EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberPtr);
2353 }
2354 
OnReceiveEvent(const EventFwk::CommonEventData & data)2355 void NetConnService::OnReceiveEvent(const EventFwk::CommonEventData &data)
2356 {
2357     auto const &want = data.GetWant();
2358     std::string action = want.GetAction();
2359     if (action == "usual.event.DATA_SHARE_READY") {
2360         NETMGR_LOG_I("on receive data_share ready.");
2361         isDataShareReady_ = true;
2362         HttpProxy httpProxy;
2363         LoadGlobalHttpProxy(httpProxy);
2364         UpdateGlobalHttpProxy(httpProxy);
2365     }
2366 }
2367 
IsSupplierMatchRequestAndNetwork(sptr<NetSupplier> ns)2368 bool NetConnService::IsSupplierMatchRequestAndNetwork(sptr<NetSupplier> ns)
2369 {
2370     if (ns == nullptr) {
2371         NETMGR_LOG_E("supplier is nullptr");
2372         return false;
2373     }
2374     NET_ACTIVATE_MAP::iterator iterActive;
2375     for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) {
2376         if (!iterActive->second) {
2377             continue;
2378         }
2379         if (iterActive->second->MatchRequestAndNetwork(ns)) {
2380             return true;
2381         }
2382     }
2383 
2384     return false;
2385 }
2386 
OnNetSysRestart()2387 void NetConnService::OnNetSysRestart()
2388 {
2389     NETMGR_LOG_I("OnNetSysRestart");
2390 
2391     NET_SUPPLIER_MAP::iterator iter;
2392     for (iter = netSuppliers_.begin(); iter != netSuppliers_.end(); ++iter) {
2393         if (iter->second == nullptr) {
2394             continue;
2395         }
2396 
2397         NETMGR_LOG_D("supplier info, supplier[%{public}d, %{public}s], realScore[%{public}d], isConnected[%{public}d]",
2398             iter->second->GetSupplierId(), iter->second->GetNetSupplierIdent().c_str(),
2399             iter->second->GetRealScore(), iter->second->IsConnected());
2400 
2401         if ((!iter->second->IsConnected()) || (!IsSupplierMatchRequestAndNetwork(iter->second))) {
2402             NETMGR_LOG_D("Supplier[%{public}d] is not connected or not match request.", iter->second->GetSupplierId());
2403             continue;
2404         }
2405 
2406         iter->second->ResumeNetworkInfo();
2407     }
2408     std::unique_lock<std::recursive_mutex> locker(netManagerMutex_);
2409     if (defaultNetSupplier_ != nullptr) {
2410         defaultNetSupplier_->ClearDefault();
2411         defaultNetSupplier_ = nullptr;
2412     }
2413     locker.unlock();
2414     FindBestNetworkForAllRequest();
2415 }
2416 
IsPreferCellularUrl(const std::string & url,bool & preferCellular)2417 int32_t NetConnService::IsPreferCellularUrl(const std::string& url, bool& preferCellular)
2418 {
2419     static std::vector<std::string> preferredUrlList = GetPreferredUrl();
2420     preferCellular = std::any_of(preferredUrlList.begin(), preferredUrlList.end(),
2421                                  [&url](const std::string &str) { return url.find(str) != std::string::npos; });
2422     return 0;
2423 }
2424 
IsAddrInOtherNetwork(const std::string & ifaceName,int32_t netId,const INetAddr & netAddr)2425 bool NetConnService::IsAddrInOtherNetwork(const std::string &ifaceName, int32_t netId, const INetAddr &netAddr)
2426 {
2427     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2428     for (const auto &network : networks_) {
2429         if (network.second->GetNetId() == netId) {
2430             continue;
2431         }
2432         if (network.second->GetIfaceName() != ifaceName) {
2433             continue;
2434         }
2435         if (network.second->GetNetLinkInfo().HasNetAddr(netAddr)) {
2436             return true;
2437         }
2438     }
2439     return false;
2440 }
2441 
IsIfaceNameInUse(const std::string & ifaceName,int32_t netId)2442 bool NetConnService::IsIfaceNameInUse(const std::string &ifaceName, int32_t netId)
2443 {
2444     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2445     for (const auto &netSupplier : netSuppliers_) {
2446         if (netSupplier.second->GetNetwork()->GetNetId() == netId) {
2447             continue;
2448         }
2449         if (!netSupplier.second->IsAvailable()) {
2450             continue;
2451         }
2452         if (netSupplier.second->GetNetwork()->GetIfaceName() == ifaceName) {
2453             return true;
2454         }
2455     }
2456     return false;
2457 }
2458 
GetNetCapabilitiesAsString(const uint32_t supplierId)2459 std::string NetConnService::GetNetCapabilitiesAsString(const uint32_t supplierId)
2460 {
2461     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2462     const auto iterNetSuppliers = netSuppliers_.find(supplierId);
2463     if (iterNetSuppliers != netSuppliers_.end() && iterNetSuppliers->second != nullptr) {
2464         return iterNetSuppliers->second->GetNetCapabilities().ToString(" ");
2465     }
2466     return {};
2467 }
2468 
GetPreferredUrl()2469 std::vector<std::string> NetConnService::GetPreferredUrl()
2470 {
2471     std::vector<std::string> preferCellularUrlList;
2472     const std::string preferCellularUrlPath = "/system/etc/prefer_cellular_url_list.txt";
2473     std::ifstream preferCellularFile(preferCellularUrlPath);
2474     if (preferCellularFile.is_open()) {
2475         std::string line;
2476         while (getline(preferCellularFile, line)) {
2477             preferCellularUrlList.push_back(line);
2478         }
2479         preferCellularFile.close();
2480     } else {
2481         NETMGR_LOG_E("open prefer cellular url file failure.");
2482     }
2483     return preferCellularUrlList;
2484 }
2485 
OnRemoteDied(const wptr<IRemoteObject> & remoteObject)2486 void NetConnService::OnRemoteDied(const wptr<IRemoteObject> &remoteObject)
2487 {
2488     sptr<IRemoteObject> diedRemoted = remoteObject.promote();
2489     if (diedRemoted == nullptr) {
2490         NETMGR_LOG_E("diedRemoted is null");
2491         return;
2492     }
2493     uint32_t callingUid = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
2494     NETMGR_LOG_I("OnRemoteDied, callingUid=%{public}u", callingUid);
2495     sptr<INetConnCallback> callback = iface_cast<INetConnCallback>(diedRemoted);
2496     UnregisterNetConnCallback(callback);
2497 }
2498 
RemoveClientDeathRecipient(const sptr<INetConnCallback> & callback)2499 void NetConnService::RemoveClientDeathRecipient(const sptr<INetConnCallback> &callback)
2500 {
2501     std::lock_guard<std::mutex> autoLock(remoteMutex_);
2502     auto iter =
2503         std::find_if(remoteCallback_.cbegin(), remoteCallback_.cend(), [&callback](const sptr<INetConnCallback> &item) {
2504             return item->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr();
2505         });
2506     if (iter == remoteCallback_.cend()) {
2507         return;
2508     }
2509     callback->AsObject()->RemoveDeathRecipient(deathRecipient_);
2510     remoteCallback_.erase(iter);
2511 }
2512 
AddClientDeathRecipient(const sptr<INetConnCallback> & callback)2513 void NetConnService::AddClientDeathRecipient(const sptr<INetConnCallback> &callback)
2514 {
2515     std::lock_guard<std::mutex> autoLock(remoteMutex_);
2516     if (deathRecipient_ == nullptr) {
2517         deathRecipient_ = new (std::nothrow) ConnCallbackDeathRecipient(*this);
2518     }
2519     if (deathRecipient_ == nullptr) {
2520         NETMGR_LOG_E("deathRecipient is null");
2521         return;
2522     }
2523     if (!callback->AsObject()->AddDeathRecipient(deathRecipient_)) {
2524         NETMGR_LOG_E("AddClientDeathRecipient failed");
2525         return;
2526     }
2527     auto iter =
2528         std::find_if(remoteCallback_.cbegin(), remoteCallback_.cend(), [&callback](const sptr<INetConnCallback> &item) {
2529             return item->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr();
2530         });
2531     if (iter == remoteCallback_.cend()) {
2532         remoteCallback_.emplace_back(callback);
2533     }
2534 }
2535 
RemoveALLClientDeathRecipient()2536 void NetConnService::RemoveALLClientDeathRecipient()
2537 {
2538     std::lock_guard<std::mutex> autoLock(remoteMutex_);
2539     for (auto &item : remoteCallback_) {
2540         item->AsObject()->RemoveDeathRecipient(deathRecipient_);
2541     }
2542     remoteCallback_.clear();
2543     deathRecipient_ = nullptr;
2544 }
2545 
FindSupplierWithInternetByBearerType(NetBearType bearerType)2546 std::vector<sptr<NetSupplier>> NetConnService::FindSupplierWithInternetByBearerType(NetBearType bearerType)
2547 {
2548     std::vector<sptr<NetSupplier>> result;
2549     NET_SUPPLIER_MAP::iterator iterSupplier;
2550     std::lock_guard<std::recursive_mutex> locker(netManagerMutex_);
2551     for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) {
2552         if (iterSupplier->second == nullptr) {
2553             continue;
2554         }
2555         if (!iterSupplier->second->GetNetCaps().HasNetCap(NET_CAPABILITY_INTERNET)) {
2556             continue;
2557         }
2558         std::set<NetBearType>::iterator iter = iterSupplier->second->GetNetCapabilities().bearerTypes_.find(bearerType);
2559         if (iter != iterSupplier->second->GetNetCapabilities().bearerTypes_.end()) {
2560             NETMGR_LOG_I("found supplierId[%{public}d] by bearertype[%{public}d].", iterSupplier->first, bearerType);
2561             result.push_back(iterSupplier->second);
2562         }
2563     }
2564     return result;
2565 }
2566 
UpdateSupplierScore(NetBearType bearerType,uint32_t detectionStatus,uint32_t & supplierId)2567 int32_t NetConnService::UpdateSupplierScore(NetBearType bearerType, uint32_t detectionStatus, uint32_t& supplierId)
2568 {
2569     int32_t result = NETMANAGER_ERROR;
2570     if (netConnEventHandler_) {
2571         netConnEventHandler_->PostSyncTask([this, bearerType, detectionStatus, &supplierId, &result]() {
2572             result = this->UpdateSupplierScoreAsync(bearerType, detectionStatus, supplierId);
2573         });
2574     }
2575     return result;
2576 }
2577 
UpdateSupplierScoreAsync(NetBearType bearerType,uint32_t detectionStatus,uint32_t & supplierId)2578 int32_t NetConnService::UpdateSupplierScoreAsync(NetBearType bearerType, uint32_t detectionStatus, uint32_t& supplierId)
2579 {
2580     NETMGR_LOG_I("update supplier score by type[%{public}d], detectionStatus[%{public}d], supplierId:%{public}d",
2581         bearerType, detectionStatus, supplierId);
2582     NetDetectionStatus state = static_cast<NetDetectionStatus>(detectionStatus);
2583     if (state == QUALITY_POOR_STATE) {
2584         // In poor network, supplierId should be an output parameter.
2585         std::vector<sptr<NetSupplier>> suppliers = FindSupplierWithInternetByBearerType(bearerType);
2586         if (suppliers.empty()) {
2587             NETMGR_LOG_E(" not found supplierId by bearertype[%{public}d].", bearerType);
2588             return NETMANAGER_ERR_INVALID_PARAMETER;
2589         }
2590         uint32_t tmpSupplierId = FindSupplierToReduceScore(suppliers, supplierId);
2591         if (tmpSupplierId == INVALID_SUPPLIER_ID) {
2592             NETMGR_LOG_E("not found supplierId, default supplier id[%{public}d], netId:[%{public}d]",
2593                          defaultNetSupplier_->GetSupplierId(), defaultNetSupplier_->GetNetId());
2594             return NETMANAGER_ERR_INVALID_PARAMETER;
2595         }
2596     }
2597     // Check supplier exist by supplierId, and check supplier's type equals to bearerType.
2598     auto supplier = FindNetSupplier(supplierId);
2599     if (supplier == nullptr || supplier->GetNetSupplierType() != bearerType) {
2600         NETMGR_LOG_E("supplier doesn't exist.");
2601         return NETMANAGER_ERR_INVALID_PARAMETER;
2602     }
2603     supplier->SetNetValid(state);
2604     // Find best network because supplier score changed.
2605     FindBestNetworkForAllRequest();
2606     // Tell other suppliers to enable if current default supplier is not better than others.
2607     if (defaultNetSupplier_ && defaultNetSupplier_->GetSupplierId() == supplierId) {
2608         RequestAllNetworkExceptDefault();
2609     }
2610     return NETMANAGER_SUCCESS;
2611 }
2612 
FindSupplierToReduceScore(std::vector<sptr<NetSupplier>> & suppliers,uint32_t & supplierId)2613 uint32_t NetConnService::FindSupplierToReduceScore(std::vector<sptr<NetSupplier>>& suppliers, uint32_t& supplierId)
2614 {
2615     uint32_t ret = INVALID_SUPPLIER_ID;
2616     if (!defaultNetSupplier_) {
2617         NETMGR_LOG_E("default net supplier nullptr");
2618         return ret;
2619     }
2620     std::vector<sptr<NetSupplier>>::iterator iter;
2621     for (iter = suppliers.begin(); iter != suppliers.end(); ++iter) {
2622         if (defaultNetSupplier_->GetNetId() == (*iter)->GetNetId()) {
2623             ret = (*iter)->GetSupplierId();
2624             supplierId = ret;
2625             break;
2626         }
2627     }
2628     return ret;
2629 }
2630 
NetConnListener(const EventFwk::CommonEventSubscribeInfo & subscribeInfo,EventReceiver receiver)2631 NetConnService::NetConnListener::NetConnListener(const EventFwk::CommonEventSubscribeInfo &subscribeInfo,
2632     EventReceiver receiver) : EventFwk::CommonEventSubscriber(subscribeInfo), eventReceiver_(receiver) {}
2633 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)2634 void NetConnService::NetConnListener::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
2635 {
2636     if (eventReceiver_ == nullptr) {
2637         NETMGR_LOG_E("eventReceiver is nullptr");
2638         return;
2639     }
2640     NETMGR_LOG_I("NetConnListener::OnReceiveEvent(), event:[%{public}s], data:[%{public}s], code:[%{public}d]",
2641                  eventData.GetWant().GetAction().c_str(), eventData.GetData().c_str(), eventData.GetCode());
2642     eventReceiver_(eventData);
2643 }
2644 
EnableVnicNetwork(const sptr<NetLinkInfo> & netLinkInfo,const std::set<int32_t> & uids)2645 int32_t NetConnService::EnableVnicNetwork(const sptr<NetLinkInfo> &netLinkInfo, const std::set<int32_t> &uids)
2646 {
2647     int32_t result = NETMANAGER_ERROR;
2648     if (netConnEventHandler_) {
2649         netConnEventHandler_->PostSyncTask(
2650             [this, &netLinkInfo, &uids, &result]() { result = this->EnableVnicNetworkAsync(netLinkInfo, uids); });
2651     }
2652     return result;
2653 }
2654 
EnableVnicNetworkAsync(const sptr<NetLinkInfo> & netLinkInfo,const std::set<int32_t> & uids)2655 int32_t NetConnService::EnableVnicNetworkAsync(const sptr<NetLinkInfo> &netLinkInfo, const std::set<int32_t> &uids)
2656 {
2657     NETMGR_LOG_I("enable vnic network");
2658 
2659     if (vnicCreated.load()) {
2660         NETMGR_LOG_E("Enable Vnic Network already");
2661         return NET_CONN_ERR_INVALID_NETWORK;
2662     }
2663 
2664     uint16_t mtu = netLinkInfo->mtu_;
2665     if (netLinkInfo->netAddrList_.empty()) {
2666         NETMGR_LOG_E("the netLinkInfo netAddrList is empty");
2667         return NET_CONN_ERR_INVALID_NETWORK;
2668     }
2669 
2670     const std::string &tunAddr = netLinkInfo->netAddrList_.front().address_;
2671     int32_t prefix = netLinkInfo->netAddrList_.front().prefixlen_;
2672     if (!CommonUtils::IsValidIPV4(tunAddr)) {
2673         NETMGR_LOG_E("the netLinkInfo tunAddr is not valid");
2674         return NET_CONN_ERR_INVALID_NETWORK;
2675     }
2676 
2677     NETMGR_LOG_I("EnableVnicNetwork tunAddr:[%{public}s], prefix:[%{public}d]", tunAddr.c_str(), prefix);
2678     if (NetsysController::GetInstance().CreateVnic(mtu, tunAddr, prefix, uids) != NETMANAGER_SUCCESS) {
2679         NETMGR_LOG_E("EnableVnicNetwork CreateVnic failed");
2680         return NETMANAGER_ERR_OPERATION_FAILED;
2681     }
2682 
2683     vnicCreated = true;
2684     return NETMANAGER_SUCCESS;
2685 }
2686 
DisableVnicNetwork()2687 int32_t NetConnService::DisableVnicNetwork()
2688 {
2689     int32_t result = NETMANAGER_ERROR;
2690     if (netConnEventHandler_) {
2691         netConnEventHandler_->PostSyncTask(
2692             [this, &result]() { result = this->DisableVnicNetworkAsync(); });
2693     }
2694     return result;
2695 }
2696 
DisableVnicNetworkAsync()2697 int32_t NetConnService::DisableVnicNetworkAsync()
2698 {
2699     NETMGR_LOG_I("del internal virtual network");
2700 
2701     if (!vnicCreated.load()) {
2702         NETMGR_LOG_E("cannot find vnic network");
2703         return NET_CONN_ERR_INVALID_NETWORK;
2704     }
2705 
2706     if (NetsysController::GetInstance().DestroyVnic() != NETMANAGER_SUCCESS) {
2707         return NETMANAGER_ERR_OPERATION_FAILED;
2708     }
2709     vnicCreated = false;
2710     return NETMANAGER_SUCCESS;
2711 }
2712 } // namespace NetManagerStandard
2713 } // namespace OHOS
2714