• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "base_bundle_installer.h"
17 
18 #include <algorithm>
19 #include <fcntl.h>
20 #include <fstream>
21 #include <sys/stat.h>
22 #include <sstream>
23 
24 #include "account_helper.h"
25 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
26 #include "aging/bundle_aging_mgr.h"
27 #endif
28 #include "aot/aot_handler.h"
29 #include "app_control_constants.h"
30 #include "app_mgr_client.h"
31 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
32 #include "default_app_mgr.h"
33 #endif
34 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
35 #include "quick_fix/app_quick_fix.h"
36 #include "quick_fix/inner_app_quick_fix.h"
37 #include "quick_fix/quick_fix_data_mgr.h"
38 #include "quick_fix/quick_fix_switcher.h"
39 #include "quick_fix/quick_fix_deleter.h"
40 #endif
41 #include "ability_manager_helper.h"
42 #include "app_log_tag_wrapper.h"
43 #include "app_provision_info_manager.h"
44 #include "bms_extension_data_mgr.h"
45 #include "bundle_clone_installer.h"
46 #include "bundle_permission_mgr.h"
47 #include "bundle_parser.h"
48 #include "bundle_resource_helper.h"
49 #include "bundle_util.h"
50 #include "code_protect_bundle_info.h"
51 #include "datetime_ex.h"
52 #include "driver_installer.h"
53 #include "hitrace_meter.h"
54 #include "installd_client.h"
55 #include "install_exception_mgr.h"
56 #include "on_demand_install_data_mgr.h"
57 #include "parameter.h"
58 #include "parameters.h"
59 #include "perf_profile.h"
60 #include "scope_guard.h"
61 #include "utd_handler.h"
62 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
63 #include "bundle_overlay_data_manager.h"
64 #include "bundle_overlay_install_checker.h"
65 #endif
66 #ifdef WEBVIEW_ENABLE
67 #include "app_fwk_update_client.h"
68 #endif
69 
70 #ifdef STORAGE_SERVICE_ENABLE
71 #include "storage_manager_proxy.h"
72 #endif
73 #include "iservice_registry.h"
74 #include "inner_bundle_clone_common.h"
75 #include "inner_patch_info.h"
76 #include "patch_data_mgr.h"
77 
78 namespace OHOS {
79 namespace AppExecFwk {
80 using namespace OHOS::Security;
81 namespace {
82 constexpr const char* DATA_PRELOAD_APP = "/data/preload/app/";
83 constexpr const char* COMPILE_SDK_TYPE_OPEN_HARMONY = "OpenHarmony";
84 constexpr const char* LOG = "log";
85 constexpr const char* HSP_VERSION_PREFIX = "v";
86 constexpr const char* PRE_INSTALL_HSP_PATH = "/shared_bundles/";
87 constexpr const char* APP_INSTALL_PATH = "/data/app/el1/bundle";
88 constexpr const char* BMS_SERVICE_PATH = "/data/service";
89 constexpr const char* APP_INSTALL_SANDBOX_PATH = "/data/bms_app_install/";
90 const int64_t FIVE_MB = 1024 * 1024 * 5; // 5MB
91 constexpr const char* DEBUG_APP_IDENTIFIER = "DEBUG_LIB_ID";
92 constexpr const char* SKILL_URI_SCHEME_HTTPS = "https";
93 constexpr const char* LIBS_TMP = "libs_tmp";
94 constexpr const char* PRIVILEGE_ALLOW_HDC_INSTALL = "AllowHdcInstall";
95 constexpr const char* KEY_STORAGE_SIZE = "storageSize";
96 
97 #ifdef STORAGE_SERVICE_ENABLE
98 #ifdef QUOTA_PARAM_SET_ENABLE
99 constexpr const char* SYSTEM_PARAM_ATOMICSERVICE_DATASIZE_THRESHOLD =
100     "persist.sys.bms.aging.policy.atomicservice.datasize.threshold";
101 constexpr int32_t THRESHOLD_VAL_LEN = 20;
102 #endif // QUOTA_PARAM_SET_ENABLE
103 constexpr int32_t STORAGE_MANAGER_MANAGER_ID = 5003;
104 #endif // STORAGE_SERVICE_ENABLE
105 constexpr int16_t ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET = 200;
106 constexpr int8_t SINGLE_HSP_VERSION = 1;
107 constexpr int8_t USER_MODE = 0;
108 constexpr int8_t ROOT_MODE = 1;
109 constexpr const char* BMS_KEY_SHELL_UID = "const.product.shell.uid";
110 constexpr const char* IS_ROOT_MODE_PARAM = "const.debuggable";
111 constexpr const char* BMS_ACTIVATION_LOCK = "persist.bms.activation-lock";
112 constexpr const char* APPSPAWN_PRELOAD_ARKWEB_ENGINE = "const.startup.appspawn.preload.arkwebEngine";
113 constexpr const char* BMS_TRUE = "true";
114 constexpr const char* BMS_FALSE = "false";
115 constexpr int8_t BMS_ACTIVATION_LOCK_VAL_LEN = 20;
116 constexpr const char* DATA_EXTENSION_PATH = "/extension/";
117 const char* INSTALL_SOURCE_UNKNOWN = "unknown";
118 const char* ARK_WEB_BUNDLE_NAME_PARAM = "persist.arkwebcore.package_name";
119 const char* OLD_ARK_WEB_BUNDLE_NAME = "com.ohos.nweb";
120 const char* NEW_ARK_WEB_BUNDLE_NAME = "com.ohos.arkwebcore";
121 
GetHapPath(const InnerBundleInfo & info,const std::string & moduleName)122 std::string GetHapPath(const InnerBundleInfo &info, const std::string &moduleName)
123 {
124     std::string fileSuffix = ServiceConstants::INSTALL_FILE_SUFFIX;
125     auto moduleInfo = info.GetInnerModuleInfoByModuleName(moduleName);
126     if (moduleInfo && moduleInfo->distro.moduleType == Profile::MODULE_TYPE_SHARED) {
127         LOG_D(BMS_TAG_INSTALLER, "The module(%{public}s) is shared", moduleName.c_str());
128         fileSuffix = ServiceConstants::HSP_FILE_SUFFIX;
129     }
130 
131     return info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR + moduleName + fileSuffix;
132 }
133 
GetHapPath(const InnerBundleInfo & info)134 std::string GetHapPath(const InnerBundleInfo &info)
135 {
136     return GetHapPath(info, info.GetModuleName(info.GetCurrentModulePackage()));
137 }
138 
BuildTempNativeLibraryPath(const std::string & nativeLibraryPath)139 std::string BuildTempNativeLibraryPath(const std::string &nativeLibraryPath)
140 {
141     auto position = nativeLibraryPath.find(ServiceConstants::PATH_SEPARATOR);
142     if (position == std::string::npos) {
143         return nativeLibraryPath;
144     }
145 
146     auto prefixPath = nativeLibraryPath.substr(0, position);
147     auto suffixPath = nativeLibraryPath.substr(position);
148     return prefixPath + ServiceConstants::TMP_SUFFIX + suffixPath;
149 }
150 } // namespace
151 
BaseBundleInstaller()152 BaseBundleInstaller::BaseBundleInstaller()
153     : bundleInstallChecker_(std::make_unique<BundleInstallChecker>()) {}
154 
~BaseBundleInstaller()155 BaseBundleInstaller::~BaseBundleInstaller()
156 {
157     bundlePaths_.clear();
158     BundleUtil::DeleteTempDirs(toDeleteTempHapPath_);
159     toDeleteTempHapPath_.clear();
160     signatureFileTmpMap_.clear();
161 }
162 
InstallBundle(const std::string & bundlePath,const InstallParam & installParam,const Constants::AppType appType)163 ErrCode BaseBundleInstaller::InstallBundle(
164     const std::string &bundlePath, const InstallParam &installParam, const Constants::AppType appType)
165 {
166     std::vector<std::string> bundlePaths { bundlePath };
167     return InstallBundle(bundlePaths, installParam, appType);
168 }
169 
SendStartInstallNotify(const InstallParam & installParam,const std::unordered_map<std::string,InnerBundleInfo> & infos)170 void BaseBundleInstaller::SendStartInstallNotify(const InstallParam &installParam,
171     const std::unordered_map<std::string, InnerBundleInfo> &infos)
172 {
173     if (!installParam.needSendEvent) {
174         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "SendStartInstallNotify needSendEvent is false");
175         return;
176     }
177     if (bundleName_.empty()) {
178         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "SendStartInstallNotify bundleName is empty");
179         return;
180     }
181     bool isAppExist;
182     if (InitDataMgr()) {
183         isAppExist = dataMgr_->HasUserInstallInBundle(bundleName_, userId_);
184     }
185     for (const auto &item : infos) {
186         LOG_D(BMS_TAG_INSTALLER, "SendStartInstallNotify %{public}s  %{public}s %{public}s %{public}s",
187             bundleName_.c_str(), item.second.GetCurModuleName().c_str(),
188             item.second.GetAppId().c_str(), item.second.GetAppIdentifier().c_str());
189         NotifyBundleEvents installRes = {
190             .isAppUpdate = isAppExist,
191             .type = NotifyType::START_INSTALL,
192             .bundleName = bundleName_,
193             .modulePackage = item.second.GetCurModuleName(),
194             .appId = item.second.GetAppId(),
195             .appIdentifier = item.second.GetAppIdentifier()
196         };
197         NotifyBundleStatus(installRes);
198     }
199 }
200 
InstallBundle(const std::vector<std::string> & bundlePaths,const InstallParam & installParam,const Constants::AppType appType)201 ErrCode BaseBundleInstaller::InstallBundle(
202     const std::vector<std::string> &bundlePaths, const InstallParam &installParam, const Constants::AppType appType)
203 {
204     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
205     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "begin to process bundle install");
206     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
207     int32_t uid = Constants::INVALID_UID;
208     ErrCode result = ProcessBundleInstall(bundlePaths, installParam, appType, uid, false);
209     if (result != ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON && result != ERR_OK &&
210         installParam.isDataPreloadHap && GetUserId(installParam.userId) == Constants::DEFAULT_USERID) {
211         LOG_E(BMS_TAG_INSTALLER, "set parameter BMS_DATA_PRELOAD false");
212         OHOS::system::SetParameter(ServiceConstants::BMS_DATA_PRELOAD, BMS_FALSE);
213     }
214     CheckPreBundleRecoverResult(result);
215     if (installParam.needSendEvent && dataMgr_ && !bundleName_.empty()) {
216         NotifyBundleEvents installRes = {
217             .isModuleUpdate = isModuleUpdate_,
218             .type = GetNotifyType(),
219             .resultCode = result,
220             .accessTokenId = accessTokenId_,
221             .uid = uid,
222             .bundleType = static_cast<int32_t>(bundleType_),
223             .atomicServiceModuleUpgrade = atomicServiceModuleUpgrade_,
224             .bundleName = bundleName_,
225             .modulePackage = moduleName_,
226             .abilityName = mainAbility_,
227             .appDistributionType = appDistributionType_,
228             .crossAppSharedConfig = isBundleCrossAppSharedConfig_
229         };
230         if (installParam.allUser || IsDriverForAllUser(bundleName_) ||
231             IsEnterpriseForAllUser(installParam, bundleName_)) {
232             AddBundleStatus(installRes);
233         } else {
234             NotifyBundleStatus(installRes);
235         }
236     }
237     if (result == ERR_OK) {
238         OnSingletonChange(installParam.GetKillProcess());
239     } else {
240         RestoreHaps(bundlePaths, installParam);
241     }
242     if (!bundlePaths.empty()) {
243         SendBundleSystemEvent(
244             bundleName_.empty() ? bundlePaths[0] : bundleName_,
245             ((isAppExist_ && hasInstalledInUser_) ? BundleEventType::UPDATE : BundleEventType::INSTALL),
246             installParam, sysEventInfo_.preBundleScene, result);
247     }
248     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
249     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "InstallBundle finished -n %{public}s -u %{public}d",
250         bundleName_.c_str(), installParam.userId);
251     return result;
252 }
253 
InstallBundleByBundleName(const std::string & bundleName,const InstallParam & installParam)254 ErrCode BaseBundleInstaller::InstallBundleByBundleName(
255     const std::string &bundleName, const InstallParam &installParam)
256 {
257     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "InstallBundleByBundleName -n %{public}s", bundleName.c_str());
258     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
259 
260     int32_t uid = Constants::INVALID_UID;
261     ErrCode result = ProcessInstallBundleByBundleName(bundleName, installParam, uid);
262     if (installParam.needSendEvent && dataMgr_ && !bundleName.empty()) {
263         NotifyBundleEvents installRes = {
264             .type = NotifyType::INSTALL,
265             .resultCode = result,
266             .accessTokenId = accessTokenId_,
267             .uid = uid,
268             .bundleType = static_cast<int32_t>(bundleType_),
269             .atomicServiceModuleUpgrade = atomicServiceModuleUpgrade_,
270             .bundleName = bundleName,
271             .appDistributionType = appDistributionType_,
272             .crossAppSharedConfig = isBundleCrossAppSharedConfig_
273         };
274         if (installParam.concentrateSendEvent) {
275             AddNotifyBundleEvents(installRes);
276         } else if (IsDriverForAllUser(bundleName) || IsEnterpriseForAllUser(installParam, bundleName)) {
277             AddBundleStatus(installRes);
278         } else {
279             NotifyBundleStatus(installRes);
280         }
281     }
282 
283     SendBundleSystemEvent(
284         bundleName,
285         BundleEventType::INSTALL,
286         installParam,
287         installParam.isPreInstallApp ? InstallScene::CREATE_USER : InstallScene::NORMAL,
288         result);
289     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
290     LOG_I(BMS_TAG_INSTALLER, "finish install %{public}s resultCode: %{public}d", bundleName.c_str(), result);
291     return result;
292 }
293 
Recover(const std::string & bundleName,const InstallParam & installParam)294 ErrCode BaseBundleInstaller::Recover(
295     const std::string &bundleName, const InstallParam &installParam)
296 {
297     LOG_I(BMS_TAG_INSTALLER, "begin to process bundle recover by bundleName, which is %{public}s", bundleName.c_str());
298     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
299     int32_t userId = GetUserId(installParam.userId);
300     if (IsAppInBlocklist(bundleName, userId)) {
301         return ERR_APPEXECFWK_INSTALL_APP_IN_BLOCKLIST;
302     }
303     int32_t uid = Constants::INVALID_UID;
304     ErrCode result = ProcessRecover(bundleName, installParam, uid);
305     if (installParam.needSendEvent && dataMgr_) {
306         NotifyBundleEvents installRes = {
307             .type = NotifyType::INSTALL,
308             .resultCode = result,
309             .accessTokenId = accessTokenId_,
310             .uid = uid,
311             .bundleType = static_cast<int32_t>(bundleType_),
312             .bundleName = bundleName,
313             .appDistributionType = appDistributionType_,
314             .crossAppSharedConfig = isBundleCrossAppSharedConfig_,
315             .isRecover = true
316         };
317         NotifyBundleStatus(installRes);
318     }
319 
320     auto recoverInstallParam = installParam;
321     recoverInstallParam.isPreInstallApp = true;
322     SendBundleSystemEvent(
323         bundleName,
324         BundleEventType::RECOVER,
325         recoverInstallParam,
326         sysEventInfo_.preBundleScene,
327         result);
328     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
329     LOG_D(BMS_TAG_INSTALLER, "finish to process %{public}s bundle recover", bundleName.c_str());
330     return result;
331 }
332 
UninstallBundle(const std::string & bundleName,const InstallParam & installParam)333 ErrCode BaseBundleInstaller::UninstallBundle(const std::string &bundleName, const InstallParam &installParam)
334 {
335     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
336     CheckSystemFreeSizeAndClean();
337     LOG_I(BMS_TAG_INSTALLER, "begin to process %{public}s bundle uninstall", bundleName.c_str());
338     PerfProfile::GetInstance().SetBundleUninstallStartTime(GetTickCount());
339 
340     std::string developerId = GetDeveloperId(bundleName);
341     std::string assetAccessGroups = GetAssetAccessGroups(bundleName);
342 
343     // uninstall all sandbox app before
344     UninstallAllSandboxApps(bundleName, installParam.userId);
345 
346     int32_t uid = Constants::INVALID_UID;
347     bool isUninstalledFromBmsExtension = false;
348     ErrCode result = ProcessBundleUninstall(bundleName, installParam, uid);
349     if (result == ERR_APPEXECFWK_UNINSTALL_STATE_NOT_ALLOW) {
350         CheckBundleNameAndStratAbility(bundleName, appIdentifier_);
351     }
352     if (result == ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE) {
353         ErrCode bmsExtensionResult = UninstallBundleFromBmsExtension(bundleName);
354         if (bmsExtensionResult == ERR_OK) {
355             isUninstalledFromBmsExtension = true;
356             result = ERR_OK;
357         } else if (bmsExtensionResult == ERR_APPEXECFWK_UNINSTALL_DISPOSED_RULE_FAILED) {
358             result = ERR_APPEXECFWK_UNINSTALL_DISPOSED_RULE_FAILED;
359         }
360     }
361 
362     if (!installParam.isKeepData && (result == ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE ||
363         result == ERR_APPEXECFWK_USER_NOT_INSTALL_HAP) &&
364         DeleteUninstallBundleInfoFromDb(bundleName)) {
365         LOG_I(BMS_TAG_INSTALLER, "del uninstalled bundle %{public}s dir and info", bundleName.c_str());
366         return ERR_OK;
367     }
368 
369     if (result == ERR_OK) {
370         UtdHandler::UninstallUtdAsync(bundleName, userId_);
371 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
372         if (!installParam.isRemoveUser) {
373             DefaultAppMgr::GetInstance().HandleUninstallBundle(userId_, bundleName);
374         }
375 #endif
376     }
377 
378     if (installParam.needSendEvent && dataMgr_) {
379         NotifyBundleEvents installRes = {
380             .isAgingUninstall = installParam.isAgingUninstall,
381             .isBmsExtensionUninstalled = isUninstalledFromBmsExtension,
382             .type = NotifyType::UNINSTALL_BUNDLE,
383             .resultCode = result,
384             .accessTokenId = accessTokenId_,
385             .uid = uid,
386             .bundleType = static_cast<int32_t>(bundleType_),
387             .bundleName = bundleName,
388             .appId = uninstallBundleAppId_,
389             .developerId = developerId,
390             .assetAccessGroups = assetAccessGroups,
391             .keepData = installParam.isKeepData,
392             .crossAppSharedConfig = isBundleCrossAppSharedConfig_
393         };
394 
395         if (installParam.concentrateSendEvent) {
396             AddNotifyBundleEvents(installRes);
397         } else {
398             NotifyBundleStatus(installRes);
399         }
400     }
401     SendBundleSystemEvent(bundleName, BundleEventType::UNINSTALL, installParam, sysEventInfo_.preBundleScene, result);
402     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
403     LOG_D(BMS_TAG_INSTALLER, "finish to process %{public}s bundle uninstall", bundleName.c_str());
404     return result;
405 }
406 
407 
CheckUninstallInnerBundleInfo(const InnerBundleInfo & info,const std::string & bundleName)408 ErrCode BaseBundleInstaller::CheckUninstallInnerBundleInfo(const InnerBundleInfo &info, const std::string &bundleName)
409 {
410     if (!info.IsRemovable()) {
411         LOG_NOFUNC_E(BMS_TAG_INSTALLER, "uninstall system app");
412         return ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR;
413     }
414     if (!info.GetUninstallState()) {
415         LOG_E(BMS_TAG_INSTALLER, "bundle : %{public}s can not be uninstalled, uninstallState : %{public}d",
416             bundleName.c_str(), info.GetUninstallState());
417         return ERR_APPEXECFWK_UNINSTALL_STATE_NOT_ALLOW;
418     }
419     if (info.GetApplicationBundleType() != BundleType::SHARED) {
420         LOG_E(BMS_TAG_INSTALLER, "uninstall bundle is not shared library");
421         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_NOT_EXIST;
422     }
423     return ERR_OK;
424 }
425 
UninstallBundleByUninstallParam(const UninstallParam & uninstallParam)426 ErrCode BaseBundleInstaller::UninstallBundleByUninstallParam(const UninstallParam &uninstallParam)
427 {
428     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "begin to process cross-app %{public}s uninstall",
429         uninstallParam.bundleName.c_str());
430     const std::string &bundleName = uninstallParam.bundleName;
431     int32_t versionCode = uninstallParam.versionCode;
432     if (bundleName.empty()) {
433         LOG_E(BMS_TAG_INSTALLER, "uninstall bundle name or module name empty");
434         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_NOT_EXIST;
435     }
436     if (!InitDataMgr()) {
437         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
438     }
439     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
440     std::lock_guard lock {mtx};
441     bool isAppExist = false;
442     InnerBundleInfo info;
443     if (!InitTempBundleFromCache(info, isAppExist, bundleName) || !isAppExist) {
444         LOG_E(BMS_TAG_INSTALLER, "uninstall bundle info missing");
445         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_NOT_EXIST;
446     }
447     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); });
448     ErrCode ret = CheckUninstallInnerBundleInfo(info, bundleName);
449     if (ret != ERR_OK) {
450         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "CheckUninstallInnerBundleInfo failed, errcode: %{public}d", ret);
451         return ret;
452     }
453     if (dataMgr_->CheckHspVersionIsRelied(versionCode, info)) {
454         LOG_E(BMS_TAG_INSTALLER, "uninstall shared library is relied");
455         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_RELIED;
456     }
457     // if uninstallParam do not contain versionCode, versionCode is ALL_VERSIONCODE
458     std::vector<uint32_t> versionCodes = info.GetAllHspVersion();
459     if (versionCode != Constants::ALL_VERSIONCODE &&
460         std::find(versionCodes.begin(), versionCodes.end(), versionCode) == versionCodes.end()) {
461         LOG_E(BMS_TAG_INSTALLER, "input versionCode is not exist");
462         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_NOT_EXIST;
463     }
464     std::string uninstallDir = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName;
465     return UninstallHspAndBundle(info, versionCode, uninstallDir);
466 }
467 
UninstallHspBundle(std::string & uninstallDir,const std::string & bundleName)468 ErrCode BaseBundleInstaller::UninstallHspBundle(std::string &uninstallDir, const std::string &bundleName)
469 {
470     LOG_D(BMS_TAG_INSTALLER, "begin to process hsp bundle %{public}s uninstall", bundleName.c_str());
471     // remove bundle dir first, then delete data in bundle data manager
472     ErrCode errCode;
473     if (!InitDataMgr()) {
474         return ERR_APPEXECFWK_NULL_PTR;
475     }
476      // delete bundle bunlde in data
477     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START)) {
478         LOG_E(BMS_TAG_INSTALLER, "uninstall start failed");
479         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
480     }
481     if ((errCode = InstalldClient::GetInstance()->RemoveDir(uninstallDir)) != ERR_OK) {
482         LOG_E(BMS_TAG_INSTALLER, "delete dir %{public}s failed", uninstallDir.c_str());
483         return errCode;
484     }
485     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_SUCCESS)) {
486         LOG_E(BMS_TAG_INSTALLER, "update uninstall success failed");
487         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
488     }
489     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->DeleteAppProvisionInfo(bundleName)) {
490         LOG_W(BMS_TAG_INSTALLER, "bundleName: %{public}s delete appProvisionInfo failed", bundleName.c_str());
491     }
492     versionCode_ = Constants::ALL_VERSIONCODE;
493     userId_ = Constants::ALL_USERID;
494     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
495     /* remove sign profile from code signature for cross-app hsp */
496     RemoveProfileFromCodeSign(bundleName);
497     return ERR_OK;
498 }
499 
UninstallHspVersion(std::string & uninstallDir,int32_t versionCode,InnerBundleInfo & info)500 ErrCode BaseBundleInstaller::UninstallHspVersion(std::string &uninstallDir, int32_t versionCode, InnerBundleInfo &info)
501 {
502     LOG_D(BMS_TAG_INSTALLER, "begin to process hsp bundle %{public}s uninstall", info.GetBundleName().c_str());
503     // remove bundle dir first, then delete data in innerBundleInfo
504     ErrCode errCode;
505     if (!InitDataMgr()) {
506         return ERR_APPEXECFWK_NULL_PTR;
507     }
508     if (!dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::UNINSTALL_START)) {
509         LOG_E(BMS_TAG_INSTALLER, "uninstall start failed");
510         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
511     }
512     if ((errCode = InstalldClient::GetInstance()->RemoveDir(uninstallDir)) != ERR_OK) {
513         LOG_E(BMS_TAG_INSTALLER, "delete dir %{public}s failed", uninstallDir.c_str());
514         return errCode;
515     }
516     if (!dataMgr_->RemoveHspModuleByVersionCode(versionCode, info)) {
517         LOG_E(BMS_TAG_INSTALLER, "remove hsp module by versionCode failed");
518         return ERR_APPEXECFWK_RMV_HSP_BY_VERSION_ERROR;
519     }
520     if (!dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::INSTALL_SUCCESS)) {
521         LOG_E(BMS_TAG_INSTALLER, "update install success failed");
522         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
523     }
524     versionCode_ = Constants::ALL_VERSIONCODE;
525     userId_ = Constants::ALL_USERID;
526     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
527     return ERR_OK;
528 }
529 
UninstallHspAndBundle(InnerBundleInfo & info,int32_t & versionCode,std::string & uninstallDir)530 ErrCode BaseBundleInstaller::UninstallHspAndBundle(InnerBundleInfo &info, int32_t &versionCode,
531     std::string &uninstallDir)
532 {
533     std::vector<uint32_t> versionCodes = info.GetAllHspVersion();
534     InstallParam installParam;
535     ErrCode ret = ERR_OK;
536     if ((versionCodes.size() > SINGLE_HSP_VERSION && versionCode == Constants::ALL_VERSIONCODE) ||
537         versionCodes.size() == SINGLE_HSP_VERSION) {
538         ErrCode ret = UninstallHspBundle(uninstallDir, info.GetBundleName());
539         SendBundleSystemEvent(info.GetBundleName(), BundleEventType::UNINSTALL, installParam,
540             sysEventInfo_.preBundleScene, ret);
541         return ret;
542     }
543     uninstallDir += std::string(ServiceConstants::PATH_SEPARATOR) +
544         HSP_VERSION_PREFIX + std::to_string(versionCode);
545     ret = UninstallHspVersion(uninstallDir, versionCode, info);
546     SendBundleSystemEvent(info.GetBundleName(), BundleEventType::UNINSTALL, installParam,
547         sysEventInfo_.preBundleScene, ret);
548     return ret;
549 }
550 
UninstallBundle(const std::string & bundleName,const std::string & modulePackage,const InstallParam & installParam)551 ErrCode BaseBundleInstaller::UninstallBundle(
552     const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam)
553 {
554     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
555     CheckSystemFreeSizeAndClean();
556     LOG_I(BMS_TAG_INSTALLER, "begin to process %{public}s module in %{public}s uninstall",
557         modulePackage.c_str(), bundleName.c_str());
558     PerfProfile::GetInstance().SetBundleUninstallStartTime(GetTickCount());
559 
560     std::string developerId;
561     std::string assetAccessGroups;
562     std::vector<std::string> moduleNames;
563     GetModuleNames(bundleName, moduleNames);
564     if (moduleNames.size() == 1) {
565         developerId = GetDeveloperId(bundleName);
566         assetAccessGroups = GetAssetAccessGroups(bundleName);
567     }
568     // uninstall all sandbox app before
569     UninstallAllSandboxApps(bundleName, installParam.userId);
570 
571     int32_t uid = Constants::INVALID_UID;
572     bool isUninstalledFromBmsExtension = false;
573     ErrCode result = ProcessBundleUninstall(bundleName, modulePackage, installParam, uid);
574     if (result == ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE) {
575         ErrCode bmsExtensionResult = UninstallBundleFromBmsExtension(bundleName);
576         if (bmsExtensionResult == ERR_OK) {
577             isUninstalledFromBmsExtension = true;
578             result = ERR_OK;
579         } else if (bmsExtensionResult == ERR_APPEXECFWK_UNINSTALL_DISPOSED_RULE_FAILED) {
580             result = ERR_APPEXECFWK_UNINSTALL_DISPOSED_RULE_FAILED;
581         }
582     }
583     if (installParam.needSendEvent && dataMgr_) {
584         NotifyBundleEvents installRes = {
585             .isAgingUninstall = installParam.isAgingUninstall,
586             .isBmsExtensionUninstalled = isUninstalledFromBmsExtension,
587             .type = NotifyType::UNINSTALL_MODULE,
588             .resultCode = result,
589             .accessTokenId = accessTokenId_,
590             .uid = uid,
591             .bundleType = static_cast<int32_t>(bundleType_),
592             .bundleName = bundleName,
593             .modulePackage = modulePackage,
594             .appId = uninstallBundleAppId_,
595             .developerId = developerId,
596             .assetAccessGroups = assetAccessGroups,
597             .keepData = installParam.isKeepData,
598             .isBundleExist = isBundleExist_,
599             .crossAppSharedConfig = isBundleCrossAppSharedConfig_
600         };
601         NotifyBundleStatus(installRes);
602     }
603 
604     SendBundleSystemEvent(bundleName, BundleEventType::UNINSTALL, installParam, sysEventInfo_.preBundleScene, result);
605     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
606     LOG_D(BMS_TAG_INSTALLER, "finish uninstall %{public}s in %{public}s", modulePackage.c_str(), bundleName.c_str());
607     return result;
608 }
609 
UninstallAppControl(const std::string & appId,int32_t userId)610 bool BaseBundleInstaller::UninstallAppControl(const std::string &appId, int32_t userId)
611 {
612 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
613     std::vector<std::string> appIds;
614     ErrCode ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
615         AppControlConstants::EDM_CALLING, AppControlConstants::APP_DISALLOWED_UNINSTALL, userId, appIds);
616     if (ret != ERR_OK) {
617         LOG_E(BMS_TAG_INSTALLER, "GetAppInstallControlRule failed code:%{public}d", ret);
618         return true;
619     }
620     if (std::find(appIds.begin(), appIds.end(), appId) == appIds.end()) {
621         return true;
622     }
623     LOG_W(BMS_TAG_INSTALLER, "appId is not removable");
624     return false;
625 #else
626     LOG_W(BMS_TAG_INSTALLER, "app control is disable");
627     return true;
628 #endif
629 }
630 
InstallNormalAppControl(const std::string & installAppId,int32_t userId,bool isPreInstallApp)631 ErrCode BaseBundleInstaller::InstallNormalAppControl(
632     const std::string &installAppId,
633     int32_t userId,
634     bool isPreInstallApp)
635 {
636     LOG_D(BMS_TAG_INSTALLER, "InstallNormalAppControl start ");
637 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
638     if (isPreInstallApp) {
639         LOG_D(BMS_TAG_INSTALLER, "the preInstalled app does not support app control feature");
640         return ERR_OK;
641     }
642     std::vector<std::string> allowedAppIds;
643     ErrCode ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
644         AppControlConstants::EDM_CALLING, AppControlConstants::APP_ALLOWED_INSTALL, userId, allowedAppIds);
645     if (ret != ERR_OK) {
646         LOG_E(BMS_TAG_INSTALLER, "GetAppInstallControlRule allowedInstall failed code:%{public}d", ret);
647         return ret;
648     }
649 
650     std::vector<std::string> disallowedAppIds;
651     ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
652         AppControlConstants::EDM_CALLING, AppControlConstants::APP_DISALLOWED_INSTALL, userId, disallowedAppIds);
653     if (ret != ERR_OK) {
654         LOG_E(BMS_TAG_INSTALLER, "GetAppInstallControlRule disallowedInstall failed code:%{public}d", ret);
655         return ret;
656     }
657 
658     // disallowed list and allowed list all empty.
659     if (disallowedAppIds.empty() && allowedAppIds.empty()) {
660         return ERR_OK;
661     }
662 
663     // only allowed list empty.
664     if (allowedAppIds.empty()) {
665         if (std::find(disallowedAppIds.begin(), disallowedAppIds.end(), installAppId) != disallowedAppIds.end()) {
666             LOG_E(BMS_TAG_INSTALLER, "disallowedAppIds:%{public}s is disallow install", installAppId.c_str());
667             return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
668         }
669         return ERR_OK;
670     }
671 
672     // only disallowed list empty.
673     if (disallowedAppIds.empty()) {
674         if (std::find(allowedAppIds.begin(), allowedAppIds.end(), installAppId) == allowedAppIds.end()) {
675             LOG_E(BMS_TAG_INSTALLER, "allowedAppIds:%{public}s is disallow install", installAppId.c_str());
676             return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
677         }
678         return ERR_OK;
679     }
680 
681     // disallowed list and allowed list all not empty.
682     if (std::find(allowedAppIds.begin(), allowedAppIds.end(), installAppId) == allowedAppIds.end()) {
683         LOG_E(BMS_TAG_INSTALLER, "allowedAppIds:%{public}s is disallow install", installAppId.c_str());
684         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
685     } else if (std::find(disallowedAppIds.begin(), disallowedAppIds.end(), installAppId) != disallowedAppIds.end()) {
686         LOG_E(BMS_TAG_INSTALLER, "disallowedAppIds:%{public}s is disallow install", installAppId.c_str());
687         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
688     }
689     return ERR_OK;
690 #else
691     LOG_W(BMS_TAG_INSTALLER, "app control is disable");
692     return ERR_OK;
693 #endif
694 }
695 
UpdateInstallerState(const InstallerState state)696 void BaseBundleInstaller::UpdateInstallerState(const InstallerState state)
697 {
698     LOG_D(BMS_TAG_INSTALLER, "UpdateInstallerState in BaseBundleInstaller state %{public}d",
699         static_cast<int32_t>(state));
700     SetInstallerState(state);
701 }
702 
SaveOldRemovableInfo(InnerModuleInfo & newModuleInfo,InnerBundleInfo & oldInfo,bool existModule)703 void BaseBundleInstaller::SaveOldRemovableInfo(
704     InnerModuleInfo &newModuleInfo, InnerBundleInfo &oldInfo, bool existModule)
705 {
706     if (existModule) {
707         // save old module useId isRemovable info to new module
708         auto oldModule = oldInfo.FetchInnerModuleInfos().find(newModuleInfo.modulePackage);
709         if (oldModule == oldInfo.FetchInnerModuleInfos().end()) {
710             LOG_E(BMS_TAG_INSTALLER, "can not find module %{public}s in oldInfo", newModuleInfo.modulePackage.c_str());
711             return;
712         }
713         for (const auto &remove : oldModule->second.isRemovable) {
714             auto result = newModuleInfo.isRemovable.try_emplace(remove.first, remove.second);
715             if (!result.second) {
716                 LOG_E(BMS_TAG_INSTALLER, "%{public}s removable add %{public}s from old:%{public}d failed",
717                     newModuleInfo.modulePackage.c_str(), remove.first.c_str(), remove.second);
718             }
719             LOG_D(BMS_TAG_INSTALLER, "%{public}s removable add %{public}s from old:%{public}d",
720                 newModuleInfo.modulePackage.c_str(), remove.first.c_str(), remove.second);
721         }
722     }
723 }
724 
CheckEnableRemovable(std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo,int32_t & userId,bool isFreeInstallFlag,bool isAppExist)725 void BaseBundleInstaller::CheckEnableRemovable(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
726     InnerBundleInfo &oldInfo, int32_t &userId, bool isFreeInstallFlag, bool isAppExist)
727 {
728     for (auto &item : newInfos) {
729         std::map<std::string, InnerModuleInfo> &moduleInfo = item.second.FetchInnerModuleInfos();
730         bool hasInstalledInUser = oldInfo.HasInnerBundleUserInfo(userId);
731         // now there are three cases for set haps isRemovable true:
732         // 1. FREE_INSTALL flag
733         // 2. bundle not exist in current user
734         // 3. bundle exist, hap not exist
735         // 4. hap exist not in current userId
736         for (auto &iter : moduleInfo) {
737             LOG_D(BMS_TAG_INSTALLER, "%{public}s, %{public}d, %{public}d, %{public}d",
738                 iter.second.modulePackage.c_str(), userId, isFreeInstallFlag, isAppExist);
739             bool existModule = oldInfo.FindModule(iter.second.modulePackage);
740             bool hasModuleInUser = item.second.IsUserExistModule(iter.second.moduleName, userId);
741             LOG_D(BMS_TAG_INSTALLER, "%{public}d, (%{public}d), (%{public}d)",
742                 hasInstalledInUser, existModule, hasModuleInUser);
743             if (isFreeInstallFlag && (!isAppExist || !hasInstalledInUser || !existModule || !hasModuleInUser)) {
744                 LOG_D(BMS_TAG_INSTALLER, "%{public}d, %{public}d (%{public}d)",
745                     hasInstalledInUser, isAppExist, existModule);
746                 item.second.SetModuleRemovable(iter.second.moduleName, true, userId);
747                 SaveOldRemovableInfo(iter.second, oldInfo, existModule);
748             }
749         }
750     }
751 }
752 
CheckDuplicateProxyData(const InnerBundleInfo & newInfo,const InnerBundleInfo & oldInfo)753 bool BaseBundleInstaller::CheckDuplicateProxyData(const InnerBundleInfo &newInfo,
754     const InnerBundleInfo &oldInfo)
755 {
756     std::vector<ProxyData> proxyDatas;
757     oldInfo.GetAllProxyDataInfos(proxyDatas);
758     newInfo.GetAllProxyDataInfos(proxyDatas);
759     return CheckDuplicateProxyData(proxyDatas);
760 }
761 
CheckDuplicateProxyData(const std::unordered_map<std::string,InnerBundleInfo> & newInfos)762 bool BaseBundleInstaller::CheckDuplicateProxyData(const std::unordered_map<std::string, InnerBundleInfo> &newInfos)
763 {
764     std::vector<ProxyData> proxyDatas;
765     for (const auto &innerBundleInfo : newInfos) {
766         innerBundleInfo.second.GetAllProxyDataInfos(proxyDatas);
767     }
768     return CheckDuplicateProxyData(proxyDatas);
769 }
770 
CheckDuplicateProxyData(const std::vector<ProxyData> & proxyDatas)771 bool BaseBundleInstaller::CheckDuplicateProxyData(const std::vector<ProxyData> &proxyDatas)
772 {
773     std::set<std::string> uriSet;
774     for (const auto &proxyData : proxyDatas) {
775         if (!uriSet.insert(proxyData.uri).second) {
776             LOG_E(BMS_TAG_INSTALLER, "uri %{public}s in proxyData is duplicated", proxyData.uri.c_str());
777             return false;
778         }
779     }
780     return true;
781 }
782 
InnerProcessBundleInstall(std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo,const InstallParam & installParam,int32_t & uid)783 ErrCode BaseBundleInstaller::InnerProcessBundleInstall(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
784     InnerBundleInfo &oldInfo, const InstallParam &installParam, int32_t &uid)
785 {
786     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
787     LOG_I(BMS_TAG_INSTALLER, "-n %{public}s -u %{public}d -f %{public}hhd isAppExist:%{public}d",
788         bundleName_.c_str(), userId_, installParam.installFlag, isAppExist_);
789     if (!InitDataMgr()) {
790         return ERR_APPEXECFWK_NULL_PTR;
791     }
792     SetOldAppIsEncrypted(oldInfo);
793 
794     KillRelatedProcessIfArkWeb(installParam.isOTA);
795     ErrCode result = ERR_OK;
796     result = CheckAppService(newInfos.begin()->second, oldInfo, isAppExist_);
797     CHECK_RESULT(result, "Check appService failed %{public}d");
798     bool u1Enable = false;
799     result = bundleInstallChecker_->CheckU1EnableSameInHaps(newInfos, bundleName_, u1Enable);
800     CHECK_RESULT(result, "Check u1Enable in haps same failed %{public}d");
801 
802     if (installParam.needSavePreInstallInfo) {
803         PreInstallBundleInfo preInstallBundleInfo;
804         preInstallBundleInfo.SetBundleName(bundleName_);
805         dataMgr_->GetPreInstallBundleInfo(bundleName_, preInstallBundleInfo);
806         preInstallBundleInfo.SetAppType(newInfos.begin()->second.GetAppType());
807         preInstallBundleInfo.SetVersionCode(newInfos.begin()->second.GetVersionCode());
808         preInstallBundleInfo.SetIsUninstalled(false);
809         preInstallBundleInfo.DeleteForceUnisntalledUser(userId_);
810         for (const auto &item : newInfos) {
811             preInstallBundleInfo.AddBundlePath(item.first);
812         }
813 #ifdef USE_PRE_BUNDLE_PROFILE
814         preInstallBundleInfo.SetRemovable(installParam.removable);
815 #else
816         preInstallBundleInfo.SetRemovable(newInfos.begin()->second.IsRemovable());
817 #endif
818         for (const auto &innerBundleInfo : newInfos) {
819             auto applicationInfo = innerBundleInfo.second.GetBaseApplicationInfo();
820             innerBundleInfo.second.AdaptMainLauncherResourceInfo(applicationInfo);
821             preInstallBundleInfo.SetLabelId(applicationInfo.labelResource.id);
822             preInstallBundleInfo.SetIconId(applicationInfo.iconResource.id);
823             preInstallBundleInfo.SetModuleName(applicationInfo.labelResource.moduleName);
824             preInstallBundleInfo.SetSystemApp(applicationInfo.isSystemApp);
825             auto moduleMap = innerBundleInfo.second.GetInnerModuleInfos();
826             if (innerBundleInfo.second.GetIsNewVersion()) {
827                 preInstallBundleInfo.SetBundleType(innerBundleInfo.second.GetApplicationBundleType());
828             } else if (!moduleMap.empty() && moduleMap.begin()->second.distro.installationFree) {
829                 preInstallBundleInfo.SetBundleType(BundleType::ATOMIC_SERVICE);
830             }
831             if (!moduleMap.empty() && moduleMap.begin()->second.distro.moduleType == Profile::MODULE_TYPE_ENTRY) {
832                 break;
833             }
834         }
835         preInstallBundleInfo.SetU1Enable(u1Enable);
836         dataMgr_->SavePreInstallBundleInfo(bundleName_, preInstallBundleInfo);
837     } else {
838         // remove userid record in preinstallbundleinfo
839         PreInstallBundleInfo preInstallBundleInfo;
840         preInstallBundleInfo.SetBundleName(bundleName_);
841         if (dataMgr_->GetPreInstallBundleInfo(bundleName_, preInstallBundleInfo)) {
842             preInstallBundleInfo.DeleteForceUnisntalledUser(userId_);
843             if (!dataMgr_->SavePreInstallBundleInfo(bundleName_, preInstallBundleInfo)) {
844                 LOG_NOFUNC_E(BMS_TAG_DEFAULT, "update preinstall DB fail -n %{public}s", bundleName_.c_str());
845             }
846         }
847     }
848 
849     result = CheckSingleton(newInfos.begin()->second, userId_);
850     CHECK_RESULT(result, "Check singleton failed %{public}d");
851 
852     result = CheckU1Enable(newInfos.begin()->second, userId_);
853     CHECK_RESULT(result, "Check u1Enable failed %{public}d");
854 
855     bool isFreeInstallFlag = (installParam.installFlag == InstallFlag::FREE_INSTALL);
856     CheckEnableRemovable(newInfos, oldInfo, userId_, isFreeInstallFlag, isAppExist_);
857     // check MDM self update
858     result = CheckMDMUpdateBundleForSelf(installParam, oldInfo, newInfos, isAppExist_);
859     CHECK_RESULT(result, "update MDM app failed %{public}d");
860 
861     GetExtensionDirsChange(newInfos, oldInfo);
862 
863     if (isAppExist_) {
864         (void)InstalldClient::GetInstance()->RemoveDir(ServiceConstants::ARK_CACHE_PATH + oldInfo.GetBundleName());
865         SetAtomicServiceModuleUpgrade(oldInfo);
866         if (oldInfo.GetApplicationBundleType() == BundleType::SHARED) {
867             LOG_E(BMS_TAG_INSTALLER, "old bundle info is shared package");
868             return ERR_APPEXECFWK_INSTALL_COMPATIBLE_POLICY_NOT_SAME;
869         }
870 
871         result = CheckInstallationFree(oldInfo, newInfos);
872         CHECK_RESULT(result, "CheckInstallationFree failed %{public}d");
873         // to guarantee that the hap version can be compatible.
874         result = CheckVersionCompatibility(oldInfo);
875         CHECK_RESULT(result, "The app has been installed and update lower version bundle %{public}d");
876         // to check native file between oldInfo and newInfos.
877         result = CheckNativeFileWithOldInfo(oldInfo, newInfos);
878         CHECK_RESULT(result, "Check native so between oldInfo and newInfos failed %{public}d");
879 
880         for (auto &info : newInfos) {
881             std::string packageName = info.second.GetCurrentModulePackage();
882             if (oldInfo.FindModule(packageName)) {
883                 installedModules_[packageName] = true;
884             }
885         }
886 
887         hasInstalledInUser_ = oldInfo.HasInnerBundleUserInfo(userId_);
888         if (!hasInstalledInUser_) {
889             if (AccountHelper::CheckOsAccountConstraintEnabled(userId_, ServiceConstants::CONSTRAINT_APPS_INSTALL)) {
890                 APP_LOGE("user %{public}d is not allowed to install app", userId_);
891                 return ERR_APPEXECFWK_INSTALL_FAILED_ACCOUNT_CONSTRAINT;
892             }
893             LOG_D(BMS_TAG_INSTALLER, "new userInfo with bundleName %{public}s and userId %{public}d",
894                 bundleName_.c_str(), userId_);
895             InnerBundleUserInfo newInnerBundleUserInfo;
896             newInnerBundleUserInfo.bundleUserInfo.userId = userId_;
897             newInnerBundleUserInfo.bundleName = bundleName_;
898             oldInfo.AddInnerBundleUserInfo(newInnerBundleUserInfo);
899             ScopeGuard userGuard([&] { RemoveBundleUserData(oldInfo, false); });
900             Security::AccessToken::AccessTokenIDEx accessTokenIdEx;
901             Security::AccessToken::HapInfoCheckResult checkResult;
902             if (!RecoverHapToken(bundleName_, userId_, accessTokenIdEx, oldInfo)
903                 && BundlePermissionMgr::InitHapToken(oldInfo, userId_, 0, accessTokenIdEx, checkResult,
904                 verifyRes_.GetProvisionInfo().appServiceCapabilities) != ERR_OK) {
905                 LOG_E(BMS_TAG_INSTALLER, "bundleName:%{public}s InitHapToken failed", bundleName_.c_str());
906                 SetVerifyPermissionResult(checkResult);
907                 return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
908             }
909             accessTokenId_ = accessTokenIdEx.tokenIdExStruct.tokenID;
910             oldInfo.SetAccessTokenIdEx(accessTokenIdEx, userId_);
911             result = CreateBundleUserData(oldInfo);
912             CHECK_RESULT(result, "CreateBundleUserData failed %{public}d");
913 
914             if (!isFeatureNeedUninstall_) {
915                 // extract ap file in old haps
916                 result = ExtractAllArkProfileFile(oldInfo, true);
917                 CHECK_RESULT(result, "ExtractAllArkProfileFile failed %{public}d");
918             }
919 
920             userGuard.Dismiss();
921         }
922         ErrCode res = CleanShaderCache(oldInfo, bundleName_, userId_);
923         if (res != ERR_OK) {
924             LOG_NOFUNC_I(BMS_TAG_INSTALLER, "%{public}s clean shader fail %{public}d", bundleName_.c_str(), res);
925         }
926         // clean ark startup cache for bundle
927         CleanArkStartupCache(ServiceConstants::SYSTEM_OPTIMIZE_PATH, bundleName_, userId_);
928     }
929 
930     auto it = newInfos.begin();
931     if (!isAppExist_) {
932         if (AccountHelper::CheckOsAccountConstraintEnabled(userId_, ServiceConstants::CONSTRAINT_APPS_INSTALL)) {
933             APP_LOGE("user %{public}d is not allowed to install app", userId_);
934             return ERR_APPEXECFWK_INSTALL_FAILED_ACCOUNT_CONSTRAINT;
935         }
936         if (!CheckInstallOnKeepData(bundleName_, installParam.isOTA, newInfos)) {
937             LOG_E(BMS_TAG_INSTALLER, "check failed");
938             return ERR_APPEXECFWK_INSTALL_FAILED_INCONSISTENT_SIGNATURE;
939         }
940         InnerBundleInfo &newInfo = it->second;
941         modulePath_ = it->first;
942         InnerBundleUserInfo newInnerBundleUserInfo;
943         newInnerBundleUserInfo.bundleUserInfo.userId = userId_;
944         newInnerBundleUserInfo.bundleName = bundleName_;
945         newInfo.AddInnerBundleUserInfo(newInnerBundleUserInfo);
946         newInfo.SetIsFreeInstallApp(InstallFlag::FREE_INSTALL == installParam.installFlag);
947         SetApplicationFlagsAndInstallSource(newInfos, installParam);
948         result = ProcessBundleInstallStatus(newInfo, uid);
949         CHECK_RESULT(result, "ProcessBundleInstallStatus failed %{public}d");
950 
951         it++;
952         hasInstalledInUser_ = true;
953     }
954 
955     InnerBundleInfo bundleInfo;
956     if (!GetTempBundleInfo(bundleInfo)) {
957         return ERR_APPEXECFWK_GET_INSTALL_TEMP_BUNDLE_ERROR;
958     }
959     bool isOldSystemApp = bundleInfo.IsSystemApp();
960 
961     InnerBundleUserInfo innerBundleUserInfo;
962     if (!bundleInfo.GetInnerBundleUserInfo(userId_, innerBundleUserInfo)) {
963         LOG_E(BMS_TAG_INSTALLER, "oldInfo do not have user");
964         return ERR_APPEXECFWK_USER_NOT_EXIST;
965     }
966     CreateExtensionDataDir(bundleInfo);
967 
968     ScopeGuard userGuard([&] {
969         if (!hasInstalledInUser_ || (!isAppExist_)) {
970             RemoveBundleUserData(oldInfo, false);
971         }
972     });
973 
974     // update haps
975     for (; it != newInfos.end(); ++it) {
976         // install entry module firstly
977         LOG_D(BMS_TAG_INSTALLER, "update module %{public}s, entry module packageName is %{public}s",
978             it->second.GetCurrentModulePackage().c_str(), entryModuleName_.c_str());
979         if ((result = InstallEntryMoudleFirst(newInfos, bundleInfo, innerBundleUserInfo,
980             installParam)) != ERR_OK) {
981             LOG_E(BMS_TAG_INSTALLER, "install entry module failed due to error %{public}d", result);
982             break;
983         }
984         if (it->second.GetCurrentModulePackage().compare(entryModuleName_) == 0) {
985             LOG_D(BMS_TAG_INSTALLER, "enrty has been installed");
986             continue;
987         }
988         modulePath_ = it->first;
989         InnerBundleInfo &newInfo = it->second;
990         newInfo.AddInnerBundleUserInfo(innerBundleUserInfo);
991         bool isReplace = (installParam.installFlag == InstallFlag::REPLACE_EXISTING ||
992             installParam.installFlag == InstallFlag::FREE_INSTALL);
993         // app exist, but module may not
994         if ((result = ProcessBundleUpdateStatus(
995             bundleInfo, newInfo, isReplace, installParam.GetKillProcess())) != ERR_OK) {
996             break;
997         }
998     }
999     if (result == ERR_OK) {
1000         result = InnerProcessUpdateHapToken(isOldSystemApp);
1001         CHECK_RESULT(result, "InnerProcessUpdateHapToken failed %{public}d");
1002     }
1003 
1004     if (result == ERR_OK) {
1005         userGuard.Dismiss();
1006     }
1007 
1008     uid = bundleInfo.GetUid(userId_);
1009     if (bundleInfo.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE) {
1010         std::string bundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[0]
1011             + ServiceConstants::PATH_SEPARATOR + std::to_string(userId_) + ServiceConstants::BASE +
1012             bundleInfo.GetBundleName();
1013         PrepareBundleDirQuota(bundleInfo.GetBundleName(), uid, bundleDataDir,
1014             ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET);
1015     }
1016     mainAbility_ = bundleInfo.GetMainAbility();
1017     return result;
1018 }
1019 
ProcessUpdateShortcut()1020 void BaseBundleInstaller::ProcessUpdateShortcut()
1021 {
1022     if (!isAppExist_ || !InitDataMgr()) {
1023         return;
1024     }
1025     dataMgr_->UpdateDesktopShortcutInfo(bundleName_);
1026 }
1027 
InnerProcessUpdateHapToken(const bool isOldSystemApp)1028 ErrCode BaseBundleInstaller::InnerProcessUpdateHapToken(const bool isOldSystemApp)
1029 {
1030     InnerBundleInfo newBundleInfo;
1031     if (!GetTempBundleInfo(newBundleInfo)) {
1032         APP_LOGE("bundleName:%{public}s not exist", bundleName_.c_str());
1033         return ERR_APPEXECFWK_GET_INSTALL_TEMP_BUNDLE_ERROR;
1034     }
1035     std::vector<std::string> moduleVec = newBundleInfo.GetModuleNameVec();
1036     if (!isAppExist_ && (moduleVec.size() == 1)) {
1037         APP_LOGD("bundleName:%{public}s only has one module, no need update", bundleName_.c_str());
1038         return ERR_OK;
1039     }
1040 
1041     if (!uninstallModuleVec_.empty()) {
1042         for (const auto &package : moduleVec) {
1043             if (std::find(uninstallModuleVec_.begin(), uninstallModuleVec_.end(), package)
1044                 == uninstallModuleVec_.end()) {
1045                 newBundleInfo.SetInnerModuleNeedDelete(package, true);
1046             }
1047         }
1048     }
1049     ErrCode result = UpdateHapToken(isOldSystemApp != newBundleInfo.IsSystemApp(), newBundleInfo);
1050     if (result != ERR_OK) {
1051         APP_LOGE("bundleName:%{public}s update hapToken failed, errCode:%{public}d", bundleName_.c_str(), result);
1052         return result;
1053     }
1054     if (isAppExist_ && isModuleUpdate_) {
1055         result = SetDirApl(newBundleInfo);
1056         if (result != ERR_OK) {
1057             APP_LOGE("bundleName:%{public}s setDirApl failed:%{public}d", bundleName_.c_str(), result);
1058             return result;
1059         }
1060     }
1061     return ERR_OK;
1062 }
1063 
SetAtomicServiceModuleUpgrade(const InnerBundleInfo & oldInfo)1064 void BaseBundleInstaller::SetAtomicServiceModuleUpgrade(const InnerBundleInfo &oldInfo)
1065 {
1066     std::vector<std::string> moduleNames;
1067     oldInfo.GetModuleNames(moduleNames);
1068     for (const std::string &moduleName : moduleNames) {
1069         int32_t flag = static_cast<int32_t>(oldInfo.GetModuleUpgradeFlag(moduleName));
1070         if (flag) {
1071             atomicServiceModuleUpgrade_ = flag;
1072             return;
1073         }
1074     }
1075 }
1076 
IsArkWeb(const std::string & bundleName) const1077 bool BaseBundleInstaller::IsArkWeb(const std::string &bundleName) const
1078 {
1079     std::string arkWebName = OHOS::system::GetParameter(ARK_WEB_BUNDLE_NAME_PARAM, "");
1080     if (!arkWebName.empty()) {
1081         if (bundleName != arkWebName) {
1082             LOG_D(BMS_TAG_INSTALLER, "Bundle(%{public}s) is not arkweb", bundleName.c_str());
1083             return false;
1084         }
1085     } else {
1086         if (bundleName != NEW_ARK_WEB_BUNDLE_NAME && bundleName != OLD_ARK_WEB_BUNDLE_NAME) {
1087             LOG_I(BMS_TAG_INSTALLER, "Failed to get arkweb name and bundle name is %{public}s",
1088                 bundleName.c_str());
1089             return false;
1090         }
1091     }
1092     LOG_I(BMS_TAG_INSTALLER, "%{public}s is arkweb", bundleName.c_str());
1093     return true;
1094 }
1095 
1096 #ifdef WEBVIEW_ENABLE
VerifyArkWebInstall()1097 ErrCode BaseBundleInstaller::VerifyArkWebInstall()
1098 {
1099     if (!IsArkWeb(bundleName_)) {
1100         return ERR_OK;
1101     }
1102     if (!InitDataMgr()) {
1103         return ERR_APPEXECFWK_NULL_PTR;
1104     }
1105     InnerBundleInfo info;
1106     if (!GetTempBundleInfo(info)) {
1107         LOG_W(BMS_TAG_INSTALLER, "bundle info missing");
1108         return ERR_APPEXECFWK_GET_INSTALL_TEMP_BUNDLE_ERROR;
1109     }
1110     std::string hapPath = info.GetModuleHapPath(info.GetEntryModuleName());
1111     LOG_I(BMS_TAG_INSTALLER, "arkweb hapPath is %{public}s", hapPath.c_str());
1112     if (NWeb::AppFwkUpdateClient::GetInstance().VerifyPackageInstall(bundleName_, hapPath) != ERR_OK) {
1113         return ERR_APPEXECFWK_VERIFY_PKG_INSTALL_ERROR;
1114     }
1115     return ERR_OK;
1116 }
1117 
RestoreconForArkweb()1118 void BaseBundleInstaller::RestoreconForArkweb()
1119 {
1120     if (!OHOS::system::GetBoolParameter(APPSPAWN_PRELOAD_ARKWEB_ENGINE, false)) {
1121         LOG_D(BMS_TAG_INSTALLER, "APPSPAWN_PRELOAD_ARKWEB_ENGINE is false");
1122         return;
1123     }
1124 
1125     if (!IsArkWeb(bundleName_)) {
1126         return;
1127     }
1128     const std::string arkWebLibPath = std::string(APP_INSTALL_PATH) + "/public/" + bundleName_ + "/libs/arm64/";
1129     LOG_I(BMS_TAG_INSTALLER, "RestoreconPath, arkWebLibPath: %{public}s", arkWebLibPath.c_str());
1130     ErrCode result = InstalldClient::GetInstance()->RestoreconPath(arkWebLibPath);
1131     if (result != ERR_OK) {
1132         LOG_E(BMS_TAG_INSTALLER, "Failed to restorecon arkweb dir, error code: %{public}d", result);
1133     }
1134 }
1135 #endif
1136 
KillRelatedProcessIfArkWeb(bool isOta)1137 void BaseBundleInstaller::KillRelatedProcessIfArkWeb(bool isOta)
1138 {
1139     if (!isAppExist_ || isOta || !IsArkWeb(bundleName_)) {
1140         return;
1141     }
1142     auto appMgrClient = DelayedSingleton<AppMgrClient>::GetInstance();
1143     if (appMgrClient == nullptr) {
1144         LOG_E(BMS_TAG_INSTALLER, "AppMgrClient is nullptr, kill ark web process failed");
1145         return;
1146     }
1147     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "KillRelatedProcessIfArkWeb begin");
1148     appMgrClient->KillProcessDependedOnWeb();
1149     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "KillRelatedProcessIfArkWeb end");
1150 }
1151 
CheckAppService(const InnerBundleInfo & newInfo,const InnerBundleInfo & oldInfo,bool isAppExist)1152 ErrCode BaseBundleInstaller::CheckAppService(
1153     const InnerBundleInfo &newInfo, const InnerBundleInfo &oldInfo, bool isAppExist)
1154 {
1155     if ((newInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK) && !isAppExist) {
1156         LOG_W(BMS_TAG_INSTALLER, "Not alloweded instal appService hap(%{public}s) due to the hsp does not exist",
1157             newInfo.GetBundleName().c_str());
1158         return ERR_APP_SERVICE_FWK_INSTALL_TYPE_FAILED;
1159     }
1160 
1161     if (isAppExist) {
1162         isAppService_ = oldInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK;
1163         if (isAppService_ && oldInfo.GetApplicationBundleType() != newInfo.GetApplicationBundleType()) {
1164             LOG_W(BMS_TAG_INSTALLER, "Bundle(%{public}s) type is not same", newInfo.GetBundleName().c_str());
1165             return ERR_APPEXECFWK_BUNDLE_TYPE_NOT_SAME;
1166         }
1167         if (isAppService_ && (oldInfo.GetVersionCode() < newInfo.GetVersionCode())) {
1168             APP_LOGW("upgrade must first upgrade the hsp, cannot upgrade hap first");
1169             return ERR_APP_SERVICE_FWK_INSTALL_TYPE_FAILED;
1170         }
1171     }
1172     return ERR_OK;
1173 }
1174 
CheckSingleton(const InnerBundleInfo & info,const int32_t userId)1175 ErrCode BaseBundleInstaller::CheckSingleton(const InnerBundleInfo &info, const int32_t userId)
1176 {
1177     if (isAppService_) {
1178         if (userId != Constants::DEFAULT_USERID) {
1179             LOG_NOFUNC_W(BMS_TAG_INSTALLER, "appService(%{public}s) only install U0", info.GetBundleName().c_str());
1180             return ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON;
1181         }
1182 
1183         return ERR_OK;
1184     }
1185     // singleton app can only be installed in U0 and U0 can only install singleton app.
1186     bool isSingleton = info.IsSingleton();
1187     if ((isSingleton && (userId != Constants::DEFAULT_USERID)) ||
1188         (!isSingleton && (userId == Constants::DEFAULT_USERID))) {
1189         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "singleton(%{public}d) app(%{public}s) and user(%{public}d) are not matched",
1190             isSingleton, info.GetBundleName().c_str(), userId);
1191         return ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON;
1192     }
1193 
1194     return ERR_OK;
1195 }
1196 
CheckU1Enable(const InnerBundleInfo & info,const int32_t userId)1197 ErrCode BaseBundleInstaller::CheckU1Enable(const InnerBundleInfo &info,
1198     const int32_t userId)
1199 {
1200     LOG_I(BMS_TAG_INSTALLER, "start for -n %{public}s -u %{public}d",
1201         info.GetBundleName().c_str(), userId);
1202     std::string bundleName = info.GetBundleName();
1203     bool u1Enable = info.IsU1Enable();
1204     bool isU1 = (userId == Constants::U1);
1205     if ((u1Enable && !isU1) || (!u1Enable && isU1)) {
1206         LOG_E(BMS_TAG_INSTALLER, "u1Enable:%{public}d and userId:%{public}d not matched for %{public}s",
1207             u1Enable, userId, bundleName.c_str());
1208         return ERR_APPEXECFWK_INSTALL_U1ENABLE_CAN_ONLY_INSTALL_IN_U1_WITH_NOT_SINGLETON;
1209     }
1210 
1211     std::vector<int32_t> currentBundleUserIds = dataMgr_->GetUserIds(bundleName);
1212     bool onlyInstallInU1 = currentBundleUserIds.size() == 1 && currentBundleUserIds[0] == Constants::U1;
1213     if (u1Enable && isU1) {
1214         if (isAppExist_ && !onlyInstallInU1) {
1215             LOG_E(BMS_TAG_INSTALLER, "%{public}s existed in other users, but not u1", bundleName.c_str());
1216             return ERR_APPEXECFWK_INSTALL_BUNDLE_CAN_NOT_BOTH_EXISTED_IN_U1_AND_OTHER_USERS;
1217         }
1218     } else {
1219         // u1Enable is false and userid is not u1
1220         if (isAppExist_ && onlyInstallInU1) {
1221             LOG_E(BMS_TAG_INSTALLER, "%{public}s existed in u1, but u1Enable is false and userId is not u1",
1222                 bundleName.c_str());
1223             return ERR_APPEXECFWK_INSTALL_BUNDLE_CAN_NOT_BOTH_EXISTED_IN_U1_AND_OTHER_USERS;
1224         }
1225     }
1226     return ERR_OK;
1227 }
1228 
ProcessBundleInstall(const std::vector<std::string> & inBundlePaths,const InstallParam & installParam,const Constants::AppType appType,int32_t & uid,bool isRecover)1229 ErrCode BaseBundleInstaller::ProcessBundleInstall(const std::vector<std::string> &inBundlePaths,
1230     const InstallParam &installParam, const Constants::AppType appType, int32_t &uid, bool isRecover)
1231 {
1232     LOG_D(BMS_TAG_INSTALLER, "ProcessBundleInstall bundlePath install paths=%{private}s, hspPaths=%{private}s",
1233         GetJsonStrFromInfo(inBundlePaths).c_str(), GetJsonStrFromInfo(installParam.sharedBundleDirPaths).c_str());
1234     if (!InitDataMgr()) {
1235         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
1236     }
1237 
1238     SharedBundleInstaller sharedBundleInstaller(installParam, appType);
1239     ErrCode result = sharedBundleInstaller.ParseFiles();
1240     CHECK_RESULT(result, "parse cross-app shared bundles failed %{public}d");
1241 
1242     if (inBundlePaths.empty() && sharedBundleInstaller.NeedToInstall()) {
1243         result = sharedBundleInstaller.Install(sysEventInfo_);
1244         bundleType_ = BundleType::SHARED;
1245         LOG_I(BMS_TAG_INSTALLER, "install cross-app shared bundles only, result : %{public}d", result);
1246         return result;
1247     }
1248 
1249     userId_ = GetUserId(installParam.userId);
1250     result = CheckUserId(userId_);
1251     CHECK_RESULT(result, "userId check failed %{public}d");
1252 
1253     std::vector<std::string> parsedPaths;
1254     result = ParseHapPaths(installParam, inBundlePaths, parsedPaths);
1255     CHECK_RESULT(result, "hap file parse failed %{public}d");
1256 
1257     std::vector<std::string> bundlePaths;
1258     // check hap paths
1259     result = BundleUtil::CheckFilePath(parsedPaths, bundlePaths);
1260     CHECK_RESULT(result, "hap file check failed %{public}d");
1261     UpdateInstallerState(InstallerState::INSTALL_BUNDLE_CHECKED);                  // ---- 5%
1262 
1263     // copy the haps to the dir which cannot be accessed from caller
1264     result = CopyHapsToSecurityDir(installParam, bundlePaths);
1265     CHECK_RESULT(result, "copy file failed %{public}d");
1266 
1267     // check syscap
1268     result = CheckSysCap(bundlePaths);
1269     bool isSysCapValid = (result == ERR_OK);
1270     if (!isSysCapValid) {
1271         APP_LOGI("hap syscap check failed %{public}d", result);
1272     }
1273     UpdateInstallerState(InstallerState::INSTALL_SYSCAP_CHECKED);                  // ---- 10%
1274 
1275     // verify signature info for all haps
1276     std::vector<Security::Verify::HapVerifyResult> hapVerifyResults;
1277     result = CheckMultipleHapsSignInfo(bundlePaths, installParam, hapVerifyResults);
1278     CHECK_RESULT(result, "hap files check signature info failed %{public}d");
1279     UpdateInstallerState(InstallerState::INSTALL_SIGNATURE_CHECKED);               // ---- 15%
1280 
1281     result = CheckShellInstall(hapVerifyResults);
1282     CHECK_RESULT(result, "check shell install failed %{public}d");
1283 
1284     result = CheckPreAppAllowHdcInstall(installParam, hapVerifyResults);
1285     CHECK_RESULT(result, "not allowed install os_integration bundle, %{public}d");
1286 
1287     result = CheckShellInstallInOobe();
1288     CHECK_RESULT(result, "check shell install in oobe failed %{public}d");
1289 
1290     // parse the bundle infos for all haps
1291     // key is bundlePath , value is innerBundleInfo
1292     std::unordered_map<std::string, InnerBundleInfo> newInfos;
1293     result = ParseHapFiles(bundlePaths, installParam, appType, hapVerifyResults, newInfos);
1294     CHECK_RESULT(result, "parse haps file failed %{public}d");
1295 
1296     result = CheckArkTSMode(newInfos);
1297     CHECK_RESULT(result, "check arkTS mode failed %{public}d");
1298 
1299     bool onDemandInstall = OnDemandInstallDataMgr::GetInstance().IsOnDemandInstall(installParam);
1300     if (!onDemandInstall) {
1301         if (userId_ == Constants::DEFAULT_USERID && installParam.isDataPreloadHap &&
1302             installParam.appIdentifier != appIdentifier_) {
1303             result = ERR_APPEXECFWK_INSTALL_VERIFICATION_FAILED;
1304         }
1305     } else {
1306         if (installParam.isDataPreloadHap &&
1307             OnDemandInstallDataMgr::GetInstance().GetAppidentifier(inBundlePaths[0]) != appIdentifier_) {
1308             result = ERR_APPEXECFWK_INSTALL_VERIFICATION_FAILED;
1309         }
1310     }
1311     CHECK_RESULT(result, "check DataPreloadHap appIdentifier failed %{public}d");
1312     // washing machine judge
1313     if (!installParam.isPreInstallApp && !newInfos.empty()) {
1314         auto &firstBundleInfo = newInfos.begin()->second;
1315         if (!firstBundleInfo.IsSystemApp()) {
1316             bool isBundleExist = dataMgr_->IsBundleExist(firstBundleInfo.GetBundleName());
1317             if (!isBundleExist && !VerifyActivationLock()) {
1318                 result = ERR_APPEXECFWK_INSTALL_FAILED_CONTROLLED;
1319             }
1320         }
1321     }
1322     CHECK_RESULT(result, "check install verifyActivation failed %{public}d");
1323     // plugin judge
1324     if (!newInfos.empty() &&
1325         newInfos.begin()->second.GetApplicationBundleType() == BundleType::APP_PLUGIN) {
1326         result = ERR_APPEXECFWK_PLUGIN_INSTALL_NOT_ALLOW;
1327         CHECK_RESULT(result, "plugin install not allow %{public}d");
1328     }
1329     result = CheckShellCanInstallPreApp(newInfos);
1330     CHECK_RESULT(result, "check shell can install pre app failed %{public}d");
1331     CheckPreBundle(newInfos, installParam, isRecover);
1332     result = CheckInstallPermission(installParam, hapVerifyResults);
1333     CHECK_RESULT(result, "check install permission failed %{public}d");
1334     result = CheckInstallCondition(hapVerifyResults, newInfos, isSysCapValid);
1335     CHECK_RESULT(result, "check install condition failed %{public}d");
1336     // check the dependencies whether or not exists
1337     result = CheckDependency(newInfos, sharedBundleInstaller);
1338     CHECK_RESULT(result, "check dependency failed %{public}d");
1339     // hapVerifyResults at here will not be empty
1340     verifyRes_ = hapVerifyResults[0];
1341 
1342     result = DeliveryProfileToCodeSign();
1343     CHECK_RESULT(result, "delivery profile failed %{public}d");
1344 
1345     UpdateInstallerState(InstallerState::INSTALL_PARSED);                          // ---- 20%
1346 
1347     userId_ = GetConfirmUserId(userId_, newInfos);
1348     result = CheckUserId(userId_);
1349     CHECK_RESULT(result, "userId check failed %{public}d");
1350 
1351     if (!installParam.isPreInstallApp && IsAppInBlocklist((newInfos.begin()->second).GetBundleName(), userId_)) {
1352         result = ERR_APPEXECFWK_INSTALL_APP_IN_BLOCKLIST;
1353         CHECK_RESULT(result, "app is in block list %{public}d");
1354     }
1355     // check hap hash param
1356     result = CheckHapHashParams(newInfos, installParam.hashParams);
1357     CHECK_RESULT(result, "check hap hash param failed %{public}d");
1358     UpdateInstallerState(InstallerState::INSTALL_HAP_HASH_PARAM_CHECKED);         // ---- 25%
1359 
1360     // check overlay installation
1361     result = CheckOverlayInstallation(newInfos, userId_);
1362     CHECK_RESULT(result, "overlay hap check failed %{public}d");
1363     UpdateInstallerState(InstallerState::INSTALL_OVERLAY_CHECKED);                // ---- 30%
1364 
1365     // check app props in the configuration file
1366     result = CheckAppLabelInfo(newInfos);
1367     CHECK_RESULT(result, "verisoncode or bundleName is different in all haps %{public}d");
1368     UpdateInstallerState(InstallerState::INSTALL_VERSION_AND_BUNDLENAME_CHECKED);  // ---- 35%
1369 
1370     // to send notify of start install application
1371     SendStartInstallNotify(installParam, newInfos);
1372 
1373     // check if bundle exists in extension
1374     result = CheckBundleInBmsExtension(bundleName_, userId_);
1375     CHECK_RESULT(result, "bundle is already existed in bms extension %{public}d");
1376 
1377     // check native file
1378     result = CheckMultiNativeFile(newInfos);
1379     CHECK_RESULT(result, "native so is incompatible in all haps %{public}d");
1380     UpdateInstallerState(InstallerState::INSTALL_NATIVE_SO_CHECKED);               // ---- 40%
1381 
1382     // check proxy data
1383     result = CheckProxyDatas(newInfos);
1384     CHECK_RESULT(result, "proxy data check failed %{public}d");
1385     UpdateInstallerState(InstallerState::INSTALL_PROXY_DATA_CHECKED);              // ---- 45%
1386 
1387     // check hap is allow install by app control
1388     result = InstallNormalAppControl((newInfos.begin()->second).GetAppId(), userId_, installParam.isPreInstallApp);
1389     CHECK_RESULT(result, "install app control failed %{public}d");
1390 
1391     auto &mtx = dataMgr_->GetBundleMutex(bundleName_);
1392     std::lock_guard lock {mtx};
1393 
1394     // uninstall all sandbox app before
1395     UninstallAllSandboxApps(bundleName_);
1396     UpdateInstallerState(InstallerState::INSTALL_REMOVE_SANDBOX_APP);              // ---- 50%
1397 
1398     // this state should always be set when return
1399     ScopeGuard stateGuard([&] {
1400         dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_SUCCESS);
1401         dataMgr_->EnableBundle(bundleName_);
1402     });
1403 
1404     InnerBundleInfo oldInfo;
1405     verifyCodeParams_ = installParam.verifyCodeParams;
1406     pgoParams_ = installParam.pgoParams;
1407     copyHapToInstallPath_ = installParam.copyHapToInstallPath;
1408     ScopeGuard extensionDirGuard([&] { RemoveCreatedExtensionDirsForException(); });
1409     // try to get the bundle info to decide use install or update. Always keep other exceptions below this line.
1410     if (!InitTempBundleFromCache(oldInfo, isAppExist_)) {
1411         return ERR_APPEXECFWK_INIT_INSTALL_TEMP_BUNDLE_ERROR;
1412     }
1413     // check AppDistributionType
1414     result = CheckAppDistributionType();
1415     CHECK_RESULT(result, "check app distribution type info failed %{public}d");
1416 
1417     // when bundle update start, bms need set disposed rule to forbidden app running.
1418     (void)SetDisposedRuleWhenBundleUpdateStart(newInfos, oldInfo, installParam.isPreInstallApp);
1419     // when bundle update end, bms need delete disposed rule.
1420     ScopeGuard deleteDisposedRuleGuard([&] { (void)DeleteDisposedRuleWhenBundleUpdateEnd(oldInfo); });
1421     ScopeGuard codePathGuard([&] { RollbackCodePath(bundleName_, isFeatureNeedUninstall_); });
1422     result = InnerProcessBundleInstall(newInfos, oldInfo, installParam, uid);
1423     CHECK_RESULT_WITH_ROLLBACK(result, "internal processing failed with result %{public}d", newInfos, oldInfo);
1424     UpdateInstallerState(InstallerState::INSTALL_INFO_SAVED);                      // ---- 80%
1425 
1426 #ifdef WEBVIEW_ENABLE
1427     result = VerifyArkWebInstall();
1428     CHECK_RESULT_WITH_ROLLBACK(result, "web verify failed %{public}d", newInfos, oldInfo);
1429 #endif
1430     // copy hap to app_tmp path
1431     (void)AddAppGalleryHapToTempPath(installParam.isPreInstallApp, newInfos);
1432     // delete app_tmp
1433     ScopeGuard deleteAppGalleryHapFromTempPathRuleGuard([&] { (void)DeleteAppGalleryHapFromTempPath(); });
1434 
1435     // Roolback is unavailable below this line
1436     // copy hap or hsp to real install dir
1437     SaveHapPathToRecords(installParam.isPreInstallApp, newInfos);
1438     if (installParam.copyHapToInstallPath) {
1439         LOG_D(BMS_TAG_INSTALLER, "begin to copy hap to install path");
1440         result = SaveHapToInstallPath(newInfos, oldInfo);
1441         CHECK_RESULT_WITH_ROLLBACK(result, "copy hap to install path failed %{public}d", newInfos, oldInfo);
1442     } else {
1443         if ((result = CheckHapEncryption(newInfos, oldInfo, false)) != ERR_OK) {
1444             LOG_E(BMS_TAG_INSTALLER, "check encryption of pre-hap failed %{public}d", result);
1445         }
1446     }
1447 
1448     if (installParam.isDataPreloadHap) {
1449         // Verify Code Signature For Data Preload Hap
1450         for (const auto &preinstalledAppPath : bundlePaths) {
1451             VerifyCodeSignatureForHap(newInfos, preinstalledAppPath, preinstalledAppPath);
1452         }
1453     }
1454     result = ProcessBundleCodePath(newInfos, oldInfo, bundleName_,
1455         isFeatureNeedUninstall_, installParam.copyHapToInstallPath);
1456     CHECK_RESULT_WITH_ROLLBACK(result, "final process code path failed %{public}d", newInfos, oldInfo);
1457 
1458     UpdateInstallerState(InstallerState::INSTALL_RENAMED);                         // ---- 90%
1459 
1460     // delete low-version hap or hsp when higher-version hap or hsp installed
1461     if (!uninstallModuleVec_.empty()) {
1462         UninstallLowerVersionFeature(uninstallModuleVec_, installParam.GetKillProcess());
1463     }
1464 
1465     // create Screen Lock File Protection Dir
1466     CreateScreenLockProtectionDir();
1467     ScopeGuard ScreenLockFileProtectionDirGuard([&] { DeleteScreenLockProtectionDir(bundleName_); });
1468 
1469     // install cross-app hsp which has rollback operation in sharedBundleInstaller when some one failure occurs
1470     result = sharedBundleInstaller.Install(sysEventInfo_);
1471     CHECK_RESULT_WITH_ROLLBACK(result, "install cross-app shared bundles failed %{public}d", newInfos, oldInfo);
1472 
1473     std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1474     result = driverInstaller->CopyAllDriverFile(newInfos, oldInfo);
1475     CHECK_RESULT_WITH_ROLLBACK(result, "copy driver files failed due to error %{public}d", newInfos, oldInfo);
1476 
1477     UpdateInstallerState(InstallerState::INSTALL_SUCCESS);                         // ---- 100%
1478 #ifdef WEBVIEW_ENABLE
1479     RestoreconForArkweb();
1480 #endif
1481     LOG_D(BMS_TAG_INSTALLER, "finish ProcessBundleInstall bundlePath install touch off aging");
1482     moduleName_ = GetModuleNames(newInfos);
1483     isBundleCrossAppSharedConfig_ = IsBundleCrossAppSharedConfig(newInfos);
1484 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
1485     if (installParam.installFlag == InstallFlag::FREE_INSTALL) {
1486         DelayedSingleton<BundleMgrService>::GetInstance()->GetAgingMgr()->Start(
1487             BundleAgingMgr::AgingTriggertype::FREE_INSTALL);
1488     }
1489 #endif
1490     InnerBundleInfo cacheInfo;
1491     tempInfo_.GetTempBundleInfo(cacheInfo);
1492 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1493     if (needDeleteQuickFixInfo_) {
1494         LOG_D(BMS_TAG_INSTALLER, "module update, quick fix old patch need to delete:%{public}s", bundleName_.c_str());
1495         if (!oldInfo.GetAppQuickFix().deployedAppqfInfo.hqfInfos.empty()) {
1496             LOG_D(BMS_TAG_INSTALLER, "quickFixInfo need disable, bundleName:%{public}s", bundleName_.c_str());
1497             auto quickFixSwitcher = std::make_unique<QuickFixSwitcher>(bundleName_, false);
1498             quickFixSwitcher->DisableQuickFix(cacheInfo);
1499         }
1500         auto quickFixDeleter = std::make_unique<QuickFixDeleter>(bundleName_);
1501         quickFixDeleter->DeleteQuickFix(cacheInfo);
1502         tempInfo_.SetTempBundleInfo(cacheInfo);
1503     }
1504 #endif
1505     DeleteUninstallBundleInfo(bundleName_);
1506     UpdateEncryptedStatus(oldInfo);
1507     GetInstallEventInfo(oldInfo, sysEventInfo_);
1508     AddAppProvisionInfo(bundleName_, hapVerifyResults[0].GetProvisionInfo(), installParam);
1509     UpdateRouterInfo();
1510     ProcessOldNativeLibraryPath(newInfos, oldInfo.GetVersionCode(), oldInfo.GetNativeLibraryPath());
1511     ProcessAOT(installParam.isOTA, newInfos);
1512     RemoveOldHapIfOTA(installParam, newInfos, oldInfo);
1513     UpdateAppInstallControlled(userId_);
1514     extensionDirGuard.Dismiss();
1515     ScreenLockFileProtectionDirGuard.Dismiss();
1516     if (isAppExist_) {
1517         RemoveDataPreloadHapFiles(bundleName_);
1518     }
1519     RemoveOldExtensionDirs();
1520     /* process quick fix when install new moudle */
1521     ProcessQuickFixWhenInstallNewModule(installParam, newInfos);
1522     VerifyDomain();
1523     PatchDataMgr::GetInstance().ProcessPatchInfo(bundleName_, inBundlePaths,
1524         newInfos.begin()->second.GetVersionCode(), AppPatchType::INTERNAL, installParam.isPatch);
1525     UpdateHasCloudkitConfig();
1526     // check mark install finish
1527     result = MarkInstallFinish();
1528     if (result != ERR_OK) {
1529         PatchDataMgr::GetInstance().DeleteInnerPatchInfo(bundleName_);
1530     }
1531     CHECK_RESULT_WITH_ROLLBACK(result, "mark install finish failed %{public}d", newInfos, oldInfo);
1532     codePathGuard.Dismiss();
1533     ProcessOldCodePath(bundleName_, isFeatureNeedUninstall_);
1534     // create data group dir
1535     ScopeGuard groupDirGuard([&] { DeleteGroupDirsForException(oldInfo); });
1536     CreateDataGroupDirs(hapVerifyResults, oldInfo);
1537     groupDirGuard.Dismiss();
1538     // process ark startup cache
1539     if (result == ERR_OK) {
1540         InnerBundleUserInfo newInnerBundleUserInfo;
1541         cacheInfo.GetInnerBundleUserInfo(userId_, newInnerBundleUserInfo);
1542         ArkStartupCache ceateArk = CreateArkStartupCacheParameter(bundleName_, userId_,
1543             oldInfo.GetApplicationBundleType(), newInnerBundleUserInfo.uid);
1544         ProcessArkStartupCache(ceateArk, cacheInfo.GetModuleSize(), userId_);
1545     }
1546     ProcessUpdateShortcut();
1547     BundleResourceHelper::AddResourceInfoByBundleName(bundleName_, userId_,
1548         (isAppExist_ && hasInstalledInUser_) ? ADD_RESOURCE_TYPE::UPDATE_BUNDLE : ADD_RESOURCE_TYPE::INSTALL_BUNDLE,
1549         !isAppExist_);
1550     if (!ProcessExtProfile(installParam)) {
1551         LOG_W(BMS_TAG_INSTALLER, "ProcessExtProfile failed");
1552     }
1553     SetHybridSpawn();
1554     LOG_I(BMS_TAG_INSTALLER, "finish install %{public}s", bundleName_.c_str());
1555     UtdHandler::InstallUtdAsync(bundleName_, userId_);
1556     return result;
1557 }
1558 
CheckAppDistributionType()1559 ErrCode BaseBundleInstaller::CheckAppDistributionType()
1560 {
1561     if (isAppExist_) {
1562         LOG_D(BMS_TAG_INSTALLER, "no check appDisType when bundle update");
1563         return ERR_OK;
1564     }
1565     auto res = bundleInstallChecker_->CheckAppDistributionType(appDistributionType_);
1566     if (res != ERR_OK) {
1567         LOG_E(BMS_TAG_INSTALLER, "check appDisType failed when bundles installed %{public}d", res);
1568         return ERR_APP_DISTRIBUTION_TYPE_NOT_ALLOW_INSTALL;
1569     }
1570     return ERR_OK;
1571 }
1572 
RollBack(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo)1573 void BaseBundleInstaller::RollBack(const std::unordered_map<std::string, InnerBundleInfo> &newInfos,
1574     InnerBundleInfo &oldInfo)
1575 {
1576     LOG_D(BMS_TAG_INSTALLER, "start rollback due to install failed");
1577     if (!isAppExist_) {
1578         if (!newInfos.empty() && newInfos.begin()->second.IsPreInstallApp() &&
1579             !BundleUtil::CheckSystemFreeSize(APP_INSTALL_PATH, FIVE_MB)) {
1580             LOG_I(BMS_TAG_INSTALLER, "pre bundleName:%{public}s no need rollback due to no space",
1581                 newInfos.begin()->second.GetBundleName().c_str());
1582             return;
1583         }
1584         if (newInfos.begin()->second.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE) {
1585             int32_t uid = newInfos.begin()->second.GetUid(userId_);
1586             if (uid != Constants::INVALID_UID) {
1587                 LOG_I(BMS_TAG_INSTALLER, "uninstall atomic service need delete quota, bundleName:%{public}s",
1588                     newInfos.begin()->second.GetBundleName().c_str());
1589                 std::string bundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1]
1590                     + ServiceConstants::PATH_SEPARATOR + std::to_string(userId_) + ServiceConstants::BASE +
1591                     newInfos.begin()->second.GetBundleName();
1592                 PrepareBundleDirQuota(newInfos.begin()->second.GetBundleName(), uid, bundleDataDir, 0);
1593             }
1594         }
1595         RemoveBundleAndDataDir(newInfos.begin()->second, false);
1596         // delete accessTokenId
1597         if (BundlePermissionMgr::DeleteAccessTokenId(newInfos.begin()->second.GetAccessTokenId(userId_)) !=
1598             AccessToken::AccessTokenKitRet::RET_SUCCESS) {
1599             LOG_E(BMS_TAG_INSTALLER, "delete accessToken failed");
1600         }
1601 
1602         // remove driver file
1603         std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1604         for (const auto &info : newInfos) {
1605             driverInstaller->RemoveDriverSoFile(info.second, "", false);
1606         }
1607         // remove profile from code signature
1608         RemoveProfileFromCodeSign(bundleName_);
1609         // remove innerBundleInfo
1610         RemoveInfo(bundleName_, "");
1611         return;
1612     }
1613     InnerBundleInfo preInfo;
1614     bool isExist = false;
1615     if (!GetInnerBundleInfoWithDisable(preInfo, isExist) || !isExist) {
1616         LOG_I(BMS_TAG_INSTALLER, "finish rollback due to install failed");
1617         return;
1618     }
1619     for (const auto &info : newInfos) {
1620         RollBack(info.second, oldInfo);
1621     }
1622     // need delete definePermissions and requestPermissions
1623     UpdateHapToken(preInfo.GetAppType() != oldInfo.GetAppType(), oldInfo);
1624     LOG_D(BMS_TAG_INSTALLER, "finish rollback due to install failed");
1625 }
1626 
RollBack(const InnerBundleInfo & info,InnerBundleInfo & oldInfo)1627 void BaseBundleInstaller::RollBack(const InnerBundleInfo &info, InnerBundleInfo &oldInfo)
1628 {
1629     // rollback hap installed
1630     std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1631     auto modulePackage = info.GetCurrentModulePackage();
1632     if (installedModules_[modulePackage]) {
1633         std::string createModulePath = info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR +
1634             modulePackage + ServiceConstants::TMP_SUFFIX;
1635         RemoveModuleDir(createModulePath);
1636         oldInfo.SetCurrentModulePackage(modulePackage);
1637         RollBackModuleInfo(bundleName_, oldInfo);
1638         // remove driver file of installed module
1639         driverInstaller->RemoveDriverSoFile(info, info.GetModuleName(modulePackage), true);
1640     } else {
1641         RemoveModuleDir(info.GetModuleDir(modulePackage));
1642         // remove driver file
1643         driverInstaller->RemoveDriverSoFile(info, info.GetModuleName(modulePackage), false);
1644         // remove module info
1645         RemoveInfo(bundleName_, modulePackage);
1646     }
1647 }
1648 
RemoveInfo(const std::string & bundleName,const std::string & packageName)1649 void BaseBundleInstaller::RemoveInfo(const std::string &bundleName, const std::string &packageName)
1650 {
1651     LOG_D(BMS_TAG_INSTALLER, "remove innerBundleInfo due to rollback");
1652     if (!InitDataMgr()) {
1653         return;
1654     }
1655     if (packageName.empty()) {
1656         dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UPDATING_FAIL);
1657     } else {
1658         InnerBundleInfo innerBundleInfo;
1659         bool isExist = false;
1660         if (!GetInnerBundleInfoWithDisable(innerBundleInfo, isExist) || !isExist) {
1661             LOG_I(BMS_TAG_INSTALLER, "finish rollback due to install failed");
1662             return;
1663         }
1664         dataMgr_->UpdateBundleInstallState(bundleName, InstallState::ROLL_BACK);
1665         dataMgr_->RemoveModuleInfo(bundleName, packageName, innerBundleInfo);
1666     }
1667     LOG_D(BMS_TAG_INSTALLER, "finish to remove innerBundleInfo due to rollback");
1668 }
1669 
RollBackModuleInfo(const std::string & bundleName,InnerBundleInfo & oldInfo)1670 void BaseBundleInstaller::RollBackModuleInfo(const std::string &bundleName, InnerBundleInfo &oldInfo)
1671 {
1672     LOG_D(BMS_TAG_INSTALLER, "rollBackMoudleInfo due to rollback");
1673     if (!InitDataMgr()) {
1674         return;
1675     }
1676     InnerBundleInfo innerBundleInfo;
1677     bool isExist = false;
1678     if (!GetInnerBundleInfoWithDisable(innerBundleInfo, isExist) || !isExist) {
1679         return;
1680     }
1681     dataMgr_->UpdateBundleInstallState(bundleName, InstallState::ROLL_BACK);
1682     dataMgr_->UpdateInnerBundleInfo(bundleName, oldInfo, innerBundleInfo);
1683     LOG_D(BMS_TAG_INSTALLER, "finsih rollBackMoudleInfo due to rollback");
1684 }
1685 
ProcessBundleUninstall(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)1686 ErrCode BaseBundleInstaller::ProcessBundleUninstall(
1687     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
1688 {
1689     LOG_D(BMS_TAG_INSTALLER, "start to process %{public}s bundle uninstall", bundleName.c_str());
1690     if (bundleName.empty()) {
1691         LOG_E(BMS_TAG_INSTALLER, "uninstall bundle name empty");
1692         return ERR_APPEXECFWK_UNINSTALL_INVALID_NAME;
1693     }
1694 
1695     if (!InitDataMgr()) {
1696         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
1697     }
1698 
1699     userId_ = GetUserId(installParam.userId);
1700     if (userId_ == Constants::INVALID_USERID) {
1701         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
1702     }
1703 
1704     if (!dataMgr_->HasUserId(userId_)) {
1705         LOG_E(BMS_TAG_INSTALLER, "The user %{public}d does not exist when uninstall", userId_);
1706         return ERR_APPEXECFWK_USER_NOT_EXIST;
1707     }
1708 
1709     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
1710     std::lock_guard lock {mtx};
1711     InnerBundleInfo oldInfo;
1712     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); });
1713     bool isAppExist = false;
1714     if (!InitTempBundleFromCache(oldInfo, isAppExist, bundleName) || !isAppExist) {
1715         LOG_W(BMS_TAG_INSTALLER, "uninstall bundle info missing");
1716         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
1717     }
1718     if (installParam.GetIsUninstallAndRecover()) {
1719         PreInstallBundleInfo preInstallBundleInfo;
1720         if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
1721             LOG_E(BMS_TAG_INSTALLER, "UninstallAndRecover %{public}s is not pre-install app", bundleName.c_str());
1722             return ERR_APPEXECFWK_UNINSTALL_AND_RECOVER_NOT_PREINSTALLED_BUNDLE;
1723         }
1724     }
1725     oldApplicationReservedFlag_ = oldInfo.GetApplicationReservedFlag();
1726     bundleType_ = oldInfo.GetApplicationBundleType();
1727     uninstallBundleAppId_ = oldInfo.GetAppId();
1728     versionCode_ = oldInfo.GetVersionCode();
1729     appIdentifier_ = oldInfo.GetAppIdentifier();
1730     isBundleCrossAppSharedConfig_ = oldInfo.IsBundleCrossAppSharedConfig();
1731     if (oldInfo.GetApplicationBundleType() == BundleType::SHARED) {
1732         LOG_E(BMS_TAG_INSTALLER, "uninstall bundle is shared library");
1733         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_IS_SHARED_LIBRARY;
1734     }
1735     UninstallBundleInfo uninstallBundleInfo;
1736     GetUninstallBundleInfo(installParam.isKeepData, userId_, oldInfo, uninstallBundleInfo);
1737 
1738     InnerBundleUserInfo curInnerBundleUserInfo;
1739     if (!oldInfo.GetInnerBundleUserInfo(userId_, curInnerBundleUserInfo)) {
1740         LOG_E(BMS_TAG_INSTALLER, "bundle(%{public}s) get user(%{public}d) failed when uninstall",
1741             oldInfo.GetBundleName().c_str(), userId_);
1742         return ERR_APPEXECFWK_USER_NOT_INSTALL_HAP;
1743     }
1744 
1745     uid = curInnerBundleUserInfo.uid;
1746     bool isForcedUninstall = installParam.IsForcedUninstall() && IsAllowEnterPrise();
1747     if (!installParam.GetForceExecuted() &&
1748         !oldInfo.IsRemovable() && installParam.GetKillProcess() && !installParam.GetIsUninstallAndRecover()) {
1749         if (!isForcedUninstall) {
1750             LOG_E(BMS_TAG_INSTALLER, "uninstall system app");
1751             return ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR;
1752         }
1753     }
1754 
1755     if (!installParam.GetForceExecuted() &&
1756         !oldInfo.GetUninstallState() && installParam.GetKillProcess() && !installParam.GetIsUninstallAndRecover()) {
1757         if (!isForcedUninstall) {
1758             LOG_E(BMS_TAG_INSTALLER, "bundle : %{public}s can not be uninstalled, uninstallState : %{public}d",
1759                 bundleName.c_str(), oldInfo.GetUninstallState());
1760             return ERR_APPEXECFWK_UNINSTALL_STATE_NOT_ALLOW;
1761         }
1762     }
1763 
1764     if (!UninstallAppControl(oldInfo.GetAppId(), userId_)) {
1765         if (!isForcedUninstall) {
1766             LOG_E(BMS_TAG_INSTALLER, "bundleName: %{public}s is not allow uninstall", bundleName.c_str());
1767             return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_UNINSTALL;
1768         }
1769     }
1770 
1771     if (!CheckWhetherCanBeUninstalled(bundleName, appIdentifier_)) {
1772         return ERR_APPEXECFWK_UNINSTALL_CONTROLLED;
1773     }
1774     bool isMultiUser = oldInfo.GetInnerBundleUserInfos().size() > 1;
1775     // when bundle uninstall start, bms need set disposed rule to forbidden app running.
1776     (void)SetDisposedRuleWhenBundleUninstallStart(bundleName, uninstallBundleAppId_, isMultiUser);
1777     // when bundle uninstall end, bms need delete disposed rule.
1778     ScopeGuard deleteDisposedRuleGuard([bundleName, isMultiUser, this] {
1779         (void)DeleteDisposedRuleWhenBundleUninstallEnd(bundleName, uninstallBundleAppId_, isMultiUser);
1780     });
1781 
1782     // reboot scan case will not kill the bundle
1783     if (installParam.GetKillProcess()) {
1784         // kill the bundle process during uninstall.
1785         if (!AbilityManagerHelper::UninstallApplicationProcesses(oldInfo.GetApplicationName(), uid)) {
1786             LOG_E(BMS_TAG_INSTALLER, "can not kill process, uid : %{public}d", uid);
1787             return ERR_APPEXECFWK_UNINSTALL_KILLING_APP_ERROR;
1788         }
1789     }
1790 
1791     std::shared_ptr<BundleCloneInstaller> cloneInstaller = std::make_shared<BundleCloneInstaller>();
1792     cloneInstaller->UninstallAllCloneApps(bundleName, installParam.isRemoveUser, installParam.userId);
1793 
1794 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
1795     std::shared_ptr<AppControlManager> appControlMgr = DelayedSingleton<AppControlManager>::GetInstance();
1796     if (appControlMgr != nullptr) {
1797         LOG_D(BMS_TAG_INSTALLER, "Delete disposed rule when bundleName :%{public}s uninstall", bundleName.c_str());
1798         appControlMgr->DeleteAllDisposedRuleByBundle(oldInfo, Constants::MAIN_APP_INDEX, userId_);
1799     }
1800 #endif
1801 
1802     auto res = RemoveDataGroupDirs(oldInfo.GetBundleName(), userId_, installParam.isKeepData);
1803     if (res != ERR_OK) {
1804         APP_LOGW("remove group dir failed for %{public}s", oldInfo.GetBundleName().c_str());
1805     }
1806 
1807     DeleteEncryptionKeyId(curInnerBundleUserInfo, installParam.isKeepData);
1808     if (!installParam.isRemoveUser &&
1809         !SaveFirstInstallBundleInfo(bundleName, userId_, oldInfo.IsPreInstallApp(), curInnerBundleUserInfo)) {
1810         LOG_E(BMS_TAG_INSTALLER, "save first install bundle info failed");
1811         return ERR_APPEXECFWK_SAVE_FIRST_INSTALL_BUNDLE_ERROR;
1812     }
1813 
1814     if (DeleteEl1ShaderCache(oldInfo, bundleName, userId_) != ERR_OK) {
1815         APP_LOGW("remove el1 shader cache dir failed for %{public}s", bundleName.c_str());
1816     }
1817 
1818     // delete ark startup cache for bundle
1819     DeleteArkStartupCache(ServiceConstants::SYSTEM_OPTIMIZE_PATH, bundleName, userId_);
1820 
1821     if (isMultiUser) {
1822         LOG_D(BMS_TAG_INSTALLER, "only delete userinfo %{public}d", userId_);
1823         if (oldInfo.IsPreInstallApp() && isForcedUninstall) {
1824             LOG_I(BMS_TAG_INSTALLER, "Pre-installed app %{public}s detected, Marking as force uninstalled",
1825                 bundleName.c_str());
1826             MarkIsForceUninstall(bundleName, isForcedUninstall);
1827         }
1828         RemovePluginOnlyInCurrentUser(oldInfo);
1829         auto res = RemoveBundleUserData(oldInfo, installParam.isKeepData, !installParam.isRemoveUser);
1830         if (res != ERR_OK) {
1831             return res;
1832         }
1833         SaveUninstallBundleInfo(bundleName, installParam.isKeepData, uninstallBundleInfo);
1834         UninstallDebugAppSandbox(bundleName, uid, oldInfo);
1835         if (dataMgr_->DeleteShortcutVisibleInfo(bundleName, userId_, 0) != ERR_OK) {
1836             LOG_E(BMS_TAG_INSTALLER,
1837                 "DeleteShortcutVisibleInfo failed, bundleName: %{public}s, userId: %{public}d, appIndex: 0",
1838                 bundleName.c_str(), userId_);
1839         }
1840         BundleResourceHelper::DeleteBundleResourceInfo(bundleName, userId_, true);
1841         return ERR_OK;
1842     }
1843     dataMgr_->DisableBundle(bundleName);
1844 
1845     // kill again after disable bundle
1846     if (installParam.GetKillProcess() && !AbilityManagerHelper::UninstallApplicationProcesses(bundleName, uid)) {
1847         LOG_E(BMS_TAG_INSTALLER, "kill process failed %{public}s", bundleName.c_str());
1848     }
1849 
1850     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START)) {
1851         LOG_E(BMS_TAG_INSTALLER, "uninstall already start");
1852         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
1853     }
1854 
1855     std::string packageName;
1856     oldInfo.SetInstallMark(bundleName, packageName, InstallExceptionStatus::UNINSTALL_BUNDLE_START);
1857     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
1858         LOG_E(BMS_TAG_INSTALLER, "save install mark failed");
1859         return ERR_APPEXECFWK_UPDATE_BUNDLE_ERROR;
1860     }
1861 
1862     ErrCode ret = ProcessBundleUnInstallNative(oldInfo, userId_, bundleName);
1863     if (ret != ERR_OK) {
1864         LOG_E(BMS_TAG_INSTALLER, "remove nativeBundle failed");
1865         return ret;
1866     }
1867 
1868     ErrCode result = RemoveBundle(oldInfo, installParam.isKeepData, !installParam.isRemoveUser);
1869     if (result != ERR_OK) {
1870         LOG_E(BMS_TAG_INSTALLER, "remove whole bundle failed");
1871         return result;
1872     }
1873 
1874     result = DeleteOldArkNativeFile(oldInfo);
1875     if (result != ERR_OK) {
1876         LOG_E(BMS_TAG_INSTALLER, "delete old arkNativeFile failed");
1877         return result;
1878     }
1879 
1880     result = DeleteArkProfile(bundleName, userId_);
1881     if (result != ERR_OK) {
1882         LOG_E(BMS_TAG_INSTALLER, "fail to removeArkProfile, error is %{public}d", result);
1883         return result;
1884     }
1885 
1886     result = DeleteShaderCache(bundleName);
1887     if (result != ERR_OK) {
1888         LOG_E(BMS_TAG_INSTALLER, "fail to DeleteShaderCache, error is %{public}d", result);
1889         return result;
1890     }
1891 
1892     if ((result = CleanAsanDirectory(oldInfo)) != ERR_OK) {
1893         LOG_E(BMS_TAG_INSTALLER, "fail to remove asan log path, error is %{public}d", result);
1894         return result;
1895     }
1896 
1897     enableGuard.Dismiss();
1898 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1899     std::shared_ptr<QuickFixDataMgr> quickFixDataMgr = DelayedSingleton<QuickFixDataMgr>::GetInstance();
1900     if (quickFixDataMgr != nullptr) {
1901         LOG_D(BMS_TAG_INSTALLER, "DeleteInnerAppQuickFix when bundleName :%{public}s uninstall", bundleName.c_str());
1902         quickFixDataMgr->DeleteInnerAppQuickFix(bundleName);
1903     }
1904 #endif
1905     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->DeleteAppProvisionInfo(bundleName)) {
1906         LOG_W(BMS_TAG_INSTALLER, "bundleName: %{public}s delete appProvisionInfo failed", bundleName.c_str());
1907     }
1908     LOG_D(BMS_TAG_INSTALLER, "finish to process %{public}s bundle uninstall", bundleName.c_str());
1909     RemoveDataPreloadHapFiles(bundleName);
1910 
1911     // remove drive so file
1912     std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1913     driverInstaller->RemoveDriverSoFile(oldInfo, "", false);
1914     if (oldInfo.IsPreInstallApp() && (oldInfo.IsRemovable() || isForcedUninstall)) {
1915         LOG_I(BMS_TAG_INSTALLER, "Pre-installed app %{public}s detected, Marking as uninstalled", bundleName.c_str());
1916         MarkPreInstallState(bundleName, true);
1917         if (isForcedUninstall) {
1918             LOG_I(BMS_TAG_INSTALLER, "Pre-installed app %{public}s detected, Marking as force uninstalled",
1919                 bundleName.c_str());
1920             MarkIsForceUninstall(bundleName, isForcedUninstall);
1921         }
1922     }
1923 
1924     DeleteEncryptedStatus(bundleName, uid);
1925     BundleResourceHelper::DeleteBundleResourceInfo(bundleName, userId_, false);
1926     DeleteRouterInfo(bundleName);
1927     // remove profile from code signature
1928     RemoveProfileFromCodeSign(bundleName);
1929     ClearDomainVerifyStatus(oldInfo.GetAppIdentifier(), bundleName);
1930     SaveUninstallBundleInfo(bundleName, installParam.isKeepData, uninstallBundleInfo);
1931     UninstallDebugAppSandbox(bundleName, uid, oldInfo);
1932     if (!PatchDataMgr::GetInstance().DeleteInnerPatchInfo(bundleName)) {
1933         LOG_E(BMS_TAG_INSTALLER, "DeleteInnerPatchInfo failed, bundleName: %{public}s", bundleName.c_str());
1934     }
1935     DeleteCloudShader(bundleName);
1936     if (dataMgr_->DeleteShortcutVisibleInfo(bundleName, userId_, 0) != ERR_OK) {
1937         LOG_E(BMS_TAG_INSTALLER,
1938             "DeleteShortcutVisibleInfo failed, bundleName: %{public}s, userId: %{public}d, appIndex: 0",
1939             bundleName.c_str(), userId_);
1940     }
1941     return ERR_OK;
1942 }
1943 
UninstallDebugAppSandbox(const std::string & bundleName,const int32_t uid,const InnerBundleInfo & innerBundleInfo)1944 void BaseBundleInstaller::UninstallDebugAppSandbox(const std::string &bundleName, const int32_t uid,
1945     const InnerBundleInfo& innerBundleInfo)
1946 {
1947     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
1948     LOG_D(BMS_TAG_INSTALLER, "call UninstallDebugAppSandbox start");
1949     bool isDeveloperMode = OHOS::system::GetBoolParameter(ServiceConstants::DEVELOPERMODE_STATE, false);
1950     bool isDebugApp = innerBundleInfo.GetBaseApplicationInfo().appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG;
1951     if (isDeveloperMode && isDebugApp) {
1952         int32_t flagIndex = 0;
1953         AppSpawnRemoveSandboxDirMsg removeSandboxDirMsg;
1954         removeSandboxDirMsg.code = MSG_UNINSTALL_DEBUG_HAP;
1955         removeSandboxDirMsg.bundleName = bundleName;
1956         removeSandboxDirMsg.bundleIndex = innerBundleInfo.GetAppIndex();
1957         removeSandboxDirMsg.uid = uid;
1958         if (innerBundleInfo.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE) {
1959             removeSandboxDirMsg.flags = APP_FLAGS_ATOMIC_SERVICE;
1960         } else {
1961             removeSandboxDirMsg.flags = static_cast<AppFlagsIndex>(flagIndex);
1962         }
1963         if (BundleAppSpawnClient::GetInstance().RemoveSandboxDir(removeSandboxDirMsg) != 0) {
1964             LOG_E(BMS_TAG_INSTALLER, "removeSandboxDir failed");
1965         }
1966     }
1967     LOG_D(BMS_TAG_INSTALLER, "call UninstallDebugAppSandbox end");
1968 }
1969 
DeleteRouterInfo(const std::string & bundleName,const std::string & moduleName)1970 void BaseBundleInstaller::DeleteRouterInfo(const std::string &bundleName, const std::string &moduleName)
1971 {
1972     if (!InitDataMgr()) {
1973         LOG_E(BMS_TAG_INSTALLER, "init failed");
1974         return;
1975     }
1976     if (moduleName.empty()) {
1977         dataMgr_->DeleteRouterInfo(bundleName);
1978     } else {
1979         dataMgr_->DeleteRouterInfo(bundleName, moduleName);
1980     }
1981 }
1982 
ProcessBundleUninstall(const std::string & bundleName,const std::string & modulePackage,const InstallParam & installParam,int32_t & uid)1983 ErrCode BaseBundleInstaller::ProcessBundleUninstall(
1984     const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam, int32_t &uid)
1985 {
1986     LOG_D(BMS_TAG_INSTALLER, "process %{public}s in %{public}s uninstall", bundleName.c_str(), modulePackage.c_str());
1987     if (bundleName.empty() || modulePackage.empty()) {
1988         LOG_E(BMS_TAG_INSTALLER, "uninstall bundle name or module name empty");
1989         return ERR_APPEXECFWK_UNINSTALL_INVALID_NAME;
1990     }
1991     if (!InitDataMgr()) {
1992         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
1993     }
1994 
1995     userId_ = GetUserId(installParam.userId);
1996     if (userId_ == Constants::INVALID_USERID) {
1997         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
1998     }
1999 
2000     if (!dataMgr_->HasUserId(userId_)) {
2001         LOG_E(BMS_TAG_INSTALLER, "The user %{public}d does not exist when uninstall", userId_);
2002         return ERR_APPEXECFWK_USER_NOT_EXIST;
2003     }
2004 
2005     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
2006     std::lock_guard lock {mtx};
2007     InnerBundleInfo oldInfo;
2008     bool isAppExist = false;
2009     if (!InitTempBundleFromCache(oldInfo, isAppExist, bundleName) || !isAppExist) {
2010         LOG_W(BMS_TAG_INSTALLER, "uninstall bundle info missing");
2011         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
2012     }
2013     uninstallBundleAppId_ = oldInfo.GetAppId();
2014     versionCode_ = oldInfo.GetVersionCode();
2015     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); });
2016     if (oldInfo.GetApplicationBundleType() == BundleType::SHARED) {
2017         LOG_E(BMS_TAG_INSTALLER, "uninstall bundle is shared library");
2018         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_IS_SHARED_LIBRARY;
2019     }
2020 
2021     InnerBundleUserInfo curInnerBundleUserInfo;
2022     if (!oldInfo.GetInnerBundleUserInfo(userId_, curInnerBundleUserInfo)) {
2023         LOG_E(BMS_TAG_INSTALLER, "bundle(%{public}s) get user(%{public}d) failed when uninstall",
2024             oldInfo.GetBundleName().c_str(), userId_);
2025         return ERR_APPEXECFWK_USER_NOT_INSTALL_HAP;
2026     }
2027 
2028     uid = curInnerBundleUserInfo.uid;
2029     if (!installParam.GetForceExecuted()
2030         && !oldInfo.IsRemovable() && installParam.GetKillProcess()) {
2031         LOG_E(BMS_TAG_INSTALLER, "uninstall system app");
2032         return ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR;
2033     }
2034 
2035     if (!installParam.GetForceExecuted() &&
2036         !oldInfo.GetUninstallState() && installParam.GetKillProcess() && !installParam.GetIsUninstallAndRecover()) {
2037         LOG_E(BMS_TAG_INSTALLER, "bundle : %{public}s can not be uninstalled, uninstallState : %{public}d",
2038             bundleName.c_str(), oldInfo.GetUninstallState());
2039         return ERR_APPEXECFWK_UNINSTALL_STATE_NOT_ALLOW;
2040     }
2041 
2042     bool isModuleExist = oldInfo.FindModule(modulePackage);
2043     if (!isModuleExist) {
2044         LOG_E(BMS_TAG_INSTALLER, "uninstall bundle info missing");
2045         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_MODULE;
2046     }
2047     isBundleCrossAppSharedConfig_ = oldInfo.IsBundleCrossAppSharedConfig();
2048 
2049     if (!UninstallAppControl(oldInfo.GetAppId(), userId_)) {
2050         LOG_D(BMS_TAG_INSTALLER, "bundleName: %{public}s is not allow uninstall", bundleName.c_str());
2051         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_UNINSTALL;
2052     }
2053 
2054     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START)) {
2055         LOG_E(BMS_TAG_INSTALLER, "uninstall already start");
2056         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
2057     }
2058 
2059     ScopeGuard stateGuard([&] { dataMgr_->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS); });
2060 
2061     // reboot scan case will not kill the bundle
2062     if (installParam.GetKillProcess()) {
2063         // kill the bundle process during uninstall.
2064         if (!AbilityManagerHelper::UninstallApplicationProcesses(oldInfo.GetApplicationName(), uid)) {
2065             LOG_E(BMS_TAG_INSTALLER, "can not kill process, uid : %{public}d", uid);
2066             return ERR_APPEXECFWK_UNINSTALL_KILLING_APP_ERROR;
2067         }
2068     }
2069 
2070     oldInfo.SetInstallMark(bundleName, modulePackage, InstallExceptionStatus::UNINSTALL_PACKAGE_START);
2071     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
2072         LOG_E(BMS_TAG_INSTALLER, "save install mark failed");
2073         return ERR_APPEXECFWK_UPDATE_BUNDLE_ERROR;
2074     }
2075     UninstallBundleInfo uninstallBundleInfo;
2076     GetUninstallBundleInfo(installParam.isKeepData, userId_, oldInfo, uninstallBundleInfo);
2077 
2078     bool onlyInstallInUser = oldInfo.GetInnerBundleUserInfos().size() == 1;
2079     ErrCode result = ERR_OK;
2080     // if it is the only module in the bundle
2081     if (oldInfo.IsOnlyModule(modulePackage)) {
2082         LOG_I(BMS_TAG_INSTALLER, "%{public}s is only module", modulePackage.c_str());
2083         enableGuard.Dismiss();
2084         stateGuard.Dismiss();
2085 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
2086         std::shared_ptr<AppControlManager> appControlMgr = DelayedSingleton<AppControlManager>::GetInstance();
2087         if (appControlMgr != nullptr) {
2088             LOG_D(BMS_TAG_INSTALLER, "Delete disposed rule when bundleName :%{public}s uninstall", bundleName.c_str());
2089             appControlMgr->DeleteAllDisposedRuleByBundle(oldInfo, Constants::MAIN_APP_INDEX, userId_);
2090         }
2091 #endif
2092         if (!installParam.isRemoveUser &&
2093             !SaveFirstInstallBundleInfo(bundleName, userId_, oldInfo.IsPreInstallApp(), curInnerBundleUserInfo)) {
2094             LOG_E(BMS_TAG_INSTALLER, "save first install bundle info failed");
2095             return ERR_APPEXECFWK_SAVE_FIRST_INSTALL_BUNDLE_ERROR;
2096         }
2097         if (onlyInstallInUser) {
2098             result = ProcessBundleUnInstallNative(oldInfo, userId_, bundleName);
2099             if (result != ERR_OK) {
2100                 LOG_E(BMS_TAG_INSTALLER, "remove nativeBundle failed");
2101                 return result;
2102             }
2103             result = RemoveBundle(oldInfo, installParam.isKeepData);
2104             if (result != ERR_OK) {
2105                 LOG_E(BMS_TAG_INSTALLER, "remove bundle failed");
2106                 return result;
2107             }
2108             // remove profile from code signature
2109             RemoveProfileFromCodeSign(bundleName);
2110 
2111             ClearDomainVerifyStatus(oldInfo.GetAppIdentifier(), bundleName);
2112 
2113             result = DeleteOldArkNativeFile(oldInfo);
2114             if (result != ERR_OK) {
2115                 LOG_E(BMS_TAG_INSTALLER, "delete old arkNativeFile failed");
2116                 return result;
2117             }
2118 
2119             result = DeleteArkProfile(bundleName, userId_);
2120             if (result != ERR_OK) {
2121                 LOG_E(BMS_TAG_INSTALLER, "fail to removeArkProfile, error is %{public}d", result);
2122                 return result;
2123             }
2124 
2125             if ((result = CleanAsanDirectory(oldInfo)) != ERR_OK) {
2126                 LOG_E(BMS_TAG_INSTALLER, "fail to remove asan log path, error is %{public}d", result);
2127                 return result;
2128             }
2129 
2130             RemoveDataPreloadHapFiles(bundleName);
2131             if (oldInfo.IsPreInstallApp() && oldInfo.IsRemovable()) {
2132                 LOG_I(BMS_TAG_INSTALLER, "%{public}s detected, Marking as uninstalled", bundleName.c_str());
2133                 MarkPreInstallState(bundleName, true);
2134             }
2135             DeleteRouterInfo(bundleName);
2136             SaveUninstallBundleInfo(bundleName, installParam.isKeepData, uninstallBundleInfo);
2137             UninstallDebugAppSandbox(bundleName, uid, oldInfo);
2138             BundleResourceHelper::DeleteBundleResourceInfo(bundleName, userId_, false);
2139             return ERR_OK;
2140         }
2141         auto removeRes = RemoveBundleUserData(oldInfo, installParam.isKeepData);
2142         if (removeRes != ERR_OK) {
2143             return removeRes;
2144         }
2145         SaveUninstallBundleInfo(bundleName, installParam.isKeepData, uninstallBundleInfo);
2146         UninstallDebugAppSandbox(bundleName, uid, oldInfo);
2147         if (!PatchDataMgr::GetInstance().DeleteInnerPatchInfo(bundleName)) {
2148             LOG_E(BMS_TAG_INSTALLER, "DeleteInnerPatchInfo failed, bundleName: %{public}s", bundleName.c_str());
2149         }
2150         BundleResourceHelper::DeleteBundleResourceInfo(bundleName, userId_, true);
2151         return ERR_OK;
2152     }
2153 
2154     if (onlyInstallInUser) {
2155         LOG_I(BMS_TAG_INSTALLER, "%{public}s is only install at the userId %{public}d", bundleName.c_str(), userId_);
2156         result = RemoveModuleAndDataDir(oldInfo, modulePackage, userId_, installParam.isKeepData);
2157         DeleteRouterInfo(bundleName, modulePackage);
2158     }
2159 
2160     if (result != ERR_OK) {
2161         LOG_E(BMS_TAG_INSTALLER, "remove module dir failed");
2162         return result;
2163     }
2164 
2165     oldInfo.SetInstallMark(bundleName, modulePackage, InstallExceptionStatus::INSTALL_FINISH);
2166     LOG_D(BMS_TAG_INSTALLER, "remove module %{public}s in %{public}s ", modulePackage.c_str(), bundleName.c_str());
2167     if (!dataMgr_->RemoveModuleInfo(bundleName, modulePackage, oldInfo)) {
2168         LOG_E(BMS_TAG_INSTALLER, "RemoveModuleInfo failed");
2169         return ERR_APPEXECFWK_RMV_MODULE_ERROR;
2170     }
2171     std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
2172     driverInstaller->RemoveDriverSoFile(oldInfo, oldInfo.GetModuleName(modulePackage), false);
2173     isBundleExist_ = true;
2174     LOG_D(BMS_TAG_INSTALLER, "finish %{public}s in %{public}s uninstall", bundleName.c_str(), modulePackage.c_str());
2175     return ERR_OK;
2176 }
2177 
MarkPreInstallState(const std::string & bundleName,bool isUninstalled)2178 void BaseBundleInstaller::MarkPreInstallState(const std::string &bundleName, bool isUninstalled)
2179 {
2180     LOG_I(BMS_TAG_INSTALLER, "bundle: %{public}s isUninstalled: %{public}d", bundleName.c_str(), isUninstalled);
2181     if (!dataMgr_) {
2182         LOG_E(BMS_TAG_INSTALLER, "dataMgr is nullptr");
2183         return;
2184     }
2185 
2186     PreInstallBundleInfo preInstallBundleInfo;
2187     preInstallBundleInfo.SetBundleName(bundleName);
2188     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
2189         LOG_I(BMS_TAG_INSTALLER, "No PreInstallBundleInfo(%{public}s) in db", bundleName.c_str());
2190         return;
2191     }
2192 
2193     preInstallBundleInfo.SetIsUninstalled(isUninstalled);
2194     dataMgr_->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
2195 }
2196 
UpdateRouterInfo()2197 void BaseBundleInstaller::UpdateRouterInfo()
2198 {
2199     InnerBundleInfo bundle;
2200     if (tempInfo_.GetTempBundleInfo(bundle)) {
2201         dataMgr_->UpdateRouterInfo(bundle);
2202     }
2203 }
2204 
ProcessInstallBundleByBundleName(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)2205 ErrCode BaseBundleInstaller::ProcessInstallBundleByBundleName(
2206     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
2207 {
2208     LOG_D(BMS_TAG_INSTALLER, "Process Install Bundle(%{public}s) start", bundleName.c_str());
2209     return InnerProcessInstallByPreInstallInfo(bundleName, installParam, uid);
2210 }
2211 
ProcessRecover(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)2212 ErrCode BaseBundleInstaller::ProcessRecover(
2213     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
2214 {
2215     LOG_D(BMS_TAG_INSTALLER, "Process Recover Bundle(%{public}s) start", bundleName.c_str());
2216     int32_t userId = GetUserId(installParam.userId);
2217     if (!CheckCanInstallPreBundle(bundleName, userId)) {
2218         LOG_E(BMS_TAG_INSTALLER, "Bundle(%{public}s) was force uninstalled before, not allow recover",
2219             bundleName.c_str());
2220         return ERR_APPEXECFWK_INSTALL_FORCE_UNINSTALLED_BUNDLE_NOT_ALLOW_RECOVER;
2221     }
2222     if (AccountHelper::CheckOsAccountConstraintEnabled(userId, ServiceConstants::CONSTRAINT_APPS_INSTALL)) {
2223         LOG_E(BMS_TAG_INSTALLER, "user %{public}d is not allowed to recover %{public}s", userId, bundleName.c_str());
2224         return ERR_APPEXECFWK_INSTALL_FAILED_ACCOUNT_CONSTRAINT;
2225     }
2226     ErrCode result = InnerProcessInstallByPreInstallInfo(bundleName, installParam, uid);
2227     return result;
2228 }
2229 
InnerProcessInstallByPreInstallInfo(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)2230 ErrCode BaseBundleInstaller::InnerProcessInstallByPreInstallInfo(
2231     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
2232 {
2233     if (!InitDataMgr()) {
2234         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
2235     }
2236 
2237     userId_ = GetUserId(installParam.userId);
2238     if (userId_ == Constants::INVALID_USERID) {
2239         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
2240     }
2241 
2242     if (!dataMgr_->HasUserId(userId_)) {
2243         LOG_E(BMS_TAG_INSTALLER, "The user %{public}d does not exist", userId_);
2244         return ERR_APPEXECFWK_USER_NOT_EXIST;
2245     }
2246 
2247     {
2248         auto &mtx = dataMgr_->GetBundleMutex(bundleName);
2249         std::lock_guard lock {mtx};
2250         InnerBundleInfo oldInfo;
2251         InitTempBundleFromCache(oldInfo, isAppExist_, bundleName);
2252         if (isAppExist_) {
2253             if (oldInfo.GetApplicationBundleType() == BundleType::SHARED) {
2254                 LOG_D(BMS_TAG_INSTALLER, "shared bundle (%{public}s) is irrelevant to user", bundleName.c_str());
2255                 return ERR_OK;
2256             }
2257 
2258             versionCode_ = oldInfo.GetVersionCode();
2259             if (oldInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK) {
2260                 LOG_D(BMS_TAG_INSTALLER, "Appservice (%{public}s) only install in U0", bundleName.c_str());
2261                 return ERR_OK;
2262             }
2263 
2264             if (oldInfo.HasInnerBundleUserInfo(userId_)) {
2265                 LOG_E(BMS_TAG_INSTALLER, "App is exist in user(%{public}d)", userId_);
2266                 return ERR_APPEXECFWK_INSTALL_ALREADY_EXIST;
2267             }
2268 
2269             ErrCode ret = InstallNormalAppControl(oldInfo.GetAppId(), userId_, installParam.isPreInstallApp);
2270             if (ret != ERR_OK) {
2271                 LOG_E(BMS_TAG_INSTALLER, "%{private}s check install app control failed", oldInfo.GetAppId().c_str());
2272                 return ret;
2273             }
2274 
2275             ret = CheckSingleton(oldInfo, userId_);
2276             CHECK_RESULT(ret, "Check singleton failed %{public}d");
2277 
2278             ret = CheckU1Enable(oldInfo, userId_);
2279             CHECK_RESULT(ret, "CheckU1Enable failed %{public}d");
2280 
2281             InnerBundleUserInfo curInnerBundleUserInfo;
2282             curInnerBundleUserInfo.bundleUserInfo.userId = userId_;
2283             curInnerBundleUserInfo.bundleName = bundleName;
2284             oldInfo.AddInnerBundleUserInfo(curInnerBundleUserInfo);
2285             ScopeGuard userGuard([&] { RemoveBundleUserData(oldInfo, false); });
2286             Security::AccessToken::AccessTokenIDEx accessTokenIdEx;
2287             Security::AccessToken::HapInfoCheckResult checkResult;
2288             if (!RecoverHapToken(bundleName_, userId_, accessTokenIdEx, oldInfo)) {
2289                 if (BundlePermissionMgr::InitHapToken(oldInfo, userId_, 0, accessTokenIdEx, checkResult,
2290                     verifyRes_.GetProvisionInfo().appServiceCapabilities) != ERR_OK) {
2291                     LOG_E(BMS_TAG_INSTALLER, "bundleName:%{public}s InitHapToken failed", bundleName_.c_str());
2292                     SetVerifyPermissionResult(checkResult);
2293                     return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
2294                 }
2295             }
2296             accessTokenId_ = accessTokenIdEx.tokenIdExStruct.tokenID;
2297             oldInfo.SetAccessTokenIdEx(accessTokenIdEx, userId_);
2298 
2299             auto result = CreateBundleUserData(oldInfo);
2300             if (result != ERR_OK) {
2301                 return result;
2302             }
2303             std::vector<std::string> extensionDirs = oldInfo.GetAllExtensionDirs();
2304             createExtensionDirs_.assign(extensionDirs.begin(), extensionDirs.end());
2305             CreateExtensionDataDir(oldInfo);
2306             bundleName_ = bundleName;
2307             CreateScreenLockProtectionDir();
2308             // extract ap file
2309             result = ExtractAllArkProfileFile(oldInfo);
2310             if (result != ERR_OK) {
2311                 LOG_W(BMS_TAG_INSTALLER, "ExtractAllArkProfileFile failed -n %{public}s", bundleName_.c_str());
2312             }
2313 
2314             userGuard.Dismiss();
2315             uid = oldInfo.GetUid(userId_);
2316             GetInstallEventInfo(oldInfo, sysEventInfo_);
2317             if (!dataMgr_->UpdateInnerBundleInfo(oldInfo, true)) {
2318                 if (!dataMgr_->UpdateInnerBundleInfo(oldInfo, true)) {
2319                     LOG_W(BMS_TAG_INSTALLER, "save mark failed, -n:%{public}s", bundleName_.c_str());
2320                     return ERR_APPEXECFWK_UPDATE_BUNDLE_ERROR;
2321                 }
2322             }
2323             SetHybridSpawn();
2324             UtdHandler::InstallUtdAsync(bundleName, userId_);
2325             GenerateNewUserDataGroupInfos(oldInfo);
2326             isBundleCrossAppSharedConfig_ = oldInfo.IsBundleCrossAppSharedConfig();
2327             // remove userid record in preInstallBundleInfo
2328             PreInstallBundleInfo preInstallBundleInfo;
2329             preInstallBundleInfo.SetBundleName(bundleName);
2330             if (dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
2331                 preInstallBundleInfo.DeleteForceUnisntalledUser(userId_);
2332                 dataMgr_->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
2333             }
2334             // process resource
2335             BundleResourceHelper::AddResourceInfoByBundleName(bundleName, userId_, ADD_RESOURCE_TYPE::CREATE_USER);
2336             return ERR_OK;
2337         }
2338     }
2339     bool onDemandInstall = OnDemandInstallDataMgr::GetInstance().IsOnDemandInstall(installParam);
2340     PreInstallBundleInfo preInstallBundleInfo;
2341     preInstallBundleInfo.SetBundleName(bundleName);
2342     if (onDemandInstall) {
2343         return RecoverOnDemandInstallBundle(bundleName, installParam, uid);
2344     }
2345     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)
2346         || preInstallBundleInfo.GetBundlePaths().empty()) {
2347         LOG_E(BMS_TAG_INSTALLER, "Get PreInstallBundleInfo failed, bundleName: %{public}s", bundleName.c_str());
2348         return ERR_APPEXECFWK_RECOVER_INVALID_BUNDLE_NAME;
2349     }
2350     LOG_D(BMS_TAG_INSTALLER, "Get preInstall bundlePath success");
2351     std::vector<std::string> pathVec;
2352     auto innerInstallParam = installParam;
2353     bool isSharedBundle = preInstallBundleInfo.GetBundlePaths().front().find(PRE_INSTALL_HSP_PATH) != std::string::npos;
2354     if (isSharedBundle) {
2355         innerInstallParam.sharedBundleDirPaths = preInstallBundleInfo.GetBundlePaths();
2356     } else {
2357         pathVec = preInstallBundleInfo.GetBundlePaths();
2358     }
2359     innerInstallParam.isPreInstallApp = true;
2360     innerInstallParam.removable = preInstallBundleInfo.IsRemovable();
2361     innerInstallParam.copyHapToInstallPath = false;
2362     innerInstallParam.isDataPreloadHap = IsDataPreloadHap(pathVec.empty() ? "" : pathVec.front());
2363     ErrCode resultCode = ProcessBundleInstall(pathVec, innerInstallParam, preInstallBundleInfo.GetAppType(), uid, true);
2364     if (resultCode != ERR_OK && innerInstallParam.isDataPreloadHap) {
2365         LOG_E(BMS_TAG_INSTALLER, "set parameter BMS_DATA_PRELOAD false");
2366         OHOS::system::SetParameter(ServiceConstants::BMS_DATA_PRELOAD, BMS_FALSE);
2367     }
2368     return resultCode;
2369 }
2370 
RemoveBundle(InnerBundleInfo & info,bool isKeepData,const bool async)2371 ErrCode BaseBundleInstaller::RemoveBundle(InnerBundleInfo &info, bool isKeepData, const bool async)
2372 {
2373     if (!InitDataMgr()) {
2374         return ERR_APPEXECFWK_NULL_PTR;
2375     }
2376     if (!dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::UNINSTALL_SUCCESS, isKeepData)) {
2377         LOG_E(BMS_TAG_INSTALLER, "delete inner info failed");
2378         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
2379     }
2380     if (info.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE) {
2381         int32_t uid = info.GetUid(userId_);
2382         if (uid != Constants::INVALID_UID) {
2383             LOG_I(BMS_TAG_INSTALLER, "uninstall atomic service need delete quota, bundleName:%{public}s",
2384                 info.GetBundleName().c_str());
2385             std::string bundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1] +
2386                 ServiceConstants::PATH_SEPARATOR + std::to_string(userId_) + ServiceConstants::BASE +
2387                 info.GetBundleName();
2388             PrepareBundleDirQuota(info.GetBundleName(), uid, bundleDataDir, 0);
2389         }
2390     }
2391     ErrCode result = RemoveBundleAndDataDir(info, isKeepData, async);
2392     if (result != ERR_OK) {
2393         LOG_E(BMS_TAG_INSTALLER, "remove bundle dir failed");
2394         return result;
2395     }
2396 
2397     accessTokenId_ = info.GetAccessTokenId(userId_);
2398     if (!isKeepData) {
2399         if (BundlePermissionMgr::DeleteAccessTokenId(accessTokenId_) !=
2400             AccessToken::AccessTokenKitRet::RET_SUCCESS) {
2401             LOG_E(BMS_TAG_INSTALLER, "delete accessToken failed");
2402         }
2403     }
2404 
2405     return ERR_OK;
2406 }
2407 
ProcessBundleInstallNative(InnerBundleInfo & info,int32_t & userId)2408 ErrCode BaseBundleInstaller::ProcessBundleInstallNative(InnerBundleInfo &info, int32_t &userId)
2409 {
2410     if (info.GetInnerModuleInfoHnpInfo(info.GetCurModuleName())) {
2411         std::string moduleHnpsPath = info.GetInnerModuleInfoHnpPath(info.GetCurModuleName());
2412         ErrCode ret = InstalldClient::GetInstance()->ProcessBundleInstallNative(std::to_string(userId), moduleHnpsPath,
2413             modulePath_, info.GetCpuAbi(), info.GetBundleName());
2414         if (ret != ERR_OK) {
2415             LOG_E(BMS_TAG_INSTALLER, "installing the native package failed. error code: %{public}d", ret);
2416             return ret;
2417         }
2418         if ((InstalldClient::GetInstance()->RemoveDir(moduleHnpsPath)) != ERR_OK) {
2419             LOG_E(BMS_TAG_INSTALLER, "delete dir %{public}s failed", moduleHnpsPath.c_str());
2420         }
2421     }
2422     return ERR_OK;
2423 }
2424 
ProcessBundleUnInstallNative(InnerBundleInfo & info,int32_t & userId,std::string bundleName)2425 ErrCode BaseBundleInstaller::ProcessBundleUnInstallNative(InnerBundleInfo &info,
2426     int32_t &userId, std::string bundleName)
2427 {
2428     if (info.GetInnerModuleInfoHnpInfo(info.GetCurModuleName())) {
2429         ErrCode ret = InstalldClient::GetInstance()->ProcessBundleUnInstallNative(
2430             std::to_string(userId).c_str(), bundleName.c_str());
2431         if (ret != ERR_OK) {
2432             LOG_E(BMS_TAG_INSTALLER, "uninstalling the native package failed. error code: %{public}d", ret);
2433             return ret;
2434         }
2435     }
2436     return ERR_OK;
2437 }
2438 
ProcessBundleInstallStatus(InnerBundleInfo & info,int32_t & uid)2439 ErrCode BaseBundleInstaller::ProcessBundleInstallStatus(InnerBundleInfo &info, int32_t &uid)
2440 {
2441     modulePackage_ = info.GetCurrentModulePackage();
2442     LOG_D(BMS_TAG_INSTALLER, "ProcessBundleInstallStatus with bundleName %{public}s and packageName %{public}s",
2443         bundleName_.c_str(), modulePackage_.c_str());
2444     if (!InitDataMgr()) {
2445         return ERR_APPEXECFWK_NULL_PTR;
2446     }
2447     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_START)) {
2448         LOG_E(BMS_TAG_INSTALLER, "install already start");
2449         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
2450     }
2451 
2452     Security::AccessToken::AccessTokenIDEx accessTokenIdEx;
2453     Security::AccessToken::HapInfoCheckResult checkResult;
2454     if (!RecoverHapToken(bundleName_, userId_, accessTokenIdEx, info)) {
2455         if (BundlePermissionMgr::InitHapToken(info, userId_, 0, accessTokenIdEx, checkResult,
2456             verifyRes_.GetProvisionInfo().appServiceCapabilities) != ERR_OK) {
2457             LOG_E(BMS_TAG_INSTALLER, "bundleName:%{public}s InitHapToken failed", bundleName_.c_str());
2458             SetVerifyPermissionResult(checkResult);
2459             return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
2460         }
2461     }
2462     accessTokenId_ = accessTokenIdEx.tokenIdExStruct.tokenID;
2463     info.SetAccessTokenIdEx(accessTokenIdEx, userId_);
2464 
2465     info.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::INSTALL_START);
2466 
2467     ScopeGuard stateGuard([&] { dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_FAIL); });
2468     ErrCode result = CreateBundleAndDataDir(info);
2469     if (result != ERR_OK) {
2470         LOG_E(BMS_TAG_INSTALLER, "create bundle and data dir failed");
2471         return result;
2472     }
2473 
2474     ScopeGuard bundleGuard([&] { RemoveBundleAndDataDir(info, false); });
2475     std::string modulePath = info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR + modulePackage_;
2476     result = ExtractModule(info, modulePath);
2477     if (result != ERR_OK) {
2478         LOG_E(BMS_TAG_INSTALLER, "extract module failed");
2479         return result;
2480     }
2481 
2482     result = ProcessBundleInstallNative(info, userId_);
2483     if (result != ERR_OK) {
2484         LOG_E(BMS_TAG_INSTALLER, "Install Native failed");
2485         return result;
2486     }
2487 
2488     uid = info.GetUid(userId_);
2489     int64_t currentTime = BundleUtil::GetCurrentTimeMs();
2490     info.SetBundleInstallTime(currentTime, userId_);
2491     SetFirstInstallTime(bundleName_, currentTime, info);
2492     tempInfo_.SetTempBundleInfo(info);
2493     stateGuard.Dismiss();
2494     bundleGuard.Dismiss();
2495 
2496     LOG_D(BMS_TAG_INSTALLER, "finish to call processBundleInstallStatus");
2497     return ERR_OK;
2498 }
2499 
AllowSingletonChange(const std::string & bundleName)2500 bool BaseBundleInstaller::AllowSingletonChange(const std::string &bundleName)
2501 {
2502     return ServiceConstants::SINGLETON_WHITE_LIST.find(bundleName) != ServiceConstants::SINGLETON_WHITE_LIST.end();
2503 }
2504 
ProcessBundleUpdateStatus(InnerBundleInfo & oldInfo,InnerBundleInfo & newInfo,bool isReplace,bool killProcess)2505 ErrCode BaseBundleInstaller::ProcessBundleUpdateStatus(
2506     InnerBundleInfo &oldInfo, InnerBundleInfo &newInfo, bool isReplace, bool killProcess)
2507 {
2508     if (!InitDataMgr()) {
2509         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
2510     }
2511     modulePackage_ = newInfo.GetCurrentModulePackage();
2512     if (modulePackage_.empty()) {
2513         LOG_E(BMS_TAG_INSTALLER, "get current package failed");
2514         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
2515     }
2516 
2517     if (isFeatureNeedUninstall_) {
2518         uninstallModuleVec_.emplace_back(modulePackage_);
2519     }
2520 
2521     if (oldInfo.IsSingleton() != newInfo.IsSingleton()) {
2522         if ((oldInfo.IsSingleton() && !newInfo.IsSingleton()) && newInfo.IsPreInstallApp()
2523             && AllowSingletonChange(newInfo.GetBundleName())) {
2524             singletonState_ = SingletonState::SINGLETON_TO_NON;
2525         } else if ((!oldInfo.IsSingleton() && newInfo.IsSingleton()) && newInfo.IsPreInstallApp()
2526             && AllowSingletonChange(newInfo.GetBundleName())) {
2527             singletonState_ = SingletonState::NON_TO_SINGLETON;
2528         } else {
2529             LOG_E(BMS_TAG_INSTALLER, "Singleton not allow changed");
2530             return ERR_APPEXECFWK_INSTALL_SINGLETON_INCOMPATIBLE;
2531         }
2532         LOG_I(BMS_TAG_INSTALLER, "Singleton %{public}s changed", newInfo.GetBundleName().c_str());
2533     }
2534 
2535     auto result = CheckOverlayUpdate(oldInfo, newInfo, userId_);
2536     if (result != ERR_OK) {
2537         LOG_E(BMS_TAG_INSTALLER, "CheckOverlayUpdate failed due to %{public}d", result);
2538         return result;
2539     }
2540 
2541     LOG_D(BMS_TAG_INSTALLER, "%{public}s, %{public}s", newInfo.GetBundleName().c_str(), modulePackage_.c_str());
2542     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_START)) {
2543         LOG_E(BMS_TAG_INSTALLER, "update already start");
2544         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
2545     }
2546 
2547     if (!CheckAppIdentifier(oldInfo.GetAppIdentifier(), newInfo.GetAppIdentifier(),
2548         oldInfo.GetProvisionId(), newInfo.GetProvisionId())) {
2549         return ERR_APPEXECFWK_INSTALL_FAILED_INCONSISTENT_SIGNATURE;
2550     }
2551     LOG_D(BMS_TAG_INSTALLER, "ProcessBundleUpdateStatus killProcess = %{public}d", killProcess);
2552     // now there are two cases for updating:
2553     // 1. bundle exist, hap exist, update hap
2554     // 2. bundle exist, install new hap
2555     bool isModuleExist = oldInfo.FindModule(modulePackage_);
2556     if (isModuleExist) {
2557         isModuleUpdate_ = true;
2558     }
2559     newInfo.RestoreFromOldInfo(oldInfo);
2560     result = isModuleExist ? ProcessModuleUpdate(newInfo, oldInfo,
2561         isReplace, killProcess) : ProcessNewModuleInstall(newInfo, oldInfo);
2562     if (result != ERR_OK) {
2563         LOG_E(BMS_TAG_INSTALLER, "install module failed %{public}d", result);
2564         return result;
2565     }
2566     LOG_D(BMS_TAG_INSTALLER, "finish to call ProcessBundleUpdateStatus");
2567     return ERR_OK;
2568 }
2569 
CheckAppIdentifier(const std::string & oldAppIdentifier,const std::string & newAppIdentifier,const std::string & oldAppId,const std::string & newAppId)2570 bool BaseBundleInstaller::CheckAppIdentifier(const std::string &oldAppIdentifier, const std::string &newAppIdentifier,
2571     const std::string &oldAppId, const std::string &newAppId)
2572 {
2573     // for versionCode update
2574     if (!oldAppIdentifier.empty() &&
2575         !newAppIdentifier.empty() &&
2576         oldAppIdentifier == newAppIdentifier) {
2577         return true;
2578     }
2579     if (oldAppId == newAppId) {
2580         return true;
2581     }
2582     LOG_E(BMS_TAG_INSTALLER, "the appIdentifier or appId of the new bundle is not the same as old one");
2583     return false;
2584 }
2585 
ProcessNewModuleInstall(InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo)2586 ErrCode BaseBundleInstaller::ProcessNewModuleInstall(InnerBundleInfo &newInfo, InnerBundleInfo &oldInfo)
2587 {
2588     LOG_D(BMS_TAG_INSTALLER, "ProcessNewModuleInstall %{public}s, userId: %{public}d",
2589         newInfo.GetBundleName().c_str(), userId_);
2590     if (!InitDataMgr()) {
2591         return ERR_APPEXECFWK_NULL_PTR;
2592     }
2593     if ((!isFeatureNeedUninstall_ && !otaInstall_) && (newInfo.HasEntry() && oldInfo.HasEntry())) {
2594         LOG_E(BMS_TAG_INSTALLER, "install more than one entry module");
2595         return ERR_APPEXECFWK_INSTALL_ENTRY_ALREADY_EXIST;
2596     }
2597 
2598     if ((!isFeatureNeedUninstall_ && !otaInstall_) &&
2599         bundleInstallChecker_->IsContainModuleName(newInfo, oldInfo)) {
2600         LOG_E(BMS_TAG_INSTALLER, "moduleName is already existed");
2601         return ERR_APPEXECFWK_INSTALL_NOT_UNIQUE_DISTRO_MODULE_NAME;
2602     }
2603 
2604     // same version need to check app label
2605     ErrCode result = ERR_OK;
2606     if (!otaInstall_ && (oldInfo.GetVersionCode() == newInfo.GetVersionCode())) {
2607         result = CheckAppLabel(oldInfo, newInfo);
2608         if (result != ERR_OK) {
2609             LOG_E(BMS_TAG_INSTALLER, "CheckAppLabel failed %{public}d", result);
2610             return result;
2611         }
2612         if (!CheckDuplicateProxyData(newInfo, oldInfo)) {
2613             LOG_E(BMS_TAG_INSTALLER, "CheckDuplicateProxyData with old info failed");
2614             return ERR_APPEXECFWK_INSTALL_CHECK_PROXY_DATA_URI_FAILED;
2615         }
2616     }
2617     if (isAppExist_) {
2618         oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_NEW_START);
2619     }
2620     std::string modulePath = GetModulePath(newInfo, isFeatureNeedUninstall_, false);
2621     result = ExtractModule(newInfo, modulePath);
2622     if (result != ERR_OK) {
2623         LOG_E(BMS_TAG_INSTALLER, "extract module and rename failed");
2624         return result;
2625     }
2626 
2627     result = ProcessBundleInstallNative(newInfo, userId_);
2628     if (result != ERR_OK) {
2629         LOG_E(BMS_TAG_INSTALLER, "Install Native failed");
2630         return result;
2631     }
2632 
2633     ScopeGuard moduleGuard([&] { RemoveModuleDir(modulePath); });
2634     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
2635         LOG_E(BMS_TAG_INSTALLER, "new moduleupdate state failed");
2636         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
2637     }
2638 
2639     oldInfo.SetBundleUpdateTime(BundleUtil::GetCurrentTimeMs(), userId_);
2640     if ((result = ProcessAsanDirectory(newInfo)) != ERR_OK) {
2641         LOG_E(BMS_TAG_INSTALLER, "process asan log directory failed");
2642         return result;
2643     }
2644     if (!dataMgr_->AddNewModuleInfo(newInfo, oldInfo)) {
2645         LOG_E(BMS_TAG_INSTALLER, "add module %{public}s to innerBundleInfo %{public}s failed",
2646             modulePackage_.c_str(), bundleName_.c_str());
2647         return ERR_APPEXECFWK_ADD_MODULE_ERROR;
2648     }
2649     tempInfo_.SetTempBundleInfo(oldInfo);
2650     moduleGuard.Dismiss();
2651     return ERR_OK;
2652 }
2653 
ProcessModuleUpdate(InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo,bool isReplace,bool killProcess)2654 ErrCode BaseBundleInstaller::ProcessModuleUpdate(InnerBundleInfo &newInfo,
2655     InnerBundleInfo &oldInfo, bool isReplace, bool killProcess)
2656 {
2657     LOG_D(BMS_TAG_INSTALLER, "bundleName :%{public}s, moduleName: %{public}s, userId: %{public}d",
2658         newInfo.GetBundleName().c_str(), newInfo.GetCurrentModulePackage().c_str(), userId_);
2659     if (!InitDataMgr()) {
2660         return ERR_APPEXECFWK_NULL_PTR;
2661     }
2662     // update module type is forbidden
2663     if ((!isFeatureNeedUninstall_ && !otaInstall_) && (newInfo.HasEntry() && oldInfo.HasEntry())) {
2664         if (!oldInfo.IsEntryModule(modulePackage_)) {
2665             LOG_E(BMS_TAG_INSTALLER, "install more than one entry module");
2666             return ERR_APPEXECFWK_INSTALL_ENTRY_ALREADY_EXIST;
2667         }
2668     }
2669 
2670     if ((!isFeatureNeedUninstall_ && !otaInstall_) &&
2671         !bundleInstallChecker_->IsExistedDistroModule(newInfo, oldInfo)) {
2672         LOG_E(BMS_TAG_INSTALLER, "moduleName is inconsistent in the updating hap");
2673         return ERR_APPEXECFWK_INSTALL_INCONSISTENT_MODULE_NAME;
2674     }
2675 
2676     ErrCode result = ERR_OK;
2677     if (!otaInstall_ && (versionCode_ == oldInfo.GetVersionCode())) {
2678         if (((result = CheckAppLabel(oldInfo, newInfo)) != ERR_OK)) {
2679             LOG_E(BMS_TAG_INSTALLER, "CheckAppLabel failed %{public}d", result);
2680             return result;
2681         }
2682 
2683         if (!isReplace) {
2684             if (hasInstalledInUser_) {
2685                 LOG_E(BMS_TAG_INSTALLER, "fail to install already existing bundle using normal flag");
2686                 return ERR_APPEXECFWK_INSTALL_ALREADY_EXIST;
2687             }
2688 
2689             // app versionCode equals to the old and do not need to update module
2690             // and only need to update userInfo
2691             newInfo.SetOnlyCreateBundleUser(true);
2692             if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
2693                 LOG_E(BMS_TAG_INSTALLER, "update state failed");
2694                 return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
2695             }
2696             return ERR_OK;
2697         }
2698     }
2699 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
2700     result = OverlayDataMgr::GetInstance()->UpdateOverlayModule(newInfo, oldInfo);
2701     CHECK_RESULT(result, "UpdateOverlayModule failed %{public}d");
2702 #endif
2703 
2704     LOG_D(BMS_TAG_INSTALLER, "ProcessModuleUpdate killProcess = %{public}d", killProcess);
2705     // reboot scan case will not kill the bundle
2706     if (killProcess) {
2707         UpdateKillApplicationProcess(oldInfo);
2708     }
2709 
2710     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_EXISTED_START);
2711 
2712     result = CheckArkProfileDir(newInfo, oldInfo);
2713     CHECK_RESULT(result, "CheckArkProfileDir failed %{public}d");
2714 
2715     auto hnpPackageOldInfos = oldInfo.GetInnerModuleInfoHnpInfo(oldInfo.GetCurModuleName());
2716     auto hnpPackageNewInfos = newInfo.GetInnerModuleInfoHnpInfo(newInfo.GetCurModuleName());
2717     if (hnpPackageOldInfos) {
2718         for (const auto &item : *hnpPackageOldInfos) {
2719             auto it = std::find_if(hnpPackageNewInfos->begin(), hnpPackageNewInfos->end(),
2720             [&](const HnpPackage &hnpPackage) {return hnpPackage.package == item.package;});
2721             if (it == hnpPackageNewInfos->end()) {
2722                 ErrCode ret = ProcessBundleUnInstallNative(oldInfo, userId_, bundleName_);
2723                 if (ret != ERR_OK) {
2724                     LOG_E(BMS_TAG_INSTALLER, "remove nativeBundle failed");
2725                     return ret;
2726                 }
2727             }
2728         }
2729     }
2730     result = ProcessAsanDirectory(newInfo);
2731     CHECK_RESULT(result, "process asan log directory failed %{public}d");
2732 
2733     result = ExtractModule(newInfo, GetModulePath(newInfo, isFeatureNeedUninstall_, true));
2734     CHECK_RESULT(result, "extract module and rename failed %{public}d");
2735 
2736     result = ProcessBundleInstallNative(newInfo, userId_);
2737     if (result != ERR_OK) {
2738         LOG_E(BMS_TAG_INSTALLER, "Install Native failed");
2739         return result;
2740     }
2741 
2742     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
2743         LOG_E(BMS_TAG_INSTALLER, "old module update state failed");
2744         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
2745     }
2746 
2747     newInfo.RestoreModuleInfo(oldInfo);
2748     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_FINISH);
2749     oldInfo.SetBundleUpdateTime(BundleUtil::GetCurrentTimeMs(), userId_);
2750     if (!dataMgr_->UpdateInnerBundleInfo(newInfo, oldInfo)) {
2751         LOG_E(BMS_TAG_INSTALLER, "update innerBundleInfo %{public}s failed", bundleName_.c_str());
2752         return ERR_APPEXECFWK_UPDATE_BUNDLE_ERROR;
2753     }
2754     tempInfo_.SetTempBundleInfo(oldInfo);
2755     needDeleteQuickFixInfo_ = true;
2756     return ERR_OK;
2757 }
2758 
ProcessQuickFixWhenInstallNewModule(const InstallParam & installParam,const std::unordered_map<std::string,InnerBundleInfo> & newInfos)2759 void BaseBundleInstaller::ProcessQuickFixWhenInstallNewModule(const InstallParam &installParam,
2760     const std::unordered_map<std::string, InnerBundleInfo> &newInfos)
2761 {
2762 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2763     // hqf extract diff file or apply diff patch failed does not affect the hap installation
2764     InnerBundleInfo bundleInfo;
2765     if (!GetTempBundleInfo(bundleInfo)) {
2766         return;
2767     }
2768     for (auto &info : newInfos) {
2769         modulePackage_ = info.second.GetCurrentModulePackage();
2770         if (!installedModules_[modulePackage_]) {
2771             modulePath_ = info.first;
2772             if (bundleInfo.IsEncryptedMoudle(modulePackage_) && installParam.copyHapToInstallPath) {
2773                 modulePath_ = GetHapPath(info.second);
2774             }
2775             ProcessHqfInfo(bundleInfo, info.second);
2776         }
2777     }
2778 #endif
2779 }
2780 
ProcessHqfInfo(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo)2781 void BaseBundleInstaller::ProcessHqfInfo(
2782     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo)
2783 {
2784 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2785     LOG_D(BMS_TAG_INSTALLER, "bundleName: %{public}s, moduleName: %{public}s", bundleName_.c_str(),
2786         modulePackage_.c_str());
2787     std::string cpuAbi;
2788     std::string nativeLibraryPath;
2789     if (!newInfo.FetchNativeSoAttrs(modulePackage_, cpuAbi, nativeLibraryPath)) {
2790         LOG_I(BMS_TAG_INSTALLER, "No native so, bundleName: %{public}s, moduleName: %{public}s", bundleName_.c_str(),
2791             modulePackage_.c_str());
2792         return;
2793     }
2794     auto pos = nativeLibraryPath.rfind(ServiceConstants::LIBS);
2795     if (pos != std::string::npos) {
2796         nativeLibraryPath = nativeLibraryPath.substr(pos, nativeLibraryPath.length() - pos);
2797     }
2798 
2799     ErrCode ret = ProcessDeployedHqfInfo(
2800         nativeLibraryPath, cpuAbi, newInfo, oldInfo.GetAppQuickFix());
2801     if (ret != ERR_OK) {
2802         LOG_W(BMS_TAG_INSTALLER, "ProcessDeployedHqfInfo failed, errcode: %{public}d", ret);
2803         return;
2804     }
2805 
2806     ret = ProcessDeployingHqfInfo(nativeLibraryPath, cpuAbi, newInfo);
2807     if (ret != ERR_OK) {
2808         LOG_W(BMS_TAG_INSTALLER, "ProcessDeployingHqfInfo failed, errcode: %{public}d", ret);
2809         return;
2810     }
2811 
2812     LOG_D(BMS_TAG_INSTALLER, "ProcessHqfInfo end");
2813 #endif
2814 }
2815 
ProcessDeployedHqfInfo(const std::string & nativeLibraryPath,const std::string & cpuAbi,const InnerBundleInfo & newInfo,const AppQuickFix & oldAppQuickFix)2816 ErrCode BaseBundleInstaller::ProcessDeployedHqfInfo(const std::string &nativeLibraryPath,
2817     const std::string &cpuAbi, const InnerBundleInfo &newInfo, const AppQuickFix &oldAppQuickFix)
2818 {
2819 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2820     LOG_D(BMS_TAG_INSTALLER, "ProcessDeployedHqfInfo");
2821     if (dataMgr_ == nullptr) {
2822         LOG_E(BMS_TAG_INSTALLER, "dataMgr_ is nullptr");
2823         return ERR_APPEXECFWK_NULL_PTR;
2824     }
2825     auto appQuickFix = oldAppQuickFix;
2826     AppqfInfo &appQfInfo = appQuickFix.deployedAppqfInfo;
2827     if (isFeatureNeedUninstall_ || appQfInfo.hqfInfos.empty()) {
2828         LOG_I(BMS_TAG_INSTALLER, "No need ProcessDeployedHqfInfo");
2829         return ERR_OK;
2830     }
2831 
2832     ErrCode ret = ProcessDiffFiles(appQfInfo, nativeLibraryPath, cpuAbi);
2833     if (ret != ERR_OK) {
2834         LOG_E(BMS_TAG_INSTALLER, "ProcessDeployedHqfInfo failed, errcode: %{public}d", ret);
2835         return ret;
2836     }
2837 
2838     std::string newSoPath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName_ +
2839         ServiceConstants::PATH_SEPARATOR + ServiceConstants::PATCH_PATH +
2840         std::to_string(appQfInfo.versionCode) + ServiceConstants::PATH_SEPARATOR + nativeLibraryPath;
2841     if (!BundleUtil::IsExistDirNoLog(newSoPath)) {
2842         LOG_E(BMS_TAG_INSTALLER, "Patch no diff file");
2843         return ERR_OK;
2844     }
2845 
2846     ret = UpdateLibAttrs(newInfo, cpuAbi, nativeLibraryPath, appQfInfo);
2847     if (ret != ERR_OK) {
2848         LOG_E(BMS_TAG_INSTALLER, "UpdateModuleLib failed, errcode: %{public}d", ret);
2849         return ret;
2850     }
2851 
2852     InnerBundleInfo innerBundleInfo;
2853     if (!GetTempBundleInfo(innerBundleInfo)) {
2854         LOG_E(BMS_TAG_INSTALLER, "Fetch bundleInfo(%{public}s) failed", bundleName_.c_str());
2855         return ERR_APPEXECFWK_GET_INSTALL_TEMP_BUNDLE_ERROR;
2856     }
2857 
2858     innerBundleInfo.SetAppQuickFix(appQuickFix);
2859     if (!tempInfo_.SetTempBundleInfo(innerBundleInfo)) {
2860         LOG_E(BMS_TAG_INSTALLER, "update quickfix innerbundleInfo failed");
2861         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2862     }
2863 #endif
2864     return ERR_OK;
2865 }
2866 
ProcessDeployingHqfInfo(const std::string & nativeLibraryPath,const std::string & cpuAbi,const InnerBundleInfo & newInfo) const2867 ErrCode BaseBundleInstaller::ProcessDeployingHqfInfo(
2868     const std::string &nativeLibraryPath, const std::string &cpuAbi, const InnerBundleInfo &newInfo) const
2869 {
2870 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2871     LOG_D(BMS_TAG_INSTALLER, "ProcessDeployingHqfInfo");
2872     std::shared_ptr<QuickFixDataMgr> quickFixDataMgr = DelayedSingleton<QuickFixDataMgr>::GetInstance();
2873     if (quickFixDataMgr == nullptr) {
2874         LOG_E(BMS_TAG_INSTALLER, "quick fix data mgr is nullptr");
2875         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2876     }
2877 
2878     InnerAppQuickFix innerAppQuickFix;
2879     if (!quickFixDataMgr->QueryInnerAppQuickFix(bundleName_, innerAppQuickFix)) {
2880         return ERR_OK;
2881     }
2882 
2883     auto appQuickFix = innerAppQuickFix.GetAppQuickFix();
2884     AppqfInfo &appQfInfo = appQuickFix.deployingAppqfInfo;
2885     ErrCode ret = ProcessDiffFiles(appQfInfo, nativeLibraryPath, cpuAbi);
2886     if (ret != ERR_OK) {
2887         LOG_E(BMS_TAG_INSTALLER, "failed errcode: %{public}d path: %{public}s", ret, nativeLibraryPath.c_str());
2888         return ret;
2889     }
2890 
2891     std::string newSoPath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName_ +
2892         ServiceConstants::PATH_SEPARATOR + ServiceConstants::PATCH_PATH +
2893         std::to_string(appQfInfo.versionCode) + ServiceConstants::PATH_SEPARATOR + nativeLibraryPath;
2894     if (!BundleUtil::IsExistDirNoLog(newSoPath)) {
2895         LOG_E(BMS_TAG_INSTALLER, "Patch no diff file");
2896         return ERR_OK;
2897     }
2898 
2899     ret = UpdateLibAttrs(newInfo, cpuAbi, nativeLibraryPath, appQfInfo);
2900     if (ret != ERR_OK) {
2901         LOG_E(BMS_TAG_INSTALLER, "UpdateModuleLib failed, errcode: %{public}d", ret);
2902         return ret;
2903     }
2904 
2905     innerAppQuickFix.SetAppQuickFix(appQuickFix);
2906     if (!quickFixDataMgr->SaveInnerAppQuickFix(innerAppQuickFix)) {
2907         LOG_E(BMS_TAG_INSTALLER, "bundleName: %{public}s, inner app quick fix save failed", bundleName_.c_str());
2908         return ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED;
2909     }
2910 #endif
2911     return ERR_OK;
2912 }
2913 
UpdateLibAttrs(const InnerBundleInfo & newInfo,const std::string & cpuAbi,const std::string & nativeLibraryPath,AppqfInfo & appQfInfo) const2914 ErrCode BaseBundleInstaller::UpdateLibAttrs(const InnerBundleInfo &newInfo,
2915     const std::string &cpuAbi, const std::string &nativeLibraryPath, AppqfInfo &appQfInfo) const
2916 {
2917 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2918     auto newNativeLibraryPath = ServiceConstants::PATCH_PATH +
2919         std::to_string(appQfInfo.versionCode) + ServiceConstants::PATH_SEPARATOR + nativeLibraryPath;
2920     auto moduleName = newInfo.GetCurModuleName();
2921     bool isLibIsolated = newInfo.IsLibIsolated(moduleName);
2922     if (!isLibIsolated) {
2923         appQfInfo.nativeLibraryPath = newNativeLibraryPath;
2924         appQfInfo.cpuAbi = cpuAbi;
2925         return ERR_OK;
2926     }
2927 
2928     for (auto &hqfInfo : appQfInfo.hqfInfos) {
2929         if (hqfInfo.moduleName != moduleName) {
2930             continue;
2931         }
2932 
2933         hqfInfo.nativeLibraryPath = newNativeLibraryPath;
2934         hqfInfo.cpuAbi = cpuAbi;
2935         if (!BundleUtil::StartWith(appQfInfo.nativeLibraryPath, ServiceConstants::PATCH_PATH)) {
2936             appQfInfo.nativeLibraryPath.clear();
2937         }
2938 
2939         return ERR_OK;
2940     }
2941 
2942     return ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST;
2943 #else
2944     return ERR_OK;
2945 #endif
2946 }
2947 
CheckHapLibsWithPatchLibs(const std::string & nativeLibraryPath,const std::string & hqfLibraryPath) const2948 bool BaseBundleInstaller::CheckHapLibsWithPatchLibs(
2949     const std::string &nativeLibraryPath, const std::string &hqfLibraryPath) const
2950 {
2951 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2952     if (!hqfLibraryPath.empty()) {
2953         auto position = hqfLibraryPath.find(ServiceConstants::PATH_SEPARATOR);
2954         if (position == std::string::npos) {
2955             return false;
2956         }
2957 
2958         auto newHqfLibraryPath = hqfLibraryPath.substr(position);
2959         if (!BundleUtil::EndWith(nativeLibraryPath, newHqfLibraryPath)) {
2960             LOG_E(BMS_TAG_INSTALLER, "error: nativeLibraryPath not same, newInfo: %{public}s, hqf: %{public}s",
2961                 nativeLibraryPath.c_str(), newHqfLibraryPath.c_str());
2962             return false;
2963         }
2964     }
2965 #endif
2966     return true;
2967 }
2968 
ExtractSoFiles(const std::string & soPath,const std::string & cpuAbi) const2969 bool BaseBundleInstaller::ExtractSoFiles(const std::string &soPath, const std::string &cpuAbi) const
2970 {
2971     ExtractParam extractParam;
2972     extractParam.extractFileType = ExtractFileType::SO;
2973     extractParam.srcPath = modulePath_;
2974     extractParam.targetPath = soPath;
2975     extractParam.cpuAbi = cpuAbi;
2976     if (InstalldClient::GetInstance()->ExtractFiles(extractParam) != ERR_OK) {
2977         LOG_E(BMS_TAG_INSTALLER, "bundleName: %{public}s moduleName: %{public}s extract so failed", bundleName_.c_str(),
2978             modulePackage_.c_str());
2979         return false;
2980     }
2981     return true;
2982 }
2983 
ExtractEncryptedSoFiles(const InnerBundleInfo & info,const std::string & tmpSoPath,int32_t uid) const2984 bool BaseBundleInstaller::ExtractEncryptedSoFiles(const InnerBundleInfo &info,
2985     const std::string &tmpSoPath, int32_t uid) const
2986 {
2987     LOG_D(BMS_TAG_INSTALLER, "start to extract decoded so files to tmp path");
2988     std::string cpuAbi = "";
2989     std::string nativeLibraryPath = "";
2990     bool isSoExisted = info.FetchNativeSoAttrs(info.GetCurrentModulePackage(), cpuAbi, nativeLibraryPath);
2991     if (!isSoExisted) {
2992         LOG_D(BMS_TAG_INSTALLER, "so is not existed");
2993         return true;
2994     }
2995     std::string realSoFilesPath;
2996     if (info.IsCompressNativeLibs(info.GetCurModuleName())) {
2997         realSoFilesPath.append(Constants::BUNDLE_CODE_DIR).append(ServiceConstants::PATH_SEPARATOR)
2998             .append(bundleName_).append(ServiceConstants::PATH_SEPARATOR).append(nativeLibraryPath);
2999         if (realSoFilesPath.back() != ServiceConstants::PATH_SEPARATOR[0]) {
3000             realSoFilesPath += ServiceConstants::PATH_SEPARATOR;
3001         }
3002     }
3003     LOG_D(BMS_TAG_INSTALLER, "real path %{public}s tmpPath %{public}s", realSoFilesPath.c_str(), tmpSoPath.c_str());
3004     return InstalldClient::GetInstance()->ExtractEncryptedSoFiles(modulePath_, realSoFilesPath, cpuAbi,
3005         tmpSoPath, uid) == ERR_OK;
3006 }
3007 
ProcessDiffFiles(const AppqfInfo & appQfInfo,const std::string & nativeLibraryPath,const std::string & cpuAbi) const3008 ErrCode BaseBundleInstaller::ProcessDiffFiles(const AppqfInfo &appQfInfo, const std::string &nativeLibraryPath,
3009     const std::string &cpuAbi) const
3010 {
3011 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3012     const std::string moduleName = modulePackage_;
3013     auto iter = find_if(appQfInfo.hqfInfos.begin(), appQfInfo.hqfInfos.end(),
3014         [&moduleName](const auto &hqfInfo) {
3015         return hqfInfo.moduleName == moduleName;
3016     });
3017     if (iter != appQfInfo.hqfInfos.end()) {
3018         std::string oldSoPath = std::string(ServiceConstants::HAP_COPY_PATH) + ServiceConstants::PATH_SEPARATOR +
3019             bundleName_ + ServiceConstants::TMP_SUFFIX + ServiceConstants::LIBS;
3020         ScopeGuard guardRemoveOldSoPath([oldSoPath] {InstalldClient::GetInstance()->RemoveDir(oldSoPath);});
3021 
3022         InnerBundleInfo innerBundleInfo;
3023         if (!GetTempBundleInfo(innerBundleInfo)) {
3024             LOG_E(BMS_TAG_INSTALLER, "Fetch bundleInfo(%{public}s) failed", bundleName_.c_str());
3025             return ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST;
3026         }
3027 
3028         int32_t bundleUid = Constants::INVALID_UID;
3029         if (innerBundleInfo.IsEncryptedMoudle(modulePackage_)) {
3030             InnerBundleUserInfo innerBundleUserInfo;
3031             if (!innerBundleInfo.GetInnerBundleUserInfo(Constants::ALL_USERID, innerBundleUserInfo)) {
3032                 LOG_E(BMS_TAG_INSTALLER, "no user info of bundle %{public}s", bundleName_.c_str());
3033                 return ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST;
3034             }
3035             bundleUid = innerBundleUserInfo.uid;
3036             if (!ExtractEncryptedSoFiles(innerBundleInfo, oldSoPath, bundleUid)) {
3037                 LOG_W(BMS_TAG_INSTALLER, "module:%{public}s has no so file", moduleName.c_str());
3038                 return ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED;
3039             }
3040         } else {
3041             if (!ExtractSoFiles(oldSoPath, cpuAbi)) {
3042                 return ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED;
3043             }
3044         }
3045 
3046         const std::string tempDiffPath = std::string(ServiceConstants::HAP_COPY_PATH) +
3047             ServiceConstants::PATH_SEPARATOR +
3048             bundleName_ + ServiceConstants::TMP_SUFFIX;
3049         ScopeGuard removeDiffPath([tempDiffPath] { InstalldClient::GetInstance()->RemoveDir(tempDiffPath); });
3050         ErrCode ret = InstalldClient::GetInstance()->ExtractDiffFiles(iter->hqfFilePath, tempDiffPath, cpuAbi);
3051         if (ret != ERR_OK) {
3052             LOG_E(BMS_TAG_INSTALLER, "error: ExtractDiffFiles failed errcode :%{public}d", ret);
3053             return ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED;
3054         }
3055 
3056         std::string newSoPath = std::string(Constants::BUNDLE_CODE_DIR) +
3057             ServiceConstants::PATH_SEPARATOR + bundleName_ +
3058             ServiceConstants::PATH_SEPARATOR + ServiceConstants::PATCH_PATH +
3059             std::to_string(appQfInfo.versionCode) + ServiceConstants::PATH_SEPARATOR + nativeLibraryPath;
3060         ret = InstalldClient::GetInstance()->ApplyDiffPatch(oldSoPath, tempDiffPath, newSoPath, bundleUid);
3061         if (ret != ERR_OK) {
3062             LOG_E(BMS_TAG_INSTALLER, "error: ApplyDiffPatch failed errcode :%{public}d", ret);
3063             return ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED;
3064         }
3065     }
3066 #endif
3067     return ERR_OK;
3068 }
3069 
SetDirApl(const InnerBundleInfo & info)3070 ErrCode BaseBundleInstaller::SetDirApl(const InnerBundleInfo &info)
3071 {
3072     auto& bundleUserInfos = info.GetInnerBundleUserInfos();
3073     CreateDirParam createDirParam;
3074     createDirParam.bundleName = info.GetBundleName();
3075     createDirParam.apl = info.GetAppPrivilegeLevel();
3076     createDirParam.isPreInstallApp = info.IsPreInstallApp();
3077     createDirParam.debug = info.GetBaseApplicationInfo().appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG;
3078     for (const auto &userInfoPair : bundleUserInfos) {
3079         auto &userInfo = userInfoPair.second;
3080         const std::map<std::string, InnerBundleCloneInfo> &cloneInfos = userInfo.cloneInfos;
3081         auto userId = userInfo.bundleUserInfo.userId;
3082         createDirParam.userId = userId;
3083         createDirParam.uid = userInfo.uid;
3084         ErrCode userRet = SetDirApl(createDirParam, info.GetBundleName());
3085         if (userRet != ERR_OK) {
3086             LOG_E(BMS_TAG_INSTALLER,
3087                 "fail to SetDirApl bundle dir, userId %{public}d, error is %{public}d", userId, userRet);
3088             return userRet;
3089         }
3090         for (const auto &cloneInfoPair : cloneInfos) {
3091             std::string cloneBundleName = BundleCloneCommonHelper::GetCloneDataDir(
3092                 info.GetBundleName(), cloneInfoPair.second.appIndex);
3093             createDirParam.uid = cloneInfoPair.second.uid;
3094             ErrCode cloneRet = this->SetDirApl(createDirParam, cloneBundleName);
3095             if (cloneRet != ERR_OK) {
3096                 LOG_E(BMS_TAG_INSTALLER, "fail to SetDirApl clone bundle dir, error is %{public}d", cloneRet);
3097                 return cloneRet;
3098             }
3099         }
3100     }
3101     return ERR_OK;
3102 }
3103 
SetDirApl(const CreateDirParam & createDirParam,const std::string & CloneBundleName)3104 ErrCode BaseBundleInstaller::SetDirApl(const CreateDirParam &createDirParam, const std::string &CloneBundleName)
3105 {
3106     for (const auto &el : ServiceConstants::BUNDLE_EL) {
3107         std::string baseBundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR +
3108                                         el +
3109                                         ServiceConstants::PATH_SEPARATOR +
3110                                         std::to_string(createDirParam.userId);
3111         std::string baseDataDir = baseBundleDataDir + ServiceConstants::BASE + CloneBundleName;
3112         std::string databaseDataDir = baseBundleDataDir + ServiceConstants::DATABASE + CloneBundleName;
3113         bool isBaseExist = true;
3114         bool isDatabaseExist = true;
3115         ErrCode result = InstalldClient::GetInstance()->IsExistDir(baseDataDir, isBaseExist);
3116         ErrCode dataResult = InstalldClient::GetInstance()->IsExistDir(databaseDataDir, isDatabaseExist);
3117         if (result != ERR_OK) {
3118             LOG_E(BMS_TAG_INSTALLER, "IsExistDir error is %{public}d", result);
3119             return result;
3120         }
3121         if (dataResult != ERR_OK) {
3122             LOG_E(BMS_TAG_INSTALLER, "IsExistDataDir error is %{public}d", dataResult);
3123             return dataResult;
3124         }
3125         if (!isBaseExist || !isDatabaseExist) {
3126             LOG_D(BMS_TAG_INSTALLER, "base %{public}s or data %{public}s is not exist", baseDataDir.c_str(),
3127                 databaseDataDir.c_str());
3128             continue;
3129         }
3130         result = InstalldClient::GetInstance()->SetDirApl(
3131             baseDataDir, createDirParam.bundleName, createDirParam.apl, createDirParam.isPreInstallApp,
3132             createDirParam.debug, createDirParam.uid);
3133         if (result != ERR_OK) {
3134             LOG_E(BMS_TAG_INSTALLER, "fail to SetDirApl baseDir dir, error is %{public}d", result);
3135             return result;
3136         }
3137         result = InstalldClient::GetInstance()->SetDirApl(
3138             databaseDataDir, createDirParam.bundleName, createDirParam.apl, createDirParam.isPreInstallApp,
3139             createDirParam.debug, createDirParam.uid);
3140         if (result != ERR_OK) {
3141             LOG_E(BMS_TAG_INSTALLER, "fail to SetDirApl databaseDir dir, error is %{public}d", result);
3142             return result;
3143         }
3144     }
3145     return ERR_OK;
3146 }
3147 
CreateBundleAndDataDir(InnerBundleInfo & info) const3148 ErrCode BaseBundleInstaller::CreateBundleAndDataDir(InnerBundleInfo &info) const
3149 {
3150     ErrCode result = CreateBundleCodeDir(info);
3151     if (result != ERR_OK) {
3152         LOG_E(BMS_TAG_INSTALLER, "fail to create bundle code dir, error is %{public}d", result);
3153         return result;
3154     }
3155     ScopeGuard codePathGuard([&] { InstalldClient::GetInstance()->RemoveDir(info.GetAppCodePath()); });
3156     result = CreateBundleDataDir(info);
3157     if (result != ERR_OK) {
3158         LOG_E(BMS_TAG_INSTALLER, "fail to create bundle data dir, error is %{public}d", result);
3159         return result;
3160     }
3161     codePathGuard.Dismiss();
3162     return ERR_OK;
3163 }
3164 
CreateBundleCodeDir(InnerBundleInfo & info) const3165 ErrCode BaseBundleInstaller::CreateBundleCodeDir(InnerBundleInfo &info) const
3166 {
3167     auto appCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName_;
3168     LOG_D(BMS_TAG_INSTALLER, "create bundle dir %{public}s", appCodePath.c_str());
3169     ErrCode result = InstalldClient::GetInstance()->CreateBundleDir(appCodePath);
3170     if (result != ERR_OK) {
3171         LOG_E(BMS_TAG_INSTALLER, "fail to create bundle dir, error is %{public}d", result);
3172         return result;
3173     }
3174 
3175     info.SetAppCodePath(appCodePath);
3176     return ERR_OK;
3177 }
3178 
SendToStorageQuota(const std::string & bundleName,const int uid,const std::string & bundleDataDirPath,const int limitSizeMb)3179 static void SendToStorageQuota(const std::string &bundleName, const int uid,
3180     const std::string &bundleDataDirPath, const int limitSizeMb)
3181 {
3182 #ifdef STORAGE_SERVICE_ENABLE
3183     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
3184     if (!systemAbilityManager) {
3185         LOG_W(BMS_TAG_INSTALLER, "SendToStorageQuota, systemAbilityManager error");
3186         return;
3187     }
3188 
3189     auto remote = systemAbilityManager->CheckSystemAbility(STORAGE_MANAGER_MANAGER_ID);
3190     if (!remote) {
3191         LOG_W(BMS_TAG_INSTALLER, "SendToStorageQuota, CheckSystemAbility error");
3192         return;
3193     }
3194 
3195     auto proxy = iface_cast<StorageManager::IStorageManager>(remote);
3196     if (!proxy) {
3197         LOG_W(BMS_TAG_INSTALLER, "SendToStorageQuotactl, proxy get error");
3198         return;
3199     }
3200 
3201     int err = proxy->SetBundleQuota(bundleName, uid, bundleDataDirPath, limitSizeMb);
3202     if (err != ERR_OK) {
3203         LOG_W(BMS_TAG_INSTALLER, "SendToStorageQuota, SetBundleQuota error, err=%{public}d, uid=%{public}d", err, uid);
3204     }
3205 #endif // STORAGE_SERVICE_ENABLE
3206 }
3207 
PrepareBundleDirQuota(const std::string & bundleName,const int32_t uid,const std::string & bundleDataDirPath,const int32_t limitSize) const3208 void BaseBundleInstaller::PrepareBundleDirQuota(const std::string &bundleName, const int32_t uid,
3209     const std::string &bundleDataDirPath, const int32_t limitSize) const
3210 {
3211     if (limitSize == 0) {
3212         SendToStorageQuota(bundleName, uid, bundleDataDirPath, 0);
3213         return;
3214     }
3215     int32_t atomicserviceDatasizeThreshold = limitSize;
3216 #ifdef STORAGE_SERVICE_ENABLE
3217 #ifdef QUOTA_PARAM_SET_ENABLE
3218     char szAtomicDatasizeThresholdMb[THRESHOLD_VAL_LEN] = {0};
3219     int32_t ret = GetParameter(SYSTEM_PARAM_ATOMICSERVICE_DATASIZE_THRESHOLD, "",
3220         szAtomicDatasizeThresholdMb, THRESHOLD_VAL_LEN);
3221     if (ret <= 0) {
3222         LOG_I(BMS_TAG_INSTALLER, "GetParameter failed");
3223     } else if (strcmp(szAtomicDatasizeThresholdMb, "") != 0) {
3224         atomicserviceDatasizeThreshold = atoi(szAtomicDatasizeThresholdMb);
3225         LOG_I(BMS_TAG_INSTALLER, "InstalldQuotaUtils init atomicserviceDataThreshold mb success");
3226     }
3227     if (atomicserviceDatasizeThreshold <= 0) {
3228         LOG_W(BMS_TAG_INSTALLER, "no need to prepare quota");
3229         return;
3230     }
3231 #endif // QUOTA_PARAM_SET_ENABLE
3232 #endif // STORAGE_SERVICE_ENABLE
3233     ParseSizeFromProvision(atomicserviceDatasizeThreshold);
3234     SendToStorageQuota(bundleName, uid, bundleDataDirPath, atomicserviceDatasizeThreshold);
3235 }
3236 
ParseSizeFromProvision(int32_t & sizeMb) const3237 void BaseBundleInstaller::ParseSizeFromProvision(int32_t &sizeMb) const
3238 {
3239     std::string appServiceCapabilities = verifyRes_.GetProvisionInfo().appServiceCapabilities;
3240     if (appServiceCapabilities.empty()) {
3241         return;
3242     }
3243     auto appServiceCapabilityMap = BundleUtil::ParseMapFromJson(appServiceCapabilities);
3244     for (auto &item : appServiceCapabilityMap) {
3245         if (item.first != ServiceConstants::PERMISSION_MANAGE_STORAGE) {
3246             continue;
3247         }
3248         std::unordered_map<std::string, std::string> storageMap = BundleUtil::ParseMapFromJson(item.second);
3249         auto it = storageMap.find(KEY_STORAGE_SIZE);
3250         if (it == storageMap.end()) {
3251             LOG_W(BMS_TAG_INSTALLER, "storageSize not found");
3252             return;
3253         }
3254         int32_t tempSize = atoi(it->second.c_str());
3255         if (tempSize >= sizeMb) {
3256             sizeMb = tempSize;
3257             LOG_I(BMS_TAG_INSTALLER, "set %{public}s quota to %{public}d", bundleName_.c_str(), sizeMb);
3258         } else {
3259             LOG_W(BMS_TAG_INSTALLER, "%{public}s storageSize %{public}d is not valid", bundleName_.c_str(), tempSize);
3260         }
3261         return;
3262     }
3263 }
3264 
CreateBundleDataDir(InnerBundleInfo & info) const3265 ErrCode BaseBundleInstaller::CreateBundleDataDir(InnerBundleInfo &info) const
3266 {
3267     LOG_I(BMS_TAG_INSTALLER, "start");
3268     if (dataMgr_ == nullptr) {
3269         LOG_E(BMS_TAG_INSTALLER, "dataMgr_ is nullptr");
3270         return ERR_APPEXECFWK_NULL_PTR;
3271     }
3272     InnerBundleUserInfo newInnerBundleUserInfo;
3273     if (!info.GetInnerBundleUserInfo(userId_, newInnerBundleUserInfo)) {
3274         LOG_E(BMS_TAG_INSTALLER, "bundle(%{public}s) get user(%{public}d) failed",
3275             info.GetBundleName().c_str(), userId_);
3276         return ERR_APPEXECFWK_USER_NOT_EXIST;
3277     }
3278 
3279     if (!dataMgr_->GenerateUidAndGid(newInnerBundleUserInfo)) {
3280         LOG_E(BMS_TAG_INSTALLER, "fail to generate uid and gid");
3281         return ERR_APPEXECFWK_INSTALL_GENERATE_UID_ERROR;
3282     }
3283     BundleUtil::MakeFsConfig(info.GetBundleName(), ServiceConstants::HMDFS_CONFIG_PATH, info.GetAppProvisionType(),
3284         Constants::APP_PROVISION_TYPE_FILE_NAME);
3285     CreateDirParam createDirParam;
3286     createDirParam.bundleName = info.GetBundleName();
3287     createDirParam.userId = userId_;
3288     createDirParam.uid = newInnerBundleUserInfo.uid;
3289     createDirParam.gid = newInnerBundleUserInfo.uid;
3290     createDirParam.apl = info.GetAppPrivilegeLevel();
3291     createDirParam.isPreInstallApp = info.IsPreInstallApp();
3292     createDirParam.debug = info.GetBaseApplicationInfo().appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG;
3293 
3294     auto result = InstalldClient::GetInstance()->CreateBundleDataDir(createDirParam);
3295     if (result != ERR_OK) {
3296         // if user is not activated, access el2-el4 may return ok but dir cannot be created
3297         if (AccountHelper::IsOsAccountVerified(userId_)) {
3298             LOG_E(BMS_TAG_INSTALLER, "fail to create bundle data dir, error is %{public}d", result);
3299             return result;
3300         } else {
3301             LOG_W(BMS_TAG_INSTALLER, "user %{public}d is not activated", userId_);
3302         }
3303     }
3304     std::string bundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1] +
3305         ServiceConstants::PATH_SEPARATOR + std::to_string(userId_) + ServiceConstants::BASE + info.GetBundleName();
3306     if (info.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE) {
3307         PrepareBundleDirQuota(info.GetBundleName(), newInnerBundleUserInfo.uid, bundleDataDir,
3308             ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET);
3309     } else {
3310         PrepareBundleDirQuota(info.GetBundleName(), newInnerBundleUserInfo.uid, bundleDataDir, 0);
3311     }
3312     if (info.GetIsNewVersion()) {
3313         int32_t gid = (info.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG) ?
3314             GetIntParameter(BMS_KEY_SHELL_UID, ServiceConstants::SHELL_UID) :
3315             newInnerBundleUserInfo.uid;
3316         result = CreateArkProfile(
3317             info.GetBundleName(), userId_, newInnerBundleUserInfo.uid, gid);
3318         if (result != ERR_OK) {
3319             LOG_E(BMS_TAG_INSTALLER, "fail to create ark profile, error is %{public}d", result);
3320             return result;
3321         }
3322     }
3323 
3324     result = CreateShaderCache(info.GetBundleName(), createDirParam.uid, createDirParam.gid);
3325     if (result != ERR_OK) {
3326         LOG_W(BMS_TAG_INSTALLER, "fail to create shader cache, error is %{public}d", result);
3327     }
3328 
3329     if (userId_ == Constants::START_USERID) {
3330         CreateCloudShader(info.GetBundleName(), createDirParam.uid, createDirParam.gid);
3331     }
3332 
3333     // create asan log directory when asanEnabled is true
3334     // In update condition, delete asan log directory when asanEnabled is false if directory is exist
3335     if ((result = ProcessAsanDirectory(info)) != ERR_OK) {
3336         LOG_E(BMS_TAG_INSTALLER, "process asan log directory failed");
3337         return result;
3338     }
3339 
3340     std::string dataBaseDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1] +
3341         ServiceConstants::DATABASE + info.GetBundleName();
3342     info.SetAppDataBaseDir(dataBaseDir);
3343     info.AddInnerBundleUserInfo(newInnerBundleUserInfo);
3344     return ERR_OK;
3345 }
3346 
CreateDataGroupDirs(const std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes,const InnerBundleInfo & oldInfo)3347 ErrCode BaseBundleInstaller::CreateDataGroupDirs(
3348     const std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes, const InnerBundleInfo &oldInfo)
3349 {
3350     if (dataMgr_ == nullptr) {
3351         LOG_W(BMS_TAG_INSTALLER, "dataMgr_ null");
3352         return ERR_APPEXECFWK_NULL_PTR;
3353     }
3354     if (hapVerifyRes.empty()) {
3355         LOG_W(BMS_TAG_INSTALLER, "hapVerifyRes empty");
3356         return ERR_APPEXECFWK_HAP_VERIFY_RES_EMPTY;
3357     }
3358     std::unordered_set<std::string> groupIds;
3359     GetDataGroupIds(hapVerifyRes, groupIds);
3360     dataMgr_->GenerateDataGroupInfos(bundleName_, groupIds, userId_, true);
3361     return ERR_OK;
3362 }
3363 
GenerateScreenLockProtectionDir(const std::string & bundleName) const3364 std::vector<std::string> BaseBundleInstaller::GenerateScreenLockProtectionDir(const std::string &bundleName) const
3365 {
3366     std::vector<std::string> dirs;
3367     if (bundleName.empty()) {
3368         LOG_E(BMS_TAG_INSTALLER, "bundleName is empty");
3369         return dirs;
3370     }
3371     dirs.emplace_back(std::string(ServiceConstants::SCREEN_LOCK_FILE_DATA_PATH) + ServiceConstants::PATH_SEPARATOR +
3372         std::to_string(userId_) + ServiceConstants::BASE + bundleName);
3373     dirs.emplace_back(std::string(ServiceConstants::SCREEN_LOCK_FILE_DATA_PATH) + ServiceConstants::PATH_SEPARATOR +
3374         std::to_string(userId_) + ServiceConstants::DATABASE + bundleName);
3375     return dirs;
3376 }
3377 
CreateScreenLockProtectionDir()3378 void BaseBundleInstaller::CreateScreenLockProtectionDir()
3379 {
3380     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "CreateScreenLockProtectionDir start");
3381     InnerBundleInfo info;
3382     if (!GetTempBundleInfo(info)) {
3383         LOG_E(BMS_TAG_INSTALLER, "get failed");
3384         return;
3385     }
3386 
3387     std::vector<std::string> dirs = GenerateScreenLockProtectionDir(bundleName_);
3388     std::vector<RequestPermission> reqPermissions = info.GetAllRequestPermissions();
3389     auto it = std::find_if(reqPermissions.begin(), reqPermissions.end(), [](const RequestPermission& permission) {
3390         return permission.name == ServiceConstants::PERMISSION_PROTECT_SCREEN_LOCK_DATA;
3391     });
3392     if (it != reqPermissions.end()) {
3393         CreateEl5AndSetPolicy(info);
3394     }
3395 }
3396 
CreateEl5AndSetPolicy(InnerBundleInfo & info)3397 void BaseBundleInstaller::CreateEl5AndSetPolicy(InnerBundleInfo &info)
3398 {
3399     if (!InitDataMgr()) {
3400         LOG_E(BMS_TAG_INSTALLER, "init failed");
3401         return;
3402     }
3403     std::vector<CreateDirParam> params;
3404     CreateDirParam el5Param;
3405     el5Param.bundleName = info.GetBundleName();
3406     el5Param.userId = userId_;
3407     el5Param.uid = info.GetUid(userId_);
3408     el5Param.apl = info.GetAppPrivilegeLevel();
3409     el5Param.isPreInstallApp = info.IsPreInstallApp();
3410     el5Param.debug = info.GetBaseApplicationInfo().appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG;
3411     params.emplace_back(el5Param);
3412     InnerBundleUserInfo userInfo;
3413     if (!info.GetInnerBundleUserInfo(userId_, userInfo)) {
3414         APP_LOGE("get user info failed");
3415         return;
3416     }
3417     for (const auto &cloneInfo : userInfo.cloneInfos) {
3418         CreateDirParam cloneParam = el5Param;
3419         cloneParam.uid = cloneInfo.second.uid;
3420         cloneParam.gid = cloneInfo.second.uid;
3421         cloneParam.appIndex = cloneInfo.second.appIndex;
3422         params.emplace_back(cloneParam);
3423     }
3424     dataMgr_->CreateEl5DirNoCache(params, info);
3425     tempInfo_.SetTempBundleInfo(info);
3426 }
3427 
GetUninstallBundleInfo(bool isKeepData,int32_t userId,const InnerBundleInfo & oldInfo,UninstallBundleInfo & uninstallBundleInfo)3428 void BaseBundleInstaller::GetUninstallBundleInfo(bool isKeepData, int32_t userId,
3429     const InnerBundleInfo &oldInfo, UninstallBundleInfo &uninstallBundleInfo)
3430 {
3431     if (!isKeepData) {
3432         return;
3433     }
3434     uninstallBundleInfo.userInfos[std::to_string(userId)].uid = oldInfo.GetUid(userId);
3435     uninstallBundleInfo.userInfos[std::to_string(userId)].gids.emplace_back(oldInfo.GetGid(userId));
3436     uninstallBundleInfo.userInfos[std::to_string(userId)].accessTokenId = oldInfo.GetAccessTokenId(userId);
3437     uninstallBundleInfo.userInfos[std::to_string(userId)].accessTokenIdEx = oldInfo.GetAccessTokenIdEx(userId);
3438     uninstallBundleInfo.appId = oldInfo.GetAppId();
3439     uninstallBundleInfo.appIdentifier = oldInfo.GetAppIdentifier();
3440     uninstallBundleInfo.appProvisionType = oldInfo.GetAppProvisionType();
3441     uninstallBundleInfo.bundleType = oldInfo.GetApplicationBundleType();
3442 }
3443 
SaveUninstallBundleInfo(const std::string bundleName,bool isKeepData,const UninstallBundleInfo & uninstallBundleInfo)3444 void BaseBundleInstaller::SaveUninstallBundleInfo(const std::string bundleName, bool isKeepData,
3445     const UninstallBundleInfo &uninstallBundleInfo)
3446 {
3447     if (!isKeepData) {
3448         return;
3449     }
3450     if (!dataMgr_->UpdateUninstallBundleInfo(bundleName, uninstallBundleInfo)) {
3451         LOG_E(BMS_TAG_INSTALLER, "update failed");
3452     }
3453 }
3454 
DeleteUninstallBundleInfo(const std::string & bundleName)3455 void BaseBundleInstaller::DeleteUninstallBundleInfo(const std::string &bundleName)
3456 {
3457     if (!InitDataMgr()) {
3458         LOG_E(BMS_TAG_INSTALLER, "init failed");
3459         return;
3460     }
3461     if (!existBeforeKeepDataApp_) {
3462         return;
3463     }
3464     if (!dataMgr_->DeleteUninstallBundleInfo(bundleName, userId_)) {
3465         LOG_E(BMS_TAG_INSTALLER, "delete failed");
3466     }
3467 }
3468 
DeleteUninstallBundleInfoFromDb(const std::string & bundleName)3469 bool BaseBundleInstaller::DeleteUninstallBundleInfoFromDb(const std::string &bundleName)
3470 {
3471     if (!InitDataMgr()) {
3472         LOG_E(BMS_TAG_INSTALLER, "init failed");
3473         return false;
3474     }
3475     UninstallBundleInfo uninstallBundleInfo;
3476     if (!dataMgr_->GetUninstallBundleInfo(bundleName, uninstallBundleInfo)) {
3477         return false;
3478     }
3479     if (uninstallBundleInfo.userInfos.find(std::to_string(userId_)) == uninstallBundleInfo.userInfos.end()) {
3480         LOG_I(BMS_TAG_INSTALLER, "%{public}s has been uninstalled on user %{public}d without keepData",
3481             bundleName.c_str(), userId_);
3482         return false;
3483     }
3484     ErrCode result = InstalldClient::GetInstance()->RemoveBundleDataDir(bundleName, userId_,
3485         uninstallBundleInfo.bundleType == BundleType::ATOMIC_SERVICE, true);
3486     LOG_I(BMS_TAG_INSTALLER, "remove dirs res %{public}d", result);
3487     if (!uninstallBundleInfo.extensionDirs.empty()) {
3488         result = InstalldClient::GetInstance()->RemoveExtensionDir(userId_, uninstallBundleInfo.extensionDirs);
3489         LOG_I(BMS_TAG_INSTALLER, "remove extension dirs res %{public}d", result);
3490     }
3491     return dataMgr_->DeleteUninstallBundleInfo(bundleName, userId_);
3492 }
3493 
SetFirstInstallTime(const std::string & bundleName,const int64_t & time,InnerBundleInfo & info)3494 void BaseBundleInstaller::SetFirstInstallTime(const std::string &bundleName, const int64_t &time,
3495     InnerBundleInfo &info)
3496 {
3497     if (!InitDataMgr()) {
3498         LOG_E(BMS_TAG_INSTALLER, "init data manager failed");
3499         info.SetFirstInstallTime(time, userId_);
3500         return;
3501     }
3502     FirstInstallBundleInfo firstInstallBundleInfo;
3503     if (dataMgr_->GetFirstInstallBundleInfo(bundleName, userId_, firstInstallBundleInfo)) {
3504         info.SetFirstInstallTime(firstInstallBundleInfo.firstInstallTime, userId_);
3505         return;
3506     }
3507     info.SetFirstInstallTime(time, userId_);
3508 }
3509 
SaveFirstInstallBundleInfo(const std::string & bundleName,const int32_t userId,bool isPreInstallApp,const InnerBundleUserInfo & innerBundleUserInfo)3510 bool BaseBundleInstaller::SaveFirstInstallBundleInfo(const std::string &bundleName, const int32_t userId,
3511     bool isPreInstallApp, const InnerBundleUserInfo &innerBundleUserInfo)
3512 {
3513     if (!InitDataMgr()) {
3514         LOG_E(BMS_TAG_INSTALLER, "init data manager failed");
3515         return false;
3516     }
3517     FirstInstallBundleInfo firstInstallInfo;
3518     if (innerBundleUserInfo.firstInstallTime == ServiceConstants::DEFAULT_FIRST_INSTALL_TIME) {
3519         firstInstallInfo.firstInstallTime = isPreInstallApp ?
3520             ServiceConstants::PREINSTALL_FIRST_INSTALL_TIME : innerBundleUserInfo.installTime;
3521     } else {
3522         firstInstallInfo.firstInstallTime = innerBundleUserInfo.firstInstallTime;
3523     }
3524     if (!dataMgr_->AddFirstInstallBundleInfo(bundleName, userId, firstInstallInfo)) {
3525         LOG_E(BMS_TAG_INSTALLER, "failed to add first install info for bundle %{public}s", bundleName.c_str());
3526         return false;
3527     }
3528     return true;
3529 }
3530 
CheckInstallOnKeepData(const std::string & bundleName,bool isOTA,const std::unordered_map<std::string,InnerBundleInfo> & infos)3531 bool BaseBundleInstaller::CheckInstallOnKeepData(const std::string &bundleName, bool isOTA,
3532     const std::unordered_map<std::string, InnerBundleInfo> &infos)
3533 {
3534     if (isOTA) {
3535         return true;
3536     }
3537     if (!InitDataMgr() || infos.empty()) {
3538         LOG_E(BMS_TAG_INSTALLER, "init failed or empty infos");
3539         return true;
3540     }
3541     UninstallBundleInfo uninstallBundleInfo;
3542     if (!dataMgr_->GetUninstallBundleInfo(bundleName, uninstallBundleInfo)) {
3543         return true;
3544     }
3545     existBeforeKeepDataApp_ = true;
3546     LOG_I(BMS_TAG_INSTALLER, "this app was uninstalled with keep data before");
3547     if (!CheckAppIdentifier(uninstallBundleInfo.appIdentifier, infos.begin()->second.GetAppIdentifier(),
3548         uninstallBundleInfo.appId, infos.begin()->second.GetAppId())) {
3549         LOG_E(BMS_TAG_INSTALLER,
3550             "%{public}s has been uninstalled with keep data, and the appIdentifier or appId is not the same",
3551             bundleName.c_str());
3552         return false;
3553     }
3554     return true;
3555 }
3556 
DeleteEncryptionKeyId(const InnerBundleUserInfo & userInfo,bool isKeepData) const3557 void BaseBundleInstaller::DeleteEncryptionKeyId(const InnerBundleUserInfo &userInfo, bool isKeepData) const
3558 {
3559     if (userInfo.bundleName.empty()) {
3560         LOG_W(BMS_TAG_INSTALLER, "bundleName is empty");
3561         return;
3562     }
3563     if (isKeepData) {
3564         LOG_I(BMS_TAG_INSTALLER, "keep el5 dir -n %{public}s", userInfo.bundleName.c_str());
3565         return;
3566     }
3567     LOG_D(BMS_TAG_INSTALLER, "delete el5 dir -n %{public}s", userInfo.bundleName.c_str());
3568     std::vector<std::string> dirs = GenerateScreenLockProtectionDir(userInfo.bundleName);
3569     for (const std::string &dir : dirs) {
3570         if (InstalldClient::GetInstance()->RemoveDir(dir) != ERR_OK) {
3571             LOG_W(BMS_TAG_INSTALLER, "remove Screen Lock Protection dir %{public}s failed", dir.c_str());
3572         }
3573     }
3574 
3575     if (userInfo.keyId.empty()) {
3576         return;
3577     }
3578     EncryptionParam encryptionParam(userInfo.bundleName, "", 0, userId_, EncryptionDirType::APP);
3579     if (InstalldClient::GetInstance()->DeleteEncryptionKeyId(encryptionParam) != ERR_OK) {
3580         LOG_W(BMS_TAG_INSTALLER, "delete encryption key id failed");
3581     }
3582 }
3583 
DeleteScreenLockProtectionDir(const std::string bundleName) const3584 void BaseBundleInstaller::DeleteScreenLockProtectionDir(const std::string bundleName) const
3585 {
3586     std::vector<std::string> dirs = GenerateScreenLockProtectionDir(bundleName);
3587     for (const std::string &dir : dirs) {
3588         auto result = InstalldClient::GetInstance()->RemoveDir(dir);
3589         if (result != ERR_OK) {
3590             LOG_W(BMS_TAG_INSTALLER, "remove Screen Lock Protection dir %{public}s failed", dir.c_str());
3591         }
3592     }
3593 }
3594 
DeleteGroupDirsForException(const InnerBundleInfo & oldInfo) const3595 void BaseBundleInstaller::DeleteGroupDirsForException(const InnerBundleInfo &oldInfo) const
3596 {
3597     if (dataMgr_ == nullptr) {
3598         LOG_W(BMS_TAG_INSTALLER, "dataMgr_ null");
3599         return;
3600     }
3601     dataMgr_->DeleteGroupDirsForException(oldInfo, userId_);
3602 }
3603 
RemoveDataGroupDirs(const std::string & bundleName,int32_t userId,bool isKeepData) const3604 ErrCode BaseBundleInstaller::RemoveDataGroupDirs(const std::string &bundleName, int32_t userId, bool isKeepData) const
3605 {
3606     if (dataMgr_ == nullptr) {
3607         LOG_E(BMS_TAG_INSTALLER, "dataMgr_ is nullptr");
3608         return ERR_APPEXECFWK_NULL_PTR;
3609     }
3610     dataMgr_->DeleteUserDataGroupInfos(bundleName, userId, isKeepData);
3611     return ERR_OK;
3612 }
3613 
CreateArkProfile(const std::string & bundleName,int32_t userId,int32_t uid,int32_t gid) const3614 ErrCode BaseBundleInstaller::CreateArkProfile(
3615     const std::string &bundleName, int32_t userId, int32_t uid, int32_t gid) const
3616 {
3617     ErrCode result = DeleteArkProfile(bundleName, userId);
3618     if (result != ERR_OK) {
3619         LOG_E(BMS_TAG_INSTALLER, "fail to removeArkProfile, error is %{public}d", result);
3620         return result;
3621     }
3622 
3623     std::string arkProfilePath = AOTHandler::BuildArkProfilePath(userId, bundleName);
3624     LOG_D(BMS_TAG_INSTALLER, "CreateArkProfile %{public}s", arkProfilePath.c_str());
3625     int32_t mode = (uid == gid) ? S_IRWXU : (S_IRWXU | S_IRGRP | S_IXGRP);
3626     return InstalldClient::GetInstance()->Mkdir(arkProfilePath, mode, uid, gid);
3627 }
3628 
DeleteArkProfile(const std::string & bundleName,int32_t userId) const3629 ErrCode BaseBundleInstaller::DeleteArkProfile(const std::string &bundleName, int32_t userId) const
3630 {
3631     std::string arkProfilePath = AOTHandler::BuildArkProfilePath(userId, bundleName);
3632     LOG_D(BMS_TAG_INSTALLER, "DeleteArkProfile %{public}s", arkProfilePath.c_str());
3633     return InstalldClient::GetInstance()->RemoveDir(arkProfilePath);
3634 }
3635 
RemoveDataPreloadHapFiles(const std::string & bundleName) const3636 bool BaseBundleInstaller::RemoveDataPreloadHapFiles(const std::string &bundleName) const
3637 {
3638     if (dataMgr_ == nullptr) {
3639         LOG_E(BMS_TAG_INSTALLER, "null dataMgr_");
3640         return false;
3641     }
3642 
3643     PreInstallBundleInfo preInstallBundleInfo;
3644     preInstallBundleInfo.SetBundleName(bundleName);
3645     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
3646         LOG_I(BMS_TAG_INSTALLER, "no PreInstallBundleInfo(%{public}s) in db", bundleName.c_str());
3647         return true;
3648     }
3649     if (preInstallBundleInfo.GetBundlePaths().empty()) {
3650         LOG_W(BMS_TAG_INSTALLER, "path is empty , bundleName: %{public}s", bundleName.c_str());
3651         return false;
3652     }
3653 
3654     auto preinstalledAppPath = preInstallBundleInfo.GetBundlePaths().front();
3655     LOG_D(BMS_TAG_INSTALLER, "preinstalledAppPath %{public}s", preinstalledAppPath.c_str());
3656     if (IsDataPreloadHap(preinstalledAppPath)) {
3657         std::filesystem::path apFilePath(preinstalledAppPath);
3658         std::string delDir = apFilePath.parent_path().string();
3659         if (InstalldClient::GetInstance()->RemoveDir(delDir) != ERR_OK) {
3660             LOG_E(BMS_TAG_INSTALLER, "removeDir failed :%{public}s", delDir.c_str());
3661         }
3662         if (!dataMgr_->DeletePreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
3663             LOG_E(BMS_TAG_INSTALLER, "deletePreInfoInDb bundle %{public}s failed", bundleName.c_str());
3664         }
3665     }
3666     return true;
3667 }
3668 
IsDataPreloadHap(const std::string & path) const3669 bool BaseBundleInstaller::IsDataPreloadHap(const std::string &path) const
3670 {
3671     return path.find(DATA_PRELOAD_APP) == 0;
3672 }
3673 
ExtractModule(InnerBundleInfo & info,const std::string & modulePath)3674 ErrCode BaseBundleInstaller::ExtractModule(InnerBundleInfo &info, const std::string &modulePath)
3675 {
3676     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
3677     // need remove modulePath, make sure the directory is empty
3678     if (InstalldClient::GetInstance()->RemoveDir(modulePath) != ERR_OK) {
3679         APP_LOGW("remove dir %{public}s failed", modulePath.c_str());
3680     }
3681     auto result = InnerProcessNativeLibs(info, modulePath);
3682     CHECK_RESULT(result, "fail to InnerProcessNativeLibs, error is %{public}d");
3683 
3684     result = ExtractArkNativeFile(info, modulePath);
3685     CHECK_RESULT(result, "fail to extractArkNativeFile, error is %{public}d");
3686     if (info.GetIsNewVersion()) {
3687         result = CopyPgoFileToArkProfileDir(modulePackage_, modulePath_, info.GetBundleName(), userId_);
3688         if (result != ERR_OK) {
3689             LOG_E(BMS_TAG_INSTALLER, "fail to CopyPgoFileToArkProfileDir, error is %{public}d", result);
3690             return result;
3691         }
3692     }
3693 
3694     ExtractResourceFiles(info, modulePath);
3695 
3696     result = ExtractResFileDir(modulePath);
3697     if (result != ERR_OK) {
3698         LOG_E(BMS_TAG_INSTALLER, "fail to ExtractResFileDir, error is %{public}d", result);
3699         return result;
3700     }
3701 
3702     if (auto hnpPackageInfos = info.GetInnerModuleInfoHnpInfo(info.GetCurModuleName())) {
3703         std::map<std::string, std::string> hnpPackageInfoMap;
3704         std::stringstream hnpPackageInfoString;
3705         for (const auto &hnp_packageInfo : *hnpPackageInfos) {
3706             hnpPackageInfoMap[hnp_packageInfo.package] = hnp_packageInfo.type;
3707         }
3708         for (const auto &hnpPackageKV : hnpPackageInfoMap) {
3709             hnpPackageInfoString << "{" << hnpPackageKV.first << ":" << hnpPackageKV.second << "}";
3710         }
3711         std::string cpuAbi = info.GetCpuAbi();
3712         result = ExtractHnpFileDir(cpuAbi, hnpPackageInfoString.str(), modulePath);
3713         if (result != ERR_OK) {
3714             LOG_E(BMS_TAG_INSTALLER, "fail to ExtractHnpsFileDir, error is %{public}d", result);
3715             return result;
3716         }
3717     }
3718 
3719     if (info.IsPreInstallApp()) {
3720         info.SetModuleHapPath(modulePath_);
3721     } else {
3722         info.SetModuleHapPath(GetHapPath(info));
3723     }
3724 
3725     auto moduleDir = info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR + info.GetCurrentModulePackage();
3726     info.AddModuleSrcDir(moduleDir);
3727     info.AddModuleResPath(moduleDir);
3728     info.AddModuleHnpsPath(modulePath);
3729     return ERR_OK;
3730 }
3731 
ExtractResourceFiles(const InnerBundleInfo & info,const std::string & targetPath) const3732 void BaseBundleInstaller::ExtractResourceFiles(const InnerBundleInfo &info, const std::string &targetPath) const
3733 {
3734     LOG_D(BMS_TAG_INSTALLER, "ExtractResourceFiles begin");
3735     int32_t apiTargetVersion = info.GetBaseApplicationInfo().apiTargetVersion;
3736     if (info.IsPreInstallApp() || apiTargetVersion > ServiceConstants::API_VERSION_NINE) {
3737         LOG_D(BMS_TAG_INSTALLER, "no need to extract resource files");
3738         return;
3739     }
3740     LOG_D(BMS_TAG_INSTALLER, "apiTargetVersion is %{public}d, extract resource files", apiTargetVersion);
3741     ExtractParam extractParam;
3742     extractParam.srcPath = modulePath_;
3743     extractParam.targetPath = targetPath + ServiceConstants::PATH_SEPARATOR;
3744     extractParam.extractFileType = ExtractFileType::RESOURCE;
3745     ErrCode ret = InstalldClient::GetInstance()->ExtractFiles(extractParam);
3746     LOG_D(BMS_TAG_INSTALLER, "ExtractResourceFiles ret : %{public}d", ret);
3747 }
3748 
ExtractResFileDir(const std::string & modulePath) const3749 ErrCode BaseBundleInstaller::ExtractResFileDir(const std::string &modulePath) const
3750 {
3751     LOG_D(BMS_TAG_INSTALLER, "ExtractResFileDir begin");
3752     ExtractParam extractParam;
3753     extractParam.srcPath = modulePath_;
3754     extractParam.targetPath = modulePath + ServiceConstants::PATH_SEPARATOR + ServiceConstants::RES_FILE_PATH;
3755     LOG_D(BMS_TAG_INSTALLER, "ExtractResFileDir targetPath: %{public}s", extractParam.targetPath.c_str());
3756     extractParam.extractFileType = ExtractFileType::RES_FILE;
3757     ErrCode ret = InstalldClient::GetInstance()->ExtractFiles(extractParam);
3758     if (ret != ERR_OK) {
3759         LOG_E(BMS_TAG_INSTALLER, "ExtractResFileDir ExtractFiles failed, error is %{public}d", ret);
3760         return ret;
3761     }
3762     LOG_D(BMS_TAG_INSTALLER, "ExtractResFileDir end");
3763     return ret;
3764 }
3765 
ExtractHnpFileDir(const std::string & cpuAbi,const std::string & hnpPackageInfoString,const std::string & modulePath) const3766 ErrCode BaseBundleInstaller::ExtractHnpFileDir(const std::string &cpuAbi, const std::string &hnpPackageInfoString,
3767     const std::string &modulePath) const
3768 {
3769     LOG_D(BMS_TAG_INSTALLER, "ExtractHnpFileDir begin");
3770     ExtractParam extractParam;
3771     extractParam.srcPath = modulePath_;
3772     extractParam.targetPath = modulePath + ServiceConstants::PATH_SEPARATOR + ServiceConstants::HNPS_FILE_PATH;
3773     if (ServiceConstants::ABI_MAP.find(cpuAbi) == ServiceConstants::ABI_MAP.end()) {
3774         LOG_E(BMS_TAG_INSTALLER, "No support %{public}s abi", cpuAbi.c_str());
3775         return ERR_APPEXECFWK_NATIVE_HNP_EXTRACT_FAILED;
3776     }
3777     extractParam.cpuAbi = cpuAbi;
3778     LOG_D(BMS_TAG_INSTALLER, "ExtractHnpFileDir targetPath: %{public}s", extractParam.targetPath.c_str());
3779     extractParam.extractFileType = ExtractFileType::HNPS_FILE;
3780     ErrCode ret = InstalldClient::GetInstance()->ExtractHnpFiles(hnpPackageInfoString, extractParam);
3781     if (ret != ERR_OK) {
3782         LOG_E(BMS_TAG_INSTALLER, "ExtractHnpFileDir ExtractFiles failed, error is %{public}d", ret);
3783         return ret;
3784     }
3785     LOG_D(BMS_TAG_INSTALLER, "ExtractHnpFileDir end");
3786     return ret;
3787 }
3788 
ExtractArkNativeFile(InnerBundleInfo & info,const std::string & modulePath)3789 ErrCode BaseBundleInstaller::ExtractArkNativeFile(InnerBundleInfo &info, const std::string &modulePath)
3790 {
3791     if (!info.GetArkNativeFilePath().empty()) {
3792         LOG_D(BMS_TAG_INSTALLER, "Module %{public}s no need to extract an", modulePackage_.c_str());
3793         return ERR_OK;
3794     }
3795 
3796     std::string cpuAbi = info.GetArkNativeFileAbi();
3797     if (cpuAbi.empty()) {
3798         LOG_D(BMS_TAG_INSTALLER, "Module %{public}s no native file", modulePackage_.c_str());
3799         return ERR_OK;
3800     }
3801 
3802     if (ServiceConstants::ABI_MAP.find(cpuAbi) == ServiceConstants::ABI_MAP.end()) {
3803         LOG_E(BMS_TAG_INSTALLER, "No support %{public}s abi", cpuAbi.c_str());
3804         return ERR_APPEXECFWK_PARSE_AN_FAILED;
3805     }
3806 
3807     std::string arkNativeFilePath;
3808     arkNativeFilePath.append(ServiceConstants::ABI_MAP.at(cpuAbi)).append(ServiceConstants::PATH_SEPARATOR);
3809     std::string targetPath;
3810     targetPath.append(ServiceConstants::ARK_CACHE_PATH).append(info.GetBundleName())
3811         .append(ServiceConstants::PATH_SEPARATOR).append(arkNativeFilePath);
3812     LOG_D(BMS_TAG_INSTALLER, "Begin extract an modulePath: %{public}s targetPath: %{public}s cpuAbi: %{public}s",
3813         modulePath.c_str(), targetPath.c_str(), cpuAbi.c_str());
3814     ExtractParam extractParam;
3815     extractParam.srcPath = modulePath_;
3816     extractParam.targetPath = targetPath;
3817     extractParam.cpuAbi = cpuAbi;
3818     extractParam.extractFileType = ExtractFileType::AN;
3819     auto result = InstalldClient::GetInstance()->ExtractFiles(extractParam);
3820     if (result != ERR_OK) {
3821         LOG_E(BMS_TAG_INSTALLER, "extract files failed, error is %{public}d", result);
3822         return result;
3823     }
3824 
3825     info.SetArkNativeFilePath(arkNativeFilePath);
3826     return ERR_OK;
3827 }
3828 
ExtractAllArkProfileFile(const InnerBundleInfo & oldInfo,bool checkRepeat) const3829 ErrCode BaseBundleInstaller::ExtractAllArkProfileFile(const InnerBundleInfo &oldInfo, bool checkRepeat) const
3830 {
3831     if (!oldInfo.GetIsNewVersion()) {
3832         return ERR_OK;
3833     }
3834     std::string bundleName = oldInfo.GetBundleName();
3835     LOG_I(BMS_TAG_INSTALLER, "Begin to ExtractAllArkProfileFile, bundleName : %{public}s", bundleName.c_str());
3836     const auto &innerModuleInfos = oldInfo.GetInnerModuleInfos();
3837     for (auto iter = innerModuleInfos.cbegin(); iter != innerModuleInfos.cend(); ++iter) {
3838         if (checkRepeat && installedModules_.find(iter->first) != installedModules_.end()) {
3839             continue;
3840         }
3841 
3842         ErrCode ret = CopyPgoFileToArkProfileDir(iter->second.name, iter->second.hapPath, bundleName, userId_);
3843         if (ret != ERR_OK) {
3844             LOG_E(BMS_TAG_INSTALLER, "fail to CopyPgoFileToArkProfileDir, error is %{public}d", ret);
3845             return ret;
3846         }
3847     }
3848     LOG_D(BMS_TAG_INSTALLER, "ExtractAllArkProfileFile succeed, bundleName : %{public}s", bundleName.c_str());
3849     return ERR_OK;
3850 }
3851 
CopyPgoFileToArkProfileDir(const std::string & moduleName,const std::string & modulePath,const std::string & bundleName,int32_t userId) const3852 ErrCode BaseBundleInstaller::CopyPgoFileToArkProfileDir(
3853     const std::string &moduleName,
3854     const std::string &modulePath,
3855     const std::string &bundleName,
3856     int32_t userId) const
3857 {
3858     auto it = pgoParams_.find(moduleName);
3859     if (it != pgoParams_.end()) {
3860         return CopyPgoFile(moduleName, it->second, bundleName, userId);
3861     }
3862     return ExtractArkProfileFile(modulePath, bundleName, userId);
3863 }
3864 
CopyPgoFile(const std::string & moduleName,const std::string & pgoPath,const std::string & bundleName,int32_t userId) const3865 ErrCode BaseBundleInstaller::CopyPgoFile(
3866     const std::string &moduleName,
3867     const std::string &pgoPath,
3868     const std::string &bundleName,
3869     int32_t userId) const
3870 {
3871     std::string targetPath =
3872         AOTHandler::BuildArkProfilePath(userId, bundleName, moduleName + ServiceConstants::AP_SUFFIX);
3873     if (InstalldClient::GetInstance()->CopyFile(pgoPath, targetPath) != ERR_OK) {
3874         LOG_E(BMS_TAG_INSTALLER, "copy file from %{public}s to %{public}s failed", pgoPath.c_str(), targetPath.c_str());
3875         return ERR_APPEXECFWK_INSTALL_COPY_HAP_FAILED;
3876     }
3877     return ERR_OK;
3878 }
3879 
ExtractArkProfileFile(const std::string & modulePath,const std::string & bundleName,int32_t userId) const3880 ErrCode BaseBundleInstaller::ExtractArkProfileFile(
3881     const std::string &modulePath,
3882     const std::string &bundleName,
3883     int32_t userId) const
3884 {
3885     std::string targetPath = AOTHandler::BuildArkProfilePath(userId, bundleName);
3886     LOG_D(BMS_TAG_INSTALLER, "Begin to extract ap file, modulePath : %{public}s, targetPath : %{public}s",
3887         modulePath.c_str(), targetPath.c_str());
3888     ExtractParam extractParam;
3889     extractParam.srcPath = modulePath;
3890     extractParam.targetPath = targetPath;
3891     extractParam.cpuAbi = Constants::EMPTY_STRING;
3892     extractParam.extractFileType = ExtractFileType::AP;
3893     auto result = InstalldClient::GetInstance()->ExtractFiles(extractParam);
3894     if (result != ERR_OK) {
3895         LOG_E(BMS_TAG_INSTALLER, "extract ap files failed, error is %{public}d", result);
3896         return result;
3897     }
3898     return ERR_OK;
3899 }
3900 
DeleteOldArkNativeFile(const InnerBundleInfo & oldInfo)3901 ErrCode BaseBundleInstaller::DeleteOldArkNativeFile(const InnerBundleInfo &oldInfo)
3902 {
3903     std::string targetPath;
3904     targetPath.append(ServiceConstants::ARK_CACHE_PATH).append(oldInfo.GetBundleName());
3905     auto result = InstalldClient::GetInstance()->RemoveDir(targetPath);
3906     if (result != ERR_OK) {
3907         LOG_E(BMS_TAG_INSTALLER, "fail to remove arkNativeFilePath %{public}s, error is %{public}d",
3908             targetPath.c_str(), result);
3909     }
3910 
3911     return result;
3912 }
3913 
RemoveBundleAndDataDir(const InnerBundleInfo & info,bool isKeepData,const bool async)3914 ErrCode BaseBundleInstaller::RemoveBundleAndDataDir(const InnerBundleInfo &info, bool isKeepData, const bool async)
3915 {
3916     ErrCode result = ERR_OK;
3917     if (!isKeepData) {
3918         result = RemoveBundleDataDir(info, false, async);
3919         if (result != ERR_OK) {
3920             LOG_E(BMS_TAG_INSTALLER, "fail to remove bundleData dir %{public}s, error is %{public}d",
3921                 info.GetBundleName().c_str(), result);
3922             return result;
3923         }
3924     }
3925     // remove bundle dir
3926     result = RemoveBundleCodeDir(info);
3927     if (result != ERR_OK) {
3928         LOG_E(BMS_TAG_INSTALLER, "remove dir fail %{public}s error %{public}d", info.GetAppCodePath().c_str(), result);
3929         return result;
3930     }
3931     return result;
3932 }
3933 
RemoveBundleCodeDir(const InnerBundleInfo & info) const3934 ErrCode BaseBundleInstaller::RemoveBundleCodeDir(const InnerBundleInfo &info) const
3935 {
3936     auto result = InstalldClient::GetInstance()->RemoveDir(info.GetAppCodePath());
3937     if (result != ERR_OK) {
3938         LOG_E(BMS_TAG_INSTALLER, "fail to remove bundle code dir %{public}s, error is %{public}d",
3939             info.GetAppCodePath().c_str(), result);
3940     }
3941     return result;
3942 }
3943 
RemoveBundleDataDir(const InnerBundleInfo & info,bool forException,const bool async)3944 ErrCode BaseBundleInstaller::RemoveBundleDataDir(
3945     const InnerBundleInfo &info, bool forException, const bool async)
3946 {
3947     ErrCode result =
3948         InstalldClient::GetInstance()->RemoveBundleDataDir(info.GetBundleName(), userId_,
3949             info.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE, async);
3950     InstallParam installParam;
3951     if (result == ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED) {
3952         LOG_W(BMS_TAG_INSTALLER, "RemoveBundleDataDir failed %{public}d", result);
3953         SendBundleSystemEvent(
3954             info.GetBundleName(),
3955             BundleEventType::UNINSTALL,
3956             installParam,
3957             sysEventInfo_.preBundleScene,
3958             ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED);
3959     }
3960 
3961     if (forException) {
3962         result = InstalldClient::GetInstance()->RemoveExtensionDir(userId_, createExtensionDirs_);
3963     } else {
3964         auto extensionDirs = info.GetAllExtensionDirs();
3965         result = InstalldClient::GetInstance()->RemoveExtensionDir(userId_, extensionDirs);
3966     }
3967     if (result == ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED) {
3968         LOG_E(BMS_TAG_INSTALLER, "fail to remove bundle extension dir, error is %{public}d", result);
3969         SendBundleSystemEvent(
3970             info.GetBundleName(),
3971             BundleEventType::UNINSTALL,
3972             installParam,
3973             sysEventInfo_.preBundleScene,
3974             result);
3975     }
3976     return ERR_OK;
3977 }
3978 
RemoveEmptyDirs(const std::unordered_map<std::string,InnerBundleInfo> & infos) const3979 void BaseBundleInstaller::RemoveEmptyDirs(const std::unordered_map<std::string, InnerBundleInfo> &infos) const
3980 {
3981     for (const auto &item : infos) {
3982         const InnerBundleInfo &info = item.second;
3983         std::string moduleDir = info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR
3984             + info.GetCurrentModulePackage();
3985         bool isDirEmpty = false;
3986         InstalldClient::GetInstance()->IsDirEmpty(moduleDir, isDirEmpty);
3987         if (isDirEmpty) {
3988             LOG_D(BMS_TAG_INSTALLER, "remove empty dir : %{public}s", moduleDir.c_str());
3989             InstalldClient::GetInstance()->RemoveDir(moduleDir);
3990         }
3991     }
3992 }
3993 
GetModuleNames(const std::unordered_map<std::string,InnerBundleInfo> & infos) const3994 std::string BaseBundleInstaller::GetModuleNames(const std::unordered_map<std::string, InnerBundleInfo> &infos) const
3995 {
3996     if (infos.empty()) {
3997         LOG_E(BMS_TAG_INSTALLER, "module info is empty");
3998         return Constants::EMPTY_STRING;
3999     }
4000     std::string moduleNames;
4001     for (const auto &item : infos) {
4002         moduleNames.append(item.second.GetCurrentModulePackage()).append(ServiceConstants::MODULE_NAME_SEPARATOR);
4003     }
4004     moduleNames.pop_back();
4005     LOG_D(BMS_TAG_INSTALLER, "moduleNames : %{public}s", moduleNames.c_str());
4006     return moduleNames;
4007 }
4008 
RemoveModuleAndDataDir(const InnerBundleInfo & info,const std::string & modulePackage,int32_t userId,bool isKeepData) const4009 ErrCode BaseBundleInstaller::RemoveModuleAndDataDir(
4010     const InnerBundleInfo &info, const std::string &modulePackage, int32_t userId, bool isKeepData) const
4011 {
4012     LOG_D(BMS_TAG_INSTALLER, "RemoveModuleAndDataDir with package name %{public}s", modulePackage.c_str());
4013     auto moduleDir = info.GetModuleDir(modulePackage);
4014     auto result = RemoveModuleDir(moduleDir);
4015     if (result != ERR_OK) {
4016         LOG_E(BMS_TAG_INSTALLER, "fail to remove module dir, error is %{public}d", result);
4017         return result;
4018     }
4019 
4020     // remove hap
4021     result = RemoveModuleDir(GetHapPath(info, info.GetModuleName(modulePackage)));
4022     if (result != ERR_OK) {
4023         LOG_E(BMS_TAG_INSTALLER, "fail to remove module hap, error is %{public}d", result);
4024         return result;
4025     }
4026     LOG_D(BMS_TAG_INSTALLER, "RemoveModuleAndDataDir successfully");
4027     return ERR_OK;
4028 }
4029 
RemoveModuleDir(const std::string & modulePath) const4030 ErrCode BaseBundleInstaller::RemoveModuleDir(const std::string &modulePath) const
4031 {
4032     LOG_D(BMS_TAG_INSTALLER, "module dir %{public}s to be removed", modulePath.c_str());
4033     return InstalldClient::GetInstance()->RemoveDir(modulePath);
4034 }
4035 
ExtractModuleFiles(const InnerBundleInfo & info,const std::string & modulePath,const std::string & targetSoPath,const std::string & cpuAbi)4036 ErrCode BaseBundleInstaller::ExtractModuleFiles(const InnerBundleInfo &info, const std::string &modulePath,
4037     const std::string &targetSoPath, const std::string &cpuAbi)
4038 {
4039     LOG_D(BMS_TAG_INSTALLER, "extract module to %{public}s", modulePath.c_str());
4040     auto result = InstalldClient::GetInstance()->ExtractModuleFiles(modulePath_, modulePath, targetSoPath, cpuAbi);
4041     if (result != ERR_OK) {
4042         LOG_E(BMS_TAG_INSTALLER, "extract module files failed, error is %{public}d", result);
4043         return result;
4044     }
4045 
4046     return ERR_OK;
4047 }
4048 
RenameModuleDir(const InnerBundleInfo & info) const4049 ErrCode BaseBundleInstaller::RenameModuleDir(const InnerBundleInfo &info) const
4050 {
4051     auto moduleDir = info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR + info.GetCurrentModulePackage();
4052     LOG_D(BMS_TAG_INSTALLER, "rename module to %{public}s", moduleDir.c_str());
4053     auto result = InstalldClient::GetInstance()->RenameModuleDir(moduleDir + ServiceConstants::TMP_SUFFIX, moduleDir);
4054     if (result != ERR_OK) {
4055         LOG_E(BMS_TAG_INSTALLER, "rename module dir failed, error is %{public}d", result);
4056         return result;
4057     }
4058     return ERR_OK;
4059 }
4060 
CheckSysCap(const std::vector<std::string> & bundlePaths)4061 ErrCode BaseBundleInstaller::CheckSysCap(const std::vector<std::string> &bundlePaths)
4062 {
4063     return bundleInstallChecker_->CheckSysCap(bundlePaths);
4064 }
4065 
CheckMultipleHapsSignInfo(const std::vector<std::string> & bundlePaths,const InstallParam & installParam,std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)4066 ErrCode BaseBundleInstaller::CheckMultipleHapsSignInfo(
4067     const std::vector<std::string> &bundlePaths,
4068     const InstallParam &installParam,
4069     std::vector<Security::Verify::HapVerifyResult>& hapVerifyRes)
4070 {
4071     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
4072     return bundleInstallChecker_->CheckMultipleHapsSignInfo(bundlePaths, hapVerifyRes);
4073 }
4074 
CheckShellInstall(std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)4075 ErrCode BaseBundleInstaller::CheckShellInstall(std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes)
4076 {
4077 #ifdef X86_EMULATOR_MODE
4078     return CheckShellInstallForEmulator(hapVerifyRes);
4079 #else
4080     if (sysEventInfo_.callingUid != ServiceConstants::SHELL_UID || hapVerifyRes.empty()) {
4081         return ERR_OK;
4082     }
4083     Security::Verify::ProvisionInfo provisionInfo = hapVerifyRes.begin()->GetProvisionInfo();
4084     if (provisionInfo.distributionType == Security::Verify::AppDistType::APP_GALLERY &&
4085         provisionInfo.type == Security::Verify::ProvisionType::RELEASE && !IsRdDevice()) {
4086         return ERR_APPEXECFWK_INSTALL_RELEASE_BUNDLE_NOT_ALLOWED_FOR_SHELL;
4087     }
4088     return ERR_OK;
4089 #endif
4090 }
4091 
4092 #ifdef X86_EMULATOR_MODE
CheckShellInstallForEmulator(std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)4093 ErrCode BaseBundleInstaller::CheckShellInstallForEmulator(std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes)
4094 {
4095     if (hapVerifyRes.empty()) {
4096         return ERR_OK;
4097     }
4098     Security::Verify::ProvisionInfo provisionInfo = hapVerifyRes.begin()->GetProvisionInfo();
4099     if (provisionInfo.distributionType != Security::Verify::AppDistType::APP_GALLERY ||
4100         provisionInfo.type != Security::Verify::ProvisionType::RELEASE) {
4101         return ERR_OK;
4102     }
4103 #ifdef BUILD_VARIANT_USER
4104     if (sysEventInfo_.callingUid == ServiceConstants::SHELL_UID ||
4105         sysEventInfo_.callingUid == Constants::ROOT_UID) {
4106         return ERR_APPEXECFWK_INSTALL_RELEASE_BUNDLE_NOT_ALLOWED_FOR_SHELL;
4107     }
4108 #else
4109     if (sysEventInfo_.callingUid == ServiceConstants::SHELL_UID && !IsRdDevice()) {
4110         return ERR_APPEXECFWK_INSTALL_RELEASE_BUNDLE_NOT_ALLOWED_FOR_SHELL;
4111     }
4112 #endif
4113     return ERR_OK;
4114 }
4115 #endif
4116 
CheckShellInstallInOobe()4117 ErrCode BaseBundleInstaller::CheckShellInstallInOobe()
4118 {
4119     if (sysEventInfo_.callingUid != ServiceConstants::SHELL_UID) {
4120         return ERR_OK;
4121     }
4122     if (!VerifyActivationLockToken()) {
4123         return ERR_APPEXECFWK_INSTALL_BUNDLE_NOT_ALLOWED_FOR_SHELL_IN_OOBE;
4124     }
4125     return ERR_OK;
4126 }
4127 
ParseHapFiles(const std::vector<std::string> & bundlePaths,const InstallParam & installParam,const Constants::AppType appType,std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes,std::unordered_map<std::string,InnerBundleInfo> & infos)4128 ErrCode BaseBundleInstaller::ParseHapFiles(
4129     const std::vector<std::string> &bundlePaths,
4130     const InstallParam &installParam,
4131     const Constants::AppType appType,
4132     std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes,
4133     std::unordered_map<std::string, InnerBundleInfo> &infos)
4134 {
4135     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
4136     InstallCheckParam checkParam;
4137     checkParam.isPreInstallApp = installParam.isPreInstallApp;
4138     checkParam.crowdtestDeadline = installParam.crowdtestDeadline;
4139     checkParam.specifiedDistributionType = installParam.specifiedDistributionType;
4140     checkParam.appType = appType;
4141     checkParam.removable = installParam.removable;
4142     checkParam.isInstalledForAllUser = installParam.IsEnterpriseForAllUser();
4143     ErrCode ret = bundleInstallChecker_->ParseHapFiles(
4144         bundlePaths, checkParam, hapVerifyRes, infos);
4145     if (ret != ERR_OK) {
4146         LOG_E(BMS_TAG_INSTALLER, "parse hap file failed due to errorCode : %{public}d", ret);
4147         return ret;
4148     }
4149     if (!infos.empty()) {
4150         bundleType_ = infos.begin()->second.GetApplicationBundleType();
4151     }
4152     // protect err scene
4153     dataMgr_->UpdateAppEncryptedStatus(infos.begin()->second.GetBundleName(), false, 0, true);
4154     GenerateOdid(infos, hapVerifyRes);
4155     isContainEntry_ = bundleInstallChecker_->IsContainEntry();
4156     /* At this place, hapVerifyRes cannot be empty and unnecessary to check it */
4157     isEnterpriseBundle_ = bundleInstallChecker_->CheckEnterpriseBundle(hapVerifyRes[0]);
4158     isInternaltestingBundle_ = bundleInstallChecker_->CheckInternaltestingBundle(hapVerifyRes[0]);
4159     appIdentifier_ = (hapVerifyRes[0].GetProvisionInfo().type == Security::Verify::ProvisionType::DEBUG) ?
4160         DEBUG_APP_IDENTIFIER : hapVerifyRes[0].GetProvisionInfo().bundleInfo.appIdentifier;
4161     SetAppDistributionType(infos);
4162     UpdateExtensionSandboxInfo(infos, hapVerifyRes);
4163     return ret;
4164 }
4165 
CheckArkTSMode(const std::unordered_map<std::string,InnerBundleInfo> & newInfos)4166 ErrCode BaseBundleInstaller::CheckArkTSMode(const std::unordered_map<std::string, InnerBundleInfo> &newInfos)
4167 {
4168     if (newInfos.empty()) {
4169         LOG_W(BMS_TAG_INSTALLER, "newInfos is empty");
4170         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
4171     }
4172     if (newInfos.begin()->second.GetApplicationBundleType() != BundleType::ATOMIC_SERVICE) {
4173         return ERR_OK;
4174     }
4175     auto needControl = std::any_of(newInfos.begin(), newInfos.end(),
4176         [](const auto &item) {
4177             return std::any_of(item.second.GetInnerModuleInfos().begin(),
4178                 item.second.GetInnerModuleInfos().end(),
4179                 [](const auto &moduleItem) {
4180                     return moduleItem.second.moduleArkTSMode != Constants::ARKTS_MODE_DYNAMIC;
4181                 });
4182         });
4183     if (needControl) {
4184         LOG_W(BMS_TAG_INSTALLER, "atomicService is not dynamic -n:%{public}s",
4185             newInfos.begin()->second.GetBundleName().c_str());
4186         return ERR_APPEXECFWK_INSTALL_NOT_SUPPORT_STATIC_ATOMIC_SERVICE;
4187     }
4188     return ERR_OK;
4189 }
4190 
UpdateExtensionSandboxInfo(std::unordered_map<std::string,InnerBundleInfo> & newInfos,const std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)4191 void BaseBundleInstaller::UpdateExtensionSandboxInfo(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
4192     const std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes)
4193 {
4194     if (newInfos.empty() || hapVerifyRes.empty()) {
4195         LOG_E(BMS_TAG_INSTALLER, "innerBundleInfo map or hapVerifyRes is empty");
4196         return;
4197     }
4198     Security::Verify::ProvisionInfo provisionInfo = hapVerifyRes.begin()->GetProvisionInfo();
4199     auto dataGroupGids = provisionInfo.bundleInfo.dataGroupIds;
4200     std::vector<std::string> typeList;
4201     ErrCode res = InstalldClient::GetInstance()->GetExtensionSandboxTypeList(typeList);
4202     if (res != ERR_OK) {
4203         LOG_E(BMS_TAG_INSTALLER, "GetExtensionSandboxTypeList failed %{public}d", res);
4204     }
4205     for (auto &item : newInfos) {
4206         item.second.UpdateExtensionSandboxInfo(typeList);
4207         auto innerBundleInfo = item.second;
4208         auto extensionInfoMap = innerBundleInfo.GetInnerExtensionInfos();
4209         for (auto iter = extensionInfoMap.begin(); iter != extensionInfoMap.end(); iter++) {
4210             if (!iter->second.needCreateSandbox) {
4211                 continue;
4212             }
4213             std::string key = iter->second.bundleName + "." + iter->second.moduleName + "." +  iter->second.name;
4214 
4215             std::vector<std::string> validGroupIds;
4216             GetValidDataGroupIds(iter->second.dataGroupIds, dataGroupGids, validGroupIds);
4217             LOG_I(BMS_TAG_INSTALLER, "extension %{public}s need to create dir on user %{public}d",
4218                 iter->second.name.c_str(), userId_);
4219             item.second.UpdateExtensionDataGroupInfo(key, validGroupIds);
4220         }
4221     }
4222 }
4223 
GetValidDataGroupIds(const std::vector<std::string> & extensionDataGroupIds,const std::vector<std::string> & bundleDataGroupIds,std::vector<std::string> & validGroupIds) const4224 void BaseBundleInstaller::GetValidDataGroupIds(const std::vector<std::string> &extensionDataGroupIds,
4225     const std::vector<std::string> &bundleDataGroupIds, std::vector<std::string> &validGroupIds) const
4226 {
4227     for (const std::string &dataGroupId : extensionDataGroupIds) {
4228         if (std::find(bundleDataGroupIds.begin(), bundleDataGroupIds.end(), dataGroupId) != bundleDataGroupIds.end()) {
4229             validGroupIds.emplace_back(dataGroupId);
4230         }
4231         LOG_I(BMS_TAG_INSTALLER, "dataGroupId %{public}s is invalid", dataGroupId.c_str());
4232     }
4233 }
4234 
GetExtensionDirsChange(std::unordered_map<std::string,InnerBundleInfo> & newInfos,const InnerBundleInfo & oldInfo)4235 void BaseBundleInstaller::GetExtensionDirsChange(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
4236     const InnerBundleInfo &oldInfo)
4237 {
4238     GetCreateExtensionDirs(newInfos);
4239     GetRemoveExtensionDirs(newInfos, oldInfo);
4240 }
4241 
CreateExtensionDataDir(InnerBundleInfo & info) const4242 void BaseBundleInstaller::CreateExtensionDataDir(InnerBundleInfo &info) const
4243 {
4244     if (createExtensionDirs_.empty()) {
4245         return;
4246     }
4247     InnerBundleUserInfo newInnerBundleUserInfo;
4248     if (!info.GetInnerBundleUserInfo(userId_, newInnerBundleUserInfo)) {
4249         LOG_E(BMS_TAG_INSTALLER, "bundle(%{public}s) get user(%{public}d) failed",
4250             info.GetBundleName().c_str(), userId_);
4251         return;
4252     }
4253     CreateDirParam createDirParam;
4254     createDirParam.bundleName = info.GetBundleName();
4255     createDirParam.userId = userId_;
4256     createDirParam.uid = newInnerBundleUserInfo.uid;
4257     createDirParam.gid = newInnerBundleUserInfo.uid;
4258     createDirParam.apl = info.GetAppPrivilegeLevel();
4259     createDirParam.isPreInstallApp = info.IsPreInstallApp();
4260     createDirParam.debug = info.GetBaseApplicationInfo().appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG;
4261     createDirParam.extensionDirs.assign(createExtensionDirs_.begin(), createExtensionDirs_.end());
4262 
4263     auto result = InstalldClient::GetInstance()->CreateExtensionDataDir(createDirParam);
4264     if (result != ERR_OK) {
4265         LOG_E(BMS_TAG_INSTALLER, "fail to create bundle extension data dir, error is %{public}d", result);
4266     }
4267 }
4268 
GenerateNewUserDataGroupInfos(InnerBundleInfo & info) const4269 void BaseBundleInstaller::GenerateNewUserDataGroupInfos(InnerBundleInfo &info) const
4270 {
4271     if (dataMgr_ == nullptr) {
4272         LOG_E(BMS_TAG_INSTALLER, "dataMgr_ is nullptr");
4273         return;
4274     }
4275     dataMgr_->GenerateNewUserDataGroupInfos(info.GetBundleName(), userId_);
4276 }
4277 
GetCreateExtensionDirs(std::unordered_map<std::string,InnerBundleInfo> & newInfos)4278 void BaseBundleInstaller::GetCreateExtensionDirs(std::unordered_map<std::string, InnerBundleInfo> &newInfos)
4279 {
4280     for (auto &item : newInfos) {
4281         auto innerBundleInfo = item.second;
4282         auto moduleName = innerBundleInfo.GetCurModuleName();
4283         auto extensionDirSet = innerBundleInfo.GetAllExtensionDirsInSpecifiedModule(moduleName);
4284         for (const std::string &dir : extensionDirSet) {
4285             newExtensionDirs_.emplace_back(dir);
4286             bool dirExist = false;
4287             auto result = InstalldClient::GetInstance()->IsExistExtensionDir(userId_, dir, dirExist);
4288             if (result != ERR_OK || !dirExist) {
4289                 LOG_I(BMS_TAG_INSTALLER, "dir: %{public}s need to be created", dir.c_str());
4290                 createExtensionDirs_.emplace_back(dir);
4291             }
4292         }
4293     }
4294 }
4295 
GetRemoveExtensionDirs(std::unordered_map<std::string,InnerBundleInfo> & newInfos,const InnerBundleInfo & oldInfo)4296 void BaseBundleInstaller::GetRemoveExtensionDirs(
4297     std::unordered_map<std::string, InnerBundleInfo> &newInfos, const InnerBundleInfo &oldInfo)
4298 {
4299     if (newInfos.empty()) {
4300         LOG_E(BMS_TAG_INSTALLER, "newInfos is empty");
4301         return;
4302     }
4303     if (!isAppExist_) {
4304         // Install it for the first time
4305         return;
4306     }
4307     std::vector<std::string> oldModuleNames;
4308     const auto &innerBundleInfo = newInfos.begin()->second;
4309     oldInfo.GetModuleNames(oldModuleNames);
4310     if (innerBundleInfo.GetVersionCode() > oldInfo.GetVersionCode()) {
4311         std::set<std::string> newModules;
4312         for (const auto &item : newInfos) {
4313             std::vector<std::string> curModules;
4314             item.second.GetModuleNames(curModules);
4315             newModules.insert(curModules.begin(), curModules.end());
4316         }
4317         for (const std::string &oldModuleName : oldModuleNames) {
4318             if (newModules.find(oldModuleName) == newModules.end()) {
4319                 // module does not exist in the later version, so it's extension dir needs to be removed
4320                 const auto oldExtensionDirs = oldInfo.GetAllExtensionDirsInSpecifiedModule(oldModuleName);
4321                 LOG_I(BMS_TAG_INSTALLER, "Dirs size %{public}zu need to be removed", oldExtensionDirs.size());
4322                 std::copy(oldExtensionDirs.begin(), oldExtensionDirs.end(), std::back_inserter(removeExtensionDirs_));
4323             }
4324         }
4325     }
4326     for (const auto& item : newInfos) {
4327         std::string modulePackage = item.second.GetCurModuleName();
4328         if (!oldInfo.FindModule(modulePackage)) {
4329             // install a new module
4330             continue;
4331         }
4332         // update a existed module
4333         auto oldDirList = oldInfo.GetAllExtensionDirsInSpecifiedModule(
4334             oldInfo.GetModuleNameByPackage(modulePackage));
4335         for (const std::string &oldDir : oldDirList) {
4336             if (std::find(newExtensionDirs_.begin(), newExtensionDirs_.end(), oldDir) == newExtensionDirs_.end()) {
4337                 LOG_I(BMS_TAG_INSTALLER, "dir %{public}s need to be removed", oldDir.c_str());
4338                 removeExtensionDirs_.emplace_back(oldDir);
4339             }
4340         }
4341     }
4342 }
4343 
RemoveCreatedExtensionDirsForException() const4344 void BaseBundleInstaller::RemoveCreatedExtensionDirsForException() const
4345 {
4346     if (createExtensionDirs_.empty()) {
4347         LOG_I(BMS_TAG_INSTALLER, "no need to remove extension sandbox dir");
4348         return;
4349     }
4350     if (InstalldClient::GetInstance()->RemoveExtensionDir(userId_, createExtensionDirs_) != ERR_OK) {
4351         LOG_W(BMS_TAG_INSTALLER, "remove created extension sandbox dir failed");
4352     }
4353 }
4354 
RemoveOldExtensionDirs() const4355 void BaseBundleInstaller::RemoveOldExtensionDirs() const
4356 {
4357     if (removeExtensionDirs_.empty()) {
4358         LOG_D(BMS_TAG_INSTALLER, "no need to remove old extension sandbox dir");
4359         return;
4360     }
4361     auto result = InstalldClient::GetInstance()->RemoveExtensionDir(userId_, removeExtensionDirs_);
4362     if (result != ERR_OK) {
4363         LOG_W(BMS_TAG_INSTALLER, "remove old extension sandbox dirfailed");
4364     }
4365 }
4366 
GetInstallSource(const InstallParam & installParam) const4367 std::string BaseBundleInstaller::GetInstallSource(const InstallParam &installParam) const
4368 {
4369     if (installParam.isPreInstallApp) {
4370         switch (installParam.preinstallSourceFlag) {
4371             case ApplicationInfoFlag::FLAG_BOOT_INSTALLED:
4372                 return ServiceConstants::INSTALL_SOURCE_PREINSTALL;
4373             case ApplicationInfoFlag::FLAG_OTA_INSTALLED:
4374                 return ServiceConstants::INSTALL_SOURCE_OTA;
4375             case ApplicationInfoFlag::FLAG_RECOVER_INSTALLED:
4376                 return ServiceConstants::INSTALL_SOURCE_RECOVERY;
4377             default:
4378                 return ServiceConstants::INSTALL_SOURCE_PREINSTALL;
4379         }
4380     }
4381     std::shared_ptr<BundleDataMgr> dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4382     if (dataMgr == nullptr) {
4383         LOG_I(BMS_TAG_INSTALLER, "dataMgr is nullptr return unknown");
4384         return INSTALL_SOURCE_UNKNOWN;
4385     }
4386     std::string callingBundleName;
4387     ErrCode ret = dataMgr->GetNameForUid(sysEventInfo_.callingUid, callingBundleName);
4388     if (ret != ERR_OK) {
4389         LOG_I(BMS_TAG_INSTALLER, "get bundle name failed return unknown");
4390         return INSTALL_SOURCE_UNKNOWN;
4391     }
4392     return callingBundleName;
4393 }
4394 
SetApplicationFlagsAndInstallSource(std::unordered_map<std::string,InnerBundleInfo> & infos,const InstallParam & installParam) const4395 void BaseBundleInstaller::SetApplicationFlagsAndInstallSource(
4396     std::unordered_map<std::string, InnerBundleInfo> &infos, const InstallParam &installParam) const
4397 {
4398     std::string installSource = GetInstallSource(installParam);
4399     for (auto &info : infos) {
4400         info.second.SetApplicationFlags(installParam.preinstallSourceFlag);
4401         info.second.SetInstallSource(installSource);
4402     }
4403 }
4404 
SetAppDistributionType(const std::unordered_map<std::string,InnerBundleInfo> & infos)4405 void BaseBundleInstaller::SetAppDistributionType(const std::unordered_map<std::string, InnerBundleInfo> &infos)
4406 {
4407     if (infos.empty()) {
4408         LOG_E(BMS_TAG_INSTALLER, "infos is empty");
4409         return;
4410     }
4411     appDistributionType_ = infos.begin()->second.GetAppDistributionType();
4412 }
4413 
GenerateOdid(std::unordered_map<std::string,InnerBundleInfo> & infos,const std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes) const4414 void BaseBundleInstaller::GenerateOdid(
4415     std::unordered_map<std::string, InnerBundleInfo> &infos,
4416     const std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes) const
4417 {
4418     if (hapVerifyRes.size() < infos.size() || infos.empty()) {
4419         LOG_E(BMS_TAG_INSTALLER, "hapVerifyRes size less than infos size or infos is empty");
4420         return;
4421     }
4422     std::shared_ptr<BundleDataMgr> dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4423     if (dataMgr == nullptr) {
4424         LOG_E(BMS_TAG_INSTALLER, "Get dataMgr shared_ptr nullptr");
4425         return;
4426     }
4427 
4428     std::string developerId = hapVerifyRes[0].GetProvisionInfo().bundleInfo.developerId;
4429     if (developerId.empty()) {
4430         developerId = hapVerifyRes[0].GetProvisionInfo().bundleInfo.bundleName;
4431     }
4432     std::string odid;
4433     dataMgr->GenerateOdid(developerId, odid);
4434 
4435     for (auto &item : infos) {
4436         item.second.UpdateOdid(developerId, odid);
4437     }
4438 }
4439 
GetDataGroupIds(const std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes,std::unordered_set<std::string> & groupIds)4440 void BaseBundleInstaller::GetDataGroupIds(const std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes,
4441     std::unordered_set<std::string> &groupIds)
4442 {
4443     for (size_t i = 0; i < hapVerifyRes.size(); i++) {
4444         Security::Verify::ProvisionInfo provisionInfo = hapVerifyRes[i].GetProvisionInfo();
4445         auto dataGroupIds = provisionInfo.bundleInfo.dataGroupIds;
4446         if (dataGroupIds.empty()) {
4447             continue;
4448         }
4449         for (const std::string &id : dataGroupIds) {
4450             groupIds.insert(id);
4451         }
4452     }
4453 }
4454 
CheckInstallCondition(std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes,std::unordered_map<std::string,InnerBundleInfo> & infos,bool isSysCapValid)4455 ErrCode BaseBundleInstaller::CheckInstallCondition(
4456     std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes,
4457     std::unordered_map<std::string, InnerBundleInfo> &infos, bool isSysCapValid)
4458 {
4459     ErrCode ret;
4460     if (!isSysCapValid) {
4461         ret = bundleInstallChecker_->CheckDeviceType(infos);
4462         if (ret != ERR_OK) {
4463             LOG_E(BMS_TAG_INSTALLER, "CheckDeviceType failed due to errorCode : %{public}d", ret);
4464             return ERR_APPEXECFWK_INSTALL_SYSCAP_FAILED_AND_DEVICE_TYPE_ERROR;
4465         }
4466     }
4467     ret = bundleInstallChecker_->CheckIsolationMode(infos);
4468     if (ret != ERR_OK) {
4469         LOG_E(BMS_TAG_INSTALLER, "CheckIsolationMode failed due to errorCode : %{public}d", ret);
4470         return ret;
4471     }
4472     ret = bundleInstallChecker_->CheckHspInstallCondition(hapVerifyRes, callerToken_);
4473     if (ret != ERR_OK) {
4474         LOG_E(BMS_TAG_INSTALLER, "CheckInstallCondition failed due to errorCode : %{public}d", ret);
4475         return ret;
4476     }
4477     return ERR_OK;
4478 }
4479 
CheckInstallPermission(const InstallParam & installParam,std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)4480 ErrCode BaseBundleInstaller::CheckInstallPermission(const InstallParam &installParam,
4481     std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes)
4482 {
4483     if ((installParam.installBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
4484         installParam.installEnterpriseBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
4485         installParam.installEtpNormalBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
4486         installParam.installEtpMdmBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
4487         installParam.installInternaltestingBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
4488         installParam.installUpdateSelfBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS) &&
4489         !bundleInstallChecker_->VaildInstallPermission(installParam, hapVerifyRes)) {
4490         // need vaild permission
4491         LOG_E(BMS_TAG_INSTALLER, "install permission denied");
4492         return ERR_APPEXECFWK_INSTALL_PERMISSION_DENIED;
4493     }
4494     return ERR_OK;
4495 }
4496 
CheckDependency(std::unordered_map<std::string,InnerBundleInfo> & infos,const SharedBundleInstaller & sharedBundleInstaller)4497 ErrCode BaseBundleInstaller::CheckDependency(std::unordered_map<std::string, InnerBundleInfo> &infos,
4498     const SharedBundleInstaller &sharedBundleInstaller)
4499 {
4500     for (const auto &info : infos) {
4501         if (!sharedBundleInstaller.CheckDependency(info.second)) {
4502             LOG_E(BMS_TAG_INSTALLER, "cross-app dependency check failed");
4503             return ERR_APPEXECFWK_INSTALL_DEPENDENT_MODULE_NOT_EXIST;
4504         }
4505     }
4506 
4507     return bundleInstallChecker_->CheckDependency(infos);
4508 }
4509 
CheckHapHashParams(std::unordered_map<std::string,InnerBundleInfo> & infos,std::map<std::string,std::string> hashParams)4510 ErrCode BaseBundleInstaller::CheckHapHashParams(
4511     std::unordered_map<std::string, InnerBundleInfo> &infos,
4512     std::map<std::string, std::string> hashParams)
4513 {
4514     return bundleInstallChecker_->CheckHapHashParams(infos, hashParams);
4515 }
4516 
CheckAppLabelInfo(const std::unordered_map<std::string,InnerBundleInfo> & infos)4517 ErrCode BaseBundleInstaller::CheckAppLabelInfo(const std::unordered_map<std::string, InnerBundleInfo> &infos)
4518 {
4519     for (const auto &info : infos) {
4520         if (info.second.GetApplicationBundleType() == BundleType::SHARED) {
4521             LOG_E(BMS_TAG_INSTALLER, "installing cross-app shared library");
4522             return ERR_APPEXECFWK_INSTALL_FILE_IS_SHARED_LIBRARY;
4523         }
4524     }
4525 
4526     ErrCode ret = bundleInstallChecker_->CheckAppLabelInfo(infos);
4527     if (ret != ERR_OK) {
4528         LOG_E(BMS_TAG_INSTALLER, "check app label info error");
4529         return ret;
4530     }
4531 
4532     if (!CheckApiInfo(infos)) {
4533         LOG_E(BMS_TAG_INSTALLER, "CheckApiInfo failed");
4534         return ERR_APPEXECFWK_INSTALL_SDK_INCOMPATIBLE;
4535     }
4536 
4537     bundleName_ = (infos.begin()->second).GetBundleName();
4538     versionCode_ = (infos.begin()->second).GetVersionCode();
4539     return ERR_OK;
4540 }
4541 
CheckApiInfo(const std::unordered_map<std::string,InnerBundleInfo> & infos)4542 bool BaseBundleInstaller::CheckApiInfo(const std::unordered_map<std::string, InnerBundleInfo> &infos)
4543 {
4544     std::string compileSdkType = infos.begin()->second.GetBaseApplicationInfo().compileSdkType;
4545     auto bundleInfo = infos.begin()->second.GetBaseBundleInfo();
4546     uint32_t systemApiVersion = static_cast<uint32_t>(GetSdkApiVersion());
4547     if (compileSdkType == COMPILE_SDK_TYPE_OPEN_HARMONY) {
4548         bool res = bundleInfo.compatibleVersion <= systemApiVersion;
4549         if (!res) {
4550             LOG_E(BMS_TAG_INSTALLER, "CheckApiInfo failed with compatibleVersion:%{public}d, sysApiVer:%{public}d",
4551                 bundleInfo.compatibleVersion, systemApiVersion);
4552         }
4553         return res;
4554     }
4555     BmsExtensionDataMgr bmsExtensionDataMgr;
4556     return bmsExtensionDataMgr.CheckApiInfo(infos.begin()->second.GetBaseBundleInfo(), systemApiVersion);
4557 }
4558 
CheckMultiNativeFile(std::unordered_map<std::string,InnerBundleInfo> & infos)4559 ErrCode BaseBundleInstaller::CheckMultiNativeFile(
4560     std::unordered_map<std::string, InnerBundleInfo> &infos)
4561 {
4562     return bundleInstallChecker_->CheckMultiNativeFile(infos);
4563 }
4564 
CheckProxyDatas(const std::unordered_map<std::string,InnerBundleInfo> & infos)4565 ErrCode BaseBundleInstaller::CheckProxyDatas(
4566     const std::unordered_map<std::string, InnerBundleInfo> &infos)
4567 {
4568     if (!CheckDuplicateProxyData(infos)) {
4569         LOG_E(BMS_TAG_INSTALLER, "duplicated uri in proxyDatas");
4570         return ERR_APPEXECFWK_INSTALL_CHECK_PROXY_DATA_URI_FAILED;
4571     }
4572     for (const auto &info : infos) {
4573         ErrCode ret = bundleInstallChecker_->CheckProxyDatas(info.second);
4574         if (ret != ERR_OK) {
4575             return ret;
4576         }
4577     }
4578     return ERR_OK;
4579 }
4580 
CheckMDMUpdateBundleForSelf(const InstallParam & installParam,InnerBundleInfo & oldInfo,const std::unordered_map<std::string,InnerBundleInfo> & newInfos,bool isAppExist)4581 ErrCode BaseBundleInstaller::CheckMDMUpdateBundleForSelf(const InstallParam &installParam,
4582     InnerBundleInfo &oldInfo, const std::unordered_map<std::string, InnerBundleInfo> &newInfos, bool isAppExist)
4583 {
4584     if (!installParam.isSelfUpdate) {
4585         return ERR_OK;
4586     }
4587     if (!OHOS::system::GetBoolParameter(ServiceConstants::ALLOW_ENTERPRISE_BUNDLE, false) &&
4588         !OHOS::system::GetBoolParameter(ServiceConstants::IS_ENTERPRISE_DEVICE, false) &&
4589         !OHOS::system::GetBoolParameter(ServiceConstants::DEVELOPERMODE_STATE, false)) {
4590         LOG_E(BMS_TAG_INSTALLER, "not enterprise device or developer mode is off");
4591         return ERR_APPEXECFWK_INSTALL_ENTERPRISE_BUNDLE_NOT_ALLOWED;
4592     }
4593     if (!isAppExist) {
4594         LOG_E(BMS_TAG_INSTALLER, "not self update");
4595         return ERR_APPEXECFWK_INSTALL_SELF_UPDATE_BUNDLENAME_NOT_SAME;
4596     }
4597     std::string appDistributionType = oldInfo.GetAppDistributionType();
4598     if (appDistributionType != Constants::APP_DISTRIBUTION_TYPE_ENTERPRISE_MDM) {
4599         LOG_E(BMS_TAG_INSTALLER, "not mdm app");
4600         return ERR_APPEXECFWK_INSTALL_SELF_UPDATE_NOT_MDM;
4601     }
4602     std::string bundleName = oldInfo.GetBundleName();
4603     for (const auto &info : newInfos) {
4604         if (bundleName != info.second.GetBundleName()) {
4605             LOG_E(BMS_TAG_INSTALLER, "bundleName %{public}s not same", info.second.GetBundleName().c_str());
4606             return ERR_APPEXECFWK_INSTALL_SELF_UPDATE_BUNDLENAME_NOT_SAME;
4607         }
4608     }
4609     return ERR_OK;
4610 }
4611 
GetInnerBundleInfoWithDisable(InnerBundleInfo & info,bool & isAppExist)4612 bool BaseBundleInstaller::GetInnerBundleInfoWithDisable(InnerBundleInfo &info, bool &isAppExist)
4613 {
4614     if (!InitDataMgr()) {
4615         return false;
4616     }
4617     isAppExist = dataMgr_->GetInnerBundleInfoWithDisable(bundleName_, info);
4618     return true;
4619 }
4620 
InitTempBundleFromCache(InnerBundleInfo & info,bool & isAppExist,std::string bundleName)4621 bool BaseBundleInstaller::InitTempBundleFromCache(InnerBundleInfo &info, bool &isAppExist, std::string bundleName)
4622 {
4623     if (!InitDataMgr()) {
4624         return false;
4625     }
4626     std::string cacheBundle = bundleName;
4627     if (cacheBundle.empty()) {
4628         cacheBundle = bundleName_;
4629     }
4630     isAppExist = dataMgr_->FetchInnerBundleInfo(cacheBundle, info);
4631     if (isAppExist) {
4632         tempInfo_.SetTempBundleInfo(info);
4633     }
4634     bundleName_ = cacheBundle;
4635     return true;
4636 }
4637 
GetTempBundleInfo(InnerBundleInfo & info) const4638 bool BaseBundleInstaller::GetTempBundleInfo(InnerBundleInfo &info) const
4639 {
4640     return tempInfo_.GetTempBundleInfo(info);
4641 }
4642 
InitDataMgr()4643 bool BaseBundleInstaller::InitDataMgr()
4644 {
4645     if (dataMgr_ == nullptr) {
4646         dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
4647         if (dataMgr_ == nullptr) {
4648             LOG_E(BMS_TAG_INSTALLER, "Get dataMgr shared_ptr nullptr");
4649             return false;
4650         }
4651     }
4652     return true;
4653 }
4654 
CheckVersionCompatibility(const InnerBundleInfo & oldInfo)4655 ErrCode BaseBundleInstaller::CheckVersionCompatibility(const InnerBundleInfo &oldInfo)
4656 {
4657     if (oldInfo.GetEntryInstallationFree()) {
4658         return CheckVersionCompatibilityForHmService(oldInfo);
4659     }
4660     return CheckVersionCompatibilityForApplication(oldInfo);
4661 }
4662 
4663 // In the process of hap updating, the version code of the entry hap which is about to be updated must not less the
4664 // version code of the current entry haps in the device; if no-entry hap in the device, the updating haps should
4665 // have same version code with the current version code; if the no-entry haps is to be updated, which should has the
4666 // same version code with that of the entry hap in the device.
CheckVersionCompatibilityForApplication(const InnerBundleInfo & oldInfo)4667 ErrCode BaseBundleInstaller::CheckVersionCompatibilityForApplication(const InnerBundleInfo &oldInfo)
4668 {
4669     LOG_D(BMS_TAG_INSTALLER, "start to check version compatibility for application");
4670     if (oldInfo.HasEntry()) {
4671         if (isContainEntry_ && versionCode_ < oldInfo.GetVersionCode()) {
4672             LOG_E(BMS_TAG_INSTALLER, "fail to update lower version bundle");
4673             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
4674         }
4675         if (!isContainEntry_ && versionCode_ > oldInfo.GetVersionCode()) {
4676             LOG_E(BMS_TAG_INSTALLER, "version code is not compatible");
4677             return ERR_APPEXECFWK_INSTALL_VERSION_NOT_COMPATIBLE;
4678         }
4679         if (!isContainEntry_ && versionCode_ < oldInfo.GetVersionCode()) {
4680             LOG_E(BMS_TAG_INSTALLER, "version code is not compatible");
4681             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
4682         }
4683     } else {
4684         if (versionCode_ < oldInfo.GetVersionCode()) {
4685             LOG_E(BMS_TAG_INSTALLER, "fail to update lower version bundle");
4686             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
4687         }
4688     }
4689 
4690     if (versionCode_ > oldInfo.GetVersionCode()) {
4691         if (oldInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK) {
4692             LOG_E(BMS_TAG_INSTALLER, "Not alloweded instal appService hap(%{public}s) due to the hsp does not exist",
4693                 oldInfo.GetBundleName().c_str());
4694             return ERR_APP_SERVICE_FWK_INSTALL_TYPE_FAILED;
4695         }
4696         LOG_D(BMS_TAG_INSTALLER, "need to uninstall lower version feature hap");
4697         isFeatureNeedUninstall_ = true;
4698     }
4699     LOG_D(BMS_TAG_INSTALLER, "finish to check version compatibility for application");
4700     return ERR_OK;
4701 }
4702 
CheckVersionCompatibilityForHmService(const InnerBundleInfo & oldInfo)4703 ErrCode BaseBundleInstaller::CheckVersionCompatibilityForHmService(const InnerBundleInfo &oldInfo)
4704 {
4705     LOG_D(BMS_TAG_INSTALLER, "start to check version compatibility for hm service");
4706     if (versionCode_ < oldInfo.GetVersionCode()) {
4707         LOG_E(BMS_TAG_INSTALLER, "fail to update lower version bundle");
4708         return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
4709     }
4710     if (versionCode_ > oldInfo.GetVersionCode()) {
4711         LOG_D(BMS_TAG_INSTALLER, "need to uninstall lower version hap");
4712         isFeatureNeedUninstall_ = true;
4713     }
4714     LOG_D(BMS_TAG_INSTALLER, "finish to check version compatibility for hm service");
4715     return ERR_OK;
4716 }
4717 
UninstallLowerVersionFeature(const std::vector<std::string> & packageVec,bool killProcess)4718 ErrCode BaseBundleInstaller::UninstallLowerVersionFeature(const std::vector<std::string> &packageVec, bool killProcess)
4719 {
4720     LOG_D(BMS_TAG_INSTALLER, "start to uninstall lower version feature hap");
4721     if (!InitDataMgr()) {
4722         return ERR_APPEXECFWK_NULL_PTR;
4723     }
4724     InnerBundleInfo info;
4725     if (!GetTempBundleInfo(info)) {
4726         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
4727     }
4728 
4729     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_START)) {
4730         LOG_E(BMS_TAG_INSTALLER, "uninstall already start");
4731         return ERR_APPEXECFWK_UPDATE_BUNDLE_INSTALL_STATUS_ERROR;
4732     }
4733 
4734     // kill the bundle process during uninstall.
4735     if (killProcess) {
4736         if (!AbilityManagerHelper::UninstallApplicationProcesses(
4737             info.GetApplicationName(), info.GetUid(userId_), true)) {
4738             LOG_W(BMS_TAG_INSTALLER, "can not kill process");
4739         }
4740         InnerBundleUserInfo userInfo;
4741         if (!info.GetInnerBundleUserInfo(userId_, userInfo)) {
4742             LOG_W(BMS_TAG_INSTALLER, "the origin application is not installed at current user");
4743             return ERR_APPEXECFWK_GET_USERINFO_ERROR;
4744         }
4745         for (auto &cloneInfo : userInfo.cloneInfos) {
4746             if (!AbilityManagerHelper::UninstallApplicationProcesses(
4747                 info.GetApplicationName(), cloneInfo.second.uid, true, atoi(cloneInfo.first.c_str()))) {
4748                 LOG_W(BMS_TAG_INSTALLER, "fail to kill clone application");
4749             }
4750         }
4751     }
4752 
4753     std::vector<std::string> moduleVec = info.GetModuleNameVec();
4754     for (const auto &package : moduleVec) {
4755         if (find(packageVec.begin(), packageVec.end(), package) == packageVec.end()) {
4756             LOG_D(BMS_TAG_INSTALLER, "uninstall package %{public}s", package.c_str());
4757             if (!isFeatureNeedUninstall_) {
4758                 ErrCode result = RemoveModuleAndDataDir(info, package, Constants::UNSPECIFIED_USERID, true);
4759                 CHECK_RESULT(result, "remove module dir failed %{public}d");
4760             }
4761 
4762             // remove driver file
4763             std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
4764             driverInstaller->RemoveDriverSoFile(info, info.GetModuleName(package), false);
4765 
4766             if (!dataMgr_->RemoveModuleInfo(bundleName_, package, info, false)) {
4767                 LOG_E(BMS_TAG_INSTALLER, "RemoveModuleInfo failed");
4768                 return ERR_APPEXECFWK_RMV_MODULE_ERROR;
4769             }
4770         }
4771     }
4772     tempInfo_.SetTempBundleInfo(info);
4773     needDeleteQuickFixInfo_ = true;
4774     LOG_D(BMS_TAG_INSTALLER, "finish to uninstall lower version feature hap");
4775     return ERR_OK;
4776 }
4777 
GetConfirmUserId(const int32_t & userId,std::unordered_map<std::string,InnerBundleInfo> & newInfos)4778 int32_t BaseBundleInstaller::GetConfirmUserId(
4779     const int32_t &userId, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
4780 {
4781     bool isSingleton = newInfos.begin()->second.IsSingleton();
4782     bool u1Enabled = newInfos.begin()->second.IsU1Enable();
4783     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "userId is Unspecified, singleton(%{public}d), u1Enabled(%{public}d)",
4784         static_cast<int32_t>(isSingleton), static_cast<int32_t>(u1Enabled));
4785     if (!otaInstall_) {
4786         if (isSingleton) {
4787             return Constants::DEFAULT_USERID;
4788         }
4789         if (u1Enabled) {
4790             return Constants::U1;
4791         }
4792     }
4793     if (userId != Constants::UNSPECIFIED_USERID || newInfos.size() <= 0) {
4794         return userId;
4795     }
4796     int32_t currUserId = sysEventInfo_.callingUid / Constants::BASE_USER_RANGE;
4797     currUserId = currUserId < Constants::START_USERID ? AccountHelper::GetCurrentActiveUserId() : currUserId;
4798     return currUserId;
4799 }
4800 
CheckUserId(const int32_t & userId) const4801 ErrCode BaseBundleInstaller::CheckUserId(const int32_t &userId) const
4802 {
4803     if (userId == Constants::UNSPECIFIED_USERID) {
4804         return ERR_OK;
4805     }
4806 
4807     if (dataMgr_ == nullptr) {
4808         LOG_E(BMS_TAG_INSTALLER, "dataMgr_ is nullptr");
4809         return ERR_APPEXECFWK_NULL_PTR;
4810     }
4811     if (!dataMgr_->HasUserId(userId)) {
4812         LOG_E(BMS_TAG_INSTALLER, "The user %{public}d does not exist when install", userId);
4813         return ERR_APPEXECFWK_USER_NOT_EXIST;
4814     }
4815 
4816     return ERR_OK;
4817 }
4818 
GetUserId(const int32_t & userId) const4819 int32_t BaseBundleInstaller::GetUserId(const int32_t &userId) const
4820 {
4821     if (userId == Constants::UNSPECIFIED_USERID) {
4822         return userId;
4823     }
4824 
4825     if (userId < Constants::DEFAULT_USERID) {
4826         LOG_E(BMS_TAG_INSTALLER, "userId(%{public}d) is invalid", userId);
4827         return Constants::INVALID_USERID;
4828     }
4829 
4830     LOG_D(BMS_TAG_INSTALLER, "BundleInstaller GetUserId, now userId is %{public}d", userId);
4831     return userId;
4832 }
4833 
CreateBundleUserData(InnerBundleInfo & innerBundleInfo)4834 ErrCode BaseBundleInstaller::CreateBundleUserData(InnerBundleInfo &innerBundleInfo)
4835 {
4836     LOG_I(BMS_TAG_INSTALLER, "CreateNewUserData %{public}s userId: %{public}d",
4837         innerBundleInfo.GetBundleName().c_str(), userId_);
4838     if (!innerBundleInfo.HasInnerBundleUserInfo(userId_)) {
4839         return ERR_APPEXECFWK_USER_NOT_EXIST;
4840     }
4841 
4842     ErrCode result = CreateBundleDataDir(innerBundleInfo);
4843     if (result != ERR_OK) {
4844         RemoveBundleDataDir(innerBundleInfo, true);
4845         return result;
4846     }
4847 
4848     int64_t currentTime = BundleUtil::GetCurrentTimeMs();
4849     innerBundleInfo.SetBundleInstallTime(currentTime, userId_);
4850     SetFirstInstallTime(innerBundleInfo.GetBundleName(), currentTime, innerBundleInfo);
4851     InnerBundleUserInfo innerBundleUserInfo;
4852     if (!innerBundleInfo.GetInnerBundleUserInfo(userId_, innerBundleUserInfo)) {
4853         LOG_E(BMS_TAG_INSTALLER, "oldInfo do not have user");
4854         return ERR_APPEXECFWK_USER_NOT_EXIST;
4855     }
4856 
4857 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
4858     OverlayDataMgr::GetInstance()->AddOverlayModuleStates(innerBundleInfo, innerBundleUserInfo);
4859 #endif
4860     innerBundleInfo.AddInnerBundleUserInfo(innerBundleUserInfo);
4861     tempInfo_.SetTempBundleInfo(innerBundleInfo);
4862     return ERR_OK;
4863 }
4864 
UninstallAllSandboxApps(const std::string & bundleName,int32_t userId)4865 ErrCode BaseBundleInstaller::UninstallAllSandboxApps(const std::string &bundleName, int32_t userId)
4866 {
4867     // All sandbox will be uninstalled when the original application is updated or uninstalled
4868     LOG_D(BMS_TAG_INSTALLER, "UninstallAllSandboxApps begin");
4869     if (bundleName.empty()) {
4870         LOG_E(BMS_TAG_INSTALLER, "UninstallAllSandboxApps failed due to empty bundle name");
4871         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
4872     }
4873     auto helper = DelayedSingleton<BundleSandboxAppHelper>::GetInstance();
4874     if (helper == nullptr) {
4875         LOG_E(BMS_TAG_INSTALLER, "UninstallAllSandboxApps failed due to helper nullptr");
4876         return ERR_APPEXECFWK_NULL_PTR;
4877     }
4878     if (helper->UninstallAllSandboxApps(bundleName, userId) != ERR_OK) {
4879         LOG_W(BMS_TAG_INSTALLER, "UninstallAllSandboxApps failed");
4880         return ERR_APPEXECFWK_UNINSTALL_ALL_SANDBOX_BUNDLE_ERROR;
4881     }
4882     LOG_D(BMS_TAG_INSTALLER, "UninstallAllSandboxApps finish");
4883     return ERR_OK;
4884 }
4885 
CheckNativeFileWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)4886 ErrCode BaseBundleInstaller::CheckNativeFileWithOldInfo(
4887     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
4888 {
4889     LOG_D(BMS_TAG_INSTALLER, "CheckNativeFileWithOldInfo begin");
4890     if (HasAllOldModuleUpdate(oldInfo, newInfos)) {
4891         LOG_D(BMS_TAG_INSTALLER, "All installed haps will be updated");
4892         return ERR_OK;
4893     }
4894 
4895     ErrCode result = CheckNativeSoWithOldInfo(oldInfo, newInfos);
4896     if (result != ERR_OK) {
4897         LOG_E(BMS_TAG_INSTALLER, "Check nativeSo with oldInfo failed, result: %{public}d", result);
4898         return result;
4899     }
4900 
4901     result = CheckArkNativeFileWithOldInfo(oldInfo, newInfos);
4902     if (result != ERR_OK) {
4903         LOG_E(BMS_TAG_INSTALLER, "Check arkNativeFile with oldInfo failed, result: %{public}d", result);
4904         return result;
4905     }
4906 
4907     LOG_D(BMS_TAG_INSTALLER, "CheckNativeFileWithOldInfo end");
4908     return ERR_OK;
4909 }
4910 
HasAllOldModuleUpdate(const InnerBundleInfo & oldInfo,const std::unordered_map<std::string,InnerBundleInfo> & newInfos)4911 bool BaseBundleInstaller::HasAllOldModuleUpdate(
4912     const InnerBundleInfo &oldInfo, const std::unordered_map<std::string, InnerBundleInfo> &newInfos)
4913 {
4914     const auto &newInfo = newInfos.begin()->second;
4915     bool allOldModuleUpdate = true;
4916     if (newInfo.GetVersionCode() > oldInfo.GetVersionCode()) {
4917         LOG_D(BMS_TAG_INSTALLER, "All installed haps will be updated");
4918         DeleteOldArkNativeFile(oldInfo);
4919         return allOldModuleUpdate;
4920     }
4921 
4922     std::vector<std::string> installedModules = oldInfo.GetModuleNameVec();
4923     for (const auto &installedModule : installedModules) {
4924         auto updateModule = std::find_if(std::begin(newInfos), std::end(newInfos),
4925             [ &installedModule ] (const auto &item) { return item.second.FindModule(installedModule); });
4926         if (updateModule == newInfos.end()) {
4927             LOG_D(BMS_TAG_INSTALLER, "Some installed haps will not be updated");
4928             allOldModuleUpdate = false;
4929             break;
4930         }
4931     }
4932     return allOldModuleUpdate;
4933 }
4934 
CheckArkNativeFileWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)4935 ErrCode BaseBundleInstaller::CheckArkNativeFileWithOldInfo(
4936     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
4937 {
4938     LOG_D(BMS_TAG_INSTALLER, "CheckArkNativeFileWithOldInfo begin");
4939     std::string oldArkNativeFileAbi = oldInfo.GetArkNativeFileAbi();
4940     if (oldArkNativeFileAbi.empty()) {
4941         LOG_D(BMS_TAG_INSTALLER, "OldInfo no arkNativeFile");
4942         return ERR_OK;
4943     }
4944 
4945     if (newInfos.empty()) {
4946         LOG_D(BMS_TAG_INSTALLER, "newInfos is empty");
4947         return ERR_APPEXECFWK_INSTALL_AN_INCOMPATIBLE;
4948     }
4949 
4950     std::string arkNativeFileAbi = newInfos.begin()->second.GetArkNativeFileAbi();
4951     if (arkNativeFileAbi.empty()) {
4952         LOG_D(BMS_TAG_INSTALLER, "NewInfos no arkNativeFile");
4953         for (auto& item : newInfos) {
4954             item.second.SetArkNativeFileAbi(oldInfo.GetArkNativeFileAbi());
4955             item.second.SetArkNativeFilePath(oldInfo.GetArkNativeFilePath());
4956         }
4957     }
4958 
4959     LOG_D(BMS_TAG_INSTALLER, "CheckArkNativeFileWithOldInfo end");
4960     return ERR_OK;
4961 }
4962 
CheckNativeSoWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)4963 ErrCode BaseBundleInstaller::CheckNativeSoWithOldInfo(
4964     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
4965 {
4966     LOG_D(BMS_TAG_INSTALLER, "CheckNativeSoWithOldInfo begin");
4967     if (oldInfo.GetNativeLibraryPath().empty()) {
4968         LOG_D(BMS_TAG_INSTALLER, "OldInfo does not has so");
4969         return ERR_OK;
4970     }
4971 
4972     const auto &newInfo = newInfos.begin()->second;
4973     bool newInfoHasSo = !newInfo.GetNativeLibraryPath().empty();
4974     //newInfo should be consistent with oldInfo
4975     if (!newInfoHasSo) {
4976         for (auto& item : newInfos) {
4977             item.second.SetNativeLibraryPath(oldInfo.GetNativeLibraryPath());
4978             item.second.SetCpuAbi(oldInfo.GetCpuAbi());
4979         }
4980     }
4981 
4982     LOG_D(BMS_TAG_INSTALLER, "CheckNativeSoWithOldInfo end");
4983     return ERR_OK;
4984 }
4985 
SetOldAppIsEncrypted(const InnerBundleInfo & oldInfo)4986 void BaseBundleInstaller::SetOldAppIsEncrypted(const InnerBundleInfo &oldInfo)
4987 {
4988     if (!isAppExist_) {
4989         return;
4990     }
4991     oldApplicationReservedFlag_ = oldInfo.GetApplicationReservedFlag();
4992 }
4993 
UpdateEncryptedStatus(const InnerBundleInfo & oldInfo)4994 bool BaseBundleInstaller::UpdateEncryptedStatus(const InnerBundleInfo &oldInfo)
4995 {
4996     if (!InitDataMgr()) {
4997         LOG_E(BMS_TAG_INSTALLER, "init failed");
4998         return false;
4999     }
5000     InnerBundleInfo innerBundleInfo;
5001     if (!GetTempBundleInfo(innerBundleInfo)) {
5002         LOG_E(BMS_TAG_INSTALLER, "get failed");
5003         return false;
5004     }
5005     CodeProtectBundleInfo info;
5006     info.bundleName = innerBundleInfo.GetBundleName();
5007     info.versionCode = innerBundleInfo.GetVersionCode();
5008     info.applicationReservedFlag = innerBundleInfo.GetApplicationReservedFlag();
5009     info.uid = innerBundleInfo.GetUid(userId_);
5010     info.appIdentifier = innerBundleInfo.GetAppIdentifier();
5011     std::vector<CodeProtectBundleInfo> infos { info };
5012     bool oldAppEncrypted = oldApplicationReservedFlag_ &
5013         static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION);
5014     bool newAppEncrypted = innerBundleInfo.GetApplicationReservedFlag() &
5015         static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION);
5016     BmsExtensionDataMgr bmsExtensionDataMgr;
5017     if (!isAppExist_ && newAppEncrypted) {
5018         // add a new encrypted app, need to add operation
5019         auto res = bmsExtensionDataMgr.KeyOperation(infos, CodeOperation::ADD);
5020         ProcessEncryptedKeyExisted(res, CodeOperation::ADD, infos);
5021         return res == ERR_OK;
5022     }
5023     if (isAppExist_ && oldAppEncrypted && !newAppEncrypted) {
5024         // new app is not a encrypted app, need to delete operation on main app & all clone app
5025         infos[0].versionCode = oldInfo.GetVersionCode();
5026         auto res = bmsExtensionDataMgr.KeyOperation(infos, CodeOperation::DELETE);
5027         ProcessEncryptedKeyExisted(res, CodeOperation::DELETE, infos);
5028         return res == ERR_OK;
5029     }
5030     if (isAppExist_ && newAppEncrypted) {
5031         // update a new encrypted app, need to update operation
5032         auto res = bmsExtensionDataMgr.KeyOperation(infos, CodeOperation::UPDATE);
5033         ProcessEncryptedKeyExisted(res, CodeOperation::UPDATE, infos);
5034         return res == ERR_OK;
5035     }
5036     return true;
5037 }
5038 
ProcessEncryptedKeyExisted(int32_t res,uint32_t type,const std::vector<CodeProtectBundleInfo> & infos)5039 void BaseBundleInstaller::ProcessEncryptedKeyExisted(int32_t res, uint32_t type,
5040     const std::vector<CodeProtectBundleInfo> &infos)
5041 {
5042     if (infos.empty()) {
5043         LOG_E(BMS_TAG_INSTALLER, "init failed or infos is empty");
5044         return;
5045     }
5046     std::string bundleName = infos.begin()->bundleName;
5047     if (type == CodeOperation::ADD) {
5048         if (res == ERR_OK) {
5049             UpdateAppEncryptedStatus(bundleName, true, 0);
5050         } else {
5051             UpdateAppEncryptedStatus(bundleName, false, 0);
5052         }
5053         return;
5054     } else if (type == CodeOperation::DELETE) {
5055         if (res == ERR_OK) {
5056             UpdateAppEncryptedStatus(bundleName, false, 0);
5057         } else {
5058             UpdateAppEncryptedStatus(bundleName, true, 0);
5059         }
5060         return;
5061     }
5062     // UPDATE
5063     if (res == ERR_OK) {
5064         UpdateAppEncryptedStatus(bundleName, true, 0);
5065         for (const auto &codeProtectBundleInfo : infos) {
5066             UpdateAppEncryptedStatus(bundleName, true, codeProtectBundleInfo.appIndex);
5067         }
5068     } else {
5069         UpdateAppEncryptedStatus(bundleName, false, 0);
5070         for (const auto &codeProtectBundleInfo : infos) {
5071             UpdateAppEncryptedStatus(bundleName, false, codeProtectBundleInfo.appIndex);
5072         }
5073     }
5074 }
5075 
UpdateAppEncryptedStatus(const std::string & bundleName,bool isExisted,int32_t appIndex)5076 ErrCode BaseBundleInstaller::UpdateAppEncryptedStatus(const std::string &bundleName, bool isExisted, int32_t appIndex)
5077 {
5078     InnerBundleInfo info;
5079     tempInfo_.GetTempBundleInfo(info);
5080     auto res = info.UpdateAppEncryptedStatus(bundleName, isExisted, appIndex);
5081     tempInfo_.SetTempBundleInfo(info);
5082     if (res != ERR_OK) {
5083         LOG_E(BMS_TAG_DEFAULT, "UpdateAppEncryptedStatus err %{public}s %{public}d", bundleName.c_str(), res);
5084         return res;
5085     }
5086     return ERR_OK;
5087 }
5088 
DeleteEncryptedStatus(const std::string & bundleName,int32_t uid)5089 bool BaseBundleInstaller::DeleteEncryptedStatus(const std::string &bundleName, int32_t uid)
5090 {
5091     bool oldAppEncrypted = oldApplicationReservedFlag_ &
5092         static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION);
5093     if (!oldAppEncrypted) {
5094         return true;
5095     }
5096     CodeProtectBundleInfo info;
5097     info.bundleName = bundleName;
5098     info.applicationReservedFlag = oldApplicationReservedFlag_;
5099     info.versionCode = versionCode_;
5100     info.uid = uid;
5101     info.appIdentifier = appIdentifier_;
5102     std::vector<CodeProtectBundleInfo> infos { info };
5103     BmsExtensionDataMgr bmsExtensionDataMgr;
5104     return bmsExtensionDataMgr.KeyOperation(infos, CodeOperation::DELETE) == ERR_OK;
5105 }
5106 
CheckAppLabel(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const5107 ErrCode BaseBundleInstaller::CheckAppLabel(const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
5108 {
5109     // check app label for inheritance installation
5110     LOG_D(BMS_TAG_INSTALLER, "CheckAppLabel begin");
5111     if (!CheckReleaseTypeIsCompatible(oldInfo, newInfo)) {
5112         return ERR_APPEXECFWK_INSTALL_RELEASETYPE_NOT_SAME;
5113     }
5114     if (oldInfo.GetAppProvisionType() != newInfo.GetAppProvisionType()) {
5115         return ERR_APPEXECFWK_INSTALL_APP_PROVISION_TYPE_NOT_SAME;
5116     }
5117     if (oldInfo.GetAppFeature() != newInfo.GetAppFeature()) {
5118         return ERR_APPEXECFWK_INSTALL_APPTYPE_NOT_SAME;
5119     }
5120     if (oldInfo.GetIsNewVersion() != newInfo.GetIsNewVersion()) {
5121         LOG_E(BMS_TAG_INSTALLER, "same version update module condition, model type must be the same");
5122         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
5123     }
5124 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
5125     if (oldInfo.GetTargetBundleName() != newInfo.GetTargetBundleName()) {
5126         return ERR_BUNDLEMANAGER_OVERLAY_INSTALLATION_FAILED_TARGET_BUNDLE_NAME_NOT_SAME;
5127     }
5128     if (oldInfo.GetTargetPriority() != newInfo.GetTargetPriority()) {
5129         return ERR_BUNDLEMANAGER_OVERLAY_INSTALLATION_FAILED_TARGET_PRIORITY_NOT_SAME;
5130     }
5131 #endif
5132     if (oldInfo.GetApplicationBundleType() != newInfo.GetApplicationBundleType()) {
5133         return ERR_APPEXECFWK_BUNDLE_TYPE_NOT_SAME;
5134     }
5135 
5136     LOG_D(BMS_TAG_INSTALLER, "CheckAppLabel end");
5137     return ERR_OK;
5138 }
5139 
CheckReleaseTypeIsCompatible(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const5140 bool BaseBundleInstaller::CheckReleaseTypeIsCompatible(
5141     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
5142 {
5143     if (oldInfo.GetReleaseType() != newInfo.GetReleaseType()) {
5144         LOG_W(BMS_TAG_INSTALLER, "the releaseType not same: [%{public}s, %{public}s] vs [%{public}s, %{public}s]",
5145             oldInfo.GetCurModuleName().c_str(), oldInfo.GetReleaseType().c_str(),
5146             newInfo.GetCurModuleName().c_str(), newInfo.GetReleaseType().c_str());
5147     }
5148     return true;
5149 }
5150 
RemoveBundleUserData(InnerBundleInfo & innerBundleInfo,bool isKeepData,const bool async)5151 ErrCode BaseBundleInstaller::RemoveBundleUserData(
5152     InnerBundleInfo &innerBundleInfo, bool isKeepData, const bool async)
5153 {
5154     auto bundleName = innerBundleInfo.GetBundleName();
5155     LOG_D(BMS_TAG_INSTALLER, "remove user(%{public}d) in bundle(%{public}s)", userId_, bundleName.c_str());
5156     if (!InitDataMgr()) {
5157         return ERR_APPEXECFWK_NULL_PTR;
5158     }
5159     if (!innerBundleInfo.HasInnerBundleUserInfo(userId_)) {
5160         return ERR_APPEXECFWK_USER_NOT_EXIST;
5161     }
5162 
5163     // delete accessTokenId
5164     accessTokenId_ = innerBundleInfo.GetAccessTokenId(userId_);
5165     if (!isKeepData) {
5166         if (BundlePermissionMgr::DeleteAccessTokenId(accessTokenId_) !=
5167             AccessToken::AccessTokenKitRet::RET_SUCCESS) {
5168             LOG_E(BMS_TAG_INSTALLER, "delete accessToken failed");
5169         }
5170     }
5171     if (innerBundleInfo.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE) {
5172         int32_t uid = innerBundleInfo.GetUid(userId_);
5173         if (uid != Constants::INVALID_UID) {
5174             LOG_I(BMS_TAG_INSTALLER, "uninstall atomic service need delete quota, bundleName:%{public}s",
5175                 innerBundleInfo.GetBundleName().c_str());
5176             std::string bundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1] +
5177                 ServiceConstants::PATH_SEPARATOR + std::to_string(userId_) + ServiceConstants::BASE +
5178                 innerBundleInfo.GetBundleName();
5179             PrepareBundleDirQuota(innerBundleInfo.GetBundleName(), uid, bundleDataDir, 0);
5180         }
5181     }
5182 
5183     innerBundleInfo.RemoveInnerBundleUserInfo(userId_);
5184     if (!dataMgr_->RemoveInnerBundleUserInfo(bundleName, userId_)) {
5185         LOG_E(BMS_TAG_INSTALLER, "update bundle user info to db failed %{public}s when remove user",
5186             bundleName.c_str());
5187         return ERR_APPEXECFWK_RMV_USERINFO_ERROR;
5188     }
5189 
5190     ErrCode result = ERR_OK;
5191     if (!isKeepData) {
5192         result = RemoveBundleDataDir(innerBundleInfo, false, async);
5193         if (result != ERR_OK) {
5194             LOG_E(BMS_TAG_INSTALLER, "remove user data directory failed");
5195             return result;
5196         }
5197     }
5198 
5199     result = DeleteArkProfile(bundleName, userId_);
5200     if (result != ERR_OK) {
5201         LOG_E(BMS_TAG_INSTALLER, "fail to removeArkProfile, error is %{public}d", result);
5202         return result;
5203     }
5204 
5205     if ((result = CleanAsanDirectory(innerBundleInfo)) != ERR_OK) {
5206         LOG_E(BMS_TAG_INSTALLER, "fail to remove asan log path, error is %{public}d", result);
5207         return result;
5208     }
5209 
5210     if (dataMgr_->DeleteDesktopShortcutInfo(bundleName, userId_, 0) != ERR_OK) {
5211         LOG_W(BMS_TAG_INSTALLER, "fail to delete shortcut info");
5212     }
5213 
5214     return ERR_OK;
5215 }
5216 
CheckInstallationFree(const InnerBundleInfo & innerBundleInfo,const std::unordered_map<std::string,InnerBundleInfo> & infos) const5217 ErrCode BaseBundleInstaller::CheckInstallationFree(const InnerBundleInfo &innerBundleInfo,
5218     const std::unordered_map<std::string, InnerBundleInfo> &infos) const
5219 {
5220     for (const auto &item : infos) {
5221         if (innerBundleInfo.GetEntryInstallationFree() != item.second.GetEntryInstallationFree()) {
5222             LOG_E(BMS_TAG_INSTALLER, "CheckInstallationFree cannot install application and hm service simultaneously");
5223             return ERR_APPEXECFWK_INSTALL_TYPE_ERROR;
5224         }
5225     }
5226     return ERR_OK;
5227 }
5228 
SaveHapPathToRecords(bool isPreInstallApp,const std::unordered_map<std::string,InnerBundleInfo> & infos)5229 void BaseBundleInstaller::SaveHapPathToRecords(
5230     bool isPreInstallApp, const std::unordered_map<std::string, InnerBundleInfo> &infos)
5231 {
5232     if (isPreInstallApp) {
5233         LOG_D(BMS_TAG_INSTALLER, "PreInstallApp do not need to save hap path to record");
5234         return;
5235     }
5236 
5237     for (const auto &item : infos) {
5238         auto hapPathIter = hapPathRecords_.find(item.first);
5239         if (hapPathIter == hapPathRecords_.end()) {
5240             std::string tempDir = GetTempHapPath(item.second);
5241             if (tempDir.empty()) {
5242                 LOG_W(BMS_TAG_INSTALLER, "get temp hap path failed");
5243                 continue;
5244             }
5245             LOG_D(BMS_TAG_INSTALLER, "tempDir is %{public}s", tempDir.c_str());
5246             hapPathRecords_.emplace(item.first, tempDir);
5247         }
5248 
5249         std::string signatureFileDir = "";
5250         FindSignatureFileDir(item.second.GetCurModuleName(), signatureFileDir);
5251         auto signatureFileIter = signatureFileMap_.find(item.first);
5252         if (signatureFileIter == signatureFileMap_.end()) {
5253             signatureFileMap_.emplace(item.first, signatureFileDir);
5254         }
5255     }
5256 }
5257 
SaveHapToInstallPath(const std::unordered_map<std::string,InnerBundleInfo> & infos,const InnerBundleInfo & oldInfo)5258 ErrCode BaseBundleInstaller::SaveHapToInstallPath(const std::unordered_map<std::string, InnerBundleInfo> &infos,
5259     const InnerBundleInfo &oldInfo)
5260 {
5261     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
5262     // size of code signature files should be same with the size of hap and hsp
5263     if (!signatureFileMap_.empty() && (signatureFileMap_.size() != hapPathRecords_.size())) {
5264         LOG_E(BMS_TAG_INSTALLER, "code signature file size not same with the size of hap and hsp");
5265         return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FILE_IS_INVALID;
5266     }
5267     // 1. copy hsp or hap file to temp installation dir
5268     ErrCode result = ERR_OK;
5269     LOG_I(BMS_TAG_INSTALLER, "codesign start");
5270     for (const auto &hapPathRecord : hapPathRecords_) {
5271         LOG_D(BMS_TAG_INSTALLER, "Save from %{public}s to %{public}s",
5272             hapPathRecord.first.c_str(), hapPathRecord.second.c_str());
5273         if ((signatureFileMap_.find(hapPathRecord.first) != signatureFileMap_.end()) &&
5274             (!signatureFileMap_.at(hapPathRecord.first).empty())) {
5275             result = InstalldClient::GetInstance()->CopyFile(hapPathRecord.first, hapPathRecord.second,
5276                 signatureFileMap_.at(hapPathRecord.first));
5277             CHECK_RESULT(result, "Copy hap to install path failed or code signature hap failed %{public}d");
5278         } else {
5279             if (InstalldClient::GetInstance()->MoveHapToCodeDir(
5280                 hapPathRecord.first, hapPathRecord.second) != ERR_OK) {
5281                 LOG_E(BMS_TAG_INSTALLER, "Move hap to install path failed");
5282                 return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
5283             }
5284             result = VerifyCodeSignatureForHap(infos, hapPathRecord.first, hapPathRecord.second);
5285             if (result != ERR_OK) {
5286                 LOG_E(BMS_TAG_INSTALLER, "enable code signature failed: %{public}d", result);
5287                 return result;
5288             }
5289         }
5290     }
5291     LOG_I(BMS_TAG_INSTALLER, "codesign end");
5292 
5293     // 2. check encryption of hap
5294     if ((result = CheckHapEncryption(infos, oldInfo)) != ERR_OK) {
5295         LOG_E(BMS_TAG_INSTALLER, "check encryption of hap failed %{public}d", result);
5296         return result;
5297     }
5298 
5299     // move file from temp dir to real installation dir, see FinalProcessHapAndSoForBundleUpdate
5300     return ERR_OK;
5301 }
5302 
ResetInstallProperties()5303 void BaseBundleInstaller::ResetInstallProperties()
5304 {
5305     bundleInstallChecker_->ResetProperties();
5306     isContainEntry_ = false;
5307     isAppExist_ = false;
5308     hasInstalledInUser_ = false;
5309     isFeatureNeedUninstall_ = false;
5310     versionCode_ = 0;
5311     uninstallModuleVec_.clear();
5312     installedModules_.clear();
5313     state_ = InstallerState::INSTALL_START;
5314     singletonState_ = SingletonState::DEFAULT;
5315     accessTokenId_ = 0;
5316     sysEventInfo_.Reset();
5317     moduleName_.clear();
5318     verifyCodeParams_.clear();
5319     pgoParams_.clear();
5320     otaInstall_ = false;
5321     signatureFileMap_.clear();
5322     hapPathRecords_.clear();
5323     uninstallBundleAppId_.clear();
5324     isModuleUpdate_ = false;
5325     isEntryInstalled_ = false;
5326     entryModuleName_.clear();
5327     isEnterpriseBundle_ = false;
5328     isInternaltestingBundle_ = false;
5329     appIdentifier_.clear();
5330     targetSoPathMap_.clear();
5331     isAppService_ = false;
5332     oldApplicationReservedFlag_ = 0;
5333     newExtensionDirs_.clear();
5334     createExtensionDirs_.clear();
5335     removeExtensionDirs_.clear();
5336     existBeforeKeepDataApp_ = false;
5337     needSetDisposeRule_ = false;
5338     needDeleteAppTempPath_ = false;
5339     isPreBundleRecovered_ = false;
5340     callerToken_ = 0;
5341     isBundleExist_ = false;
5342     isBundleCrossAppSharedConfig_ = false;
5343 }
5344 
OnSingletonChange(bool killProcess)5345 void BaseBundleInstaller::OnSingletonChange(bool killProcess)
5346 {
5347     if (singletonState_ == SingletonState::DEFAULT) {
5348         return;
5349     }
5350     if (!InitDataMgr()) {
5351         return;
5352     }
5353     // need enable bundle when return
5354     ScopeGuard enableGuard([&] {
5355         dataMgr_->EnableBundle(bundleName_);
5356     });
5357 
5358     InnerBundleInfo info;
5359     bool isExist = false;
5360     if (!GetInnerBundleInfoWithDisable(info, isExist) || !isExist) {
5361         LOG_E(BMS_TAG_INSTALLER, "Get innerBundleInfo failed when singleton changed");
5362         return;
5363     }
5364 
5365     InstallParam installParam;
5366     installParam.needSendEvent = false;
5367     installParam.SetForceExecuted(true);
5368     installParam.SetKillProcess(killProcess);
5369     if (singletonState_ == SingletonState::SINGLETON_TO_NON) {
5370         LOG_I(BMS_TAG_INSTALLER, "Bundle changes from singleton app to non singleton app");
5371         installParam.userId = Constants::DEFAULT_USERID;
5372         UninstallBundle(bundleName_, installParam);
5373         return;
5374     }
5375 
5376     if (singletonState_ == SingletonState::NON_TO_SINGLETON) {
5377         LOG_I(BMS_TAG_INSTALLER, "Bundle changes from non singleton app to singleton app");
5378         for (const auto &infoItem : info.GetInnerBundleUserInfos()) {
5379             int32_t installedUserId = infoItem.second.bundleUserInfo.userId;
5380             if (installedUserId == Constants::DEFAULT_USERID) {
5381                 continue;
5382             }
5383 
5384             installParam.userId = installedUserId;
5385             UninstallBundle(bundleName_, installParam);
5386         }
5387     }
5388 }
5389 
RestoreHaps(const std::vector<std::string> & bundlePaths,const InstallParam & installParam)5390 void BaseBundleInstaller::RestoreHaps(const std::vector<std::string> &bundlePaths, const InstallParam &installParam)
5391 {
5392     if (!installParam.IsRenameInstall() || bundlePaths_.empty() || bundlePaths.empty()) {
5393         LOG_I(BMS_TAG_INSTALLER, "No need to restore haps");
5394         return;
5395     }
5396     const std::string newPrefix = std::string(ServiceConstants::BUNDLE_MANAGER_SERVICE_PATH) +
5397         ServiceConstants::GALLERY_DOWNLOAD_PATH + std::to_string(userId_) + ServiceConstants::PATH_SEPARATOR;
5398     std::string targetDir = bundlePaths.front().substr(0, bundlePaths.front().find_last_of('/') + 1);
5399     if (bundlePaths.front().find(APP_INSTALL_SANDBOX_PATH) == 0) {
5400         targetDir = newPrefix + targetDir.substr(std::strlen(APP_INSTALL_SANDBOX_PATH));
5401     } else {
5402         LOG_W(BMS_TAG_INSTALLER, "Invalid bundle path: %{public}s", bundlePaths.front().c_str());
5403         return;
5404     }
5405 
5406     for (const auto &originPath : bundlePaths_) {
5407         std::string targetPath = targetDir + originPath.substr(originPath.find_last_of('/') + 1);
5408         LOG_I(BMS_TAG_INSTALLER, "Restore hap: %{public}s -> %{public}s", originPath.c_str(), targetPath.c_str());
5409         if (!BundleUtil::RenameFile(originPath, targetPath)) {
5410             LOG_W(BMS_TAG_INSTALLER, "failed: %{public}s -> %{public}s", originPath.c_str(), targetPath.c_str());
5411         }
5412     }
5413 }
5414 
SendBundleSystemEvent(const std::string & bundleName,BundleEventType bundleEventType,const InstallParam & installParam,InstallScene preBundleScene,ErrCode errCode)5415 void BaseBundleInstaller::SendBundleSystemEvent(const std::string &bundleName, BundleEventType bundleEventType,
5416     const InstallParam &installParam, InstallScene preBundleScene, ErrCode errCode)
5417 {
5418     if (std::find(Constants::EXPECTED_ERROR.begin(), Constants::EXPECTED_ERROR.end(), errCode) !=
5419         Constants::EXPECTED_ERROR.end()) {
5420         APP_LOGD("No need report for -e:%{public}d", errCode);
5421         return;
5422     }
5423     sysEventInfo_.bundleName = bundleName;
5424     sysEventInfo_.isPreInstallApp = installParam.isPreInstallApp;
5425     sysEventInfo_.errCode = errCode;
5426     sysEventInfo_.isFreeInstallMode = (installParam.installFlag == InstallFlag::FREE_INSTALL);
5427     sysEventInfo_.userId = userId_;
5428     sysEventInfo_.versionCode = versionCode_;
5429     sysEventInfo_.preBundleScene = preBundleScene;
5430     sysEventInfo_.isPatch = installParam.isPatch;
5431     GetCallingEventInfo(sysEventInfo_);
5432     EventReport::SendBundleSystemEvent(bundleEventType, sysEventInfo_);
5433 }
5434 
GetCallingEventInfo(EventInfo & eventInfo)5435 void BaseBundleInstaller::GetCallingEventInfo(EventInfo &eventInfo)
5436 {
5437     LOG_D(BMS_TAG_INSTALLER, "GetCallingEventInfo start, bundleName:%{public}s", eventInfo.callingBundleName.c_str());
5438     if (!InitDataMgr()) {
5439         LOG_E(BMS_TAG_INSTALLER, "Get dataMgr shared_ptr nullptr");
5440         return;
5441     }
5442     if (!dataMgr_->GetBundleNameForUid(eventInfo.callingUid, eventInfo.callingBundleName)) {
5443         LOG_W(BMS_TAG_INSTALLER, "CallingUid %{public}d is not hap, no bundleName", eventInfo.callingUid);
5444         eventInfo.callingBundleName = Constants::EMPTY_STRING;
5445         return;
5446     }
5447     BundleInfo bundleInfo;
5448     if (!dataMgr_->GetBundleInfo(eventInfo.callingBundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo,
5449         eventInfo.callingUid / Constants::BASE_USER_RANGE)) {
5450         LOG_E(BMS_TAG_INSTALLER, "GetBundleInfo failed, bundleName: %{public}s", eventInfo.callingBundleName.c_str());
5451         return;
5452     }
5453     eventInfo.callingAppId = bundleInfo.appId;
5454 }
5455 
GetInstallEventInfo(EventInfo & eventInfo)5456 void BaseBundleInstaller::GetInstallEventInfo(EventInfo &eventInfo)
5457 {
5458     LOG_D(BMS_TAG_INSTALLER, "GetInstallEventInfo start, bundleName:%{public}s", bundleName_.c_str());
5459     if (!InitDataMgr()) {
5460         LOG_E(BMS_TAG_INSTALLER, "Get dataMgr shared_ptr nullptr");
5461         return;
5462     }
5463     InnerBundleInfo info;
5464     if (!dataMgr_->FetchInnerBundleInfo(bundleName_, info)) {
5465         LOG_E(BMS_TAG_INSTALLER, "Get innerBundleInfo failed, bundleName: %{public}s", bundleName_.c_str());
5466         return;
5467     }
5468     GetInstallEventInfo(info, eventInfo);
5469 }
5470 
GetInstallEventInfo(const InnerBundleInfo & bundleInfo,EventInfo & eventInfo)5471 void BaseBundleInstaller::GetInstallEventInfo(const InnerBundleInfo &bundleInfo, EventInfo &eventInfo)
5472 {
5473     LOG_D(BMS_TAG_INSTALLER, "GetInstallEventInfo start, bundleName:%{public}s", bundleInfo.GetBundleName().c_str());
5474     eventInfo.fingerprint = bundleInfo.GetCertificateFingerprint();
5475     eventInfo.appDistributionType = bundleInfo.GetAppDistributionType();
5476     eventInfo.hideDesktopIcon = bundleInfo.IsHideDesktopIcon();
5477     eventInfo.timeStamp = bundleInfo.GetBundleUpdateTime(userId_);
5478     // report hapPath and hashValue
5479     for (const auto &innerModuleInfo : bundleInfo.GetInnerModuleInfos()) {
5480         eventInfo.filePath.push_back(innerModuleInfo.second.hapPath);
5481         eventInfo.hashValue.push_back(innerModuleInfo.second.hashValue);
5482     }
5483 }
5484 
SetCallingUid(int32_t callingUid)5485 void BaseBundleInstaller::SetCallingUid(int32_t callingUid)
5486 {
5487     sysEventInfo_.callingUid = callingUid;
5488 }
5489 
SetCallingTokenId(const Security::AccessToken::AccessTokenID callerToken)5490 void BaseBundleInstaller::SetCallingTokenId(const Security::AccessToken::AccessTokenID callerToken)
5491 {
5492     callerToken_ = callerToken;
5493 }
5494 
NotifyBundleStatus(const NotifyBundleEvents & installRes)5495 void BaseBundleInstaller::NotifyBundleStatus(const NotifyBundleEvents &installRes)
5496 {
5497     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
5498     commonEventMgr->NotifyBundleStatus(installRes, dataMgr_);
5499 }
5500 
AddBundleStatus(const NotifyBundleEvents & installRes)5501 void BaseBundleInstaller::AddBundleStatus(const NotifyBundleEvents &installRes)
5502 {
5503     bundleEvents_.emplace_back(installRes);
5504 }
5505 
NotifyAllBundleStatus()5506 bool BaseBundleInstaller::NotifyAllBundleStatus()
5507 {
5508     if (bundleEvents_.empty()) {
5509         LOG_E(BMS_TAG_INSTALLER, "bundleEvents is empty");
5510         return false;
5511     }
5512 
5513     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
5514     if (!dataMgr) {
5515         LOG_E(BMS_TAG_INSTALLER, "Get dataMgr shared_ptr nullptr");
5516         return false;
5517     }
5518 
5519     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
5520     for (const auto &bundleEvent : bundleEvents_) {
5521         commonEventMgr->NotifyBundleStatus(bundleEvent, dataMgr);
5522     }
5523     return true;
5524 }
5525 
AddNotifyBundleEvents(const NotifyBundleEvents & notifyBundleEvents)5526 void BaseBundleInstaller::AddNotifyBundleEvents(const NotifyBundleEvents &notifyBundleEvents)
5527 {
5528     auto userMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleUserMgr();
5529     if (userMgr == nullptr) {
5530         LOG_E(BMS_TAG_INSTALLER, "userMgr is null");
5531         return;
5532     }
5533 
5534     userMgr->AddNotifyBundleEvents(notifyBundleEvents);
5535 }
5536 
CheckOverlayInstallation(std::unordered_map<std::string,InnerBundleInfo> & newInfos,int32_t userId)5537 ErrCode BaseBundleInstaller::CheckOverlayInstallation(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
5538     int32_t userId)
5539 {
5540 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
5541     std::shared_ptr<BundleOverlayInstallChecker> overlayChecker = std::make_shared<BundleOverlayInstallChecker>();
5542     return overlayChecker->CheckOverlayInstallation(newInfos, userId, overlayType_);
5543 #else
5544     LOG_D(BMS_TAG_INSTALLER, "overlay is not supported");
5545     return ERR_OK;
5546 #endif
5547 }
5548 
CheckOverlayUpdate(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo,int32_t userId) const5549 ErrCode BaseBundleInstaller::CheckOverlayUpdate(const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo,
5550     int32_t userId) const
5551 {
5552 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
5553     std::shared_ptr<BundleOverlayInstallChecker> overlayChecker = std::make_shared<BundleOverlayInstallChecker>();
5554     return overlayChecker->CheckOverlayUpdate(oldInfo, newInfo, userId);
5555 #else
5556     LOG_D(BMS_TAG_INSTALLER, "overlay is not supported");
5557     return ERR_OK;
5558 #endif
5559 }
5560 
GetNotifyType()5561 NotifyType BaseBundleInstaller::GetNotifyType()
5562 {
5563     if (isAppExist_ && hasInstalledInUser_) {
5564         if (overlayType_ != NON_OVERLAY_TYPE) {
5565             return NotifyType::OVERLAY_UPDATE;
5566         }
5567         return NotifyType::UPDATE;
5568     }
5569 
5570     if (overlayType_ != NON_OVERLAY_TYPE) {
5571         return NotifyType::OVERLAY_INSTALL;
5572     }
5573     return NotifyType::INSTALL;
5574 }
5575 
CheckArkProfileDir(const InnerBundleInfo & newInfo,const InnerBundleInfo & oldInfo) const5576 ErrCode BaseBundleInstaller::CheckArkProfileDir(const InnerBundleInfo &newInfo, const InnerBundleInfo &oldInfo) const
5577 {
5578     if (newInfo.GetVersionCode() > oldInfo.GetVersionCode()) {
5579         const auto userInfos = oldInfo.GetInnerBundleUserInfos();
5580         for (auto iter = userInfos.begin(); iter != userInfos.end(); iter++) {
5581             int32_t userId = iter->second.bundleUserInfo.userId;
5582             int32_t gid = (newInfo.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG) ?
5583                 GetIntParameter(BMS_KEY_SHELL_UID, ServiceConstants::SHELL_UID) :
5584                 oldInfo.GetUid(userId);
5585             ErrCode result = newInfo.GetIsNewVersion() ?
5586                 CreateArkProfile(bundleName_, userId, oldInfo.GetUid(userId), gid) :
5587                 DeleteArkProfile(bundleName_, userId);
5588             if (result != ERR_OK) {
5589                 LOG_E(BMS_TAG_INSTALLER, "bundleName: %{public}s CheckArkProfileDir failed, result:%{public}d",
5590                     bundleName_.c_str(), result);
5591                 return result;
5592             }
5593         }
5594     }
5595     return ERR_OK;
5596 }
5597 
ProcessAsanDirectory(InnerBundleInfo & info) const5598 ErrCode BaseBundleInstaller::ProcessAsanDirectory(InnerBundleInfo &info) const
5599 {
5600     if (dataMgr_ == nullptr) {
5601         LOG_E(BMS_TAG_INSTALLER, "dataMgr_ is nullptr");
5602         return ERR_APPEXECFWK_NULL_PTR;
5603     }
5604     const std::string bundleName = info.GetBundleName();
5605     const std::string asanLogDir = std::string(ServiceConstants::BUNDLE_ASAN_LOG_DIR) + ServiceConstants::PATH_SEPARATOR
5606         + std::to_string(userId_) + ServiceConstants::PATH_SEPARATOR + bundleName
5607         + ServiceConstants::PATH_SEPARATOR + LOG;
5608     bool dirExist = false;
5609     ErrCode errCode = InstalldClient::GetInstance()->IsExistDir(asanLogDir, dirExist);
5610     if (errCode != ERR_OK) {
5611         LOG_E(BMS_TAG_INSTALLER, "check asan log directory failed");
5612         return errCode;
5613     }
5614     bool asanEnabled = info.GetAsanEnabled();
5615     // create asan log directory if asanEnabled is true
5616     if (asanEnabled) {
5617         InnerBundleUserInfo newInnerBundleUserInfo;
5618         if (!info.GetInnerBundleUserInfo(userId_, newInnerBundleUserInfo)) {
5619             LOG_E(BMS_TAG_INSTALLER, "bundle(%{public}s) get user(%{public}d) failed",
5620                 info.GetBundleName().c_str(), userId_);
5621             return ERR_APPEXECFWK_USER_NOT_EXIST;
5622         }
5623 
5624         if (!dataMgr_->GenerateUidAndGid(newInnerBundleUserInfo)) {
5625             LOG_E(BMS_TAG_INSTALLER, "fail to gererate uid and gid");
5626             return ERR_APPEXECFWK_INSTALL_GENERATE_UID_ERROR;
5627         }
5628         BundleUtil::MakeFsConfig(info.GetBundleName(), ServiceConstants::HMDFS_CONFIG_PATH, info.GetAppProvisionType(),
5629             Constants::APP_PROVISION_TYPE_FILE_NAME);
5630         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
5631         if ((errCode = InstalldClient::GetInstance()->Mkdir(asanLogDir, mode,
5632             newInnerBundleUserInfo.uid, newInnerBundleUserInfo.uid)) != ERR_OK) {
5633             LOG_E(BMS_TAG_INSTALLER, "create asan log directory failed");
5634             return errCode;
5635         }
5636     }
5637     if (asanEnabled) {
5638         info.SetAsanLogPath(LOG);
5639     }
5640     // clean asan directory
5641     if (dirExist && !asanEnabled) {
5642         if ((errCode = CleanAsanDirectory(info)) != ERR_OK) {
5643             LOG_E(BMS_TAG_INSTALLER, "clean asan log directory failed");
5644             return errCode;
5645         }
5646     }
5647     return ERR_OK;
5648 }
5649 
CleanAsanDirectory(InnerBundleInfo & info) const5650 ErrCode BaseBundleInstaller::CleanAsanDirectory(InnerBundleInfo &info) const
5651 {
5652     const std::string bundleName = info.GetBundleName();
5653     const std::string asanLogDir = std::string(ServiceConstants::BUNDLE_ASAN_LOG_DIR) + ServiceConstants::PATH_SEPARATOR
5654         + std::to_string(userId_) + ServiceConstants::PATH_SEPARATOR + bundleName;
5655     ErrCode errCode =  InstalldClient::GetInstance()->RemoveDir(asanLogDir);
5656     if (errCode != ERR_OK) {
5657         LOG_E(BMS_TAG_INSTALLER, "clean asan log path failed");
5658         return errCode;
5659     }
5660     info.SetAsanLogPath("");
5661     return errCode;
5662 }
5663 
AddAppProvisionInfo(const std::string & bundleName,const Security::Verify::ProvisionInfo & provisionInfo,const InstallParam & installParam) const5664 void BaseBundleInstaller::AddAppProvisionInfo(const std::string &bundleName,
5665     const Security::Verify::ProvisionInfo &provisionInfo,
5666     const InstallParam &installParam) const
5667 {
5668     AppProvisionInfo appProvisionInfo = bundleInstallChecker_->ConvertToAppProvisionInfo(provisionInfo);
5669     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->AddAppProvisionInfo(
5670         bundleName, appProvisionInfo)) {
5671         LOG_W(BMS_TAG_INSTALLER, "bundleName: %{public}s add appProvisionInfo failed", bundleName.c_str());
5672     }
5673     if (!installParam.specifiedDistributionType.empty()) {
5674         if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->SetSpecifiedDistributionType(
5675             bundleName, installParam.specifiedDistributionType)) {
5676             LOG_W(BMS_TAG_INSTALLER, "bundleName: %{public}s SetSpecifiedDistributionType failed", bundleName.c_str());
5677         }
5678     }
5679     if (!installParam.additionalInfo.empty()) {
5680         if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->SetAdditionalInfo(
5681             bundleName, installParam.additionalInfo)) {
5682             LOG_W(BMS_TAG_INSTALLER, "bundleName: %{public}s SetAdditionalInfo failed", bundleName.c_str());
5683         }
5684     }
5685 }
5686 
InnerProcessNativeLibs(InnerBundleInfo & info,const std::string & modulePath)5687 ErrCode BaseBundleInstaller::InnerProcessNativeLibs(InnerBundleInfo &info, const std::string &modulePath)
5688 {
5689     std::string targetSoPath;
5690     std::string cpuAbi;
5691     std::string nativeLibraryPath;
5692     bool isCompressNativeLibrary = info.IsCompressNativeLibs(info.GetCurModuleName());
5693     if (info.FetchNativeSoAttrs(modulePackage_, cpuAbi, nativeLibraryPath)) {
5694         if (isCompressNativeLibrary) {
5695             InnerProcessTargetSoPath(info, isFeatureNeedUninstall_, modulePath, nativeLibraryPath, targetSoPath);
5696             // for code signature
5697             targetSoPathMap_.emplace(info.GetCurModuleName(), targetSoPath);
5698         }
5699     }
5700 
5701     LOG_I(BMS_TAG_INSTALLER, "extract module %{public}s targetSo %{public}s abi:%{public}s compress %{public}d",
5702         modulePath.c_str(), targetSoPath.c_str(), cpuAbi.c_str(), isCompressNativeLibrary);
5703     std::string signatureFileDir = "";
5704     auto ret = FindSignatureFileDir(info.GetCurModuleName(), signatureFileDir);
5705     if (ret != ERR_OK) {
5706         return ret;
5707     }
5708     if (isCompressNativeLibrary) {
5709         auto result = ExtractModuleFiles(info, modulePath, targetSoPath, cpuAbi);
5710         CHECK_RESULT(result, "fail to extract module dir, error is %{public}d");
5711         // verify hap or hsp code signature for compressed so files
5712         result = VerifyCodeSignatureForNativeFiles(info, cpuAbi, targetSoPath, signatureFileDir);
5713         CHECK_RESULT(result, "fail to VerifyCodeSignature, error is %{public}d");
5714         // check whether the hap or hsp is encrypted
5715         result = CheckSoEncryption(info, cpuAbi, targetSoPath);
5716         CHECK_RESULT(result, "fail to CheckSoEncryption, error is %{public}d");
5717     } else {
5718         auto result = InstalldClient::GetInstance()->CreateBundleDir(modulePath);
5719         CHECK_RESULT(result, "fail to create temp bundle dir, error is %{public}d");
5720         std::vector<std::string> fileNames;
5721         result = InstalldClient::GetInstance()->GetNativeLibraryFileNames(modulePath_, cpuAbi, fileNames);
5722         CHECK_RESULT(result, "fail to GetNativeLibraryFileNames, error is %{public}d");
5723         info.SetNativeLibraryFileNames(modulePackage_, fileNames);
5724     }
5725     return ERR_OK;
5726 }
5727 
VerifyCodeSignatureForNativeFiles(InnerBundleInfo & info,const std::string & cpuAbi,const std::string & targetSoPath,const std::string & signatureFileDir) const5728 ErrCode BaseBundleInstaller::VerifyCodeSignatureForNativeFiles(InnerBundleInfo &info, const std::string &cpuAbi,
5729     const std::string &targetSoPath, const std::string &signatureFileDir) const
5730 {
5731     if (copyHapToInstallPath_) {
5732         LOG_D(BMS_TAG_INSTALLER, "hap will be copied to install path, verified code signature later");
5733         return ERR_OK;
5734     }
5735     LOG_D(BMS_TAG_INSTALLER, "begin to verify code signature for native files");
5736     const std::string compileSdkType = info.GetBaseApplicationInfo().compileSdkType;
5737     CodeSignatureParam codeSignatureParam;
5738     codeSignatureParam.modulePath = modulePath_;
5739     codeSignatureParam.cpuAbi = cpuAbi;
5740     codeSignatureParam.targetSoPath = targetSoPath;
5741     codeSignatureParam.signatureFileDir = signatureFileDir;
5742     codeSignatureParam.isEnterpriseBundle = isEnterpriseBundle_;
5743     codeSignatureParam.isInternaltestingBundle = isInternaltestingBundle_;
5744     codeSignatureParam.appIdentifier = appIdentifier_;
5745     codeSignatureParam.isPreInstalledBundle = IsDataPreloadHap(modulePath_) ? false : info.IsPreInstallApp();
5746     codeSignatureParam.isCompileSdkOpenHarmony = (compileSdkType == COMPILE_SDK_TYPE_OPEN_HARMONY);
5747     return InstalldClient::GetInstance()->VerifyCodeSignature(codeSignatureParam);
5748 }
5749 
VerifyCodeSignatureForHap(const std::unordered_map<std::string,InnerBundleInfo> & infos,const std::string & srcHapPath,const std::string & realHapPath)5750 ErrCode BaseBundleInstaller::VerifyCodeSignatureForHap(const std::unordered_map<std::string, InnerBundleInfo> &infos,
5751     const std::string &srcHapPath, const std::string &realHapPath)
5752 {
5753     LOG_D(BMS_TAG_INSTALLER, "begin to verify code signature for hap or internal hsp");
5754     auto iter = infos.find(srcHapPath);
5755     if (iter == infos.end()) {
5756         return ERR_OK;
5757     }
5758     const auto &info = iter->second;
5759     std::string moduleName = info.GetCurModuleName();
5760     std::string cpuAbi;
5761     std::string nativeLibraryPath;
5762     info.FetchNativeSoAttrs(info.GetCurrentModulePackage(), cpuAbi, nativeLibraryPath);
5763     const std::string compileSdkType = info.GetBaseApplicationInfo().compileSdkType;
5764     std::string signatureFileDir = "";
5765     auto ret = FindSignatureFileDir(moduleName, signatureFileDir);
5766     if (ret != ERR_OK) {
5767         return ret;
5768     }
5769     auto targetSoPath = targetSoPathMap_.find(moduleName);
5770     CodeSignatureParam codeSignatureParam;
5771     if (targetSoPath != targetSoPathMap_.end()) {
5772         codeSignatureParam.targetSoPath = targetSoPath->second;
5773     }
5774     codeSignatureParam.cpuAbi = cpuAbi;
5775     codeSignatureParam.modulePath = realHapPath;
5776     codeSignatureParam.signatureFileDir = signatureFileDir;
5777     codeSignatureParam.isEnterpriseBundle = isEnterpriseBundle_;
5778     codeSignatureParam.isInternaltestingBundle = isInternaltestingBundle_;
5779     codeSignatureParam.appIdentifier = appIdentifier_;
5780     codeSignatureParam.isCompileSdkOpenHarmony = (compileSdkType == COMPILE_SDK_TYPE_OPEN_HARMONY);
5781     codeSignatureParam.isPreInstalledBundle = IsDataPreloadHap(realHapPath) ? false : info.IsPreInstallApp();
5782     codeSignatureParam.isCompressNativeLibrary = info.IsCompressNativeLibs(info.GetCurModuleName());
5783     return InstalldClient::GetInstance()->VerifyCodeSignatureForHap(codeSignatureParam);
5784 }
5785 
CheckSoEncryption(InnerBundleInfo & info,const std::string & cpuAbi,const std::string & targetSoPath)5786 ErrCode BaseBundleInstaller::CheckSoEncryption(InnerBundleInfo &info, const std::string &cpuAbi,
5787     const std::string &targetSoPath)
5788 {
5789     LOG_D(BMS_TAG_INSTALLER, "begin to check so encryption");
5790     CheckEncryptionParam param;
5791     param.modulePath = modulePath_;
5792     param.cpuAbi = cpuAbi;
5793     param.targetSoPath = targetSoPath;
5794     int uid = info.GetUid(userId_);
5795     param.bundleId = uid - userId_ * Constants::BASE_USER_RANGE;
5796     param.isCompressNativeLibrary = info.IsCompressNativeLibs(info.GetCurModuleName());
5797     param.appIdentifier = info.GetAppIdentifier();
5798     param.versionCode = info.GetVersionCode();
5799     if (info.GetModuleTypeByPackage(modulePackage_) == Profile::MODULE_TYPE_SHARED) {
5800         param.installBundleType = InstallBundleType::INTER_APP_HSP;
5801     }
5802     bool isEncrypted = false;
5803     ErrCode result = InstalldClient::GetInstance()->CheckEncryption(param, isEncrypted);
5804     CHECK_RESULT(result, "fail to CheckSoEncryption, error is %{public}d");
5805     if ((info.GetBaseApplicationInfo().debug || (info.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG))
5806         && isEncrypted) {
5807         LOG_E(BMS_TAG_INSTALLER, "-n %{public}s debug encrypted bundle is not allowed to install",
5808             info.GetBundleName().c_str());
5809         return ERR_APPEXECFWK_INSTALL_DEBUG_ENCRYPTED_BUNDLE_FAILED;
5810     }
5811     if (isEncrypted && sysEventInfo_.callingUid == ServiceConstants::SHELL_UID) {
5812         LOG_E(BMS_TAG_INSTALLER, "-n %{public}s encrypted bundle is not allowed for shell",
5813             info.GetBundleName().c_str());
5814         return ERR_APPEXECFWK_INSTALL_ENCRYPTED_BUNDLE_NOT_ALLOWED_FOR_SHELL;
5815     }
5816     if (isEncrypted) {
5817         LOG_D(BMS_TAG_INSTALLER, "module %{public}s is encrypted", modulePath_.c_str());
5818         info.SetApplicationReservedFlag(static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION));
5819     }
5820     return ERR_OK;
5821 }
5822 
ProcessOldNativeLibraryPath(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,uint32_t oldVersionCode,const std::string & oldNativeLibraryPath) const5823 void BaseBundleInstaller::ProcessOldNativeLibraryPath(const std::unordered_map<std::string, InnerBundleInfo> &newInfos,
5824     uint32_t oldVersionCode, const std::string &oldNativeLibraryPath) const
5825 {
5826     if (isFeatureNeedUninstall_) {
5827         return;
5828     }
5829     if (((oldVersionCode >= versionCode_) && !otaInstall_) || oldNativeLibraryPath.empty()) {
5830         return;
5831     }
5832     for (const auto &item : newInfos) {
5833         const auto &moduleInfos = item.second.GetInnerModuleInfos();
5834         for (const auto &moduleItem: moduleInfos) {
5835             if (moduleItem.second.compressNativeLibs) {
5836                 // no need to delete library path
5837                 return;
5838             }
5839         }
5840     }
5841     std::string oldLibPath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName_ +
5842         ServiceConstants::PATH_SEPARATOR + ServiceConstants::LIBS;
5843     if (InstalldClient::GetInstance()->RemoveDir(oldLibPath) != ERR_OK) {
5844         LOG_W(BMS_TAG_INSTALLER, "bundleNmae: %{public}s remove old libs dir failed", bundleName_.c_str());
5845     }
5846 }
5847 
ProcessAOT(bool isOTA,const std::unordered_map<std::string,InnerBundleInfo> & infos) const5848 void BaseBundleInstaller::ProcessAOT(bool isOTA, const std::unordered_map<std::string, InnerBundleInfo> &infos) const
5849 {
5850     if (isOTA) {
5851         LOG_D(BMS_TAG_INSTALLER, "is OTA, no need to AOT");
5852         return;
5853     }
5854     AOTHandler::GetInstance().HandleInstall(infos);
5855 }
5856 
RemoveOldHapIfOTA(const InstallParam & installParam,const std::unordered_map<std::string,InnerBundleInfo> & newInfos,const InnerBundleInfo & oldInfo)5857 void BaseBundleInstaller::RemoveOldHapIfOTA(const InstallParam &installParam,
5858     const std::unordered_map<std::string, InnerBundleInfo> &newInfos, const InnerBundleInfo &oldInfo)
5859 {
5860     if (!installParam.isOTA || installParam.copyHapToInstallPath) {
5861         return;
5862     }
5863     InnerBundleInfo newInfo;
5864     if (!GetTempBundleInfo(newInfo)) {
5865         LOG_E(BMS_TAG_INSTALLER, "get failed for %{public}s", bundleName_.c_str());
5866         return;
5867     }
5868     for (const auto &info : newInfos) {
5869         std::string oldHapPath = oldInfo.GetModuleHapPath(info.second.GetCurrentModulePackage());
5870         std::string newHapPath = newInfo.GetModuleHapPath(info.second.GetCurrentModulePackage());
5871         if (oldHapPath == newHapPath || oldHapPath.find(Constants::BUNDLE_CODE_DIR) == std::string::npos) {
5872             continue;
5873         }
5874         LOG_W(BMS_TAG_INSTALLER, "remove old hap %{public}s", oldHapPath.c_str());
5875         if (InstalldClient::GetInstance()->RemoveDir(oldHapPath) != ERR_OK) {
5876             LOG_W(BMS_TAG_INSTALLER, "remove old hap failed, errno: %{public}d", errno);
5877         }
5878     }
5879 }
5880 
CopyHapsToSecurityDir(const InstallParam & installParam,std::vector<std::string> & bundlePaths)5881 ErrCode BaseBundleInstaller::CopyHapsToSecurityDir(const InstallParam &installParam,
5882     std::vector<std::string> &bundlePaths)
5883 {
5884     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
5885     if (!installParam.withCopyHaps) {
5886         LOG_D(BMS_TAG_INSTALLER, "no need to copy preInstallApp to secure dir");
5887         return ERR_OK;
5888     }
5889     for (size_t index = 0; index < bundlePaths.size(); ++index) {
5890         if (!BundleUtil::CheckSystemSize(bundlePaths[index], APP_INSTALL_PATH)) {
5891             LOG_E(BMS_TAG_INSTALLER, "install %{private}s failed insufficient disk memory", bundlePaths[index].c_str());
5892             return ERR_APPEXECFWK_INSTALL_DISK_MEM_INSUFFICIENT;
5893         }
5894         auto destination = BundleUtil::CopyFileToSecurityDir(bundlePaths[index], DirType::STREAM_INSTALL_DIR,
5895             toDeleteTempHapPath_, installParam.IsRenameInstall());
5896         if (destination.empty()) {
5897             LOG_E(BMS_TAG_INSTALLER, "copy file %{private}s to security dir failed", bundlePaths[index].c_str());
5898             return ERR_APPEXECFWK_INSTALL_COPY_HAP_FAILED;
5899         }
5900         bundlePaths[index] = destination;
5901     }
5902     bundlePaths_ = bundlePaths;
5903     return ERR_OK;
5904 }
5905 
ParseHapPaths(const InstallParam & installParam,const std::vector<std::string> & inBundlePaths,std::vector<std::string> & parsedPaths)5906 ErrCode BaseBundleInstaller::ParseHapPaths(const InstallParam &installParam,
5907     const std::vector<std::string> &inBundlePaths, std::vector<std::string> &parsedPaths)
5908 {
5909     parsedPaths.reserve(inBundlePaths.size());
5910     if (!installParam.IsRenameInstall()) {
5911         parsedPaths.assign(inBundlePaths.begin(), inBundlePaths.end());
5912         return ERR_OK;
5913     }
5914     LOG_I(BMS_TAG_INSTALLER, "rename install");
5915     int32_t userId = userId_ < Constants::START_USERID ?
5916         sysEventInfo_.callingUid / Constants::BASE_USER_RANGE : userId_;
5917     const std::string newPrefix = std::string(ServiceConstants::BUNDLE_MANAGER_SERVICE_PATH) +
5918         ServiceConstants::GALLERY_DOWNLOAD_PATH + std::to_string(userId) + ServiceConstants::PATH_SEPARATOR;
5919 
5920     for (const auto &bundlePath : inBundlePaths) {
5921         if (bundlePath.find("..") != std::string::npos) {
5922             LOG_E(BMS_TAG_INSTALLER, "path invalid: %{public}s", bundlePath.c_str());
5923             return ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID;
5924         }
5925         if (bundlePath.find(APP_INSTALL_SANDBOX_PATH) == 0) {
5926             std::string newPath = newPrefix + bundlePath.substr(std::strlen(APP_INSTALL_SANDBOX_PATH));
5927             parsedPaths.push_back(newPath);
5928             LOG_D(BMS_TAG_INSTALLER, "parsed path: %{public}s", newPath.c_str());
5929         } else {
5930             LOG_E(BMS_TAG_INSTALLER, "path invalid: %{public}s", bundlePath.c_str());
5931             return ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID;
5932         }
5933     }
5934     if (!parsedPaths.empty()) {
5935         std::filesystem::path hapPath(parsedPaths.front());
5936         std::string bundleNameDir = hapPath.parent_path().string();
5937         FileStat fileStat;
5938         ErrCode res = InstalldClient::GetInstance()->GetFileStat(bundleNameDir, fileStat);
5939         int32_t sharedMode = S_IRWXU | S_IRWXG | S_ISGID;
5940         if (res == ERR_OK && (static_cast<uint32_t>(fileStat.mode) & ServiceConstants::MODE_BASE) != sharedMode) {
5941             LOG_W(BMS_TAG_INSTALLER, "shared dir mode is not correct %{public}d for %{public}s",
5942                 fileStat.mode, bundleNameDir.c_str());
5943             fileStat.mode = sharedMode;
5944             InstalldClient::GetInstance()->ChangeFileStat(bundleNameDir, fileStat);
5945             fileStat.mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
5946             for (const auto &path : parsedPaths) {
5947                 InstalldClient::GetInstance()->ChangeFileStat(path, fileStat);
5948             }
5949         }
5950     }
5951     return ERR_OK;
5952 }
5953 
RenameAllTempDir(const std::unordered_map<std::string,InnerBundleInfo> & newInfos) const5954 ErrCode BaseBundleInstaller::RenameAllTempDir(const std::unordered_map<std::string, InnerBundleInfo> &newInfos) const
5955 {
5956     LOG_D(BMS_TAG_INSTALLER, "begin to rename all temp dir");
5957     ErrCode ret = ERR_OK;
5958     for (const auto &info : newInfos) {
5959         if (info.second.IsOnlyCreateBundleUser()) {
5960             continue;
5961         }
5962         if ((ret = RenameModuleDir(info.second)) != ERR_OK) {
5963             LOG_E(BMS_TAG_INSTALLER, "rename dir failed");
5964             break;
5965         }
5966     }
5967     RemoveEmptyDirs(newInfos);
5968     return ret;
5969 }
5970 
FindSignatureFileDir(const std::string & moduleName,std::string & signatureFileDir)5971 ErrCode BaseBundleInstaller::FindSignatureFileDir(const std::string &moduleName, std::string &signatureFileDir)
5972 {
5973     LOG_D(BMS_TAG_INSTALLER, "begin to find code signature file of moudle %{public}s", moduleName.c_str());
5974     if (verifyCodeParams_.empty()) {
5975         signatureFileDir = "";
5976         LOG_D(BMS_TAG_INSTALLER, "verifyCodeParams_ is empty and no need to verify code signature of module %{public}s",
5977             moduleName.c_str());
5978         return ERR_OK;
5979     }
5980     if (signatureFileTmpMap_.find(moduleName) != signatureFileTmpMap_.end()) {
5981         signatureFileDir = signatureFileTmpMap_.at(moduleName);
5982         LOG_D(BMS_TAG_INSTALLER, "signature file of %{public}s is existed in temp map", moduleName.c_str());
5983         return ERR_OK;
5984     }
5985     auto iterator = verifyCodeParams_.find(moduleName);
5986     if (iterator == verifyCodeParams_.end()) {
5987         LOG_E(BMS_TAG_INSTALLER, "no signature file dir exist of module %{public}s", moduleName.c_str());
5988         return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FAILED;
5989     }
5990     signatureFileDir = verifyCodeParams_.at(moduleName);
5991 
5992     // check validity of the signature file
5993     auto ret = bundleInstallChecker_->CheckSignatureFileDir(signatureFileDir);
5994     if (ret != ERR_OK) {
5995         LOG_E(BMS_TAG_INSTALLER, "checkout signature file dir %{private}s failed", signatureFileDir.c_str());
5996         return ret;
5997     }
5998 
5999     // copy code signature file to security dir
6000     std::string destinationStr =
6001         BundleUtil::CopyFileToSecurityDir(signatureFileDir, DirType::SIG_FILE_DIR, toDeleteTempHapPath_);
6002     if (destinationStr.empty()) {
6003         LOG_E(BMS_TAG_INSTALLER, "copy file %{private}s to security dir failed", signatureFileDir.c_str());
6004         return ERR_APPEXECFWK_INSTALL_COPY_HAP_FAILED;
6005     }
6006     if (signatureFileDir.find(ServiceConstants::SIGNATURE_FILE_PATH) != std::string::npos) {
6007         BundleUtil::DeleteDir(signatureFileDir);
6008     }
6009     signatureFileDir = destinationStr;
6010     signatureFileTmpMap_.emplace(moduleName, destinationStr);
6011     LOG_D(BMS_TAG_INSTALLER, "signatureFileDir is %{public}s", signatureFileDir.c_str());
6012     return ERR_OK;
6013 }
6014 
GetTempHapPath(const InnerBundleInfo & info)6015 std::string BaseBundleInstaller::GetTempHapPath(const InnerBundleInfo &info)
6016 {
6017     std::string hapPath = GetHapPath(info);
6018     if (hapPath.empty() || (!BundleUtil::EndWith(hapPath, ServiceConstants::INSTALL_FILE_SUFFIX) &&
6019         !BundleUtil::EndWith(hapPath, ServiceConstants::HSP_FILE_SUFFIX))) {
6020         LOG_E(BMS_TAG_INSTALLER, "invalid hapPath %{public}s", hapPath.c_str());
6021         return "";
6022     }
6023     auto posOfPathSep = hapPath.rfind(ServiceConstants::PATH_SEPARATOR);
6024     if (posOfPathSep == std::string::npos) {
6025         return "";
6026     }
6027 
6028     if (isFeatureNeedUninstall_) {
6029         return std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
6030             std::string(ServiceConstants::BUNDLE_NEW_CODE_DIR) + info.GetBundleName() +
6031             hapPath.substr(posOfPathSep);
6032     }
6033     std::string tempDir = hapPath.substr(0, posOfPathSep + 1) + info.GetCurrentModulePackage();
6034     if (installedModules_[info.GetCurrentModulePackage()]) {
6035         tempDir += ServiceConstants::TMP_SUFFIX;
6036     }
6037 
6038     return tempDir.append(hapPath.substr(posOfPathSep));
6039 }
6040 
CheckHapEncryption(const std::unordered_map<std::string,InnerBundleInfo> & infos,const InnerBundleInfo & oldInfo,bool isHapCopied)6041 ErrCode BaseBundleInstaller::CheckHapEncryption(const std::unordered_map<std::string, InnerBundleInfo> &infos,
6042     const InnerBundleInfo &oldInfo, bool isHapCopied)
6043 {
6044     LOG_I(BMS_TAG_INSTALLER, "begin");
6045     InnerBundleInfo newInfo;
6046     if (!GetTempBundleInfo(newInfo)) {
6047         LOG_E(BMS_TAG_INSTALLER, "Get innerBundleInfo failed, bundleName: %{public}s", bundleName_.c_str());
6048         return ERR_APPEXECFWK_GET_INSTALL_TEMP_BUNDLE_ERROR;
6049     }
6050     for (const auto &info : infos) {
6051         std::string hapPath;
6052         if (!isHapCopied) {
6053             hapPath = info.first;
6054         } else {
6055             if (hapPathRecords_.find(info.first) == hapPathRecords_.end()) {
6056                 LOG_E(BMS_TAG_INSTALLER, "path %{public}s cannot be found in hapPathRecord", info.first.c_str());
6057                 return ERR_APPEXECFWK_HAP_ENCRYPTION_CHECK_ERROR;
6058             }
6059             hapPath = hapPathRecords_.at(info.first);
6060         }
6061         CheckEncryptionParam param;
6062         param.modulePath = hapPath;
6063         int uid = info.second.GetUid(userId_);
6064         param.bundleId = uid - userId_ * Constants::BASE_USER_RANGE;
6065         param.isCompressNativeLibrary = info.second.IsCompressNativeLibs(info.second.GetCurModuleName());
6066         param.appIdentifier = info.second.GetAppIdentifier();
6067         param.versionCode = info.second.GetVersionCode();
6068         if (info.second.GetModuleTypeByPackage(modulePackage_) == Profile::MODULE_TYPE_SHARED) {
6069             param.installBundleType = InstallBundleType::INTER_APP_HSP;
6070         }
6071         bool isEncrypted = false;
6072         ErrCode result = InstalldClient::GetInstance()->CheckEncryption(param, isEncrypted);
6073         if (isHapCopied) {
6074             CHECK_RESULT(result, "fail to CheckHapEncryption, error is %{public}d");
6075         }
6076         if ((info.second.GetBaseApplicationInfo().debug ||
6077             (info.second.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG)) && isEncrypted) {
6078             LOG_E(BMS_TAG_INSTALLER, "-n %{public}s debug encrypted bundle is not allowed to install",
6079                 bundleName_.c_str());
6080             return ERR_APPEXECFWK_INSTALL_DEBUG_ENCRYPTED_BUNDLE_FAILED;
6081         }
6082         newInfo.SetMoudleIsEncrpted(info.second.GetCurrentModulePackage(), isEncrypted);
6083     }
6084     UpdateEncryptionStatus(infos, oldInfo, newInfo);
6085     if (!tempInfo_.SetTempBundleInfo(newInfo)) {
6086         LOG_E(BMS_TAG_INSTALLER, "save UpdateInnerBundleInfo failed");
6087         return ERR_APPEXECFWK_SET_INSTALL_TEMP_BUNDLE_ERROR;
6088     }
6089     LOG_I(BMS_TAG_INSTALLER, "end");
6090     return ERR_OK;
6091 }
6092 
UpdateEncryptionStatus(const std::unordered_map<std::string,InnerBundleInfo> & infos,const InnerBundleInfo & oldInfo,InnerBundleInfo & newInfo)6093 void BaseBundleInstaller::UpdateEncryptionStatus(const std::unordered_map<std::string, InnerBundleInfo> &infos,
6094     const InnerBundleInfo &oldInfo, InnerBundleInfo &newInfo)
6095 {
6096     if (IsBundleEncrypted(infos, oldInfo, newInfo)) {
6097         LOG_I(BMS_TAG_INSTALLER, "%{public}s is encrypted", newInfo.GetBundleName().c_str());
6098         newInfo.SetApplicationReservedFlag(static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION));
6099     } else {
6100         LOG_D(BMS_TAG_INSTALLER, "application does not contain encrypted module");
6101         newInfo.ClearApplicationReservedFlag(static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION));
6102     }
6103 }
6104 
IsBundleEncrypted(const std::unordered_map<std::string,InnerBundleInfo> & infos,const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo)6105 bool BaseBundleInstaller::IsBundleEncrypted(const std::unordered_map<std::string, InnerBundleInfo> &infos,
6106     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo)
6107 {
6108     // any of the new module is entryped, then the bundle is entryped
6109     for (const auto &info : infos) {
6110         if (newInfo.IsEncryptedMoudle(info.second.GetCurrentModulePackage())) {
6111             LOG_D(BMS_TAG_INSTALLER, "new installed module is encrypted");
6112             return true;
6113         }
6114     }
6115     // infos does not contain encrypted module
6116     // if upgrade, no need to check old bundle
6117     if (infos.empty() || infos.begin()->second.GetVersionCode() > oldInfo.GetVersionCode()) {
6118         return false;
6119     }
6120     // if not upgrade and old bundle is not encrypted, the new bundle is alse not encrypted
6121     if (!oldInfo.IsContainEncryptedModule()) {
6122         return false;
6123     }
6124     // if old bundle is encrypted, check whether all encrypted old modules are updated
6125     std::vector<std::string> encryptedModuleNames;
6126     oldInfo.GetAllEncryptedModuleNames(encryptedModuleNames);
6127     for (const auto &moduleName : encryptedModuleNames) {
6128         bool moduleUpdated = false;
6129         for (const auto &info : infos) {
6130             if (moduleName == info.second.GetModuleName(info.second.GetCurrentModulePackage())) {
6131                 moduleUpdated = true;
6132                 break;
6133             }
6134         }
6135         if (!moduleUpdated) {
6136             LOG_I(BMS_TAG_INSTALLER, "%{public}s is encrypted and not updated", moduleName.c_str());
6137             return true;
6138         }
6139     }
6140     return false;
6141 }
6142 
MoveFileToRealInstallationDir(const std::unordered_map<std::string,InnerBundleInfo> & infos)6143 ErrCode BaseBundleInstaller::MoveFileToRealInstallationDir(
6144     const std::unordered_map<std::string, InnerBundleInfo> &infos)
6145 {
6146     LOG_D(BMS_TAG_INSTALLER, "start to move file to real installation dir");
6147     for (const auto &info : infos) {
6148         if (hapPathRecords_.find(info.first) == hapPathRecords_.end()) {
6149             LOG_E(BMS_TAG_INSTALLER, "path %{public}s cannot be found in hapPathRecord", info.first.c_str());
6150             return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
6151         }
6152 
6153         std::string realInstallationPath = GetHapPath(info.second);
6154         LOG_D(BMS_TAG_INSTALLER, "move hsp or hsp file from path %{public}s to path %{public}s",
6155             hapPathRecords_.at(info.first).c_str(), realInstallationPath.c_str());
6156         // 1. move hap or hsp to real installation dir
6157         auto result = InstalldClient::GetInstance()->MoveFile(hapPathRecords_.at(info.first), realInstallationPath);
6158         if (result != ERR_OK) {
6159             LOG_E(BMS_TAG_INSTALLER, "move file to real path failed %{public}d", result);
6160             return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
6161         }
6162         FILE *hapFp = fopen(realInstallationPath.c_str(), "r");
6163         if (hapFp == nullptr) {
6164             LOG_E(BMS_TAG_INSTALLER, "fopen %{public}s failed", realInstallationPath.c_str());
6165             continue;
6166         }
6167         int32_t hapFd = fileno(hapFp);
6168         if (hapFd < 0) {
6169             LOG_E(BMS_TAG_INSTALLER, "open %{public}s failed", realInstallationPath.c_str());
6170             (void)fclose(hapFp);
6171             continue;
6172         }
6173         if (fsync(hapFd) != 0) {
6174             LOG_E(BMS_TAG_INSTALLER, "fsync %{public}s failed", realInstallationPath.c_str());
6175         }
6176         (void)fclose(hapFp);
6177     }
6178     return ERR_OK;
6179 }
6180 
GetRealSoPath(const std::string & bundleName,const std::string & nativeLibraryPath,bool isNeedDeleteOldPath) const6181 std::string BaseBundleInstaller::GetRealSoPath(const std::string &bundleName,
6182     const std::string &nativeLibraryPath, bool isNeedDeleteOldPath) const
6183 {
6184     std::string realSoDir;
6185     if (isNeedDeleteOldPath) {
6186         realSoDir.append(Constants::BUNDLE_CODE_DIR).append(ServiceConstants::PATH_SEPARATOR)
6187             .append(bundleName).append(ServiceConstants::PATH_SEPARATOR)
6188             .append(LIBS_TMP);
6189     } else {
6190         realSoDir.append(Constants::BUNDLE_CODE_DIR).append(ServiceConstants::PATH_SEPARATOR)
6191             .append(bundleName).append(ServiceConstants::PATH_SEPARATOR)
6192             .append(nativeLibraryPath);
6193     }
6194     return realSoDir;
6195 }
6196 
FinalProcessHapAndSoForBundleUpdate(const std::unordered_map<std::string,InnerBundleInfo> & infos,bool needCopyHapToInstallPath,bool needDeleteOldLibraryPath)6197 ErrCode BaseBundleInstaller::FinalProcessHapAndSoForBundleUpdate(
6198     const std::unordered_map<std::string, InnerBundleInfo> &infos,
6199     bool needCopyHapToInstallPath, bool needDeleteOldLibraryPath)
6200 {
6201     if (infos.empty()) {
6202         LOG_E(BMS_TAG_INSTALLER, "infos are empty");
6203         return ERR_OK;
6204     }
6205     std::string bundleName = infos.begin()->second.GetBundleName();
6206     ErrCode result = ERR_OK;
6207     if (needCopyHapToInstallPath) {
6208         // move hap file from temp dir to real installation dir
6209         LOG_I(BMS_TAG_INSTALLER, "-n %{public}s start to move file", bundleName.c_str());
6210         result = MoveFileToRealInstallationDir(infos);
6211         if (result != ERR_OK) {
6212             LOG_E(BMS_TAG_INSTALLER, "-n %{public}s move file failed %{public}d", bundleName.c_str(), result);
6213             return result;
6214         }
6215     }
6216     if (needDeleteOldLibraryPath) {
6217         // move so file from temp dir to real installation dir
6218         LOG_I(BMS_TAG_INSTALLER, "-n %{public}s process so start", bundleName.c_str());
6219         std::string nativeLibraryPath = "";
6220         for (const auto &info : infos) {
6221             if (info.second.GetNativeLibraryPath().empty() ||
6222                 info.second.IsLibIsolated(info.second.GetCurModuleName()) ||
6223                 !info.second.IsCompressNativeLibs(info.second.GetCurModuleName())) {
6224                 continue;
6225             }
6226             // multi-hap application nativeLiraryPath is same, CheckMultiNativeSo
6227             nativeLibraryPath = info.second.GetNativeLibraryPath();
6228             break;
6229         }
6230         // delete old native library path
6231         DeleteOldNativeLibraryPath();
6232         if (!nativeLibraryPath.empty()) {
6233             std::string realSoDir = GetRealSoPath(bundleName, nativeLibraryPath, false);
6234             InstalldClient::GetInstance()->CreateBundleDir(realSoDir);
6235             std::string tempSoDir = GetRealSoPath(bundleName, nativeLibraryPath, true);
6236             result = InstalldClient::GetInstance()->RenameModuleDir(tempSoDir, realSoDir);
6237             if (result != ERR_OK) {
6238                 LOG_E(BMS_TAG_INSTALLER, "-n %{public}s rename module dir failed, error is %{public}d",
6239                     bundleName.c_str(), result);
6240                 return result;
6241             }
6242         }
6243         LOG_I(BMS_TAG_INSTALLER, "-n %{public}s process so end", bundleName.c_str());
6244     }
6245     return ERR_OK;
6246 }
6247 
MoveSoFileToRealInstallationDir(const std::unordered_map<std::string,InnerBundleInfo> & infos,bool needDeleteOldLibraryPath)6248 ErrCode BaseBundleInstaller::MoveSoFileToRealInstallationDir(
6249     const std::unordered_map<std::string, InnerBundleInfo> &infos, bool needDeleteOldLibraryPath)
6250 {
6251     LOG_D(BMS_TAG_INSTALLER, "start to move so file to real installation dir");
6252     if (infos.empty()) {
6253         LOG_NOFUNC_I(BMS_TAG_INSTALLER, "no hap info to process");
6254         return ERR_OK;
6255     }
6256     std::string bundleName = infos.begin()->second.GetBundleName();
6257     if (needDeleteOldLibraryPath) {
6258         // first delete libs_tmp dir, make sure is empty
6259         std::string tempSoDir;
6260         tempSoDir.append(Constants::BUNDLE_CODE_DIR).append(ServiceConstants::PATH_SEPARATOR)
6261             .append(bundleName).append(ServiceConstants::PATH_SEPARATOR).append(LIBS_TMP);
6262         InstalldClient::GetInstance()->RemoveDir(tempSoDir);
6263     }
6264     for (const auto &info : infos) {
6265         if (info.second.IsLibIsolated(info.second.GetCurModuleName()) ||
6266             !info.second.IsCompressNativeLibs(info.second.GetCurModuleName())) {
6267             LOG_NOFUNC_I(BMS_TAG_INSTALLER, "-n %{public}s so files are isolated or decompressed no necessary to move",
6268                 bundleName.c_str());
6269             continue;
6270         }
6271         std::string cpuAbi = "";
6272         std::string nativeLibraryPath = "";
6273         bool isSoExisted = info.second.FetchNativeSoAttrs(info.second.GetCurrentModulePackage(), cpuAbi,
6274             nativeLibraryPath);
6275         if (isSoExisted) {
6276             std::string tempSoDir;
6277             tempSoDir.append(Constants::BUNDLE_CODE_DIR).append(ServiceConstants::PATH_SEPARATOR)
6278                 .append(bundleName).append(ServiceConstants::PATH_SEPARATOR)
6279                 .append(info.second.GetCurrentModulePackage())
6280                 .append(ServiceConstants::TMP_SUFFIX).append(ServiceConstants::PATH_SEPARATOR)
6281                 .append(nativeLibraryPath);
6282             bool isDirExisted = BundleUtil::IsExistDirNoLog(tempSoDir);
6283             if (!isDirExisted) {
6284                 LOG_NOFUNC_W(BMS_TAG_INSTALLER, "%{public}s not existed not need move", tempSoDir.c_str());
6285                 continue;
6286             }
6287             std::string realSoDir = GetRealSoPath(bundleName, nativeLibraryPath, needDeleteOldLibraryPath);
6288             LOG_D(BMS_TAG_INSTALLER, "move file from %{public}s to %{public}s", tempSoDir.c_str(), realSoDir.c_str());
6289             isDirExisted = BundleUtil::IsExistDirNoLog(realSoDir);
6290             if (!isDirExisted) {
6291                 LOG_NOFUNC_W(BMS_TAG_INSTALLER, "%{public}s not existed", realSoDir.c_str());
6292                 InstalldClient::GetInstance()->CreateBundleDir(realSoDir);
6293             }
6294             auto result = InstalldClient::GetInstance()->MoveFiles(tempSoDir, realSoDir);
6295             if (result != ERR_OK) {
6296                 LOG_E(BMS_TAG_INSTALLER, "move file to real path failed %{public}d", result);
6297                 return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
6298             }
6299             RemoveTempSoDir(tempSoDir);
6300             if (!installedModules_[info.second.GetCurrentModulePackage()]) {
6301                 RemoveTempPathOnlyUsedForSo(info.second);
6302             }
6303         }
6304     }
6305     return ERR_OK;
6306 }
6307 
UpdateAppInstallControlled(int32_t userId)6308 void BaseBundleInstaller::UpdateAppInstallControlled(int32_t userId)
6309 {
6310 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
6311     if (!DelayedSingleton<AppControlManager>::GetInstance()->IsAppInstallControlEnabled()) {
6312         LOG_D(BMS_TAG_INSTALLER, "app control feature is disabled");
6313         return;
6314     }
6315 
6316     if (bundleName_.empty() || dataMgr_ == nullptr) {
6317         LOG_W(BMS_TAG_INSTALLER, "invalid bundleName_ or dataMgr is nullptr");
6318         return;
6319     }
6320     if (!isAppExist_) {
6321         LOG_W(BMS_TAG_INSTALLER, "bundle %{public}s is not existed", bundleName_.c_str());
6322         return;
6323     }
6324 
6325     InnerBundleInfo info;
6326     tempInfo_.GetTempBundleInfo(info);
6327     InnerBundleUserInfo userInfo;
6328     if (!info.GetInnerBundleUserInfo(userId, userInfo)) {
6329         LOG_W(BMS_TAG_INSTALLER, "current bundle (%{public}s) is not installed at current userId (%{public}d)",
6330             bundleName_.c_str(), userId);
6331         return;
6332     }
6333 
6334     std::string currentAppId = info.GetAppId();
6335     std::vector<std::string> appIds;
6336     ErrCode ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
6337         AppControlConstants::EDM_CALLING, AppControlConstants::APP_DISALLOWED_UNINSTALL, userId, appIds);
6338     if ((ret == ERR_OK) && (std::find(appIds.begin(), appIds.end(), currentAppId) != appIds.end())) {
6339         LOG_W(BMS_TAG_INSTALLER, "bundle %{public}s cannot be removed", bundleName_.c_str());
6340         userInfo.isRemovable = false;
6341         info.AddInnerBundleUserInfo(userInfo);
6342         info.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
6343         tempInfo_.SetTempBundleInfo(info);
6344     }
6345 #else
6346     LOG_W(BMS_TAG_INSTALLER, "app control is disable");
6347 #endif
6348 }
6349 
UpdateHasCloudkitConfig()6350 void BaseBundleInstaller::UpdateHasCloudkitConfig()
6351 {
6352     InnerBundleInfo info;
6353     tempInfo_.GetTempBundleInfo(info);
6354     info.UpdateHasCloudkitConfig();
6355     tempInfo_.SetTempBundleInfo(info);
6356 }
6357 
UninstallBundleFromBmsExtension(const std::string & bundleName)6358 ErrCode BaseBundleInstaller::UninstallBundleFromBmsExtension(const std::string &bundleName)
6359 {
6360     LOG_D(BMS_TAG_INSTALLER, "start to uninstall bundle from bms extension");
6361     if (!DelayedSingleton<BundleMgrService>::GetInstance()->IsBrokerServiceStarted()) {
6362         LOG_W(BMS_TAG_INSTALLER, "broker is not started");
6363         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
6364     }
6365     BmsExtensionDataMgr bmsExtensionDataMgr;
6366     auto ret = bmsExtensionDataMgr.Uninstall(bundleName);
6367     if (ret == ERR_OK) {
6368         LOG_D(BMS_TAG_INSTALLER, "uninstall bundle(%{public}s) from bms extension successfully", bundleName.c_str());
6369         return ERR_OK;
6370     }
6371     if ((ret == ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE) ||
6372         (ret == ERR_BUNDLE_MANAGER_INSTALL_FAILED_BUNDLE_EXTENSION_NOT_EXISTED)) {
6373         LOG_E(BMS_TAG_INSTALLER, "uninstall failed due to bundle(%{public}s is not existed)", bundleName.c_str());
6374         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
6375     }
6376     LOG_E(BMS_TAG_INSTALLER, "uninstall bundle(%{public}s) from bms extension faile due to errcode %{public}d",
6377         bundleName.c_str(), ret);
6378     return ret;
6379 }
6380 
CheckBundleInBmsExtension(const std::string & bundleName,int32_t userId)6381 ErrCode BaseBundleInstaller::CheckBundleInBmsExtension(const std::string &bundleName, int32_t userId)
6382 {
6383     LOG_D(BMS_TAG_INSTALLER, "start to check bundle(%{public}s) from bms extension", bundleName.c_str());
6384     if (!DelayedSingleton<BundleMgrService>::GetInstance()->IsBrokerServiceStarted()) {
6385         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "broker is not started");
6386         return ERR_OK;
6387     }
6388     BmsExtensionDataMgr bmsExtensionDataMgr;
6389     BundleInfo extensionBundleInfo;
6390     auto ret = bmsExtensionDataMgr.GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, userId,
6391         extensionBundleInfo);
6392     if (ret == ERR_OK) {
6393         LOG_E(BMS_TAG_INSTALLER, "the bundle(%{public}s) is already existed in the bms extension", bundleName.c_str());
6394         return ERR_APPEXECFWK_INSTALL_ALREADY_EXIST;
6395     }
6396     return ERR_OK;
6397 }
6398 
RemoveTempSoDir(const std::string & tempSoDir)6399 void BaseBundleInstaller::RemoveTempSoDir(const std::string &tempSoDir)
6400 {
6401     auto firstPos = tempSoDir.find(ServiceConstants::TMP_SUFFIX);
6402     if (firstPos == std::string::npos) {
6403         LOG_W(BMS_TAG_INSTALLER, "invalid tempSoDir %{public}s", tempSoDir.c_str());
6404         return;
6405     }
6406     auto secondPos = tempSoDir.find(ServiceConstants::PATH_SEPARATOR, firstPos);
6407     if (secondPos == std::string::npos) {
6408         LOG_W(BMS_TAG_INSTALLER, "invalid tempSoDir %{public}s", tempSoDir.c_str());
6409         return;
6410     }
6411     auto thirdPos = tempSoDir.find(ServiceConstants::PATH_SEPARATOR, secondPos + 1);
6412     if (thirdPos == std::string::npos) {
6413         InstalldClient::GetInstance()->RemoveDir(tempSoDir);
6414         return;
6415     }
6416     std::string subTempSoDir = tempSoDir.substr(0, thirdPos);
6417     InstalldClient::GetInstance()->RemoveDir(subTempSoDir);
6418 }
6419 
InstallEntryMoudleFirst(std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & bundleInfo,const InnerBundleUserInfo & innerBundleUserInfo,const InstallParam & installParam)6420 ErrCode BaseBundleInstaller::InstallEntryMoudleFirst(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
6421     InnerBundleInfo &bundleInfo, const InnerBundleUserInfo &innerBundleUserInfo, const InstallParam &installParam)
6422 {
6423     LOG_D(BMS_TAG_INSTALLER, "start to install entry firstly");
6424     if (!isAppExist_ || isEntryInstalled_) {
6425         LOG_D(BMS_TAG_INSTALLER, "no need to install entry firstly");
6426         return ERR_OK;
6427     }
6428     ErrCode result = ERR_OK;
6429     for (auto &info : newInfos) {
6430         if (info.second.HasEntry()) {
6431             modulePath_ = info.first;
6432             InnerBundleInfo &newInfo = info.second;
6433             newInfo.AddInnerBundleUserInfo(innerBundleUserInfo);
6434             bool isReplace = (installParam.installFlag == InstallFlag::REPLACE_EXISTING ||
6435                 installParam.installFlag == InstallFlag::FREE_INSTALL);
6436             // app exist, but module may not
6437             result = ProcessBundleUpdateStatus(bundleInfo, newInfo, isReplace, installParam.GetKillProcess());
6438             if (result == ERR_OK) {
6439                 entryModuleName_ = info.second.GetCurrentModulePackage();
6440                 LOG_D(BMS_TAG_INSTALLER, "entry packageName is %{public}s", entryModuleName_.c_str());
6441             }
6442             break;
6443         }
6444     }
6445     isEntryInstalled_ = true;
6446     return result;
6447 }
6448 
DeliveryProfileToCodeSign() const6449 ErrCode BaseBundleInstaller::DeliveryProfileToCodeSign() const
6450 {
6451     LOG_D(BMS_TAG_INSTALLER, "start to delivery sign profile to code signature");
6452     Security::Verify::ProvisionInfo provisionInfo = verifyRes_.GetProvisionInfo();
6453     if (provisionInfo.profileBlockLength == 0 || provisionInfo.profileBlock == nullptr) {
6454         LOG_D(BMS_TAG_INSTALLER, "Emulator does not verify signature");
6455         return ERR_OK;
6456     }
6457     if (provisionInfo.distributionType == Security::Verify::AppDistType::ENTERPRISE ||
6458         provisionInfo.distributionType == Security::Verify::AppDistType::ENTERPRISE_NORMAL ||
6459         provisionInfo.distributionType == Security::Verify::AppDistType::ENTERPRISE_MDM ||
6460         provisionInfo.distributionType == Security::Verify::AppDistType::INTERNALTESTING ||
6461         provisionInfo.type == Security::Verify::ProvisionType::DEBUG) {
6462         return InstalldClient::GetInstance()->DeliverySignProfile(provisionInfo.bundleInfo.bundleName,
6463             provisionInfo.profileBlockLength, provisionInfo.profileBlock.get());
6464     }
6465     return ERR_OK;
6466 }
6467 
RemoveProfileFromCodeSign(const std::string & bundleName) const6468 ErrCode BaseBundleInstaller::RemoveProfileFromCodeSign(const std::string &bundleName) const
6469 {
6470     LOG_D(BMS_TAG_INSTALLER, "remove sign profile of bundle %{public}s from code signature", bundleName.c_str());
6471     return InstalldClient::GetInstance()->RemoveSignProfile(bundleName);
6472 }
6473 
DeleteOldNativeLibraryPath() const6474 void BaseBundleInstaller::DeleteOldNativeLibraryPath() const
6475 {
6476     std::string oldLibPath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName_ +
6477         ServiceConstants::PATH_SEPARATOR + ServiceConstants::LIBS;
6478     if (InstalldClient::GetInstance()->RemoveDir(oldLibPath) != ERR_OK) {
6479         LOG_W(BMS_TAG_INSTALLER, "bundleNmae: %{public}s remove old libs dir failed", bundleName_.c_str());
6480     }
6481 }
6482 
RemoveTempPathOnlyUsedForSo(const InnerBundleInfo & innerBundleInfo) const6483 void BaseBundleInstaller::RemoveTempPathOnlyUsedForSo(const InnerBundleInfo &innerBundleInfo) const
6484 {
6485     LOG_D(BMS_TAG_INSTALLER, "start");
6486     std::string tempDir;
6487     tempDir.append(Constants::BUNDLE_CODE_DIR).append(ServiceConstants::PATH_SEPARATOR)
6488         .append(innerBundleInfo.GetBundleName()).append(ServiceConstants::PATH_SEPARATOR)
6489         .append(innerBundleInfo.GetCurrentModulePackage())
6490         .append(ServiceConstants::TMP_SUFFIX);
6491     bool isDirEmpty = false;
6492     if (InstalldClient::GetInstance()->IsDirEmpty(tempDir, isDirEmpty) != ERR_OK) {
6493         LOG_W(BMS_TAG_INSTALLER, "IsDirEmpty failed");
6494     }
6495     if (isDirEmpty && (InstalldClient::GetInstance()->RemoveDir(tempDir) != ERR_OK)) {
6496         LOG_W(BMS_TAG_INSTALLER, "remove tmp so path:%{public}s failed", tempDir.c_str());
6497     }
6498     LOG_D(BMS_TAG_INSTALLER, "end");
6499 }
6500 
NeedDeleteOldNativeLib(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,const InnerBundleInfo & oldInfo)6501 bool BaseBundleInstaller::NeedDeleteOldNativeLib(
6502     const std::unordered_map<std::string, InnerBundleInfo> &newInfos,
6503     const InnerBundleInfo &oldInfo)
6504 {
6505     if (newInfos.empty()) {
6506         LOG_D(BMS_TAG_INSTALLER, "NewInfos is null");
6507         return false;
6508     }
6509 
6510     if (!isAppExist_) {
6511         LOG_D(BMS_TAG_INSTALLER, "No old app");
6512         return false;
6513     }
6514 
6515     if (oldInfo.GetNativeLibraryPath().empty()) {
6516         LOG_D(BMS_TAG_INSTALLER, "Old app no library");
6517         return false;
6518     }
6519 
6520     if ((versionCode_ > oldInfo.GetVersionCode())) {
6521         LOG_D(BMS_TAG_INSTALLER, "Higher versionCode");
6522         return true;
6523     }
6524 
6525     if (oldInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK) {
6526         LOG_D(BMS_TAG_INSTALLER, "Appservice not delete library");
6527         return false;
6528     }
6529 
6530     for (const auto &info : newInfos) {
6531         if (info.second.IsOnlyCreateBundleUser()) {
6532             LOG_D(BMS_TAG_INSTALLER, "Some hap no update module");
6533             return false;
6534         }
6535     }
6536 
6537     return otaInstall_ || HasAllOldModuleUpdate(oldInfo, newInfos);
6538 }
6539 
UpdateHapToken(bool needUpdate,InnerBundleInfo & newInfo)6540 ErrCode BaseBundleInstaller::UpdateHapToken(bool needUpdate, InnerBundleInfo &newInfo)
6541 {
6542     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "UpdateHapToken %{public}s start, needUpdate:%{public}d",
6543         bundleName_.c_str(), needUpdate);
6544     if (!InitDataMgr()) {
6545         return ERR_APPEXECFWK_NULL_PTR;
6546     }
6547     auto bundleUserInfos = newInfo.GetInnerBundleUserInfos();
6548     for (const auto &uerInfo : bundleUserInfos) {
6549         if (uerInfo.second.accessTokenId == 0) {
6550             continue;
6551         }
6552         int32_t userId = uerInfo.second.bundleUserInfo.userId;
6553         Security::AccessToken::AccessTokenIDEx accessTokenIdEx;
6554         accessTokenIdEx.tokenIDEx = uerInfo.second.accessTokenIdEx;
6555         Security::AccessToken::HapInfoCheckResult checkResult;
6556         if (BundlePermissionMgr::UpdateHapToken(accessTokenIdEx, newInfo, userId, checkResult,
6557             verifyRes_.GetProvisionInfo().appServiceCapabilities) != ERR_OK) {
6558             LOG_NOFUNC_E(BMS_TAG_INSTALLER, "UpdateHapToken failed %{public}s", bundleName_.c_str());
6559             SetVerifyPermissionResult(checkResult);
6560             return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
6561         }
6562         if (needUpdate) {
6563             newInfo.SetAccessTokenIdEx(accessTokenIdEx, uerInfo.second.bundleUserInfo.userId);
6564         }
6565 
6566         const std::map<std::string, InnerBundleCloneInfo> &cloneInfos = uerInfo.second.cloneInfos;
6567         for (const auto &cloneInfoPair : cloneInfos) {
6568             Security::AccessToken::AccessTokenIDEx cloneAccessTokenIdEx;
6569             cloneAccessTokenIdEx.tokenIDEx = cloneInfoPair.second.accessTokenIdEx;
6570             Security::AccessToken::HapInfoCheckResult checkResult;
6571             if (BundlePermissionMgr::UpdateHapToken(cloneAccessTokenIdEx, newInfo, userId, checkResult,
6572                 verifyRes_.GetProvisionInfo().appServiceCapabilities) != ERR_OK) {
6573                 LOG_NOFUNC_E(BMS_TAG_INSTALLER, "UpdateHapToken failed %{public}s", bundleName_.c_str());
6574                 SetVerifyPermissionResult(checkResult);
6575                 return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
6576             }
6577             if (needUpdate) {
6578                 newInfo.SetAccessTokenIdExWithAppIndex(cloneAccessTokenIdEx,
6579                     uerInfo.second.bundleUserInfo.userId, cloneInfoPair.second.appIndex);
6580             }
6581         }
6582     }
6583     if (needUpdate && !tempInfo_.SetTempBundleInfo(newInfo)) {
6584         LOG_NOFUNC_E(BMS_TAG_INSTALLER, "save UpdateInnerBundleInfo failed %{public}s", bundleName_.c_str());
6585         return ERR_APPEXECFWK_SET_INSTALL_TEMP_BUNDLE_ERROR;
6586     }
6587     return ERR_OK;
6588 }
6589 
6590 #ifdef APP_DOMAIN_VERIFY_ENABLED
PrepareSkillUri(const std::vector<Skill> & skills,std::vector<AppDomainVerify::SkillUri> & skillUris) const6591 void BaseBundleInstaller::PrepareSkillUri(const std::vector<Skill> &skills,
6592     std::vector<AppDomainVerify::SkillUri> &skillUris) const
6593 {
6594     for (const auto &skill : skills) {
6595         if (!skill.domainVerify) {
6596             continue;
6597         }
6598         for (const auto &uri : skill.uris) {
6599             if (uri.scheme != SKILL_URI_SCHEME_HTTPS) {
6600                 continue;
6601             }
6602             AppDomainVerify::SkillUri skillUri;
6603             skillUri.scheme = uri.scheme;
6604             skillUri.host = uri.host;
6605             skillUri.port = uri.port;
6606             skillUri.path = uri.path;
6607             skillUri.pathStartWith = uri.pathStartWith;
6608             skillUri.pathRegex = uri.pathRegex;
6609             skillUri.type = uri.type;
6610             skillUris.push_back(skillUri);
6611         }
6612     }
6613 }
6614 #endif
6615 
VerifyDomain()6616 void BaseBundleInstaller::VerifyDomain()
6617 {
6618 #ifdef APP_DOMAIN_VERIFY_ENABLED
6619     LOG_D(BMS_TAG_INSTALLER, "start to verify domain");
6620     InnerBundleInfo bundleInfo;
6621     if (!GetTempBundleInfo(bundleInfo)) {
6622         LOG_E(BMS_TAG_INSTALLER, "Get innerBundleInfo failed, bundleName: %{public}s", bundleName_.c_str());
6623         return;
6624     }
6625     std::string appIdentifier = bundleInfo.GetAppIdentifier();
6626     if (isAppExist_) {
6627         LOG_NOFUNC_I(BMS_TAG_INSTALLER, "app exist, need to clear old domain info");
6628         ClearDomainVerifyStatus(appIdentifier, bundleName_);
6629     }
6630     std::vector<AppDomainVerify::SkillUri> skillUris;
6631     std::map<std::string, std::vector<Skill>> skillInfos = bundleInfo.GetInnerSkillInfos();
6632     for (const auto &skillInfo : skillInfos) {
6633         PrepareSkillUri(skillInfo.second, skillUris);
6634     }
6635     if (skillUris.empty()) {
6636         LOG_NOFUNC_I(BMS_TAG_INSTALLER, "no skill uri need to verify domain");
6637         return;
6638     }
6639     std::string fingerprint = bundleInfo.GetCertificateFingerprint();
6640     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "start VerifyDomain, size: %{public}zu", skillUris.size());
6641     // call VerifyDomain
6642     std::string identity = IPCSkeleton::ResetCallingIdentity();
6643     DelayedSingleton<AppDomainVerify::AppDomainVerifyMgrClient>::GetInstance()->VerifyDomain(
6644         appIdentifier, bundleName_, fingerprint, skillUris);
6645     IPCSkeleton::SetCallingIdentity(identity);
6646     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "end VerifyDomain");
6647 #else
6648     LOG_I(BMS_TAG_INSTALLER, "app domain verify is disabled");
6649     return;
6650 #endif
6651 }
6652 
ClearDomainVerifyStatus(const std::string & appIdentifier,const std::string & bundleName) const6653 void BaseBundleInstaller::ClearDomainVerifyStatus(const std::string &appIdentifier,
6654     const std::string &bundleName) const
6655 {
6656 #ifdef APP_DOMAIN_VERIFY_ENABLED
6657     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "start ClearDomainVerifyStatus");
6658     std::string identity = IPCSkeleton::ResetCallingIdentity();
6659     // call ClearDomainVerifyStatus
6660     if (!DelayedSingleton<AppDomainVerify::AppDomainVerifyMgrClient>::GetInstance()->ClearDomainVerifyStatus(
6661         appIdentifier, bundleName)) {
6662         LOG_W(BMS_TAG_INSTALLER, "ClearDomainVerifyStatus failed");
6663     }
6664     IPCSkeleton::SetCallingIdentity(identity);
6665     LOG_NOFUNC_I(BMS_TAG_INSTALLER, "end ClearDomainVerifyStatus");
6666 #else
6667     LOG_I(BMS_TAG_INSTALLER, "app domain verify is disabled");
6668     return;
6669 #endif
6670 }
6671 
IsRdDevice() const6672 bool BaseBundleInstaller::IsRdDevice() const
6673 {
6674     BmsExtensionDataMgr bmsExtensionDataMgr;
6675     bool res = bmsExtensionDataMgr.IsRdDevice();
6676     if (res) {
6677         LOG_I(BMS_TAG_INSTALLER, "current device is rd device");
6678         return true;
6679     }
6680     return false;
6681 }
6682 
CreateShaderCache(const std::string & bundleName,int32_t uid,int32_t gid) const6683 ErrCode BaseBundleInstaller::CreateShaderCache(const std::string &bundleName,
6684     int32_t uid, int32_t gid) const
6685 {
6686     std::string shaderCachePath;
6687     shaderCachePath.append(ServiceConstants::SHADER_CACHE_PATH).append(bundleName);
6688     LOG_D(BMS_TAG_INSTALLER, "CreateShaderCache %{public}s", shaderCachePath.c_str());
6689     return InstalldClient::GetInstance()->Mkdir(shaderCachePath, S_IRWXU, uid, gid);
6690 }
6691 
DeleteShaderCache(const std::string & bundleName) const6692 ErrCode BaseBundleInstaller::DeleteShaderCache(const std::string &bundleName) const
6693 {
6694     std::string shaderCachePath;
6695     shaderCachePath.append(ServiceConstants::SHADER_CACHE_PATH).append(bundleName);
6696     LOG_D(BMS_TAG_INSTALLER, "DeleteShaderCache %{public}s", shaderCachePath.c_str());
6697     return InstalldClient::GetInstance()->RemoveDir(shaderCachePath);
6698 }
6699 
CleanBundleClonesShaderCache(const std::vector<int32_t> allAppIndexes,const std::string & bundleName,int32_t userId) const6700 ErrCode BaseBundleInstaller::CleanBundleClonesShaderCache(const std::vector<int32_t> allAppIndexes,
6701     const std::string &bundleName, int32_t userId) const
6702 {
6703     ErrCode ret = ERR_OK;
6704     for (int32_t appIndex: allAppIndexes) {
6705         std::string cloneBundleName = bundleName;
6706         if (appIndex != 0) {
6707             cloneBundleName = BundleCloneCommonHelper::GetCloneDataDir(bundleName, appIndex);
6708         }
6709         std::string el1ShaderCachePath = std::string(ServiceConstants::NEW_SHADER_CACHE_PATH);
6710         el1ShaderCachePath = el1ShaderCachePath.replace(el1ShaderCachePath.find("%"), 1, std::to_string(userId));
6711         el1ShaderCachePath = el1ShaderCachePath + cloneBundleName;
6712         InstalldClient::GetInstance()->CleanBundleDataDir(el1ShaderCachePath);
6713 
6714         // clean shader cache in /system_optimize
6715         std::string systemOptimizeShaderCache = ServiceConstants::SYSTEM_OPTIMIZE_SHADER_CACHE_PATH +
6716             cloneBundleName + ServiceConstants::SHADER_CACHE_SUBDIR;
6717         systemOptimizeShaderCache = systemOptimizeShaderCache.replace(systemOptimizeShaderCache.find("%"),
6718             1, std::to_string(userId));
6719         ret = InstalldClient::GetInstance()->CleanBundleDataDir(systemOptimizeShaderCache);
6720         if (ret != ERR_OK) {
6721             LOG_W(BMS_TAG_DEFAULT, "%{public}s clean shader cache fail %{public}d", bundleName.c_str(), ret);
6722             return ret;
6723         }
6724     }
6725     return ret;
6726 }
6727 
CleanShaderCache(const InnerBundleInfo & oldInfo,const std::string & bundleName,int32_t userId) const6728 ErrCode BaseBundleInstaller::CleanShaderCache(const InnerBundleInfo &oldInfo,
6729     const std::string &bundleName, int32_t userId) const
6730 {
6731     std::string shaderCachePath;
6732     shaderCachePath.append(ServiceConstants::SHADER_CACHE_PATH).append(bundleName);
6733     LOG_D(BMS_TAG_INSTALLER, "CleanShaderCache %{public}s", shaderCachePath.c_str());
6734     ErrCode ret = InstalldClient::GetInstance()->CleanBundleDataDir(shaderCachePath);
6735     if (ret != ERR_OK) {
6736         LOG_E(BMS_TAG_INSTALLER, "CleanShaderCache %{public}s failed", shaderCachePath.c_str());
6737     }
6738     std::vector<int32_t> allAppIndexes = {0};
6739     std::vector<int32_t> cloneAppIndexes = dataMgr_->GetCloneAppIndexesByInnerBundleInfo(oldInfo, userId);
6740     allAppIndexes.insert(allAppIndexes.end(), cloneAppIndexes.begin(), cloneAppIndexes.end());
6741     return CleanBundleClonesShaderCache(allAppIndexes, bundleName, userId);
6742 }
6743 
CreateCloudShader(const std::string & bundleName,int32_t uid,int32_t gid) const6744 void BaseBundleInstaller::CreateCloudShader(const std::string &bundleName, int32_t uid, int32_t gid) const
6745 {
6746     const std::string cloudShaderOwner = OHOS::system::GetParameter(ServiceConstants::CLOUD_SHADER_OWNER, "");
6747     if (cloudShaderOwner.empty() || (bundleName != cloudShaderOwner)) {
6748         return;
6749     }
6750 
6751     constexpr int32_t mode = (S_IRWXU | S_IXGRP | S_IXOTH);
6752     ErrCode result = InstalldClient::GetInstance()->Mkdir(ServiceConstants::CLOUD_SHADER_PATH, mode, uid, gid);
6753     if (result != ERR_OK) {
6754         LOG_W(BMS_TAG_DEFAULT, "Mkdir %{public}s failed, error is %{public}d",
6755             ServiceConstants::CLOUD_SHADER_PATH, result);
6756         return;
6757     }
6758 
6759     constexpr int32_t commonMode = (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
6760     result = InstalldClient::GetInstance()->Mkdir(ServiceConstants::CLOUD_SHADER_COMMON_PATH, commonMode, uid, gid);
6761     if (result != ERR_OK) {
6762         LOG_W(BMS_TAG_DEFAULT, "Mkdir %{public}s failed, error is %{public}d",
6763             ServiceConstants::CLOUD_SHADER_COMMON_PATH, result);
6764         return;
6765     }
6766     LOG_I(BMS_TAG_INSTALLER, "Create cloud shader cache result: %{public}d", result);
6767 }
6768 
DeleteCloudShader(const std::string & bundleName) const6769 ErrCode BaseBundleInstaller::DeleteCloudShader(const std::string &bundleName) const
6770 {
6771     std::string newShaderCloudPath;
6772     newShaderCloudPath.append(ServiceConstants::NEW_CLOUD_SHADER_PATH).append(bundleName);
6773     LOG_D(BMS_TAG_INSTALLER, "DeleteCloudShader %{public}s", newShaderCloudPath.c_str());
6774     return InstalldClient::GetInstance()->RemoveDir(newShaderCloudPath);
6775 }
6776 
DeleteBundleClonesShaderCache(const std::vector<int32_t> allAppIndexes,const std::string & bundleName,int32_t userId) const6777 ErrCode BaseBundleInstaller::DeleteBundleClonesShaderCache(const std::vector<int32_t> allAppIndexes,
6778     const std::string &bundleName, int32_t userId) const
6779 {
6780     ErrCode ret = ERR_OK;
6781     for (int32_t appIndex: allAppIndexes) {
6782         std::string cloneBundleName = bundleName;
6783         if (appIndex != 0) {
6784             cloneBundleName = BundleCloneCommonHelper::GetCloneDataDir(bundleName, appIndex);
6785         }
6786         std::string el1ShaderCachePath = std::string(ServiceConstants::NEW_SHADER_CACHE_PATH);
6787         el1ShaderCachePath = el1ShaderCachePath.replace(el1ShaderCachePath.find("%"), 1, std::to_string(userId));
6788         el1ShaderCachePath = el1ShaderCachePath + cloneBundleName;
6789         InstalldClient::GetInstance()->RemoveDir(el1ShaderCachePath);
6790 
6791         // Remove shader cache in /system_optimize
6792         std::string systemOptimizeShaderCache = ServiceConstants::SYSTEM_OPTIMIZE_SHADER_CACHE_PATH +
6793             cloneBundleName;
6794         systemOptimizeShaderCache = systemOptimizeShaderCache.replace(systemOptimizeShaderCache.find("%"),
6795             1, std::to_string(userId));
6796         ret = InstalldClient::GetInstance()->RemoveDir(systemOptimizeShaderCache);
6797         if (ret != ERR_OK) {
6798             LOG_W(BMS_TAG_DEFAULT, "%{public}s clean shader cache fail %{public}d", bundleName.c_str(), ret);
6799             return ret;
6800         }
6801     }
6802     return ret;
6803 }
6804 
DeleteEl1ShaderCache(const InnerBundleInfo & oldInfo,const std::string & bundleName,int32_t userId) const6805 ErrCode BaseBundleInstaller::DeleteEl1ShaderCache(const InnerBundleInfo &oldInfo,
6806     const std::string &bundleName, int32_t userId) const
6807 {
6808     std::vector<int32_t> allAppIndexes = {0};
6809     std::vector<int32_t> cloneAppIndexes = dataMgr_->GetCloneAppIndexesByInnerBundleInfo(oldInfo, userId);
6810     allAppIndexes.insert(allAppIndexes.end(), cloneAppIndexes.begin(), cloneAppIndexes.end());
6811     return DeleteBundleClonesShaderCache(allAppIndexes, bundleName, userId);
6812 }
6813 
CreateArkStartupCacheParameter(const std::string & bundleName,int32_t userId,BundleType bundleType,int32_t uid)6814 ArkStartupCache BaseBundleInstaller::CreateArkStartupCacheParameter(const std::string &bundleName,
6815     int32_t userId, BundleType bundleType, int32_t uid)
6816 {
6817     std::string el1ArkStartupCachePath = ServiceConstants::SYSTEM_OPTIMIZE_PATH +
6818         bundleName + ServiceConstants::ARK_STARTUP_CACHE_DIR;
6819     el1ArkStartupCachePath = el1ArkStartupCachePath.replace(el1ArkStartupCachePath.find("%"), 1,
6820         std::to_string(userId));
6821     ArkStartupCache ceateArk;
6822     ceateArk.bundleName = bundleName;
6823     ceateArk.bundleType = bundleType;
6824     ceateArk.cacheDir = el1ArkStartupCachePath;
6825     ceateArk.mode = ServiceConstants::SYSTEM_OPTIMIZE_MODE;
6826     ceateArk.uid = uid;
6827     ceateArk.gid = uid;
6828     return ceateArk;
6829 }
6830 
ProcessArkStartupCache(const ArkStartupCache & createArk,int32_t moduleNum,int32_t userId) const6831 ErrCode BaseBundleInstaller::ProcessArkStartupCache(const ArkStartupCache &createArk,
6832     int32_t moduleNum, int32_t userId) const
6833 {
6834     if (moduleNum != 1) {
6835         return DeleteArkStartupCache(ServiceConstants::SYSTEM_OPTIMIZE_PATH, createArk.bundleName, userId);
6836     }
6837     return CreateArkStartupCache(createArk);
6838 }
6839 
CreateArkStartupCache(const ArkStartupCache & createArk) const6840 ErrCode BaseBundleInstaller::CreateArkStartupCache(const ArkStartupCache &createArk) const
6841 {
6842     if (createArk.bundleType != BundleType::APP && createArk.bundleType != BundleType::ATOMIC_SERVICE) {
6843         LOG_W(BMS_TAG_INSTALLER, "%{public}s is not app or atomic service, not allow create ark startup cache dir",
6844             createArk.bundleName.c_str());
6845         return ERR_APPEXECFWK_ARK_STARTUP_CACHE_ONLY_ALLOW_CREATE_APP_OR_ATOMIC;
6846     }
6847 
6848     std::unordered_set<std::string> startupBundles;
6849     BundleParser::ParseArkStartupCacheConfig(ServiceConstants::APP_STARTUP_CACHE_CONG, startupBundles);
6850     if (startupBundles.find(createArk.bundleName) == startupBundles.end()) {
6851         LOG_W(BMS_TAG_INSTALLER, "%{public}s is not in startupBundles", createArk.bundleName.c_str());
6852         return ERR_APPEXECFWK_ARK_STARTUP_CACHE_ONLY_ALLOW_CREATE_IN_WHITE_LIST;
6853     }
6854 
6855     bool isDirExist = false;
6856     ErrCode result = InstalldClient::GetInstance()->Mkdir(createArk.cacheDir,
6857         createArk.mode, createArk.uid, createArk.gid);
6858     if (result != ERR_OK) {
6859         LOG_W(BMS_TAG_DEFAULT, "-n: %{public}s, Mkdir %{public}s failed, error:%{public}d",
6860             createArk.bundleName.c_str(), createArk.cacheDir.c_str(), errno);
6861         return result;
6862     }
6863     return InstalldClient::GetInstance()->SetArkStartupCacheApl(createArk.cacheDir);
6864 }
6865 
CleanArkStartupCache(const std::string & cacheDir,const std::string & bundleName,int32_t userId) const6866 ErrCode BaseBundleInstaller::CleanArkStartupCache(const std::string &cacheDir,
6867     const std::string &bundleName, int32_t userId) const
6868 {
6869     std::string el1ArkStartupCachePath = cacheDir + bundleName + ServiceConstants::ARK_STARTUP_CACHE_DIR;
6870     el1ArkStartupCachePath = el1ArkStartupCachePath.replace(el1ArkStartupCachePath.find("%"), 1,
6871         std::to_string(userId));
6872     return InstalldClient::GetInstance()->CleanBundleDataDir(el1ArkStartupCachePath);
6873 }
6874 
DeleteArkStartupCache(const std::string & cacheDir,const std::string & bundleName,int32_t userId) const6875 ErrCode BaseBundleInstaller::DeleteArkStartupCache(const std::string &cacheDir,
6876     const std::string &bundleName, int32_t userId) const
6877 {
6878     std::string el1ArkStartupCachePath = cacheDir + bundleName + ServiceConstants::ARK_STARTUP_CACHE_DIR;
6879     el1ArkStartupCachePath = el1ArkStartupCachePath.replace(el1ArkStartupCachePath.find("%"), 1,
6880         std::to_string(userId));
6881     return InstalldClient::GetInstance()->RemoveDir(el1ArkStartupCachePath);
6882 }
6883 
GetCheckResultMsg() const6884 std::string BaseBundleInstaller::GetCheckResultMsg() const
6885 {
6886     return bundleInstallChecker_->GetCheckResultMsg();
6887 }
6888 
SetCheckResultMsg(const std::string checkResultMsg) const6889 void BaseBundleInstaller::SetCheckResultMsg(const std::string checkResultMsg) const
6890 {
6891     bundleInstallChecker_->SetCheckResultMsg(checkResultMsg);
6892 }
6893 
SetVerifyPermissionResult(const Security::AccessToken::HapInfoCheckResult & checkResult)6894 void BaseBundleInstaller::SetVerifyPermissionResult(const Security::AccessToken::HapInfoCheckResult &checkResult)
6895 {
6896     auto result = BundlePermissionMgr::GetCheckResultMsg(checkResult);
6897     SetCheckResultMsg(result);
6898     LOG_NOFUNC_E(BMS_TAG_INSTALLER, "%{public}s", result.c_str());
6899 }
6900 
VerifyActivationLock() const6901 bool BaseBundleInstaller::VerifyActivationLock() const
6902 {
6903     LOG_I(BMS_TAG_INSTALLER, "verify activation lock start");
6904     int32_t mode = GetIntParameter(IS_ROOT_MODE_PARAM, USER_MODE);
6905     if (mode != USER_MODE) {
6906         char enableActivationLock[BMS_ACTIVATION_LOCK_VAL_LEN] = {0};
6907         int32_t ret = GetParameter(BMS_ACTIVATION_LOCK, "", enableActivationLock, BMS_ACTIVATION_LOCK_VAL_LEN);
6908         if (ret <= 0) {
6909             return true;
6910         }
6911         if (std::strcmp(enableActivationLock, BMS_TRUE) != 0) {
6912             LOG_D(BMS_TAG_INSTALLER, "activation lock no check, because lock is off");
6913             return true;
6914         }
6915     }
6916 
6917     BmsExtensionDataMgr bmsExtensionDataMgr;
6918     bool pass = false;
6919     ErrCode res = bmsExtensionDataMgr.VerifyActivationLock(pass);
6920     if ((res == ERR_OK) && !pass) {
6921         LOG_E(BMS_TAG_INSTALLER, "machine be controlled, not allow to install app");
6922         return false;
6923     }
6924 
6925     LOG_D(BMS_TAG_INSTALLER, "activation lock pass");
6926     // otherwise, pass
6927     return true;
6928 }
6929 
VerifyActivationLockToken() const6930 bool BaseBundleInstaller::VerifyActivationLockToken() const
6931 {
6932     BmsExtensionDataMgr bmsExtensionDataMgr;
6933     bool pass = false;
6934     ErrCode res = bmsExtensionDataMgr.VerifyActivationLockToken(pass);
6935     if ((res == ERR_OK) && !pass) {
6936         LOG_E(BMS_TAG_INSTALLER, "oobe phrase, not allow to install in hdc");
6937         return false;
6938     }
6939 
6940     LOG_D(BMS_TAG_INSTALLER, "activation lock pass not in oobe");
6941     // otherwise, pass
6942     return true;
6943 }
6944 
RollbackHmpUserInfo(const std::string & bundleName)6945 ErrCode BaseBundleInstaller::RollbackHmpUserInfo(const std::string &bundleName)
6946 {
6947     LOG_I(BMS_TAG_INSTALLER, "RollbackHmpInstall %{public}s start", bundleName.c_str());
6948     if (bundleName.empty()) {
6949         LOG_E(BMS_TAG_INSTALLER, "rollback hmp bundle name empty");
6950         return ERR_APPEXECFWK_UNINSTALL_INVALID_NAME;
6951     }
6952     if (!InitDataMgr()) {
6953         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
6954     }
6955     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
6956     std::lock_guard lock {mtx};
6957     InnerBundleInfo oldInfo;
6958     if (!dataMgr_->FetchInnerBundleInfo(bundleName, oldInfo)) {
6959         LOG_W(BMS_TAG_INSTALLER, "rollback hmp bundle info missing");
6960         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
6961     }
6962     std::set<int32_t> userIds;
6963     if (!dataMgr_->GetInnerBundleInfoUsers(bundleName, userIds)) {
6964         LOG_W(BMS_TAG_INSTALLER, "rollback hmp bundle users missing");
6965         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
6966     }
6967     for (auto userId : userIds) {
6968         if (oldInfo.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE &&
6969             oldInfo.GetUid(userId) != Constants::INVALID_UID) {
6970             std::string bundleDataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1]
6971                 + ServiceConstants::PATH_SEPARATOR + std::to_string(userId) + ServiceConstants::BASE +
6972                 oldInfo.GetBundleName();
6973             PrepareBundleDirQuota(oldInfo.GetBundleName(), oldInfo.GetUid(userId), bundleDataDir, 0);
6974         }
6975     }
6976     return ERR_OK;
6977 }
6978 
RollbackHmpCommonInfo(const std::string & bundleName)6979 ErrCode BaseBundleInstaller::RollbackHmpCommonInfo(const std::string &bundleName)
6980 {
6981     if (bundleName.empty()) {
6982         LOG_E(BMS_TAG_INSTALLER, "rollback hmp bundle name empty");
6983         return ERR_APPEXECFWK_UNINSTALL_INVALID_NAME;
6984     }
6985     if (!InitDataMgr()) {
6986         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
6987     }
6988     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
6989     std::lock_guard lock {mtx};
6990     InnerBundleInfo oldInfo;
6991     if (!dataMgr_->FetchInnerBundleInfo(bundleName, oldInfo)) {
6992         LOG_W(BMS_TAG_INSTALLER, "rollback hmp bundle info missing");
6993         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
6994     }
6995     if (!dataMgr_->UpdateBundleInstallState(oldInfo.GetBundleName(), InstallState::UNINSTALL_START)) {
6996         APP_LOGE("rollback hmp start uninstall failed");
6997         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
6998     }
6999     if (!dataMgr_->UpdateBundleInstallState(oldInfo.GetBundleName(), InstallState::UNINSTALL_SUCCESS)) {
7000         LOG_E(BMS_TAG_INSTALLER, "rollback hmp delete inner info failed");
7001         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
7002     }
7003     PreInstallBundleInfo preInfo;
7004     preInfo.SetBundleName(bundleName);
7005     if (!dataMgr_->DeletePreInstallBundleInfo(bundleName, preInfo)) {
7006         LOG_E(BMS_TAG_INSTALLER, "rollback hmp delete pre install info failed");
7007     }
7008 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
7009     std::shared_ptr<QuickFixDataMgr> quickFixDataMgr = DelayedSingleton<QuickFixDataMgr>::GetInstance();
7010     if (quickFixDataMgr != nullptr) {
7011         LOG_D(BMS_TAG_INSTALLER, "DeleteInnerAppQuickFix when bundleName :%{public}s uninstall",
7012             oldInfo.GetBundleName().c_str());
7013         quickFixDataMgr->DeleteInnerAppQuickFix(oldInfo.GetBundleName());
7014     }
7015 #endif
7016     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->DeleteAppProvisionInfo(oldInfo.GetBundleName())) {
7017         LOG_W(BMS_TAG_INSTALLER, "bundleName: %{public}s delete appProvisionInfo failed",
7018             oldInfo.GetBundleName().c_str());
7019     }
7020     DeleteRouterInfo(oldInfo.GetBundleName());
7021     BundleResourceHelper::DeleteBundleResourceInfo(oldInfo.GetBundleName(), userId_, false);
7022     RemoveProfileFromCodeSign(oldInfo.GetBundleName());
7023     ClearDomainVerifyStatus(oldInfo.GetAppIdentifier(), oldInfo.GetBundleName());
7024     return ERR_OK;
7025 }
7026 
IsAppInBlocklist(const std::string & bundleName,const int32_t userId) const7027 bool BaseBundleInstaller::IsAppInBlocklist(const std::string &bundleName, const int32_t userId) const
7028 {
7029     BmsExtensionDataMgr bmsExtensionDataMgr;
7030     bool res = bmsExtensionDataMgr.IsAppInBlocklist(bundleName, userId);
7031     if (res) {
7032         LOG_E(BMS_TAG_INSTALLER, "app %{public}s is in blocklist", bundleName.c_str());
7033         return true;
7034     }
7035     return false;
7036 }
7037 
CheckWhetherCanBeUninstalled(const std::string & bundleName,const std::string & appIdentifier) const7038 bool BaseBundleInstaller::CheckWhetherCanBeUninstalled(const std::string &bundleName,
7039     const std::string &appIdentifier) const
7040 {
7041     BmsExtensionDataMgr bmsExtensionDataMgr;
7042     LOG_I(BMS_TAG_INSTALLER, "CheckUninstall %{public}s", bundleName.c_str());
7043     bool res = bmsExtensionDataMgr.CheckWhetherCanBeUninstalled(bundleName, appIdentifier);
7044     if (!res) {
7045         LOG_E(BMS_TAG_INSTALLER, "uninstall %{public}s rejected", bundleName.c_str());
7046         return false;
7047     }
7048     return true;
7049 }
7050 
CheckSystemFreeSizeAndClean() const7051 void BaseBundleInstaller::CheckSystemFreeSizeAndClean() const
7052 {
7053     if (BundleUtil::CheckSystemFreeSize(BMS_SERVICE_PATH, FIVE_MB)) {
7054         return;
7055     }
7056     BundleMgrHostImpl impl;
7057     ErrCode ret = impl.CleanBundleCacheFilesAutomatic(FIVE_MB);
7058     LOG_I(BMS_TAG_INSTALLER, "clean disk ret:%{public}d", ret);
7059 }
7060 
CheckBundleNameAndStratAbility(const std::string & bundleName,const std::string & appIdentifier) const7061 void BaseBundleInstaller::CheckBundleNameAndStratAbility(const std::string &bundleName,
7062     const std::string &appIdentifier) const
7063 {
7064     LOG_I(BMS_TAG_INSTALLER, "CheckBundleNameAndStratAbility %{public}s", bundleName.c_str());
7065     BmsExtensionDataMgr bmsExtensionDataMgr;
7066     bmsExtensionDataMgr.CheckBundleNameAndStratAbility(bundleName, appIdentifier);
7067 }
7068 
MarkInstallFinish()7069 ErrCode BaseBundleInstaller::MarkInstallFinish()
7070 {
7071     InnerBundleInfo info;
7072     if (!GetTempBundleInfo(info)) {
7073         LOG_W(BMS_TAG_INSTALLER, "mark finish failed");
7074         return ERR_APPEXECFWK_GET_INSTALL_TEMP_BUNDLE_ERROR;
7075     }
7076     (void)bundleInstallChecker_->DetermineCloneApp(info);
7077     info.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
7078     info.SetInstallMark(bundleName_, info.GetCurModuleName(), InstallExceptionStatus::INSTALL_FINISH);
7079     if (!InitDataMgr()) {
7080         return ERR_APPEXECFWK_NULL_PTR;
7081     }
7082     if (isAppExist_) {
7083         if (!dataMgr_->UpdateInnerBundleInfo(info, true)) {
7084             if (!dataMgr_->UpdateInnerBundleInfo(info, true)) {
7085                 LOG_W(BMS_TAG_INSTALLER, "save mark failed, -n:%{public}s", bundleName_.c_str());
7086                 return ERR_APPEXECFWK_ADD_BUNDLE_ERROR;
7087             }
7088         }
7089         PrintStartWindowIconId(info);
7090         return ERR_OK;
7091     }
7092     if (!dataMgr_->AddInnerBundleInfo(bundleName_, info, false)) {
7093         LOG_E(BMS_TAG_INSTALLER, "add bundle failed, -n:%{public}s", bundleName_.c_str());
7094         dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_START);
7095         dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_SUCCESS);
7096         return ERR_APPEXECFWK_UPDATE_BUNDLE_ERROR;
7097     }
7098     if (!dataMgr_->SaveInnerBundleInfo(info)) {
7099         LOG_W(BMS_TAG_INSTALLER, "save mark failed, -n:%{public}s", bundleName_.c_str());
7100         return ERR_APPEXECFWK_UPDATE_BUNDLE_ERROR;
7101     }
7102     PrintStartWindowIconId(info);
7103     return ERR_OK;
7104 }
7105 
PrintStartWindowIconId(const InnerBundleInfo & info)7106 void BaseBundleInstaller::PrintStartWindowIconId(const InnerBundleInfo &info)
7107 {
7108     const auto &abilityMap = info.GetInnerAbilityInfos();
7109     for (const auto &ability : abilityMap) {
7110         const auto &abilityInfo = ability.second;
7111         if (abilityInfo.isLauncherAbility) {
7112             APP_LOGI_NOFUNC("startWindowIconId %{public}s_%{public}s_%{public}s_%{public}d",
7113                 abilityInfo.bundleName.c_str(), abilityInfo.moduleName.c_str(), abilityInfo.name.c_str(),
7114                 abilityInfo.startWindowIconId);
7115         }
7116     }
7117 }
7118 
IsDriverForAllUser(const std::string & bundleName)7119 bool BaseBundleInstaller::IsDriverForAllUser(const std::string &bundleName)
7120 {
7121     if (!OHOS::system::GetBoolParameter(ServiceConstants::IS_DRIVER_FOR_ALL_USERS, true)) {
7122         return false;
7123     }
7124 
7125     if (!InitDataMgr()) {
7126         return false;
7127     }
7128 
7129     InnerBundleInfo info;
7130     bool isAppExist = dataMgr_->FetchInnerBundleInfo(bundleName, info);
7131     if (isAppExist) {
7132         const auto extensions = info.GetInnerExtensionInfos();
7133         for (const auto &item : extensions) {
7134             if (item.second.type == ExtensionAbilityType::DRIVER) {
7135                 APP_LOGI("find driver extension ability, bundleName: %{public}s, moduleName: %{public}s",
7136                     item.second.bundleName.c_str(), item.second.moduleName.c_str());
7137                 return true;
7138             }
7139         }
7140     }
7141     return false;
7142 }
7143 
GetDriverInstallUser(const std::string & bundleName)7144 int32_t BaseBundleInstaller::GetDriverInstallUser(const std::string &bundleName)
7145 {
7146     if (!InitDataMgr()) {
7147         return Constants::START_USERID;
7148     }
7149 
7150     InnerBundleInfo info;
7151     bool isAppExist = dataMgr_->FetchInnerBundleInfo(bundleName, info);
7152     if (isAppExist) {
7153         const auto userInfos = info.GetInnerBundleUserInfos();
7154         if (!userInfos.empty()) {
7155             const auto item = userInfos.begin();
7156             return item->second.bundleUserInfo.userId;
7157         }
7158     }
7159     return Constants::START_USERID;
7160 }
7161 
IsEnterpriseForAllUser(const InstallParam & installParam,const std::string & bundleName)7162 bool BaseBundleInstaller::IsEnterpriseForAllUser(const InstallParam &installParam, const std::string &bundleName)
7163 {
7164     if (!installParam.IsEnterpriseForAllUser()) {
7165         return false;
7166     }
7167     if (!OHOS::system::GetBoolParameter(ServiceConstants::IS_ENTERPRISE_DEVICE, false)) {
7168         LOG_W(BMS_TAG_INSTALLER, "not enterprise device, bundleName: %{public}s", bundleName.c_str());
7169         return false;
7170     }
7171     if (!InitDataMgr()) {
7172         return false;
7173     }
7174     InnerBundleInfo info;
7175     bool isAppExist = dataMgr_->FetchInnerBundleInfo(bundleName, info);
7176     if (isAppExist) {
7177         std::string appDistributionType = info.GetAppDistributionType();
7178         if (Constants::APP_DISTRIBUTION_TYPE_ENTERPRISE_MDM != appDistributionType &&
7179             Constants::APP_DISTRIBUTION_TYPE_ENTERPRISE_NORMAL != appDistributionType) {
7180             LOG_W(BMS_TAG_INSTALLER, "not enterprise app, bundleName: %{public}s", bundleName.c_str());
7181             return false;
7182         }
7183         return info.IsInstalledForAllUser();
7184     }
7185     LOG_W(BMS_TAG_INSTALLER, "app not exist: %{public}s", bundleName.c_str());
7186     return false;
7187 }
7188 
SetDisposedRuleWhenBundleUpdateStart(const std::unordered_map<std::string,InnerBundleInfo> & infos,const InnerBundleInfo & oldBundleInfo,bool isPreInstallApp)7189 bool BaseBundleInstaller::SetDisposedRuleWhenBundleUpdateStart(
7190     const std::unordered_map<std::string, InnerBundleInfo> &infos,
7191     const InnerBundleInfo &oldBundleInfo, bool isPreInstallApp)
7192 {
7193 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
7194     if (isPreInstallApp || !isAppExist_) {
7195         return false;
7196     }
7197     std::vector<std::string> oldModuleNames;
7198     oldBundleInfo.GetModuleNames(oldModuleNames);
7199     std::vector<std::string> newModuleNames;
7200     for (const auto &iter : infos) {
7201         iter.second.GetModuleNames(newModuleNames);
7202     }
7203     needSetDisposeRule_ = false;
7204     for (const auto &moduleName : oldModuleNames) {
7205         if (std::find(newModuleNames.begin(), newModuleNames.end(), moduleName) != newModuleNames.end()) {
7206             needSetDisposeRule_ = true;
7207             break;
7208         }
7209     }
7210     if (needSetDisposeRule_) {
7211         LOG_I(BMS_TAG_INSTALLER, "set bms disposed rule when -n :%{public}s install start",
7212             bundleName_.c_str());
7213         std::shared_ptr<AppControlManager> appControlMgr = DelayedSingleton<AppControlManager>::GetInstance();
7214         if (appControlMgr == nullptr) {
7215             LOG_E(BMS_TAG_INSTALLER, "appControlMgr is nullptr, when -n :%{public}s install start",
7216                 bundleName_.c_str());
7217             return false;
7218         }
7219         appControlMgr->SetDisposedRuleOnlyForBms(oldBundleInfo.GetAppId());
7220     }
7221     return needSetDisposeRule_;
7222 #else
7223     LOG_W(BMS_TAG_INSTALLER, "app control is disable");
7224     return false;
7225 #endif
7226 }
7227 
DeleteDisposedRuleWhenBundleUpdateEnd(const InnerBundleInfo & oldBundleInfo)7228 bool BaseBundleInstaller::DeleteDisposedRuleWhenBundleUpdateEnd(const InnerBundleInfo &oldBundleInfo)
7229 {
7230 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
7231     if (!needSetDisposeRule_) {
7232         return false;
7233     }
7234     LOG_I(BMS_TAG_INSTALLER, "delete bms disposed rule when -n :%{public}s install end", bundleName_.c_str());
7235     std::shared_ptr<AppControlManager> appControlMgr = DelayedSingleton<AppControlManager>::GetInstance();
7236     if (appControlMgr == nullptr) {
7237         LOG_E(BMS_TAG_INSTALLER, "appControlMgr is nullptr, when -n :%{public}s install end", bundleName_.c_str());
7238         return false;
7239     }
7240 
7241     appControlMgr->DeleteDisposedRuleOnlyForBms(oldBundleInfo.GetAppId());
7242     return true;
7243 #else
7244     LOG_W(BMS_TAG_INSTALLER, "app control is disable");
7245     return false;
7246 #endif
7247 }
7248 
SetDisposedRuleWhenBundleUninstallStart(const std::string & bundleName,const std::string & appId,bool isMultiUser)7249 bool BaseBundleInstaller::SetDisposedRuleWhenBundleUninstallStart(
7250     const std::string &bundleName, const std::string &appId, bool isMultiUser)
7251 {
7252 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
7253     if (isMultiUser) {
7254         return false;
7255     }
7256     LOG_I(BMS_TAG_INSTALLER, "set bms disposed rule when -n :%{public}s uninstall start",
7257         bundleName.c_str());
7258     std::shared_ptr<AppControlManager> appControlMgr = DelayedSingleton<AppControlManager>::GetInstance();
7259     if (appControlMgr == nullptr) {
7260         LOG_E(BMS_TAG_INSTALLER, "appControlMgr is nullptr, when -n :%{public}s uninstall start",
7261             bundleName.c_str());
7262         return false;
7263     }
7264     appControlMgr->SetDisposedRuleOnlyForBms(appId);
7265     return true;
7266 #else
7267     LOG_W(BMS_TAG_INSTALLER, "app control is disable");
7268     return false;
7269 #endif
7270 }
7271 
DeleteDisposedRuleWhenBundleUninstallEnd(const std::string & bundleName,const std::string & appId,bool isMultiUser)7272 bool BaseBundleInstaller::DeleteDisposedRuleWhenBundleUninstallEnd(
7273     const std::string &bundleName, const std::string &appId, bool isMultiUser)
7274 {
7275 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
7276     if (isMultiUser) {
7277         return false;
7278     }
7279     LOG_I(BMS_TAG_INSTALLER, "delete bms disposed rule when -n :%{public}s uninstall end", bundleName.c_str());
7280     std::shared_ptr<AppControlManager> appControlMgr = DelayedSingleton<AppControlManager>::GetInstance();
7281     if (appControlMgr == nullptr) {
7282         LOG_E(BMS_TAG_INSTALLER, "appControlMgr is nullptr, when -n :%{public}s uninstall end", bundleName.c_str());
7283         return false;
7284     }
7285     appControlMgr->DeleteDisposedRuleOnlyForBms(appId);
7286     return true;
7287 #else
7288     LOG_W(BMS_TAG_INSTALLER, "app control is disable");
7289     return false;
7290 #endif
7291 }
7292 
AddAppGalleryHapToTempPath(const bool isPreInstall,const std::unordered_map<std::string,InnerBundleInfo> & infos)7293 bool BaseBundleInstaller::AddAppGalleryHapToTempPath(const bool isPreInstall,
7294     const std::unordered_map<std::string, InnerBundleInfo> &infos)
7295 {
7296     if ((dataMgr_ == nullptr) || isPreInstall || infos.empty()) {
7297         LOG_D(BMS_TAG_INSTALLER, "no need to process");
7298         return false;
7299     }
7300     const InnerBundleInfo &bundleInfo = infos.begin()->second;
7301     if (!bundleInfo.IsSystemApp()) {
7302         LOG_D(BMS_TAG_INSTALLER, "not system app");
7303         return false;
7304     }
7305     std::string bundleName = OHOS::system::GetParameter(ServiceConstants::CLOUD_SHADER_OWNER, "");
7306     if (bundleName.empty()) {
7307         LOG_E(BMS_TAG_INSTALLER, "ag param get failed");
7308         return false;
7309     }
7310     if (bundleInfo.GetBundleName() != bundleName) {
7311         LOG_D(BMS_TAG_INSTALLER, "bundle %{public}s is not appGallery", bundleInfo.GetBundleName().c_str());
7312         return false;
7313     }
7314     std::string targetPath = BundleUtil::CreateTempDir(ServiceConstants::BMS_APP_COPY_TEMP_PATH);
7315     if (targetPath.empty()) {
7316         LOG_E(BMS_TAG_INSTALLER, "app copy temp path create failed %{public}d", errno);
7317         return false;
7318     }
7319     needDeleteAppTempPath_ = true;
7320     for (const auto &item : infos) {
7321         auto pos = item.first.rfind(ServiceConstants::FILE_SEPARATOR_CHAR);
7322         if (pos == std::string::npos) {
7323             LOG_E(BMS_TAG_INSTALLER, "path %{public}s may error", item.first.c_str());
7324             continue;
7325         }
7326         if (!BundleUtil::CopyFileFast(item.first, targetPath + item.first.substr(pos), true)) {
7327             LOG_E(BMS_TAG_INSTALLER, "copy hap %{public}s failed err %{public}d", item.first.c_str(), errno);
7328             return false;
7329         }
7330     }
7331     if (!BundleUtil::RenameFile(targetPath, ServiceConstants::BMS_APP_TEMP_PATH)) {
7332         LOG_E(BMS_TAG_INSTALLER, "rename app temp path failed %{public}d", errno);
7333         return false;
7334     }
7335 
7336     LOG_I(BMS_TAG_INSTALLER, "copy hap file to app_temp end");
7337     return true;
7338 }
7339 
DeleteAppGalleryHapFromTempPath()7340 bool BaseBundleInstaller::DeleteAppGalleryHapFromTempPath()
7341 {
7342     if (!needDeleteAppTempPath_) {
7343         return true;
7344     }
7345     if (!BundleUtil::DeleteDir(ServiceConstants::BMS_APP_TEMP_PATH)) {
7346         LOG_E(BMS_TAG_INSTALLER, "delete app_temp failed %{public}d", errno);
7347         return false;
7348     }
7349     if (!BundleUtil::DeleteDir(ServiceConstants::BMS_APP_COPY_TEMP_PATH)) {
7350         LOG_E(BMS_TAG_INSTALLER, "delete app_copy_temp failed %{public}d", errno);
7351         return false;
7352     }
7353     LOG_I(BMS_TAG_INSTALLER, "delete app_temp file end");
7354     return true;
7355 }
7356 
CheckPreBundle(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,const InstallParam & installParam,bool isRecover)7357 void BaseBundleInstaller::CheckPreBundle(const std::unordered_map<std::string, InnerBundleInfo> &newInfos,
7358     const InstallParam &installParam, bool isRecover)
7359 {
7360     if (newInfos.empty() || isRecover || installParam.isPreInstallApp) {
7361         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "newInfos is null or no need to check");
7362         return;
7363     }
7364     // check is system app or not
7365     const auto &newInfo = newInfos.begin()->second;
7366     std::string bundleName = newInfo.GetBundleName();
7367     if (!newInfo.IsSystemApp()) {
7368         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "%{public}s not system app", bundleName.c_str());
7369         return;
7370     }
7371     // check is uninstalled preset app or not
7372     if (dataMgr_->IsBundleExist(bundleName)) {
7373         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "%{public}s has installed", bundleName.c_str());
7374         return;
7375     }
7376     PreInstallBundleInfo preInstallBundleInfo;
7377     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
7378         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "%{public}s not preset app", bundleName.c_str());
7379         return;
7380     }
7381     if (preInstallBundleInfo.GetBundlePaths().empty()) {
7382         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "preset app bundle path empty");
7383         return;
7384     }
7385     // check identifier and appId
7386     std::string hapPath = preInstallBundleInfo.GetBundlePaths().front();
7387     Security::Verify::HapVerifyResult hapVerifyResult;
7388     ErrCode result = BundleVerifyMgr::HapVerify(hapPath, hapVerifyResult);
7389     if (result != ERR_OK) {
7390         LOG_NOFUNC_W(BMS_TAG_INSTALLER, "get preset app's appId fail %{public}s", hapPath.c_str());
7391         return;
7392     }
7393     Security::Verify::ProvisionInfo provisionInfo = hapVerifyResult.GetProvisionInfo();
7394     if (CheckAppIdentifier(provisionInfo.bundleInfo.appIdentifier, newInfo.GetAppIdentifier(),
7395         provisionInfo.appId, newInfo.GetProvisionId())) {
7396         LOG_NOFUNC_I(BMS_TAG_INSTALLER, "%{public}s need recover before install", bundleName.c_str());
7397         InstallParam userInstallParam;
7398         userInstallParam.userId = installParam.userId;
7399         userInstallParam.installFlag = InstallFlag::REPLACE_EXISTING;
7400         BaseBundleInstaller installer;
7401         result = installer.Recover(bundleName, userInstallParam);
7402         isPreBundleRecovered_ = (result == ERR_OK);
7403         if (!isPreBundleRecovered_) {
7404             LOG_NOFUNC_E(BMS_TAG_INSTALLER, "recover before install result: %{public}d", result);
7405         }
7406         return;
7407     }
7408     LOG_NOFUNC_W(BMS_TAG_INSTALLER, "%{public}s appId or appIdentifier not same with preset app, need not recover",
7409         bundleName.c_str());
7410 }
7411 
CheckShellCanInstallPreApp(const std::unordered_map<std::string,InnerBundleInfo> & newInfos)7412 ErrCode BaseBundleInstaller::CheckShellCanInstallPreApp(
7413     const std::unordered_map<std::string, InnerBundleInfo> &newInfos)
7414 {
7415     if (sysEventInfo_.callingUid != ServiceConstants::SHELL_UID) {
7416         return ERR_OK;
7417     }
7418     if (newInfos.empty()) {
7419         return ERR_OK;
7420     }
7421     std::string bundleName = newInfos.begin()->second.GetBundleName();
7422     if (dataMgr_->IsBundleExist(bundleName)) {
7423         return ERR_OK;
7424     }
7425     PreInstallBundleInfo preInstallBundleInfo;
7426     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
7427         return ERR_OK;
7428     }
7429     if (preInstallBundleInfo.GetBundlePaths().empty()) {
7430         LOG_NOFUNC_W(BMS_TAG_DEFAULT, "pre bundle path empty");
7431         return ERR_OK;
7432     }
7433     std::string hapPath = preInstallBundleInfo.GetBundlePaths().front();
7434     Security::Verify::HapVerifyResult hapVerifyResult;
7435     ErrCode verifyRes = BundleVerifyMgr::HapVerify(hapPath, hapVerifyResult);
7436     if (verifyRes != ERR_OK) {
7437         LOG_NOFUNC_W(BMS_TAG_DEFAULT, "get appId fail %{public}s", hapPath.c_str());
7438         return ERR_OK;
7439     }
7440     Security::Verify::ProvisionInfo provisionInfo = hapVerifyResult.GetProvisionInfo();
7441     if (CheckAppIdentifier(provisionInfo.bundleInfo.appIdentifier, newInfos.begin()->second.GetAppIdentifier(),
7442         provisionInfo.appId, newInfos.begin()->second.GetProvisionId())) {
7443         return ERR_OK;
7444     }
7445     LOG_E(BMS_TAG_DEFAULT, "%{public}s appId or appIdentifier not same with preinstalled app",
7446         newInfos.begin()->second.GetBundleName().c_str());
7447     return ERR_APPEXECFWK_INSTALL_APPID_NOT_SAME_WITH_PREINSTALLED;
7448 }
7449 
RecoverHapToken(const std::string & bundleName,const int32_t userId,Security::AccessToken::AccessTokenIDEx & accessTokenIdEx,const InnerBundleInfo & innerBundleInfo)7450 bool BaseBundleInstaller::RecoverHapToken(const std::string &bundleName, const int32_t userId,
7451     Security::AccessToken::AccessTokenIDEx& accessTokenIdEx, const InnerBundleInfo &innerBundleInfo)
7452 {
7453     UninstallBundleInfo uninstallBundleInfo;
7454     if (!dataMgr_->GetUninstallBundleInfo(bundleName, uninstallBundleInfo)) {
7455         return false;
7456     }
7457     LOG_I(BMS_TAG_INSTALLER, "bundleName:%{public}s getUninstallBundleInfo success", bundleName.c_str());
7458     if (uninstallBundleInfo.userInfos.empty()) {
7459         LOG_W(BMS_TAG_INSTALLER, "bundleName:%{public}s empty userInfos", bundleName.c_str());
7460         return false;
7461     }
7462     if (uninstallBundleInfo.userInfos.find(std::to_string(userId)) != uninstallBundleInfo.userInfos.end()) {
7463         accessTokenIdEx.tokenIdExStruct.tokenID =
7464             uninstallBundleInfo.userInfos.at(std::to_string(userId)).accessTokenId;
7465         accessTokenIdEx.tokenIDEx = uninstallBundleInfo.userInfos.at(std::to_string(userId)).accessTokenIdEx;
7466         Security::AccessToken::HapInfoCheckResult checkResult;
7467         if (BundlePermissionMgr::UpdateHapToken(accessTokenIdEx, innerBundleInfo, userId, checkResult,
7468             verifyRes_.GetProvisionInfo().appServiceCapabilities) == ERR_OK) {
7469             return true;
7470         } else {
7471             LOG_W(BMS_TAG_INSTALLER, "bundleName:%{public}s UpdateHapToken failed", bundleName.c_str());
7472             SetVerifyPermissionResult(checkResult);
7473         }
7474     }
7475     return false;
7476 }
7477 
GetAssetAccessGroups(const std::string & bundleName)7478 std::string BaseBundleInstaller::GetAssetAccessGroups(const std::string &bundleName)
7479 {
7480     if (!InitDataMgr()) {
7481         LOG_E(BMS_TAG_INSTALLER, "DataMgr null");
7482         return Constants::EMPTY_STRING;
7483     }
7484     std::vector<std::string> assetAccessGroups;
7485     ErrCode ret = dataMgr_->GetAssetAccessGroups(bundleName, assetAccessGroups);
7486     if (ret != ERR_OK) {
7487         LOG_E(BMS_TAG_INSTALLER, "GetAssetAccessGroups failed, ret=%{public}d", ret);
7488         return Constants::EMPTY_STRING;
7489     }
7490     std::string assetAccessGroupsStr;
7491     if (!assetAccessGroups.empty()) {
7492         std::stringstream assetAccessGroupsStream;
7493         std::copy(assetAccessGroups.begin(), assetAccessGroups.end(),
7494             std::ostream_iterator<std::string>(assetAccessGroupsStream, ","));
7495         assetAccessGroupsStr = assetAccessGroupsStream.str();
7496         if (!assetAccessGroupsStr.empty()) {
7497             assetAccessGroupsStr.pop_back();
7498         }
7499     }
7500     return assetAccessGroupsStr;
7501 }
7502 
GetDeveloperId(const std::string & bundleName)7503 std::string BaseBundleInstaller::GetDeveloperId(const std::string &bundleName)
7504 {
7505     if (!InitDataMgr()) {
7506         LOG_E(BMS_TAG_INSTALLER, "DataMgr null");
7507         return Constants::EMPTY_STRING;
7508     }
7509     std::string developerId;
7510     ErrCode ret = dataMgr_->GetDeveloperId(bundleName, developerId);
7511     if (ret != ERR_OK) {
7512         LOG_E(BMS_TAG_INSTALLER, "GetDeveloperId failed, ret=%{public}d", ret);
7513     }
7514     return developerId;
7515 }
7516 
GetModuleNames(const std::string & bundleName,std::vector<std::string> & moduleNames)7517 void BaseBundleInstaller::GetModuleNames(const std::string &bundleName, std::vector<std::string> &moduleNames)
7518 {
7519     if (!InitDataMgr()) {
7520         LOG_E(BMS_TAG_INSTALLER, "DataMgr null");
7521         return;
7522     }
7523     dataMgr_->GetBundleModuleNames(bundleName, moduleNames);
7524 }
7525 
UpdateKillApplicationProcess(const InnerBundleInfo & oldInfo)7526 void BaseBundleInstaller::UpdateKillApplicationProcess(const InnerBundleInfo &oldInfo)
7527 {
7528     if (!InitDataMgr()) {
7529         LOG_E(BMS_TAG_INSTALLER, "DataMgr null");
7530         return;
7531     }
7532     auto currentBundleUserIds = dataMgr_->GetUserIds(bundleName_);
7533     //kill the bundle process in all user during updating
7534     for (auto userId : currentBundleUserIds) {
7535         // kill the bundle process during updating
7536         if (!AbilityManagerHelper::UninstallApplicationProcesses(
7537             oldInfo.GetApplicationName(), oldInfo.GetUid(userId), true)) {
7538             LOG_W(BMS_TAG_INSTALLER, "fail to kill running application");
7539         }
7540         InnerBundleUserInfo userInfo;
7541         if (!oldInfo.GetInnerBundleUserInfo(userId, userInfo)) {
7542             LOG_W(BMS_TAG_INSTALLER, "the origin application is not installed at current user");
7543             continue;
7544         }
7545         for (auto &cloneInfo : userInfo.cloneInfos) {
7546             if (!AbilityManagerHelper::UninstallApplicationProcesses(
7547                 oldInfo.GetApplicationName(), cloneInfo.second.uid, true, atoi(cloneInfo.first.c_str()))) {
7548                 LOG_W(BMS_TAG_INSTALLER, "fail to kill clone application");
7549             }
7550         }
7551     }
7552 }
7553 
CheckPreAppAllowHdcInstall(const InstallParam & installParam,const std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)7554 ErrCode BaseBundleInstaller::CheckPreAppAllowHdcInstall(const InstallParam &installParam,
7555     const std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes)
7556 {
7557     if (!installParam.isCallByShell || sysEventInfo_.callingUid == Constants::ROOT_UID) {
7558         return ERR_OK;
7559     }
7560 
7561     if (hapVerifyRes.empty()) {
7562         return ERR_OK;
7563     }
7564 
7565     Security::Verify::ProvisionInfo provisionInfo = hapVerifyRes.begin()->GetProvisionInfo();
7566     if (provisionInfo.isOpenHarmony) {
7567         return ERR_OK;
7568     }
7569 
7570     if (provisionInfo.distributionType != Security::Verify::AppDistType::OS_INTEGRATION) {
7571         return ERR_OK;
7572     }
7573 
7574     if (provisionInfo.type != Security::Verify::ProvisionType::RELEASE) {
7575         return ERR_OK;
7576     }
7577 
7578     auto privileges = provisionInfo.appPrivilegeCapabilities;
7579     if (find(privileges.begin(), privileges.end(), PRIVILEGE_ALLOW_HDC_INSTALL) != privileges.end()) {
7580         return ERR_OK;
7581     }
7582 
7583     if (IsRdDevice()) {
7584         return ERR_OK;
7585     }
7586     return ERR_APPEXECFWK_INSTALL_OS_INTEGRATION_BUNDLE_NOT_ALLOWED_FOR_SHELL;
7587 }
7588 
IsAllowEnterPrise()7589 bool BaseBundleInstaller::IsAllowEnterPrise()
7590 {
7591     if (!OHOS::system::GetBoolParameter(ServiceConstants::ALLOW_ENTERPRISE_BUNDLE, false) &&
7592         !OHOS::system::GetBoolParameter(ServiceConstants::IS_ENTERPRISE_DEVICE, false)) {
7593         LOG_E(BMS_TAG_INSTALLER, "not enterprise device or developer mode is off");
7594         return false;
7595     }
7596     return true;
7597 }
7598 
MarkIsForceUninstall(const std::string & bundleName,bool isForceUninstalled)7599 void BaseBundleInstaller::MarkIsForceUninstall(const std::string &bundleName, bool isForceUninstalled)
7600 {
7601     if (!dataMgr_) {
7602         LOG_E(BMS_TAG_INSTALLER, "dataMgr is nullptr");
7603         return;
7604     }
7605 
7606     PreInstallBundleInfo preInstallBundleInfo;
7607     preInstallBundleInfo.SetBundleName(bundleName);
7608     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
7609         LOG_D(BMS_TAG_INSTALLER, "No PreInstallBundleInfo(%{public}s) in db", bundleName.c_str());
7610         return;
7611     }
7612     if (isForceUninstalled) {
7613         preInstallBundleInfo.AddForceUnisntalledUser(userId_);
7614         dataMgr_->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
7615     }
7616     return;
7617 }
7618 
CheckCanInstallPreBundle(const std::string & bundleName,const int32_t userId)7619 bool BaseBundleInstaller::CheckCanInstallPreBundle(const std::string &bundleName, const int32_t userId)
7620 {
7621     if (!InitDataMgr()) {
7622         LOG_E(BMS_TAG_INSTALLER, "DataMgr null");
7623         return false;
7624     }
7625     PreInstallBundleInfo preInstallBundleInfo;
7626     preInstallBundleInfo.SetBundleName(bundleName);
7627     dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo);
7628     if (!preInstallBundleInfo.HasForceUninstalledUser(userId)) {
7629         LOG_D(BMS_TAG_INSTALLER, "GetBundleNameForUid %{public}s is not forceuninstalled in  %{public}d",
7630             bundleName.c_str(), userId);
7631         return true;
7632     }
7633     return false;
7634 }
7635 
CheckPreBundleRecoverResult(ErrCode & result)7636 void BaseBundleInstaller::CheckPreBundleRecoverResult(ErrCode &result)
7637 {
7638     if (isPreBundleRecovered_ && result != ERR_OK && sysEventInfo_.callingUid != ServiceConstants::SHELL_UID &&
7639         sysEventInfo_.callingUid != Constants::ROOT_UID) {
7640         LOG_E(BMS_TAG_INSTALLER, "install failed, result = %{public}d, only restore to preinstalled", result);
7641         result = ERR_APPEXECFWK_INSTALL_FAILED_AND_RESTORE_TO_PREINSTALLED;
7642     }
7643 }
7644 
RemovePluginOnlyInCurrentUser(const InnerBundleInfo & info)7645 void BaseBundleInstaller::RemovePluginOnlyInCurrentUser(const InnerBundleInfo &info)
7646 {
7647     InnerBundleUserInfo userInfo;
7648     std::string hostBundleName = info.GetBundleName();
7649     if (!info.GetInnerBundleUserInfo(userId_, userInfo)) {
7650         LOG_E(BMS_TAG_INSTALLER, "%{public}s get user %{public}d failed",
7651             hostBundleName.c_str(), userId_);
7652         return;
7653     }
7654     if (!InitDataMgr()) {
7655         return;
7656     }
7657     std::unordered_map<std::string, PluginBundleInfo> pluginBundleInfos = info.GetAllPluginBundleInfo();
7658     for (const auto &pluginName : userInfo.installedPluginSet) {
7659         if (info.HasMultiUserPlugin(pluginName)) {
7660             continue;
7661         }
7662         LOG_I(BMS_TAG_INSTALLER, "%{public}s remove plugin %{public}s", hostBundleName.c_str(), pluginName.c_str());
7663         if (dataMgr_->RemovePluginInfo(hostBundleName, pluginName, userId_) != ERR_OK) {
7664             LOG_E(BMS_TAG_INSTALLER, "remove plugin %{public}s fail when uninstall %{public}s",
7665                 pluginName.c_str(), hostBundleName.c_str());
7666             continue;
7667         }
7668         auto it = pluginBundleInfos.find(pluginName);
7669         if (it == pluginBundleInfos.end()) {
7670             LOG_E(BMS_TAG_INSTALLER, "can not find plugin %{public}s when uninstall %{public}s",
7671                 pluginName.c_str(), hostBundleName.c_str());
7672             continue;
7673         }
7674         if ((InstalldClient::GetInstance()->RemoveDir(it->second.codePath)) != ERR_OK) {
7675             LOG_E(BMS_TAG_INSTALLER, "delete dir %{public}s failed", it->second.codePath.c_str());
7676         }
7677     }
7678 }
7679 
GetModulePath(const InnerBundleInfo & info,const bool isBundleUpdate,const bool isModuleUpdate)7680 std::string BaseBundleInstaller::GetModulePath(
7681     const InnerBundleInfo &info, const bool isBundleUpdate, const bool isModuleUpdate)
7682 {
7683     if (isBundleUpdate) {
7684         return std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
7685             std::string(ServiceConstants::BUNDLE_NEW_CODE_DIR) + info.GetBundleName() +
7686             ServiceConstants::PATH_SEPARATOR + info.GetCurrentModulePackage();
7687     }
7688     if (isModuleUpdate) {
7689         return info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR +
7690             info.GetCurrentModulePackage() + ServiceConstants::TMP_SUFFIX;
7691     }
7692     return info.GetAppCodePath() + ServiceConstants::PATH_SEPARATOR + info.GetCurrentModulePackage();
7693 }
7694 
ProcessBundleCodePath(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,const InnerBundleInfo & oldInfo,const std::string & bundleName,const bool isBundleUpdate,const bool needCopyHap)7695 ErrCode BaseBundleInstaller::ProcessBundleCodePath(
7696     const std::unordered_map<std::string, InnerBundleInfo> &newInfos,
7697     const InnerBundleInfo &oldInfo, const std::string &bundleName,
7698     const bool isBundleUpdate, const bool needCopyHap)
7699 {
7700     if (!isBundleUpdate) {
7701         // move so file to real installation dir
7702         bool needDeleteOldLibraryPath = NeedDeleteOldNativeLib(newInfos, oldInfo);
7703         auto result = MoveSoFileToRealInstallationDir(newInfos, needDeleteOldLibraryPath);
7704         CHECK_RESULT(result, "move so file to install path failed %{public}d");
7705         result = FinalProcessHapAndSoForBundleUpdate(newInfos, needCopyHap, needDeleteOldLibraryPath);
7706         CHECK_RESULT(result, "final process hap and so failed %{public}d");
7707         // attention pls, rename operation shoule be almost the last operation to guarantee the rollback operation
7708         // when someone failure occurs in the installation flow
7709         result = RenameAllTempDir(newInfos);
7710         CHECK_RESULT(result, "rename temp dirs failed with result %{public}d");
7711         return result;
7712     }
7713     LOG_I(BMS_TAG_INSTALLER, "bundle %{public}s processBundleCodePath start", bundleName.c_str());
7714     // rename real code path to +old- code path
7715     std::string realAppCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
7716         bundleName;
7717     std::string oldAppCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
7718         std::string(ServiceConstants::BUNDLE_OLD_CODE_DIR) + bundleName;
7719     auto result = InstalldClient::GetInstance()->RenameModuleDir(realAppCodePath, oldAppCodePath);
7720     CHECK_RESULT(result, "rename real to +old- code path failed, error is %{public}d");
7721     InstallExceptionInfo exceptionInfo;
7722     exceptionInfo.status = InstallRenameExceptionStatus::RENAME_RELA_TO_OLD_PATH;
7723     exceptionInfo.versionCode = oldInfo.GetVersionCode();
7724     result = DelayedSingleton<InstallExceptionMgr>::GetInstance()->SaveBundleExceptionInfo(bundleName,
7725         exceptionInfo);
7726     if (result != ERR_OK) {
7727         LOG_W(BMS_TAG_INSTALLER, "save bundle exception failed, error is %{public}d", result);
7728     }
7729     // rename +new- code path to real code path
7730     std::string newAppCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
7731         std::string(ServiceConstants::BUNDLE_NEW_CODE_DIR) + bundleName;
7732     result = InstalldClient::GetInstance()->RenameModuleDir(newAppCodePath, realAppCodePath);
7733     CHECK_RESULT(result, "rename +new- to real code path failed, error is %{public}d");
7734 
7735     exceptionInfo.status = InstallRenameExceptionStatus::RENAME_NEW_TO_RELA_PATH;
7736     result = DelayedSingleton<InstallExceptionMgr>::GetInstance()->SaveBundleExceptionInfo(bundleName,
7737         exceptionInfo);
7738     if (result != ERR_OK) {
7739         LOG_E(BMS_TAG_INSTALLER, "save bundle exception failed, error is %{public}d", result);
7740     }
7741     // rename so path
7742     result = MoveSoFileToRealInstallationDir(newInfos, false);
7743     CHECK_RESULT(result, "move so file to install path failed %{public}d");
7744     RemoveEmptyDirs(newInfos);
7745     for (const auto &item : newInfos) {
7746         RemoveTempPathOnlyUsedForSo(item.second);
7747     }
7748     // process dynamic icon file
7749     result = ProcessDynamicIconFileWhenUpdate(oldInfo, oldAppCodePath, realAppCodePath);
7750     if (result != ERR_OK) {
7751         APP_LOGE("copy extend resource to install path failed %{public}d", result);
7752     }
7753     LOG_I(BMS_TAG_INSTALLER, "bundle %{public}s processBundleCodePath end", bundleName.c_str());
7754     return ERR_OK;
7755 }
7756 
ProcessDynamicIconFileWhenUpdate(const InnerBundleInfo & oldInfo,const std::string & oldPath,const std::string & newPath)7757 ErrCode BaseBundleInstaller::ProcessDynamicIconFileWhenUpdate(
7758     const InnerBundleInfo &oldInfo,
7759     const std::string &oldPath,
7760     const std::string &newPath)
7761 {
7762     auto extendResourceInfos = oldInfo.GetExtendResourceInfos();
7763     if (extendResourceInfos.empty()) {
7764         return ERR_OK;
7765     }
7766     APP_LOGI("-n %{public}s has dynamic icon, process start", oldInfo.GetBundleName().c_str());
7767     std::string oldExtendResourcePath = oldPath + ServiceConstants::PATH_SEPARATOR +
7768         ServiceConstants::EXT_RESOURCE_FILE_PATH;
7769     bool isExtResource = false;
7770     InstalldClient::GetInstance()->IsExistDir(oldExtendResourcePath, isExtResource);
7771     if (!isExtResource) {
7772         APP_LOGW("-n %{public}s old ext_resource path not exist", oldInfo.GetBundleName().c_str());
7773         return ERR_OK;
7774     }
7775     std::string newExtendResourcePath = newPath + ServiceConstants::PATH_SEPARATOR +
7776         ServiceConstants::EXT_RESOURCE_FILE_PATH;
7777     auto result = InstalldClient::GetInstance()->CreateBundleDir(newExtendResourcePath);
7778     if (result != ERR_OK) {
7779         APP_LOGE("-n %{public}s create ext_resource failed", oldInfo.GetBundleName().c_str());
7780         return result;
7781     }
7782     for (const auto &extendResource : extendResourceInfos) {
7783         std::string fileName = ServiceConstants::PATH_SEPARATOR +extendResource.second.moduleName +
7784             ServiceConstants::HSP_FILE_SUFFIX;
7785         result = InstalldClient::GetInstance()->CopyFile(oldExtendResourcePath + fileName,
7786             newExtendResourcePath + fileName);
7787         if (result != ERR_OK) {
7788             APP_LOGE("-n %{public}s copy ext_resource failed", oldInfo.GetBundleName().c_str());
7789             return result;
7790         }
7791     }
7792     APP_LOGI("-n %{public}s has dynamic icon, process end", oldInfo.GetBundleName().c_str());
7793     return ERR_OK;
7794 }
7795 
ProcessOldCodePath(const std::string & bundleName,const bool isBundleUpdate)7796 void BaseBundleInstaller::ProcessOldCodePath(
7797     const std::string &bundleName, const bool isBundleUpdate)
7798 {
7799     if (!isBundleUpdate) {
7800         return;
7801     }
7802     LOG_I(BMS_TAG_INSTALLER, "bundle %{public}s ProcessOldCodePath start", bundleName.c_str());
7803     InstallExceptionInfo exceptionInfo;
7804     exceptionInfo.status = InstallRenameExceptionStatus::DELETE_OLD_PATH;
7805     ErrCode result = DelayedSingleton<InstallExceptionMgr>::GetInstance()->SaveBundleExceptionInfo(bundleName,
7806         exceptionInfo);
7807     if (result != ERR_OK) {
7808         LOG_W(BMS_TAG_INSTALLER, "save bundle exception failed, error is %{public}d", result);
7809     }
7810     // delete +old- code path
7811     std::string oldAppCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
7812         std::string(ServiceConstants::BUNDLE_OLD_CODE_DIR) + bundleName;
7813     result = InstalldClient::GetInstance()->RemoveDir(oldAppCodePath);
7814     if (result != ERR_OK) {
7815         LOG_W(BMS_TAG_INSTALLER, "remove bundle %{public}s old code path error is %{public}d",
7816             bundleName.c_str(), result);
7817     }
7818     result = DelayedSingleton<InstallExceptionMgr>::GetInstance()->DeleteBundleExceptionInfo(bundleName);
7819     if (result != ERR_OK) {
7820         LOG_W(BMS_TAG_INSTALLER, "delete bundle %{public}s exception error is %{public}d",
7821             bundleName.c_str(), result);
7822     }
7823     LOG_I(BMS_TAG_INSTALLER, "bundle %{public}s ProcessOldCodePath end", bundleName.c_str());
7824 }
7825 
RollbackCodePath(const std::string & bundleName,bool isBundleUpdate)7826 void BaseBundleInstaller::RollbackCodePath(const std::string &bundleName, bool isBundleUpdate)
7827 {
7828     if (!isBundleUpdate) {
7829         return;
7830     }
7831     // rename +old- to real code path
7832     std::string realAppCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
7833         bundleName;
7834     std::string oldAppCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
7835         std::string(ServiceConstants::BUNDLE_OLD_CODE_DIR) + bundleName;
7836     auto result = InstalldClient::GetInstance()->RenameModuleDir(oldAppCodePath, realAppCodePath);
7837     if (result != ERR_OK) {
7838         LOG_W(BMS_TAG_INSTALLER, "bundle %{public}s rename +old- to real code path failed, error is %{public}d",
7839             bundleName.c_str(), result);
7840     }
7841     // delete +new- code path
7842     std::string newAppCodePath = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR +
7843         std::string(ServiceConstants::BUNDLE_NEW_CODE_DIR) + bundleName;
7844     result = InstalldClient::GetInstance()->RemoveDir(newAppCodePath);
7845     if (result != ERR_OK) {
7846         LOG_W(BMS_TAG_INSTALLER, "bundle %{public}s remove +new- code path failed, error is %{public}d",
7847             bundleName.c_str(), result);
7848     }
7849     (void)DelayedSingleton<InstallExceptionMgr>::GetInstance()->DeleteBundleExceptionInfo(bundleName);
7850 }
7851 
InnerProcessTargetSoPath(const InnerBundleInfo & info,const bool isBundleUpdate,const std::string & modulePath,std::string & nativeLibraryPath,std::string & targetSoPath)7852 void BaseBundleInstaller::InnerProcessTargetSoPath(const InnerBundleInfo &info, const bool isBundleUpdate,
7853     const std::string &modulePath, std::string &nativeLibraryPath, std::string &targetSoPath)
7854 {
7855     bool isLibIsolated = info.IsLibIsolated(info.GetCurModuleName());
7856     // extract so file: if hap so is not isolated, then extract so to tmp path.
7857     if (isLibIsolated) {
7858         if (BundleUtil::EndWith(modulePath, ServiceConstants::TMP_SUFFIX)) {
7859             nativeLibraryPath = BuildTempNativeLibraryPath(nativeLibraryPath);
7860         }
7861     } else {
7862         nativeLibraryPath = info.GetCurrentModulePackage() + ServiceConstants::TMP_SUFFIX +
7863             ServiceConstants::PATH_SEPARATOR + nativeLibraryPath;
7864     }
7865     if (isBundleUpdate) {
7866         targetSoPath.append(Constants::BUNDLE_CODE_DIR).append(ServiceConstants::PATH_SEPARATOR)
7867             .append(ServiceConstants::BUNDLE_NEW_CODE_DIR).append(info.GetBundleName())
7868             .append(ServiceConstants::PATH_SEPARATOR).append(nativeLibraryPath)
7869             .append(ServiceConstants::PATH_SEPARATOR);
7870     } else {
7871         targetSoPath.append(Constants::BUNDLE_CODE_DIR).append(ServiceConstants::PATH_SEPARATOR)
7872             .append(info.GetBundleName()).append(ServiceConstants::PATH_SEPARATOR).append(nativeLibraryPath)
7873             .append(ServiceConstants::PATH_SEPARATOR);
7874     }
7875 }
7876 
RecoverOnDemandInstallBundle(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)7877 ErrCode BaseBundleInstaller::RecoverOnDemandInstallBundle(const std::string &bundleName,
7878     const InstallParam &installParam, int32_t &uid)
7879 {
7880     LOG_I(BMS_TAG_INSTALLER, "recover on demand install bundle -n: %{public}s", bundleName.c_str());
7881     PreInstallBundleInfo preInstallBundleInfo;
7882     preInstallBundleInfo.SetBundleName(bundleName);
7883     if (!OnDemandInstallDataMgr::GetInstance().GetOnDemandInstallBundleInfo(bundleName, preInstallBundleInfo)
7884         || preInstallBundleInfo.GetBundlePaths().empty()) {
7885         LOG_E(BMS_TAG_INSTALLER, "Get onDemandBundle failed, -n: %{public}s", bundleName.c_str());
7886         return ERR_APPEXECFWK_RECOVER_INVALID_BUNDLE_NAME;
7887     }
7888     LOG_D(BMS_TAG_INSTALLER, "Get on demand bundle success");
7889     std::vector<std::string> pathVec = preInstallBundleInfo.GetBundlePaths();
7890     auto innerInstallParam = installParam;
7891     innerInstallParam.needSavePreInstallInfo = true;
7892     innerInstallParam.isPreInstallApp = true;
7893     innerInstallParam.removable = true;
7894     innerInstallParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_PREINSTALLED_APP;
7895     innerInstallParam.isDataPreloadHap = IsDataPreloadHap(pathVec.empty() ? "" : pathVec.front());
7896     if (!innerInstallParam.isDataPreloadHap) {
7897         innerInstallParam.copyHapToInstallPath = false;
7898     }
7899     ErrCode result = ProcessBundleInstall(pathVec, innerInstallParam, preInstallBundleInfo.GetAppType(), uid, true);
7900     if (result == ERR_OK) {
7901         OnDemandInstallDataMgr::GetInstance().DeleteOnDemandInstallBundleInfo(bundleName);
7902     }
7903     return result;
7904 }
7905 
ProcessExtProfile(const InstallParam & installParam)7906 bool BaseBundleInstaller::ProcessExtProfile(const InstallParam &installParam)
7907 {
7908     auto extProfileDir = std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName_
7909         + ServiceConstants::PATH_SEPARATOR + ServiceConstants::EXT_PROFILE;
7910     std::string targetPath = extProfileDir + ServiceConstants::PATH_SEPARATOR + ServiceConstants::MANIFEST_JSON;
7911     auto iter = installParam.parameters.find(ServiceConstants::ENTERPRISE_MANIFEST);
7912     if ((iter == installParam.parameters.end()) || (iter->second.empty())) {
7913         bool isExtProfileExist = false;
7914         InstalldClient::GetInstance()->IsExistDir(extProfileDir, isExtProfileExist);
7915         if (isExtProfileExist) {
7916             if (RemoveModuleDir(targetPath) != ERR_OK) {
7917                 LOG_E(BMS_TAG_INSTALLER, "fail to delete ext profile file, error is %{public}d", errno);
7918                 return false;
7919             }
7920         }
7921         return true;
7922     }
7923     LOG_I(BMS_TAG_INSTALLER, "create ext profile dir %{public}s", extProfileDir.c_str());
7924     ErrCode result = InstalldClient::GetInstance()->CreateBundleDir(extProfileDir);
7925     if (result != ERR_OK) {
7926         LOG_E(BMS_TAG_INSTALLER, "fail to create ext profile dir, error is %{public}d", result);
7927         return false;
7928     }
7929     if (InstalldClient::GetInstance()->CopyFile(iter->second, targetPath) != ERR_OK) {
7930         LOG_E(BMS_TAG_INSTALLER, "copy file from %{public}s to %{public}s failed", iter->second.c_str(),
7931             targetPath.c_str());
7932         return false;
7933     }
7934     return true;
7935 }
7936 
SetHybridSpawn()7937 void BaseBundleInstaller::SetHybridSpawn()
7938 {
7939     if (!InitDataMgr()) {
7940         return;
7941     }
7942     InnerBundleInfo info;
7943     if (!dataMgr_->FetchInnerBundleInfo(bundleName_, info)) {
7944         LOG_E(BMS_TAG_INSTALLER, "Get innerBundleInfo failed");
7945         return;
7946     }
7947     std::string arkTSMode = info.GetApplicationArkTSMode();
7948     if (arkTSMode == Constants::ARKTS_MODE_STATIC || arkTSMode == Constants::ARKTS_MODE_HYBRID) {
7949         LOG_I(BMS_TAG_INSTALLER, "set persist.appspawn.hybridspawn.enable true");
7950         OHOS::system::SetParameter(ServiceConstants::HYBRID_SPAWN_ENABLE, BMS_TRUE);
7951     }
7952 }
7953 
IsBundleCrossAppSharedConfig(const std::unordered_map<std::string,InnerBundleInfo> & newInfos)7954 bool BaseBundleInstaller::IsBundleCrossAppSharedConfig(const std::unordered_map<std::string, InnerBundleInfo> &newInfos)
7955 {
7956     for (const auto &item : newInfos) {
7957         if (item.second.IsBundleCrossAppSharedConfig()) {
7958             return true;
7959         }
7960     }
7961     return false;
7962 }
7963 }  // namespace AppExecFwk
7964 }  // namespace OHOS
7965