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