• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
CheckHapCalling(bool & isHap)122 bool BackgroundTaskMgrService::CheckHapCalling(bool &isHap)
123 {
124     Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
125     auto tokenFlag = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
126     if (tokenFlag == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
127         isHap = true;
128         return BundleManagerHelper::GetInstance()->CheckPermission(BGMODE_PERMISSION);
129     }
130     return false;
131 }
132 
RequestSuspendDelay(const std::u16string & reason,const sptr<IExpiredCallback> & callback,std::shared_ptr<DelaySuspendInfo> & delayInfo)133 ErrCode BackgroundTaskMgrService::RequestSuspendDelay(const std::u16string& reason,
134     const sptr<IExpiredCallback>& callback, std::shared_ptr<DelaySuspendInfo> &delayInfo)
135 {
136     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->RequestSuspendDelay(reason, callback, delayInfo);
137 }
138 
CancelSuspendDelay(int32_t requestId)139 ErrCode BackgroundTaskMgrService::CancelSuspendDelay(int32_t requestId)
140 {
141     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->CancelSuspendDelay(requestId);
142 }
143 
GetRemainingDelayTime(int32_t requestId,int32_t & delayTime)144 ErrCode BackgroundTaskMgrService::GetRemainingDelayTime(int32_t requestId, int32_t &delayTime)
145 {
146     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->GetRemainingDelayTime(requestId, delayTime);
147 }
148 
ForceCancelSuspendDelay(int32_t requestId)149 void BackgroundTaskMgrService::ForceCancelSuspendDelay(int32_t requestId)
150 {
151     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->ForceCancelSuspendDelay(requestId);
152 }
153 
StartBackgroundRunning(const sptr<ContinuousTaskParam> & taskParam)154 ErrCode BackgroundTaskMgrService::StartBackgroundRunning(const sptr<ContinuousTaskParam> &taskParam)
155 {
156     return BgContinuousTaskMgr::GetInstance()->StartBackgroundRunning(taskParam);
157 }
158 
UpdateBackgroundRunning(const sptr<ContinuousTaskParam> & taskParam)159 ErrCode BackgroundTaskMgrService::UpdateBackgroundRunning(const sptr<ContinuousTaskParam> &taskParam)
160 {
161     return BgContinuousTaskMgr::GetInstance()->UpdateBackgroundRunning(taskParam);
162 }
163 
RequestBackgroundRunningForInner(const sptr<ContinuousTaskParamForInner> & taskParam)164 ErrCode BackgroundTaskMgrService::RequestBackgroundRunningForInner(const sptr<ContinuousTaskParamForInner> &taskParam)
165 {
166     return BgContinuousTaskMgr::GetInstance()->RequestBackgroundRunningForInner(taskParam);
167 }
168 
StopBackgroundRunning(const std::string & abilityName,const sptr<IRemoteObject> & abilityToken,int32_t abilityId)169 ErrCode BackgroundTaskMgrService::StopBackgroundRunning(const std::string &abilityName,
170     const sptr<IRemoteObject> &abilityToken, int32_t abilityId)
171 {
172     return BgContinuousTaskMgr::GetInstance()->StopBackgroundRunning(abilityName, abilityId);
173 }
174 
GetTransientTaskApps(std::vector<std::shared_ptr<TransientTaskAppInfo>> & list)175 ErrCode BackgroundTaskMgrService::GetTransientTaskApps(std::vector<std::shared_ptr<TransientTaskAppInfo>> &list)
176 {
177     if (!CheckCallingToken()) {
178         BGTASK_LOGW("GetTransientTaskApps not allowed");
179         return ERR_BGTASK_PERMISSION_DENIED;
180     }
181     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->GetTransientTaskApps(list);
182 }
183 
PauseTransientTaskTimeForInner(int32_t uid)184 ErrCode BackgroundTaskMgrService::PauseTransientTaskTimeForInner(int32_t uid)
185 {
186     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->PauseTransientTaskTimeForInner(uid);
187 }
188 
StartTransientTaskTimeForInner(int32_t uid)189 ErrCode BackgroundTaskMgrService::StartTransientTaskTimeForInner(int32_t uid)
190 {
191     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->StartTransientTaskTimeForInner(uid);
192 }
193 
GetContinuousTaskApps(std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> & list)194 ErrCode BackgroundTaskMgrService::GetContinuousTaskApps(std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> &list)
195 {
196     bool isHap = false;
197     pid_t callingPid = IPCSkeleton::GetCallingPid();
198     pid_t callingUid = IPCSkeleton::GetCallingUid();
199     if (!CheckCallingToken() && !CheckHapCalling(isHap)) {
200         BGTASK_LOGW("uid %{public}d pid %{public}d GetContinuousTaskApps not allowed", callingUid, callingPid);
201         return ERR_BGTASK_PERMISSION_DENIED;
202     }
203     return BgContinuousTaskMgr::GetInstance()->GetContinuousTaskApps(list);
204 }
205 
SubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber> & subscriber)206 ErrCode BackgroundTaskMgrService::SubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber>& subscriber)
207 {
208     bool isHap = false;
209     if (!CheckCallingToken() && !CheckHapCalling(isHap)) {
210         BGTASK_LOGW("SubscribeBackgroundTask not allowed");
211         return ERR_BGTASK_PERMISSION_DENIED;
212     }
213     pid_t callingPid = IPCSkeleton::GetCallingPid();
214     pid_t callingUid = IPCSkeleton::GetCallingUid();
215     BGTASK_LOGI("uid %{public}d pid %{public}d isHap %{public}d subscribe", callingUid, callingPid, isHap);
216     auto subscriberInfo = std::make_shared<SubscriberInfo>(subscriber, callingUid, callingPid, isHap);
217     if (BgContinuousTaskMgr::GetInstance()->AddSubscriber(subscriberInfo) != ERR_OK) {
218         BGTASK_LOGE("continuous task subscribe background task failed");
219         return ERR_BGTASK_SYS_NOT_READY;
220     }
221     if (!isHap) {
222         if (DelayedSingleton<BgTransientTaskMgr>::GetInstance()->SubscribeBackgroundTask(subscriber) != ERR_OK
223             || DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->AddSubscriber(subscriber) != ERR_OK) {
224             BGTASK_LOGE("transient task or efficiency resource subscribe background task failed");
225             return ERR_BGTASK_SYS_NOT_READY;
226         }
227     }
228     BGTASK_LOGW("subscribe background task success");
229     return ERR_OK;
230 }
231 
UnsubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber> & subscriber)232 ErrCode BackgroundTaskMgrService::UnsubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber>& subscriber)
233 {
234     bool isHap = false;
235     if (!CheckCallingToken() && !CheckHapCalling(isHap)) {
236         BGTASK_LOGW("UnsubscribeBackgroundTask not allowed");
237         return ERR_BGTASK_PERMISSION_DENIED;
238     }
239     if (BgContinuousTaskMgr::GetInstance()->RemoveSubscriber(subscriber) != ERR_OK) {
240         BGTASK_LOGE("continuous task unsubscribe background task failed");
241         return ERR_BGTASK_SYS_NOT_READY;
242     }
243     if (!isHap) {
244         if (DelayedSingleton<BgTransientTaskMgr>::GetInstance()->UnsubscribeBackgroundTask(subscriber) != ERR_OK
245             || DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->RemoveSubscriber(subscriber) != ERR_OK) {
246             BGTASK_LOGE("transient task or efficiency resource unsubscribe background task failed");
247             return ERR_BGTASK_SYS_NOT_READY;
248         }
249     }
250     BGTASK_LOGW("unsubscribe background task success");
251     return ERR_OK;
252 }
253 
HandleRequestExpired(const int32_t requestId)254 void BackgroundTaskMgrService::HandleRequestExpired(const int32_t requestId)
255 {
256     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleRequestExpired(requestId);
257 }
258 
HandleExpiredCallbackDeath(const wptr<IRemoteObject> & remote)259 void BackgroundTaskMgrService::HandleExpiredCallbackDeath(const wptr<IRemoteObject>& remote)
260 {
261     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleExpiredCallbackDeath(remote);
262 }
263 
HandleSubscriberDeath(const wptr<IRemoteObject> & remote)264 void BackgroundTaskMgrService::HandleSubscriberDeath(const wptr<IRemoteObject>& remote)
265 {
266     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleSubscriberDeath(remote);
267 }
268 
ApplyEfficiencyResources(const sptr<EfficiencyResourceInfo> & resourceInfo)269 ErrCode BackgroundTaskMgrService::ApplyEfficiencyResources(const sptr<EfficiencyResourceInfo> &resourceInfo)
270 {
271     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ApplyEfficiencyResources(resourceInfo);
272 }
273 
ResetAllEfficiencyResources()274 ErrCode BackgroundTaskMgrService::ResetAllEfficiencyResources()
275 {
276     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ResetAllEfficiencyResources();
277 }
278 
GetEfficiencyResourcesInfos(std::vector<std::shared_ptr<ResourceCallbackInfo>> & appList,std::vector<std::shared_ptr<ResourceCallbackInfo>> & procList)279 ErrCode BackgroundTaskMgrService::GetEfficiencyResourcesInfos(
280     std::vector<std::shared_ptr<ResourceCallbackInfo>> &appList,
281     std::vector<std::shared_ptr<ResourceCallbackInfo>> &procList)
282 {
283     if (!CheckCallingToken()) {
284         BGTASK_LOGW("GetEfficiencyResourcesInfos not allowed");
285         return ERR_BGTASK_PERMISSION_DENIED;
286     }
287     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->GetEfficiencyResourcesInfos(appList, procList);
288 }
289 
StopContinuousTask(int32_t uid,int32_t pid,uint32_t taskType,const std::string & key)290 ErrCode BackgroundTaskMgrService::StopContinuousTask(int32_t uid, int32_t pid, uint32_t taskType,
291     const std::string &key)
292 {
293     if (!CheckCallingToken()) {
294         BGTASK_LOGW("StopContinuousTask not allowed");
295         return ERR_BGTASK_PERMISSION_DENIED;
296     }
297     BgContinuousTaskMgr::GetInstance()->StopContinuousTask(uid, pid, taskType, key);
298     return ERR_OK;
299 }
300 
SetBgTaskConfig(const std::string & configData,int32_t sourceType)301 ErrCode BackgroundTaskMgrService::SetBgTaskConfig(const std::string &configData, int32_t sourceType)
302 {
303     if (!CheckCallingToken()) {
304         BGTASK_LOGW("SetBgTaskConfig not allowed");
305         return ERR_BGTASK_PERMISSION_DENIED;
306     }
307     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->SetBgTaskConfig(configData, sourceType);
308 }
309 
AllowDump()310 bool BackgroundTaskMgrService::AllowDump()
311 {
312     if (ENG_MODE == 0) {
313         BGTASK_LOGE("Not eng mode");
314         return false;
315     }
316     Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetFirstTokenID();
317     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, "ohos.permission.DUMP");
318     if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
319         BGTASK_LOGE("CheckPermission failed");
320         return false;
321     }
322     return true;
323 }
324 
Dump(int32_t fd,const std::vector<std::u16string> & args)325 int32_t BackgroundTaskMgrService::Dump(int32_t fd, const std::vector<std::u16string> &args)
326 {
327     if (!AllowDump()) {
328         return ERR_BGTASK_PERMISSION_DENIED;
329     }
330     std::vector<std::string> argsInStr;
331     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
332         [](const std::u16string &arg) {
333         return Str16ToStr8(arg);
334     });
335     std::string result;
336 
337     int32_t ret = ERR_OK;
338 
339     if (argsInStr.size() == NO_DUMP_PARAM_NUMS) {
340         DumpUsage(result);
341     } else {
342         std::vector<std::string> infos;
343         if (argsInStr[0] == "-h") {
344             DumpUsage(result);
345         } else if (argsInStr[0] == "-T") {
346             ret = DelayedSingleton<BgTransientTaskMgr>::GetInstance()->ShellDump(argsInStr, infos);
347         } else if (argsInStr[0] == "-C") {
348             ret = BgContinuousTaskMgr::GetInstance()->ShellDump(argsInStr, infos);
349         } else if (argsInStr[0] == "-E") {
350             ret = DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ShellDump(argsInStr, infos);
351         } else {
352             infos.emplace_back("Error params.\n");
353             ret = ERR_BGTASK_INVALID_PARAM;
354         }
355         for (auto info : infos) {
356             result.append(info);
357         }
358     }
359 
360     if (!SaveStringToFd(fd, result)) {
361         BGTASK_LOGE("BackgroundTaskMgrService dump save string to fd failed!");
362         ret = ERR_BGTASK_METHOD_CALLED_FAILED;
363     }
364     return ret;
365 }
366 
DumpUsage(std::string & result)367 void BackgroundTaskMgrService::DumpUsage(std::string &result)
368 {
369     std::string dumpHelpMsg =
370     "usage: bgtask dump [<options>]\n"
371     "options list:\n"
372     "    -h                                   help menu\n"
373     "    -T                                   transient task commands:\n"
374     "        BATTARY_LOW                          battary low mode\n"
375     "        BATTARY_OKAY                         battary okay mode\n"
376     "        DUMP_CANCEL                          cancel dump mode\n"
377     "        All                                  list all request\n"
378     "    -C                                   continuous task commands:\n"
379     "        --all                                list all running continuous task infos\n"
380     "        --cancel_all                         cancel all running continuous task\n"
381     "        --cancel {continuous task key}       cancel one task by specifying task key\n"
382     "    -E                                   efficiency resources commands;\n"
383     "        --all                                list all efficiency resource aplications\n"
384     "        --reset_all                          reset all efficiency resource aplications\n"
385     "        --resetapp {uid} {resources}          reset one application of uid by specifying \n"
386     "        --resetproc {pid} {resources}         reset one application of pid by specifying \n";
387 
388     result.append(dumpHelpMsg);
389 }  // namespace
390 }  // namespace BackgroundTaskMgr
391 }  // namespace OHOS
392