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