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 "bundle_common_event.h"
25 #include "bundle_memory_guard.h"
26 #include "bundle_resource_helper.h"
27 #include "datetime_ex.h"
28 #include "el5_filekey_callback.h"
29 #include "el5_filekey_manager_kit.h"
30 #include "installd_client.h"
31 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
32 #include "app_control_manager_host_impl.h"
33 #endif
34 #include "perf_profile.h"
35 #include "scope_guard.h"
36 #include "system_ability_definition.h"
37 #include "system_ability_helper.h"
38 #include "xcollie_helper.h"
39 
40 namespace OHOS {
41 namespace AppExecFwk {
42 namespace {
43 const int32_t BUNDLE_BROKER_SERVICE_ABILITY_ID = 0x00010500;
44 const int32_t EL5_FILEKEY_SERVICE_ABILITY_ID = 8250;
45 constexpr const char* FUN_BMS_START = "BundleMgrService::Start";
46 constexpr unsigned int BMS_START_TIME_OUT_SECONDS = 60 * 4;
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_NOFUNC("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_NOFUNC("BundleMgrService OnStart end");
94 }
95 
OnStop()96 void BundleMgrService::OnStop()
97 {
98     APP_LOGI("OnStop is called");
99     SelfClean();
100 }
101 
IsServiceReady() const102 bool BundleMgrService::IsServiceReady() const
103 {
104     return ready_;
105 }
106 
Init()107 bool BundleMgrService::Init()
108 {
109     if (ready_) {
110         APP_LOGW("init more than one time");
111         return false;
112     }
113 
114     APP_LOGI_NOFUNC("BundleMgrService Init begin");
115     CreateBmsServiceDir();
116     InitBmsParam();
117     InitPreInstallExceptionMgr();
118     CHECK_INIT_RESULT(InitBundleMgrHost(), "Init bundleMgr fail");
119     CHECK_INIT_RESULT(InitBundleInstaller(), "Init bundleInstaller fail");
120     InitBundleDataMgr();
121     CHECK_INIT_RESULT(InitBundleUserMgr(), "Init bundleUserMgr fail");
122     CHECK_INIT_RESULT(InitVerifyManager(), "Init verifyManager fail");
123     CHECK_INIT_RESULT(InitExtendResourceManager(), "Init extendResourceManager fail");
124     CHECK_INIT_RESULT(InitBundleEventHandler(), "Init bundleEventHandler fail");
125     InitHidumpHelper();
126     InitFreeInstall();
127     CHECK_INIT_RESULT(InitDefaultApp(), "Init defaultApp fail");
128     CHECK_INIT_RESULT(InitAppControl(), "Init appControl fail");
129     CHECK_INIT_RESULT(InitQuickFixManager(), "Init quickFixManager fail");
130     CHECK_INIT_RESULT(InitOverlayManager(), "Init overlayManager fail");
131     CHECK_INIT_RESULT(InitBundleResourceMgr(), "Init BundleResourceMgr fail");
132     BundleResourceHelper::BundleSystemStateInit();
133     ready_ = true;
134     APP_LOGI_NOFUNC("BundleMgrService Init success");
135     return true;
136 }
137 
InitBmsParam()138 void BundleMgrService::InitBmsParam()
139 {
140     bmsParam_ = std::make_shared<BmsParam>();
141 }
142 
InitPreInstallExceptionMgr()143 void BundleMgrService::InitPreInstallExceptionMgr()
144 {
145     preInstallExceptionMgr_ = std::make_shared<PreInstallExceptionMgr>();
146 }
147 
InitBundleMgrHost()148 bool BundleMgrService::InitBundleMgrHost()
149 {
150     if (host_ == nullptr) {
151         host_ = new (std::nothrow) BundleMgrHostImpl();
152     }
153 
154     return host_ != nullptr;
155 }
156 
InitBundleInstaller()157 bool BundleMgrService::InitBundleInstaller()
158 {
159     if (installer_ == nullptr) {
160         installer_ = new (std::nothrow) BundleInstallerHost();
161         if (installer_ == nullptr) {
162             APP_LOGE("init installer fail");
163             return false;
164         }
165         installer_->Init();
166     }
167 
168     return true;
169 }
170 
InitBundleDataMgr()171 void BundleMgrService::InitBundleDataMgr()
172 {
173     if (dataMgr_ == nullptr) {
174         APP_LOGI("Create BundledataMgr");
175         dataMgr_ = std::make_shared<BundleDataMgr>();
176         dataMgr_->AddUserId(Constants::DEFAULT_USERID);
177     }
178 }
179 
InitBundleUserMgr()180 bool BundleMgrService::InitBundleUserMgr()
181 {
182     if (userMgrHost_ == nullptr) {
183         userMgrHost_ = new (std::nothrow) BundleUserMgrHostImpl();
184     }
185 
186     return userMgrHost_ != nullptr;
187 }
188 
InitVerifyManager()189 bool BundleMgrService::InitVerifyManager()
190 {
191     if (verifyManager_ == nullptr) {
192         verifyManager_ = new (std::nothrow) VerifyManagerHostImpl();
193     }
194 
195     return verifyManager_ != nullptr;
196 }
197 
InitExtendResourceManager()198 bool BundleMgrService::InitExtendResourceManager()
199 {
200     if (extendResourceManager_ == nullptr) {
201         extendResourceManager_ = new (std::nothrow) ExtendResourceManagerHostImpl();
202     }
203 
204     return extendResourceManager_ != nullptr;
205 }
206 
InitBundleEventHandler()207 bool BundleMgrService::InitBundleEventHandler()
208 {
209     if (handler_ == nullptr) {
210         handler_ = std::make_shared<BMSEventHandler>();
211     }
212     auto task = [this]() {
213         BundleMemoryGuard memoryGuard;
214         int32_t timerId = XCollieHelper::SetRecoveryTimer(FUN_BMS_START, BMS_START_TIME_OUT_SECONDS);
215         ScopeGuard cancelTimerGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
216         handler_->BmsStartEvent();
217     };
218     ffrt::submit(task);
219     return true;
220 }
221 
InitHidumpHelper()222 void BundleMgrService::InitHidumpHelper()
223 {
224     if (hidumpHelper_ == nullptr) {
225         APP_LOGI("Create hidump helper");
226         hidumpHelper_ = std::make_shared<HidumpHelper>(dataMgr_);
227     }
228 }
229 
InitFreeInstall()230 void BundleMgrService::InitFreeInstall()
231 {
232 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
233     if (agingMgr_ == nullptr) {
234         APP_LOGI("Create aging manager");
235         agingMgr_ = std::make_shared<BundleAgingMgr>();
236         agingMgr_->InitAgingtTimer();
237     }
238     if (bundleDistributedManager_ == nullptr) {
239         APP_LOGI("Create bundleDistributedManager");
240         bundleDistributedManager_ = std::make_shared<BundleDistributedManager>();
241     }
242 #endif
243 }
244 
InitDefaultApp()245 bool BundleMgrService::InitDefaultApp()
246 {
247 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
248     if (defaultAppHostImpl_ == nullptr) {
249         defaultAppHostImpl_ = new (std::nothrow) DefaultAppHostImpl();
250         if (defaultAppHostImpl_ == nullptr) {
251             APP_LOGE("create DefaultAppHostImpl failed");
252             return false;
253         }
254     }
255 #endif
256     return true;
257 }
258 
InitAppControl()259 bool BundleMgrService::InitAppControl()
260 {
261 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
262     if (appControlManagerHostImpl_ == nullptr) {
263         appControlManagerHostImpl_ = new (std::nothrow) AppControlManagerHostImpl();
264         if (appControlManagerHostImpl_ == nullptr) {
265             APP_LOGE("create appControlManagerHostImpl failed");
266             return false;
267         }
268     }
269 #endif
270     return true;
271 }
272 
InitQuickFixManager()273 bool BundleMgrService::InitQuickFixManager()
274 {
275 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
276     if (quickFixManagerHostImpl_ == nullptr) {
277         quickFixManagerHostImpl_ = new (std::nothrow) QuickFixManagerHostImpl();
278         if (quickFixManagerHostImpl_ == nullptr) {
279             APP_LOGE("create QuickFixManagerHostImpl failed");
280             return false;
281         }
282     }
283 #endif
284     return true;
285 }
286 
InitOverlayManager()287 bool BundleMgrService::InitOverlayManager()
288 {
289 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
290     if (overlayManagerHostImpl_ == nullptr) {
291         overlayManagerHostImpl_ = new (std::nothrow) OverlayManagerHostImpl();
292         if (overlayManagerHostImpl_ == nullptr) {
293             APP_LOGE("create OverlayManagerHostImpl failed");
294             return false;
295         }
296     }
297 #endif
298     return true;
299 }
300 
CreateBmsServiceDir()301 void BundleMgrService::CreateBmsServiceDir()
302 {
303     auto ret = InstalldClient::GetInstance()->Mkdir(
304         ServiceConstants::HAP_COPY_PATH, S_IRWXU | S_IXGRP | S_IRGRP | S_IROTH | S_IXOTH,
305         Constants::FOUNDATION_UID, ServiceConstants::BMS_GID);
306     if (!ret) {
307         APP_LOGE("create dir failed");
308     }
309     ret = InstalldClient::GetInstance()->Mkdir(
310         std::string(ServiceConstants::HAP_COPY_PATH) + ServiceConstants::GALLERY_DOWNLOAD_PATH,
311         S_IRWXU | S_IRWXG | S_IXOTH,
312         Constants::FOUNDATION_UID, ServiceConstants::APP_INSTALL_GID);
313     if (!ret) {
314         APP_LOGE("create app_install failed");
315     }
316 }
317 
InitBundleResourceMgr()318 bool BundleMgrService::InitBundleResourceMgr()
319 {
320 #ifdef BUNDLE_FRAMEWORK_BUNDLE_RESOURCE
321     if (bundleResourceHostImpl_ == nullptr) {
322         bundleResourceHostImpl_ = new (std::nothrow) BundleResourceHostImpl();
323         if (bundleResourceHostImpl_ == nullptr) {
324             APP_LOGE("create bundleResourceHostImpl failed");
325             return false;
326         }
327     }
328 #endif
329     return true;
330 }
331 
GetBundleInstaller() const332 sptr<BundleInstallerHost> BundleMgrService::GetBundleInstaller() const
333 {
334     return installer_;
335 }
336 
RegisterDataMgr(std::shared_ptr<BundleDataMgr> dataMgrImpl)337 void BundleMgrService::RegisterDataMgr(std::shared_ptr<BundleDataMgr> dataMgrImpl)
338 {
339     dataMgr_ = dataMgrImpl;
340     if (dataMgr_ != nullptr) {
341         dataMgr_->AddUserId(Constants::DEFAULT_USERID);
342     }
343 }
344 
GetDataMgr() const345 const std::shared_ptr<BundleDataMgr> BundleMgrService::GetDataMgr() const
346 {
347     return dataMgr_;
348 }
349 
350 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
GetAgingMgr() const351 const std::shared_ptr<BundleAgingMgr> BundleMgrService::GetAgingMgr() const
352 {
353     return agingMgr_;
354 }
355 
GetConnectAbility(int32_t userId)356 const std::shared_ptr<BundleConnectAbilityMgr> BundleMgrService::GetConnectAbility(int32_t userId)
357 {
358     int32_t currentUserId = userId;
359     if (currentUserId == Constants::UNSPECIFIED_USERID) {
360         currentUserId = AccountHelper::GetCurrentActiveUserId();
361     }
362     std::lock_guard<std::mutex> connectLock(bundleConnectMutex_);
363     if (connectAbilityMgr_.find(userId) == connectAbilityMgr_.end() ||
364         connectAbilityMgr_[userId] == nullptr) {
365         auto ptr = std::make_shared<BundleConnectAbilityMgr>();
366         connectAbilityMgr_[userId] = ptr;
367     }
368     return connectAbilityMgr_[userId];
369 }
370 
GetBundleDistributedManager() const371 const std::shared_ptr<BundleDistributedManager> BundleMgrService::GetBundleDistributedManager() const
372 {
373     return bundleDistributedManager_;
374 }
375 #endif
376 
SelfClean()377 void BundleMgrService::SelfClean()
378 {
379     if (ready_) {
380         ready_ = false;
381         if (registerToService_) {
382             registerToService_ = false;
383         }
384     }
385 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
386     agingMgr_.reset();
387     {
388         std::lock_guard<std::mutex> connectLock(bundleConnectMutex_);
389         connectAbilityMgr_.clear();
390     }
391     bundleDistributedManager_.reset();
392 #endif
393 }
394 
GetBundleUserMgr() const395 sptr<BundleUserMgrHostImpl> BundleMgrService::GetBundleUserMgr() const
396 {
397     return userMgrHost_;
398 }
399 
GetVerifyManager() const400 sptr<IVerifyManager> BundleMgrService::GetVerifyManager() const
401 {
402     return verifyManager_;
403 }
404 
GetExtendResourceManager() const405 sptr<IExtendResourceManager> BundleMgrService::GetExtendResourceManager() const
406 {
407     return extendResourceManager_;
408 }
409 
GetBmsParam() const410 const std::shared_ptr<BmsParam> BundleMgrService::GetBmsParam() const
411 {
412     return bmsParam_;
413 }
414 
GetPreInstallExceptionMgr() const415 const std::shared_ptr<PreInstallExceptionMgr> BundleMgrService::GetPreInstallExceptionMgr() const
416 {
417     return preInstallExceptionMgr_;
418 }
419 
420 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
GetDefaultAppProxy() const421 sptr<IDefaultApp> BundleMgrService::GetDefaultAppProxy() const
422 {
423     return defaultAppHostImpl_;
424 }
425 #endif
426 
427 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
GetAppControlProxy() const428 sptr<IAppControlMgr> BundleMgrService::GetAppControlProxy() const
429 {
430     return appControlManagerHostImpl_;
431 }
432 #endif
433 
434 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
GetQuickFixManagerProxy() const435 sptr<QuickFixManagerHostImpl> BundleMgrService::GetQuickFixManagerProxy() const
436 {
437     return quickFixManagerHostImpl_;
438 }
439 #endif
440 
441 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
GetOverlayManagerProxy() const442 sptr<IOverlayManager> BundleMgrService::GetOverlayManagerProxy() const
443 {
444     return overlayManagerHostImpl_;
445 }
446 #endif
447 
448 #ifdef BUNDLE_FRAMEWORK_BUNDLE_RESOURCE
GetBundleResourceProxy() const449 sptr<IBundleResource> BundleMgrService::GetBundleResourceProxy() const
450 {
451     return bundleResourceHostImpl_;
452 }
453 #endif
454 
RegisterChargeIdleListener()455 void BundleMgrService::RegisterChargeIdleListener()
456 {
457     APP_LOGI("begin to register charge idle listener");
458     EventFwk::MatchingSkills matchingSkills;
459     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGE_IDLE_MODE_CHANGED);
460     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
461     chargeIdleListener_ = std::make_shared<ChargeIdleListener>(subscribeInfo);
462     (void)EventFwk::CommonEventManager::SubscribeCommonEvent(chargeIdleListener_);
463     APP_LOGI("register charge idle listener done");
464 }
465 
CheckAllUser()466 void BundleMgrService::CheckAllUser()
467 {
468     if (dataMgr_ == nullptr) {
469         return;
470     }
471 
472     APP_LOGI("Check all user start");
473     std::set<int32_t> userIds = dataMgr_->GetAllUser();
474     for (auto userId : userIds) {
475         if (userId == Constants::DEFAULT_USERID) {
476             continue;
477         }
478 
479         bool isExists = false;
480         if (AccountHelper::IsOsAccountExists(userId, isExists) != ERR_OK) {
481             APP_LOGW("Failed query whether user(%{public}d) exists", userId);
482             continue;
483         }
484 
485         if (!isExists) {
486             APP_LOGI("Query user(%{public}d) success but not complete and remove it", userId);
487             userMgrHost_->RemoveUser(userId);
488 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
489             {
490                 std::lock_guard<std::mutex> connectLock(bundleConnectMutex_);
491                 connectAbilityMgr_.erase(userId);
492             }
493 #endif
494         }
495     }
496     APP_LOGI("Check all user end");
497 }
498 
RegisterService()499 void BundleMgrService::RegisterService()
500 {
501     if (!registerToService_) {
502         if (!SystemAbilityHelper::AddSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, host_)) {
503             APP_LOGE("fail to register to system ability manager");
504             return;
505         }
506         APP_LOGI("BundleMgrService register to sam success");
507         registerToService_ = true;
508     }
509 
510     PerfProfile::GetInstance().SetBmsLoadEndTime(GetTickCount());
511     PerfProfile::GetInstance().Dump();
512 }
513 
NotifyBundleScanStatus()514 void BundleMgrService::NotifyBundleScanStatus()
515 {
516     APP_LOGI("PublishCommonEvent for bundle scan finished");
517     AAFwk::Want want;
518     want.SetAction(COMMON_EVENT_BUNDLE_SCAN_FINISHED);
519     EventFwk::CommonEventData commonEventData { want };
520     if (!EventFwk::CommonEventManager::PublishCommonEvent(commonEventData)) {
521         notifyBundleScanStatus = true;
522         APP_LOGE("PublishCommonEvent for bundle scan finished failed");
523     } else {
524         APP_LOGI("PublishCommonEvent for bundle scan finished succeed");
525     }
526 }
527 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)528 void BundleMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
529 {
530     APP_LOGI("OnAddSystemAbility systemAbilityId:%{public}d added", systemAbilityId);
531     if (COMMON_EVENT_SERVICE_ID == systemAbilityId && notifyBundleScanStatus) {
532         NotifyBundleScanStatus();
533     }
534 #ifdef CODE_SIGNATURE_ENABLE
535     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
536         AOTSignDataCacheMgr::GetInstance().RegisterScreenUnlockListener();
537     }
538 #endif
539     if (BUNDLE_BROKER_SERVICE_ABILITY_ID == systemAbilityId) {
540         if (host_ != nullptr) {
541             isBrokerServiceStarted_ = true;
542             host_->SetBrokerServiceStatus(true);
543         }
544     }
545     if (EL5_FILEKEY_SERVICE_ABILITY_ID == systemAbilityId) {
546         int32_t reg = Security::AccessToken::El5FilekeyManagerKit::RegisterCallback(sptr(new El5FilekeyCallback()));
547         APP_LOGI("Register El5FilekeyCallback result: %{public}d", reg);
548     }
549 }
550 
Hidump(const std::vector<std::string> & args,std::string & result) const551 bool BundleMgrService::Hidump(const std::vector<std::string> &args, std::string& result) const
552 {
553     if (hidumpHelper_ && hidumpHelper_->Dump(args, result)) {
554         return true;
555     }
556 
557     APP_LOGD("HidumpHelper failed");
558     return false;
559 }
560 
IsBrokerServiceStarted() const561 bool BundleMgrService::IsBrokerServiceStarted() const
562 {
563     return isBrokerServiceStarted_;
564 }
565 }  // namespace AppExecFwk
566 }  // namespace OHOS
567