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.h"
17
18 #include <functional>
19 #include <map>
20
21 #include "accesstoken_kit.h"
22 #include "parameter.h"
23 #include "ipc_skeleton.h"
24 #include "file_ex.h"
25 #include "string_ex.h"
26
27 #include "system_ability_definition.h"
28 #include "device_standby_switch.h"
29 #include "standby_service_impl.h"
30 #include "standby_hitrace_chain.h"
31 #include "standby_service_log.h"
32 #include "standby_config_manager.h"
33
34 namespace OHOS {
35 namespace DevStandbyMgr {
36 namespace {
37 const uint32_t COMMON_EVENT_READY = 1;
38 const uint32_t TIMER_SERVICE_READY = 2;
39 const uint32_t ABILITY_SERVICE_READY = 4;
40 const uint32_t BUNDLE_MGR_READY = 8;
41 const uint32_t POWER_SERVICE_READY = 16;
42 const uint32_t APP_MGR_SERVICE_READY = 32;
43 const uint32_t MULTIMODAL_INPUT_SERVICE_READY = 64;
44 const uint32_t ALL_DEPENDS_READY = 127;
45 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
46 StandbyService::GetInstance().get());
47 const bool SOFTWARE_SLEEP = system::GetBoolParameter("persist.sys.standby_switch", true);
48 const std::string RSS_PROCESS_NAME = "resource_schedule_service";
49 const std::string PUSH_PROCESS_NAME = "push_manager_service";
50 const int32_t ENG_MODE = OHOS::system::GetIntParameter("const.debuggable", 0);
51 const std::string EXTENSION_BACKUP = "backup";
52 const std::string EXTENSION_RESTORE = "restore";
53 }
54
StandbyService()55 StandbyService::StandbyService() : SystemAbility(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID, true) {}
56
StandbyService(const int32_t systemAbilityId,bool runOnCreate)57 StandbyService::StandbyService(const int32_t systemAbilityId, bool runOnCreate)
58 : SystemAbility(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID, true) {}
59
~StandbyService()60 StandbyService::~StandbyService() {}
61
GetInstance()62 std::shared_ptr<StandbyService> StandbyService::GetInstance()
63 {
64 return DelayedSingleton<StandbyService>::GetInstance();
65 }
66
OnStart()67 void StandbyService::OnStart()
68 {
69 StandbyHitraceChain traceChain(__func__);
70 if (!SOFTWARE_SLEEP) {
71 return;
72 }
73 if (state_.load() == ServiceRunningState::STATE_RUNNING) {
74 STANDBYSERVICE_LOGW("device standby service has already started.");
75 return;
76 }
77 if (!StandbyServiceImpl::GetInstance()->Init()) {
78 STANDBYSERVICE_LOGE("failed to init device standby service");
79 return;
80 }
81 InitStandyMode();
82 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
83 AddSystemAbilityListener(TIME_SERVICE_ID);
84 AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
85 AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
86 AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID);
87 AddSystemAbilityListener(APP_MGR_SERVICE_ID);
88 AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
89 if (!Publish(StandbyService::GetInstance().get())) {
90 STANDBYSERVICE_LOGE("standby service start failed!");
91 return;
92 }
93 state_.store(ServiceRunningState::STATE_RUNNING);
94 STANDBYSERVICE_LOGI("standby service start succeed!");
95 }
96
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)97 void StandbyService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
98 {
99 STANDBYSERVICE_LOGI("add system ability, systemAbilityId : %{public}d", systemAbilityId);
100 std::lock_guard<std::mutex> systemAbilityLock(systemAbilityLock_);
101 auto serviceImpl = StandbyServiceImpl::GetInstance();
102 switch (systemAbilityId) {
103 case COMMON_EVENT_SERVICE_ID:
104 STANDBYSERVICE_LOGD("common event service is ready!");
105 serviceImpl->UpdateSaDependValue(true, COMMON_EVENT_READY);
106 serviceImpl->RegisterCommEventObserver();
107 break;
108 case TIME_SERVICE_ID:
109 STANDBYSERVICE_LOGD("timer service is ready!");
110 serviceImpl->UpdateSaDependValue(true, TIMER_SERVICE_READY);
111 serviceImpl->RegisterTimeObserver();
112 break;
113 case ABILITY_MGR_SERVICE_ID:
114 STANDBYSERVICE_LOGD("ability mgr service is ready!");
115 serviceImpl->UpdateSaDependValue(true, ABILITY_SERVICE_READY);
116 break;
117 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID:
118 STANDBYSERVICE_LOGD("bundle mgr service is ready!");
119 serviceImpl->UpdateSaDependValue(true, BUNDLE_MGR_READY);
120 break;
121 case POWER_MANAGER_SERVICE_ID:
122 STANDBYSERVICE_LOGD("power service is ready!");
123 serviceImpl->UpdateSaDependValue(true, POWER_SERVICE_READY);
124 break;
125 case APP_MGR_SERVICE_ID:
126 STANDBYSERVICE_LOGD("app mgr service is ready!");
127 serviceImpl->UpdateSaDependValue(true, APP_MGR_SERVICE_READY);
128 serviceImpl->RegisterAppStateObserver();
129 break;
130 case MULTIMODAL_INPUT_SERVICE_ID:
131 STANDBYSERVICE_LOGD("multi modal input service is ready!");
132 serviceImpl->UpdateSaDependValue(true, MULTIMODAL_INPUT_SERVICE_READY);
133 break;
134 default:
135 NotifySystemAbilityStatusChanged(true, systemAbilityId);
136 break;
137 }
138 if (serviceImpl->GetSaDependValue() == ALL_DEPENDS_READY) {
139 STANDBYSERVICE_LOGI("all necessary system service for standby service has been satisfied!");
140 serviceImpl->InitReadyState();
141 }
142 }
143
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)144 void StandbyService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
145 {
146 StandbyHitraceChain traceChain(__func__);
147 STANDBYSERVICE_LOGI("remove system ability, systemAbilityId : %{public}d", systemAbilityId);
148 std::lock_guard<std::mutex> systemAbilityLock(systemAbilityLock_);
149 auto serviceImpl = StandbyServiceImpl::GetInstance();
150 switch (systemAbilityId) {
151 case COMMON_EVENT_SERVICE_ID:
152 STANDBYSERVICE_LOGI("common event service is removed!");
153 serviceImpl->UpdateSaDependValue(false, COMMON_EVENT_READY);
154 serviceImpl->UnregisterCommEventObserver();
155 break;
156 case TIME_SERVICE_ID:
157 STANDBYSERVICE_LOGI("time service is removed!");
158 serviceImpl->UpdateSaDependValue(false, TIMER_SERVICE_READY);
159 serviceImpl->UnregisterTimeObserver();
160 break;
161 case ABILITY_MGR_SERVICE_ID:
162 STANDBYSERVICE_LOGI("ability mgr service is removed!");
163 serviceImpl->UpdateSaDependValue(false, ABILITY_SERVICE_READY);
164 break;
165 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID:
166 STANDBYSERVICE_LOGI("bundle mgr service is removed!");
167 serviceImpl->UpdateSaDependValue(false, BUNDLE_MGR_READY);
168 break;
169 case POWER_MANAGER_SERVICE_ID:
170 STANDBYSERVICE_LOGI("power service is removed!");
171 serviceImpl->UpdateSaDependValue(false, POWER_SERVICE_READY);
172 break;
173 case APP_MGR_SERVICE_ID:
174 STANDBYSERVICE_LOGI("app mgr service is removed!");
175 serviceImpl->UpdateSaDependValue(false, APP_MGR_SERVICE_READY);
176 serviceImpl->UnregisterAppStateObserver();
177 break;
178 case MULTIMODAL_INPUT_SERVICE_ID:
179 STANDBYSERVICE_LOGI("multi modal input service is removed!");
180 serviceImpl->UpdateSaDependValue(false, MULTIMODAL_INPUT_SERVICE_READY);
181 break;
182 default:
183 NotifySystemAbilityStatusChanged(false, systemAbilityId);
184 break;
185 }
186 if (serviceImpl->GetSaDependValue() != ALL_DEPENDS_READY) {
187 STANDBYSERVICE_LOGI("necessary system service for standby service has been unsatisfied");
188 serviceImpl->UninitReadyState();
189 }
190 }
191
SubscribeStandbyCallback(const sptr<IStandbyServiceSubscriber> & subscriber,const std::string & subscriberName,const std::string & moduleName)192 ErrCode StandbyService::SubscribeStandbyCallback(const sptr<IStandbyServiceSubscriber>& subscriber,
193 const std::string& subscriberName, const std::string& moduleName)
194 {
195 StandbyHitraceChain traceChain(__func__);
196 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
197 STANDBYSERVICE_LOGW("standby service is not running");
198 return ERR_STANDBY_SYS_NOT_READY;
199 }
200 subscriber->SetSubscriberName(subscriberName);
201 subscriber->SetModuleName(moduleName);
202 return StandbyServiceImpl::GetInstance()->SubscribeStandbyCallback(subscriber);
203 }
204
UnsubscribeStandbyCallback(const sptr<IStandbyServiceSubscriber> & subscriber)205 ErrCode StandbyService::UnsubscribeStandbyCallback(const sptr<IStandbyServiceSubscriber>& subscriber)
206 {
207 StandbyHitraceChain traceChain(__func__);
208 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
209 STANDBYSERVICE_LOGW("standby service is not running");
210 return ERR_STANDBY_SYS_NOT_READY;
211 }
212 return StandbyServiceImpl::GetInstance()->UnsubscribeStandbyCallback(subscriber);
213 }
214
ApplyAllowResource(const ResourceRequest & resourceRequest)215 ErrCode StandbyService::ApplyAllowResource(const ResourceRequest& resourceRequest)
216 {
217 StandbyHitraceChain traceChain(__func__);
218 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
219 STANDBYSERVICE_LOGW("standby service is not running");
220 return ERR_STANDBY_SYS_NOT_READY;
221 }
222 ResourceRequest request(resourceRequest);
223 return StandbyServiceImpl::GetInstance()->ApplyAllowResource(request);
224 }
225
UnapplyAllowResource(const ResourceRequest & resourceRequest)226 ErrCode StandbyService::UnapplyAllowResource(const ResourceRequest& resourceRequest)
227 {
228 StandbyHitraceChain traceChain(__func__);
229 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
230 STANDBYSERVICE_LOGW("standby service is not running");
231 return ERR_STANDBY_SYS_NOT_READY;
232 }
233 ResourceRequest request(resourceRequest);
234 return StandbyServiceImpl::GetInstance()->UnapplyAllowResource(request);
235 }
236
GetAllowList(uint32_t allowType,std::vector<AllowInfo> & allowInfoList,uint32_t reasonCode)237 ErrCode StandbyService::GetAllowList(uint32_t allowType, std::vector<AllowInfo>& allowInfoList,
238 uint32_t reasonCode)
239 {
240 StandbyHitraceChain traceChain(__func__);
241 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
242 STANDBYSERVICE_LOGW("standby service is not running");
243 return ERR_STANDBY_SYS_NOT_READY;
244 }
245 return StandbyServiceImpl::GetInstance()->GetAllowList(allowType, allowInfoList, reasonCode);
246 }
247
IsDeviceInStandby(bool & isStandby)248 ErrCode StandbyService::IsDeviceInStandby(bool& isStandby)
249 {
250 StandbyHitraceChain traceChain(__func__);
251 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
252 STANDBYSERVICE_LOGW("standby service is not running");
253 return ERR_STANDBY_SYS_NOT_READY;
254 }
255 return StandbyServiceImpl::GetInstance()->IsDeviceInStandby(isStandby);
256 }
257
SetNatInterval(uint32_t type,bool enable,uint32_t interval)258 ErrCode StandbyService::SetNatInterval(uint32_t type, bool enable, uint32_t interval)
259 {
260 StandbyHitraceChain traceChain(__func__);
261 if (!CheckProcessNamePermission(PUSH_PROCESS_NAME)) {
262 STANDBYSERVICE_LOGE("set nat interval permission check fail");
263 return ERR_PERMISSION_DENIED;
264 }
265 StandbyMessage standbyMessage{StandbyMessageType::NAT_DETECT_INTERVAL_CHANGED};
266 standbyMessage.want_ = AAFwk::Want {};
267 standbyMessage.want_->SetParam(MESSAGE_TYPE, static_cast<int32_t>(type));
268 standbyMessage.want_->SetParam(MESSAGE_ENABLE, enable);
269 standbyMessage.want_->SetParam(MESSAGE_INTERVAL, static_cast<int32_t>(interval));
270 StandbyServiceImpl::GetInstance()->DispatchEvent(standbyMessage);
271 return ERR_OK;
272 }
273
DelayHeartBeat(int64_t timestamp)274 ErrCode StandbyService::DelayHeartBeat(int64_t timestamp)
275 {
276 StandbyHitraceChain traceChain(__func__);
277 if (!CheckProcessNamePermission(PUSH_PROCESS_NAME)) {
278 STANDBYSERVICE_LOGE("delay heartbeat permission check fail");
279 return ERR_PERMISSION_DENIED;
280 }
281 StandbyMessage standbyMessage{StandbyMessageType::NAT_MSG_RECV};
282 standbyMessage.want_ = AAFwk::Want {};
283 standbyMessage.want_->SetParam(MESSAGE_TIMESTAMP, static_cast<int32_t>(timestamp));
284 StandbyServiceImpl::GetInstance()->DispatchEvent(standbyMessage);
285 return ERR_OK;
286 }
287
ReportSceneInfo(uint32_t resType,int64_t value,const std::string & sceneInfo)288 ErrCode StandbyService::ReportSceneInfo(uint32_t resType, int64_t value, const std::string &sceneInfo)
289 {
290 StandbyHitraceChain traceChain(__func__);
291 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
292 STANDBYSERVICE_LOGW("standby service is not running");
293 return ERR_STANDBY_SYS_NOT_READY;
294 }
295 return StandbyServiceImpl::GetInstance()->ReportSceneInfo(resType, value, sceneInfo);
296 }
297
AddPluginSysAbilityListener(int32_t systemAbilityId)298 void StandbyService::AddPluginSysAbilityListener(int32_t systemAbilityId)
299 {
300 std::lock_guard<std::mutex> pluginListenerLock(listenedSALock_);
301 STANDBYSERVICE_LOGI("add listener to system ability %{public}d", systemAbilityId);
302 AddSystemAbilityListener(systemAbilityId);
303 }
304
NotifySystemAbilityStatusChanged(bool isAdded,int32_t systemAbilityId)305 ErrCode StandbyService::NotifySystemAbilityStatusChanged(bool isAdded, int32_t systemAbilityId)
306 {
307 StandbyMessage standbyMessage{StandbyMessageType::SYS_ABILITY_STATUS_CHANGED};
308 standbyMessage.want_ = AAFwk::Want {};
309 standbyMessage.want_->SetParam(SA_STATUS, isAdded);
310 standbyMessage.want_->SetParam(SA_ID, systemAbilityId);
311 StandbyServiceImpl::GetInstance()->DispatchEvent(standbyMessage);
312 return ERR_OK;
313 }
314
OnStop()315 void StandbyService::OnStop()
316 {
317 StandbyHitraceChain traceChain(__func__);
318 StandbyServiceImpl::GetInstance()->UnInit();
319 state_.store(ServiceRunningState::STATE_NOT_START);
320 STANDBYSERVICE_LOGI("standby service task manager stop");
321 }
322
OnExtension(const std::string & extension,MessageParcel & data,MessageParcel & reply)323 int32_t StandbyService::OnExtension(const std::string& extension, MessageParcel& data, MessageParcel& reply)
324 {
325 STANDBYSERVICE_LOGI("extension is %{public}s.", extension.c_str());
326 if (extension == EXTENSION_BACKUP) {
327 return StandbyServiceImpl::GetInstance()->OnBackup(data, reply);
328 } else if (extension == EXTENSION_RESTORE) {
329 return StandbyServiceImpl::GetInstance()->OnRestore(data, reply);
330 }
331 return ERR_OK;
332 }
333
ReportWorkSchedulerStatus(bool started,int32_t uid,const std::string & bundleName)334 ErrCode StandbyService::ReportWorkSchedulerStatus(bool started, int32_t uid, const std::string& bundleName)
335 {
336 StandbyHitraceChain traceChain(__func__);
337 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
338 STANDBYSERVICE_LOGW("standby service is not running");
339 return ERR_STANDBY_SYS_NOT_READY;
340 }
341 return StandbyServiceImpl::GetInstance()->ReportWorkSchedulerStatus(started, uid, bundleName);
342 }
343
GetRestrictList(uint32_t restrictType,std::vector<AllowInfo> & restrictInfoList,uint32_t reasonCode)344 ErrCode StandbyService::GetRestrictList(uint32_t restrictType, std::vector<AllowInfo>& restrictInfoList,
345 uint32_t reasonCode)
346 {
347 StandbyHitraceChain traceChain(__func__);
348 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
349 STANDBYSERVICE_LOGW("standby service is not running");
350 return ERR_STANDBY_SYS_NOT_READY;
351 }
352 return StandbyServiceImpl::GetInstance()->GetRestrictList(restrictType, restrictInfoList, reasonCode);
353 }
354
IsStrategyEnabled(const std::string & strategyName,bool & isEnabled)355 ErrCode StandbyService::IsStrategyEnabled(const std::string& strategyName, bool& isEnabled)
356 {
357 StandbyHitraceChain traceChain(__func__);
358 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
359 STANDBYSERVICE_LOGW("standby service is not running");
360 return ERR_STANDBY_SYS_NOT_READY;
361 }
362 return StandbyServiceImpl::GetInstance()->IsStrategyEnabled(strategyName, isEnabled);
363 }
364
ReportPowerOverused(const std::string & module,uint32_t level)365 ErrCode StandbyService::ReportPowerOverused(const std::string &module, uint32_t level)
366 {
367 StandbyHitraceChain traceChain(__func__);
368 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
369 STANDBYSERVICE_LOGW("standby service is not running");
370 return ERR_STANDBY_SYS_NOT_READY;
371 }
372
373 return StandbyServiceImpl::GetInstance()->ReportPowerOverused(module, level);
374 }
375
ReportDeviceStateChanged(int32_t type,bool enabled)376 ErrCode StandbyService::ReportDeviceStateChanged(int32_t type, bool enabled)
377 {
378 StandbyHitraceChain traceChain(__func__);
379 if (state_.load() != ServiceRunningState::STATE_RUNNING) {
380 STANDBYSERVICE_LOGW("standby service is not running");
381 return ERR_STANDBY_SYS_NOT_READY;
382 }
383 return StandbyServiceImpl::GetInstance()->ReportDeviceStateChanged(type, enabled);
384 }
385
Dump(int32_t fd,const std::vector<std::u16string> & args)386 int32_t StandbyService::Dump(int32_t fd, const std::vector<std::u16string>& args)
387 {
388 StandbyHitraceChain traceChain(__func__);
389 if (ENG_MODE == 0) {
390 STANDBYSERVICE_LOGE("Not Engineer mode");
391 return ERR_PERMISSION_DENIED;
392 }
393 Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
394 int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, "ohos.permission.DUMP");
395 if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
396 return ERR_PERMISSION_DENIED;
397 }
398 std::vector<std::string> argsInStr;
399 std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
400 [](const std::u16string& arg) {
401 return Str16ToStr8(arg);
402 });
403 std::string result;
404 StandbyServiceImpl::GetInstance()->ShellDump(argsInStr, result);
405 if (!SaveStringToFd(fd, result)) {
406 STANDBYSERVICE_LOGE("StandbyService dump save string to fd failed!");
407 return ERR_STANDBY_DUMP_SAVE_DENIED;
408 }
409 return ERR_OK;
410 }
411
CheckProcessNamePermission(const std::string & processName)412 bool StandbyService::CheckProcessNamePermission(const std::string& processName)
413 {
414 Security::AccessToken::NativeTokenInfo nativeTokenInfo;
415 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
416 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessToken);
417 int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
418 if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
419 result != ERR_OK || nativeTokenInfo.processName != processName) {
420 STANDBYSERVICE_LOGE("check processName failed,tokenType=%{public}d,processName=%{public}s",
421 tokenType, nativeTokenInfo.processName.c_str());
422 return false;
423 }
424 return true;
425 }
426
HandleEvent(const uint32_t resType,const int64_t value,const std::string & sceneInfo)427 ErrCode StandbyService::HandleEvent(const uint32_t resType, const int64_t value,
428 const std::string &sceneInfo)
429 {
430 StandbyHitraceChain traceChain(__func__);
431 if (!CheckProcessNamePermission(RSS_PROCESS_NAME)) {
432 return ERR_PERMISSION_DENIED;
433 }
434 StandbyServiceImpl::GetInstance()->HandleCommonEvent(resType, value, sceneInfo);
435 return ERR_OK;
436 }
437 } // namespace DevStandbyMgr
438 } // namespace OHOS
439