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(const BundleActiveEvent & event,int32_t userId)246 ErrCode BundleActiveService::ReportEvent(const BundleActiveEvent& event, 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 BundleActiveEvent eventNew(event);
258 tmpHandlerObject.event_ = eventNew;
259 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
260 tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
261 std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
262 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
263 reportHandler_->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr);
264 return ERR_OK;
265 } else {
266 BUNDLE_ACTIVE_LOGE("token does not belong to fms service process, return");
267 return ERR_PERMISSION_DENIED;
268 }
269 } else {
270 BUNDLE_ACTIVE_LOGE("token does not belong to native process, return");
271 return ERR_PERMISSION_DENIED;
272 }
273 }
274
IsBundleIdle(bool & isBundleIdle,const std::string & bundleName,int32_t userId)275 ErrCode BundleActiveService::IsBundleIdle(bool& isBundleIdle, const std::string& bundleName, int32_t userId)
276 {
277 // get uid
278 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
279 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
280 ErrCode ret = ERR_OK;
281 std::string callingBundleName = "";
282 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, callingBundleName);
283 BUNDLE_ACTIVE_LOGI("UID is %{public}d, bundle name is %{public}s", callingUid, callingBundleName.c_str());
284 // get user id
285 int32_t result = -1;
286 if (userId == -1) {
287 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
288 if (ret != ERR_OK || userId == -1) {
289 return ret;
290 }
291 }
292
293 if (callingBundleName == bundleName) {
294 if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
295 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
296 return ERR_NOT_SYSTEM_APP;
297 }
298 BUNDLE_ACTIVE_LOGI("%{public}s check its own idle state", bundleName.c_str());
299 result = bundleActiveCore_->IsBundleIdle(bundleName, userId);
300 } else {
301 ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
302 if (ret == ERR_OK) {
303 result = bundleActiveCore_->IsBundleIdle(bundleName, userId);
304 } else {
305 return ret;
306 }
307 }
308 if (result == 0 || result == -1) {
309 isBundleIdle = false;
310 } else {
311 isBundleIdle = true;
312 }
313 return ERR_OK;
314 }
315
IsBundleUsePeriod(bool & IsUsePeriod,const std::string & bundleName,int32_t userId)316 ErrCode BundleActiveService::IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId)
317 {
318 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
319 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
320 if (AccessToken::AccessTokenKit::GetTokenType(tokenId) != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
321 return ERR_PERMISSION_DENIED;
322 }
323 auto ret = CheckNativePermission(tokenId);
324 if (ret != ERR_OK) {
325 return ret;
326 }
327 if (userId == -1) {
328 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
329 if (ret != ERR_OK || userId == -1) {
330 return ret;
331 }
332 }
333 IsUsePeriod = bundleActiveCore_->IsBundleUsePeriod(bundleName, userId);
334 BUNDLE_ACTIVE_LOGI("IsBundleUsePeriod %{public}d", IsUsePeriod);
335 return ERR_OK;
336 }
337
QueryBundleStatsInfoByInterval(std::vector<BundleActivePackageStats> & packageStats,const int32_t intervalType,const int64_t beginTime,const int64_t endTime,int32_t userId)338 ErrCode BundleActiveService::QueryBundleStatsInfoByInterval(std::vector<BundleActivePackageStats>& packageStats,
339 const int32_t intervalType, const int64_t beginTime, const int64_t endTime, int32_t userId)
340 {
341 BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfoByInterval stats called, intervaltype is %{public}d", intervalType);
342 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
343 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
344 ErrCode ret = ERR_OK;
345 if (userId == -1) {
346 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
347 if (ret != ERR_OK || userId == -1) {
348 return ret;
349 }
350 }
351 BUNDLE_ACTIVE_LOGI("QueryBundleStatsInfos user id is %{public}d", userId);
352 ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
353 if (ret != ERR_OK) {
354 return ret;
355 }
356 std::vector<BundleActivePackageStats> tempPackageStats;
357 int32_t convertedIntervalType = ConvertIntervalType(intervalType);
358 ret = bundleActiveCore_->QueryBundleStatsInfos(
359 tempPackageStats, userId, convertedIntervalType, beginTime, endTime, "");
360 for (auto& packageStat : tempPackageStats) {
361 packageStat.appIndex_ = GetNameAndIndexForUid(packageStat.uid_);
362 }
363 packageStats = MergePackageStats(tempPackageStats);
364 return ret;
365 }
366
GetNameAndIndexForUid(int32_t uid)367 int32_t BundleActiveService::GetNameAndIndexForUid(int32_t uid)
368 {
369 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
370 if (systemAbilityManager == nullptr) {
371 BUNDLE_ACTIVE_LOGE("failed to get samgr");
372 return -1;
373 }
374
375 sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
376 if (remoteObject == nullptr) {
377 BUNDLE_ACTIVE_LOGE("failed to get bundle manager service");
378 return -1;
379 }
380
381 sptr<AppExecFwk::IBundleMgr> bundleManager = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
382 int32_t appIndex = -1;
383 if (bundleManager != nullptr) {
384 std::string bundleName;
385 bundleManager->GetNameAndIndexForUid(uid, bundleName, appIndex);
386 }
387 return appIndex;
388 }
389
QueryBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvents,const int64_t beginTime,const int64_t endTime,int32_t userId)390 ErrCode BundleActiveService::QueryBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvents,
391 const int64_t beginTime, const int64_t endTime, int32_t userId)
392 {
393 ErrCode ret = ERR_OK;
394 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
395 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
396 if (userId == -1) {
397 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
398 if (ret != ERR_OK || userId == -1) {
399 return ret;
400 }
401 }
402 BUNDLE_ACTIVE_LOGI("QueryBundleEvents userid is %{public}d", userId);
403 ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
404 if (ret == ERR_OK) {
405 ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, "");
406 BUNDLE_ACTIVE_LOGI("QueryBundleEvents result is %{public}zu", bundleActiveEvents.size());
407 }
408 return ret;
409 }
410
SetAppGroup(const std::string & bundleName,int32_t newGroup,int32_t userId)411 ErrCode BundleActiveService::SetAppGroup(const std::string& bundleName, int32_t newGroup, int32_t userId)
412 {
413 ErrCode ret = ERR_OK;
414 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
415 bool isFlush = false;
416 if (userId == -1) {
417 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
418 if (ret != ERR_OK || userId == -1) {
419 return ERR_SYSTEM_ABILITY_SUPPORT_FAILED;
420 }
421 isFlush = true;
422 }
423 BUNDLE_ACTIVE_LOGI("SetAppGroup userId is %{public}d", userId);
424
425 std::string localBundleName = "";
426 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, localBundleName);
427 if (localBundleName == bundleName) {
428 BUNDLE_ACTIVE_LOGI("SetAppGroup can not set its bundleName");
429 return ERR_PERMISSION_DENIED;
430 }
431 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
432 ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
433 if (ret == ERR_OK) {
434 ret = bundleActiveCore_->SetAppGroup(bundleName, newGroup, userId, isFlush);
435 }
436 return ret;
437 }
438
QueryBundleStatsInfos(std::vector<BundleActivePackageStats> & bundleActivePackageStats,const int32_t intervalType,const int64_t beginTime,const int64_t endTime)439 ErrCode BundleActiveService::QueryBundleStatsInfos(std::vector<BundleActivePackageStats>& bundleActivePackageStats,
440 const int32_t intervalType, const int64_t beginTime, const int64_t endTime)
441 {
442 // get uid
443 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
444 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
445 BUNDLE_ACTIVE_LOGD("UID is %{public}d", callingUid);
446 // get userid
447 int32_t userId = -1;
448 ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
449 if (ret != ERR_OK || userId == -1) {
450 return ret;
451 }
452 std::vector<BundleActivePackageStats> tempPackageStats;
453 BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfos userid is %{public}d", userId);
454 std::string bundleName = "";
455 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, bundleName);
456 ErrCode isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId);
457 if (!bundleName.empty() && isSystemAppAndHasPermission == ERR_OK) {
458 int32_t convertedIntervalType = ConvertIntervalType(intervalType);
459 ret = bundleActiveCore_->QueryBundleStatsInfos(tempPackageStats, userId, convertedIntervalType,
460 beginTime, endTime, bundleName);
461 }
462 bundleActivePackageStats = MergePackageStats(tempPackageStats);
463 return ret;
464 }
465
QueryCurrentBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvents,const int64_t beginTime,const int64_t endTime)466 ErrCode BundleActiveService::QueryCurrentBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvents,
467 const int64_t beginTime, const int64_t endTime)
468 {
469 // get uid
470 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
471 BUNDLE_ACTIVE_LOGD("QueryCurrentBundleEvents UID is %{public}d", callingUid);
472 // get userid
473 int32_t userId = -1;
474 ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
475 if (ret == ERR_OK && userId != -1) {
476 std::string bundleName = "";
477 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, bundleName);
478 if (!bundleName.empty()) {
479 if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
480 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
481 return ERR_NOT_SYSTEM_APP;
482 }
483 BUNDLE_ACTIVE_LOGI("QueryCurrentBundleEvents buindle name is %{public}s",
484 bundleName.c_str());
485 ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, bundleName);
486 }
487 }
488 BUNDLE_ACTIVE_LOGD("QueryCurrentBundleEvents bundleActiveEvents size is %{public}zu", bundleActiveEvents.size());
489 return ret;
490 }
491
QueryAppGroup(int32_t & appGroup,const std::string & bundleName,int32_t userId)492 ErrCode BundleActiveService::QueryAppGroup(int32_t& appGroup, const std::string& bundleName, int32_t userId)
493 {
494 // get uid
495 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
496 BUNDLE_ACTIVE_LOGD("QueryAppGroup UID is %{public}d", callingUid);
497 ErrCode ret = ERR_OK;
498 if (userId == -1) {
499 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
500 if (ret != ERR_OK || userId == -1) {
501 return ERR_SYSTEM_ABILITY_SUPPORT_FAILED;
502 }
503 }
504 if (bundleName.empty()) {
505 std::string localBundleName = "";
506 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, localBundleName);
507 if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
508 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", localBundleName.c_str());
509 return ERR_NOT_SYSTEM_APP;
510 }
511 ret = bundleActiveCore_->QueryAppGroup(appGroup, localBundleName, userId);
512 } else {
513 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
514 ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
515 if (ret == ERR_OK) {
516 ret = bundleActiveCore_->QueryAppGroup(appGroup, bundleName, userId);
517 }
518 }
519 return ret;
520 }
521
RegisterAppGroupCallBack(const sptr<IAppGroupCallback> & observer)522 ErrCode BundleActiveService::RegisterAppGroupCallBack(const sptr<IAppGroupCallback> &observer)
523 {
524 if (!bundleActiveCore_) {
525 return ERR_MEMORY_OPERATION_FAILED;
526 }
527 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
528 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
529 ErrCode ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
530 if (ret == ERR_OK) {
531 ret = bundleActiveCore_->RegisterAppGroupCallBack(tokenId, observer);
532 }
533 return ret;
534 }
535
UnRegisterAppGroupCallBack(const sptr<IAppGroupCallback> & observer)536 ErrCode BundleActiveService::UnRegisterAppGroupCallBack(const sptr<IAppGroupCallback> &observer)
537 {
538 if (!bundleActiveCore_) {
539 return ERR_MEMORY_OPERATION_FAILED;
540 }
541 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
542 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
543 ErrCode ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
544 if (ret == ERR_OK) {
545 ret = bundleActiveCore_->UnRegisterAppGroupCallBack(tokenId, observer);
546 }
547 return ret;
548 }
549
ConvertIntervalType(const int32_t intervalType)550 int32_t BundleActiveService::ConvertIntervalType(const int32_t intervalType)
551 {
552 if (intervalType == PERIOD_BEST_JS) {
553 return PERIOD_BEST_SERVICE;
554 } else if (intervalType > PERIOD_BEST_JS && intervalType <= PERIOD_YEARLY_JS) {
555 return intervalType - 1;
556 }
557 return -1;
558 }
559
CheckBundleIsSystemAppAndHasPermission(const int32_t uid,OHOS::Security::AccessToken::AccessTokenID tokenId)560 ErrCode BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_t uid,
561 OHOS::Security::AccessToken::AccessTokenID tokenId)
562 {
563 std::string bundleName = "";
564 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(uid, bundleName);
565
566 if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
567 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
568 return ERR_NOT_SYSTEM_APP;
569 }
570
571 int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION);
572 if (bundleHasPermission != 0) {
573 BUNDLE_ACTIVE_LOGE("%{public}s hasn't permission", bundleName.c_str());
574 return ERR_PERMISSION_DENIED;
575 }
576 BUNDLE_ACTIVE_LOGI("%{public}s has permission", bundleName.c_str());
577 return ERR_OK;
578 }
579
CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId)580 ErrCode BundleActiveService::CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId)
581 {
582 int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION);
583 if (bundleHasPermission != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
584 BUNDLE_ACTIVE_LOGE("check native permission not have permission");
585 return ERR_PERMISSION_DENIED;
586 }
587 auto tokenFlag = AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
588 if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) {
589 return ERR_OK;
590 }
591 if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_SHELL) {
592 return ERR_OK;
593 }
594 return ERR_PERMISSION_DENIED;
595 }
596
CheckSystemAppOrNativePermission(const int32_t uid,OHOS::Security::AccessToken::AccessTokenID tokenId)597 ErrCode BundleActiveService::CheckSystemAppOrNativePermission(const int32_t uid,
598 OHOS::Security::AccessToken::AccessTokenID tokenId)
599 {
600 if (AccessToken::AccessTokenKit::GetTokenType(tokenId) == AccessToken::ATokenTypeEnum::TOKEN_HAP) {
601 return CheckBundleIsSystemAppAndHasPermission(uid, tokenId);
602 }
603 return CheckNativePermission(tokenId);
604 }
605
QueryModuleUsageRecords(int32_t maxNum,std::vector<BundleActiveModuleRecord> & results,int32_t userId)606 ErrCode BundleActiveService::QueryModuleUsageRecords(int32_t maxNum, std::vector<BundleActiveModuleRecord>& results,
607 int32_t userId)
608 {
609 ErrCode errCode = ERR_OK;
610 if (maxNum > MAXNUM_UP_LIMIT || maxNum <= 0) {
611 BUNDLE_ACTIVE_LOGE("MaxNum is Invalid!");
612 return ERR_FIND_APP_USAGE_RECORDS_FAILED;
613 }
614 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
615 if (userId == -1) {
616 errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
617 if (errCode != ERR_OK || userId == -1) {
618 return errCode;
619 }
620 }
621 BUNDLE_ACTIVE_LOGI("QueryModuleUsageRecords userid is %{public}d", userId);
622 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
623 errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
624 if (errCode == ERR_OK) {
625 errCode = bundleActiveCore_->QueryModuleUsageRecords(maxNum, results, userId);
626 for (auto& oneResult : results) {
627 QueryModuleRecordInfos(oneResult);
628 }
629 }
630 return errCode;
631 }
632
QueryDeviceEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)633 ErrCode BundleActiveService::QueryDeviceEventStats(int64_t beginTime, int64_t endTime,
634 std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
635 {
636 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
637 ErrCode errCode = ERR_OK;
638 if (userId == -1) {
639 errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
640 if (errCode != ERR_OK || userId == -1) {
641 return errCode;
642 }
643 }
644 BUNDLE_ACTIVE_LOGI("QueryDeviceEventStats userid is %{public}d", userId);
645 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
646 errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
647 if (errCode == ERR_OK) {
648 errCode = bundleActiveCore_->QueryDeviceEventStats(beginTime, endTime, eventStats, userId);
649 }
650 BUNDLE_ACTIVE_LOGD("QueryDeviceEventStats result size is %{public}zu", eventStats.size());
651 return errCode;
652 }
653
QueryNotificationEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)654 ErrCode BundleActiveService::QueryNotificationEventStats(int64_t beginTime, int64_t endTime,
655 std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
656 {
657 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
658 BUNDLE_ACTIVE_LOGD("QueryNotificationEventStats UID is %{public}d", callingUid);
659 // get userid when userId is -1
660 ErrCode errCode = ERR_OK;
661 if (userId == -1) {
662 errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
663 if (errCode != ERR_OK || userId == -1) {
664 return errCode;
665 }
666 }
667 BUNDLE_ACTIVE_LOGI("QueryNotificationEventStats userid is %{public}d", userId);
668 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
669 errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
670 if (errCode == ERR_OK) {
671 errCode = bundleActiveCore_->QueryNotificationEventStats(beginTime, endTime, eventStats, userId);
672 }
673 return errCode;
674 }
675
QueryModuleRecordInfos(BundleActiveModuleRecord & moduleRecord)676 void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord)
677 {
678 ApplicationInfo appInfo;
679 bool getInfoIsSuccess = BundleActiveBundleMgrHelper::GetInstance()->GetApplicationInfo(moduleRecord.bundleName_,
680 ApplicationFlag::GET_BASIC_APPLICATION_INFO, moduleRecord.userId_, appInfo);
681 if (!getInfoIsSuccess) {
682 BUNDLE_ACTIVE_LOGE("GetApplicationInfo failed!");
683 return;
684 }
685 BundleInfo bundleInfo;
686 getInfoIsSuccess = BundleActiveBundleMgrHelper::GetInstance()->GetBundleInfo(moduleRecord.bundleName_,
687 BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, moduleRecord.userId_);
688 if (!getInfoIsSuccess) {
689 BUNDLE_ACTIVE_LOGE("GetBundleInfo failed!");
690 return;
691 }
692 for (const auto& oneModuleInfo : bundleInfo.hapModuleInfos) {
693 if (oneModuleInfo.moduleName == moduleRecord.moduleName_) {
694 std::string mainAbility = oneModuleInfo.mainAbility;
695 for (auto oneAbilityInfo : oneModuleInfo.abilityInfos) {
696 if (oneAbilityInfo.type != AbilityType::PAGE) {
697 continue;
698 }
699 if (mainAbility.empty() || mainAbility.compare(oneAbilityInfo.name) == 0) {
700 SerModuleProperties(oneModuleInfo, appInfo, oneAbilityInfo, moduleRecord);
701 break;
702 }
703 }
704 }
705 }
706 }
707
SerModuleProperties(const HapModuleInfo & hapModuleInfo,const ApplicationInfo & appInfo,const AbilityInfo & abilityInfo,BundleActiveModuleRecord & moduleRecord)708 void BundleActiveService::SerModuleProperties(const HapModuleInfo& hapModuleInfo,
709 const ApplicationInfo& appInfo, const AbilityInfo& abilityInfo, BundleActiveModuleRecord& moduleRecord)
710 {
711 moduleRecord.deviceId_ = appInfo.deviceId;
712 moduleRecord.abilityName_ = abilityInfo.name;
713 moduleRecord.appLabelId_ = appInfo.labelId;
714 moduleRecord.labelId_ = static_cast<uint32_t>(hapModuleInfo.labelId);
715 moduleRecord.abilityLableId_ = abilityInfo.labelId;
716 moduleRecord.descriptionId_ = abilityInfo.descriptionId;
717 moduleRecord.abilityIconId_ = abilityInfo.iconId;
718 moduleRecord.installFreeSupported_ = hapModuleInfo.installationFree;
719 }
720
AllowDump()721 bool BundleActiveService::AllowDump()
722 {
723 if (ENG_MODE == 0) {
724 BUNDLE_ACTIVE_LOGE("Not eng mode");
725 return false;
726 }
727 Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetFirstTokenID();
728 int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, "ohos.permission.DUMP");
729 if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
730 BUNDLE_ACTIVE_LOGE("CheckPermission failed");
731 return false;
732 }
733 return true;
734 }
735
Dump(int32_t fd,const std::vector<std::u16string> & args)736 int32_t BundleActiveService::Dump(int32_t fd, const std::vector<std::u16string> &args)
737 {
738 if (!AllowDump()) {
739 return ERR_PERMISSION_DENIED;
740 }
741 std::vector<std::string> argsInStr;
742 std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
743 [](const std::u16string &arg) {
744 return Str16ToStr8(arg);
745 });
746 std::string result;
747 int32_t ret = ERR_OK;
748 if (argsInStr.size() == NO_DUMP_PARAM_NUMS) {
749 DumpUsage(result);
750 } else {
751 std::vector<std::string> infos;
752 if (argsInStr[0] == "-h") {
753 DumpUsage(result);
754 } else if (argsInStr[0] == "-A") {
755 ret = ShellDump(argsInStr, infos);
756 } else {
757 infos.emplace_back("BundleActiveService Error params.\n");
758 ret = ERR_USAGE_STATS_INVALID_PARAM;
759 }
760 for (auto info : infos) {
761 result.append(info);
762 }
763 }
764 if (!SaveStringToFd(fd, result)) {
765 BUNDLE_ACTIVE_LOGE("BundleActiveService dump save string to fd failed!");
766 ret = ERR_USAGE_STATS_METHOD_CALLED_FAILED;
767 }
768 return ret;
769 }
770
ShellDump(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)771 int32_t BundleActiveService::ShellDump(const std::vector<std::string> &dumpOption, std::vector<std::string> &dumpInfo)
772 {
773 int32_t ret = -1;
774 if (!bundleActiveCore_) {
775 return ret;
776 }
777 if (dumpOption[1] == "Events") {
778 ret = DumpEvents(dumpOption, dumpInfo);
779 } else if (dumpOption[1] == "PackageUsage") {
780 ret = DumpPackageUsage(dumpOption, dumpInfo);
781 } else if (dumpOption[1] == "ModuleUsage") {
782 ret = DumpModuleUsage(dumpOption, dumpInfo);
783 }
784 return ret;
785 }
786
DumpEvents(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)787 int32_t BundleActiveService::DumpEvents(const std::vector<std::string> &dumpOption, std::vector<std::string> &dumpInfo)
788 {
789 int32_t ret = -1;
790 std::vector<BundleActiveEvent> eventResult;
791 if (static_cast<int32_t>(dumpOption.size()) != EVENTS_PARAM) {
792 return ret;
793 }
794 int64_t beginTime = BundleActiveUtil::StringToInt64(dumpOption[2]);
795 int64_t endTime = BundleActiveUtil::StringToInt64(dumpOption[3]);
796 int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[4]);
797 bundleActiveCore_->QueryBundleEvents(eventResult, userId, beginTime, endTime, "");
798 for (auto& oneEvent : eventResult) {
799 dumpInfo.emplace_back(oneEvent.ToString());
800 }
801 return ret;
802 }
803
DumpPackageUsage(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)804 int32_t BundleActiveService::DumpPackageUsage(const std::vector<std::string> &dumpOption,
805 std::vector<std::string> &dumpInfo)
806 {
807 int32_t ret = -1;
808 std::vector<BundleActivePackageStats> tempPackageUsage;
809 if (static_cast<int32_t>(dumpOption.size()) != PACKAGE_USAGE_PARAM) {
810 return ret;
811 }
812 int32_t intervalType = ConvertIntervalType(BundleActiveUtil::StringToInt32(dumpOption[2]));
813 int64_t beginTime = BundleActiveUtil::StringToInt64(dumpOption[3]);
814 int64_t endTime = BundleActiveUtil::StringToInt64(dumpOption[4]);
815 int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[5]);
816 bundleActiveCore_->QueryBundleStatsInfos(
817 tempPackageUsage, userId, intervalType, beginTime, endTime, "");
818 auto packageUsageResult = MergePackageStats(tempPackageUsage);
819 for (auto& onePackageRecord : packageUsageResult) {
820 dumpInfo.emplace_back(onePackageRecord.ToString());
821 }
822 return ret;
823 }
824
DumpModuleUsage(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)825 int32_t BundleActiveService::DumpModuleUsage(const std::vector<std::string> &dumpOption,
826 std::vector<std::string> &dumpInfo)
827 {
828 int32_t ret = -1;
829 std::vector<BundleActiveModuleRecord> moduleResult;
830 if (static_cast<int32_t>(dumpOption.size()) != MODULE_USAGE_PARAM) {
831 return ret;
832 }
833 int32_t maxNum = BundleActiveUtil::StringToInt32(dumpOption[2]);
834 int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[3]);
835 BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId);
836 ret = bundleActiveCore_->QueryModuleUsageRecords(maxNum, moduleResult, userId);
837 for (auto& oneResult : moduleResult) {
838 QueryModuleRecordInfos(oneResult);
839 }
840 for (auto& oneModuleRecord : moduleResult) {
841 dumpInfo.emplace_back(oneModuleRecord.ToString());
842 for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) {
843 std::string oneFormInfo = "form " + std::to_string(static_cast<int32_t>(i) + 1) + ", ";
844 dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString());
845 }
846 }
847 return ret;
848 }
849
DumpUsage(std::string & result)850 void BundleActiveService::DumpUsage(std::string &result)
851 {
852 std::string dumpHelpMsg =
853 "usage: bundleactive dump [<options>]\n"
854 "options list:\n"
855 " -h help menu\n"
856 " -A \n"
857 " Events [beginTime] [endTime] [userId] get events for one user\n"
858 " PackageUsage [intervalType] [beginTime] [endTime] [userId] get package usage for one user\n"
859 " ModuleUsage [maxNum] [userId] get module usage for one user\n";
860 result.append(dumpHelpMsg);
861 }
862
MergePackageStats(const std::vector<BundleActivePackageStats> & packageStats)863 std::vector<BundleActivePackageStats> BundleActiveService::MergePackageStats(
864 const std::vector<BundleActivePackageStats>& packageStats)
865 {
866 if (packageStats.empty()) {
867 return packageStats;
868 }
869 std::vector<BundleActivePackageStats> tempPackageStats;
870 std::shared_ptr<std::map<std::string, BundleActivePackageStats>> mergedPackageStats =
871 std::make_shared<std::map<std::string, BundleActivePackageStats>>();
872 for (auto packageStat : packageStats) {
873 std::string mergedPackageStatsKey = packageStat.bundleName_ + std::to_string(packageStat.uid_);
874 auto iter = mergedPackageStats->find(mergedPackageStatsKey);
875 if (iter != mergedPackageStats->end()) {
876 MergeSamePackageStats(iter->second, packageStat);
877 } else {
878 mergedPackageStats->
879 insert(std::pair<std::string, BundleActivePackageStats>(mergedPackageStatsKey, packageStat));
880 }
881 }
882 for (auto pair : *mergedPackageStats) {
883 tempPackageStats.push_back(pair.second);
884 }
885 return tempPackageStats;
886 }
887
MergeSamePackageStats(BundleActivePackageStats & left,const BundleActivePackageStats & right)888 void BundleActiveService::MergeSamePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right)
889 {
890 if (left.bundleName_ != right.bundleName_) {
891 BUNDLE_ACTIVE_LOGE("Merge package stats failed, existing packageName : %{public}s,"
892 " new packageName : %{public}s,", left.bundleName_.c_str(), right.bundleName_.c_str());
893 return;
894 }
895 left.lastTimeUsed_ = std::max(left.lastTimeUsed_, right.lastTimeUsed_);
896 left.lastContiniousTaskUsed_ = std::max(left.lastContiniousTaskUsed_, right.lastContiniousTaskUsed_);
897 left.totalInFrontTime_ += right.totalInFrontTime_;
898 left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_;
899 left.bundleStartedCount_ += right.bundleStartedCount_;
900 }
901 } // namespace DeviceUsageStats
902 } // namespace OHOS
903
904