• 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 "time_service_client.h"
17 #include "power_mgr_client.h"
18 #include "shutdown/shutdown_client.h"
19 #include "unistd.h"
20 #include "accesstoken_kit.h"
21 
22 #include "bundle_state_inner_errors.h"
23 #include "bundle_active_event.h"
24 #include "bundle_active_package_stats.h"
25 #include "bundle_active_account_helper.h"
26 #include "bundle_active_bundle_mgr_helper.h"
27 #include "bundle_active_shutdown_callback_service.h"
28 #include "tokenid_kit.h"
29 
30 #include "bundle_active_service.h"
31 
32 namespace OHOS {
33 namespace DeviceUsageStats {
34 using namespace OHOS::Security;
35 static const int32_t PERIOD_BEST_JS = 0;
36 static const int32_t PERIOD_YEARLY_JS = 4;
37 static const int32_t PERIOD_BEST_SERVICE = 4;
38 static const int32_t DELAY_TIME = 2000;
39 static const std::string PERMITTED_PROCESS_NAME = "foundation";
40 static const int32_t MAXNUM_UP_LIMIT = 1000;
41 const int32_t EVENTS_PARAM = 5;
42 static constexpr int32_t NO_DUMP_PARAM_NUMS = 0;
43 const int32_t PACKAGE_USAGE_PARAM = 6;
44 const int32_t MODULE_USAGE_PARAM = 4;
45 const std::string NEEDED_PERMISSION = "ohos.permission.BUNDLE_ACTIVE_INFO";
46 const bool REGISTER_RESULT =
47     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<BundleActiveService>::GetInstance().get());
48 
BundleActiveService()49 BundleActiveService::BundleActiveService() : SystemAbility(DEVICE_USAGE_STATISTICS_SYS_ABILITY_ID, true)
50 {
51 }
52 
~BundleActiveService()53 BundleActiveService::~BundleActiveService()
54 {
55 }
56 
OnStart()57 void BundleActiveService::OnStart()
58 {
59     BUNDLE_ACTIVE_LOGI("OnStart() called");
60     if (ready_) {
61         BUNDLE_ACTIVE_LOGI("service is ready. nothing to do.");
62         return;
63     }
64     runner_ = AppExecFwk::EventRunner::Create("device_usage_stats_init_handler");
65     if (runner_ == nullptr) {
66         BUNDLE_ACTIVE_LOGI("BundleActiveService runner create failed!");
67         return;
68     }
69     handler_ = std::make_shared<OHOS::AppExecFwk::EventHandler>(runner_);
70     if (handler_ == nullptr) {
71         BUNDLE_ACTIVE_LOGI("BundleActiveService handler create failed!");
72         return;
73     }
74     auto registerTask = [this]() { this->InitNecessaryState(); };
75     handler_->PostSyncTask(registerTask);
76 }
77 
InitNecessaryState()78 void BundleActiveService::InitNecessaryState()
79 {
80     std::set<int32_t> serviceIdSets{
81         APP_MGR_SERVICE_ID, BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, POWER_MANAGER_SERVICE_ID, COMMON_EVENT_SERVICE_ID,
82         BACKGROUND_TASK_MANAGER_SERVICE_ID, TIME_SERVICE_ID,
83     };
84     sptr<ISystemAbilityManager> systemAbilityManager
85         = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
86     if (systemAbilityManager == nullptr) {
87         BUNDLE_ACTIVE_LOGI("GetSystemAbilityManager fail!");
88         auto task = [this]() { this->InitNecessaryState(); };
89         handler_->PostTask(task, DELAY_TIME);
90         return;
91     }
92     for (const auto& serviceItem : serviceIdSets) {
93         auto checkResult = systemAbilityManager->CheckSystemAbility(serviceItem);
94         if (!checkResult) {
95             BUNDLE_ACTIVE_LOGI("request system service is not ready yet!");
96             auto task = [this]() { this->InitNecessaryState(); };
97             handler_->PostTask(task, DELAY_TIME);
98             return;
99         }
100     }
101 
102     for (const auto& serviceItem : serviceIdSets) {
103         auto getAbility = systemAbilityManager->GetSystemAbility(serviceItem);
104         if (!getAbility) {
105             BUNDLE_ACTIVE_LOGI("request system service object is not ready yet!");
106             auto task = [this]() { this->InitNecessaryState(); };
107             handler_->PostTask(task, DELAY_TIME);
108             return;
109         }
110     }
111     InitService();
112     ready_ = true;
113     int32_t ret = Publish(DelayedSingleton<BundleActiveService>::GetInstance().get());
114     if (!ret) {
115         BUNDLE_ACTIVE_LOGE("[Server] OnStart, Register SystemAbility[1907] FAIL.");
116         return;
117     }
118     BUNDLE_ACTIVE_LOGI("[Server] OnStart, Register SystemAbility[1907] SUCCESS.");
119 }
120 
InitService()121 void BundleActiveService::InitService()
122 {
123     if (bundleActiveCore_ == nullptr) {
124         bundleActiveCore_ = std::make_shared<BundleActiveCore>();
125         bundleActiveCore_->Init();
126     }
127     if (reportHandler_ == nullptr) {
128         std::string threadName = "bundle_active_report_handler";
129         auto runner = AppExecFwk::EventRunner::Create(threadName);
130         if (runner == nullptr) {
131             BUNDLE_ACTIVE_LOGE("report handler is null");
132             return;
133         }
134         reportHandler_ = std::make_shared<BundleActiveReportHandler>(runner);
135         if (reportHandler_ == nullptr) {
136             return;
137         }
138         reportHandler_->Init(bundleActiveCore_);
139     }
140     if (reportHandler_ != nullptr && bundleActiveCore_ != nullptr) {
141         BUNDLE_ACTIVE_LOGI("core and handler is not null");
142         bundleActiveCore_->SetHandler(reportHandler_);
143     } else {
144         return;
145     }
146     shutdownCallback_ = new (std::nothrow) BundleActiveShutdownCallbackService(bundleActiveCore_);
147     powerStateCallback_ = new (std::nothrow) BundleActivePowerStateCallbackService(bundleActiveCore_);
148     auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
149     auto& shutdownClient = OHOS::PowerMgr::ShutdownClient::GetInstance();
150     if (shutdownCallback_) {
151         shutdownClient.RegisterShutdownCallback(shutdownCallback_);
152     }
153     if (powerStateCallback_) {
154         powerManagerClient.RegisterPowerStateCallback(powerStateCallback_);
155     }
156     InitAppStateSubscriber(reportHandler_);
157     InitContinuousSubscriber(reportHandler_);
158     bundleActiveCore_->InitBundleGroupController();
159     SubscribeAppState();
160     SubscribeContinuousTask();
161 }
162 
GetAppManagerInstance()163 OHOS::sptr<OHOS::AppExecFwk::IAppMgr> BundleActiveService::GetAppManagerInstance()
164 {
165     OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
166         OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
167     OHOS::sptr<OHOS::IRemoteObject> object = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID);
168     if (!object) {
169         return nullptr;
170     }
171     return OHOS::iface_cast<OHOS::AppExecFwk::IAppMgr>(object);
172 }
173 
InitAppStateSubscriber(const std::shared_ptr<BundleActiveReportHandler> & reportHandler)174 void BundleActiveService::InitAppStateSubscriber(const std::shared_ptr<BundleActiveReportHandler>& reportHandler)
175 {
176     if (!appStateObserver_) {
177         appStateObserver_ = new (std::nothrow)BundleActiveAppStateObserver();
178         if (!appStateObserver_) {
179             BUNDLE_ACTIVE_LOGE("malloc app state observer failed");
180             return;
181         }
182         appStateObserver_->Init(reportHandler);
183     }
184 }
185 
InitContinuousSubscriber(const std::shared_ptr<BundleActiveReportHandler> & reportHandler)186 void BundleActiveService::InitContinuousSubscriber(const std::shared_ptr<BundleActiveReportHandler>& reportHandler)
187 {
188 #ifdef BGTASKMGR_ENABLE
189     if (continuousTaskObserver_ == nullptr) {
190         continuousTaskObserver_ = std::make_shared<BundleActiveContinuousTaskObserver>();
191         continuousTaskObserver_->Init(reportHandler);
192     }
193 #endif
194 }
195 
SubscribeAppState()196 bool BundleActiveService::SubscribeAppState()
197 {
198     sptr<OHOS::AppExecFwk::IAppMgr> appManager = GetAppManagerInstance();
199     if (appStateObserver_ == nullptr || appManager == nullptr) {
200         BUNDLE_ACTIVE_LOGE("SubscribeAppState appstateobserver is null, return");
201         return false;
202     }
203     int32_t err = appManager->RegisterApplicationStateObserver(appStateObserver_);
204     if (err != 0) {
205         BUNDLE_ACTIVE_LOGE("RegisterApplicationStateObserver failed. err:%{public}d", err);
206         return false;
207     }
208     BUNDLE_ACTIVE_LOGD("RegisterApplicationStateObserver success.");
209     return true;
210 }
211 
SubscribeContinuousTask()212 bool BundleActiveService::SubscribeContinuousTask()
213 {
214 #ifdef BGTASKMGR_ENABLE
215     if (continuousTaskObserver_ == nullptr) {
216         BUNDLE_ACTIVE_LOGE("SubscribeContinuousTask continuousTaskObserver_ is null, return");
217         return false;
218     }
219     ErrCode errCode = BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*continuousTaskObserver_);
220     if (errCode != ERR_OK) {
221         BUNDLE_ACTIVE_LOGE("SubscribeBackgroundTask failed.");
222         return false;
223     }
224 #endif
225     return true;
226 }
227 
OnStop()228 void BundleActiveService::OnStop()
229 {
230     if (shutdownCallback_ != nullptr) {
231         auto& shutdownClient = OHOS::PowerMgr::ShutdownClient::GetInstance();
232         auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
233         shutdownClient.UnRegisterShutdownCallback(shutdownCallback_);
234         powerManagerClient.UnRegisterPowerStateCallback(powerStateCallback_);
235         return;
236     }
237     BUNDLE_ACTIVE_LOGI("[Server] OnStop");
238     ready_ = false;
239 }
240 
ReportEvent(BundleActiveEvent & event,const int32_t userId)241 ErrCode BundleActiveService::ReportEvent(BundleActiveEvent& event, const int32_t userId)
242 {
243     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
244     if (CheckNativePermission(tokenId) == ERR_OK) {
245         AccessToken::NativeTokenInfo callingTokenInfo;
246         AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, callingTokenInfo);
247         int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
248         BUNDLE_ACTIVE_LOGI("calling process name is %{public}s, uid is %{public}d",
249             callingTokenInfo.processName.c_str(), callingUid);
250         if (callingTokenInfo.processName == PERMITTED_PROCESS_NAME) {
251             BundleActiveReportHandlerObject tmpHandlerObject(userId, "");
252             tmpHandlerObject.event_ = event;
253             sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
254             tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
255             std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
256                 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
257             auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr);
258             reportHandler_->SendEvent(event);
259             return ERR_OK;
260         } else {
261             BUNDLE_ACTIVE_LOGE("token does not belong to fms service process, return");
262             return ERR_PERMISSION_DENIED;
263         }
264     } else {
265         BUNDLE_ACTIVE_LOGE("token does not belong to native process, return");
266         return ERR_PERMISSION_DENIED;
267     }
268 }
269 
IsBundleIdle(bool & isBundleIdle,const std::string & bundleName,int32_t userId)270 ErrCode BundleActiveService::IsBundleIdle(bool& isBundleIdle, const std::string& bundleName, int32_t userId)
271 {
272     // get uid
273     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
274     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
275     ErrCode ret = ERR_OK;
276     std::string callingBundleName = "";
277     BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, callingBundleName);
278     BUNDLE_ACTIVE_LOGI("UID is %{public}d, bundle name is %{public}s", callingUid, callingBundleName.c_str());
279     // get user id
280     int32_t result = -1;
281     if (userId == -1) {
282         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
283         if (ret != ERR_OK || userId == -1) {
284             return ret;
285         }
286     }
287 
288     if (callingBundleName == bundleName) {
289         if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
290             BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
291             return ERR_NOT_SYSTEM_APP;
292         }
293         BUNDLE_ACTIVE_LOGI("%{public}s check its own idle state", bundleName.c_str());
294         result = bundleActiveCore_->IsBundleIdle(bundleName, userId);
295     } else {
296         ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
297         if (ret == ERR_OK) {
298             result = bundleActiveCore_->IsBundleIdle(bundleName, userId);
299         } else {
300             return ret;
301         }
302     }
303     if (result == 0 || result == -1) {
304         isBundleIdle = false;
305     } else {
306         isBundleIdle = true;
307     }
308     return ERR_OK;
309 }
310 
QueryBundleStatsInfoByInterval(std::vector<BundleActivePackageStats> & PackageStats,const int32_t intervalType,const int64_t beginTime,const int64_t endTime,int32_t userId)311 ErrCode BundleActiveService::QueryBundleStatsInfoByInterval(std::vector<BundleActivePackageStats>& PackageStats,
312     const int32_t intervalType, const int64_t beginTime, const int64_t endTime, int32_t userId)
313 {
314     BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfoByInterval stats called, intervaltype is %{public}d", intervalType);
315     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
316     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
317     ErrCode ret = ERR_OK;
318     if (userId == -1) {
319         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
320         if (ret != ERR_OK || userId == -1) {
321             return ret;
322         }
323     }
324     BUNDLE_ACTIVE_LOGI("QueryBundleStatsInfos user id is %{public}d", userId);
325     ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
326     if (ret == ERR_OK) {
327         int32_t convertedIntervalType = ConvertIntervalType(intervalType);
328         ret = bundleActiveCore_->QueryBundleStatsInfos(
329             PackageStats, userId, convertedIntervalType, beginTime, endTime, "");
330     }
331     return ret;
332 }
333 
QueryBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvents,const int64_t beginTime,const int64_t endTime,int32_t userId)334 ErrCode BundleActiveService::QueryBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvents,
335     const int64_t beginTime, const int64_t endTime, int32_t userId)
336 {
337     ErrCode ret = ERR_OK;
338     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
339     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
340     if (userId == -1) {
341         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
342         if (ret != ERR_OK || userId == -1) {
343             return ret;
344         }
345     }
346     BUNDLE_ACTIVE_LOGI("QueryBundleEvents userid is %{public}d", userId);
347     ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
348     if (ret == ERR_OK) {
349         ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, "");
350         BUNDLE_ACTIVE_LOGI("QueryBundleEvents result is %{public}zu", bundleActiveEvents.size());
351     }
352     return ret;
353 }
354 
SetAppGroup(const std::string & bundleName,int32_t newGroup,int32_t userId)355 ErrCode BundleActiveService::SetAppGroup(const std::string& bundleName, int32_t newGroup, int32_t userId)
356 {
357     ErrCode ret = ERR_OK;
358     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
359     bool isFlush = false;
360     if (userId == -1) {
361         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
362         if (ret != ERR_OK || userId == -1) {
363             return ERR_SYSTEM_ABILITY_SUPPORT_FAILED;
364         }
365         isFlush = true;
366     }
367     BUNDLE_ACTIVE_LOGI("SetAppGroup userId is %{public}d", userId);
368 
369     std::string localBundleName = "";
370     BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, localBundleName);
371     if (localBundleName == bundleName) {
372         BUNDLE_ACTIVE_LOGI("SetAppGroup can not set its bundleName");
373         return ERR_PERMISSION_DENIED;
374     }
375     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
376     ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
377     if (ret == ERR_OK) {
378         ret = bundleActiveCore_->SetAppGroup(bundleName, newGroup, userId, isFlush);
379     }
380     return ret;
381 }
382 
QueryBundleStatsInfos(std::vector<BundleActivePackageStats> & bundleActivePackageStats,const int32_t intervalType,const int64_t beginTime,const int64_t endTime)383 ErrCode BundleActiveService::QueryBundleStatsInfos(std::vector<BundleActivePackageStats>& bundleActivePackageStats,
384     const int32_t intervalType, const int64_t beginTime, const int64_t endTime)
385 {
386     // get uid
387     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
388     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
389     BUNDLE_ACTIVE_LOGD("UID is %{public}d", callingUid);
390     // get userid
391     int32_t userId = -1;
392     ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
393     if (ret == ERR_OK && userId != -1) {
394         BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfos userid is %{public}d", userId);
395         std::string bundleName = "";
396         BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, bundleName);
397         ErrCode isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId);
398         if (!bundleName.empty() && isSystemAppAndHasPermission == ERR_OK) {
399             int32_t convertedIntervalType = ConvertIntervalType(intervalType);
400             ret = bundleActiveCore_->QueryBundleStatsInfos(bundleActivePackageStats, userId, convertedIntervalType,
401                 beginTime, endTime, bundleName);
402         }
403     }
404     return ret;
405 }
406 
QueryCurrentBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvents,const int64_t beginTime,const int64_t endTime)407 ErrCode BundleActiveService::QueryCurrentBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvents,
408     const int64_t beginTime, const int64_t endTime)
409 {
410     // get uid
411     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
412     BUNDLE_ACTIVE_LOGD("QueryCurrentBundleEvents UID is %{public}d", callingUid);
413     // get userid
414     int32_t userId = -1;
415     ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
416     if (ret == ERR_OK && userId != -1) {
417         std::string bundleName = "";
418         BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, bundleName);
419         if (!bundleName.empty()) {
420             if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
421                 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
422                 return ERR_NOT_SYSTEM_APP;
423             }
424             BUNDLE_ACTIVE_LOGI("QueryCurrentBundleEvents buindle name is %{public}s",
425                 bundleName.c_str());
426             ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, bundleName);
427         }
428     }
429     BUNDLE_ACTIVE_LOGD("QueryCurrentBundleEvents bundleActiveEvents size is %{public}zu", bundleActiveEvents.size());
430     return ret;
431 }
432 
QueryAppGroup(int32_t & appGroup,std::string & bundleName,int32_t userId)433 ErrCode BundleActiveService::QueryAppGroup(int32_t& appGroup, std::string& bundleName, int32_t userId)
434 {
435     // get uid
436     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
437     BUNDLE_ACTIVE_LOGD("QueryAppGroup UID is %{public}d", callingUid);
438     ErrCode ret = ERR_OK;
439     if (userId == -1) {
440         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
441         if (ret != ERR_OK || userId == -1) {
442             return ERR_SYSTEM_ABILITY_SUPPORT_FAILED;
443         }
444     }
445     if (bundleName.empty()) {
446         std::string localBundleName = "";
447         BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, localBundleName);
448         if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
449             BUNDLE_ACTIVE_LOGE("%{public}s is not system app", localBundleName.c_str());
450             return ERR_NOT_SYSTEM_APP;
451         }
452         bundleName = localBundleName;
453         ret = bundleActiveCore_->QueryAppGroup(appGroup, bundleName, userId);
454     } else {
455         AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
456         ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
457         if (ret == ERR_OK) {
458             ret = bundleActiveCore_->QueryAppGroup(appGroup, bundleName, userId);
459         }
460     }
461     return ret;
462 }
463 
RegisterAppGroupCallBack(const sptr<IAppGroupCallback> & observer)464 ErrCode BundleActiveService::RegisterAppGroupCallBack(const sptr<IAppGroupCallback> &observer)
465 {
466     if (!bundleActiveCore_) {
467         return ERR_MEMORY_OPERATION_FAILED;
468     }
469     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
470     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
471     ErrCode ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
472     if (ret == ERR_OK) {
473         ret = bundleActiveCore_->RegisterAppGroupCallBack(tokenId, observer);
474     }
475     return ret;
476 }
477 
UnRegisterAppGroupCallBack(const sptr<IAppGroupCallback> & observer)478 ErrCode BundleActiveService::UnRegisterAppGroupCallBack(const sptr<IAppGroupCallback> &observer)
479 {
480     if (!bundleActiveCore_) {
481         return ERR_MEMORY_OPERATION_FAILED;
482     }
483     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
484     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
485     ErrCode ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
486     if (ret == ERR_OK) {
487         ret = bundleActiveCore_->UnRegisterAppGroupCallBack(tokenId, observer);
488     }
489     return ret;
490 }
491 
ConvertIntervalType(const int32_t intervalType)492 int32_t BundleActiveService::ConvertIntervalType(const int32_t intervalType)
493 {
494     if (intervalType == PERIOD_BEST_JS) {
495         return PERIOD_BEST_SERVICE;
496     } else if (intervalType > PERIOD_BEST_JS && intervalType <= PERIOD_YEARLY_JS) {
497         return intervalType - 1;
498     }
499     return -1;
500 }
501 
CheckBundleIsSystemAppAndHasPermission(const int32_t uid,OHOS::Security::AccessToken::AccessTokenID tokenId)502 ErrCode BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_t uid,
503     OHOS::Security::AccessToken::AccessTokenID tokenId)
504 {
505     std::string bundleName = "";
506     BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(uid, bundleName);
507 
508     if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
509         BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
510         return ERR_NOT_SYSTEM_APP;
511     }
512 
513     int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION);
514     if (bundleHasPermission != 0) {
515         BUNDLE_ACTIVE_LOGE("%{public}s hasn't permission", bundleName.c_str());
516         return ERR_PERMISSION_DENIED;
517     }
518     BUNDLE_ACTIVE_LOGI("%{public}s has permission", bundleName.c_str());
519     return ERR_OK;
520 }
521 
CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId)522 ErrCode BundleActiveService::CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId)
523 {
524     auto tokenFlag = AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
525     if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) {
526         return ERR_OK;
527     }
528     if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_SHELL) {
529         return ERR_OK;
530     }
531     return ERR_PERMISSION_DENIED;
532 }
533 
CheckSystemAppOrNativePermission(const int32_t uid,OHOS::Security::AccessToken::AccessTokenID tokenId)534 ErrCode BundleActiveService::CheckSystemAppOrNativePermission(const int32_t uid,
535     OHOS::Security::AccessToken::AccessTokenID tokenId)
536 {
537     if (AccessToken::AccessTokenKit::GetTokenType(tokenId) == AccessToken::ATokenTypeEnum::TOKEN_HAP) {
538         return CheckBundleIsSystemAppAndHasPermission(uid, tokenId);
539     }
540     return CheckNativePermission(tokenId);
541 }
542 
QueryModuleUsageRecords(int32_t maxNum,std::vector<BundleActiveModuleRecord> & results,int32_t userId)543 ErrCode BundleActiveService::QueryModuleUsageRecords(int32_t maxNum, std::vector<BundleActiveModuleRecord>& results,
544     int32_t userId)
545 {
546     ErrCode errCode = ERR_OK;
547     if (maxNum > MAXNUM_UP_LIMIT || maxNum <= 0) {
548         BUNDLE_ACTIVE_LOGE("MaxNum is Invalid!");
549         return ERR_FIND_APP_USAGE_RECORDS_FAILED;
550     }
551     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
552     if (userId == -1) {
553         errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
554         if (errCode != ERR_OK || userId == -1) {
555             return errCode;
556         }
557     }
558     BUNDLE_ACTIVE_LOGI("QueryModuleUsageRecords userid is %{public}d", userId);
559     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
560     errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
561     if (errCode == ERR_OK) {
562         errCode = bundleActiveCore_->QueryModuleUsageRecords(maxNum, results, userId);
563         for (auto& oneResult : results) {
564             QueryModuleRecordInfos(oneResult);
565         }
566     }
567     return errCode;
568 }
569 
QueryDeviceEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)570 ErrCode BundleActiveService::QueryDeviceEventStats(int64_t beginTime, int64_t endTime,
571     std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
572 {
573     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
574     ErrCode errCode = ERR_OK;
575     if (userId == -1) {
576         errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
577         if (errCode != ERR_OK || userId == -1) {
578             return errCode;
579         }
580     }
581     BUNDLE_ACTIVE_LOGI("QueryDeviceEventStats userid is %{public}d", userId);
582     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
583     errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
584     if (errCode == ERR_OK) {
585         errCode = bundleActiveCore_->QueryDeviceEventStats(beginTime, endTime, eventStats, userId);
586     }
587     BUNDLE_ACTIVE_LOGD("QueryDeviceEventStats result size is %{public}zu", eventStats.size());
588     return errCode;
589 }
590 
QueryNotificationEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)591 ErrCode BundleActiveService::QueryNotificationEventStats(int64_t beginTime, int64_t endTime,
592     std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
593 {
594     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
595     BUNDLE_ACTIVE_LOGD("QueryNotificationEventStats UID is %{public}d", callingUid);
596     // get userid when userId is -1
597     ErrCode errCode = ERR_OK;
598     if (userId == -1) {
599         errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
600         if (errCode != ERR_OK || userId == -1) {
601             return errCode;
602         }
603     }
604     BUNDLE_ACTIVE_LOGI("QueryNotificationEventStats userid is %{public}d", userId);
605     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
606     errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
607     if (errCode == ERR_OK) {
608         errCode = bundleActiveCore_->QueryNotificationEventStats(beginTime, endTime, eventStats, userId);
609     }
610     return errCode;
611 }
612 
QueryModuleRecordInfos(BundleActiveModuleRecord & moduleRecord)613 void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord)
614 {
615     ApplicationInfo appInfo;
616     bool getInfoIsSuccess = BundleActiveBundleMgrHelper::GetInstance()->GetApplicationInfo(moduleRecord.bundleName_,
617         ApplicationFlag::GET_BASIC_APPLICATION_INFO, moduleRecord.userId_, appInfo);
618     if (!getInfoIsSuccess) {
619         BUNDLE_ACTIVE_LOGE("GetApplicationInfo failed!");
620         return;
621     }
622     BundleInfo bundleInfo;
623     getInfoIsSuccess = BundleActiveBundleMgrHelper::GetInstance()->GetBundleInfo(moduleRecord.bundleName_,
624         BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, moduleRecord.userId_);
625     if (!getInfoIsSuccess) {
626         BUNDLE_ACTIVE_LOGE("GetBundleInfo failed!");
627         return;
628     }
629     for (const auto & oneModuleInfo : bundleInfo.hapModuleInfos) {
630         if (oneModuleInfo.moduleName == moduleRecord.moduleName_) {
631             std::string mainAbility = oneModuleInfo.mainAbility;
632             for (auto oneAbilityInfo : oneModuleInfo.abilityInfos) {
633                 if (oneAbilityInfo.type != AbilityType::PAGE) {
634                     continue;
635                 }
636                 if (mainAbility.empty() || mainAbility.compare(oneAbilityInfo.name) == 0) {
637                     SerModuleProperties(oneModuleInfo, appInfo, oneAbilityInfo, moduleRecord);
638                     break;
639                 }
640             }
641         }
642     }
643 }
644 
SerModuleProperties(const HapModuleInfo & hapModuleInfo,const ApplicationInfo & appInfo,const AbilityInfo & abilityInfo,BundleActiveModuleRecord & moduleRecord)645 void BundleActiveService::SerModuleProperties(const HapModuleInfo& hapModuleInfo,
646     const ApplicationInfo& appInfo, const AbilityInfo& abilityInfo, BundleActiveModuleRecord& moduleRecord)
647 {
648     moduleRecord.deviceId_ = appInfo.deviceId;
649     moduleRecord.abilityName_ = abilityInfo.name;
650     moduleRecord.appLabelId_ = appInfo.labelId;
651     moduleRecord.labelId_ = static_cast<uint32_t>(hapModuleInfo.labelId);
652     moduleRecord.abilityLableId_ = abilityInfo.labelId;
653     moduleRecord.descriptionId_ = abilityInfo.descriptionId;
654     moduleRecord.abilityIconId_ = abilityInfo.iconId;
655     moduleRecord.installFreeSupported_ = hapModuleInfo.installationFree;
656 }
657 
Dump(int32_t fd,const std::vector<std::u16string> & args)658 int32_t BundleActiveService::Dump(int32_t fd, const std::vector<std::u16string> &args)
659 {
660     std::vector<std::string> argsInStr;
661     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
662         [](const std::u16string &arg) {
663         return Str16ToStr8(arg);
664     });
665     std::string result;
666     int32_t ret = ERR_OK;
667     if (argsInStr.size() == NO_DUMP_PARAM_NUMS) {
668         DumpUsage(result);
669     } else {
670         std::vector<std::string> infos;
671         if (argsInStr[0] == "-h") {
672             DumpUsage(result);
673         } else if (argsInStr[0] == "-A") {
674             ret = ShellDump(argsInStr, infos);
675         } else {
676             infos.emplace_back("BundleActiveService Error params.\n");
677             ret = ERR_USAGE_STATS_INVALID_PARAM;
678         }
679         for (auto info : infos) {
680             result.append(info);
681         }
682     }
683     if (!SaveStringToFd(fd, result)) {
684         BUNDLE_ACTIVE_LOGE("BundleActiveService dump save string to fd failed!");
685         ret = ERR_USAGE_STATS_METHOD_CALLED_FAILED;
686     }
687     return ret;
688 }
689 
ShellDump(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)690 int32_t BundleActiveService::ShellDump(const std::vector<std::string> &dumpOption, std::vector<std::string> &dumpInfo)
691 {
692     int32_t ret = -1;
693     if (dumpOption[1] == "Events") {
694         std::vector<BundleActiveEvent> eventResult;
695         if (static_cast<int32_t>(dumpOption.size()) != EVENTS_PARAM) {
696             return ret;
697         }
698         int64_t beginTime = std::stoll(dumpOption[2]);
699         int64_t endTime = std::stoll(dumpOption[3]);
700         int32_t userId = std::stoi(dumpOption[4]);
701         this->QueryBundleEvents(eventResult, beginTime, endTime, userId);
702         for (auto& oneEvent : eventResult) {
703             dumpInfo.emplace_back(oneEvent.ToString());
704         }
705     } else if (dumpOption[1] == "PackageUsage") {
706         std::vector<BundleActivePackageStats> packageUsageResult;
707         if (static_cast<int32_t>(dumpOption.size()) != PACKAGE_USAGE_PARAM) {
708             return ret;
709         }
710         int32_t intervalType = std::stoi(dumpOption[2]);
711         int64_t beginTime = std::stoll(dumpOption[3]);
712         int64_t endTime = std::stoll(dumpOption[4]);
713         int32_t userId = std::stoi(dumpOption[5]);
714         this->QueryBundleStatsInfoByInterval(packageUsageResult, intervalType, beginTime, endTime, userId);
715         for (auto& onePackageRecord : packageUsageResult) {
716             dumpInfo.emplace_back(onePackageRecord.ToString());
717         }
718     } else if (dumpOption[1] == "ModuleUsage") {
719         std::vector<BundleActiveModuleRecord> moduleResult;
720         if (static_cast<int32_t>(dumpOption.size()) != MODULE_USAGE_PARAM) {
721             return ret;
722         }
723         int32_t maxNum = std::stoi(dumpOption[2]);
724         int32_t userId = std::stoi(dumpOption[3]);
725         BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId);
726         ret = this->QueryModuleUsageRecords(maxNum, moduleResult, userId);
727         for (auto& oneModuleRecord : moduleResult) {
728             dumpInfo.emplace_back(oneModuleRecord.ToString());
729             for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) {
730                 std::string oneFormInfo = "form " + std::to_string(static_cast<int32_t>(i) + 1) + ", ";
731                 dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString());
732             }
733         }
734     }
735     return ret;
736 }
737 
DumpUsage(std::string & result)738 void BundleActiveService::DumpUsage(std::string &result)
739 {
740     std::string dumpHelpMsg =
741         "usage: bundleactive dump [<options>]\n"
742         "options list:\n"
743         "  -h                                                             help menu\n"
744         "  -A                                                                                    \n"
745         "      Events [beginTime] [endTime] [userId]                      get events for one user\n"
746         "      PackageUsage [intervalType] [beginTime] [endTime] [userId] get package usage for one user\n"
747         "      ModuleUsage [maxNum] [userId]                              get module usage for one user\n";
748     result.append(dumpHelpMsg);
749 }
750 }  // namespace DeviceUsageStats
751 }  // namespace OHOS
752 
753