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