1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "bundle_mgr_service_event_handler.h"
17
18 #include <sstream>
19 #include <sys/stat.h>
20
21 #include "account_helper.h"
22 #include "aot/aot_handler.h"
23 #include "app_log_tag_wrapper.h"
24 #include "app_provision_info_manager.h"
25 #include "app_service_fwk_installer.h"
26 #include "bms_extension_data_mgr.h"
27 #include "bms_key_event_mgr.h"
28 #include "bundle_parser.h"
29 #include "bundle_permission_mgr.h"
30 #include "bundle_resource_helper.h"
31 #include "bundle_scanner.h"
32 #ifdef CONFIG_POLOCY_ENABLE
33 #include "config_policy_utils.h"
34 #endif
35 #include "directory_ex.h"
36 #if defined (BUNDLE_FRAMEWORK_SANDBOX_APP) && defined (DLP_PERMISSION_ENABLE)
37 #include "dlp_permission_kit.h"
38 #endif
39 #include "hmp_bundle_installer.h"
40 #include "inner_patch_info.h"
41 #include "installd_client.h"
42 #include "parameter.h"
43 #include "parameters.h"
44 #include "patch_data_mgr.h"
45 #include "perf_profile.h"
46 #ifdef WINDOW_ENABLE
47 #include "scene_board_judgement.h"
48 #endif
49 #include "status_receiver_host.h"
50 #include "system_bundle_installer.h"
51 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
52 #include "quick_fix_boot_scanner.h"
53 #endif
54 #include "user_unlocked_event_subscriber.h"
55 #ifdef STORAGE_SERVICE_ENABLE
56 #include "storage_manager_proxy.h"
57 #include "iservice_registry.h"
58 #endif
59
60 namespace OHOS {
61 namespace AppExecFwk {
62 namespace {
63 constexpr const char* APP_SUFFIX = "/app";
64 constexpr const char* TEMP_PREFIX = "temp_";
65 constexpr const char* MODULE_PREFIX = "module_";
66 constexpr const char* PRE_INSTALL_HSP_PATH = "/shared_bundles/";
67 constexpr const char* BMS_TEST_UPGRADE = "persist.bms.test-upgrade";
68 constexpr const char* MODULE_UPDATE_PATH = "module_update";
69 constexpr const char* MODULE_UPDATE_PARAM = "persist.moduleupdate.bms.scan";
70 constexpr const char* MODULE_UPDATE_VALUE_UPDATE = "update";
71 constexpr const char* MODULE_UPDATE_VALUE_REVERT_BMS = "revert_bms";
72 constexpr const char* MODULE_UPDATE_VALUE_REVERT = "revert";
73 constexpr const char* MODULE_UPDATE_APP_SERVICE_DIR = "appServiceFwk";
74 constexpr const char* MODULE_UPDATE_INSTALL_RESULT = "persist.moduleupdate.bms.install.";
75 constexpr const char* HAP_PATH_DATA_AREA = "/data/app/el1/bundle/public";
76 constexpr const char* MODULE_UPDATE_INSTALL_RESULT_FALSE = "false";
77 constexpr const char* MODULE_UPDATE_PARAM_EMPTY = "";
78 constexpr const char* FINGERPRINT = "fingerprint";
79 constexpr const char* UNKNOWN = "";
80 constexpr const char* VALUE_TRUE = "true";
81 constexpr int8_t VERSION_LEN = 64;
82 const std::vector<std::string> FINGERPRINTS = {
83 "const.product.software.version",
84 "const.product.build.type",
85 "const.product.brand",
86 "const.product.name",
87 "const.product.devicetype",
88 "const.product.incremental.version",
89 "const.comp.hl.product_base_version.real"
90 };
91 constexpr const char* HSP_VERSION_PREFIX = "v";
92 constexpr const char* OTA_FLAG = "otaFlag";
93 // pre bundle profile
94 constexpr const char* DEFAULT_PRE_BUNDLE_ROOT_DIR = "/system";
95 constexpr const char* DEFAULT_DATA_PRE_BUNDLE_DIR = "/app_list.json";
96 constexpr const char* PRODUCT_SUFFIX = "/etc/app";
97 constexpr const char* MODULE_UPDATE_PRODUCT_SUFFIX = "/etc/app/module_update";
98 constexpr const char* INSTALL_LIST_CONFIG = "/install_list.json";
99 constexpr const char* APP_SERVICE_FWK_INSTALL_LIST_CONFIG = "/app_service_fwk_install_list.json";
100 constexpr const char* UNINSTALL_LIST_CONFIG = "/uninstall_list.json";
101 constexpr const char* INSTALL_LIST_CAPABILITY_CONFIG = "/install_list_capability.json";
102 constexpr const char* EXTENSION_TYPE_LIST_CONFIG = "/extension_type_config.json";
103 constexpr const char* SHARED_BUNDLES_INSTALL_LIST_CONFIG = "/shared_bundles_install_list.json";
104 constexpr const char* SYSTEM_RESOURCES_APP_PATH = "/system/app/ohos.global.systemres";
105 constexpr const char* QUICK_FIX_APP_PATH = "/data/update/quickfix/app/temp/cold";
106 constexpr const char* SYSTEM_BUNDLE_PATH = "/internal";
107 constexpr const char* RESTOR_BUNDLE_NAME_LIST = "list";
108 constexpr const char* QUICK_FIX_APP_RECOVER_FILE = "/data/update/quickfix/app/temp/quickfix_app_recover.json";
109 constexpr const char* INNER_UNDER_LINE = "_";
110 constexpr char SEPARATOR = '/';
111 constexpr const char* SYSTEM_RESOURCES_APP = "ohos.global.systemres";
112 constexpr const char* FOUNDATION_PROCESS_NAME = "foundation";
113 constexpr int32_t SCENE_ID_OTA_INSTALL = 3;
114 constexpr const char* PGO_FILE_PATH = "pgo_files";
115 constexpr const char* BUNDLE_SCAN_PARAM = "bms.scanning_apps.status";
116 constexpr const char* BUNDLE_SCAN_START = "0";
117 constexpr const char* BUNDLE_SCAN_FINISH = "1";
118 constexpr const char* CODE_PROTECT_FLAG = "codeProtectFlag";
119 constexpr const char* CODE_PROTECT_FLAG_CHECKED = "checked";
120 constexpr int64_t TEN_MB = 1024 * 1024 * 10; //10MB
121
122 std::set<PreScanInfo> installList_;
123 std::set<PreScanInfo> systemHspList_;
124 std::set<std::string> uninstallList_;
125 std::set<PreBundleConfigInfo> installListCapabilities_;
126 std::set<std::string> extensiontype_;
127 bool hasLoadPreInstallProFile_ = false;
128 std::vector<std::string> bundleNameList_;
129
130 #ifdef STORAGE_SERVICE_ENABLE
131 #ifdef QUOTA_PARAM_SET_ENABLE
132 const std::string SYSTEM_PARAM_ATOMICSERVICE_DATASIZE_THRESHOLD =
133 "persist.sys.bms.aging.policy.atomicservice.datasize.threshold";
134 const int32_t THRESHOLD_VAL_LEN = 20;
135 #endif // QUOTA_PARAM_SET_ENABLE
136 const int32_t STORAGE_MANAGER_MANAGER_ID = 5003;
137 #endif // STORAGE_SERVICE_ENABLE
138 const int32_t ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET = 200;
139
MoveTempPath(const std::vector<std::string> & fromPaths,const std::string & bundleName,std::vector<std::string> & toPaths)140 void MoveTempPath(const std::vector<std::string> &fromPaths,
141 const std::string &bundleName, std::vector<std::string> &toPaths)
142 {
143 std::string tempDir =
144 std::string(ServiceConstants::HAP_COPY_PATH) + ServiceConstants::PATH_SEPARATOR + TEMP_PREFIX + bundleName;
145 if (!BundleUtil::CreateDir(tempDir)) {
146 LOG_E(BMS_TAG_DEFAULT, "create tempdir failed %{public}s", tempDir.c_str());
147 return;
148 }
149
150 int32_t hapIndex = 0;
151 for (const auto &path : fromPaths) {
152 auto toPath = tempDir + ServiceConstants::PATH_SEPARATOR + MODULE_PREFIX
153 + std::to_string(hapIndex) + ServiceConstants::INSTALL_FILE_SUFFIX;
154 hapIndex++;
155 if (InstalldClient::GetInstance()->MoveFile(path, toPath) != ERR_OK) {
156 LOG_W(BMS_TAG_DEFAULT, "move from %{public}s to %{public}s failed", path.c_str(), toPath.c_str());
157 continue;
158 }
159
160 toPaths.emplace_back(toPath);
161 }
162 }
163
164 class InnerReceiverImpl : public StatusReceiverHost {
165 public:
166 InnerReceiverImpl() = default;
167 virtual ~InnerReceiverImpl() override = default;
168
SetBundleName(const std::string & bundleName)169 void SetBundleName(const std::string &bundleName)
170 {
171 bundleName_ = bundleName;
172 }
173
OnStatusNotify(const int progress)174 virtual void OnStatusNotify(const int progress) override {}
OnFinished(const int32_t resultCode,const std::string & resultMsg)175 virtual void OnFinished(
176 const int32_t resultCode, const std::string &resultMsg) override
177 {
178 if (bundleName_.empty()) {
179 LOG_D(BMS_TAG_DEFAULT, "bundleName_ is empty");
180 return;
181 }
182
183 std::string tempDir = std::string(ServiceConstants::HAP_COPY_PATH)
184 + ServiceConstants::PATH_SEPARATOR + TEMP_PREFIX + bundleName_;
185 LOG_D(BMS_TAG_DEFAULT, "delete tempDir %{public}s", tempDir.c_str());
186 BundleUtil::DeleteDir(tempDir);
187 }
188
189 private:
190 std::string bundleName_;
191 };
192 }
193
BMSEventHandler()194 BMSEventHandler::BMSEventHandler()
195 {
196 LOG_D(BMS_TAG_DEFAULT, "instance is created");
197 }
198
~BMSEventHandler()199 BMSEventHandler::~BMSEventHandler()
200 {
201 LOG_D(BMS_TAG_DEFAULT, "instance is destroyed");
202 }
203
BmsStartEvent()204 void BMSEventHandler::BmsStartEvent()
205 {
206 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "BmsStartEvent start");
207 BeforeBmsStart();
208 OnBmsStarting();
209 AfterBmsStart();
210 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "BmsStartEvent end");
211 }
212
BeforeBmsStart()213 void BMSEventHandler::BeforeBmsStart()
214 {
215 needNotifyBundleScanStatus_ = false;
216 if (!BundlePermissionMgr::Init()) {
217 LOG_W(BMS_TAG_DEFAULT, "BundlePermissionMgr::Init failed");
218 }
219
220 EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_START);
221 if (SetParameter(BUNDLE_SCAN_PARAM, BUNDLE_SCAN_START) != 0) {
222 LOG_E(BMS_TAG_DEFAULT, "set bms.scanning_apps.status 0 failed");
223 }
224 }
225
OnBmsStarting()226 void BMSEventHandler::OnBmsStarting()
227 {
228 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "BMSEventHandler OnBmsStarting start");
229 // Judge whether there is install info in the persistent Db
230 if (LoadInstallInfosFromDb()) {
231 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OnBmsStarting Load install info from db success");
232 BundleRebootStartEvent();
233 return;
234 }
235
236 if (!BundleUtil::CheckSystemFreeSize(ServiceConstants::BUNDLE_MANAGER_SERVICE_PATH, TEN_MB)) {
237 LOG_NOFUNC_E(BMS_TAG_DEFAULT, "OnBmsStarting no space");
238 return;
239 }
240
241 // If the preInstall infos does not exist in preInstall db,
242 // all preInstall directory applications will be reinstalled.
243 if (!LoadAllPreInstallBundleInfos()) {
244 LOG_NOFUNC_E(BMS_TAG_DEFAULT, "OnBmsStarting Load all preInstall bundleInfos failed");
245 needRebootOta_ = true;
246 }
247
248 /* Guard against install infos lossed strategy.
249 * 1. Scan user data dir
250 * 1.1. If no data, first boot.
251 * 1.2. If has data, but parse data to InnerBundleUserInfos failed,
252 * reInstall all app from install dir and preInstall dir
253 * 1.3. If has data and parse data to InnerBundleUserInfos success, goto 2
254 * 2. Scan installDir include common install dir and preInstall dir
255 * And the parse the hap to InnerBundleInfos
256 * 3. Combine InnerBundleInfos and InnerBundleUserInfos to cache and db
257 * 4. According to needRebootOta determine whether OTA detection is required
258 */
259 ResultCode resultCode = GuardAgainstInstallInfosLossedStrategy();
260 switch (resultCode) {
261 case ResultCode::RECOVER_OK: {
262 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OnBmsStarting Guard against install infos lossed strategy take effect");
263 if (needRebootOta_) {
264 BundleRebootStartEvent();
265 } else {
266 needNotifyBundleScanStatus_ = true;
267 }
268
269 break;
270 }
271 case ResultCode::REINSTALL_OK: {
272 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OnBmsStarting ReInstall all haps");
273 needNotifyBundleScanStatus_ = true;
274 break;
275 }
276 case ResultCode::NO_INSTALLED_DATA: {
277 // First boot
278 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OnBmsStarting first boot");
279 BundleBootStartEvent();
280 break;
281 }
282 default:
283 LOG_NOFUNC_E(BMS_TAG_DEFAULT, "System internal error, install informations missing");
284 break;
285 }
286
287 SaveSystemFingerprint();
288 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "BMSEventHandler OnBmsStarting end");
289 }
290
AfterBmsStart()291 void BMSEventHandler::AfterBmsStart()
292 {
293 LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler AfterBmsStart start");
294 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
295 if (OHOS::system::GetBoolParameter(ServiceConstants::DEVELOPERMODE_STATE, false)) {
296 DelayedSingleton<QuickFixBootScanner>::GetInstance()->ProcessQuickFixBootUp();
297 }
298 #endif
299 DelayedSingleton<BundleMgrService>::GetInstance()->CheckAllUser();
300 CreateAppInstallDir();
301 SetAllInstallFlag();
302 HandleSceneBoard();
303 CleanTempDir();
304 DelayedSingleton<BundleMgrService>::GetInstance()->RegisterService();
305 EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_END);
306 if (SetParameter(BUNDLE_SCAN_PARAM, BUNDLE_SCAN_FINISH) != 0) {
307 LOG_E(BMS_TAG_DEFAULT, "set bms.scanning_apps.status 1 failed");
308 }
309 ClearCache();
310 if (needNotifyBundleScanStatus_) {
311 DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
312 }
313 ListeningUserUnlocked();
314 RemoveUnreservedSandbox();
315 BundleResourceHelper::RegisterCommonEventSubscriber();
316 BundleResourceHelper::RegisterConfigurationObserver();
317 ProcessCheckAppEl1Dir();
318 LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler AfterBmsStart end");
319 }
320
ClearCache()321 void BMSEventHandler::ClearCache()
322 {
323 hapParseInfoMap_.clear();
324 loadExistData_.clear();
325 hasLoadAllPreInstallBundleInfosFromDb_ = false;
326 }
327
LoadInstallInfosFromDb()328 bool BMSEventHandler::LoadInstallInfosFromDb()
329 {
330 LOG_I(BMS_TAG_DEFAULT, "Load install infos from db");
331 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
332 if (dataMgr == nullptr) {
333 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
334 return false;
335 }
336
337 return dataMgr->LoadDataFromPersistentStorage();
338 }
339
BundleBootStartEvent()340 void BMSEventHandler::BundleBootStartEvent()
341 {
342 EventReport::SendCpuSceneEvent(FOUNDATION_PROCESS_NAME, SCENE_ID_OTA_INSTALL);
343 OnBundleBootStart(Constants::DEFAULT_USERID);
344 #ifdef CHECK_ELDIR_ENABLED
345 UpdateOtaFlag(OTAFlag::CHECK_ELDIR);
346 #endif
347 UpdateOtaFlag(OTAFlag::CHECK_LOG_DIR);
348 UpdateOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR);
349 UpdateOtaFlag(OTAFlag::CHECK_PREINSTALL_DATA);
350 UpdateOtaFlag(OTAFlag::CHECK_SHADER_CAHCE_DIR);
351 UpdateOtaFlag(OTAFlag::CHECK_CLOUD_SHADER_DIR);
352 UpdateOtaFlag(OTAFlag::CHECK_BACK_UP_DIR);
353 UpdateOtaFlag(OTAFlag::CHECK_RECOVERABLE_APPLICATION_INFO);
354 UpdateOtaFlag(OTAFlag::CHECK_INSTALL_SOURCE);
355 UpdateOtaFlag(OTAFlag::DELETE_DEPRECATED_ARK_PATHS);
356 PerfProfile::GetInstance().Dump();
357 }
358
BundleRebootStartEvent()359 void BMSEventHandler::BundleRebootStartEvent()
360 {
361 #ifdef USE_PRE_BUNDLE_PROFILE
362 if (LoadPreInstallProFile()) {
363 UpdateAllPrivilegeCapability();
364 }
365 #endif
366
367 if (IsSystemUpgrade()) {
368 EventReport::SendCpuSceneEvent(FOUNDATION_PROCESS_NAME, SCENE_ID_OTA_INSTALL);
369 OnBundleRebootStart();
370 HandleOTACodeEncryption();
371 SaveSystemFingerprint();
372 AOTHandler::GetInstance().HandleOTA();
373 } else {
374 HandlePreInstallException();
375 ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, false);
376 ProcessRebootQuickFixUnInstallAndRecover(QUICK_FIX_APP_RECOVER_FILE);
377 CheckBundleProvisionInfo();
378 CheckALLResourceInfo();
379 }
380 // need process main bundle status
381 BmsKeyEventMgr::ProcessMainBundleStatusFinally();
382
383 if (IsModuleUpdate()) {
384 HandleModuleUpdate();
385 }
386
387 // need check /data/service/el1/public/bms/bundle_manager_service/app_temp
388 ProcessAppTmpPath();
389
390 needNotifyBundleScanStatus_ = true;
391 }
392
GuardAgainstInstallInfosLossedStrategy()393 ResultCode BMSEventHandler::GuardAgainstInstallInfosLossedStrategy()
394 {
395 LOG_I(BMS_TAG_DEFAULT, "GuardAgainstInstallInfosLossedStrategy start");
396 // Check user path, and parse userData to InnerBundleUserInfo
397 std::map<std::string, std::vector<InnerBundleUserInfo>> innerBundleUserInfoMaps;
398 ScanResultCode scanResultCode = ScanAndAnalyzeUserDatas(innerBundleUserInfoMaps);
399 if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
400 LOG_E(BMS_TAG_DEFAULT, "Scan the user data directory failed");
401 return ResultCode::NO_INSTALLED_DATA;
402 }
403
404 // When data exist, but parse all userinfo fails, reinstall all app.
405 // For example: the AT database is lost or others.
406 if (scanResultCode == ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED) {
407 // Reinstall all app from install dir
408 return ReInstallAllInstallDirApps();
409 }
410
411 // When data exist and parse all userinfo success,
412 // it can be judged that some bundles has installed.
413 // Check install dir, and parse the hap in install dir to InnerBundleInfo
414 std::map<std::string, std::vector<InnerBundleInfo>> installInfos;
415 ScanAndAnalyzeInstallInfos(installInfos);
416 if (installInfos.empty()) {
417 LOG_E(BMS_TAG_DEFAULT, "check bundle path failed due to hap lossd or parse failed");
418 return ResultCode::SYSTEM_ERROR;
419 }
420
421 // Combine InnerBundleInfo and InnerBundleUserInfo
422 if (!CombineBundleInfoAndUserInfo(installInfos, innerBundleUserInfoMaps)) {
423 LOG_E(BMS_TAG_DEFAULT, "System internal error");
424 return ResultCode::SYSTEM_ERROR;
425 }
426
427 return ResultCode::RECOVER_OK;
428 }
429
ScanAndAnalyzeUserDatas(std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)430 ScanResultCode BMSEventHandler::ScanAndAnalyzeUserDatas(
431 std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
432 {
433 ScanResultCode scanResultCode = ScanResultCode::SCAN_NO_DATA;
434 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
435 if (dataMgr == nullptr) {
436 LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
437 return scanResultCode;
438 }
439
440 std::string baseDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[0];
441 std::vector<std::string> userIds;
442 if (!ScanDir(baseDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userIds)) {
443 LOG_D(BMS_TAG_DEFAULT, "Check the base user directory(%{public}s) failed", baseDataDir.c_str());
444 return scanResultCode;
445 }
446
447 for (const auto &userId : userIds) {
448 int32_t userIdInt = Constants::INVALID_USERID;
449 if (!StrToInt(userId, userIdInt)) {
450 LOG_E(BMS_TAG_DEFAULT, "UserId(%{public}s) strToInt failed", userId.c_str());
451 continue;
452 }
453
454 dataMgr->AddUserId(userIdInt);
455 std::vector<std::string> userDataBundleNames;
456 std::string userDataDir = baseDataDir + ServiceConstants::PATH_SEPARATOR + userId + ServiceConstants::BASE;
457 if (!ScanDir(userDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userDataBundleNames)) {
458 LOG_D(BMS_TAG_DEFAULT, "Check the user installation directory(%{public}s) failed", userDataDir.c_str());
459 continue;
460 }
461
462 for (const auto &userDataBundleName : userDataBundleNames) {
463 if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
464 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED;
465 }
466
467 if (AnalyzeUserData(userIdInt, userDataDir, userDataBundleName, userMaps)) {
468 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_SUCCESS;
469 }
470 }
471 }
472
473 return scanResultCode;
474 }
475
AnalyzeUserData(int32_t userId,const std::string & userDataDir,const std::string & userDataBundleName,std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)476 bool BMSEventHandler::AnalyzeUserData(
477 int32_t userId, const std::string &userDataDir, const std::string &userDataBundleName,
478 std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
479 {
480 if (userDataDir.empty() || userDataBundleName.empty()) {
481 LOG_E(BMS_TAG_DEFAULT, "UserDataDir or UserDataBundleName is empty");
482 return false;
483 }
484
485 std::string userDataBundlePath = userDataDir + userDataBundleName;
486 LOG_D(BMS_TAG_DEFAULT, "Analyze user data path(%{public}s)", userDataBundlePath.c_str());
487 FileStat fileStat;
488 if (InstalldClient::GetInstance()->GetFileStat(userDataBundlePath, fileStat) != ERR_OK) {
489 LOG_E(BMS_TAG_DEFAULT, "GetFileStat path(%{public}s) failed", userDataBundlePath.c_str());
490 return false;
491 }
492
493 // It should be a bundleName dir
494 if (!fileStat.isDir) {
495 LOG_E(BMS_TAG_DEFAULT, "UserDataBundlePath(%{public}s) is not dir", userDataBundlePath.c_str());
496 return false;
497 }
498
499 InnerBundleUserInfo innerBundleUserInfo;
500 innerBundleUserInfo.bundleName = userDataBundleName;
501 innerBundleUserInfo.bundleUserInfo.userId = userId;
502 innerBundleUserInfo.uid = fileStat.uid;
503 innerBundleUserInfo.gids.emplace_back(fileStat.gid);
504 innerBundleUserInfo.installTime = fileStat.lastModifyTime;
505 innerBundleUserInfo.updateTime = innerBundleUserInfo.installTime;
506 auto accessTokenIdEx = OHOS::Security::AccessToken::AccessTokenKit::GetHapTokenIDEx(
507 innerBundleUserInfo.bundleUserInfo.userId, userDataBundleName, 0);
508 if (accessTokenIdEx.tokenIdExStruct.tokenID == 0) {
509 LOG_E(BMS_TAG_DEFAULT, "get tokenId failed");
510 return false;
511 }
512
513 innerBundleUserInfo.accessTokenId = accessTokenIdEx.tokenIdExStruct.tokenID;
514 innerBundleUserInfo.accessTokenIdEx = accessTokenIdEx.tokenIDEx;
515 auto userIter = userMaps.find(userDataBundleName);
516 if (userIter == userMaps.end()) {
517 std::vector<InnerBundleUserInfo> innerBundleUserInfos = { innerBundleUserInfo };
518 userMaps.emplace(userDataBundleName, innerBundleUserInfos);
519 return true;
520 }
521
522 userMaps.at(userDataBundleName).emplace_back(innerBundleUserInfo);
523 return true;
524 }
525
ReInstallAllInstallDirApps()526 ResultCode BMSEventHandler::ReInstallAllInstallDirApps()
527 {
528 // First, reinstall all preInstall app from preInstall dir
529 std::vector<std::string> preInstallDirs;
530 GetPreInstallDir(preInstallDirs);
531 for (const auto &preInstallDir : preInstallDirs) {
532 std::vector<std::string> filePaths { preInstallDir };
533 bool removable = IsPreInstallRemovable(preInstallDir);
534 if (!OTAInstallSystemBundle(
535 filePaths, Constants::AppType::SYSTEM_APP, removable)) {
536 LOG_E(BMS_TAG_DEFAULT, "Reinstall bundle(%{public}s) error", preInstallDir.c_str());
537 SavePreInstallException(preInstallDir);
538 continue;
539 }
540 }
541
542 auto installer = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
543 if (installer == nullptr) {
544 LOG_E(BMS_TAG_DEFAULT, "installer is nullptr");
545 return ResultCode::SYSTEM_ERROR;
546 }
547
548 // Second, reInstall all common install app from install dir
549 std::map<std::string, std::vector<std::string>> hapPathsMap;
550 ScanInstallDir(hapPathsMap);
551 for (const auto &hapPaths : hapPathsMap) {
552 InstallParam installParam;
553 installParam.userId = Constants::ALL_USERID;
554 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
555 sptr<InnerReceiverImpl> innerReceiverImpl(new (std::nothrow) InnerReceiverImpl());
556 if (innerReceiverImpl == nullptr) {
557 LOG_E(BMS_TAG_DEFAULT, "InnerReceiverImpl create fail");
558 continue;
559 }
560 innerReceiverImpl->SetBundleName(hapPaths.first);
561 std::vector<std::string> tempHaps;
562 MoveTempPath(hapPaths.second, hapPaths.first, tempHaps);
563 installer->Install(tempHaps, installParam, innerReceiverImpl);
564 }
565
566 return ResultCode::REINSTALL_OK;
567 }
568
ScanAndAnalyzeInstallInfos(std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)569 void BMSEventHandler::ScanAndAnalyzeInstallInfos(
570 std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
571 {
572 // Scan the installed directory
573 std::map<std::string, std::vector<std::string>> hapPathsMap;
574 ScanInstallDir(hapPathsMap);
575 AnalyzeHaps(false, hapPathsMap, installInfos);
576
577 // Scan preBundle directory
578 std::vector<std::string> preInstallDirs;
579 GetPreInstallDir(preInstallDirs);
580 AnalyzeHaps(true, preInstallDirs, installInfos);
581 }
582
ScanInstallDir(std::map<std::string,std::vector<std::string>> & hapPathsMap)583 void BMSEventHandler::ScanInstallDir(
584 std::map<std::string, std::vector<std::string>> &hapPathsMap)
585 {
586 LOG_D(BMS_TAG_DEFAULT, "Scan the installed directory start");
587 std::vector<std::string> bundleNameList;
588 if (!ScanDir(Constants::BUNDLE_CODE_DIR, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, bundleNameList)) {
589 LOG_E(BMS_TAG_DEFAULT, "Check the bundle directory(%{public}s) failed", Constants::BUNDLE_CODE_DIR);
590 return;
591 }
592
593 for (const auto &bundleName : bundleNameList) {
594 std::vector<std::string> hapPaths;
595 auto appCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName;
596 if (!ScanDir(appCodePath, ScanMode::SUB_FILE_FILE, ResultMode::ABSOLUTE_PATH, hapPaths)) {
597 LOG_E(BMS_TAG_DEFAULT, "Scan the appCodePath(%{public}s) failed", appCodePath.c_str());
598 continue;
599 }
600
601 if (hapPaths.empty()) {
602 LOG_D(BMS_TAG_DEFAULT, "The directory(%{public}s) scan result is empty", appCodePath.c_str());
603 continue;
604 }
605
606 std::vector<std::string> checkHapPaths = CheckHapPaths(hapPaths);
607 hapPathsMap.emplace(bundleName, checkHapPaths);
608 }
609
610 LOG_D(BMS_TAG_DEFAULT, "Scan the installed directory end");
611 }
612
CheckHapPaths(const std::vector<std::string> & hapPaths)613 std::vector<std::string> BMSEventHandler::CheckHapPaths(
614 const std::vector<std::string> &hapPaths)
615 {
616 std::vector<std::string> checkHapPaths;
617 for (const auto &hapPath : hapPaths) {
618 if (!BundleUtil::CheckFileType(hapPath, ServiceConstants::INSTALL_FILE_SUFFIX) &&
619 !BundleUtil::CheckFileType(hapPath, ServiceConstants::HSP_FILE_SUFFIX)) {
620 LOG_E(BMS_TAG_DEFAULT, "Check hapPath(%{public}s) failed", hapPath.c_str());
621 continue;
622 }
623
624 checkHapPaths.emplace_back(hapPath);
625 }
626
627 return checkHapPaths;
628 }
629
GetPreInstallRootDirList(std::vector<std::string> & rootDirList)630 void BMSEventHandler::GetPreInstallRootDirList(std::vector<std::string> &rootDirList)
631 {
632 #ifdef CONFIG_POLOCY_ENABLE
633 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "print GetPreInstallRootDirList");
634 auto cfgDirList = GetCfgDirList();
635 if (cfgDirList != nullptr) {
636 for (const auto &cfgDir : cfgDirList->paths) {
637 if (cfgDir == nullptr) {
638 continue;
639 }
640
641 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "%{public}s", cfgDir);
642 rootDirList.emplace_back(cfgDir);
643 }
644
645 FreeCfgDirList(cfgDirList);
646 }
647 #endif
648 bool ret = std::find(
649 rootDirList.begin(), rootDirList.end(), DEFAULT_PRE_BUNDLE_ROOT_DIR) != rootDirList.end();
650 if (!ret) {
651 rootDirList.emplace_back(DEFAULT_PRE_BUNDLE_ROOT_DIR);
652 }
653 }
654
ClearPreInstallCache()655 void BMSEventHandler::ClearPreInstallCache()
656 {
657 if (!hasLoadPreInstallProFile_) {
658 return;
659 }
660
661 installList_.clear();
662 uninstallList_.clear();
663 systemHspList_.clear();
664 installListCapabilities_.clear();
665 extensiontype_.clear();
666 hasLoadPreInstallProFile_ = false;
667 }
668
LoadPreInstallProFile()669 bool BMSEventHandler::LoadPreInstallProFile()
670 {
671 if (hasLoadPreInstallProFile_) {
672 return !installList_.empty();
673 }
674
675 std::vector<std::string> rootDirList;
676 GetPreInstallRootDirList(rootDirList);
677 if (rootDirList.empty()) {
678 LOG_E(BMS_TAG_DEFAULT, "dirList is empty");
679 return false;
680 }
681
682 for (const auto &rootDir : rootDirList) {
683 ParsePreBundleProFile(rootDir + PRODUCT_SUFFIX);
684 ParsePreBundleProFile(rootDir + MODULE_UPDATE_PRODUCT_SUFFIX);
685 }
686
687 hasLoadPreInstallProFile_ = true;
688 return !installList_.empty();
689 }
690
HasPreInstallProfile()691 bool BMSEventHandler::HasPreInstallProfile()
692 {
693 return !installList_.empty();
694 }
695
ParsePreBundleProFile(const std::string & dir)696 void BMSEventHandler::ParsePreBundleProFile(const std::string &dir)
697 {
698 if (!BundleUtil::IsExistDirNoLog(dir)) {
699 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "parse dir %{public}s not exist", dir.c_str());
700 return;
701 }
702 BundleParser bundleParser;
703 bundleParser.ParsePreInstallConfig(
704 dir + INSTALL_LIST_CONFIG, installList_);
705 bundleParser.ParsePreInstallConfig(
706 dir + APP_SERVICE_FWK_INSTALL_LIST_CONFIG, systemHspList_);
707 bundleParser.ParsePreUnInstallConfig(
708 dir + UNINSTALL_LIST_CONFIG, uninstallList_);
709 bundleParser.ParsePreInstallAbilityConfig(
710 dir + INSTALL_LIST_CAPABILITY_CONFIG, installListCapabilities_);
711 bundleParser.ParseExtTypeConfig(
712 dir + EXTENSION_TYPE_LIST_CONFIG, extensiontype_);
713 bundleParser.ParsePreInstallConfig(
714 dir + SHARED_BUNDLES_INSTALL_LIST_CONFIG, installList_);
715
716 std::string oldSystemFingerprint = GetOldSystemFingerprint();
717 if (oldSystemFingerprint.empty()) {
718 LOG_W(BMS_TAG_DEFAULT, "only scan app_list.json on first startup");
719 bundleParser.ParsePreAppListConfig(dir + DEFAULT_DATA_PRE_BUNDLE_DIR, installList_);
720 } else {
721 LOG_W(BMS_TAG_DEFAULT, "data preload app is not support OTA");
722 }
723 }
724
GetPreInstallDir(std::vector<std::string> & bundleDirs)725 void BMSEventHandler::GetPreInstallDir(std::vector<std::string> &bundleDirs)
726 {
727 #ifdef USE_PRE_BUNDLE_PROFILE
728 if (LoadPreInstallProFile()) {
729 GetPreInstallDirFromLoadProFile(bundleDirs);
730 return;
731 }
732 #endif
733
734 GetPreInstallDirFromScan(bundleDirs);
735 }
736
GetPreInstallDirFromLoadProFile(std::vector<std::string> & bundleDirs)737 void BMSEventHandler::GetPreInstallDirFromLoadProFile(std::vector<std::string> &bundleDirs)
738 {
739 for (const auto &installInfo : installList_) {
740 if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
741 LOG_W(BMS_TAG_DEFAULT, "bundle(%{public}s) not allowed installed", installInfo.bundleDir.c_str());
742 continue;
743 }
744
745 bundleDirs.emplace_back(installInfo.bundleDir);
746 }
747 }
748
GetPreInstallDirFromScan(std::vector<std::string> & bundleDirs)749 void BMSEventHandler::GetPreInstallDirFromScan(std::vector<std::string> &bundleDirs)
750 {
751 std::list<std::string> scanbundleDirs;
752 GetBundleDirFromScan(scanbundleDirs);
753 std::copy(scanbundleDirs.begin(), scanbundleDirs.end(), std::back_inserter(bundleDirs));
754 }
755
AnalyzeHaps(bool isPreInstallApp,const std::map<std::string,std::vector<std::string>> & hapPathsMap,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)756 void BMSEventHandler::AnalyzeHaps(
757 bool isPreInstallApp,
758 const std::map<std::string, std::vector<std::string>> &hapPathsMap,
759 std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
760 {
761 for (const auto &hapPaths : hapPathsMap) {
762 std::unordered_map<std::string, InnerBundleInfo> hapInfos;
763 if (!CheckAndParseHapFiles(hapPaths.second, isPreInstallApp, hapInfos) || hapInfos.empty()) {
764 LOG_E(BMS_TAG_DEFAULT, "Parse bundleDir failed");
765 continue;
766 }
767
768 CollectInstallInfos(hapInfos, installInfos);
769 }
770 }
771
AnalyzeHaps(bool isPreInstallApp,const std::vector<std::string> & bundleDirs,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)772 void BMSEventHandler::AnalyzeHaps(
773 bool isPreInstallApp,
774 const std::vector<std::string> &bundleDirs,
775 std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
776 {
777 for (const auto &bundleDir : bundleDirs) {
778 std::unordered_map<std::string, InnerBundleInfo> hapInfos;
779 if (!CheckAndParseHapFiles(bundleDir, isPreInstallApp, hapInfos) || hapInfos.empty()) {
780 LOG_E(BMS_TAG_DEFAULT, "Parse bundleDir(%{public}s) failed", bundleDir.c_str());
781 continue;
782 }
783
784 CollectInstallInfos(hapInfos, installInfos);
785 }
786 }
787
CollectInstallInfos(const std::unordered_map<std::string,InnerBundleInfo> & hapInfos,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)788 void BMSEventHandler::CollectInstallInfos(
789 const std::unordered_map<std::string, InnerBundleInfo> &hapInfos,
790 std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
791 {
792 for (const auto &hapInfoIter : hapInfos) {
793 auto bundleName = hapInfoIter.second.GetBundleName();
794 if (installInfos.find(bundleName) == installInfos.end()) {
795 std::vector<InnerBundleInfo> innerBundleInfos { hapInfoIter.second };
796 installInfos.emplace(bundleName, innerBundleInfos);
797 continue;
798 } else {
799 std::vector<InnerBundleInfo> &infos = installInfos.at(bundleName);
800 if (!infos.empty() && hapInfoIter.second.GetVersionCode() < infos[0].GetVersionCode()) {
801 continue;
802 }
803 if (std::find_if(infos.begin(), infos.end(), [&hapInfoIter](const InnerBundleInfo &info) {
804 return info.GetCurModuleName() == hapInfoIter.second.GetCurModuleName();
805 }) == infos.end()) {
806 installInfos.at(bundleName).emplace_back(hapInfoIter.second);
807 }
808 }
809 }
810 }
811
CombineBundleInfoAndUserInfo(const std::map<std::string,std::vector<InnerBundleInfo>> & installInfos,const std::map<std::string,std::vector<InnerBundleUserInfo>> & userInfoMaps)812 bool BMSEventHandler::CombineBundleInfoAndUserInfo(
813 const std::map<std::string, std::vector<InnerBundleInfo>> &installInfos,
814 const std::map<std::string, std::vector<InnerBundleUserInfo>> &userInfoMaps)
815 {
816 LOG_D(BMS_TAG_DEFAULT, "Combine code information and user data start");
817 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
818 if (dataMgr == nullptr) {
819 LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
820 return false;
821 }
822
823 if (installInfos.empty() || userInfoMaps.empty()) {
824 LOG_E(BMS_TAG_DEFAULT, "bundleInfos or userInfos is empty");
825 return false;
826 }
827
828 for (auto hasInstallInfo : installInfos) {
829 auto bundleName = hasInstallInfo.first;
830 auto userIter = userInfoMaps.find(bundleName);
831 if (userIter == userInfoMaps.end()) {
832 LOG_E(BMS_TAG_DEFAULT, "User data directory missing with bundle %{public}s ", bundleName.c_str());
833 needRebootOta_ = true;
834 continue;
835 }
836
837 for (auto &info : hasInstallInfo.second) {
838 SaveInstallInfoToCache(info);
839 }
840
841 for (const auto &userInfo : userIter->second) {
842 dataMgr->AddInnerBundleUserInfo(bundleName, userInfo);
843 }
844 }
845
846 // Parsing uid, gids and other user information
847 dataMgr->RestoreUidAndGid();
848 // Load all bundle state data from jsonDb
849 dataMgr->LoadAllBundleStateDataFromJsonDb();
850 LOG_D(BMS_TAG_DEFAULT, "Combine code information and user data end");
851 return true;
852 }
853
SaveInstallInfoToCache(InnerBundleInfo & info)854 void BMSEventHandler::SaveInstallInfoToCache(InnerBundleInfo &info)
855 {
856 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
857 if (dataMgr == nullptr) {
858 LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
859 return;
860 }
861
862 auto bundleName = info.GetBundleName();
863 auto appCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName;
864 info.SetAppCodePath(appCodePath);
865
866 std::string dataBaseDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1]
867 + ServiceConstants::DATABASE + bundleName;
868 info.SetAppDataBaseDir(dataBaseDir);
869
870 auto moduleDir = info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR + info.GetCurrentModulePackage();
871 info.AddModuleSrcDir(moduleDir);
872 info.AddModuleResPath(moduleDir);
873
874 bool bundleExist = false;
875 InnerBundleInfo dbInfo;
876 {
877 auto &mtx = dataMgr->GetBundleMutex(bundleName);
878 std::lock_guard lock { mtx };
879 bundleExist = dataMgr->FetchInnerBundleInfo(bundleName, dbInfo);
880 }
881
882 if (!bundleExist) {
883 dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_START);
884 if (!dataMgr->AddInnerBundleInfo(bundleName, info)) {
885 LOG_E(BMS_TAG_DEFAULT, "add bundle %{public}s failed", bundleName.c_str());
886 dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_FAIL);
887 return;
888 }
889 dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS);
890 return;
891 }
892
893 auto& hapModuleName = info.GetCurModuleName();
894 std::vector<std::string> dbModuleNames;
895 dbInfo.GetModuleNames(dbModuleNames);
896 auto iter = std::find(dbModuleNames.begin(), dbModuleNames.end(), hapModuleName);
897 if (iter != dbModuleNames.end()) {
898 LOG_E(BMS_TAG_DEFAULT, "module(%{public}s) has install", hapModuleName.c_str());
899 return;
900 }
901
902 dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_START);
903 dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_SUCCESS);
904 dataMgr->AddNewModuleInfo(bundleName, info, dbInfo);
905 }
906
ScanDir(const std::string & dir,ScanMode scanMode,ResultMode resultMode,std::vector<std::string> & resultList)907 bool BMSEventHandler::ScanDir(
908 const std::string& dir, ScanMode scanMode, ResultMode resultMode, std::vector<std::string> &resultList)
909 {
910 LOG_D(BMS_TAG_DEFAULT, "Scan the directory(%{public}s) start", dir.c_str());
911 ErrCode result = InstalldClient::GetInstance()->ScanDir(dir, scanMode, resultMode, resultList);
912 if (result != ERR_OK) {
913 LOG_E(BMS_TAG_DEFAULT, "Scan the directory(%{public}s) failed", dir.c_str());
914 return false;
915 }
916
917 return true;
918 }
919
OnBundleBootStart(int32_t userId)920 void BMSEventHandler::OnBundleBootStart(int32_t userId)
921 {
922 #ifdef USE_PRE_BUNDLE_PROFILE
923 if (LoadPreInstallProFile()) {
924 LOG_I(BMS_TAG_DEFAULT, "Process boot bundle install from pre bundle proFile for userId:%{public}d", userId);
925 InnerProcessBootSystemHspInstall();
926 InnerProcessBootPreBundleProFileInstall(userId);
927 ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, true);
928 ProcessRebootQuickFixUnInstallAndRecover(QUICK_FIX_APP_RECOVER_FILE);
929 return;
930 }
931 #else
932 ProcessBootBundleInstallFromScan(userId);
933 #endif
934 }
935
ProcessBootBundleInstallFromScan(int32_t userId)936 void BMSEventHandler::ProcessBootBundleInstallFromScan(int32_t userId)
937 {
938 LOG_D(BMS_TAG_DEFAULT, "Process boot bundle install from scan");
939 std::list<std::string> bundleDirs;
940 GetBundleDirFromScan(bundleDirs);
941 for (auto item : bundleDirs) {
942 ProcessSystemBundleInstall(item, Constants::AppType::SYSTEM_APP, userId);
943 }
944 }
945
GetBundleDirFromScan(std::list<std::string> & bundleDirs)946 void BMSEventHandler::GetBundleDirFromScan(std::list<std::string> &bundleDirs)
947 {
948 std::vector<std::string> rootDirList;
949 GetPreInstallRootDirList(rootDirList);
950 if (rootDirList.empty()) {
951 LOG_E(BMS_TAG_DEFAULT, "rootDirList is empty");
952 return;
953 }
954
955 for (const auto &rootDir : rootDirList) {
956 ProcessScanDir(rootDir + APP_SUFFIX, bundleDirs);
957 }
958
959 auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), SYSTEM_RESOURCES_APP_PATH);
960 if (iter != bundleDirs.end()) {
961 bundleDirs.erase(iter);
962 bundleDirs.insert(bundleDirs.begin(), SYSTEM_RESOURCES_APP_PATH);
963 }
964 }
965
ProcessScanDir(const std::string & dir,std::list<std::string> & bundleDirs)966 void BMSEventHandler::ProcessScanDir(const std::string &dir, std::list<std::string> &bundleDirs)
967 {
968 BundleScanner scanner;
969 std::list<std::string> bundleList = scanner.Scan(dir);
970 for (auto item : bundleList) {
971 auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), item);
972 if (iter == bundleDirs.end()) {
973 bundleDirs.push_back(item);
974 }
975 }
976 }
977
InnerProcessBootSystemHspInstall()978 void BMSEventHandler::InnerProcessBootSystemHspInstall()
979 {
980 for (const auto &systemHspPath : systemHspList_) {
981 ProcessSystemHspInstall(systemHspPath);
982 }
983 }
984
ProcessSystemHspInstall(const PreScanInfo & preScanInfo)985 void BMSEventHandler::ProcessSystemHspInstall(const PreScanInfo &preScanInfo)
986 {
987 InstallParam installParam;
988 installParam.isPreInstallApp = true;
989 installParam.removable = false;
990 installParam.copyHapToInstallPath = false;
991 installParam.needSavePreInstallInfo = true;
992 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
993 AppServiceFwkInstaller installer;
994 SavePreInstallExceptionAppService(preScanInfo.bundleDir);
995 ErrCode ret = installer.Install({preScanInfo.bundleDir}, installParam);
996 LOG_I(BMS_TAG_DEFAULT, "Install systemHsp %{public}s result %{public}d", preScanInfo.bundleDir.c_str(), ret);
997 if (ret == ERR_OK) {
998 DeletePreInstallExceptionAppService(preScanInfo.bundleDir);
999 }
1000 }
1001
ProcessSystemHspInstall(const std::string & systemHspDir)1002 bool BMSEventHandler::ProcessSystemHspInstall(const std::string &systemHspDir)
1003 {
1004 LOG_I(BMS_TAG_DEFAULT, "Install systemHsp by bundleDir(%{public}s)", systemHspDir.c_str());
1005 InstallParam installParam;
1006 installParam.isPreInstallApp = true;
1007 installParam.removable = false;
1008 installParam.copyHapToInstallPath = false;
1009 installParam.needSavePreInstallInfo = true;
1010 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
1011 AppServiceFwkInstaller installer;
1012 ErrCode ret = installer.Install({systemHspDir}, installParam);
1013 if (ret != ERR_OK) {
1014 LOG_W(BMS_TAG_DEFAULT, "Install systemHsp %{public}s error", systemHspDir.c_str());
1015 return false;
1016 }
1017 return true;
1018 }
1019
InnerProcessBootPreBundleProFileInstall(int32_t userId)1020 void BMSEventHandler::InnerProcessBootPreBundleProFileInstall(int32_t userId)
1021 {
1022 // Sort in descending order of install priority
1023 std::map<int32_t, std::vector<PreScanInfo>, std::greater<int32_t>> taskMap;
1024 std::list<std::string> hspDirs;
1025 for (const auto &installInfo : installList_) {
1026 LOG_D(BMS_TAG_DEFAULT, "Inner process boot preBundle proFile install %{public}s",
1027 installInfo.ToString().c_str());
1028 if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
1029 LOG_I(BMS_TAG_DEFAULT, "bundle(%{public}s) not allowed installed when boot", installInfo.bundleDir.c_str());
1030 continue;
1031 }
1032 if (installInfo.bundleDir.find(PRE_INSTALL_HSP_PATH) != std::string::npos) {
1033 hspDirs.emplace_back(installInfo.bundleDir);
1034 } else {
1035 taskMap[installInfo.priority].emplace_back(installInfo);
1036 }
1037 }
1038
1039 for (const auto &hspDir : hspDirs) {
1040 ProcessSystemSharedBundleInstall(hspDir, Constants::AppType::SYSTEM_APP);
1041 }
1042
1043 if (taskMap.size() <= 0) {
1044 LOG_W(BMS_TAG_DEFAULT, "taskMap is empty");
1045 return;
1046 }
1047 AddTasks(taskMap, userId);
1048 }
1049
AddTasks(const std::map<int32_t,std::vector<PreScanInfo>,std::greater<int32_t>> & taskMap,int32_t userId)1050 void BMSEventHandler::AddTasks(
1051 const std::map<int32_t, std::vector<PreScanInfo>, std::greater<int32_t>> &taskMap, int32_t userId)
1052 {
1053 for (const auto &tasks : taskMap) {
1054 AddTaskParallel(tasks.first, tasks.second, userId);
1055 }
1056 }
1057
AddTaskParallel(int32_t taskPriority,const std::vector<PreScanInfo> & tasks,int32_t userId)1058 void BMSEventHandler::AddTaskParallel(
1059 int32_t taskPriority, const std::vector<PreScanInfo> &tasks, int32_t userId)
1060 {
1061 int32_t taskTotalNum = static_cast<int32_t>(tasks.size());
1062 if (taskTotalNum <= 0) {
1063 LOG_E(BMS_TAG_DEFAULT, "The number of tasks is empty");
1064 return;
1065 }
1066
1067 auto bundleMgrService = DelayedSingleton<BundleMgrService>::GetInstance();
1068 if (bundleMgrService == nullptr) {
1069 LOG_E(BMS_TAG_DEFAULT, "bundleMgrService is nullptr");
1070 return;
1071 }
1072
1073 sptr<BundleInstallerHost> installerHost = bundleMgrService->GetBundleInstaller();
1074 if (installerHost == nullptr) {
1075 LOG_E(BMS_TAG_DEFAULT, "installerHost is nullptr");
1076 return;
1077 }
1078
1079 size_t threadsNum = static_cast<size_t>(installerHost->GetThreadsNum());
1080 LOG_I(BMS_TAG_DEFAULT, "priority: %{public}d, tasks: %{public}zu, userId: %{public}d, threadsNum: %{public}zu",
1081 taskPriority, tasks.size(), userId, threadsNum);
1082 std::atomic_uint taskEndNum = 0;
1083 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
1084 for (const auto &installInfo : tasks) {
1085 if (installerHost->GetCurTaskNum() >= threadsNum) {
1086 BMSEventHandler::ProcessSystemBundleInstall(installInfo, Constants::AppType::SYSTEM_APP, userId);
1087 taskEndNum++;
1088 continue;
1089 }
1090
1091 auto task = [installInfo, userId, taskTotalNum, &taskEndNum, &bundlePromise]() {
1092 BMSEventHandler::ProcessSystemBundleInstall(installInfo, Constants::AppType::SYSTEM_APP, userId);
1093 taskEndNum++;
1094 if (bundlePromise && static_cast<int32_t>(taskEndNum) >= taskTotalNum) {
1095 bundlePromise->NotifyAllTasksExecuteFinished();
1096 LOG_I(BMS_TAG_DEFAULT, "All tasks has executed and notify promise in priority(%{public}d)",
1097 installInfo.priority);
1098 }
1099 };
1100
1101 installerHost->AddTask(task, "BootStartInstall : " + installInfo.bundleDir);
1102 }
1103
1104 if (static_cast<int32_t>(taskEndNum) < taskTotalNum) {
1105 bundlePromise->WaitForAllTasksExecute();
1106 LOG_I(BMS_TAG_DEFAULT, "Wait for all tasks execute in priority(%{public}d)", taskPriority);
1107 }
1108 }
1109
ProcessSystemBundleInstall(const PreScanInfo & preScanInfo,Constants::AppType appType,int32_t userId)1110 void BMSEventHandler::ProcessSystemBundleInstall(
1111 const PreScanInfo &preScanInfo, Constants::AppType appType, int32_t userId)
1112 {
1113 LOG_D(BMS_TAG_DEFAULT, "Process system bundle install by bundleDir(%{public}s)", preScanInfo.bundleDir.c_str());
1114 InstallParam installParam;
1115 installParam.userId = userId;
1116 installParam.isPreInstallApp = true;
1117 installParam.SetKillProcess(false);
1118 installParam.needSendEvent = false;
1119 installParam.removable = preScanInfo.removable;
1120 installParam.needSavePreInstallInfo = true;
1121 installParam.copyHapToInstallPath = false;
1122 installParam.isDataPreloadHap = preScanInfo.isDataPreloadHap;
1123 installParam.appIdentifier = preScanInfo.appIdentifier;
1124 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
1125 SystemBundleInstaller installer;
1126 ErrCode ret = installer.InstallSystemBundle(preScanInfo.bundleDir, installParam, appType);
1127 if (ret != ERR_OK && ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON && !preScanInfo.isDataPreloadHap) {
1128 LOG_W(BMS_TAG_DEFAULT, "Install System app:%{public}s error", preScanInfo.bundleDir.c_str());
1129 SavePreInstallException(preScanInfo.bundleDir);
1130 }
1131 }
1132
ProcessSystemBundleInstall(const std::string & bundleDir,Constants::AppType appType,int32_t userId)1133 void BMSEventHandler::ProcessSystemBundleInstall(
1134 const std::string &bundleDir, Constants::AppType appType, int32_t userId)
1135 {
1136 LOG_I(BMS_TAG_DEFAULT, "Process system bundle install by bundleDir(%{public}s)", bundleDir.c_str());
1137 InstallParam installParam;
1138 installParam.userId = userId;
1139 installParam.isPreInstallApp = true;
1140 installParam.SetKillProcess(false);
1141 installParam.needSendEvent = false;
1142 installParam.removable = false;
1143 installParam.needSavePreInstallInfo = true;
1144 installParam.copyHapToInstallPath = false;
1145 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
1146 SystemBundleInstaller installer;
1147 ErrCode ret = installer.InstallSystemBundle(bundleDir, installParam, appType);
1148 if (ret != ERR_OK && ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON) {
1149 LOG_W(BMS_TAG_DEFAULT, "Install System app:%{public}s error", bundleDir.c_str());
1150 SavePreInstallException(bundleDir);
1151 }
1152 }
1153
ProcessSystemSharedBundleInstall(const std::string & sharedBundlePath,Constants::AppType appType)1154 void BMSEventHandler::ProcessSystemSharedBundleInstall(const std::string &sharedBundlePath, Constants::AppType appType)
1155 {
1156 LOG_I(BMS_TAG_DEFAULT, "Process system shared bundle by sharedBundlePath(%{public}s)", sharedBundlePath.c_str());
1157 InstallParam installParam;
1158 installParam.isPreInstallApp = true;
1159 installParam.SetKillProcess(false);
1160 installParam.needSendEvent = false;
1161 installParam.removable = false;
1162 installParam.needSavePreInstallInfo = true;
1163 installParam.sharedBundleDirPaths = {sharedBundlePath};
1164 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
1165 SystemBundleInstaller installer;
1166 if (!installer.InstallSystemSharedBundle(installParam, false, appType)) {
1167 LOG_W(BMS_TAG_DEFAULT, "install system shared bundle: %{public}s error", sharedBundlePath.c_str());
1168 }
1169 }
1170
CreateAppInstallDir() const1171 void BMSEventHandler::CreateAppInstallDir() const
1172 {
1173 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1174 if (dataMgr == nullptr) {
1175 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1176 return;
1177 }
1178
1179 std::set<int32_t> userIds = dataMgr->GetAllUser();
1180 for (const auto &userId : userIds) {
1181 if (userId == Constants::DEFAULT_USERID) {
1182 continue;
1183 }
1184 dataMgr->CreateAppInstallDir(userId);
1185 }
1186 }
1187
SetAllInstallFlag() const1188 void BMSEventHandler::SetAllInstallFlag() const
1189 {
1190 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1191 if (dataMgr == nullptr) {
1192 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1193 return;
1194 }
1195
1196 dataMgr->SetInitialUserFlag(true);
1197 }
1198
OnBundleRebootStart()1199 void BMSEventHandler::OnBundleRebootStart()
1200 {
1201 ProcessRebootBundle();
1202 }
1203
ProcessRebootBundle()1204 void BMSEventHandler::ProcessRebootBundle()
1205 {
1206 LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler Process reboot bundle start");
1207 LoadAllPreInstallBundleInfos();
1208 BundleResourceHelper::DeleteNotExistResourceInfo();
1209 InnerProcessRebootUninstallWrongBundle();
1210 ProcessRebootBundleInstall();
1211 ProcessRebootBundleUninstall();
1212 ProcessRebootAppServiceUninstall();
1213 ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, true);
1214 ProcessRebootQuickFixUnInstallAndRecover(QUICK_FIX_APP_RECOVER_FILE);
1215 ProcessBundleResourceInfo();
1216 ProcessAllBundleDataGroupInfo();
1217 #ifdef CHECK_ELDIR_ENABLED
1218 ProcessCheckAppDataDir();
1219 #endif
1220 ProcessCheckAppLogDir();
1221 ProcessCheckAppFileManagerDir();
1222 ProcessCheckPreinstallData();
1223 ProcessCheckShaderCacheDir();
1224 ProcessCheckCloudShaderDir();
1225 ProcessNewBackupDir();
1226 CheckAndCreateShareFilesSubDataDirs();
1227 RefreshQuotaForAllUid();
1228 ProcessCheckRecoverableApplicationInfo();
1229 ProcessCheckInstallSource();
1230 // Driver update may cause shader cache invalidity and need to be cleared
1231 CleanAllBundleShaderCache();
1232 CleanAllBundleEl1ShaderCacheLocal();
1233 }
1234
CheckOtaFlag(OTAFlag flag,bool & result)1235 bool BMSEventHandler::CheckOtaFlag(OTAFlag flag, bool &result)
1236 {
1237 auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1238 if (bmsPara == nullptr) {
1239 LOG_E(BMS_TAG_DEFAULT, "bmsPara is nullptr");
1240 return false;
1241 }
1242
1243 std::string val;
1244 if (!bmsPara->GetBmsParam(OTA_FLAG, val)) {
1245 LOG_I(BMS_TAG_DEFAULT, "GetBmsParam OTA_FLAG failed");
1246 return false;
1247 }
1248
1249 int32_t valInt = 0;
1250 if (!StrToInt(val, valInt)) {
1251 LOG_E(BMS_TAG_DEFAULT, "val(%{public}s) strToInt failed", val.c_str());
1252 return false;
1253 }
1254
1255 result = static_cast<uint32_t>(flag) & static_cast<uint32_t>(valInt);
1256 return true;
1257 }
1258
UpdateOtaFlag(OTAFlag flag)1259 bool BMSEventHandler::UpdateOtaFlag(OTAFlag flag)
1260 {
1261 auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1262 if (bmsPara == nullptr) {
1263 LOG_E(BMS_TAG_DEFAULT, "bmsPara is nullptr");
1264 return false;
1265 }
1266
1267 std::string val;
1268 if (!bmsPara->GetBmsParam(OTA_FLAG, val)) {
1269 LOG_I(BMS_TAG_DEFAULT, "GetBmsParam OTA_FLAG failed");
1270 return bmsPara->SaveBmsParam(OTA_FLAG, std::to_string(flag));
1271 }
1272
1273 int32_t valInt = 0;
1274 if (!StrToInt(val, valInt)) {
1275 LOG_E(BMS_TAG_DEFAULT, "val(%{public}s) strToInt failed", val.c_str());
1276 return bmsPara->SaveBmsParam(OTA_FLAG, std::to_string(flag));
1277 }
1278
1279 return bmsPara->SaveBmsParam(
1280 OTA_FLAG, std::to_string(static_cast<uint32_t>(flag) | static_cast<uint32_t>(valInt)));
1281 }
1282
ProcessCheckAppDataDir()1283 void BMSEventHandler::ProcessCheckAppDataDir()
1284 {
1285 bool checkElDir = false;
1286 CheckOtaFlag(OTAFlag::CHECK_ELDIR, checkElDir);
1287 if (checkElDir) {
1288 LOG_I(BMS_TAG_DEFAULT, "Not need to check data dir due to has checked");
1289 return;
1290 }
1291
1292 LOG_I(BMS_TAG_DEFAULT, "Need to check data dir");
1293 InnerProcessCheckAppDataDir();
1294 UpdateOtaFlag(OTAFlag::CHECK_ELDIR);
1295 }
1296
InnerProcessCheckAppDataDir()1297 void BMSEventHandler::InnerProcessCheckAppDataDir()
1298 {
1299 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1300 if (dataMgr == nullptr) {
1301 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1302 return;
1303 }
1304
1305 std::set<int32_t> userIds = dataMgr->GetAllUser();
1306 for (const auto &userId : userIds) {
1307 std::vector<BundleInfo> bundleInfos;
1308 if (!dataMgr->GetBundleInfos(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
1309 bundleInfos, userId)) {
1310 LOG_W(BMS_TAG_DEFAULT, "UpdateAppDataDir GetAllBundleInfos failed");
1311 continue;
1312 }
1313
1314 UpdateAppDataMgr::ProcessUpdateAppDataDir(
1315 userId, bundleInfos, ServiceConstants::DIR_EL3);
1316 UpdateAppDataMgr::ProcessUpdateAppDataDir(
1317 userId, bundleInfos, ServiceConstants::DIR_EL4);
1318 }
1319 }
1320
ProcessCheckPreinstallData()1321 void BMSEventHandler::ProcessCheckPreinstallData()
1322 {
1323 bool checkPreinstallData = false;
1324 CheckOtaFlag(OTAFlag::CHECK_PREINSTALL_DATA, checkPreinstallData);
1325 if (checkPreinstallData) {
1326 LOG_I(BMS_TAG_DEFAULT, "Not need to check preinstall app data due to has checked");
1327 return;
1328 }
1329 LOG_I(BMS_TAG_DEFAULT, "Need to check preinstall data");
1330 InnerProcessCheckPreinstallData();
1331 UpdateOtaFlag(OTAFlag::CHECK_PREINSTALL_DATA);
1332 }
1333
InnerProcessCheckPreinstallData()1334 void BMSEventHandler::InnerProcessCheckPreinstallData()
1335 {
1336 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1337 if (dataMgr == nullptr) {
1338 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1339 return;
1340 }
1341 std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
1342 for (auto &preInstallBundleInfo : preInstallBundleInfos) {
1343 BundleInfo bundleInfo;
1344 if (dataMgr->GetBundleInfo(preInstallBundleInfo.GetBundleName(),
1345 static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
1346 bundleInfo, Constants::ALL_USERID)) {
1347 preInstallBundleInfo.SetIconId(bundleInfo.applicationInfo.iconResource.id);
1348 preInstallBundleInfo.SetLabelId(bundleInfo.applicationInfo.labelResource.id);
1349 preInstallBundleInfo.SetModuleName(bundleInfo.applicationInfo.labelResource.moduleName);
1350 dataMgr->SavePreInstallBundleInfo(bundleInfo.name, preInstallBundleInfo);
1351 continue;
1352 }
1353 BundleMgrHostImpl impl;
1354 BundleInfo resultBundleInfo;
1355 auto preinstalledAppPaths = preInstallBundleInfo.GetBundlePaths();
1356 for (auto preinstalledAppPath: preinstalledAppPaths) {
1357 if (!impl.GetBundleArchiveInfo(preinstalledAppPath, GET_BUNDLE_DEFAULT, resultBundleInfo)) {
1358 LOG_E(BMS_TAG_DEFAULT, "Get bundle archive info fail");
1359 break;
1360 }
1361 preInstallBundleInfo.SetLabelId(resultBundleInfo.applicationInfo.labelResource.id);
1362 preInstallBundleInfo.SetIconId(resultBundleInfo.applicationInfo.iconResource.id);
1363 preInstallBundleInfo.SetModuleName(resultBundleInfo.applicationInfo.labelResource.moduleName);
1364 if (!bundleInfo.hapModuleInfos.empty() &&
1365 resultBundleInfo.hapModuleInfos[0].moduleType == ModuleType::ENTRY) {
1366 break;
1367 }
1368 }
1369 dataMgr->SavePreInstallBundleInfo(resultBundleInfo.name, preInstallBundleInfo);
1370 }
1371 }
1372
ProcessCheckAppLogDir()1373 void BMSEventHandler::ProcessCheckAppLogDir()
1374 {
1375 bool checkLogDir = false;
1376 CheckOtaFlag(OTAFlag::CHECK_LOG_DIR, checkLogDir);
1377 if (checkLogDir) {
1378 LOG_I(BMS_TAG_DEFAULT, "Not need to check log dir due to has checked");
1379 return;
1380 }
1381 LOG_I(BMS_TAG_DEFAULT, "Need to check log dir");
1382 InnerProcessCheckAppLogDir();
1383 UpdateOtaFlag(OTAFlag::CHECK_LOG_DIR);
1384 }
1385
InnerProcessCheckAppLogDir()1386 void BMSEventHandler::InnerProcessCheckAppLogDir()
1387 {
1388 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1389 if (dataMgr == nullptr) {
1390 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1391 return;
1392 }
1393 std::vector<BundleInfo> bundleInfos;
1394 if (!dataMgr->GetBundleInfos(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
1395 bundleInfos, Constants::DEFAULT_USERID)) {
1396 LOG_E(BMS_TAG_DEFAULT, "GetAllBundleInfos failed");
1397 return;
1398 }
1399 UpdateAppDataMgr::ProcessUpdateAppLogDir(bundleInfos, Constants::DEFAULT_USERID);
1400 }
1401
ProcessCheckAppFileManagerDir()1402 void BMSEventHandler::ProcessCheckAppFileManagerDir()
1403 {
1404 bool checkDir = false;
1405 CheckOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR, checkDir);
1406 if (checkDir) {
1407 LOG_I(BMS_TAG_DEFAULT, "Not need to check file manager dir due to has checked");
1408 return;
1409 }
1410 LOG_I(BMS_TAG_DEFAULT, "Need to check file manager dir");
1411 InnerProcessCheckAppFileManagerDir();
1412 UpdateOtaFlag(OTAFlag::CHECK_FILE_MANAGER_DIR);
1413 }
1414
InnerProcessCheckAppFileManagerDir()1415 void BMSEventHandler::InnerProcessCheckAppFileManagerDir()
1416 {
1417 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1418 if (dataMgr == nullptr) {
1419 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1420 return;
1421 }
1422 std::vector<BundleInfo> bundleInfos;
1423 if (!dataMgr->GetBundleInfos(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
1424 bundleInfos, Constants::DEFAULT_USERID)) {
1425 LOG_E(BMS_TAG_DEFAULT, "GetAllBundleInfos failed");
1426 return;
1427 }
1428 UpdateAppDataMgr::ProcessFileManagerDir(bundleInfos, Constants::DEFAULT_USERID);
1429 }
1430
ProcessCheckShaderCacheDir()1431 void BMSEventHandler::ProcessCheckShaderCacheDir()
1432 {
1433 bool checkShaderCache = false;
1434 CheckOtaFlag(OTAFlag::CHECK_SHADER_CAHCE_DIR, checkShaderCache);
1435 if (checkShaderCache) {
1436 LOG_I(BMS_TAG_DEFAULT, "Not need to check shader cache dir due to has checked");
1437 return;
1438 }
1439 LOG_I(BMS_TAG_DEFAULT, "Need to check shader cache dir");
1440 InnerProcessCheckShaderCacheDir();
1441 CheckAllBundleEl1ShaderCacheLocal();
1442 UpdateOtaFlag(OTAFlag::CHECK_SHADER_CAHCE_DIR);
1443 }
1444
InnerProcessCheckShaderCacheDir()1445 void BMSEventHandler::InnerProcessCheckShaderCacheDir()
1446 {
1447 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1448 if (dataMgr == nullptr) {
1449 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1450 return;
1451 }
1452 std::vector<BundleInfo> bundleInfos;
1453 ErrCode res = dataMgr->GetBundleInfosV9(
1454 static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE), bundleInfos, Constants::ALL_USERID);
1455 if (res != ERR_OK) {
1456 LOG_E(BMS_TAG_DEFAULT, "GetAllBundleInfos failed");
1457 return;
1458 }
1459 for (const auto &bundleInfo : bundleInfos) {
1460 if (bundleInfo.name.empty()) {
1461 continue;
1462 }
1463 std::string shaderCachePath;
1464 shaderCachePath.append(ServiceConstants::SHADER_CACHE_PATH).append(bundleInfo.name);
1465 ErrCode res = InstalldClient::GetInstance()->Mkdir(shaderCachePath, S_IRWXU, bundleInfo.uid, bundleInfo.gid);
1466 if (res != ERR_OK) {
1467 LOG_W(BMS_TAG_DEFAULT, "create shader cache failed: %{public}s ", shaderCachePath.c_str());
1468 }
1469 }
1470 }
1471
CheckBundleCloneEl1ShaderCacheLocal(const std::string & bundleName,int32_t appIndex,int32_t userId,int32_t uid)1472 void BMSEventHandler::CheckBundleCloneEl1ShaderCacheLocal(const std::string &bundleName,
1473 int32_t appIndex, int32_t userId, int32_t uid)
1474 {
1475 std::string cloneBundleName = bundleName;
1476 if (appIndex != 0) {
1477 cloneBundleName = BundleCloneCommonHelper::GetCloneDataDir(bundleName,
1478 appIndex);
1479 }
1480 if (uid == Constants::INVALID_UID) {
1481 LOG_W(BMS_TAG_DEFAULT, "invalid uid for: %{public}s", cloneBundleName.c_str());
1482 return;
1483 }
1484 std::string el1ShaderCachePath = std::string(ServiceConstants::NEW_SHADER_CACHE_PATH);
1485 el1ShaderCachePath = el1ShaderCachePath.replace(el1ShaderCachePath.find("%"),
1486 1, std::to_string(userId));
1487 el1ShaderCachePath = el1ShaderCachePath + cloneBundleName + ServiceConstants::PATH_SEPARATOR +
1488 ServiceConstants::SHADER_CACHE;
1489 bool isExist = true;
1490 ErrCode result = InstalldClient::GetInstance()->IsExistDir(el1ShaderCachePath, isExist);
1491 if (result == ERR_OK && isExist) {
1492 return;
1493 }
1494 result = InstalldClient::GetInstance()->Mkdir(el1ShaderCachePath,
1495 ServiceConstants::NEW_SHADRE_CACHE_MODE,
1496 uid, ServiceConstants::NEW_SHADRE_CACHE_GID);
1497 if (result != ERR_OK) {
1498 LOG_W(BMS_TAG_DEFAULT, "create new shadercache failed: %{public}s ", el1ShaderCachePath.c_str());
1499 }
1500 }
1501
CheckAllBundleEl1ShaderCacheLocal()1502 void BMSEventHandler::CheckAllBundleEl1ShaderCacheLocal()
1503 {
1504 LOG_I(BMS_TAG_DEFAULT, "start");
1505 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1506 if (dataMgr == nullptr) {
1507 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1508 return;
1509 }
1510 std::set<int32_t> userIds = dataMgr->GetAllUser();
1511 for (const auto &userId : userIds) {
1512 std::map<std::string, InnerBundleInfo> infos = dataMgr->GetAllInnerBundleInfos();
1513 for (auto &infoPair : infos) {
1514 auto &info = infoPair.second;
1515 std::string bundleName = info.GetBundleName();
1516 BundleType type = info.GetApplicationBundleType();
1517 std::vector<int32_t> allAppIndexes = {0};
1518 std::vector<int32_t> cloneAppIndexes = dataMgr->GetCloneAppIndexesByInnerBundleInfo(info, userId);
1519 allAppIndexes.insert(allAppIndexes.end(), cloneAppIndexes.begin(), cloneAppIndexes.end());
1520 for (int32_t appIndex: allAppIndexes) {
1521 int32_t uid = info.GetUid(userId, appIndex);
1522 CheckBundleCloneEl1ShaderCacheLocal(bundleName, appIndex, userId, uid);
1523 }
1524 }
1525 }
1526 }
1527
CleanBundleCloneEl1ShaderCacheLocal(const std::string & bundleName,int32_t appIndex,int32_t userId)1528 void BMSEventHandler::CleanBundleCloneEl1ShaderCacheLocal(const std::string &bundleName,
1529 int32_t appIndex, int32_t userId)
1530 {
1531 std::string cloneBundleName = bundleName;
1532 if (appIndex != 0) {
1533 cloneBundleName = BundleCloneCommonHelper::GetCloneDataDir(bundleName,
1534 appIndex);
1535 }
1536 std::string el1ShaderCachePath = std::string(ServiceConstants::NEW_SHADER_CACHE_PATH);
1537 el1ShaderCachePath = el1ShaderCachePath.replace(el1ShaderCachePath.find("%"),
1538 1, std::to_string(userId));
1539 el1ShaderCachePath = el1ShaderCachePath + cloneBundleName + ServiceConstants::PATH_SEPARATOR +
1540 ServiceConstants::SHADER_CACHE;
1541 ErrCode res = InstalldClient::GetInstance()->CleanBundleDataDir(el1ShaderCachePath);
1542 if (res != ERR_OK) {
1543 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "%{public}s clean shader cache fail %{public}d",
1544 bundleName.c_str(), res);
1545 }
1546 }
1547
CleanAllBundleEl1ShaderCacheLocal()1548 void BMSEventHandler::CleanAllBundleEl1ShaderCacheLocal()
1549 {
1550 LOG_I(BMS_TAG_DEFAULT, "start");
1551 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1552 if (dataMgr == nullptr) {
1553 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1554 return;
1555 }
1556 std::set<int32_t> userIds = dataMgr->GetAllUser();
1557 for (const auto &userId : userIds) {
1558 std::map<std::string, InnerBundleInfo> infos = dataMgr->GetAllInnerBundleInfos();
1559 for (auto &infoPair : infos) {
1560 auto &info = infoPair.second;
1561 std::string bundleName = info.GetBundleName();
1562 BundleType type = info.GetApplicationBundleType();
1563 std::vector<int32_t> allAppIndexes = {0};
1564 std::vector<int32_t> cloneAppIndexes = dataMgr->GetCloneAppIndexesByInnerBundleInfo(info, userId);
1565 allAppIndexes.insert(allAppIndexes.end(), cloneAppIndexes.begin(), cloneAppIndexes.end());
1566 for (int32_t appIndex: allAppIndexes) {
1567 CleanBundleCloneEl1ShaderCacheLocal(bundleName, appIndex, userId);
1568 }
1569 }
1570 }
1571 }
1572
ProcessCheckCloudShaderDir()1573 void BMSEventHandler::ProcessCheckCloudShaderDir()
1574 {
1575 bool checkCloudShader = false;
1576 CheckOtaFlag(OTAFlag::CHECK_CLOUD_SHADER_DIR, checkCloudShader);
1577 if (checkCloudShader) {
1578 LOG_D(BMS_TAG_DEFAULT, "Not need to check cloud shader cache dir due to has checked");
1579 return;
1580 }
1581 LOG_D(BMS_TAG_DEFAULT, "Need to check cloud shader cache dir");
1582 InnerProcessCheckCloudShaderDir();
1583 UpdateOtaFlag(OTAFlag::CHECK_CLOUD_SHADER_DIR);
1584 }
1585
ProcessNewBackupDir()1586 void BMSEventHandler::ProcessNewBackupDir()
1587 {
1588 bool checkBackup = false;
1589 CheckOtaFlag(OTAFlag::CHECK_BACK_UP_DIR, checkBackup);
1590 if (checkBackup) {
1591 LOG_D(BMS_TAG_DEFAULT, "Not need to check back up dir due to has checked");
1592 return;
1593 }
1594 LOG_I(BMS_TAG_DEFAULT, "Need to check back up dir");
1595 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1596 if (dataMgr == nullptr) {
1597 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1598 return;
1599 }
1600 std::set<int32_t> userIds = dataMgr->GetAllUser();
1601 for (const auto &userId : userIds) {
1602 if (userId == Constants::DEFAULT_USERID) {
1603 continue;
1604 }
1605 std::vector<BundleInfo> bundleInfos;
1606 if (!dataMgr->GetBundleInfos(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
1607 bundleInfos, userId)) {
1608 LOG_W(BMS_TAG_DEFAULT, "ProcessNewBackupDir GetAllBundleInfos failed");
1609 continue;
1610 }
1611 UpdateAppDataMgr::ProcessNewBackupDir(bundleInfos, userId);
1612 }
1613 UpdateOtaFlag(OTAFlag::CHECK_BACK_UP_DIR);
1614 }
1615
InnerProcessCheckCloudShaderDir()1616 void BMSEventHandler::InnerProcessCheckCloudShaderDir()
1617 {
1618 bool cloudExist = true;
1619 bool commonExist = true;
1620 ErrCode result = InstalldClient::GetInstance()->IsExistDir(ServiceConstants::CLOUD_SHADER_PATH, cloudExist);
1621 if (result != ERR_OK) {
1622 LOG_W(BMS_TAG_DEFAULT, "IsExistDir failed, error is %{public}d", result);
1623 return;
1624 }
1625 result = InstalldClient::GetInstance()->IsExistDir(ServiceConstants::CLOUD_SHADER_COMMON_PATH, commonExist);
1626 if (result != ERR_OK) {
1627 LOG_W(BMS_TAG_DEFAULT, "IsExistDir failed, error is %{public}d", result);
1628 commonExist = false;
1629 }
1630 if (cloudExist && commonExist) {
1631 LOG_D(BMS_TAG_DEFAULT, "CLOUD_SHADER_PATH and CLOUD_SHADER_COMMON_PATH existed");
1632 return;
1633 }
1634 const std::string bundleName = OHOS::system::GetParameter(ServiceConstants::CLOUD_SHADER_OWNER, "");
1635 if (bundleName.empty()) {
1636 return;
1637 }
1638
1639 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1640 if (dataMgr == nullptr) {
1641 LOG_W(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1642 return;
1643 }
1644
1645 BundleInfo info;
1646 auto hasBundleInstalled = dataMgr->GetBundleInfo(
1647 bundleName, static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
1648 info, Constants::ANY_USERID);
1649 if (!hasBundleInstalled) {
1650 LOG_D(BMS_TAG_DEFAULT, "Obtain bundleInfo failed, bundleName: %{public}s not exist", bundleName.c_str());
1651 return;
1652 }
1653 if (!cloudExist) {
1654 constexpr int32_t mode = (S_IRWXU | S_IXGRP | S_IXOTH);
1655 result = InstalldClient::GetInstance()->Mkdir(ServiceConstants::CLOUD_SHADER_PATH, mode, info.uid, info.gid);
1656 if (result != ERR_OK) {
1657 LOG_W(BMS_TAG_DEFAULT, "Mkdir CLOUD_SHADER_PATH failed, error is %{public}d", result);
1658 return;
1659 }
1660 }
1661 if (!commonExist) {
1662 InnerProcessCheckCloudShaderCommonDir(info.uid, info.gid);
1663 }
1664 LOG_I(BMS_TAG_DEFAULT, "Create cloud shader cache result: %{public}d", result);
1665 }
1666
InnerProcessCheckCloudShaderCommonDir(const int32_t uid,const int32_t gid)1667 void BMSEventHandler::InnerProcessCheckCloudShaderCommonDir(const int32_t uid, const int32_t gid)
1668 {
1669 constexpr int32_t commonMode = (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
1670 ErrCode result = InstalldClient::GetInstance()->Mkdir(ServiceConstants::CLOUD_SHADER_COMMON_PATH,
1671 commonMode, uid, gid);
1672 if (result != ERR_OK) {
1673 LOG_W(BMS_TAG_DEFAULT, "Mkdir CLOUD_SHADER_COMMON_PATH failed, error is %{public}d", result);
1674 return;
1675 }
1676 LOG_I(BMS_TAG_DEFAULT, "Create cloud shader cache result: %{public}d", result);
1677 }
1678
ProcessCheckRecoverableApplicationInfo()1679 void BMSEventHandler::ProcessCheckRecoverableApplicationInfo()
1680 {
1681 bool hasCheck = false;
1682 CheckOtaFlag(OTAFlag::CHECK_RECOVERABLE_APPLICATION_INFO, hasCheck);
1683 if (hasCheck) {
1684 LOG_D(BMS_TAG_DEFAULT, "recoverable app info has checked");
1685 return;
1686 }
1687 LOG_D(BMS_TAG_DEFAULT, "Need to check recoverable app info");
1688 InnerProcessCheckRecoverableApplicationInfo();
1689 UpdateOtaFlag(OTAFlag::CHECK_RECOVERABLE_APPLICATION_INFO);
1690 }
1691
InnerProcessCheckRecoverableApplicationInfo()1692 void BMSEventHandler::InnerProcessCheckRecoverableApplicationInfo()
1693 {
1694 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1695 if (dataMgr == nullptr) {
1696 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1697 return;
1698 }
1699 std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
1700 for (auto &preInstallBundleInfo : preInstallBundleInfos) {
1701 BundleInfo bundleInfo;
1702 if (dataMgr->GetBundleInfo(preInstallBundleInfo.GetBundleName(),
1703 static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
1704 bundleInfo, Constants::ALL_USERID)) {
1705 preInstallBundleInfo.SetSystemApp(bundleInfo.applicationInfo.isSystemApp);
1706 if (bundleInfo.isNewVersion) {
1707 preInstallBundleInfo.SetBundleType(bundleInfo.applicationInfo.bundleType);
1708 } else if (!bundleInfo.hapModuleInfos.empty() &&
1709 bundleInfo.hapModuleInfos[0].installationFree) {
1710 preInstallBundleInfo.SetBundleType(BundleType::ATOMIC_SERVICE);
1711 }
1712 dataMgr->SavePreInstallBundleInfo(preInstallBundleInfo.GetBundleName(), preInstallBundleInfo);
1713 continue;
1714 }
1715 BundleMgrHostImpl impl;
1716 auto preinstalledAppPaths = preInstallBundleInfo.GetBundlePaths();
1717 for (auto preinstalledAppPath: preinstalledAppPaths) {
1718 BundleInfo archiveBundleInfo;
1719 if (!impl.GetBundleArchiveInfo(preinstalledAppPath, GET_BUNDLE_DEFAULT, archiveBundleInfo)) {
1720 LOG_E(BMS_TAG_DEFAULT, "Get bundle archive info fail");
1721 break;
1722 }
1723 preInstallBundleInfo.SetSystemApp(archiveBundleInfo.applicationInfo.isSystemApp);
1724 if (archiveBundleInfo.isNewVersion) {
1725 preInstallBundleInfo.SetBundleType(archiveBundleInfo.applicationInfo.bundleType);
1726 } else if (!archiveBundleInfo.hapModuleInfos.empty() &&
1727 archiveBundleInfo.hapModuleInfos[0].installationFree) {
1728 preInstallBundleInfo.SetBundleType(BundleType::ATOMIC_SERVICE);
1729 }
1730 if (!archiveBundleInfo.hapModuleInfos.empty() &&
1731 archiveBundleInfo.hapModuleInfos[0].moduleType == ModuleType::ENTRY) {
1732 break;
1733 }
1734 }
1735 dataMgr->SavePreInstallBundleInfo(preInstallBundleInfo.GetBundleName(), preInstallBundleInfo);
1736 }
1737 }
1738
ProcessCheckInstallSource()1739 void BMSEventHandler::ProcessCheckInstallSource()
1740 {
1741 bool hasCheck = false;
1742 CheckOtaFlag(OTAFlag::CHECK_INSTALL_SOURCE, hasCheck);
1743 if (hasCheck) {
1744 LOG_D(BMS_TAG_DEFAULT, "install source has checked");
1745 return;
1746 }
1747 LOG_D(BMS_TAG_DEFAULT, "Need to check install source");
1748 InnerProcessCheckInstallSource();
1749 UpdateOtaFlag(OTAFlag::CHECK_INSTALL_SOURCE);
1750 }
1751
InnerProcessCheckInstallSource()1752 void BMSEventHandler::InnerProcessCheckInstallSource()
1753 {
1754 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1755 if (dataMgr == nullptr) {
1756 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1757 return;
1758 }
1759 std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
1760 for (const auto &preInstallBundleInfo : preInstallBundleInfos) {
1761 InnerBundleInfo innerBundleInfo;
1762 if (!dataMgr->FetchInnerBundleInfo(preInstallBundleInfo.GetBundleName(), innerBundleInfo)) {
1763 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "update installSorce FetchInnerBundleInfo fail -n %{public}s",
1764 preInstallBundleInfo.GetBundleName().c_str());
1765 continue;
1766 }
1767 std::string installSource = ConvertApplicationFlagToInstallSource(innerBundleInfo.GetApplicationFlags());
1768 if (installSource.empty()) {
1769 continue;
1770 }
1771 innerBundleInfo.SetInstallSource(installSource);
1772 if (!dataMgr->UpdateInnerBundleInfo(innerBundleInfo)) {
1773 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "update installSorce UpdateInnerBundleInfo fail -n %{public}s",
1774 preInstallBundleInfo.GetBundleName().c_str());
1775 }
1776 }
1777 }
1778
ConvertApplicationFlagToInstallSource(int32_t flag)1779 std::string BMSEventHandler::ConvertApplicationFlagToInstallSource(int32_t flag)
1780 {
1781 if (static_cast<uint32_t>(flag) & static_cast<uint32_t>(ApplicationInfoFlag::FLAG_BOOT_INSTALLED)) {
1782 return ServiceConstants::INSTALL_SOURCE_PREINSTALL;
1783 }
1784 if (static_cast<uint32_t>(flag) & static_cast<uint32_t>(ApplicationInfoFlag::FLAG_OTA_INSTALLED)) {
1785 return ServiceConstants::INSTALL_SOURCE_OTA;
1786 }
1787 if (static_cast<uint32_t>(flag) & static_cast<uint32_t>(ApplicationInfoFlag::FLAG_RECOVER_INSTALLED)) {
1788 return ServiceConstants::INSTALL_SOURCE_RECOVERY;
1789 }
1790 return Constants::EMPTY_STRING;
1791 }
1792
SendToStorageQuota(const std::string & bundleName,const int32_t uid,const std::string & bundleDataDirPath,const int32_t limitSizeMb)1793 static void SendToStorageQuota(const std::string &bundleName, const int32_t uid,
1794 const std::string &bundleDataDirPath, const int32_t limitSizeMb)
1795 {
1796 #ifdef STORAGE_SERVICE_ENABLE
1797 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1798 if (!systemAbilityManager) {
1799 LOG_W(BMS_TAG_DEFAULT, "SendToStorageQuota, systemAbilityManager error");
1800 return;
1801 }
1802
1803 auto remote = systemAbilityManager->CheckSystemAbility(STORAGE_MANAGER_MANAGER_ID);
1804 if (!remote) {
1805 LOG_W(BMS_TAG_DEFAULT, "SendToStorageQuota, CheckSystemAbility error");
1806 return;
1807 }
1808
1809 auto proxy = iface_cast<StorageManager::IStorageManager>(remote);
1810 if (!proxy) {
1811 LOG_W(BMS_TAG_DEFAULT, "SendToStorageQuotactl, proxy get error");
1812 return;
1813 }
1814
1815 int err = proxy->SetBundleQuota(bundleName, uid, bundleDataDirPath, limitSizeMb);
1816 if (err != ERR_OK) {
1817 LOG_W(BMS_TAG_DEFAULT, "SendToStorageQuota, SetBundleQuota error, err=%{public}d, uid=%{public}d", err, uid);
1818 }
1819 #endif // STORAGE_SERVICE_ENABLE
1820 }
1821
PrepareBundleDirQuota(const std::string & bundleName,const int32_t uid,const std::string & bundleDataDirPath,const int32_t limitSize) const1822 void BMSEventHandler::PrepareBundleDirQuota(const std::string &bundleName, const int32_t uid,
1823 const std::string &bundleDataDirPath, const int32_t limitSize) const
1824 {
1825 if (limitSize == 0) {
1826 SendToStorageQuota(bundleName, uid, bundleDataDirPath, 0);
1827 return;
1828 }
1829 int32_t atomicserviceDatasizeThreshold = limitSize;
1830 #ifdef STORAGE_SERVICE_ENABLE
1831 #ifdef QUOTA_PARAM_SET_ENABLE
1832 char szAtomicDatasizeThresholdMb[THRESHOLD_VAL_LEN] = {0};
1833 int32_t ret = GetParameter(SYSTEM_PARAM_ATOMICSERVICE_DATASIZE_THRESHOLD.c_str(), "",
1834 szAtomicDatasizeThresholdMb, THRESHOLD_VAL_LEN);
1835 if (ret <= 0) {
1836 LOG_I(BMS_TAG_DEFAULT, "GetParameter failed");
1837 } else if (strcmp(szAtomicDatasizeThresholdMb, "") != 0) {
1838 atomicserviceDatasizeThreshold = atoi(szAtomicDatasizeThresholdMb);
1839 LOG_I(BMS_TAG_DEFAULT, "InstalldQuotaUtils init atomicserviceDataThreshold mb success");
1840 }
1841 if (atomicserviceDatasizeThreshold <= 0) {
1842 LOG_W(BMS_TAG_DEFAULT, "no need to prepare quota");
1843 return;
1844 }
1845 #endif // QUOTA_PARAM_SET_ENABLE
1846 #endif // STORAGE_SERVICE_ENABLE
1847 SendToStorageQuota(bundleName, uid, bundleDataDirPath, atomicserviceDatasizeThreshold);
1848 }
1849
RefreshQuotaForAllUid()1850 void BMSEventHandler::RefreshQuotaForAllUid()
1851 {
1852 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1853 if (dataMgr == nullptr) {
1854 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1855 return;
1856 }
1857 std::map<std::string, InnerBundleInfo> infos = dataMgr->GetAllInnerBundleInfos();
1858 for (auto &infoPair : infos) {
1859 auto &info = infoPair.second;
1860 std::map<std::string, InnerBundleUserInfo> userInfos = info.GetInnerBundleUserInfos();
1861 for (auto &userInfoPair : userInfos) {
1862 auto &userInfo = userInfoPair.second;
1863 std::string bundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[0] +
1864 ServiceConstants::PATH_SEPARATOR + std::to_string(userInfo.bundleUserInfo.userId) +
1865 ServiceConstants::BASE + info.GetBundleName();
1866 if (info.GetApplicationBundleType() != BundleType::ATOMIC_SERVICE) {
1867 PrepareBundleDirQuota(info.GetBundleName(), info.GetUid(userInfo.bundleUserInfo.userId),
1868 bundleDataDir, 0);
1869 } else {
1870 PrepareBundleDirQuota(info.GetBundleName(), info.GetUid(userInfo.bundleUserInfo.userId),
1871 bundleDataDir, ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET);
1872 }
1873 }
1874 }
1875 }
1876
LoadAllPreInstallBundleInfos()1877 bool BMSEventHandler::LoadAllPreInstallBundleInfos()
1878 {
1879 if (hasLoadAllPreInstallBundleInfosFromDb_) {
1880 LOG_I(BMS_TAG_DEFAULT, "Has load all preInstall bundleInfos from db");
1881 return true;
1882 }
1883
1884 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1885 if (dataMgr == nullptr) {
1886 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1887 return false;
1888 }
1889
1890 std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
1891 for (auto &iter : preInstallBundleInfos) {
1892 LOG_D(BMS_TAG_DEFAULT, "load preInstallBundleInfos: %{public}s ", iter.GetBundleName().c_str());
1893 loadExistData_.emplace(iter.GetBundleName(), iter);
1894 }
1895
1896 hasLoadAllPreInstallBundleInfosFromDb_ = true;
1897 return !preInstallBundleInfos.empty();
1898 }
1899
ProcessRebootBundleInstall()1900 void BMSEventHandler::ProcessRebootBundleInstall()
1901 {
1902 LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler Process reboot bundle install start");
1903 #ifdef USE_PRE_BUNDLE_PROFILE
1904 if (LoadPreInstallProFile()) {
1905 ProcessReBootPreBundleProFileInstall();
1906 return;
1907 }
1908 #else
1909 ProcessRebootBundleInstallFromScan();
1910 #endif
1911 }
1912
ProcessReBootPreBundleProFileInstall()1913 void BMSEventHandler::ProcessReBootPreBundleProFileInstall()
1914 {
1915 std::list<std::string> bundleDirs;
1916 std::list<std::string> sharedBundleDirs;
1917 for (const auto &installInfo : installList_) {
1918 if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
1919 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "(%{public}s) not allowed installed when reboot",
1920 installInfo.bundleDir.c_str());
1921 continue;
1922 }
1923
1924 if (installInfo.bundleDir.find(PRE_INSTALL_HSP_PATH) != std::string::npos) {
1925 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "found shared bundle path: %{public}s", installInfo.bundleDir.c_str());
1926 sharedBundleDirs.emplace_back(installInfo.bundleDir);
1927 } else {
1928 bundleDirs.emplace_back(installInfo.bundleDir);
1929 }
1930 }
1931
1932 std::list<std::string> systemHspDirs;
1933 for (const auto &systemHspScanInfo : systemHspList_) {
1934 systemHspDirs.emplace_back(systemHspScanInfo.bundleDir);
1935 }
1936
1937 InnerProcessRebootSystemHspInstall(systemHspDirs);
1938 InnerProcessRebootSharedBundleInstall(sharedBundleDirs, Constants::AppType::SYSTEM_APP);
1939 InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
1940 InnerProcessStockBundleProvisionInfo();
1941 InnerProcessStockBundleRouterInfo();
1942 }
1943
ProcessRebootBundleInstallFromScan()1944 void BMSEventHandler::ProcessRebootBundleInstallFromScan()
1945 {
1946 LOG_D(BMS_TAG_DEFAULT, "Process reboot bundle install from scan");
1947 std::list<std::string> bundleDirs;
1948 GetBundleDirFromScan(bundleDirs);
1949 InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
1950 InnerProcessStockBundleProvisionInfo();
1951 InnerProcessStockBundleRouterInfo();
1952 }
1953
InnerProcessRebootBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)1954 void BMSEventHandler::InnerProcessRebootBundleInstall(
1955 const std::list<std::string> &scanPathList, Constants::AppType appType)
1956 {
1957 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1958 if (dataMgr == nullptr) {
1959 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
1960 return;
1961 }
1962
1963 std::unordered_map<std::string, std::pair<std::string, bool>> needInstallMap;
1964 for (auto &scanPathIter : scanPathList) {
1965 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "reboot scan bundle path: %{public}s ", scanPathIter.c_str());
1966 bool removable = IsPreInstallRemovable(scanPathIter);
1967 std::unordered_map<std::string, InnerBundleInfo> infos;
1968 if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
1969 LOG_E(BMS_TAG_DEFAULT, "obtain bundleinfo failed : %{public}s ", scanPathIter.c_str());
1970 BmsKeyEventMgr::ProcessMainBundleInstallFailed(scanPathIter, ERR_APPEXECFWK_PARSE_UNEXPECTED);
1971 SavePreInstallException(scanPathIter);
1972 continue;
1973 }
1974
1975 auto bundleName = infos.begin()->second.GetBundleName();
1976 auto hapVersionCode = infos.begin()->second.GetVersionCode();
1977 AddParseInfosToMap(bundleName, infos);
1978 auto mapIter = loadExistData_.find(bundleName);
1979 if (mapIter == loadExistData_.end()) {
1980 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OTA Install new -n %{public}s by path:%{public}s",
1981 bundleName.c_str(), scanPathIter.c_str());
1982 std::vector<std::string> filePaths { scanPathIter };
1983 if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1984 LOG_E(BMS_TAG_DEFAULT, "OTA Install new bundle(%{public}s) error", bundleName.c_str());
1985 SavePreInstallException(scanPathIter);
1986 }
1987 continue;
1988 }
1989
1990 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OTA process -n %{public}s path:%{public}s",
1991 bundleName.c_str(), scanPathIter.c_str());
1992 BundleInfo hasInstalledInfo;
1993 auto hasBundleInstalled = dataMgr->GetBundleInfo(
1994 bundleName, static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
1995 hasInstalledInfo, Constants::ANY_USERID);
1996 if (!hasBundleInstalled && mapIter->second.IsUninstalled()) {
1997 LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) has been uninstalled and do not OTA install",
1998 bundleName.c_str());
1999 continue;
2000 }
2001 std::vector<int32_t> currentBundleUserIds;
2002 if (HotPatchAppProcessing(bundleName, hasInstalledInfo.versionCode, hapVersionCode, currentBundleUserIds)) {
2003 LOG_I(BMS_TAG_DEFAULT, "OTA Install prefab bundle(%{public}s) by path(%{public}s) for hotPatch upgrade",
2004 bundleName.c_str(), scanPathIter.c_str());
2005 // After the patch app is uninstalled, install the preconfigured app of the ota version.
2006 std::vector<std::string> filePaths{scanPathIter};
2007 if (!OTAInstallSystemBundleTargetUser(filePaths, bundleName, appType, removable, currentBundleUserIds)) {
2008 LOG_E(BMS_TAG_DEFAULT, "OTA install prefab bundle(%{public}s) error", bundleName.c_str());
2009 SavePreInstallException(scanPathIter);
2010 }
2011 continue;
2012 }
2013 std::vector<std::string> filePaths;
2014 bool updateSelinuxLabel = false;
2015 bool updateBundle = false;
2016 for (auto item : infos) {
2017 auto parserModuleNames = item.second.GetModuleNameVec();
2018 if (parserModuleNames.empty()) {
2019 LOG_E(BMS_TAG_DEFAULT, "module is empty when parser path(%{public}s)", item.first.c_str());
2020 continue;
2021 }
2022 // Generally, when the versionCode of Hap is greater than the installed versionCode,
2023 // Except for the uninstalled app, they can be installed or upgraded directly by OTA.
2024 if (hasInstalledInfo.versionCode < hapVersionCode) {
2025 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OTA update module(%{public}s) by path(%{public}s)",
2026 parserModuleNames[0].c_str(), item.first.c_str());
2027 updateBundle = true;
2028 break;
2029 }
2030
2031 // When the accessTokenIdEx is equal to 0, the old application needs to be updated.
2032 if (hasInstalledInfo.applicationInfo.accessTokenIdEx == 0) {
2033 LOG_I(BMS_TAG_DEFAULT, "OTA update module %{public}s by path %{public}s, accessTokenIdEx is equal to 0",
2034 parserModuleNames[0].c_str(), item.first.c_str());
2035 updateBundle = true;
2036 break;
2037 }
2038
2039 // The versionCode of Hap is equal to the installed versionCode.
2040 // You can only install new modules by OTA
2041 if (hasInstalledInfo.versionCode == hapVersionCode) {
2042 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "versionCode same -n %{public}s -v %{public}d",
2043 bundleName.c_str(), hapVersionCode);
2044 InnerBundleInfo info;
2045 if (dataMgr->FetchInnerBundleInfo(bundleName, info) &&
2046 info.GetInstallMark().status != InstallExceptionStatus::INSTALL_FINISH) {
2047 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "OTA status error: %{public}s %{public}d",
2048 bundleName.c_str(), info.GetInstallMark().status);
2049 updateBundle = true;
2050 break;
2051 }
2052 // update pre install app data dir selinux label
2053 if (!updateSelinuxLabel) {
2054 UpdateAppDataSelinuxLabel(bundleName, hasInstalledInfo.applicationInfo.appPrivilegeLevel,
2055 hasInstalledInfo.isPreInstallApp,
2056 hasInstalledInfo.applicationInfo.appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG);
2057 updateSelinuxLabel = true;
2058 }
2059 // Used to judge whether the module has been installed.
2060 bool hasModuleInstalled = std::find(
2061 hasInstalledInfo.hapModuleNames.begin(), hasInstalledInfo.hapModuleNames.end(),
2062 parserModuleNames[0]) != hasInstalledInfo.hapModuleNames.end();
2063 if (hasModuleInstalled) {
2064 if (UpdateModuleByHash(hasInstalledInfo, item.second)) {
2065 updateBundle = true;
2066 break;
2067 }
2068 LOG_D(BMS_TAG_DEFAULT, "module(%{public}s) has been installed and versionCode is same",
2069 parserModuleNames[0].c_str());
2070 continue;
2071 }
2072
2073 LOG_I(BMS_TAG_DEFAULT, "OTA install module(%{public}s) by path(%{public}s)",
2074 parserModuleNames[0].c_str(), item.first.c_str());
2075 updateBundle = true;
2076 break;
2077 }
2078
2079 if (hasInstalledInfo.versionCode > hapVersionCode) {
2080 if (CheckIsBundleUpdatedByHapPath(hasInstalledInfo)) {
2081 break;
2082 }
2083 LOG_NOFUNC_E(BMS_TAG_DEFAULT, "-n %{public}s update failed versionCode:%{public}d lower than "
2084 "current:%{public}d", bundleName.c_str(), hapVersionCode, hasInstalledInfo.versionCode);
2085 SendBundleUpdateFailedEvent(hasInstalledInfo);
2086 break;
2087 }
2088 }
2089 if (!updateBundle) {
2090 #ifdef USE_PRE_BUNDLE_PROFILE
2091 UpdateRemovable(bundleName, removable);
2092 #endif
2093 continue;
2094 }
2095 // system resource need update first
2096 if (bundleName == SYSTEM_RESOURCES_APP) {
2097 std::vector<std::string> filePaths = {scanPathIter};
2098 (void)BMSEventHandler::OTAInstallSystemBundleNeedCheckUser(filePaths, bundleName, appType, removable);
2099 continue;
2100 }
2101 needInstallMap[bundleName] = std::make_pair(scanPathIter, removable);
2102 }
2103 if (!InnerMultiProcessBundleInstall(needInstallMap, appType)) {
2104 LOG_E(BMS_TAG_DEFAULT, "multi install failed");
2105 }
2106 UpdatePreinstallDB(needInstallMap);
2107 }
2108
CheckIsBundleUpdatedByHapPath(const BundleInfo & bundleInfo)2109 bool BMSEventHandler::CheckIsBundleUpdatedByHapPath(const BundleInfo &bundleInfo)
2110 {
2111 for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) {
2112 if (hapModuleInfo.hapPath.find(Constants::BUNDLE_CODE_DIR) != 0) {
2113 return false;
2114 }
2115 }
2116 return true;
2117 }
2118
HotPatchAppProcessing(const std::string & bundleName,uint32_t hasInstallVersionCode,uint32_t hapVersionCode,std::vector<int32_t> & userIds)2119 bool BMSEventHandler::HotPatchAppProcessing(const std::string &bundleName, uint32_t hasInstallVersionCode,
2120 uint32_t hapVersionCode, std::vector<int32_t> &userIds)
2121 {
2122 if (bundleName.empty()) {
2123 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s empty", bundleName.c_str());
2124 return false;
2125 }
2126
2127 if (IsQuickfixPatchApp(bundleName, hasInstallVersionCode)) {
2128 LOG_I(BMS_TAG_DEFAULT, "hasInstallVersionCode: %{public}u, hapVersionCode: %{public}u",
2129 hasInstallVersionCode, hapVersionCode);
2130 // installed patch application version greater than or equal to OTA Preconfigured APP Version
2131 if (hasInstallVersionCode >= hapVersionCode) {
2132 // obtains the users to which the app is installed
2133 LOG_I(BMS_TAG_DEFAULT, "get patch success, bundleName: %{public}s", bundleName.c_str());
2134 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2135 if (dataMgr == nullptr) {
2136 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2137 return false;
2138 }
2139 userIds = dataMgr->GetUserIds(bundleName);
2140 // uninstall the patch app
2141 SystemBundleInstaller installer;
2142 if (!installer.UninstallSystemBundle(bundleName, true)) {
2143 LOG_E(BMS_TAG_DEFAULT, "keep data to uninstall app failed, bundleName: %{public}s", bundleName.c_str());
2144 return false;
2145 }
2146 }
2147 // delete patch data
2148 if (!PatchDataMgr::GetInstance().DeleteInnerPatchInfo(bundleName)) {
2149 LOG_W(BMS_TAG_DEFAULT, "DeleteInnerPatchInfo failed, bundleName: %{public}s", bundleName.c_str());
2150 }
2151 return true;
2152 }
2153 return false;
2154 }
2155
InnerMultiProcessBundleInstall(const std::unordered_map<std::string,std::pair<std::string,bool>> & needInstallMap,Constants::AppType appType)2156 bool BMSEventHandler::InnerMultiProcessBundleInstall(
2157 const std::unordered_map<std::string, std::pair<std::string, bool>> &needInstallMap,
2158 Constants::AppType appType)
2159 {
2160 if (needInstallMap.empty()) {
2161 LOG_I(BMS_TAG_DEFAULT, "no bundle need to update when ota");
2162 return true;
2163 }
2164 auto bundleMgrService = DelayedSingleton<BundleMgrService>::GetInstance();
2165 if (bundleMgrService == nullptr) {
2166 LOG_E(BMS_TAG_DEFAULT, "bundleMgrService is nullptr");
2167 return false;
2168 }
2169
2170 sptr<BundleInstallerHost> installerHost = bundleMgrService->GetBundleInstaller();
2171 if (installerHost == nullptr) {
2172 LOG_E(BMS_TAG_DEFAULT, "installerHost is nullptr");
2173 return false;
2174 }
2175
2176 size_t taskTotalNum = needInstallMap.size();
2177 size_t threadsNum = static_cast<size_t>(installerHost->GetThreadsNum());
2178 LOG_I(BMS_TAG_DEFAULT, "multi install start, totalNum: %{public}zu, num: %{public}zu", taskTotalNum, threadsNum);
2179 std::atomic_uint taskEndNum = 0;
2180 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
2181 for (auto iter = needInstallMap.begin(); iter != needInstallMap.end(); ++iter) {
2182 std::string bundleName = iter->first;
2183 std::pair pair = iter->second;
2184 auto task = [bundleName, pair, taskTotalNum, appType, &taskEndNum, &bundlePromise]() {
2185 std::vector<std::string> filePaths = {pair.first};
2186 (void)BMSEventHandler::OTAInstallSystemBundleNeedCheckUser(filePaths, bundleName, appType, pair.second);
2187 taskEndNum++;
2188 if (bundlePromise && taskEndNum >= taskTotalNum) {
2189 bundlePromise->NotifyAllTasksExecuteFinished();
2190 LOG_I(BMS_TAG_DEFAULT, "All tasks has executed and notify promise when ota");
2191 }
2192 };
2193
2194 installerHost->AddTask(task, "BootRebootStartInstall : " + bundleName);
2195 }
2196
2197 if (taskEndNum < taskTotalNum) {
2198 bundlePromise->WaitForAllTasksExecute();
2199 LOG_I(BMS_TAG_DEFAULT, "Wait for all tasks execute when ota");
2200 }
2201 LOG_I(BMS_TAG_DEFAULT, "multi install end");
2202 return true;
2203 }
2204
UpdateModuleByHash(const BundleInfo & oldBundleInfo,const InnerBundleInfo & newInfo) const2205 bool BMSEventHandler::UpdateModuleByHash(const BundleInfo &oldBundleInfo, const InnerBundleInfo &newInfo) const
2206 {
2207 auto moduleName = newInfo.GetModuleNameVec().at(0);
2208 std::string existModuleHash;
2209 for (auto hapInfo : oldBundleInfo.hapModuleInfos) {
2210 if (hapInfo.package == moduleName) {
2211 existModuleHash = hapInfo.buildHash;
2212 }
2213 }
2214 std::string curModuleHash;
2215 if (!newInfo.GetModuleBuildHash(moduleName, curModuleHash)) {
2216 LOG_D(BMS_TAG_DEFAULT, "module(%{public}s) is not existed", moduleName.c_str());
2217 return false;
2218 }
2219 if (existModuleHash != curModuleHash) {
2220 LOG_D(BMS_TAG_DEFAULT, "(%{public}s) buildHash changed update corresponding hap or hsp", moduleName.c_str());
2221 return true;
2222 }
2223 return false;
2224 }
2225
InnerProcessRebootSharedBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)2226 void BMSEventHandler::InnerProcessRebootSharedBundleInstall(
2227 const std::list<std::string> &scanPathList, Constants::AppType appType)
2228 {
2229 LOG_I(BMS_TAG_DEFAULT, "InnerProcessRebootSharedBundleInstall");
2230 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2231 if (dataMgr == nullptr) {
2232 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2233 return;
2234 }
2235 for (const auto &scanPath : scanPathList) {
2236 bool removable = IsPreInstallRemovable(scanPath);
2237 std::unordered_map<std::string, InnerBundleInfo> infos;
2238 if (!ParseHapFiles(scanPath, infos) || infos.empty()) {
2239 LOG_E(BMS_TAG_DEFAULT, "obtain bundleinfo failed : %{public}s ", scanPath.c_str());
2240 continue;
2241 }
2242
2243 auto bundleName = infos.begin()->second.GetBundleName();
2244 auto versionCode = infos.begin()->second.GetVersionCode();
2245 AddParseInfosToMap(bundleName, infos);
2246 auto mapIter = loadExistData_.find(bundleName);
2247 if (mapIter == loadExistData_.end()) {
2248 LOG_I(BMS_TAG_DEFAULT, "OTA Install new shared bundle(%{public}s) by path(%{public}s)",
2249 bundleName.c_str(), scanPath.c_str());
2250 if (!OTAInstallSystemSharedBundle({scanPath}, appType, removable)) {
2251 LOG_E(BMS_TAG_DEFAULT, "OTA Install new shared bundle(%{public}s) error", bundleName.c_str());
2252 }
2253 continue;
2254 }
2255
2256 InnerBundleInfo oldBundleInfo;
2257 bool hasInstalled = dataMgr->FetchInnerBundleInfo(bundleName, oldBundleInfo);
2258 if (!hasInstalled) {
2259 LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) has been uninstalled and do not OTA install", bundleName.c_str());
2260 continue;
2261 }
2262
2263 if (oldBundleInfo.GetVersionCode() > versionCode) {
2264 LOG_D(BMS_TAG_DEFAULT, "the installed version is up-to-date");
2265 continue;
2266 }
2267 if (oldBundleInfo.GetVersionCode() == versionCode) {
2268 if (!IsNeedToUpdateSharedAppByHash(oldBundleInfo, infos.begin()->second)) {
2269 LOG_D(BMS_TAG_DEFAULT, "the installed version is up-to-date");
2270 continue;
2271 }
2272 }
2273
2274 if (!OTAInstallSystemSharedBundle({scanPath}, appType, removable)) {
2275 LOG_E(BMS_TAG_DEFAULT, "OTA update shared bundle(%{public}s) error", bundleName.c_str());
2276 }
2277 }
2278 }
2279
InnerProcessRebootSystemHspInstall(const std::list<std::string> & scanPathList)2280 void BMSEventHandler::InnerProcessRebootSystemHspInstall(const std::list<std::string> &scanPathList)
2281 {
2282 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "InnerProcessRebootSystemHspInstall");
2283 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2284 if (dataMgr == nullptr) {
2285 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2286 return;
2287 }
2288 for (const auto &scanPath : scanPathList) {
2289 std::unordered_map<std::string, InnerBundleInfo> infos;
2290 if (!ParseHapFiles(scanPath, infos) || infos.empty()) {
2291 LOG_E(BMS_TAG_DEFAULT, "obtain bundleinfo failed : %{public}s ", scanPath.c_str());
2292 SavePreInstallExceptionAppService(scanPath);
2293 continue;
2294 }
2295 auto bundleName = infos.begin()->second.GetBundleName();
2296 auto versionCode = infos.begin()->second.GetVersionCode();
2297 AddParseInfosToMap(bundleName, infos);
2298 auto mapIter = loadExistData_.find(bundleName);
2299 if (mapIter == loadExistData_.end()) {
2300 SavePreInstallExceptionAppService(scanPath);
2301 auto ret = OTAInstallSystemHsp({scanPath});
2302 LOG_I(BMS_TAG_DEFAULT, "OTA Install new system hsp(%{public}s) by path(%{public}s) ret %{public}d",
2303 bundleName.c_str(), scanPath.c_str(), ret);
2304 if (ret == ERR_OK) {
2305 DeletePreInstallExceptionAppService(scanPath);
2306 }
2307 continue;
2308 }
2309 InnerBundleInfo oldBundleInfo;
2310 bool hasInstalled = dataMgr->FetchInnerBundleInfo(bundleName, oldBundleInfo);
2311 if (!hasInstalled) {
2312 LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) has been uninstalled and do not OTA install", bundleName.c_str());
2313 continue;
2314 }
2315 if (oldBundleInfo.GetVersionCode() > versionCode) {
2316 LOG_D(BMS_TAG_DEFAULT, "the installed version is up-to-date");
2317 continue;
2318 }
2319 if (oldBundleInfo.GetVersionCode() == versionCode) {
2320 for (const auto &item : infos) {
2321 if (!IsNeedToUpdateSharedHspByHash(oldBundleInfo, item.second)) {
2322 LOG_D(BMS_TAG_DEFAULT, "the installed version is up-to-date");
2323 continue;
2324 }
2325 }
2326 }
2327 SavePreInstallExceptionAppService(scanPath);
2328 auto ret = OTAInstallSystemHsp({scanPath});
2329 LOG_I(BMS_TAG_DEFAULT, "OTA Install system hsp(%{public}s) by path(%{public}s) ret %{public}d",
2330 bundleName.c_str(), scanPath.c_str(), ret);
2331 if (ret == ERR_OK) {
2332 DeletePreInstallExceptionAppService(scanPath);
2333 }
2334 }
2335 }
2336
ProcessRebootAppServiceUninstall()2337 void BMSEventHandler::ProcessRebootAppServiceUninstall()
2338 {
2339 APP_LOGI("Reboot scan and OTA uninstall for appServiceFwk start");
2340 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2341 if (dataMgr == nullptr) {
2342 APP_LOGE("DataMgr is nullptr");
2343 return;
2344 }
2345 for (const auto &loadIter : loadExistData_) {
2346 std::string bundleName = loadIter.first;
2347 auto listIter = hapParseInfoMap_.find(bundleName);
2348 if (listIter == hapParseInfoMap_.end()) {
2349 continue;
2350 }
2351
2352 InnerBundleInfo info;
2353 if (!dataMgr->FetchInnerBundleInfo(bundleName, info)) {
2354 APP_LOGW("app(%{public}s) maybe has been uninstall.", bundleName.c_str());
2355 continue;
2356 }
2357 if (info.GetApplicationBundleType() != BundleType::APP_SERVICE_FWK) {
2358 continue;
2359 }
2360 // Check the installed module
2361 bool isDownGrade = false;
2362 if (InnerProcessUninstallAppServiceModule(info, listIter->second, isDownGrade)) {
2363 APP_LOGI("bundleName:%{public}s need delete module", bundleName.c_str());
2364 }
2365 if (isDownGrade) {
2366 APP_LOGI("bundleName:%{public}s is being downgraded for ota", bundleName.c_str());
2367 continue;
2368 }
2369 // Check the preInstall path in Db.
2370 // If the corresponding Hap does not exist, it should be deleted.
2371 auto parserInfoMap = listIter->second;
2372 for (const auto &preBundlePath : loadIter.second.GetBundlePaths()) {
2373 auto parserInfoIter = parserInfoMap.find(preBundlePath);
2374 if (parserInfoIter != parserInfoMap.end()) {
2375 APP_LOGI("OTA uninstall app(%{public}s) module path(%{public}s) exits.",
2376 bundleName.c_str(), preBundlePath.c_str());
2377 continue;
2378 }
2379
2380 APP_LOGI("OTA app(%{public}s) delete path(%{public}s).",
2381 bundleName.c_str(), preBundlePath.c_str());
2382 DeletePreInfoInDb(bundleName, preBundlePath, false);
2383 }
2384 }
2385 APP_LOGI("Reboot scan and OTA uninstall for appServiceFwk success");
2386 }
2387
InnerProcessUninstallAppServiceModule(const InnerBundleInfo & innerBundleInfo,const std::unordered_map<std::string,InnerBundleInfo> & infos,bool & isDownGrade)2388 bool BMSEventHandler::InnerProcessUninstallAppServiceModule(const InnerBundleInfo &innerBundleInfo,
2389 const std::unordered_map<std::string, InnerBundleInfo> &infos, bool &isDownGrade)
2390 {
2391 if (infos.empty()) {
2392 APP_LOGI("bundleName:%{public}s infos is empty", innerBundleInfo.GetBundleName().c_str());
2393 return false;
2394 }
2395 if (innerBundleInfo.GetVersionCode() > infos.begin()->second.GetVersionCode()) {
2396 APP_LOGI("bundleName:%{public}s version code is bigger than new pre-hap",
2397 innerBundleInfo.GetBundleName().c_str());
2398 isDownGrade = true;
2399 return false;
2400 }
2401 std::vector<std::string> moduleNameList;
2402 innerBundleInfo.GetModuleNames(moduleNameList);
2403 // Check the installed module.
2404 // If the corresponding module does not exist, it should be uninstalled.
2405 std::vector<std::string> moduleNeedUnsinstall;
2406 for (const auto &moduleName : moduleNameList) {
2407 bool isModuleExist = false;
2408 for (const auto &parserInfoIter : infos) {
2409 auto parserModuleNames = parserInfoIter.second.GetModuleNameVec();
2410 if (!parserModuleNames.empty() && moduleName == parserModuleNames[0]) {
2411 isModuleExist = true;
2412 break;
2413 }
2414 }
2415
2416 if (!isModuleExist) {
2417 APP_LOGI("ProcessRebootBundleUninstall OTA app(%{public}s) uninstall module(%{public}s).",
2418 innerBundleInfo.GetBundleName().c_str(), moduleName.c_str());
2419 moduleNeedUnsinstall.emplace_back(moduleName);
2420 }
2421 }
2422 if (moduleNeedUnsinstall.empty()) {
2423 return true;
2424 }
2425 for (const std::string &moduleName : moduleNeedUnsinstall) {
2426 AppServiceFwkInstaller installer;
2427 if (installer.UnInstall(innerBundleInfo.GetBundleName(), moduleName) != ERR_OK) {
2428 APP_LOGW("uninstall failed");
2429 }
2430 }
2431 return true;
2432 }
2433
OTAInstallSystemHsp(const std::vector<std::string> & filePaths)2434 ErrCode BMSEventHandler::OTAInstallSystemHsp(const std::vector<std::string> &filePaths)
2435 {
2436 InstallParam installParam;
2437 installParam.isPreInstallApp = true;
2438 installParam.removable = false;
2439 installParam.isOTA = true;
2440 installParam.copyHapToInstallPath = false;
2441 installParam.needSavePreInstallInfo = true;
2442 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
2443 AppServiceFwkInstaller installer;
2444
2445 return installer.Install(filePaths, installParam);
2446 }
2447
IsNeedToUpdateSharedHspByHash(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const2448 bool BMSEventHandler::IsNeedToUpdateSharedHspByHash(
2449 const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
2450 {
2451 std::string moduleName = newInfo.GetCurrentModulePackage();
2452 std::string newModuleBuildHash;
2453 if (!newInfo.GetModuleBuildHash(moduleName, newModuleBuildHash)) {
2454 LOG_E(BMS_TAG_DEFAULT, "internal error, can not find module %{public}s", moduleName.c_str());
2455 return false;
2456 }
2457
2458 std::string oldModuleBuildHash;
2459 if (!oldInfo.GetModuleBuildHash(moduleName, oldModuleBuildHash) ||
2460 newModuleBuildHash != oldModuleBuildHash) {
2461 LOG_D(BMS_TAG_DEFAULT, "module %{public}s need to be updated", moduleName.c_str());
2462 return true;
2463 }
2464 return false;
2465 }
2466
IsNeedToUpdateSharedAppByHash(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const2467 bool BMSEventHandler::IsNeedToUpdateSharedAppByHash(
2468 const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
2469 {
2470 auto oldSharedModuleMap = oldInfo.GetInnerSharedModuleInfos();
2471 auto newSharedModuleMap = newInfo.GetInnerSharedModuleInfos();
2472 for (const auto &item : newSharedModuleMap) {
2473 auto newModuleName = item.first;
2474 auto oldModuleInfos = oldSharedModuleMap[newModuleName];
2475 auto newModuleInfos = item.second;
2476 if (!oldModuleInfos.empty() && !newModuleInfos.empty()) {
2477 auto oldBuildHash = oldModuleInfos[0].buildHash;
2478 auto newBuildHash = newModuleInfos[0].buildHash;
2479 return oldBuildHash != newBuildHash;
2480 } else {
2481 return true;
2482 }
2483 }
2484 return false;
2485 }
2486
SaveSystemFingerprint()2487 void BMSEventHandler::SaveSystemFingerprint()
2488 {
2489 auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
2490 if (bmsPara == nullptr) {
2491 LOG_E(BMS_TAG_DEFAULT, "bmsPara is nullptr");
2492 return;
2493 }
2494
2495 std::string curSystemFingerprint = GetCurSystemFingerprint();
2496 LOG_I(BMS_TAG_DEFAULT, "curSystemFingerprint(%{public}s)", curSystemFingerprint.c_str());
2497 if (curSystemFingerprint.empty()) {
2498 return;
2499 }
2500
2501 bmsPara->SaveBmsParam(FINGERPRINT, curSystemFingerprint);
2502 }
2503
HandleOTACodeEncryption()2504 void BMSEventHandler::HandleOTACodeEncryption()
2505 {
2506 std::string codeProtectFlag;
2507 auto bmsParam = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
2508 if (bmsParam != nullptr) {
2509 bmsParam->GetBmsParam(CODE_PROTECT_FLAG, codeProtectFlag);
2510 if (codeProtectFlag == std::string{ CODE_PROTECT_FLAG_CHECKED }) {
2511 LOG_I(BMS_TAG_DEFAULT, "checked");
2512 return;
2513 }
2514 }
2515 LOG_I(BMS_TAG_DEFAULT, "begin");
2516 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2517 if (dataMgr == nullptr) {
2518 LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
2519 return;
2520 }
2521 dataMgr->HandleOTACodeEncryption();
2522 BmsExtensionDataMgr bmsExtensionDataMgr;
2523 std::vector<CodeProtectBundleInfo> infos;
2524 auto res = bmsExtensionDataMgr.KeyOperation(infos, CodeOperation::OTA_CHECK_FINISHED);
2525 LOG_I(BMS_TAG_DEFAULT, "keyOperation result %{public}d", res);
2526 SaveCodeProtectFlag();
2527 }
2528
SaveCodeProtectFlag()2529 void BMSEventHandler::SaveCodeProtectFlag()
2530 {
2531 auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
2532 if (bmsPara == nullptr) {
2533 LOG_E(BMS_TAG_DEFAULT, "bmsPara is nullptr");
2534 return;
2535 }
2536 if (!bmsPara->SaveBmsParam(CODE_PROTECT_FLAG, std::string{ CODE_PROTECT_FLAG_CHECKED })) {
2537 LOG_E(BMS_TAG_DEFAULT, "save failed");
2538 }
2539 }
2540
IsModuleUpdate()2541 bool BMSEventHandler::IsModuleUpdate()
2542 {
2543 std::string paramValue;
2544 if (!GetSystemParameter(MODULE_UPDATE_PARAM, paramValue) || paramValue.empty()) {
2545 LOG_E(BMS_TAG_DEFAULT, "get system paramter failed");
2546 return false;
2547 }
2548 LOG_I(BMS_TAG_DEFAULT, "parameter %{public}s is %{public}s", MODULE_UPDATE_PARAM, paramValue.c_str());
2549 if (paramValue == MODULE_UPDATE_VALUE_UPDATE) {
2550 moduleUpdateStatus_ = ModuleUpdateStatus::UPDATE;
2551 } else if (paramValue == MODULE_UPDATE_VALUE_REVERT_BMS) {
2552 moduleUpdateStatus_ = ModuleUpdateStatus::REVERT;
2553 } else {
2554 moduleUpdateStatus_ = ModuleUpdateStatus::DEFAULT;
2555 return false;
2556 }
2557 return true;
2558 }
2559
HandleModuleUpdate()2560 void BMSEventHandler::HandleModuleUpdate()
2561 {
2562 // 1. get hmp list and dir path
2563 // key: hmp name, value: appServiceFwk path of the hmp
2564 std::map<std::string, std::vector<std::string>> moduleUpdateAppServiceMap;
2565 // key: hmp name, value: normal app path of the hmp
2566 std::map<std::string, std::vector<std::string>> moduleUpdateNotAppServiceMap;
2567 if (!GetModuleUpdatePathList(moduleUpdateAppServiceMap, moduleUpdateNotAppServiceMap)) {
2568 LOG_E(BMS_TAG_DEFAULT, "get module update path map failed");
2569 return;
2570 }
2571 // 2. process rollback if needed
2572 ModuleUpdateRollBack();
2573 // 2. install all hmp, if install failed,
2574 HandleInstallHmp(moduleUpdateAppServiceMap, moduleUpdateNotAppServiceMap);
2575 // 3. update system parmeters
2576 ProcessModuleUpdateSystemParameters();
2577 // 4. uninstall redundant module
2578 HandleHmpUninstall();
2579 }
2580
CheckIsModuleUpdate(const std::string & str)2581 bool BMSEventHandler::CheckIsModuleUpdate(const std::string &str)
2582 {
2583 return str.find(MODULE_UPDATE_PATH) == 0 ||
2584 str.find(std::string(ServiceConstants::PATH_SEPARATOR) +
2585 MODULE_UPDATE_PATH) == 0;
2586 }
2587
GetModuleUpdatePathList(std::map<std::string,std::vector<std::string>> & moduleUpdateAppServiceMap,std::map<std::string,std::vector<std::string>> & moduleUpdateNotAppServiceMap)2588 bool BMSEventHandler::GetModuleUpdatePathList(
2589 std::map<std::string, std::vector<std::string>> &moduleUpdateAppServiceMap,
2590 std::map<std::string, std::vector<std::string>> &moduleUpdateNotAppServiceMap)
2591 {
2592 #ifdef USE_PRE_BUNDLE_PROFILE
2593 if (!LoadPreInstallProFile()) {
2594 LOG_W(BMS_TAG_DEFAULT, "LoadPreInstallProFile failed");
2595 return false;
2596 }
2597 std::vector<std::string> systemHspDirList;
2598 for (const auto &item : systemHspList_) {
2599 systemHspDirList.emplace_back(item.bundleDir);
2600 }
2601 FilterModuleUpdate(systemHspDirList, moduleUpdateAppServiceMap, true);
2602 std::vector<std::string> preInstallDirs;
2603 GetPreInstallDirFromLoadProFile(preInstallDirs);
2604 FilterModuleUpdate(preInstallDirs, moduleUpdateNotAppServiceMap, false);
2605 return true;
2606 #endif
2607 LOG_W(BMS_TAG_DEFAULT, "USE_PRE_BUNDLE_PROFILE is not defined");
2608 return false;
2609 }
2610
HandleInstallHmp(const std::map<std::string,std::vector<std::string>> & moduleUpdateAppServiceMap,const std::map<std::string,std::vector<std::string>> & moduleUpdateNotAppServiceMap)2611 bool BMSEventHandler::HandleInstallHmp(
2612 const std::map<std::string, std::vector<std::string>> &moduleUpdateAppServiceMap,
2613 const std::map<std::string, std::vector<std::string>> &moduleUpdateNotAppServiceMap)
2614 {
2615 LOG_I(BMS_TAG_DEFAULT, "begin to HandleInstallHmp");
2616 for (const auto &item : moduleUpdateAppServiceMap) {
2617 LOG_I(BMS_TAG_DEFAULT, "begin to install hmp %{public}s", item.first.c_str());
2618 if (!HandleInstallModuleUpdateSystemHsp(item.second)) {
2619 LOG_E(BMS_TAG_DEFAULT, "hmp %{public}s install appServiceFwk failed", item.first.c_str());
2620 moduleUpdateInstallResults_[item.first] = false;
2621 continue;
2622 }
2623 LOG_I(BMS_TAG_DEFAULT, "hmp %{public}s install appService success", item.first.c_str());
2624 moduleUpdateInstallResults_[item.first] = true;
2625 }
2626
2627 for (const auto &item : moduleUpdateNotAppServiceMap) {
2628 LOG_I(BMS_TAG_DEFAULT, "begin to install hmp %{public}s", item.first.c_str());
2629 if (!HandleInstallModuleUpdateNormalApp(item.second)) {
2630 LOG_E(BMS_TAG_DEFAULT, "hmp %{public}s install app failed", item.first.c_str());
2631 moduleUpdateInstallResults_[item.first] = false;
2632 continue;
2633 }
2634 auto iter = moduleUpdateInstallResults_.find(item.first);
2635 if (iter != moduleUpdateInstallResults_.end() && !(iter->second)) {
2636 LOG_I(BMS_TAG_DEFAULT, "hmp %{public}s install appService has been failed",
2637 item.first.c_str());
2638 continue;
2639 }
2640 LOG_I(BMS_TAG_DEFAULT, "hmp %{public}s install success", item.first.c_str());
2641 moduleUpdateInstallResults_[item.first] = true;
2642 }
2643 return true;
2644 }
2645
HandleInstallModuleUpdateSystemHsp(const std::vector<std::string> & appDirList)2646 bool BMSEventHandler::HandleInstallModuleUpdateSystemHsp(const std::vector<std::string> &appDirList)
2647 {
2648 bool result = true;
2649 for (const std::string &systemHspDir : appDirList) {
2650 if (!ProcessSystemHspInstall(systemHspDir)) {
2651 LOG_E(BMS_TAG_DEFAULT, "install %{public}s path failed", systemHspDir.c_str());
2652 result = false;
2653 }
2654 }
2655
2656 return result;
2657 }
2658
HandleInstallModuleUpdateNormalApp(const std::vector<std::string> & appDirList)2659 bool BMSEventHandler::HandleInstallModuleUpdateNormalApp(const std::vector<std::string> &appDirList)
2660 {
2661 bool result = true;
2662 for (const std::string &appDir : appDirList) {
2663 std::string normalizedAppDir = appDir;
2664 if (!appDir.empty() && appDir.back() == SEPARATOR) {
2665 normalizedAppDir = appDir.substr(0, appDir.size() - 1);
2666 }
2667
2668 std::shared_ptr<HmpBundleInstaller> installer = std::make_shared<HmpBundleInstaller>();
2669 bool removable = GetRemovableInfo(appDir);
2670 auto res = installer->InstallNormalAppInHmp(normalizedAppDir, removable);
2671 LOG_I(BMS_TAG_DEFAULT, "install %{public}s %{public}d", appDir.c_str(), res);
2672 if (res == ERR_OK || (res == ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE && CheckAppIsUpdatedByUser(appDir))) {
2673 continue;
2674 }
2675 LOG_E(BMS_TAG_DEFAULT, "install %{public}s path failed", appDir.c_str());
2676 result = false;
2677 }
2678 return result;
2679 }
2680
CheckAppIsUpdatedByUser(const std::string & appDir)2681 bool BMSEventHandler::CheckAppIsUpdatedByUser(const std::string& appDir)
2682 {
2683 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2684 if (dataMgr == nullptr) {
2685 LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
2686 return false;
2687 }
2688 std::string bundleName = GetBundleNameByPreInstallPath(appDir);
2689 if (bundleName.empty()) {
2690 LOG_E(BMS_TAG_DEFAULT, "get bundleName failed, %{public}s", appDir.c_str());
2691 return false;
2692 }
2693 BundleInfo bundleInfo;
2694 auto baseFlag = static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
2695 static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE);
2696 ErrCode ret = dataMgr->GetBundleInfoV9(bundleName, baseFlag, bundleInfo, Constants::ANY_USERID);
2697 if (ret != ERR_OK) {
2698 LOG_I(BMS_TAG_DEFAULT, "%{public}s not found", bundleName.c_str());
2699 return false;
2700 }
2701 for (const auto &hapInfo : bundleInfo.hapModuleInfos) {
2702 if (hapInfo.hapPath.size() > std::string(HAP_PATH_DATA_AREA).size() &&
2703 hapInfo.hapPath.compare(0, std::string(HAP_PATH_DATA_AREA).size(), std::string(HAP_PATH_DATA_AREA)) == 0) {
2704 LOG_I(BMS_TAG_DEFAULT, "%{public}s has been updated by user", hapInfo.name.c_str());
2705 return true;
2706 }
2707 }
2708 LOG_I(BMS_TAG_DEFAULT, "%{public}s has not been updated by user", bundleName.c_str());
2709 return false;
2710 }
2711
GetRemovableInfo(const std::string & bundleDir)2712 bool BMSEventHandler::GetRemovableInfo(const std::string& bundleDir)
2713 {
2714 auto it = std::find_if(installList_.begin(), installList_.end(), [&bundleDir](const PreScanInfo& info) {
2715 return info.bundleDir == bundleDir;
2716 });
2717 if (it != installList_.end()) {
2718 return it->removable;
2719 }
2720 LOG_W(BMS_TAG_DEFAULT, "%{public}s not found", bundleDir.c_str());
2721 return true;
2722 }
2723
FilterModuleUpdate(const std::vector<std::string> & preInstallDirs,std::map<std::string,std::vector<std::string>> & moduleUpdatePathMap,bool isAppService)2724 void BMSEventHandler::FilterModuleUpdate(const std::vector<std::string> &preInstallDirs,
2725 std::map<std::string, std::vector<std::string>> &moduleUpdatePathMap, bool isAppService)
2726 {
2727 for (const std::string &preInstallDir : preInstallDirs) {
2728 if (!CheckIsModuleUpdate(preInstallDir)) {
2729 continue;
2730 }
2731 std::string moduleUpdatePath = std::string(MODULE_UPDATE_PATH) + ServiceConstants::PATH_SEPARATOR;
2732 size_t start = preInstallDir.find(moduleUpdatePath);
2733 if (start == std::string::npos) {
2734 continue;
2735 }
2736 start += std::string(moduleUpdatePath).length();
2737
2738 size_t end = preInstallDir.find(ServiceConstants::PATH_SEPARATOR, start);
2739 if (end == std::string::npos) {
2740 continue;
2741 }
2742 std::string hmpName = preInstallDir.substr(start, end - start);
2743 LOG_I(BMS_TAG_DEFAULT, "path %{public}s added to hmp %{public}s", preInstallDir.c_str(), hmpName.c_str());
2744 moduleUpdatePathMap[hmpName].emplace_back(preInstallDir);
2745 std::string bundleName = GetBundleNameByPreInstallPath(preInstallDir);
2746 if (isAppService) {
2747 LOG_I(BMS_TAG_DEFAULT, "appService %{public}s added to hmp %{public}s",
2748 bundleName.c_str(), hmpName.c_str());
2749 moduleUpdateAppService_[hmpName].insert(bundleName);
2750 } else {
2751 if (moduleUpdateAppService_[hmpName].find(bundleName) == moduleUpdateAppService_[hmpName].end()) {
2752 LOG_I(BMS_TAG_DEFAULT, "app %{public}s added to hmp %{public}s", bundleName.c_str(), hmpName.c_str());
2753 moduleUpdateNormalApp_[hmpName].insert(bundleName);
2754 }
2755 }
2756 SaveHmpBundlePathInfo(hmpName, bundleName, preInstallDir, isAppService);
2757 }
2758 }
2759
SaveHmpBundlePathInfo(const std::string & hmpName,const std::string & bundleName,const std::string bundlePath,bool isAppService)2760 void BMSEventHandler::SaveHmpBundlePathInfo(const std::string &hmpName,
2761 const std::string &bundleName, const std::string bundlePath, bool isAppService)
2762 {
2763 HmpBundlePathInfo info;
2764 info.bundleName = bundleName;
2765 info.hmpName = hmpName;
2766 auto it = hmpBundlePathInfos_.find(bundleName);
2767 if (it != hmpBundlePathInfos_.end()) {
2768 info = it->second;
2769 }
2770 if (isAppService) {
2771 info.hspDir = bundlePath;
2772 } else {
2773 info.bundleDir = bundlePath;
2774 }
2775 hmpBundlePathInfos_[bundleName] = info;
2776 }
2777
GetHmpList(std::vector<std::string> & hmpList,std::map<std::string,std::vector<std::string>> & moduleUpdateAppServiceMap,std::map<std::string,std::vector<std::string>> & moduleUpdateNotAppServiceMap)2778 void BMSEventHandler::GetHmpList(std::vector<std::string> &hmpList,
2779 std::map<std::string, std::vector<std::string>> &moduleUpdateAppServiceMap,
2780 std::map<std::string, std::vector<std::string>> &moduleUpdateNotAppServiceMap)
2781 {
2782 std::set<std::string> hmpSet;
2783 for (const auto &item : moduleUpdateAppServiceMap) {
2784 hmpSet.insert(item.first);
2785 }
2786 for (const auto &item : moduleUpdateNotAppServiceMap) {
2787 hmpSet.insert(item.first);
2788 }
2789 hmpList.assign(hmpSet.begin(), hmpSet.end());
2790 }
2791
GetBundleNameByPreInstallPath(const std::string & path)2792 std::string BMSEventHandler::GetBundleNameByPreInstallPath(const std::string& path)
2793 {
2794 std::vector<std::string> parts;
2795 std::string part;
2796 std::stringstream ss(path);
2797
2798 while (getline(ss, part, SEPARATOR)) {
2799 if (!part.empty()) {
2800 parts.push_back(part);
2801 }
2802 }
2803
2804 if (!parts.empty()) {
2805 return parts.back();
2806 } else {
2807 return std::string{};
2808 }
2809 }
2810
ModuleUpdateRollBack()2811 void BMSEventHandler::ModuleUpdateRollBack()
2812 {
2813 if (moduleUpdateStatus_ != ModuleUpdateStatus::REVERT) {
2814 return;
2815 }
2816 std::set<std::string> normalAppSet;
2817 std::set<std::string> appServiceSet;
2818 for (const auto &item : moduleUpdateNormalApp_) {
2819 normalAppSet.insert(item.second.begin(), item.second.end());
2820 }
2821 for (const auto &item : moduleUpdateAppService_) {
2822 appServiceSet.insert(item.second.begin(), item.second.end());
2823 }
2824 LOG_W(BMS_TAG_DEFAULT, "hmp need to rollback");
2825 // rollback hmp which install failed
2826 std::shared_ptr<HmpBundleInstaller> installer = std::make_shared<HmpBundleInstaller>();
2827 installer->RollbackHmpBundle(appServiceSet, normalAppSet);
2828 }
2829
ProcessModuleUpdateSystemParameters()2830 void BMSEventHandler::ProcessModuleUpdateSystemParameters()
2831 {
2832 if (moduleUpdateStatus_ == ModuleUpdateStatus::UPDATE) {
2833 bool hasFailed = false;
2834 for (const auto &item : moduleUpdateInstallResults_) {
2835 if (item.second) {
2836 LOG_I(BMS_TAG_DEFAULT, "hmp %{public}s install success", item.first.c_str());
2837 continue;
2838 }
2839 hasFailed = true;
2840 LOG_W(BMS_TAG_DEFAULT, "hmp %{public}s install failed", item.first.c_str());
2841 std::string parameter = MODULE_UPDATE_INSTALL_RESULT + item.first;
2842 system::SetParameter(parameter, MODULE_UPDATE_INSTALL_RESULT_FALSE);
2843 }
2844 if (hasFailed) {
2845 LOG_I(BMS_TAG_DEFAULT, "module update failed, parameter %{public}s modified to revert",
2846 MODULE_UPDATE_PARAM);
2847 system::SetParameter(MODULE_UPDATE_PARAM, MODULE_UPDATE_VALUE_REVERT);
2848 } else {
2849 LOG_I(BMS_TAG_DEFAULT, "module update success");
2850 system::SetParameter(MODULE_UPDATE_PARAM, MODULE_UPDATE_PARAM_EMPTY);
2851 }
2852 } else if (moduleUpdateStatus_ == ModuleUpdateStatus::REVERT) {
2853 LOG_I(BMS_TAG_DEFAULT, "revert end, all parameters modified to empty");
2854 system::SetParameter(MODULE_UPDATE_PARAM, MODULE_UPDATE_PARAM_EMPTY);
2855 for (const auto &item : moduleUpdateInstallResults_) {
2856 std::string parameter = MODULE_UPDATE_INSTALL_RESULT + item.first;
2857 system::SetParameter(parameter, MODULE_UPDATE_PARAM_EMPTY);
2858 }
2859 }
2860 }
2861
HandleHmpUninstall()2862 void BMSEventHandler::HandleHmpUninstall()
2863 {
2864 for (const auto &item : hmpBundlePathInfos_) {
2865 std::string hmpName = item.second.hmpName;
2866 if (moduleUpdateStatus_ == ModuleUpdateStatus::UPDATE && !moduleUpdateInstallResults_[hmpName]) {
2867 LOG_I(BMS_TAG_DEFAULT, "hmp %{public}s update failed, it has been rollback", hmpName.c_str());
2868 continue;
2869 }
2870 std::shared_ptr<HmpBundleInstaller> installer = std::make_shared<HmpBundleInstaller>();
2871 installer->UpdateBundleInfo(item.second.bundleName, item.second.bundleDir, item.second.hspDir);
2872 }
2873 }
2874
IsSystemUpgrade()2875 bool BMSEventHandler::IsSystemUpgrade()
2876 {
2877 return IsTestSystemUpgrade() || IsSystemFingerprintChanged();
2878 }
2879
IsTestSystemUpgrade()2880 bool BMSEventHandler::IsTestSystemUpgrade()
2881 {
2882 std::string paramValue;
2883 if (!GetSystemParameter(BMS_TEST_UPGRADE, paramValue) || paramValue.empty()) {
2884 return false;
2885 }
2886
2887 LOG_I(BMS_TAG_DEFAULT, "TestSystemUpgrade value is %{public}s", paramValue.c_str());
2888 return paramValue == VALUE_TRUE;
2889 }
2890
IsSystemFingerprintChanged()2891 bool BMSEventHandler::IsSystemFingerprintChanged()
2892 {
2893 std::string oldSystemFingerprint = GetOldSystemFingerprint();
2894 if (oldSystemFingerprint.empty()) {
2895 LOG_D(BMS_TAG_DEFAULT, "System should be upgraded due to oldSystemFingerprint is empty");
2896 return true;
2897 }
2898
2899 std::string curSystemFingerprint = GetCurSystemFingerprint();
2900 LOG_D(BMS_TAG_DEFAULT, "oldSystemFingerprint(%{public}s), curSystemFingerprint(%{public}s)",
2901 oldSystemFingerprint.c_str(), curSystemFingerprint.c_str());
2902 return curSystemFingerprint != oldSystemFingerprint;
2903 }
2904
GetCurSystemFingerprint()2905 std::string BMSEventHandler::GetCurSystemFingerprint()
2906 {
2907 std::string curSystemFingerprint;
2908 for (const auto &item : FINGERPRINTS) {
2909 std::string itemFingerprint;
2910 if (!GetSystemParameter(item, itemFingerprint) || itemFingerprint.empty()) {
2911 continue;
2912 }
2913
2914 if (!curSystemFingerprint.empty()) {
2915 curSystemFingerprint.append(ServiceConstants::PATH_SEPARATOR);
2916 }
2917
2918 curSystemFingerprint.append(itemFingerprint);
2919 }
2920
2921 return curSystemFingerprint;
2922 }
2923
GetSystemParameter(const std::string & key,std::string & value)2924 bool BMSEventHandler::GetSystemParameter(const std::string &key, std::string &value)
2925 {
2926 char firmware[VERSION_LEN] = {0};
2927 int32_t ret = GetParameter(key.c_str(), UNKNOWN, firmware, VERSION_LEN);
2928 if (ret <= 0) {
2929 LOG_E(BMS_TAG_DEFAULT, "GetParameter failed");
2930 return false;
2931 }
2932
2933 value = firmware;
2934 return true;
2935 }
2936
GetOldSystemFingerprint()2937 std::string BMSEventHandler::GetOldSystemFingerprint()
2938 {
2939 std::string oldSystemFingerprint;
2940 auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
2941 if (bmsPara != nullptr) {
2942 bmsPara->GetBmsParam(FINGERPRINT, oldSystemFingerprint);
2943 }
2944
2945 return oldSystemFingerprint;
2946 }
2947
AddParseInfosToMap(const std::string & bundleName,const std::unordered_map<std::string,InnerBundleInfo> & infos)2948 void BMSEventHandler::AddParseInfosToMap(
2949 const std::string &bundleName, const std::unordered_map<std::string, InnerBundleInfo> &infos)
2950 {
2951 auto hapParseInfoMapIter = hapParseInfoMap_.find(bundleName);
2952 if (hapParseInfoMapIter == hapParseInfoMap_.end()) {
2953 hapParseInfoMap_.emplace(bundleName, infos);
2954 return;
2955 }
2956
2957 auto iterMap = hapParseInfoMapIter->second;
2958 for (auto infoIter : infos) {
2959 iterMap.emplace(infoIter.first, infoIter.second);
2960 }
2961
2962 hapParseInfoMap_.at(bundleName) = iterMap;
2963 }
2964
ProcessRebootBundleUninstall()2965 void BMSEventHandler::ProcessRebootBundleUninstall()
2966 {
2967 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "Reboot scan and OTA uninstall start");
2968 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2969 if (dataMgr == nullptr) {
2970 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
2971 return;
2972 }
2973
2974 for (auto &loadIter : loadExistData_) {
2975 std::string bundleName = loadIter.first;
2976 BundleInfo hasInstalledInfo;
2977 auto hasBundleInstalled = dataMgr->GetBundleInfo(
2978 bundleName, static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
2979 hasInstalledInfo, Constants::ANY_USERID);
2980 auto listIter = hapParseInfoMap_.find(bundleName);
2981 if (listIter == hapParseInfoMap_.end()) {
2982 LOG_I(BMS_TAG_DEFAULT, "ProcessRebootBundleUninstall OTA uninstall app(%{public}s)", bundleName.c_str());
2983 if (InnerProcessUninstallForExistPreBundle(hasInstalledInfo)) {
2984 continue;
2985 }
2986 SystemBundleInstaller installer;
2987 if (!installer.UninstallSystemBundle(bundleName)) {
2988 LOG_E(BMS_TAG_DEFAULT, "OTA uninstall app(%{public}s) error", bundleName.c_str());
2989 } else {
2990 LOG_I(BMS_TAG_DEFAULT, "OTA uninstall preInstall bundleName:%{public}s succeed", bundleName.c_str());
2991 std::string moduleName;
2992 DeletePreInfoInDb(bundleName, moduleName, true);
2993 }
2994
2995 continue;
2996 }
2997
2998 if (!hasBundleInstalled) {
2999 LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) maybe has been uninstall", bundleName.c_str());
3000 continue;
3001 }
3002 // Check the installed module
3003 bool isDownGrade = false;
3004 if (InnerProcessUninstallModule(hasInstalledInfo, listIter->second, isDownGrade)) {
3005 LOG_I(BMS_TAG_DEFAULT, "bundleName:%{public}s need delete module", bundleName.c_str());
3006 }
3007 if (isDownGrade) {
3008 LOG_I(BMS_TAG_DEFAULT, "bundleName:%{public}s is being downgraded for ota", bundleName.c_str());
3009 continue;
3010 }
3011 // Check the preInstall path in Db.
3012 // If the corresponding Hap does not exist, it should be deleted.
3013 auto parserInfoMap = listIter->second;
3014 for (auto preBundlePath : loadIter.second.GetBundlePaths()) {
3015 auto parserInfoIter = parserInfoMap.find(preBundlePath);
3016 if (parserInfoIter != parserInfoMap.end()) {
3017 continue;
3018 }
3019
3020 LOG_I(BMS_TAG_DEFAULT, "OTA app(%{public}s) delete path(%{public}s)",
3021 bundleName.c_str(), preBundlePath.c_str());
3022 DeletePreInfoInDb(bundleName, preBundlePath, false);
3023 }
3024 }
3025
3026 LOG_I(BMS_TAG_DEFAULT, "Reboot scan and OTA uninstall success");
3027 }
3028
InnerProcessUninstallModule(const BundleInfo & bundleInfo,const std::unordered_map<std::string,InnerBundleInfo> & infos,bool & isDownGrade)3029 bool BMSEventHandler::InnerProcessUninstallModule(const BundleInfo &bundleInfo,
3030 const std::unordered_map<std::string, InnerBundleInfo> &infos, bool &isDownGrade)
3031 {
3032 if (infos.empty()) {
3033 LOG_I(BMS_TAG_DEFAULT, "bundleName:%{public}s infos is empty", bundleInfo.name.c_str());
3034 return false;
3035 }
3036 if (bundleInfo.versionCode > infos.begin()->second.GetVersionCode()) {
3037 LOG_I(BMS_TAG_DEFAULT, "%{public}s version code is bigger than new pre-hap", bundleInfo.name.c_str());
3038 isDownGrade = true;
3039 return false;
3040 }
3041 for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) {
3042 if (hapModuleInfo.hapPath.find(Constants::BUNDLE_CODE_DIR) == 0) {
3043 return false;
3044 }
3045 }
3046 if (bundleInfo.hapModuleNames.size() == 1) {
3047 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "InnerProcessUninstallModule -n %{public}s only one module forbid uninstall",
3048 bundleInfo.name.c_str());
3049 return false;
3050 }
3051 bool needUninstallModule = false;
3052 // Check the installed module.
3053 // If the corresponding Hap does not exist, it should be uninstalled.
3054 for (auto moduleName : bundleInfo.hapModuleNames) {
3055 bool hasModuleHapExist = false;
3056 for (auto parserInfoIter : infos) {
3057 auto parserModuleNames = parserInfoIter.second.GetModuleNameVec();
3058 if (!parserModuleNames.empty() && moduleName == parserModuleNames[0]) {
3059 hasModuleHapExist = true;
3060 break;
3061 }
3062 }
3063
3064 if (!hasModuleHapExist) {
3065 LOG_I(BMS_TAG_DEFAULT, "ProcessRebootBundleUninstall OTA app(%{public}s) uninstall module(%{public}s)",
3066 bundleInfo.name.c_str(), moduleName.c_str());
3067 needUninstallModule = true;
3068 SystemBundleInstaller installer;
3069 if (!installer.UninstallSystemBundle(bundleInfo.name, moduleName)) {
3070 LOG_E(BMS_TAG_DEFAULT, "OTA app(%{public}s) uninstall module(%{public}s) error",
3071 bundleInfo.name.c_str(), moduleName.c_str());
3072 }
3073 }
3074 }
3075 return needUninstallModule;
3076 }
3077
DeletePreInfoInDb(const std::string & bundleName,const std::string & bundlePath,bool bundleLevel)3078 void BMSEventHandler::DeletePreInfoInDb(
3079 const std::string &bundleName, const std::string &bundlePath, bool bundleLevel)
3080 {
3081 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3082 if (dataMgr == nullptr) {
3083 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3084 return;
3085 }
3086
3087 PreInstallBundleInfo preInstallBundleInfo;
3088 preInstallBundleInfo.SetBundleName(bundleName);
3089 if (bundleLevel) {
3090 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "DeletePreInfoInDb bundle %{public}s bundleLevel", bundleName.c_str());
3091 dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
3092 return;
3093 }
3094
3095 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "DeletePreInfoInDb -n %{public}s bundleLevel=false path:%{public}s",
3096 bundleName.c_str(), bundlePath.c_str());
3097 dataMgr->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo);
3098 preInstallBundleInfo.DeleteBundlePath(bundlePath);
3099 if (preInstallBundleInfo.GetBundlePaths().empty()) {
3100 dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
3101 } else {
3102 dataMgr->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
3103 }
3104 }
3105
HasModuleSavedInPreInstalledDb(const std::string & bundleName,const std::string & bundlePath)3106 bool BMSEventHandler::HasModuleSavedInPreInstalledDb(
3107 const std::string &bundleName, const std::string &bundlePath)
3108 {
3109 auto preInstallIter = loadExistData_.find(bundleName);
3110 if (preInstallIter == loadExistData_.end()) {
3111 LOG_E(BMS_TAG_DEFAULT, "app(%{public}s) does not save in PreInstalledDb", bundleName.c_str());
3112 return false;
3113 }
3114
3115 return preInstallIter->second.HasBundlePath(bundlePath);
3116 }
3117
SavePreInstallException(const std::string & bundleDir)3118 void BMSEventHandler::SavePreInstallException(const std::string &bundleDir)
3119 {
3120 auto preInstallExceptionMgr =
3121 DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
3122 if (preInstallExceptionMgr == nullptr) {
3123 LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
3124 return;
3125 }
3126
3127 preInstallExceptionMgr->SavePreInstallExceptionPath(bundleDir);
3128 }
3129
SavePreInstallExceptionAppService(const std::string & bundleDir)3130 void BMSEventHandler::SavePreInstallExceptionAppService(const std::string &bundleDir)
3131 {
3132 auto preInstallExceptionMgr =
3133 DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
3134 if (preInstallExceptionMgr == nullptr) {
3135 LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
3136 return;
3137 }
3138
3139 preInstallExceptionMgr->SavePreInstallExceptionAppServicePath(bundleDir);
3140 }
3141
DeletePreInstallExceptionAppService(const std::string & bundleDir)3142 void BMSEventHandler::DeletePreInstallExceptionAppService(const std::string &bundleDir)
3143 {
3144 auto preInstallExceptionMgr =
3145 DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
3146 if (preInstallExceptionMgr == nullptr) {
3147 LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
3148 return;
3149 }
3150
3151 preInstallExceptionMgr->DeletePreInstallExceptionAppServicePath(bundleDir);
3152 }
3153
HandlePreInstallException()3154 void BMSEventHandler::HandlePreInstallException()
3155 {
3156 auto preInstallExceptionMgr =
3157 DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
3158 if (preInstallExceptionMgr == nullptr) {
3159 LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
3160 return;
3161 }
3162
3163 std::set<std::string> exceptionPaths;
3164 std::set<std::string> exceptionBundleNames;
3165 std::set<std::string> exceptionAppServicePaths;
3166 std::set<std::string> exceptionAppServiceBundleNames;
3167 if (!preInstallExceptionMgr->GetAllPreInstallExceptionInfo(
3168 exceptionPaths, exceptionBundleNames, exceptionAppServicePaths, exceptionAppServiceBundleNames)) {
3169 LOG_I(BMS_TAG_DEFAULT, "No pre-install exception information found");
3170 return;
3171 }
3172
3173 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "handle exception %{public}zu %{public}zu %{public}zu %{public}zu",
3174 exceptionPaths.size(), exceptionBundleNames.size(),
3175 exceptionAppServicePaths.size(), exceptionAppServiceBundleNames.size());
3176 HandlePreInstallAppServicePathsException(preInstallExceptionMgr, exceptionAppServicePaths);
3177 HandlePreInstallAppPathsException(preInstallExceptionMgr, exceptionPaths);
3178 if (!exceptionBundleNames.empty() || !exceptionAppServiceBundleNames.empty()) {
3179 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "Loading all pre-install bundle infos");
3180 LoadAllPreInstallBundleInfos();
3181 }
3182 HandlePreInstallAppServiceBundleNamesException(preInstallExceptionMgr, exceptionAppServiceBundleNames);
3183 HandlePreInstallBundleNamesException(preInstallExceptionMgr, exceptionBundleNames);
3184
3185 preInstallExceptionMgr->ClearAll();
3186 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "Pre-install exception information cleared successfully");
3187 }
3188
HandlePreInstallAppServicePathsException(std::shared_ptr<PreInstallExceptionMgr> preInstallExceptionMgr,const std::set<std::string> & exceptionAppServicePaths)3189 void BMSEventHandler::HandlePreInstallAppServicePathsException(
3190 std::shared_ptr<PreInstallExceptionMgr> preInstallExceptionMgr,
3191 const std::set<std::string> &exceptionAppServicePaths)
3192 {
3193 if (preInstallExceptionMgr == nullptr) {
3194 LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
3195 return;
3196 }
3197 for (const auto &pathIter : exceptionAppServicePaths) {
3198 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "fwk path:%{public}s", pathIter.c_str());
3199 std::vector<std::string> filePaths { pathIter };
3200 if (OTAInstallSystemHsp(filePaths) != ERR_OK) {
3201 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "ota install fwk path(%{public}s) error", pathIter.c_str());
3202 }
3203
3204 preInstallExceptionMgr->DeletePreInstallExceptionPath(pathIter);
3205 }
3206 }
3207
HandlePreInstallAppPathsException(std::shared_ptr<PreInstallExceptionMgr> preInstallExceptionMgr,const std::set<std::string> & exceptionPaths)3208 void BMSEventHandler::HandlePreInstallAppPathsException(
3209 std::shared_ptr<PreInstallExceptionMgr> preInstallExceptionMgr, const std::set<std::string> &exceptionPaths)
3210 {
3211 if (preInstallExceptionMgr == nullptr) {
3212 LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
3213 return;
3214 }
3215 for (const auto &pathIter : exceptionPaths) {
3216 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "HandlePreInstallException path:%{public}s", pathIter.c_str());
3217 std::vector<std::string> filePaths { pathIter };
3218 bool removable = IsPreInstallRemovable(pathIter);
3219 if (!OTAInstallSystemBundle(filePaths, Constants::AppType::SYSTEM_APP, removable)) {
3220 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "HandlePreInstallException path(%{public}s) error", pathIter.c_str());
3221 }
3222
3223 preInstallExceptionMgr->DeletePreInstallExceptionPath(pathIter);
3224 }
3225 }
3226
HandlePreInstallAppServiceBundleNamesException(std::shared_ptr<PreInstallExceptionMgr> preInstallExceptionMgr,const std::set<std::string> & exceptionAppServiceBundleNames)3227 void BMSEventHandler::HandlePreInstallAppServiceBundleNamesException(
3228 std::shared_ptr<PreInstallExceptionMgr> preInstallExceptionMgr,
3229 const std::set<std::string> &exceptionAppServiceBundleNames)
3230 {
3231 if (preInstallExceptionMgr == nullptr) {
3232 LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
3233 return;
3234 }
3235 for (const auto &bundleNameIter : exceptionAppServiceBundleNames) {
3236 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "handle fwk exception -n: %{public}s", bundleNameIter.c_str());
3237 auto iter = loadExistData_.find(bundleNameIter);
3238 if (iter == loadExistData_.end()) {
3239 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "there is no(%{public}s) in PreInstallDb",
3240 bundleNameIter.c_str());
3241 continue;
3242 }
3243 const auto &preInstallBundleInfo = iter->second;
3244 if (OTAInstallSystemHsp(preInstallBundleInfo.GetBundlePaths()) != ERR_OK) {
3245 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "ota install fwk(%{public}s) error", bundleNameIter.c_str());
3246 }
3247
3248 preInstallExceptionMgr->DeletePreInstallExceptionBundleName(bundleNameIter);
3249 }
3250 }
3251
HandlePreInstallBundleNamesException(std::shared_ptr<PreInstallExceptionMgr> preInstallExceptionMgr,const std::set<std::string> & exceptionBundleNames)3252 void BMSEventHandler::HandlePreInstallBundleNamesException(
3253 std::shared_ptr<PreInstallExceptionMgr> preInstallExceptionMgr, const std::set<std::string> &exceptionBundleNames)
3254 {
3255 if (preInstallExceptionMgr == nullptr) {
3256 LOG_E(BMS_TAG_DEFAULT, "preInstallExceptionMgr is nullptr");
3257 return;
3258 }
3259 for (const auto &bundleNameIter : exceptionBundleNames) {
3260 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "HandlePreInstallException bundleName: %{public}s", bundleNameIter.c_str());
3261 auto iter = loadExistData_.find(bundleNameIter);
3262 if (iter == loadExistData_.end()) {
3263 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "HandlePreInstallException no bundleName(%{public}s) in PreInstallDb",
3264 bundleNameIter.c_str());
3265 continue;
3266 }
3267
3268 const auto &preInstallBundleInfo = iter->second;
3269 if (!OTAInstallSystemBundle(preInstallBundleInfo.GetBundlePaths(),
3270 Constants::AppType::SYSTEM_APP, preInstallBundleInfo.IsRemovable())) {
3271 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "HandlePreInstallException bundleName(%{public}s) error",
3272 bundleNameIter.c_str());
3273 }
3274
3275 preInstallExceptionMgr->DeletePreInstallExceptionBundleName(bundleNameIter);
3276 }
3277 }
3278
OTAInstallSystemBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)3279 bool BMSEventHandler::OTAInstallSystemBundle(
3280 const std::vector<std::string> &filePaths,
3281 Constants::AppType appType,
3282 bool removable)
3283 {
3284 if (filePaths.empty()) {
3285 LOG_E(BMS_TAG_DEFAULT, "File path is empty");
3286 return false;
3287 }
3288
3289 InstallParam installParam;
3290 installParam.isPreInstallApp = true;
3291 installParam.SetKillProcess(false);
3292 installParam.needSendEvent = false;
3293 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
3294 installParam.removable = removable;
3295 installParam.needSavePreInstallInfo = true;
3296 installParam.copyHapToInstallPath = false;
3297 installParam.isOTA = true;
3298 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
3299 SystemBundleInstaller installer;
3300 ErrCode ret = installer.OTAInstallSystemBundle(filePaths, installParam, appType);
3301 if (ret == ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON) {
3302 ret = ERR_OK;
3303 }
3304 return ret == ERR_OK;
3305 }
3306
OTAInstallSystemBundleNeedCheckUser(const std::vector<std::string> & filePaths,const std::string & bundleName,Constants::AppType appType,bool removable)3307 bool BMSEventHandler::OTAInstallSystemBundleNeedCheckUser(
3308 const std::vector<std::string> &filePaths,
3309 const std::string &bundleName,
3310 Constants::AppType appType,
3311 bool removable)
3312 {
3313 if (filePaths.empty()) {
3314 LOG_E(BMS_TAG_DEFAULT, "File path is empty");
3315 return false;
3316 }
3317
3318 InstallParam installParam;
3319 installParam.isPreInstallApp = true;
3320 installParam.SetKillProcess(false);
3321 installParam.needSendEvent = false;
3322 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
3323 installParam.removable = removable;
3324 installParam.needSavePreInstallInfo = true;
3325 installParam.copyHapToInstallPath = false;
3326 installParam.isOTA = true;
3327 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
3328 SystemBundleInstaller installer;
3329 ErrCode ret = installer.OTAInstallSystemBundleNeedCheckUser(filePaths, installParam, bundleName, appType);
3330 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "bundle %{public}s with return code: %{public}d", bundleName.c_str(), ret);
3331 if ((ret != ERR_OK) && (ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON)) {
3332 APP_LOGE("OTA bundle(%{public}s) failed, errCode:%{public}d", bundleName.c_str(), ret);
3333 if (!filePaths.empty()) {
3334 SavePreInstallException(filePaths[0]);
3335 }
3336 return false;
3337 }
3338 return true;
3339 }
3340
OTAInstallSystemBundleTargetUser(const std::vector<std::string> & filePaths,const std::string & bundleName,Constants::AppType appType,bool removable,const std::vector<int32_t> & userIds)3341 bool BMSEventHandler::OTAInstallSystemBundleTargetUser(const std::vector<std::string> &filePaths,
3342 const std::string &bundleName, Constants::AppType appType, bool removable, const std::vector<int32_t> &userIds)
3343 {
3344 if (filePaths.empty()) {
3345 LOG_E(BMS_TAG_DEFAULT, "File path is empty");
3346 return false;
3347 }
3348 if (userIds.empty()) {
3349 LOG_E(BMS_TAG_DEFAULT, "userIds is empty");
3350 return false;
3351 }
3352 InstallParam installParam;
3353 installParam.isPreInstallApp = true;
3354 installParam.SetKillProcess(false);
3355 installParam.needSendEvent = false;
3356 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
3357 installParam.removable = removable;
3358 installParam.needSavePreInstallInfo = true;
3359 installParam.copyHapToInstallPath = false;
3360 installParam.isOTA = true;
3361 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
3362 SystemBundleInstaller installer;
3363 ErrCode ret = installer.OTAInstallSystemBundleTargetUser(filePaths, installParam, bundleName, appType, userIds);
3364 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "bundle %{public}s with return code: %{public}d", bundleName.c_str(), ret);
3365 if ((ret != ERR_OK) && (ret != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON)) {
3366 APP_LOGE("OTA bundle(%{public}s) failed, errCode:%{public}d", bundleName.c_str(), ret);
3367 if (!filePaths.empty()) {
3368 SavePreInstallException(filePaths[0]);
3369 }
3370 return false;
3371 }
3372 return true;
3373 }
3374
OTAInstallSystemSharedBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)3375 bool BMSEventHandler::OTAInstallSystemSharedBundle(
3376 const std::vector<std::string> &filePaths,
3377 Constants::AppType appType,
3378 bool removable)
3379 {
3380 if (filePaths.empty()) {
3381 LOG_E(BMS_TAG_DEFAULT, "File path is empty");
3382 return false;
3383 }
3384
3385 InstallParam installParam;
3386 installParam.isPreInstallApp = true;
3387 installParam.needSendEvent = false;
3388 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
3389 installParam.removable = removable;
3390 installParam.needSavePreInstallInfo = true;
3391 installParam.sharedBundleDirPaths = filePaths;
3392 installParam.isOTA = true;
3393 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_OTA_INSTALLED;
3394 SystemBundleInstaller installer;
3395 return installer.InstallSystemSharedBundle(installParam, true, appType);
3396 }
3397
CheckAndParseHapFiles(const std::string & hapFilePath,bool isPreInstallApp,std::unordered_map<std::string,InnerBundleInfo> & infos)3398 bool BMSEventHandler::CheckAndParseHapFiles(
3399 const std::string &hapFilePath,
3400 bool isPreInstallApp,
3401 std::unordered_map<std::string, InnerBundleInfo> &infos)
3402 {
3403 std::vector<std::string> hapFilePathVec { hapFilePath };
3404 std::vector<std::string> realPaths;
3405 auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
3406 if (ret != ERR_OK) {
3407 LOG_E(BMS_TAG_DEFAULT, "File path %{public}s invalid", hapFilePath.c_str());
3408 return false;
3409 }
3410 return CheckAndParseHapFiles(realPaths, isPreInstallApp, infos);
3411 }
3412
CheckAndParseHapFiles(const std::vector<std::string> & realPaths,bool isPreInstallApp,std::unordered_map<std::string,InnerBundleInfo> & infos)3413 bool BMSEventHandler::CheckAndParseHapFiles(
3414 const std::vector<std::string> &realPaths,
3415 bool isPreInstallApp,
3416 std::unordered_map<std::string, InnerBundleInfo> &infos)
3417 {
3418 std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
3419 std::make_unique<BundleInstallChecker>();
3420
3421 auto ret = bundleInstallChecker->CheckSysCap(realPaths);
3422 if (ret != ERR_OK) {
3423 LOG_I(BMS_TAG_DEFAULT, "hap syscap check failed");
3424 }
3425 bool isSysCapValid = (ret == ERR_OK);
3426
3427 std::vector<Security::Verify::HapVerifyResult> hapVerifyResults;
3428 ret = bundleInstallChecker->CheckMultipleHapsSignInfo(realPaths, hapVerifyResults, true);
3429 if (ret != ERR_OK) {
3430 LOG_E(BMS_TAG_DEFAULT, "CheckMultipleHapsSignInfo failed");
3431 return false;
3432 }
3433
3434 InstallCheckParam checkParam;
3435 checkParam.isPreInstallApp = isPreInstallApp;
3436 if (isPreInstallApp) {
3437 checkParam.appType = Constants::AppType::SYSTEM_APP;
3438 }
3439
3440 if (!LoadPreInstallProFile()) {
3441 LOG_W(BMS_TAG_DEFAULT, "load json failed for restore");
3442 }
3443 ret = bundleInstallChecker->ParseHapFiles(
3444 realPaths, checkParam, hapVerifyResults, infos);
3445 if (ret != ERR_OK) {
3446 LOG_E(BMS_TAG_DEFAULT, "parse haps file failed");
3447 return false;
3448 }
3449
3450 if (!isSysCapValid) {
3451 ret = bundleInstallChecker->CheckDeviceType(infos);
3452 if (ret != ERR_OK) {
3453 LOG_E(BMS_TAG_INSTALLER, "CheckDeviceType failed due to errorCode : %{public}d", ret);
3454 return false;
3455 }
3456 }
3457
3458 ret = bundleInstallChecker->CheckHspInstallCondition(hapVerifyResults);
3459 if (ret != ERR_OK) {
3460 LOG_E(BMS_TAG_DEFAULT, "CheckHspInstallCondition failed %{public}d", ret);
3461 return false;
3462 }
3463
3464 ret = bundleInstallChecker->CheckAppLabelInfo(infos);
3465 if (ret != ERR_OK) {
3466 LOG_E(BMS_TAG_DEFAULT, "Check APP label failed %{public}d", ret);
3467 return false;
3468 }
3469
3470 ret = bundleInstallChecker->CheckMultiNativeFile(infos);
3471 if (ret != ERR_OK) {
3472 LOG_E(BMS_TAG_DEFAULT, "CheckMultiNativeFile failed %{public}d", ret);
3473 return false;
3474 }
3475
3476 // set hapPath
3477 std::for_each(infos.begin(), infos.end(), [](auto &item) {
3478 item.second.SetModuleHapPath(item.first);
3479 });
3480
3481 return true;
3482 }
3483
ParseHapFiles(const std::string & hapFilePath,std::unordered_map<std::string,InnerBundleInfo> & infos)3484 bool BMSEventHandler::ParseHapFiles(
3485 const std::string &hapFilePath,
3486 std::unordered_map<std::string, InnerBundleInfo> &infos)
3487 {
3488 std::vector<std::string> hapFilePathVec { hapFilePath };
3489 std::vector<std::string> realPaths;
3490 auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
3491 if (ret != ERR_OK) {
3492 LOG_E(BMS_TAG_DEFAULT, "File path %{public}s invalid", hapFilePath.c_str());
3493 return false;
3494 }
3495
3496 BundleParser bundleParser;
3497 for (auto realPath : realPaths) {
3498 InnerBundleInfo innerBundleInfo;
3499 ret = bundleParser.Parse(realPath, innerBundleInfo);
3500 if (ret != ERR_OK) {
3501 LOG_E(BMS_TAG_DEFAULT, "Parse bundle info failed, error: %{public}d", ret);
3502 continue;
3503 }
3504
3505 infos.emplace(realPath, innerBundleInfo);
3506 }
3507
3508 if (infos.empty()) {
3509 LOG_E(BMS_TAG_DEFAULT, "Parse hap(%{public}s) empty ", hapFilePath.c_str());
3510 return false;
3511 }
3512
3513 return true;
3514 }
3515
IsPreInstallRemovable(const std::string & path)3516 bool BMSEventHandler::IsPreInstallRemovable(const std::string &path)
3517 {
3518 #ifdef USE_PRE_BUNDLE_PROFILE
3519 if (!HasPreInstallProfile()) {
3520 return false;
3521 }
3522
3523 if (!hasLoadPreInstallProFile_) {
3524 LOG_E(BMS_TAG_DEFAULT, "Not load preInstall proFile or release");
3525 return false;
3526 }
3527
3528 if (path.empty() || installList_.empty()) {
3529 LOG_E(BMS_TAG_DEFAULT, "path or installList is empty");
3530 return false;
3531 }
3532 auto installInfo = std::find_if(installList_.begin(), installList_.end(),
3533 [path](const auto &installInfo) {
3534 return installInfo.bundleDir == path;
3535 });
3536 if (installInfo != installList_.end()) {
3537 return (*installInfo).removable;
3538 }
3539 return true;
3540 #else
3541 return false;
3542 #endif
3543 }
3544
GetPreInstallCapability(PreBundleConfigInfo & preBundleConfigInfo)3545 bool BMSEventHandler::GetPreInstallCapability(PreBundleConfigInfo &preBundleConfigInfo)
3546 {
3547 if (!hasLoadPreInstallProFile_) {
3548 LOG_E(BMS_TAG_DEFAULT, "Not load preInstall proFile or release");
3549 return false;
3550 }
3551
3552 if (preBundleConfigInfo.bundleName.empty() || installListCapabilities_.empty()) {
3553 LOG_E(BMS_TAG_DEFAULT, "BundleName or installListCapabilities is empty");
3554 return false;
3555 }
3556
3557 auto iter = installListCapabilities_.find(preBundleConfigInfo);
3558 if (iter == installListCapabilities_.end()) {
3559 LOG_D(BMS_TAG_DEFAULT, "BundleName(%{public}s) no has preinstall capability",
3560 preBundleConfigInfo.bundleName.c_str());
3561 return false;
3562 }
3563
3564 preBundleConfigInfo = *iter;
3565 return true;
3566 }
3567
CheckExtensionTypeInConfig(const std::string & typeName)3568 bool BMSEventHandler::CheckExtensionTypeInConfig(const std::string &typeName)
3569 {
3570 if (!hasLoadPreInstallProFile_) {
3571 LOG_E(BMS_TAG_DEFAULT, "Not load typeName proFile or release");
3572 return false;
3573 }
3574
3575 if (typeName.empty() || extensiontype_.empty()) {
3576 LOG_E(BMS_TAG_DEFAULT, "TypeName or typeName configuration file is empty");
3577 return false;
3578 }
3579
3580 auto iter = extensiontype_.find(typeName);
3581 if (iter == extensiontype_.end()) {
3582 LOG_E(BMS_TAG_DEFAULT, "ExtensionTypeConfig does not have '(%{public}s)' type",
3583 typeName.c_str());
3584 return false;
3585 }
3586
3587 return true;
3588 }
3589
3590 #ifdef USE_PRE_BUNDLE_PROFILE
UpdateRemovable(const std::string & bundleName,bool removable)3591 void BMSEventHandler::UpdateRemovable(const std::string &bundleName, bool removable)
3592 {
3593 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3594 if (dataMgr == nullptr) {
3595 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3596 return;
3597 }
3598
3599 dataMgr->UpdateRemovable(bundleName, removable);
3600 }
3601
UpdateAllPrivilegeCapability()3602 void BMSEventHandler::UpdateAllPrivilegeCapability()
3603 {
3604 for (const auto &preBundleConfigInfo : installListCapabilities_) {
3605 UpdatePrivilegeCapability(preBundleConfigInfo);
3606 }
3607 }
3608
UpdatePrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)3609 void BMSEventHandler::UpdatePrivilegeCapability(
3610 const PreBundleConfigInfo &preBundleConfigInfo)
3611 {
3612 auto &bundleName = preBundleConfigInfo.bundleName;
3613 InnerBundleInfo innerBundleInfo;
3614 if (!FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
3615 LOG_NOFUNC_W(BMS_TAG_DEFAULT, "App(%{public}s) is not installed", bundleName.c_str());
3616 return;
3617 }
3618 // match both fingerprint and appId
3619 if (!MatchSignature(preBundleConfigInfo, innerBundleInfo.GetCertificateFingerprint()) &&
3620 !MatchSignature(preBundleConfigInfo, innerBundleInfo.GetAppId()) &&
3621 !MatchSignature(preBundleConfigInfo, innerBundleInfo.GetAppIdentifier()) &&
3622 !MatchOldSignatures(preBundleConfigInfo, innerBundleInfo.GetOldAppIds())) {
3623 LOG_E(BMS_TAG_DEFAULT, "bundleName: %{public}s no match pre bundle config info", bundleName.c_str());
3624 return;
3625 }
3626
3627 UpdateTrustedPrivilegeCapability(preBundleConfigInfo);
3628 }
3629
MatchSignature(const PreBundleConfigInfo & configInfo,const std::string & signature)3630 bool BMSEventHandler::MatchSignature(
3631 const PreBundleConfigInfo &configInfo, const std::string &signature)
3632 {
3633 if (configInfo.appSignature.empty() || signature.empty()) {
3634 LOG_W(BMS_TAG_DEFAULT, "appSignature or signature is empty");
3635 return false;
3636 }
3637
3638 return std::find(configInfo.appSignature.begin(),
3639 configInfo.appSignature.end(), signature) != configInfo.appSignature.end();
3640 }
3641
MatchOldSignatures(const PreBundleConfigInfo & configInfo,const std::vector<std::string> & oldSignatures)3642 bool BMSEventHandler::MatchOldSignatures(const PreBundleConfigInfo &configInfo,
3643 const std::vector<std::string> &oldSignatures)
3644 {
3645 if (configInfo.appSignature.empty() || oldSignatures.empty()) {
3646 LOG_W(BMS_TAG_DEFAULT, "appSignature or oldSignatures is empty");
3647 return false;
3648 }
3649 for (const auto &signature : oldSignatures) {
3650 if (std::find(configInfo.appSignature.begin(), configInfo.appSignature.end(), signature) !=
3651 configInfo.appSignature.end()) {
3652 return true;
3653 }
3654 }
3655
3656 return false;
3657 }
3658
UpdateTrustedPrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)3659 void BMSEventHandler::UpdateTrustedPrivilegeCapability(
3660 const PreBundleConfigInfo &preBundleConfigInfo)
3661 {
3662 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3663 if (dataMgr == nullptr) {
3664 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3665 return;
3666 }
3667
3668 ApplicationInfo appInfo;
3669 appInfo.keepAlive = preBundleConfigInfo.keepAlive;
3670 appInfo.singleton = preBundleConfigInfo.singleton;
3671 appInfo.runningResourcesApply = preBundleConfigInfo.runningResourcesApply;
3672 appInfo.associatedWakeUp = preBundleConfigInfo.associatedWakeUp;
3673 appInfo.allowCommonEvent = preBundleConfigInfo.allowCommonEvent;
3674 appInfo.resourcesApply = preBundleConfigInfo.resourcesApply;
3675 appInfo.allowAppRunWhenDeviceFirstLocked = preBundleConfigInfo.allowAppRunWhenDeviceFirstLocked;
3676 appInfo.allowEnableNotification = preBundleConfigInfo.allowEnableNotification;
3677 appInfo.hideDesktopIcon = preBundleConfigInfo.hideDesktopIcon;
3678 appInfo.allowMultiProcess = preBundleConfigInfo.allowMultiProcess;
3679 appInfo.userDataClearable = preBundleConfigInfo.userDataClearable;
3680 appInfo.formVisibleNotify = preBundleConfigInfo.formVisibleNotify;
3681 dataMgr->UpdatePrivilegeCapability(preBundleConfigInfo.bundleName, appInfo);
3682 }
3683 #endif
3684
FetchInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & innerBundleInfo)3685 bool BMSEventHandler::FetchInnerBundleInfo(
3686 const std::string &bundleName, InnerBundleInfo &innerBundleInfo)
3687 {
3688 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3689 if (dataMgr == nullptr) {
3690 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3691 return false;
3692 }
3693
3694 return dataMgr->FetchInnerBundleInfo(bundleName, innerBundleInfo);
3695 }
3696
ListeningUserUnlocked() const3697 void BMSEventHandler::ListeningUserUnlocked() const
3698 {
3699 LOG_I(BMS_TAG_DEFAULT, "BMSEventHandler listen the unlock of someone user start");
3700 EventFwk::MatchingSkills matchingSkills;
3701 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
3702 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
3703 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
3704 subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
3705
3706 auto subscriberPtr = std::make_shared<UserUnlockedEventSubscriber>(subscribeInfo);
3707 if (AccountHelper::IsOsAccountVerified(Constants::START_USERID)) {
3708 LOG_I(BMS_TAG_DEFAULT, "user 100 is unlocked");
3709 OHOS::AAFwk::Want want;
3710 want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
3711 EventFwk::CommonEventData data { want };
3712 data.SetCode(Constants::START_USERID);
3713 subscriberPtr->OnReceiveEvent(data);
3714 }
3715 if (!EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberPtr)) {
3716 LOG_W(BMS_TAG_DEFAULT, "BMSEventHandler subscribe common event %{public}s failed",
3717 EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED.c_str());
3718 }
3719 }
3720
RemoveUnreservedSandbox() const3721 void BMSEventHandler::RemoveUnreservedSandbox() const
3722 {
3723 #if defined (BUNDLE_FRAMEWORK_SANDBOX_APP) && defined (DLP_PERMISSION_ENABLE)
3724 LOG_I(BMS_TAG_DEFAULT, "Start to RemoveUnreservedSandbox");
3725 const int32_t WAIT_TIMES = 40;
3726 const int32_t EACH_TIME = 1000; // 1000ms
3727 auto execFunc = [](int32_t waitTimes, int32_t eachTime) {
3728 int32_t currentUserId = Constants::INVALID_USERID;
3729 while (waitTimes--) {
3730 std::this_thread::sleep_for(std::chrono::milliseconds(eachTime));
3731 LOG_D(BMS_TAG_DEFAULT, "wait for account started");
3732 if (currentUserId == Constants::INVALID_USERID) {
3733 currentUserId = AccountHelper::GetCurrentActiveUserId();
3734 LOG_D(BMS_TAG_DEFAULT, "current active userId is %{public}d", currentUserId);
3735 if (currentUserId == Constants::INVALID_USERID) {
3736 continue;
3737 }
3738 }
3739 LOG_I(BMS_TAG_DEFAULT, "RemoveUnreservedSandbox call ClearUnreservedSandbox");
3740 Security::DlpPermission::DlpPermissionKit::ClearUnreservedSandbox();
3741 break;
3742 }
3743 };
3744 std::thread removeThread(execFunc, WAIT_TIMES, EACH_TIME);
3745 removeThread.detach();
3746 #endif
3747 LOG_I(BMS_TAG_DEFAULT, "RemoveUnreservedSandbox finish");
3748 }
3749
AddStockAppProvisionInfoByOTA(const std::string & bundleName,const std::string & filePath)3750 void BMSEventHandler::AddStockAppProvisionInfoByOTA(const std::string &bundleName, const std::string &filePath)
3751 {
3752 LOG_D(BMS_TAG_DEFAULT, "AddStockAppProvisionInfoByOTA bundleName: %{public}s", bundleName.c_str());
3753 // parse profile info
3754 Security::Verify::HapVerifyResult hapVerifyResult;
3755 auto ret = BundleVerifyMgr::ParseHapProfile(filePath, hapVerifyResult, true);
3756 if (ret != ERR_OK) {
3757 LOG_E(BMS_TAG_DEFAULT, "BundleVerifyMgr::HapVerify failed, bundleName: %{public}s, errCode: %{public}d",
3758 bundleName.c_str(), ret);
3759 return;
3760 }
3761
3762 std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
3763 std::make_unique<BundleInstallChecker>();
3764 AppProvisionInfo appProvisionInfo = bundleInstallChecker->ConvertToAppProvisionInfo(
3765 hapVerifyResult.GetProvisionInfo());
3766 if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->AddAppProvisionInfo(bundleName, appProvisionInfo)) {
3767 LOG_E(BMS_TAG_DEFAULT, "AddAppProvisionInfo failed, bundleName:%{public}s", bundleName.c_str());
3768 }
3769 }
3770
UpdateAppDataSelinuxLabel(const std::string & bundleName,const std::string & apl,bool isPreInstall,bool debug)3771 void BMSEventHandler::UpdateAppDataSelinuxLabel(const std::string &bundleName, const std::string &apl,
3772 bool isPreInstall, bool debug)
3773 {
3774 LOG_D(BMS_TAG_DEFAULT, "UpdateAppDataSelinuxLabel bundleName: %{public}s start", bundleName.c_str());
3775 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3776 if (dataMgr == nullptr) {
3777 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3778 return;
3779 }
3780 std::set<int32_t> userIds = dataMgr->GetAllUser();
3781 for (const auto &userId : userIds) {
3782 for (const auto &el : ServiceConstants::BUNDLE_EL) {
3783 std::string baseBundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR +
3784 el +
3785 ServiceConstants::PATH_SEPARATOR +
3786 std::to_string(userId);
3787 std::string baseDataDir = baseBundleDataDir + ServiceConstants::BASE + bundleName;
3788 bool isExist = true;
3789 ErrCode result = InstalldClient::GetInstance()->IsExistDir(baseDataDir, isExist);
3790 if (result != ERR_OK) {
3791 LOG_E(BMS_TAG_DEFAULT, "IsExistDir failed, error is %{public}d", result);
3792 continue;
3793 }
3794 if (!isExist) {
3795 // Update only accessible directories when OTA,
3796 // and other directories need to be set after the device is unlocked.
3797 // Can see UserUnlockedEventSubscriber::UpdateAppDataDirSelinuxLabel
3798 continue;
3799 }
3800 result = InstalldClient::GetInstance()->SetDirApl(baseDataDir, bundleName, apl, isPreInstall, debug);
3801 if (result != ERR_OK) {
3802 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s, fail to SetDirApl baseDataDir dir, error is %{public}d",
3803 bundleName.c_str(), result);
3804 }
3805 std::string databaseDataDir = baseBundleDataDir + ServiceConstants::DATABASE + bundleName;
3806 result = InstalldClient::GetInstance()->SetDirApl(databaseDataDir, bundleName, apl, isPreInstall, debug);
3807 if (result != ERR_OK) {
3808 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s, fail to SetDirApl databaseDir dir, error is %{public}d",
3809 bundleName.c_str(), result);
3810 }
3811 }
3812 }
3813 LOG_D(BMS_TAG_DEFAULT, "UpdateAppDataSelinuxLabel bundleName: %{public}s end", bundleName.c_str());
3814 }
3815
HandleSceneBoard() const3816 void BMSEventHandler::HandleSceneBoard() const
3817 {
3818 #ifdef WINDOW_ENABLE
3819 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3820 if (dataMgr == nullptr) {
3821 LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
3822 return;
3823 }
3824 bool sceneBoardEnable = Rosen::SceneBoardJudgement::IsSceneBoardEnabled();
3825 LOG_I(BMS_TAG_DEFAULT, "HandleSceneBoard sceneBoardEnable : %{public}d", sceneBoardEnable);
3826 dataMgr->SetApplicationEnabled(ServiceConstants::SYSTEM_UI_BUNDLE_NAME, 0, !sceneBoardEnable,
3827 ServiceConstants::CALLER_NAME_BMS, Constants::DEFAULT_USERID);
3828 std::set<int32_t> userIds = dataMgr->GetAllUser();
3829 std::for_each(userIds.cbegin(), userIds.cend(), [dataMgr, sceneBoardEnable](const int32_t userId) {
3830 if (userId == 0) {
3831 return;
3832 }
3833 dataMgr->SetApplicationEnabled(Constants::SCENE_BOARD_BUNDLE_NAME, 0, sceneBoardEnable,
3834 ServiceConstants::CALLER_NAME_BMS, userId);
3835 dataMgr->SetApplicationEnabled(ServiceConstants::LAUNCHER_BUNDLE_NAME, 0, !sceneBoardEnable,
3836 ServiceConstants::CALLER_NAME_BMS, userId);
3837 });
3838 #endif
3839 }
3840
InnerProcessStockBundleProvisionInfo()3841 void BMSEventHandler::InnerProcessStockBundleProvisionInfo()
3842 {
3843 LOG_D(BMS_TAG_DEFAULT, "InnerProcessStockBundleProvisionInfo start");
3844 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3845 if (dataMgr == nullptr) {
3846 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3847 return;
3848 }
3849 std::unordered_set<std::string> allBundleNames;
3850 if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->GetAllAppProvisionInfoBundleName(allBundleNames)) {
3851 LOG_W(BMS_TAG_DEFAULT, "GetAllAppProvisionInfoBundleName failed");
3852 }
3853 // get all installed bundleName
3854 std::vector<std::string> installedBundleNames = dataMgr->GetAllBundleName();
3855 //check diss missed
3856 for (const auto &bundleName : installedBundleNames) {
3857 if (allBundleNames.find(bundleName) == allBundleNames.end()) {
3858 InnerBundleInfo innerBundleInfo;
3859 if (!dataMgr->FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
3860 LOG_W(BMS_TAG_DEFAULT, "fetch failed -n %{public}s", bundleName.c_str());
3861 continue;
3862 }
3863 auto moduleMap = innerBundleInfo.GetInnerModuleInfos();
3864 if (!moduleMap.empty()) {
3865 AddStockAppProvisionInfoByOTA(bundleName, moduleMap.begin()->second.hapPath);
3866 }
3867 }
3868 }
3869 LOG_D(BMS_TAG_DEFAULT, "InnerProcessStockBundleProvisionInfo end");
3870 }
3871
InnerProcessStockBundleRouterInfo()3872 void BMSEventHandler::InnerProcessStockBundleRouterInfo()
3873 {
3874 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3875 if (dataMgr == nullptr) {
3876 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3877 return;
3878 }
3879 std::set<std::string> bundleNames;
3880 dataMgr->GetAllBundleNames(bundleNames);
3881 std::vector<BundleInfo> bundleInfos;
3882 auto baseFlag = static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
3883 static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE);
3884 if (dataMgr->GetBundleInfosV9(baseFlag, bundleInfos, Constants::ALL_USERID) != ERR_OK) {
3885 LOG_E(BMS_TAG_DEFAULT, "GetBundleInfos failed");
3886 return;
3887 }
3888 for (const auto &bundleInfo : bundleInfos) {
3889 bool hasRouter = false;
3890 for (const HapModuleInfo &hapModuleInfo : bundleInfo.hapModuleInfos) {
3891 if (!hapModuleInfo.routerMap.empty()) {
3892 hasRouter = true;
3893 break;
3894 }
3895 }
3896 if (hasRouter && (bundleNames.find(bundleInfo.name) == bundleNames.end())) {
3897 dataMgr->UpdateRouterInfo(bundleInfo.name);
3898 }
3899 }
3900 }
3901
ProcessRebootQuickFixBundleInstall(const std::string & path,bool isOta)3902 void BMSEventHandler::ProcessRebootQuickFixBundleInstall(const std::string &path, bool isOta)
3903 {
3904 LOG_I(BMS_TAG_DEFAULT, "start, isOta:%{public}d", isOta);
3905 std::string systemHspPath = path + ServiceConstants::PATH_SEPARATOR + MODULE_UPDATE_APP_SERVICE_DIR;
3906 std::string systemBundlePath = path + SYSTEM_BUNDLE_PATH;
3907 PatchSystemHspInstall(systemHspPath, isOta);
3908 PatchSystemBundleInstall(systemBundlePath, isOta);
3909 LOG_I(BMS_TAG_DEFAULT, "end");
3910 }
3911
PatchSystemHspInstall(const std::string & path,bool isOta)3912 void BMSEventHandler::PatchSystemHspInstall(const std::string &path, bool isOta)
3913 {
3914 LOG_I(BMS_TAG_DEFAULT, "start");
3915 std::list<std::string> bundleDirs;
3916 ProcessScanDir(path, bundleDirs);
3917 if (bundleDirs.empty()) {
3918 LOG_I(BMS_TAG_DEFAULT, "end, bundleDirs is empty");
3919 return;
3920 }
3921 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3922 if (dataMgr == nullptr) {
3923 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3924 return;
3925 }
3926 for (auto &scanPathIter : bundleDirs) {
3927 std::unordered_map<std::string, InnerBundleInfo> infos;
3928 if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
3929 LOG_E(BMS_TAG_DEFAULT, "ParseHapFiles failed : %{public}s ", scanPathIter.c_str());
3930 continue;
3931 }
3932 auto bundleName = infos.begin()->second.GetBundleName();
3933 auto versionCode = infos.begin()->second.GetVersionCode();
3934 InnerBundleInfo hasInstalledInfo;
3935 auto hasBundleInstalled = dataMgr->FetchInnerBundleInfo(bundleName, hasInstalledInfo);
3936 if (!hasBundleInstalled) {
3937 LOG_W(BMS_TAG_DEFAULT, "bundleName %{public}s not exist", bundleName.c_str());
3938 continue;
3939 }
3940 if ((versionCode <= hasInstalledInfo.GetVersionCode()) && IsHspPathExist(hasInstalledInfo)) {
3941 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s downgrade",
3942 bundleName.c_str());
3943 continue;
3944 }
3945 InstallParam installParam;
3946 installParam.SetKillProcess(false);
3947 installParam.removable = false;
3948 installParam.needSendEvent = false;
3949 installParam.copyHapToInstallPath = true;
3950 installParam.needSavePreInstallInfo = false;
3951 installParam.isOTA = isOta;
3952 installParam.isPatch = true;
3953 AppServiceFwkInstaller installer;
3954 std::vector<std::string> filePaths { scanPathIter };
3955 if (installer.Install(filePaths, installParam) != ERR_OK) {
3956 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s: install failed", bundleName.c_str());
3957 }
3958 }
3959 LOG_I(BMS_TAG_DEFAULT, "end");
3960 }
3961
PatchSystemBundleInstall(const std::string & path,bool isOta)3962 void BMSEventHandler::PatchSystemBundleInstall(const std::string &path, bool isOta)
3963 {
3964 LOG_I(BMS_TAG_DEFAULT, "start");
3965 std::list<std::string> bundleDirs;
3966 ProcessScanDir(path, bundleDirs);
3967 if (bundleDirs.empty()) {
3968 LOG_I(BMS_TAG_DEFAULT, "end, bundleDirs is empty");
3969 return;
3970 }
3971 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3972 if (dataMgr == nullptr) {
3973 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
3974 return;
3975 }
3976 for (auto &scanPathIter : bundleDirs) {
3977 std::unordered_map<std::string, InnerBundleInfo> infos;
3978 if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
3979 LOG_E(BMS_TAG_DEFAULT, "ParseHapFiles failed : %{public}s ", scanPathIter.c_str());
3980 continue;
3981 }
3982 auto bundleName = infos.begin()->second.GetBundleName();
3983 auto hapVersionCode = infos.begin()->second.GetVersionCode();
3984 BundleInfo hasInstalledInfo;
3985 auto hasBundleInstalled = dataMgr->GetBundleInfo(
3986 bundleName, static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
3987 hasInstalledInfo, Constants::ANY_USERID);
3988 if (!hasBundleInstalled) {
3989 LOG_W(BMS_TAG_DEFAULT, "obtain bundleInfo failed, bundleName :%{public}s not exist", bundleName.c_str());
3990 continue;
3991 }
3992 if ((hapVersionCode <= hasInstalledInfo.versionCode) && IsHapPathExist(hasInstalledInfo)) {
3993 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s: hapVersionCode is less than old hap versionCode",
3994 bundleName.c_str());
3995 continue;
3996 }
3997 InstallParam installParam;
3998 installParam.SetKillProcess(false);
3999 installParam.needSendEvent = false;
4000 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
4001 installParam.copyHapToInstallPath = true;
4002 installParam.isOTA = isOta;
4003 installParam.withCopyHaps = true;
4004 installParam.isPatch = true;
4005 SystemBundleInstaller installer;
4006 std::vector<std::string> filePaths { scanPathIter };
4007 if (installer.OTAInstallSystemBundleNeedCheckUser(
4008 filePaths, installParam, bundleName, Constants::AppType::SYSTEM_APP) != ERR_OK) {
4009 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s: install failed", bundleName.c_str());
4010 }
4011 }
4012 LOG_I(BMS_TAG_DEFAULT, "end");
4013 }
4014
IsHapPathExist(const BundleInfo & bundleInfo)4015 bool BMSEventHandler::IsHapPathExist(const BundleInfo &bundleInfo)
4016 {
4017 LOG_I(BMS_TAG_DEFAULT, "-n %{public}s need to check hap path exist", bundleInfo.name.c_str());
4018 if (bundleInfo.hapModuleInfos.empty()) {
4019 LOG_E(BMS_TAG_DEFAULT, "-n %{public}s has no moduleInfo", bundleInfo.name.c_str());
4020 return false;
4021 }
4022 for (const auto &moduleInfo : bundleInfo.hapModuleInfos) {
4023 if ((moduleInfo.hapPath.find(Constants::BUNDLE_CODE_DIR) == 0) &&
4024 !BundleUtil::IsExistFile(moduleInfo.hapPath)) {
4025 LOG_E(BMS_TAG_DEFAULT, "-p %{public}s hap path not exist", moduleInfo.hapPath.c_str());
4026 return false;
4027 }
4028 }
4029 return true;
4030 }
4031
IsHspPathExist(const InnerBundleInfo & innerBundleInfo)4032 bool BMSEventHandler::IsHspPathExist(const InnerBundleInfo &innerBundleInfo)
4033 {
4034 LOG_I(BMS_TAG_DEFAULT, "-n %{public}s need to check hsp path exist", innerBundleInfo.GetBundleName().c_str());
4035 if (innerBundleInfo.GetInnerModuleInfos().empty()) {
4036 LOG_E(BMS_TAG_DEFAULT, "-n %{public}s has no moduleInfo", innerBundleInfo.GetBundleName().c_str());
4037 return false;
4038 }
4039 for (const auto &moduleInfoIter : innerBundleInfo.GetInnerModuleInfos()) {
4040 if ((moduleInfoIter.second.hapPath.find(Constants::BUNDLE_CODE_DIR) == 0) &&
4041 !BundleUtil::IsExistFile(moduleInfoIter.second.hapPath)) {
4042 LOG_E(BMS_TAG_DEFAULT, "-p %{public}s hsp path not exist", moduleInfoIter.second.hapPath.c_str());
4043 return false;
4044 }
4045 }
4046 return true;
4047 }
4048
CheckALLResourceInfo()4049 void BMSEventHandler::CheckALLResourceInfo()
4050 {
4051 LOG_I(BMS_TAG_DEFAULT, "start");
4052 std::thread ProcessBundleResourceThread(ProcessBundleResourceInfo);
4053 ProcessBundleResourceThread.detach();
4054 }
4055
ProcessBundleResourceInfo()4056 void BMSEventHandler::ProcessBundleResourceInfo()
4057 {
4058 LOG_I(BMS_TAG_DEFAULT, "ProcessBundleResourceInfo start");
4059 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4060 if (dataMgr == nullptr) {
4061 LOG_E(BMS_TAG_DEFAULT, "dataMgr is nullptr");
4062 return;
4063 }
4064 std::vector<std::string> bundleNames = dataMgr->GetAllBundleName();
4065 if (bundleNames.empty()) {
4066 LOG_E(BMS_TAG_DEFAULT, "bundleNames is empty");
4067 return;
4068 }
4069 std::vector<std::string> resourceNames;
4070 BundleResourceHelper::GetAllBundleResourceName(resourceNames);
4071
4072 std::set<std::string> needAddResourceBundles;
4073 for (const auto &bundleName : bundleNames) {
4074 if (std::find(resourceNames.begin(), resourceNames.end(), bundleName) == resourceNames.end()) {
4075 needAddResourceBundles.insert(bundleName);
4076 }
4077 }
4078 if (needAddResourceBundles.empty()) {
4079 LOG_I(BMS_TAG_DEFAULT, "needAddResourceBundles is empty, no need to add resource");
4080 return;
4081 }
4082
4083 for (const auto &bundleName : needAddResourceBundles) {
4084 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "-n %{public}s add resource when reboot", bundleName.c_str());
4085 BundleResourceHelper::AddResourceInfoByBundleName(bundleName, Constants::START_USERID);
4086 }
4087 LOG_I(BMS_TAG_DEFAULT, "ProcessBundleResourceInfo end");
4088 }
4089
ProcessAllBundleDataGroupInfo()4090 void BMSEventHandler::ProcessAllBundleDataGroupInfo()
4091 {
4092 LOG_I(BMS_TAG_DEFAULT, "start");
4093 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4094 if (dataMgr == nullptr) {
4095 LOG_E(BMS_TAG_DEFAULT, "dataMgr is nullptr");
4096 return;
4097 }
4098 dataMgr->ScanAllBundleGroupInfo();
4099 LOG_I(BMS_TAG_DEFAULT, "end");
4100 }
4101
SendBundleUpdateFailedEvent(const BundleInfo & bundleInfo)4102 void BMSEventHandler::SendBundleUpdateFailedEvent(const BundleInfo &bundleInfo)
4103 {
4104 LOG_I(BMS_TAG_DEFAULT, "SendBundleUpdateFailedEvent start, bundleName:%{public}s", bundleInfo.name.c_str());
4105 EventInfo eventInfo;
4106 eventInfo.userId = Constants::ANY_USERID;
4107 eventInfo.bundleName = bundleInfo.name;
4108 eventInfo.versionCode = bundleInfo.versionCode;
4109 eventInfo.errCode = ERR_APPEXECFWK_OTA_INSTALL_VERSION_DOWNGRADE;
4110 eventInfo.isPreInstallApp = bundleInfo.isPreInstallApp;
4111 EventReport::SendBundleSystemEvent(BundleEventType::UPDATE, eventInfo);
4112 }
4113
UpdatePreinstallDB(const std::unordered_map<std::string,std::pair<std::string,bool>> & needInstallMap)4114 void BMSEventHandler::UpdatePreinstallDB(
4115 const std::unordered_map<std::string, std::pair<std::string, bool>> &needInstallMap)
4116 {
4117 for (const auto &existInfo : loadExistData_) {
4118 std::string bundleName = existInfo.first;
4119 auto it = needInstallMap.find(bundleName);
4120 if (it != needInstallMap.end()) {
4121 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "%{public}s installed already update", bundleName.c_str());
4122 continue;
4123 }
4124 auto hapParseInfoMapIter = hapParseInfoMap_.find(bundleName);
4125 if (hapParseInfoMapIter == hapParseInfoMap_.end()) {
4126 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "%{public}s not preinstalled", bundleName.c_str());
4127 continue;
4128 }
4129 UpdatePreinstallDBForNotUpdatedBundle(bundleName, hapParseInfoMapIter->second);
4130 }
4131 }
4132
UpdatePreinstallDBForNotUpdatedBundle(const std::string & bundleName,const std::unordered_map<std::string,InnerBundleInfo> & innerBundleInfos)4133 void BMSEventHandler::UpdatePreinstallDBForNotUpdatedBundle(const std::string &bundleName,
4134 const std::unordered_map<std::string, InnerBundleInfo> &innerBundleInfos)
4135 {
4136 if (innerBundleInfos.empty()) {
4137 LOG_W(BMS_TAG_DEFAULT, "innerBundleInfos is empty");
4138 return;
4139 }
4140 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4141 if (dataMgr == nullptr) {
4142 LOG_W(BMS_TAG_DEFAULT, "dataMgr is nullptr");
4143 return;
4144 }
4145 PreInstallBundleInfo preInstallBundleInfo;
4146 if (!dataMgr->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
4147 LOG_W(BMS_TAG_DEFAULT, "get preinstalled bundle info failed :%{public}s", bundleName.c_str());
4148 return;
4149 }
4150 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "begin update preinstall DB for %{public}s", bundleName.c_str());
4151 preInstallBundleInfo.ClearBundlePath();
4152 bool findEntry = false;
4153 for (const auto &item : innerBundleInfos) {
4154 preInstallBundleInfo.AddBundlePath(item.first);
4155 if (!findEntry) {
4156 auto applicationInfo = item.second.GetBaseApplicationInfo();
4157 item.second.AdaptMainLauncherResourceInfo(applicationInfo);
4158 preInstallBundleInfo.SetLabelId(applicationInfo.labelResource.id);
4159 preInstallBundleInfo.SetIconId(applicationInfo.iconResource.id);
4160 preInstallBundleInfo.SetModuleName(applicationInfo.labelResource.moduleName);
4161 }
4162 auto innerModuleInfos = item.second.GetInnerModuleInfos();
4163 if (!innerModuleInfos.empty() &&
4164 innerModuleInfos.begin()->second.distro.moduleType == Profile::MODULE_TYPE_ENTRY) {
4165 findEntry = true;
4166 }
4167 }
4168 if (!dataMgr->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
4169 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "update preinstall DB fail -n %{public}s", bundleName.c_str());
4170 }
4171 }
4172
IsQuickfixPatchApp(const std::string & bundleName,uint32_t versionCode)4173 bool BMSEventHandler::IsQuickfixPatchApp(const std::string &bundleName, uint32_t versionCode)
4174 {
4175 // 1. check whether a patch has been installed on the app
4176 InnerPatchInfo innerPatchInfo;
4177 if (!PatchDataMgr::GetInstance().GetInnerPatchInfo(bundleName, innerPatchInfo)) {
4178 LOG_W(BMS_TAG_DEFAULT, "the app is not patch, bundleName: %{public}s", bundleName.c_str());
4179 return false;
4180 }
4181 // 2. check appType, current only Internal app types can be uninstall
4182 if (innerPatchInfo.GetAppPatchType() != AppPatchType::INTERNAL) {
4183 LOG_W(BMS_TAG_DEFAULT, "bundleName: %{public}s, app patch type err", bundleName.c_str());
4184 return false;
4185 }
4186 // 3. check version
4187 if (innerPatchInfo.GetVersionCode() != versionCode) {
4188 LOG_W(BMS_TAG_DEFAULT,
4189 "bundleName: %{public}s is not patch app, patchVersionCode: %{public}u, versionCode: %{public}u",
4190 bundleName.c_str(), innerPatchInfo.GetVersionCode(), versionCode);
4191 return false;
4192 }
4193 LOG_I(BMS_TAG_DEFAULT, "bundleName: %{public}s is patch app", bundleName.c_str());
4194 return true;
4195 }
4196
GetValueFromJson(nlohmann::json & jsonObject)4197 bool BMSEventHandler::GetValueFromJson(nlohmann::json &jsonObject)
4198 {
4199 const auto &jsonObjectEnd = jsonObject.end();
4200 int32_t parseResult = ERR_OK;
4201 GetValueIfFindKey<std::vector<std::string>>(jsonObject,
4202 jsonObjectEnd,
4203 RESTOR_BUNDLE_NAME_LIST,
4204 bundleNameList_,
4205 JsonType::ARRAY,
4206 false,
4207 parseResult,
4208 ArrayType::STRING);
4209 if (parseResult != ERR_OK) {
4210 LOG_E(BMS_TAG_DEFAULT, "read bundleNameList from json file error, error code : %{public}d", parseResult);
4211 return false;
4212 }
4213 return true;
4214 }
4215
ProcessRebootQuickFixUnInstallAndRecover(const std::string & path)4216 void BMSEventHandler::ProcessRebootQuickFixUnInstallAndRecover(const std::string &path)
4217 {
4218 LOG_I(BMS_TAG_DEFAULT, "ProcessRebootQuickFixUnInstallAndRecover start");
4219 if (!BundleUtil::IsExistFile(QUICK_FIX_APP_RECOVER_FILE)) {
4220 LOG_E(BMS_TAG_DEFAULT, "end, reinstall json file is empty");
4221 return;
4222 }
4223 auto installer = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
4224 if (installer == nullptr) {
4225 LOG_E(BMS_TAG_DEFAULT, "installer is nullptr");
4226 return;
4227 }
4228 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4229 if (dataMgr == nullptr) {
4230 LOG_E(BMS_TAG_DEFAULT, "dataMgr is nullptr");
4231 return;
4232 }
4233 sptr<InnerReceiverImpl> innerReceiverImpl(new (std::nothrow) InnerReceiverImpl());
4234 if (innerReceiverImpl == nullptr) {
4235 LOG_E(BMS_TAG_DEFAULT, "innerReceiverImpl is nullptr");
4236 return;
4237 }
4238 nlohmann::json jsonObject;
4239 if (!BundleParser::ReadFileIntoJson(QUICK_FIX_APP_RECOVER_FILE, jsonObject) || !jsonObject.is_object() ||
4240 !GetValueFromJson(jsonObject)) {
4241 LOG_E(BMS_TAG_DEFAULT, "get jsonObject from path failed or get value failed");
4242 return;
4243 }
4244 for (const std::string &bundleName : bundleNameList_) {
4245 BundleInfo hasInstalledInfo;
4246 auto hasBundleInstalled = dataMgr->GetBundleInfo(bundleName,
4247 static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
4248 hasInstalledInfo, Constants::ANY_USERID);
4249 if (!hasBundleInstalled) {
4250 LOG_W(BMS_TAG_DEFAULT, "obtain bundleInfo failed, bundleName :%{public}s not exist", bundleName.c_str());
4251 continue;
4252 }
4253 if (IsQuickfixPatchApp(hasInstalledInfo.name, hasInstalledInfo.versionCode)) {
4254 // If metadata name has quickfix flag, it should be uninstall and recover.
4255 InstallParam installParam;
4256 installParam.SetIsUninstallAndRecover(true);
4257 installParam.SetKillProcess(false);
4258 installParam.needSendEvent = false;
4259 installParam.isKeepData = true;
4260 installer->UninstallAndRecover(bundleName, installParam, innerReceiverImpl);
4261 }
4262 }
4263 LOG_I(BMS_TAG_DEFAULT, "ProcessRebootQuickFixUnInstallAndRecover end");
4264 }
4265
InnerProcessRebootUninstallWrongBundle()4266 void BMSEventHandler::InnerProcessRebootUninstallWrongBundle()
4267 {
4268 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4269 if (dataMgr == nullptr) {
4270 LOG_E(BMS_TAG_DEFAULT, "dataMgr is null");
4271 return;
4272 }
4273 for (const auto &bundleName : ServiceConstants::SINGLETON_WHITE_LIST) {
4274 InnerBundleInfo bundleInfo;
4275 if (!dataMgr->FetchInnerBundleInfo(bundleName, bundleInfo)) {
4276 LOG_W(BMS_TAG_DEFAULT, "-n %{public}s is not exist", bundleName.c_str());
4277 continue;
4278 }
4279 InnerCheckSingletonBundleUserInfo(bundleInfo);
4280 }
4281 }
4282
InnerCheckSingletonBundleUserInfo(const InnerBundleInfo & bundleInfo)4283 bool BMSEventHandler::InnerCheckSingletonBundleUserInfo(const InnerBundleInfo &bundleInfo)
4284 {
4285 const auto bundleUserInfos = bundleInfo.GetInnerBundleUserInfos();
4286 if (bundleUserInfos.size() <= 1) {
4287 return true;
4288 }
4289 std::set<int32_t> userIds;
4290 for (const auto &item : bundleUserInfos) {
4291 userIds.insert(item.second.bundleUserInfo.userId);
4292 }
4293 if (userIds.find(Constants::DEFAULT_USERID) == userIds.end()) {
4294 return true;
4295 }
4296 const std::string bundleName = bundleInfo.GetBundleName();
4297 LOG_I(BMS_TAG_DEFAULT, "-n %{public}s is exist different user info", bundleName.c_str());
4298 InstallParam installParam;
4299 installParam.userId = Constants::DEFAULT_USERID;
4300 installParam.SetKillProcess(false);
4301 installParam.needSendEvent = false;
4302 if (!bundleInfo.IsSingleton()) {
4303 LOG_I(BMS_TAG_DEFAULT, "-n %{public}s delete 0 userInfo", bundleName.c_str());
4304 SystemBundleInstaller installer;
4305 if (!installer.UninstallSystemBundle(bundleName, installParam)) {
4306 LOG_W(BMS_TAG_DEFAULT, "OTA uninstall bundle %{public}s userId %{public}d error", bundleName.c_str(),
4307 installParam.userId);
4308 return false;
4309 }
4310 return true;
4311 }
4312 for (const auto &userId : userIds) {
4313 if (userId == Constants::DEFAULT_USERID) {
4314 continue;
4315 }
4316 LOG_I(BMS_TAG_DEFAULT, "-n %{public}s delete %{public}d userInfo", bundleName.c_str(), userId);
4317 installParam.userId = userId;
4318 SystemBundleInstaller installer;
4319 if (!installer.UninstallSystemBundle(bundleName, installParam)) {
4320 LOG_W(BMS_TAG_DEFAULT, "OTA uninstall bundle %{public}s userId %{public}d error", bundleName.c_str(),
4321 installParam.userId);
4322 return false;
4323 }
4324 }
4325 return true;
4326 }
4327
ProcessCheckAppEl1Dir()4328 void BMSEventHandler::ProcessCheckAppEl1Dir()
4329 {
4330 LOG_I(BMS_TAG_DEFAULT, "start");
4331 std::thread thread(ProcessCheckAppEl1DirTask);
4332 thread.detach();
4333 }
4334
ProcessCheckAppEl1DirTask()4335 void BMSEventHandler::ProcessCheckAppEl1DirTask()
4336 {
4337 LOG_I(BMS_TAG_DEFAULT, "begin");
4338 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4339 if (dataMgr == nullptr) {
4340 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
4341 return;
4342 }
4343
4344 std::set<int32_t> userIds = dataMgr->GetAllUser();
4345 for (const auto &userId : userIds) {
4346 std::vector<BundleInfo> bundleInfos;
4347 if (!dataMgr->GetBundleInfos(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
4348 bundleInfos, userId)) {
4349 LOG_W(BMS_TAG_DEFAULT, "GetBundleInfos failed");
4350 continue;
4351 }
4352
4353 UpdateAppDataMgr::ProcessUpdateAppDataDir(userId, bundleInfos, ServiceConstants::DIR_EL1);
4354 }
4355 LOG_I(BMS_TAG_DEFAULT, "end");
4356 }
4357
CheckAndCreateShareFilesSubDataDirs()4358 void BMSEventHandler::CheckAndCreateShareFilesSubDataDirs()
4359 {
4360 LOG_D(BMS_TAG_DEFAULT, "begin");
4361 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4362 if (dataMgr == nullptr) {
4363 LOG_W(BMS_TAG_DEFAULT, "DataMgr is nullptr");
4364 return;
4365 }
4366
4367 std::set<int32_t> userIds = dataMgr->GetAllUser();
4368 for (const auto &userId : userIds) {
4369 std::vector<BundleInfo> bundleInfos;
4370 if (dataMgr->GetBundleInfosV9(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE),
4371 bundleInfos, userId) != ERR_OK) {
4372 LOG_W(BMS_TAG_DEFAULT, "failed to GetBundleInfos for: [%{public}d]",
4373 userId);
4374 continue;
4375 }
4376 std::string shareFilesDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1] +
4377 ServiceConstants::PATH_SEPARATOR + std::to_string(userId) + ServiceConstants::SHAREFILES;
4378 bool isExist = true;
4379 ErrCode result = InstalldClient::GetInstance()->IsExistDir(shareFilesDir, isExist);
4380 if (result != ERR_OK || !isExist) {
4381 LOG_W(BMS_TAG_DEFAULT, "sharefile dir no exist: %{public}s",
4382 shareFilesDir.c_str());
4383 continue;
4384 }
4385 UpdateAppDataMgr::CreateSharefilesSubDataDirs(bundleInfos, userId);
4386 }
4387 LOG_D(BMS_TAG_DEFAULT, "end");
4388 }
4389
CleanAllBundleShaderCache() const4390 void BMSEventHandler::CleanAllBundleShaderCache() const
4391 {
4392 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4393 if (dataMgr == nullptr) {
4394 LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
4395 return;
4396 }
4397 std::vector<BundleInfo> bundleInfos;
4398 ErrCode res = dataMgr->GetBundleInfosV9(
4399 static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE), bundleInfos, Constants::ALL_USERID);
4400 if (res != ERR_OK) {
4401 LOG_E(BMS_TAG_DEFAULT, "GetAllBundleInfos failed");
4402 return;
4403 }
4404 for (const auto &bundleInfo : bundleInfos) {
4405 if (bundleInfo.name.empty()) {
4406 continue;
4407 }
4408 std::string shaderCachePath;
4409 shaderCachePath.append(ServiceConstants::SHADER_CACHE_PATH).append(bundleInfo.name);
4410 ErrCode res = InstalldClient::GetInstance()->CleanBundleDataDir(shaderCachePath);
4411 if (res != ERR_OK) {
4412 LOG_NOFUNC_I(BMS_TAG_DEFAULT, "%{public}s clean shader fail %{public}d", bundleInfo.name.c_str(), res);
4413 }
4414 }
4415 }
4416
InnerProcessUninstallForExistPreBundle(const BundleInfo & installedInfo)4417 bool BMSEventHandler::InnerProcessUninstallForExistPreBundle(const BundleInfo &installedInfo)
4418 {
4419 if (installedInfo.hapModuleInfos.empty()) {
4420 LOG_W(BMS_TAG_DEFAULT, "app(%{public}s) moduleInfos empty", installedInfo.name.c_str());
4421 return false;
4422 }
4423 bool isUpdated = std::all_of(installedInfo.hapModuleInfos.begin(), installedInfo.hapModuleInfos.end(),
4424 [] (const HapModuleInfo &moduleInfo) {
4425 return moduleInfo.hapPath.find(Constants::BUNDLE_CODE_DIR) == 0;
4426 });
4427 if (isUpdated) {
4428 LOG_I(BMS_TAG_DEFAULT, "no need to uninstall app(%{public}s) due to update", installedInfo.name.c_str());
4429 std::string moduleName;
4430 DeletePreInfoInDb(installedInfo.name, moduleName, true);
4431 if (installedInfo.isPreInstallApp) {
4432 // need update isPreInstallApp false
4433 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4434 if (dataMgr == nullptr) {
4435 LOG_W(BMS_TAG_DEFAULT, "DataMgr is nullptr, -n %{public}s need change isPreInstallApp",
4436 installedInfo.name.c_str());
4437 return isUpdated;
4438 }
4439 dataMgr->UpdateIsPreInstallApp(installedInfo.name, false);
4440 }
4441 }
4442 return isUpdated;
4443 }
4444
ProcessAppTmpPath()4445 void BMSEventHandler::ProcessAppTmpPath()
4446 {
4447 if (!BundleUtil::IsExistDirNoLog(ServiceConstants::BMS_APP_TEMP_PATH)) {
4448 return;
4449 }
4450 LOG_I(BMS_TAG_DEFAULT, "process app_temp start");
4451 InstallParam installParam;
4452 installParam.SetKillProcess(false);
4453 installParam.needSendEvent = false;
4454 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
4455 installParam.copyHapToInstallPath = true;
4456 installParam.isOTA = false;
4457 installParam.withCopyHaps = true;
4458 installParam.isPatch = false;
4459 SystemBundleInstaller installer;
4460 std::vector<std::string> filePaths { ServiceConstants::BMS_APP_TEMP_PATH };
4461 if (installer.OTAInstallSystemBundle(filePaths, installParam, Constants::AppType::SYSTEM_APP) != ERR_OK) {
4462 LOG_W(BMS_TAG_DEFAULT, "app_temp path install failed");
4463 return;
4464 }
4465 if (!BundleUtil::DeleteDir(ServiceConstants::BMS_APP_TEMP_PATH)) {
4466 LOG_E(BMS_TAG_INSTALLER, "delete app_temp failed %{public}d", errno);
4467 }
4468 LOG_I(BMS_TAG_DEFAULT, "process app_temp end");
4469 }
4470
CleanTempDir() const4471 void BMSEventHandler::CleanTempDir() const
4472 {
4473 BundleUtil::RestoreAppInstallHaps();
4474 std::vector<std::string> dirs = {
4475 std::string(ServiceConstants::HAP_COPY_PATH) + ServiceConstants::PATH_SEPARATOR +
4476 ServiceConstants::STREAM_INSTALL_PATH,
4477 std::string(ServiceConstants::HAP_COPY_PATH) + ServiceConstants::PATH_SEPARATOR +
4478 ServiceConstants::SECURITY_STREAM_INSTALL_PATH,
4479 std::string(ServiceConstants::HAP_COPY_PATH) + ServiceConstants::PATH_SEPARATOR +
4480 ServiceConstants::SIGNATURE_FILE_PATH,
4481 std::string(ServiceConstants::HAP_COPY_PATH) + ServiceConstants::PATH_SEPARATOR +
4482 PGO_FILE_PATH,
4483 };
4484
4485 for (const auto& dir : dirs) {
4486 if (OHOS::IsEmptyFolder(dir)) {
4487 continue;
4488 }
4489 LOG_I(BMS_TAG_DEFAULT, "clean %{public}s", dir.c_str());
4490 if (!OHOS::ForceRemoveDirectoryBMS(dir)) {
4491 LOG_E(BMS_TAG_DEFAULT, "remove failed: %{public}s", dir.c_str());
4492 continue;
4493 }
4494 if (!BundleUtil::CreateTempDir(dir).empty()) {
4495 LOG_E(BMS_TAG_DEFAULT, "create failed: %{public}s", dir.c_str());
4496 }
4497 }
4498
4499 UpdateAppDataMgr::DeleteUninstallTmpDirs(Constants::DEFAULT_USERID);
4500 }
4501
CheckBundleProvisionInfo()4502 void BMSEventHandler::CheckBundleProvisionInfo()
4503 {
4504 LOG_I(BMS_TAG_DEFAULT, "start");
4505 std::thread ProcessBundleProvisionInfoThread(InnerProcessStockBundleProvisionInfo);
4506 ProcessBundleProvisionInfoThread.detach();
4507 }
4508 } // namespace AppExecFwk
4509 } // namespace OHOS
4510