• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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_event_handler.h"
17 
18 #include <future>
19 #include <sys/stat.h>
20 
21 #include "accesstoken_kit.h"
22 #include "access_token.h"
23 #include "account_helper.h"
24 #include "aot/aot_handler.h"
25 #include "app_log_wrapper.h"
26 #include "app_provision_info.h"
27 #include "app_provision_info_manager.h"
28 #include "app_privilege_capability.h"
29 #include "app_service_fwk_installer.h"
30 #include "bundle_install_checker.h"
31 #include "bundle_mgr_service.h"
32 #include "bundle_parser.h"
33 #include "bundle_permission_mgr.h"
34 #include "bundle_resource_helper.h"
35 #include "bundle_scanner.h"
36 #include "bundle_util.h"
37 #include "common_event_data.h"
38 #include "common_event_manager.h"
39 #include "common_event_support.h"
40 #include "common_event_subscriber.h"
41 #ifdef CONFIG_POLOCY_ENABLE
42 #include "config_policy_utils.h"
43 #endif
44 #if defined (BUNDLE_FRAMEWORK_SANDBOX_APP) && defined (DLP_PERMISSION_ENABLE)
45 #include "dlp_permission_kit.h"
46 #endif
47 #include "event_report.h"
48 #include "installd_client.h"
49 #include "parameter.h"
50 #include "perf_profile.h"
51 #ifdef WINDOW_ENABLE
52 #include "scene_board_judgement.h"
53 #endif
54 #include "status_receiver_host.h"
55 #include "system_bundle_installer.h"
56 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
57 #include "quick_fix_boot_scanner.h"
58 #endif
59 #include "want.h"
60 #include "user_unlocked_event_subscriber.h"
61 
62 namespace OHOS {
63 namespace AppExecFwk {
64 namespace {
65 const std::string APP_SUFFIX = "/app";
66 const std::string TEMP_PREFIX = "temp_";
67 const std::string MODULE_PREFIX = "module_";
68 const std::string PRE_INSTALL_HSP_PATH = "/shared_bundles/";
69 const std::string BMS_TEST_UPGRADE = "persist.bms.test-upgrade";
70 // this metadata used to indicate those system application update by hotpatch upgrade.
71 const std::string HOT_PATCH_METADATA = "ohos.app.quickfix";
72 const std::string FINGERPRINT = "fingerprint";
73 const std::string UNKNOWN = "";
74 const std::string VALUE_TRUE = "true";
75 const int32_t VERSION_LEN = 64;
76 const std::vector<std::string> FINGERPRINTS = {
77     "const.product.software.version",
78     "const.product.build.type",
79     "const.product.brand",
80     "const.product.name",
81     "const.product.devicetype",
82     "const.product.incremental.version",
83     "const.comp.hl.product_base_version.real"
84 };
85 const std::string HSP_VERSION_PREFIX = "v";
86 const std::string OTA_FLAG = "otaFlag";
87 // pre bundle profile
88 constexpr const char* DEFAULT_PRE_BUNDLE_ROOT_DIR = "/system";
89 constexpr const char* PRODUCT_SUFFIX = "/etc/app";
90 constexpr const char* INSTALL_LIST_CONFIG = "/install_list.json";
91 constexpr const char* APP_SERVICE_FWK_INSTALL_LIST_CONFIG = "/app_service_fwk_install_list.json";
92 constexpr const char* UNINSTALL_LIST_CONFIG = "/uninstall_list.json";
93 constexpr const char* INSTALL_LIST_CAPABILITY_CONFIG = "/install_list_capability.json";
94 constexpr const char* EXTENSION_TYPE_LIST_CONFIG = "/extension_type_config.json";
95 constexpr const char* SHARED_BUNDLES_INSTALL_LIST_CONFIG = "/shared_bundles_install_list.json";
96 constexpr const char* SYSTEM_RESOURCES_APP_PATH = "/system/app/ohos.global.systemres";
97 constexpr const char* QUICK_FIX_APP_PATH = "/data/update/quickfix/app/temp/keepalive";
98 
99 std::set<PreScanInfo> installList_;
100 std::set<PreScanInfo> systemHspList_;
101 std::set<std::string> uninstallList_;
102 std::set<PreBundleConfigInfo> installListCapabilities_;
103 std::set<std::string> extensiontype_;
104 bool hasLoadPreInstallProFile_ = false;
105 
MoveTempPath(const std::vector<std::string> & fromPaths,const std::string & bundleName,std::vector<std::string> & toPaths)106 void MoveTempPath(const std::vector<std::string> &fromPaths,
107     const std::string &bundleName, std::vector<std::string> &toPaths)
108 {
109     std::string tempDir =
110         Constants::HAP_COPY_PATH + Constants::PATH_SEPARATOR + TEMP_PREFIX + bundleName;
111     if (!BundleUtil::CreateDir(tempDir)) {
112         APP_LOGE("create tempdir failed %{public}s", tempDir.c_str());
113         return;
114     }
115 
116     int32_t hapIndex = 0;
117     for (const auto &path : fromPaths) {
118         auto toPath = tempDir + Constants::PATH_SEPARATOR + MODULE_PREFIX
119             + std::to_string(hapIndex) + Constants::INSTALL_FILE_SUFFIX;
120         hapIndex++;
121         if (InstalldClient::GetInstance()->MoveFile(path, toPath) != ERR_OK) {
122             APP_LOGW("move from %{public}s to %{public}s failed", path.c_str(), toPath.c_str());
123             continue;
124         }
125 
126         toPaths.emplace_back(toPath);
127     }
128 }
129 
130 class InnerReceiverImpl : public StatusReceiverHost {
131 public:
132     InnerReceiverImpl() = default;
133     virtual ~InnerReceiverImpl() override = default;
134 
SetBundleName(const std::string & bundleName)135     void SetBundleName(const std::string &bundleName)
136     {
137         bundleName_ = bundleName;
138     }
139 
OnStatusNotify(const int progress)140     virtual void OnStatusNotify(const int progress) override {}
OnFinished(const int32_t resultCode,const std::string & resultMsg)141     virtual void OnFinished(
142         const int32_t resultCode, const std::string &resultMsg) override
143     {
144         if (bundleName_.empty()) {
145             return;
146         }
147 
148         std::string tempDir = Constants::HAP_COPY_PATH
149             + Constants::PATH_SEPARATOR + TEMP_PREFIX + bundleName_;
150         APP_LOGD("delete tempDir %{public}s", tempDir.c_str());
151         BundleUtil::DeleteDir(tempDir);
152     }
153 
154 private:
155     std::string bundleName_;
156 };
157 }
158 
BMSEventHandler()159 BMSEventHandler::BMSEventHandler()
160 {
161     APP_LOGD("instance is created");
162 }
163 
~BMSEventHandler()164 BMSEventHandler::~BMSEventHandler()
165 {
166     APP_LOGD("instance is destroyed");
167 }
168 
BmsStartEvent()169 void BMSEventHandler::BmsStartEvent()
170 {
171     APP_LOGI("BMSEventHandler BmsStartEvent start");
172     BeforeBmsStart();
173     OnBmsStarting();
174     AfterBmsStart();
175     APP_LOGI("BMSEventHandler BmsStartEvent end");
176 }
177 
BeforeBmsStart()178 void BMSEventHandler::BeforeBmsStart()
179 {
180     needNotifyBundleScanStatus_ = false;
181     if (!BundlePermissionMgr::Init()) {
182         APP_LOGW("BundlePermissionMgr::Init failed");
183     }
184 
185     EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_START);
186 }
187 
OnBmsStarting()188 void BMSEventHandler::OnBmsStarting()
189 {
190     APP_LOGI("BMSEventHandler OnBmsStarting start");
191     // Judge whether there is install info in the persistent Db
192     if (LoadInstallInfosFromDb()) {
193         APP_LOGI("OnBmsStarting Load install info from db success");
194         BundleRebootStartEvent();
195         return;
196     }
197 
198     // If the preInstall infos does not exist in preInstall db,
199     // all preInstall directory applications will be reinstalled.
200     if (!LoadAllPreInstallBundleInfos()) {
201         APP_LOGE("OnBmsStarting Load all preInstall bundleInfos failed.");
202         needRebootOta_ = true;
203     }
204 
205     /* Guard against install infos lossed strategy.
206      * 1. Scan user data dir
207      *   1.1. If no data, first boot.
208      *   1.2. If has data, but parse data to InnerBundleUserInfos failed,
209      *        reInstall all app from install dir and preInstall dir
210      *   1.3. If has data and parse data to InnerBundleUserInfos success, goto 2
211      * 2. Scan installDir include common install dir and preInstall dir
212      *    And the parse the hap to InnerBundleInfos
213      * 3. Combine InnerBundleInfos and InnerBundleUserInfos to cache and db
214      * 4. According to needRebootOta determine whether OTA detection is required
215      */
216     ResultCode resultCode = GuardAgainstInstallInfosLossedStrategy();
217     switch (resultCode) {
218         case ResultCode::RECOVER_OK: {
219             APP_LOGI("OnBmsStarting Guard against install infos lossed strategy take effect.");
220             if (needRebootOta_) {
221                 BundleRebootStartEvent();
222             } else {
223                 needNotifyBundleScanStatus_ = true;
224             }
225 
226             break;
227         }
228         case ResultCode::REINSTALL_OK: {
229             APP_LOGI("OnBmsStarting ReInstall all haps.");
230             needNotifyBundleScanStatus_ = true;
231             break;
232         }
233         case ResultCode::NO_INSTALLED_DATA: {
234             // First boot
235             APP_LOGI("OnBmsStarting first boot.");
236             BundleBootStartEvent();
237             break;
238         }
239         default:
240             APP_LOGE("System internal error, install informations missing.");
241             break;
242     }
243 
244     SaveSystemFingerprint();
245     APP_LOGI("BMSEventHandler OnBmsStarting end");
246 }
247 
AfterBmsStart()248 void BMSEventHandler::AfterBmsStart()
249 {
250     APP_LOGI("BMSEventHandler AfterBmsStart start");
251 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
252     DelayedSingleton<QuickFixBootScanner>::GetInstance()->ProcessQuickFixBootUp();
253 #endif
254     DelayedSingleton<BundleMgrService>::GetInstance()->CheckAllUser();
255     SetAllInstallFlag();
256     HandleSceneBoard();
257     DelayedSingleton<BundleMgrService>::GetInstance()->RegisterService();
258     EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_END);
259     ClearCache();
260     if (needNotifyBundleScanStatus_) {
261         DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
262     }
263     ListeningUserUnlocked();
264     RemoveUnreservedSandbox();
265     DelayedSingleton<BundleMgrService>::GetInstance()->RegisterChargeIdleListener();
266     BundleResourceHelper::RegisterCommonEventSubscriber();
267     BundleResourceHelper::RegisterConfigurationObserver();
268     APP_LOGI("BMSEventHandler AfterBmsStart end");
269 }
270 
ClearCache()271 void BMSEventHandler::ClearCache()
272 {
273     hapParseInfoMap_.clear();
274     loadExistData_.clear();
275     hasLoadAllPreInstallBundleInfosFromDb_ = false;
276 }
277 
LoadInstallInfosFromDb()278 bool BMSEventHandler::LoadInstallInfosFromDb()
279 {
280     APP_LOGI("Load install infos from db");
281     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
282     if (dataMgr == nullptr) {
283         APP_LOGE("DataMgr is nullptr");
284         return false;
285     }
286 
287     return dataMgr->LoadDataFromPersistentStorage();
288 }
289 
BundleBootStartEvent()290 void BMSEventHandler::BundleBootStartEvent()
291 {
292     OnBundleBootStart(Constants::DEFAULT_USERID);
293 #ifdef CHECK_ELDIR_ENABLED
294     UpdateOtaFlag(OTAFlag::CHECK_ELDIR);
295 #endif
296     UpdateOtaFlag(OTAFlag::CHECK_LOG_DIR);
297     UpdateOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR);
298     PerfProfile::GetInstance().Dump();
299 }
300 
BundleRebootStartEvent()301 void BMSEventHandler::BundleRebootStartEvent()
302 {
303 #ifdef USE_PRE_BUNDLE_PROFILE
304     if (LoadPreInstallProFile()) {
305         UpdateAllPrivilegeCapability();
306     }
307 #endif
308 
309     if (IsSystemUpgrade()) {
310         OnBundleRebootStart();
311         SaveSystemFingerprint();
312         AOTHandler::GetInstance().HandleOTA();
313     } else {
314         HandlePreInstallException();
315         ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, false);
316     }
317 
318     needNotifyBundleScanStatus_ = true;
319 }
320 
GuardAgainstInstallInfosLossedStrategy()321 ResultCode BMSEventHandler::GuardAgainstInstallInfosLossedStrategy()
322 {
323     APP_LOGI("GuardAgainstInstallInfosLossedStrategy start");
324     // Check user path, and parse userData to InnerBundleUserInfo
325     std::map<std::string, std::vector<InnerBundleUserInfo>> innerBundleUserInfoMaps;
326     ScanResultCode scanResultCode = ScanAndAnalyzeUserDatas(innerBundleUserInfoMaps);
327     if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
328         APP_LOGE("Scan the user data directory failed");
329         return ResultCode::NO_INSTALLED_DATA;
330     }
331 
332     // When data exist, but parse all userinfo fails, reinstall all app.
333     // For example: the AT database is lost or others.
334     if (scanResultCode == ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED) {
335         // Reinstall all app from install dir
336         return ReInstallAllInstallDirApps();
337     }
338 
339     // When data exist and parse all userinfo success,
340     // it can be judged that some bundles has installed.
341     // Check install dir, and parse the hap in install dir to InnerBundleInfo
342     std::map<std::string, std::vector<InnerBundleInfo>> installInfos;
343     ScanAndAnalyzeInstallInfos(installInfos);
344     if (installInfos.empty()) {
345         APP_LOGE("check bundle path failed due to hap lossd or parse failed");
346         return ResultCode::SYSTEM_ERROR;
347     }
348 
349     // Combine InnerBundleInfo and InnerBundleUserInfo
350     if (!CombineBundleInfoAndUserInfo(installInfos, innerBundleUserInfoMaps)) {
351         APP_LOGE("System internal error");
352         return ResultCode::SYSTEM_ERROR;
353     }
354 
355     return ResultCode::RECOVER_OK;
356 }
357 
ScanAndAnalyzeUserDatas(std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)358 ScanResultCode BMSEventHandler::ScanAndAnalyzeUserDatas(
359     std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
360 {
361     ScanResultCode scanResultCode = ScanResultCode::SCAN_NO_DATA;
362     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
363     if (dataMgr == nullptr) {
364         APP_LOGE("dataMgr is null");
365         return scanResultCode;
366     }
367 
368     std::string baseDataDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[0];
369     std::vector<std::string> userIds;
370     if (!ScanDir(baseDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userIds)) {
371         APP_LOGD("Check the base user directory(%{public}s) failed", baseDataDir.c_str());
372         return scanResultCode;
373     }
374 
375     for (const auto &userId : userIds) {
376         int32_t userIdInt = Constants::INVALID_USERID;
377         if (!StrToInt(userId, userIdInt)) {
378             APP_LOGE("UserId(%{public}s) strToInt failed", userId.c_str());
379             continue;
380         }
381 
382         dataMgr->AddUserId(userIdInt);
383         std::vector<std::string> userDataBundleNames;
384         std::string userDataDir = baseDataDir + Constants::PATH_SEPARATOR + userId + Constants::BASE;
385         if (!ScanDir(userDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userDataBundleNames)) {
386             APP_LOGD("Check the user installation directory(%{public}s) failed", userDataDir.c_str());
387             continue;
388         }
389 
390         for (const auto &userDataBundleName : userDataBundleNames) {
391             if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
392                 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED;
393             }
394 
395             if (AnalyzeUserData(userIdInt, userDataDir, userDataBundleName, userMaps)) {
396                 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_SUCCESS;
397             }
398         }
399     }
400 
401     return scanResultCode;
402 }
403 
AnalyzeUserData(int32_t userId,const std::string & userDataDir,const std::string & userDataBundleName,std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)404 bool BMSEventHandler::AnalyzeUserData(
405     int32_t userId, const std::string &userDataDir, const std::string &userDataBundleName,
406     std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
407 {
408     if (userDataDir.empty() || userDataBundleName.empty()) {
409         APP_LOGE("UserDataDir or UserDataBundleName is empty");
410         return false;
411     }
412 
413     std::string userDataBundlePath = userDataDir + userDataBundleName;
414     APP_LOGD("Analyze user data path(%{public}s)", userDataBundlePath.c_str());
415     FileStat fileStat;
416     if (InstalldClient::GetInstance()->GetFileStat(userDataBundlePath, fileStat) != ERR_OK) {
417         APP_LOGE("GetFileStat path(%{public}s) failed", userDataBundlePath.c_str());
418         return false;
419     }
420 
421     // It should be a bundleName dir
422     if (!fileStat.isDir) {
423         APP_LOGE("UserDataBundlePath(%{public}s) is not dir", userDataBundlePath.c_str());
424         return false;
425     }
426 
427     InnerBundleUserInfo innerBundleUserInfo;
428     innerBundleUserInfo.bundleName = userDataBundleName;
429     innerBundleUserInfo.bundleUserInfo.userId = userId;
430     innerBundleUserInfo.uid = fileStat.uid;
431     innerBundleUserInfo.gids.emplace_back(fileStat.gid);
432     innerBundleUserInfo.installTime = fileStat.lastModifyTime;
433     innerBundleUserInfo.updateTime = innerBundleUserInfo.installTime;
434     auto accessTokenIdEx = OHOS::Security::AccessToken::AccessTokenKit::GetHapTokenIDEx(
435         innerBundleUserInfo.bundleUserInfo.userId, userDataBundleName, 0);
436     if (accessTokenIdEx.tokenIdExStruct.tokenID == 0) {
437         APP_LOGE("get tokenId failed.");
438         return false;
439     }
440 
441     innerBundleUserInfo.accessTokenId = accessTokenIdEx.tokenIdExStruct.tokenID;
442     innerBundleUserInfo.accessTokenIdEx = accessTokenIdEx.tokenIDEx;
443     auto userIter = userMaps.find(userDataBundleName);
444     if (userIter == userMaps.end()) {
445         std::vector<InnerBundleUserInfo> innerBundleUserInfos = { innerBundleUserInfo };
446         userMaps.emplace(userDataBundleName, innerBundleUserInfos);
447         return true;
448     }
449 
450     userMaps.at(userDataBundleName).emplace_back(innerBundleUserInfo);
451     return true;
452 }
453 
ReInstallAllInstallDirApps()454 ResultCode BMSEventHandler::ReInstallAllInstallDirApps()
455 {
456     // First, reinstall all preInstall app from preInstall dir
457     std::vector<std::string> preInstallDirs;
458     GetPreInstallDir(preInstallDirs);
459     for (const auto &preInstallDir : preInstallDirs) {
460         std::vector<std::string> filePaths { preInstallDir };
461         bool removable = IsPreInstallRemovable(preInstallDir);
462         if (!OTAInstallSystemBundle(
463             filePaths, Constants::AppType::SYSTEM_APP, removable)) {
464             APP_LOGE("Reinstall bundle(%{public}s) error.", preInstallDir.c_str());
465             SavePreInstallException(preInstallDir);
466             continue;
467         }
468     }
469 
470     auto installer = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
471     if (installer == nullptr) {
472         APP_LOGE("installer is nullptr");
473         return ResultCode::SYSTEM_ERROR;
474     }
475 
476     // Second, reInstall all common install app from install dir
477     std::map<std::string, std::vector<std::string>> hapPathsMap;
478     ScanInstallDir(hapPathsMap);
479     for (const auto &hapPaths : hapPathsMap) {
480         InstallParam installParam;
481         installParam.userId = Constants::ALL_USERID;
482         installParam.installFlag = InstallFlag::REPLACE_EXISTING;
483         sptr<InnerReceiverImpl> innerReceiverImpl(new (std::nothrow) InnerReceiverImpl());
484         innerReceiverImpl->SetBundleName(hapPaths.first);
485         std::vector<std::string> tempHaps;
486         MoveTempPath(hapPaths.second, hapPaths.first, tempHaps);
487         installer->Install(tempHaps, installParam, innerReceiverImpl);
488     }
489 
490     return ResultCode::REINSTALL_OK;
491 }
492 
ScanAndAnalyzeInstallInfos(std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)493 void BMSEventHandler::ScanAndAnalyzeInstallInfos(
494     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
495 {
496     // Scan the installed directory
497     std::map<std::string, std::vector<std::string>> hapPathsMap;
498     ScanInstallDir(hapPathsMap);
499     AnalyzeHaps(false, hapPathsMap, installInfos);
500 
501     // Scan preBundle directory
502     std::vector<std::string> preInstallDirs;
503     GetPreInstallDir(preInstallDirs);
504     AnalyzeHaps(true, preInstallDirs, installInfos);
505 }
506 
ScanInstallDir(std::map<std::string,std::vector<std::string>> & hapPathsMap)507 void BMSEventHandler::ScanInstallDir(
508     std::map<std::string, std::vector<std::string>> &hapPathsMap)
509 {
510     APP_LOGD("Scan the installed directory start");
511     std::vector<std::string> bundleNameList;
512     if (!ScanDir(Constants::BUNDLE_CODE_DIR, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, bundleNameList)) {
513         APP_LOGE("Check the bundle directory(%{public}s) failed", Constants::BUNDLE_CODE_DIR);
514         return;
515     }
516 
517     for (const auto &bundleName : bundleNameList) {
518         std::vector<std::string> hapPaths;
519         auto appCodePath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName;
520         if (!ScanDir(appCodePath, ScanMode::SUB_FILE_FILE, ResultMode::ABSOLUTE_PATH, hapPaths)) {
521             APP_LOGE("Scan the appCodePath(%{public}s) failed", appCodePath.c_str());
522             continue;
523         }
524 
525         if (hapPaths.empty()) {
526             APP_LOGD("The directory(%{public}s) scan result is empty", appCodePath.c_str());
527             continue;
528         }
529 
530         std::vector<std::string> checkHapPaths = CheckHapPaths(hapPaths);
531         hapPathsMap.emplace(bundleName, checkHapPaths);
532     }
533 
534     APP_LOGD("Scan the installed directory end");
535 }
536 
CheckHapPaths(const std::vector<std::string> & hapPaths)537 std::vector<std::string> BMSEventHandler::CheckHapPaths(
538     const std::vector<std::string> &hapPaths)
539 {
540     std::vector<std::string> checkHapPaths;
541     for (const auto &hapPath : hapPaths) {
542         if (!BundleUtil::CheckFileType(hapPath, Constants::INSTALL_FILE_SUFFIX)) {
543             APP_LOGE("Check hapPath(%{public}s) failed", hapPath.c_str());
544             continue;
545         }
546 
547         checkHapPaths.emplace_back(hapPath);
548     }
549 
550     return checkHapPaths;
551 }
552 
GetPreInstallRootDirList(std::vector<std::string> & rootDirList)553 void BMSEventHandler::GetPreInstallRootDirList(std::vector<std::string> &rootDirList)
554 {
555 #ifdef CONFIG_POLOCY_ENABLE
556     auto cfgDirList = GetCfgDirList();
557     if (cfgDirList != nullptr) {
558         for (const auto &cfgDir : cfgDirList->paths) {
559             if (cfgDir == nullptr) {
560                 continue;
561             }
562 
563             APP_LOGI("cfgDir: %{public}s ", cfgDir);
564             rootDirList.emplace_back(cfgDir);
565         }
566 
567         FreeCfgDirList(cfgDirList);
568     }
569 #endif
570     bool ret = std::find(
571         rootDirList.begin(), rootDirList.end(), DEFAULT_PRE_BUNDLE_ROOT_DIR) != rootDirList.end();
572     if (!ret) {
573         rootDirList.emplace_back(DEFAULT_PRE_BUNDLE_ROOT_DIR);
574     }
575 }
576 
ClearPreInstallCache()577 void BMSEventHandler::ClearPreInstallCache()
578 {
579     if (!hasLoadPreInstallProFile_) {
580         return;
581     }
582 
583     installList_.clear();
584     uninstallList_.clear();
585     systemHspList_.clear();
586     installListCapabilities_.clear();
587     extensiontype_.clear();
588     hasLoadPreInstallProFile_ = false;
589 }
590 
LoadPreInstallProFile()591 bool BMSEventHandler::LoadPreInstallProFile()
592 {
593     if (hasLoadPreInstallProFile_) {
594         return !installList_.empty();
595     }
596 
597     std::vector<std::string> rootDirList;
598     GetPreInstallRootDirList(rootDirList);
599     if (rootDirList.empty()) {
600         APP_LOGE("dirList is empty");
601         return false;
602     }
603 
604     for (const auto &rootDir : rootDirList) {
605         ParsePreBundleProFile(rootDir + PRODUCT_SUFFIX);
606     }
607 
608     hasLoadPreInstallProFile_ = true;
609     return !installList_.empty();
610 }
611 
HasPreInstallProfile()612 bool BMSEventHandler::HasPreInstallProfile()
613 {
614     return !installList_.empty();
615 }
616 
ParsePreBundleProFile(const std::string & dir)617 void BMSEventHandler::ParsePreBundleProFile(const std::string &dir)
618 {
619     BundleParser bundleParser;
620     bundleParser.ParsePreInstallConfig(
621         dir + INSTALL_LIST_CONFIG, installList_);
622     bundleParser.ParsePreInstallConfig(
623         dir + APP_SERVICE_FWK_INSTALL_LIST_CONFIG, systemHspList_);
624     bundleParser.ParsePreUnInstallConfig(
625         dir + UNINSTALL_LIST_CONFIG, uninstallList_);
626     bundleParser.ParsePreInstallAbilityConfig(
627         dir + INSTALL_LIST_CAPABILITY_CONFIG, installListCapabilities_);
628     bundleParser.ParseExtTypeConfig(
629         dir + EXTENSION_TYPE_LIST_CONFIG, extensiontype_);
630     bundleParser.ParsePreInstallConfig(
631         dir + SHARED_BUNDLES_INSTALL_LIST_CONFIG, installList_);
632 }
633 
GetPreInstallDir(std::vector<std::string> & bundleDirs)634 void BMSEventHandler::GetPreInstallDir(std::vector<std::string> &bundleDirs)
635 {
636 #ifdef USE_PRE_BUNDLE_PROFILE
637     if (LoadPreInstallProFile()) {
638         GetPreInstallDirFromLoadProFile(bundleDirs);
639         return;
640     }
641 #endif
642 
643     GetPreInstallDirFromScan(bundleDirs);
644 }
645 
GetPreInstallDirFromLoadProFile(std::vector<std::string> & bundleDirs)646 void BMSEventHandler::GetPreInstallDirFromLoadProFile(std::vector<std::string> &bundleDirs)
647 {
648     for (const auto &installInfo : installList_) {
649         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
650             APP_LOGW("bundle(%{public}s) not allowed installed", installInfo.bundleDir.c_str());
651             continue;
652         }
653 
654         bundleDirs.emplace_back(installInfo.bundleDir);
655     }
656 }
657 
GetPreInstallDirFromScan(std::vector<std::string> & bundleDirs)658 void BMSEventHandler::GetPreInstallDirFromScan(std::vector<std::string> &bundleDirs)
659 {
660     std::list<std::string> scanbundleDirs;
661     GetBundleDirFromScan(scanbundleDirs);
662     std::copy(scanbundleDirs.begin(), scanbundleDirs.end(), std::back_inserter(bundleDirs));
663 }
664 
AnalyzeHaps(bool isPreInstallApp,const std::map<std::string,std::vector<std::string>> & hapPathsMap,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)665 void BMSEventHandler::AnalyzeHaps(
666     bool isPreInstallApp,
667     const std::map<std::string, std::vector<std::string>> &hapPathsMap,
668     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
669 {
670     for (const auto &hapPaths : hapPathsMap) {
671         AnalyzeHaps(isPreInstallApp, hapPaths.second, installInfos);
672     }
673 }
674 
AnalyzeHaps(bool isPreInstallApp,const std::vector<std::string> & bundleDirs,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)675 void BMSEventHandler::AnalyzeHaps(
676     bool isPreInstallApp,
677     const std::vector<std::string> &bundleDirs,
678     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
679 {
680     for (const auto &bundleDir : bundleDirs) {
681         std::unordered_map<std::string, InnerBundleInfo> hapInfos;
682         if (!CheckAndParseHapFiles(bundleDir, isPreInstallApp, hapInfos) || hapInfos.empty()) {
683             APP_LOGE("Parse bundleDir(%{public}s) failed", bundleDir.c_str());
684             continue;
685         }
686 
687         CollectInstallInfos(hapInfos, installInfos);
688     }
689 }
690 
CollectInstallInfos(const std::unordered_map<std::string,InnerBundleInfo> & hapInfos,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)691 void BMSEventHandler::CollectInstallInfos(
692     const std::unordered_map<std::string, InnerBundleInfo> &hapInfos,
693     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
694 {
695     for (const auto &hapInfoIter : hapInfos) {
696         auto bundleName = hapInfoIter.second.GetBundleName();
697         if (installInfos.find(bundleName) == installInfos.end()) {
698             std::vector<InnerBundleInfo> innerBundleInfos { hapInfoIter.second };
699             installInfos.emplace(bundleName, innerBundleInfos);
700             continue;
701         }
702 
703         installInfos.at(bundleName).emplace_back(hapInfoIter.second);
704     }
705 }
706 
CombineBundleInfoAndUserInfo(const std::map<std::string,std::vector<InnerBundleInfo>> & installInfos,const std::map<std::string,std::vector<InnerBundleUserInfo>> & userInfoMaps)707 bool BMSEventHandler::CombineBundleInfoAndUserInfo(
708     const std::map<std::string, std::vector<InnerBundleInfo>> &installInfos,
709     const std::map<std::string, std::vector<InnerBundleUserInfo>> &userInfoMaps)
710 {
711     APP_LOGD("Combine code information and user data start");
712     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
713     if (dataMgr == nullptr) {
714         APP_LOGE("dataMgr is null");
715         return false;
716     }
717 
718     if (installInfos.empty() || userInfoMaps.empty()) {
719         APP_LOGE("bundleInfos or userInfos is empty");
720         return false;
721     }
722 
723     for (auto hasInstallInfo : installInfos) {
724         auto bundleName = hasInstallInfo.first;
725         auto userIter = userInfoMaps.find(bundleName);
726         if (userIter == userInfoMaps.end()) {
727             APP_LOGE("User data directory missing with bundle %{public}s ", bundleName.c_str());
728             needRebootOta_ = true;
729             continue;
730         }
731 
732         for (auto &info : hasInstallInfo.second) {
733             SaveInstallInfoToCache(info);
734         }
735 
736         for (const auto &userInfo : userIter->second) {
737             dataMgr->AddInnerBundleUserInfo(bundleName, userInfo);
738         }
739     }
740 
741     // Parsing uid, gids and other user information
742     dataMgr->RestoreUidAndGid();
743     // Load all bundle state data from jsonDb
744     dataMgr->LoadAllBundleStateDataFromJsonDb();
745     APP_LOGD("Combine code information and user data end");
746     return true;
747 }
748 
SaveInstallInfoToCache(InnerBundleInfo & info)749 void BMSEventHandler::SaveInstallInfoToCache(InnerBundleInfo &info)
750 {
751     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
752     if (dataMgr == nullptr) {
753         APP_LOGE("dataMgr is null");
754         return;
755     }
756 
757     auto bundleName = info.GetBundleName();
758     auto appCodePath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName;
759     info.SetAppCodePath(appCodePath);
760 
761     std::string dataBaseDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[1]
762         + Constants::DATABASE + bundleName;
763     info.SetAppDataBaseDir(dataBaseDir);
764 
765     auto moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
766     info.AddModuleSrcDir(moduleDir);
767     info.AddModuleResPath(moduleDir);
768 
769     bool bundleExist = false;
770     InnerBundleInfo dbInfo;
771     {
772         auto &mtx = dataMgr->GetBundleMutex(bundleName);
773         std::lock_guard lock { mtx };
774         bundleExist = dataMgr->GetInnerBundleInfo(bundleName, dbInfo);
775         if (bundleExist) {
776             dataMgr->EnableBundle(bundleName);
777         }
778     }
779 
780     if (!bundleExist) {
781         dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_START);
782         dataMgr->AddInnerBundleInfo(bundleName, info);
783         dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS);
784         return;
785     }
786 
787     auto& hapModuleName = info.GetCurModuleName();
788     std::vector<std::string> dbModuleNames;
789     dbInfo.GetModuleNames(dbModuleNames);
790     auto iter = std::find(dbModuleNames.begin(), dbModuleNames.end(), hapModuleName);
791     if (iter != dbModuleNames.end()) {
792         APP_LOGE("module(%{public}s) has install", hapModuleName.c_str());
793         return;
794     }
795 
796     dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_START);
797     dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_SUCCESS);
798     dataMgr->AddNewModuleInfo(bundleName, info, dbInfo);
799 }
800 
ScanDir(const std::string & dir,ScanMode scanMode,ResultMode resultMode,std::vector<std::string> & resultList)801 bool BMSEventHandler::ScanDir(
802     const std::string& dir, ScanMode scanMode, ResultMode resultMode, std::vector<std::string> &resultList)
803 {
804     APP_LOGD("Scan the directory(%{public}s) start", dir.c_str());
805     ErrCode result = InstalldClient::GetInstance()->ScanDir(dir, scanMode, resultMode, resultList);
806     if (result != ERR_OK) {
807         APP_LOGE("Scan the directory(%{public}s) failed", dir.c_str());
808         return false;
809     }
810 
811     return true;
812 }
813 
OnBundleBootStart(int32_t userId)814 void BMSEventHandler::OnBundleBootStart(int32_t userId)
815 {
816 #ifdef USE_PRE_BUNDLE_PROFILE
817     if (LoadPreInstallProFile()) {
818         APP_LOGI("Process boot bundle install from pre bundle proFile for userId:%{public}d", userId);
819         InnerProcessBootSystemHspInstall();
820         InnerProcessBootPreBundleProFileInstall(userId);
821         ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, true);
822         return;
823     }
824 #else
825     ProcessBootBundleInstallFromScan(userId);
826 #endif
827 }
828 
ProcessBootBundleInstallFromScan(int32_t userId)829 void BMSEventHandler::ProcessBootBundleInstallFromScan(int32_t userId)
830 {
831     APP_LOGD("Process boot bundle install from scan");
832     std::list<std::string> bundleDirs;
833     GetBundleDirFromScan(bundleDirs);
834     for (auto item : bundleDirs) {
835         ProcessSystemBundleInstall(item, Constants::AppType::SYSTEM_APP, userId);
836     }
837 }
838 
GetBundleDirFromScan(std::list<std::string> & bundleDirs)839 void BMSEventHandler::GetBundleDirFromScan(std::list<std::string> &bundleDirs)
840 {
841     std::vector<std::string> rootDirList;
842     GetPreInstallRootDirList(rootDirList);
843     if (rootDirList.empty()) {
844         APP_LOGE("rootDirList is empty");
845         return;
846     }
847 
848     for (const auto &rootDir : rootDirList) {
849         ProcessScanDir(rootDir + APP_SUFFIX, bundleDirs);
850     }
851 
852     auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), SYSTEM_RESOURCES_APP_PATH);
853     if (iter != bundleDirs.end()) {
854         bundleDirs.erase(iter);
855         bundleDirs.insert(bundleDirs.begin(), SYSTEM_RESOURCES_APP_PATH);
856     }
857 }
858 
ProcessScanDir(const std::string & dir,std::list<std::string> & bundleDirs)859 void BMSEventHandler::ProcessScanDir(const std::string &dir, std::list<std::string> &bundleDirs)
860 {
861     BundleScanner scanner;
862     std::list<std::string> bundleList = scanner.Scan(dir);
863     for (auto item : bundleList) {
864         auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), item);
865         if (iter == bundleDirs.end()) {
866             bundleDirs.push_back(item);
867         }
868     }
869 }
870 
InnerProcessBootSystemHspInstall()871 void BMSEventHandler::InnerProcessBootSystemHspInstall()
872 {
873     for (const auto &systemHspPath : systemHspList_) {
874         ProcessSystemHspInstall(systemHspPath);
875     }
876 }
877 
ProcessSystemHspInstall(const PreScanInfo & preScanInfo)878 void BMSEventHandler::ProcessSystemHspInstall(const PreScanInfo &preScanInfo)
879 {
880     APP_LOGI("Install systemHsp by bundleDir(%{public}s)", preScanInfo.bundleDir.c_str());
881     InstallParam installParam;
882     installParam.isPreInstallApp = true;
883     installParam.removable = false;
884     AppServiceFwkInstaller installer;
885     ErrCode ret = installer.Install({preScanInfo.bundleDir}, installParam);
886     if (ret != ERR_OK) {
887         APP_LOGW("Install systemHsp %{public}s error", preScanInfo.bundleDir.c_str());
888     }
889 }
890 
InnerProcessBootPreBundleProFileInstall(int32_t userId)891 void BMSEventHandler::InnerProcessBootPreBundleProFileInstall(int32_t userId)
892 {
893     // Sort in descending order of install priority
894     std::map<int32_t, std::vector<PreScanInfo>, std::greater<int32_t>> taskMap;
895     std::list<std::string> hspDirs;
896     std::list<PreScanInfo> normalSystemApps;
897     for (const auto &installInfo : installList_) {
898         APP_LOGD("Inner process boot preBundle proFile install %{public}s", installInfo.ToString().c_str());
899         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
900             APP_LOGI("bundle(%{public}s) not allowed installed when boot", installInfo.bundleDir.c_str());
901             continue;
902         }
903         if (installInfo.bundleDir.find(PRE_INSTALL_HSP_PATH) != std::string::npos) {
904             hspDirs.emplace_back(installInfo.bundleDir);
905         } else {
906             taskMap[installInfo.priority].emplace_back(installInfo);
907         }
908     }
909 
910     for (const auto &hspDir : hspDirs) {
911         ProcessSystemSharedBundleInstall(hspDir, Constants::AppType::SYSTEM_APP);
912     }
913 
914     if (taskMap.size() <= 0) {
915         APP_LOGW("taskMap is empty.");
916         return;
917     }
918     AddTasks(taskMap, userId);
919 }
920 
AddTasks(const std::map<int32_t,std::vector<PreScanInfo>,std::greater<int32_t>> & taskMap,int32_t userId)921 void BMSEventHandler::AddTasks(
922     const std::map<int32_t, std::vector<PreScanInfo>, std::greater<int32_t>> &taskMap, int32_t userId)
923 {
924     for (const auto &tasks : taskMap) {
925         AddTaskParallel(tasks.first, tasks.second, userId);
926     }
927 }
928 
AddTaskParallel(int32_t taskPriority,const std::vector<PreScanInfo> & tasks,int32_t userId)929 void BMSEventHandler::AddTaskParallel(
930     int32_t taskPriority, const std::vector<PreScanInfo> &tasks, int32_t userId)
931 {
932     int32_t taskTotalNum = static_cast<int32_t>(tasks.size());
933     if (taskTotalNum <= 0) {
934         APP_LOGE("The number of tasks is empty.");
935         return;
936     }
937 
938     auto bundleMgrService = DelayedSingleton<BundleMgrService>::GetInstance();
939     if (bundleMgrService == nullptr) {
940         APP_LOGE("bundleMgrService is nullptr");
941         return;
942     }
943 
944     sptr<BundleInstallerHost> installerHost = bundleMgrService->GetBundleInstaller();
945     if (installerHost == nullptr) {
946         APP_LOGE("installerHost is nullptr");
947         return;
948     }
949 
950     size_t threadsNum = installerHost->GetThreadsNum();
951     APP_LOGI("priority: %{public}d, tasks: %{public}zu, userId: %{public}d, threadsNum: %{public}zu.",
952         taskPriority, tasks.size(), userId, threadsNum);
953     std::atomic_uint taskEndNum = 0;
954     std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
955     for (const auto &installInfo : tasks) {
956         if (installerHost->GetCurTaskNum() >= threadsNum) {
957             BMSEventHandler::ProcessSystemBundleInstall(installInfo, Constants::AppType::SYSTEM_APP, userId);
958             taskEndNum++;
959             continue;
960         }
961 
962         auto task = [installInfo, userId, taskTotalNum, &taskEndNum, &bundlePromise]() {
963             BMSEventHandler::ProcessSystemBundleInstall(installInfo, Constants::AppType::SYSTEM_APP, userId);
964             taskEndNum++;
965             if (bundlePromise && static_cast<int32_t>(taskEndNum) >= taskTotalNum) {
966                 bundlePromise->NotifyAllTasksExecuteFinished();
967                 APP_LOGI("All tasks has executed and notify promise in priority(%{public}d).",
968                     installInfo.priority);
969             }
970         };
971 
972         installerHost->AddTask(task, "BootStartInstall : " + installInfo.bundleDir);
973     }
974 
975     if (static_cast<int32_t>(taskEndNum) < taskTotalNum) {
976         bundlePromise->WaitForAllTasksExecute();
977         APP_LOGI("Wait for all tasks execute in priority(%{public}d).", taskPriority);
978     }
979 }
980 
ProcessSystemBundleInstall(const PreScanInfo & preScanInfo,Constants::AppType appType,int32_t userId)981 void BMSEventHandler::ProcessSystemBundleInstall(
982     const PreScanInfo &preScanInfo, Constants::AppType appType, int32_t userId)
983 {
984     APP_LOGD("Process system bundle install by bundleDir(%{public}s)", preScanInfo.bundleDir.c_str());
985     InstallParam installParam;
986     installParam.userId = userId;
987     installParam.isPreInstallApp = true;
988     installParam.noSkipsKill = false;
989     installParam.needSendEvent = false;
990     installParam.removable = preScanInfo.removable;
991     installParam.needSavePreInstallInfo = true;
992     installParam.copyHapToInstallPath = false;
993     SystemBundleInstaller installer;
994     ErrCode ret = installer.InstallSystemBundle(preScanInfo.bundleDir, installParam, appType);
995     if (ret != ERR_OK && ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON) {
996         APP_LOGW("Install System app:%{public}s error", preScanInfo.bundleDir.c_str());
997         SavePreInstallException(preScanInfo.bundleDir);
998     }
999 }
1000 
ProcessSystemBundleInstall(const std::string & bundleDir,Constants::AppType appType,int32_t userId)1001 void BMSEventHandler::ProcessSystemBundleInstall(
1002     const std::string &bundleDir, Constants::AppType appType, int32_t userId)
1003 {
1004     APP_LOGI("Process system bundle install by bundleDir(%{public}s)", bundleDir.c_str());
1005     InstallParam installParam;
1006     installParam.userId = userId;
1007     installParam.isPreInstallApp = true;
1008     installParam.noSkipsKill = false;
1009     installParam.needSendEvent = false;
1010     installParam.removable = false;
1011     installParam.needSavePreInstallInfo = true;
1012     installParam.copyHapToInstallPath = false;
1013     SystemBundleInstaller installer;
1014     ErrCode ret = installer.InstallSystemBundle(bundleDir, installParam, appType);
1015     if (ret != ERR_OK && ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON) {
1016         APP_LOGW("Install System app:%{public}s error", bundleDir.c_str());
1017         SavePreInstallException(bundleDir);
1018     }
1019 }
1020 
ProcessSystemSharedBundleInstall(const std::string & sharedBundlePath,Constants::AppType appType)1021 void BMSEventHandler::ProcessSystemSharedBundleInstall(const std::string &sharedBundlePath, Constants::AppType appType)
1022 {
1023     APP_LOGI("Process system shared bundle by sharedBundlePath(%{public}s)", sharedBundlePath.c_str());
1024     InstallParam installParam;
1025     installParam.isPreInstallApp = true;
1026     installParam.noSkipsKill = false;
1027     installParam.needSendEvent = false;
1028     installParam.removable = false;
1029     installParam.needSavePreInstallInfo = true;
1030     installParam.sharedBundleDirPaths = {sharedBundlePath};
1031     SystemBundleInstaller installer;
1032     if (!installer.InstallSystemSharedBundle(installParam, false, appType)) {
1033         APP_LOGW("install system shared bundle: %{public}s error", sharedBundlePath.c_str());
1034     }
1035 }
1036 
SetAllInstallFlag() const1037 void BMSEventHandler::SetAllInstallFlag() const
1038 {
1039     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1040     if (dataMgr == nullptr) {
1041         APP_LOGE("DataMgr is nullptr");
1042         return;
1043     }
1044 
1045     dataMgr->SetInitialUserFlag(true);
1046 }
1047 
OnBundleRebootStart()1048 void BMSEventHandler::OnBundleRebootStart()
1049 {
1050     ProcessRebootBundle();
1051 }
1052 
ProcessRebootBundle()1053 void BMSEventHandler::ProcessRebootBundle()
1054 {
1055     APP_LOGI("BMSEventHandler Process reboot bundle start");
1056     ProcessRebootDeleteAotPath();
1057     LoadAllPreInstallBundleInfos();
1058     ProcessRebootBundleInstall();
1059     ProcessRebootBundleUninstall();
1060     ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, true);
1061     ProcessBundleResourceInfo();
1062 #ifdef CHECK_ELDIR_ENABLED
1063     ProcessCheckAppDataDir();
1064 #endif
1065     ProcessCheckAppLogDir();
1066     ProcessCheckAppFileManagerDir();
1067 }
1068 
ProcessRebootDeleteAotPath()1069 void BMSEventHandler::ProcessRebootDeleteAotPath()
1070 {
1071     std::string removeAotPath = Constants::ARK_CACHE_PATH;
1072     removeAotPath.append("*");
1073     if (InstalldClient::GetInstance()->RemoveDir(removeAotPath) != ERR_OK) {
1074         APP_LOGE("delete aot dir %{public}s failed!", removeAotPath.c_str());
1075         return;
1076     }
1077 }
1078 
CheckOtaFlag(OTAFlag flag,bool & result)1079 bool BMSEventHandler::CheckOtaFlag(OTAFlag flag, bool &result)
1080 {
1081     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1082     if (bmsPara == nullptr) {
1083         APP_LOGE("bmsPara is nullptr");
1084         return false;
1085     }
1086 
1087     std::string val;
1088     if (!bmsPara->GetBmsParam(OTA_FLAG, val)) {
1089         APP_LOGI("GetBmsParam OTA_FLAG failed.");
1090         return false;
1091     }
1092 
1093     int32_t valInt = 0;
1094     if (!StrToInt(val, valInt)) {
1095         APP_LOGE("val(%{public}s) strToInt failed", val.c_str());
1096         return false;
1097     }
1098 
1099     result = static_cast<uint32_t>(flag) & static_cast<uint32_t>(valInt);
1100     return true;
1101 }
1102 
UpdateOtaFlag(OTAFlag flag)1103 bool BMSEventHandler::UpdateOtaFlag(OTAFlag flag)
1104 {
1105     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1106     if (bmsPara == nullptr) {
1107         APP_LOGE("bmsPara is nullptr");
1108         return false;
1109     }
1110 
1111     std::string val;
1112     if (!bmsPara->GetBmsParam(OTA_FLAG, val)) {
1113         APP_LOGI("GetBmsParam OTA_FLAG failed.");
1114         return bmsPara->SaveBmsParam(OTA_FLAG, std::to_string(flag));
1115     }
1116 
1117     int32_t valInt = 0;
1118     if (!StrToInt(val, valInt)) {
1119         APP_LOGE("val(%{public}s) strToInt failed", val.c_str());
1120         return bmsPara->SaveBmsParam(OTA_FLAG, std::to_string(flag));
1121     }
1122 
1123     return bmsPara->SaveBmsParam(
1124         OTA_FLAG, std::to_string(static_cast<uint32_t>(flag) | static_cast<uint32_t>(valInt)));
1125 }
1126 
ProcessCheckAppDataDir()1127 void BMSEventHandler::ProcessCheckAppDataDir()
1128 {
1129     bool checkElDir = false;
1130     CheckOtaFlag(OTAFlag::CHECK_ELDIR, checkElDir);
1131     if (checkElDir) {
1132         APP_LOGI("Not need to check data dir due to has checked.");
1133         return;
1134     }
1135 
1136     APP_LOGI("Need to check data dir.");
1137     InnerProcessCheckAppDataDir();
1138     UpdateOtaFlag(OTAFlag::CHECK_ELDIR);
1139 }
1140 
InnerProcessCheckAppDataDir()1141 void BMSEventHandler::InnerProcessCheckAppDataDir()
1142 {
1143     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1144     if (dataMgr == nullptr) {
1145         APP_LOGE("DataMgr is nullptr");
1146         return;
1147     }
1148 
1149     std::set<int32_t> userIds = dataMgr->GetAllUser();
1150     for (const auto &userId : userIds) {
1151         std::vector<BundleInfo> bundleInfos;
1152         if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, userId)) {
1153             APP_LOGW("UpdateAppDataDir GetAllBundleInfos failed");
1154             continue;
1155         }
1156 
1157         UpdateAppDataMgr::ProcessUpdateAppDataDir(
1158             userId, bundleInfos, Constants::DIR_EL3);
1159         UpdateAppDataMgr::ProcessUpdateAppDataDir(
1160             userId, bundleInfos, Constants::DIR_EL4);
1161     }
1162 }
1163 
ProcessCheckAppLogDir()1164 void BMSEventHandler::ProcessCheckAppLogDir()
1165 {
1166     bool checkLogDir = false;
1167     CheckOtaFlag(OTAFlag::CHECK_LOG_DIR, checkLogDir);
1168     if (checkLogDir) {
1169         APP_LOGI("Not need to check log dir due to has checked.");
1170         return;
1171     }
1172     APP_LOGI("Need to check log dir.");
1173     InnerProcessCheckAppLogDir();
1174     UpdateOtaFlag(OTAFlag::CHECK_LOG_DIR);
1175 }
1176 
InnerProcessCheckAppLogDir()1177 void BMSEventHandler::InnerProcessCheckAppLogDir()
1178 {
1179     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1180     if (dataMgr == nullptr) {
1181         APP_LOGE("DataMgr is nullptr");
1182         return;
1183     }
1184     std::vector<BundleInfo> bundleInfos;
1185     if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, Constants::DEFAULT_USERID)) {
1186         APP_LOGE("GetAllBundleInfos failed");
1187         return;
1188     }
1189     UpdateAppDataMgr::ProcessUpdateAppLogDir(bundleInfos, Constants::DEFAULT_USERID);
1190 }
1191 
ProcessCheckAppFileManagerDir()1192 void BMSEventHandler::ProcessCheckAppFileManagerDir()
1193 {
1194     bool checkDir = false;
1195     CheckOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR, checkDir);
1196     if (checkDir) {
1197         APP_LOGI("Not need to check file manager dir due to has checked.");
1198         return;
1199     }
1200     APP_LOGI("Need to check file manager dir.");
1201     InnerProcessCheckAppFileManagerDir();
1202     UpdateOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR);
1203 }
1204 
InnerProcessCheckAppFileManagerDir()1205 void BMSEventHandler::InnerProcessCheckAppFileManagerDir()
1206 {
1207     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1208     if (dataMgr == nullptr) {
1209         APP_LOGE("DataMgr is nullptr");
1210         return;
1211     }
1212     std::vector<BundleInfo> bundleInfos;
1213     if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, Constants::DEFAULT_USERID)) {
1214         APP_LOGE("GetAllBundleInfos failed");
1215         return;
1216     }
1217     UpdateAppDataMgr::ProcessFileManagerDir(bundleInfos, Constants::DEFAULT_USERID);
1218 }
1219 
LoadAllPreInstallBundleInfos()1220 bool BMSEventHandler::LoadAllPreInstallBundleInfos()
1221 {
1222     if (hasLoadAllPreInstallBundleInfosFromDb_) {
1223         APP_LOGI("Has load all preInstall bundleInfos from db");
1224         return true;
1225     }
1226 
1227     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1228     if (dataMgr == nullptr) {
1229         APP_LOGE("DataMgr is nullptr");
1230         return false;
1231     }
1232 
1233     std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
1234     for (auto &iter : preInstallBundleInfos) {
1235         APP_LOGW("load preInstallBundleInfos: %{public}s ", iter.GetBundleName().c_str());
1236         loadExistData_.emplace(iter.GetBundleName(), iter);
1237     }
1238 
1239     hasLoadAllPreInstallBundleInfosFromDb_ = true;
1240     return !preInstallBundleInfos.empty();
1241 }
1242 
ProcessRebootBundleInstall()1243 void BMSEventHandler::ProcessRebootBundleInstall()
1244 {
1245     APP_LOGI("BMSEventHandler Process reboot bundle install start");
1246 #ifdef USE_PRE_BUNDLE_PROFILE
1247     if (LoadPreInstallProFile()) {
1248         ProcessReBootPreBundleProFileInstall();
1249         return;
1250     }
1251 #else
1252     ProcessRebootBundleInstallFromScan();
1253 #endif
1254 }
1255 
ProcessReBootPreBundleProFileInstall()1256 void BMSEventHandler::ProcessReBootPreBundleProFileInstall()
1257 {
1258     std::list<std::string> bundleDirs;
1259     std::list<std::string> sharedBundleDirs;
1260     for (const auto &installInfo : installList_) {
1261         APP_LOGI("Process reboot preBundle proFile install %{public}s", installInfo.ToString().c_str());
1262         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
1263             APP_LOGW("bundle(%{public}s) not allowed installed when reboot", installInfo.bundleDir.c_str());
1264             continue;
1265         }
1266 
1267         if (installInfo.bundleDir.find(PRE_INSTALL_HSP_PATH) != std::string::npos) {
1268             APP_LOGI("found shared bundle path: %{public}s", installInfo.bundleDir.c_str());
1269             sharedBundleDirs.emplace_back(installInfo.bundleDir);
1270         } else {
1271             bundleDirs.emplace_back(installInfo.bundleDir);
1272         }
1273     }
1274 
1275     std::list<std::string> systemHspDirs;
1276     for (const auto &systemHspScanInfo : systemHspList_) {
1277         systemHspDirs.emplace_back(systemHspScanInfo.bundleDir);
1278     }
1279 
1280     InnerProcessRebootSystemHspInstall(systemHspDirs);
1281     InnerProcessRebootSharedBundleInstall(sharedBundleDirs, Constants::AppType::SYSTEM_APP);
1282     InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
1283     InnerProcessStockBundleProvisionInfo();
1284 }
1285 
ProcessRebootBundleInstallFromScan()1286 void BMSEventHandler::ProcessRebootBundleInstallFromScan()
1287 {
1288     APP_LOGD("Process reboot bundle install from scan");
1289     std::list<std::string> bundleDirs;
1290     GetBundleDirFromScan(bundleDirs);
1291     InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
1292     InnerProcessStockBundleProvisionInfo();
1293 }
1294 
InnerProcessRebootBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)1295 void BMSEventHandler::InnerProcessRebootBundleInstall(
1296     const std::list<std::string> &scanPathList, Constants::AppType appType)
1297 {
1298     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1299     if (dataMgr == nullptr) {
1300         APP_LOGE("DataMgr is nullptr");
1301         return;
1302     }
1303 
1304     for (auto &scanPathIter : scanPathList) {
1305         APP_LOGI("InnerProcessRebootBundleInstall reboot scan bundle path: %{public}s ", scanPathIter.c_str());
1306         bool removable = IsPreInstallRemovable(scanPathIter);
1307         std::unordered_map<std::string, InnerBundleInfo> infos;
1308         if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
1309             APP_LOGE("obtain bundleinfo failed : %{public}s ", scanPathIter.c_str());
1310             SavePreInstallException(scanPathIter);
1311             continue;
1312         }
1313 
1314         auto bundleName = infos.begin()->second.GetBundleName();
1315         auto hapVersionCode = infos.begin()->second.GetVersionCode();
1316         AddParseInfosToMap(bundleName, infos);
1317         auto mapIter = loadExistData_.find(bundleName);
1318         if (mapIter == loadExistData_.end()) {
1319             APP_LOGI("OTA Install new bundle(%{public}s) by path(%{public}s).",
1320                 bundleName.c_str(), scanPathIter.c_str());
1321             std::vector<std::string> filePaths { scanPathIter };
1322             if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1323                 APP_LOGE("OTA Install new bundle(%{public}s) error.", bundleName.c_str());
1324                 SavePreInstallException(scanPathIter);
1325             }
1326 
1327             continue;
1328         }
1329 
1330         APP_LOGI("OTA process bundle(%{public}s) by path(%{public}s).",
1331             bundleName.c_str(), scanPathIter.c_str());
1332         BundleInfo hasInstalledInfo;
1333         auto hasBundleInstalled = dataMgr->GetBundleInfo(
1334             bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
1335         if (!hasBundleInstalled && mapIter->second.GetIsUninstalled()) {
1336             APP_LOGW("app(%{public}s) has been uninstalled and do not OTA install.",
1337                 bundleName.c_str());
1338             if (!removable) {
1339                 std::vector<std::string> filePaths { scanPathIter };
1340                 if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1341                     APP_LOGE("OTA Install prefab bundle(%{public}s) error.", bundleName.c_str());
1342                     SavePreInstallException(scanPathIter);
1343                 }
1344             }
1345             continue;
1346         }
1347 
1348         if (HotPatchAppProcessing(bundleName)) {
1349             APP_LOGI("OTA Install prefab bundle(%{public}s) by path(%{public}s) for hotPath upgrade.",
1350                 bundleName.c_str(), scanPathIter.c_str());
1351             std::vector<std::string> filePaths { scanPathIter };
1352             if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1353                 APP_LOGE("OTA Install prefab bundle(%{public}s) error.", bundleName.c_str());
1354                 SavePreInstallException(scanPathIter);
1355             }
1356 
1357             continue;
1358         }
1359 
1360         std::vector<std::string> filePaths;
1361         bool updateSelinuxLabel = false;
1362         bool updateBundle = false;
1363         for (auto item : infos) {
1364             auto parserModuleNames = item.second.GetModuleNameVec();
1365             if (parserModuleNames.empty()) {
1366                 APP_LOGE("module is empty when parser path(%{public}s).", item.first.c_str());
1367                 continue;
1368             }
1369             // Generally, when the versionCode of Hap is greater than the installed versionCode,
1370             // Except for the uninstalled app, they can be installed or upgraded directly by OTA.
1371             if (hasInstalledInfo.versionCode < hapVersionCode) {
1372                 APP_LOGI("OTA update module(%{public}s) by path(%{public}s)",
1373                     parserModuleNames[0].c_str(), item.first.c_str());
1374                 updateBundle = true;
1375                 break;
1376             }
1377 
1378             // When the accessTokenIdEx is equal to 0, the old application needs to be updated.
1379             if (hasInstalledInfo.applicationInfo.accessTokenIdEx == 0) {
1380                 APP_LOGI("OTA update module(%{public}s) by path(%{public}s), accessTokenIdEx is equal to 0",
1381                     parserModuleNames[0].c_str(), item.first.c_str());
1382                 updateBundle = true;
1383                 break;
1384             }
1385 
1386             // The versionCode of Hap is equal to the installed versionCode.
1387             // You can only install new modules by OTA
1388             if (hasInstalledInfo.versionCode == hapVersionCode) {
1389                 // update pre install app data dir selinux label
1390                 if (!updateSelinuxLabel) {
1391                     UpdateAppDataSelinuxLabel(bundleName, hasInstalledInfo.applicationInfo.appPrivilegeLevel,
1392                         hasInstalledInfo.isPreInstallApp,
1393                         hasInstalledInfo.applicationInfo.debug);
1394                     updateSelinuxLabel = true;
1395                 }
1396                 // Used to judge whether the module has been installed.
1397                 bool hasModuleInstalled = std::find(
1398                     hasInstalledInfo.hapModuleNames.begin(), hasInstalledInfo.hapModuleNames.end(),
1399                     parserModuleNames[0]) != hasInstalledInfo.hapModuleNames.end();
1400                 if (hasModuleInstalled) {
1401                     if (UpdateModuleByHash(hasInstalledInfo, item.second)) {
1402                         updateBundle = true;
1403                         break;
1404                     }
1405                     APP_LOGD("module(%{public}s) has been installed and versionCode is same.",
1406                         parserModuleNames[0].c_str());
1407                     continue;
1408                 }
1409 
1410                 APP_LOGI("OTA install module(%{public}s) by path(%{public}s)",
1411                     parserModuleNames[0].c_str(), item.first.c_str());
1412                 updateBundle = true;
1413                 break;
1414             }
1415 
1416             if (hasInstalledInfo.versionCode > hapVersionCode) {
1417                 APP_LOGE("bundleName: %{public}s update failed, versionCode(%{public}d) is lower than "
1418                     "installed bundle(%{public}d)", bundleName.c_str(), hapVersionCode, hasInstalledInfo.versionCode);
1419                 SendBundleUpdateFailedEvent(hasInstalledInfo);
1420                 break;
1421             }
1422         }
1423 
1424         if (updateBundle) {
1425             filePaths.clear();
1426             filePaths.emplace_back(scanPathIter);
1427         }
1428 
1429         if (filePaths.empty()) {
1430 #ifdef USE_PRE_BUNDLE_PROFILE
1431             UpdateRemovable(bundleName, removable);
1432 #endif
1433             continue;
1434         }
1435 
1436         if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1437             APP_LOGE("OTA bundle(%{public}s) failed", bundleName.c_str());
1438             SavePreInstallException(scanPathIter);
1439 #ifdef USE_PRE_BUNDLE_PROFILE
1440             UpdateRemovable(bundleName, removable);
1441 #endif
1442         }
1443     }
1444 }
1445 
UpdateModuleByHash(const BundleInfo & oldBundleInfo,const InnerBundleInfo & newInfo) const1446 bool BMSEventHandler::UpdateModuleByHash(const BundleInfo &oldBundleInfo, const InnerBundleInfo &newInfo) const
1447 {
1448     auto moduleName = newInfo.GetModuleNameVec().at(0);
1449     std::string existModuleHash;
1450     for (auto hapInfo : oldBundleInfo.hapModuleInfos) {
1451         if (hapInfo.package == moduleName) {
1452             existModuleHash = hapInfo.buildHash;
1453         }
1454     }
1455     std::string curModuleHash;
1456     if (!newInfo.GetModuleBuildHash(moduleName, curModuleHash)) {
1457         APP_LOGD("module(%{public}s) is not existed.", moduleName.c_str());
1458         return false;
1459     }
1460     if (existModuleHash != curModuleHash) {
1461         APP_LOGD("module(%{public}s) buildHash changed, so update corresponding hap or hsp.", moduleName.c_str());
1462         return true;
1463     }
1464     return false;
1465 }
1466 
InnerProcessRebootSharedBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)1467 void BMSEventHandler::InnerProcessRebootSharedBundleInstall(
1468     const std::list<std::string> &scanPathList, Constants::AppType appType)
1469 {
1470     APP_LOGI("InnerProcessRebootSharedBundleInstall");
1471     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1472     if (dataMgr == nullptr) {
1473         APP_LOGE("DataMgr is nullptr");
1474         return;
1475     }
1476     for (const auto &scanPath : scanPathList) {
1477         bool removable = IsPreInstallRemovable(scanPath);
1478         std::unordered_map<std::string, InnerBundleInfo> infos;
1479         if (!ParseHapFiles(scanPath, infos) || infos.empty()) {
1480             APP_LOGE("obtain bundleinfo failed : %{public}s ", scanPath.c_str());
1481             continue;
1482         }
1483 
1484         auto bundleName = infos.begin()->second.GetBundleName();
1485         auto versionCode = infos.begin()->second.GetVersionCode();
1486         AddParseInfosToMap(bundleName, infos);
1487         auto mapIter = loadExistData_.find(bundleName);
1488         if (mapIter == loadExistData_.end()) {
1489             APP_LOGI("OTA Install new shared bundle(%{public}s) by path(%{public}s).",
1490                 bundleName.c_str(), scanPath.c_str());
1491             if (!OTAInstallSystemSharedBundle({scanPath}, appType, removable)) {
1492                 APP_LOGE("OTA Install new shared bundle(%{public}s) error.", bundleName.c_str());
1493             }
1494             continue;
1495         }
1496 
1497         InnerBundleInfo oldBundleInfo;
1498         bool hasInstalled = dataMgr->FetchInnerBundleInfo(bundleName, oldBundleInfo);
1499         if (!hasInstalled) {
1500             APP_LOGW("app(%{public}s) has been uninstalled and do not OTA install.", bundleName.c_str());
1501             continue;
1502         }
1503 
1504         if (oldBundleInfo.GetVersionCode() > versionCode) {
1505             APP_LOGD("the installed version is up-to-date");
1506             continue;
1507         }
1508         if (oldBundleInfo.GetVersionCode() == versionCode) {
1509             if (!IsNeedToUpdateSharedAppByHash(oldBundleInfo, infos.begin()->second)) {
1510                 APP_LOGD("the installed version is up-to-date");
1511                 continue;
1512             }
1513         }
1514 
1515         if (!OTAInstallSystemSharedBundle({scanPath}, appType, removable)) {
1516             APP_LOGE("OTA update shared bundle(%{public}s) error.", bundleName.c_str());
1517         }
1518     }
1519 }
1520 
InnerProcessRebootSystemHspInstall(const std::list<std::string> & scanPathList)1521 void BMSEventHandler::InnerProcessRebootSystemHspInstall(const std::list<std::string> &scanPathList)
1522 {
1523     APP_LOGI("InnerProcessRebootSystemHspInstall");
1524     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1525     if (dataMgr == nullptr) {
1526         APP_LOGE("DataMgr is nullptr");
1527         return;
1528     }
1529     for (const auto &scanPath : scanPathList) {
1530         std::unordered_map<std::string, InnerBundleInfo> infos;
1531         if (!ParseHapFiles(scanPath, infos) || infos.empty()) {
1532             APP_LOGE("obtain bundleinfo failed : %{public}s ", scanPath.c_str());
1533             continue;
1534         }
1535         auto bundleName = infos.begin()->second.GetBundleName();
1536         auto versionCode = infos.begin()->second.GetVersionCode();
1537         AddParseInfosToMap(bundleName, infos);
1538         auto mapIter = loadExistData_.find(bundleName);
1539         if (mapIter == loadExistData_.end()) {
1540             APP_LOGI("OTA Install new system hsp(%{public}s) by path(%{public}s).",
1541                 bundleName.c_str(), scanPath.c_str());
1542             if (OTAInstallSystemHsp({scanPath}) != ERR_OK) {
1543                 APP_LOGE("OTA Install new system hsp(%{public}s) error.", bundleName.c_str());
1544             }
1545             continue;
1546         }
1547         InnerBundleInfo oldBundleInfo;
1548         bool hasInstalled = dataMgr->FetchInnerBundleInfo(bundleName, oldBundleInfo);
1549         if (!hasInstalled) {
1550             APP_LOGW("app(%{public}s) has been uninstalled and do not OTA install.", bundleName.c_str());
1551             continue;
1552         }
1553         if (oldBundleInfo.GetVersionCode() > versionCode) {
1554             APP_LOGD("the installed version is up-to-date");
1555             continue;
1556         }
1557         if (oldBundleInfo.GetVersionCode() == versionCode) {
1558             for (const auto &item : infos) {
1559                 if (!IsNeedToUpdateSharedHspByHash(oldBundleInfo, item.second)) {
1560                     APP_LOGD("the installed version is up-to-date");
1561                     continue;
1562                 }
1563             }
1564         }
1565         if (OTAInstallSystemHsp({scanPath}) != ERR_OK) {
1566             APP_LOGE("OTA update shared bundle(%{public}s) error.", bundleName.c_str());
1567         }
1568     }
1569 }
1570 
OTAInstallSystemHsp(const std::vector<std::string> & filePaths)1571 ErrCode BMSEventHandler::OTAInstallSystemHsp(const std::vector<std::string> &filePaths)
1572 {
1573     InstallParam installParam;
1574     installParam.isPreInstallApp = true;
1575     installParam.removable = false;
1576     AppServiceFwkInstaller installer;
1577 
1578     return installer.Install(filePaths, installParam);
1579 }
1580 
IsNeedToUpdateSharedHspByHash(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const1581 bool BMSEventHandler::IsNeedToUpdateSharedHspByHash(
1582     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
1583 {
1584     std::string moduleName = newInfo.GetCurrentModulePackage();
1585     std::string newModuleBuildHash;
1586     if (!newInfo.GetModuleBuildHash(moduleName, newModuleBuildHash)) {
1587         APP_LOGE("internal error, can not find module %{public}s", moduleName.c_str());
1588         return false;
1589     }
1590 
1591     std::string oldModuleBuildHash;
1592     if (!oldInfo.GetModuleBuildHash(moduleName, oldModuleBuildHash) ||
1593         newModuleBuildHash != oldModuleBuildHash) {
1594         APP_LOGD("module %{public}s need to be updated", moduleName.c_str());
1595         return true;
1596     }
1597     return false;
1598 }
1599 
IsNeedToUpdateSharedAppByHash(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const1600 bool BMSEventHandler::IsNeedToUpdateSharedAppByHash(
1601     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
1602 {
1603     auto oldSharedModuleMap = oldInfo.GetInnerSharedModuleInfos();
1604     auto newSharedModuleMap = newInfo.GetInnerSharedModuleInfos();
1605     for (const auto &item : newSharedModuleMap) {
1606         auto newModuleName = item.first;
1607         auto oldModuleInfos = oldSharedModuleMap[newModuleName];
1608         auto newModuleInfos = item.second;
1609         if (!oldModuleInfos.empty() && !newModuleInfos.empty()) {
1610             auto oldBuildHash = oldModuleInfos[0].buildHash;
1611             auto newBuildHash = newModuleInfos[0].buildHash;
1612             return oldBuildHash != newBuildHash;
1613         } else {
1614             return true;
1615         }
1616     }
1617     return false;
1618 }
1619 
IsHotPatchApp(const std::string & bundleName)1620 bool BMSEventHandler::IsHotPatchApp(const std::string &bundleName)
1621 {
1622     InnerBundleInfo innerBundleInfo;
1623     if (!FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
1624         APP_LOGE("can not get InnerBundleInfo, bundleName=%{public}s", bundleName.c_str());
1625         return false;
1626     }
1627 
1628     return innerBundleInfo.CheckSpecialMetaData(HOT_PATCH_METADATA);
1629 }
1630 
HotPatchAppProcessing(const std::string & bundleName)1631 bool BMSEventHandler::HotPatchAppProcessing(const std::string &bundleName)
1632 {
1633     if (bundleName.empty()) {
1634         APP_LOGW("bundleName:%{public}s empty", bundleName.c_str());
1635         return false;
1636     }
1637 
1638     if (IsHotPatchApp(bundleName)) {
1639         APP_LOGI("get hotpatch meta-data success, bundleName=%{public}s", bundleName.c_str());
1640         SystemBundleInstaller installer;
1641         if (!installer.UninstallSystemBundle(bundleName, true)) {
1642             APP_LOGE("keep data to uninstall app(%{public}s) error", bundleName.c_str());
1643             return false;
1644         }
1645         return true;
1646     }
1647     return false;
1648 }
1649 
SaveSystemFingerprint()1650 void BMSEventHandler::SaveSystemFingerprint()
1651 {
1652     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1653     if (bmsPara == nullptr) {
1654         APP_LOGE("bmsPara is nullptr");
1655         return;
1656     }
1657 
1658     std::string curSystemFingerprint = GetCurSystemFingerprint();
1659     APP_LOGI("curSystemFingerprint(%{public}s)", curSystemFingerprint.c_str());
1660     if (curSystemFingerprint.empty()) {
1661         return;
1662     }
1663 
1664     bmsPara->SaveBmsParam(FINGERPRINT, curSystemFingerprint);
1665 }
1666 
IsSystemUpgrade()1667 bool BMSEventHandler::IsSystemUpgrade()
1668 {
1669     return IsTestSystemUpgrade() || IsSystemFingerprintChanged();
1670 }
1671 
IsTestSystemUpgrade()1672 bool BMSEventHandler::IsTestSystemUpgrade()
1673 {
1674     std::string paramValue;
1675     if (!GetSystemParameter(BMS_TEST_UPGRADE, paramValue) || paramValue.empty()) {
1676         return false;
1677     }
1678 
1679     APP_LOGI("TestSystemUpgrade value is %{public}s", paramValue.c_str());
1680     return paramValue == VALUE_TRUE;
1681 }
1682 
IsSystemFingerprintChanged()1683 bool BMSEventHandler::IsSystemFingerprintChanged()
1684 {
1685     std::string oldSystemFingerprint = GetOldSystemFingerprint();
1686     if (oldSystemFingerprint.empty()) {
1687         APP_LOGD("System should be upgraded due to oldSystemFingerprint is empty");
1688         return true;
1689     }
1690 
1691     std::string curSystemFingerprint = GetCurSystemFingerprint();
1692     APP_LOGD("oldSystemFingerprint(%{public}s), curSystemFingerprint(%{public}s)",
1693         oldSystemFingerprint.c_str(), curSystemFingerprint.c_str());
1694     return curSystemFingerprint != oldSystemFingerprint;
1695 }
1696 
GetCurSystemFingerprint()1697 std::string BMSEventHandler::GetCurSystemFingerprint()
1698 {
1699     std::string curSystemFingerprint;
1700     for (const auto &item : FINGERPRINTS) {
1701         std::string itemFingerprint;
1702         if (!GetSystemParameter(item, itemFingerprint) || itemFingerprint.empty()) {
1703             continue;
1704         }
1705 
1706         if (!curSystemFingerprint.empty()) {
1707             curSystemFingerprint.append(Constants::PATH_SEPARATOR);
1708         }
1709 
1710         curSystemFingerprint.append(itemFingerprint);
1711     }
1712 
1713     return curSystemFingerprint;
1714 }
1715 
GetSystemParameter(const std::string & key,std::string & value)1716 bool BMSEventHandler::GetSystemParameter(const std::string &key, std::string &value)
1717 {
1718     char firmware[VERSION_LEN] = {0};
1719     int32_t ret = GetParameter(key.c_str(), UNKNOWN.c_str(), firmware, VERSION_LEN);
1720     if (ret <= 0) {
1721         APP_LOGE("GetParameter failed!");
1722         return false;
1723     }
1724 
1725     value = firmware;
1726     return true;
1727 }
1728 
GetOldSystemFingerprint()1729 std::string BMSEventHandler::GetOldSystemFingerprint()
1730 {
1731     std::string oldSystemFingerprint;
1732     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1733     if (bmsPara != nullptr) {
1734         bmsPara->GetBmsParam(FINGERPRINT, oldSystemFingerprint);
1735     }
1736 
1737     return oldSystemFingerprint;
1738 }
1739 
AddParseInfosToMap(const std::string & bundleName,const std::unordered_map<std::string,InnerBundleInfo> & infos)1740 void BMSEventHandler::AddParseInfosToMap(
1741     const std::string &bundleName, const std::unordered_map<std::string, InnerBundleInfo> &infos)
1742 {
1743     auto hapParseInfoMapIter = hapParseInfoMap_.find(bundleName);
1744     if (hapParseInfoMapIter == hapParseInfoMap_.end()) {
1745         hapParseInfoMap_.emplace(bundleName, infos);
1746         return;
1747     }
1748 
1749     auto iterMap = hapParseInfoMapIter->second;
1750     for (auto infoIter : infos) {
1751         iterMap.emplace(infoIter.first, infoIter.second);
1752     }
1753 
1754     hapParseInfoMap_.at(bundleName) = iterMap;
1755 }
1756 
ProcessRebootBundleUninstall()1757 void BMSEventHandler::ProcessRebootBundleUninstall()
1758 {
1759     APP_LOGI("Reboot scan and OTA uninstall start");
1760     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1761     if (dataMgr == nullptr) {
1762         APP_LOGE("DataMgr is nullptr");
1763         return;
1764     }
1765 
1766     for (auto &loadIter : loadExistData_) {
1767         std::string bundleName = loadIter.first;
1768         auto listIter = hapParseInfoMap_.find(bundleName);
1769         if (listIter == hapParseInfoMap_.end()) {
1770             APP_LOGI("ProcessRebootBundleUninstall OTA uninstall app(%{public}s).", bundleName.c_str());
1771             SystemBundleInstaller installer;
1772             if (!installer.UninstallSystemBundle(bundleName)) {
1773                 APP_LOGE("OTA uninstall app(%{public}s) error", bundleName.c_str());
1774             } else {
1775                 std::string moduleName;
1776                 DeletePreInfoInDb(bundleName, moduleName, true);
1777             }
1778 
1779             continue;
1780         }
1781 
1782         BundleInfo hasInstalledInfo;
1783         auto hasBundleInstalled = dataMgr->GetBundleInfo(
1784             bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
1785         if (!hasBundleInstalled) {
1786             APP_LOGW("app(%{public}s) maybe has been uninstall.", bundleName.c_str());
1787             continue;
1788         }
1789 
1790         // Check the installed module.
1791         // If the corresponding Hap does not exist, it should be uninstalled.
1792         for (auto moduleName : hasInstalledInfo.hapModuleNames) {
1793             bool hasModuleHapExist = false;
1794             for (auto parserInfoIter : listIter->second) {
1795                 auto parserModuleNames = parserInfoIter.second.GetModuleNameVec();
1796                 if (!parserModuleNames.empty() && moduleName == parserModuleNames[0]) {
1797                     hasModuleHapExist = true;
1798                     break;
1799                 }
1800             }
1801 
1802             if (!hasModuleHapExist) {
1803                 APP_LOGI("ProcessRebootBundleUninstall OTA app(%{public}s) uninstall module(%{public}s).",
1804                     bundleName.c_str(), moduleName.c_str());
1805                 SystemBundleInstaller installer;
1806                 if (!installer.UninstallSystemBundle(bundleName, moduleName)) {
1807                     APP_LOGE("OTA app(%{public}s) uninstall module(%{public}s) error.",
1808                         bundleName.c_str(), moduleName.c_str());
1809                 }
1810             }
1811         }
1812 
1813         // Check the preInstall path in Db.
1814         // If the corresponding Hap does not exist, it should be deleted.
1815         auto parserInfoMap = listIter->second;
1816         for (auto preBundlePath : loadIter.second.GetBundlePaths()) {
1817             auto parserInfoIter = parserInfoMap.find(preBundlePath);
1818             if (parserInfoIter != parserInfoMap.end()) {
1819                 APP_LOGI("OTA uninstall app(%{public}s) module path(%{public}s) exits.",
1820                     bundleName.c_str(), preBundlePath.c_str());
1821                 continue;
1822             }
1823 
1824             APP_LOGI("OTA app(%{public}s) delete path(%{public}s).",
1825                 bundleName.c_str(), preBundlePath.c_str());
1826             DeletePreInfoInDb(bundleName, preBundlePath, false);
1827         }
1828     }
1829 
1830     APP_LOGI("Reboot scan and OTA uninstall success");
1831 }
1832 
DeletePreInfoInDb(const std::string & bundleName,const std::string & bundlePath,bool bundleLevel)1833 void BMSEventHandler::DeletePreInfoInDb(
1834     const std::string &bundleName, const std::string &bundlePath, bool bundleLevel)
1835 {
1836     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1837     if (dataMgr == nullptr) {
1838         APP_LOGE("DataMgr is nullptr");
1839         return;
1840     }
1841 
1842     PreInstallBundleInfo preInstallBundleInfo;
1843     preInstallBundleInfo.SetBundleName(bundleName);
1844     if (bundleLevel) {
1845         APP_LOGI("DeletePreInfoInDb bundle %{public}s bundleLevel", bundleName.c_str());
1846         dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1847         return;
1848     }
1849 
1850     APP_LOGI("DeletePreInfoInDb bundle %{public}s not bundleLevel with path(%{public}s)",
1851         bundleName.c_str(), bundlePath.c_str());
1852     dataMgr->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo);
1853     preInstallBundleInfo.DeleteBundlePath(bundlePath);
1854     if (preInstallBundleInfo.GetBundlePaths().empty()) {
1855         dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1856     } else {
1857         dataMgr->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1858     }
1859 }
1860 
HasModuleSavedInPreInstalledDb(const std::string & bundleName,const std::string & bundlePath)1861 bool BMSEventHandler::HasModuleSavedInPreInstalledDb(
1862     const std::string &bundleName, const std::string &bundlePath)
1863 {
1864     auto preInstallIter = loadExistData_.find(bundleName);
1865     if (preInstallIter == loadExistData_.end()) {
1866         APP_LOGE("app(%{public}s) does not save in PreInstalledDb.", bundleName.c_str());
1867         return false;
1868     }
1869 
1870     return preInstallIter->second.HasBundlePath(bundlePath);
1871 }
1872 
SavePreInstallException(const std::string & bundleDir)1873 void BMSEventHandler::SavePreInstallException(const std::string &bundleDir)
1874 {
1875     auto preInstallExceptionMgr =
1876         DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
1877     if (preInstallExceptionMgr == nullptr) {
1878         APP_LOGE("preInstallExceptionMgr is nullptr");
1879         return;
1880     }
1881 
1882     preInstallExceptionMgr->SavePreInstallExceptionPath(bundleDir);
1883 }
1884 
HandlePreInstallException()1885 void BMSEventHandler::HandlePreInstallException()
1886 {
1887     auto preInstallExceptionMgr =
1888         DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
1889     if (preInstallExceptionMgr == nullptr) {
1890         APP_LOGE("preInstallExceptionMgr is nullptr");
1891         return;
1892     }
1893 
1894     std::set<std::string> exceptionPaths;
1895     std::set<std::string> exceptionBundleNames;
1896     if (!preInstallExceptionMgr->GetAllPreInstallExceptionInfo(
1897         exceptionPaths, exceptionBundleNames)) {
1898         return;
1899     }
1900 
1901     APP_LOGI("HandlePreInstallExceptions pathSize: %{public}zu, bundleNameSize: %{public}zu",
1902         exceptionPaths.size(), exceptionBundleNames.size());
1903     for (const auto &pathIter : exceptionPaths) {
1904         APP_LOGI("HandlePreInstallException path: %{public}s", pathIter.c_str());
1905         std::vector<std::string> filePaths { pathIter };
1906         bool removable = IsPreInstallRemovable(pathIter);
1907         if (!OTAInstallSystemBundle(filePaths, Constants::AppType::SYSTEM_APP, removable)) {
1908             APP_LOGW("HandlePreInstallException path(%{public}s) error.", pathIter.c_str());
1909         }
1910 
1911         preInstallExceptionMgr->DeletePreInstallExceptionPath(pathIter);
1912     }
1913 
1914     if (exceptionBundleNames.size() > 0) {
1915         LoadAllPreInstallBundleInfos();
1916     }
1917 
1918     for (const auto &bundleNameIter : exceptionBundleNames) {
1919         APP_LOGI("HandlePreInstallException bundleName: %{public}s", bundleNameIter.c_str());
1920         auto iter = loadExistData_.find(bundleNameIter);
1921         if (iter == loadExistData_.end()) {
1922             APP_LOGW("HandlePreInstallException no bundleName(%{public}s) in PreInstallDb.",
1923                 bundleNameIter.c_str());
1924             continue;
1925         }
1926 
1927         const auto &preInstallBundleInfo = iter->second;
1928         if (!OTAInstallSystemBundle(preInstallBundleInfo.GetBundlePaths(),
1929             Constants::AppType::SYSTEM_APP, preInstallBundleInfo.GetRemovable())) {
1930             APP_LOGW("HandlePreInstallException bundleName(%{public}s) error.", bundleNameIter.c_str());
1931         }
1932 
1933         preInstallExceptionMgr->DeletePreInstallExceptionBundleName(bundleNameIter);
1934     }
1935 
1936     preInstallExceptionMgr->ClearAll();
1937 }
1938 
OTAInstallSystemBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)1939 bool BMSEventHandler::OTAInstallSystemBundle(
1940     const std::vector<std::string> &filePaths,
1941     Constants::AppType appType,
1942     bool removable)
1943 {
1944     if (filePaths.empty()) {
1945         APP_LOGE("File path is empty");
1946         return false;
1947     }
1948 
1949     InstallParam installParam;
1950     installParam.isPreInstallApp = true;
1951     installParam.noSkipsKill = false;
1952     installParam.needSendEvent = false;
1953     installParam.installFlag = InstallFlag::REPLACE_EXISTING;
1954     installParam.removable = removable;
1955     installParam.needSavePreInstallInfo = true;
1956     installParam.copyHapToInstallPath = false;
1957     installParam.isOTA = true;
1958     SystemBundleInstaller installer;
1959     ErrCode ret = installer.OTAInstallSystemBundle(filePaths, installParam, appType);
1960     if (ret == ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON) {
1961         ret = ERR_OK;
1962     }
1963     return ret == ERR_OK;
1964 }
1965 
OTAInstallSystemSharedBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)1966 bool BMSEventHandler::OTAInstallSystemSharedBundle(
1967     const std::vector<std::string> &filePaths,
1968     Constants::AppType appType,
1969     bool removable)
1970 {
1971     if (filePaths.empty()) {
1972         APP_LOGE("File path is empty");
1973         return false;
1974     }
1975 
1976     InstallParam installParam;
1977     installParam.isPreInstallApp = true;
1978     installParam.needSendEvent = false;
1979     installParam.installFlag = InstallFlag::REPLACE_EXISTING;
1980     installParam.removable = removable;
1981     installParam.needSavePreInstallInfo = true;
1982     installParam.sharedBundleDirPaths = filePaths;
1983     installParam.isOTA = true;
1984     SystemBundleInstaller installer;
1985     return installer.InstallSystemSharedBundle(installParam, true, appType);
1986 }
1987 
CheckAndParseHapFiles(const std::string & hapFilePath,bool isPreInstallApp,std::unordered_map<std::string,InnerBundleInfo> & infos)1988 bool BMSEventHandler::CheckAndParseHapFiles(
1989     const std::string &hapFilePath,
1990     bool isPreInstallApp,
1991     std::unordered_map<std::string, InnerBundleInfo> &infos)
1992 {
1993     std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
1994         std::make_unique<BundleInstallChecker>();
1995     std::vector<std::string> hapFilePathVec { hapFilePath };
1996     std::vector<std::string> realPaths;
1997     auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
1998     if (ret != ERR_OK) {
1999         APP_LOGE("File path %{public}s invalid", hapFilePath.c_str());
2000         return false;
2001     }
2002 
2003     ret = bundleInstallChecker->CheckSysCap(realPaths);
2004     if (ret != ERR_OK) {
2005         APP_LOGE("hap(%{public}s) syscap check failed", hapFilePath.c_str());
2006         return false;
2007     }
2008 
2009     std::vector<Security::Verify::HapVerifyResult> hapVerifyResults;
2010     ret = bundleInstallChecker->CheckMultipleHapsSignInfo(realPaths, hapVerifyResults);
2011     if (ret != ERR_OK) {
2012         APP_LOGE("CheckMultipleHapsSignInfo %{public}s failed", hapFilePath.c_str());
2013         return false;
2014     }
2015 
2016     InstallCheckParam checkParam;
2017     checkParam.isPreInstallApp = isPreInstallApp;
2018     if (isPreInstallApp) {
2019         checkParam.appType = Constants::AppType::SYSTEM_APP;
2020     }
2021 
2022     ret = bundleInstallChecker->ParseHapFiles(
2023         realPaths, checkParam, hapVerifyResults, infos);
2024     if (ret != ERR_OK) {
2025         APP_LOGE("parse haps file(%{public}s) failed", hapFilePath.c_str());
2026         return false;
2027     }
2028 
2029     ret = bundleInstallChecker->CheckHspInstallCondition(hapVerifyResults);
2030     if (ret != ERR_OK) {
2031         APP_LOGE("CheckHspInstallCondition failed %{public}d", ret);
2032         return false;
2033     }
2034 
2035     ret = bundleInstallChecker->CheckAppLabelInfo(infos);
2036     if (ret != ERR_OK) {
2037         APP_LOGE("Check APP label failed %{public}d", ret);
2038         return false;
2039     }
2040 
2041     // set hapPath
2042     std::for_each(infos.begin(), infos.end(), [](auto &item) {
2043         item.second.SetModuleHapPath(item.first);
2044     });
2045 
2046     return true;
2047 }
2048 
ParseHapFiles(const std::string & hapFilePath,std::unordered_map<std::string,InnerBundleInfo> & infos)2049 bool BMSEventHandler::ParseHapFiles(
2050     const std::string &hapFilePath,
2051     std::unordered_map<std::string, InnerBundleInfo> &infos)
2052 {
2053     std::vector<std::string> hapFilePathVec { hapFilePath };
2054     std::vector<std::string> realPaths;
2055     auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
2056     if (ret != ERR_OK) {
2057         APP_LOGE("File path %{public}s invalid", hapFilePath.c_str());
2058         return false;
2059     }
2060 
2061     BundleParser bundleParser;
2062     for (auto realPath : realPaths) {
2063         InnerBundleInfo innerBundleInfo;
2064         ret = bundleParser.Parse(realPath, innerBundleInfo);
2065         if (ret != ERR_OK) {
2066             APP_LOGE("Parse bundle info failed, error: %{public}d", ret);
2067             continue;
2068         }
2069 
2070         infos.emplace(realPath, innerBundleInfo);
2071     }
2072 
2073     if (infos.empty()) {
2074         APP_LOGE("Parse hap(%{public}s) empty ", hapFilePath.c_str());
2075         return false;
2076     }
2077 
2078     return true;
2079 }
2080 
IsPreInstallRemovable(const std::string & path)2081 bool BMSEventHandler::IsPreInstallRemovable(const std::string &path)
2082 {
2083 #ifdef USE_PRE_BUNDLE_PROFILE
2084     if (!HasPreInstallProfile()) {
2085         return false;
2086     }
2087 
2088     if (!hasLoadPreInstallProFile_) {
2089         APP_LOGE("Not load preInstall proFile or release.");
2090         return false;
2091     }
2092 
2093     if (path.empty() || installList_.empty()) {
2094         APP_LOGE("path or installList is empty.");
2095         return false;
2096     }
2097     auto installInfo = std::find_if(installList_.begin(), installList_.end(),
2098         [path](const auto &installInfo) {
2099         return installInfo.bundleDir == path;
2100     });
2101     if (installInfo != installList_.end()) {
2102         return (*installInfo).removable;
2103     }
2104     return true;
2105 #else
2106     return false;
2107 #endif
2108 }
2109 
GetPreInstallCapability(PreBundleConfigInfo & preBundleConfigInfo)2110 bool BMSEventHandler::GetPreInstallCapability(PreBundleConfigInfo &preBundleConfigInfo)
2111 {
2112     if (!hasLoadPreInstallProFile_) {
2113         APP_LOGE("Not load preInstall proFile or release.");
2114         return false;
2115     }
2116 
2117     if (preBundleConfigInfo.bundleName.empty() || installListCapabilities_.empty()) {
2118         APP_LOGE("BundleName or installListCapabilities is empty.");
2119         return false;
2120     }
2121 
2122     auto iter = installListCapabilities_.find(preBundleConfigInfo);
2123     if (iter == installListCapabilities_.end()) {
2124         APP_LOGD("BundleName(%{public}s) no has preinstall capability.",
2125             preBundleConfigInfo.bundleName.c_str());
2126         return false;
2127     }
2128 
2129     preBundleConfigInfo = *iter;
2130     return true;
2131 }
2132 
CheckExtensionTypeInConfig(const std::string & typeName)2133 bool BMSEventHandler::CheckExtensionTypeInConfig(const std::string &typeName)
2134 {
2135     if (!hasLoadPreInstallProFile_) {
2136         APP_LOGE("Not load typeName proFile or release.");
2137         return false;
2138     }
2139 
2140     if (typeName.empty() || extensiontype_.empty()) {
2141         APP_LOGE("TypeName or typeName configuration file is empty.");
2142         return false;
2143     }
2144 
2145     auto iter = extensiontype_.find(typeName);
2146     if (iter == extensiontype_.end()) {
2147         APP_LOGE("ExtensionTypeConfig does not have '(%{public}s)' type",
2148             typeName.c_str());
2149         return false;
2150     }
2151 
2152     return true;
2153 }
2154 
2155 #ifdef USE_PRE_BUNDLE_PROFILE
UpdateRemovable(const std::string & bundleName,bool removable)2156 void BMSEventHandler::UpdateRemovable(const std::string &bundleName, bool removable)
2157 {
2158     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2159     if (dataMgr == nullptr) {
2160         APP_LOGE("DataMgr is nullptr");
2161         return;
2162     }
2163 
2164     dataMgr->UpdateRemovable(bundleName, removable);
2165 }
2166 
UpdateAllPrivilegeCapability()2167 void BMSEventHandler::UpdateAllPrivilegeCapability()
2168 {
2169     for (const auto &preBundleConfigInfo : installListCapabilities_) {
2170         UpdatePrivilegeCapability(preBundleConfigInfo);
2171     }
2172 }
2173 
UpdatePrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)2174 void BMSEventHandler::UpdatePrivilegeCapability(
2175     const PreBundleConfigInfo &preBundleConfigInfo)
2176 {
2177     auto &bundleName = preBundleConfigInfo.bundleName;
2178     InnerBundleInfo innerBundleInfo;
2179     if (!FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
2180         APP_LOGW("App(%{public}s) is not installed.", bundleName.c_str());
2181         return;
2182     }
2183     // match both fingerprint and appId
2184     if (!MatchSignature(preBundleConfigInfo, innerBundleInfo.GetCertificateFingerprint()) &&
2185         !MatchSignature(preBundleConfigInfo, innerBundleInfo.GetAppId()) &&
2186         !MatchSignature(preBundleConfigInfo, innerBundleInfo.GetAppIdentifier()) &&
2187         !MatchOldSignatures(preBundleConfigInfo, innerBundleInfo.GetOldAppIds())) {
2188         APP_LOGE("bundleName: %{public}s no match pre bundle config info", bundleName.c_str());
2189         return;
2190     }
2191 
2192     UpdateTrustedPrivilegeCapability(preBundleConfigInfo);
2193 }
2194 
MatchSignature(const PreBundleConfigInfo & configInfo,const std::string & signature)2195 bool BMSEventHandler::MatchSignature(
2196     const PreBundleConfigInfo &configInfo, const std::string &signature)
2197 {
2198     if (configInfo.appSignature.empty() || signature.empty()) {
2199         APP_LOGW("appSignature or signature is empty");
2200         return false;
2201     }
2202 
2203     return std::find(configInfo.appSignature.begin(),
2204         configInfo.appSignature.end(), signature) != configInfo.appSignature.end();
2205 }
2206 
MatchOldSignatures(const PreBundleConfigInfo & configInfo,const std::vector<std::string> & oldSignatures)2207 bool BMSEventHandler::MatchOldSignatures(const PreBundleConfigInfo &configInfo,
2208     const std::vector<std::string> &oldSignatures)
2209 {
2210     if (configInfo.appSignature.empty() || oldSignatures.empty()) {
2211         APP_LOGW("appSignature or oldSignatures is empty");
2212         return false;
2213     }
2214     for (const auto &signature : oldSignatures) {
2215         if (std::find(configInfo.appSignature.begin(), configInfo.appSignature.end(), signature) !=
2216             configInfo.appSignature.end()) {
2217             return true;
2218         }
2219     }
2220 
2221     return false;
2222 }
2223 
UpdateTrustedPrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)2224 void BMSEventHandler::UpdateTrustedPrivilegeCapability(
2225     const PreBundleConfigInfo &preBundleConfigInfo)
2226 {
2227     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2228     if (dataMgr == nullptr) {
2229         APP_LOGE("DataMgr is nullptr");
2230         return;
2231     }
2232 
2233     ApplicationInfo appInfo;
2234     appInfo.keepAlive = preBundleConfigInfo.keepAlive;
2235     appInfo.singleton = preBundleConfigInfo.singleton;
2236     appInfo.runningResourcesApply = preBundleConfigInfo.runningResourcesApply;
2237     appInfo.associatedWakeUp = preBundleConfigInfo.associatedWakeUp;
2238     appInfo.allowCommonEvent = preBundleConfigInfo.allowCommonEvent;
2239     appInfo.resourcesApply = preBundleConfigInfo.resourcesApply;
2240     dataMgr->UpdatePrivilegeCapability(preBundleConfigInfo.bundleName, appInfo);
2241 }
2242 #endif
2243 
FetchInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & innerBundleInfo)2244 bool BMSEventHandler::FetchInnerBundleInfo(
2245     const std::string &bundleName, InnerBundleInfo &innerBundleInfo)
2246 {
2247     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2248     if (dataMgr == nullptr) {
2249         APP_LOGE("DataMgr is nullptr");
2250         return false;
2251     }
2252 
2253     return dataMgr->FetchInnerBundleInfo(bundleName, innerBundleInfo);
2254 }
2255 
ListeningUserUnlocked() const2256 void BMSEventHandler::ListeningUserUnlocked() const
2257 {
2258     APP_LOGI("BMSEventHandler listen the unlock of someone user start.");
2259     EventFwk::MatchingSkills matchingSkills;
2260     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
2261     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
2262     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
2263     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
2264 
2265     auto subscriberPtr = std::make_shared<UserUnlockedEventSubscriber>(subscribeInfo);
2266     if (!EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberPtr)) {
2267         APP_LOGW("BMSEventHandler subscribe common event %{public}s failed",
2268             EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED.c_str());
2269     }
2270 }
2271 
RemoveUnreservedSandbox() const2272 void BMSEventHandler::RemoveUnreservedSandbox() const
2273 {
2274 #if defined (BUNDLE_FRAMEWORK_SANDBOX_APP) && defined (DLP_PERMISSION_ENABLE)
2275     APP_LOGI("Start to RemoveUnreservedSandbox");
2276     const int32_t WAIT_TIMES = 40;
2277     const int32_t EACH_TIME = 1000; // 1000ms
2278     auto execFunc = [](int32_t waitTimes, int32_t eachTime) {
2279         int32_t currentUserId = Constants::INVALID_USERID;
2280         while (waitTimes--) {
2281             std::this_thread::sleep_for(std::chrono::milliseconds(eachTime));
2282             APP_LOGD("wait for account started");
2283             if (currentUserId == Constants::INVALID_USERID) {
2284                 currentUserId = AccountHelper::GetCurrentActiveUserId();
2285                 APP_LOGD("current active userId is %{public}d", currentUserId);
2286                 if (currentUserId == Constants::INVALID_USERID) {
2287                     continue;
2288                 }
2289             }
2290             APP_LOGI("RemoveUnreservedSandbox call ClearUnreservedSandbox");
2291             Security::DlpPermission::DlpPermissionKit::ClearUnreservedSandbox();
2292             break;
2293         }
2294     };
2295     std::thread removeThread(execFunc, WAIT_TIMES, EACH_TIME);
2296     removeThread.detach();
2297 #endif
2298     APP_LOGI("RemoveUnreservedSandbox finish");
2299 }
2300 
AddStockAppProvisionInfoByOTA(const std::string & bundleName,const std::string & filePath)2301 void BMSEventHandler::AddStockAppProvisionInfoByOTA(const std::string &bundleName, const std::string &filePath)
2302 {
2303     APP_LOGD("AddStockAppProvisionInfoByOTA bundleName: %{public}s", bundleName.c_str());
2304     // parse profile info
2305     Security::Verify::HapVerifyResult hapVerifyResult;
2306     auto ret = BundleVerifyMgr::ParseHapProfile(filePath, hapVerifyResult);
2307     if (ret != ERR_OK) {
2308         APP_LOGE("BundleVerifyMgr::HapVerify failed, bundleName: %{public}s, errCode: %{public}d",
2309             bundleName.c_str(), ret);
2310         return;
2311     }
2312 
2313     std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
2314         std::make_unique<BundleInstallChecker>();
2315     AppProvisionInfo appProvisionInfo = bundleInstallChecker->ConvertToAppProvisionInfo(
2316         hapVerifyResult.GetProvisionInfo());
2317     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->AddAppProvisionInfo(bundleName, appProvisionInfo)) {
2318         APP_LOGE("AddAppProvisionInfo failed, bundleName:%{public}s", bundleName.c_str());
2319     }
2320 }
2321 
UpdateAppDataSelinuxLabel(const std::string & bundleName,const std::string & apl,bool isPreInstall,bool debug)2322 void BMSEventHandler::UpdateAppDataSelinuxLabel(const std::string &bundleName, const std::string &apl,
2323     bool isPreInstall, bool debug)
2324 {
2325     APP_LOGD("UpdateAppDataSelinuxLabel bundleName: %{public}s start.", bundleName.c_str());
2326     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2327     if (dataMgr == nullptr) {
2328         APP_LOGE("DataMgr is nullptr");
2329         return;
2330     }
2331     std::set<int32_t> userIds = dataMgr->GetAllUser();
2332     for (const auto &userId : userIds) {
2333         for (const auto &el : Constants::BUNDLE_EL) {
2334             std::string baseBundleDataDir = Constants::BUNDLE_APP_DATA_BASE_DIR +
2335                                             el +
2336                                             Constants::PATH_SEPARATOR +
2337                                             std::to_string(userId);
2338             std::string baseDataDir = baseBundleDataDir + Constants::BASE + bundleName;
2339             bool isExist = true;
2340             ErrCode result = InstalldClient::GetInstance()->IsExistDir(baseDataDir, isExist);
2341             if (result != ERR_OK) {
2342                 APP_LOGE("IsExistDir failed, error is %{public}d", result);
2343                 continue;
2344             }
2345             if (!isExist) {
2346                 // Update only accessible directories when OTA,
2347                 // and other directories need to be set after the device is unlocked.
2348                 // Can see UserUnlockedEventSubscriber::UpdateAppDataDirSelinuxLabel
2349                 continue;
2350             }
2351             result = InstalldClient::GetInstance()->SetDirApl(baseDataDir, bundleName, apl, isPreInstall, debug);
2352             if (result != ERR_OK) {
2353                 APP_LOGW("bundleName: %{public}s, fail to SetDirApl baseDataDir dir, error is %{public}d",
2354                     bundleName.c_str(), result);
2355             }
2356             std::string databaseDataDir = baseBundleDataDir + Constants::DATABASE + bundleName;
2357             result = InstalldClient::GetInstance()->SetDirApl(databaseDataDir, bundleName, apl, isPreInstall, debug);
2358             if (result != ERR_OK) {
2359                 APP_LOGW("bundleName: %{public}s, fail to SetDirApl databaseDir dir, error is %{public}d",
2360                     bundleName.c_str(), result);
2361             }
2362         }
2363     }
2364     APP_LOGD("UpdateAppDataSelinuxLabel bundleName: %{public}s end.", bundleName.c_str());
2365 }
2366 
HandleSceneBoard() const2367 void BMSEventHandler::HandleSceneBoard() const
2368 {
2369 #ifdef WINDOW_ENABLE
2370     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2371     if (dataMgr == nullptr) {
2372         APP_LOGE("dataMgr is null");
2373         return;
2374     }
2375     bool sceneBoardEnable = Rosen::SceneBoardJudgement::IsSceneBoardEnabled();
2376     APP_LOGI("HandleSceneBoard sceneBoardEnable : %{public}d", sceneBoardEnable);
2377     dataMgr->SetApplicationEnabled(Constants::SYSTEM_UI_BUNDLE_NAME, !sceneBoardEnable, Constants::DEFAULT_USERID);
2378     std::set<int32_t> userIds = dataMgr->GetAllUser();
2379     std::for_each(userIds.cbegin(), userIds.cend(), [dataMgr, sceneBoardEnable](const int32_t userId) {
2380         dataMgr->SetApplicationEnabled(Constants::SCENE_BOARD_BUNDLE_NAME, sceneBoardEnable, userId);
2381         dataMgr->SetApplicationEnabled(Constants::LAUNCHER_BUNDLE_NAME, !sceneBoardEnable, userId);
2382     });
2383 #endif
2384 }
2385 
InnerProcessStockBundleProvisionInfo()2386 void BMSEventHandler::InnerProcessStockBundleProvisionInfo()
2387 {
2388     APP_LOGD("InnerProcessStockBundleProvisionInfo start.");
2389     std::unordered_set<std::string> allBundleNames;
2390     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->GetAllAppProvisionInfoBundleName(allBundleNames)) {
2391         APP_LOGE("GetAllAppProvisionInfoBundleName failed");
2392         return;
2393     }
2394     // process normal bundle
2395     ProcessBundleProvisionInfo(allBundleNames);
2396     // process shared bundle
2397     ProcessSharedBundleProvisionInfo(allBundleNames);
2398     APP_LOGD("InnerProcessStockBundleProvisionInfo end.");
2399 }
2400 
ProcessBundleProvisionInfo(const std::unordered_set<std::string> & allBundleNames)2401 void BMSEventHandler::ProcessBundleProvisionInfo(const std::unordered_set<std::string> &allBundleNames)
2402 {
2403     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2404     if (dataMgr == nullptr) {
2405         APP_LOGE("DataMgr is nullptr");
2406         return;
2407     }
2408     std::vector<BundleInfo> bundleInfos;
2409     if (dataMgr->GetBundleInfosV9(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
2410         bundleInfos, Constants::ALL_USERID) != ERR_OK) {
2411         APP_LOGE("GetBundleInfos failed");
2412         return;
2413     }
2414     for (const auto &bundleInfo : bundleInfos) {
2415         // not exist in appProvisionInfo table, then parse profile info and save it
2416         if ((allBundleNames.find(bundleInfo.name) == allBundleNames.end()) &&
2417             !bundleInfo.hapModuleInfos.empty()) {
2418             AddStockAppProvisionInfoByOTA(bundleInfo.name, bundleInfo.hapModuleInfos[0].hapPath);
2419         }
2420     }
2421 }
2422 
ProcessSharedBundleProvisionInfo(const std::unordered_set<std::string> & allBundleNames)2423 void BMSEventHandler::ProcessSharedBundleProvisionInfo(const std::unordered_set<std::string> &allBundleNames)
2424 {
2425     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2426     if (dataMgr == nullptr) {
2427         APP_LOGE("DataMgr is nullptr");
2428         return;
2429     }
2430     std::vector<SharedBundleInfo> shareBundleInfos;
2431     if (dataMgr->GetAllSharedBundleInfo(shareBundleInfos) != ERR_OK) {
2432         APP_LOGE("GetAllSharedBundleInfo failed");
2433         return;
2434     }
2435     for (const auto &sharedBundleInfo : shareBundleInfos) {
2436         // not exist in appProvisionInfo table, then parse profile info and save it
2437         if ((allBundleNames.find(sharedBundleInfo.name) == allBundleNames.end()) &&
2438             !sharedBundleInfo.sharedModuleInfos.empty()) {
2439             std::string hspPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + sharedBundleInfo.name +
2440                 Constants::PATH_SEPARATOR + HSP_VERSION_PREFIX +
2441                 std::to_string(sharedBundleInfo.sharedModuleInfos[0].versionCode) + Constants::PATH_SEPARATOR +
2442                 sharedBundleInfo.sharedModuleInfos[0].name + Constants::PATH_SEPARATOR +
2443                 sharedBundleInfo.sharedModuleInfos[0].name + Constants::HSP_FILE_SUFFIX;
2444             AddStockAppProvisionInfoByOTA(sharedBundleInfo.name, hspPath);
2445         }
2446     }
2447 }
2448 
ProcessRebootQuickFixBundleInstall(const std::string & path,bool isOta)2449 void BMSEventHandler::ProcessRebootQuickFixBundleInstall(const std::string &path, bool isOta)
2450 {
2451     APP_LOGI("ProcessRebootQuickFixBundleInstall start, isOta:%{public}d", isOta);
2452     std::list<std::string> bundleDirs;
2453     ProcessScanDir(path, bundleDirs);
2454     if (bundleDirs.empty()) {
2455         APP_LOGI("end, bundleDirs is empty");
2456         return;
2457     }
2458     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2459     if (dataMgr == nullptr) {
2460         APP_LOGE("DataMgr is nullptr");
2461         return;
2462     }
2463     for (auto &scanPathIter : bundleDirs) {
2464         std::unordered_map<std::string, InnerBundleInfo> infos;
2465         if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
2466             APP_LOGE("ParseHapFiles failed : %{public}s ", scanPathIter.c_str());
2467             continue;
2468         }
2469         auto bundleName = infos.begin()->second.GetBundleName();
2470         auto hapVersionCode = infos.begin()->second.GetVersionCode();
2471         BundleInfo hasInstalledInfo;
2472         auto hasBundleInstalled = dataMgr->GetBundleInfo(
2473             bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
2474         if (!hasBundleInstalled) {
2475             APP_LOGW("obtain bundleInfo failed, bundleName :%{public}s not exist.", bundleName.c_str());
2476             continue;
2477         }
2478         if (hapVersionCode <= hasInstalledInfo.versionCode) {
2479             APP_LOGW("bundleName: %{public}s: hapVersionCode is less than old hap versionCode.", bundleName.c_str());
2480             continue;
2481         }
2482         if (!hasInstalledInfo.isKeepAlive) {
2483             APP_LOGW("bundleName: %{public}s: is not keep alive bundle", bundleName.c_str());
2484             continue;
2485         }
2486         InstallParam installParam;
2487         installParam.noSkipsKill = false;
2488         installParam.needSendEvent = false;
2489         installParam.installFlag = InstallFlag::REPLACE_EXISTING;
2490         installParam.copyHapToInstallPath = true;
2491         installParam.isOTA = isOta;
2492         SystemBundleInstaller installer;
2493         std::vector<std::string> filePaths { scanPathIter };
2494         if (!installer.OTAInstallSystemBundle(filePaths, installParam, Constants::AppType::SYSTEM_APP)) {
2495             APP_LOGW("bundleName: %{public}s: install failed.", bundleName.c_str());
2496         }
2497     }
2498     APP_LOGI("ProcessRebootQuickFixBundleInstall end");
2499 }
2500 
ProcessBundleResourceInfo()2501 void BMSEventHandler::ProcessBundleResourceInfo()
2502 {
2503     APP_LOGI("ProcessBundleResourceInfo start");
2504     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2505     if (dataMgr == nullptr) {
2506         APP_LOGE("DataMgr is nullptr");
2507         return;
2508     }
2509     std::vector<std::string> bundleNames = dataMgr->GetAllBundleName();
2510     if (bundleNames.empty()) {
2511         APP_LOGE("bundleNames is empty");
2512         return;
2513     }
2514     std::vector<std::string> resourceNames;
2515     BundleResourceHelper::GetAllBundleResourceName(resourceNames);
2516     if (resourceNames.empty()) {
2517         APP_LOGI("rdb has no resource info, need add all");
2518     }
2519     for (const auto &bundleName : bundleNames) {
2520         if (std::find(resourceNames.begin(), resourceNames.end(), bundleName) == resourceNames.end()) {
2521             APP_LOGD("need add bundleName: %{public}s resource", bundleName.c_str());
2522             BundleResourceHelper::AddResourceInfoByBundleName(bundleName, Constants::START_USERID);
2523         }
2524     }
2525     APP_LOGI("ProcessBundleResourceInfo end");
2526 }
2527 
SendBundleUpdateFailedEvent(const BundleInfo & bundleInfo)2528 void BMSEventHandler::SendBundleUpdateFailedEvent(const BundleInfo &bundleInfo)
2529 {
2530     APP_LOGI("SendBundleUpdateFailedEvent start, bundleName:%{public}s", bundleInfo.name.c_str());
2531     EventInfo eventInfo;
2532     eventInfo.userId = Constants::ANY_USERID;
2533     eventInfo.bundleName = bundleInfo.name;
2534     eventInfo.versionCode = bundleInfo.versionCode;
2535     eventInfo.errCode = ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
2536     eventInfo.isPreInstallApp = bundleInfo.isPreInstallApp;
2537     EventReport::SendBundleSystemEvent(BundleEventType::UPDATE, eventInfo);
2538 }
2539 }  // namespace AppExecFwk
2540 }  // namespace OHOS
2541