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