• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "bundle_mgr_service_event_handler.h"
17 
18 #include <future>
19 #include <sys/stat.h>
20 
21 #include "accesstoken_kit.h"
22 #include "access_token.h"
23 #include "account_helper.h"
24 #include "aot/aot_handler.h"
25 #include "app_log_wrapper.h"
26 #include "app_provision_info.h"
27 #include "app_provision_info_manager.h"
28 #include "app_privilege_capability.h"
29 #include "bundle_install_checker.h"
30 #include "bundle_mgr_service.h"
31 #include "bundle_parser.h"
32 #include "bundle_permission_mgr.h"
33 #include "bundle_scanner.h"
34 #include "bundle_util.h"
35 #include "common_event_data.h"
36 #include "common_event_manager.h"
37 #include "common_event_support.h"
38 #include "common_event_subscriber.h"
39 #ifdef CONFIG_POLOCY_ENABLE
40 #include "config_policy_utils.h"
41 #endif
42 #if defined (BUNDLE_FRAMEWORK_SANDBOX_APP) && defined (DLP_PERMISSION_ENABLE)
43 #include "dlp_permission_kit.h"
44 #endif
45 #include "event_report.h"
46 #include "installd_client.h"
47 #include "parameter.h"
48 #include "perf_profile.h"
49 #ifdef WINDOW_ENABLE
50 #include "scene_board_judgement.h"
51 #endif
52 #include "status_receiver_host.h"
53 #include "system_bundle_installer.h"
54 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
55 #include "quick_fix_boot_scanner.h"
56 #endif
57 #include "want.h"
58 #include "user_unlocked_event_subscriber.h"
59 
60 namespace OHOS {
61 namespace AppExecFwk {
62 namespace {
63 const std::string SYSTEM_UI_BUNDLE_NAME = "com.ohos.systemui";
64 const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher";
65 const std::string SCENE_BOARD_BUNDLE_NAME = "com.ohos.sceneboard";
66 const std::string APP_SUFFIX = "/app";
67 const std::string TEMP_PREFIX = "temp_";
68 const std::string MODULE_PREFIX = "module_";
69 const std::string PRE_INSTALL_HSP_PATH = "/shared_bundles/";
70 const std::string BMS_TEST_UPGRADE = "persist.bms.test-upgrade";
71 // this metadata used to indicate those system application update by hotpatch upgrade.
72 const std::string HOT_PATCH_METADATA = "ohos.app.quickfix";
73 const std::string FINGERPRINT = "fingerprint";
74 const std::string UNKNOWN = "";
75 const std::string VALUE_TRUE = "true";
76 const std::string BMS_EXTENSION_SERVICE_KEY = "startup.service.ctl.broker";
77 const std::string BMS_EXTENSION_SERVICE_VALUE = "2";
78 const int32_t BMS_EXTENSION_SERVICE_SLEEP_TIME = 10; // 10s
79 const int32_t VERSION_LEN = 64;
80 const std::vector<std::string> FINGERPRINTS = {
81     "const.product.software.version",
82     "const.product.build.type",
83     "const.product.brand",
84     "const.product.name",
85     "const.product.devicetype",
86     "const.product.incremental.version",
87     "const.comp.hl.product_base_version.real"
88 };
89 const std::string HSP_VERSION_PREFIX = "v";
90 // pre bundle profile
91 constexpr const char* DEFAULT_PRE_BUNDLE_ROOT_DIR = "/system";
92 constexpr const char* PRODUCT_SUFFIX = "/etc/app";
93 constexpr const char* INSTALL_LIST_CONFIG = "/install_list.json";
94 constexpr const char* UNINSTALL_LIST_CONFIG = "/uninstall_list.json";
95 constexpr const char* INSTALL_LIST_CAPABILITY_CONFIG = "/install_list_capability.json";
96 constexpr const char* SYSTEM_RESOURCES_APP_PATH = "/system/app/ohos.global.systemres";
97 
98 std::set<PreScanInfo> installList_;
99 std::set<std::string> uninstallList_;
100 std::set<PreBundleConfigInfo> installListCapabilities_;
101 bool hasLoadPreInstallProFile_ = false;
102 
MoveTempPath(const std::vector<std::string> & fromPaths,const std::string & bundleName,std::vector<std::string> & toPaths)103 void MoveTempPath(const std::vector<std::string> &fromPaths,
104     const std::string &bundleName, std::vector<std::string> &toPaths)
105 {
106     std::string tempDir =
107         Constants::HAP_COPY_PATH + Constants::PATH_SEPARATOR + TEMP_PREFIX + bundleName;
108     if (!BundleUtil::CreateDir(tempDir)) {
109         APP_LOGE("create tempdir failed %{public}s", tempDir.c_str());
110         return;
111     }
112 
113     int32_t hapIndex = 0;
114     for (const auto &path : fromPaths) {
115         auto toPath = tempDir + Constants::PATH_SEPARATOR + MODULE_PREFIX
116             + std::to_string(hapIndex) + Constants::INSTALL_FILE_SUFFIX;
117         hapIndex++;
118         if (InstalldClient::GetInstance()->MoveFile(path, toPath) != ERR_OK) {
119             APP_LOGW("move from %{public}s to %{public}s failed", path.c_str(), toPath.c_str());
120             continue;
121         }
122 
123         toPaths.emplace_back(toPath);
124     }
125 }
126 
127 class InnerReceiverImpl : public StatusReceiverHost {
128 public:
129     InnerReceiverImpl() = default;
130     virtual ~InnerReceiverImpl() override = default;
131 
SetBundleName(const std::string & bundleName)132     void SetBundleName(const std::string &bundleName)
133     {
134         bundleName_ = bundleName;
135     }
136 
OnStatusNotify(const int progress)137     virtual void OnStatusNotify(const int progress) override {}
OnFinished(const int32_t resultCode,const std::string & resultMsg)138     virtual void OnFinished(
139         const int32_t resultCode, const std::string &resultMsg) override
140     {
141         if (bundleName_.empty()) {
142             return;
143         }
144 
145         std::string tempDir = Constants::HAP_COPY_PATH
146             + Constants::PATH_SEPARATOR + TEMP_PREFIX + bundleName_;
147         APP_LOGD("delete tempDir %{public}s", tempDir.c_str());
148         BundleUtil::DeleteDir(tempDir);
149     }
150 
151 private:
152     std::string bundleName_;
153 };
154 }
155 
BMSEventHandler()156 BMSEventHandler::BMSEventHandler()
157 {
158     APP_LOGD("instance is created");
159 }
160 
~BMSEventHandler()161 BMSEventHandler::~BMSEventHandler()
162 {
163     APP_LOGD("instance is destroyed");
164 }
165 
BmsStartEvent()166 void BMSEventHandler::BmsStartEvent()
167 {
168     APP_LOGI("BMSEventHandler BmsStartEvent start");
169     BeforeBmsStart();
170     OnBmsStarting();
171     AfterBmsStart();
172     APP_LOGI("BMSEventHandler BmsStartEvent end");
173 }
174 
BeforeBmsStart()175 void BMSEventHandler::BeforeBmsStart()
176 {
177     needNotifyBundleScanStatus_ = false;
178     if (!BundlePermissionMgr::Init()) {
179         APP_LOGW("BundlePermissionMgr::Init failed");
180     }
181 
182     EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_START);
183 }
184 
OnBmsStarting()185 void BMSEventHandler::OnBmsStarting()
186 {
187     APP_LOGI("BMSEventHandler OnBmsStarting start");
188     // Judge whether there is install info in the persistent Db
189     if (LoadInstallInfosFromDb()) {
190         APP_LOGI("OnBmsStarting Load install info from db success");
191         BundleRebootStartEvent();
192         return;
193     }
194 
195     // If the preInstall infos does not exist in preInstall db,
196     // all preInstall directory applications will be reinstalled.
197     if (!LoadAllPreInstallBundleInfos()) {
198         APP_LOGE("OnBmsStarting Load all preInstall bundleInfos failed.");
199         needRebootOta_ = true;
200     }
201 
202     /* Guard against install infos lossed strategy.
203      * 1. Scan user data dir
204      *   1.1. If no data, first boot.
205      *   1.2. If has data, but parse data to InnerBundleUserInfos failed,
206      *        reInstall all app from install dir and preInstall dir
207      *   1.3. If has data and parse data to InnerBundleUserInfos success, goto 2
208      * 2. Scan installDir include common install dir and preInstall dir
209      *    And the parse the hap to InnerBundleInfos
210      * 3. Combine InnerBundleInfos and InnerBundleUserInfos to cache and db
211      * 4. According to needRebootOta determine whether OTA detection is required
212      */
213     ResultCode resultCode = GuardAgainstInstallInfosLossedStrategy();
214     switch (resultCode) {
215         case ResultCode::RECOVER_OK: {
216             APP_LOGI("OnBmsStarting Guard against install infos lossed strategy take effect.");
217             if (needRebootOta_) {
218                 BundleRebootStartEvent();
219             } else {
220                 needNotifyBundleScanStatus_ = true;
221             }
222 
223             break;
224         }
225         case ResultCode::REINSTALL_OK: {
226             APP_LOGI("OnBmsStarting ReInstall all haps.");
227             needNotifyBundleScanStatus_ = true;
228             break;
229         }
230         case ResultCode::NO_INSTALLED_DATA: {
231             // First boot
232             APP_LOGI("OnBmsStarting first boot.");
233             BundleBootStartEvent();
234             break;
235         }
236         default:
237             APP_LOGE("System internal error, install informations missing.");
238             break;
239     }
240 
241     SaveSystemFingerprint();
242     APP_LOGI("BMSEventHandler OnBmsStarting end");
243 }
244 
AfterBmsStart()245 void BMSEventHandler::AfterBmsStart()
246 {
247     APP_LOGI("BMSEventHandler AfterBmsStart start");
248 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
249     DelayedSingleton<QuickFixBootScanner>::GetInstance()->ProcessQuickFixBootUp();
250 #endif
251     DelayedSingleton<BundleMgrService>::GetInstance()->CheckAllUser();
252     BundlePermissionMgr::UnInit();
253     SetAllInstallFlag();
254     HandleSceneBoard();
255     DelayedSingleton<BundleMgrService>::GetInstance()->RegisterService();
256     EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_END);
257     ClearCache();
258     if (needNotifyBundleScanStatus_) {
259         DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
260     }
261     ListeningUserUnlocked();
262     RemoveUnreservedSandbox();
263     DelayedSingleton<BundleMgrService>::GetInstance()->GetAOTLoopTask()->ScheduleLoopTask();
264     StartBmsExtensionService();
265     APP_LOGI("BMSEventHandler AfterBmsStart end");
266 }
267 
ClearCache()268 void BMSEventHandler::ClearCache()
269 {
270     hapParseInfoMap_.clear();
271     loadExistData_.clear();
272     hasLoadAllPreInstallBundleInfosFromDb_ = false;
273 }
274 
LoadInstallInfosFromDb()275 bool BMSEventHandler::LoadInstallInfosFromDb()
276 {
277     APP_LOGD("Load install infos from db");
278     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
279     if (dataMgr == nullptr) {
280         APP_LOGE("DataMgr is nullptr");
281         return false;
282     }
283 
284     return dataMgr->LoadDataFromPersistentStorage();
285 }
286 
BundleBootStartEvent()287 void BMSEventHandler::BundleBootStartEvent()
288 {
289     OnBundleBootStart(Constants::DEFAULT_USERID);
290     PerfProfile::GetInstance().Dump();
291 }
292 
BundleRebootStartEvent()293 void BMSEventHandler::BundleRebootStartEvent()
294 {
295 #ifdef USE_PRE_BUNDLE_PROFILE
296     if (LoadPreInstallProFile()) {
297         UpdateAllPrivilegeCapability();
298     }
299 #endif
300 
301     if (IsSystemUpgrade()) {
302         OnBundleRebootStart();
303         SaveSystemFingerprint();
304         AOTHandler::GetInstance().HandleOTA();
305     }
306 
307     needNotifyBundleScanStatus_ = true;
308 }
309 
GuardAgainstInstallInfosLossedStrategy()310 ResultCode BMSEventHandler::GuardAgainstInstallInfosLossedStrategy()
311 {
312     APP_LOGD("GuardAgainstInstallInfosLossedStrategy start");
313     // Check user path, and parse userData to InnerBundleUserInfo
314     std::map<std::string, std::vector<InnerBundleUserInfo>> innerBundleUserInfoMaps;
315     ScanResultCode scanResultCode = ScanAndAnalyzeUserDatas(innerBundleUserInfoMaps);
316     if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
317         APP_LOGE("Scan the user data directory failed");
318         return ResultCode::NO_INSTALLED_DATA;
319     }
320 
321     // When data exist, but parse all userinfo fails, reinstall all app.
322     // For example: the AT database is lost or others.
323     if (scanResultCode == ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED) {
324         // Reinstall all app from install dir
325         return ReInstallAllInstallDirApps();
326     }
327 
328     // When data exist and parse all userinfo success,
329     // it can be judged that some bundles has installed.
330     // Check install dir, and parse the hap in install dir to InnerBundleInfo
331     std::map<std::string, std::vector<InnerBundleInfo>> installInfos;
332     ScanAndAnalyzeInstallInfos(installInfos);
333     if (installInfos.empty()) {
334         APP_LOGE("check bundle path failed due to hap lossd or parse failed");
335         return ResultCode::SYSTEM_ERROR;
336     }
337 
338     // Combine InnerBundleInfo and InnerBundleUserInfo
339     if (!CombineBundleInfoAndUserInfo(installInfos, innerBundleUserInfoMaps)) {
340         APP_LOGE("System internal error");
341         return ResultCode::SYSTEM_ERROR;
342     }
343 
344     return ResultCode::RECOVER_OK;
345 }
346 
ScanAndAnalyzeUserDatas(std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)347 ScanResultCode BMSEventHandler::ScanAndAnalyzeUserDatas(
348     std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
349 {
350     ScanResultCode scanResultCode = ScanResultCode::SCAN_NO_DATA;
351     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
352     if (dataMgr == nullptr) {
353         APP_LOGE("dataMgr is null");
354         return scanResultCode;
355     }
356 
357     std::string baseDataDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[0];
358     std::vector<std::string> userIds;
359     if (!ScanDir(baseDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userIds)) {
360         APP_LOGD("Check the base user directory(%{public}s) failed", baseDataDir.c_str());
361         return scanResultCode;
362     }
363 
364     for (const auto &userId : userIds) {
365         int32_t userIdInt = Constants::INVALID_USERID;
366         if (!StrToInt(userId, userIdInt)) {
367             APP_LOGE("UserId(%{public}s) strToInt failed", userId.c_str());
368             continue;
369         }
370 
371         dataMgr->AddUserId(userIdInt);
372         std::vector<std::string> userDataBundleNames;
373         std::string userDataDir = baseDataDir + Constants::PATH_SEPARATOR + userId + Constants::BASE;
374         if (!ScanDir(userDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userDataBundleNames)) {
375             APP_LOGD("Check the user installation directory(%{public}s) failed", userDataDir.c_str());
376             continue;
377         }
378 
379         for (const auto &userDataBundleName : userDataBundleNames) {
380             if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
381                 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED;
382             }
383 
384             if (AnalyzeUserData(userIdInt, userDataDir, userDataBundleName, userMaps)) {
385                 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_SUCCESS;
386             }
387         }
388     }
389 
390     return scanResultCode;
391 }
392 
AnalyzeUserData(int32_t userId,const std::string & userDataDir,const std::string & userDataBundleName,std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)393 bool BMSEventHandler::AnalyzeUserData(
394     int32_t userId, const std::string &userDataDir, const std::string &userDataBundleName,
395     std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
396 {
397     if (userDataDir.empty() || userDataBundleName.empty()) {
398         APP_LOGE("UserDataDir or UserDataBundleName is empty");
399         return false;
400     }
401 
402     std::string userDataBundlePath = userDataDir + userDataBundleName;
403     APP_LOGD("Analyze user data path(%{public}s)", userDataBundlePath.c_str());
404     FileStat fileStat;
405     if (InstalldClient::GetInstance()->GetFileStat(userDataBundlePath, fileStat) != ERR_OK) {
406         APP_LOGE("GetFileStat path(%{public}s) failed", userDataBundlePath.c_str());
407         return false;
408     }
409 
410     // It should be a bundleName dir
411     if (!fileStat.isDir) {
412         APP_LOGE("UserDataBundlePath(%{public}s) is not dir", userDataBundlePath.c_str());
413         return false;
414     }
415 
416     InnerBundleUserInfo innerBundleUserInfo;
417     innerBundleUserInfo.bundleName = userDataBundleName;
418     innerBundleUserInfo.bundleUserInfo.userId = userId;
419     innerBundleUserInfo.uid = fileStat.uid;
420     innerBundleUserInfo.gids.emplace_back(fileStat.gid);
421     innerBundleUserInfo.installTime = fileStat.lastModifyTime;
422     innerBundleUserInfo.updateTime = innerBundleUserInfo.installTime;
423     auto accessTokenIdEx = OHOS::Security::AccessToken::AccessTokenKit::GetHapTokenIDEx(
424         innerBundleUserInfo.bundleUserInfo.userId, userDataBundleName, 0);
425     if (accessTokenIdEx.tokenIdExStruct.tokenID == 0) {
426         APP_LOGE("get tokenId failed.");
427         return false;
428     }
429 
430     innerBundleUserInfo.accessTokenId = accessTokenIdEx.tokenIdExStruct.tokenID;
431     innerBundleUserInfo.accessTokenIdEx = accessTokenIdEx.tokenIDEx;
432     auto userIter = userMaps.find(userDataBundleName);
433     if (userIter == userMaps.end()) {
434         std::vector<InnerBundleUserInfo> innerBundleUserInfos = { innerBundleUserInfo };
435         userMaps.emplace(userDataBundleName, innerBundleUserInfos);
436         return true;
437     }
438 
439     userMaps.at(userDataBundleName).emplace_back(innerBundleUserInfo);
440     return true;
441 }
442 
ReInstallAllInstallDirApps()443 ResultCode BMSEventHandler::ReInstallAllInstallDirApps()
444 {
445     // First, reinstall all preInstall app from preInstall dir
446     std::vector<std::string> preInstallDirs;
447     GetPreInstallDir(preInstallDirs);
448     for (const auto &preInstallDir : preInstallDirs) {
449         std::vector<std::string> filePaths { preInstallDir };
450         bool removable = IsPreInstallRemovable(preInstallDir);
451         if (!OTAInstallSystemBundle(
452             filePaths, Constants::AppType::SYSTEM_APP, removable)) {
453             APP_LOGE("Reinstall bundle(%{public}s) error.", preInstallDir.c_str());
454             continue;
455         }
456     }
457 
458     auto installer = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
459     if (installer == nullptr) {
460         APP_LOGE("installer is nullptr");
461         return ResultCode::SYSTEM_ERROR;
462     }
463 
464     // Second, reInstall all common install app from install dir
465     std::map<std::string, std::vector<std::string>> hapPathsMap;
466     ScanInstallDir(hapPathsMap);
467     for (const auto &hapPaths : hapPathsMap) {
468         InstallParam installParam;
469         installParam.userId = Constants::ALL_USERID;
470         installParam.installFlag = InstallFlag::REPLACE_EXISTING;
471         sptr<InnerReceiverImpl> innerReceiverImpl(new (std::nothrow) InnerReceiverImpl());
472         innerReceiverImpl->SetBundleName(hapPaths.first);
473         std::vector<std::string> tempHaps;
474         MoveTempPath(hapPaths.second, hapPaths.first, tempHaps);
475         installer->Install(tempHaps, installParam, innerReceiverImpl);
476     }
477 
478     return ResultCode::REINSTALL_OK;
479 }
480 
ScanAndAnalyzeInstallInfos(std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)481 void BMSEventHandler::ScanAndAnalyzeInstallInfos(
482     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
483 {
484     // Scan the installed directory
485     std::map<std::string, std::vector<std::string>> hapPathsMap;
486     ScanInstallDir(hapPathsMap);
487     AnalyzeHaps(false, hapPathsMap, installInfos);
488 
489     // Scan preBundle directory
490     std::vector<std::string> preInstallDirs;
491     GetPreInstallDir(preInstallDirs);
492     AnalyzeHaps(true, preInstallDirs, installInfos);
493 }
494 
ScanInstallDir(std::map<std::string,std::vector<std::string>> & hapPathsMap)495 void BMSEventHandler::ScanInstallDir(
496     std::map<std::string, std::vector<std::string>> &hapPathsMap)
497 {
498     APP_LOGD("Scan the installed directory start");
499     std::vector<std::string> bundleNameList;
500     if (!ScanDir(Constants::BUNDLE_CODE_DIR, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, bundleNameList)) {
501         APP_LOGE("Check the bundle directory(%{public}s) failed", Constants::BUNDLE_CODE_DIR);
502         return;
503     }
504 
505     for (const auto &bundleName : bundleNameList) {
506         std::vector<std::string> hapPaths;
507         auto appCodePath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName;
508         if (!ScanDir(appCodePath, ScanMode::SUB_FILE_FILE, ResultMode::ABSOLUTE_PATH, hapPaths)) {
509             APP_LOGE("Scan the appCodePath(%{public}s) failed", appCodePath.c_str());
510             continue;
511         }
512 
513         if (hapPaths.empty()) {
514             APP_LOGD("The directory(%{public}s) scan result is empty", appCodePath.c_str());
515             continue;
516         }
517 
518         std::vector<std::string> checkHapPaths = CheckHapPaths(hapPaths);
519         hapPathsMap.emplace(bundleName, checkHapPaths);
520     }
521 
522     APP_LOGD("Scan the installed directory end");
523 }
524 
CheckHapPaths(const std::vector<std::string> & hapPaths)525 std::vector<std::string> BMSEventHandler::CheckHapPaths(
526     const std::vector<std::string> &hapPaths)
527 {
528     std::vector<std::string> checkHapPaths;
529     for (const auto &hapPath : hapPaths) {
530         if (!BundleUtil::CheckFileType(hapPath, Constants::INSTALL_FILE_SUFFIX)) {
531             APP_LOGE("Check hapPath(%{public}s) failed", hapPath.c_str());
532             continue;
533         }
534 
535         checkHapPaths.emplace_back(hapPath);
536     }
537 
538     return checkHapPaths;
539 }
540 
GetPreInstallRootDirList(std::vector<std::string> & rootDirList)541 void BMSEventHandler::GetPreInstallRootDirList(std::vector<std::string> &rootDirList)
542 {
543 #ifdef CONFIG_POLOCY_ENABLE
544     auto cfgDirList = GetCfgDirList();
545     if (cfgDirList != nullptr) {
546         for (const auto &cfgDir : cfgDirList->paths) {
547             if (cfgDir == nullptr) {
548                 continue;
549             }
550 
551             APP_LOGI("BMSEventHandler cfgDir: %{public}s ", cfgDir);
552             rootDirList.emplace_back(cfgDir);
553         }
554 
555         FreeCfgDirList(cfgDirList);
556     }
557 #endif
558     bool ret = std::find(
559         rootDirList.begin(), rootDirList.end(), DEFAULT_PRE_BUNDLE_ROOT_DIR) != rootDirList.end();
560     if (!ret) {
561         rootDirList.emplace_back(DEFAULT_PRE_BUNDLE_ROOT_DIR);
562     }
563 }
564 
ClearPreInstallCache()565 void BMSEventHandler::ClearPreInstallCache()
566 {
567     if (!hasLoadPreInstallProFile_) {
568         return;
569     }
570 
571     installList_.clear();
572     uninstallList_.clear();
573     installListCapabilities_.clear();
574     hasLoadPreInstallProFile_ = false;
575 }
576 
LoadPreInstallProFile()577 bool BMSEventHandler::LoadPreInstallProFile()
578 {
579     if (hasLoadPreInstallProFile_) {
580         return !installList_.empty();
581     }
582 
583     std::vector<std::string> rootDirList;
584     GetPreInstallRootDirList(rootDirList);
585     if (rootDirList.empty()) {
586         APP_LOGE("dirList is empty");
587         return false;
588     }
589 
590     for (const auto &rootDir : rootDirList) {
591         ParsePreBundleProFile(rootDir + PRODUCT_SUFFIX);
592     }
593 
594     hasLoadPreInstallProFile_ = true;
595     return !installList_.empty();
596 }
597 
HasPreInstallProfile()598 bool BMSEventHandler::HasPreInstallProfile()
599 {
600     return !installList_.empty();
601 }
602 
ParsePreBundleProFile(const std::string & dir)603 void BMSEventHandler::ParsePreBundleProFile(const std::string &dir)
604 {
605     BundleParser bundleParser;
606     bundleParser.ParsePreInstallConfig(
607         dir + INSTALL_LIST_CONFIG, installList_);
608     bundleParser.ParsePreUnInstallConfig(
609         dir + UNINSTALL_LIST_CONFIG, uninstallList_);
610     bundleParser.ParsePreInstallAbilityConfig(
611         dir + INSTALL_LIST_CAPABILITY_CONFIG, installListCapabilities_);
612 }
613 
GetPreInstallDir(std::vector<std::string> & bundleDirs)614 void BMSEventHandler::GetPreInstallDir(std::vector<std::string> &bundleDirs)
615 {
616 #ifdef USE_PRE_BUNDLE_PROFILE
617     if (LoadPreInstallProFile()) {
618         GetPreInstallDirFromLoadProFile(bundleDirs);
619         return;
620     }
621 #endif
622 
623     GetPreInstallDirFromScan(bundleDirs);
624 }
625 
GetPreInstallDirFromLoadProFile(std::vector<std::string> & bundleDirs)626 void BMSEventHandler::GetPreInstallDirFromLoadProFile(std::vector<std::string> &bundleDirs)
627 {
628     for (const auto &installInfo : installList_) {
629         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
630             APP_LOGW("bundle(%{public}s) not allowed installed", installInfo.bundleDir.c_str());
631             continue;
632         }
633 
634         bundleDirs.emplace_back(installInfo.bundleDir);
635     }
636 }
637 
GetPreInstallDirFromScan(std::vector<std::string> & bundleDirs)638 void BMSEventHandler::GetPreInstallDirFromScan(std::vector<std::string> &bundleDirs)
639 {
640     std::list<std::string> scanbundleDirs;
641     GetBundleDirFromScan(scanbundleDirs);
642     std::copy(scanbundleDirs.begin(), scanbundleDirs.end(), std::back_inserter(bundleDirs));
643 }
644 
AnalyzeHaps(bool isPreInstallApp,const std::map<std::string,std::vector<std::string>> & hapPathsMap,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)645 void BMSEventHandler::AnalyzeHaps(
646     bool isPreInstallApp,
647     const std::map<std::string, std::vector<std::string>> &hapPathsMap,
648     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
649 {
650     for (const auto &hapPaths : hapPathsMap) {
651         AnalyzeHaps(isPreInstallApp, hapPaths.second, installInfos);
652     }
653 }
654 
AnalyzeHaps(bool isPreInstallApp,const std::vector<std::string> & bundleDirs,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)655 void BMSEventHandler::AnalyzeHaps(
656     bool isPreInstallApp,
657     const std::vector<std::string> &bundleDirs,
658     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
659 {
660     for (const auto &bundleDir : bundleDirs) {
661         std::unordered_map<std::string, InnerBundleInfo> hapInfos;
662         if (!CheckAndParseHapFiles(bundleDir, isPreInstallApp, hapInfos) || hapInfos.empty()) {
663             APP_LOGE("Parse bundleDir(%{public}s) failed", bundleDir.c_str());
664             continue;
665         }
666 
667         CollectInstallInfos(hapInfos, installInfos);
668     }
669 }
670 
CollectInstallInfos(const std::unordered_map<std::string,InnerBundleInfo> & hapInfos,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)671 void BMSEventHandler::CollectInstallInfos(
672     const std::unordered_map<std::string, InnerBundleInfo> &hapInfos,
673     std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
674 {
675     for (const auto &hapInfoIter : hapInfos) {
676         auto bundleName = hapInfoIter.second.GetBundleName();
677         if (installInfos.find(bundleName) == installInfos.end()) {
678             std::vector<InnerBundleInfo> innerBundleInfos { hapInfoIter.second };
679             installInfos.emplace(bundleName, innerBundleInfos);
680             continue;
681         }
682 
683         installInfos.at(bundleName).emplace_back(hapInfoIter.second);
684     }
685 }
686 
CombineBundleInfoAndUserInfo(const std::map<std::string,std::vector<InnerBundleInfo>> & installInfos,const std::map<std::string,std::vector<InnerBundleUserInfo>> & userInfoMaps)687 bool BMSEventHandler::CombineBundleInfoAndUserInfo(
688     const std::map<std::string, std::vector<InnerBundleInfo>> &installInfos,
689     const std::map<std::string, std::vector<InnerBundleUserInfo>> &userInfoMaps)
690 {
691     APP_LOGD("Combine code information and user data start");
692     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
693     if (dataMgr == nullptr) {
694         APP_LOGE("dataMgr is null");
695         return false;
696     }
697 
698     if (installInfos.empty() || userInfoMaps.empty()) {
699         APP_LOGE("bundleInfos or userInfos is empty");
700         return false;
701     }
702 
703     for (auto hasInstallInfo : installInfos) {
704         auto bundleName = hasInstallInfo.first;
705         auto userIter = userInfoMaps.find(bundleName);
706         if (userIter == userInfoMaps.end()) {
707             APP_LOGE("User data directory missing with bundle %{public}s ", bundleName.c_str());
708             needRebootOta_ = true;
709             continue;
710         }
711 
712         for (auto &info : hasInstallInfo.second) {
713             SaveInstallInfoToCache(info);
714         }
715 
716         for (const auto &userInfo : userIter->second) {
717             dataMgr->AddInnerBundleUserInfo(bundleName, userInfo);
718         }
719     }
720 
721     // Parsing uid, gids and other user information
722     dataMgr->RestoreUidAndGid();
723     // Load all bundle state data from jsonDb
724     dataMgr->LoadAllBundleStateDataFromJsonDb();
725     APP_LOGD("Combine code information and user data end");
726     return true;
727 }
728 
SaveInstallInfoToCache(InnerBundleInfo & info)729 void BMSEventHandler::SaveInstallInfoToCache(InnerBundleInfo &info)
730 {
731     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
732     if (dataMgr == nullptr) {
733         APP_LOGE("dataMgr is null");
734         return;
735     }
736 
737     auto bundleName = info.GetBundleName();
738     auto appCodePath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName;
739     info.SetAppCodePath(appCodePath);
740 
741     std::string dataBaseDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[1]
742         + Constants::DATABASE + bundleName;
743     info.SetAppDataBaseDir(dataBaseDir);
744 
745     auto moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
746     info.AddModuleSrcDir(moduleDir);
747     info.AddModuleResPath(moduleDir);
748 
749     bool bundleExist = false;
750     InnerBundleInfo dbInfo;
751     {
752         auto &mtx = dataMgr->GetBundleMutex(bundleName);
753         std::lock_guard lock { mtx };
754         bundleExist = dataMgr->GetInnerBundleInfo(bundleName, dbInfo);
755         if (bundleExist) {
756             dataMgr->EnableBundle(bundleName);
757         }
758     }
759 
760     if (!bundleExist) {
761         dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_START);
762         dataMgr->AddInnerBundleInfo(bundleName, info);
763         dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS);
764         return;
765     }
766 
767     auto& hapModuleName = info.GetCurModuleName();
768     std::vector<std::string> dbModuleNames;
769     dbInfo.GetModuleNames(dbModuleNames);
770     auto iter = std::find(dbModuleNames.begin(), dbModuleNames.end(), hapModuleName);
771     if (iter != dbModuleNames.end()) {
772         APP_LOGE("module(%{public}s) has install", hapModuleName.c_str());
773         return;
774     }
775 
776     dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_START);
777     dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_SUCCESS);
778     dataMgr->AddNewModuleInfo(bundleName, info, dbInfo);
779 }
780 
ScanDir(const std::string & dir,ScanMode scanMode,ResultMode resultMode,std::vector<std::string> & resultList)781 bool BMSEventHandler::ScanDir(
782     const std::string& dir, ScanMode scanMode, ResultMode resultMode, std::vector<std::string> &resultList)
783 {
784     APP_LOGD("Scan the directory(%{public}s) start", dir.c_str());
785     ErrCode result = InstalldClient::GetInstance()->ScanDir(dir, scanMode, resultMode, resultList);
786     if (result != ERR_OK) {
787         APP_LOGE("Scan the directory(%{public}s) failed", dir.c_str());
788         return false;
789     }
790 
791     return true;
792 }
793 
OnBundleBootStart(int32_t userId)794 void BMSEventHandler::OnBundleBootStart(int32_t userId)
795 {
796 #ifdef USE_PRE_BUNDLE_PROFILE
797     if (LoadPreInstallProFile()) {
798         APP_LOGI("Process boot bundle install from pre bundle proFile for userId:%{public}d", userId);
799         InnerProcessBootPreBundleProFileInstall(userId);
800         return;
801     }
802 #else
803     ProcessBootBundleInstallFromScan(userId);
804 #endif
805 }
806 
ProcessBootBundleInstallFromScan(int32_t userId)807 void BMSEventHandler::ProcessBootBundleInstallFromScan(int32_t userId)
808 {
809     APP_LOGD("Process boot bundle install from scan");
810     std::list<std::string> bundleDirs;
811     GetBundleDirFromScan(bundleDirs);
812     for (auto item : bundleDirs) {
813         ProcessSystemBundleInstall(item, Constants::AppType::SYSTEM_APP, userId);
814     }
815 }
816 
GetBundleDirFromScan(std::list<std::string> & bundleDirs)817 void BMSEventHandler::GetBundleDirFromScan(std::list<std::string> &bundleDirs)
818 {
819     std::vector<std::string> rootDirList;
820     GetPreInstallRootDirList(rootDirList);
821     if (rootDirList.empty()) {
822         APP_LOGE("rootDirList is empty");
823         return;
824     }
825 
826     for (const auto &rootDir : rootDirList) {
827         ProcessScanDir(rootDir + APP_SUFFIX, bundleDirs);
828     }
829 
830     auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), SYSTEM_RESOURCES_APP_PATH);
831     if (iter != bundleDirs.end()) {
832         bundleDirs.erase(iter);
833         bundleDirs.insert(bundleDirs.begin(), SYSTEM_RESOURCES_APP_PATH);
834     }
835 }
836 
ProcessScanDir(const std::string & dir,std::list<std::string> & bundleDirs)837 void BMSEventHandler::ProcessScanDir(const std::string &dir, std::list<std::string> &bundleDirs)
838 {
839     BundleScanner scanner;
840     std::list<std::string> bundleList = scanner.Scan(dir);
841     for (auto item : bundleList) {
842         auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), item);
843         if (iter == bundleDirs.end()) {
844             bundleDirs.push_back(item);
845         }
846     }
847 }
848 
InnerProcessBootPreBundleProFileInstall(int32_t userId)849 void BMSEventHandler::InnerProcessBootPreBundleProFileInstall(int32_t userId)
850 {
851     std::list<std::string> hspDirs;
852     std::list<PreScanInfo> normalSystemApps;
853     for (const auto &installInfo : installList_) {
854         APP_LOGD("Inner process boot preBundle proFile install %{public}s", installInfo.ToString().c_str());
855         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
856             APP_LOGW("bundle(%{public}s) not allowed installed when boot", installInfo.bundleDir.c_str());
857             continue;
858         }
859         if (installInfo.bundleDir.find(PRE_INSTALL_HSP_PATH) != std::string::npos) {
860             APP_LOGD("found hsp path: %{public}s", installInfo.bundleDir.c_str());
861             hspDirs.emplace_back(installInfo.bundleDir);
862         } else {
863             normalSystemApps.emplace_back(installInfo);
864         }
865     }
866 
867     for (const auto &hspDir : hspDirs) {
868         ProcessSystemSharedBundleInstall(hspDir, Constants::AppType::SYSTEM_APP);
869     }
870 
871     for (const auto &installInfo : normalSystemApps) {
872         ProcessSystemBundleInstall(installInfo, Constants::AppType::SYSTEM_APP, userId);
873     }
874 }
875 
ProcessSystemBundleInstall(const PreScanInfo & preScanInfo,Constants::AppType appType,int32_t userId)876 void BMSEventHandler::ProcessSystemBundleInstall(
877     const PreScanInfo &preScanInfo, Constants::AppType appType, int32_t userId)
878 {
879     APP_LOGD("Process system bundle install by bundleDir(%{public}s)", preScanInfo.bundleDir.c_str());
880     InstallParam installParam;
881     installParam.userId = userId;
882     installParam.isPreInstallApp = true;
883     installParam.noSkipsKill = false;
884     installParam.needSendEvent = false;
885     installParam.removable = preScanInfo.removable;
886     installParam.needSavePreInstallInfo = true;
887     installParam.copyHapToInstallPath = false;
888     SystemBundleInstaller installer;
889     if (!installer.InstallSystemBundle(preScanInfo.bundleDir, installParam, appType)) {
890         APP_LOGW("Install System app:%{public}s error", preScanInfo.bundleDir.c_str());
891     }
892 }
893 
ProcessSystemBundleInstall(const std::string & bundleDir,Constants::AppType appType,int32_t userId)894 void BMSEventHandler::ProcessSystemBundleInstall(
895     const std::string &bundleDir, Constants::AppType appType, int32_t userId)
896 {
897     APP_LOGD("Process system bundle install by bundleDir(%{public}s)", bundleDir.c_str());
898     InstallParam installParam;
899     installParam.userId = userId;
900     installParam.isPreInstallApp = true;
901     installParam.noSkipsKill = false;
902     installParam.needSendEvent = false;
903     installParam.removable = false;
904     installParam.needSavePreInstallInfo = true;
905     installParam.copyHapToInstallPath = false;
906     SystemBundleInstaller installer;
907     if (!installer.InstallSystemBundle(bundleDir, installParam, appType)) {
908         APP_LOGW("Install System app:%{public}s error", bundleDir.c_str());
909     }
910 }
911 
ProcessSystemSharedBundleInstall(const std::string & sharedBundlePath,Constants::AppType appType)912 void BMSEventHandler::ProcessSystemSharedBundleInstall(const std::string &sharedBundlePath, Constants::AppType appType)
913 {
914     APP_LOGD("Process system shared bundle by sharedBundlePath(%{public}s)", sharedBundlePath.c_str());
915     InstallParam installParam;
916     installParam.isPreInstallApp = true;
917     installParam.noSkipsKill = false;
918     installParam.needSendEvent = false;
919     installParam.removable = false;
920     installParam.needSavePreInstallInfo = true;
921     installParam.sharedBundleDirPaths = {sharedBundlePath};
922     SystemBundleInstaller installer;
923     if (!installer.InstallSystemSharedBundle(installParam, false, appType)) {
924         APP_LOGW("install system shared bundle: %{public}s error", sharedBundlePath.c_str());
925     }
926 }
927 
SetAllInstallFlag() const928 void BMSEventHandler::SetAllInstallFlag() const
929 {
930     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
931     if (dataMgr == nullptr) {
932         APP_LOGE("DataMgr is nullptr");
933         return;
934     }
935 
936     dataMgr->SetInitialUserFlag(true);
937 }
938 
OnBundleRebootStart()939 void BMSEventHandler::OnBundleRebootStart()
940 {
941     ProcessRebootBundle();
942 }
943 
ProcessRebootBundle()944 void BMSEventHandler::ProcessRebootBundle()
945 {
946     APP_LOGI("BMSEventHandler Process reboot bundle start");
947     LoadAllPreInstallBundleInfos();
948     ProcessRebootBundleInstall();
949     ProcessRebootBundleUninstall();
950 }
951 
LoadAllPreInstallBundleInfos()952 bool BMSEventHandler::LoadAllPreInstallBundleInfos()
953 {
954     if (hasLoadAllPreInstallBundleInfosFromDb_) {
955         APP_LOGI("Has load all preInstall bundleInfos from db");
956         return true;
957     }
958 
959     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
960     if (dataMgr == nullptr) {
961         APP_LOGE("DataMgr is nullptr");
962         return false;
963     }
964 
965     std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
966     for (auto &iter : preInstallBundleInfos) {
967         APP_LOGW("load preInstallBundleInfos: %{public}s ", iter.GetBundleName().c_str());
968         loadExistData_.emplace(iter.GetBundleName(), iter);
969     }
970 
971     hasLoadAllPreInstallBundleInfosFromDb_ = true;
972     return !preInstallBundleInfos.empty();
973 }
974 
ProcessRebootBundleInstall()975 void BMSEventHandler::ProcessRebootBundleInstall()
976 {
977     APP_LOGI("BMSEventHandler Process reboot bundle install start");
978 #ifdef USE_PRE_BUNDLE_PROFILE
979     if (LoadPreInstallProFile()) {
980         ProcessReBootPreBundleProFileInstall();
981         return;
982     }
983 #else
984     ProcessRebootBundleInstallFromScan();
985 #endif
986 }
987 
ProcessReBootPreBundleProFileInstall()988 void BMSEventHandler::ProcessReBootPreBundleProFileInstall()
989 {
990     std::list<std::string> bundleDirs;
991     std::list<std::string> sharedBundleDirs;
992     for (const auto &installInfo : installList_) {
993         APP_LOGI("Process reboot preBundle proFile install %{public}s", installInfo.ToString().c_str());
994         if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
995             APP_LOGW("bundle(%{public}s) not allowed installed when reboot", installInfo.bundleDir.c_str());
996             continue;
997         }
998 
999         if (installInfo.bundleDir.find(PRE_INSTALL_HSP_PATH) != std::string::npos) {
1000             APP_LOGI("found shared bundle path: %{private}s", installInfo.bundleDir.c_str());
1001             sharedBundleDirs.emplace_back(installInfo.bundleDir);
1002         } else {
1003             bundleDirs.emplace_back(installInfo.bundleDir);
1004         }
1005     }
1006 
1007     InnerProcessRebootSharedBundleInstall(sharedBundleDirs, Constants::AppType::SYSTEM_APP);
1008     InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
1009     InnerProcessStockBundleProvisionInfo();
1010 }
1011 
ProcessRebootBundleInstallFromScan()1012 void BMSEventHandler::ProcessRebootBundleInstallFromScan()
1013 {
1014     APP_LOGD("Process reboot bundle install from scan");
1015     std::list<std::string> bundleDirs;
1016     GetBundleDirFromScan(bundleDirs);
1017     InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
1018     InnerProcessStockBundleProvisionInfo();
1019 }
1020 
InnerProcessRebootBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)1021 void BMSEventHandler::InnerProcessRebootBundleInstall(
1022     const std::list<std::string> &scanPathList, Constants::AppType appType)
1023 {
1024     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1025     if (dataMgr == nullptr) {
1026         APP_LOGE("DataMgr is nullptr");
1027         return;
1028     }
1029 
1030     for (auto &scanPathIter : scanPathList) {
1031         APP_LOGI("InnerProcessRebootBundleInstall reboot scan bundle path: %{public}s ", scanPathIter.c_str());
1032         bool removable = IsPreInstallRemovable(scanPathIter);
1033         std::unordered_map<std::string, InnerBundleInfo> infos;
1034         if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
1035             APP_LOGE("obtain bundleinfo failed : %{public}s ", scanPathIter.c_str());
1036             continue;
1037         }
1038 
1039         auto bundleName = infos.begin()->second.GetBundleName();
1040         auto hapVersionCode = infos.begin()->second.GetVersionCode();
1041         AddParseInfosToMap(bundleName, infos);
1042         auto mapIter = loadExistData_.find(bundleName);
1043         if (mapIter == loadExistData_.end()) {
1044             APP_LOGI("OTA Install new bundle(%{public}s) by path(%{private}s).",
1045                 bundleName.c_str(), scanPathIter.c_str());
1046             std::vector<std::string> filePaths { scanPathIter };
1047             if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1048                 APP_LOGE("OTA Install new bundle(%{public}s) error.", bundleName.c_str());
1049             }
1050 
1051             continue;
1052         }
1053 
1054         APP_LOGI("OTA process bundle(%{public}s) by path(%{private}s).",
1055             bundleName.c_str(), scanPathIter.c_str());
1056         BundleInfo hasInstalledInfo;
1057         auto hasBundleInstalled = dataMgr->GetBundleInfo(
1058             bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
1059         if (!hasBundleInstalled) {
1060             APP_LOGW("app(%{public}s) has been uninstalled and do not OTA install.",
1061                 bundleName.c_str());
1062             if (!removable) {
1063                 std::vector<std::string> filePaths { scanPathIter };
1064                 if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1065                     APP_LOGE("OTA Install prefab bundle(%{public}s) error.", bundleName.c_str());
1066                 }
1067             }
1068             continue;
1069         }
1070 
1071         if (HotPatchAppProcessing(bundleName)) {
1072             APP_LOGI("OTA Install prefab bundle(%{public}s) by path(%{private}s) for hotPath upgrade.",
1073                 bundleName.c_str(), scanPathIter.c_str());
1074             std::vector<std::string> filePaths { scanPathIter };
1075             if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1076                 APP_LOGE("OTA Install prefab bundle(%{public}s) error.", bundleName.c_str());
1077             }
1078 
1079             continue;
1080         }
1081 
1082         std::vector<std::string> filePaths;
1083         bool updateSelinuxLabel = false;
1084         bool updateBundle = false;
1085         for (auto item : infos) {
1086             auto parserModuleNames = item.second.GetModuleNameVec();
1087             if (parserModuleNames.empty()) {
1088                 APP_LOGE("module is empty when parser path(%{public}s).", item.first.c_str());
1089                 continue;
1090             }
1091             // Generally, when the versionCode of Hap is greater than the installed versionCode,
1092             // Except for the uninstalled app, they can be installed or upgraded directly by OTA.
1093             if (hasInstalledInfo.versionCode < hapVersionCode) {
1094                 APP_LOGI("OTA update module(%{public}s) by path(%{private}s)",
1095                     parserModuleNames[0].c_str(), item.first.c_str());
1096                 updateBundle = true;
1097                 break;
1098             }
1099 
1100             // When the accessTokenIdEx is equal to 0, the old application needs to be updated.
1101             if (hasInstalledInfo.applicationInfo.accessTokenIdEx == 0) {
1102                 APP_LOGD("OTA update module(%{public}s) by path(%{private}s), accessTokenIdEx is equal to 0",
1103                     parserModuleNames[0].c_str(), item.first.c_str());
1104                 updateBundle = true;
1105                 break;
1106             }
1107 
1108             // The versionCode of Hap is equal to the installed versionCode.
1109             // You can only install new modules by OTA
1110             if (hasInstalledInfo.versionCode == hapVersionCode) {
1111                 // update pre install app data dir selinux label
1112                 if (!updateSelinuxLabel) {
1113                     UpdateAppDataSelinuxLabel(bundleName, hasInstalledInfo.applicationInfo.appPrivilegeLevel,
1114                         hasInstalledInfo.isPreInstallApp,
1115                         hasInstalledInfo.applicationInfo.debug);
1116                     updateSelinuxLabel = true;
1117                 }
1118                 // Used to judge whether the module has been installed.
1119                 bool hasModuleInstalled = std::find(
1120                     hasInstalledInfo.hapModuleNames.begin(), hasInstalledInfo.hapModuleNames.end(),
1121                     parserModuleNames[0]) != hasInstalledInfo.hapModuleNames.end();
1122                 if (hasModuleInstalled) {
1123                     if (UpdateModuleByHash(hasInstalledInfo, item.second)) {
1124                         updateBundle = true;
1125                         break;
1126                     }
1127                     APP_LOGD("module(%{public}s) has been installed and versionCode is same.",
1128                         parserModuleNames[0].c_str());
1129                     continue;
1130                 }
1131 
1132                 APP_LOGI("OTA install module(%{public}s) by path(%{private}s)",
1133                     parserModuleNames[0].c_str(), item.first.c_str());
1134                 filePaths.emplace_back(item.first);
1135             }
1136         }
1137 
1138         if (updateBundle) {
1139             filePaths.clear();
1140             filePaths.emplace_back(scanPathIter);
1141         }
1142 
1143         if (filePaths.empty()) {
1144 #ifdef USE_PRE_BUNDLE_PROFILE
1145             UpdateRemovable(bundleName, removable);
1146 #endif
1147             continue;
1148         }
1149 
1150         if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1151             APP_LOGE("OTA bundle(%{public}s) failed", bundleName.c_str());
1152 #ifdef USE_PRE_BUNDLE_PROFILE
1153             UpdateRemovable(bundleName, removable);
1154 #endif
1155         }
1156     }
1157 }
1158 
UpdateModuleByHash(const BundleInfo & oldBundleInfo,const InnerBundleInfo & newInfo) const1159 bool BMSEventHandler::UpdateModuleByHash(const BundleInfo &oldBundleInfo, const InnerBundleInfo &newInfo) const
1160 {
1161     auto moduleName = newInfo.GetModuleNameVec().at(0);
1162     std::string existModuleHash;
1163     for (auto hapInfo : oldBundleInfo.hapModuleInfos) {
1164         if (hapInfo.package == moduleName) {
1165             existModuleHash = hapInfo.buildHash;
1166         }
1167     }
1168     std::string curModuleHash;
1169     if (!newInfo.GetModuleBuildHash(moduleName, curModuleHash)) {
1170         APP_LOGD("module(%{public}s) is not existed.", moduleName.c_str());
1171         return false;
1172     }
1173     if (existModuleHash != curModuleHash) {
1174         APP_LOGD("module(%{public}s) buildHash changed, so update corresponding hap or hsp.", moduleName.c_str());
1175         return true;
1176     }
1177     return false;
1178 }
1179 
InnerProcessRebootSharedBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)1180 void BMSEventHandler::InnerProcessRebootSharedBundleInstall(
1181     const std::list<std::string> &scanPathList, Constants::AppType appType)
1182 {
1183     APP_LOGD("InnerProcessRebootSharedBundleInstall");
1184     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1185     if (dataMgr == nullptr) {
1186         APP_LOGE("DataMgr is nullptr");
1187         return;
1188     }
1189     for (const auto &scanPath : scanPathList) {
1190         bool removable = IsPreInstallRemovable(scanPath);
1191         std::unordered_map<std::string, InnerBundleInfo> infos;
1192         if (!ParseHapFiles(scanPath, infos) || infos.empty()) {
1193             APP_LOGE("obtain bundleinfo failed : %{public}s ", scanPath.c_str());
1194             continue;
1195         }
1196 
1197         auto bundleName = infos.begin()->second.GetBundleName();
1198         auto versionCode = infos.begin()->second.GetVersionCode();
1199         AddParseInfosToMap(bundleName, infos);
1200         auto mapIter = loadExistData_.find(bundleName);
1201         if (mapIter == loadExistData_.end()) {
1202             APP_LOGI("OTA Install new shared bundle(%{public}s) by path(%{private}s).",
1203                 bundleName.c_str(), scanPath.c_str());
1204             if (!OTAInstallSystemSharedBundle({scanPath}, appType, removable)) {
1205                 APP_LOGE("OTA Install new shared bundle(%{public}s) error.", bundleName.c_str());
1206             }
1207             continue;
1208         }
1209 
1210         InnerBundleInfo oldBundleInfo;
1211         bool hasInstalled = dataMgr->FetchInnerBundleInfo(bundleName, oldBundleInfo);
1212         if (!hasInstalled) {
1213             APP_LOGW("app(%{public}s) has been uninstalled and do not OTA install.", bundleName.c_str());
1214             continue;
1215         }
1216 
1217         if (oldBundleInfo.GetVersionCode() > versionCode) {
1218             APP_LOGD("the installed version is up-to-date");
1219             continue;
1220         }
1221         if (oldBundleInfo.GetVersionCode() == versionCode) {
1222             if (!IsNeedToUpdateSharedAppByHash(oldBundleInfo, infos.begin()->second)) {
1223                 APP_LOGD("the installed version is up-to-date");
1224                 continue;
1225             }
1226         }
1227 
1228         if (!OTAInstallSystemSharedBundle({scanPath}, appType, removable)) {
1229             APP_LOGE("OTA update shared bundle(%{public}s) error.", bundleName.c_str());
1230         }
1231     }
1232 }
1233 
IsNeedToUpdateSharedAppByHash(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const1234 bool BMSEventHandler::IsNeedToUpdateSharedAppByHash(
1235     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
1236 {
1237     auto oldSharedModuleMap = oldInfo.GetInnerSharedModuleInfos();
1238     auto newSharedModuleMap = newInfo.GetInnerSharedModuleInfos();
1239     for (const auto &item : newSharedModuleMap) {
1240         auto newModuleName = item.first;
1241         auto oldModuleInfos = oldSharedModuleMap[newModuleName];
1242         auto newModuleInfos = item.second;
1243         if (!oldModuleInfos.empty() && !newModuleInfos.empty()) {
1244             auto oldBuildHash = oldModuleInfos[0].buildHash;
1245             auto newBuildHash = newModuleInfos[0].buildHash;
1246             return oldBuildHash != newBuildHash;
1247         } else {
1248             return true;
1249         }
1250     }
1251     return false;
1252 }
1253 
IsHotPatchApp(const std::string & bundleName)1254 bool BMSEventHandler::IsHotPatchApp(const std::string &bundleName)
1255 {
1256     InnerBundleInfo innerBundleInfo;
1257     if (!FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
1258         APP_LOGE("can not get InnerBundleInfo, bundleName=%{public}s", bundleName.c_str());
1259         return false;
1260     }
1261 
1262     return innerBundleInfo.CheckSpecialMetaData(HOT_PATCH_METADATA);
1263 }
1264 
HotPatchAppProcessing(const std::string & bundleName)1265 bool BMSEventHandler::HotPatchAppProcessing(const std::string &bundleName)
1266 {
1267     if (bundleName.empty()) {
1268         APP_LOGW("bundleName:%{public}s empty", bundleName.c_str());
1269         return false;
1270     }
1271 
1272     if (IsHotPatchApp(bundleName)) {
1273         APP_LOGI("get hotpatch meta-data success, bundleName=%{public}s", bundleName.c_str());
1274         SystemBundleInstaller installer;
1275         if (!installer.UninstallSystemBundle(bundleName, true)) {
1276             APP_LOGE("keep data to uninstall app(%{public}s) error", bundleName.c_str());
1277             return false;
1278         }
1279         return true;
1280     }
1281     return false;
1282 }
1283 
SaveSystemFingerprint()1284 void BMSEventHandler::SaveSystemFingerprint()
1285 {
1286     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1287     if (bmsPara == nullptr) {
1288         APP_LOGE("bmsPara is nullptr");
1289         return;
1290     }
1291 
1292     std::string curSystemFingerprint = GetCurSystemFingerprint();
1293     APP_LOGI("curSystemFingerprint(%{public}s)", curSystemFingerprint.c_str());
1294     if (curSystemFingerprint.empty()) {
1295         return;
1296     }
1297 
1298     bmsPara->SaveBmsParam(FINGERPRINT, curSystemFingerprint);
1299 }
1300 
IsSystemUpgrade()1301 bool BMSEventHandler::IsSystemUpgrade()
1302 {
1303     return IsTestSystemUpgrade() || IsSystemFingerprintChanged();
1304 }
1305 
IsTestSystemUpgrade()1306 bool BMSEventHandler::IsTestSystemUpgrade()
1307 {
1308     std::string paramValue;
1309     if (!GetSystemParameter(BMS_TEST_UPGRADE, paramValue) || paramValue.empty()) {
1310         return false;
1311     }
1312 
1313     APP_LOGI("TestSystemUpgrade value is %{public}s", paramValue.c_str());
1314     return paramValue == VALUE_TRUE;
1315 }
1316 
IsSystemFingerprintChanged()1317 bool BMSEventHandler::IsSystemFingerprintChanged()
1318 {
1319     std::string oldSystemFingerprint = GetOldSystemFingerprint();
1320     if (oldSystemFingerprint.empty()) {
1321         APP_LOGD("System should be upgraded due to oldSystemFingerprint is empty");
1322         return true;
1323     }
1324 
1325     std::string curSystemFingerprint = GetCurSystemFingerprint();
1326     APP_LOGD("oldSystemFingerprint(%{public}s), curSystemFingerprint(%{public}s)",
1327         oldSystemFingerprint.c_str(), curSystemFingerprint.c_str());
1328     return curSystemFingerprint != oldSystemFingerprint;
1329 }
1330 
GetCurSystemFingerprint()1331 std::string BMSEventHandler::GetCurSystemFingerprint()
1332 {
1333     std::string curSystemFingerprint;
1334     for (const auto &item : FINGERPRINTS) {
1335         std::string itemFingerprint;
1336         if (!GetSystemParameter(item, itemFingerprint) || itemFingerprint.empty()) {
1337             continue;
1338         }
1339 
1340         if (!curSystemFingerprint.empty()) {
1341             curSystemFingerprint.append(Constants::PATH_SEPARATOR);
1342         }
1343 
1344         curSystemFingerprint.append(itemFingerprint);
1345     }
1346 
1347     return curSystemFingerprint;
1348 }
1349 
GetSystemParameter(const std::string & key,std::string & value)1350 bool BMSEventHandler::GetSystemParameter(const std::string &key, std::string &value)
1351 {
1352     char firmware[VERSION_LEN] = {0};
1353     int32_t ret = GetParameter(key.c_str(), UNKNOWN.c_str(), firmware, VERSION_LEN);
1354     if (ret <= 0) {
1355         APP_LOGE("GetParameter failed!");
1356         return false;
1357     }
1358 
1359     value = firmware;
1360     return true;
1361 }
1362 
GetOldSystemFingerprint()1363 std::string BMSEventHandler::GetOldSystemFingerprint()
1364 {
1365     std::string oldSystemFingerprint;
1366     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1367     if (bmsPara != nullptr) {
1368         bmsPara->GetBmsParam(FINGERPRINT, oldSystemFingerprint);
1369     }
1370 
1371     return oldSystemFingerprint;
1372 }
1373 
AddParseInfosToMap(const std::string & bundleName,const std::unordered_map<std::string,InnerBundleInfo> & infos)1374 void BMSEventHandler::AddParseInfosToMap(
1375     const std::string &bundleName, const std::unordered_map<std::string, InnerBundleInfo> &infos)
1376 {
1377     auto hapParseInfoMapIter = hapParseInfoMap_.find(bundleName);
1378     if (hapParseInfoMapIter == hapParseInfoMap_.end()) {
1379         hapParseInfoMap_.emplace(bundleName, infos);
1380         return;
1381     }
1382 
1383     auto iterMap = hapParseInfoMapIter->second;
1384     for (auto infoIter : infos) {
1385         iterMap.emplace(infoIter.first, infoIter.second);
1386     }
1387 
1388     hapParseInfoMap_.at(bundleName) = iterMap;
1389 }
1390 
ProcessRebootBundleUninstall()1391 void BMSEventHandler::ProcessRebootBundleUninstall()
1392 {
1393     APP_LOGI("Reboot scan and OTA uninstall start");
1394     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1395     if (dataMgr == nullptr) {
1396         APP_LOGE("DataMgr is nullptr");
1397         return;
1398     }
1399 
1400     for (auto &loadIter : loadExistData_) {
1401         std::string bundleName = loadIter.first;
1402         auto listIter = hapParseInfoMap_.find(bundleName);
1403         if (listIter == hapParseInfoMap_.end()) {
1404             APP_LOGI("ProcessRebootBundleUninstall OTA uninstall app(%{public}s).", bundleName.c_str());
1405             SystemBundleInstaller installer;
1406             if (!installer.UninstallSystemBundle(bundleName)) {
1407                 APP_LOGE("OTA uninstall app(%{public}s) error", bundleName.c_str());
1408             } else {
1409                 std::string moduleName;
1410                 DeletePreInfoInDb(bundleName, moduleName, true);
1411             }
1412 
1413             continue;
1414         }
1415 
1416         BundleInfo hasInstalledInfo;
1417         auto hasBundleInstalled = dataMgr->GetBundleInfo(
1418             bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
1419         if (!hasBundleInstalled) {
1420             APP_LOGW("app(%{public}s) maybe has been uninstall.", bundleName.c_str());
1421             continue;
1422         }
1423 
1424         // Check the installed module.
1425         // If the corresponding Hap does not exist, it should be uninstalled.
1426         for (auto moduleName : hasInstalledInfo.hapModuleNames) {
1427             bool hasModuleHapExist = false;
1428             for (auto parserInfoIter : listIter->second) {
1429                 auto parserModuleNames = parserInfoIter.second.GetModuleNameVec();
1430                 if (!parserModuleNames.empty() && moduleName == parserModuleNames[0]) {
1431                     hasModuleHapExist = true;
1432                     break;
1433                 }
1434             }
1435 
1436             if (!hasModuleHapExist) {
1437                 APP_LOGI("ProcessRebootBundleUninstall OTA app(%{public}s) uninstall module(%{public}s).",
1438                     bundleName.c_str(), moduleName.c_str());
1439                 SystemBundleInstaller installer;
1440                 if (!installer.UninstallSystemBundle(bundleName, moduleName)) {
1441                     APP_LOGE("OTA app(%{public}s) uninstall module(%{public}s) error.",
1442                         bundleName.c_str(), moduleName.c_str());
1443                 }
1444             }
1445         }
1446 
1447         // Check the preInstall path in Db.
1448         // If the corresponding Hap does not exist, it should be deleted.
1449         auto parserInfoMap = listIter->second;
1450         for (auto preBundlePath : loadIter.second.GetBundlePaths()) {
1451             auto parserInfoIter = parserInfoMap.find(preBundlePath);
1452             if (parserInfoIter != parserInfoMap.end()) {
1453                 APP_LOGI("ProcessRebootBundleUninstall OTA uninstall app(%{public}s) module path(%{private}s) exits.",
1454                     bundleName.c_str(), preBundlePath.c_str());
1455                 continue;
1456             }
1457 
1458             APP_LOGI("ProcessRebootBundleUninstall OTA app(%{public}s) delete path(%{private}s).",
1459                 bundleName.c_str(), preBundlePath.c_str());
1460             DeletePreInfoInDb(bundleName, preBundlePath, false);
1461         }
1462     }
1463 
1464     APP_LOGI("Reboot scan and OTA uninstall success");
1465 }
1466 
DeletePreInfoInDb(const std::string & bundleName,const std::string & bundlePath,bool bundleLevel)1467 void BMSEventHandler::DeletePreInfoInDb(
1468     const std::string &bundleName, const std::string &bundlePath, bool bundleLevel)
1469 {
1470     APP_LOGD("DeletePreInfoInDb bundle(%{public}s)", bundleName.c_str());
1471     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1472     if (dataMgr == nullptr) {
1473         APP_LOGE("DataMgr is nullptr");
1474         return;
1475     }
1476 
1477     PreInstallBundleInfo preInstallBundleInfo;
1478     preInstallBundleInfo.SetBundleName(bundleName);
1479     if (bundleLevel) {
1480         APP_LOGD("DeletePreInfoInDb bundle bundleLevel");
1481         dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1482         return;
1483     }
1484 
1485     APP_LOGD("DeletePreInfoInDb bundle not bundleLevel with path(%{private}s)",
1486         bundlePath.c_str());
1487     dataMgr->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo);
1488     preInstallBundleInfo.DeleteBundlePath(bundlePath);
1489     if (preInstallBundleInfo.GetBundlePaths().empty()) {
1490         dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1491     } else {
1492         dataMgr->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1493     }
1494 }
1495 
HasModuleSavedInPreInstalledDb(const std::string & bundleName,const std::string & bundlePath)1496 bool BMSEventHandler::HasModuleSavedInPreInstalledDb(
1497     const std::string &bundleName, const std::string &bundlePath)
1498 {
1499     auto preInstallIter = loadExistData_.find(bundleName);
1500     if (preInstallIter == loadExistData_.end()) {
1501         APP_LOGE("app(%{public}s) does not save in PreInstalledDb.", bundleName.c_str());
1502         return false;
1503     }
1504 
1505     return preInstallIter->second.HasBundlePath(bundlePath);
1506 }
1507 
OTAInstallSystemBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)1508 bool BMSEventHandler::OTAInstallSystemBundle(
1509     const std::vector<std::string> &filePaths,
1510     Constants::AppType appType,
1511     bool removable)
1512 {
1513     if (filePaths.empty()) {
1514         APP_LOGE("File path is empty");
1515         return false;
1516     }
1517 
1518     InstallParam installParam;
1519     installParam.isPreInstallApp = true;
1520     installParam.noSkipsKill = false;
1521     installParam.needSendEvent = false;
1522     installParam.installFlag = InstallFlag::REPLACE_EXISTING;
1523     installParam.removable = removable;
1524     installParam.needSavePreInstallInfo = true;
1525     installParam.copyHapToInstallPath = false;
1526     installParam.isOTA = true;
1527     SystemBundleInstaller installer;
1528     return installer.OTAInstallSystemBundle(filePaths, installParam, appType);
1529 }
1530 
OTAInstallSystemSharedBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)1531 bool BMSEventHandler::OTAInstallSystemSharedBundle(
1532     const std::vector<std::string> &filePaths,
1533     Constants::AppType appType,
1534     bool removable)
1535 {
1536     if (filePaths.empty()) {
1537         APP_LOGE("File path is empty");
1538         return false;
1539     }
1540 
1541     InstallParam installParam;
1542     installParam.isPreInstallApp = true;
1543     installParam.needSendEvent = false;
1544     installParam.installFlag = InstallFlag::REPLACE_EXISTING;
1545     installParam.removable = removable;
1546     installParam.needSavePreInstallInfo = true;
1547     installParam.sharedBundleDirPaths = filePaths;
1548     installParam.isOTA = true;
1549     SystemBundleInstaller installer;
1550     return installer.InstallSystemSharedBundle(installParam, true, appType);
1551 }
1552 
CheckAndParseHapFiles(const std::string & hapFilePath,bool isPreInstallApp,std::unordered_map<std::string,InnerBundleInfo> & infos)1553 bool BMSEventHandler::CheckAndParseHapFiles(
1554     const std::string &hapFilePath,
1555     bool isPreInstallApp,
1556     std::unordered_map<std::string, InnerBundleInfo> &infos)
1557 {
1558     std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
1559         std::make_unique<BundleInstallChecker>();
1560     std::vector<std::string> hapFilePathVec { hapFilePath };
1561     std::vector<std::string> realPaths;
1562     auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
1563     if (ret != ERR_OK) {
1564         APP_LOGE("File path %{public}s invalid", hapFilePath.c_str());
1565         return false;
1566     }
1567 
1568     ret = bundleInstallChecker->CheckSysCap(realPaths);
1569     if (ret != ERR_OK) {
1570         APP_LOGE("hap(%{public}s) syscap check failed", hapFilePath.c_str());
1571         return false;
1572     }
1573 
1574     std::vector<Security::Verify::HapVerifyResult> hapVerifyResults;
1575     ret = bundleInstallChecker->CheckMultipleHapsSignInfo(realPaths, hapVerifyResults);
1576     if (ret != ERR_OK) {
1577         APP_LOGE("CheckMultipleHapsSignInfo %{public}s failed", hapFilePath.c_str());
1578         return false;
1579     }
1580 
1581     InstallCheckParam checkParam;
1582     checkParam.isPreInstallApp = isPreInstallApp;
1583     if (isPreInstallApp) {
1584         checkParam.appType = Constants::AppType::SYSTEM_APP;
1585     }
1586 
1587     ret = bundleInstallChecker->ParseHapFiles(
1588         realPaths, checkParam, hapVerifyResults, infos);
1589     if (ret != ERR_OK) {
1590         APP_LOGE("parse haps file(%{public}s) failed", hapFilePath.c_str());
1591         return false;
1592     }
1593 
1594     ret = bundleInstallChecker->CheckAppLabelInfo(infos);
1595     if (ret != ERR_OK) {
1596         APP_LOGE("Check APP label failed %{public}d", ret);
1597         return false;
1598     }
1599 
1600     // set hapPath
1601     std::for_each(infos.begin(), infos.end(), [](auto &item) {
1602         item.second.SetModuleHapPath(item.first);
1603     });
1604 
1605     return true;
1606 }
1607 
ParseHapFiles(const std::string & hapFilePath,std::unordered_map<std::string,InnerBundleInfo> & infos)1608 bool BMSEventHandler::ParseHapFiles(
1609     const std::string &hapFilePath,
1610     std::unordered_map<std::string, InnerBundleInfo> &infos)
1611 {
1612     std::vector<std::string> hapFilePathVec { hapFilePath };
1613     std::vector<std::string> realPaths;
1614     auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
1615     if (ret != ERR_OK) {
1616         APP_LOGE("File path %{public}s invalid", hapFilePath.c_str());
1617         return false;
1618     }
1619 
1620     BundleParser bundleParser;
1621     for (auto realPath : realPaths) {
1622         InnerBundleInfo innerBundleInfo;
1623         ret = bundleParser.Parse(realPath, innerBundleInfo);
1624         if (ret != ERR_OK) {
1625             APP_LOGE("Parse bundle info failed, error: %{public}d", ret);
1626             continue;
1627         }
1628 
1629         infos.emplace(realPath, innerBundleInfo);
1630     }
1631 
1632     if (infos.empty()) {
1633         APP_LOGE("Parse hap(%{public}s) empty ", hapFilePath.c_str());
1634         return false;
1635     }
1636 
1637     return true;
1638 }
1639 
IsPreInstallRemovable(const std::string & path)1640 bool BMSEventHandler::IsPreInstallRemovable(const std::string &path)
1641 {
1642 #ifdef USE_PRE_BUNDLE_PROFILE
1643     if (!HasPreInstallProfile()) {
1644         return false;
1645     }
1646 
1647     if (!hasLoadPreInstallProFile_) {
1648         APP_LOGE("Not load preInstall proFile or release.");
1649         return false;
1650     }
1651 
1652     if (path.empty() || installList_.empty()) {
1653         APP_LOGE("path or installList is empty.");
1654         return false;
1655     }
1656     auto installInfo = std::find_if(installList_.begin(), installList_.end(),
1657         [path](const auto &installInfo) {
1658         return installInfo.bundleDir == path;
1659     });
1660     if (installInfo != installList_.end()) {
1661         return (*installInfo).removable;
1662     }
1663     return true;
1664 #else
1665     return false;
1666 #endif
1667 }
1668 
GetPreInstallCapability(PreBundleConfigInfo & preBundleConfigInfo)1669 bool BMSEventHandler::GetPreInstallCapability(PreBundleConfigInfo &preBundleConfigInfo)
1670 {
1671     if (!hasLoadPreInstallProFile_) {
1672         APP_LOGE("Not load preInstall proFile or release.");
1673         return false;
1674     }
1675 
1676     if (preBundleConfigInfo.bundleName.empty() || installListCapabilities_.empty()) {
1677         APP_LOGE("BundleName or installListCapabilities is empty.");
1678         return false;
1679     }
1680 
1681     auto iter = installListCapabilities_.find(preBundleConfigInfo);
1682     if (iter == installListCapabilities_.end()) {
1683         APP_LOGD("BundleName(%{public}s) no has preinstall capability.",
1684             preBundleConfigInfo.bundleName.c_str());
1685         return false;
1686     }
1687 
1688     preBundleConfigInfo = *iter;
1689     return true;
1690 }
1691 
1692 #ifdef USE_PRE_BUNDLE_PROFILE
UpdateRemovable(const std::string & bundleName,bool removable)1693 void BMSEventHandler::UpdateRemovable(const std::string &bundleName, bool removable)
1694 {
1695     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1696     if (dataMgr == nullptr) {
1697         APP_LOGE("DataMgr is nullptr");
1698         return;
1699     }
1700 
1701     dataMgr->UpdateRemovable(bundleName, removable);
1702 }
1703 
UpdateAllPrivilegeCapability()1704 void BMSEventHandler::UpdateAllPrivilegeCapability()
1705 {
1706     for (const auto &preBundleConfigInfo : installListCapabilities_) {
1707         UpdatePrivilegeCapability(preBundleConfigInfo);
1708     }
1709 }
1710 
UpdatePrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)1711 void BMSEventHandler::UpdatePrivilegeCapability(
1712     const PreBundleConfigInfo &preBundleConfigInfo)
1713 {
1714     auto &bundleName = preBundleConfigInfo.bundleName;
1715     InnerBundleInfo innerBundleInfo;
1716     if (!FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
1717         APP_LOGW("App(%{public}s) is not installed.", bundleName.c_str());
1718         return;
1719     }
1720 
1721     if (!MatchSignature(preBundleConfigInfo, innerBundleInfo.GetCertificateFingerprint())) {
1722         APP_LOGW("App(%{public}s) signature verify failed", bundleName.c_str());
1723         return;
1724     }
1725 
1726     UpdateTrustedPrivilegeCapability(preBundleConfigInfo);
1727 }
1728 
MatchSignature(const PreBundleConfigInfo & configInfo,const std::string & signature)1729 bool BMSEventHandler::MatchSignature(
1730     const PreBundleConfigInfo &configInfo, const std::string &signature)
1731 {
1732     if (configInfo.appSignature.empty()) {
1733         APP_LOGW("appSignature is empty");
1734         return false;
1735     }
1736 
1737     return std::find(configInfo.appSignature.begin(),
1738         configInfo.appSignature.end(), signature) != configInfo.appSignature.end();
1739 }
1740 
UpdateTrustedPrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)1741 void BMSEventHandler::UpdateTrustedPrivilegeCapability(
1742     const PreBundleConfigInfo &preBundleConfigInfo)
1743 {
1744     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1745     if (dataMgr == nullptr) {
1746         APP_LOGE("DataMgr is nullptr");
1747         return;
1748     }
1749 
1750     ApplicationInfo appInfo;
1751     appInfo.keepAlive = preBundleConfigInfo.keepAlive;
1752     appInfo.singleton = preBundleConfigInfo.singleton;
1753     appInfo.runningResourcesApply = preBundleConfigInfo.runningResourcesApply;
1754     appInfo.associatedWakeUp = preBundleConfigInfo.associatedWakeUp;
1755     appInfo.allowCommonEvent = preBundleConfigInfo.allowCommonEvent;
1756     appInfo.resourcesApply = preBundleConfigInfo.resourcesApply;
1757     dataMgr->UpdatePrivilegeCapability(preBundleConfigInfo.bundleName, appInfo);
1758 }
1759 #endif
1760 
FetchInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & innerBundleInfo)1761 bool BMSEventHandler::FetchInnerBundleInfo(
1762     const std::string &bundleName, InnerBundleInfo &innerBundleInfo)
1763 {
1764     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1765     if (dataMgr == nullptr) {
1766         APP_LOGE("DataMgr is nullptr");
1767         return false;
1768     }
1769 
1770     return dataMgr->FetchInnerBundleInfo(bundleName, innerBundleInfo);
1771 }
1772 
ListeningUserUnlocked() const1773 void BMSEventHandler::ListeningUserUnlocked() const
1774 {
1775     APP_LOGI("BMSEventHandler listen the unlock of someone user start.");
1776     EventFwk::MatchingSkills matchingSkills;
1777     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
1778     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
1779     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
1780     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
1781 
1782     auto subscriberPtr = std::make_shared<UserUnlockedEventSubscriber>(subscribeInfo);
1783     if (!EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberPtr)) {
1784         APP_LOGW("BMSEventHandler subscribe common event %{public}s failed",
1785             EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED.c_str());
1786     }
1787 }
1788 
RemoveUnreservedSandbox() const1789 void BMSEventHandler::RemoveUnreservedSandbox() const
1790 {
1791 #if defined (BUNDLE_FRAMEWORK_SANDBOX_APP) && defined (DLP_PERMISSION_ENABLE)
1792     APP_LOGI("Start to RemoveUnreservedSandbox");
1793     const int32_t WAIT_TIMES = 40;
1794     const int32_t EACH_TIME = 1000; // 1000ms
1795     auto execFunc = [](int32_t waitTimes, int32_t eachTime) {
1796         int32_t currentUserId = Constants::INVALID_USERID;
1797         while (waitTimes--) {
1798             std::this_thread::sleep_for(std::chrono::milliseconds(eachTime));
1799             APP_LOGD("wait for account started");
1800             if (currentUserId == Constants::INVALID_USERID) {
1801                 currentUserId = AccountHelper::GetCurrentActiveUserId();
1802                 APP_LOGD("current active userId is %{public}d", currentUserId);
1803                 if (currentUserId == Constants::INVALID_USERID) {
1804                     continue;
1805                 }
1806             }
1807             APP_LOGI("RemoveUnreservedSandbox call ClearUnreservedSandbox");
1808             Security::DlpPermission::DlpPermissionKit::ClearUnreservedSandbox();
1809             break;
1810         }
1811     };
1812     std::thread removeThread(execFunc, WAIT_TIMES, EACH_TIME);
1813     removeThread.detach();
1814 #endif
1815     APP_LOGI("RemoveUnreservedSandbox finish");
1816 }
1817 
StartBmsExtensionService() const1818 void BMSEventHandler::StartBmsExtensionService() const
1819 {
1820     APP_LOGD("Start to start bms extension service");
1821     auto execFunc = [](int32_t sleepTime, const std::string &key, const std::string &value) {
1822         std::this_thread::sleep_for(std::chrono::seconds(sleepTime));
1823         int32_t ret = SetParameter(key.c_str(), value.c_str());
1824         if (ret <= 0) {
1825             APP_LOGE("SetParameter failed!");
1826             return;
1827         }
1828     };
1829     std::thread startBmsExtensionServiceThread(execFunc, BMS_EXTENSION_SERVICE_SLEEP_TIME, BMS_EXTENSION_SERVICE_KEY,
1830         BMS_EXTENSION_SERVICE_VALUE);
1831     startBmsExtensionServiceThread.detach();
1832 }
1833 
AddStockAppProvisionInfoByOTA(const std::string & bundleName,const std::string & filePath)1834 void BMSEventHandler::AddStockAppProvisionInfoByOTA(const std::string &bundleName, const std::string &filePath)
1835 {
1836     APP_LOGD("AddStockAppProvisionInfoByOTA bundleName: %{public}s", bundleName.c_str());
1837     // parse profile info
1838     Security::Verify::HapVerifyResult hapVerifyResult;
1839     auto ret = BundleVerifyMgr::ParseHapProfile(filePath, hapVerifyResult);
1840     if (ret != ERR_OK) {
1841         APP_LOGE("BundleVerifyMgr::HapVerify failed, bundleName: %{public}s, errCode: %{public}d",
1842             bundleName.c_str(), ret);
1843         return;
1844     }
1845 
1846     std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
1847         std::make_unique<BundleInstallChecker>();
1848     AppProvisionInfo appProvisionInfo = bundleInstallChecker->ConvertToAppProvisionInfo(
1849         hapVerifyResult.GetProvisionInfo());
1850     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->AddAppProvisionInfo(bundleName, appProvisionInfo)) {
1851         APP_LOGE("AddAppProvisionInfo failed, bundleName:%{public}s", bundleName.c_str());
1852     }
1853 }
1854 
UpdateAppDataSelinuxLabel(const std::string & bundleName,const std::string & apl,bool isPreInstall,bool debug)1855 void BMSEventHandler::UpdateAppDataSelinuxLabel(const std::string &bundleName, const std::string &apl,
1856     bool isPreInstall, bool debug)
1857 {
1858     APP_LOGD("UpdateAppDataSelinuxLabel bundleName: %{public}s start.", bundleName.c_str());
1859     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1860     if (dataMgr == nullptr) {
1861         APP_LOGE("DataMgr is nullptr");
1862         return;
1863     }
1864     std::set<int32_t> userIds = dataMgr->GetAllUser();
1865     for (const auto &userId : userIds) {
1866         for (const auto &el : Constants::BUNDLE_EL) {
1867             std::string baseBundleDataDir = Constants::BUNDLE_APP_DATA_BASE_DIR +
1868                                             el +
1869                                             Constants::PATH_SEPARATOR +
1870                                             std::to_string(userId);
1871             std::string baseDataDir = baseBundleDataDir + Constants::BASE + bundleName;
1872             bool isExist = true;
1873             ErrCode result = InstalldClient::GetInstance()->IsExistDir(baseDataDir, isExist);
1874             if (result != ERR_OK) {
1875                 APP_LOGE("IsExistDir failed, error is %{public}d", result);
1876                 continue;
1877             }
1878             if (!isExist) {
1879                 // Update only accessible directories when OTA,
1880                 // and other directories need to be set after the device is unlocked.
1881                 // Can see UserUnlockedEventSubscriber::UpdateAppDataDirSelinuxLabel
1882                 continue;
1883             }
1884             result = InstalldClient::GetInstance()->SetDirApl(baseDataDir, bundleName, apl, isPreInstall, debug);
1885             if (result != ERR_OK) {
1886                 APP_LOGW("bundleName: %{public}s, fail to SetDirApl baseDataDir dir, error is %{public}d",
1887                     bundleName.c_str(), result);
1888             }
1889             std::string databaseDataDir = baseBundleDataDir + Constants::DATABASE + bundleName;
1890             result = InstalldClient::GetInstance()->SetDirApl(databaseDataDir, bundleName, apl, isPreInstall, debug);
1891             if (result != ERR_OK) {
1892                 APP_LOGW("bundleName: %{public}s, fail to SetDirApl databaseDir dir, error is %{public}d",
1893                     bundleName.c_str(), result);
1894             }
1895         }
1896     }
1897     APP_LOGD("UpdateAppDataSelinuxLabel bundleName: %{public}s end.", bundleName.c_str());
1898 }
1899 
HandleSceneBoard() const1900 void BMSEventHandler::HandleSceneBoard() const
1901 {
1902 #ifdef WINDOW_ENABLE
1903     APP_LOGD("begin to HandleSceneBoard");
1904     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1905     if (dataMgr == nullptr) {
1906         APP_LOGE("dataMgr is null");
1907         return;
1908     }
1909     bool sceneBoardEnable = Rosen::SceneBoardJudgement::IsSceneBoardEnabled();
1910     APP_LOGI("HandleSceneBoard sceneBoardEnable : %{public}d", sceneBoardEnable);
1911     dataMgr->SetApplicationEnabled(SCENE_BOARD_BUNDLE_NAME, sceneBoardEnable, Constants::DEFAULT_USERID);
1912     dataMgr->SetApplicationEnabled(SYSTEM_UI_BUNDLE_NAME, !sceneBoardEnable, Constants::DEFAULT_USERID);
1913     std::set<int32_t> userIds = dataMgr->GetAllUser();
1914     std::for_each(userIds.cbegin(), userIds.cend(), [dataMgr, sceneBoardEnable](const int32_t userId) {
1915         dataMgr->SetApplicationEnabled(LAUNCHER_BUNDLE_NAME, !sceneBoardEnable, userId);
1916     });
1917     APP_LOGD("HandleSceneBoard finish");
1918 #endif
1919 }
1920 
InnerProcessStockBundleProvisionInfo()1921 void BMSEventHandler::InnerProcessStockBundleProvisionInfo()
1922 {
1923     APP_LOGD("InnerProcessStockBundleProvisionInfo start.");
1924     std::unordered_set<std::string> allBundleNames;
1925     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->GetAllAppProvisionInfoBundleName(allBundleNames)) {
1926         APP_LOGE("GetAllAppProvisionInfoBundleName failed");
1927         return;
1928     }
1929     // process normal bundle
1930     ProcessBundleProvisionInfo(allBundleNames);
1931     // process shared bundle
1932     ProcessSharedBundleProvisionInfo(allBundleNames);
1933     APP_LOGD("InnerProcessStockBundleProvisionInfo end.");
1934 }
1935 
ProcessBundleProvisionInfo(const std::unordered_set<std::string> & allBundleNames)1936 void BMSEventHandler::ProcessBundleProvisionInfo(const std::unordered_set<std::string> &allBundleNames)
1937 {
1938     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1939     if (dataMgr == nullptr) {
1940         APP_LOGE("DataMgr is nullptr");
1941         return;
1942     }
1943     std::vector<BundleInfo> bundleInfos;
1944     if (dataMgr->GetBundleInfosV9(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
1945         bundleInfos, Constants::ALL_USERID) != ERR_OK) {
1946         APP_LOGE("GetBundleInfos failed");
1947         return;
1948     }
1949     for (const auto &bundleInfo : bundleInfos) {
1950         // not exist in appProvisionInfo table, then parse profile info and save it
1951         if ((allBundleNames.find(bundleInfo.name) == allBundleNames.end()) &&
1952             !bundleInfo.hapModuleInfos.empty()) {
1953             AddStockAppProvisionInfoByOTA(bundleInfo.name, bundleInfo.hapModuleInfos[0].hapPath);
1954         }
1955     }
1956 }
1957 
ProcessSharedBundleProvisionInfo(const std::unordered_set<std::string> & allBundleNames)1958 void BMSEventHandler::ProcessSharedBundleProvisionInfo(const std::unordered_set<std::string> &allBundleNames)
1959 {
1960     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1961     if (dataMgr == nullptr) {
1962         APP_LOGE("DataMgr is nullptr");
1963         return;
1964     }
1965     std::vector<SharedBundleInfo> shareBundleInfos;
1966     if (dataMgr->GetAllSharedBundleInfo(shareBundleInfos) != ERR_OK) {
1967         APP_LOGE("GetAllSharedBundleInfo failed");
1968         return;
1969     }
1970     for (const auto &sharedBundleInfo : shareBundleInfos) {
1971         // not exist in appProvisionInfo table, then parse profile info and save it
1972         if ((allBundleNames.find(sharedBundleInfo.name) == allBundleNames.end()) &&
1973             !sharedBundleInfo.sharedModuleInfos.empty()) {
1974             std::string hspPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + sharedBundleInfo.name +
1975                 Constants::PATH_SEPARATOR + HSP_VERSION_PREFIX +
1976                 std::to_string(sharedBundleInfo.sharedModuleInfos[0].versionCode) + Constants::PATH_SEPARATOR +
1977                 sharedBundleInfo.sharedModuleInfos[0].name + Constants::PATH_SEPARATOR +
1978                 sharedBundleInfo.sharedModuleInfos[0].name + Constants::INSTALL_SHARED_FILE_SUFFIX;
1979             AddStockAppProvisionInfoByOTA(sharedBundleInfo.name, hspPath);
1980         }
1981     }
1982 }
1983 }  // namespace AppExecFwk
1984 }  // namespace OHOS
1985