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