1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "bundle_mgr_service_event_handler.h"
17
18 #include <future>
19 #include <sys/stat.h>
20
21 #include "accesstoken_kit.h"
22 #include "access_token.h"
23 #include "app_log_wrapper.h"
24 #include "app_privilege_capability.h"
25 #include "bundle_install_checker.h"
26 #include "bundle_mgr_service.h"
27 #include "bundle_parser.h"
28 #include "bundle_permission_mgr.h"
29 #include "bundle_scanner.h"
30 #include "bundle_util.h"
31 #ifdef CONFIG_POLOCY_ENABLE
32 #include "config_policy_utils.h"
33 #endif
34 #include "event_report.h"
35 #include "installd_client.h"
36 #include "parameter.h"
37 #include "perf_profile.h"
38 #include "status_receiver_host.h"
39 #include "system_bundle_installer.h"
40 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
41 #include "quick_fix_boot_scanner.h"
42 #endif
43
44 namespace OHOS {
45 namespace AppExecFwk {
46 namespace {
47 const std::string APP_SUFFIX = "/app";
48 const std::string TEMP_PREFIX = "temp_";
49 const std::string MODULE_PREFIX = "module_";
50 // system version && hotpatch information
51 const std::string BASE_VERSION_PARAM_NAME = "const.product.software.version";
52 const std::string BASE_VERSION_PARAM_RO_NAME = "ro.comp.hl.product_base_version.real";
53 // this metadata used to indicate those system application update by hotpatch upgrade.
54 const std::string HOT_PATCH_METADATA = "ohos.app.quickfix";
55 const std::string FINGERPRINT = "fingerprint";
56 const std::string UNKNOWN = "UNKNOWN";
57 const int32_t VERSION_LEN = 64;
58
59 std::set<PreScanInfo> installList_;
60 std::set<std::string> uninstallList_;
61 std::set<PreBundleConfigInfo> installListCapabilities_;
62 bool hasLoadPreInstallProFile_ = false;
63
MoveTempPath(const std::vector<std::string> & fromPaths,const std::string & bundleName,std::vector<std::string> & toPaths)64 void MoveTempPath(const std::vector<std::string> &fromPaths,
65 const std::string &bundleName, std::vector<std::string> &toPaths)
66 {
67 std::string tempDir =
68 Constants::HAP_COPY_PATH + Constants::PATH_SEPARATOR + TEMP_PREFIX + bundleName;
69 if (!BundleUtil::CreateDir(tempDir)) {
70 APP_LOGE("create tempdir failed %{public}s", tempDir.c_str());
71 return;
72 }
73
74 int32_t hapIndex = 0;
75 for (const auto &path : fromPaths) {
76 auto toPath = tempDir + Constants::PATH_SEPARATOR + MODULE_PREFIX
77 + std::to_string(hapIndex) + Constants::INSTALL_FILE_SUFFIX;
78 hapIndex++;
79 if (InstalldClient::GetInstance()->MoveFile(path, toPath) != ERR_OK) {
80 APP_LOGW("move from %{public}s to %{public}s failed", path.c_str(), toPath.c_str());
81 continue;
82 }
83
84 toPaths.emplace_back(toPath);
85 }
86 }
87
88 class InnerReceiverImpl : public StatusReceiverHost {
89 public:
90 InnerReceiverImpl() = default;
91 virtual ~InnerReceiverImpl() override = default;
92
SetBundleName(const std::string & bundleName)93 void SetBundleName(const std::string &bundleName)
94 {
95 bundleName_ = bundleName;
96 }
97
OnStatusNotify(const int progress)98 virtual void OnStatusNotify(const int progress) override {}
OnFinished(const int32_t resultCode,const std::string & resultMsg)99 virtual void OnFinished(
100 const int32_t resultCode, const std::string &resultMsg) override
101 {
102 if (bundleName_.empty()) {
103 return;
104 }
105
106 std::string tempDir = Constants::HAP_COPY_PATH
107 + Constants::PATH_SEPARATOR + TEMP_PREFIX + bundleName_;
108 APP_LOGD("delete tempDir %{public}s", tempDir.c_str());
109 BundleUtil::DeleteDir(tempDir);
110 }
111
112 private:
113 std::string bundleName_;
114 };
115 }
116
BMSEventHandler(const std::shared_ptr<EventRunner> & runner)117 BMSEventHandler::BMSEventHandler(const std::shared_ptr<EventRunner> &runner) : EventHandler(runner)
118 {
119 APP_LOGD("instance is created");
120 }
121
~BMSEventHandler()122 BMSEventHandler::~BMSEventHandler()
123 {
124 APP_LOGD("instance is destroyed");
125 }
126
ProcessEvent(const InnerEvent::Pointer & event)127 void BMSEventHandler::ProcessEvent(const InnerEvent::Pointer &event)
128 {
129 switch (event->GetInnerEventId()) {
130 case BMS_START: {
131 BmsStartEvent();
132 break;
133 }
134 default:
135 APP_LOGE("the eventId is not supported");
136 break;
137 }
138 }
139
BmsStartEvent()140 void BMSEventHandler::BmsStartEvent()
141 {
142 BeforeBmsStart();
143 OnBmsStarting();
144 AfterBmsStart();
145 }
146
BeforeBmsStart()147 void BMSEventHandler::BeforeBmsStart()
148 {
149 needNotifyBundleScanStatus_ = false;
150 if (!BundlePermissionMgr::Init()) {
151 APP_LOGW("BundlePermissionMgr::Init failed");
152 }
153
154 EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_START);
155 }
156
OnBmsStarting()157 void BMSEventHandler::OnBmsStarting()
158 {
159 // Judge whether there is install info in the persistent Db
160 if (LoadInstallInfosFromDb()) {
161 APP_LOGD("Load install info from db success");
162 BundleRebootStartEvent();
163 return;
164 }
165
166 // If the preInstall infos does not exist in preInstall db,
167 // all preInstall directory applications will be reinstalled.
168 if (!LoadAllPreInstallBundleInfos()) {
169 APP_LOGE("Load all preInstall bundleInfos failed.");
170 needRebootOta_ = true;
171 }
172
173 /* Guard against install infos lossed strategy.
174 * 1. Scan user data dir
175 * 1.1. If no data, first boot.
176 * 1.2. If has data, but parse data to InnerBundleUserInfos failed,
177 * reInstall all app from install dir and preInstall dir
178 * 1.3. If has data and parse data to InnerBundleUserInfos success, goto 2
179 * 2. Scan installDir include common install dir and preInstall dir
180 * And the parse the hap to InnerBundleInfos
181 * 3. Combine InnerBundleInfos and InnerBundleUserInfos to cache and db
182 * 4. According to needRebootOta determine whether OTA detection is required
183 */
184 ResultCode resultCode = GuardAgainstInstallInfosLossedStrategy();
185 switch (resultCode) {
186 case ResultCode::RECOVER_OK: {
187 APP_LOGD("Guard against install infos lossed strategy take effect.");
188 if (needRebootOta_) {
189 BundleRebootStartEvent();
190 } else {
191 needNotifyBundleScanStatus_ = true;
192 }
193
194 break;
195 }
196 case ResultCode::REINSTALL_OK: {
197 APP_LOGD("ReInstall all haps.");
198 needNotifyBundleScanStatus_ = true;
199 break;
200 }
201 case ResultCode::NO_INSTALLED_DATA: {
202 // First boot
203 BundleBootStartEvent();
204 break;
205 }
206 default:
207 APP_LOGE("System internal error, install informations missing.");
208 break;
209 }
210 SaveSystemVersion();
211 }
212
AfterBmsStart()213 void BMSEventHandler::AfterBmsStart()
214 {
215 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
216 DelayedSingleton<QuickFixBootScanner>::GetInstance()->ProcessQuickFixBootUp();
217 #endif
218 DelayedSingleton<BundleMgrService>::GetInstance()->CheckAllUser();
219 BundlePermissionMgr::UnInit();
220 SetAllInstallFlag();
221 DelayedSingleton<BundleMgrService>::GetInstance()->RegisterService();
222 EventReport::SendScanSysEvent(BMSEventType::BOOT_SCAN_END);
223 ClearCache();
224 if (needNotifyBundleScanStatus_) {
225 DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
226 }
227 }
228
ClearCache()229 void BMSEventHandler::ClearCache()
230 {
231 hapParseInfoMap_.clear();
232 loadExistData_.clear();
233 hasLoadAllPreInstallBundleInfosFromDb_ = false;
234 }
235
LoadInstallInfosFromDb()236 bool BMSEventHandler::LoadInstallInfosFromDb()
237 {
238 APP_LOGD("Load install infos from db");
239 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
240 if (dataMgr == nullptr) {
241 APP_LOGE("DataMgr is nullptr");
242 return false;
243 }
244
245 return dataMgr->LoadDataFromPersistentStorage();
246 }
247
BundleBootStartEvent()248 void BMSEventHandler::BundleBootStartEvent()
249 {
250 OnBundleBootStart(Constants::DEFAULT_USERID);
251 PerfProfile::GetInstance().Dump();
252 }
253
BundleRebootStartEvent()254 void BMSEventHandler::BundleRebootStartEvent()
255 {
256 #ifdef USE_PRE_BUNDLE_PROFILE
257 if (LoadPreInstallProFile()) {
258 UpdateAllPrivilegeCapability();
259 }
260 #endif
261
262 if (IsSystemUpgrade()) {
263 OnBundleRebootStart();
264 SaveSystemVersion();
265 }
266 needNotifyBundleScanStatus_ = true;
267 }
268
GuardAgainstInstallInfosLossedStrategy()269 ResultCode BMSEventHandler::GuardAgainstInstallInfosLossedStrategy()
270 {
271 APP_LOGD("GuardAgainstInstallInfosLossedStrategy start");
272 // Check user path, and parse userData to InnerBundleUserInfo
273 std::map<std::string, std::vector<InnerBundleUserInfo>> innerBundleUserInfoMaps;
274 ScanResultCode scanResultCode = ScanAndAnalyzeUserDatas(innerBundleUserInfoMaps);
275 if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
276 APP_LOGE("Scan the user data directory failed");
277 return ResultCode::NO_INSTALLED_DATA;
278 }
279
280 // When data exist, but parse all userinfo fails, reinstall all app.
281 // For example: the AT database is lost or others.
282 if (scanResultCode == ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED) {
283 // Reinstall all app from install dir
284 return ReInstallAllInstallDirApps();
285 }
286
287 // When data exist and parse all userinfo success,
288 // it can be judged that some bundles has installed.
289 // Check install dir, and parse the hap in install dir to InnerBundleInfo
290 std::map<std::string, std::vector<InnerBundleInfo>> installInfos;
291 ScanAndAnalyzeInstallInfos(installInfos);
292 if (installInfos.empty()) {
293 APP_LOGE("check bundle path failed due to hap lossd or parse failed");
294 return ResultCode::SYSTEM_ERROR;
295 }
296
297 // Combine InnerBundleInfo and InnerBundleUserInfo
298 if (!CombineBundleInfoAndUserInfo(installInfos, innerBundleUserInfoMaps)) {
299 APP_LOGE("System internal error");
300 return ResultCode::SYSTEM_ERROR;
301 }
302
303 return ResultCode::RECOVER_OK;
304 }
305
ScanAndAnalyzeUserDatas(std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)306 ScanResultCode BMSEventHandler::ScanAndAnalyzeUserDatas(
307 std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
308 {
309 ScanResultCode scanResultCode = ScanResultCode::SCAN_NO_DATA;
310 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
311 if (dataMgr == nullptr) {
312 APP_LOGE("dataMgr is null");
313 return scanResultCode;
314 }
315
316 std::string baseDataDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[0];
317 std::vector<std::string> userIds;
318 if (!ScanDir(baseDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userIds)) {
319 APP_LOGD("Check the base user directory(%{public}s) failed", baseDataDir.c_str());
320 return scanResultCode;
321 }
322
323 for (const auto &userId : userIds) {
324 int32_t userIdInt = Constants::INVALID_USERID;
325 if (!StrToInt(userId, userIdInt)) {
326 APP_LOGE("UserId(%{public}s) strToInt failed", userId.c_str());
327 continue;
328 }
329
330 dataMgr->AddUserId(userIdInt);
331 std::vector<std::string> userDataBundleNames;
332 std::string userDataDir = baseDataDir + Constants::PATH_SEPARATOR + userId + Constants::BASE;
333 if (!ScanDir(userDataDir, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, userDataBundleNames)) {
334 APP_LOGD("Check the user installation directory(%{public}s) failed", userDataDir.c_str());
335 continue;
336 }
337
338 for (const auto &userDataBundleName : userDataBundleNames) {
339 if (scanResultCode == ScanResultCode::SCAN_NO_DATA) {
340 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_FAILED;
341 }
342
343 if (AnalyzeUserData(userIdInt, userDataDir, userDataBundleName, userMaps)) {
344 scanResultCode = ScanResultCode::SCAN_HAS_DATA_PARSE_SUCCESS;
345 }
346 }
347 }
348
349 return scanResultCode;
350 }
351
AnalyzeUserData(int32_t userId,const std::string & userDataDir,const std::string & userDataBundleName,std::map<std::string,std::vector<InnerBundleUserInfo>> & userMaps)352 bool BMSEventHandler::AnalyzeUserData(
353 int32_t userId, const std::string &userDataDir, const std::string &userDataBundleName,
354 std::map<std::string, std::vector<InnerBundleUserInfo>> &userMaps)
355 {
356 if (userDataDir.empty() || userDataBundleName.empty()) {
357 APP_LOGE("UserDataDir or UserDataBundleName is empty");
358 return false;
359 }
360
361 std::string userDataBundlePath = userDataDir + userDataBundleName;
362 APP_LOGD("Analyze user data path(%{public}s)", userDataBundlePath.c_str());
363 FileStat fileStat;
364 if (InstalldClient::GetInstance()->GetFileStat(userDataBundlePath, fileStat) != ERR_OK) {
365 APP_LOGE("GetFileStat path(%{public}s) failed", userDataBundlePath.c_str());
366 return false;
367 }
368
369 // It should be a bundleName dir
370 if (!fileStat.isDir) {
371 APP_LOGE("UserDataBundlePath(%{public}s) is not dir", userDataBundlePath.c_str());
372 return false;
373 }
374
375 InnerBundleUserInfo innerBundleUserInfo;
376 innerBundleUserInfo.bundleName = userDataBundleName;
377 innerBundleUserInfo.bundleUserInfo.userId = userId;
378 innerBundleUserInfo.uid = fileStat.uid;
379 innerBundleUserInfo.gids.emplace_back(fileStat.gid);
380 innerBundleUserInfo.installTime = fileStat.lastModifyTime;
381 innerBundleUserInfo.updateTime = innerBundleUserInfo.installTime;
382 auto tokenId = OHOS::Security::AccessToken::AccessTokenKit::GetHapTokenID(
383 innerBundleUserInfo.bundleUserInfo.userId, userDataBundleName, 0);
384 if (tokenId == 0) {
385 APP_LOGE("get tokenId failed.");
386 return false;
387 }
388
389 innerBundleUserInfo.accessTokenId = tokenId;
390 auto userIter = userMaps.find(userDataBundleName);
391 if (userIter == userMaps.end()) {
392 std::vector<InnerBundleUserInfo> innerBundleUserInfos = { innerBundleUserInfo };
393 userMaps.emplace(userDataBundleName, innerBundleUserInfos);
394 return true;
395 }
396
397 userMaps.at(userDataBundleName).emplace_back(innerBundleUserInfo);
398 return true;
399 }
400
ReInstallAllInstallDirApps()401 ResultCode BMSEventHandler::ReInstallAllInstallDirApps()
402 {
403 // First, reinstall all preInstall app from preInstall dir
404 std::vector<std::string> preInstallDirs;
405 GetPreInstallDir(preInstallDirs);
406 for (const auto &preInstallDir : preInstallDirs) {
407 std::vector<std::string> filePaths { preInstallDir };
408 bool removable = IsPreInstallRemovable(preInstallDir);
409 if (!OTAInstallSystemBundle(
410 filePaths, Constants::AppType::SYSTEM_APP, removable)) {
411 APP_LOGE("Reinstall bundle(%{public}s) error.", preInstallDir.c_str());
412 continue;
413 }
414 }
415
416 auto installer = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
417 if (installer == nullptr) {
418 APP_LOGE("installer is nullptr");
419 return ResultCode::SYSTEM_ERROR;
420 }
421
422 // Second, reInstall all common install app from install dir
423 std::map<std::string, std::vector<std::string>> hapPathsMap;
424 ScanInstallDir(hapPathsMap);
425 for (const auto &hapPaths : hapPathsMap) {
426 InstallParam installParam;
427 installParam.userId = Constants::ALL_USERID;
428 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
429 installParam.streamInstallMode = true;
430 sptr<InnerReceiverImpl> innerReceiverImpl(new (std::nothrow) InnerReceiverImpl());
431 innerReceiverImpl->SetBundleName(hapPaths.first);
432 std::vector<std::string> tempHaps;
433 MoveTempPath(hapPaths.second, hapPaths.first, tempHaps);
434 installer->Install(tempHaps, installParam, innerReceiverImpl);
435 }
436
437 return ResultCode::REINSTALL_OK;
438 }
439
ScanAndAnalyzeInstallInfos(std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)440 void BMSEventHandler::ScanAndAnalyzeInstallInfos(
441 std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
442 {
443 // Scan the installed directory
444 std::map<std::string, std::vector<std::string>> hapPathsMap;
445 ScanInstallDir(hapPathsMap);
446 AnalyzeHaps(false, hapPathsMap, installInfos);
447
448 // Scan preBundle directory
449 std::vector<std::string> preInstallDirs;
450 GetPreInstallDir(preInstallDirs);
451 AnalyzeHaps(true, preInstallDirs, installInfos);
452 }
453
ScanInstallDir(std::map<std::string,std::vector<std::string>> & hapPathsMap)454 void BMSEventHandler::ScanInstallDir(
455 std::map<std::string, std::vector<std::string>> &hapPathsMap)
456 {
457 APP_LOGD("Scan the installed directory start");
458 std::vector<std::string> bundleNameList;
459 if (!ScanDir(Constants::BUNDLE_CODE_DIR, ScanMode::SUB_FILE_DIR, ResultMode::RELATIVE_PATH, bundleNameList)) {
460 APP_LOGE("Check the bundle directory(%{public}s) failed", Constants::BUNDLE_CODE_DIR);
461 return;
462 }
463
464 for (const auto &bundleName : bundleNameList) {
465 std::vector<std::string> hapPaths;
466 auto appCodePath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName;
467 if (!ScanDir(appCodePath, ScanMode::SUB_FILE_FILE, ResultMode::ABSOLUTE_PATH, hapPaths)) {
468 APP_LOGE("Scan the appCodePath(%{public}s) failed", appCodePath.c_str());
469 continue;
470 }
471
472 if (hapPaths.empty()) {
473 APP_LOGD("The directory(%{public}s) scan result is empty", appCodePath.c_str());
474 continue;
475 }
476
477 std::vector<std::string> checkHapPaths = CheckHapPaths(hapPaths);
478 hapPathsMap.emplace(bundleName, checkHapPaths);
479 }
480
481 APP_LOGD("Scan the installed directory end");
482 }
483
CheckHapPaths(const std::vector<std::string> & hapPaths)484 std::vector<std::string> BMSEventHandler::CheckHapPaths(
485 const std::vector<std::string> &hapPaths)
486 {
487 std::vector<std::string> checkHapPaths;
488 for (const auto &hapPath : hapPaths) {
489 if (!BundleUtil::CheckFileType(hapPath, Constants::INSTALL_FILE_SUFFIX)) {
490 APP_LOGE("Check hapPath(%{public}s) failed", hapPath.c_str());
491 continue;
492 }
493
494 checkHapPaths.emplace_back(hapPath);
495 }
496
497 return checkHapPaths;
498 }
499
GetPreInstallRootDirList(std::vector<std::string> & rootDirList)500 void BMSEventHandler::GetPreInstallRootDirList(std::vector<std::string> &rootDirList)
501 {
502 #ifdef CONFIG_POLOCY_ENABLE
503 auto cfgDirList = GetCfgDirList();
504 if (cfgDirList != nullptr) {
505 for (const auto &cfgDir : cfgDirList->paths) {
506 if (cfgDir == nullptr) {
507 continue;
508 }
509
510 APP_LOGD("cfgDir: %{public}s ", cfgDir);
511 rootDirList.emplace_back(cfgDir);
512 }
513
514 FreeCfgDirList(cfgDirList);
515 }
516 #endif
517 bool ret = std::find(
518 rootDirList.begin(), rootDirList.end(), Constants::DEFAULT_PRE_BUNDLE_ROOT_DIR) != rootDirList.end();
519 if (!ret) {
520 rootDirList.emplace_back(Constants::DEFAULT_PRE_BUNDLE_ROOT_DIR);
521 }
522 }
523
ClearPreInstallCache()524 void BMSEventHandler::ClearPreInstallCache()
525 {
526 if (!hasLoadPreInstallProFile_) {
527 return;
528 }
529
530 installList_.clear();
531 uninstallList_.clear();
532 installListCapabilities_.clear();
533 hasLoadPreInstallProFile_ = false;
534 }
535
LoadPreInstallProFile()536 bool BMSEventHandler::LoadPreInstallProFile()
537 {
538 if (hasLoadPreInstallProFile_) {
539 return !installList_.empty();
540 }
541
542 std::vector<std::string> rootDirList;
543 GetPreInstallRootDirList(rootDirList);
544 if (rootDirList.empty()) {
545 APP_LOGE("dirList is empty");
546 return false;
547 }
548
549 for (const auto &rootDir : rootDirList) {
550 ParsePreBundleProFile(rootDir + Constants::PRODUCT_SUFFIX);
551 }
552
553 hasLoadPreInstallProFile_ = true;
554 return !installList_.empty();
555 }
556
HasPreInstallProfile()557 bool BMSEventHandler::HasPreInstallProfile()
558 {
559 return !installList_.empty();
560 }
561
ParsePreBundleProFile(const std::string & dir)562 void BMSEventHandler::ParsePreBundleProFile(const std::string &dir)
563 {
564 BundleParser bundleParser;
565 bundleParser.ParsePreInstallConfig(
566 dir + Constants::INSTALL_LIST_CONFIG, installList_);
567 bundleParser.ParsePreUnInstallConfig(
568 dir + Constants::UNINSTALL_LIST_CONFIG, uninstallList_);
569 bundleParser.ParsePreInstallAbilityConfig(
570 dir + Constants::INSTALL_LIST_CAPABILITY_CONFIG, installListCapabilities_);
571 }
572
GetPreInstallDir(std::vector<std::string> & bundleDirs)573 void BMSEventHandler::GetPreInstallDir(std::vector<std::string> &bundleDirs)
574 {
575 #ifdef USE_PRE_BUNDLE_PROFILE
576 if (LoadPreInstallProFile()) {
577 GetPreInstallDirFromLoadProFile(bundleDirs);
578 return;
579 }
580 #endif
581
582 GetPreInstallDirFromScan(bundleDirs);
583 }
584
GetPreInstallDirFromLoadProFile(std::vector<std::string> & bundleDirs)585 void BMSEventHandler::GetPreInstallDirFromLoadProFile(std::vector<std::string> &bundleDirs)
586 {
587 for (const auto &installInfo : installList_) {
588 if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
589 APP_LOGW("bundle(%{public}s) not allowed installed", installInfo.bundleDir.c_str());
590 continue;
591 }
592
593 bundleDirs.emplace_back(installInfo.bundleDir);
594 }
595 }
596
GetPreInstallDirFromScan(std::vector<std::string> & bundleDirs)597 void BMSEventHandler::GetPreInstallDirFromScan(std::vector<std::string> &bundleDirs)
598 {
599 std::list<std::string> scanbundleDirs;
600 GetBundleDirFromScan(scanbundleDirs);
601 std::copy(scanbundleDirs.begin(), scanbundleDirs.end(), std::back_inserter(bundleDirs));
602 }
603
AnalyzeHaps(bool isPreInstallApp,const std::map<std::string,std::vector<std::string>> & hapPathsMap,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)604 void BMSEventHandler::AnalyzeHaps(
605 bool isPreInstallApp,
606 const std::map<std::string, std::vector<std::string>> &hapPathsMap,
607 std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
608 {
609 for (const auto &hapPaths : hapPathsMap) {
610 AnalyzeHaps(isPreInstallApp, hapPaths.second, installInfos);
611 }
612 }
613
AnalyzeHaps(bool isPreInstallApp,const std::vector<std::string> & bundleDirs,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)614 void BMSEventHandler::AnalyzeHaps(
615 bool isPreInstallApp,
616 const std::vector<std::string> &bundleDirs,
617 std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
618 {
619 for (const auto &bundleDir : bundleDirs) {
620 std::unordered_map<std::string, InnerBundleInfo> hapInfos;
621 if (!CheckAndParseHapFiles(bundleDir, isPreInstallApp, hapInfos) || hapInfos.empty()) {
622 APP_LOGE("Parse bundleDir(%{public}s) failed", bundleDir.c_str());
623 continue;
624 }
625
626 CollectInstallInfos(hapInfos, installInfos);
627 }
628 }
629
CollectInstallInfos(const std::unordered_map<std::string,InnerBundleInfo> & hapInfos,std::map<std::string,std::vector<InnerBundleInfo>> & installInfos)630 void BMSEventHandler::CollectInstallInfos(
631 const std::unordered_map<std::string, InnerBundleInfo> &hapInfos,
632 std::map<std::string, std::vector<InnerBundleInfo>> &installInfos)
633 {
634 for (const auto &hapInfoIter : hapInfos) {
635 auto bundleName = hapInfoIter.second.GetBundleName();
636 if (installInfos.find(bundleName) == installInfos.end()) {
637 std::vector<InnerBundleInfo> innerBundleInfos { hapInfoIter.second };
638 installInfos.emplace(bundleName, innerBundleInfos);
639 continue;
640 }
641
642 installInfos.at(bundleName).emplace_back(hapInfoIter.second);
643 }
644 }
645
CombineBundleInfoAndUserInfo(const std::map<std::string,std::vector<InnerBundleInfo>> & installInfos,const std::map<std::string,std::vector<InnerBundleUserInfo>> & userInfoMaps)646 bool BMSEventHandler::CombineBundleInfoAndUserInfo(
647 const std::map<std::string, std::vector<InnerBundleInfo>> &installInfos,
648 const std::map<std::string, std::vector<InnerBundleUserInfo>> &userInfoMaps)
649 {
650 APP_LOGD("Combine code information and user data start");
651 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
652 if (dataMgr == nullptr) {
653 APP_LOGE("dataMgr is null");
654 return false;
655 }
656
657 if (installInfos.empty() || userInfoMaps.empty()) {
658 APP_LOGE("bundleInfos or userInfos is empty");
659 return false;
660 }
661
662 for (auto hasInstallInfo : installInfos) {
663 auto bundleName = hasInstallInfo.first;
664 auto userIter = userInfoMaps.find(bundleName);
665 if (userIter == userInfoMaps.end()) {
666 APP_LOGE("User data directory missing with bundle %{public}s ", bundleName.c_str());
667 needRebootOta_ = true;
668 continue;
669 }
670
671 for (auto &info : hasInstallInfo.second) {
672 SaveInstallInfoToCache(info);
673 }
674
675 for (const auto &userInfo : userIter->second) {
676 dataMgr->AddInnerBundleUserInfo(bundleName, userInfo);
677 }
678 }
679
680 // Parsing uid, gids and other user information
681 dataMgr->RestoreUidAndGid();
682 // Load all bundle state data from jsonDb
683 dataMgr->LoadAllBundleStateDataFromJsonDb();
684 APP_LOGD("Combine code information and user data end");
685 return true;
686 }
687
SaveInstallInfoToCache(InnerBundleInfo & info)688 void BMSEventHandler::SaveInstallInfoToCache(InnerBundleInfo &info)
689 {
690 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
691 if (dataMgr == nullptr) {
692 APP_LOGE("dataMgr is null");
693 return;
694 }
695
696 auto bundleName = info.GetBundleName();
697 auto appCodePath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName;
698 info.SetAppCodePath(appCodePath);
699
700 std::string dataBaseDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[1]
701 + Constants::DATABASE + bundleName;
702 info.SetAppDataBaseDir(dataBaseDir);
703
704 auto moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
705 info.AddModuleSrcDir(moduleDir);
706 info.AddModuleResPath(moduleDir);
707
708 bool bundleExist = false;
709 InnerBundleInfo dbInfo;
710 {
711 auto &mtx = dataMgr->GetBundleMutex(bundleName);
712 std::lock_guard lock { mtx };
713 bundleExist = dataMgr->GetInnerBundleInfo(bundleName, dbInfo);
714 if (bundleExist) {
715 dataMgr->EnableBundle(bundleName);
716 }
717 }
718
719 if (!bundleExist) {
720 dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_START);
721 dataMgr->AddInnerBundleInfo(bundleName, info);
722 dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS);
723 return;
724 }
725
726 auto& hapModuleName = info.GetCurModuleName();
727 std::vector<std::string> dbModuleNames;
728 dbInfo.GetModuleNames(dbModuleNames);
729 auto iter = std::find(dbModuleNames.begin(), dbModuleNames.end(), hapModuleName);
730 if (iter != dbModuleNames.end()) {
731 APP_LOGE("module(%{public}s) has install", hapModuleName.c_str());
732 return;
733 }
734
735 dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_START);
736 dataMgr->UpdateBundleInstallState(bundleName, InstallState::UPDATING_SUCCESS);
737 dataMgr->AddNewModuleInfo(bundleName, info, dbInfo);
738 }
739
ScanDir(const std::string & dir,ScanMode scanMode,ResultMode resultMode,std::vector<std::string> & resultList)740 bool BMSEventHandler::ScanDir(
741 const std::string& dir, ScanMode scanMode, ResultMode resultMode, std::vector<std::string> &resultList)
742 {
743 APP_LOGD("Scan the directory(%{public}s) start", dir.c_str());
744 ErrCode result = InstalldClient::GetInstance()->ScanDir(dir, scanMode, resultMode, resultList);
745 if (result != ERR_OK) {
746 APP_LOGE("Scan the directory(%{public}s) failed", dir.c_str());
747 return false;
748 }
749
750 return true;
751 }
752
OnBundleBootStart(int32_t userId)753 void BMSEventHandler::OnBundleBootStart(int32_t userId)
754 {
755 #ifdef USE_PRE_BUNDLE_PROFILE
756 if (LoadPreInstallProFile()) {
757 APP_LOGD("Process boot bundle install from pre bundle proFile");
758 InnerProcessBootPreBundleProFileInstall(userId);
759 return;
760 }
761 #else
762 ProcessBootBundleInstallFromScan(userId);
763 #endif
764 }
765
ProcessBootBundleInstallFromScan(int32_t userId)766 void BMSEventHandler::ProcessBootBundleInstallFromScan(int32_t userId)
767 {
768 APP_LOGD("Process boot bundle install from scan");
769 std::list<std::string> bundleDirs;
770 GetBundleDirFromScan(bundleDirs);
771 for (auto item : bundleDirs) {
772 ProcessSystemBundleInstall(item, Constants::AppType::SYSTEM_APP, userId);
773 }
774 }
775
GetBundleDirFromScan(std::list<std::string> & bundleDirs)776 void BMSEventHandler::GetBundleDirFromScan(std::list<std::string> &bundleDirs)
777 {
778 std::vector<std::string> rootDirList;
779 GetPreInstallRootDirList(rootDirList);
780 if (rootDirList.empty()) {
781 APP_LOGE("rootDirList is empty");
782 return;
783 }
784
785 for (const auto &rootDir : rootDirList) {
786 ProcessScanDir(rootDir + APP_SUFFIX, bundleDirs);
787 }
788
789 auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), Constants::SYSTEM_RESOURCES_APP_PATH);
790 if (iter != bundleDirs.end()) {
791 bundleDirs.erase(iter);
792 bundleDirs.insert(bundleDirs.begin(), Constants::SYSTEM_RESOURCES_APP_PATH);
793 }
794 }
795
ProcessScanDir(const std::string & dir,std::list<std::string> & bundleDirs)796 void BMSEventHandler::ProcessScanDir(const std::string &dir, std::list<std::string> &bundleDirs)
797 {
798 BundleScanner scanner;
799 std::list<std::string> bundleList = scanner.Scan(dir);
800 for (auto item : bundleList) {
801 auto iter = std::find(bundleDirs.begin(), bundleDirs.end(), item);
802 if (iter == bundleDirs.end()) {
803 bundleDirs.push_back(item);
804 }
805 }
806 }
807
InnerProcessBootPreBundleProFileInstall(int32_t userId)808 void BMSEventHandler::InnerProcessBootPreBundleProFileInstall(int32_t userId)
809 {
810 for (const auto &installInfo : installList_) {
811 APP_LOGD("Inner process boot preBundle proFile install %{public}s", installInfo.ToString().c_str());
812 if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
813 APP_LOGW("bundle(%{public}s) not allowed installed when boot", installInfo.bundleDir.c_str());
814 continue;
815 }
816
817 ProcessSystemBundleInstall(
818 installInfo, Constants::AppType::SYSTEM_APP, userId);
819 }
820 }
821
ProcessSystemBundleInstall(const PreScanInfo & preScanInfo,Constants::AppType appType,int32_t userId)822 void BMSEventHandler::ProcessSystemBundleInstall(
823 const PreScanInfo &preScanInfo, Constants::AppType appType, int32_t userId)
824 {
825 APP_LOGD("Process system bundle install by bundleDir(%{public}s)", preScanInfo.bundleDir.c_str());
826 InstallParam installParam;
827 installParam.userId = userId;
828 installParam.isPreInstallApp = true;
829 installParam.noSkipsKill = false;
830 installParam.needSendEvent = false;
831 installParam.removable = preScanInfo.removable;
832 installParam.needSavePreInstallInfo = true;
833 installParam.copyHapToInstallPath = false;
834 SystemBundleInstaller installer;
835 if (!installer.InstallSystemBundle(preScanInfo.bundleDir, installParam, appType)) {
836 APP_LOGW("Install System app:%{public}s error", preScanInfo.bundleDir.c_str());
837 }
838 }
839
ProcessSystemBundleInstall(const std::string & bundleDir,Constants::AppType appType,int32_t userId)840 void BMSEventHandler::ProcessSystemBundleInstall(
841 const std::string &bundleDir, Constants::AppType appType, int32_t userId)
842 {
843 APP_LOGD("Process system bundle install by bundleDir(%{public}s)", bundleDir.c_str());
844 InstallParam installParam;
845 installParam.userId = userId;
846 installParam.isPreInstallApp = true;
847 installParam.noSkipsKill = false;
848 installParam.needSendEvent = false;
849 installParam.removable = false;
850 installParam.needSavePreInstallInfo = true;
851 installParam.copyHapToInstallPath = false;
852 SystemBundleInstaller installer;
853 if (!installer.InstallSystemBundle(bundleDir, installParam, appType)) {
854 APP_LOGW("Install System app:%{public}s error", bundleDir.c_str());
855 }
856 }
857
SetAllInstallFlag() const858 void BMSEventHandler::SetAllInstallFlag() const
859 {
860 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
861 if (dataMgr == nullptr) {
862 APP_LOGE("DataMgr is nullptr");
863 return;
864 }
865
866 dataMgr->SetInitialUserFlag(true);
867 }
868
OnBundleRebootStart()869 void BMSEventHandler::OnBundleRebootStart()
870 {
871 ProcessRebootBundle();
872 }
873
ProcessRebootBundle()874 void BMSEventHandler::ProcessRebootBundle()
875 {
876 APP_LOGD("Process reboot bundle start");
877 LoadAllPreInstallBundleInfos();
878 ProcessRebootBundleInstall();
879 ProcessRebootBundleUninstall();
880 }
881
LoadAllPreInstallBundleInfos()882 bool BMSEventHandler::LoadAllPreInstallBundleInfos()
883 {
884 if (hasLoadAllPreInstallBundleInfosFromDb_) {
885 APP_LOGD("Has load all preInstall bundleInfos from db");
886 return true;
887 }
888
889 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
890 if (dataMgr == nullptr) {
891 APP_LOGE("DataMgr is nullptr");
892 return false;
893 }
894
895 std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
896 for (auto &iter : preInstallBundleInfos) {
897 APP_LOGD("preInstallBundleInfos: %{public}s ", iter.GetBundleName().c_str());
898 loadExistData_.emplace(iter.GetBundleName(), iter);
899 }
900
901 hasLoadAllPreInstallBundleInfosFromDb_ = true;
902 return !preInstallBundleInfos.empty();
903 }
904
ProcessRebootBundleInstall()905 void BMSEventHandler::ProcessRebootBundleInstall()
906 {
907 APP_LOGD("Process reboot bundle install start");
908 #ifdef USE_PRE_BUNDLE_PROFILE
909 if (LoadPreInstallProFile()) {
910 ProcessReBootPreBundleProFileInstall();
911 return;
912 }
913 #else
914 ProcessRebootBundleInstallFromScan();
915 #endif
916 }
917
ProcessReBootPreBundleProFileInstall()918 void BMSEventHandler::ProcessReBootPreBundleProFileInstall()
919 {
920 std::list<std::string> bundleDirs;
921 for (const auto &installInfo : installList_) {
922 APP_LOGD("Process reboot preBundle proFile install %{public}s", installInfo.ToString().c_str());
923 if (uninstallList_.find(installInfo.bundleDir) != uninstallList_.end()) {
924 APP_LOGW("bundle(%{public}s) not allowed installed when reboot", installInfo.bundleDir.c_str());
925 continue;
926 }
927
928 bundleDirs.emplace_back(installInfo.bundleDir);
929 }
930
931 InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
932 }
933
ProcessRebootBundleInstallFromScan()934 void BMSEventHandler::ProcessRebootBundleInstallFromScan()
935 {
936 APP_LOGD("Process reboot bundle install from scan");
937 std::list<std::string> bundleDirs;
938 GetBundleDirFromScan(bundleDirs);
939 InnerProcessRebootBundleInstall(bundleDirs, Constants::AppType::SYSTEM_APP);
940 }
941
InnerProcessRebootBundleInstall(const std::list<std::string> & scanPathList,Constants::AppType appType)942 void BMSEventHandler::InnerProcessRebootBundleInstall(
943 const std::list<std::string> &scanPathList, Constants::AppType appType)
944 {
945 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
946 if (dataMgr == nullptr) {
947 APP_LOGE("DataMgr is nullptr");
948 return;
949 }
950
951 for (auto &scanPathIter : scanPathList) {
952 APP_LOGD("reboot scan bundle path: %{public}s ", scanPathIter.c_str());
953 bool removable = IsPreInstallRemovable(scanPathIter);
954 std::unordered_map<std::string, InnerBundleInfo> infos;
955 if (!ParseHapFiles(scanPathIter, infos) || infos.empty()) {
956 APP_LOGE("obtain bundleinfo failed : %{public}s ", scanPathIter.c_str());
957 continue;
958 }
959
960 auto bundleName = infos.begin()->second.GetBundleName();
961 auto hapVersionCode = infos.begin()->second.GetVersionCode();
962 AddParseInfosToMap(bundleName, infos);
963 auto mapIter = loadExistData_.find(bundleName);
964 if (mapIter == loadExistData_.end()) {
965 APP_LOGD("OTA Install new bundle(%{public}s) by path(%{private}s).",
966 bundleName.c_str(), scanPathIter.c_str());
967 std::vector<std::string> filePaths { scanPathIter };
968 if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
969 APP_LOGE("OTA Install new bundle(%{public}s) error.", bundleName.c_str());
970 }
971
972 continue;
973 }
974
975 APP_LOGD("OTA process bundle(%{public}s) by path(%{private}s).",
976 bundleName.c_str(), scanPathIter.c_str());
977 BundleInfo hasInstalledInfo;
978 auto hasBundleInstalled = dataMgr->GetBundleInfo(
979 bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
980 if (!hasBundleInstalled) {
981 APP_LOGW("app(%{public}s) has been uninstalled and do not OTA install.",
982 bundleName.c_str());
983 continue;
984 }
985
986 if (HotPatchAppProcessing(bundleName)) {
987 APP_LOGD("OTA Install prefab bundle(%{public}s) by path(%{private}s) for hotPath upgrade.",
988 bundleName.c_str(), scanPathIter.c_str());
989 std::vector<std::string> filePaths { scanPathIter };
990 if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
991 APP_LOGE("OTA Install prefab bundle(%{public}s) error.", bundleName.c_str());
992 }
993
994 continue;
995 }
996
997 std::vector<std::string> filePaths;
998 for (auto item : infos) {
999 auto parserModuleNames = item.second.GetModuleNameVec();
1000 if (parserModuleNames.empty()) {
1001 APP_LOGE("module is empty when parser path(%{public}s).", item.first.c_str());
1002 continue;
1003 }
1004
1005 // Used to judge whether the module has been installed.
1006 bool hasModuleInstalled = std::find(
1007 hasInstalledInfo.hapModuleNames.begin(), hasInstalledInfo.hapModuleNames.end(),
1008 parserModuleNames[0]) != hasInstalledInfo.hapModuleNames.end();
1009 if (HasModuleSavedInPreInstalledDb(bundleName, item.first) && !hasModuleInstalled) {
1010 APP_LOGW("module(%{public}s) has been uninstalled and do not OTA install",
1011 parserModuleNames[0].c_str());
1012 continue;
1013 }
1014
1015 // Generally, when the versionCode of Hap is greater than the installed versionCode,
1016 // Except for the uninstalled app, they can be installed or upgraded directly by OTA.
1017 if (hasInstalledInfo.versionCode < hapVersionCode) {
1018 APP_LOGD("OTA update module(%{public}s) by path(%{private}s)",
1019 parserModuleNames[0].c_str(), item.first.c_str());
1020 filePaths.emplace_back(item.first);
1021 }
1022
1023 // The versionCode of Hap is equal to the installed versionCode.
1024 // You can only install new modules by OTA
1025 if (hasInstalledInfo.versionCode == hapVersionCode) {
1026 if (hasModuleInstalled) {
1027 APP_LOGD("module(%{public}s) has been installed and versionCode is same.",
1028 parserModuleNames[0].c_str());
1029 continue;
1030 }
1031
1032 APP_LOGD("OTA install module(%{public}s) by path(%{private}s)",
1033 parserModuleNames[0].c_str(), item.first.c_str());
1034 filePaths.emplace_back(item.first);
1035 }
1036 }
1037
1038 if (filePaths.empty()) {
1039 #ifdef USE_PRE_BUNDLE_PROFILE
1040 UpdateRemovable(bundleName, removable);
1041 #endif
1042 continue;
1043 }
1044
1045 if (!OTAInstallSystemBundle(filePaths, appType, removable)) {
1046 APP_LOGE("OTA bundle(%{public}s) failed", bundleName.c_str());
1047 #ifdef USE_PRE_BUNDLE_PROFILE
1048 UpdateRemovable(bundleName, removable);
1049 #endif
1050 }
1051 }
1052 }
1053
IsHotPatchApp(const std::string & bundleName)1054 bool BMSEventHandler::IsHotPatchApp(const std::string &bundleName)
1055 {
1056 InnerBundleInfo innerBundleInfo;
1057 if (!FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
1058 APP_LOGE("can not get InnerBundleInfo, bundleName=%{public}s", bundleName.c_str());
1059 return false;
1060 }
1061
1062 return innerBundleInfo.CheckSpecialMetaData(HOT_PATCH_METADATA);
1063 }
1064
HotPatchAppProcessing(const std::string & bundleName)1065 bool BMSEventHandler::HotPatchAppProcessing(const std::string &bundleName)
1066 {
1067 if (bundleName.empty()) {
1068 APP_LOGW("bundleName:%{public}s empty", bundleName.c_str());
1069 return false;
1070 }
1071
1072 if (IsHotPatchApp(bundleName)) {
1073 APP_LOGI("get hotpatch meta-data success, bundleName=%{public}s", bundleName.c_str());
1074 SystemBundleInstaller installer;
1075 if (!installer.UninstallSystemBundle(bundleName, true)) {
1076 APP_LOGE("keep data to uninstall app(%{public}s) error", bundleName.c_str());
1077 return false;
1078 }
1079 return true;
1080 }
1081 return false;
1082 }
1083
SaveSystemVersion()1084 void BMSEventHandler::SaveSystemVersion()
1085 {
1086 std::string curSystemVersion;
1087 if (!GetCurSystemVersion(curSystemVersion)) {
1088 APP_LOGE("get currrnet system version fail!");
1089 return;
1090 }
1091
1092 if (curSystemVersion.empty()) {
1093 APP_LOGE("curSystemVersion:%{public}s empty", curSystemVersion.c_str());
1094 return;
1095 }
1096
1097 auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1098 if (bmsPara == nullptr) {
1099 APP_LOGE("bmsPara is nullptr");
1100 return;
1101 }
1102
1103 bmsPara->SaveBmsParam(FINGERPRINT, curSystemVersion);
1104 }
1105
IsSystemUpgrade()1106 bool BMSEventHandler::IsSystemUpgrade()
1107 {
1108 std::string oldSystemVersion;
1109 if (!GetOldSystemVersion(oldSystemVersion)) {
1110 APP_LOGI("get system version from db fail, auto upgrade");
1111 return true;
1112 }
1113 if (oldSystemVersion.empty()) {
1114 APP_LOGI("old system version is empty, auto upgrade");
1115 return true;
1116 }
1117
1118 std::string curSystemVersion;
1119 if (!GetCurSystemVersion(curSystemVersion)) {
1120 APP_LOGI("get currrnet system version fail, auto upgrade");
1121 return true;
1122 }
1123
1124 return oldSystemVersion != curSystemVersion;
1125 }
1126
GetCurSystemVersion(std::string & curSystemVersion)1127 bool BMSEventHandler::GetCurSystemVersion(std::string &curSystemVersion)
1128 {
1129 char firmware[VERSION_LEN] = {0};
1130 int32_t ret = GetParameter(BASE_VERSION_PARAM_NAME.c_str(), Constants::EMPTY_STRING.c_str(), firmware, VERSION_LEN);
1131 if (ret <= 0) {
1132 APP_LOGE("GetParameter failed!");
1133 return false;
1134 }
1135 curSystemVersion = firmware;
1136 return true;
1137 }
1138
GetOldSystemVersion(std::string & oldSystemVersion)1139 bool BMSEventHandler::GetOldSystemVersion(std::string &oldSystemVersion)
1140 {
1141 auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
1142 if (bmsPara == nullptr) {
1143 APP_LOGE("bmsPara is nullptr");
1144 return false;
1145 }
1146
1147 if (!bmsPara->GetBmsParam(FINGERPRINT, oldSystemVersion)) {
1148 APP_LOGE("GetOldSystemVersion failed!");
1149 return false;
1150 }
1151 return true;
1152 }
1153
AddParseInfosToMap(const std::string & bundleName,const std::unordered_map<std::string,InnerBundleInfo> & infos)1154 void BMSEventHandler::AddParseInfosToMap(
1155 const std::string &bundleName, const std::unordered_map<std::string, InnerBundleInfo> &infos)
1156 {
1157 auto hapParseInfoMapIter = hapParseInfoMap_.find(bundleName);
1158 if (hapParseInfoMapIter == hapParseInfoMap_.end()) {
1159 hapParseInfoMap_.emplace(bundleName, infos);
1160 return;
1161 }
1162
1163 auto iterMap = hapParseInfoMapIter->second;
1164 for (auto infoIter : infos) {
1165 iterMap.emplace(infoIter.first, infoIter.second);
1166 }
1167
1168 hapParseInfoMap_.at(bundleName) = iterMap;
1169 }
1170
ProcessRebootBundleUninstall()1171 void BMSEventHandler::ProcessRebootBundleUninstall()
1172 {
1173 APP_LOGD("Reboot scan and OTA uninstall start");
1174 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1175 if (dataMgr == nullptr) {
1176 APP_LOGE("DataMgr is nullptr");
1177 return;
1178 }
1179
1180 for (auto &loadIter : loadExistData_) {
1181 std::string bundleName = loadIter.first;
1182 auto listIter = hapParseInfoMap_.find(bundleName);
1183 if (listIter == hapParseInfoMap_.end()) {
1184 APP_LOGD("OTA uninstall app(%{public}s).", bundleName.c_str());
1185 SystemBundleInstaller installer;
1186 if (!installer.UninstallSystemBundle(bundleName)) {
1187 APP_LOGE("OTA uninstall app(%{public}s) error", bundleName.c_str());
1188 } else {
1189 std::string moduleName;
1190 DeletePreInfoInDb(bundleName, moduleName, true);
1191 }
1192
1193 continue;
1194 }
1195
1196 BundleInfo hasInstalledInfo;
1197 auto hasBundleInstalled = dataMgr->GetBundleInfo(
1198 bundleName, BundleFlag::GET_BUNDLE_DEFAULT, hasInstalledInfo, Constants::ANY_USERID);
1199 if (!hasBundleInstalled) {
1200 APP_LOGW("app(%{public}s) maybe has been uninstall.", bundleName.c_str());
1201 continue;
1202 }
1203
1204 // Check the installed module.
1205 // If the corresponding Hap does not exist, it should be uninstalled.
1206 for (auto moduleName : hasInstalledInfo.hapModuleNames) {
1207 bool hasModuleHapExist = false;
1208 for (auto parserInfoIter : listIter->second) {
1209 auto parserModuleNames = parserInfoIter.second.GetModuleNameVec();
1210 if (!parserModuleNames.empty() && moduleName == parserModuleNames[0]) {
1211 hasModuleHapExist = true;
1212 break;
1213 }
1214 }
1215
1216 if (!hasModuleHapExist) {
1217 APP_LOGD("OTA app(%{public}s) uninstall module(%{public}s).",
1218 bundleName.c_str(), moduleName.c_str());
1219 SystemBundleInstaller installer;
1220 if (!installer.UninstallSystemBundle(bundleName, moduleName)) {
1221 APP_LOGE("OTA app(%{public}s) uninstall module(%{public}s) error.",
1222 bundleName.c_str(), moduleName.c_str());
1223 }
1224 }
1225 }
1226
1227 // Check the preInstall path in Db.
1228 // If the corresponding Hap does not exist, it should be deleted.
1229 auto parserInfoMap = listIter->second;
1230 for (auto preBundlePath : loadIter.second.GetBundlePaths()) {
1231 auto parserInfoIter = parserInfoMap.find(preBundlePath);
1232 if (parserInfoIter != parserInfoMap.end()) {
1233 APP_LOGD("OTA uninstall app(%{public}s) module path(%{private}s) exits.",
1234 bundleName.c_str(), preBundlePath.c_str());
1235 continue;
1236 }
1237
1238 APP_LOGD("OTA app(%{public}s) delete path(%{private}s).",
1239 bundleName.c_str(), preBundlePath.c_str());
1240 DeletePreInfoInDb(bundleName, preBundlePath, false);
1241 }
1242 }
1243
1244 APP_LOGD("Reboot scan and OTA uninstall success");
1245 }
1246
DeletePreInfoInDb(const std::string & bundleName,const std::string & bundlePath,bool bundleLevel)1247 void BMSEventHandler::DeletePreInfoInDb(
1248 const std::string &bundleName, const std::string &bundlePath, bool bundleLevel)
1249 {
1250 APP_LOGD("DeletePreInfoInDb bundle(%{public}s)", bundleName.c_str());
1251 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1252 if (dataMgr == nullptr) {
1253 APP_LOGE("DataMgr is nullptr");
1254 return;
1255 }
1256
1257 PreInstallBundleInfo preInstallBundleInfo;
1258 preInstallBundleInfo.SetBundleName(bundleName);
1259 if (bundleLevel) {
1260 APP_LOGD("DeletePreInfoInDb bundle bundleLevel");
1261 dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1262 return;
1263 }
1264
1265 APP_LOGD("DeletePreInfoInDb bundle not bundleLevel with path(%{private}s)",
1266 bundlePath.c_str());
1267 dataMgr->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo);
1268 preInstallBundleInfo.DeleteBundlePath(bundlePath);
1269 if (preInstallBundleInfo.GetBundlePaths().empty()) {
1270 dataMgr->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1271 } else {
1272 dataMgr->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1273 }
1274 }
1275
HasModuleSavedInPreInstalledDb(const std::string & bundleName,const std::string & bundlePath)1276 bool BMSEventHandler::HasModuleSavedInPreInstalledDb(
1277 const std::string &bundleName, const std::string &bundlePath)
1278 {
1279 auto preInstallIter = loadExistData_.find(bundleName);
1280 if (preInstallIter == loadExistData_.end()) {
1281 APP_LOGE("app(%{public}s) does not save in PreInstalledDb.", bundleName.c_str());
1282 return false;
1283 }
1284
1285 return preInstallIter->second.HasBundlePath(bundlePath);
1286 }
1287
OTAInstallSystemBundle(const std::vector<std::string> & filePaths,Constants::AppType appType,bool removable)1288 bool BMSEventHandler::OTAInstallSystemBundle(
1289 const std::vector<std::string> &filePaths,
1290 Constants::AppType appType,
1291 bool removable)
1292 {
1293 if (filePaths.empty()) {
1294 APP_LOGE("File path is empty");
1295 return false;
1296 }
1297
1298 InstallParam installParam;
1299 installParam.isPreInstallApp = true;
1300 installParam.noSkipsKill = false;
1301 installParam.needSendEvent = false;
1302 installParam.installFlag = InstallFlag::REPLACE_EXISTING;
1303 installParam.removable = removable;
1304 installParam.needSavePreInstallInfo = true;
1305 installParam.copyHapToInstallPath = false;
1306 SystemBundleInstaller installer;
1307 return installer.OTAInstallSystemBundle(filePaths, installParam, appType);
1308 }
1309
CheckAndParseHapFiles(const std::string & hapFilePath,bool isPreInstallApp,std::unordered_map<std::string,InnerBundleInfo> & infos)1310 bool BMSEventHandler::CheckAndParseHapFiles(
1311 const std::string &hapFilePath,
1312 bool isPreInstallApp,
1313 std::unordered_map<std::string, InnerBundleInfo> &infos)
1314 {
1315 std::unique_ptr<BundleInstallChecker> bundleInstallChecker =
1316 std::make_unique<BundleInstallChecker>();
1317 std::vector<std::string> hapFilePathVec { hapFilePath };
1318 std::vector<std::string> realPaths;
1319 auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
1320 if (ret != ERR_OK) {
1321 APP_LOGE("File path %{public}s invalid", hapFilePath.c_str());
1322 return false;
1323 }
1324
1325 ret = bundleInstallChecker->CheckSysCap(realPaths);
1326 if (ret != ERR_OK) {
1327 APP_LOGE("hap(%{public}s) syscap check failed", hapFilePath.c_str());
1328 return false;
1329 }
1330
1331 std::vector<Security::Verify::HapVerifyResult> hapVerifyResults;
1332 ret = bundleInstallChecker->CheckMultipleHapsSignInfo(realPaths, hapVerifyResults);
1333 if (ret != ERR_OK) {
1334 APP_LOGE("CheckMultipleHapsSignInfo %{public}s failed", hapFilePath.c_str());
1335 return false;
1336 }
1337
1338 InstallCheckParam checkParam;
1339 checkParam.isPreInstallApp = isPreInstallApp;
1340 if (isPreInstallApp) {
1341 checkParam.appType = Constants::AppType::SYSTEM_APP;
1342 }
1343
1344 ret = bundleInstallChecker->ParseHapFiles(
1345 realPaths, checkParam, hapVerifyResults, infos);
1346 if (ret != ERR_OK) {
1347 APP_LOGE("parse haps file(%{public}s) failed", hapFilePath.c_str());
1348 return false;
1349 }
1350
1351 ret = bundleInstallChecker->CheckAppLabelInfo(infos);
1352 if (ret != ERR_OK) {
1353 APP_LOGE("Check APP label failed %{public}d", ret);
1354 return false;
1355 }
1356
1357 // set hapPath
1358 std::for_each(infos.begin(), infos.end(), [](auto &item) {
1359 item.second.SetModuleHapPath(item.first);
1360 });
1361
1362 return true;
1363 }
1364
ParseHapFiles(const std::string & hapFilePath,std::unordered_map<std::string,InnerBundleInfo> & infos)1365 bool BMSEventHandler::ParseHapFiles(
1366 const std::string &hapFilePath,
1367 std::unordered_map<std::string, InnerBundleInfo> &infos)
1368 {
1369 std::vector<std::string> hapFilePathVec { hapFilePath };
1370 std::vector<std::string> realPaths;
1371 auto ret = BundleUtil::CheckFilePath(hapFilePathVec, realPaths);
1372 if (ret != ERR_OK) {
1373 APP_LOGE("File path %{public}s invalid", hapFilePath.c_str());
1374 return false;
1375 }
1376
1377 BundleParser bundleParser;
1378 for (auto realPath : realPaths) {
1379 InnerBundleInfo innerBundleInfo;
1380 ret = bundleParser.Parse(realPath, innerBundleInfo);
1381 if (ret != ERR_OK) {
1382 APP_LOGE("Parse bundle info failed, error: %{public}d", ret);
1383 continue;
1384 }
1385
1386 infos.emplace(realPath, innerBundleInfo);
1387 }
1388
1389 if (infos.empty()) {
1390 APP_LOGE("Parse hap(%{public}s) empty ", hapFilePath.c_str());
1391 return false;
1392 }
1393
1394 return true;
1395 }
1396
IsPreInstallRemovable(const std::string & path)1397 bool BMSEventHandler::IsPreInstallRemovable(const std::string &path)
1398 {
1399 #ifdef USE_PRE_BUNDLE_PROFILE
1400 if (!HasPreInstallProfile()) {
1401 return false;
1402 }
1403
1404 if (!hasLoadPreInstallProFile_) {
1405 APP_LOGE("Not load preInstall proFile or release.");
1406 return false;
1407 }
1408
1409 if (path.empty() || installList_.empty()) {
1410 APP_LOGE("path or installList is empty.");
1411 return false;
1412 }
1413 auto installInfo = std::find_if(installList_.begin(), installList_.end(),
1414 [path](const auto &installInfo) {
1415 return installInfo.bundleDir == path;
1416 });
1417 if (installInfo != installList_.end()) {
1418 return (*installInfo).removable;
1419 }
1420 return true;
1421 #else
1422 return false;
1423 #endif
1424 }
1425
GetPreInstallCapability(PreBundleConfigInfo & preBundleConfigInfo)1426 bool BMSEventHandler::GetPreInstallCapability(PreBundleConfigInfo &preBundleConfigInfo)
1427 {
1428 if (!hasLoadPreInstallProFile_) {
1429 APP_LOGE("Not load preInstall proFile or release.");
1430 return false;
1431 }
1432
1433 if (preBundleConfigInfo.bundleName.empty() || installListCapabilities_.empty()) {
1434 APP_LOGE("BundleName or installListCapabilities is empty.");
1435 return false;
1436 }
1437
1438 auto iter = installListCapabilities_.find(preBundleConfigInfo);
1439 if (iter == installListCapabilities_.end()) {
1440 APP_LOGE("BundleName(%{public}s) no has preinstall capability.",
1441 preBundleConfigInfo.bundleName.c_str());
1442 return false;
1443 }
1444
1445 preBundleConfigInfo = *iter;
1446 return true;
1447 }
1448
1449 #ifdef USE_PRE_BUNDLE_PROFILE
UpdateRemovable(const std::string & bundleName,bool removable)1450 void BMSEventHandler::UpdateRemovable(const std::string &bundleName, bool removable)
1451 {
1452 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1453 if (dataMgr == nullptr) {
1454 APP_LOGE("DataMgr is nullptr");
1455 return;
1456 }
1457
1458 dataMgr->UpdateRemovable(bundleName, removable);
1459 }
1460
UpdateAllPrivilegeCapability()1461 void BMSEventHandler::UpdateAllPrivilegeCapability()
1462 {
1463 for (const auto &preBundleConfigInfo : installListCapabilities_) {
1464 UpdatePrivilegeCapability(preBundleConfigInfo);
1465 }
1466 }
1467
UpdatePrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)1468 void BMSEventHandler::UpdatePrivilegeCapability(
1469 const PreBundleConfigInfo &preBundleConfigInfo)
1470 {
1471 auto &bundleName = preBundleConfigInfo.bundleName;
1472 InnerBundleInfo innerBundleInfo;
1473 if (!FetchInnerBundleInfo(bundleName, innerBundleInfo)) {
1474 APP_LOGW("App(%{public}s) is not installed.", bundleName.c_str());
1475 return;
1476 }
1477
1478 if (!MatchSignature(preBundleConfigInfo, innerBundleInfo.GetCertificateFingerprint())) {
1479 APP_LOGW("App(%{public}s) signature verify failed", bundleName.c_str());
1480 return;
1481 }
1482
1483 UpdateTrustedPrivilegeCapability(preBundleConfigInfo);
1484 }
1485
MatchSignature(const PreBundleConfigInfo & configInfo,const std::string & signature)1486 bool BMSEventHandler::MatchSignature(
1487 const PreBundleConfigInfo &configInfo, const std::string &signature)
1488 {
1489 if (configInfo.appSignature.empty()) {
1490 APP_LOGW("appSignature is empty");
1491 return false;
1492 }
1493
1494 return std::find(configInfo.appSignature.begin(),
1495 configInfo.appSignature.end(), signature) != configInfo.appSignature.end();
1496 }
1497
UpdateTrustedPrivilegeCapability(const PreBundleConfigInfo & preBundleConfigInfo)1498 void BMSEventHandler::UpdateTrustedPrivilegeCapability(
1499 const PreBundleConfigInfo &preBundleConfigInfo)
1500 {
1501 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1502 if (dataMgr == nullptr) {
1503 APP_LOGE("DataMgr is nullptr");
1504 return;
1505 }
1506
1507 ApplicationInfo appInfo;
1508 appInfo.keepAlive = preBundleConfigInfo.keepAlive;
1509 appInfo.singleton = preBundleConfigInfo.singleton;
1510 appInfo.runningResourcesApply = preBundleConfigInfo.runningResourcesApply;
1511 appInfo.associatedWakeUp = preBundleConfigInfo.associatedWakeUp;
1512 for (const auto &event : preBundleConfigInfo.allowCommonEvent) {
1513 appInfo.allowCommonEvent.emplace_back(event);
1514 }
1515
1516 dataMgr->UpdatePrivilegeCapability(preBundleConfigInfo.bundleName, appInfo);
1517 }
1518 #endif
1519
FetchInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & innerBundleInfo)1520 bool BMSEventHandler::FetchInnerBundleInfo(
1521 const std::string &bundleName, InnerBundleInfo &innerBundleInfo)
1522 {
1523 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1524 if (dataMgr == nullptr) {
1525 APP_LOGE("DataMgr is nullptr");
1526 return false;
1527 }
1528
1529 return dataMgr->FetchInnerBundleInfo(bundleName, innerBundleInfo);
1530 }
1531 } // namespace AppExecFwk
1532 } // namespace OHOS
1533