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