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