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