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