1 /*
2  * Copyright (c) 2023-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 "base_network_strategy.h"
16 #include <algorithm>
17 #include "system_ability_definition.h"
18 #ifdef STANDBY_RSS_WORK_SCHEDULER_ENABLE
19 #include "workscheduler_srv_client.h"
20 #endif
21 
22 #include "standby_service_log.h"
23 #ifdef ENABLE_BACKGROUND_TASK_MGR
24 #include "background_task_helper.h"
25 #endif
26 #ifdef STANDBY_COMMUNICATION_NETMANAGER_BASE_ENABLE
27 #include "net_policy_client.h"
28 #endif
29 #include "app_mgr_helper.h"
30 #include "standby_service.h"
31 #include "allow_type.h"
32 #include "standby_state.h"
33 #include "bundle_manager_helper.h"
34 #include "standby_config_manager.h"
35 #include "time_provider.h"
36 #include "standby_service_impl.h"
37 #include "common_constant.h"
38 
39 namespace OHOS {
40 namespace DevStandbyMgr {
41 namespace {
42 const std::map<std::string, uint8_t> BGTASK_EXEMPTION_FLAG_MAP {
43     {CONTINUOUS_TASK, ExemptionTypeFlag::CONTINUOUS_TASK},
44     {TRANSIENT_TASK, ExemptionTypeFlag::TRANSIENT_TASK},
45     {WORK_SCHEDULER, ExemptionTypeFlag::WORK_SCHEDULER},
46 };
47 }
48 
49 bool BaseNetworkStrategy::isFirewallEnabled_ = false;
50 std::unordered_map<std::int32_t, NetLimtedAppInfo> BaseNetworkStrategy::netLimitedAppInfo_;
51 static std::mutex mutex_;
52 
HandleEvent(const StandbyMessage & message)53 void BaseNetworkStrategy::HandleEvent(const StandbyMessage& message)
54 {
55     STANDBYSERVICE_LOGD("BaseNetworkStrategy revceived message %{public}u, action: %{public}s",
56         message.eventId_, message.action_.c_str());
57     switch (message.eventId_) {
58         case StandbyMessageType::ALLOW_LIST_CHANGED:
59             UpdateExemptionList(message);
60             break;
61         case StandbyMessageType::BG_TASK_STATUS_CHANGE:
62             UpdateBgTaskAppStatus(message);
63             break;
64         case StandbyMessageType::PROCESS_STATE_CHANGED:
65             HandleProcessStatusChanged(message);
66             break;
67         case StandbyMessageType::SYS_ABILITY_STATUS_CHANGED:
68             ResetFirewallStatus(message);
69             break;
70         default:
71             break;
72     }
73 }
74 
OnCreated()75 ErrCode BaseNetworkStrategy::OnCreated()
76 {
77     // when initialized, stop net limit mode in case of unexpected process restart
78     ResetFirewallAllowList();
79     isFirewallEnabled_ = false;
80     isIdleMaintence_ = false;
81     return ERR_OK;
82 }
83 
OnDestroy()84 ErrCode BaseNetworkStrategy::OnDestroy()
85 {
86     ResetFirewallAllowList();
87     return ERR_OK;
88 }
89 
UpdateExemptionList(const StandbyMessage & message)90 ErrCode BaseNetworkStrategy::UpdateExemptionList(const StandbyMessage& message)
91 {
92     uint32_t allowType = static_cast<uint32_t>(message.want_->GetIntParam("allowType", 0));
93     if ((allowType & AllowType::NETWORK) == 0) {
94         STANDBYSERVICE_LOGD("allowType is not network, currentType is %{public}d", allowType);
95         return ERR_STANDBY_STRATEGY_NOT_MATCH;
96     }
97     if (!isFirewallEnabled_) {
98         STANDBYSERVICE_LOGD("current state is not sleep or maintenance, ignore exemption");
99         return ERR_STANDBY_CURRENT_STATE_NOT_MATCH;
100     }
101     // start update exemption flag
102     std::string processName = message.want_->GetStringParam("name");
103     bool added = message.want_->GetBoolParam("added", false);
104     int32_t uid = message.want_->GetIntParam("uid", -1);
105     STANDBYSERVICE_LOGI("updatee exemption list, %{public}s apply exemption, added is %{public}d",
106         processName.c_str(), added);
107     if (added) {
108         AddExemptionFlag(uid, processName, ExemptionTypeFlag::EXEMPTION);
109     } else {
110         RemoveExemptionFlag(uid, ExemptionTypeFlag::EXEMPTION);
111     }
112     return ERR_OK;
113 }
114 
UpdateFirewallAllowList()115 ErrCode BaseNetworkStrategy::UpdateFirewallAllowList()
116 {
117     ResetFirewallAllowList();
118     netLimitedAppInfo_.clear();
119     if (InitNetLimitedAppInfo() != ERR_OK) {
120         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
121     }
122     SetFirewallStatus(true);
123     return ERR_OK;
124 }
125 
EnableNetworkFirewall(const StandbyMessage & message)126 ErrCode BaseNetworkStrategy::EnableNetworkFirewall(const StandbyMessage& message)
127 {
128     if (isFirewallEnabled_) {
129         STANDBYSERVICE_LOGD("now is doze, do not need start net limit mode, repeat process");
130         return ERR_STANDBY_STRATEGY_STATE_REPEAT;
131     }
132     STANDBYSERVICE_LOGD("start net limit mode");
133     // if enter sleep state and app_res_deep phase, start net limit mode.
134     if (auto ret = EnableNetworkFirewallInner(); ret != ERR_OK) {
135         return ret;
136     }
137     isFirewallEnabled_ = true;
138     isIdleMaintence_ = false;
139     return ERR_OK;
140 }
141 
EnableNetworkFirewallInner()142 ErrCode BaseNetworkStrategy::EnableNetworkFirewallInner()
143 {
144     netLimitedAppInfo_.clear();
145     if (InitNetLimitedAppInfo() != ERR_OK) {
146         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
147     }
148     SetFirewallStatus(true);
149     return ERR_OK;
150 }
151 
152 // get app info, add exemption according to the status of app.
InitNetLimitedAppInfo()153 ErrCode BaseNetworkStrategy::InitNetLimitedAppInfo()
154 {
155     if (GetAllRunningAppInfo() != ERR_OK) {
156         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
157     }
158     std::vector<AppExecFwk::ApplicationInfo> applicationInfos {};
159     if (!BundleManagerHelper::GetInstance()->GetApplicationInfos(
160         AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO,
161         AppExecFwk::Constants::ALL_USERID, applicationInfos)) {
162         STANDBYSERVICE_LOGW("failed to get all applicationInfos");
163         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
164     }
165     STANDBYSERVICE_LOGD("succeed GetApplicationInfos, size is %{public}d",
166         static_cast<int32_t>(applicationInfos.size()));
167     for (const auto& info : applicationInfos) {
168         if (netLimitedAppInfo_.find(info.uid) == netLimitedAppInfo_.end()) {
169             continue;
170         }
171         if (info.isSystemApp) {
172             netLimitedAppInfo_[info.uid].appExemptionFlag_ |= ExemptionTypeFlag::UNRESTRICTED;
173         }
174     }
175 
176     if (GetForegroundApplications() !=ERR_OK || GetBackgroundTaskApp() != ERR_OK ||
177         GetWorkSchedulerTask() != ERR_OK || GetExemptionConfig() != ERR_OK) {
178         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
179     }
180     return ERR_OK;
181 }
182 
GetAllRunningAppInfo()183 ErrCode BaseNetworkStrategy::GetAllRunningAppInfo()
184 {
185     std::vector<AppExecFwk::RunningProcessInfo> allAppProcessInfos {};
186     if (!AppMgrHelper::GetInstance()->GetAllRunningProcesses(allAppProcessInfos)) {
187         STANDBYSERVICE_LOGE("connect to app manager service failed");
188         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
189     }
190     STANDBYSERVICE_LOGI("current running processes size %{public}d", static_cast<int32_t>(allAppProcessInfos.size()));
191     std::lock_guard<std::mutex> lock(mutex_);
192     for (const auto &info : allAppProcessInfos) {
193         netLimitedAppInfo_.emplace(info.uid_, NetLimtedAppInfo {info.processName_});
194     }
195     return ERR_OK;
196 }
197 
GetForegroundApplications()198 ErrCode BaseNetworkStrategy::GetForegroundApplications()
199 {
200     std::vector<AppExecFwk::AppStateData> fgApps {};
201     if (!AppMgrHelper::GetInstance()->GetForegroundApplications(fgApps)) {
202         STANDBYSERVICE_LOGW("get foreground app failed");
203         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
204     }
205     for (const auto& appInfo : fgApps) {
206         AddExemptionFlagByUid(appInfo.uid, ExemptionTypeFlag::FOREGROUND_APP);
207     }
208     return ERR_OK;
209 }
210 
GetBackgroundTaskApp()211 ErrCode BaseNetworkStrategy::GetBackgroundTaskApp()
212 {
213     #ifdef ENABLE_BACKGROUND_TASK_MGR
214     std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> continuousTaskList;
215     if (!BackgroundTaskHelper::GetInstance()->GetContinuousTaskApps(continuousTaskList)) {
216         STANDBYSERVICE_LOGW("get continuous task app failed");
217         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
218     }
219     STANDBYSERVICE_LOGD("succeed GetContinuousTaskApps, size is %{public}d",
220         static_cast<int32_t>(continuousTaskList.size()));
221     std::vector<std::shared_ptr<TransientTaskAppInfo>> transientTaskList;
222     if (!BackgroundTaskHelper::GetInstance()->GetTransientTaskApps(transientTaskList)) {
223         STANDBYSERVICE_LOGW("get transient task app failed");
224         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
225     }
226     STANDBYSERVICE_LOGD("succeed GetTransientTaskApps, size is %{public}d",
227         static_cast<int32_t>(transientTaskList.size()));
228     condition_ = TimeProvider::GetCondition();
229     for (const auto& task : continuousTaskList) {
230         if (auto infoIter = netLimitedAppInfo_.find(task->GetCreatorUid()); infoIter == netLimitedAppInfo_.end()) {
231             continue;
232         } else if (condition_ == ConditionType::DAY_STANDBY ||
233             (nightExemptionTaskType_ & (1<< task->GetTypeId())) != 0) {
234             infoIter->second.appExemptionFlag_ |= ExemptionTypeFlag::CONTINUOUS_TASK;
235         }
236     }
237     for (const auto& task : transientTaskList) {
238         AddExemptionFlagByUid(task->GetUid(), ExemptionTypeFlag::TRANSIENT_TASK);
239     }
240     #endif
241     return ERR_OK;
242 }
243 
GetWorkSchedulerTask()244 ErrCode BaseNetworkStrategy::GetWorkSchedulerTask()
245 {
246     #ifdef STANDBY_RSS_WORK_SCHEDULER_ENABLE
247     std::list<std::shared_ptr<WorkScheduler::WorkInfo>> workInfos;
248     if (WorkScheduler::WorkSchedulerSrvClient::GetInstance().GetAllRunningWorks(workInfos) != ERR_OK) {
249         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
250     }
251     STANDBYSERVICE_LOGD("GetWorkSchedulerTask succeed, size is %{public}d", static_cast<int32_t>(workInfos.size()));
252     for (const auto& task : workInfos) {
253         AddExemptionFlagByUid(task->GetUid(), ExemptionTypeFlag::WORK_SCHEDULER);
254     }
255     #endif
256     return ERR_OK;
257 }
258 
AddExemptionFlagByUid(int32_t uid,uint8_t flag)259 void BaseNetworkStrategy::AddExemptionFlagByUid(int32_t uid, uint8_t flag)
260 {
261     if (auto iter = netLimitedAppInfo_.find(uid); iter != netLimitedAppInfo_.end()) {
262         iter->second.appExemptionFlag_ |= flag;
263     }
264 }
265 
GetExemptionConfig()266 ErrCode BaseNetworkStrategy::GetExemptionConfig()
267 {
268     // if app in exemption list, add exemption flag
269     std::vector<AllowInfo> allowInfoList {};
270     StandbyServiceImpl::GetInstance()->GetAllowListInner(AllowType::NETWORK, allowInfoList,
271         ReasonCodeEnum::REASON_APP_API);
272     std::set<std::string> allowNameList {};
273     for (const auto& info : allowInfoList) {
274         allowNameList.emplace(info.GetName());
275     }
276     for (auto& [key, value] : netLimitedAppInfo_) {
277         if (allowNameList.find(value.name_) == allowNameList.end()) {
278             continue;
279         }
280         value.appExemptionFlag_ |= ExemptionTypeFlag::EXEMPTION;
281     }
282     // if app in restricted list, add retricted flag
283     std::set<std::string> restrictNameList {};
284     StandbyServiceImpl::GetInstance()->GetEligiableRestrictSet(AllowType::NETWORK, "NETWORK",
285         ReasonCodeEnum::REASON_APP_API, restrictNameList);
286     for (auto& [key, value] : netLimitedAppInfo_) {
287         if (restrictNameList.find(value.name_) == restrictNameList.end()) {
288             continue;
289         }
290         value.appExemptionFlag_ |= ExemptionTypeFlag::RESTRICTED;
291     }
292     return ERR_OK;
293 }
294 
GetExemptionConfigForApp(NetLimtedAppInfo & appInfo,const std::string & bundleName)295 ErrCode BaseNetworkStrategy::GetExemptionConfigForApp(NetLimtedAppInfo& appInfo, const std::string& bundleName)
296 {
297     // if app in exemption list, add exemption flag
298     std::vector<AllowInfo> allowInfoList {};
299     StandbyServiceImpl::GetInstance()->GetAllowListInner(AllowType::NETWORK, allowInfoList,
300         ReasonCodeEnum::REASON_APP_API);
301     std::set<std::string> allowNameList {};
302     for (const auto& info : allowInfoList) {
303         if (info.GetName() != bundleName) {
304             continue;
305         }
306         appInfo.appExemptionFlag_ |= ExemptionTypeFlag::EXEMPTION;
307     }
308 
309     // if app in restricted list, add retricted flag
310     std::set<std::string> restrictNameList {};
311     StandbyServiceImpl::GetInstance()->GetEligiableRestrictSet(AllowType::NETWORK, "NETWORK",
312         ReasonCodeEnum::REASON_APP_API, restrictNameList);
313     if (restrictNameList.find(bundleName) != restrictNameList.end()) {
314         appInfo.appExemptionFlag_ |= ExemptionTypeFlag::RESTRICTED;
315     }
316     return ERR_OK;
317 }
318 
SetNetAllowApps(bool isAllow)319 void BaseNetworkStrategy::SetNetAllowApps(bool isAllow)
320 {
321     std::vector<uint32_t> uids;
322     for (const auto& [key, value] : netLimitedAppInfo_) {
323         if (!ExemptionTypeFlag::IsExempted(value.appExemptionFlag_)) {
324             continue;
325         }
326         if ((condition_ == ConditionType::NIGHT_STANDBY) &&
327             (!ExemptionTypeFlag::IsExempted(value.appExemptionFlag_ & (~ExemptionTypeFlag::UNRESTRICTED)))) {
328             continue;
329         }
330         uids.emplace_back(key);
331         STANDBYSERVICE_LOGD("uid: %{public}d, name: %{public}s, isAllow: %{public}d",
332             key, value.name_.c_str(), isAllow);
333     }
334     STANDBYSERVICE_LOGD("all application size: %{public}d, network allow: %{public}d",
335         static_cast<int32_t>(netLimitedAppInfo_.size()), static_cast<int32_t>(uids.size()));
336     SetFirewallAllowedList(uids, isAllow);
337 }
338 
DisableNetworkFirewall(const StandbyMessage & message)339 ErrCode BaseNetworkStrategy::DisableNetworkFirewall(const StandbyMessage& message)
340 {
341     if (!isFirewallEnabled_) {
342         return ERR_STANDBY_CURRENT_STATE_NOT_MATCH;
343     }
344     uint32_t preState = static_cast<uint32_t>(message.want_->GetIntParam(PREVIOUS_STATE, 0));
345     uint32_t curState = static_cast<uint32_t>(message.want_->GetIntParam(CURRENT_STATE, 0));
346     if ((curState == StandbyState::MAINTENANCE) && (preState == StandbyState::SLEEP)) {
347         // restart net limit mode
348         SetFirewallStatus(false);
349         isIdleMaintence_ = true;
350         isFirewallEnabled_ = false;
351     } else if ((curState == StandbyState::SLEEP) && (preState == StandbyState::MAINTENANCE)) {
352         isIdleMaintence_ = false;
353         // stop net limit mode
354         SetFirewallStatus(true);
355         isFirewallEnabled_ = true;
356     } else if (preState == StandbyState::SLEEP || preState == StandbyState::MAINTENANCE) {
357         DisableNetworkFirewallInner();
358         isIdleMaintence_ = false;
359         isFirewallEnabled_ = false;
360     }
361     return ERR_OK;
362 }
363 
DisableNetworkFirewallInner()364 ErrCode BaseNetworkStrategy::DisableNetworkFirewallInner()
365 {
366     ResetFirewallAllowList();
367     netLimitedAppInfo_.clear();
368     return ERR_OK;
369 }
370 
HandleDeviceIdlePolicy(bool enableFirewall)371 int32_t BaseNetworkStrategy::HandleDeviceIdlePolicy(bool enableFirewall)
372 {
373     int32_t ret = NETMANAGER_SUCCESS;
374     #ifdef STANDBY_COMMUNICATION_NETMANAGER_BASE_ENABLE
375     ret = DelayedSingleton<NetManagerStandard::NetPolicyClient>::GetInstance()->
376         SetDeviceIdlePolicy(enableFirewall);
377     STANDBYSERVICE_LOGI("set status of powersaving firewall: %{public}d , res: %{public}d",
378         enableFirewall, ret);
379     if (ret == NETMANAGER_SUCCESS || ret == NETMANAGER_ERR_STATUS_EXIST) {
380         StandbyMessage standbyMessage {StandbyMessageType::DEVICE_NET_IDLE_POLICY_TRANSIT};
381         standbyMessage.want_ = AAFwk::Want{};
382         standbyMessage.want_->SetParam(NET_IDLE_POLICY_STATUS, enableFirewall);
383         StandbyServiceImpl::GetInstance()->DispatchEvent(standbyMessage);
384     }
385     #endif
386     return ret;
387 }
388 
UpdateBgTaskAppStatus(const StandbyMessage & message)389 ErrCode BaseNetworkStrategy::UpdateBgTaskAppStatus(const StandbyMessage& message)
390 {
391     if (!isFirewallEnabled_) {
392         STANDBYSERVICE_LOGD("current state is not sleep or maintenance, ignore exemption");
393         return ERR_STANDBY_CURRENT_STATE_NOT_MATCH;
394     }
395 
396     std::string type = message.want_->GetStringParam(BG_TASK_TYPE);
397     bool started = message.want_->GetBoolParam(BG_TASK_STATUS, false);
398     int32_t uid = message.want_->GetIntParam(BG_TASK_UID, 0);
399     std::string bundleName = message.want_->GetStringParam(BG_TASK_BUNDLE_NAME);
400     if (BGTASK_EXEMPTION_FLAG_MAP.find(type) == BGTASK_EXEMPTION_FLAG_MAP.end()) {
401         return ERR_STANDBY_KEY_INFO_NOT_MATCH;
402     }
403     if (bundleName.empty()) {
404         bundleName = BundleManagerHelper::GetInstance()->GetClientBundleName(uid);
405     }
406     if (started) {
407         AddExemptionFlag(static_cast<uint32_t>(uid), bundleName, BGTASK_EXEMPTION_FLAG_MAP.at(type));
408     } else {
409         RemoveExemptionFlag(static_cast<uint32_t>(uid), BGTASK_EXEMPTION_FLAG_MAP.at(type));
410     }
411     return ERR_OK;
412 }
413 
HandleProcessStatusChanged(const StandbyMessage & message)414 void BaseNetworkStrategy::HandleProcessStatusChanged(const StandbyMessage& message)
415 {
416     if (!isFirewallEnabled_) {
417         STANDBYSERVICE_LOGD("current state is not sleep or maintenance, ignore state of process");
418         return;
419     }
420     int32_t uid = message.want_->GetIntParam("uid", -1);
421     std::string bundleName = message.want_->GetStringParam("name");
422     bool isCreated = message.want_->GetBoolParam("isCreated", false);
423     if (isCreated) {
424         GetAndCreateAppInfo(uid, bundleName);
425         auto iter = netLimitedAppInfo_.find(uid);
426         if (ExemptionTypeFlag::IsExempted(iter->second.appExemptionFlag_)) {
427             SetFirewallAllowedList({uid}, isCreated);
428         }
429     } else {
430         bool isRunning {false};
431         if (AppMgrHelper::GetInstance()->GetAppRunningStateByBundleName(bundleName, isRunning) && !isRunning) {
432             std::lock_guard<std::mutex> lock(mutex_);
433             netLimitedAppInfo_.erase(uid);
434             SetFirewallAllowedList({uid}, isCreated);
435         }
436     }
437 }
438 
AddExemptionFlag(uint32_t uid,const std::string & bundleName,uint8_t flag)439 void BaseNetworkStrategy::AddExemptionFlag(uint32_t uid, const std::string& bundleName, uint8_t flag)
440 {
441     if (!isFirewallEnabled_) {
442         return;
443     }
444     STANDBYSERVICE_LOGD("AddExemptionFlag uid is %{public}u, flag is %{public}d", uid, flag);
445     GetAndCreateAppInfo(uid, bundleName);
446     auto iter = netLimitedAppInfo_.find(uid);
447     if (iter == netLimitedAppInfo_.end()) {
448         netLimitedAppInfo_[uid] = NetLimtedAppInfo {bundleName};
449     }
450     auto lastAppExemptionFlag = iter->second.appExemptionFlag_;
451     iter->second.appExemptionFlag_ |= flag;
452     if (GetExemptedFlag(lastAppExemptionFlag, iter->second.appExemptionFlag_)) {
453         SetFirewallAllowedList({iter->first}, true);
454     }
455     iter->second.appExemptionFlag_ |= flag;
456 }
457 
RemoveExemptionFlag(uint32_t uid,uint8_t flag)458 void BaseNetworkStrategy::RemoveExemptionFlag(uint32_t uid, uint8_t flag)
459 {
460     if (!isFirewallEnabled_) {
461         return;
462     }
463     auto iter = netLimitedAppInfo_.find(uid);
464     if (iter == netLimitedAppInfo_.end()) {
465         return;
466     }
467 
468     STANDBYSERVICE_LOGD("RemoveExemptionFlag uid is flag is %{public}d, flag is %{public}d", uid, flag);
469     auto lastAppExemptionFlag = iter->second.appExemptionFlag_;
470     iter->second.appExemptionFlag_ &= (~flag);
471     if (GetExemptedFlag(iter->second.appExemptionFlag_, lastAppExemptionFlag)) {
472         SetFirewallAllowedList({iter->first}, false);
473     }
474 }
475 
GetExemptedFlag(uint8_t appNoExemptionFlag,uint8_t appExemptionFlag)476 bool BaseNetworkStrategy::GetExemptedFlag(uint8_t appNoExemptionFlag, uint8_t appExemptionFlag)
477 {
478     condition_ = TimeProvider::GetCondition();
479     if ((condition_ == ConditionType::NIGHT_STANDBY) &&
480         (!ExemptionTypeFlag::IsExempted(appNoExemptionFlag & (~ExemptionTypeFlag::UNRESTRICTED))) &&
481         ExemptionTypeFlag::IsExempted(appExemptionFlag)) {
482         return true;
483     } else if (!ExemptionTypeFlag::IsExempted(appNoExemptionFlag) &&
484         ExemptionTypeFlag::IsExempted(appExemptionFlag)) {
485         return true;
486     }
487     return false;
488 }
489 
ResetFirewallAllowList()490 void BaseNetworkStrategy::ResetFirewallAllowList()
491 {
492     #ifdef STANDBY_COMMUNICATION_NETMANAGER_BASE_ENABLE
493     STANDBYSERVICE_LOGI("start reset firewall allow list");
494     std::vector<uint32_t> uids;
495     if (DelayedSingleton<NetManagerStandard::NetPolicyClient>::GetInstance()->
496         GetDeviceIdleTrustlist(uids) != NETMANAGER_SUCCESS) {
497         STANDBYSERVICE_LOGE("get deviceIdle netLimited list is failed");
498         return;
499     }
500     int32_t ret = HandleDeviceIdlePolicy(false);
501     if (ret != NETMANAGER_SUCCESS && ret != NETMANAGER_ERR_STATUS_EXIST) {
502         STANDBYSERVICE_LOGE("handle device idle policy netLimited is false");
503         return;
504     }
505     if (DelayedSingleton<NetManagerStandard::NetPolicyClient>::GetInstance()->
506         SetDeviceIdleTrustlist(uids, false) != NETMANAGER_SUCCESS) {
507         STANDBYSERVICE_LOGE("SetFirewallAllowedList failed");
508     }
509     #endif
510 }
511 
SetFirewallStatus(bool enableFirewall)512 ErrCode BaseNetworkStrategy::SetFirewallStatus(bool enableFirewall)
513 {
514     if (enableFirewall) {
515         SetNetAllowApps(enableFirewall);
516         int32_t ret = HandleDeviceIdlePolicy(enableFirewall);
517         if (ret == NETMANAGER_SUCCESS || (!enableFirewall && ret == NETMANAGER_ERR_STATUS_EXIST)) {
518             STANDBYSERVICE_LOGI("Succeed to enable powersaving firewall");
519             return ERR_OK;
520         } else {
521             STANDBYSERVICE_LOGE("Failed to enable powersaving firewall");
522             return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
523         }
524     } else {
525         int32_t ret = HandleDeviceIdlePolicy(enableFirewall);
526         if (ret == NETMANAGER_SUCCESS || (!enableFirewall && ret == NETMANAGER_ERR_STATUS_EXIST)) {
527             STANDBYSERVICE_LOGI("Succeed to disable powersaving firewall");
528             SetNetAllowApps(enableFirewall);
529             return ERR_OK;
530         } else {
531             STANDBYSERVICE_LOGE("Failed to disable powersaving firewall");
532             return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
533         }
534     }
535 }
536 
537 // when app is created, add app info to cache
GetAndCreateAppInfo(uint32_t uid,const std::string & bundleName)538 void BaseNetworkStrategy::GetAndCreateAppInfo(uint32_t uid, const std::string& bundleName)
539 {
540     auto iter = netLimitedAppInfo_.find(uid);
541     if (iter != netLimitedAppInfo_.end()) {
542         return;
543     }
544     std::lock_guard<std::mutex> lock(mutex_);
545     std::tie(iter, std::ignore) = netLimitedAppInfo_.emplace(uid, NetLimtedAppInfo {bundleName});
546 
547     bool isSystemApp {false};
548     if (BundleManagerHelper::GetInstance()->CheckIsSystemAppByUid(uid, isSystemApp) && isSystemApp) {
549         iter->second.appExemptionFlag_ |= ExemptionTypeFlag::UNRESTRICTED;
550     }
551     GetExemptionConfigForApp(iter->second, bundleName);
552 }
553 
554 // when bgtask or work_scheduler service crash, reset relative flag
ResetFirewallStatus(const StandbyMessage & message)555 void BaseNetworkStrategy::ResetFirewallStatus(const StandbyMessage& message)
556 {
557     if (!isFirewallEnabled_ || isIdleMaintence_) {
558         return;
559     }
560     bool isAdded = message.want_->GetBoolParam(SA_STATUS, false);
561     if (isAdded) {
562         return;
563     }
564     int32_t saId = message.want_->GetIntParam(SA_ID, 0);
565     if (saId != WORK_SCHEDULE_SERVICE_ID && saId != BACKGROUND_TASK_MANAGER_SERVICE_ID) {
566         return;
567     }
568     const uint8_t bgTaskFlag = (ExemptionTypeFlag::TRANSIENT_TASK | ExemptionTypeFlag::WORK_SCHEDULER);
569     for (const auto& [key, value] : netLimitedAppInfo_) {
570         if ((value.appExemptionFlag_ & bgTaskFlag) == 0) {
571             continue;
572         }
573         RemoveExemptionFlag(key, (value.appExemptionFlag_ & bgTaskFlag));
574     }
575     return;
576 }
577 
ShellDump(const std::vector<std::string> & argsInStr,std::string & result)578 void BaseNetworkStrategy::ShellDump(const std::vector<std::string>& argsInStr, std::string& result)
579 {
580     result.append("Network Strategy:\n").append("isFirewallEnabled: " + std::to_string(isFirewallEnabled_))
581         .append(" isIdleMaintence: " + std::to_string(isIdleMaintence_)).append("\n");
582     result.append("limited app info: \n");
583     for (const auto& [key, value] : netLimitedAppInfo_) {
584         result.append("uid: ").append(std::to_string(key)).append(" name: ").append(value.name_).append(" uid: ")
585             .append(std::to_string(key)).append(" exemption flag: ")
586             .append(std::to_string(value.appExemptionFlag_)).append("\n");
587     }
588 }
589 }  // namespace DevStandbyMgr
590 }  // namespace OHOS
591