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