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