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