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