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 "bundle_mgr_service.h"
17 
18 #include <sys/stat.h>
19 
20 #include "account_helper.h"
21 #ifdef CODE_SIGNATURE_ENABLE
22 #include "aot/aot_sign_data_cache_mgr.h"
23 #endif
24 #include "aot/aot_device_idle_listener.h"
25 #include "bundle_common_event.h"
26 #include "bundle_memory_guard.h"
27 #include "bundle_resource_helper.h"
28 #include "datetime_ex.h"
29 #include "el5_filekey_callback.h"
30 #include "el5_filekey_manager_kit.h"
31 #include "installd_client.h"
32 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
33 #include "app_control_manager_host_impl.h"
34 #endif
35 #include "perf_profile.h"
36 #include "system_ability_definition.h"
37 #include "system_ability_helper.h"
38 #ifdef HICOLLIE_ENABLE
39 #include "xcollie/watchdog.h"
40 #endif
41 
42 namespace OHOS {
43 namespace AppExecFwk {
44 namespace {
45 constexpr int32_t BUNDLE_BROKER_SERVICE_ABILITY_ID = 0x00010500;
46 constexpr int16_t EL5_FILEKEY_SERVICE_ABILITY_ID = 8250;
47 } // namespace
48 
49 const bool REGISTER_RESULT =
50     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<BundleMgrService>::GetInstance().get());
51 
BundleMgrService()52 BundleMgrService::BundleMgrService() : SystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, true)
53 {
54     APP_LOGI("instance is created");
55     PerfProfile::GetInstance().SetBmsLoadStartTime(GetTickCount());
56 }
57 
~BundleMgrService()58 BundleMgrService::~BundleMgrService()
59 {
60     host_ = nullptr;
61     installer_ = nullptr;
62     if (handler_) {
63         handler_.reset();
64     }
65     if (dataMgr_) {
66         dataMgr_.reset();
67     }
68 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
69     {
70         std::lock_guard<std::mutex> connectLock(bundleConnectMutex_);
71         if (!connectAbilityMgr_.empty()) {
72             connectAbilityMgr_.clear();
73         }
74     }
75 #endif
76     if (hidumpHelper_) {
77         hidumpHelper_.reset();
78     }
79     APP_LOGI("BundleMgrService instance is destroyed");
80 }
81 
OnStart()82 void BundleMgrService::OnStart()
83 {
84     APP_LOGI("BundleMgrService OnStart start");
85     if (!Init()) {
86         APP_LOGE("BundleMgrService init fail");
87         return;
88     }
89 
90     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
91     AddSystemAbilityListener(BUNDLE_BROKER_SERVICE_ABILITY_ID);
92     AddSystemAbilityListener(EL5_FILEKEY_SERVICE_ABILITY_ID);
93     APP_LOGI("BundleMgrService OnStart end");
94 }
95 
OnStop()96 void BundleMgrService::OnStop()
97 {
98     APP_LOGI("OnStop is called");
99     SelfClean();
100 }
101 
OnDeviceLevelChanged(int32_t type, int32_t level, std::string& action)102 void BundleMgrService::OnDeviceLevelChanged(int32_t type, int32_t level, std::string& action)
103 {
104     APP_LOGD("SystemAbility OnDeviceLevelChanged is called");
105     // DeviceStatus::DEVICE_IDLE = 5
106     if (type == 5) {
107         APP_LOGI("receive device idle notification");
108         // 1.screen-off; 2.last-time >= 10mins; 3.power-capacity > 91%
109         AOTDeviceIdleListener::GetInstance().OnReceiveDeviceIdle();
110     }
111 }
112 
IsServiceReady() const113 bool BundleMgrService::IsServiceReady() const
114 {
115     return ready_;
116 }
117 
Init()118 bool BundleMgrService::Init()
119 {
120     if (ready_) {
121         APP_LOGW("init more than one time");
122         return false;
123     }
124 
125     APP_LOGI("BundleMgrService Init begin");
126     CreateBmsServiceDir();
127     InitBmsParam();
128     InitPreInstallExceptionMgr();
129     CHECK_INIT_RESULT(InitBundleMgrHost(), "Init bundleMgr fail");
130     CHECK_INIT_RESULT(InitBundleInstaller(), "Init bundleInstaller fail");
131     InitBundleDataMgr();
132     CHECK_INIT_RESULT(InitBundleUserMgr(), "Init bundleUserMgr fail");
133     CHECK_INIT_RESULT(InitVerifyManager(), "Init verifyManager fail");
134     CHECK_INIT_RESULT(InitExtendResourceManager(), "Init extendResourceManager fail");
135     CHECK_INIT_RESULT(InitBundleEventHandler(), "Init bundleEventHandler fail");
136     InitHidumpHelper();
137     InitFreeInstall();
138     CHECK_INIT_RESULT(InitDefaultApp(), "Init defaultApp fail");
139     CHECK_INIT_RESULT(InitAppControl(), "Init appControl fail");
140     CHECK_INIT_RESULT(InitQuickFixManager(), "Init quickFixManager fail");
141     CHECK_INIT_RESULT(InitOverlayManager(), "Init overlayManager fail");
142     CHECK_INIT_RESULT(InitBundleResourceMgr(), "Init BundleResourceMgr fail");
143     BundleResourceHelper::BundleSystemStateInit();
144     ready_ = true;
145     APP_LOGI("BundleMgrService Init success");
146     return true;
147 }
148 
InitBmsParam()149 void BundleMgrService::InitBmsParam()
150 {
151     bmsParam_ = std::make_shared<BmsParam>();
152 }
153 
InitPreInstallExceptionMgr()154 void BundleMgrService::InitPreInstallExceptionMgr()
155 {
156     preInstallExceptionMgr_ = std::make_shared<PreInstallExceptionMgr>();
157 }
158 
InitBundleMgrHost()159 bool BundleMgrService::InitBundleMgrHost()
160 {
161     if (host_ == nullptr) {
162         host_ = new (std::nothrow) BundleMgrHostImpl();
163     }
164 
165     return host_ != nullptr;
166 }
167 
InitBundleInstaller()168 bool BundleMgrService::InitBundleInstaller()
169 {
170     if (installer_ == nullptr) {
171         installer_ = new (std::nothrow) BundleInstallerHost();
172         if (installer_ == nullptr) {
173             APP_LOGE("init installer fail");
174             return false;
175         }
176         installer_->Init();
177     }
178 
179     return true;
180 }
181 
InitBundleDataMgr()182 void BundleMgrService::InitBundleDataMgr()
183 {
184     if (dataMgr_ == nullptr) {
185         APP_LOGI("Create BundledataMgr");
186         dataMgr_ = std::make_shared<BundleDataMgr>();
187         dataMgr_->AddUserId(Constants::DEFAULT_USERID);
188     }
189 }
190 
InitBundleUserMgr()191 bool BundleMgrService::InitBundleUserMgr()
192 {
193     if (userMgrHost_ == nullptr) {
194         userMgrHost_ = new (std::nothrow) BundleUserMgrHostImpl();
195     }
196 
197     return userMgrHost_ != nullptr;
198 }
199 
InitVerifyManager()200 bool BundleMgrService::InitVerifyManager()
201 {
202     if (verifyManager_ == nullptr) {
203         verifyManager_ = new (std::nothrow) VerifyManagerHostImpl();
204     }
205 
206     return verifyManager_ != nullptr;
207 }
208 
InitExtendResourceManager()209 bool BundleMgrService::InitExtendResourceManager()
210 {
211     if (extendResourceManager_ == nullptr) {
212         extendResourceManager_ = new (std::nothrow) ExtendResourceManagerHostImpl();
213     }
214 
215     return extendResourceManager_ != nullptr;
216 }
217 
InitBundleEventHandler()218 bool BundleMgrService::InitBundleEventHandler()
219 {
220     if (handler_ == nullptr) {
221         handler_ = std::make_shared<BMSEventHandler>();
222     }
223     auto task = [this]() {
224         BundleMemoryGuard memoryGuard;
225         handler_->BmsStartEvent();
226     };
227     ffrt::submit(task);
228     return true;
229 }
230 
InitHidumpHelper()231 void BundleMgrService::InitHidumpHelper()
232 {
233     if (hidumpHelper_ == nullptr) {
234         APP_LOGI("Create hidump helper");
235         hidumpHelper_ = std::make_shared<HidumpHelper>(dataMgr_);
236     }
237 }
238 
InitFreeInstall()239 void BundleMgrService::InitFreeInstall()
240 {
241 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
242     if (agingMgr_ == nullptr) {
243         APP_LOGI("Create aging manager");
244         agingMgr_ = std::make_shared<BundleAgingMgr>();
245         agingMgr_->InitAgingtTimer();
246     }
247     if (bundleDistributedManager_ == nullptr) {
248         APP_LOGI("Create bundleDistributedManager");
249         bundleDistributedManager_ = std::make_shared<BundleDistributedManager>();
250     }
251 #endif
252 }
253 
InitDefaultApp()254 bool BundleMgrService::InitDefaultApp()
255 {
256 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
257     if (defaultAppHostImpl_ == nullptr) {
258         defaultAppHostImpl_ = new (std::nothrow) DefaultAppHostImpl();
259         if (defaultAppHostImpl_ == nullptr) {
260             APP_LOGE("create DefaultAppHostImpl failed");
261             return false;
262         }
263     }
264 #endif
265     return true;
266 }
267 
InitAppControl()268 bool BundleMgrService::InitAppControl()
269 {
270 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
271     if (appControlManagerHostImpl_ == nullptr) {
272         appControlManagerHostImpl_ = new (std::nothrow) AppControlManagerHostImpl();
273         if (appControlManagerHostImpl_ == nullptr) {
274             APP_LOGE("create appControlManagerHostImpl failed");
275             return false;
276         }
277     }
278 #endif
279     return true;
280 }
281 
InitQuickFixManager()282 bool BundleMgrService::InitQuickFixManager()
283 {
284 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
285     if (quickFixManagerHostImpl_ == nullptr) {
286         quickFixManagerHostImpl_ = new (std::nothrow) QuickFixManagerHostImpl();
287         if (quickFixManagerHostImpl_ == nullptr) {
288             APP_LOGE("create QuickFixManagerHostImpl failed");
289             return false;
290         }
291     }
292 #endif
293     return true;
294 }
295 
InitOverlayManager()296 bool BundleMgrService::InitOverlayManager()
297 {
298 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
299     if (overlayManagerHostImpl_ == nullptr) {
300         overlayManagerHostImpl_ = new (std::nothrow) OverlayManagerHostImpl();
301         if (overlayManagerHostImpl_ == nullptr) {
302             APP_LOGE("create OverlayManagerHostImpl failed");
303             return false;
304         }
305     }
306 #endif
307     return true;
308 }
309 
CreateBmsServiceDir()310 void BundleMgrService::CreateBmsServiceDir()
311 {
312     auto ret = InstalldClient::GetInstance()->Mkdir(
313         ServiceConstants::HAP_COPY_PATH, S_IRWXU | S_IXGRP | S_IRGRP | S_IROTH | S_IXOTH,
314         Constants::FOUNDATION_UID, ServiceConstants::BMS_GID);
315     if (!ret) {
316         APP_LOGE("create dir failed");
317     }
318 }
319 
InitBundleResourceMgr()320 bool BundleMgrService::InitBundleResourceMgr()
321 {
322 #ifdef BUNDLE_FRAMEWORK_BUNDLE_RESOURCE
323     if (bundleResourceHostImpl_ == nullptr) {
324         bundleResourceHostImpl_ = new (std::nothrow) BundleResourceHostImpl();
325         if (bundleResourceHostImpl_ == nullptr) {
326             APP_LOGE("create bundleResourceHostImpl failed");
327             return false;
328         }
329     }
330 #endif
331     return true;
332 }
333 
GetBundleInstaller() const334 sptr<BundleInstallerHost> BundleMgrService::GetBundleInstaller() const
335 {
336     return installer_;
337 }
338 
RegisterDataMgr(std::shared_ptr<BundleDataMgr> dataMgrImpl)339 void BundleMgrService::RegisterDataMgr(std::shared_ptr<BundleDataMgr> dataMgrImpl)
340 {
341     dataMgr_ = dataMgrImpl;
342     if (dataMgr_ != nullptr) {
343         dataMgr_->AddUserId(Constants::DEFAULT_USERID);
344     }
345 }
346 
GetDataMgr() const347 const std::shared_ptr<BundleDataMgr> BundleMgrService::GetDataMgr() const
348 {
349     return dataMgr_;
350 }
351 
352 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
GetAgingMgr() const353 const std::shared_ptr<BundleAgingMgr> BundleMgrService::GetAgingMgr() const
354 {
355     return agingMgr_;
356 }
357 
GetConnectAbility(int32_t userId)358 const std::shared_ptr<BundleConnectAbilityMgr> BundleMgrService::GetConnectAbility(int32_t userId)
359 {
360     int32_t currentUserId = userId;
361     if (currentUserId == Constants::UNSPECIFIED_USERID) {
362         currentUserId = AccountHelper::GetCurrentActiveUserId();
363     }
364     std::lock_guard<std::mutex> connectLock(bundleConnectMutex_);
365     if (connectAbilityMgr_.find(userId) == connectAbilityMgr_.end() ||
366         connectAbilityMgr_[userId] == nullptr) {
367         auto ptr = std::make_shared<BundleConnectAbilityMgr>();
368         connectAbilityMgr_[userId] = ptr;
369     }
370     return connectAbilityMgr_[userId];
371 }
372 
GetBundleDistributedManager() const373 const std::shared_ptr<BundleDistributedManager> BundleMgrService::GetBundleDistributedManager() const
374 {
375     return bundleDistributedManager_;
376 }
377 #endif
378 
SelfClean()379 void BundleMgrService::SelfClean()
380 {
381     if (ready_) {
382         ready_ = false;
383         if (registerToService_) {
384             registerToService_ = false;
385         }
386     }
387 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
388     agingMgr_.reset();
389     {
390         std::lock_guard<std::mutex> connectLock(bundleConnectMutex_);
391         connectAbilityMgr_.clear();
392     }
393     bundleDistributedManager_.reset();
394 #endif
395 }
396 
GetBundleUserMgr() const397 sptr<BundleUserMgrHostImpl> BundleMgrService::GetBundleUserMgr() const
398 {
399     return userMgrHost_;
400 }
401 
GetVerifyManager() const402 sptr<IVerifyManager> BundleMgrService::GetVerifyManager() const
403 {
404     return verifyManager_;
405 }
406 
GetExtendResourceManager() const407 sptr<IExtendResourceManager> BundleMgrService::GetExtendResourceManager() const
408 {
409     return extendResourceManager_;
410 }
411 
GetBmsParam() const412 const std::shared_ptr<BmsParam> BundleMgrService::GetBmsParam() const
413 {
414     return bmsParam_;
415 }
416 
GetPreInstallExceptionMgr() const417 const std::shared_ptr<PreInstallExceptionMgr> BundleMgrService::GetPreInstallExceptionMgr() const
418 {
419     return preInstallExceptionMgr_;
420 }
421 
422 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
GetDefaultAppProxy() const423 sptr<IDefaultApp> BundleMgrService::GetDefaultAppProxy() const
424 {
425     return defaultAppHostImpl_;
426 }
427 #endif
428 
429 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
GetAppControlProxy() const430 sptr<IAppControlMgr> BundleMgrService::GetAppControlProxy() const
431 {
432     return appControlManagerHostImpl_;
433 }
434 #endif
435 
436 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
GetQuickFixManagerProxy() const437 sptr<QuickFixManagerHostImpl> BundleMgrService::GetQuickFixManagerProxy() const
438 {
439     return quickFixManagerHostImpl_;
440 }
441 #endif
442 
443 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
GetOverlayManagerProxy() const444 sptr<IOverlayManager> BundleMgrService::GetOverlayManagerProxy() const
445 {
446     return overlayManagerHostImpl_;
447 }
448 #endif
449 
450 #ifdef BUNDLE_FRAMEWORK_BUNDLE_RESOURCE
GetBundleResourceProxy() const451 sptr<IBundleResource> BundleMgrService::GetBundleResourceProxy() const
452 {
453     return bundleResourceHostImpl_;
454 }
455 #endif
456 
CheckAllUser()457 void BundleMgrService::CheckAllUser()
458 {
459     if (dataMgr_ == nullptr) {
460         return;
461     }
462 
463     APP_LOGI("Check all user start");
464     std::set<int32_t> userIds = dataMgr_->GetAllUser();
465     for (auto userId : userIds) {
466         if (userId == Constants::DEFAULT_USERID) {
467             continue;
468         }
469 
470         bool isExists = false;
471         if (AccountHelper::IsOsAccountExists(userId, isExists) != ERR_OK) {
472             APP_LOGW("Failed query whether user(%{public}d) exists", userId);
473             continue;
474         }
475 
476         if (!isExists) {
477             APP_LOGI("Query user(%{public}d) success but not complete and remove it", userId);
478             userMgrHost_->RemoveUser(userId);
479 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
480             {
481                 std::lock_guard<std::mutex> connectLock(bundleConnectMutex_);
482                 connectAbilityMgr_.erase(userId);
483             }
484 #endif
485         }
486     }
487     APP_LOGI("Check all user end");
488 }
489 
RegisterService()490 void BundleMgrService::RegisterService()
491 {
492     if (!registerToService_) {
493         if (!SystemAbilityHelper::AddSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, host_)) {
494             APP_LOGE("fail to register to system ability manager");
495             return;
496         }
497         APP_LOGI("BundleMgrService register to sam success");
498         registerToService_ = true;
499     }
500 
501     PerfProfile::GetInstance().SetBmsLoadEndTime(GetTickCount());
502     PerfProfile::GetInstance().Dump();
503 }
504 
NotifyBundleScanStatus()505 void BundleMgrService::NotifyBundleScanStatus()
506 {
507     APP_LOGI("PublishCommonEvent for bundle scan finished");
508     AAFwk::Want want;
509     want.SetAction(COMMON_EVENT_BUNDLE_SCAN_FINISHED);
510     EventFwk::CommonEventData commonEventData { want };
511     if (!EventFwk::CommonEventManager::PublishCommonEvent(commonEventData)) {
512         notifyBundleScanStatus = true;
513         APP_LOGE("PublishCommonEvent for bundle scan finished failed");
514     } else {
515         APP_LOGI("PublishCommonEvent for bundle scan finished succeed");
516     }
517 }
518 
OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)519 void BundleMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
520 {
521     APP_LOGI("OnAddSystemAbility systemAbilityId:%{public}d added", systemAbilityId);
522     if (COMMON_EVENT_SERVICE_ID == systemAbilityId && notifyBundleScanStatus) {
523         NotifyBundleScanStatus();
524     }
525 #ifdef CODE_SIGNATURE_ENABLE
526     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
527         AOTSignDataCacheMgr::GetInstance().RegisterScreenUnlockListener();
528     }
529 #endif
530     if (BUNDLE_BROKER_SERVICE_ABILITY_ID == systemAbilityId) {
531         if (host_ != nullptr) {
532             isBrokerServiceStarted_ = true;
533             host_->SetBrokerServiceStatus(true);
534         }
535     }
536     if (EL5_FILEKEY_SERVICE_ABILITY_ID == systemAbilityId) {
537         int32_t reg = Security::AccessToken::El5FilekeyManagerKit::RegisterCallback(sptr(new El5FilekeyCallback()));
538         APP_LOGI("Register El5FilekeyCallback result: %{public}d", reg);
539     }
540 }
541 
Hidump(const std::vector<std::string> &args, std::string& result) const542 bool BundleMgrService::Hidump(const std::vector<std::string> &args, std::string& result) const
543 {
544     if (hidumpHelper_ && hidumpHelper_->Dump(args, result)) {
545         return true;
546     }
547 
548     APP_LOGD("HidumpHelper failed");
549     return false;
550 }
551 
IsBrokerServiceStarted() const552 bool BundleMgrService::IsBrokerServiceStarted() const
553 {
554     return isBrokerServiceStarted_;
555 }
556 }  // namespace AppExecFwk
557 }  // namespace OHOS
558