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