1 /*
2  * Copyright (c) 2022 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 "background_task_mgr_service.h"
17 #include "bgtask_config.h"
18 #include "bundle_manager_helper.h"
19 #include <functional>
20 #include "ability_manager_client.h"
21 #include "accesstoken_kit.h"
22 #include "bgtaskmgr_inner_errors.h"
23 #include "bundle_constants.h"
24 #include "common_event_manager.h"
25 #include "common_event_support.h"
26 #include "file_ex.h"
27 #include "ipc_skeleton.h"
28 #include "string_ex.h"
29 
30 #include "bgtaskmgr_log_wrapper.h"
31 #include <parameters.h>
32 
33 namespace OHOS {
34 namespace BackgroundTaskMgr {
35 namespace {
36 static constexpr int32_t NO_DUMP_PARAM_NUMS = 0;
37 static constexpr char BGMODE_PERMISSION[] = "ohos.permission.KEEP_BACKGROUND_RUNNING";
38 const int32_t ENG_MODE = OHOS::system::GetIntParameter("const.debuggable", 0);
39 const std::string BGTASK_SERVICE_NAME = "BgtaskMgrService";
40 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
41     DelayedSingleton<BackgroundTaskMgrService>::GetInstance().get());
42 }
43 
BackgroundTaskMgrService()44 BackgroundTaskMgrService::BackgroundTaskMgrService()
45     : SystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID, true) {}
46 
~BackgroundTaskMgrService()47 BackgroundTaskMgrService::~BackgroundTaskMgrService() {}
48 
OnStart()49 void BackgroundTaskMgrService::OnStart()
50 {
51     if (state_ == ServiceRunningState::STATE_RUNNING) {
52         BGTASK_LOGW("Service has already started.");
53         return;
54     }
55     Init();
56     AddSystemAbilityListener(APP_MGR_SERVICE_ID);
57     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
58     AddSystemAbilityListener(SA_ID_VOIP_CALL_MANAGER);
59     AddSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
60 }
61 
SetReady(uint32_t flag)62 void BackgroundTaskMgrService::SetReady(uint32_t flag)
63 {
64     {
65         std::lock_guard<std::mutex> lock(readyMutex_);
66         if (dependsReady_ == ServiceReadyState::ALL_READY) {
67             return;
68         }
69         dependsReady_ |= flag;
70         if (dependsReady_ != ServiceReadyState::ALL_READY) {
71             return;
72         }
73     }
74     DelayedSingleton<BgtaskConfig>::GetInstance()->Init();
75     if (!Publish(DelayedSingleton<BackgroundTaskMgrService>::GetInstance().get())) {
76         BGTASK_LOGE("Service start failed!");
77         return;
78     }
79     state_ = ServiceRunningState::STATE_RUNNING;
80     BGTASK_LOGI("background task manager service start succeed!");
81 }
82 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)83 void BackgroundTaskMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
84 {
85     DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->OnAddSystemAbility(systemAbilityId, deviceId);
86 }
87 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)88 void BackgroundTaskMgrService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
89 {
90     DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->OnRemoveSystemAbility(systemAbilityId, deviceId);
91     BgContinuousTaskMgr::GetInstance()->OnRemoveSystemAbility(systemAbilityId, deviceId);
92     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->OnRemoveSystemAbility(systemAbilityId, deviceId);
93 }
94 
Init()95 void BackgroundTaskMgrService::Init()
96 {
97     runner_ = AppExecFwk::EventRunner::Create(BGTASK_SERVICE_NAME);
98     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->Init(runner_);
99     DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->Init(runner_);
100     BgContinuousTaskMgr::GetInstance()->Init(runner_);
101 }
102 
OnStop()103 void BackgroundTaskMgrService::OnStop()
104 {
105     BgContinuousTaskMgr::GetInstance()->Clear();
106     DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->Clear();
107     state_ = ServiceRunningState::STATE_NOT_START;
108     BGTASK_LOGI("background task manager stop");
109 }
110 
CheckCallingToken()111 bool BackgroundTaskMgrService::CheckCallingToken()
112 {
113     Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
114     auto tokenFlag = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
115     if (tokenFlag == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
116         tokenFlag == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL) {
117         return true;
118     }
119     return false;
120 }
121 
RequestSuspendDelay(const std::u16string & reason,const sptr<IExpiredCallback> & callback,std::shared_ptr<DelaySuspendInfo> & delayInfo)122 ErrCode BackgroundTaskMgrService::RequestSuspendDelay(const std::u16string& reason,
123     const sptr<IExpiredCallback>& callback, std::shared_ptr<DelaySuspendInfo> &delayInfo)
124 {
125     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->RequestSuspendDelay(reason, callback, delayInfo);
126 }
127 
CancelSuspendDelay(int32_t requestId)128 ErrCode BackgroundTaskMgrService::CancelSuspendDelay(int32_t requestId)
129 {
130     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->CancelSuspendDelay(requestId);
131 }
132 
GetRemainingDelayTime(int32_t requestId,int32_t & delayTime)133 ErrCode BackgroundTaskMgrService::GetRemainingDelayTime(int32_t requestId, int32_t &delayTime)
134 {
135     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->GetRemainingDelayTime(requestId, delayTime);
136 }
137 
ForceCancelSuspendDelay(int32_t requestId)138 void BackgroundTaskMgrService::ForceCancelSuspendDelay(int32_t requestId)
139 {
140     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->ForceCancelSuspendDelay(requestId);
141 }
142 
StartBackgroundRunning(const sptr<ContinuousTaskParam> & taskParam)143 ErrCode BackgroundTaskMgrService::StartBackgroundRunning(const sptr<ContinuousTaskParam> &taskParam)
144 {
145     return BgContinuousTaskMgr::GetInstance()->StartBackgroundRunning(taskParam);
146 }
147 
UpdateBackgroundRunning(const sptr<ContinuousTaskParam> & taskParam)148 ErrCode BackgroundTaskMgrService::UpdateBackgroundRunning(const sptr<ContinuousTaskParam> &taskParam)
149 {
150     return BgContinuousTaskMgr::GetInstance()->UpdateBackgroundRunning(taskParam);
151 }
152 
RequestBackgroundRunningForInner(const sptr<ContinuousTaskParamForInner> & taskParam)153 ErrCode BackgroundTaskMgrService::RequestBackgroundRunningForInner(const sptr<ContinuousTaskParamForInner> &taskParam)
154 {
155     return BgContinuousTaskMgr::GetInstance()->RequestBackgroundRunningForInner(taskParam);
156 }
157 
StopBackgroundRunning(const std::string & abilityName,const sptr<IRemoteObject> & abilityToken,int32_t abilityId)158 ErrCode BackgroundTaskMgrService::StopBackgroundRunning(const std::string &abilityName,
159     const sptr<IRemoteObject> &abilityToken, int32_t abilityId)
160 {
161     return BgContinuousTaskMgr::GetInstance()->StopBackgroundRunning(abilityName, abilityId);
162 }
163 
GetTransientTaskApps(std::vector<std::shared_ptr<TransientTaskAppInfo>> & list)164 ErrCode BackgroundTaskMgrService::GetTransientTaskApps(std::vector<std::shared_ptr<TransientTaskAppInfo>> &list)
165 {
166     if (!CheckCallingToken()) {
167         BGTASK_LOGW("GetTransientTaskApps not allowed");
168         return ERR_BGTASK_PERMISSION_DENIED;
169     }
170     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->GetTransientTaskApps(list);
171 }
172 
PauseTransientTaskTimeForInner(int32_t uid)173 ErrCode BackgroundTaskMgrService::PauseTransientTaskTimeForInner(int32_t uid)
174 {
175     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->PauseTransientTaskTimeForInner(uid);
176 }
177 
StartTransientTaskTimeForInner(int32_t uid)178 ErrCode BackgroundTaskMgrService::StartTransientTaskTimeForInner(int32_t uid)
179 {
180     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->StartTransientTaskTimeForInner(uid);
181 }
182 
GetContinuousTaskApps(std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> & list)183 ErrCode BackgroundTaskMgrService::GetContinuousTaskApps(std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> &list)
184 {
185     if (!CheckCallingToken() && !BundleManagerHelper::GetInstance()->CheckPermission(BGMODE_PERMISSION)) {
186         BGTASK_LOGW("GetContinuousTaskApps not allowed");
187         return ERR_BGTASK_PERMISSION_DENIED;
188     }
189     return BgContinuousTaskMgr::GetInstance()->GetContinuousTaskApps(list);
190 }
191 
SubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber> & subscriber)192 ErrCode BackgroundTaskMgrService::SubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber>& subscriber)
193 {
194     if (!CheckCallingToken()) {
195         BGTASK_LOGW("SubscribeBackgroundTask not allowed");
196         return ERR_BGTASK_PERMISSION_DENIED;
197     }
198     if (DelayedSingleton<BgTransientTaskMgr>::GetInstance()->SubscribeBackgroundTask(subscriber) == ERR_OK
199         && DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->AddSubscriber(subscriber) == ERR_OK
200         && BgContinuousTaskMgr::GetInstance()->AddSubscriber(subscriber) == ERR_OK) {
201         BGTASK_LOGD("all bgtask subscribe success");
202         return ERR_OK;
203     } else {
204         BGTASK_LOGW("subscribe background task failed");
205     }
206     return ERR_BGTASK_SYS_NOT_READY;
207 }
208 
UnsubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber> & subscriber)209 ErrCode BackgroundTaskMgrService::UnsubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber>& subscriber)
210 {
211     if (!CheckCallingToken()) {
212         BGTASK_LOGW("UnsubscribeBackgroundTask not allowed");
213         return ERR_BGTASK_PERMISSION_DENIED;
214     }
215     if (DelayedSingleton<BgTransientTaskMgr>::GetInstance()->UnsubscribeBackgroundTask(subscriber) == ERR_OK
216         && DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->RemoveSubscriber(subscriber) == ERR_OK
217         && BgContinuousTaskMgr::GetInstance()->RemoveSubscriber(subscriber) == ERR_OK) {
218         return ERR_OK;
219     }
220     return ERR_BGTASK_SYS_NOT_READY;
221 }
222 
HandleRequestExpired(const int32_t requestId)223 void BackgroundTaskMgrService::HandleRequestExpired(const int32_t requestId)
224 {
225     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleRequestExpired(requestId);
226 }
227 
HandleExpiredCallbackDeath(const wptr<IRemoteObject> & remote)228 void BackgroundTaskMgrService::HandleExpiredCallbackDeath(const wptr<IRemoteObject>& remote)
229 {
230     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleExpiredCallbackDeath(remote);
231 }
232 
HandleSubscriberDeath(const wptr<IRemoteObject> & remote)233 void BackgroundTaskMgrService::HandleSubscriberDeath(const wptr<IRemoteObject>& remote)
234 {
235     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleSubscriberDeath(remote);
236 }
237 
ApplyEfficiencyResources(const sptr<EfficiencyResourceInfo> & resourceInfo)238 ErrCode BackgroundTaskMgrService::ApplyEfficiencyResources(const sptr<EfficiencyResourceInfo> &resourceInfo)
239 {
240     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ApplyEfficiencyResources(resourceInfo);
241 }
242 
ResetAllEfficiencyResources()243 ErrCode BackgroundTaskMgrService::ResetAllEfficiencyResources()
244 {
245     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ResetAllEfficiencyResources();
246 }
247 
GetEfficiencyResourcesInfos(std::vector<std::shared_ptr<ResourceCallbackInfo>> & appList,std::vector<std::shared_ptr<ResourceCallbackInfo>> & procList)248 ErrCode BackgroundTaskMgrService::GetEfficiencyResourcesInfos(
249     std::vector<std::shared_ptr<ResourceCallbackInfo>> &appList,
250     std::vector<std::shared_ptr<ResourceCallbackInfo>> &procList)
251 {
252     if (!CheckCallingToken()) {
253         BGTASK_LOGW("GetEfficiencyResourcesInfos not allowed");
254         return ERR_BGTASK_PERMISSION_DENIED;
255     }
256     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->GetEfficiencyResourcesInfos(appList, procList);
257 }
258 
StopContinuousTask(int32_t uid,int32_t pid,uint32_t taskType,const std::string & key)259 ErrCode BackgroundTaskMgrService::StopContinuousTask(int32_t uid, int32_t pid, uint32_t taskType,
260     const std::string &key)
261 {
262     if (!CheckCallingToken()) {
263         BGTASK_LOGW("StopContinuousTask not allowed");
264         return ERR_BGTASK_PERMISSION_DENIED;
265     }
266     BgContinuousTaskMgr::GetInstance()->StopContinuousTask(uid, pid, taskType, key);
267     return ERR_OK;
268 }
269 
SetBgTaskConfig(const std::string & configData,int32_t sourceType)270 ErrCode BackgroundTaskMgrService::SetBgTaskConfig(const std::string &configData, int32_t sourceType)
271 {
272     if (!CheckCallingToken()) {
273         BGTASK_LOGW("SetBgTaskConfig not allowed");
274         return ERR_BGTASK_PERMISSION_DENIED;
275     }
276     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->SetBgTaskConfig(configData, sourceType);
277 }
278 
AllowDump()279 bool BackgroundTaskMgrService::AllowDump()
280 {
281     if (ENG_MODE == 0) {
282         BGTASK_LOGE("Not eng mode");
283         return false;
284     }
285     Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetFirstTokenID();
286     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, "ohos.permission.DUMP");
287     if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
288         BGTASK_LOGE("CheckPermission failed");
289         return false;
290     }
291     return true;
292 }
293 
Dump(int32_t fd,const std::vector<std::u16string> & args)294 int32_t BackgroundTaskMgrService::Dump(int32_t fd, const std::vector<std::u16string> &args)
295 {
296     if (!AllowDump()) {
297         return ERR_BGTASK_PERMISSION_DENIED;
298     }
299     std::vector<std::string> argsInStr;
300     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
301         [](const std::u16string &arg) {
302         return Str16ToStr8(arg);
303     });
304     std::string result;
305 
306     int32_t ret = ERR_OK;
307 
308     if (argsInStr.size() == NO_DUMP_PARAM_NUMS) {
309         DumpUsage(result);
310     } else {
311         std::vector<std::string> infos;
312         if (argsInStr[0] == "-h") {
313             DumpUsage(result);
314         } else if (argsInStr[0] == "-T") {
315             ret = DelayedSingleton<BgTransientTaskMgr>::GetInstance()->ShellDump(argsInStr, infos);
316         } else if (argsInStr[0] == "-C") {
317             ret = BgContinuousTaskMgr::GetInstance()->ShellDump(argsInStr, infos);
318         } else if (argsInStr[0] == "-E") {
319             ret = DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ShellDump(argsInStr, infos);
320         } else {
321             infos.emplace_back("Error params.\n");
322             ret = ERR_BGTASK_INVALID_PARAM;
323         }
324         for (auto info : infos) {
325             result.append(info);
326         }
327     }
328 
329     if (!SaveStringToFd(fd, result)) {
330         BGTASK_LOGE("BackgroundTaskMgrService dump save string to fd failed!");
331         ret = ERR_BGTASK_METHOD_CALLED_FAILED;
332     }
333     return ret;
334 }
335 
DumpUsage(std::string & result)336 void BackgroundTaskMgrService::DumpUsage(std::string &result)
337 {
338     std::string dumpHelpMsg =
339     "usage: bgtask dump [<options>]\n"
340     "options list:\n"
341     "    -h                                   help menu\n"
342     "    -T                                   transient task commands:\n"
343     "        BATTARY_LOW                          battary low mode\n"
344     "        BATTARY_OKAY                         battary okay mode\n"
345     "        DUMP_CANCEL                          cancel dump mode\n"
346     "        All                                  list all request\n"
347     "    -C                                   continuous task commands:\n"
348     "        --all                                list all running continuous task infos\n"
349     "        --cancel_all                         cancel all running continuous task\n"
350     "        --cancel {continuous task key}       cancel one task by specifying task key\n"
351     "    -E                                   efficiency resources commands;\n"
352     "        --all                                list all efficiency resource aplications\n"
353     "        --reset_all                          reset all efficiency resource aplications\n"
354     "        --resetapp {uid} {resources}          reset one application of uid by specifying \n"
355     "        --resetproc {pid} {resources}         reset one application of pid by specifying \n";
356 
357     result.append(dumpHelpMsg);
358 }  // namespace
359 }  // namespace BackgroundTaskMgr
360 }  // namespace OHOS
361