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 for (auto& packageStat : PackageStats) {
357 packageStat.appIndex_ = GetNameAndIndexForUid(packageStat.uid_);
358 }
359 }
360 return ret;
361 }
362
GetNameAndIndexForUid(int32_t uid)363 int32_t BundleActiveService::GetNameAndIndexForUid(int32_t uid)
364 {
365 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
366 if (systemAbilityManager == nullptr) {
367 BUNDLE_ACTIVE_LOGE("failed to get samgr");
368 return -1;
369 }
370
371 sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
372 if (remoteObject == nullptr) {
373 BUNDLE_ACTIVE_LOGE("failed to get bundle manager service");
374 return -1;
375 }
376
377 sptr<AppExecFwk::IBundleMgr> bundleManager = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
378 int32_t appIndex = -1;
379 if (bundleManager != nullptr) {
380 std::string bundleName;
381 bundleManager->GetNameAndIndexForUid(uid, bundleName, appIndex);
382 }
383 return appIndex;
384 }
385
QueryBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvents,const int64_t beginTime,const int64_t endTime,int32_t userId)386 ErrCode BundleActiveService::QueryBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvents,
387 const int64_t beginTime, const int64_t endTime, int32_t userId)
388 {
389 ErrCode ret = ERR_OK;
390 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
391 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
392 if (userId == -1) {
393 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
394 if (ret != ERR_OK || userId == -1) {
395 return ret;
396 }
397 }
398 BUNDLE_ACTIVE_LOGI("QueryBundleEvents userid is %{public}d", userId);
399 ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
400 if (ret == ERR_OK) {
401 ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, "");
402 BUNDLE_ACTIVE_LOGI("QueryBundleEvents result is %{public}zu", bundleActiveEvents.size());
403 }
404 return ret;
405 }
406
SetAppGroup(const std::string & bundleName,int32_t newGroup,int32_t userId)407 ErrCode BundleActiveService::SetAppGroup(const std::string& bundleName, int32_t newGroup, int32_t userId)
408 {
409 ErrCode ret = ERR_OK;
410 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
411 bool isFlush = false;
412 if (userId == -1) {
413 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
414 if (ret != ERR_OK || userId == -1) {
415 return ERR_SYSTEM_ABILITY_SUPPORT_FAILED;
416 }
417 isFlush = true;
418 }
419 BUNDLE_ACTIVE_LOGI("SetAppGroup userId is %{public}d", userId);
420
421 std::string localBundleName = "";
422 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, localBundleName);
423 if (localBundleName == bundleName) {
424 BUNDLE_ACTIVE_LOGI("SetAppGroup can not set its bundleName");
425 return ERR_PERMISSION_DENIED;
426 }
427 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
428 ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
429 if (ret == ERR_OK) {
430 ret = bundleActiveCore_->SetAppGroup(bundleName, newGroup, userId, isFlush);
431 }
432 return ret;
433 }
434
QueryBundleStatsInfos(std::vector<BundleActivePackageStats> & bundleActivePackageStats,const int32_t intervalType,const int64_t beginTime,const int64_t endTime)435 ErrCode BundleActiveService::QueryBundleStatsInfos(std::vector<BundleActivePackageStats>& bundleActivePackageStats,
436 const int32_t intervalType, const int64_t beginTime, const int64_t endTime)
437 {
438 // get uid
439 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
440 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
441 BUNDLE_ACTIVE_LOGD("UID is %{public}d", callingUid);
442 // get userid
443 int32_t userId = -1;
444 ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
445 if (ret == ERR_OK && userId != -1) {
446 BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfos userid is %{public}d", userId);
447 std::string bundleName = "";
448 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, bundleName);
449 ErrCode isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId);
450 if (!bundleName.empty() && isSystemAppAndHasPermission == ERR_OK) {
451 int32_t convertedIntervalType = ConvertIntervalType(intervalType);
452 ret = bundleActiveCore_->QueryBundleStatsInfos(bundleActivePackageStats, userId, convertedIntervalType,
453 beginTime, endTime, bundleName);
454 }
455 }
456 return ret;
457 }
458
QueryCurrentBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvents,const int64_t beginTime,const int64_t endTime)459 ErrCode BundleActiveService::QueryCurrentBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvents,
460 const int64_t beginTime, const int64_t endTime)
461 {
462 // get uid
463 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
464 BUNDLE_ACTIVE_LOGD("QueryCurrentBundleEvents UID is %{public}d", callingUid);
465 // get userid
466 int32_t userId = -1;
467 ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
468 if (ret == ERR_OK && userId != -1) {
469 std::string bundleName = "";
470 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, bundleName);
471 if (!bundleName.empty()) {
472 if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
473 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
474 return ERR_NOT_SYSTEM_APP;
475 }
476 BUNDLE_ACTIVE_LOGI("QueryCurrentBundleEvents buindle name is %{public}s",
477 bundleName.c_str());
478 ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, bundleName);
479 }
480 }
481 BUNDLE_ACTIVE_LOGD("QueryCurrentBundleEvents bundleActiveEvents size is %{public}zu", bundleActiveEvents.size());
482 return ret;
483 }
484
QueryAppGroup(int32_t & appGroup,std::string & bundleName,int32_t userId)485 ErrCode BundleActiveService::QueryAppGroup(int32_t& appGroup, std::string& bundleName, int32_t userId)
486 {
487 // get uid
488 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
489 BUNDLE_ACTIVE_LOGD("QueryAppGroup UID is %{public}d", callingUid);
490 ErrCode ret = ERR_OK;
491 if (userId == -1) {
492 ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
493 if (ret != ERR_OK || userId == -1) {
494 return ERR_SYSTEM_ABILITY_SUPPORT_FAILED;
495 }
496 }
497 if (bundleName.empty()) {
498 std::string localBundleName = "";
499 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, localBundleName);
500 if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
501 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", localBundleName.c_str());
502 return ERR_NOT_SYSTEM_APP;
503 }
504 bundleName = localBundleName;
505 ret = bundleActiveCore_->QueryAppGroup(appGroup, bundleName, userId);
506 } else {
507 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
508 ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
509 if (ret == ERR_OK) {
510 ret = bundleActiveCore_->QueryAppGroup(appGroup, bundleName, userId);
511 }
512 }
513 return ret;
514 }
515
RegisterAppGroupCallBack(const sptr<IAppGroupCallback> & observer)516 ErrCode BundleActiveService::RegisterAppGroupCallBack(const sptr<IAppGroupCallback> &observer)
517 {
518 if (!bundleActiveCore_) {
519 return ERR_MEMORY_OPERATION_FAILED;
520 }
521 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
522 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
523 ErrCode ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
524 if (ret == ERR_OK) {
525 ret = bundleActiveCore_->RegisterAppGroupCallBack(tokenId, observer);
526 }
527 return ret;
528 }
529
UnRegisterAppGroupCallBack(const sptr<IAppGroupCallback> & observer)530 ErrCode BundleActiveService::UnRegisterAppGroupCallBack(const sptr<IAppGroupCallback> &observer)
531 {
532 if (!bundleActiveCore_) {
533 return ERR_MEMORY_OPERATION_FAILED;
534 }
535 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
536 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
537 ErrCode ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
538 if (ret == ERR_OK) {
539 ret = bundleActiveCore_->UnRegisterAppGroupCallBack(tokenId, observer);
540 }
541 return ret;
542 }
543
ConvertIntervalType(const int32_t intervalType)544 int32_t BundleActiveService::ConvertIntervalType(const int32_t intervalType)
545 {
546 if (intervalType == PERIOD_BEST_JS) {
547 return PERIOD_BEST_SERVICE;
548 } else if (intervalType > PERIOD_BEST_JS && intervalType <= PERIOD_YEARLY_JS) {
549 return intervalType - 1;
550 }
551 return -1;
552 }
553
CheckBundleIsSystemAppAndHasPermission(const int32_t uid,OHOS::Security::AccessToken::AccessTokenID tokenId)554 ErrCode BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_t uid,
555 OHOS::Security::AccessToken::AccessTokenID tokenId)
556 {
557 std::string bundleName = "";
558 BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(uid, bundleName);
559
560 if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
561 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
562 return ERR_NOT_SYSTEM_APP;
563 }
564
565 int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION);
566 if (bundleHasPermission != 0) {
567 BUNDLE_ACTIVE_LOGE("%{public}s hasn't permission", bundleName.c_str());
568 return ERR_PERMISSION_DENIED;
569 }
570 BUNDLE_ACTIVE_LOGI("%{public}s has permission", bundleName.c_str());
571 return ERR_OK;
572 }
573
CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId)574 ErrCode BundleActiveService::CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId)
575 {
576 int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION);
577 if (bundleHasPermission != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
578 BUNDLE_ACTIVE_LOGE("check native permission not have permission");
579 return ERR_PERMISSION_DENIED;
580 }
581 auto tokenFlag = AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
582 if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) {
583 return ERR_OK;
584 }
585 if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_SHELL) {
586 return ERR_OK;
587 }
588 return ERR_PERMISSION_DENIED;
589 }
590
CheckSystemAppOrNativePermission(const int32_t uid,OHOS::Security::AccessToken::AccessTokenID tokenId)591 ErrCode BundleActiveService::CheckSystemAppOrNativePermission(const int32_t uid,
592 OHOS::Security::AccessToken::AccessTokenID tokenId)
593 {
594 if (AccessToken::AccessTokenKit::GetTokenType(tokenId) == AccessToken::ATokenTypeEnum::TOKEN_HAP) {
595 return CheckBundleIsSystemAppAndHasPermission(uid, tokenId);
596 }
597 return CheckNativePermission(tokenId);
598 }
599
QueryModuleUsageRecords(int32_t maxNum,std::vector<BundleActiveModuleRecord> & results,int32_t userId)600 ErrCode BundleActiveService::QueryModuleUsageRecords(int32_t maxNum, std::vector<BundleActiveModuleRecord>& results,
601 int32_t userId)
602 {
603 ErrCode errCode = ERR_OK;
604 if (maxNum > MAXNUM_UP_LIMIT || maxNum <= 0) {
605 BUNDLE_ACTIVE_LOGE("MaxNum is Invalid!");
606 return ERR_FIND_APP_USAGE_RECORDS_FAILED;
607 }
608 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
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("QueryModuleUsageRecords 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_->QueryModuleUsageRecords(maxNum, results, userId);
620 for (auto& oneResult : results) {
621 QueryModuleRecordInfos(oneResult);
622 }
623 }
624 return errCode;
625 }
626
QueryDeviceEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)627 ErrCode BundleActiveService::QueryDeviceEventStats(int64_t beginTime, int64_t endTime,
628 std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
629 {
630 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
631 ErrCode errCode = ERR_OK;
632 if (userId == -1) {
633 errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
634 if (errCode != ERR_OK || userId == -1) {
635 return errCode;
636 }
637 }
638 BUNDLE_ACTIVE_LOGI("QueryDeviceEventStats userid is %{public}d", userId);
639 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
640 errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
641 if (errCode == ERR_OK) {
642 errCode = bundleActiveCore_->QueryDeviceEventStats(beginTime, endTime, eventStats, userId);
643 }
644 BUNDLE_ACTIVE_LOGD("QueryDeviceEventStats result size is %{public}zu", eventStats.size());
645 return errCode;
646 }
647
QueryNotificationEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)648 ErrCode BundleActiveService::QueryNotificationEventStats(int64_t beginTime, int64_t endTime,
649 std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
650 {
651 int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
652 BUNDLE_ACTIVE_LOGD("QueryNotificationEventStats UID is %{public}d", callingUid);
653 // get userid when userId is -1
654 ErrCode errCode = ERR_OK;
655 if (userId == -1) {
656 errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
657 if (errCode != ERR_OK || userId == -1) {
658 return errCode;
659 }
660 }
661 BUNDLE_ACTIVE_LOGI("QueryNotificationEventStats userid is %{public}d", userId);
662 AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
663 errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
664 if (errCode == ERR_OK) {
665 errCode = bundleActiveCore_->QueryNotificationEventStats(beginTime, endTime, eventStats, userId);
666 }
667 return errCode;
668 }
669
QueryModuleRecordInfos(BundleActiveModuleRecord & moduleRecord)670 void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord)
671 {
672 ApplicationInfo appInfo;
673 bool getInfoIsSuccess = BundleActiveBundleMgrHelper::GetInstance()->GetApplicationInfo(moduleRecord.bundleName_,
674 ApplicationFlag::GET_BASIC_APPLICATION_INFO, moduleRecord.userId_, appInfo);
675 if (!getInfoIsSuccess) {
676 BUNDLE_ACTIVE_LOGE("GetApplicationInfo failed!");
677 return;
678 }
679 BundleInfo bundleInfo;
680 getInfoIsSuccess = BundleActiveBundleMgrHelper::GetInstance()->GetBundleInfo(moduleRecord.bundleName_,
681 BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, moduleRecord.userId_);
682 if (!getInfoIsSuccess) {
683 BUNDLE_ACTIVE_LOGE("GetBundleInfo failed!");
684 return;
685 }
686 for (const auto& oneModuleInfo : bundleInfo.hapModuleInfos) {
687 if (oneModuleInfo.moduleName == moduleRecord.moduleName_) {
688 std::string mainAbility = oneModuleInfo.mainAbility;
689 for (auto oneAbilityInfo : oneModuleInfo.abilityInfos) {
690 if (oneAbilityInfo.type != AbilityType::PAGE) {
691 continue;
692 }
693 if (mainAbility.empty() || mainAbility.compare(oneAbilityInfo.name) == 0) {
694 SerModuleProperties(oneModuleInfo, appInfo, oneAbilityInfo, moduleRecord);
695 break;
696 }
697 }
698 }
699 }
700 }
701
SerModuleProperties(const HapModuleInfo & hapModuleInfo,const ApplicationInfo & appInfo,const AbilityInfo & abilityInfo,BundleActiveModuleRecord & moduleRecord)702 void BundleActiveService::SerModuleProperties(const HapModuleInfo& hapModuleInfo,
703 const ApplicationInfo& appInfo, const AbilityInfo& abilityInfo, BundleActiveModuleRecord& moduleRecord)
704 {
705 moduleRecord.deviceId_ = appInfo.deviceId;
706 moduleRecord.abilityName_ = abilityInfo.name;
707 moduleRecord.appLabelId_ = appInfo.labelId;
708 moduleRecord.labelId_ = static_cast<uint32_t>(hapModuleInfo.labelId);
709 moduleRecord.abilityLableId_ = abilityInfo.labelId;
710 moduleRecord.descriptionId_ = abilityInfo.descriptionId;
711 moduleRecord.abilityIconId_ = abilityInfo.iconId;
712 moduleRecord.installFreeSupported_ = hapModuleInfo.installationFree;
713 }
714
AllowDump()715 bool BundleActiveService::AllowDump()
716 {
717 if (ENG_MODE == 0) {
718 BUNDLE_ACTIVE_LOGE("Not eng mode");
719 return false;
720 }
721 Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetFirstTokenID();
722 int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, "ohos.permission.DUMP");
723 if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
724 BUNDLE_ACTIVE_LOGE("CheckPermission failed");
725 return false;
726 }
727 return true;
728 }
729
Dump(int32_t fd,const std::vector<std::u16string> & args)730 int32_t BundleActiveService::Dump(int32_t fd, const std::vector<std::u16string> &args)
731 {
732 if (!AllowDump()) {
733 return ERR_PERMISSION_DENIED;
734 }
735 std::vector<std::string> argsInStr;
736 std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
737 [](const std::u16string &arg) {
738 return Str16ToStr8(arg);
739 });
740 std::string result;
741 int32_t ret = ERR_OK;
742 if (argsInStr.size() == NO_DUMP_PARAM_NUMS) {
743 DumpUsage(result);
744 } else {
745 std::vector<std::string> infos;
746 if (argsInStr[0] == "-h") {
747 DumpUsage(result);
748 } else if (argsInStr[0] == "-A") {
749 ret = ShellDump(argsInStr, infos);
750 } else {
751 infos.emplace_back("BundleActiveService Error params.\n");
752 ret = ERR_USAGE_STATS_INVALID_PARAM;
753 }
754 for (auto info : infos) {
755 result.append(info);
756 }
757 }
758 if (!SaveStringToFd(fd, result)) {
759 BUNDLE_ACTIVE_LOGE("BundleActiveService dump save string to fd failed!");
760 ret = ERR_USAGE_STATS_METHOD_CALLED_FAILED;
761 }
762 return ret;
763 }
764
ShellDump(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)765 int32_t BundleActiveService::ShellDump(const std::vector<std::string> &dumpOption, std::vector<std::string> &dumpInfo)
766 {
767 int32_t ret = -1;
768 if (!bundleActiveCore_) {
769 return ret;
770 }
771 if (dumpOption[1] == "Events") {
772 ret = DumpEvents(dumpOption, dumpInfo);
773 } else if (dumpOption[1] == "PackageUsage") {
774 ret = DumpPackageUsage(dumpOption, dumpInfo);
775 } else if (dumpOption[1] == "ModuleUsage") {
776 ret = DumpModuleUsage(dumpOption, dumpInfo);
777 }
778 return ret;
779 }
780
DumpEvents(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)781 int32_t BundleActiveService::DumpEvents(const std::vector<std::string> &dumpOption, std::vector<std::string> &dumpInfo)
782 {
783 int32_t ret = -1;
784 std::vector<BundleActiveEvent> eventResult;
785 if (static_cast<int32_t>(dumpOption.size()) != EVENTS_PARAM) {
786 return ret;
787 }
788 int64_t beginTime = BundleActiveUtil::StringToInt64(dumpOption[2]);
789 int64_t endTime = BundleActiveUtil::StringToInt64(dumpOption[3]);
790 int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[4]);
791 bundleActiveCore_->QueryBundleEvents(eventResult, userId, beginTime, endTime, "");
792 for (auto& oneEvent : eventResult) {
793 dumpInfo.emplace_back(oneEvent.ToString());
794 }
795 return ret;
796 }
797
DumpPackageUsage(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)798 int32_t BundleActiveService::DumpPackageUsage(const std::vector<std::string> &dumpOption,
799 std::vector<std::string> &dumpInfo)
800 {
801 int32_t ret = -1;
802 std::vector<BundleActivePackageStats> packageUsageResult;
803 if (static_cast<int32_t>(dumpOption.size()) != PACKAGE_USAGE_PARAM) {
804 return ret;
805 }
806 int32_t intervalType = ConvertIntervalType(BundleActiveUtil::StringToInt32(dumpOption[2]));
807 int64_t beginTime = BundleActiveUtil::StringToInt64(dumpOption[3]);
808 int64_t endTime = BundleActiveUtil::StringToInt64(dumpOption[4]);
809 int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[5]);
810 bundleActiveCore_->QueryBundleStatsInfos(
811 packageUsageResult, userId, intervalType, beginTime, endTime, "");
812 for (auto& onePackageRecord : packageUsageResult) {
813 dumpInfo.emplace_back(onePackageRecord.ToString());
814 }
815 return ret;
816 }
817
DumpModuleUsage(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)818 int32_t BundleActiveService::DumpModuleUsage(const std::vector<std::string> &dumpOption,
819 std::vector<std::string> &dumpInfo)
820 {
821 int32_t ret = -1;
822 std::vector<BundleActiveModuleRecord> moduleResult;
823 if (static_cast<int32_t>(dumpOption.size()) != MODULE_USAGE_PARAM) {
824 return ret;
825 }
826 int32_t maxNum = BundleActiveUtil::StringToInt32(dumpOption[2]);
827 int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[3]);
828 BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId);
829 ret = bundleActiveCore_->QueryModuleUsageRecords(maxNum, moduleResult, userId);
830 for (auto& oneResult : moduleResult) {
831 QueryModuleRecordInfos(oneResult);
832 }
833 for (auto& oneModuleRecord : moduleResult) {
834 dumpInfo.emplace_back(oneModuleRecord.ToString());
835 for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) {
836 std::string oneFormInfo = "form " + std::to_string(static_cast<int32_t>(i) + 1) + ", ";
837 dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString());
838 }
839 }
840 return ret;
841 }
842
DumpUsage(std::string & result)843 void BundleActiveService::DumpUsage(std::string &result)
844 {
845 std::string dumpHelpMsg =
846 "usage: bundleactive dump [<options>]\n"
847 "options list:\n"
848 " -h help menu\n"
849 " -A \n"
850 " Events [beginTime] [endTime] [userId] get events for one user\n"
851 " PackageUsage [intervalType] [beginTime] [endTime] [userId] get package usage for one user\n"
852 " ModuleUsage [maxNum] [userId] get module usage for one user\n";
853 result.append(dumpHelpMsg);
854 }
855 } // namespace DeviceUsageStats
856 } // namespace OHOS
857
858