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