• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "net_policy_service.h"
17 
18 #include <algorithm>
19 #include <dlfcn.h>
20 
21 #include "system_ability_definition.h"
22 
23 #include "bundle_constants.h"
24 #include "bundle_mgr_proxy.h"
25 #include "ffrt_inner.h"
26 #include "iservice_registry.h"
27 #include "net_access_policy_config.h"
28 #include "net_manager_center.h"
29 #include "net_manager_constants.h"
30 #include "net_mgr_log_wrapper.h"
31 #include "net_policy_base.h"
32 #include "net_policy_constants.h"
33 #include "net_policy_core.h"
34 #include "net_policy_file.h"
35 #include "net_policy_inner_define.h"
36 #include "net_quota_policy.h"
37 #include "net_settings.h"
38 #include "netmanager_base_common_utils.h"
39 #include "netmanager_base_permission.h"
40 #include "system_ability_definition.h"
41 #include "net_policy_listener.h"
42 #include "net_access_policy_dialog.h"
43 #include "os_account_manager.h"
44 
45 #ifdef __LP64__
46 const std::string LIB_LOAD_PATH = "/system/lib64/libnet_access_policy_dialog.z.so";
47 #else
48 const std::string LIB_LOAD_PATH = "/system/lib/libnet_access_policy_dialog.z.so";
49 #endif
50 
51 using GetNetBundleClass = OHOS::NetManagerStandard::INetAccessPolicyDialog *(*)();
52 namespace OHOS {
53 namespace NetManagerStandard {
54 namespace {
55 const std::string LIB_NET_BUNDLE_UTILS_PATH = "libnet_bundle_utils.z.so";
56 constexpr const char *INSTALL_SOURCE_DEFAULT = "default";
57 constexpr uint64_t DELAY_US = 30 * 1000 * 1000;
GetBundleMgrProxy()58 sptr<AppExecFwk::BundleMgrProxy> GetBundleMgrProxy()
59 {
60     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
61     if (!systemAbilityManager) {
62         NETMGR_LOG_E("fail to get system ability mgr.");
63         return nullptr;
64     }
65 
66     auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
67     if (!remoteObject) {
68         NETMGR_LOG_E("fail to get bundle manager proxy.");
69         return nullptr;
70     }
71 
72     sptr<AppExecFwk::BundleMgrProxy> bundleMgrProxy = iface_cast<AppExecFwk::BundleMgrProxy>(remoteObject);
73     if (bundleMgrProxy == nullptr) {
74         NETMGR_LOG_E("Failed to get bundle manager proxy.");
75         return nullptr;
76     }
77     return bundleMgrProxy;
78 }
79 const int32_t MAIN_USER_ID = 100;
80 const int32_t NET_ACCESS_POLICY_ALLOW_VALUE = 1;
81 } // namespace
82 static std::atomic<bool> g_RegisterToService(
83     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<NetPolicyService>::GetInstance().get()));
84 
NetPolicyService()85 NetPolicyService::NetPolicyService()
86     : SystemAbility(COMM_NET_POLICY_MANAGER_SYS_ABILITY_ID, true), state_(STATE_STOPPED)
87 {
88 }
89 
90 NetPolicyService::~NetPolicyService() = default;
91 
OnStart()92 void NetPolicyService::OnStart()
93 {
94     NETMGR_LOG_I("OnStart");
95     if (state_ == STATE_RUNNING) {
96         NETMGR_LOG_W("NetPolicyService already start.");
97         return;
98     }
99 
100     if (!g_RegisterToService) {
101         g_RegisterToService =
102             SystemAbility::MakeAndRegisterAbility(DelayedSingleton<NetPolicyService>::GetInstance().get());
103         if (!g_RegisterToService) {
104             NETMGR_LOG_E("Register to local sa manager failed again, give up.");
105             return;
106         }
107     }
108 
109     state_ = STATE_RUNNING;
110     Init();
111 }
112 
OnStop()113 void NetPolicyService::OnStop()
114 {
115     handler_.reset();
116     netPolicyCore_.reset();
117     netPolicyCallback_.reset();
118     netPolicyTraffic_.reset();
119     netPolicyFirewall_.reset();
120     netPolicyRule_.reset();
121     state_ = STATE_STOPPED;
122     g_RegisterToService = false;
123 }
124 
Dump(int32_t fd,const std::vector<std::u16string> & args)125 int32_t NetPolicyService::Dump(int32_t fd, const std::vector<std::u16string> &args)
126 {
127     NETMGR_LOG_D("Start policy Dump, fd: %{public}d", fd);
128     std::string result;
129     GetDumpMessage(result);
130     int32_t ret = dprintf(fd, "%s\n", result.c_str());
131     return ret < 0 ? NETMANAGER_ERR_PARAMETER_ERROR : NETMANAGER_SUCCESS;
132 }
133 
Init()134 void NetPolicyService::Init()
135 {
136     NETMGR_LOG_D("Init");
137     AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID);
138     AddSystemAbilityListener(COMM_NETSYS_NATIVE_SYS_ABILITY_ID);
139     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
140     ffrtQueue_.submit(
141         [this]() {
142             serviceComm_ = (std::make_unique<NetPolicyServiceCommon>()).release();
143             NetManagerCenter::GetInstance().RegisterPolicyService(serviceComm_);
144             netPolicyCore_ = DelayedSingleton<NetPolicyCore>::GetInstance();
145             netPolicyCallback_ = DelayedSingleton<NetPolicyCallback>::GetInstance();
146             netPolicyTraffic_ = netPolicyCore_->CreateCore<NetPolicyTraffic>();
147             netPolicyFirewall_ = netPolicyCore_->CreateCore<NetPolicyFirewall>();
148             netPolicyRule_ = netPolicyCore_->CreateCore<NetPolicyRule>();
149             NetAccessPolicyRDB netAccessPolicy;
150             netAccessPolicy.InitRdbStore();
151             UpdateNetAccessPolicyToMapFromDB();
152             if (!Publish(DelayedSingleton<NetPolicyService>::GetInstance().get())) {
153                 NETMGR_LOG_E("Register to sa manager failed");
154             }
155         }, ffrt::task_attr().name("FfrtNetPolicyServiceInit"));
156     ffrtQueue_.submit([this]() { SetBrokerUidAccessPolicyMap(std::nullopt); },
157                       ffrt::task_attr().name("InitSetBrokerUidAccessPolicyMapFunc").delay(DELAY_US));
158 }
159 
SetPolicyByUid(uint32_t uid,uint32_t policy)160 int32_t NetPolicyService::SetPolicyByUid(uint32_t uid, uint32_t policy)
161 {
162     NETMGR_LOG_I("SetPolicyByUid uid[%{public}d] policy[%{public}d]", uid, policy);
163     if (netPolicyRule_ == nullptr) {
164         NETMGR_LOG_E("netPolicyRule_ is nullptr");
165         return NETMANAGER_ERR_LOCAL_PTR_NULL;
166     }
167     return netPolicyRule_->TransPolicyToRule(uid, policy);
168 }
169 
GetPolicyByUid(uint32_t uid,uint32_t & policy)170 int32_t NetPolicyService::GetPolicyByUid(uint32_t uid, uint32_t &policy)
171 {
172     NETMGR_LOG_D("GetPolicyByUid uid[%{public}d]", uid);
173     if (netPolicyRule_ == nullptr) {
174         NETMGR_LOG_E("netPolicyRule_ is nullptr");
175         return NETMANAGER_ERR_LOCAL_PTR_NULL;
176     }
177     return netPolicyRule_->GetPolicyByUid(uid, policy);
178 }
179 
GetUidsByPolicy(uint32_t policy,std::vector<uint32_t> & uids)180 int32_t NetPolicyService::GetUidsByPolicy(uint32_t policy, std::vector<uint32_t> &uids)
181 {
182     NETMGR_LOG_D("GetUidsByPolicy policy[%{public}d]", policy);
183     if (netPolicyRule_ == nullptr) {
184         NETMGR_LOG_E("netPolicyRule_ is nullptr");
185         return NETMANAGER_ERR_LOCAL_PTR_NULL;
186     }
187     return netPolicyRule_->GetUidsByPolicy(policy, uids);
188 }
189 
IsUidNetAllowed(uint32_t uid,bool metered,bool & isAllowed)190 int32_t NetPolicyService::IsUidNetAllowed(uint32_t uid, bool metered, bool &isAllowed)
191 {
192     NETMGR_LOG_I("IsUidNetAllowed uid[%{public}d metered[%{public}d]", uid, metered);
193     if (NetSettings::GetInstance().IsSystem(uid)) {
194         isAllowed = true;
195         return NETMANAGER_SUCCESS;
196     }
197     if (netPolicyRule_ != nullptr) {
198         return netPolicyRule_->IsUidNetAllowed(uid, metered, isAllowed);
199     }
200     return NETMANAGER_ERR_LOCAL_PTR_NULL;
201 }
202 
IsUidNetAllowed(uint32_t uid,const std::string & ifaceName,bool & isAllowed)203 int32_t NetPolicyService::IsUidNetAllowed(uint32_t uid, const std::string &ifaceName, bool &isAllowed)
204 {
205     NETMGR_LOG_D("IsUidNetAllowed uid[%{public}d ifaceName[%{public}s]", uid, ifaceName.c_str());
206     const auto &vec = netPolicyTraffic_->GetMeteredIfaces();
207     if (std::find(vec.begin(), vec.end(), ifaceName) != vec.end()) {
208         return IsUidNetAllowed(uid, true, isAllowed);
209     }
210     return IsUidNetAllowed(uid, false, isAllowed);
211 }
212 
RegisterNetPolicyCallback(const sptr<INetPolicyCallback> & callback)213 int32_t NetPolicyService::RegisterNetPolicyCallback(const sptr<INetPolicyCallback> &callback)
214 {
215     NETMGR_LOG_I("RegisterNetPolicyCallback");
216     if (callback == nullptr) {
217         NETMGR_LOG_E("RegisterNetPolicyCallback parameter callback is null");
218         return NETMANAGER_ERR_LOCAL_PTR_NULL;
219     }
220 
221     if (netPolicyCallback_ == nullptr) {
222         NETMGR_LOG_E("netPolicyCallback_ is null");
223         return NETMANAGER_ERR_LOCAL_PTR_NULL;
224     }
225 
226     return netPolicyCallback_->RegisterNetPolicyCallbackAsync(callback);
227 }
228 
UnregisterNetPolicyCallback(const sptr<INetPolicyCallback> & callback)229 int32_t NetPolicyService::UnregisterNetPolicyCallback(const sptr<INetPolicyCallback> &callback)
230 {
231     NETMGR_LOG_I("UnregisterNetPolicyCallback");
232     if (callback == nullptr) {
233         NETMGR_LOG_E("UnregisterNetPolicyCallback parameter callback is null");
234         return NETMANAGER_ERR_LOCAL_PTR_NULL;
235     }
236 
237     if (netPolicyCallback_ == nullptr) {
238         NETMGR_LOG_E("netPolicyCallback_ is null");
239         return NETMANAGER_ERR_LOCAL_PTR_NULL;
240     }
241     return netPolicyCallback_->UnregisterNetPolicyCallbackAsync(callback);
242 }
243 
SetNetQuotaPolicies(const std::vector<NetQuotaPolicy> & quotaPolicies)244 int32_t NetPolicyService::SetNetQuotaPolicies(const std::vector<NetQuotaPolicy> &quotaPolicies)
245 {
246     NETMGR_LOG_I("SetNetQuotaPolicies quotaPolicySize[%{public}zd]", quotaPolicies.size());
247     if (netPolicyTraffic_ == nullptr) {
248         NETMGR_LOG_E("netPolicyTraffic_ is nullptr");
249         return NETMANAGER_ERR_LOCAL_PTR_NULL;
250     }
251     return netPolicyTraffic_->UpdateQuotaPolicies(quotaPolicies);
252 }
253 
GetNetQuotaPolicies(std::vector<NetQuotaPolicy> & quotaPolicies)254 int32_t NetPolicyService::GetNetQuotaPolicies(std::vector<NetQuotaPolicy> &quotaPolicies)
255 {
256     NETMGR_LOG_D("GetNetQuotaPolicies begin");
257     if (netPolicyTraffic_ == nullptr) {
258         NETMGR_LOG_E("netPolicyTraffic_ is nullptr");
259         return NETMANAGER_ERR_LOCAL_PTR_NULL;
260     }
261     return netPolicyTraffic_->GetNetQuotaPolicies(quotaPolicies);
262 }
263 
ResetPolicies(const std::string & simId)264 int32_t NetPolicyService::ResetPolicies(const std::string &simId)
265 {
266     NETMGR_LOG_I("ResetPolicies begin");
267     if (netPolicyRule_ != nullptr && netPolicyFirewall_ != nullptr && netPolicyTraffic_ != nullptr) {
268         netPolicyRule_->ResetPolicies();
269         netPolicyFirewall_->ResetPolicies();
270         netPolicyTraffic_->ResetPolicies(simId);
271         NETMGR_LOG_I("ResetPolicies end.");
272         return NETMANAGER_SUCCESS;
273     }
274     return NETMANAGER_ERR_LOCAL_PTR_NULL;
275 }
276 
SetBackgroundPolicy(bool allow)277 int32_t NetPolicyService::SetBackgroundPolicy(bool allow)
278 {
279     NETMGR_LOG_I("SetBackgroundPolicy allow[%{public}d]", allow);
280     if (netPolicyRule_ == nullptr) {
281         NETMGR_LOG_E("netPolicyRule_ is nullptr");
282         return NETMANAGER_ERR_LOCAL_PTR_NULL;
283     }
284     return netPolicyRule_->SetBackgroundPolicy(allow);
285 }
286 
GetBackgroundPolicy(bool & backgroundPolicy)287 int32_t NetPolicyService::GetBackgroundPolicy(bool &backgroundPolicy)
288 {
289     NETMGR_LOG_D("GetBackgroundPolicy begin");
290     if (netPolicyRule_ == nullptr) {
291         NETMGR_LOG_E("netPolicyRule_ is nullptr");
292         return NETMANAGER_ERR_LOCAL_PTR_NULL;
293     }
294     return netPolicyRule_->GetBackgroundPolicy(backgroundPolicy);
295 }
296 
GetBackgroundPolicyByUid(uint32_t uid,uint32_t & backgroundPolicyOfUid)297 int32_t NetPolicyService::GetBackgroundPolicyByUid(uint32_t uid, uint32_t &backgroundPolicyOfUid)
298 {
299     NETMGR_LOG_D("GetBackgroundPolicyByUid uid[%{public}d]", uid);
300     if (netPolicyRule_ == nullptr) {
301         NETMGR_LOG_E("netPolicyRule_ is nullptr");
302         return NETMANAGER_ERR_LOCAL_PTR_NULL;
303     }
304     return netPolicyRule_->GetBackgroundPolicyByUid(uid, backgroundPolicyOfUid);
305 }
306 
UpdateRemindPolicy(int32_t netType,const std::string & simId,uint32_t remindType)307 int32_t NetPolicyService::UpdateRemindPolicy(int32_t netType, const std::string &simId, uint32_t remindType)
308 {
309     NETMGR_LOG_I("UpdateRemindPolicy start");
310     if (netPolicyTraffic_ == nullptr) {
311         NETMGR_LOG_E("netPolicyTraffic_ is nullptr");
312         return NETMANAGER_ERR_LOCAL_PTR_NULL;
313     }
314     return netPolicyTraffic_->UpdateRemindPolicy(netType, simId, remindType);
315 }
316 
SetDeviceIdleTrustlist(const std::vector<uint32_t> & uids,bool isAllowed)317 int32_t NetPolicyService::SetDeviceIdleTrustlist(const std::vector<uint32_t> &uids, bool isAllowed)
318 {
319     NETMGR_LOG_D("SetDeviceIdleTrustlist start");
320     if (netPolicyFirewall_ == nullptr) {
321         NETMGR_LOG_E("netPolicyFirewall_ is nullptr");
322         return NETMANAGER_ERR_LOCAL_PTR_NULL;
323     }
324     return netPolicyFirewall_->SetDeviceIdleTrustlist(uids, isAllowed);
325 }
326 
GetDeviceIdleTrustlist(std::vector<uint32_t> & uids)327 int32_t NetPolicyService::GetDeviceIdleTrustlist(std::vector<uint32_t> &uids)
328 {
329     NETMGR_LOG_D("GetDeviceIdleTrustlist start");
330     if (netPolicyFirewall_ == nullptr) {
331         NETMGR_LOG_E("netPolicyFirewall_ is nullptr");
332         return NETMANAGER_ERR_LOCAL_PTR_NULL;
333     }
334     return netPolicyFirewall_->GetDeviceIdleTrustlist(uids);
335 }
336 
SetDeviceIdlePolicy(bool enable)337 int32_t NetPolicyService::SetDeviceIdlePolicy(bool enable)
338 {
339     NETMGR_LOG_I("SetDeviceIdlePolicy enable[%{public}d]", enable);
340     if (netPolicyFirewall_ == nullptr) {
341         NETMGR_LOG_E("netPolicyFirewall_ is nullptr");
342         return NETMANAGER_ERR_LOCAL_PTR_NULL;
343     }
344     return netPolicyFirewall_->UpdateDeviceIdlePolicy(enable);
345 }
346 
GetPowerSaveTrustlist(std::vector<uint32_t> & uids)347 int32_t NetPolicyService::GetPowerSaveTrustlist(std::vector<uint32_t> &uids)
348 {
349     NETMGR_LOG_D("GetPowerSaveTrustlist start");
350     if (netPolicyFirewall_ == nullptr) {
351         NETMGR_LOG_E("netPolicyFirewall_ is nullptr");
352         return NETMANAGER_ERR_LOCAL_PTR_NULL;
353     }
354     return netPolicyFirewall_->GetPowerSaveTrustlist(uids);
355 }
356 
SetPowerSaveTrustlist(const std::vector<uint32_t> & uids,bool isAllowed)357 int32_t NetPolicyService::SetPowerSaveTrustlist(const std::vector<uint32_t> &uids, bool isAllowed)
358 {
359     NETMGR_LOG_I("SetPowerSaveTrustlist start");
360     if (netPolicyFirewall_ == nullptr) {
361         NETMGR_LOG_E("netPolicyFirewall_ is nullptr");
362         return NETMANAGER_ERR_LOCAL_PTR_NULL;
363     }
364     return netPolicyFirewall_->SetPowerSaveTrustlist(uids, isAllowed);
365 }
366 
SetPowerSavePolicy(bool enable)367 int32_t NetPolicyService::SetPowerSavePolicy(bool enable)
368 {
369     NETMGR_LOG_I("SetPowerSavePolicy enable[%{public}d]", enable);
370     if (netPolicyFirewall_ == nullptr) {
371         NETMGR_LOG_E("netPolicyFirewall_ is nullptr");
372         return NETMANAGER_ERR_LOCAL_PTR_NULL;
373     }
374     return netPolicyFirewall_->UpdatePowerSavePolicy(enable);
375 }
376 
GetDumpMessage(std::string & message)377 int32_t NetPolicyService::GetDumpMessage(std::string &message)
378 {
379     if (netPolicyRule_ == nullptr || netPolicyTraffic_ == nullptr) {
380         NETMGR_LOG_E("netPolicyFirewall_ or netPolicyTraffic_ is nullptr");
381         return NETMANAGER_ERR_LOCAL_PTR_NULL;
382     }
383     netPolicyRule_->GetDumpMessage(message);
384     netPolicyTraffic_->GetDumpMessage(message);
385     return NETMANAGER_SUCCESS;
386 }
387 
CheckPermission()388 int32_t NetPolicyService::CheckPermission()
389 {
390     return NETMANAGER_SUCCESS;
391 }
392 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)393 void NetPolicyService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
394 {
395     NETMGR_LOG_I("OnAddSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
396     if (systemAbilityId == COMM_NET_CONN_MANAGER_SYS_ABILITY_ID) {
397         RegisterFactoryResetCallback();
398     }
399     if (systemAbilityId == BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) {
400         ffrtQueue_.submit([this]() { SetBrokerUidAccessPolicyMap(std::nullopt); },
401                           ffrt::task_attr().name("SetBrokerUidAccessPolicyMapFunc").delay(DELAY_US));
402 
403         EventFwk::MatchingSkills matchingSkills;
404         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
405         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED);
406         matchingSkills.AddEvent(COMMON_EVENT_STATUS_CHANGED);
407         EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
408         subscribeInfo.SetPriority(1);
409         std::shared_ptr<NetPolicyListener> subscriber = std::make_shared<NetPolicyListener>(
410             subscribeInfo, std::static_pointer_cast<NetPolicyService>(shared_from_this()));
411         EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber);
412 
413         ffrtQueue_.submit(
414             [this]() {
415                 OverwriteNetAccessPolicyToDBFromConfig();
416                 UpdateNetAccessPolicyToMapFromDB();
417             },
418             ffrt::task_attr().name("NetworkAccessPolicyConfigFlush"));
419     }
420     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
421         if (hasSARemoved_) {
422             OnNetSysRestart();
423             hasSARemoved_ = false;
424         }
425     }
426 }
427 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)428 void NetPolicyService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
429 {
430     NETMGR_LOG_I("OnRemoveSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
431     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
432         hasSARemoved_ = true;
433     }
434 }
435 
OnNetSysRestart()436 void NetPolicyService::OnNetSysRestart()
437 {
438     NETMGR_LOG_I("OnNetSysRestart");
439 
440     if (netPolicyRule_ != nullptr) {
441         netPolicyRule_->TransPolicyToRule();
442     }
443 }
444 
FactoryResetPolicies()445 int32_t NetPolicyService::FactoryResetPolicies()
446 {
447     NETMGR_LOG_I("FactoryResetPolicies begin");
448     if (netPolicyRule_ != nullptr && netPolicyFirewall_ != nullptr && netPolicyTraffic_ != nullptr) {
449         netPolicyRule_->ResetPolicies();
450         netPolicyFirewall_->ResetPolicies();
451         netPolicyTraffic_->ResetPolicies();
452         ResetNetAccessPolicy();
453         NETMGR_LOG_I("FactoryResetPolicies end.");
454         return NETMANAGER_SUCCESS;
455     }
456     return NETMANAGER_ERR_LOCAL_PTR_NULL;
457 }
458 
RegisterFactoryResetCallback()459 void NetPolicyService::RegisterFactoryResetCallback()
460 {
461     NETMGR_LOG_I("RegisterFactetCallback enter.");
462 
463     if (netFactoryResetCallback_ == nullptr) {
464         netFactoryResetCallback_ =
465             (std::make_unique<FactoryResetCallBack>(std::static_pointer_cast<NetPolicyService>(shared_from_this())))
466                 .release();
467     }
468 
469     if (netFactoryResetCallback_ != nullptr) {
470         int32_t ret = NetManagerCenter::GetInstance().RegisterNetFactoryResetCallback(netFactoryResetCallback_);
471         if (ret != NETMANAGER_SUCCESS) {
472             NETMGR_LOG_E("RegisterFactoryResetCallback ret[%{public}d]", ret);
473         }
474     } else {
475         NETMGR_LOG_E("netFactoryResetCallback_ is null");
476     }
477 }
478 
479 
RefreshNetworkAccessPolicyFromConfig()480 int32_t NetPolicyService::RefreshNetworkAccessPolicyFromConfig()
481 {
482     NETMGR_LOG_I("RefreshNetworkAccessPolicyFromConfigs Enter.");
483     OverwriteNetAccessPolicyToDBFromConfig();
484     UpdateNetAccessPolicyToMapFromDB();
485     return NETMANAGER_SUCCESS;
486 }
487 
OverwriteNetAccessPolicyToDBFromConfig()488 void NetPolicyService::OverwriteNetAccessPolicyToDBFromConfig()
489 {
490     std::vector<NetAccessPolicyConfig> configs = NetAccessPolicyConfigUtils::GetInstance().GetNetAccessPolicyConfig();
491     if (configs.empty()) {
492         NETMGR_LOG_W("configs is empty");
493         return;
494     }
495 
496     sptr<AppExecFwk::BundleMgrProxy> bundleMgrProxy = GetBundleMgrProxy();
497     if (bundleMgrProxy == nullptr) {
498         NETMGR_LOG_E("Failed to get bundle manager proxy.");
499         return;
500     }
501     NetAccessPolicyRDB netAccessPolicyRdb;
502     auto ret = ERR_OK;
503     int32_t userId = MAIN_USER_ID;
504     if (GetActivatedOsAccountId(userId) != NETMANAGER_SUCCESS) {
505         NETMGR_LOG_W("use default userId.");
506     }
507     for (size_t i = 0; i < configs.size(); i++) {
508         if (!configs[i].disableWlanSwitch && !configs[i].disableCellularSwitch) {
509             continue;
510         }
511         auto uid = bundleMgrProxy->GetUidByBundleName(configs[i].bundleName, userId);
512         if (uid == -1) {
513             NETMGR_LOG_E("Failed to get uid from bundleName. [%{public}s]", configs[i].bundleName.c_str());
514             continue;
515         }
516         NetAccessPolicyData policyData;
517         policyData.wifiPolicy = NET_ACCESS_POLICY_ALLOW_VALUE;
518         policyData.cellularPolicy = NET_ACCESS_POLICY_ALLOW_VALUE;
519         auto ret = netAccessPolicyRdb.QueryByUid(uid, policyData);
520         if (configs[i].disableWlanSwitch) {
521             policyData.wifiPolicy = NET_ACCESS_POLICY_ALLOW_VALUE;
522         }
523         if (configs[i].disableCellularSwitch) {
524             policyData.cellularPolicy = NET_ACCESS_POLICY_ALLOW_VALUE;
525         }
526         policyData.setFromConfigFlag = 0;
527         if (ret != NETMANAGER_SUCCESS) {
528             policyData.uid = uid;
529             netAccessPolicyRdb.InsertData(policyData);
530             continue;
531         }
532         netAccessPolicyRdb.UpdateByUid(uid, policyData);
533     }
534 }
535 
GetActivatedOsAccountId(int32_t & userId)536 int32_t NetPolicyService::GetActivatedOsAccountId(int32_t &userId)
537 {
538     std::vector<int32_t> activatedOsAccountIds;
539     int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds);
540     if (ret != ERR_OK) {
541         NETMGR_LOG_E("QueryActiveOsAccountIds failed. ret is %{public}d", ret);
542         return NETMANAGER_ERR_INTERNAL;
543     }
544     if (activatedOsAccountIds.empty()) {
545         NETMGR_LOG_E("QueryActiveOsAccountIds is empty");
546         return NETMANAGER_ERR_INTERNAL;
547     }
548     userId = activatedOsAccountIds[0];
549     NETMGR_LOG_I("QueryActiveOsAccountIds is %{public}d", userId);
550     return NETMANAGER_SUCCESS;
551 }
552 
UpdateNetAccessPolicyToMapFromDB()553 void NetPolicyService::UpdateNetAccessPolicyToMapFromDB()
554 {
555     NETMGR_LOG_I("UpdateNetAccessPolicyToMapFromDB enter.");
556     if (netPolicyRule_ == nullptr) {
557         NETMGR_LOG_E("netPolicyRule_ is nullptr");
558         return;
559     }
560     NetAccessPolicyRDB netAccessPolicy;
561     std::vector<NetAccessPolicyData> result = netAccessPolicy.QueryAll();
562     for (size_t i = 0; i < result.size(); i++) {
563         NetworkAccessPolicy policy;
564         policy.wifiAllow = result[i].wifiPolicy;
565         policy.cellularAllow = result[i].cellularPolicy;
566         if (netPolicyRule_ == nullptr) {
567             NETMGR_LOG_E("netPolicyRule_ is nullptr");
568             break;
569         }
570         (void)netPolicyRule_->SetNetworkAccessPolicy(result[i].uid, policy, result[i].setFromConfigFlag);
571     }
572 }
573 
ResetNetAccessPolicy()574 void NetPolicyService::ResetNetAccessPolicy()
575 {
576     NETMGR_LOG_I("ResetNetAccessPolicy enter.");
577     if (netPolicyRule_ == nullptr) {
578         NETMGR_LOG_E("netPolicyRule_ is nullptr");
579         return;
580     }
581     NetAccessPolicyRDB netAccessPolicyRdb;
582     std::vector<NetAccessPolicyData> result = netAccessPolicyRdb.QueryAll();
583     for (size_t i = 0; i < result.size(); i++) {
584         if (result[i].wifiPolicy && result[i].cellularPolicy) {
585             continue;
586         }
587         result[i].wifiPolicy = 1;
588         result[i].cellularPolicy = 1;
589         netAccessPolicyRdb.UpdateByUid(result[i].uid, result[i]);
590         NetworkAccessPolicy policy;
591         policy.wifiAllow = result[i].wifiPolicy;
592         policy.cellularAllow = result[i].cellularPolicy;
593         if (netPolicyRule_ == nullptr) {
594             NETMGR_LOG_E("netPolicyRule_ is nullptr");
595             break;
596         }
597         (void)netPolicyRule_->SetNetworkAccessPolicy(result[i].uid, policy, result[i].setFromConfigFlag);
598     }
599 }
600 
601 // Do not post into event handler, because this interface should have good performance
SetNetworkAccessPolicy(uint32_t uid,NetworkAccessPolicy policy,bool reconfirmFlag)602 int32_t NetPolicyService::SetNetworkAccessPolicy(uint32_t uid, NetworkAccessPolicy policy, bool reconfirmFlag)
603 {
604     NETMGR_LOG_I("SetNetworkAccessPolicy enter.");
605     if (netPolicyRule_ == nullptr) {
606         NETMGR_LOG_E("netPolicyRule_ is nullptr");
607         return NETMANAGER_ERR_LOCAL_PTR_NULL;
608     }
609 
610     NetAccessPolicyData data;
611     data.uid = uid;
612     data.wifiPolicy = policy.wifiAllow;
613     data.cellularPolicy = policy.cellularAllow;
614     data.setFromConfigFlag = !reconfirmFlag;
615     NetAccessPolicyRDB netAccessPolicy;
616     netAccessPolicy.InsertData(data);
617 
618     return netPolicyRule_->SetNetworkAccessPolicy(uid, policy, !reconfirmFlag);
619 }
620 
GetNetworkAccessPolicy(AccessPolicyParameter parameter,AccessPolicySave & policy)621 int32_t NetPolicyService::GetNetworkAccessPolicy(AccessPolicyParameter parameter, AccessPolicySave &policy)
622 {
623     NETMGR_LOG_I("GetNetworkAccessPolicy enter.");
624     NetAccessPolicyRDB netAccessPolicy;
625 
626     sptr<AppExecFwk::BundleMgrProxy> bundleMgrProxy = GetBundleMgrProxy();
627     if (bundleMgrProxy == nullptr) {
628         NETMGR_LOG_E("Failed to get bundle manager proxy.");
629         return NETMANAGER_ERR_INTERNAL;
630     }
631 
632     if (parameter.flag) {
633         std::string uidBundleName;
634         if (bundleMgrProxy->GetBundleNameForUid(parameter.uid, uidBundleName)) {
635             UpdateNetworkAccessPolicyFromConfig(uidBundleName, policy.policy);
636         } else {
637             NETMGR_LOG_E("GetBundleNameForUid Failed");
638         }
639         NetAccessPolicyData policyData;
640         if (netAccessPolicy.QueryByUid(parameter.uid, policyData) != NETMANAGER_SUCCESS) {
641             policy.policy.wifiAllow = true;
642             policy.policy.cellularAllow = true;
643             return NETMANAGER_SUCCESS;
644         }
645         policy.policy.wifiAllow = policyData.wifiPolicy;
646         policy.policy.cellularAllow = policyData.cellularPolicy;
647         return NETMANAGER_SUCCESS;
648     }
649 
650     std::vector<AppExecFwk::ApplicationInfo> appInfos;
651     bool retC = bundleMgrProxy->GetApplicationInfos(AppExecFwk::ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMISSION,
652                                                     static_cast<uint32_t>(parameter.userId), appInfos);
653     if (!retC) {
654         NETMGR_LOG_E("GetApplicationInfos Error");
655         return NETMANAGER_ERR_INTERNAL;
656     }
657     for (const auto &appInfo : appInfos) {
658         NetworkAccessPolicy policyTmp;
659         NetAccessPolicyData policyData;
660         if (netAccessPolicy.QueryByUid(appInfo.uid, policyData) == NETMANAGER_SUCCESS) {
661             policyTmp.wifiAllow = policyData.wifiPolicy;
662             policyTmp.cellularAllow = policyData.cellularPolicy;
663         } else {
664             policyTmp.wifiAllow = true;
665             policyTmp.cellularAllow = true;
666         }
667         UpdateNetworkAccessPolicyFromConfig(appInfo.bundleName, policyTmp);
668         policy.uid_policies.insert(std::pair<uint32_t, NetworkAccessPolicy>(appInfo.uid, policyTmp));
669     }
670 
671     return NETMANAGER_SUCCESS;
672 }
673 
DeleteNetworkAccessPolicy(uint32_t uid)674 int32_t NetPolicyService::DeleteNetworkAccessPolicy(uint32_t uid)
675 {
676     if (netPolicyRule_ == nullptr) {
677         NETMGR_LOG_E("netPolicyRule_ is nullptr");
678         return NETMANAGER_ERR_LOCAL_PTR_NULL;
679     }
680 
681     return netPolicyRule_->DeleteNetworkAccessPolicy(uid);
682 }
683 
NotifyNetAccessPolicyDiag(uint32_t uid)684 int32_t NetPolicyService::NotifyNetAccessPolicyDiag(uint32_t uid)
685 {
686     NETMGR_LOG_I("NotifyNetAccessPolicyDiag");
687 
688     std::lock_guard<std::mutex> lock(mutex_);
689     void *handler = dlopen(LIB_LOAD_PATH.c_str(), RTLD_LAZY | RTLD_NODELETE);
690     if (handler == nullptr) {
691         NETMGR_LOG_E("load failed, failed reason : %{public}s", dlerror());
692         return NETMANAGER_ERR_INTERNAL;
693     }
694 
695     GetNetBundleClass GetNetAccessPolicyDialog = (GetNetBundleClass)dlsym(handler, "GetNetAccessPolicyDialog");
696     if (GetNetAccessPolicyDialog == nullptr) {
697         NETMGR_LOG_E("GetNetAccessPolicyDialog faild, failed reason : %{public}s", dlerror());
698         dlclose(handler);
699         return NETMANAGER_ERR_INTERNAL;
700     }
701     auto netPolicyDialog = GetNetAccessPolicyDialog();
702     if (netPolicyDialog == nullptr) {
703         NETMGR_LOG_E("netPolicyDialog is nullptr");
704         dlclose(handler);
705         return NETMANAGER_ERR_INTERNAL;
706     }
707 
708     auto ret = netPolicyDialog->ConnectSystemUi(uid);
709     if (!ret) {
710         NETMGR_LOG_E("netPolicyDialog ConnectSystemUi failed");
711         dlclose(handler);
712         return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL;
713     }
714 
715     NETMGR_LOG_D("NotifyNetAccessPolicyDiag success");
716     dlclose(handler);
717 
718     return NETMANAGER_SUCCESS;
719 }
720 
SetNicTrafficAllowed(const std::vector<std::string> & ifaceNames,bool status)721 int32_t NetPolicyService::SetNicTrafficAllowed(const std::vector<std::string> &ifaceNames, bool status)
722 {
723     if (netPolicyRule_ == nullptr) {
724         NETMGR_LOG_E("netPolicyRule_ is nullptr");
725         return NETMANAGER_ERR_LOCAL_PTR_NULL;
726     }
727 
728     return netPolicyRule_->PolicySetNicTrafficAllowed(ifaceNames, status);
729 }
730 
SetBrokerUidAccessPolicyMap(std::optional<uint32_t> uid)731 void NetPolicyService::SetBrokerUidAccessPolicyMap(std::optional<uint32_t> uid)
732 {
733     NETMGR_LOG_I("SetBrokerUidAccessPolicyMap Enter. uid[%{public}u]", uid.has_value() ? uid.value() : 0);
734     std::unordered_map<uint32_t, SampleBundleInfo> sampleBundleInfos = GetSampleBundleInfosForActiveUser();
735     if (sampleBundleInfos.empty()) {
736         NETMGR_LOG_W("bundleInfos is empty");
737         return;
738     }
739     auto uidFindRet = std::find_if(sampleBundleInfos.begin(), sampleBundleInfos.end(),
740                                    [uid](const auto &item) { return uid.has_value() && uid == item.second.uid_; });
741     auto simFindRet = std::find_if(sampleBundleInfos.begin(), sampleBundleInfos.end(),
742                                    [](const auto &item) { return CommonUtils::IsSim(item.second.bundleName_); });
743     auto sim2FindRet = std::find_if(sampleBundleInfos.begin(), sampleBundleInfos.end(),
744                                     [](const auto &item) { return CommonUtils::IsSim2(item.second.bundleName_); });
745     NETMGR_LOG_I("SetBrokerUidAccessPolicyMap findRet[%{public}d, %{public}d], uidBundleName[%{public}s]",
746                  simFindRet != sampleBundleInfos.end(), sim2FindRet != sampleBundleInfos.end(),
747                  uidFindRet != sampleBundleInfos.end() ? uidFindRet->second.bundleName_.c_str() : "");
748     std::unordered_map<uint32_t, uint32_t> params;
749     if (simFindRet != sampleBundleInfos.end() && simFindRet->second.Valid()) {
750         params.emplace(UINT16_MAX, simFindRet->second.uid_);
751     }
752     for (auto iter = sampleBundleInfos.begin(); iter != sampleBundleInfos.end(); iter++) {
753         if (uid.has_value() && uidFindRet != sampleBundleInfos.end() &&
754             !CommonUtils::IsSim(uidFindRet->second.bundleName_) &&
755             !CommonUtils::IsSim2(uidFindRet->second.bundleName_) && uid.value() != iter->first) {
756             continue;
757         }
758         if (simFindRet != sampleBundleInfos.end() && simFindRet->second.Valid() &&
759             (CommonUtils::IsSim(iter->second.bundleName_) || CommonUtils::IsSimAnco(iter->second.bundleName_) ||
760             iter->second.installSource_ == INSTALL_SOURCE_DEFAULT)) {
761             params.emplace(iter->second.uid_, simFindRet->second.uid_);
762             continue;
763         }
764         if (simFindRet != sampleBundleInfos.end() && simFindRet->second.Valid() &&
765             (CommonUtils::IsInstallSourceFromSim(iter->second.installSource_))) {
766             params.emplace(iter->second.uid_, iter->second.uid_);
767             continue;
768         }
769         if (sim2FindRet != sampleBundleInfos.end() && sim2FindRet->second.Valid() &&
770             (CommonUtils::IsSim2(iter->second.bundleName_) || CommonUtils::IsSim2Anco(iter->second.bundleName_) ||
771             iter->second.installSource_ == INSTALL_SOURCE_DEFAULT)) {
772             params.emplace(iter->second.uid_, sim2FindRet->second.uid_);
773             continue;
774         }
775         if (sim2FindRet != sampleBundleInfos.end() && sim2FindRet->second.Valid() &&
776             CommonUtils::IsInstallSourceFromSim2(iter->second.installSource_)) {
777             params.emplace(iter->second.uid_,  iter->second.uid_);
778             continue;
779         }
780     }
781     auto ret = NetsysController::GetInstance().SetBrokerUidAccessPolicyMap(params);
782     if (ret != NETMANAGER_SUCCESS) {
783         NETMGR_LOG_E("SetBrokerUidAccessPolicyMap failed.");
784     }
785 }
786 
DelBrokerUidAccessPolicyMap(uint32_t uid)787 void NetPolicyService::DelBrokerUidAccessPolicyMap(uint32_t uid)
788 {
789     NETMGR_LOG_I("DelBrokerUidAccessPolicyMap Enter");
790     auto ret = NetsysController::GetInstance().DelBrokerUidAccessPolicyMap(uid);
791     if (ret != NETMANAGER_SUCCESS) {
792         NETMGR_LOG_E("DelBrokerUidAccessPolicyMap failed.");
793     }
794 }
795 
GetSampleBundleInfosForActiveUser()796 std::unordered_map<uint32_t, SampleBundleInfo> NetPolicyService::GetSampleBundleInfosForActiveUser()
797 {
798     void *handler = dlopen(LIB_NET_BUNDLE_UTILS_PATH.c_str(), RTLD_LAZY | RTLD_NODELETE);
799     if (handler == nullptr) {
800         NETMGR_LOG_E("load lib failed, reason : %{public}s", dlerror());
801         return std::unordered_map<uint32_t, SampleBundleInfo>{};
802     }
803     using GetNetBundleClass = INetBundle *(*)();
804     auto getNetBundle = (GetNetBundleClass)dlsym(handler, "GetNetBundle");
805     if (getNetBundle == nullptr) {
806         NETMGR_LOG_E("GetNetBundle failed, reason : %{public}s", dlerror());
807         dlclose(handler);
808         return std::unordered_map<uint32_t, SampleBundleInfo>{};
809     }
810     auto netBundle = getNetBundle();
811     if (netBundle == nullptr) {
812         NETMGR_LOG_E("netBundle is nullptr");
813         dlclose(handler);
814         return std::unordered_map<uint32_t, SampleBundleInfo>{};
815     }
816     std::optional<std::unordered_map<uint32_t, SampleBundleInfo>> result = netBundle->ObtainBundleInfoForActive();
817     dlclose(handler);
818     if (!result.has_value()) {
819         NETMGR_LOG_W("ObtainBundleInfoForActive is nullopt");
820         return std::unordered_map<uint32_t, SampleBundleInfo>{};
821     }
822     return result.value();
823 }
824 
UpdateNetworkAccessPolicyFromConfig(const std::string & bundleName,NetworkAccessPolicy & policy)825 void NetPolicyService::UpdateNetworkAccessPolicyFromConfig(const std::string &bundleName, NetworkAccessPolicy &policy)
826 {
827     std::vector<NetAccessPolicyConfig> configs = NetAccessPolicyConfigUtils::GetInstance().GetNetAccessPolicyConfig();
828     if (configs.empty()) {
829         NETMGR_LOG_W("net access policy configs is empty");
830         return;
831     }
832     auto policyConfig = std::find_if(configs.begin(), configs.end(),
833                                      [&bundleName](const auto &item) { return item.bundleName == bundleName; });
834     if (policyConfig == configs.end()) {
835         return;
836     }
837     policy.wifiSwitchDisable = policyConfig->disableWlanSwitch;
838     policy.cellularSwitchDisable = policyConfig->disableCellularSwitch;
839 }
840 } // namespace NetManagerStandard
841 } // namespace OHOS
842