• 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 <sys/stat.h>
19 
20 #include "account_helper.h"
21 #include "aot/aot_handler.h"
22 #include "app_log_tag_wrapper.h"
23 #include "app_provision_info_manager.h"
24 #include "app_service_fwk_installer.h"
25 #include "bms_key_event_mgr.h"
26 #include "bundle_parser.h"
27 #include "bundle_permission_mgr.h"
28 #include "bundle_resource_helper.h"
29 #include "running_process_info.h"
30 #include "bundle_scanner.h"
31 #ifdef CONFIG_POLOCY_ENABLE
32 #include "config_policy_utils.h"
33 #endif
34 #if defined (BUNDLE_FRAMEWORK_SANDBOX_APP) && defined (DLP_PERMISSION_ENABLE)
35 #include "dlp_permission_kit.h"
36 #endif
37 #include "installd_client.h"
38 #include "parameter.h"
39 #include "parameters.h"
40 #include "perf_profile.h"
41 #ifdef WINDOW_ENABLE
42 #include "scene_board_judgement.h"
43 #endif
44 #include "status_receiver_host.h"
45 #include "system_bundle_installer.h"
46 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
47 #include "quick_fix_boot_scanner.h"
48 #endif
49 #include "user_unlocked_event_subscriber.h"
50 #ifdef STORAGE_SERVICE_ENABLE
51 #include "storage_manager_proxy.h"
52 #include "iservice_registry.h"
53 #endif
54 
55 namespace OHOS {
56 namespace AppExecFwk {
57 namespace {
58 const std::string APP_SUFFIX = "/app";
59 const std::string TEMP_PREFIX = "temp_";
60 const std::string MODULE_PREFIX = "module_";
61 const std::string PRE_INSTALL_HSP_PATH = "/shared_bundles/";
62 const std::string BMS_TEST_UPGRADE = "persist.bms.test-upgrade";
63 constexpr const char* MODULE_UPDATE_APP_SERVICE_DIR = "appServiceFwk";
64 const std::string FINGERPRINT = "fingerprint";
65 const std::string UNKNOWN = "";
66 const std::string VALUE_TRUE = "true";
67 const int32_t VERSION_LEN = 64;
68 const std::vector<std::string> FINGERPRINTS = {
69     "const.product.software.version",
70     "const.product.build.type",
71     "const.product.brand",
72     "const.product.name",
73     "const.product.devicetype",
74     "const.product.incremental.version",
75     "const.comp.hl.product_base_version.real"
76 };
77 const std::string HSP_VERSION_PREFIX = "v";
78 const std::string OTA_FLAG = "otaFlag";
79 // pre bundle profile
80 constexpr const char* DEFAULT_PRE_BUNDLE_ROOT_DIR = "/system";
81 constexpr const char* PRODUCT_SUFFIX = "/etc/app";
82 constexpr const char* MODULE_UPDATE_PRODUCT_SUFFIX = "/etc/app/module_update";
83 constexpr const char* INSTALL_LIST_CONFIG = "/install_list.json";
84 constexpr const char* APP_SERVICE_FWK_INSTALL_LIST_CONFIG = "/app_service_fwk_install_list.json";
85 constexpr const char* UNINSTALL_LIST_CONFIG = "/uninstall_list.json";
86 constexpr const char* INSTALL_LIST_CAPABILITY_CONFIG = "/install_list_capability.json";
87 constexpr const char* EXTENSION_TYPE_LIST_CONFIG = "/extension_type_config.json";
88 constexpr const char* SHARED_BUNDLES_INSTALL_LIST_CONFIG = "/shared_bundles_install_list.json";
89 constexpr const char* SYSTEM_RESOURCES_APP_PATH = "/system/app/ohos.global.systemres";
90 constexpr const char* QUICK_FIX_APP_PATH = "/data/update/quickfix/app/temp/cold";
91 constexpr const char* SYSTEM_BUNDLE_PATH = "/internal";
92 constexpr const char* RESTOR_BUNDLE_NAME_LIST = "list";
93 constexpr const char* QUICK_FIX_APP_RECOVER_FILE = "/data/update/quickfix/app/temp/quickfix_app_recover.json";
94 constexpr const char* INNER_UNDER_LINE = "_";
95 constexpr const char* SYSTEM_RESOURCES_APP = "ohos.global.systemres";
96 constexpr const char* FOUNDATION_PROCESS_NAME = "foundation";
97 constexpr int32_t SCENE_ID_OTA_INSTALL = 3;
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 std::vector<std::string> bundleNameList_;
106 
107 #ifdef STORAGE_SERVICE_ENABLE
108 #ifdef QUOTA_PARAM_SET_ENABLE
109 const std::string SYSTEM_PARAM_ATOMICSERVICE_DATASIZE_THRESHOLD =
110     "persist.sys.bms.aging.policy.atomicservice.datasize.threshold";
111 const int32_t THRESHOLD_VAL_LEN = 20;
112 #endif // QUOTA_PARAM_SET_ENABLE
113 const int32_t STORAGE_MANAGER_MANAGER_ID = 5003;
114 #endif // STORAGE_SERVICE_ENABLE
115 const int32_t ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET = 200;
116 
MoveTempPath(const std::vector<std::string> & fromPaths,const std::string & bundleName,std::vector<std::string> & toPaths)117 void MoveTempPath(const std::vector<std::string> &fromPaths,
118     const std::string &bundleName, std::vector<std::string> &toPaths)
119 {
120     std::string tempDir =
121         ServiceConstants::HAP_COPY_PATH + ServiceConstants::PATH_SEPARATOR + TEMP_PREFIX + bundleName;
122     if (!BundleUtil::CreateDir(tempDir)) {
123         LOG_E(BMS_TAG_DEFAULT, "create tempdir failed %{public}s", tempDir.c_str());
124         return;
125     }
126 
127     int32_t hapIndex = 0;
128     for (const auto &path : fromPaths) {
129         auto toPath = tempDir + ServiceConstants::PATH_SEPARATOR + MODULE_PREFIX
130             + std::to_string(hapIndex) + ServiceConstants::INSTALL_FILE_SUFFIX;
131         hapIndex++;
132         if (InstalldClient::GetInstance()->MoveFile(path, toPath) != ERR_OK) {
133             LOG_W(BMS_TAG_DEFAULT, "move from %{public}s to %{public}s failed", path.c_str(), toPath.c_str());
134             continue;
135         }
136 
137         toPaths.emplace_back(toPath);
138     }
139 }
140 
141 class InnerReceiverImpl : public StatusReceiverHost {
142 public:
143     InnerReceiverImpl() = default;
144     virtual ~InnerReceiverImpl() override = default;
145 
SetBundleName(const std::string & bundleName)146     void SetBundleName(const std::string &bundleName)
147     {
148         bundleName_ = bundleName;
149     }
150 
OnStatusNotify(const int progress)151     virtual void OnStatusNotify(const int progress) override {}
OnFinished(const int32_t resultCode,const std::string & resultMsg)152     virtual void OnFinished(
153         const int32_t resultCode, const std::string &resultMsg) override
154     {
155         if (bundleName_.empty()) {
156             LOG_D(BMS_TAG_DEFAULT, "bundleName_ is empty");
157             return;
158         }
159 
160         std::string tempDir = ServiceConstants::HAP_COPY_PATH
161             + ServiceConstants::PATH_SEPARATOR + TEMP_PREFIX + bundleName_;
162         LOG_D(BMS_TAG_DEFAULT, "delete tempDir %{public}s", tempDir.c_str());
163         BundleUtil::DeleteDir(tempDir);
164     }
165 
166 private:
167     std::string bundleName_;
168 };
169 }
170 
BMSEventHandler()171 BMSEventHandler::BMSEventHandler()
172 {
173     LOG_D(BMS_TAG_DEFAULT, "instance is created");
174 }
175 
~BMSEventHandler()176 BMSEventHandler::~BMSEventHandler()
177 {
178     LOG_D(BMS_TAG_DEFAULT, "instance is destroyed");
179 }
180 
BmsStartEvent()181 void BMSEventHandler::BmsStartEvent()
182 {
183     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler BmsStartEvent start");
184     BeforeBmsStart();
185     OnBmsStarting();
186     AfterBmsStart();
187     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler BmsStartEvent end");
188 }
189 
BeforeBmsStart()190 void BMSEventHandler::BeforeBmsStart()
191 {
192     needNotifyBundleScanStatus_ = false;
193     if (!BundlePermissionMgr::Init()) {
194         LOG_W(BMS_TAG_DEFAULT, "BundlePermissionMgr::Init failed");
195     }
196 
197     EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_START);
198 }
199 
OnBmsStarting()200 void BMSEventHandler::OnBmsStarting()
201 {
202     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler OnBmsStarting start");
203     // Judge whether there is install info in the persistent Db
204     if (LoadInstallInfosFromDb()) {
205         LOG_I(BMS_TAG_DEFAULT, "OnBmsStarting Load install info from db success");
206         BundleRebootStartEvent();
207         return;
208     }
209 
210     // If the preInstall infos does not exist in preInstall db,
211     // all preInstall directory applications will be reinstalled.
212     if (!LoadAllPreInstallBundleInfos()) {
213         LOG_E(BMS_TAG_DEFAULT, "OnBmsStarting Load all preInstall bundleInfos failed");
214         needRebootOta_ = true;
215     }
216 
217     /* Guard against install infos lossed strategy.
218      * 1. Scan user data dir
219      *   1.1. If no data, first boot.
220      *   1.2. If has data, but parse data to InnerBundleUserInfos failed,
221      *        reInstall all app from install dir and preInstall dir
222      *   1.3. If has data and parse data to InnerBundleUserInfos success, goto 2
223      * 2. Scan installDir include common install dir and preInstall dir
224      *    And the parse the hap to InnerBundleInfos
225      * 3. Combine InnerBundleInfos and InnerBundleUserInfos to cache and db
226      * 4. According to needRebootOta determine whether OTA detection is required
227      */
228     ResultCode resultCode = GuardAgainstInstallInfosLossedStrategy();
229     switch (resultCode) {
230         case ResultCode::RECOVER_OK: {
231             LOG_I(BMS_TAG_DEFAULT, "OnBmsStarting Guard against install infos lossed strategy take effect");
232             if (needRebootOta_) {
233                 BundleRebootStartEvent();
234             } else {
235                 needNotifyBundleScanStatus_ = true;
236             }
237 
238             break;
239         }
240         case ResultCode::REINSTALL_OK: {
241             LOG_I(BMS_TAG_DEFAULT, "OnBmsStarting ReInstall all haps");
242             needNotifyBundleScanStatus_ = true;
243             break;
244         }
245         case ResultCode::NO_INSTALLED_DATA: {
246             // First boot
247             LOG_I(BMS_TAG_DEFAULT, "OnBmsStarting first boot");
248             BundleBootStartEvent();
249             break;
250         }
251         default:
252             LOG_E(BMS_TAG_DEFAULT, "System internal error, install informations missing");
253             break;
254     }
255 
256     SaveSystemFingerprint();
257     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler OnBmsStarting end");
258 }
259 
AfterBmsStart()260 void BMSEventHandler::AfterBmsStart()
261 {
262     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler AfterBmsStart start");
263 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
264     DelayedSingleton<QuickFixBootScanner>::GetInstance()->ProcessQuickFixBootUp();
265 #endif
266     DelayedSingleton<BundleMgrService>::GetInstance()->CheckAllUser();
267     SetAllInstallFlag();
268     HandleSceneBoard();
269     DelayedSingleton<BundleMgrService>::GetInstance()->RegisterService();
270     EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_END);
271     ClearCache();
272     if (needNotifyBundleScanStatus_) {
273         DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
274     }
275     ListeningUserUnlocked();
276     RemoveUnreservedSandbox();
277     DelayedSingleton<BundleMgrService>::GetInstance()->RegisterChargeIdleListener();
278     BundleResourceHelper::RegisterCommonEventSubscriber();
279     BundleResourceHelper::RegisterConfigurationObserver();
280     ProcessCheckAppEl1Dir();
281     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler AfterBmsStart end");
282 }
283 
ClearCache()284 void BMSEventHandler::ClearCache()
285 {
286     hapParseInfoMap_.clear();
287     loadExistData_.clear();
288     hasLoadAllPreInstallBundleInfosFromDb_ = false;
289 }
290 
LoadInstallInfosFromDb()291 bool BMSEventHandler::LoadInstallInfosFromDb()
292 {
293     LOG_I(BMS_TAG_DEFAULT, "Load install infos from db");
294     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
295     if (dataMgr == nullptr) {
296         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
297         return false;
298     }
299 
300     return dataMgr->LoadDataFromPersistentStorage();
301 }
302 
BundleBootStartEvent()303 void BMSEventHandler::BundleBootStartEvent()
304 {
305     EventReport::SendCpuSceneEvent(FOUNDATION_PROCESS_NAME, SCENE_ID_OTA_INSTALL);
306     OnBundleBootStart(Constants::DEFAULT_USERID);
307 #ifdef CHECK_ELDIR_ENABLED
308     UpdateOtaFlag(OTAFlag::CHECK_ELDIR);
309 #endif
310     UpdateOtaFlag(OTAFlag::CHECK_LOG_DIR);
311     UpdateOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR);
312     UpdateOtaFlag(OTAFlag::CHECK_PREINSTALL_DATA);
313     UpdateOtaFlag(OTAFlag::CHECK_SHADER_CAHCE_DIR);
314     UpdateOtaFlag(OTAFlag::CHECK_CLOUD_SHADER_DIR);
315     UpdateOtaFlag(OTAFlag::CHECK_BACK_UP_DIR);
316     UpdateOtaFlag(OTAFlag::CHECK_RECOVERABLE_APPLICATION_INFO);
317     PerfProfile::GetInstance().Dump();
318 }
319 
BundleRebootStartEvent()320 void BMSEventHandler::BundleRebootStartEvent()
321 {
322 #ifdef USE_PRE_BUNDLE_PROFILE
323     if (LoadPreInstallProFile()) {
324         UpdateAllPrivilegeCapability();
325     }
326 #endif
327 
328     if (IsSystemUpgrade()) {
329         EventReport::SendCpuSceneEvent(FOUNDATION_PROCESS_NAME, SCENE_ID_OTA_INSTALL);
330         OnBundleRebootStart();
331         SaveSystemFingerprint();
332         AOTHandler::GetInstance().HandleOTA();
333     } else {
334         HandlePreInstallException();
335         ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, false);
336         ProcessRebootQuickFixUnInstallAndRecover(QUICK_FIX_APP_RECOVER_FILE);
337         CheckALLResourceInfo();
338     }
339     // need process main bundle status
340     BmsKeyEventMgr::ProcessMainBundleStatusFinally();
341 
342     needNotifyBundleScanStatus_ = true;
343 }
344 
GuardAgainstInstallInfosLossedStrategy()345 ResultCode BMSEventHandler::GuardAgainstInstallInfosLossedStrategy()
346 {
347     LOG_I(BMS_TAG_DEFAULT, "GuardAgainstInstallInfosLossedStrategy start");
348     // Check user path, and parse userData to InnerBundleUserInfo
349     std::map<std::string, std::vector<InnerBundleUserInfo>> innerBundleUserInfoMaps;
350     ScanResultCode scanResultCode = ScanAndAnalyzeUserDatas(innerBundleUserInfoMaps);
351     if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
352         LOG_E(BMS_TAG_DEFAULT, "Scan the user data directory failed");
353         return ResultCode::NO_INSTALLED_DATA;
354     }
355 
356     // When data exist, but parse all userinfo fails, reinstall all app.
357     // For example: the AT database is lost or others.
358     if (scanResultCode == ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED) {
359         // Reinstall all app from install dir
360         return ReInstallAllInstallDirApps();
361     }
362 
363     // When data exist and parse all userinfo success,
364     // it can be judged that some bundles has installed.
365     // Check install dir, and parse the hap in install dir to InnerBundleInfo
366     std::map<std::string, std::vector<InnerBundleInfo>> installInfos;
367     ScanAndAnalyzeInstallInfos(installInfos);
368     if (installInfos.empty()) {
369         LOG_E(BMS_TAG_DEFAULT, "check bundle path failed due to hap lossd or parse failed");
370         return ResultCode::SYSTEM_ERROR;
371     }
372 
373     // Combine InnerBundleInfo and InnerBundleUserInfo
374     if (!CombineBundleInfoAndUserInfo(installInfos, innerBundleUserInfoMaps)) {
375         LOG_E(BMS_TAG_DEFAULT, "System internal error");
376         return ResultCode::SYSTEM_ERROR;
377     }
378 
379     return ResultCode::RECOVER_OK;
380 }
381 
ScanAndAnalyzeUserDatas(std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)382 ScanResultCode BMSEventHandler::ScanAndAnalyzeUserDatas(
383     std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
384 {
385     ScanResultCode scanResultCode = ScanResultCode::SCAN_NO_DATA;
386     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
387     if (dataMgr == nullptr) {
388         LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
389         return scanResultCode;
390     }
391 
392     std::string baseDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[0];
393     std::vector<std::string> userIds;
394     if (!ScanDir(baseDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userIds)) {
395         LOG_D(BMS_TAG_DEFAULT, "Check the base user directory(%{public}s) failed", baseDataDir.c_str());
396         return scanResultCode;
397     }
398 
399     for (const auto &userId : userIds) {
400         int32_t userIdInt = Constants::INVALID_USERID;
401         if (!StrToInt(userId, userIdInt)) {
402             LOG_E(BMS_TAG_DEFAULT, "UserId(%{public}s) strToInt failed", userId.c_str());
403             continue;
404         }
405 
406         dataMgr->AddUserId(userIdInt);
407         std::vector<std::string> userDataBundleNames;
408         std::string userDataDir = baseDataDir + ServiceConstants::PATH_SEPARATOR + userId + ServiceConstants::BASE;
409         if (!ScanDir(userDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userDataBundleNames)) {
410             LOG_D(BMS_TAG_DEFAULT, "Check the user installation directory(%{public}s) failed", userDataDir.c_str());
411             continue;
412         }
413 
414         for (const auto &userDataBundleName : userDataBundleNames) {
415             if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
416                 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED;
417             }
418 
419             if (AnalyzeUserData(userIdInt, userDataDir, userDataBundleName, userMaps)) {
420                 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_SUCCESS;
421             }
422         }
423     }
424 
425     return scanResultCode;
426 }
427 
AnalyzeUserData(int32_t userId,const std::string & userDataDir,const std::string & userDataBundleName,std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)428 bool BMSEventHandler::AnalyzeUserData(
429     int32_t userId, const std::string &userDataDir, const std::string &userDataBundleName,
430     std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
431 {
432     if (userDataDir.empty() || userDataBundleName.empty()) {
433         LOG_E(BMS_TAG_DEFAULT, "UserDataDir or UserDataBundleName is empty");
434         return false;
435     }
436 
437     std::string userDataBundlePath = userDataDir + userDataBundleName;
438     LOG_D(BMS_TAG_DEFAULT, "Analyze user data path(%{public}s)", userDataBundlePath.c_str());
439     FileStat fileStat;
440     if (InstalldClient::GetInstance()->GetFileStat(userDataBundlePath, fileStat) != ERR_OK) {
441         LOG_E(BMS_TAG_DEFAULT, "GetFileStat path(%{public}s) failed", userDataBundlePath.c_str());
442         return false;
443     }
444 
445     // It should be a bundleName dir
446     if (!fileStat.isDir) {
447         LOG_E(BMS_TAG_DEFAULT, "UserDataBundlePath(%{public}s) is not dir", userDataBundlePath.c_str());
448         return false;
449     }
450 
451     InnerBundleUserInfo innerBundleUserInfo;
452     innerBundleUserInfo.bundleName = userDataBundleName;
453     innerBundleUserInfo.bundleUserInfo.userId = userId;
454     innerBundleUserInfo.uid = fileStat.uid;
455     innerBundleUserInfo.gids.emplace_back(fileStat.gid);
456     innerBundleUserInfo.installTime = fileStat.lastModifyTime;
457     innerBundleUserInfo.updateTime = innerBundleUserInfo.installTime;
458     auto accessTokenIdEx = OHOS::Security::AccessToken::AccessTokenKit::GetHapTokenIDEx(
459         innerBundleUserInfo.bundleUserInfo.userId, userDataBundleName, 0);
460     if (accessTokenIdEx.tokenIdExStruct.tokenID == 0) {
461         LOG_E(BMS_TAG_DEFAULT, "get tokenId failed");
462         return false;
463     }
464 
465     innerBundleUserInfo.accessTokenId = accessTokenIdEx.tokenIdExStruct.tokenID;
466     innerBundleUserInfo.accessTokenIdEx = accessTokenIdEx.tokenIDEx;
467     auto userIter = userMaps.find(userDataBundleName);
468     if (userIter == userMaps.end()) {
469         std::vector<InnerBundleUserInfo> innerBundleUserInfos = { innerBundleUserInfo };
470         userMaps.emplace(userDataBundleName, innerBundleUserInfos);
471         return true;
472     }
473 
474     userMaps.at(userDataBundleName).emplace_back(innerBundleUserInfo);
475     return true;
476 }
477 
ReInstallAllInstallDirApps()478 ResultCode BMSEventHandler::ReInstallAllInstallDirApps()
479 {
480     // First, reinstall all preInstall app from preInstall dir
481     std::vector<std::string> preInstallDirs;
482     GetPreInstallDir(preInstallDirs);
483     for (const auto &preInstallDir : preInstallDirs) {
484         std::vector<std::string> filePaths { preInstallDir };
485         bool removable = IsPreInstallRemovable(preInstallDir);
486         if (!OTAInstallSystemBundle(
487             filePaths, Constants::AppType::SYSTEM_APP, removable)) {
488             LOG_E(BMS_TAG_DEFAULT, "Reinstall bundle(%{public}s) error", preInstallDir.c_str());
489             SavePreInstallException(preInstallDir);
490             continue;
491         }
492     }
493 
494     auto installer = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
495     if (installer == nullptr) {
496         LOG_E(BMS_TAG_DEFAULT, "installer is nullptr");
497         return ResultCode::SYSTEM_ERROR;
498     }
499 
500     // Second, reInstall all common install app from install dir
501     std::map<std::string, std::vector<std::string>> hapPathsMap;
502     ScanInstallDir(hapPathsMap);
503     for (const auto &hapPaths : hapPathsMap) {
504         InstallParam installParam;
505         installParam.userId = Constants::ALL_USERID;
506         installParam.installFlag = InstallFlag::REPLACE_EXISTING;
507         sptr<InnerReceiverImpl> innerReceiverImpl(new (std::nothrow) InnerReceiverImpl());
508         innerReceiverImpl->SetBundleName(hapPaths.first);
509         std::vector<std::string> tempHaps;
510         MoveTempPath(hapPaths.second, hapPaths.first, tempHaps);
511         installer->Install(tempHaps, installParam, innerReceiverImpl);
512     }
513 
514     return ResultCode::REINSTALL_OK;
515 }
516 
ScanAndAnalyzeInstallInfos(std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)517 void BMSEventHandler::ScanAndAnalyzeInstallInfos(
518     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
519 {
520     // Scan the installed directory
521     std::map<std::string, std::vector<std::string>> hapPathsMap;
522     ScanInstallDir(hapPathsMap);
523     AnalyzeHaps(false, hapPathsMap, installInfos);
524 
525     // Scan preBundle directory
526     std::vector<std::string> preInstallDirs;
527     GetPreInstallDir(preInstallDirs);
528     AnalyzeHaps(true, preInstallDirs, installInfos);
529 }
530 
ScanInstallDir(std::map<std::string,std::vector<std::string>> & hapPathsMap)531 void BMSEventHandler::ScanInstallDir(
532     std::map<std::string, std::vector<std::string>> &hapPathsMap)
533 {
534     LOG_D(BMS_TAG_DEFAULT, "Scan the installed directory start");
535     std::vector<std::string> bundleNameList;
536     if (!ScanDir(Constants::BUNDLE_CODE_DIR, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, bundleNameList)) {
537         LOG_E(BMS_TAG_DEFAULT, "Check the bundle directory(%{public}s) failed", Constants::BUNDLE_CODE_DIR);
538         return;
539     }
540 
541     for (const auto &bundleName : bundleNameList) {
542         std::vector<std::string> hapPaths;
543         auto appCodePath = Constants::BUNDLE_CODE_DIR + ServiceConstants::PATH_SEPARATOR + bundleName;
544         if (!ScanDir(appCodePath, ScanMode::SUB_FILE_FILE, ResultMode::ABSOLUTE_PATH, hapPaths)) {
545             LOG_E(BMS_TAG_DEFAULT, "Scan the appCodePath(%{public}s) failed", appCodePath.c_str());
546             continue;
547         }
548 
549         if (hapPaths.empty()) {
550             LOG_D(BMS_TAG_DEFAULT, "The directory(%{public}s) scan result is empty", appCodePath.c_str());
551             continue;
552         }
553 
554         std::vector<std::string> checkHapPaths = CheckHapPaths(hapPaths);
555         hapPathsMap.emplace(bundleName, checkHapPaths);
556     }
557 
558     LOG_D(BMS_TAG_DEFAULT, "Scan the installed directory end");
559 }
560 
CheckHapPaths(const std::vector<std::string> & hapPaths)561 std::vector<std::string> BMSEventHandler::CheckHapPaths(
562     const std::vector<std::string> &hapPaths)
563 {
564     std::vector<std::string> checkHapPaths;
565     for (const auto &hapPath : hapPaths) {
566         if (!BundleUtil::CheckFileType(hapPath, ServiceConstants::INSTALL_FILE_SUFFIX)) {
567             LOG_E(BMS_TAG_DEFAULT, "Check hapPath(%{public}s) failed", hapPath.c_str());
568             continue;
569         }
570 
571         checkHapPaths.emplace_back(hapPath);
572     }
573 
574     return checkHapPaths;
575 }
576 
GetPreInstallRootDirList(std::vector<std::string> & rootDirList)577 void BMSEventHandler::GetPreInstallRootDirList(std::vector<std::string> &rootDirList)
578 {
579 #ifdef CONFIG_POLOCY_ENABLE
580     auto cfgDirList = GetCfgDirList();
581     if (cfgDirList != nullptr) {
582         for (const auto &cfgDir : cfgDirList->paths) {
583             if (cfgDir == nullptr) {
584                 continue;
585             }
586 
587             LOG_NOFUNC_I(BMS_TAG_DEFAULT, "GetPreInstallRootDirList cfgDir: %{public}s", cfgDir);
588             rootDirList.emplace_back(cfgDir);
589         }
590 
591         FreeCfgDirList(cfgDirList);
592     }
593 #endif
594     bool ret = std::find(
595         rootDirList.begin(), rootDirList.end(), DEFAULT_PRE_BUNDLE_ROOT_DIR) != rootDirList.end();
596     if (!ret) {
597         rootDirList.emplace_back(DEFAULT_PRE_BUNDLE_ROOT_DIR);
598     }
599 }
600 
ClearPreInstallCache()601 void BMSEventHandler::ClearPreInstallCache()
602 {
603     if (!hasLoadPreInstallProFile_) {
604         return;
605     }
606 
607     installList_.clear();
608     uninstallList_.clear();
609     systemHspList_.clear();
610     installListCapabilities_.clear();
611     extensiontype_.clear();
612     hasLoadPreInstallProFile_ = false;
613 }
614 
LoadPreInstallProFile()615 bool BMSEventHandler::LoadPreInstallProFile()
616 {
617     if (hasLoadPreInstallProFile_) {
618         return !installList_.empty();
619     }
620 
621     std::vector<std::string> rootDirList;
622     GetPreInstallRootDirList(rootDirList);
623     if (rootDirList.empty()) {
624         LOG_E(BMS_TAG_DEFAULT, "dirList is empty");
625         return false;
626     }
627 
628     for (const auto &rootDir : rootDirList) {
629         ParsePreBundleProFile(rootDir + PRODUCT_SUFFIX);
630         ParsePreBundleProFile(rootDir + MODULE_UPDATE_PRODUCT_SUFFIX);
631     }
632 
633     hasLoadPreInstallProFile_ = true;
634     return !installList_.empty();
635 }
636 
HasPreInstallProfile()637 bool BMSEventHandler::HasPreInstallProfile()
638 {
639     return !installList_.empty();
640 }
641 
ParsePreBundleProFile(const std::string & dir)642 void BMSEventHandler::ParsePreBundleProFile(const std::string &dir)
643 {
644     BundleParser bundleParser;
645     bundleParser.ParsePreInstallConfig(
646         dir + INSTALL_LIST_CONFIG, installList_);
647     bundleParser.ParsePreInstallConfig(
648         dir + APP_SERVICE_FWK_INSTALL_LIST_CONFIG, systemHspList_);
649     bundleParser.ParsePreUnInstallConfig(
650         dir + UNINSTALL_LIST_CONFIG, uninstallList_);
651     bundleParser.ParsePreInstallAbilityConfig(
652         dir + INSTALL_LIST_CAPABILITY_CONFIG, installListCapabilities_);
653     bundleParser.ParseExtTypeConfig(
654         dir + EXTENSION_TYPE_LIST_CONFIG, extensiontype_);
655     bundleParser.ParsePreInstallConfig(
656         dir + SHARED_BUNDLES_INSTALL_LIST_CONFIG, installList_);
657 }
658 
GetPreInstallDir(std::vector<std::string> & bundleDirs)659 void BMSEventHandler::GetPreInstallDir(std::vector<std::string> &bundleDirs)
660 {
661 #ifdef USE_PRE_BUNDLE_PROFILE
662     if (LoadPreInstallProFile()) {
663         GetPreInstallDirFromLoadProFile(bundleDirs);
664         return;
665     }
666 #endif
667 
668     GetPreInstallDirFromScan(bundleDirs);
669 }
670 
GetPreInstallDirFromLoadProFile(std::vector<std::string> & bundleDirs)671 void BMSEventHandler::GetPreInstallDirFromLoadProFile(std::vector<std::string> &bundleDirs)
672 {
673     for (const auto &installInfo : installList_) {
674         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
675             LOG_W(BMS_TAG_DEFAULT, "bundle(%{public}s) not allowed installed", installInfo.bundleDir.c_str());
676             continue;
677         }
678 
679         bundleDirs.emplace_back(installInfo.bundleDir);
680     }
681 }
682 
GetPreInstallDirFromScan(std::vector<std::string> & bundleDirs)683 void BMSEventHandler::GetPreInstallDirFromScan(std::vector<std::string> &bundleDirs)
684 {
685     std::list<std::string> scanbundleDirs;
686     GetBundleDirFromScan(scanbundleDirs);
687     std::copy(scanbundleDirs.begin(), scanbundleDirs.end(), std::back_inserter(bundleDirs));
688 }
689 
AnalyzeHaps(bool isPreInstallApp,const std::map<std::string,std::vector<std::string>> & hapPathsMap,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)690 void BMSEventHandler::AnalyzeHaps(
691     bool isPreInstallApp,
692     const std::map<std::string, std::vector<std::string>> &hapPathsMap,
693     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
694 {
695     for (const auto &hapPaths : hapPathsMap) {
696         AnalyzeHaps(isPreInstallApp, hapPaths.second, installInfos);
697     }
698 }
699 
AnalyzeHaps(bool isPreInstallApp,const std::vector<std::string> & bundleDirs,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)700 void BMSEventHandler::AnalyzeHaps(
701     bool isPreInstallApp,
702     const std::vector<std::string> &bundleDirs,
703     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
704 {
705     for (const auto &bundleDir : bundleDirs) {
706         std::unordered_map<std::string, InnerBundleInfo> hapInfos;
707         if (!CheckAndParseHapFiles(bundleDir, isPreInstallApp, hapInfos) || hapInfos.empty()) {
708             LOG_E(BMS_TAG_DEFAULT, "Parse bundleDir(%{public}s) failed", bundleDir.c_str());
709             continue;
710         }
711 
712         CollectInstallInfos(hapInfos, installInfos);
713     }
714 }
715 
CollectInstallInfos(const std::unordered_map<std::string,InnerBundleInfo> & hapInfos,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)716 void BMSEventHandler::CollectInstallInfos(
717     const std::unordered_map<std::string, InnerBundleInfo> &hapInfos,
718     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
719 {
720     for (const auto &hapInfoIter : hapInfos) {
721         auto bundleName = hapInfoIter.second.GetBundleName();
722         if (installInfos.find(bundleName) == installInfos.end()) {
723             std::vector<InnerBundleInfo> innerBundleInfos { hapInfoIter.second };
724             installInfos.emplace(bundleName, innerBundleInfos);
725             continue;
726         }
727 
728         installInfos.at(bundleName).emplace_back(hapInfoIter.second);
729     }
730 }
731 
CombineBundleInfoAndUserInfo(const std::map<std::string,std::vector<InnerBundleInfo>> & installInfos,const std::map<std::string,std::vector<InnerBundleUserInfo>> & userInfoMaps)732 bool BMSEventHandler::CombineBundleInfoAndUserInfo(
733     const std::map<std::string, std::vector<InnerBundleInfo>> &installInfos,
734     const std::map<std::string, std::vector<InnerBundleUserInfo>> &userInfoMaps)
735 {
736     LOG_D(BMS_TAG_DEFAULT, "Combine code information and user data start");
737     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
738     if (dataMgr == nullptr) {
739         LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
740         return false;
741     }
742 
743     if (installInfos.empty() || userInfoMaps.empty()) {
744         LOG_E(BMS_TAG_DEFAULT, "bundleInfos or userInfos is empty");
745         return false;
746     }
747 
748     for (auto hasInstallInfo : installInfos) {
749         auto bundleName = hasInstallInfo.first;
750         auto userIter = userInfoMaps.find(bundleName);
751         if (userIter == userInfoMaps.end()) {
752             LOG_E(BMS_TAG_DEFAULT, "User data directory missing with bundle %{public}s ", bundleName.c_str());
753             needRebootOta_ = true;
754             continue;
755         }
756 
757         for (auto &info : hasInstallInfo.second) {
758             SaveInstallInfoToCache(info);
759         }
760 
761         for (const auto &userInfo : userIter->second) {
762             dataMgr->AddInnerBundleUserInfo(bundleName, userInfo);
763         }
764     }
765 
766     // Parsing uid, gids and other user information
767     dataMgr->RestoreUidAndGid();
768     // Load all bundle state data from jsonDb
769     dataMgr->LoadAllBundleStateDataFromJsonDb();
770     LOG_D(BMS_TAG_DEFAULT, "Combine code information and user data end");
771     return true;
772 }
773 
SaveInstallInfoToCache(InnerBundleInfo & info)774 void BMSEventHandler::SaveInstallInfoToCache(InnerBundleInfo &info)
775 {
776     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
777     if (dataMgr == nullptr) {
778         LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
779         return;
780     }
781 
782     auto bundleName = info.GetBundleName();
783     auto appCodePath = Constants::BUNDLE_CODE_DIR + ServiceConstants::PATH_SEPARATOR + bundleName;
784     info.SetAppCodePath(appCodePath);
785 
786     std::string dataBaseDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1]
787         + ServiceConstants::DATABASE + bundleName;
788     info.SetAppDataBaseDir(dataBaseDir);
789 
790     auto moduleDir = info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR + info.GetCurrentModulePackage();
791     info.AddModuleSrcDir(moduleDir);
792     info.AddModuleResPath(moduleDir);
793 
794     bool bundleExist = false;
795     InnerBundleInfo dbInfo;
796     {
797         auto &mtx = dataMgr->GetBundleMutex(bundleName);
798         std::lock_guard lock { mtx };
799         bundleExist = dataMgr->GetInnerBundleInfo(bundleName, dbInfo);
800         if (bundleExist) {
801             dataMgr->EnableBundle(bundleName);
802         }
803     }
804 
805     if (!bundleExist) {
806         dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_START);
807         if (!dataMgr->AddInnerBundleInfo(bundleName, info)) {
808             LOG_E(BMS_TAG_DEFAULT, "add bundle %{public}s failed", bundleName.c_str());
809             dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_FAIL);
810             return;
811         }
812         dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS);
813         return;
814     }
815 
816     auto& hapModuleName = info.GetCurModuleName();
817     std::vector<std::string> dbModuleNames;
818     dbInfo.GetModuleNames(dbModuleNames);
819     auto iter = std::find(dbModuleNames.begin(), dbModuleNames.end(), hapModuleName);
820     if (iter != dbModuleNames.end()) {
821         LOG_E(BMS_TAG_DEFAULT, "module(%{public}s) has install", hapModuleName.c_str());
822         return;
823     }
824 
825     dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_START);
826     dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_SUCCESS);
827     dataMgr->AddNewModuleInfo(bundleName, info, dbInfo);
828 }
829 
ScanDir(const std::string & dir,ScanMode scanMode,ResultMode resultMode,std::vector<std::string> & resultList)830 bool BMSEventHandler::ScanDir(
831     const std::string& dir, ScanMode scanMode, ResultMode resultMode, std::vector<std::string> &resultList)
832 {
833     LOG_D(BMS_TAG_DEFAULT, "Scan the directory(%{public}s) start", dir.c_str());
834     ErrCode result = InstalldClient::GetInstance()->ScanDir(dir, scanMode, resultMode, resultList);
835     if (result != ERR_OK) {
836         LOG_E(BMS_TAG_DEFAULT, "Scan the directory(%{public}s) failed", dir.c_str());
837         return false;
838     }
839 
840     return true;
841 }
842 
OnBundleBootStart(int32_t userId)843 void BMSEventHandler::OnBundleBootStart(int32_t userId)
844 {
845 #ifdef USE_PRE_BUNDLE_PROFILE
846     if (LoadPreInstallProFile()) {
847         LOG_I(BMS_TAG_DEFAULT, "Process boot bundle install from pre bundle proFile for userId:%{public}d", userId);
848         InnerProcessBootSystemHspInstall();
849         InnerProcessBootPreBundleProFileInstall(userId);
850         ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, true);
851         ProcessRebootQuickFixUnInstallAndRecover(QUICK_FIX_APP_RECOVER_FILE);
852         return;
853     }
854 #else
855     ProcessBootBundleInstallFromScan(userId);
856 #endif
857 }
858 
ProcessBootBundleInstallFromScan(int32_t userId)859 void BMSEventHandler::ProcessBootBundleInstallFromScan(int32_t userId)
860 {
861     LOG_D(BMS_TAG_DEFAULT, "Process boot bundle install from scan");
862     std::list<std::string> bundleDirs;
863     GetBundleDirFromScan(bundleDirs);
864     for (auto item : bundleDirs) {
865         ProcessSystemBundleInstall(item, Constants::AppType::SYSTEM_APP, userId);
866     }
867 }
868 
GetBundleDirFromScan(std::list<std::string> & bundleDirs)869 void BMSEventHandler::GetBundleDirFromScan(std::list<std::string> &bundleDirs)
870 {
871     std::vector<std::string> rootDirList;
872     GetPreInstallRootDirList(rootDirList);
873     if (rootDirList.empty()) {
874         LOG_E(BMS_TAG_DEFAULT, "rootDirList is empty");
875         return;
876     }
877 
878     for (const auto &rootDir : rootDirList) {
879         ProcessScanDir(rootDir + APP_SUFFIX, bundleDirs);
880     }
881 
882     auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), SYSTEM_RESOURCES_APP_PATH);
883     if (iter != bundleDirs.end()) {
884         bundleDirs.erase(iter);
885         bundleDirs.insert(bundleDirs.begin(), SYSTEM_RESOURCES_APP_PATH);
886     }
887 }
888 
ProcessScanDir(const std::string & dir,std::list<std::string> & bundleDirs)889 void BMSEventHandler::ProcessScanDir(const std::string &dir, std::list<std::string> &bundleDirs)
890 {
891     BundleScanner scanner;
892     std::list<std::string> bundleList = scanner.Scan(dir);
893     for (auto item : bundleList) {
894         auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), item);
895         if (iter == bundleDirs.end()) {
896             bundleDirs.push_back(item);
897         }
898     }
899 }
900 
InnerProcessBootSystemHspInstall()901 void BMSEventHandler::InnerProcessBootSystemHspInstall()
902 {
903     for (const auto &systemHspPath : systemHspList_) {
904         ProcessSystemHspInstall(systemHspPath);
905     }
906 }
907 
ProcessSystemHspInstall(const PreScanInfo & preScanInfo)908 void BMSEventHandler::ProcessSystemHspInstall(const PreScanInfo &preScanInfo)
909 {
910     LOG_I(BMS_TAG_DEFAULT, "Install systemHsp by bundleDir(%{public}s)", preScanInfo.bundleDir.c_str());
911     InstallParam installParam;
912     installParam.isPreInstallApp = true;
913     installParam.removable = false;
914     installParam.copyHapToInstallPath = false;
915     installParam.needSavePreInstallInfo = true;
916     installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
917     AppServiceFwkInstaller installer;
918     ErrCode ret = installer.Install({preScanInfo.bundleDir}, installParam);
919     if (ret != ERR_OK) {
920         LOG_W(BMS_TAG_DEFAULT, "Install systemHsp %{public}s error", preScanInfo.bundleDir.c_str());
921     }
922 }
923 
InnerProcessBootPreBundleProFileInstall(int32_t userId)924 void BMSEventHandler::InnerProcessBootPreBundleProFileInstall(int32_t userId)
925 {
926     // Sort in descending order of install priority
927     std::map<int32_t, std::vector<PreScanInfo>, std::greater<int32_t>> taskMap;
928     std::list<std::string> hspDirs;
929     for (const auto &installInfo : installList_) {
930         LOG_D(BMS_TAG_DEFAULT, "Inner process boot preBundle proFile install %{public}s",
931             installInfo.ToString().c_str());
932         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
933             LOG_I(BMS_TAG_DEFAULT, "bundle(%{public}s) not allowed installed when boot", installInfo.bundleDir.c_str());
934             continue;
935         }
936         if (installInfo.bundleDir.find(PRE_INSTALL_HSP_PATH) != std::string::npos) {
937             hspDirs.emplace_back(installInfo.bundleDir);
938         } else {
939             taskMap[installInfo.priority].emplace_back(installInfo);
940         }
941     }
942 
943     for (const auto &hspDir : hspDirs) {
944         ProcessSystemSharedBundleInstall(hspDir, Constants::AppType::SYSTEM_APP);
945     }
946 
947     if (taskMap.size() <= 0) {
948         LOG_W(BMS_TAG_DEFAULT, "taskMap is empty");
949         return;
950     }
951     AddTasks(taskMap, userId);
952 }
953 
AddTasks(const std::map<int32_t,std::vector<PreScanInfo>,std::greater<int32_t>> & taskMap,int32_t userId)954 void BMSEventHandler::AddTasks(
955     const std::map<int32_t, std::vector<PreScanInfo>, std::greater<int32_t>> &taskMap, int32_t userId)
956 {
957     for (const auto &tasks : taskMap) {
958         AddTaskParallel(tasks.first, tasks.second, userId);
959     }
960 }
961 
AddTaskParallel(int32_t taskPriority,const std::vector<PreScanInfo> & tasks,int32_t userId)962 void BMSEventHandler::AddTaskParallel(
963     int32_t taskPriority, const std::vector<PreScanInfo> &tasks, int32_t userId)
964 {
965     int32_t taskTotalNum = static_cast<int32_t>(tasks.size());
966     if (taskTotalNum <= 0) {
967         LOG_E(BMS_TAG_DEFAULT, "The number of tasks is empty");
968         return;
969     }
970 
971     auto bundleMgrService = DelayedSingleton<BundleMgrService>::GetInstance();
972     if (bundleMgrService == nullptr) {
973         LOG_E(BMS_TAG_DEFAULT, "bundleMgrService is nullptr");
974         return;
975     }
976 
977     sptr<BundleInstallerHost> installerHost = bundleMgrService->GetBundleInstaller();
978     if (installerHost == nullptr) {
979         LOG_E(BMS_TAG_DEFAULT, "installerHost is nullptr");
980         return;
981     }
982 
983     size_t threadsNum = static_cast<size_t>(installerHost->GetThreadsNum());
984     LOG_I(BMS_TAG_DEFAULT, "priority: %{public}d, tasks: %{public}zu, userId: %{public}d, threadsNum: %{public}zu",
985         taskPriority, tasks.size(), userId, threadsNum);
986     std::atomic_uint taskEndNum = 0;
987     std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
988     for (const auto &installInfo : tasks) {
989         if (installerHost->GetCurTaskNum() >= threadsNum) {
990             BMSEventHandler::ProcessSystemBundleInstall(installInfo, Constants::AppType::SYSTEM_APP, userId);
991             taskEndNum++;
992             continue;
993         }
994 
995         auto task = [installInfo, userId, taskTotalNum, &taskEndNum, &bundlePromise]() {
996             BMSEventHandler::ProcessSystemBundleInstall(installInfo, Constants::AppType::SYSTEM_APP, userId);
997             taskEndNum++;
998             if (bundlePromise && static_cast<int32_t>(taskEndNum) >= taskTotalNum) {
999                 bundlePromise->NotifyAllTasksExecuteFinished();
1000                 LOG_I(BMS_TAG_DEFAULT, "All tasks has executed and notify promise in priority(%{public}d)",
1001                     installInfo.priority);
1002             }
1003         };
1004 
1005         installerHost->AddTask(task, "BootStartInstall : " + installInfo.bundleDir);
1006     }
1007 
1008     if (static_cast<int32_t>(taskEndNum) < taskTotalNum) {
1009         bundlePromise->WaitForAllTasksExecute();
1010         LOG_I(BMS_TAG_DEFAULT, "Wait for all tasks execute in priority(%{public}d)", taskPriority);
1011     }
1012 }
1013 
ProcessSystemBundleInstall(const PreScanInfo & preScanInfo,Constants::AppType appType,int32_t userId)1014 void BMSEventHandler::ProcessSystemBundleInstall(
1015     const PreScanInfo &preScanInfo, Constants::AppType appType, int32_t userId)
1016 {
1017     LOG_D(BMS_TAG_DEFAULT, "Process system bundle install by bundleDir(%{public}s)", preScanInfo.bundleDir.c_str());
1018     InstallParam installParam;
1019     installParam.userId = userId;
1020     installParam.isPreInstallApp = true;
1021     installParam.SetKillProcess(false);
1022     installParam.needSendEvent = false;
1023     installParam.removable = preScanInfo.removable;
1024     installParam.needSavePreInstallInfo = true;
1025     installParam.copyHapToInstallPath = false;
1026     installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
1027     SystemBundleInstaller installer;
1028     ErrCode ret = installer.InstallSystemBundle(preScanInfo.bundleDir, installParam, appType);
1029     if (ret != ERR_OK && ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON) {
1030         LOG_W(BMS_TAG_DEFAULT, "Install System app:%{public}s error", preScanInfo.bundleDir.c_str());
1031         SavePreInstallException(preScanInfo.bundleDir);
1032     }
1033 }
1034 
ProcessSystemBundleInstall(const std::string & bundleDir,Constants::AppType appType,int32_t userId)1035 void BMSEventHandler::ProcessSystemBundleInstall(
1036     const std::string &bundleDir, Constants::AppType appType, int32_t userId)
1037 {
1038     LOG_I(BMS_TAG_DEFAULT, "Process system bundle install by bundleDir(%{public}s)", bundleDir.c_str());
1039     InstallParam installParam;
1040     installParam.userId = userId;
1041     installParam.isPreInstallApp = true;
1042     installParam.SetKillProcess(false);
1043     installParam.needSendEvent = false;
1044     installParam.removable = false;
1045     installParam.needSavePreInstallInfo = true;
1046     installParam.copyHapToInstallPath = false;
1047     installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
1048     SystemBundleInstaller installer;
1049     ErrCode ret = installer.InstallSystemBundle(bundleDir, installParam, appType);
1050     if (ret != ERR_OK && ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON) {
1051         LOG_W(BMS_TAG_DEFAULT, "Install System app:%{public}s error", bundleDir.c_str());
1052         SavePreInstallException(bundleDir);
1053     }
1054 }
1055 
ProcessSystemSharedBundleInstall(const std::string & sharedBundlePath,Constants::AppType appType)1056 void BMSEventHandler::ProcessSystemSharedBundleInstall(const std::string &sharedBundlePath, Constants::AppType appType)
1057 {
1058     LOG_I(BMS_TAG_DEFAULT, "Process system shared bundle by sharedBundlePath(%{public}s)", sharedBundlePath.c_str());
1059     InstallParam installParam;
1060     installParam.isPreInstallApp = true;
1061     installParam.SetKillProcess(false);
1062     installParam.needSendEvent = false;
1063     installParam.removable = false;
1064     installParam.needSavePreInstallInfo = true;
1065     installParam.sharedBundleDirPaths = {sharedBundlePath};
1066     installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
1067     SystemBundleInstaller installer;
1068     if (!installer.InstallSystemSharedBundle(installParam, false, appType)) {
1069         LOG_W(BMS_TAG_DEFAULT, "install system shared bundle: %{public}s error", sharedBundlePath.c_str());
1070     }
1071 }
1072 
SetAllInstallFlag() const1073 void BMSEventHandler::SetAllInstallFlag() const
1074 {
1075     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1076     if (dataMgr == nullptr) {
1077         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1078         return;
1079     }
1080 
1081     dataMgr->SetInitialUserFlag(true);
1082 }
1083 
OnBundleRebootStart()1084 void BMSEventHandler::OnBundleRebootStart()
1085 {
1086     ProcessRebootBundle();
1087 }
1088 
ProcessRebootBundle()1089 void BMSEventHandler::ProcessRebootBundle()
1090 {
1091     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler Process reboot bundle start");
1092     LoadAllPreInstallBundleInfos();
1093     BundleResourceHelper::DeleteNotExistResourceInfo();
1094     InnerProcessRebootUninstallWrongBundle();
1095     ProcessRebootBundleInstall();
1096     ProcessRebootBundleUninstall();
1097     ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, true);
1098     ProcessRebootQuickFixUnInstallAndRecover(QUICK_FIX_APP_RECOVER_FILE);
1099     ProcessBundleResourceInfo();
1100 #ifdef CHECK_ELDIR_ENABLED
1101     ProcessCheckAppDataDir();
1102 #endif
1103     ProcessCheckAppLogDir();
1104     ProcessCheckAppFileManagerDir();
1105     ProcessCheckPreinstallData();
1106     ProcessCheckShaderCacheDir();
1107     ProcessCheckCloudShaderDir();
1108     ProcessNewBackupDir();
1109     RefreshQuotaForAllUid();
1110     ProcessCheckRecoverableApplicationInfo();
1111     // Driver update may cause shader cache invalidity and need to be cleared
1112     CleanAllBundleShaderCache();
1113 }
1114 
CheckOtaFlag(OTAFlag flag,bool & result)1115 bool BMSEventHandler::CheckOtaFlag(OTAFlag flag, bool &result)
1116 {
1117     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1118     if (bmsPara == nullptr) {
1119         LOG_E(BMS_TAG_DEFAULT, "bmsPara is nullptr");
1120         return false;
1121     }
1122 
1123     std::string val;
1124     if (!bmsPara->GetBmsParam(OTA_FLAG, val)) {
1125         LOG_I(BMS_TAG_DEFAULT, "GetBmsParam OTA_FLAG failed");
1126         return false;
1127     }
1128 
1129     int32_t valInt = 0;
1130     if (!StrToInt(val, valInt)) {
1131         LOG_E(BMS_TAG_DEFAULT, "val(%{public}s) strToInt failed", val.c_str());
1132         return false;
1133     }
1134 
1135     result = static_cast<uint32_t>(flag) & static_cast<uint32_t>(valInt);
1136     return true;
1137 }
1138 
UpdateOtaFlag(OTAFlag flag)1139 bool BMSEventHandler::UpdateOtaFlag(OTAFlag flag)
1140 {
1141     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1142     if (bmsPara == nullptr) {
1143         LOG_E(BMS_TAG_DEFAULT, "bmsPara is nullptr");
1144         return false;
1145     }
1146 
1147     std::string val;
1148     if (!bmsPara->GetBmsParam(OTA_FLAG, val)) {
1149         LOG_I(BMS_TAG_DEFAULT, "GetBmsParam OTA_FLAG failed");
1150         return bmsPara->SaveBmsParam(OTA_FLAG, std::to_string(flag));
1151     }
1152 
1153     int32_t valInt = 0;
1154     if (!StrToInt(val, valInt)) {
1155         LOG_E(BMS_TAG_DEFAULT, "val(%{public}s) strToInt failed", val.c_str());
1156         return bmsPara->SaveBmsParam(OTA_FLAG, std::to_string(flag));
1157     }
1158 
1159     return bmsPara->SaveBmsParam(
1160         OTA_FLAG, std::to_string(static_cast<uint32_t>(flag) | static_cast<uint32_t>(valInt)));
1161 }
1162 
ProcessCheckAppDataDir()1163 void BMSEventHandler::ProcessCheckAppDataDir()
1164 {
1165     bool checkElDir = false;
1166     CheckOtaFlag(OTAFlag::CHECK_ELDIR, checkElDir);
1167     if (checkElDir) {
1168         LOG_I(BMS_TAG_DEFAULT, "Not need to check data dir due to has checked");
1169         return;
1170     }
1171 
1172     LOG_I(BMS_TAG_DEFAULT, "Need to check data dir");
1173     InnerProcessCheckAppDataDir();
1174     UpdateOtaFlag(OTAFlag::CHECK_ELDIR);
1175 }
1176 
InnerProcessCheckAppDataDir()1177 void BMSEventHandler::InnerProcessCheckAppDataDir()
1178 {
1179     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1180     if (dataMgr == nullptr) {
1181         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1182         return;
1183     }
1184 
1185     std::set<int32_t> userIds = dataMgr->GetAllUser();
1186     for (const auto &userId : userIds) {
1187         std::vector<BundleInfo> bundleInfos;
1188         if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, userId)) {
1189             LOG_W(BMS_TAG_DEFAULT, "UpdateAppDataDir GetAllBundleInfos failed");
1190             continue;
1191         }
1192 
1193         UpdateAppDataMgr::ProcessUpdateAppDataDir(
1194             userId, bundleInfos, ServiceConstants::DIR_EL3);
1195         UpdateAppDataMgr::ProcessUpdateAppDataDir(
1196             userId, bundleInfos, ServiceConstants::DIR_EL4);
1197     }
1198 }
1199 
ProcessCheckPreinstallData()1200 void BMSEventHandler::ProcessCheckPreinstallData()
1201 {
1202     bool checkPreinstallData = false;
1203     CheckOtaFlag(OTAFlag::CHECK_PREINSTALL_DATA, checkPreinstallData);
1204     if (checkPreinstallData) {
1205         LOG_I(BMS_TAG_DEFAULT, "Not need to check preinstall app data due to has checked");
1206         return;
1207     }
1208     LOG_I(BMS_TAG_DEFAULT, "Need to check preinstall data");
1209     InnerProcessCheckPreinstallData();
1210     UpdateOtaFlag(OTAFlag::CHECK_PREINSTALL_DATA);
1211 }
1212 
InnerProcessCheckPreinstallData()1213 void BMSEventHandler::InnerProcessCheckPreinstallData()
1214 {
1215     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1216     if (dataMgr == nullptr) {
1217         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1218         return;
1219     }
1220     std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
1221     for (auto &preInstallBundleInfo : preInstallBundleInfos) {
1222         BundleInfo bundleInfo;
1223         if (dataMgr->GetBundleInfo(preInstallBundleInfo.GetBundleName(),
1224             BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, Constants::ALL_USERID)) {
1225             preInstallBundleInfo.SetIconId(bundleInfo.applicationInfo.iconResource.id);
1226             preInstallBundleInfo.SetLabelId(bundleInfo.applicationInfo.labelResource.id);
1227             preInstallBundleInfo.SetModuleName(bundleInfo.applicationInfo.labelResource.moduleName);
1228             dataMgr->SavePreInstallBundleInfo(bundleInfo.name, preInstallBundleInfo);
1229             continue;
1230         }
1231         BundleMgrHostImpl impl;
1232         BundleInfo resultBundleInfo;
1233         auto preinstalledAppPaths = preInstallBundleInfo.GetBundlePaths();
1234         for (auto preinstalledAppPath: preinstalledAppPaths) {
1235             if (!impl.GetBundleArchiveInfo(preinstalledAppPath, GET_BUNDLE_DEFAULT, resultBundleInfo)) {
1236                 LOG_E(BMS_TAG_DEFAULT, "Get bundle archive info fail");
1237                 break;
1238             }
1239             preInstallBundleInfo.SetLabelId(resultBundleInfo.applicationInfo.labelResource.id);
1240             preInstallBundleInfo.SetIconId(resultBundleInfo.applicationInfo.iconResource.id);
1241             preInstallBundleInfo.SetModuleName(resultBundleInfo.applicationInfo.labelResource.moduleName);
1242             if (!bundleInfo.hapModuleInfos.empty() &&
1243                 resultBundleInfo.hapModuleInfos[0].moduleType == ModuleType::ENTRY) {
1244                 break;
1245             }
1246         }
1247         dataMgr->SavePreInstallBundleInfo(resultBundleInfo.name, preInstallBundleInfo);
1248     }
1249 }
1250 
ProcessCheckAppLogDir()1251 void BMSEventHandler::ProcessCheckAppLogDir()
1252 {
1253     bool checkLogDir = false;
1254     CheckOtaFlag(OTAFlag::CHECK_LOG_DIR, checkLogDir);
1255     if (checkLogDir) {
1256         LOG_I(BMS_TAG_DEFAULT, "Not need to check log dir due to has checked");
1257         return;
1258     }
1259     LOG_I(BMS_TAG_DEFAULT, "Need to check log dir");
1260     InnerProcessCheckAppLogDir();
1261     UpdateOtaFlag(OTAFlag::CHECK_LOG_DIR);
1262 }
1263 
InnerProcessCheckAppLogDir()1264 void BMSEventHandler::InnerProcessCheckAppLogDir()
1265 {
1266     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1267     if (dataMgr == nullptr) {
1268         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1269         return;
1270     }
1271     std::vector<BundleInfo> bundleInfos;
1272     if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, Constants::DEFAULT_USERID)) {
1273         LOG_E(BMS_TAG_DEFAULT, "GetAllBundleInfos failed");
1274         return;
1275     }
1276     UpdateAppDataMgr::ProcessUpdateAppLogDir(bundleInfos, Constants::DEFAULT_USERID);
1277 }
1278 
ProcessCheckAppFileManagerDir()1279 void BMSEventHandler::ProcessCheckAppFileManagerDir()
1280 {
1281     bool checkDir = false;
1282     CheckOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR, checkDir);
1283     if (checkDir) {
1284         LOG_I(BMS_TAG_DEFAULT, "Not need to check file manager dir due to has checked");
1285         return;
1286     }
1287     LOG_I(BMS_TAG_DEFAULT, "Need to check file manager dir");
1288     InnerProcessCheckAppFileManagerDir();
1289     UpdateOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR);
1290 }
1291 
InnerProcessCheckAppFileManagerDir()1292 void BMSEventHandler::InnerProcessCheckAppFileManagerDir()
1293 {
1294     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1295     if (dataMgr == nullptr) {
1296         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1297         return;
1298     }
1299     std::vector<BundleInfo> bundleInfos;
1300     if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, Constants::DEFAULT_USERID)) {
1301         LOG_E(BMS_TAG_DEFAULT, "GetAllBundleInfos failed");
1302         return;
1303     }
1304     UpdateAppDataMgr::ProcessFileManagerDir(bundleInfos, Constants::DEFAULT_USERID);
1305 }
1306 
ProcessCheckShaderCacheDir()1307 void BMSEventHandler::ProcessCheckShaderCacheDir()
1308 {
1309     bool checkShaderCache = false;
1310     CheckOtaFlag(OTAFlag::CHECK_SHADER_CAHCE_DIR, checkShaderCache);
1311     if (checkShaderCache) {
1312         LOG_I(BMS_TAG_DEFAULT, "Not need to check shader cache dir due to has checked");
1313         return;
1314     }
1315     LOG_I(BMS_TAG_DEFAULT, "Need to check shader cache dir");
1316     InnerProcessCheckShaderCacheDir();
1317     UpdateOtaFlag(OTAFlag::CHECK_SHADER_CAHCE_DIR);
1318 }
1319 
InnerProcessCheckShaderCacheDir()1320 void BMSEventHandler::InnerProcessCheckShaderCacheDir()
1321 {
1322     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1323     if (dataMgr == nullptr) {
1324         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1325         return;
1326     }
1327     std::vector<BundleInfo> bundleInfos;
1328     ErrCode res = dataMgr->GetBundleInfosV9(
1329         static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE), bundleInfos, Constants::ALL_USERID);
1330     if (res != ERR_OK) {
1331         LOG_E(BMS_TAG_DEFAULT, "GetAllBundleInfos failed");
1332         return;
1333     }
1334     for (const auto &bundleInfo : bundleInfos) {
1335         if (bundleInfo.name.empty()) {
1336             continue;
1337         }
1338         std::string shaderCachePath;
1339         shaderCachePath.append(ServiceConstants::SHADER_CACHE_PATH).append(bundleInfo.name);
1340         ErrCode res = InstalldClient::GetInstance()->Mkdir(shaderCachePath, S_IRWXU, bundleInfo.uid, bundleInfo.gid);
1341         if (res != ERR_OK) {
1342             LOG_I(BMS_TAG_DEFAULT, "create shader cache failed: %{public}s ", shaderCachePath.c_str());
1343         }
1344     }
1345 }
1346 
ProcessCheckCloudShaderDir()1347 void BMSEventHandler::ProcessCheckCloudShaderDir()
1348 {
1349     bool checkCloudShader = false;
1350     CheckOtaFlag(OTAFlag::CHECK_CLOUD_SHADER_DIR, checkCloudShader);
1351     if (checkCloudShader) {
1352         LOG_D(BMS_TAG_DEFAULT, "Not need to check cloud shader cache dir due to has checked");
1353         return;
1354     }
1355     LOG_D(BMS_TAG_DEFAULT, "Need to check cloud shader cache dir");
1356     InnerProcessCheckCloudShaderDir();
1357     UpdateOtaFlag(OTAFlag::CHECK_CLOUD_SHADER_DIR);
1358 }
1359 
ProcessNewBackupDir()1360 void BMSEventHandler::ProcessNewBackupDir()
1361 {
1362     bool checkBackup = false;
1363     CheckOtaFlag(OTAFlag::CHECK_BACK_UP_DIR, checkBackup);
1364     if (checkBackup) {
1365         LOG_D(BMS_TAG_DEFAULT, "Not need to check back up dir due to has checked");
1366         return;
1367     }
1368     LOG_I(BMS_TAG_DEFAULT, "Need to check back up dir");
1369     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1370     if (dataMgr == nullptr) {
1371         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1372         return;
1373     }
1374     std::set<int32_t> userIds = dataMgr->GetAllUser();
1375     for (const auto &userId : userIds) {
1376         if (userId == Constants::DEFAULT_USERID) {
1377             continue;
1378         }
1379         std::vector<BundleInfo> bundleInfos;
1380         if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, userId)) {
1381             LOG_W(BMS_TAG_DEFAULT, "ProcessNewBackupDir GetAllBundleInfos failed");
1382             continue;
1383         }
1384         UpdateAppDataMgr::ProcessNewBackupDir(bundleInfos, userId);
1385     }
1386     UpdateOtaFlag(OTAFlag::CHECK_BACK_UP_DIR);
1387 }
1388 
InnerProcessCheckCloudShaderDir()1389 void BMSEventHandler::InnerProcessCheckCloudShaderDir()
1390 {
1391     bool cloudExist = true;
1392     ErrCode result = InstalldClient::GetInstance()->IsExistDir(ServiceConstants::CLOUD_SHADER_PATH, cloudExist);
1393     if (result != ERR_OK) {
1394         LOG_W(BMS_TAG_DEFAULT, "IsExistDir failed, error is %{public}d", result);
1395         return;
1396     }
1397     if (cloudExist) {
1398         LOG_D(BMS_TAG_DEFAULT, "CLOUD_SHADER_PATH is exist");
1399         return;
1400     }
1401 
1402     const std::string bundleName = OHOS::system::GetParameter(ServiceConstants::CLOUD_SHADER_OWNER, "");
1403     if (bundleName.empty()) {
1404         return;
1405     }
1406 
1407     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1408     if (dataMgr == nullptr) {
1409         LOG_W(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1410         return;
1411     }
1412 
1413     BundleInfo info;
1414     auto hasBundleInstalled = dataMgr->GetBundleInfo(
1415         bundleName, BundleFlag::GET_BUNDLE_DEFAULT, info, Constants::ANY_USERID);
1416     if (!hasBundleInstalled) {
1417         LOG_D(BMS_TAG_DEFAULT, "Obtain bundleInfo failed, bundleName: %{public}s not exist", bundleName.c_str());
1418         return;
1419     }
1420 
1421     constexpr int32_t mode = (S_IRWXU | S_IXGRP | S_IXOTH);
1422     result = InstalldClient::GetInstance()->Mkdir(ServiceConstants::CLOUD_SHADER_PATH, mode, info.uid, info.gid);
1423     LOG_I(BMS_TAG_DEFAULT, "Create cloud shader cache result: %{public}d", result);
1424 }
1425 
ProcessCheckRecoverableApplicationInfo()1426 void BMSEventHandler::ProcessCheckRecoverableApplicationInfo()
1427 {
1428     bool hasCheck = false;
1429     CheckOtaFlag(OTAFlag::CHECK_RECOVERABLE_APPLICATION_INFO, hasCheck);
1430     if (hasCheck) {
1431         LOG_D(BMS_TAG_DEFAULT, "recoverable app info has checked");
1432         return;
1433     }
1434     LOG_D(BMS_TAG_DEFAULT, "Need to check recoverable app info");
1435     InnerProcessCheckRecoverableApplicationInfo();
1436     UpdateOtaFlag(OTAFlag::CHECK_RECOVERABLE_APPLICATION_INFO);
1437 }
1438 
InnerProcessCheckRecoverableApplicationInfo()1439 void BMSEventHandler::InnerProcessCheckRecoverableApplicationInfo()
1440 {
1441     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1442     if (dataMgr == nullptr) {
1443         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1444         return;
1445     }
1446     std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
1447     for (auto &preInstallBundleInfo : preInstallBundleInfos) {
1448         BundleInfo bundleInfo;
1449         if (dataMgr->GetBundleInfo(preInstallBundleInfo.GetBundleName(),
1450             BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, Constants::ALL_USERID)) {
1451             preInstallBundleInfo.SetSystemApp(bundleInfo.applicationInfo.isSystemApp);
1452             if (bundleInfo.isNewVersion) {
1453                 preInstallBundleInfo.SetBundleType(bundleInfo.applicationInfo.bundleType);
1454             } else if (!bundleInfo.hapModuleInfos.empty() &&
1455                 bundleInfo.hapModuleInfos[0].installationFree) {
1456                 preInstallBundleInfo.SetBundleType(BundleType::ATOMIC_SERVICE);
1457             }
1458             dataMgr->SavePreInstallBundleInfo(preInstallBundleInfo.GetBundleName(), preInstallBundleInfo);
1459             continue;
1460         }
1461         BundleMgrHostImpl impl;
1462         auto preinstalledAppPaths = preInstallBundleInfo.GetBundlePaths();
1463         for (auto preinstalledAppPath: preinstalledAppPaths) {
1464             BundleInfo archiveBundleInfo;
1465             if (!impl.GetBundleArchiveInfo(preinstalledAppPath, GET_BUNDLE_DEFAULT, archiveBundleInfo)) {
1466                 LOG_E(BMS_TAG_DEFAULT, "Get bundle archive info fail");
1467                 break;
1468             }
1469             preInstallBundleInfo.SetSystemApp(archiveBundleInfo.applicationInfo.isSystemApp);
1470             if (archiveBundleInfo.isNewVersion) {
1471                 preInstallBundleInfo.SetBundleType(archiveBundleInfo.applicationInfo.bundleType);
1472             } else if (!archiveBundleInfo.hapModuleInfos.empty() &&
1473                 archiveBundleInfo.hapModuleInfos[0].installationFree) {
1474                 preInstallBundleInfo.SetBundleType(BundleType::ATOMIC_SERVICE);
1475             }
1476             if (!archiveBundleInfo.hapModuleInfos.empty() &&
1477                 archiveBundleInfo.hapModuleInfos[0].moduleType == ModuleType::ENTRY) {
1478                 break;
1479             }
1480         }
1481         dataMgr->SavePreInstallBundleInfo(preInstallBundleInfo.GetBundleName(), preInstallBundleInfo);
1482     }
1483 }
1484 
SendToStorageQuota(const std::string & bundleName,const int32_t uid,const std::string & bundleDataDirPath,const int32_t limitSizeMb)1485 static void SendToStorageQuota(const std::string &bundleName, const int32_t uid,
1486     const std::string &bundleDataDirPath, const int32_t limitSizeMb)
1487 {
1488 #ifdef STORAGE_SERVICE_ENABLE
1489     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1490     if (!systemAbilityManager) {
1491         LOG_W(BMS_TAG_DEFAULT, "SendToStorageQuota, systemAbilityManager error");
1492         return;
1493     }
1494 
1495     auto remote = systemAbilityManager->CheckSystemAbility(STORAGE_MANAGER_MANAGER_ID);
1496     if (!remote) {
1497         LOG_W(BMS_TAG_DEFAULT, "SendToStorageQuota, CheckSystemAbility error");
1498         return;
1499     }
1500 
1501     auto proxy = iface_cast<StorageManager::IStorageManager>(remote);
1502     if (!proxy) {
1503         LOG_W(BMS_TAG_DEFAULT, "SendToStorageQuotactl, proxy get error");
1504         return;
1505     }
1506 
1507     int err = proxy->SetBundleQuota(bundleName, uid, bundleDataDirPath, limitSizeMb);
1508     if (err != ERR_OK) {
1509         LOG_W(BMS_TAG_DEFAULT, "SendToStorageQuota, SetBundleQuota error, err=%{public}d, uid=%{public}d", err, uid);
1510     }
1511 #endif // STORAGE_SERVICE_ENABLE
1512 }
1513 
PrepareBundleDirQuota(const std::string & bundleName,const int32_t uid,const std::string & bundleDataDirPath,const int32_t limitSize) const1514 void BMSEventHandler::PrepareBundleDirQuota(const std::string &bundleName, const int32_t uid,
1515     const std::string &bundleDataDirPath, const int32_t limitSize) const
1516 {
1517     if (limitSize == 0) {
1518         SendToStorageQuota(bundleName, uid, bundleDataDirPath, 0);
1519         return;
1520     }
1521     int32_t atomicserviceDatasizeThreshold = limitSize;
1522 #ifdef STORAGE_SERVICE_ENABLE
1523 #ifdef QUOTA_PARAM_SET_ENABLE
1524     char szAtomicDatasizeThresholdMb[THRESHOLD_VAL_LEN] = {0};
1525     int32_t ret = GetParameter(SYSTEM_PARAM_ATOMICSERVICE_DATASIZE_THRESHOLD.c_str(), "",
1526         szAtomicDatasizeThresholdMb, THRESHOLD_VAL_LEN);
1527     if (ret <= 0) {
1528         LOG_I(BMS_TAG_DEFAULT, "GetParameter failed");
1529     } else if (strcmp(szAtomicDatasizeThresholdMb, "") != 0) {
1530         atomicserviceDatasizeThreshold = atoi(szAtomicDatasizeThresholdMb);
1531         LOG_I(BMS_TAG_DEFAULT, "InstalldQuotaUtils init atomicserviceDataThreshold mb success");
1532     }
1533     if (atomicserviceDatasizeThreshold <= 0) {
1534         LOG_W(BMS_TAG_DEFAULT, "no need to prepare quota");
1535         return;
1536     }
1537 #endif // QUOTA_PARAM_SET_ENABLE
1538 #endif // STORAGE_SERVICE_ENABLE
1539     SendToStorageQuota(bundleName, uid, bundleDataDirPath, atomicserviceDatasizeThreshold);
1540 }
1541 
RefreshQuotaForAllUid()1542 void BMSEventHandler::RefreshQuotaForAllUid()
1543 {
1544     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1545     if (dataMgr == nullptr) {
1546         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1547         return;
1548     }
1549     std::map<std::string, InnerBundleInfo> infos = dataMgr->GetAllInnerBundleInfos();
1550     for (auto &infoPair : infos) {
1551         auto &info = infoPair.second;
1552         std::map<std::string, InnerBundleUserInfo> userInfos = info.GetInnerBundleUserInfos();
1553         for (auto &userInfoPair : userInfos) {
1554             auto &userInfo = userInfoPair.second;
1555             std::string bundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[0] +
1556                 ServiceConstants::PATH_SEPARATOR + std::to_string(userInfo.bundleUserInfo.userId) +
1557                 ServiceConstants::BASE + info.GetBundleName();
1558             if (info.GetApplicationBundleType() != BundleType::ATOMIC_SERVICE) {
1559                 PrepareBundleDirQuota(info.GetBundleName(), info.GetUid(userInfo.bundleUserInfo.userId),
1560                     bundleDataDir, 0);
1561             } else {
1562                 PrepareBundleDirQuota(info.GetBundleName(), info.GetUid(userInfo.bundleUserInfo.userId),
1563                     bundleDataDir, ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET);
1564             }
1565         }
1566     }
1567 }
1568 
LoadAllPreInstallBundleInfos()1569 bool BMSEventHandler::LoadAllPreInstallBundleInfos()
1570 {
1571     if (hasLoadAllPreInstallBundleInfosFromDb_) {
1572         LOG_I(BMS_TAG_DEFAULT, "Has load all preInstall bundleInfos from db");
1573         return true;
1574     }
1575 
1576     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1577     if (dataMgr == nullptr) {
1578         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1579         return false;
1580     }
1581 
1582     std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
1583     for (auto &iter : preInstallBundleInfos) {
1584         LOG_D(BMS_TAG_DEFAULT, "load preInstallBundleInfos: %{public}s ", iter.GetBundleName().c_str());
1585         loadExistData_.emplace(iter.GetBundleName(), iter);
1586     }
1587 
1588     hasLoadAllPreInstallBundleInfosFromDb_ = true;
1589     return !preInstallBundleInfos.empty();
1590 }
1591 
ProcessRebootBundleInstall()1592 void BMSEventHandler::ProcessRebootBundleInstall()
1593 {
1594     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler Process reboot bundle install start");
1595 #ifdef USE_PRE_BUNDLE_PROFILE
1596     if (LoadPreInstallProFile()) {
1597         ProcessReBootPreBundleProFileInstall();
1598         return;
1599     }
1600 #else
1601     ProcessRebootBundleInstallFromScan();
1602 #endif
1603 }
1604 
ProcessReBootPreBundleProFileInstall()1605 void BMSEventHandler::ProcessReBootPreBundleProFileInstall()
1606 {
1607     std::list<std::string> bundleDirs;
1608     std::list<std::string> sharedBundleDirs;
1609     for (const auto &installInfo : installList_) {
1610         LOG_I(BMS_TAG_DEFAULT, "Process reboot preBundle proFile install %{public}s", installInfo.ToString().c_str());
1611         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
1612             LOG_W(BMS_TAG_DEFAULT, "(%{public}s) not allowed installed when reboot", installInfo.bundleDir.c_str());
1613             continue;
1614         }
1615 
1616         if (installInfo.bundleDir.find(PRE_INSTALL_HSP_PATH) != std::string::npos) {
1617             LOG_I(BMS_TAG_DEFAULT, "found shared bundle path: %{public}s", installInfo.bundleDir.c_str());
1618             sharedBundleDirs.emplace_back(installInfo.bundleDir);
1619         } else {
1620             bundleDirs.emplace_back(installInfo.bundleDir);
1621         }
1622     }
1623 
1624     std::list<std::string> systemHspDirs;
1625     for (const auto &systemHspScanInfo : systemHspList_) {
1626         systemHspDirs.emplace_back(systemHspScanInfo.bundleDir);
1627     }
1628 
1629     InnerProcessRebootSystemHspInstall(systemHspDirs);
1630     InnerProcessRebootSharedBundleInstall(sharedBundleDirs, Constants::AppType::SYSTEM_APP);
1631     InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
1632     InnerProcessStockBundleProvisionInfo();
1633 }
1634 
ProcessRebootBundleInstallFromScan()1635 void BMSEventHandler::ProcessRebootBundleInstallFromScan()
1636 {
1637     LOG_D(BMS_TAG_DEFAULT, "Process reboot bundle install from scan");
1638     std::list<std::string> bundleDirs;
1639     GetBundleDirFromScan(bundleDirs);
1640     InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
1641     InnerProcessStockBundleProvisionInfo();
1642 }
1643 
InnerProcessRebootBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)1644 void BMSEventHandler::InnerProcessRebootBundleInstall(
1645     const std::list<std::string> &scanPathList, Constants::AppType appType)
1646 {
1647     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1648     if (dataMgr == nullptr) {
1649         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1650         return;
1651     }
1652 
1653     std::unordered_map<std::string, std::pair<std::string, bool>> needInstallMap;
1654     for (auto &scanPathIter : scanPathList) {
1655         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "reboot scan bundle path: %{public}s ", scanPathIter.c_str());
1656         bool removable = IsPreInstallRemovable(scanPathIter);
1657         std::unordered_map<std::string, InnerBundleInfo> infos;
1658         if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
1659             LOG_E(BMS_TAG_DEFAULT, "obtain bundleinfo failed : %{public}s ", scanPathIter.c_str());
1660             BmsKeyEventMgr::ProcessMainBundleInstallFailed(scanPathIter, ERR_APPEXECFWK_PARSE_UNEXPECTED);
1661             SavePreInstallException(scanPathIter);
1662             continue;
1663         }
1664 
1665         auto bundleName = infos.begin()->second.GetBundleName();
1666         auto hapVersionCode = infos.begin()->second.GetVersionCode();
1667         AddParseInfosToMap(bundleName, infos);
1668         auto mapIter = loadExistData_.find(bundleName);
1669         if (mapIter == loadExistData_.end()) {
1670             LOG_I(BMS_TAG_DEFAULT, "OTA Install new bundle(%{public}s) by path(%{public}s)",
1671                 bundleName.c_str(), scanPathIter.c_str());
1672             std::vector<std::string> filePaths { scanPathIter };
1673             if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1674                 LOG_E(BMS_TAG_DEFAULT, "OTA Install new bundle(%{public}s) error", bundleName.c_str());
1675                 SavePreInstallException(scanPathIter);
1676             }
1677             continue;
1678         }
1679 
1680         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OTA process bundle(%{public}s) by path(%{public}s)",
1681             bundleName.c_str(), scanPathIter.c_str());
1682         BundleInfo hasInstalledInfo;
1683         auto hasBundleInstalled = dataMgr->GetBundleInfo(
1684             bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
1685         if (!hasBundleInstalled && mapIter->second.IsUninstalled()) {
1686             LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) has been uninstalled and do not OTA install",
1687                 bundleName.c_str());
1688             if (!removable) {
1689                 std::vector<std::string> filePaths { scanPathIter };
1690                 if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1691                     LOG_E(BMS_TAG_DEFAULT, "OTA Install prefab bundle(%{public}s) error", bundleName.c_str());
1692                     SavePreInstallException(scanPathIter);
1693                 }
1694             }
1695             continue;
1696         }
1697 
1698         std::vector<std::string> filePaths;
1699         bool updateSelinuxLabel = false;
1700         bool updateBundle = false;
1701         for (auto item : infos) {
1702             auto parserModuleNames = item.second.GetModuleNameVec();
1703             if (parserModuleNames.empty()) {
1704                 LOG_E(BMS_TAG_DEFAULT, "module is empty when parser path(%{public}s)", item.first.c_str());
1705                 continue;
1706             }
1707             // Generally, when the versionCode of Hap is greater than the installed versionCode,
1708             // Except for the uninstalled app, they can be installed or upgraded directly by OTA.
1709             if (hasInstalledInfo.versionCode < hapVersionCode) {
1710                 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OTA update module(%{public}s) by path(%{public}s)",
1711                     parserModuleNames[0].c_str(), item.first.c_str());
1712                 updateBundle = true;
1713                 break;
1714             }
1715 
1716             // When the accessTokenIdEx is equal to 0, the old application needs to be updated.
1717             if (hasInstalledInfo.applicationInfo.accessTokenIdEx == 0) {
1718                 LOG_I(BMS_TAG_DEFAULT, "OTA update module %{public}s by path %{public}s, accessTokenIdEx is equal to 0",
1719                     parserModuleNames[0].c_str(), item.first.c_str());
1720                 updateBundle = true;
1721                 break;
1722             }
1723 
1724             // The versionCode of Hap is equal to the installed versionCode.
1725             // You can only install new modules by OTA
1726             if (hasInstalledInfo.versionCode == hapVersionCode) {
1727                 InnerBundleInfo info;
1728                 if (dataMgr->FetchInnerBundleInfo(bundleName, info) &&
1729                     info.GetInstallMark().status != InstallExceptionStatus::INSTALL_FINISH) {
1730                     LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OTA status error: %{public}s %{public}d",
1731                         bundleName.c_str(), info.GetInstallMark().status);
1732                     updateBundle = true;
1733                     break;
1734                 }
1735                 // update pre install app data dir selinux label
1736                 if (!updateSelinuxLabel) {
1737                     UpdateAppDataSelinuxLabel(bundleName, hasInstalledInfo.applicationInfo.appPrivilegeLevel,
1738                         hasInstalledInfo.isPreInstallApp,
1739                         hasInstalledInfo.applicationInfo.appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG);
1740                     updateSelinuxLabel = true;
1741                 }
1742                 // Used to judge whether the module has been installed.
1743                 bool hasModuleInstalled = std::find(
1744                     hasInstalledInfo.hapModuleNames.begin(), hasInstalledInfo.hapModuleNames.end(),
1745                     parserModuleNames[0]) != hasInstalledInfo.hapModuleNames.end();
1746                 if (hasModuleInstalled) {
1747                     if (UpdateModuleByHash(hasInstalledInfo, item.second)) {
1748                         updateBundle = true;
1749                         break;
1750                     }
1751                     LOG_D(BMS_TAG_DEFAULT, "module(%{public}s) has been installed and versionCode is same",
1752                         parserModuleNames[0].c_str());
1753                     continue;
1754                 }
1755 
1756                 LOG_I(BMS_TAG_DEFAULT, "OTA install module(%{public}s) by path(%{public}s)",
1757                     parserModuleNames[0].c_str(), item.first.c_str());
1758                 updateBundle = true;
1759                 break;
1760             }
1761 
1762             if (hasInstalledInfo.versionCode > hapVersionCode) {
1763                 LOG_E(BMS_TAG_DEFAULT, "bundleName: %{public}s update failed, versionCode(%{public}d) is lower than "
1764                     "installed bundle(%{public}d)", bundleName.c_str(), hapVersionCode, hasInstalledInfo.versionCode);
1765                 SendBundleUpdateFailedEvent(hasInstalledInfo);
1766                 break;
1767             }
1768         }
1769         if (!updateBundle) {
1770 #ifdef USE_PRE_BUNDLE_PROFILE
1771             UpdateRemovable(bundleName, removable);
1772 #endif
1773             continue;
1774         }
1775         // system resource need update first
1776         if (bundleName == SYSTEM_RESOURCES_APP) {
1777             std::vector<std::string> filePaths = {scanPathIter};
1778             (void)BMSEventHandler::OTAInstallSystemBundleNeedCheckUser(filePaths, bundleName, appType, removable);
1779             continue;
1780         }
1781         needInstallMap[bundleName] = std::make_pair(scanPathIter, removable);
1782     }
1783     if (!InnerMultiProcessBundleInstall(needInstallMap, appType)) {
1784         LOG_E(BMS_TAG_DEFAULT, "multi install failed");
1785     }
1786     UpdatePreinstallDB(needInstallMap);
1787 }
1788 
InnerMultiProcessBundleInstall(const std::unordered_map<std::string,std::pair<std::string,bool>> & needInstallMap,Constants::AppType appType)1789 bool BMSEventHandler::InnerMultiProcessBundleInstall(
1790     const std::unordered_map<std::string, std::pair<std::string, bool>> &needInstallMap,
1791     Constants::AppType appType)
1792 {
1793     if (needInstallMap.empty()) {
1794         LOG_I(BMS_TAG_DEFAULT, "no bundle need to update when ota");
1795         return true;
1796     }
1797     auto bundleMgrService = DelayedSingleton<BundleMgrService>::GetInstance();
1798     if (bundleMgrService == nullptr) {
1799         LOG_E(BMS_TAG_DEFAULT, "bundleMgrService is nullptr");
1800         return false;
1801     }
1802 
1803     sptr<BundleInstallerHost> installerHost = bundleMgrService->GetBundleInstaller();
1804     if (installerHost == nullptr) {
1805         LOG_E(BMS_TAG_DEFAULT, "installerHost is nullptr");
1806         return false;
1807     }
1808 
1809     size_t taskTotalNum = needInstallMap.size();
1810     size_t threadsNum = static_cast<size_t>(installerHost->GetThreadsNum());
1811     LOG_I(BMS_TAG_DEFAULT, "multi install start, totalNum: %{public}zu, num: %{public}zu", taskTotalNum, threadsNum);
1812     std::atomic_uint taskEndNum = 0;
1813     std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
1814     for (auto iter = needInstallMap.begin(); iter != needInstallMap.end(); ++iter) {
1815         std::string bundleName = iter->first;
1816         std::pair pair = iter->second;
1817         auto task = [bundleName, pair, taskTotalNum, appType, &taskEndNum, &bundlePromise]() {
1818             std::vector<std::string> filePaths = {pair.first};
1819             (void)BMSEventHandler::OTAInstallSystemBundleNeedCheckUser(filePaths, bundleName, appType, pair.second);
1820             taskEndNum++;
1821             if (bundlePromise && taskEndNum >= taskTotalNum) {
1822                 bundlePromise->NotifyAllTasksExecuteFinished();
1823                 LOG_I(BMS_TAG_DEFAULT, "All tasks has executed and notify promise when ota");
1824             }
1825         };
1826 
1827         installerHost->AddTask(task, "BootRebootStartInstall : " + bundleName);
1828     }
1829 
1830     if (taskEndNum < taskTotalNum) {
1831         bundlePromise->WaitForAllTasksExecute();
1832         LOG_I(BMS_TAG_DEFAULT, "Wait for all tasks execute when ota");
1833     }
1834     LOG_I(BMS_TAG_DEFAULT, "multi install end");
1835     return true;
1836 }
1837 
UpdateModuleByHash(const BundleInfo & oldBundleInfo,const InnerBundleInfo & newInfo) const1838 bool BMSEventHandler::UpdateModuleByHash(const BundleInfo &oldBundleInfo, const InnerBundleInfo &newInfo) const
1839 {
1840     auto moduleName = newInfo.GetModuleNameVec().at(0);
1841     std::string existModuleHash;
1842     for (auto hapInfo : oldBundleInfo.hapModuleInfos) {
1843         if (hapInfo.package == moduleName) {
1844             existModuleHash = hapInfo.buildHash;
1845         }
1846     }
1847     std::string curModuleHash;
1848     if (!newInfo.GetModuleBuildHash(moduleName, curModuleHash)) {
1849         LOG_D(BMS_TAG_DEFAULT, "module(%{public}s) is not existed", moduleName.c_str());
1850         return false;
1851     }
1852     if (existModuleHash != curModuleHash) {
1853         LOG_D(BMS_TAG_DEFAULT, "(%{public}s) buildHash changed update corresponding hap or hsp", moduleName.c_str());
1854         return true;
1855     }
1856     return false;
1857 }
1858 
InnerProcessRebootSharedBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)1859 void BMSEventHandler::InnerProcessRebootSharedBundleInstall(
1860     const std::list<std::string> &scanPathList, Constants::AppType appType)
1861 {
1862     LOG_I(BMS_TAG_DEFAULT, "InnerProcessRebootSharedBundleInstall");
1863     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1864     if (dataMgr == nullptr) {
1865         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1866         return;
1867     }
1868     for (const auto &scanPath : scanPathList) {
1869         bool removable = IsPreInstallRemovable(scanPath);
1870         std::unordered_map<std::string, InnerBundleInfo> infos;
1871         if (!ParseHapFiles(scanPath, infos) || infos.empty()) {
1872             LOG_E(BMS_TAG_DEFAULT, "obtain bundleinfo failed : %{public}s ", scanPath.c_str());
1873             continue;
1874         }
1875 
1876         auto bundleName = infos.begin()->second.GetBundleName();
1877         auto versionCode = infos.begin()->second.GetVersionCode();
1878         AddParseInfosToMap(bundleName, infos);
1879         auto mapIter = loadExistData_.find(bundleName);
1880         if (mapIter == loadExistData_.end()) {
1881             LOG_I(BMS_TAG_DEFAULT, "OTA Install new shared bundle(%{public}s) by path(%{public}s)",
1882                 bundleName.c_str(), scanPath.c_str());
1883             if (!OTAInstallSystemSharedBundle({scanPath}, appType, removable)) {
1884                 LOG_E(BMS_TAG_DEFAULT, "OTA Install new shared bundle(%{public}s) error", bundleName.c_str());
1885             }
1886             continue;
1887         }
1888 
1889         InnerBundleInfo oldBundleInfo;
1890         bool hasInstalled = dataMgr->FetchInnerBundleInfo(bundleName, oldBundleInfo);
1891         if (!hasInstalled) {
1892             LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) has been uninstalled and do not OTA install", bundleName.c_str());
1893             continue;
1894         }
1895 
1896         if (oldBundleInfo.GetVersionCode() > versionCode) {
1897             LOG_D(BMS_TAG_DEFAULT, "the installed version is up-to-date");
1898             continue;
1899         }
1900         if (oldBundleInfo.GetVersionCode() == versionCode) {
1901             if (!IsNeedToUpdateSharedAppByHash(oldBundleInfo, infos.begin()->second)) {
1902                 LOG_D(BMS_TAG_DEFAULT, "the installed version is up-to-date");
1903                 continue;
1904             }
1905         }
1906 
1907         if (!OTAInstallSystemSharedBundle({scanPath}, appType, removable)) {
1908             LOG_E(BMS_TAG_DEFAULT, "OTA update shared bundle(%{public}s) error", bundleName.c_str());
1909         }
1910     }
1911 }
1912 
InnerProcessRebootSystemHspInstall(const std::list<std::string> & scanPathList)1913 void BMSEventHandler::InnerProcessRebootSystemHspInstall(const std::list<std::string> &scanPathList)
1914 {
1915     LOG_I(BMS_TAG_DEFAULT, "InnerProcessRebootSystemHspInstall");
1916     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1917     if (dataMgr == nullptr) {
1918         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1919         return;
1920     }
1921     for (const auto &scanPath : scanPathList) {
1922         std::unordered_map<std::string, InnerBundleInfo> infos;
1923         if (!ParseHapFiles(scanPath, infos) || infos.empty()) {
1924             LOG_E(BMS_TAG_DEFAULT, "obtain bundleinfo failed : %{public}s ", scanPath.c_str());
1925             continue;
1926         }
1927         auto bundleName = infos.begin()->second.GetBundleName();
1928         auto versionCode = infos.begin()->second.GetVersionCode();
1929         AddParseInfosToMap(bundleName, infos);
1930         auto mapIter = loadExistData_.find(bundleName);
1931         if (mapIter == loadExistData_.end()) {
1932             LOG_I(BMS_TAG_DEFAULT, "OTA Install new system hsp(%{public}s) by path(%{public}s)",
1933                 bundleName.c_str(), scanPath.c_str());
1934             if (OTAInstallSystemHsp({scanPath}) != ERR_OK) {
1935                 LOG_E(BMS_TAG_DEFAULT, "OTA Install new system hsp(%{public}s) error", bundleName.c_str());
1936             }
1937             continue;
1938         }
1939         InnerBundleInfo oldBundleInfo;
1940         bool hasInstalled = dataMgr->FetchInnerBundleInfo(bundleName, oldBundleInfo);
1941         if (!hasInstalled) {
1942             LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) has been uninstalled and do not OTA install", bundleName.c_str());
1943             continue;
1944         }
1945         if (oldBundleInfo.GetVersionCode() > versionCode) {
1946             LOG_D(BMS_TAG_DEFAULT, "the installed version is up-to-date");
1947             continue;
1948         }
1949         if (oldBundleInfo.GetVersionCode() == versionCode) {
1950             for (const auto &item : infos) {
1951                 if (!IsNeedToUpdateSharedHspByHash(oldBundleInfo, item.second)) {
1952                     LOG_D(BMS_TAG_DEFAULT, "the installed version is up-to-date");
1953                     continue;
1954                 }
1955             }
1956         }
1957         if (OTAInstallSystemHsp({scanPath}) != ERR_OK) {
1958             LOG_E(BMS_TAG_DEFAULT, "OTA update shared bundle(%{public}s) error", bundleName.c_str());
1959         }
1960     }
1961 }
1962 
OTAInstallSystemHsp(const std::vector<std::string> & filePaths)1963 ErrCode BMSEventHandler::OTAInstallSystemHsp(const std::vector<std::string> &filePaths)
1964 {
1965     InstallParam installParam;
1966     installParam.isPreInstallApp = true;
1967     installParam.removable = false;
1968     installParam.isOTA = true;
1969     installParam.copyHapToInstallPath = false;
1970     installParam.needSavePreInstallInfo = true;
1971     installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
1972     AppServiceFwkInstaller installer;
1973 
1974     return installer.Install(filePaths, installParam);
1975 }
1976 
IsNeedToUpdateSharedHspByHash(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const1977 bool BMSEventHandler::IsNeedToUpdateSharedHspByHash(
1978     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
1979 {
1980     std::string moduleName = newInfo.GetCurrentModulePackage();
1981     std::string newModuleBuildHash;
1982     if (!newInfo.GetModuleBuildHash(moduleName, newModuleBuildHash)) {
1983         LOG_E(BMS_TAG_DEFAULT, "internal error, can not find module %{public}s", moduleName.c_str());
1984         return false;
1985     }
1986 
1987     std::string oldModuleBuildHash;
1988     if (!oldInfo.GetModuleBuildHash(moduleName, oldModuleBuildHash) ||
1989         newModuleBuildHash != oldModuleBuildHash) {
1990         LOG_D(BMS_TAG_DEFAULT, "module %{public}s need to be updated", moduleName.c_str());
1991         return true;
1992     }
1993     return false;
1994 }
1995 
IsNeedToUpdateSharedAppByHash(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const1996 bool BMSEventHandler::IsNeedToUpdateSharedAppByHash(
1997     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
1998 {
1999     auto oldSharedModuleMap = oldInfo.GetInnerSharedModuleInfos();
2000     auto newSharedModuleMap = newInfo.GetInnerSharedModuleInfos();
2001     for (const auto &item : newSharedModuleMap) {
2002         auto newModuleName = item.first;
2003         auto oldModuleInfos = oldSharedModuleMap[newModuleName];
2004         auto newModuleInfos = item.second;
2005         if (!oldModuleInfos.empty() && !newModuleInfos.empty()) {
2006             auto oldBuildHash = oldModuleInfos[0].buildHash;
2007             auto newBuildHash = newModuleInfos[0].buildHash;
2008             return oldBuildHash != newBuildHash;
2009         } else {
2010             return true;
2011         }
2012     }
2013     return false;
2014 }
2015 
SaveSystemFingerprint()2016 void BMSEventHandler::SaveSystemFingerprint()
2017 {
2018     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
2019     if (bmsPara == nullptr) {
2020         LOG_E(BMS_TAG_DEFAULT, "bmsPara is nullptr");
2021         return;
2022     }
2023 
2024     std::string curSystemFingerprint = GetCurSystemFingerprint();
2025     LOG_I(BMS_TAG_DEFAULT, "curSystemFingerprint(%{public}s)", curSystemFingerprint.c_str());
2026     if (curSystemFingerprint.empty()) {
2027         return;
2028     }
2029 
2030     bmsPara->SaveBmsParam(FINGERPRINT, curSystemFingerprint);
2031 }
2032 
IsSystemUpgrade()2033 bool BMSEventHandler::IsSystemUpgrade()
2034 {
2035     return IsTestSystemUpgrade() || IsSystemFingerprintChanged();
2036 }
2037 
IsTestSystemUpgrade()2038 bool BMSEventHandler::IsTestSystemUpgrade()
2039 {
2040     std::string paramValue;
2041     if (!GetSystemParameter(BMS_TEST_UPGRADE, paramValue) || paramValue.empty()) {
2042         return false;
2043     }
2044 
2045     LOG_I(BMS_TAG_DEFAULT, "TestSystemUpgrade value is %{public}s", paramValue.c_str());
2046     return paramValue == VALUE_TRUE;
2047 }
2048 
IsSystemFingerprintChanged()2049 bool BMSEventHandler::IsSystemFingerprintChanged()
2050 {
2051     std::string oldSystemFingerprint = GetOldSystemFingerprint();
2052     if (oldSystemFingerprint.empty()) {
2053         LOG_D(BMS_TAG_DEFAULT, "System should be upgraded due to oldSystemFingerprint is empty");
2054         return true;
2055     }
2056 
2057     std::string curSystemFingerprint = GetCurSystemFingerprint();
2058     LOG_D(BMS_TAG_DEFAULT, "oldSystemFingerprint(%{public}s), curSystemFingerprint(%{public}s)",
2059         oldSystemFingerprint.c_str(), curSystemFingerprint.c_str());
2060     return curSystemFingerprint != oldSystemFingerprint;
2061 }
2062 
GetCurSystemFingerprint()2063 std::string BMSEventHandler::GetCurSystemFingerprint()
2064 {
2065     std::string curSystemFingerprint;
2066     for (const auto &item : FINGERPRINTS) {
2067         std::string itemFingerprint;
2068         if (!GetSystemParameter(item, itemFingerprint) || itemFingerprint.empty()) {
2069             continue;
2070         }
2071 
2072         if (!curSystemFingerprint.empty()) {
2073             curSystemFingerprint.append(ServiceConstants::PATH_SEPARATOR);
2074         }
2075 
2076         curSystemFingerprint.append(itemFingerprint);
2077     }
2078 
2079     return curSystemFingerprint;
2080 }
2081 
GetSystemParameter(const std::string & key,std::string & value)2082 bool BMSEventHandler::GetSystemParameter(const std::string &key, std::string &value)
2083 {
2084     char firmware[VERSION_LEN] = {0};
2085     int32_t ret = GetParameter(key.c_str(), UNKNOWN.c_str(), firmware, VERSION_LEN);
2086     if (ret <= 0) {
2087         LOG_E(BMS_TAG_DEFAULT, "GetParameter failed");
2088         return false;
2089     }
2090 
2091     value = firmware;
2092     return true;
2093 }
2094 
GetOldSystemFingerprint()2095 std::string BMSEventHandler::GetOldSystemFingerprint()
2096 {
2097     std::string oldSystemFingerprint;
2098     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
2099     if (bmsPara != nullptr) {
2100         bmsPara->GetBmsParam(FINGERPRINT, oldSystemFingerprint);
2101     }
2102 
2103     return oldSystemFingerprint;
2104 }
2105 
AddParseInfosToMap(const std::string & bundleName,const std::unordered_map<std::string,InnerBundleInfo> & infos)2106 void BMSEventHandler::AddParseInfosToMap(
2107     const std::string &bundleName, const std::unordered_map<std::string, InnerBundleInfo> &infos)
2108 {
2109     auto hapParseInfoMapIter = hapParseInfoMap_.find(bundleName);
2110     if (hapParseInfoMapIter == hapParseInfoMap_.end()) {
2111         hapParseInfoMap_.emplace(bundleName, infos);
2112         return;
2113     }
2114 
2115     auto iterMap = hapParseInfoMapIter->second;
2116     for (auto infoIter : infos) {
2117         iterMap.emplace(infoIter.first, infoIter.second);
2118     }
2119 
2120     hapParseInfoMap_.at(bundleName) = iterMap;
2121 }
2122 
ProcessRebootBundleUninstall()2123 void BMSEventHandler::ProcessRebootBundleUninstall()
2124 {
2125     LOG_I(BMS_TAG_DEFAULT, "Reboot scan and OTA uninstall start");
2126     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2127     if (dataMgr == nullptr) {
2128         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2129         return;
2130     }
2131 
2132     for (auto &loadIter : loadExistData_) {
2133         std::string bundleName = loadIter.first;
2134         BundleInfo hasInstalledInfo;
2135         auto hasBundleInstalled = dataMgr->GetBundleInfo(
2136             bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
2137         auto listIter = hapParseInfoMap_.find(bundleName);
2138         if (listIter == hapParseInfoMap_.end()) {
2139             LOG_I(BMS_TAG_DEFAULT, "ProcessRebootBundleUninstall OTA uninstall app(%{public}s)", bundleName.c_str());
2140             if (InnerProcessUninstallForExistPreBundle(hasInstalledInfo)) {
2141                 continue;
2142             }
2143             SystemBundleInstaller installer;
2144             if (!installer.UninstallSystemBundle(bundleName)) {
2145                 LOG_E(BMS_TAG_DEFAULT, "OTA uninstall app(%{public}s) error", bundleName.c_str());
2146             } else {
2147                 LOG_I(BMS_TAG_DEFAULT, "OTA uninstall preInstall bundleName:%{public}s succeed", bundleName.c_str());
2148                 std::string moduleName;
2149                 DeletePreInfoInDb(bundleName, moduleName, true);
2150             }
2151 
2152             continue;
2153         }
2154 
2155         if (!hasBundleInstalled) {
2156             LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) maybe has been uninstall", bundleName.c_str());
2157             continue;
2158         }
2159         // Check the installed module
2160         if (InnerProcessUninstallModule(hasInstalledInfo, listIter->second)) {
2161             LOG_I(BMS_TAG_DEFAULT, "bundleName:%{public}s need delete module", bundleName.c_str());
2162         }
2163         // Check the preInstall path in Db.
2164         // If the corresponding Hap does not exist, it should be deleted.
2165         auto parserInfoMap = listIter->second;
2166         for (auto preBundlePath : loadIter.second.GetBundlePaths()) {
2167             auto parserInfoIter = parserInfoMap.find(preBundlePath);
2168             if (parserInfoIter != parserInfoMap.end()) {
2169                 LOG_I(BMS_TAG_DEFAULT, "OTA uninstall app(%{public}s) module path(%{public}s) exits",
2170                     bundleName.c_str(), preBundlePath.c_str());
2171                 continue;
2172             }
2173 
2174             LOG_I(BMS_TAG_DEFAULT, "OTA app(%{public}s) delete path(%{public}s)",
2175                 bundleName.c_str(), preBundlePath.c_str());
2176             DeletePreInfoInDb(bundleName, preBundlePath, false);
2177         }
2178     }
2179 
2180     LOG_I(BMS_TAG_DEFAULT, "Reboot scan and OTA uninstall success");
2181 }
2182 
InnerProcessUninstallModule(const BundleInfo & bundleInfo,const std::unordered_map<std::string,InnerBundleInfo> & infos)2183 bool BMSEventHandler::InnerProcessUninstallModule(const BundleInfo &bundleInfo,
2184     const std::unordered_map<std::string, InnerBundleInfo> &infos)
2185 {
2186     if (infos.empty()) {
2187         LOG_I(BMS_TAG_DEFAULT, "bundleName:%{public}s infos is empty", bundleInfo.name.c_str());
2188         return false;
2189     }
2190     if (bundleInfo.versionCode > infos.begin()->second.GetVersionCode()) {
2191         LOG_I(BMS_TAG_DEFAULT, "%{public}s version code is bigger than new pre-hap", bundleInfo.name.c_str());
2192         return false;
2193     }
2194     for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) {
2195         if (hapModuleInfo.hapPath.find(Constants::BUNDLE_CODE_DIR) == 0) {
2196             return false;
2197         }
2198     }
2199     if (bundleInfo.hapModuleNames.size() == 1) {
2200         LOG_I(BMS_TAG_DEFAULT, "bundleName:%{public}s only has one module, can not be uninstalled",
2201             bundleInfo.name.c_str());
2202         return false;
2203     }
2204     bool needUninstallModule = false;
2205     // Check the installed module.
2206     // If the corresponding Hap does not exist, it should be uninstalled.
2207     for (auto moduleName : bundleInfo.hapModuleNames) {
2208         bool hasModuleHapExist = false;
2209         for (auto parserInfoIter : infos) {
2210             auto parserModuleNames = parserInfoIter.second.GetModuleNameVec();
2211             if (!parserModuleNames.empty() && moduleName == parserModuleNames[0]) {
2212                 hasModuleHapExist = true;
2213                 break;
2214             }
2215         }
2216 
2217         if (!hasModuleHapExist) {
2218             LOG_I(BMS_TAG_DEFAULT, "ProcessRebootBundleUninstall OTA app(%{public}s) uninstall module(%{public}s)",
2219                 bundleInfo.name.c_str(), moduleName.c_str());
2220             needUninstallModule = true;
2221             SystemBundleInstaller installer;
2222             if (!installer.UninstallSystemBundle(bundleInfo.name, moduleName)) {
2223                 LOG_E(BMS_TAG_DEFAULT, "OTA app(%{public}s) uninstall module(%{public}s) error",
2224                     bundleInfo.name.c_str(), moduleName.c_str());
2225             }
2226         }
2227     }
2228     return needUninstallModule;
2229 }
2230 
DeletePreInfoInDb(const std::string & bundleName,const std::string & bundlePath,bool bundleLevel)2231 void BMSEventHandler::DeletePreInfoInDb(
2232     const std::string &bundleName, const std::string &bundlePath, bool bundleLevel)
2233 {
2234     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2235     if (dataMgr == nullptr) {
2236         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2237         return;
2238     }
2239 
2240     PreInstallBundleInfo preInstallBundleInfo;
2241     preInstallBundleInfo.SetBundleName(bundleName);
2242     if (bundleLevel) {
2243         LOG_I(BMS_TAG_DEFAULT, "DeletePreInfoInDb bundle %{public}s bundleLevel", bundleName.c_str());
2244         dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
2245         return;
2246     }
2247 
2248     LOG_I(BMS_TAG_DEFAULT, "DeletePreInfoInDb bundle %{public}s not bundleLevel with path(%{public}s)",
2249         bundleName.c_str(), bundlePath.c_str());
2250     dataMgr->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo);
2251     preInstallBundleInfo.DeleteBundlePath(bundlePath);
2252     if (preInstallBundleInfo.GetBundlePaths().empty()) {
2253         dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
2254     } else {
2255         dataMgr->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
2256     }
2257 }
2258 
HasModuleSavedInPreInstalledDb(const std::string & bundleName,const std::string & bundlePath)2259 bool BMSEventHandler::HasModuleSavedInPreInstalledDb(
2260     const std::string &bundleName, const std::string &bundlePath)
2261 {
2262     auto preInstallIter = loadExistData_.find(bundleName);
2263     if (preInstallIter == loadExistData_.end()) {
2264         LOG_E(BMS_TAG_DEFAULT, "app(%{public}s) does not save in PreInstalledDb", bundleName.c_str());
2265         return false;
2266     }
2267 
2268     return preInstallIter->second.HasBundlePath(bundlePath);
2269 }
2270 
SavePreInstallException(const std::string & bundleDir)2271 void BMSEventHandler::SavePreInstallException(const std::string &bundleDir)
2272 {
2273     auto preInstallExceptionMgr =
2274         DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
2275     if (preInstallExceptionMgr == nullptr) {
2276         LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
2277         return;
2278     }
2279 
2280     LOG_I(BMS_TAG_DEFAULT, "Starting to save pre-install exception for bundle: %{public}s", bundleDir.c_str());
2281     preInstallExceptionMgr->SavePreInstallExceptionPath(bundleDir);
2282 }
2283 
HandlePreInstallException()2284 void BMSEventHandler::HandlePreInstallException()
2285 {
2286     auto preInstallExceptionMgr =
2287         DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
2288     if (preInstallExceptionMgr == nullptr) {
2289         LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
2290         return;
2291     }
2292 
2293     std::set<std::string> exceptionPaths;
2294     std::set<std::string> exceptionBundleNames;
2295     if (!preInstallExceptionMgr->GetAllPreInstallExceptionInfo(
2296         exceptionPaths, exceptionBundleNames)) {
2297         LOG_I(BMS_TAG_DEFAULT, "No pre-install exception information found");
2298         return;
2299     }
2300 
2301     LOG_NOFUNC_I(BMS_TAG_DEFAULT, "HandlePreInstallException pathSize:%{public}zu bundleNameSize:%{public}zu",
2302         exceptionPaths.size(), exceptionBundleNames.size());
2303     for (const auto &pathIter : exceptionPaths) {
2304         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "HandlePreInstallException path:%{public}s", pathIter.c_str());
2305         std::vector<std::string> filePaths { pathIter };
2306         bool removable = IsPreInstallRemovable(pathIter);
2307         if (!OTAInstallSystemBundle(filePaths, Constants::AppType::SYSTEM_APP, removable)) {
2308             LOG_NOFUNC_W(BMS_TAG_DEFAULT, "HandlePreInstallException path(%{public}s) error", pathIter.c_str());
2309         }
2310 
2311         preInstallExceptionMgr->DeletePreInstallExceptionPath(pathIter);
2312         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "Del pre-install exception path:%{public}s", pathIter.c_str());
2313     }
2314 
2315     if (exceptionBundleNames.size() > 0) {
2316         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "Loading all pre-install bundle infos");
2317         LoadAllPreInstallBundleInfos();
2318     }
2319 
2320     for (const auto &bundleNameIter : exceptionBundleNames) {
2321         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "HandlePreInstallException bundleName: %{public}s", bundleNameIter.c_str());
2322         auto iter = loadExistData_.find(bundleNameIter);
2323         if (iter == loadExistData_.end()) {
2324             LOG_NOFUNC_W(BMS_TAG_DEFAULT, "HandlePreInstallException no bundleName(%{public}s) in PreInstallDb",
2325                 bundleNameIter.c_str());
2326             continue;
2327         }
2328 
2329         const auto &preInstallBundleInfo = iter->second;
2330         if (!OTAInstallSystemBundle(preInstallBundleInfo.GetBundlePaths(),
2331             Constants::AppType::SYSTEM_APP, preInstallBundleInfo.IsRemovable())) {
2332             LOG_NOFUNC_W(BMS_TAG_DEFAULT, "HandlePreInstallException bundleName(%{public}s) error",
2333                 bundleNameIter.c_str());
2334         }
2335 
2336         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "Deleting %{public}s from pre-install exception list", bundleNameIter.c_str());
2337         preInstallExceptionMgr->DeletePreInstallExceptionBundleName(bundleNameIter);
2338     }
2339 
2340     preInstallExceptionMgr->ClearAll();
2341     LOG_NOFUNC_I(BMS_TAG_DEFAULT, "Pre-install exception information cleared successfully");
2342 }
2343 
OTAInstallSystemBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)2344 bool BMSEventHandler::OTAInstallSystemBundle(
2345     const std::vector<std::string> &filePaths,
2346     Constants::AppType appType,
2347     bool removable)
2348 {
2349     if (filePaths.empty()) {
2350         LOG_E(BMS_TAG_DEFAULT, "File path is empty");
2351         return false;
2352     }
2353 
2354     InstallParam installParam;
2355     installParam.isPreInstallApp = true;
2356     installParam.SetKillProcess(false);
2357     installParam.needSendEvent = false;
2358     installParam.installFlag = InstallFlag::REPLACE_EXISTING;
2359     installParam.removable = removable;
2360     installParam.needSavePreInstallInfo = true;
2361     installParam.copyHapToInstallPath = false;
2362     installParam.isOTA = true;
2363     installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
2364     SystemBundleInstaller installer;
2365     ErrCode ret = installer.OTAInstallSystemBundle(filePaths, installParam, appType);
2366     if (ret == ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON) {
2367         ret = ERR_OK;
2368     }
2369     return ret == ERR_OK;
2370 }
2371 
OTAInstallSystemBundleNeedCheckUser(const std::vector<std::string> & filePaths,const std::string & bundleName,Constants::AppType appType,bool removable)2372 bool BMSEventHandler::OTAInstallSystemBundleNeedCheckUser(
2373     const std::vector<std::string> &filePaths,
2374     const std::string &bundleName,
2375     Constants::AppType appType,
2376     bool removable)
2377 {
2378     if (filePaths.empty()) {
2379         LOG_E(BMS_TAG_DEFAULT, "File path is empty");
2380         return false;
2381     }
2382 
2383     InstallParam installParam;
2384     installParam.isPreInstallApp = true;
2385     installParam.SetKillProcess(false);
2386     installParam.needSendEvent = false;
2387     installParam.installFlag = InstallFlag::REPLACE_EXISTING;
2388     installParam.removable = removable;
2389     installParam.needSavePreInstallInfo = true;
2390     installParam.copyHapToInstallPath = false;
2391     installParam.isOTA = true;
2392     installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
2393     SystemBundleInstaller installer;
2394     ErrCode ret = installer.OTAInstallSystemBundleNeedCheckUser(filePaths, installParam, bundleName, appType);
2395     LOG_NOFUNC_I(BMS_TAG_DEFAULT, "bundle %{public}s with return code: %{public}d", bundleName.c_str(), ret);
2396     if ((ret != ERR_OK) && (ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON)) {
2397         APP_LOGE("OTA bundle(%{public}s) failed, errCode:%{public}d", bundleName.c_str(), ret);
2398         if (!filePaths.empty()) {
2399             SavePreInstallException(filePaths[0]);
2400         }
2401         return false;
2402     }
2403     return true;
2404 }
2405 
OTAInstallSystemSharedBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)2406 bool BMSEventHandler::OTAInstallSystemSharedBundle(
2407     const std::vector<std::string> &filePaths,
2408     Constants::AppType appType,
2409     bool removable)
2410 {
2411     if (filePaths.empty()) {
2412         LOG_E(BMS_TAG_DEFAULT, "File path is empty");
2413         return false;
2414     }
2415 
2416     InstallParam installParam;
2417     installParam.isPreInstallApp = true;
2418     installParam.needSendEvent = false;
2419     installParam.installFlag = InstallFlag::REPLACE_EXISTING;
2420     installParam.removable = removable;
2421     installParam.needSavePreInstallInfo = true;
2422     installParam.sharedBundleDirPaths = filePaths;
2423     installParam.isOTA = true;
2424     installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
2425     SystemBundleInstaller installer;
2426     return installer.InstallSystemSharedBundle(installParam, true, appType);
2427 }
2428 
CheckAndParseHapFiles(const std::string & hapFilePath,bool isPreInstallApp,std::unordered_map<std::string,InnerBundleInfo> & infos)2429 bool BMSEventHandler::CheckAndParseHapFiles(
2430     const std::string &hapFilePath,
2431     bool isPreInstallApp,
2432     std::unordered_map<std::string, InnerBundleInfo> &infos)
2433 {
2434     std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
2435         std::make_unique<BundleInstallChecker>();
2436     std::vector<std::string> hapFilePathVec { hapFilePath };
2437     std::vector<std::string> realPaths;
2438     auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
2439     if (ret != ERR_OK) {
2440         LOG_E(BMS_TAG_DEFAULT, "File path %{public}s invalid", hapFilePath.c_str());
2441         return false;
2442     }
2443 
2444     ret = bundleInstallChecker->CheckSysCap(realPaths);
2445     if (ret != ERR_OK) {
2446         LOG_E(BMS_TAG_DEFAULT, "hap(%{public}s) syscap check failed", hapFilePath.c_str());
2447         return false;
2448     }
2449 
2450     std::vector<Security::Verify::HapVerifyResult> hapVerifyResults;
2451     ret = bundleInstallChecker->CheckMultipleHapsSignInfo(realPaths, hapVerifyResults, true);
2452     if (ret != ERR_OK) {
2453         LOG_E(BMS_TAG_DEFAULT, "CheckMultipleHapsSignInfo %{public}s failed", hapFilePath.c_str());
2454         return false;
2455     }
2456 
2457     InstallCheckParam checkParam;
2458     checkParam.isPreInstallApp = isPreInstallApp;
2459     if (isPreInstallApp) {
2460         checkParam.appType = Constants::AppType::SYSTEM_APP;
2461     }
2462 
2463     ret = bundleInstallChecker->ParseHapFiles(
2464         realPaths, checkParam, hapVerifyResults, infos);
2465     if (ret != ERR_OK) {
2466         LOG_E(BMS_TAG_DEFAULT, "parse haps file(%{public}s) failed", hapFilePath.c_str());
2467         return false;
2468     }
2469 
2470     ret = bundleInstallChecker->CheckHspInstallCondition(hapVerifyResults);
2471     if (ret != ERR_OK) {
2472         LOG_E(BMS_TAG_DEFAULT, "CheckHspInstallCondition failed %{public}d", ret);
2473         return false;
2474     }
2475 
2476     ret = bundleInstallChecker->CheckAppLabelInfo(infos);
2477     if (ret != ERR_OK) {
2478         LOG_E(BMS_TAG_DEFAULT, "Check APP label failed %{public}d", ret);
2479         return false;
2480     }
2481 
2482     // set hapPath
2483     std::for_each(infos.begin(), infos.end(), [](auto &item) {
2484         item.second.SetModuleHapPath(item.first);
2485     });
2486 
2487     return true;
2488 }
2489 
ParseHapFiles(const std::string & hapFilePath,std::unordered_map<std::string,InnerBundleInfo> & infos)2490 bool BMSEventHandler::ParseHapFiles(
2491     const std::string &hapFilePath,
2492     std::unordered_map<std::string, InnerBundleInfo> &infos)
2493 {
2494     std::vector<std::string> hapFilePathVec { hapFilePath };
2495     std::vector<std::string> realPaths;
2496     auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
2497     if (ret != ERR_OK) {
2498         LOG_E(BMS_TAG_DEFAULT, "File path %{public}s invalid", hapFilePath.c_str());
2499         return false;
2500     }
2501 
2502     BundleParser bundleParser;
2503     for (auto realPath : realPaths) {
2504         InnerBundleInfo innerBundleInfo;
2505         ret = bundleParser.Parse(realPath, innerBundleInfo);
2506         if (ret != ERR_OK) {
2507             LOG_E(BMS_TAG_DEFAULT, "Parse bundle info failed, error: %{public}d", ret);
2508             continue;
2509         }
2510 
2511         infos.emplace(realPath, innerBundleInfo);
2512     }
2513 
2514     if (infos.empty()) {
2515         LOG_E(BMS_TAG_DEFAULT, "Parse hap(%{public}s) empty ", hapFilePath.c_str());
2516         return false;
2517     }
2518 
2519     return true;
2520 }
2521 
IsPreInstallRemovable(const std::string & path)2522 bool BMSEventHandler::IsPreInstallRemovable(const std::string &path)
2523 {
2524 #ifdef USE_PRE_BUNDLE_PROFILE
2525     if (!HasPreInstallProfile()) {
2526         return false;
2527     }
2528 
2529     if (!hasLoadPreInstallProFile_) {
2530         LOG_E(BMS_TAG_DEFAULT, "Not load preInstall proFile or release");
2531         return false;
2532     }
2533 
2534     if (path.empty() || installList_.empty()) {
2535         LOG_E(BMS_TAG_DEFAULT, "path or installList is empty");
2536         return false;
2537     }
2538     auto installInfo = std::find_if(installList_.begin(), installList_.end(),
2539         [path](const auto &installInfo) {
2540         return installInfo.bundleDir == path;
2541     });
2542     if (installInfo != installList_.end()) {
2543         return (*installInfo).removable;
2544     }
2545     return true;
2546 #else
2547     return false;
2548 #endif
2549 }
2550 
GetPreInstallCapability(PreBundleConfigInfo & preBundleConfigInfo)2551 bool BMSEventHandler::GetPreInstallCapability(PreBundleConfigInfo &preBundleConfigInfo)
2552 {
2553     if (!hasLoadPreInstallProFile_) {
2554         LOG_E(BMS_TAG_DEFAULT, "Not load preInstall proFile or release");
2555         return false;
2556     }
2557 
2558     if (preBundleConfigInfo.bundleName.empty() || installListCapabilities_.empty()) {
2559         LOG_E(BMS_TAG_DEFAULT, "BundleName or installListCapabilities is empty");
2560         return false;
2561     }
2562 
2563     auto iter = installListCapabilities_.find(preBundleConfigInfo);
2564     if (iter == installListCapabilities_.end()) {
2565         LOG_D(BMS_TAG_DEFAULT, "BundleName(%{public}s) no has preinstall capability",
2566             preBundleConfigInfo.bundleName.c_str());
2567         return false;
2568     }
2569 
2570     preBundleConfigInfo = *iter;
2571     return true;
2572 }
2573 
CheckExtensionTypeInConfig(const std::string & typeName)2574 bool BMSEventHandler::CheckExtensionTypeInConfig(const std::string &typeName)
2575 {
2576     if (!hasLoadPreInstallProFile_) {
2577         LOG_E(BMS_TAG_DEFAULT, "Not load typeName proFile or release");
2578         return false;
2579     }
2580 
2581     if (typeName.empty() || extensiontype_.empty()) {
2582         LOG_E(BMS_TAG_DEFAULT, "TypeName or typeName configuration file is empty");
2583         return false;
2584     }
2585 
2586     auto iter = extensiontype_.find(typeName);
2587     if (iter == extensiontype_.end()) {
2588         LOG_E(BMS_TAG_DEFAULT, "ExtensionTypeConfig does not have '(%{public}s)' type",
2589             typeName.c_str());
2590         return false;
2591     }
2592 
2593     return true;
2594 }
2595 
2596 #ifdef USE_PRE_BUNDLE_PROFILE
UpdateRemovable(const std::string & bundleName,bool removable)2597 void BMSEventHandler::UpdateRemovable(const std::string &bundleName, bool removable)
2598 {
2599     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2600     if (dataMgr == nullptr) {
2601         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2602         return;
2603     }
2604 
2605     dataMgr->UpdateRemovable(bundleName, removable);
2606 }
2607 
UpdateAllPrivilegeCapability()2608 void BMSEventHandler::UpdateAllPrivilegeCapability()
2609 {
2610     for (const auto &preBundleConfigInfo : installListCapabilities_) {
2611         UpdatePrivilegeCapability(preBundleConfigInfo);
2612     }
2613 }
2614 
UpdatePrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)2615 void BMSEventHandler::UpdatePrivilegeCapability(
2616     const PreBundleConfigInfo &preBundleConfigInfo)
2617 {
2618     auto &bundleName = preBundleConfigInfo.bundleName;
2619     InnerBundleInfo innerBundleInfo;
2620     if (!FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
2621         LOG_NOFUNC_W(BMS_TAG_DEFAULT, "App(%{public}s) is not installed", bundleName.c_str());
2622         return;
2623     }
2624     // match both fingerprint and appId
2625     if (!MatchSignature(preBundleConfigInfo, innerBundleInfo.GetCertificateFingerprint()) &&
2626         !MatchSignature(preBundleConfigInfo, innerBundleInfo.GetAppId()) &&
2627         !MatchSignature(preBundleConfigInfo, innerBundleInfo.GetAppIdentifier()) &&
2628         !MatchOldSignatures(preBundleConfigInfo, innerBundleInfo.GetOldAppIds())) {
2629         LOG_E(BMS_TAG_DEFAULT, "bundleName: %{public}s no match pre bundle config info", bundleName.c_str());
2630         return;
2631     }
2632 
2633     UpdateTrustedPrivilegeCapability(preBundleConfigInfo);
2634 }
2635 
MatchSignature(const PreBundleConfigInfo & configInfo,const std::string & signature)2636 bool BMSEventHandler::MatchSignature(
2637     const PreBundleConfigInfo &configInfo, const std::string &signature)
2638 {
2639     if (configInfo.appSignature.empty() || signature.empty()) {
2640         LOG_W(BMS_TAG_DEFAULT, "appSignature or signature is empty");
2641         return false;
2642     }
2643 
2644     return std::find(configInfo.appSignature.begin(),
2645         configInfo.appSignature.end(), signature) != configInfo.appSignature.end();
2646 }
2647 
MatchOldSignatures(const PreBundleConfigInfo & configInfo,const std::vector<std::string> & oldSignatures)2648 bool BMSEventHandler::MatchOldSignatures(const PreBundleConfigInfo &configInfo,
2649     const std::vector<std::string> &oldSignatures)
2650 {
2651     if (configInfo.appSignature.empty() || oldSignatures.empty()) {
2652         LOG_W(BMS_TAG_DEFAULT, "appSignature or oldSignatures is empty");
2653         return false;
2654     }
2655     for (const auto &signature : oldSignatures) {
2656         if (std::find(configInfo.appSignature.begin(), configInfo.appSignature.end(), signature) !=
2657             configInfo.appSignature.end()) {
2658             return true;
2659         }
2660     }
2661 
2662     return false;
2663 }
2664 
UpdateTrustedPrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)2665 void BMSEventHandler::UpdateTrustedPrivilegeCapability(
2666     const PreBundleConfigInfo &preBundleConfigInfo)
2667 {
2668     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2669     if (dataMgr == nullptr) {
2670         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2671         return;
2672     }
2673 
2674     ApplicationInfo appInfo;
2675     appInfo.keepAlive = preBundleConfigInfo.keepAlive;
2676     appInfo.singleton = preBundleConfigInfo.singleton;
2677     appInfo.runningResourcesApply = preBundleConfigInfo.runningResourcesApply;
2678     appInfo.associatedWakeUp = preBundleConfigInfo.associatedWakeUp;
2679     appInfo.allowCommonEvent = preBundleConfigInfo.allowCommonEvent;
2680     appInfo.resourcesApply = preBundleConfigInfo.resourcesApply;
2681     appInfo.allowAppRunWhenDeviceFirstLocked = preBundleConfigInfo.allowAppRunWhenDeviceFirstLocked;
2682     appInfo.allowEnableNotification = preBundleConfigInfo.allowEnableNotification;
2683     dataMgr->UpdatePrivilegeCapability(preBundleConfigInfo.bundleName, appInfo);
2684 }
2685 #endif
2686 
FetchInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & innerBundleInfo)2687 bool BMSEventHandler::FetchInnerBundleInfo(
2688     const std::string &bundleName, InnerBundleInfo &innerBundleInfo)
2689 {
2690     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2691     if (dataMgr == nullptr) {
2692         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2693         return false;
2694     }
2695 
2696     return dataMgr->FetchInnerBundleInfo(bundleName, innerBundleInfo);
2697 }
2698 
ListeningUserUnlocked() const2699 void BMSEventHandler::ListeningUserUnlocked() const
2700 {
2701     LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler listen the unlock of someone user start");
2702     EventFwk::MatchingSkills matchingSkills;
2703     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
2704     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
2705     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
2706     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
2707 
2708     auto subscriberPtr = std::make_shared<UserUnlockedEventSubscriber>(subscribeInfo);
2709     if (AccountHelper::IsOsAccountVerified(Constants::START_USERID)) {
2710         LOG_I(BMS_TAG_DEFAULT, "user 100 is unlocked");
2711         OHOS::AAFwk::Want want;
2712         want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
2713         EventFwk::CommonEventData data { want };
2714         data.SetCode(Constants::START_USERID);
2715         subscriberPtr->OnReceiveEvent(data);
2716     }
2717     if (!EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberPtr)) {
2718         LOG_W(BMS_TAG_DEFAULT, "BMSEventHandler subscribe common event %{public}s failed",
2719             EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED.c_str());
2720     }
2721 }
2722 
RemoveUnreservedSandbox() const2723 void BMSEventHandler::RemoveUnreservedSandbox() const
2724 {
2725 #if defined (BUNDLE_FRAMEWORK_SANDBOX_APP) && defined (DLP_PERMISSION_ENABLE)
2726     LOG_I(BMS_TAG_DEFAULT, "Start to RemoveUnreservedSandbox");
2727     const int32_t WAIT_TIMES = 40;
2728     const int32_t EACH_TIME = 1000; // 1000ms
2729     auto execFunc = [](int32_t waitTimes, int32_t eachTime) {
2730         int32_t currentUserId = Constants::INVALID_USERID;
2731         while (waitTimes--) {
2732             std::this_thread::sleep_for(std::chrono::milliseconds(eachTime));
2733             LOG_D(BMS_TAG_DEFAULT, "wait for account started");
2734             if (currentUserId == Constants::INVALID_USERID) {
2735                 currentUserId = AccountHelper::GetCurrentActiveUserId();
2736                 LOG_D(BMS_TAG_DEFAULT, "current active userId is %{public}d", currentUserId);
2737                 if (currentUserId == Constants::INVALID_USERID) {
2738                     continue;
2739                 }
2740             }
2741             LOG_I(BMS_TAG_DEFAULT, "RemoveUnreservedSandbox call ClearUnreservedSandbox");
2742             Security::DlpPermission::DlpPermissionKit::ClearUnreservedSandbox();
2743             break;
2744         }
2745     };
2746     std::thread removeThread(execFunc, WAIT_TIMES, EACH_TIME);
2747     removeThread.detach();
2748 #endif
2749     LOG_I(BMS_TAG_DEFAULT, "RemoveUnreservedSandbox finish");
2750 }
2751 
AddStockAppProvisionInfoByOTA(const std::string & bundleName,const std::string & filePath)2752 void BMSEventHandler::AddStockAppProvisionInfoByOTA(const std::string &bundleName, const std::string &filePath)
2753 {
2754     LOG_D(BMS_TAG_DEFAULT, "AddStockAppProvisionInfoByOTA bundleName: %{public}s", bundleName.c_str());
2755     // parse profile info
2756     Security::Verify::HapVerifyResult hapVerifyResult;
2757     auto ret = BundleVerifyMgr::ParseHapProfile(filePath, hapVerifyResult);
2758     if (ret != ERR_OK) {
2759         LOG_E(BMS_TAG_DEFAULT, "BundleVerifyMgr::HapVerify failed, bundleName: %{public}s, errCode: %{public}d",
2760             bundleName.c_str(), ret);
2761         return;
2762     }
2763 
2764     std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
2765         std::make_unique<BundleInstallChecker>();
2766     AppProvisionInfo appProvisionInfo = bundleInstallChecker->ConvertToAppProvisionInfo(
2767         hapVerifyResult.GetProvisionInfo());
2768     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->AddAppProvisionInfo(bundleName, appProvisionInfo)) {
2769         LOG_E(BMS_TAG_DEFAULT, "AddAppProvisionInfo failed, bundleName:%{public}s", bundleName.c_str());
2770     }
2771 }
2772 
UpdateAppDataSelinuxLabel(const std::string & bundleName,const std::string & apl,bool isPreInstall,bool debug)2773 void BMSEventHandler::UpdateAppDataSelinuxLabel(const std::string &bundleName, const std::string &apl,
2774     bool isPreInstall, bool debug)
2775 {
2776     LOG_D(BMS_TAG_DEFAULT, "UpdateAppDataSelinuxLabel bundleName: %{public}s start", bundleName.c_str());
2777     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2778     if (dataMgr == nullptr) {
2779         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2780         return;
2781     }
2782     std::set<int32_t> userIds = dataMgr->GetAllUser();
2783     for (const auto &userId : userIds) {
2784         for (const auto &el : ServiceConstants::BUNDLE_EL) {
2785             std::string baseBundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR +
2786                                             el +
2787                                             ServiceConstants::PATH_SEPARATOR +
2788                                             std::to_string(userId);
2789             std::string baseDataDir = baseBundleDataDir + ServiceConstants::BASE + bundleName;
2790             bool isExist = true;
2791             ErrCode result = InstalldClient::GetInstance()->IsExistDir(baseDataDir, isExist);
2792             if (result != ERR_OK) {
2793                 LOG_E(BMS_TAG_DEFAULT, "IsExistDir failed, error is %{public}d", result);
2794                 continue;
2795             }
2796             if (!isExist) {
2797                 // Update only accessible directories when OTA,
2798                 // and other directories need to be set after the device is unlocked.
2799                 // Can see UserUnlockedEventSubscriber::UpdateAppDataDirSelinuxLabel
2800                 continue;
2801             }
2802             result = InstalldClient::GetInstance()->SetDirApl(baseDataDir, bundleName, apl, isPreInstall, debug);
2803             if (result != ERR_OK) {
2804                 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s, fail to SetDirApl baseDataDir dir, error is %{public}d",
2805                     bundleName.c_str(), result);
2806             }
2807             std::string databaseDataDir = baseBundleDataDir + ServiceConstants::DATABASE + bundleName;
2808             result = InstalldClient::GetInstance()->SetDirApl(databaseDataDir, bundleName, apl, isPreInstall, debug);
2809             if (result != ERR_OK) {
2810                 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s, fail to SetDirApl databaseDir dir, error is %{public}d",
2811                     bundleName.c_str(), result);
2812             }
2813         }
2814     }
2815     LOG_D(BMS_TAG_DEFAULT, "UpdateAppDataSelinuxLabel bundleName: %{public}s end", bundleName.c_str());
2816 }
2817 
HandleSceneBoard() const2818 void BMSEventHandler::HandleSceneBoard() const
2819 {
2820 #ifdef WINDOW_ENABLE
2821     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2822     if (dataMgr == nullptr) {
2823         LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
2824         return;
2825     }
2826     bool sceneBoardEnable = Rosen::SceneBoardJudgement::IsSceneBoardEnabled();
2827     LOG_I(BMS_TAG_DEFAULT, "HandleSceneBoard sceneBoardEnable : %{public}d", sceneBoardEnable);
2828     dataMgr->SetApplicationEnabled(ServiceConstants::SYSTEM_UI_BUNDLE_NAME, 0, !sceneBoardEnable,
2829         ServiceConstants::CALLER_NAME_BMS, Constants::DEFAULT_USERID);
2830     std::set<int32_t> userIds = dataMgr->GetAllUser();
2831     std::for_each(userIds.cbegin(), userIds.cend(), [dataMgr, sceneBoardEnable](const int32_t userId) {
2832         if (userId == 0) {
2833             return;
2834         }
2835         dataMgr->SetApplicationEnabled(Constants::SCENE_BOARD_BUNDLE_NAME, 0, sceneBoardEnable,
2836             ServiceConstants::CALLER_NAME_BMS, userId);
2837         dataMgr->SetApplicationEnabled(ServiceConstants::LAUNCHER_BUNDLE_NAME, 0, !sceneBoardEnable,
2838             ServiceConstants::CALLER_NAME_BMS, userId);
2839     });
2840 #endif
2841 }
2842 
InnerProcessStockBundleProvisionInfo()2843 void BMSEventHandler::InnerProcessStockBundleProvisionInfo()
2844 {
2845     LOG_D(BMS_TAG_DEFAULT, "InnerProcessStockBundleProvisionInfo start");
2846     std::unordered_set<std::string> allBundleNames;
2847     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->GetAllAppProvisionInfoBundleName(allBundleNames)) {
2848         LOG_E(BMS_TAG_DEFAULT, "GetAllAppProvisionInfoBundleName failed");
2849         return;
2850     }
2851     // process normal bundle
2852     ProcessBundleProvisionInfo(allBundleNames);
2853     // process shared bundle
2854     ProcessSharedBundleProvisionInfo(allBundleNames);
2855     LOG_D(BMS_TAG_DEFAULT, "InnerProcessStockBundleProvisionInfo end");
2856 }
2857 
ProcessBundleProvisionInfo(const std::unordered_set<std::string> & allBundleNames)2858 void BMSEventHandler::ProcessBundleProvisionInfo(const std::unordered_set<std::string> &allBundleNames)
2859 {
2860     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2861     if (dataMgr == nullptr) {
2862         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2863         return;
2864     }
2865     std::vector<BundleInfo> bundleInfos;
2866     if (dataMgr->GetBundleInfosV9(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
2867         bundleInfos, Constants::ALL_USERID) != ERR_OK) {
2868         LOG_E(BMS_TAG_DEFAULT, "GetBundleInfos failed");
2869         return;
2870     }
2871     for (const auto &bundleInfo : bundleInfos) {
2872         // not exist in appProvisionInfo table, then parse profile info and save it
2873         if ((allBundleNames.find(bundleInfo.name) == allBundleNames.end()) &&
2874             !bundleInfo.hapModuleInfos.empty()) {
2875             AddStockAppProvisionInfoByOTA(bundleInfo.name, bundleInfo.hapModuleInfos[0].hapPath);
2876         }
2877     }
2878 }
2879 
ProcessSharedBundleProvisionInfo(const std::unordered_set<std::string> & allBundleNames)2880 void BMSEventHandler::ProcessSharedBundleProvisionInfo(const std::unordered_set<std::string> &allBundleNames)
2881 {
2882     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2883     if (dataMgr == nullptr) {
2884         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2885         return;
2886     }
2887     std::vector<SharedBundleInfo> shareBundleInfos;
2888     if (dataMgr->GetAllSharedBundleInfo(shareBundleInfos) != ERR_OK) {
2889         LOG_E(BMS_TAG_DEFAULT, "GetAllSharedBundleInfo failed");
2890         return;
2891     }
2892     for (const auto &sharedBundleInfo : shareBundleInfos) {
2893         // not exist in appProvisionInfo table, then parse profile info and save it
2894         if ((allBundleNames.find(sharedBundleInfo.name) == allBundleNames.end()) &&
2895             !sharedBundleInfo.sharedModuleInfos.empty()) {
2896             std::string hspPath = Constants::BUNDLE_CODE_DIR + ServiceConstants::PATH_SEPARATOR + sharedBundleInfo.name
2897                 + ServiceConstants::PATH_SEPARATOR + HSP_VERSION_PREFIX
2898                 + std::to_string(sharedBundleInfo.sharedModuleInfos[0].versionCode) + ServiceConstants::PATH_SEPARATOR
2899                 + sharedBundleInfo.sharedModuleInfos[0].name + ServiceConstants::PATH_SEPARATOR
2900                 + sharedBundleInfo.sharedModuleInfos[0].name + ServiceConstants::HSP_FILE_SUFFIX;
2901             AddStockAppProvisionInfoByOTA(sharedBundleInfo.name, hspPath);
2902         }
2903     }
2904 }
2905 
ProcessRebootQuickFixBundleInstall(const std::string & path,bool isOta)2906 void BMSEventHandler::ProcessRebootQuickFixBundleInstall(const std::string &path, bool isOta)
2907 {
2908     LOG_I(BMS_TAG_DEFAULT, "start, isOta:%{public}d", isOta);
2909     std::string systemHspPath = path + ServiceConstants::PATH_SEPARATOR + MODULE_UPDATE_APP_SERVICE_DIR;
2910     std::string systemBundlePath = path + SYSTEM_BUNDLE_PATH;
2911     PatchSystemHspInstall(systemHspPath, isOta);
2912     PatchSystemBundleInstall(systemBundlePath, isOta);
2913     LOG_I(BMS_TAG_DEFAULT, "end");
2914 }
2915 
PatchSystemHspInstall(const std::string & path,bool isOta)2916 void BMSEventHandler::PatchSystemHspInstall(const std::string &path, bool isOta)
2917 {
2918     LOG_I(BMS_TAG_DEFAULT, "start");
2919     std::list<std::string> bundleDirs;
2920     ProcessScanDir(path, bundleDirs);
2921     if (bundleDirs.empty()) {
2922         LOG_I(BMS_TAG_DEFAULT, "end, bundleDirs is empty");
2923         return;
2924     }
2925     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2926     if (dataMgr == nullptr) {
2927         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2928         return;
2929     }
2930     for (auto &scanPathIter : bundleDirs) {
2931         std::unordered_map<std::string, InnerBundleInfo> infos;
2932         if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
2933             LOG_E(BMS_TAG_DEFAULT, "ParseHapFiles failed : %{public}s ", scanPathIter.c_str());
2934             continue;
2935         }
2936         auto bundleName = infos.begin()->second.GetBundleName();
2937         auto versionCode = infos.begin()->second.GetVersionCode();
2938         InnerBundleInfo hasInstalledInfo;
2939         auto hasBundleInstalled = dataMgr->FetchInnerBundleInfo(bundleName, hasInstalledInfo);
2940         if (!hasBundleInstalled) {
2941             LOG_W(BMS_TAG_DEFAULT, "bundleName %{public}s not exist", bundleName.c_str());
2942             continue;
2943         }
2944         if ((versionCode <= hasInstalledInfo.GetVersionCode()) && IsHspPathExist(hasInstalledInfo)) {
2945             LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s downgrade",
2946                 bundleName.c_str());
2947             continue;
2948         }
2949         InstallParam installParam;
2950         installParam.SetKillProcess(false);
2951         installParam.removable = false;
2952         installParam.needSendEvent = false;
2953         installParam.copyHapToInstallPath = true;
2954         installParam.needSavePreInstallInfo = false;
2955         installParam.isOTA = isOta;
2956         AppServiceFwkInstaller installer;
2957         std::vector<std::string> filePaths { scanPathIter };
2958         if (installer.Install(filePaths, installParam) != ERR_OK) {
2959             LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s: install failed", bundleName.c_str());
2960         }
2961     }
2962     LOG_I(BMS_TAG_DEFAULT, "end");
2963 }
2964 
PatchSystemBundleInstall(const std::string & path,bool isOta)2965 void BMSEventHandler::PatchSystemBundleInstall(const std::string &path, bool isOta)
2966 {
2967     LOG_I(BMS_TAG_DEFAULT, "start");
2968     std::list<std::string> bundleDirs;
2969     ProcessScanDir(path, bundleDirs);
2970     if (bundleDirs.empty()) {
2971         LOG_I(BMS_TAG_DEFAULT, "end, bundleDirs is empty");
2972         return;
2973     }
2974     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2975     if (dataMgr == nullptr) {
2976         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2977         return;
2978     }
2979     for (auto &scanPathIter : bundleDirs) {
2980         std::unordered_map<std::string, InnerBundleInfo> infos;
2981         if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
2982             LOG_E(BMS_TAG_DEFAULT, "ParseHapFiles failed : %{public}s ", scanPathIter.c_str());
2983             continue;
2984         }
2985         auto bundleName = infos.begin()->second.GetBundleName();
2986         auto hapVersionCode = infos.begin()->second.GetVersionCode();
2987         BundleInfo hasInstalledInfo;
2988         auto hasBundleInstalled = dataMgr->GetBundleInfo(
2989             bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
2990         if (!hasBundleInstalled) {
2991             LOG_W(BMS_TAG_DEFAULT, "obtain bundleInfo failed, bundleName :%{public}s not exist", bundleName.c_str());
2992             continue;
2993         }
2994         if ((hapVersionCode <= hasInstalledInfo.versionCode) && IsHapPathExist(hasInstalledInfo)) {
2995             LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s: hapVersionCode is less than old hap versionCode",
2996                 bundleName.c_str());
2997             continue;
2998         }
2999         if (!hasInstalledInfo.isKeepAlive) {
3000             LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s: is not keep alive bundle", bundleName.c_str());
3001             continue;
3002         }
3003         InstallParam installParam;
3004         installParam.SetKillProcess(false);
3005         installParam.needSendEvent = false;
3006         installParam.installFlag = InstallFlag::REPLACE_EXISTING;
3007         installParam.copyHapToInstallPath = true;
3008         installParam.isOTA = isOta;
3009         SystemBundleInstaller installer;
3010         std::vector<std::string> filePaths { scanPathIter };
3011         if (installer.OTAInstallSystemBundle(filePaths, installParam, Constants::AppType::SYSTEM_APP) != ERR_OK) {
3012             LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s: install failed", bundleName.c_str());
3013         }
3014     }
3015     LOG_I(BMS_TAG_DEFAULT, "end");
3016 }
3017 
IsHapPathExist(const BundleInfo & bundleInfo)3018 bool BMSEventHandler::IsHapPathExist(const BundleInfo &bundleInfo)
3019 {
3020     LOG_I(BMS_TAG_DEFAULT, "-n %{public}s need to check hap path exist", bundleInfo.name.c_str());
3021     if (bundleInfo.hapModuleInfos.empty()) {
3022         LOG_E(BMS_TAG_DEFAULT, "-n %{public}s has no moduleInfo", bundleInfo.name.c_str());
3023         return false;
3024     }
3025     for (const auto &moduleInfo : bundleInfo.hapModuleInfos) {
3026         if ((moduleInfo.hapPath.find(Constants::BUNDLE_CODE_DIR) == 0) &&
3027             !BundleUtil::IsExistFile(moduleInfo.hapPath)) {
3028             LOG_E(BMS_TAG_DEFAULT, "-p %{public}s hap path not exist", moduleInfo.hapPath.c_str());
3029             return false;
3030         }
3031     }
3032     return true;
3033 }
3034 
IsHspPathExist(const InnerBundleInfo & innerBundleInfo)3035 bool BMSEventHandler::IsHspPathExist(const InnerBundleInfo &innerBundleInfo)
3036 {
3037     LOG_I(BMS_TAG_DEFAULT, "-n %{public}s need to check hsp path exist", innerBundleInfo.GetBundleName().c_str());
3038     if (innerBundleInfo.GetInnerModuleInfos().empty()) {
3039         LOG_E(BMS_TAG_DEFAULT, "-n %{public}s has no moduleInfo", innerBundleInfo.GetBundleName().c_str());
3040         return false;
3041     }
3042     for (const auto &moduleInfoIter : innerBundleInfo.GetInnerModuleInfos()) {
3043         if ((moduleInfoIter.second.hapPath.find(Constants::BUNDLE_CODE_DIR) == 0) &&
3044             !BundleUtil::IsExistFile(moduleInfoIter.second.hapPath)) {
3045             LOG_E(BMS_TAG_DEFAULT, "-p %{public}s hsp path not exist", moduleInfoIter.second.hapPath.c_str());
3046             return false;
3047         }
3048     }
3049     return true;
3050 }
3051 
CheckALLResourceInfo()3052 void BMSEventHandler::CheckALLResourceInfo()
3053 {
3054     LOG_I(BMS_TAG_DEFAULT, "start");
3055     std::thread ProcessBundleResourceThread(ProcessBundleResourceInfo);
3056     ProcessBundleResourceThread.detach();
3057 }
3058 
ProcessBundleResourceInfo()3059 void BMSEventHandler::ProcessBundleResourceInfo()
3060 {
3061     LOG_I(BMS_TAG_DEFAULT, "ProcessBundleResourceInfo start");
3062     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3063     if (dataMgr == nullptr) {
3064         LOG_E(BMS_TAG_DEFAULT, "dataMgr is nullptr");
3065         return;
3066     }
3067     std::vector<std::string> bundleNames = dataMgr->GetAllBundleName();
3068     if (bundleNames.empty()) {
3069         LOG_E(BMS_TAG_DEFAULT, "bundleNames is empty");
3070         return;
3071     }
3072     std::vector<std::string> resourceNames;
3073     BundleResourceHelper::GetAllBundleResourceName(resourceNames);
3074 
3075     std::set<std::string> needAddResourceBundles;
3076     for (const auto &bundleName : bundleNames) {
3077         if (std::find(resourceNames.begin(), resourceNames.end(), bundleName) == resourceNames.end()) {
3078             needAddResourceBundles.insert(bundleName);
3079         }
3080     }
3081     if (needAddResourceBundles.empty()) {
3082         LOG_I(BMS_TAG_DEFAULT, "needAddResourceBundles is empty, no need to add resource");
3083         return;
3084     }
3085 
3086     for (const auto &bundleName : needAddResourceBundles) {
3087         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "-n %{public}s add resource when reboot", bundleName.c_str());
3088         BundleResourceHelper::AddResourceInfoByBundleName(bundleName, Constants::START_USERID);
3089     }
3090     LOG_I(BMS_TAG_DEFAULT, "ProcessBundleResourceInfo end");
3091 }
3092 
SendBundleUpdateFailedEvent(const BundleInfo & bundleInfo)3093 void BMSEventHandler::SendBundleUpdateFailedEvent(const BundleInfo &bundleInfo)
3094 {
3095     LOG_I(BMS_TAG_DEFAULT, "SendBundleUpdateFailedEvent start, bundleName:%{public}s", bundleInfo.name.c_str());
3096     EventInfo eventInfo;
3097     eventInfo.userId = Constants::ANY_USERID;
3098     eventInfo.bundleName = bundleInfo.name;
3099     eventInfo.versionCode = bundleInfo.versionCode;
3100     eventInfo.errCode = ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
3101     eventInfo.isPreInstallApp = bundleInfo.isPreInstallApp;
3102     EventReport::SendBundleSystemEvent(BundleEventType::UPDATE, eventInfo);
3103 }
3104 
UpdatePreinstallDB(const std::unordered_map<std::string,std::pair<std::string,bool>> & needInstallMap)3105 void BMSEventHandler::UpdatePreinstallDB(
3106     const std::unordered_map<std::string, std::pair<std::string, bool>> &needInstallMap)
3107 {
3108     for (const auto &existInfo : loadExistData_) {
3109         std::string bundleName = existInfo.first;
3110         auto it = needInstallMap.find(bundleName);
3111         if (it != needInstallMap.end()) {
3112             LOG_NOFUNC_I(BMS_TAG_DEFAULT, "%{public}s installed already update", bundleName.c_str());
3113             continue;
3114         }
3115         auto hapParseInfoMapIter = hapParseInfoMap_.find(bundleName);
3116         if (hapParseInfoMapIter == hapParseInfoMap_.end()) {
3117             LOG_NOFUNC_I(BMS_TAG_DEFAULT, "%{public}s not preinstalled", bundleName.c_str());
3118             continue;
3119         }
3120         UpdatePreinstallDBForNotUpdatedBundle(bundleName, hapParseInfoMapIter->second);
3121     }
3122 }
3123 
UpdatePreinstallDBForNotUpdatedBundle(const std::string & bundleName,const std::unordered_map<std::string,InnerBundleInfo> & innerBundleInfos)3124 void BMSEventHandler::UpdatePreinstallDBForNotUpdatedBundle(const std::string &bundleName,
3125     const std::unordered_map<std::string, InnerBundleInfo> &innerBundleInfos)
3126 {
3127     if (innerBundleInfos.empty()) {
3128         LOG_W(BMS_TAG_DEFAULT, "innerBundleInfos is empty");
3129         return;
3130     }
3131     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3132     if (dataMgr == nullptr) {
3133         LOG_W(BMS_TAG_DEFAULT, "dataMgr is nullptr");
3134         return;
3135     }
3136     PreInstallBundleInfo preInstallBundleInfo;
3137     if (!dataMgr->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
3138         LOG_W(BMS_TAG_DEFAULT, "get preinstalled bundle info failed :%{public}s", bundleName.c_str());
3139         return;
3140     }
3141     LOG_NOFUNC_I(BMS_TAG_DEFAULT, "begin update preinstall DB for %{public}s", bundleName.c_str());
3142     preInstallBundleInfo.ClearBundlePath();
3143     bool findEntry = false;
3144     for (const auto &item : innerBundleInfos) {
3145         preInstallBundleInfo.AddBundlePath(item.first);
3146         if (!findEntry) {
3147             auto applicationInfo = item.second.GetBaseApplicationInfo();
3148             item.second.AdaptMainLauncherResourceInfo(applicationInfo);
3149             preInstallBundleInfo.SetLabelId(applicationInfo.labelResource.id);
3150             preInstallBundleInfo.SetIconId(applicationInfo.iconResource.id);
3151             preInstallBundleInfo.SetModuleName(applicationInfo.labelResource.moduleName);
3152         }
3153         auto bundleInfo = item.second.GetBaseBundleInfo();
3154         if (!bundleInfo.hapModuleInfos.empty() &&
3155             bundleInfo.hapModuleInfos[0].moduleType == ModuleType::ENTRY) {
3156             findEntry = true;
3157         }
3158     }
3159     if (!dataMgr->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
3160         LOG_NOFUNC_I(BMS_TAG_DEFAULT, "update preinstall DB fail -n %{public}s", bundleName.c_str());
3161     }
3162 }
3163 
IsQuickfixFlagExsit(const BundleInfo & bundleInfo)3164 bool BMSEventHandler::IsQuickfixFlagExsit(const BundleInfo &bundleInfo)
3165 {
3166     // check the quickfix flag.
3167     for (auto const & hapModuleInfo : bundleInfo.hapModuleInfos) {
3168         for (auto const & metadata : hapModuleInfo.metadata) {
3169             if (metadata.name.compare("ohos.app.quickfix") == 0) {
3170                 return true;
3171             }
3172         }
3173     }
3174     return false;
3175 }
3176 
GetValueFromJson(nlohmann::json & jsonObject)3177 bool BMSEventHandler::GetValueFromJson(nlohmann::json &jsonObject)
3178 {
3179     const auto &jsonObjectEnd = jsonObject.end();
3180     int32_t parseResult = ERR_OK;
3181     GetValueIfFindKey<std::vector<std::string>>(jsonObject,
3182         jsonObjectEnd,
3183         RESTOR_BUNDLE_NAME_LIST,
3184         bundleNameList_,
3185         JsonType::ARRAY,
3186         false,
3187         parseResult,
3188         ArrayType::STRING);
3189     if (parseResult != ERR_OK) {
3190         LOG_E(BMS_TAG_DEFAULT, "read bundleNameList from json file error, error code : %{public}d", parseResult);
3191         return false;
3192     }
3193     return true;
3194 }
3195 
ProcessRebootQuickFixUnInstallAndRecover(const std::string & path)3196 void BMSEventHandler::ProcessRebootQuickFixUnInstallAndRecover(const std::string &path)
3197 {
3198     LOG_I(BMS_TAG_DEFAULT, "ProcessRebootQuickFixUnInstallAndRecover start");
3199     if (!BundleUtil::IsExistFile(QUICK_FIX_APP_RECOVER_FILE)) {
3200         LOG_E(BMS_TAG_DEFAULT, "end, reinstall json file is empty");
3201         return;
3202     }
3203     auto installer = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
3204     if (installer == nullptr) {
3205         LOG_E(BMS_TAG_DEFAULT, "installer is nullptr");
3206         return;
3207     }
3208     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3209     if (dataMgr == nullptr) {
3210         LOG_E(BMS_TAG_DEFAULT, "dataMgr is nullptr");
3211         return;
3212     }
3213     sptr<InnerReceiverImpl> innerReceiverImpl(new (std::nothrow) InnerReceiverImpl());
3214     if (innerReceiverImpl == nullptr) {
3215         LOG_E(BMS_TAG_DEFAULT, "innerReceiverImpl is nullptr");
3216         return;
3217     }
3218     nlohmann::json jsonObject;
3219     if (!BundleParser::ReadFileIntoJson(QUICK_FIX_APP_RECOVER_FILE, jsonObject) || !jsonObject.is_object() ||
3220         !GetValueFromJson(jsonObject)) {
3221         LOG_E(BMS_TAG_DEFAULT, "get jsonObject from path failed or get value failed");
3222         return;
3223     }
3224     for (const std::string &bundleName : bundleNameList_) {
3225         BundleInfo hasInstalledInfo;
3226         auto hasBundleInstalled =
3227             dataMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
3228         if (!hasBundleInstalled) {
3229             LOG_W(BMS_TAG_DEFAULT, "obtain bundleInfo failed, bundleName :%{public}s not exist", bundleName.c_str());
3230             continue;
3231         }
3232         if (IsQuickfixFlagExsit(hasInstalledInfo)) {
3233             // If metadata name has quickfix flag, it should be uninstall and recover.
3234             InstallParam installParam;
3235             installParam.SetIsUninstallAndRecover(true);
3236             installParam.SetKillProcess(false);
3237             installParam.needSendEvent = false;
3238             installParam.isKeepData = true;
3239             installer->UninstallAndRecover(bundleName, installParam, innerReceiverImpl);
3240         }
3241     }
3242     LOG_I(BMS_TAG_DEFAULT, "ProcessRebootQuickFixUnInstallAndRecover end");
3243 }
3244 
InnerProcessRebootUninstallWrongBundle()3245 void BMSEventHandler::InnerProcessRebootUninstallWrongBundle()
3246 {
3247     InstallParam installParam;
3248     installParam.userId = Constants::DEFAULT_USERID;
3249     installParam.SetKillProcess(false);
3250     installParam.needSendEvent = false;
3251     std::vector<std::string> wrongBundleNameList;
3252     wrongBundleNameList.emplace_back(Constants::SCENE_BOARD_BUNDLE_NAME);
3253 
3254     for (const auto &bundle : wrongBundleNameList) {
3255         SystemBundleInstaller installer;
3256         if (!installer.UninstallSystemBundle(bundle, installParam)) {
3257             LOG_W(BMS_TAG_DEFAULT, "OTA uninstall bundle %{public}s userId %{public}d error", bundle.c_str(),
3258                 installParam.userId);
3259         }
3260     }
3261 }
3262 
ProcessCheckAppEl1Dir()3263 void BMSEventHandler::ProcessCheckAppEl1Dir()
3264 {
3265     LOG_I(BMS_TAG_DEFAULT, "start");
3266     std::thread thread(ProcessCheckAppEl1DirTask);
3267     thread.detach();
3268 }
3269 
ProcessCheckAppEl1DirTask()3270 void BMSEventHandler::ProcessCheckAppEl1DirTask()
3271 {
3272     LOG_I(BMS_TAG_DEFAULT, "begin");
3273     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3274     if (dataMgr == nullptr) {
3275         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3276         return;
3277     }
3278 
3279     std::set<int32_t> userIds = dataMgr->GetAllUser();
3280     for (const auto &userId : userIds) {
3281         std::vector<BundleInfo> bundleInfos;
3282         if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, userId)) {
3283             LOG_W(BMS_TAG_DEFAULT, "GetBundleInfos failed");
3284             continue;
3285         }
3286 
3287         UpdateAppDataMgr::ProcessUpdateAppDataDir(userId, bundleInfos, ServiceConstants::DIR_EL1);
3288     }
3289     LOG_I(BMS_TAG_DEFAULT, "end");
3290 }
3291 
CleanAllBundleShaderCache() const3292 void BMSEventHandler::CleanAllBundleShaderCache() const
3293 {
3294     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3295     if (dataMgr == nullptr) {
3296         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3297         return;
3298     }
3299     std::vector<BundleInfo> bundleInfos;
3300     ErrCode res = dataMgr->GetBundleInfosV9(
3301         static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE), bundleInfos, Constants::ALL_USERID);
3302     if (res != ERR_OK) {
3303         LOG_E(BMS_TAG_DEFAULT, "GetAllBundleInfos failed");
3304         return;
3305     }
3306     for (const auto &bundleInfo : bundleInfos) {
3307         if (bundleInfo.name.empty()) {
3308             continue;
3309         }
3310         std::string shaderCachePath;
3311         shaderCachePath.append(ServiceConstants::SHADER_CACHE_PATH).append(bundleInfo.name);
3312         ErrCode res = InstalldClient::GetInstance()->CleanBundleDataDir(shaderCachePath);
3313         if (res != ERR_OK) {
3314             LOG_NOFUNC_I(BMS_TAG_DEFAULT, "%{public}s clean shader fail %{public}d", bundleInfo.name.c_str(), res);
3315         }
3316     }
3317 }
3318 
InnerProcessUninstallForExistPreBundle(const BundleInfo & installedInfo)3319 bool BMSEventHandler::InnerProcessUninstallForExistPreBundle(const BundleInfo &installedInfo)
3320 {
3321     if (installedInfo.hapModuleInfos.empty()) {
3322         LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) moduleInfos empty", installedInfo.name.c_str());
3323         return false;
3324     }
3325     bool isUpdated = std::all_of(installedInfo.hapModuleInfos.begin(), installedInfo.hapModuleInfos.end(),
3326         [] (const HapModuleInfo &moduleInfo) {
3327             return moduleInfo.hapPath.find(Constants::BUNDLE_CODE_DIR) == 0;
3328         });
3329     if (isUpdated) {
3330         LOG_I(BMS_TAG_DEFAULT, "no need to uninstall app(%{public}s) due to update", installedInfo.name.c_str());
3331         std::string moduleName;
3332         DeletePreInfoInDb(installedInfo.name, moduleName, true);
3333         if (installedInfo.isPreInstallApp) {
3334             // need update isPreInstallApp false
3335             auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3336             if (dataMgr == nullptr) {
3337                 LOG_W(BMS_TAG_DEFAULT, "DataMgr is nullptr, -n %{public}s need change isPreInstallApp",
3338                     installedInfo.name.c_str());
3339                 return isUpdated;
3340             }
3341             dataMgr->UpdateIsPreInstallApp(installedInfo.name, false);
3342         }
3343     }
3344     return isUpdated;
3345 }
3346 }  // namespace AppExecFwk
3347 }  // namespace OHOS
3348