• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
16 #include "standby_service_impl.h"
17 
18 #include <algorithm>
19 #include <dlfcn.h>
20 #include <fcntl.h>
21 #include <file_ex.h>
22 #include <functional>
23 #include <securec.h>
24 #include <set>
25 #include <sstream>
26 #include <string>
27 #include <unique_fd.h>
28 #include <vector>
29 #include <cinttypes>
30 
31 #include "ability_manager_helper.h"
32 #include "access_token.h"
33 #include "accesstoken_kit.h"
34 #include "xcollie/watchdog.h"
35 #include "allow_type.h"
36 #include "app_mgr_helper.h"
37 #include "bundle_manager_helper.h"
38 #include "common_event_observer.h"
39 #include "common_event_support.h"
40 #include "event_runner.h"
41 #include "istandby_service.h"
42 #include "json_utils.h"
43 #include "res_common_util.h"
44 #include "res_sched_event_reporter.h"
45 #include "standby_config_manager.h"
46 #include "standby_service.h"
47 #include "standby_service_log.h"
48 #include "system_ability_definition.h"
49 #include "timed_task.h"
50 #include "time_provider.h"
51 #include "time_service_client.h"
52 #include "tokenid_kit.h"
53 
54 namespace OHOS {
55 namespace DevStandbyMgr {
56 namespace {
57 const std::string ALLOW_RECORD_FILE_PATH = "/data/service/el1/public/device_standby/allow_record";
58 const std::string CLONE_BACKUP_FILE_PATH = "/data/service/el1/public/device_standby/device_standby_clone";
59 const std::string DEVICE_STANDBY_DIR = "/data/service/el1/public/device_standby";
60 const std::string DEVICE_STANDBY_RDB_DIR = "/data/service/el3/100/device_standby/rdb";
61 const std::string STANDBY_MSG_HANDLER = "StandbyMsgHandler";
62 const std::string ON_PLUGIN_REGISTER = "OnPluginRegister";
63 const std::string TAG_PROCESS_ABNORMAL_TIME = "process_abnormal_time";
64 const int32_t PROCESS_ABNORMAL_TIME = 20000;
65 const std::string STANDBY_EXEMPTION_PERMISSION = "ohos.permission.DEVICE_STANDBY_EXEMPTION";
66 const uint32_t EXEMPT_ALL_RESOURCES = 100;
67 const std::string COMMON_EVENT_TIMER_SA_ABILITY = "COMMON_EVENT_TIMER_SA_ABILITY";
68 const uint32_t ONE_SECOND = 1000;
69 const std::string DUMP_ON_POWER_OVERUSED = "--poweroverused";
70 const std::string DUMP_ON_ACTION_CHANGED = "--actionchanged";
71 const int32_t EXTENSION_ERROR_CODE = 13500099;
72 }
73 
StandbyServiceImpl()74 StandbyServiceImpl::StandbyServiceImpl() {}
75 
~StandbyServiceImpl()76 StandbyServiceImpl::~StandbyServiceImpl() {}
77 
GetInstance()78 std::shared_ptr<StandbyServiceImpl> StandbyServiceImpl::GetInstance()
79 {
80     return DelayedSingleton<StandbyServiceImpl>::GetInstance();
81 }
82 
Init()83 bool StandbyServiceImpl::Init()
84 {
85     auto runner = AppExecFwk::EventRunner::Create(STANDBY_MSG_HANDLER);
86     if (runner == nullptr) {
87         STANDBYSERVICE_LOGE("dev standby service runner create failed");
88         return false;
89     }
90     handler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
91     if (!handler_) {
92         STANDBYSERVICE_LOGE("standby msg handler create failed");
93         return false;
94     }
95     if (StandbyConfigManager::GetInstance()->Init() != ERR_OK) {
96         STANDBYSERVICE_LOGE("failed to init device standby config manager");
97         return false;
98     }
99     if (RegisterPlugin(StandbyConfigManager::GetInstance()->GetPluginName()) != ERR_OK
100         && RegisterPlugin(DEFAULT_PLUGIN_NAME) != ERR_OK) {
101         STANDBYSERVICE_LOGE("register plugin failed");
102         return false;
103     }
104     AddWatchDog();
105     HandleReportFileSizeEvent();
106     STANDBYSERVICE_LOGI("register plugin secceed, dev standby service implement finish Init");
107     return true;
108 }
109 
InitReadyState()110 void StandbyServiceImpl::InitReadyState()
111 {
112     STANDBYSERVICE_LOGD("start init necessary plugin");
113     handler_->PostTask([this]() {
114         if (isServiceReady_.load()) {
115             STANDBYSERVICE_LOGW("standby service is already ready, do not need repeat");
116             return;
117         }
118         if (!standbyStateManager_->Init()) {
119             STANDBYSERVICE_LOGE("standby state manager init failed");
120             return;
121         }
122         if (!strategyManager_->Init()) {
123             STANDBYSERVICE_LOGE("strategy plugin init failed");
124             return;
125         }
126         if (!constraintManager_->Init()) {
127             STANDBYSERVICE_LOGE("constraint plugin init failed");
128             return;
129         }
130         if (!listenerManager_->Init() || listenerManager_->StartListener() != ERR_OK) {
131             STANDBYSERVICE_LOGE("listener plugin init failed");
132             return;
133         }
134 
135         RegisterTimeObserver();
136         ParsePersistentData();
137         isServiceReady_.store(true);
138 
139         StandbyService::GetInstance()->AddPluginSysAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID);
140         StandbyService::GetInstance()->AddPluginSysAbilityListener(WORK_SCHEDULE_SERVICE_ID);
141         }, AppExecFwk::EventQueue::Priority::HIGH);
142 }
143 
AddWatchDog()144 void StandbyServiceImpl::AddWatchDog()
145 {
146     if (!handler_) {
147         STANDBYSERVICE_LOGE("standby msg handler is null");
148         return;
149     }
150     int32_t abnoramlTime = StandbyConfigManager::GetInstance()->GetStandbyParam(TAG_PROCESS_ABNORMAL_TIME);
151     abnoramlTime = (abnoramlTime <= 0) ? PROCESS_ABNORMAL_TIME : abnoramlTime;
152     int32_t ret = HiviewDFX::Watchdog::GetInstance().AddThread(STANDBY_MSG_HANDLER, handler_, abnoramlTime);
153     STANDBYSERVICE_LOGI("get handler abnormalTime: %{public}d, AddThread: %{public}d", abnoramlTime, ret);
154 }
155 
RegisterCommEventObserver()156 ErrCode StandbyServiceImpl::RegisterCommEventObserver()
157 {
158     STANDBYSERVICE_LOGI("register common event observer");
159     std::lock_guard<std::mutex> lock(eventObserverMutex_);
160     if (commonEventObserver_) {
161         return ERR_STANDBY_OBSERVER_ALREADY_EXIST;
162     }
163     commonEventObserver_ = CommonEventObserver::CreateCommonEventObserver(handler_);
164     if (!commonEventObserver_) {
165         STANDBYSERVICE_LOGE("register common event observer failed");
166         return ERR_STANDBY_OBSERVER_INIT_FAILED;
167     }
168     if (!commonEventObserver_->Subscribe()) {
169         STANDBYSERVICE_LOGE("SubscribeCommonEvent failed");
170         return ERR_STANDBY_OBSERVER_INIT_FAILED;
171     }
172     return ERR_OK;
173 }
174 
RegisterAppStateObserver()175 ErrCode StandbyServiceImpl::RegisterAppStateObserver()
176 {
177     std::lock_guard<std::mutex> lock(appStateObserverMutex_);
178     if (appStateObserver_) {
179         return ERR_STANDBY_OBSERVER_ALREADY_EXIST;
180     }
181     appStateObserver_ = new (std::nothrow) AppStateObserver(handler_);
182     if (!appStateObserver_) {
183         STANDBYSERVICE_LOGE("malloc appStateObserver failed");
184         return ERR_STANDBY_OBSERVER_INIT_FAILED;
185     }
186     if (!AppMgrHelper::GetInstance()->SubscribeObserver(appStateObserver_)) {
187         STANDBYSERVICE_LOGE("subscribe appStateObserver failed");
188         return ERR_STANDBY_OBSERVER_INIT_FAILED;
189     }
190     return ERR_OK;
191 }
192 
UnregisterAppStateObserver()193 ErrCode StandbyServiceImpl::UnregisterAppStateObserver()
194 {
195     STANDBYSERVICE_LOGI("unregister app state observer");
196     std::lock_guard<std::mutex> lock(appStateObserverMutex_);
197     if (appStateObserver_) {
198         AppMgrHelper::GetInstance()->UnsubscribeObserver(appStateObserver_);
199         appStateObserver_ = nullptr;
200     }
201     return ERR_OK;
202 }
203 
DayNightSwitchCallback()204 void StandbyServiceImpl::DayNightSwitchCallback()
205 {
206     handler_->PostTask([standbyImpl = shared_from_this()]() {
207         STANDBYSERVICE_LOGD("start day and night switch");
208         if (!standbyImpl->isServiceReady_.load()) {
209             STANDBYSERVICE_LOGW("standby service is not ready");
210             if (!TimedTask::StartDayNightSwitchTimer(standbyImpl->dayNightSwitchTimerId_)) {
211                 standbyImpl->ResetTimeObserver();
212             }
213             return;
214         }
215         auto curState = standbyImpl->standbyStateManager_->GetCurState();
216         if (curState == StandbyState::SLEEP) {
217             StandbyMessage standbyMessage {StandbyMessageType::RES_CTRL_CONDITION_CHANGED};
218             standbyMessage.want_ = AAFwk::Want {};
219             uint32_t condition = TimeProvider::GetCondition();
220             standbyMessage.want_->SetParam(RES_CTRL_CONDITION, static_cast<int32_t>(condition));
221             standbyImpl->DispatchEvent(standbyMessage);
222         }
223         if (!TimedTask::StartDayNightSwitchTimer(standbyImpl->dayNightSwitchTimerId_)) {
224             STANDBYSERVICE_LOGE("start day and night switch timer failed");
225             standbyImpl->ResetTimeObserver();
226         }
227     });
228 }
229 
RegisterTimeObserver()230 ErrCode StandbyServiceImpl::RegisterTimeObserver()
231 {
232     std::lock_guard<std::recursive_mutex> lock(timerObserverMutex_);
233     handler_->PostTask([=]() {
234             STANDBYSERVICE_LOGE("Dispatch COMMON_EVENT_TIMER_SA_ABILITY begin");
235             StandbyMessage message(StandbyMessageType::COMMON_EVENT, COMMON_EVENT_TIMER_SA_ABILITY);
236             StandbyServiceImpl::GetInstance()->DispatchEvent(message);
237         }, ONE_SECOND);
238     if (dayNightSwitchTimerId_ > 0) {
239         return ERR_STANDBY_OBSERVER_ALREADY_EXIST;
240     }
241     auto callBack = [standbyImpl = shared_from_this()]() {
242         standbyImpl->DayNightSwitchCallback();
243     };
244     if (!TimedTask::RegisterDayNightSwitchTimer(dayNightSwitchTimerId_, false, 0, callBack)) {
245         STANDBYSERVICE_LOGE("RegisterTimer failed");
246         return ERR_STANDBY_OBSERVER_INIT_FAILED;
247     }
248     return ERR_OK;
249 }
250 
UnregisterCommEventObserver()251 ErrCode StandbyServiceImpl::UnregisterCommEventObserver()
252 {
253     STANDBYSERVICE_LOGI("unregister common event observer");
254     std::lock_guard<std::mutex> lock(eventObserverMutex_);
255     if (commonEventObserver_) {
256         commonEventObserver_->Unsubscribe();
257         commonEventObserver_.reset();
258     }
259     return ERR_OK;
260 }
261 
UnregisterTimeObserver()262 ErrCode StandbyServiceImpl::UnregisterTimeObserver()
263 {
264     std::lock_guard<std::recursive_mutex> lock(timerObserverMutex_);
265     if (!MiscServices::TimeServiceClient::GetInstance()->StopTimer(dayNightSwitchTimerId_)) {
266         STANDBYSERVICE_LOGE("day and night switch observer stop failed");
267     }
268     if (!MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(dayNightSwitchTimerId_)) {
269         STANDBYSERVICE_LOGE("day and night switch observer destroy failed");
270     }
271     dayNightSwitchTimerId_ = 0;
272     return ERR_OK;
273 }
274 
ResetTimeObserver()275 ErrCode StandbyServiceImpl::ResetTimeObserver()
276 {
277     std::lock_guard<std::recursive_mutex> lock(timerObserverMutex_);
278     if (UnregisterTimeObserver() != ERR_OK || RegisterTimeObserver() != ERR_OK) {
279         STANDBYSERVICE_LOGE("day and night switch observer reset failed");
280         return ERR_STANDBY_OBSERVER_RESET_FAILED;
281     }
282     return ERR_OK;
283 }
284 
UpdateSaDependValue(const bool & isAdd,const uint32_t & saId)285 void StandbyServiceImpl::UpdateSaDependValue(const bool& isAdd, const uint32_t& saId)
286 {
287     if (isAdd) {
288         dependsReady_ |= saId;
289     } else {
290         dependsReady_ &= (~saId);
291     }
292 }
293 
GetSaDependValue()294 uint32_t StandbyServiceImpl::GetSaDependValue()
295 {
296     return dependsReady_;
297 }
298 
IsServiceReady()299 bool StandbyServiceImpl::IsServiceReady()
300 {
301     if (!isServiceReady_.load()) {
302         STANDBYSERVICE_LOGW("standby service is not ready, dependsReady is %{public}d", dependsReady_);
303         return false;
304     }
305     return true;
306 }
307 
RegisterPlugin(const std::string & pluginName)308 ErrCode StandbyServiceImpl::RegisterPlugin(const std::string& pluginName)
309 {
310     STANDBYSERVICE_LOGI("start register plugin %{public}s", pluginName.c_str());
311     registerPlugin_ = dlopen(pluginName.c_str(), RTLD_NOW);
312     if (!registerPlugin_) {
313         dlclose(registerPlugin_);
314         STANDBYSERVICE_LOGE("failed to open plugin %{public}s", pluginName.c_str());
315         return ERR_STANDBY_PLUGIN_NOT_EXIST;
316     }
317     void* pluginFunc = dlsym(registerPlugin_, ON_PLUGIN_REGISTER.c_str());
318     if (!pluginFunc) {
319         dlclose(registerPlugin_);
320         STANDBYSERVICE_LOGE("failed to find extern func of plugin %{public}s", pluginName.c_str());
321         return ERR_STANDBY_PLUGIN_NOT_EXIST;
322     }
323     auto onPluginInitFunc = reinterpret_cast<bool (*)()>(pluginFunc);
324     if (!onPluginInitFunc()) {
325         dlclose(registerPlugin_);
326         return ERR_STANDBY_PLUGIN_NOT_AVAILABLE;
327     }
328     return ERR_OK;
329 }
330 
RegisterPluginInner(IConstraintManagerAdapter * constraintManager,IListenerManagerAdapter * listenerManager,IStrategyManagerAdapter * strategyManager,IStateManagerAdapter * stateManager)331 void StandbyServiceImpl::RegisterPluginInner(IConstraintManagerAdapter* constraintManager,
332     IListenerManagerAdapter* listenerManager,
333     IStrategyManagerAdapter* strategyManager,
334     IStateManagerAdapter* stateManager)
335 {
336     constraintManager_ = std::shared_ptr<IConstraintManagerAdapter>(constraintManager);
337     listenerManager_ = std::shared_ptr<IListenerManagerAdapter>(listenerManager);
338     strategyManager_ = std::shared_ptr<IStrategyManagerAdapter>(strategyManager);
339     standbyStateManager_ = std::shared_ptr<IStateManagerAdapter>(stateManager);
340 }
341 
GetHandler()342 std::shared_ptr<AppExecFwk::EventHandler>& StandbyServiceImpl::GetHandler()
343 {
344     return handler_;
345 }
346 
GetConstraintManager()347 std::shared_ptr<IConstraintManagerAdapter>& StandbyServiceImpl::GetConstraintManager()
348 {
349     return constraintManager_;
350 }
351 
GetListenerManager()352 std::shared_ptr<IListenerManagerAdapter>& StandbyServiceImpl::GetListenerManager()
353 {
354     return listenerManager_;
355 }
356 
GetStrategyManager()357 std::shared_ptr<IStrategyManagerAdapter>& StandbyServiceImpl::GetStrategyManager()
358 {
359     return strategyManager_;
360 }
361 
GetStateManager()362 std::shared_ptr<IStateManagerAdapter>& StandbyServiceImpl::GetStateManager()
363 {
364     return standbyStateManager_;
365 }
366 
UninitReadyState()367 void StandbyServiceImpl::UninitReadyState()
368 {
369     handler_->PostSyncTask([this]() {
370         if (!isServiceReady_.load()) {
371             STANDBYSERVICE_LOGW("standby service is already not ready, do not need uninit");
372             return;
373         }
374         STANDBYSERVICE_LOGE("start uninit necessary observer");
375         listenerManager_->UnInit();
376         constraintManager_->UnInit();
377         strategyManager_->UnInit();
378         standbyStateManager_->UnInit();
379         isServiceReady_.store(false);
380         }, AppExecFwk::EventQueue::Priority::HIGH);
381 }
382 
ParsePersistentData()383 bool StandbyServiceImpl::ParsePersistentData()
384 {
385     STANDBYSERVICE_LOGD("service start, parse persistent data");
386     std::unordered_map<int32_t, std::string> pidNameMap {};
387     GetPidAndProcName(pidNameMap);
388     if (pidNameMap.empty()) {
389         return false;
390     }
391     nlohmann::json root;
392     if (!JsonUtils::LoadJsonValueFromFile(root, ALLOW_RECORD_FILE_PATH)) {
393         STANDBYSERVICE_LOGE("failed to load allow record from file");
394         return false;
395     }
396 
397     std::lock_guard<std::mutex> allowRecordLock(allowRecordMutex_);
398     for (auto iter = root.begin(); iter != root.end(); ++iter) {
399         std::shared_ptr<AllowRecord> recordPtr = std::make_shared<AllowRecord>();
400         if (recordPtr->ParseFromJson(iter.value())) {
401             allowInfoMap_.emplace(iter.key(), recordPtr);
402         }
403     }
404     for (auto iter = allowInfoMap_.begin(); iter != allowInfoMap_.end();) {
405         auto pidNameIter = pidNameMap.find(iter->second->pid_);
406         if (pidNameIter == pidNameMap.end() || pidNameIter->second != iter->second->name_) {
407             allowInfoMap_.erase(iter++);
408         } else {
409             iter++;
410         }
411     }
412 
413     STANDBYSERVICE_LOGI("after reboot, allowInfoMap_ size is %{public}d", static_cast<int32_t>(allowInfoMap_.size()));
414     RecoverTimeLimitedTask();
415     DumpPersistantData();
416     return true;
417 }
418 
GetPidAndProcName(std::unordered_map<int32_t,std::string> & pidNameMap)419 void StandbyServiceImpl::GetPidAndProcName(std::unordered_map<int32_t, std::string>& pidNameMap)
420 {
421     std::vector<AppExecFwk::RunningProcessInfo> allAppProcessInfos {};
422     if (!AppMgrHelper::GetInstance()->GetAllRunningProcesses(allAppProcessInfos)) {
423         STANDBYSERVICE_LOGE("connect to app manager service failed");
424         return;
425     }
426     STANDBYSERVICE_LOGD("GetAllRunningProcesses result size is %{public}d",
427         static_cast<int32_t>(allAppProcessInfos.size()));
428     for (const auto& info : allAppProcessInfos) {
429         pidNameMap.emplace(info.pid_, info.processName_);
430     }
431     std::list<SystemProcessInfo> systemProcessInfos {};
432     if (!AbilityManagerHelper::GetInstance()->GetRunningSystemProcess(systemProcessInfos)) {
433         STANDBYSERVICE_LOGE("connect to app ability service failed");
434         return;
435     }
436     STANDBYSERVICE_LOGD("GetRunningSystemProcess result size is %{public}d",
437         static_cast<int32_t>(systemProcessInfos.size()));
438     for (const auto& info : systemProcessInfos) {
439         pidNameMap.emplace(info.pid, info.processName);
440     }
441 }
442 
RecoverTimeLimitedTask()443 void StandbyServiceImpl::RecoverTimeLimitedTask()
444 {
445     STANDBYSERVICE_LOGD("start to recovery delayed task");
446     const auto &mgr = shared_from_this();
447     for (auto iter = allowInfoMap_.begin(); iter != allowInfoMap_.end(); ++iter) {
448         auto &allowTimeList = iter->second->allowTimeList_;
449         for (auto allowTimeIter = allowTimeList.begin(); allowTimeIter != allowTimeList.end(); ++allowTimeIter) {
450             auto task = [mgr, uid = iter->second->uid_, name = iter->second->name_] () {
451                 mgr->UnapplyAllowResInner(uid, name, MAX_ALLOW_TYPE_NUMBER, false);
452             };
453             int32_t timeOut = static_cast<int32_t>(allowTimeIter->endTime_ -
454                 MiscServices::TimeServiceClient::GetInstance()->GetMonotonicTimeMs());
455             handler_->PostTask(task, std::max(0, timeOut));
456         }
457     }
458 }
459 
DumpPersistantData()460 void StandbyServiceImpl::DumpPersistantData()
461 {
462     nlohmann::json root;
463     STANDBYSERVICE_LOGD("dump persistant data");
464     for (auto& [uid, allowInfo] : allowInfoMap_) {
465         root[uid] = allowInfo->ParseToJson();
466     }
467     JsonUtils::DumpJsonValueToFile(root, ALLOW_RECORD_FILE_PATH);
468 }
469 
UnInit()470 void StandbyServiceImpl::UnInit()
471 {
472     if (!registerPlugin_) {
473         dlclose(registerPlugin_);
474         registerPlugin_ = nullptr;
475     }
476     HiviewDFX::Watchdog::GetInstance().RemoveThread(STANDBY_MSG_HANDLER);
477     STANDBYSERVICE_LOGI("succeed to clear stawndby service implement");
478 }
479 
SubscribeBackupRestoreCallback(const std::string & moduleName,const std::function<ErrCode (std::vector<char> &)> & onBackupFunc,const std::function<ErrCode (std::vector<char> &)> & onRestoreFunc)480 ErrCode StandbyServiceImpl::SubscribeBackupRestoreCallback(const std::string& moduleName,
481     const std::function<ErrCode(std::vector<char>&)>& onBackupFunc,
482     const std::function<ErrCode(std::vector<char>&)>& onRestoreFunc)
483 {
484     std::lock_guard<std::mutex> lock(backupRestoreMutex_);
485     if (onBackupFuncMap_.find(moduleName) != onBackupFuncMap_.end()) {
486         STANDBYSERVICE_LOGE("Repeat subscribe backup restore callback, module name: %{public}s", moduleName.c_str());
487         return ERR_INVALID_OPERATION;
488     }
489 
490     onBackupFuncMap_.insert(std::make_pair(moduleName, onBackupFunc));
491     onRestoreFuncMap_.insert(std::make_pair(moduleName, onRestoreFunc));
492     return ERR_OK;
493 }
494 
UnsubscribeBackupRestoreCallback(const std::string & moduleName)495 ErrCode StandbyServiceImpl::UnsubscribeBackupRestoreCallback(const std::string& moduleName)
496 {
497     std::lock_guard<std::mutex> lock(backupRestoreMutex_);
498     onBackupFuncMap_.erase(moduleName);
499     onRestoreFuncMap_.erase(moduleName);
500     return ERR_OK;
501 }
502 
OnBackup(MessageParcel & data,MessageParcel & reply)503 ErrCode StandbyServiceImpl::OnBackup(MessageParcel& data, MessageParcel& reply)
504 {
505     UniqueFd fd(-1);
506     std::string replyCode = BuildBackupReplyCode(0);
507     std::vector<char> buff;
508     {
509         std::lock_guard<std::mutex> lock(backupRestoreMutex_);
510         for (const auto& [moduleName, func] : onBackupFuncMap_) {
511             std::vector<char> moduleBuff;
512             CloneFileHead head {};
513             ErrCode err = func(moduleBuff);
514             if (err != ERR_OK ||
515                 strncpy_s(head.moduleName, sizeof(head.moduleName), moduleName.c_str(), moduleName.size()) != 0) {
516                 continue;
517             }
518             head.fileOffset = buff.size();
519             head.fileSize = moduleBuff.size();
520             std::copy(reinterpret_cast<char*>(&head), reinterpret_cast<char*>(&head) + sizeof(CloneFileHead),
521                 std::back_inserter(buff));
522             buff.insert(buff.end(), moduleBuff.begin(), moduleBuff.end());
523         }
524     }
525     if (buff.size() != 0 && SaveBufferToFile(CLONE_BACKUP_FILE_PATH, buff)) {
526         fd = UniqueFd(open(CLONE_BACKUP_FILE_PATH.c_str(), O_RDONLY));
527     } else {
528         STANDBYSERVICE_LOGE("OnBackup fail: save buff to file fail");
529         replyCode  = BuildBackupReplyCode(EXTENSION_ERROR_CODE);
530     }
531 
532     if ((!reply.WriteFileDescriptor(fd)) || (!reply.WriteString(replyCode))) {
533         close(fd.Release());
534         int32_t ret = remove(CLONE_BACKUP_FILE_PATH.c_str());
535         STANDBYSERVICE_LOGE("OnBackup fail: reply write fail! remove ret: %{public}d", ret);
536         return ERR_INVALID_OPERATION;
537     }
538     close(fd.Release());
539     int32_t ret = remove(CLONE_BACKUP_FILE_PATH.c_str());
540     STANDBYSERVICE_LOGI("OnBackup succ: backup data success! remove ret: %{public}d", ret);
541     return ERR_OK;
542 }
543 
OnRestore(MessageParcel & data,MessageParcel & reply)544 ErrCode StandbyServiceImpl::OnRestore(MessageParcel& data, MessageParcel& reply)
545 {
546     std::string replyCode = BuildBackupReplyCode(0);
547     std::vector<char> buff;
548     UniqueFd fd(data.ReadFileDescriptor());
549     if (fd.Get() < 0) {
550         STANDBYSERVICE_LOGE("OnRestore fail: ReadFileDescriptor fail");
551         return ERR_INVALID_OPERATION;
552     }
553     const off_t fileLength = lseek(fd.Get(), 0, SEEK_END);
554     lseek(fd, 0, SEEK_SET);
555     buff.resize(fileLength);
556     const ssize_t len = read(fd, buff.data(), fileLength);
557     if (len == fileLength && fileLength != 0) {
558         std::lock_guard<std::mutex> lock(backupRestoreMutex_);
559         off_t offset = 0;
560         while (offset + static_cast<off_t>(sizeof(CloneFileHead)) < fileLength) {
561             CloneFileHead* head = reinterpret_cast<CloneFileHead*>(buff.data() + offset);
562             head->moduleName[sizeof(CloneFileHead::moduleName) - 1] = '\0';
563             if (offset + static_cast<off_t>(sizeof(CloneFileHead) + head->fileSize) > fileLength) {
564                 break;
565             }
566             const auto& onRestoreFunc = onRestoreFuncMap_.find(std::string(head->moduleName));
567             if (onRestoreFunc != onRestoreFuncMap_.end()) {
568                 std::vector<char> moduleBuff;
569                 std::copy(reinterpret_cast<char*>(&head->data), reinterpret_cast<char*>(&head->data) + head->fileSize,
570                     std::back_inserter(moduleBuff));
571                 (onRestoreFunc->second)(moduleBuff);
572             }
573             offset += static_cast<off_t>(sizeof(CloneFileHead) + head->fileSize);
574         }
575     } else {
576         STANDBYSERVICE_LOGE("OnRestore fail: get file fail");
577         replyCode  = BuildBackupReplyCode(EXTENSION_ERROR_CODE);
578     }
579 
580     if (!reply.WriteString(replyCode)) {
581         close(fd.Release());
582         STANDBYSERVICE_LOGE("OnRestore fail: reply write fail!");
583         return ERR_INVALID_OPERATION;
584     }
585     close(fd.Release());
586     STANDBYSERVICE_LOGI("OnRestore succ: reply write success!");
587     return ERR_OK;
588 }
589 
BuildBackupReplyCode(int32_t replyCode)590 std::string StandbyServiceImpl::BuildBackupReplyCode(int32_t replyCode)
591 {
592     nlohmann::json root;
593     nlohmann::json resultInfo;
594     nlohmann::json errorInfo;
595 
596     errorInfo["type"] = "ErrorInfo";
597     errorInfo["errorCode"] = std::to_string(replyCode);
598     errorInfo["errorInfo"] = "";
599 
600     resultInfo.push_back(errorInfo);
601     root["resultInfo"] = resultInfo;
602     return root.dump();
603 }
604 
CheckAllowTypeInfo(uint32_t allowType)605 bool StandbyServiceImpl::CheckAllowTypeInfo(uint32_t allowType)
606 {
607     return allowType > 0 && allowType <= MAX_ALLOW_TYPE_NUMBER;
608 }
609 
RemoveAppAllowRecord(int32_t uid,const std::string & bundleName,bool resetAll)610 ErrCode StandbyServiceImpl::RemoveAppAllowRecord(int32_t uid, const std::string &bundleName, bool resetAll)
611 {
612     if (!IsServiceReady()) {
613         return ERR_STANDBY_SYS_NOT_READY;
614     }
615     STANDBYSERVICE_LOGD("app died, uid: %{public}d, bundleName: %{public}s", uid, bundleName.c_str());
616     int allowType = resetAll ? MAX_ALLOW_TYPE_NUMBER : (MAX_ALLOW_TYPE_NUMBER ^ AllowType::TIMER ^
617         AllowType::WORK_SCHEDULER);
618     this->UnapplyAllowResInner(uid, bundleName, allowType, true);
619     return ERR_OK;
620 }
621 
CheckCallerPermission(uint32_t reasonCode)622 ErrCode StandbyServiceImpl::CheckCallerPermission(uint32_t reasonCode)
623 {
624     int32_t uid = IPCSkeleton::GetCallingUid();
625     STANDBYSERVICE_LOGD("check caller permission, uid of caller is %{public}d", uid);
626     Security::AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
627     if (Security::AccessToken::AccessTokenKit::GetTokenType(tokenId)
628         == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
629         return IsSystemAppWithPermission(uid, tokenId, reasonCode);
630     }
631     return ERR_OK;
632 }
633 
IsSystemAppWithPermission(int32_t uid,Security::AccessToken::AccessTokenID tokenId,uint32_t reasonCode)634 ErrCode StandbyServiceImpl::IsSystemAppWithPermission(int32_t uid,
635     Security::AccessToken::AccessTokenID tokenId, uint32_t reasonCode)
636 {
637     Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
638     if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, STANDBY_EXEMPTION_PERMISSION)
639         != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
640         STANDBYSERVICE_LOGE("CheckPermission: ohos.permission.DEVICE_STANDBY_EXEMPTION failed");
641         return ERR_STANDBY_PERMISSION_DENIED;
642     }
643 
644     uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
645     bool isSystemApp = Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId);
646     if (!isSystemApp) {
647         STANDBYSERVICE_LOGE("uid %{public}d is not system app", uid);
648         return ERR_STANDBY_NOT_SYSTEM_APP;
649     }
650     if (reasonCode != ReasonCodeEnum::REASON_APP_API) {
651         STANDBYSERVICE_LOGE("reasonCode error, uid %{public}d  must be app api", uid);
652         return ERR_STANDBY_PERMISSION_DENIED;
653     }
654     return ERR_OK;
655 }
656 
GetExemptedResourceType(uint32_t resourceType)657 uint32_t StandbyServiceImpl::GetExemptedResourceType(uint32_t resourceType)
658 {
659     int32_t uid = IPCSkeleton::GetCallingUid();
660     auto bundleName = BundleManagerHelper::GetInstance()->GetClientBundleName(uid);
661     const std::vector<int32_t>& resourcesApply = QueryRunningResourcesApply(uid, bundleName);
662 
663     uint32_t exemptedResourceType = 0;
664     if (resourcesApply.empty()) {
665         return exemptedResourceType;
666     }
667 
668     if (std::find(resourcesApply.begin(), resourcesApply.end(), EXEMPT_ALL_RESOURCES) != resourcesApply.end()) {
669         return resourceType;
670     }
671 
672     // traverse resourcesApply and get exempted resource type
673     for (const uint32_t resourceType : resourcesApply) {
674         if (resourceType <= EXEMPT_ALL_RESOURCES || resourceType > EXEMPT_ALL_RESOURCES + MAX_ALLOW_TYPE_NUM + 1) {
675             continue;
676         }
677         // maps number in resourceApply to resourceType defined in allow_type.h
678         exemptedResourceType |= (1 << (resourceType - EXEMPT_ALL_RESOURCES - 1));
679     }
680     exemptedResourceType &= resourceType;
681 
682     return exemptedResourceType;
683 }
684 
685 // meaning of number in resourcesApply list: 100 - all type of resources, 101 - NETWORK,
686 // 102 - RUNNING_LOCK, 103 - TIMER, 104 - WORK_SCHEDULER, 105 - AUTO_SYNC, 106 - PUSH, 107 - FREEZE
QueryRunningResourcesApply(const int32_t uid,const std::string & bundleName)687 std::vector<int32_t> StandbyServiceImpl::QueryRunningResourcesApply(const int32_t uid, const std::string &bundleName)
688 {
689     AppExecFwk::ApplicationInfo applicationInfo;
690     if (!BundleManagerHelper::GetInstance()->GetApplicationInfo(bundleName,
691         AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, GetUserIdByUid(uid), applicationInfo)) {
692         STANDBYSERVICE_LOGE("failed to get applicationInfo, bundleName is %{public}s", bundleName.c_str());
693         return {};
694     }
695     STANDBYSERVICE_LOGD("size of applicationInfo.resourcesApply is %{public}d",
696         static_cast<int32_t>(applicationInfo.resourcesApply.size()));
697     return applicationInfo.resourcesApply;
698 }
699 
GetUserIdByUid(int32_t uid)700 int32_t StandbyServiceImpl::GetUserIdByUid(int32_t uid)
701 {
702     const int32_t BASE_USER_RANGE = 200000;
703     return uid / BASE_USER_RANGE;
704 }
705 
SubscribeStandbyCallback(const sptr<IStandbyServiceSubscriber> & subscriber)706 ErrCode StandbyServiceImpl::SubscribeStandbyCallback(const sptr<IStandbyServiceSubscriber>& subscriber)
707 {
708     if (auto checkRet = CheckCallerPermission(); checkRet != ERR_OK) {
709         STANDBYSERVICE_LOGE("caller permission denied.");
710         return checkRet;
711     }
712 
713     STANDBYSERVICE_LOGI("add %{public}s subscriber to stanby service", subscriber->GetSubscriberName().c_str());
714     const auto& strategyConfigList = StandbyConfigManager::GetInstance()->GetStrategyConfigList();
715     auto item = std::find(strategyConfigList.begin(), strategyConfigList.end(), subscriber->GetSubscriberName());
716     if (item == strategyConfigList.end()) {
717         STANDBYSERVICE_LOGI("%{public}s is not exist in StrategyConfigList", subscriber->GetSubscriberName().c_str());
718         return ERR_STANDBY_STRATEGY_NOT_DEPLOY;
719     }
720     return StandbyStateSubscriber::GetInstance()->AddSubscriber(subscriber);
721 }
722 
UnsubscribeStandbyCallback(const sptr<IStandbyServiceSubscriber> & subscriber)723 ErrCode StandbyServiceImpl::UnsubscribeStandbyCallback(const sptr<IStandbyServiceSubscriber>& subscriber)
724 {
725     if (auto checkRet = CheckCallerPermission(); checkRet != ERR_OK) {
726         STANDBYSERVICE_LOGE("caller permission denied.");
727         return checkRet;
728     }
729 
730     STANDBYSERVICE_LOGI("add subscriber to stanby service succeed");
731     return StandbyStateSubscriber::GetInstance()->RemoveSubscriber(subscriber);
732 }
733 
ApplyAllowResource(ResourceRequest & resourceRequest)734 ErrCode StandbyServiceImpl::ApplyAllowResource(ResourceRequest& resourceRequest)
735 {
736     if (!IsServiceReady()) {
737         return ERR_STANDBY_SYS_NOT_READY;
738     }
739     STANDBYSERVICE_LOGD("start AddAllowList");
740     if (auto checkRet = CheckCallerPermission(resourceRequest.GetReasonCode()); checkRet != ERR_OK) {
741         return checkRet;
742     }
743 
744     // update allow type according to configuration
745     if (Security::AccessToken::AccessTokenKit::GetTokenType(OHOS::IPCSkeleton::GetCallingTokenID())
746         == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
747         resourceRequest.SetAllowType(GetExemptedResourceType(resourceRequest.GetAllowType()));
748     }
749 
750     if (!CheckAllowTypeInfo(resourceRequest.GetAllowType()) || resourceRequest.GetUid() < 0) {
751         STANDBYSERVICE_LOGE("resourceRequest param is invalid");
752         return ERR_RESOURCE_TYPES_INVALID;
753     }
754     if (resourceRequest.GetDuration() < 0) {
755         STANDBYSERVICE_LOGE("duration param is invalid");
756         return ERR_DURATION_INVALID;
757     }
758     int32_t pid = IPCSkeleton::GetCallingPid();
759     ApplyAllowResInner(resourceRequest, pid);
760     return ERR_OK;
761 }
762 
ApplyAllowResInner(const ResourceRequest & resourceRequest,int32_t pid)763 void StandbyServiceImpl::ApplyAllowResInner(const ResourceRequest& resourceRequest, int32_t pid)
764 {
765     STANDBYSERVICE_LOGI("apply res inner, uid: %{public}d, name: %{public}s, allowType: %{public}u,"\
766         " duration: %{public}d, reason: %{public}s", resourceRequest.GetUid(),
767         resourceRequest.GetName().c_str(), resourceRequest.GetAllowType(),
768         resourceRequest.GetDuration(), resourceRequest.GetReason().c_str());
769 
770     int32_t uid = resourceRequest.GetUid();
771     const std::string& name = resourceRequest.GetName();
772     std::string keyStr = std::to_string(uid) + "_" + name;
773     uint32_t preAllowType = 0;
774 
775     std::lock_guard<std::mutex> allowRecordLock(allowRecordMutex_);
776     auto iter = allowInfoMap_.find(keyStr);
777     if (iter == allowInfoMap_.end()) {
778         std::tie(iter, std::ignore) =
779             allowInfoMap_.emplace(keyStr, std::make_shared<AllowRecord>(uid, pid, name, 0));
780         iter->second->reasonCode_ = resourceRequest.GetReasonCode();
781     } else {
782         preAllowType = iter->second->allowType_;
783         iter->second->pid_ = pid;
784     }
785     UpdateRecord(iter->second, resourceRequest);
786     if (preAllowType != iter->second->allowType_) {
787         uint32_t alowTypeDiff = iter->second->allowType_ ^ (preAllowType &
788             iter->second->allowType_);
789         STANDBYSERVICE_LOGI("after update record, there is added exemption type: %{public}d",
790             alowTypeDiff);
791         StandbyStateSubscriber::GetInstance()->ReportAllowListChanged(uid, name, alowTypeDiff, true);
792         NotifyAllowListChanged(uid, name, alowTypeDiff, true);
793     }
794     if (iter->second->allowType_ == 0) {
795         STANDBYSERVICE_LOGI("%{public}s does not have valid record, delete record", keyStr.c_str());
796         allowInfoMap_.erase(iter);
797     }
798     DumpPersistantData();
799 }
800 
UpdateRecord(std::shared_ptr<AllowRecord> & allowRecord,const ResourceRequest & resourceRequest)801 void StandbyServiceImpl::UpdateRecord(std::shared_ptr<AllowRecord>& allowRecord,
802     const ResourceRequest& resourceRequest)
803 {
804     int32_t uid = resourceRequest.GetUid();
805     const std::string& name = resourceRequest.GetName();
806     uint32_t allowType = resourceRequest.GetAllowType();
807     bool isApp = (resourceRequest.GetReasonCode() == ReasonCodeEnum::REASON_APP_API);
808     int64_t curTime = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
809     int64_t endTime {0};
810     uint32_t condition = TimeProvider::GetCondition();
811     STANDBYSERVICE_LOGI(
812         "start UpdateRecord uid: %{public}d, name: %{public}s, isApp: %{public}d, condition: %{public}u",
813         uid, name.c_str(), isApp, condition);
814     for (uint32_t allowTypeIndex = 0; allowTypeIndex < MAX_ALLOW_TYPE_NUM; ++allowTypeIndex) {
815         uint32_t allowNumber = allowType & (1 << allowTypeIndex);
816         if (allowNumber == 0) {
817             continue;
818         }
819         int64_t maxDuration = 0;
820         if (allowNumber != AllowType::WORK_SCHEDULER) {
821             maxDuration = std::min(resourceRequest.GetDuration(), StandbyConfigManager::GetInstance()->
822                 GetMaxDuration(name, AllowTypeName[allowTypeIndex], condition, isApp)) * TimeConstant::MSEC_PER_SEC;
823         } else {
824             maxDuration = resourceRequest.GetDuration() * TimeConstant::MSEC_PER_SEC;
825         }
826         if (maxDuration <= 0) {
827             continue;
828         }
829         endTime = curTime + maxDuration;
830         auto& allowTimeList = allowRecord->allowTimeList_;
831         auto findRecordTask = [allowTypeIndex](const auto& it) { return it.allowTypeIndex_ == allowTypeIndex; };
832         auto it = std::find_if(allowTimeList.begin(), allowTimeList.end(), findRecordTask);
833         if (it == allowTimeList.end()) {
834             allowTimeList.emplace_back(AllowTime {allowTypeIndex, endTime, resourceRequest.GetReason()});
835         } else {
836             it->reason_ = resourceRequest.GetReason();
837             it->endTime_ = std::max(it->endTime_, endTime);
838         }
839         allowRecord->allowType_ = (allowRecord->allowType_ | allowNumber);
840         auto task = [this, uid, name, allowType] () {
841             this->UnapplyAllowResInner(uid, name, allowType, false);
842         };
843         handler_->PostTask(task, maxDuration);
844     }
845     STANDBYSERVICE_LOGE("update end time of allow list");
846 }
847 
UnapplyAllowResource(ResourceRequest & resourceRequest)848 ErrCode StandbyServiceImpl::UnapplyAllowResource(ResourceRequest& resourceRequest)
849 {
850     if (!IsServiceReady()) {
851         return ERR_STANDBY_SYS_NOT_READY;
852     }
853     STANDBYSERVICE_LOGD("start UnapplyAllowResource");
854     if (auto checkRet = CheckCallerPermission(resourceRequest.GetReasonCode()); checkRet != ERR_OK) {
855         return checkRet;
856     }
857 
858     // update allow type according to configuration
859     if (Security::AccessToken::AccessTokenKit::GetTokenType(OHOS::IPCSkeleton::GetCallingTokenID())
860         == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
861         resourceRequest.SetAllowType(GetExemptedResourceType(resourceRequest.GetAllowType()));
862     }
863 
864     if (!CheckAllowTypeInfo(resourceRequest.GetAllowType()) || resourceRequest.GetUid() < 0) {
865         STANDBYSERVICE_LOGE("param of resourceRequest is invalid");
866         return ERR_RESOURCE_TYPES_INVALID;
867     }
868     UnapplyAllowResInner(resourceRequest.GetUid(), resourceRequest.GetName(), resourceRequest.GetAllowType(), true);
869     return ERR_OK;
870 }
871 
UnapplyAllowResInner(int32_t uid,const std::string & name,uint32_t allowType,bool removeAll)872 void StandbyServiceImpl::UnapplyAllowResInner(int32_t uid, const std::string& name,
873     uint32_t allowType, bool removeAll)
874 {
875     STANDBYSERVICE_LOGD("start UnapplyAllowResInner, uid is %{public}d, allowType is %{public}d, removeAll is "\
876         "%{public}d", uid, allowType, removeAll);
877     std::string keyStr = std::to_string(uid) + "_" + name;
878 
879     std::lock_guard<std::mutex> allowRecordLock(allowRecordMutex_);
880     auto iter = allowInfoMap_.find(keyStr);
881     if (iter == allowInfoMap_.end()) {
882         STANDBYSERVICE_LOGD("uid has no corresponding allow list");
883         return;
884     }
885     if ((allowType & iter->second->allowType_) == 0) {
886         STANDBYSERVICE_LOGD("allow list has no corresponding allow type");
887         return;
888     }
889     auto& allowRecordPtr = iter->second;
890     auto& allowTimeList = allowRecordPtr->allowTimeList_;
891     uint32_t removedNumber = 0;
892     int64_t curTime = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
893     for (auto it = allowTimeList.begin(); it != allowTimeList.end();) {
894         uint32_t allowNumber = allowType & (1 << it->allowTypeIndex_);
895         if (allowNumber != 0 && (removeAll || curTime >= it->endTime_)) {
896             it = allowTimeList.erase(it);
897             removedNumber |= allowNumber;
898         } else {
899             ++it;
900         }
901     }
902     STANDBYSERVICE_LOGD("remove allow list, uid: %{public}d, type: %{public}u", uid, removedNumber);
903     if (removedNumber == 0) {
904         STANDBYSERVICE_LOGW("none member of the allow list should be removed");
905         return;
906     }
907     if (removedNumber == allowRecordPtr->allowType_) {
908         allowInfoMap_.erase(keyStr);
909         STANDBYSERVICE_LOGI("allow list has been delete");
910     } else {
911         allowRecordPtr->allowType_ = allowRecordPtr->allowType_ - removedNumber;
912     }
913     StandbyStateSubscriber::GetInstance()->ReportAllowListChanged(uid, name, removedNumber, false);
914     NotifyAllowListChanged(uid, name, removedNumber, false);
915     DumpPersistantData();
916 }
917 
OnProcessStatusChanged(int32_t uid,int32_t pid,const std::string & bundleName,bool isCreated)918 void StandbyServiceImpl::OnProcessStatusChanged(int32_t uid, int32_t pid, const std::string& bundleName, bool isCreated)
919 {
920     if (!IsServiceReady()) {
921         return;
922     }
923     STANDBYSERVICE_LOGI("process status change, uid: %{public}d, pid: %{public}d, name: %{public}s, alive: %{public}d",
924         uid, pid, bundleName.c_str(), isCreated);
925     StandbyMessage standbyMessage {StandbyMessageType::PROCESS_STATE_CHANGED};
926     standbyMessage.want_ = AAFwk::Want {};
927     standbyMessage.want_->SetParam("uid", uid);
928     standbyMessage.want_->SetParam("pid", pid);
929     standbyMessage.want_->SetParam("name", bundleName);
930     standbyMessage.want_->SetParam("isCreated", isCreated);
931     DispatchEvent(standbyMessage);
932 }
933 
NotifyAllowListChanged(int32_t uid,const std::string & name,uint32_t allowType,bool added)934 void StandbyServiceImpl::NotifyAllowListChanged(int32_t uid, const std::string& name,
935     uint32_t allowType, bool added)
936 {
937     StandbyMessage standbyMessage {StandbyMessageType::ALLOW_LIST_CHANGED};
938     standbyMessage.want_ = AAFwk::Want {};
939     standbyMessage.want_->SetParam("uid", uid);
940     standbyMessage.want_->SetParam("name", name);
941     standbyMessage.want_->SetParam("allowType", static_cast<int>(allowType));
942     standbyMessage.want_->SetParam("added", added);
943     DispatchEvent(standbyMessage);
944 }
945 
GetAllowList(uint32_t allowType,std::vector<AllowInfo> & allowInfoList,uint32_t reasonCode)946 ErrCode StandbyServiceImpl::GetAllowList(uint32_t allowType, std::vector<AllowInfo>& allowInfoList,
947     uint32_t reasonCode)
948 {
949     if (!IsServiceReady()) {
950         return ERR_STANDBY_SYS_NOT_READY;
951     }
952 
953     STANDBYSERVICE_LOGD("start GetAllowList");
954     if (auto checkRet = CheckCallerPermission(reasonCode); checkRet != ERR_OK) {
955         return checkRet;
956     }
957 
958     if (!CheckAllowTypeInfo(allowType)) {
959         STANDBYSERVICE_LOGE("allowtype param is invalid");
960         return ERR_RESOURCE_TYPES_INVALID;
961     }
962     GetAllowListInner(allowType, allowInfoList, reasonCode);
963     return ERR_OK;
964 }
965 
GetAllowListInner(uint32_t allowType,std::vector<AllowInfo> & allowInfoList,uint32_t reasonCode)966 void StandbyServiceImpl::GetAllowListInner(uint32_t allowType, std::vector<AllowInfo>& allowInfoList,
967     uint32_t reasonCode)
968 {
969     STANDBYSERVICE_LOGD("start GetAllowListInner, allowType is %{public}d", allowType);
970 
971     std::lock_guard<std::mutex> allowRecordLock(allowRecordMutex_);
972     for (uint32_t allowTypeIndex = 0; allowTypeIndex < MAX_ALLOW_TYPE_NUM; ++allowTypeIndex) {
973         uint32_t allowNumber = allowType & (1 << allowTypeIndex);
974         if (allowNumber == 0) {
975             continue;
976         }
977         GetTemporaryAllowList(allowTypeIndex, allowInfoList, reasonCode);
978         bool isApp = (reasonCode == ReasonCodeEnum::REASON_APP_API);
979         GetPersistAllowList(allowTypeIndex, allowInfoList, true, isApp);
980     }
981 }
982 
GetTemporaryAllowList(uint32_t allowTypeIndex,std::vector<AllowInfo> & allowInfoList,uint32_t reasonCode)983 void StandbyServiceImpl::GetTemporaryAllowList(uint32_t allowTypeIndex, std::vector<AllowInfo>&
984     allowInfoList, uint32_t reasonCode)
985 {
986     int64_t curTime = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
987     auto findRecordTask = [allowTypeIndex](const auto& it) { return it.allowTypeIndex_ == allowTypeIndex; };
988     for (auto& [key, allowRecordPtr] : allowInfoMap_) {
989         if ((allowRecordPtr->allowType_ & (1 << allowTypeIndex)) == 0) {
990             continue;
991         }
992         if (allowRecordPtr->reasonCode_ != reasonCode) {
993             continue;
994         }
995         auto& allowTimeList = allowRecordPtr->allowTimeList_;
996         auto it = std::find_if(allowTimeList.begin(), allowTimeList.end(), findRecordTask);
997         if (it == allowTimeList.end()) {
998             continue;
999         }
1000         int64_t duration =  std::max(static_cast<int64_t>(it->endTime_ - curTime), static_cast<int64_t>(0L));
1001         if (duration > 0) {
1002             allowInfoList.emplace_back((1 << allowTypeIndex), allowRecordPtr->name_, duration);
1003         } else {
1004             auto task = [this, allowRecordPtr = allowRecordPtr] () {
1005                 this->UnapplyAllowResInner(allowRecordPtr->uid_, allowRecordPtr->name_,
1006                     allowRecordPtr->allowType_, false);
1007             };
1008             handler_->PostTask(task);
1009         }
1010     }
1011 }
1012 
GetPersistAllowList(uint32_t allowTypeIndex,std::vector<AllowInfo> & allowInfoList,bool isAllow,bool isApp)1013 void StandbyServiceImpl::GetPersistAllowList(uint32_t allowTypeIndex, std::vector<AllowInfo>& allowInfoList,
1014     bool isAllow, bool isApp)
1015 {
1016     uint32_t condition = TimeProvider::GetCondition();
1017     std::set<std::string> psersistAllowList;
1018     if (isApp) {
1019         psersistAllowList = StandbyConfigManager::GetInstance()->GetEligiblePersistAllowConfig(
1020             AllowTypeName[allowTypeIndex], condition, isAllow, true);
1021     } else {
1022         psersistAllowList = StandbyConfigManager::GetInstance()->GetEligiblePersistAllowConfig(
1023             AllowTypeName[allowTypeIndex], condition, isAllow, false);
1024     }
1025     for (const auto& allowName : psersistAllowList) {
1026         allowInfoList.emplace_back((1 << allowTypeIndex), allowName, -1);
1027     }
1028 }
1029 
IsDeviceInStandby(bool & isStandby)1030 ErrCode StandbyServiceImpl::IsDeviceInStandby(bool& isStandby)
1031 {
1032     if (auto checkRet = CheckCallerPermission(); checkRet != ERR_OK) {
1033         STANDBYSERVICE_LOGE("caller permission denied.");
1034         return checkRet;
1035     }
1036 
1037     if (!IsServiceReady()) {
1038         return ERR_STANDBY_SYS_NOT_READY;
1039     }
1040     handler_->PostSyncTask([this, &isStandby]() {
1041         auto curState = standbyStateManager_->GetCurState();
1042         isStandby = (curState == StandbyState::SLEEP);
1043         }, AppExecFwk::EventQueue::Priority::HIGH);
1044     return ERR_OK;
1045 }
1046 
GetEligiableRestrictSet(uint32_t allowType,const std::string & strategyName,uint32_t resonCode,std::set<std::string> & restrictSet)1047 ErrCode StandbyServiceImpl::GetEligiableRestrictSet(uint32_t allowType, const std::string& strategyName,
1048     uint32_t resonCode, std::set<std::string>& restrictSet)
1049 {
1050     uint32_t condition = TimeProvider::GetCondition();
1051     std::set<std::string> originRestrictSet = StandbyConfigManager::GetInstance()->GetEligiblePersistAllowConfig(
1052         strategyName, condition, false, resonCode == ReasonCodeEnum::REASON_APP_API);
1053     std::vector<AllowInfo> allowInfoList;
1054     GetAllowListInner(allowType, allowInfoList, resonCode);
1055     std::set<std::string> allowSet;
1056     for_each(allowInfoList.begin(), allowInfoList.end(),
1057         [&allowSet](AllowInfo& allowInfo) { allowSet.insert(allowInfo.GetName()); });
1058 
1059     std::set_difference(originRestrictSet.begin(), originRestrictSet.end(), allowSet.begin(),
1060         allowSet.end(), std::inserter(restrictSet, restrictSet.begin()));
1061     STANDBYSERVICE_LOGD("origin restrict size is %{public}d, restrictSet size is %{public}d, "\
1062         "restrictSet size is %{public}d", static_cast<int32_t>(originRestrictSet.size()),
1063         static_cast<int32_t>(allowInfoList.size()), static_cast<int32_t>(restrictSet.size()));
1064     return ERR_OK;
1065 }
1066 
ReportWorkSchedulerStatus(bool started,int32_t uid,const std::string & bundleName)1067 ErrCode StandbyServiceImpl::ReportWorkSchedulerStatus(bool started, int32_t uid, const std::string& bundleName)
1068 {
1069     if (auto checkRet = CheckCallerPermission(); checkRet != ERR_OK) {
1070         STANDBYSERVICE_LOGE("caller permission denied.");
1071         return checkRet;
1072     }
1073 
1074     if (!IsServiceReady()) {
1075         return ERR_STANDBY_SYS_NOT_READY;
1076     }
1077     STANDBYSERVICE_LOGD("work scheduler status changed, isstarted: %{public}d, uid: %{public}d, bundleName: %{public}s",
1078         started, uid, bundleName.c_str());
1079     StandbyMessage standbyMessage {StandbyMessageType::BG_TASK_STATUS_CHANGE};
1080     standbyMessage.want_ = AAFwk::Want {};
1081     standbyMessage.want_->SetParam(BG_TASK_TYPE, WORK_SCHEDULER);
1082     standbyMessage.want_->SetParam(BG_TASK_STATUS, started);
1083     standbyMessage.want_->SetParam(BG_TASK_UID, uid);
1084     DispatchEvent(standbyMessage);
1085     return ERR_OK;
1086 }
1087 
GetRestrictList(uint32_t restrictType,std::vector<AllowInfo> & restrictInfoList,uint32_t reasonCode)1088 ErrCode StandbyServiceImpl::GetRestrictList(uint32_t restrictType, std::vector<AllowInfo>& restrictInfoList,
1089     uint32_t reasonCode)
1090 {
1091     if (auto checkRet = CheckCallerPermission(reasonCode); checkRet != ERR_OK) {
1092         STANDBYSERVICE_LOGE("caller permission denied.");
1093         return checkRet;
1094     }
1095     if (!IsServiceReady()) {
1096         return ERR_STANDBY_SYS_NOT_READY;
1097     }
1098     STANDBYSERVICE_LOGD("start GetRestrictList");
1099     if (!CheckAllowTypeInfo(restrictType)) {
1100         STANDBYSERVICE_LOGE("restrictType param is invalid");
1101         return ERR_RESOURCE_TYPES_INVALID;
1102     }
1103     GetRestrictListInner(restrictType, restrictInfoList, reasonCode);
1104     return ERR_OK;
1105 }
1106 
GetRestrictListInner(uint32_t restrictType,std::vector<AllowInfo> & restrictInfoList,uint32_t reasonCode)1107 void StandbyServiceImpl::GetRestrictListInner(uint32_t restrictType, std::vector<AllowInfo>& restrictInfoList,
1108     uint32_t reasonCode)
1109 {
1110     STANDBYSERVICE_LOGD("start GetRestrictListInner, restrictType is %{public}d", restrictType);
1111     for (uint32_t restrictTypeIndex = 0; restrictTypeIndex < MAX_ALLOW_TYPE_NUM; ++restrictTypeIndex) {
1112         uint32_t restrictNumber = restrictType & (1 << restrictTypeIndex);
1113         if (restrictNumber == 0) {
1114             continue;
1115         }
1116         bool isApp = (reasonCode == ReasonCodeEnum::REASON_APP_API);
1117         GetPersistAllowList(restrictTypeIndex, restrictInfoList, false, isApp);
1118     }
1119 }
1120 
IsStrategyEnabled(const std::string & strategyName,bool & isStandby)1121 ErrCode StandbyServiceImpl::IsStrategyEnabled(const std::string& strategyName, bool& isStandby)
1122 {
1123     if (auto checkRet = CheckCallerPermission(); checkRet != ERR_OK) {
1124         STANDBYSERVICE_LOGE("caller permission denied.");
1125         return checkRet;
1126     }
1127 
1128     if (!IsServiceReady()) {
1129         return ERR_STANDBY_SYS_NOT_READY;
1130     }
1131     STANDBYSERVICE_LOGD("start IsStrategyEnabled");
1132     const auto& strategyConfigList = StandbyConfigManager::GetInstance()->GetStrategyConfigList();
1133     auto item = std::find(strategyConfigList.begin(), strategyConfigList.end(), strategyName);
1134     isStandby = item != strategyConfigList.end();
1135     return ERR_OK;
1136 }
1137 
ReportPowerOverused(const std::string & module,uint32_t level)1138 ErrCode StandbyServiceImpl::ReportPowerOverused(const std::string &module, uint32_t level)
1139 {
1140     STANDBYSERVICE_LOGD("[PowerOverused] StandbyServiceImpl: power overused, "
1141         "modue name: %{public}s, level: %{public}u", module.c_str(), level);
1142 
1143     if (auto checkRet = CheckCallerPermission(); checkRet != ERR_OK) {
1144         STANDBYSERVICE_LOGE("[PowerOverused] Caller permission denied.");
1145         return checkRet;
1146     }
1147 
1148     HandlePowerOverused(0, module, level);
1149     return ERR_OK;
1150 }
1151 
ReportSceneInfo(uint32_t resType,int64_t value,const std::string & sceneInfo)1152 ErrCode StandbyServiceImpl::ReportSceneInfo(uint32_t resType, int64_t value, const std::string &sceneInfo)
1153 {
1154     if (auto checkRet = CheckCallerPermission(ReasonCodeEnum::REASON_NATIVE_API); checkRet != ERR_OK) {
1155         STANDBYSERVICE_LOGE("caller permission denied.");
1156         return checkRet;
1157     }
1158 
1159     if (!IsServiceReady()) {
1160         return ERR_STANDBY_SYS_NOT_READY;
1161     }
1162     StandbyMessage standbyMessage {resType};
1163     standbyMessage.want_ = AAFwk::Want {};
1164     standbyMessage.want_->SetParam("value", static_cast<int32_t>(value));
1165     standbyMessage.want_->SetParam("sceneInfo", sceneInfo);
1166     DispatchEvent(standbyMessage);
1167     return ERR_OK;
1168 }
1169 
ReportDeviceStateChanged(int32_t type,bool enabled)1170 ErrCode StandbyServiceImpl::ReportDeviceStateChanged(int32_t type, bool enabled)
1171 {
1172     if (!IsServiceReady()) {
1173         return ERR_STANDBY_SYS_NOT_READY;
1174     }
1175 
1176     if (auto checkRet = CheckCallerPermission(); checkRet != ERR_OK) {
1177         STANDBYSERVICE_LOGE("caller permission denied.");
1178         return checkRet;
1179     }
1180 
1181     STANDBYSERVICE_LOGI("device state changed, state type: %{public}d, enabled: %{public}d",
1182         static_cast<int32_t>(type), enabled);
1183     DeviceStateCache::GetInstance()->SetDeviceState(type, enabled);
1184     if (!enabled) {
1185         return ERR_OK;
1186     }
1187     StandbyMessage standbyMessage {StandbyMessageType::DEVICE_STATE_CHANGED};
1188     standbyMessage.want_ = AAFwk::Want {};
1189     standbyMessage.want_->SetParam("DIS_COMP_STATE", enabled);
1190     DispatchEvent(standbyMessage);
1191     return ERR_OK;
1192 }
1193 
HandleCallStateChanged(const std::string & sceneInfo)1194 void WEAK_FUNC StandbyServiceImpl::HandleCallStateChanged(const std::string &sceneInfo)
1195 {
1196     nlohmann::json payload = nlohmann::json::parse(sceneInfo, nullptr, false);
1197     if (payload.is_discarded()) {
1198         STANDBYSERVICE_LOGE("parse json failed");
1199     }
1200     int32_t state = -1;
1201     if (payload.at("state").is_string()) {
1202         state = atoi(payload["state"].get<std::string>().c_str());
1203     }
1204     if (payload.at("state").is_number_integer()) {
1205         state = payload["state"].get<std::int32_t>();
1206     }
1207     bool disable = (state == static_cast<int32_t>(TelCallState::CALL_STATUS_UNKNOWN) ||
1208                     state == static_cast<int32_t>(TelCallState::CALL_STATUS_DISCONNECTED) ||
1209                     state == static_cast<int32_t>(TelCallState::CALL_STATUS_IDLE));
1210     DeviceStateCache::GetInstance()->SetDeviceState(
1211     static_cast<int32_t>(DeviceStateType::TELEPHONE_STATE_CHANGE), !disable);
1212 }
1213 
HandleP2PStateChanged(int32_t state)1214 void WEAK_FUNC StandbyServiceImpl::HandleP2PStateChanged(int32_t state)
1215 {
1216     bool disable = (state == static_cast<int32_t>(P2pState::P2P_STATE_IDLE) ||
1217                     state == static_cast<int32_t>(P2pState::P2P_STATE_NONE) ||
1218                     state == static_cast<int32_t>(P2pState::P2P_STATE_CLOSED));
1219     DeviceStateCache::GetInstance()->SetDeviceState(
1220     static_cast<int32_t>(DeviceStateType::WIFI_P2P_CHANGE), !disable);
1221 }
1222 
HandleScreenStateChanged(const int64_t value)1223 void StandbyServiceImpl::HandleScreenStateChanged(const int64_t value)
1224 {
1225     if (value == 1) {
1226             DispatchEvent(StandbyMessage(StandbyMessageType::COMMON_EVENT,
1227                                          EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON));
1228     } else {
1229             DispatchEvent(StandbyMessage(StandbyMessageType::COMMON_EVENT,
1230                                          EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF));
1231     }
1232 }
1233 
HandleChargeStateChanged(const int64_t value)1234 void StandbyServiceImpl::HandleChargeStateChanged(const int64_t value)
1235 {
1236     auto event = value == 0 ? EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING :
1237         EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING;
1238     DispatchEvent(StandbyMessage(StandbyMessageType::COMMON_EVENT, event));
1239 }
1240 
HandleScreenClickRecognize(const int64_t value)1241 void StandbyServiceImpl::HandleScreenClickRecognize(const int64_t value)
1242 {
1243     StandbyMessage standbyMessage {StandbyMessageType::SCREEN_CLICK_RECOGNIZE};
1244     standbyMessage.want_ = AAFwk::Want {};
1245     standbyMessage.want_->SetParam("clickType", static_cast<int32_t>(value));
1246     DispatchEvent(standbyMessage);
1247 }
1248 
HandleBTServiceEvent(const int64_t value,const std::string & sceneInfo)1249 void StandbyServiceImpl::HandleBTServiceEvent(const int64_t value, const std::string &sceneInfo)
1250 {
1251     STANDBYSERVICE_LOGI("HandleBTSerciceEvent value: %{public}" PRId64, value);
1252     nlohmann::json payload = nlohmann::json::parse(sceneInfo, nullptr, false);
1253     if (payload.is_discarded()) {
1254         STANDBYSERVICE_LOGE("parse json failed");
1255     }
1256     if (value == ResourceSchedule::ResType::BtServiceEvent::GATT_APP_REGISTER) {
1257         if (!payload.contains("ACTION") || !payload.contains("ADDRESS") || !payload.contains("PID") ||
1258             !payload.at("ACTION").is_string() || !payload.at("ADDRESS").is_string() || !payload.at("PID").is_string()) {
1259             STANDBYSERVICE_LOGE("Bt Gatt Register info is valid");
1260             return;
1261         }
1262         std::string action = payload["ACTION"].get<std::string>();
1263         std::string address = payload["ADDRESS"].get<std::string>();
1264         int32_t uid = atoi(payload["UID"].get<std::string>().c_str());
1265         StandbyMessage standbyMessage {StandbyMessageType::GATT_APP_REGISTER};
1266         standbyMessage.want_ = AAFwk::Want {};
1267         standbyMessage.want_->SetParam("ACTION", action);
1268         standbyMessage.want_->SetParam("ADDRESS", address);
1269         standbyMessage.want_->SetParam("UID", uid);
1270         DispatchEvent(standbyMessage);
1271     } else if (value == ResourceSchedule::ResType::BtServiceEvent::GATT_CONNECT_STATE) {
1272         if (!payload.contains("ADDRESS") || !payload.contains("STATE") ||
1273             !payload.at("ADDRESS").is_string() || !payload.at("STATE").is_string()) {
1274             STANDBYSERVICE_LOGE("Bt Gatt Connection info is valid");
1275             return;
1276         }
1277         std::string address = payload["ADDRESS"].get<std::string>();
1278         int32_t state = atoi(payload["STATE"].get<std::string>().c_str());
1279         StandbyMessage standbyMessage {StandbyMessageType::GATT_CONNECT_STATE};
1280         standbyMessage.want_ = AAFwk::Want {};
1281         standbyMessage.want_->SetParam("ADDRESS", address);
1282         standbyMessage.want_->SetParam("STATE", state);
1283         DispatchEvent(standbyMessage);
1284     }
1285 }
1286 
HandleBrokerGattConnect(const int64_t value,const std::string & sceneInfo)1287 void StandbyServiceImpl::HandleBrokerGattConnect(const int64_t value, const std::string &sceneInfo)
1288 {
1289     STANDBYSERVICE_LOGI("HandleBrokerGattConnect value: %{public}" PRId64, value);
1290     nlohmann::json payload = nlohmann::json::parse(sceneInfo, nullptr, false);
1291     if (payload.is_discarded()) {
1292         STANDBYSERVICE_LOGE("parse json failed");
1293     }
1294     if (value) {
1295         if (!payload.contains("clientIf") || !payload.contains("pkg") || !payload.at("clientIf").is_string() ||
1296             !payload.at("pkg").is_string()) {
1297             STANDBYSERVICE_LOGE("Broker Gatt connect info is valid");
1298             return;
1299         }
1300         std::string pkg = payload["pkg"].get<std::string>();
1301         int32_t clientIf = atoi(payload["clientIf"].get<std::string>().c_str());
1302         bool connect = true;
1303         StandbyMessage standbyMessage {StandbyMessageType::BROKER_GATT_CONNECT};
1304         standbyMessage.want_ = AAFwk::Want {};
1305         standbyMessage.want_->SetParam("clientIf", clientIf);
1306         standbyMessage.want_->SetParam("pkg", pkg);
1307         standbyMessage.want_->SetParam("connect", connect);
1308         DispatchEvent(standbyMessage);
1309     } else {
1310         if (!payload.contains("clientIf") || !payload.at("clientIf").is_string()) {
1311             STANDBYSERVICE_LOGE("Broker Gatt disconnect info is valid");
1312             return;
1313         }
1314         int32_t clientIf = atoi(payload["clientIf"].get<std::string>().c_str());
1315         bool connect = false;
1316         StandbyMessage standbyMessage {StandbyMessageType::BROKER_GATT_CONNECT};
1317         standbyMessage.want_ = AAFwk::Want {};
1318         standbyMessage.want_->SetParam("clientIf", clientIf);
1319         standbyMessage.want_->SetParam("connect", connect);
1320         DispatchEvent(standbyMessage);
1321     }
1322 }
1323 
HandleMmiInputPowerKeyDown(const int64_t value)1324 void StandbyServiceImpl::HandleMmiInputPowerKeyDown(const int64_t value)
1325 {
1326     StandbyMessage standbyMessage {StandbyMessageType::MMI_INPUT_POWER_KEY_DOWN};
1327     standbyMessage.want_ = AAFwk::Want {};
1328     standbyMessage.want_->SetParam("keyCode", value);
1329     DispatchEvent(standbyMessage);
1330 }
1331 
HandleReportFileSizeEvent()1332 void StandbyServiceImpl::HandleReportFileSizeEvent()
1333 {
1334     std::vector<std::string> currentDir;
1335     const std::vector<std::string> directories = {DEVICE_STANDBY_DIR, DEVICE_STANDBY_RDB_DIR};
1336 
1337     for (const auto& dirPath : directories) {
1338         bool result = ResourceSchedule::ResCommonUtil::DirIterator(dirPath, currentDir);
1339         if (!result) {
1340             STANDBYSERVICE_LOGE("Failed to iterate directory: %{public}s", dirPath.c_str());
1341             return;
1342         }
1343     }
1344     ResourceSchedule::ResschedEventReporter::GetInstance().ReportFileSizeEvent(currentDir);
1345 }
1346 
DumpOnPowerOverused(const std::vector<std::string> & argsInStr,std::string & result)1347 void StandbyServiceImpl::DumpOnPowerOverused(const std::vector<std::string> &argsInStr, std::string &result)
1348 {
1349     constexpr uint16_t DUMP_THREE_PARAM = 3;
1350     if (argsInStr.size() != DUMP_THREE_PARAM) {
1351         STANDBYSERVICE_LOGE("DumpOnPowerOverused param check failed, shoule be [--poweroverused module level].");
1352         return;
1353     }
1354 
1355     const std::string &module = argsInStr[DUMP_SECOND_PARAM];
1356     uint32_t level = static_cast<uint32_t>(std::atoi(argsInStr[DUMP_THIRD_PARAM].c_str()));
1357     HandlePowerOverused(0, module, level);
1358 }
1359 
DumpOnActionChanged(const std::vector<std::string> & argsInStr,std::string & result)1360 void StandbyServiceImpl::DumpOnActionChanged(const std::vector<std::string> &argsInStr, std::string &result)
1361 {
1362     constexpr uint16_t DUMP_THREE_PARAM = 3;
1363     if (argsInStr.size() != DUMP_THREE_PARAM) {
1364         STANDBYSERVICE_LOGE("DumpOnActionChanged param check failed, shoule be [--actionchanged module action].");
1365         return;
1366     }
1367 
1368     const std::string &module = argsInStr[DUMP_SECOND_PARAM];
1369     uint32_t action = static_cast<uint32_t>(std::atoi(argsInStr[DUMP_THIRD_PARAM].c_str()));
1370     HandleActionChanged(0, module, action);
1371 }
1372 
1373 // handle power overused, resType for extend
HandlePowerOverused(uint32_t resType,const std::string & module,uint32_t level)1374 void StandbyServiceImpl::HandlePowerOverused([[maybe_unused]]uint32_t resType,
1375     const std::string &module, uint32_t level)
1376 {
1377     StandbyStateSubscriber::GetInstance()->NotifyPowerOverusedByCallback(module, level);
1378 }
1379 
1380 // handle action changed, resType for extend
HandleActionChanged(uint32_t resType,const std::string & module,uint32_t action)1381 void StandbyServiceImpl::HandleActionChanged([[maybe_unused]]uint32_t resType,
1382     const std::string &module, uint32_t action)
1383 {
1384     StandbyStateSubscriber::GetInstance()->NotifyLowpowerActionByCallback(module, action);
1385 }
1386 
HandleResourcesStateChanged(const int64_t value,const std::string & sceneInfo)1387 void StandbyServiceImpl::HandleResourcesStateChanged(const int64_t value, const std::string &sceneInfo)
1388 {
1389         bool isApply = false;
1390         if (value == ResourceSchedule::ResType::EfficiencyResourcesStatus::APP_EFFICIENCY_RESOURCES_APPLY ||
1391             value == ResourceSchedule::ResType::EfficiencyResourcesStatus::PROC_EFFICIENCY_RESOURCES_APPLY) {
1392             isApply = true;
1393         }
1394         nlohmann::json payload = nlohmann::json::parse(sceneInfo, nullptr, false);
1395         if (payload.is_discarded()) {
1396             STANDBYSERVICE_LOGE("parse json failed");
1397             return;
1398         }
1399         if (!payload.contains("bundleName") || !payload.contains("resourceNumber")) {
1400             STANDBYSERVICE_LOGE("param does not exist");
1401             return;
1402         }
1403         if (!payload.at("bundleName").is_string()) {
1404             STANDBYSERVICE_LOGE("bundle name param is invalid");
1405             return;
1406         }
1407         std::string bundleName = payload.at("bundleName").get<std::string>();
1408         if (!payload.at("resourceNumber").is_number_unsigned()) {
1409             STANDBYSERVICE_LOGE("resource number param is invalid");
1410             return;
1411         }
1412         uint32_t resourceNumber = payload["resourceNumber"].get<std::uint32_t>();
1413         StandbyMessage standbyMessage {StandbyMessageType::BG_EFFICIENCY_RESOURCE_APPLY};
1414         standbyMessage.want_ = AAFwk::Want {};
1415         standbyMessage.want_->SetParam(BG_TASK_BUNDLE_NAME, bundleName);
1416         standbyMessage.want_->SetParam(BG_TASK_RESOURCE_STATUS, isApply);
1417         standbyMessage.want_->SetParam(BG_TASK_TYPE, static_cast<int32_t>(resourceNumber));
1418         DispatchEvent(standbyMessage);
1419 }
1420 
HandleBootCompleted()1421 void StandbyServiceImpl::HandleBootCompleted()
1422 {
1423     DispatchEvent(StandbyMessage(StandbyMessageType::COMMON_EVENT,
1424         EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED));
1425 }
1426 
HandleThermalScenarioReport(const int64_t value,const std::string & sceneInfo)1427 void StandbyServiceImpl::HandleThermalScenarioReport(const int64_t value, const std::string &sceneInfo)
1428 {
1429     StandbyMessage standbyMessage {StandbyMessageType::THERMAL_SCENARIO_REPORT};
1430     standbyMessage.want_ = AAFwk::Want {};
1431     standbyMessage.want_->SetParam("scenario", value);
1432     standbyMessage.want_->SetParam("sceneInfo", sceneInfo);
1433     DispatchEvent(standbyMessage);
1434 }
1435 
HandleCommonEvent(const uint32_t resType,const int64_t value,const std::string & sceneInfo)1436 ErrCode StandbyServiceImpl::HandleCommonEvent(const uint32_t resType, const int64_t value, const std::string &sceneInfo)
1437 {
1438     STANDBYSERVICE_LOGD("HandleCommonEvent resType = %{public}u, value = %{public}lld, sceneInfo = %{public}s",
1439                         resType, (long long)(value), sceneInfo.c_str());
1440     switch (resType) {
1441         case ResourceSchedule::ResType::RES_TYPE_SCREEN_STATUS:
1442             HandleScreenStateChanged(value);
1443             break;
1444         case ResourceSchedule::ResType::RES_TYPE_CHARGING_DISCHARGING:
1445             HandleChargeStateChanged(value);
1446             break;
1447         case ResourceSchedule::ResType::RES_TYPE_USB_DEVICE:
1448             DispatchEvent(StandbyMessage(StandbyMessageType::COMMON_EVENT,
1449                 (value ? EventFwk::CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED :
1450                     EventFwk::CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED)));
1451             break;
1452         case ResourceSchedule::ResType::RES_TYPE_CALL_STATE_CHANGED:
1453             HandleCallStateChanged(sceneInfo);
1454             break;
1455         case ResourceSchedule::ResType::RES_TYPE_WIFI_P2P_STATE_CHANGED:
1456             HandleP2PStateChanged(value);
1457             break;
1458         case ResourceSchedule::ResType::RES_TYPE_CLICK_RECOGNIZE:
1459             HandleScreenClickRecognize(value);
1460             break;
1461         case ResourceSchedule::ResType::RES_TYPE_MMI_INPUT_POWER_KEY:
1462             HandleMmiInputPowerKeyDown(value);
1463             break;
1464         case ResourceSchedule::ResType::RES_TYPE_BT_SERVICE_EVENT:
1465             HandleBTServiceEvent(value, sceneInfo);
1466             break;
1467         case ResourceSchedule::ResType::RES_TYPE_REPORT_BOKER_GATT_CONNECT:
1468             HandleBrokerGattConnect(value, sceneInfo);
1469             break;
1470         case ResourceSchedule::ResType::RES_TYPE_POWER_MODE_CHANGED:
1471             HandlePowerModeChanged(value);
1472             break;
1473         case ResourceSchedule::ResType::RES_TYPE_EFFICIENCY_RESOURCES_STATE_CHANGED:
1474             HandleResourcesStateChanged(value, sceneInfo);
1475             break;
1476         case ResourceSchedule::ResType::RES_TYPE_BOOT_COMPLETED:
1477             HandleBootCompleted();
1478             break;
1479         case ResourceSchedule::ResType::RES_TYPE_THERMAL_SCENARIO_REPORT:
1480             HandleThermalScenarioReport(value, sceneInfo);
1481             break;
1482         default:
1483             AppEventHandler(resType, value, sceneInfo);
1484             break;
1485     }
1486     return ERR_OK;
1487 }
1488 
HandlePowerModeChanged(const int64_t value)1489 void StandbyServiceImpl::HandlePowerModeChanged(const int64_t value)
1490 {
1491     StandbyMessage message(StandbyMessageType::COMMON_EVENT);
1492     message.action_ = EventFwk::CommonEventSupport::COMMON_EVENT_POWER_SAVE_MODE_CHANGED;
1493     message.want_ = AAFwk::Want {};
1494     message.want_->SetParam("current_power_mode", static_cast<int32_t>(value));
1495     DispatchEvent(message);
1496 }
1497 
AppEventHandler(const uint32_t resType,const int64_t value,const std::string & sceneInfo)1498 void StandbyServiceImpl::AppEventHandler(const uint32_t resType, const int64_t value, const std::string &sceneInfo)
1499 {
1500     if (resType == ResourceSchedule::ResType::RES_TYPE_APP_INSTALL_UNINSTALL &&
1501         (value == ResourceSchedule::ResType::AppInstallStatus::APP_UNINSTALL ||
1502          value == ResourceSchedule::ResType::AppInstallStatus::APP_CHANGED ||
1503          value == ResourceSchedule::ResType::AppInstallStatus::APP_REPLACED ||
1504          value == ResourceSchedule::ResType::AppInstallStatus::BUNDLE_REMOVED ||
1505          value == ResourceSchedule::ResType::AppInstallStatus::APP_FULLY_REMOVED)
1506         ) {
1507         nlohmann::json payload = nlohmann::json::parse(sceneInfo, nullptr, false);
1508         if (payload.is_discarded()) {
1509             STANDBYSERVICE_LOGE("parse json failed");
1510             return;
1511         }
1512         if (!payload.contains("bundleName") || !payload.contains("uid")) {
1513             STANDBYSERVICE_LOGE("HandleCommonEvent,There is no valid bundle name in payload");
1514             return;
1515         }
1516         if (!payload.at("bundleName").is_string()) {
1517             STANDBYSERVICE_LOGE("bundle name is invaild");
1518             return;
1519         }
1520         std::string bundleName = payload.at("bundleName").get<std::string>();
1521         int32_t uid = -1;
1522         if (payload.at("uid").is_string()) {
1523             uid = atoi(payload["uid"].get<std::string>().c_str());
1524         }
1525         if (payload.at("uid").is_number_integer()) {
1526             uid = payload["uid"].get<std::int32_t>();
1527         }
1528         handler_->PostTask([uid, bundleName]() {
1529             StandbyServiceImpl::GetInstance()->RemoveAppAllowRecord(uid, bundleName, true);
1530         });
1531     } else if (resType == ResourceSchedule::ResType::RES_TYPE_TIMEZONE_CHANGED ||
1532                resType == ResourceSchedule::ResType::RES_TYPE_NITZ_TIMEZONE_CHANGED ||
1533                resType == ResourceSchedule::ResType::RES_TYPE_TIME_CHANGED ||
1534                resType == ResourceSchedule::ResType::RES_TYPE_NITZ_TIME_CHANGED) {
1535         handler_->PostTask([]() {StandbyServiceImpl::GetInstance()->ResetTimeObserver(); });
1536     }
1537 }
1538 
DispatchEvent(const StandbyMessage & message)1539 void StandbyServiceImpl::DispatchEvent(const StandbyMessage& message)
1540 {
1541     if (!IsServiceReady()) {
1542         return;
1543     }
1544 
1545     auto dispatchEventFunc = [this, message]() {
1546         STANDBYSERVICE_LOGD("standby service implement dispatch message %{public}d", message.eventId_);
1547         if (!listenerManager_ || !standbyStateManager_ || !strategyManager_) {
1548             STANDBYSERVICE_LOGE("can not dispatch event, state manager or strategy manager is nullptr");
1549             return;
1550         };
1551         listenerManager_->HandleEvent(message);
1552         standbyStateManager_->HandleEvent(message);
1553         strategyManager_->HandleEvent(message);
1554     };
1555 
1556     handler_->PostTask(dispatchEventFunc);
1557 }
1558 
IsDebugMode()1559 bool StandbyServiceImpl::IsDebugMode()
1560 {
1561     return debugMode_;
1562 }
1563 
ShellDump(const std::vector<std::string> & argsInStr,std::string & result)1564 void StandbyServiceImpl::ShellDump(const std::vector<std::string>& argsInStr,
1565     std::string& result)
1566 {
1567     if (!isServiceReady_.load()) {
1568         result += "standby service manager is not ready";
1569         return;
1570     }
1571     handler_->PostSyncTask([this, &argsInStr, &result]() {
1572         this->ShellDumpInner(argsInStr, result);
1573         }, AppExecFwk::EventQueue::Priority::HIGH);
1574 }
1575 
ShellDumpInner(const std::vector<std::string> & argsInStr,std::string & result)1576 void StandbyServiceImpl::ShellDumpInner(const std::vector<std::string>& argsInStr,
1577     std::string& result)
1578 {
1579     auto argc = argsInStr.size();
1580     if (argc == NO_DUMP_PARAM_NUMS || argsInStr[DUMP_FIRST_PARAM] == "-h") {
1581         DumpUsage(result);
1582     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_DETAIL_INFO) {
1583         DumpShowDetailInfo(argsInStr, result);
1584         OnPluginShellDump(argsInStr, result);
1585     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_ENTER_STATE) {
1586         DumpEnterSpecifiedState(argsInStr, result);
1587     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_APPLY_ALLOW_RECORD) {
1588         DumpModifyAllowList(argsInStr, result);
1589     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_SIMULATE_SENSOR) {
1590         OnPluginShellDump(argsInStr, result);
1591     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_SUBSCRIBER_OBSERVER) {
1592         DumpSubScriberObserver(argsInStr, result);
1593     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_TURN_ON_OFF_SWITCH) {
1594         DumpTurnOnOffSwitch(argsInStr, result);
1595     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_CHANGE_STATE_TIMEOUT) {
1596         DumpChangeConfigParam(argsInStr, result);
1597     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_PUSH_STRATEGY_CHANGE) {
1598         DumpPushStrategyChange(argsInStr, result);
1599     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_ON_POWER_OVERUSED) {
1600         DumpOnPowerOverused(argsInStr, result);
1601     } else if (argsInStr[DUMP_FIRST_PARAM] == DUMP_ON_ACTION_CHANGED) {
1602         DumpOnActionChanged(argsInStr, result);
1603     } else {
1604         result += "Error params.\n";
1605     }
1606 }
1607 
OnPluginShellDump(const std::vector<std::string> & argsInStr,std::string & result)1608 void StandbyServiceImpl::OnPluginShellDump(const std::vector<std::string>& argsInStr, std::string& result)
1609 {
1610     standbyStateManager_->ShellDump(argsInStr, result);
1611     constraintManager_->ShellDump(argsInStr, result);
1612     strategyManager_->ShellDump(argsInStr, result);
1613     listenerManager_->ShellDump(argsInStr, result);
1614 }
1615 
DumpUsage(std::string & result)1616 void StandbyServiceImpl::DumpUsage(std::string& result)
1617 {
1618     std::string dumpHelpMsg =
1619     "usage: dev standby service dump [<options>]\n"
1620     "options list:\n"
1621     "    -h                                                 help menu\n"
1622     "    -D                                                 show detail information\n"
1623     "        --config                                            show all info, including config\n"
1624     "        --reset_state                                       reset parameter, validate debug parameter\n"
1625     "        --strategy                                          dump strategy info\n"
1626     "    -E                                                 enter the specified state:\n"
1627     "        {name of state} {whether skip evalution}       enter the specified state, respectively named\n"
1628     "                                                            woking, dark, nap, maintenance, sleep\n"
1629     "    -A                                                 modify the allow list:\n"
1630     "        --apply {uid} {name} {type} {duration} {reasoncode} apply the type of the uid to allow list\n"
1631     "        --unapply {uid} {name} {type}                  delete the type of the uid from allow list\n"
1632     "        --get {type} {isApp}                                get allow list info\n"
1633     "    -S                                                 simulate some action:\n"
1634     "        {--motion}                                          activate the motion sensor when enter idle\n"
1635     "        {--repeat}                                          be in motion mode, only used in idle state\n"
1636     "        {--blocked}                                         block current state\n"
1637     "        {--poweroff}                                        power off strategy\n"
1638     "        {--powersave}                                       enable power save firwwall\n"
1639     "        {--halfhour}                                        screen off for half hour\n"
1640     "    -T  {switch name} {on or off}                      turn on or turn off some switches, switch can be debug,\n"
1641     "                                                            nap_switch, sleep_switch, detect_motion, other\n"
1642     "                                                            switch only be used after open debug switch\n"
1643     "    -C  {parameter name} {parameter value}             change config parameter, only can be used when debug\n"
1644     "    -P                                                 sending network limiting and restoring network broadcasts\n"
1645     "        {--whitelist} {parameter value}                send whitelist changes event\n"
1646     "        {--ctrinetwork}                                send network limiting broadcasts\n"
1647     "        {--restorectrlnetwork}                         send restore network broadcasts\n";
1648 
1649     result.append(dumpHelpMsg);
1650 }
1651 
DumpShowDetailInfo(const std::vector<std::string> & argsInStr,std::string & result)1652 void StandbyServiceImpl::DumpShowDetailInfo(const std::vector<std::string>& argsInStr,
1653     std::string& result)
1654 {
1655     DumpAllowListInfo(result);
1656     if (argsInStr.size() < DUMP_DETAILED_INFO_MAX_NUMS) {
1657         return;
1658     }
1659     if (argsInStr[DUMP_SECOND_PARAM] == DUMP_DETAIL_CONFIG) {
1660         DumpStandbyConfigInfo(result);
1661     }
1662 }
1663 
DumpAllowListInfo(std::string & result)1664 void StandbyServiceImpl::DumpAllowListInfo(std::string& result)
1665 {
1666     std::lock_guard<std::mutex> allowRecordLock(allowRecordMutex_);
1667     if (allowInfoMap_.empty()) {
1668         result += "allow resources record is empty\n";
1669         return;
1670     }
1671 
1672     std::stringstream stream;
1673     uint32_t index = 1;
1674     for (auto iter = allowInfoMap_.begin(); iter != allowInfoMap_.end(); iter++) {
1675         stream << "No." << index << "\n";
1676         stream << "\tuid: " << iter->first << "\n";
1677         stream << "\tallow record: " << "\n";
1678         stream << "\t\tname: " << iter->second->name_ << "\n";
1679         stream << "\t\tpid: " << iter->second->pid_ << "\n";
1680         stream << "\t\tallow type: " << iter->second->allowType_ << "\n";
1681         stream << "\t\treason code: " << iter->second->reasonCode_ << "\n";
1682         int64_t curTime = MiscServices::TimeServiceClient::GetInstance()->GetMonotonicTimeMs();
1683         auto &allowTimeList = iter->second->allowTimeList_;
1684         for (auto unitIter = allowTimeList.begin();
1685             unitIter != allowTimeList.end(); ++unitIter) {
1686             stream << "\t\t\tallow type: " << AllowTypeName[unitIter->allowTypeIndex_] << "\n";
1687             stream << "\t\t\tremainTime: " << unitIter->endTime_ - curTime << "\n";
1688             stream << "\t\t\treason: " << unitIter->reason_ << "\n";
1689         }
1690         stream << "\n";
1691         result += stream.str();
1692         stream.str("");
1693         stream.clear();
1694         index++;
1695     }
1696 }
1697 
DumpStandbyConfigInfo(std::string & result)1698 void StandbyServiceImpl::DumpStandbyConfigInfo(std::string& result)
1699 {
1700     result += (debugMode_ ? "debugMode: true\n" : "debugMode: false\n");
1701     StandbyConfigManager::GetInstance()->DumpStandbyConfigInfo(result);
1702 }
1703 
DumpEnterSpecifiedState(const std::vector<std::string> & argsInStr,std::string & result)1704 void StandbyServiceImpl::DumpEnterSpecifiedState(const std::vector<std::string>& argsInStr,
1705     std::string& result)
1706 {
1707     if (argsInStr.size() < DUMP_SLEEP_ENTER_STATE_NUMS) {
1708         result += "not enough parameter for changing sleep mode\n";
1709         return;
1710     } else {
1711         standbyStateManager_->ShellDump(argsInStr, result);
1712     }
1713 }
1714 
DumpModifyAllowList(const std::vector<std::string> & argsInStr,std::string & result)1715 void StandbyServiceImpl::DumpModifyAllowList(const std::vector<std::string>& argsInStr,
1716     std::string& result)
1717 {
1718     if (argsInStr.size() < DUMP_SLEEP_ALLOW_LIST_NUMS || (argsInStr[DUMP_SECOND_PARAM] != "--get" &&
1719         argsInStr.size() < DUMP_SLEEP_APPLY_ALLOW_LIST_NUMS)) {
1720         result += "not enough parameter for changing allow list\n";
1721         return;
1722     }
1723     int32_t uid = std::atoi(argsInStr[DUMP_THIRD_PARAM].c_str());
1724     std::string name = argsInStr[DUMP_FOURTH_PARAM];
1725     if (argsInStr[DUMP_SECOND_PARAM] == "--apply") {
1726         uint32_t allowType = static_cast<uint32_t>(std::atoi(argsInStr[DUMP_FIFTH_PARAM].c_str()));
1727         int32_t duration = std::atoi(argsInStr[DUMP_SIXTH_PARAM].c_str());
1728         std::shared_ptr<ResourceRequest> resourceRequest = std::make_shared<ResourceRequest>(allowType,
1729             uid, name, duration, "dump", std::atoi(argsInStr[DUMP_SEVENTH_PARAM].c_str()));
1730         ApplyAllowResource(*resourceRequest);
1731         result += "add one object to allow list\n";
1732     } else if (argsInStr[DUMP_SECOND_PARAM] == "--unapply") {
1733         uint32_t allowType = static_cast<uint32_t>(std::atoi(argsInStr[DUMP_FIFTH_PARAM].c_str()));
1734         std::shared_ptr<ResourceRequest> resourceRequest = std::make_shared<ResourceRequest>(allowType,
1735             uid, name, 0, "dump", std::atoi(argsInStr[DUMP_SEVENTH_PARAM].c_str()));
1736         UnapplyAllowResource(*resourceRequest);
1737         result += "remove one object to allow list\n";
1738     } else if (argsInStr[DUMP_SECOND_PARAM] == "--get") {
1739         uint32_t allowType = static_cast<uint32_t>(std::atoi(argsInStr[DUMP_THIRD_PARAM].c_str()));
1740         bool isApp = (std::atoi(argsInStr[DUMP_FOURTH_PARAM].c_str()) == 0);
1741         std::vector<AllowInfo> allowInfoList;
1742         GetAllowListInner(allowType, allowInfoList, isApp);
1743         for (const auto& allowInfo : allowInfoList) {
1744             result += "allowType: " + std::to_string(allowInfo.GetAllowType()) + "\n" +
1745             "name: " + allowInfo.GetName() + "\n" +
1746             "duration: " + std::to_string(allowInfo.GetDuration()) + "\n";
1747         }
1748         allowInfoList.clear();
1749         GetRestrictListInner(allowType, allowInfoList, isApp);
1750         for (const auto& allowInfo : allowInfoList) {
1751             result += "restrictType: " + std::to_string(allowInfo.GetAllowType()) + "\n" +
1752             "name: " + allowInfo.GetName() + "\n";
1753         }
1754     }
1755 }
1756 
DumpTurnOnOffSwitch(const std::vector<std::string> & argsInStr,std::string & result)1757 void StandbyServiceImpl::DumpTurnOnOffSwitch(const std::vector<std::string>& argsInStr, std::string& result)
1758 {
1759     if (argsInStr.size() != DUMP_SWITCH_PARAM_NUMS) {
1760         result += "not correct parameter number for turn on or turn off switch\n";
1761         return;
1762     }
1763     bool switchStatus {false};
1764     if (argsInStr[DUMP_THIRD_PARAM] == DUMP_ON) {
1765         switchStatus = true;
1766     } else if (argsInStr[DUMP_THIRD_PARAM] == DUMP_OFF) {
1767         switchStatus = false;
1768     } else {
1769         result += "not correct parameter for turn on or turn off switch\n";
1770         return;
1771     }
1772     const std::string& switchName = argsInStr[DUMP_SECOND_PARAM];
1773     if (switchName == DUMP_DEBUG_SWITCH) {
1774         debugMode_ = switchStatus;
1775         StandbyConfigManager::GetInstance()->DumpSetDebugMode(debugMode_);
1776         result += (debugMode_ ? "debugMode: true\n" : "debugMode: false\n");
1777         return;
1778     } else if (!debugMode_) {
1779         result += "other switch can be changed only in debug mode\n";
1780         return;
1781     }
1782     StandbyConfigManager::GetInstance()->DumpSetSwitch(switchName, switchStatus, result);
1783 }
1784 
DumpChangeConfigParam(const std::vector<std::string> & argsInStr,std::string & result)1785 void StandbyServiceImpl::DumpChangeConfigParam(const std::vector<std::string>& argsInStr, std::string& result)
1786 {
1787     if (argsInStr.size() != DUMP_STATE_TIMEOUT_PARAM_NUMS) {
1788         result += "not correct parameter number for change state timeout\n";
1789         return;
1790     }
1791     if (!debugMode_) {
1792         result += "current is not in debug mode, can not change timeout\n";
1793         return;
1794     }
1795     StandbyConfigManager::GetInstance()->DumpSetParameter(argsInStr[DUMP_SECOND_PARAM],
1796         std::atoi(argsInStr[DUMP_THIRD_PARAM].c_str()), result);
1797 }
1798 
DumpPushStrategyChange(const std::vector<std::string> & argsInStr,std::string & result)1799 void StandbyServiceImpl::DumpPushStrategyChange(const std::vector<std::string>& argsInStr, std::string& result)
1800 {
1801     if (argsInStr[DUMP_SECOND_PARAM] == "--whitelist") {
1802         StandbyStateSubscriber::GetInstance()->NotifyAllowChangedByCommonEvent(
1803             std::atoi(argsInStr[DUMP_THIRD_PARAM].c_str()), argsInStr[DUMP_FOURTH_PARAM],
1804             std::atoi(argsInStr[DUMP_FIFTH_PARAM].c_str()), argsInStr[DUMP_SIXTH_PARAM] == "true");
1805     }
1806     strategyManager_->ShellDump(argsInStr, result);
1807 }
1808 
DumpSubScriberObserver(const std::vector<std::string> & argsInStr,std::string & result)1809 void StandbyServiceImpl::DumpSubScriberObserver(const std::vector<std::string>& argsInStr, std::string& result)
1810 {
1811     StandbyStateSubscriber::GetInstance()->ShellDump(argsInStr, result);
1812 }
1813 
DeviceStateCache()1814 DeviceStateCache::DeviceStateCache()
1815 {
1816     deviceState_ = {false, false, false};
1817 }
1818 
~DeviceStateCache()1819 DeviceStateCache::~DeviceStateCache() {}
1820 
GetInstance()1821 std::shared_ptr<DeviceStateCache> DeviceStateCache::GetInstance()
1822 {
1823     return DelayedSingleton<DeviceStateCache>::GetInstance();
1824 }
1825 
SetDeviceState(int32_t type,bool enabled)1826 bool DeviceStateCache::SetDeviceState(int32_t type, bool enabled)
1827 {
1828     STANDBYSERVICE_LOGD("set device state %{public}d, enabled is %{public}d", type, enabled);
1829     if (type < 0 || type >= DEVICE_STATE_NUM) {
1830         return false;
1831     }
1832     std::lock_guard<std::mutex> lock(mutex_);
1833     if (deviceState_[type] == enabled) {
1834         return false;
1835     }
1836     deviceState_[type] = enabled;
1837     return true;
1838 }
1839 
GetDeviceState(int32_t type)1840 bool DeviceStateCache::GetDeviceState(int32_t type)
1841 {
1842     if (type < 0 || type >= DEVICE_STATE_NUM) {
1843         return false;
1844     }
1845     STANDBYSERVICE_LOGD("get device state %{public}d, enabled is %{public}d", type, deviceState_[type]);
1846     return deviceState_[type];
1847 }
1848 }  // namespace DevStandbyMgr
1849 }  // namespace OHOS
1850