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     if (!BundleManagerHelper::GetInstance()->GetApplicationInfos(
166         AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO,
167         UserSpace::SPECIAL_USERID, applicationInfos)) {
168         STANDBYSERVICE_LOGW("failed to get special applicationInfos");
169     }
170     STANDBYSERVICE_LOGD("succeed GetApplicationInfos, size is %{public}d",
171         static_cast<int32_t>(applicationInfos.size()));
172     for (const auto& info : applicationInfos) {
173         if (netLimitedAppInfo_.find(info.uid) == netLimitedAppInfo_.end()) {
174             continue;
175         }
176         if (info.isSystemApp) {
177             netLimitedAppInfo_[info.uid].appExemptionFlag_ |= ExemptionTypeFlag::UNRESTRICTED;
178         }
179     }
180 
181     if (GetForegroundApplications() !=ERR_OK || GetBackgroundTaskApp() != ERR_OK ||
182         GetWorkSchedulerTask() != ERR_OK || GetExemptionConfig() != ERR_OK) {
183         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
184     }
185     return ERR_OK;
186 }
187 
GetAllRunningAppInfo()188 ErrCode BaseNetworkStrategy::GetAllRunningAppInfo()
189 {
190     std::vector<AppExecFwk::RunningProcessInfo> allAppProcessInfos {};
191     if (!AppMgrHelper::GetInstance()->GetAllRunningProcesses(allAppProcessInfos)) {
192         STANDBYSERVICE_LOGE("connect to app manager service failed");
193         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
194     }
195     STANDBYSERVICE_LOGI("current running processes size %{public}d", static_cast<int32_t>(allAppProcessInfos.size()));
196     std::lock_guard<std::mutex> lock(mutex_);
197     for (const auto &info : allAppProcessInfos) {
198         netLimitedAppInfo_.emplace(info.uid_, NetLimtedAppInfo {info.processName_});
199     }
200     return ERR_OK;
201 }
202 
GetForegroundApplications()203 ErrCode BaseNetworkStrategy::GetForegroundApplications()
204 {
205     std::vector<AppExecFwk::AppStateData> fgApps {};
206     if (!AppMgrHelper::GetInstance()->GetForegroundApplications(fgApps)) {
207         STANDBYSERVICE_LOGW("get foreground app failed");
208         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
209     }
210     for (const auto& appInfo : fgApps) {
211         AddExemptionFlagByUid(appInfo.uid, ExemptionTypeFlag::FOREGROUND_APP);
212     }
213     return ERR_OK;
214 }
215 
GetBackgroundTaskApp()216 ErrCode BaseNetworkStrategy::GetBackgroundTaskApp()
217 {
218     #ifdef ENABLE_BACKGROUND_TASK_MGR
219     std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> continuousTaskList;
220     if (!BackgroundTaskHelper::GetInstance()->GetContinuousTaskApps(continuousTaskList)) {
221         STANDBYSERVICE_LOGW("get continuous task app failed");
222         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
223     }
224     STANDBYSERVICE_LOGD("succeed GetContinuousTaskApps, size is %{public}d",
225         static_cast<int32_t>(continuousTaskList.size()));
226     std::vector<std::shared_ptr<TransientTaskAppInfo>> transientTaskList;
227     if (!BackgroundTaskHelper::GetInstance()->GetTransientTaskApps(transientTaskList)) {
228         STANDBYSERVICE_LOGW("get transient task app failed");
229         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
230     }
231     STANDBYSERVICE_LOGD("succeed GetTransientTaskApps, size is %{public}d",
232         static_cast<int32_t>(transientTaskList.size()));
233     condition_ = TimeProvider::GetCondition();
234     for (const auto& task : continuousTaskList) {
235         if (auto infoIter = netLimitedAppInfo_.find(task->GetCreatorUid()); infoIter == netLimitedAppInfo_.end()) {
236             continue;
237         } else if (condition_ == ConditionType::DAY_STANDBY ||
238             (nightExemptionTaskType_ & (1<< task->GetTypeId())) != 0) {
239             infoIter->second.appExemptionFlag_ |= ExemptionTypeFlag::CONTINUOUS_TASK;
240         }
241     }
242     for (const auto& task : transientTaskList) {
243         AddExemptionFlagByUid(task->GetUid(), ExemptionTypeFlag::TRANSIENT_TASK);
244     }
245     #endif
246     return ERR_OK;
247 }
248 
GetWorkSchedulerTask()249 ErrCode BaseNetworkStrategy::GetWorkSchedulerTask()
250 {
251     #ifdef STANDBY_RSS_WORK_SCHEDULER_ENABLE
252     std::list<std::shared_ptr<WorkScheduler::WorkInfo>> workInfos;
253     if (WorkScheduler::WorkSchedulerSrvClient::GetInstance().GetAllRunningWorks(workInfos) != ERR_OK) {
254         return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
255     }
256     STANDBYSERVICE_LOGD("GetWorkSchedulerTask succeed, size is %{public}d", static_cast<int32_t>(workInfos.size()));
257     for (const auto& task : workInfos) {
258         AddExemptionFlagByUid(task->GetUid(), ExemptionTypeFlag::WORK_SCHEDULER);
259     }
260     #endif
261     return ERR_OK;
262 }
263 
AddExemptionFlagByUid(int32_t uid, uint8_t flag)264 void BaseNetworkStrategy::AddExemptionFlagByUid(int32_t uid, uint8_t flag)
265 {
266     if (auto iter = netLimitedAppInfo_.find(uid); iter != netLimitedAppInfo_.end()) {
267         iter->second.appExemptionFlag_ |= flag;
268     }
269 }
270 
GetExemptionConfig()271 ErrCode BaseNetworkStrategy::GetExemptionConfig()
272 {
273     // if app in exemption list, add exemption flag
274     std::vector<AllowInfo> allowInfoList {};
275     StandbyServiceImpl::GetInstance()->GetAllowListInner(AllowType::NETWORK, allowInfoList,
276         ReasonCodeEnum::REASON_APP_API);
277     std::set<std::string> allowNameList {};
278     for (const auto& info : allowInfoList) {
279         allowNameList.emplace(info.GetName());
280     }
281     for (auto& [key, value] : netLimitedAppInfo_) {
282         if (allowNameList.find(value.name_) == allowNameList.end()) {
283             continue;
284         }
285         value.appExemptionFlag_ |= ExemptionTypeFlag::EXEMPTION;
286     }
287     // if app in restricted list, add retricted flag
288     std::set<std::string> restrictNameList {};
289     StandbyServiceImpl::GetInstance()->GetEligiableRestrictSet(AllowType::NETWORK, "NETWORK",
290         ReasonCodeEnum::REASON_APP_API, restrictNameList);
291     for (auto& [key, value] : netLimitedAppInfo_) {
292         if (restrictNameList.find(value.name_) == restrictNameList.end()) {
293             continue;
294         }
295         value.appExemptionFlag_ |= ExemptionTypeFlag::RESTRICTED;
296     }
297     return ERR_OK;
298 }
299 
GetExemptionConfigForApp(NetLimtedAppInfo& appInfo, const std::string& bundleName)300 ErrCode BaseNetworkStrategy::GetExemptionConfigForApp(NetLimtedAppInfo& appInfo, const std::string& bundleName)
301 {
302     // if app in exemption list, add exemption flag
303     std::vector<AllowInfo> allowInfoList {};
304     StandbyServiceImpl::GetInstance()->GetAllowListInner(AllowType::NETWORK, allowInfoList,
305         ReasonCodeEnum::REASON_APP_API);
306     std::set<std::string> allowNameList {};
307     for (const auto& info : allowInfoList) {
308         if (info.GetName() != bundleName) {
309             continue;
310         }
311         appInfo.appExemptionFlag_ |= ExemptionTypeFlag::EXEMPTION;
312     }
313 
314     // if app in restricted list, add retricted flag
315     std::set<std::string> restrictNameList {};
316     StandbyServiceImpl::GetInstance()->GetEligiableRestrictSet(AllowType::NETWORK, "NETWORK",
317         ReasonCodeEnum::REASON_APP_API, restrictNameList);
318     if (restrictNameList.find(bundleName) != restrictNameList.end()) {
319         appInfo.appExemptionFlag_ |= ExemptionTypeFlag::RESTRICTED;
320     }
321     return ERR_OK;
322 }
323 
SetNetAllowApps(bool isAllow)324 void BaseNetworkStrategy::SetNetAllowApps(bool isAllow)
325 {
326     std::vector<uint32_t> uids;
327     for (const auto& [key, value] : netLimitedAppInfo_) {
328         if (!ExemptionTypeFlag::IsExempted(value.appExemptionFlag_)) {
329             continue;
330         }
331         if ((condition_ == ConditionType::NIGHT_STANDBY) &&
332             (!ExemptionTypeFlag::IsExempted(value.appExemptionFlag_ & (~ExemptionTypeFlag::UNRESTRICTED)))) {
333             continue;
334         }
335         uids.emplace_back(key);
336         STANDBYSERVICE_LOGD("uid: %{public}d, name: %{public}s, isAllow: %{public}d",
337             key, value.name_.c_str(), isAllow);
338     }
339     STANDBYSERVICE_LOGD("all application size: %{public}d, network allow: %{public}d",
340         static_cast<int32_t>(netLimitedAppInfo_.size()), static_cast<int32_t>(uids.size()));
341     SetFirewallAllowedList(uids, isAllow);
342 }
343 
DisableNetworkFirewall(const StandbyMessage& message)344 ErrCode BaseNetworkStrategy::DisableNetworkFirewall(const StandbyMessage& message)
345 {
346     if (!isFirewallEnabled_) {
347         return ERR_STANDBY_CURRENT_STATE_NOT_MATCH;
348     }
349     uint32_t preState = static_cast<uint32_t>(message.want_->GetIntParam(PREVIOUS_STATE, 0));
350     uint32_t curState = static_cast<uint32_t>(message.want_->GetIntParam(CURRENT_STATE, 0));
351     if ((curState == StandbyState::MAINTENANCE) && (preState == StandbyState::SLEEP)) {
352         // restart net limit mode
353         SetFirewallStatus(false);
354         isIdleMaintence_ = true;
355         isFirewallEnabled_ = false;
356     } else if ((curState == StandbyState::SLEEP) && (preState == StandbyState::MAINTENANCE)) {
357         isIdleMaintence_ = false;
358         // stop net limit mode
359         SetFirewallStatus(true);
360         isFirewallEnabled_ = true;
361     } else if (preState == StandbyState::SLEEP || preState == StandbyState::MAINTENANCE) {
362         DisableNetworkFirewallInner();
363         isIdleMaintence_ = false;
364         isFirewallEnabled_ = false;
365     }
366     return ERR_OK;
367 }
368 
DisableNetworkFirewallInner()369 ErrCode BaseNetworkStrategy::DisableNetworkFirewallInner()
370 {
371     ResetFirewallAllowList();
372     netLimitedAppInfo_.clear();
373     return ERR_OK;
374 }
375 
HandleDeviceIdlePolicy(bool enableFirewall)376 int32_t BaseNetworkStrategy::HandleDeviceIdlePolicy(bool enableFirewall)
377 {
378     int32_t ret = NETMANAGER_SUCCESS;
379     #ifdef STANDBY_COMMUNICATION_NETMANAGER_BASE_ENABLE
380     ret = DelayedSingleton<NetManagerStandard::NetPolicyClient>::GetInstance()->
381         SetDeviceIdlePolicy(enableFirewall);
382     STANDBYSERVICE_LOGI("set status of powersaving firewall: %{public}d , res: %{public}d",
383         enableFirewall, ret);
384     if (ret == NETMANAGER_SUCCESS || ret == NETMANAGER_ERR_STATUS_EXIST) {
385         StandbyMessage standbyMessage {StandbyMessageType::DEVICE_NET_IDLE_POLICY_TRANSIT};
386         standbyMessage.want_ = AAFwk::Want{};
387         standbyMessage.want_->SetParam(NET_IDLE_POLICY_STATUS, enableFirewall);
388         StandbyServiceImpl::GetInstance()->DispatchEvent(standbyMessage);
389     }
390     #endif
391     return ret;
392 }
393 
UpdateBgTaskAppStatus(const StandbyMessage& message)394 ErrCode BaseNetworkStrategy::UpdateBgTaskAppStatus(const StandbyMessage& message)
395 {
396     if (!isFirewallEnabled_) {
397         STANDBYSERVICE_LOGD("current state is not sleep or maintenance, ignore exemption");
398         return ERR_STANDBY_CURRENT_STATE_NOT_MATCH;
399     }
400 
401     std::string type = message.want_->GetStringParam(BG_TASK_TYPE);
402     bool started = message.want_->GetBoolParam(BG_TASK_STATUS, false);
403     int32_t uid = message.want_->GetIntParam(BG_TASK_UID, 0);
404     std::string bundleName = message.want_->GetStringParam(BG_TASK_BUNDLE_NAME);
405     if (BGTASK_EXEMPTION_FLAG_MAP.find(type) == BGTASK_EXEMPTION_FLAG_MAP.end()) {
406         return ERR_STANDBY_KEY_INFO_NOT_MATCH;
407     }
408     if (bundleName.empty()) {
409         bundleName = BundleManagerHelper::GetInstance()->GetClientBundleName(uid);
410     }
411     if (started) {
412         AddExemptionFlag(static_cast<uint32_t>(uid), bundleName, BGTASK_EXEMPTION_FLAG_MAP.at(type));
413     } else {
414         RemoveExemptionFlag(static_cast<uint32_t>(uid), BGTASK_EXEMPTION_FLAG_MAP.at(type));
415     }
416     return ERR_OK;
417 }
418 
HandleProcessStatusChanged(const StandbyMessage& message)419 void BaseNetworkStrategy::HandleProcessStatusChanged(const StandbyMessage& message)
420 {
421     if (!isFirewallEnabled_) {
422         STANDBYSERVICE_LOGD("current state is not sleep or maintenance, ignore state of process");
423         return;
424     }
425     int32_t uid = message.want_->GetIntParam("uid", -1);
426     std::string bundleName = message.want_->GetStringParam("name");
427     bool isCreated = message.want_->GetBoolParam("isCreated", false);
428     if (isCreated) {
429         GetAndCreateAppInfo(uid, bundleName);
430         auto iter = netLimitedAppInfo_.find(uid);
431         if (ExemptionTypeFlag::IsExempted(iter->second.appExemptionFlag_)) {
432             SetFirewallAllowedList({uid}, isCreated);
433         }
434     } else {
435         bool isRunning {false};
436         if (AppMgrHelper::GetInstance()->GetAppRunningStateByBundleName(bundleName, isRunning) && !isRunning) {
437             std::lock_guard<std::mutex> lock(mutex_);
438             netLimitedAppInfo_.erase(uid);
439             SetFirewallAllowedList({uid}, isCreated);
440         }
441     }
442 }
443 
AddExemptionFlag(uint32_t uid, const std::string& bundleName, uint8_t flag)444 void BaseNetworkStrategy::AddExemptionFlag(uint32_t uid, const std::string& bundleName, uint8_t flag)
445 {
446     if (!isFirewallEnabled_) {
447         return;
448     }
449     STANDBYSERVICE_LOGD("AddExemptionFlag uid is %{public}u, flag is %{public}d", uid, flag);
450     GetAndCreateAppInfo(uid, bundleName);
451     auto iter = netLimitedAppInfo_.find(uid);
452     if (iter == netLimitedAppInfo_.end()) {
453         netLimitedAppInfo_[uid] = NetLimtedAppInfo {bundleName};
454     }
455     auto lastAppExemptionFlag = iter->second.appExemptionFlag_;
456     iter->second.appExemptionFlag_ |= flag;
457     if (GetExemptedFlag(lastAppExemptionFlag, iter->second.appExemptionFlag_)) {
458         SetFirewallAllowedList({iter->first}, true);
459     }
460     iter->second.appExemptionFlag_ |= flag;
461 }
462 
RemoveExemptionFlag(uint32_t uid, uint8_t flag)463 void BaseNetworkStrategy::RemoveExemptionFlag(uint32_t uid, uint8_t flag)
464 {
465     if (!isFirewallEnabled_) {
466         return;
467     }
468     auto iter = netLimitedAppInfo_.find(uid);
469     if (iter == netLimitedAppInfo_.end()) {
470         return;
471     }
472 
473     STANDBYSERVICE_LOGD("RemoveExemptionFlag uid is flag is %{public}d, flag is %{public}d", uid, flag);
474     auto lastAppExemptionFlag = iter->second.appExemptionFlag_;
475     iter->second.appExemptionFlag_ &= (~flag);
476     if (GetExemptedFlag(iter->second.appExemptionFlag_, lastAppExemptionFlag)) {
477         SetFirewallAllowedList({iter->first}, false);
478     }
479 }
480 
GetExemptedFlag(uint8_t appNoExemptionFlag, uint8_t appExemptionFlag)481 bool BaseNetworkStrategy::GetExemptedFlag(uint8_t appNoExemptionFlag, uint8_t appExemptionFlag)
482 {
483     condition_ = TimeProvider::GetCondition();
484     if ((condition_ == ConditionType::NIGHT_STANDBY) &&
485         (!ExemptionTypeFlag::IsExempted(appNoExemptionFlag & (~ExemptionTypeFlag::UNRESTRICTED))) &&
486         ExemptionTypeFlag::IsExempted(appExemptionFlag)) {
487         return true;
488     } else if (!ExemptionTypeFlag::IsExempted(appNoExemptionFlag) &&
489         ExemptionTypeFlag::IsExempted(appExemptionFlag)) {
490         return true;
491     }
492     return false;
493 }
494 
ResetFirewallAllowList()495 void BaseNetworkStrategy::ResetFirewallAllowList()
496 {
497     #ifdef STANDBY_COMMUNICATION_NETMANAGER_BASE_ENABLE
498     STANDBYSERVICE_LOGI("start reset firewall allow list");
499     std::vector<uint32_t> uids;
500     if (DelayedSingleton<NetManagerStandard::NetPolicyClient>::GetInstance()->
501         GetDeviceIdleTrustlist(uids) != NETMANAGER_SUCCESS) {
502         STANDBYSERVICE_LOGE("get deviceIdle netLimited list is failed");
503         return;
504     }
505     int32_t ret = HandleDeviceIdlePolicy(false);
506     if (ret != NETMANAGER_SUCCESS && ret != NETMANAGER_ERR_STATUS_EXIST) {
507         STANDBYSERVICE_LOGE("handle device idle policy netLimited is false");
508         return;
509     }
510     if (DelayedSingleton<NetManagerStandard::NetPolicyClient>::GetInstance()->
511         SetDeviceIdleTrustlist(uids, false) != NETMANAGER_SUCCESS) {
512         STANDBYSERVICE_LOGE("SetFirewallAllowedList failed");
513     }
514     #endif
515 }
516 
SetFirewallStatus(bool enableFirewall)517 ErrCode BaseNetworkStrategy::SetFirewallStatus(bool enableFirewall)
518 {
519     if (enableFirewall) {
520         SetNetAllowApps(enableFirewall);
521         int32_t ret = HandleDeviceIdlePolicy(enableFirewall);
522         if (ret == NETMANAGER_SUCCESS || (!enableFirewall && ret == NETMANAGER_ERR_STATUS_EXIST)) {
523             STANDBYSERVICE_LOGI("Succeed to enable powersaving firewall");
524             return ERR_OK;
525         } else {
526             STANDBYSERVICE_LOGE("Failed to enable powersaving firewall");
527             return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
528         }
529     } else {
530         int32_t ret = HandleDeviceIdlePolicy(enableFirewall);
531         if (ret == NETMANAGER_SUCCESS || (!enableFirewall && ret == NETMANAGER_ERR_STATUS_EXIST)) {
532             STANDBYSERVICE_LOGI("Succeed to disable powersaving firewall");
533             SetNetAllowApps(enableFirewall);
534             return ERR_OK;
535         } else {
536             STANDBYSERVICE_LOGE("Failed to disable powersaving firewall");
537             return ERR_STRATEGY_DEPENDS_SA_NOT_AVAILABLE;
538         }
539     }
540 }
541 
542 // when app is created, add app info to cache
GetAndCreateAppInfo(uint32_t uid, const std::string& bundleName)543 void BaseNetworkStrategy::GetAndCreateAppInfo(uint32_t uid, const std::string& bundleName)
544 {
545     auto iter = netLimitedAppInfo_.find(uid);
546     if (iter != netLimitedAppInfo_.end()) {
547         return;
548     }
549     std::lock_guard<std::mutex> lock(mutex_);
550     std::tie(iter, std::ignore) = netLimitedAppInfo_.emplace(uid, NetLimtedAppInfo {bundleName});
551 
552     bool isSystemApp {false};
553     if (BundleManagerHelper::GetInstance()->CheckIsSystemAppByUid(uid, isSystemApp) && isSystemApp) {
554         iter->second.appExemptionFlag_ |= ExemptionTypeFlag::UNRESTRICTED;
555     }
556     GetExemptionConfigForApp(iter->second, bundleName);
557 }
558 
559 // when bgtask or work_scheduler service crash, reset relative flag
ResetFirewallStatus(const StandbyMessage& message)560 void BaseNetworkStrategy::ResetFirewallStatus(const StandbyMessage& message)
561 {
562     if (!isFirewallEnabled_ || isIdleMaintence_) {
563         return;
564     }
565     bool isAdded = message.want_->GetBoolParam(SA_STATUS, false);
566     if (isAdded) {
567         return;
568     }
569     int32_t saId = message.want_->GetIntParam(SA_ID, 0);
570     if (saId != WORK_SCHEDULE_SERVICE_ID && saId != BACKGROUND_TASK_MANAGER_SERVICE_ID) {
571         return;
572     }
573     const uint8_t bgTaskFlag = (ExemptionTypeFlag::TRANSIENT_TASK | ExemptionTypeFlag::WORK_SCHEDULER);
574     for (const auto& [key, value] : netLimitedAppInfo_) {
575         if ((value.appExemptionFlag_ & bgTaskFlag) == 0) {
576             continue;
577         }
578         RemoveExemptionFlag(key, (value.appExemptionFlag_ & bgTaskFlag));
579     }
580     return;
581 }
582 
ShellDump(const std::vector<std::string>& argsInStr, std::string& result)583 void BaseNetworkStrategy::ShellDump(const std::vector<std::string>& argsInStr, std::string& result)
584 {
585     result.append("Network Strategy:\n").append("isFirewallEnabled: " + std::to_string(isFirewallEnabled_))
586         .append(" isIdleMaintence: " + std::to_string(isIdleMaintence_)).append("\n");
587     result.append("limited app info: \n");
588     for (const auto& [key, value] : netLimitedAppInfo_) {
589         result.append("uid: ").append(std::to_string(key)).append(" name: ").append(value.name_).append(" uid: ")
590             .append(std::to_string(key)).append(" exemption flag: ")
591             .append(std::to_string(value.appExemptionFlag_)).append("\n");
592     }
593 }
594 }  // namespace DevStandbyMgr
595 }  // namespace OHOS
596