• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "base_bundle_installer.h"
17 
18 #include <sys/stat.h>
19 #include <unordered_set>
20 #include "nlohmann/json.hpp"
21 
22 #include <unistd.h>
23 
24 #include "account_helper.h"
25 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
26 #include "aging/bundle_aging_mgr.h"
27 #endif
28 #include "aot/aot_handler.h"
29 #include "app_control_constants.h"
30 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
31 #include "default_app_mgr.h"
32 #endif
33 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
34 #include "quick_fix/app_quick_fix.h"
35 #include "quick_fix/inner_app_quick_fix.h"
36 #include "quick_fix/quick_fix_data_mgr.h"
37 #include "quick_fix/quick_fix_switcher.h"
38 #include "quick_fix/quick_fix_deleter.h"
39 #endif
40 #include "ability_manager_helper.h"
41 #include "app_log_wrapper.h"
42 #include "app_provision_info_manager.h"
43 #include "bms_extension_data_mgr.h"
44 #include "bundle_constants.h"
45 #include "bundle_extractor.h"
46 #include "bundle_mgr_service.h"
47 #include "bundle_sandbox_app_helper.h"
48 #include "bundle_permission_mgr.h"
49 #include "bundle_resource_helper.h"
50 #include "bundle_util.h"
51 #include "data_group_info.h"
52 #include "datetime_ex.h"
53 #include "driver_installer.h"
54 #include "hitrace_meter.h"
55 #include "installd_client.h"
56 #include "parameter.h"
57 #include "parameters.h"
58 #include "perf_profile.h"
59 #include "scope_guard.h"
60 #include "string_ex.h"
61 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
62 #include "bundle_overlay_data_manager.h"
63 #include "bundle_overlay_install_checker.h"
64 #endif
65 
66 #ifdef STORAGE_SERVICE_ENABLE
67 #include "storage_manager_proxy.h"
68 #endif
69 #include "iservice_registry.h"
70 
71 namespace OHOS {
72 namespace AppExecFwk {
73 using namespace OHOS::Security;
74 namespace {
75 const std::string ARK_CACHE_PATH = "/data/local/ark-cache/";
76 const std::string ARK_PROFILE_PATH = "/data/local/ark-profile/";
77 const std::string COMPILE_SDK_TYPE_OPEN_HARMONY = "OpenHarmony";
78 const std::string LOG = "log";
79 const std::string HSP_VERSION_PREFIX = "v";
80 const std::string PRE_INSTALL_HSP_PATH = "/shared_bundles/";
81 const std::string APP_INSTALL_PATH = "/data/app/el1/bundle";
82 const std::string DEBUG_APP_IDENTIFIER = "DEBUG_LIB_ID";
83 constexpr int32_t DATA_GROUP_DIR_MODE = 02770;
84 
85 #ifdef STORAGE_SERVICE_ENABLE
86 #ifdef QUOTA_PARAM_SET_ENABLE
87 const std::string SYSTEM_PARAM_ATOMICSERVICE_DATASIZE_THRESHOLD =
88     "persist.sys.bms.aging.policy.atomicservice.datasize.threshold";
89 const int32_t THRESHOLD_VAL_LEN = 20;
90 #endif // QUOTA_PARAM_SET_ENABLE
91 const int32_t STORAGE_MANAGER_MANAGER_ID = 5003;
92 #endif // STORAGE_SERVICE_ENABLE
93 const int32_t ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET = 50;
94 const int32_t SINGLE_HSP_VERSION = 1;
95 const char* BMS_KEY_SHELL_UID = "const.product.shell.uid";
96 const std::set<std::string> SINGLETON_WHITE_LIST = {
97     "com.ohos.sceneboard",
98     "com.ohos.callui",
99     "com.ohos.mms"
100 };
101 
GetHapPath(const InnerBundleInfo & info,const std::string & moduleName)102 std::string GetHapPath(const InnerBundleInfo &info, const std::string &moduleName)
103 {
104     std::string fileSuffix = Constants::INSTALL_FILE_SUFFIX;
105     auto moduleInfo = info.GetInnerModuleInfoByModuleName(moduleName);
106     if (moduleInfo && moduleInfo->distro.moduleType == Profile::MODULE_TYPE_SHARED) {
107         APP_LOGD("The module(%{public}s) is shared.", moduleName.c_str());
108         fileSuffix = Constants::HSP_FILE_SUFFIX;
109     }
110 
111     return info.GetAppCodePath() + Constants::PATH_SEPARATOR + moduleName + fileSuffix;
112 }
113 
GetHapPath(const InnerBundleInfo & info)114 std::string GetHapPath(const InnerBundleInfo &info)
115 {
116     return GetHapPath(info, info.GetModuleName(info.GetCurrentModulePackage()));
117 }
118 
BuildTempNativeLibraryPath(const std::string & nativeLibraryPath)119 std::string BuildTempNativeLibraryPath(const std::string &nativeLibraryPath)
120 {
121     auto position = nativeLibraryPath.find(Constants::PATH_SEPARATOR);
122     if (position == std::string::npos) {
123         return nativeLibraryPath;
124     }
125 
126     auto prefixPath = nativeLibraryPath.substr(0, position);
127     auto suffixPath = nativeLibraryPath.substr(position);
128     return prefixPath + Constants::TMP_SUFFIX + suffixPath;
129 }
130 } // namespace
131 
BaseBundleInstaller()132 BaseBundleInstaller::BaseBundleInstaller()
133     : bundleInstallChecker_(std::make_unique<BundleInstallChecker>()) {}
134 
~BaseBundleInstaller()135 BaseBundleInstaller::~BaseBundleInstaller()
136 {
137     bundlePaths_.clear();
138     BundleUtil::DeleteTempDirs(toDeleteTempHapPath_);
139     toDeleteTempHapPath_.clear();
140     signatureFileTmpMap_.clear();
141 }
142 
InstallBundle(const std::string & bundlePath,const InstallParam & installParam,const Constants::AppType appType)143 ErrCode BaseBundleInstaller::InstallBundle(
144     const std::string &bundlePath, const InstallParam &installParam, const Constants::AppType appType)
145 {
146     std::vector<std::string> bundlePaths { bundlePath };
147     return InstallBundle(bundlePaths, installParam, appType);
148 }
149 
InstallBundle(const std::vector<std::string> & bundlePaths,const InstallParam & installParam,const Constants::AppType appType)150 ErrCode BaseBundleInstaller::InstallBundle(
151     const std::vector<std::string> &bundlePaths, const InstallParam &installParam, const Constants::AppType appType)
152 {
153     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
154     APP_LOGI("begin to process bundle install");
155 
156     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
157 
158     int32_t uid = Constants::INVALID_UID;
159     ErrCode result = ProcessBundleInstall(bundlePaths, installParam, appType, uid);
160     if (installParam.needSendEvent && dataMgr_ && !bundleName_.empty()) {
161         NotifyBundleEvents installRes = {
162             .bundleName = bundleName_,
163             .modulePackage = moduleName_,
164             .abilityName = mainAbility_,
165             .resultCode = result,
166             .type = GetNotifyType(),
167             .uid = uid,
168             .accessTokenId = accessTokenId_,
169             .isModuleUpdate = isModuleUpdate_
170         };
171         if (installParam.allUser) {
172             AddBundleStatus(installRes);
173         } else if (NotifyBundleStatus(installRes) != ERR_OK) {
174             APP_LOGW("notify status failed for installation");
175         }
176     }
177 
178     if (result == ERR_OK) {
179         OnSingletonChange(installParam.noSkipsKill);
180     }
181 
182     if (!bundleName_.empty()) {
183         SendBundleSystemEvent(
184             bundleName_,
185             ((isAppExist_ && hasInstalledInUser_) ? BundleEventType::UPDATE : BundleEventType::INSTALL),
186             installParam,
187             sysEventInfo_.preBundleScene,
188             result);
189     }
190     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
191     APP_LOGD("finish to process bundle install");
192     return result;
193 }
194 
InstallBundleByBundleName(const std::string & bundleName,const InstallParam & installParam)195 ErrCode BaseBundleInstaller::InstallBundleByBundleName(
196     const std::string &bundleName, const InstallParam &installParam)
197 {
198     APP_LOGI("begin to process bundle install by bundleName, which is %{public}s.", bundleName.c_str());
199     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
200 
201     int32_t uid = Constants::INVALID_UID;
202     ErrCode result = ProcessInstallBundleByBundleName(bundleName, installParam, uid);
203     if (installParam.needSendEvent && dataMgr_ && !bundleName.empty()) {
204         NotifyBundleEvents installRes = {
205             .bundleName = bundleName,
206             .resultCode = result,
207             .type = NotifyType::INSTALL,
208             .uid = uid,
209             .accessTokenId = accessTokenId_
210         };
211         if (installParam.concentrateSendEvent) {
212             AddNotifyBundleEvents(installRes);
213         } else if (NotifyBundleStatus(installRes) != ERR_OK) {
214             APP_LOGW("notify status failed for installation");
215         }
216     }
217 
218     SendBundleSystemEvent(
219         bundleName,
220         BundleEventType::INSTALL,
221         installParam,
222         InstallScene::CREATE_USER,
223         result);
224     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
225     APP_LOGD("finish to process %{public}s bundle install", bundleName.c_str());
226     return result;
227 }
228 
Recover(const std::string & bundleName,const InstallParam & installParam)229 ErrCode BaseBundleInstaller::Recover(
230     const std::string &bundleName, const InstallParam &installParam)
231 {
232     APP_LOGI("begin to process bundle recover by bundleName, which is %{public}s.", bundleName.c_str());
233     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
234     if (!BundlePermissionMgr::Init()) {
235         APP_LOGW("BundlePermissionMgr::Init failed");
236     }
237     int32_t uid = Constants::INVALID_UID;
238     ErrCode result = ProcessRecover(bundleName, installParam, uid);
239     if (installParam.needSendEvent && dataMgr_ && !bundleName_.empty() && !modulePackage_.empty()) {
240         NotifyBundleEvents installRes = {
241             .bundleName = bundleName,
242             .resultCode = result,
243             .type = NotifyType::INSTALL,
244             .uid = uid,
245             .accessTokenId = accessTokenId_
246         };
247         if (NotifyBundleStatus(installRes) != ERR_OK) {
248             APP_LOGW("notify status failed for installation");
249         }
250     }
251 
252     auto recoverInstallParam = installParam;
253     recoverInstallParam.isPreInstallApp = true;
254     SendBundleSystemEvent(
255         bundleName,
256         BundleEventType::RECOVER,
257         recoverInstallParam,
258         sysEventInfo_.preBundleScene,
259         result);
260     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
261     BundlePermissionMgr::UnInit();
262     APP_LOGD("finish to process %{public}s bundle recover", bundleName.c_str());
263     return result;
264 }
265 
UninstallBundle(const std::string & bundleName,const InstallParam & installParam)266 ErrCode BaseBundleInstaller::UninstallBundle(const std::string &bundleName, const InstallParam &installParam)
267 {
268     APP_LOGI("begin to process %{public}s bundle uninstall", bundleName.c_str());
269     PerfProfile::GetInstance().SetBundleUninstallStartTime(GetTickCount());
270 
271     // uninstall all sandbox app before
272     UninstallAllSandboxApps(bundleName, installParam.userId);
273 
274     int32_t uid = Constants::INVALID_UID;
275     bool isUninstalledFromBmsExtension = false;
276     ErrCode result = ProcessBundleUninstall(bundleName, installParam, uid);
277     if ((result == ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE) &&
278         (UninstallBundleFromBmsExtension(bundleName) == ERR_OK)) {
279         isUninstalledFromBmsExtension = true;
280         result = ERR_OK;
281     }
282     if (installParam.needSendEvent && dataMgr_) {
283         NotifyBundleEvents installRes = {
284             .bundleName = bundleName,
285             .resultCode = result,
286             .type = NotifyType::UNINSTALL_BUNDLE,
287             .uid = uid,
288             .accessTokenId = accessTokenId_,
289             .isAgingUninstall = installParam.isAgingUninstall,
290             .isBmsExtensionUninstalled = isUninstalledFromBmsExtension,
291             .appId = uninstallBundleAppId_
292         };
293 
294         if (installParam.concentrateSendEvent) {
295             AddNotifyBundleEvents(installRes);
296         } else if (NotifyBundleStatus(installRes) != ERR_OK) {
297             APP_LOGW("notify status failed for installation");
298         }
299     }
300 
301     if (result == ERR_OK) {
302 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
303         DefaultAppMgr::GetInstance().HandleUninstallBundle(userId_, bundleName);
304 #endif
305     }
306 
307     SendBundleSystemEvent(
308         bundleName,
309         BundleEventType::UNINSTALL,
310         installParam,
311         sysEventInfo_.preBundleScene,
312         result);
313     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
314     APP_LOGD("finish to process %{public}s bundle uninstall", bundleName.c_str());
315     return result;
316 }
317 
UninstallBundleByUninstallParam(const UninstallParam & uninstallParam)318 ErrCode BaseBundleInstaller::UninstallBundleByUninstallParam(const UninstallParam &uninstallParam)
319 {
320     APP_LOGI("begin to process cross-app bundle %{public}s uninstall", uninstallParam.bundleName.c_str());
321     std::string bundleName = uninstallParam.bundleName;
322     int32_t versionCode = uninstallParam.versionCode;
323     if (bundleName.empty()) {
324         APP_LOGE("uninstall bundle name or module name empty");
325         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_NOT_EXIST;
326     }
327 
328     dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
329     if (!dataMgr_) {
330         APP_LOGE("Get dataMgr shared_ptr nullptr");
331         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
332     }
333     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
334     std::lock_guard lock {mtx};
335     InnerBundleInfo info;
336     if (!dataMgr_->GetInnerBundleInfo(bundleName, info)) {
337         APP_LOGE("uninstall bundle info missing");
338         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_NOT_EXIST;
339     }
340     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); });
341     if (!info.GetRemovable()) {
342         APP_LOGE("uninstall system app");
343         return ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR;
344     }
345     if (info.GetApplicationBundleType() != BundleType::SHARED) {
346         APP_LOGE("uninstall bundle is not shared library");
347         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_NOT_EXIST;
348     }
349     if (dataMgr_->CheckHspVersionIsRelied(versionCode, info)) {
350         APP_LOGE("uninstall shared library is relied");
351         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_RELIED;
352     }
353     // if uninstallParam do not contain versionCode, versionCode is ALL_VERSIONCODE
354     std::vector<uint32_t> versionCodes = info.GetAllHspVersion();
355     if (versionCode != Constants::ALL_VERSIONCODE &&
356         std::find(versionCodes.begin(), versionCodes.end(), versionCode) == versionCodes.end()) {
357         APP_LOGE("input versionCode is not exist");
358         return ERR_APPEXECFWK_UNINSTALL_SHARE_APP_LIBRARY_IS_NOT_EXIST;
359     }
360     std::string uninstallDir = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName;
361     if ((versionCodes.size() > SINGLE_HSP_VERSION && versionCode == Constants::ALL_VERSIONCODE) ||
362         versionCodes.size() == SINGLE_HSP_VERSION) {
363         return UninstallHspBundle(uninstallDir, info.GetBundleName());
364     } else {
365         uninstallDir += Constants::PATH_SEPARATOR + HSP_VERSION_PREFIX + std::to_string(versionCode);
366         return UninstallHspVersion(uninstallDir, versionCode, info);
367     }
368 }
369 
UninstallHspBundle(std::string & uninstallDir,const std::string & bundleName)370 ErrCode BaseBundleInstaller::UninstallHspBundle(std::string &uninstallDir, const std::string &bundleName)
371 {
372     APP_LOGD("begin to process hsp bundle %{public}s uninstall", bundleName.c_str());
373     // remove bundle dir first, then delete data in bundle data manager
374     ErrCode errCode;
375      // delete bundle bunlde in data
376     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START)) {
377         APP_LOGE("uninstall start failed");
378         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
379     }
380     if ((errCode = InstalldClient::GetInstance()->RemoveDir(uninstallDir)) != ERR_OK) {
381         APP_LOGE("delete dir %{public}s failed!", uninstallDir.c_str());
382         return errCode;
383     }
384     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_SUCCESS)) {
385         APP_LOGE("update uninstall success failed");
386         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
387     }
388     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->DeleteAppProvisionInfo(bundleName)) {
389         APP_LOGW("bundleName: %{public}s delete appProvisionInfo failed.", bundleName.c_str());
390     }
391     InstallParam installParam;
392     versionCode_ = Constants::ALL_VERSIONCODE;
393     userId_ = Constants::ALL_USERID;
394     SendBundleSystemEvent(
395         bundleName,
396         BundleEventType::UNINSTALL,
397         installParam,
398         sysEventInfo_.preBundleScene,
399         errCode);
400     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
401     /* remove sign profile from code signature for cross-app hsp */
402     RemoveProfileFromCodeSign(bundleName);
403     return ERR_OK;
404 }
405 
UninstallHspVersion(std::string & uninstallDir,int32_t versionCode,InnerBundleInfo & info)406 ErrCode BaseBundleInstaller::UninstallHspVersion(std::string &uninstallDir, int32_t versionCode, InnerBundleInfo &info)
407 {
408     APP_LOGD("begin to process hsp bundle %{public}s uninstall", info.GetBundleName().c_str());
409     // remove bundle dir first, then delete data in innerBundleInfo
410     ErrCode errCode;
411     if (!dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::UNINSTALL_START)) {
412         APP_LOGE("uninstall start failed");
413         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
414     }
415     if ((errCode = InstalldClient::GetInstance()->RemoveDir(uninstallDir)) != ERR_OK) {
416         APP_LOGE("delete dir %{public}s failed!", uninstallDir.c_str());
417         return errCode;
418     }
419     if (!dataMgr_->RemoveHspModuleByVersionCode(versionCode, info)) {
420         APP_LOGE("remove hsp module by versionCode failed!");
421         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
422     }
423     if (!dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::INSTALL_SUCCESS)) {
424         APP_LOGE("update install success failed");
425         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
426     }
427     InstallParam installParam;
428     versionCode_ = Constants::ALL_VERSIONCODE;
429     userId_ = Constants::ALL_USERID;
430     std::string bundleName = info.GetBundleName();
431     SendBundleSystemEvent(
432         bundleName,
433         BundleEventType::UNINSTALL,
434         installParam,
435         sysEventInfo_.preBundleScene,
436         errCode);
437     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
438     return ERR_OK;
439 }
440 
UninstallBundle(const std::string & bundleName,const std::string & modulePackage,const InstallParam & installParam)441 ErrCode BaseBundleInstaller::UninstallBundle(
442     const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam)
443 {
444     APP_LOGI("begin to process %{public}s module in %{public}s uninstall", modulePackage.c_str(), bundleName.c_str());
445     PerfProfile::GetInstance().SetBundleUninstallStartTime(GetTickCount());
446 
447     // uninstall all sandbox app before
448     UninstallAllSandboxApps(bundleName, installParam.userId);
449 
450     int32_t uid = Constants::INVALID_UID;
451     bool isUninstalledFromBmsExtension = false;
452     ErrCode result = ProcessBundleUninstall(bundleName, modulePackage, installParam, uid);
453     if ((result == ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE) &&
454         (UninstallBundleFromBmsExtension(bundleName) == ERR_OK)) {
455         isUninstalledFromBmsExtension = true;
456         result = ERR_OK;
457     }
458     if (installParam.needSendEvent && dataMgr_) {
459         NotifyBundleEvents installRes = {
460             .bundleName = bundleName,
461             .modulePackage = modulePackage,
462             .resultCode = result,
463             .type = NotifyType::UNINSTALL_MODULE,
464             .uid = uid,
465             .accessTokenId = accessTokenId_,
466             .isAgingUninstall = installParam.isAgingUninstall,
467             .isBmsExtensionUninstalled = isUninstalledFromBmsExtension,
468             .appId = uninstallBundleAppId_
469         };
470         if (NotifyBundleStatus(installRes) != ERR_OK) {
471             APP_LOGW("notify status failed for installation");
472         }
473     }
474 
475     SendBundleSystemEvent(
476         bundleName,
477         BundleEventType::UNINSTALL,
478         installParam,
479         sysEventInfo_.preBundleScene,
480         result);
481     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
482     APP_LOGD("finish to process %{public}s module in %{public}s uninstall", modulePackage.c_str(), bundleName.c_str());
483     return result;
484 }
485 
UninstallAppControl(const std::string & appId,int32_t userId)486 bool BaseBundleInstaller::UninstallAppControl(const std::string &appId, int32_t userId)
487 {
488 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
489     std::vector<std::string> appIds;
490     ErrCode ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
491         AppControlConstants::EDM_CALLING, AppControlConstants::APP_DISALLOWED_UNINSTALL, userId, appIds);
492     if (ret != ERR_OK) {
493         APP_LOGE("GetAppInstallControlRule failed code:%{public}d", ret);
494         return true;
495     }
496     if (std::find(appIds.begin(), appIds.end(), appId) == appIds.end()) {
497         return true;
498     }
499     APP_LOGW("appId is not removable");
500     return false;
501 #else
502     APP_LOGW("app control is disable");
503     return true;
504 #endif
505 }
506 
InstallNormalAppControl(const std::string & installAppId,int32_t userId,bool isPreInstallApp)507 ErrCode BaseBundleInstaller::InstallNormalAppControl(
508     const std::string &installAppId,
509     int32_t userId,
510     bool isPreInstallApp)
511 {
512     APP_LOGD("InstallNormalAppControl start ");
513 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
514     if (isPreInstallApp) {
515         APP_LOGD("the preInstalled app does not support app control feature");
516         return ERR_OK;
517     }
518     std::vector<std::string> allowedAppIds;
519     ErrCode ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
520         AppControlConstants::EDM_CALLING, AppControlConstants::APP_ALLOWED_INSTALL, userId, allowedAppIds);
521     if (ret != ERR_OK) {
522         APP_LOGE("GetAppInstallControlRule allowedInstall failed code:%{public}d", ret);
523         return ret;
524     }
525 
526     std::vector<std::string> disallowedAppIds;
527     ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
528         AppControlConstants::EDM_CALLING, AppControlConstants::APP_DISALLOWED_INSTALL, userId, disallowedAppIds);
529     if (ret != ERR_OK) {
530         APP_LOGE("GetAppInstallControlRule disallowedInstall failed code:%{public}d", ret);
531         return ret;
532     }
533 
534     // disallowed list and allowed list all empty.
535     if (disallowedAppIds.empty() && allowedAppIds.empty()) {
536         return ERR_OK;
537     }
538 
539     // only allowed list empty.
540     if (allowedAppIds.empty()) {
541         if (std::find(disallowedAppIds.begin(), disallowedAppIds.end(), installAppId) != disallowedAppIds.end()) {
542             APP_LOGE("disallowedAppIds:%{public}s is disallow install", installAppId.c_str());
543             return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
544         }
545         return ERR_OK;
546     }
547 
548     // only disallowed list empty.
549     if (disallowedAppIds.empty()) {
550         if (std::find(allowedAppIds.begin(), allowedAppIds.end(), installAppId) == allowedAppIds.end()) {
551             APP_LOGE("allowedAppIds:%{public}s is disallow install", installAppId.c_str());
552             return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
553         }
554         return ERR_OK;
555     }
556 
557     // disallowed list and allowed list all not empty.
558     if (std::find(allowedAppIds.begin(), allowedAppIds.end(), installAppId) == allowedAppIds.end()) {
559         APP_LOGE("allowedAppIds:%{public}s is disallow install", installAppId.c_str());
560         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
561     } else if (std::find(disallowedAppIds.begin(), disallowedAppIds.end(), installAppId) != disallowedAppIds.end()) {
562         APP_LOGE("disallowedAppIds:%{public}s is disallow install", installAppId.c_str());
563         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
564     }
565     return ERR_OK;
566 #else
567     APP_LOGW("app control is disable");
568     return ERR_OK;
569 #endif
570 }
571 
UpdateInstallerState(const InstallerState state)572 void BaseBundleInstaller::UpdateInstallerState(const InstallerState state)
573 {
574     APP_LOGD("UpdateInstallerState in BaseBundleInstaller state %{public}d", state);
575     SetInstallerState(state);
576 }
577 
SaveOldRemovableInfo(InnerModuleInfo & newModuleInfo,InnerBundleInfo & oldInfo,bool existModule)578 void BaseBundleInstaller::SaveOldRemovableInfo(
579     InnerModuleInfo &newModuleInfo, InnerBundleInfo &oldInfo, bool existModule)
580 {
581     if (existModule) {
582         // save old module useId isRemovable info to new module
583         auto oldModule = oldInfo.FetchInnerModuleInfos().find(newModuleInfo.modulePackage);
584         if (oldModule == oldInfo.FetchInnerModuleInfos().end()) {
585             APP_LOGE("can not find module %{public}s in oldInfo", newModuleInfo.modulePackage.c_str());
586             return;
587         }
588         for (const auto &remove : oldModule->second.isRemovable) {
589             auto result = newModuleInfo.isRemovable.try_emplace(remove.first, remove.second);
590             if (!result.second) {
591                 APP_LOGE("%{public}s removable add %{public}s from old:%{public}d failed",
592                     newModuleInfo.modulePackage.c_str(), remove.first.c_str(), remove.second);
593             }
594             APP_LOGD("%{public}s removable add %{public}s from old:%{public}d",
595                 newModuleInfo.modulePackage.c_str(), remove.first.c_str(), remove.second);
596         }
597     }
598 }
599 
CheckEnableRemovable(std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo,int32_t & userId,bool isFreeInstallFlag,bool isAppExist)600 void BaseBundleInstaller::CheckEnableRemovable(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
601     InnerBundleInfo &oldInfo, int32_t &userId, bool isFreeInstallFlag, bool isAppExist)
602 {
603     for (auto &item : newInfos) {
604         std::map<std::string, InnerModuleInfo> &moduleInfo = item.second.FetchInnerModuleInfos();
605         bool hasInstalledInUser = oldInfo.HasInnerBundleUserInfo(userId);
606         // now there are three cases for set haps isRemovable true:
607         // 1. FREE_INSTALL flag
608         // 2. bundle not exist in current user
609         // 3. bundle exist, hap not exist
610         // 4. hap exist not in current userId
611         for (auto &iter : moduleInfo) {
612             APP_LOGD("modulePackage:(%{public}s), userId:%{public}d, flag:%{public}d, isAppExist:%{public}d",
613                 iter.second.modulePackage.c_str(), userId, isFreeInstallFlag, isAppExist);
614             bool existModule = oldInfo.FindModule(iter.second.modulePackage);
615             bool hasModuleInUser = item.second.IsUserExistModule(iter.second.moduleName, userId);
616             APP_LOGD("hasInstalledInUser:%{public}d, existModule:(%{public}d), hasModuleInUser:(%{public}d)",
617                 hasInstalledInUser, existModule, hasModuleInUser);
618             if (isFreeInstallFlag && (!isAppExist || !hasInstalledInUser || !existModule || !hasModuleInUser)) {
619                 APP_LOGD("hasInstalledInUser:%{public}d, isAppExist:%{public}d existModule:(%{public}d)",
620                     hasInstalledInUser, isAppExist, existModule);
621                 item.second.SetModuleRemovable(iter.second.moduleName, true, userId);
622                 SaveOldRemovableInfo(iter.second, oldInfo, existModule);
623             }
624         }
625     }
626 }
627 
CheckDuplicateProxyData(const InnerBundleInfo & newInfo,const InnerBundleInfo & oldInfo)628 bool BaseBundleInstaller::CheckDuplicateProxyData(const InnerBundleInfo &newInfo,
629     const InnerBundleInfo &oldInfo)
630 {
631     std::vector<ProxyData> proxyDatas;
632     oldInfo.GetAllProxyDataInfos(proxyDatas);
633     newInfo.GetAllProxyDataInfos(proxyDatas);
634     return CheckDuplicateProxyData(proxyDatas);
635 }
636 
CheckDuplicateProxyData(const std::unordered_map<std::string,InnerBundleInfo> & newInfos)637 bool BaseBundleInstaller::CheckDuplicateProxyData(const std::unordered_map<std::string, InnerBundleInfo> &newInfos)
638 {
639     std::vector<ProxyData> proxyDatas;
640     for (const auto &innerBundleInfo : newInfos) {
641         innerBundleInfo.second.GetAllProxyDataInfos(proxyDatas);
642     }
643     return CheckDuplicateProxyData(proxyDatas);
644 }
645 
CheckDuplicateProxyData(const std::vector<ProxyData> & proxyDatas)646 bool BaseBundleInstaller::CheckDuplicateProxyData(const std::vector<ProxyData> &proxyDatas)
647 {
648     std::set<std::string> uriSet;
649     for (const auto &proxyData : proxyDatas) {
650         if (!uriSet.insert(proxyData.uri).second) {
651             APP_LOGE("uri %{public}s in proxyData is duplicated", proxyData.uri.c_str());
652             return false;
653         }
654     }
655     return true;
656 }
657 
InnerProcessBundleInstall(std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo,const InstallParam & installParam,int32_t & uid)658 ErrCode BaseBundleInstaller::InnerProcessBundleInstall(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
659     InnerBundleInfo &oldInfo, const InstallParam &installParam, int32_t &uid)
660 {
661     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
662     APP_LOGI("InnerProcessBundleInstall with bundleName %{public}s, userId is %{public}d", bundleName_.c_str(),
663         userId_);
664     // try to get the bundle info to decide use install or update. Always keep other exceptions below this line.
665     if (!GetInnerBundleInfo(oldInfo, isAppExist_)) {
666         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
667     }
668     APP_LOGI("flag:%{public}d, userId:%{public}d, isAppExist:%{public}d",
669         installParam.installFlag, userId_, isAppExist_);
670 
671     ErrCode result = ERR_OK;
672     result = CheckAppService(newInfos.begin()->second, oldInfo, isAppExist_);
673     CHECK_RESULT(result, "Check appService failed %{public}d");
674 
675     if (installParam.needSavePreInstallInfo) {
676         PreInstallBundleInfo preInstallBundleInfo;
677         preInstallBundleInfo.SetBundleName(bundleName_);
678         dataMgr_->GetPreInstallBundleInfo(bundleName_, preInstallBundleInfo);
679         preInstallBundleInfo.SetAppType(newInfos.begin()->second.GetAppType());
680         preInstallBundleInfo.SetVersionCode(newInfos.begin()->second.GetVersionCode());
681         preInstallBundleInfo.SetIsUninstalled(false);
682         for (const auto &item : newInfos) {
683             preInstallBundleInfo.AddBundlePath(item.first);
684         }
685 #ifdef USE_PRE_BUNDLE_PROFILE
686         preInstallBundleInfo.SetRemovable(installParam.removable);
687 #else
688         preInstallBundleInfo.SetRemovable(newInfos.begin()->second.GetRemovable());
689 #endif
690         dataMgr_->SavePreInstallBundleInfo(bundleName_, preInstallBundleInfo);
691     }
692 
693     result = CheckSingleton(newInfos.begin()->second, userId_);
694     CHECK_RESULT(result, "Check singleton failed %{public}d");
695 
696     bool isFreeInstallFlag = (installParam.installFlag == InstallFlag::FREE_INSTALL);
697     CheckEnableRemovable(newInfos, oldInfo, userId_, isFreeInstallFlag, isAppExist_);
698     // check MDM self update
699     result = CheckMDMUpdateBundleForSelf(installParam, oldInfo, newInfos, isAppExist_);
700     CHECK_RESULT(result, "update MDM app failed %{public}d");
701 
702     if (isAppExist_) {
703         if (oldInfo.GetApplicationBundleType() == BundleType::SHARED) {
704             APP_LOGE("old bundle info is shared package");
705             return ERR_APPEXECFWK_INSTALL_COMPATIBLE_POLICY_NOT_SAME;
706         }
707 
708         result = CheckInstallationFree(oldInfo, newInfos);
709         CHECK_RESULT(result, "CheckInstallationFree failed %{public}d");
710         // to guarantee that the hap version can be compatible.
711         result = CheckVersionCompatibility(oldInfo);
712         CHECK_RESULT(result, "The app has been installed and update lower version bundle %{public}d");
713         // to check native file between oldInfo and newInfos.
714         result = CheckNativeFileWithOldInfo(oldInfo, newInfos);
715         CHECK_RESULT(result, "Check native so between oldInfo and newInfos failed %{public}d");
716 
717         for (auto &info : newInfos) {
718             std::string packageName = info.second.GetCurrentModulePackage();
719             if (oldInfo.FindModule(packageName)) {
720                 installedModules_[packageName] = true;
721             }
722         }
723 
724         hasInstalledInUser_ = oldInfo.HasInnerBundleUserInfo(userId_);
725         if (!hasInstalledInUser_) {
726             APP_LOGD("new userInfo with bundleName %{public}s and userId %{public}d",
727                 bundleName_.c_str(), userId_);
728             InnerBundleUserInfo newInnerBundleUserInfo;
729             newInnerBundleUserInfo.bundleUserInfo.userId = userId_;
730             newInnerBundleUserInfo.bundleName = bundleName_;
731             oldInfo.AddInnerBundleUserInfo(newInnerBundleUserInfo);
732             ScopeGuard userGuard([&] { RemoveBundleUserData(oldInfo, false); });
733             auto accessTokenIdEx = CreateAccessTokenIdEx(oldInfo);
734             accessTokenId_ = accessTokenIdEx.tokenIdExStruct.tokenID;
735             oldInfo.SetAccessTokenIdEx(accessTokenIdEx, userId_);
736             result = GrantRequestPermissions(oldInfo, accessTokenId_);
737             CHECK_RESULT(result, "GrantRequestPermissions failed %{public}d");
738 
739             result = CreateBundleUserData(oldInfo);
740             CHECK_RESULT(result, "CreateBundleUserData failed %{public}d");
741 
742             if (!isFeatureNeedUninstall_) {
743                 // extract ap file in old haps
744                 result = ExtractAllArkProfileFile(oldInfo, true);
745                 CHECK_RESULT(result, "ExtractAllArkProfileFile failed %{public}d");
746             }
747 
748             userGuard.Dismiss();
749         }
750     }
751 
752     auto it = newInfos.begin();
753     if (!isAppExist_) {
754         APP_LOGI("app is not exist");
755         InnerBundleInfo &newInfo = it->second;
756         modulePath_ = it->first;
757         InnerBundleUserInfo newInnerBundleUserInfo;
758         newInnerBundleUserInfo.bundleUserInfo.userId = userId_;
759         newInnerBundleUserInfo.bundleName = bundleName_;
760         newInfo.AddInnerBundleUserInfo(newInnerBundleUserInfo);
761         APP_LOGI("SetIsFreeInstallApp(%{public}d)", InstallFlag::FREE_INSTALL == installParam.installFlag);
762         newInfo.SetIsFreeInstallApp(InstallFlag::FREE_INSTALL == installParam.installFlag);
763         result = ProcessBundleInstallStatus(newInfo, uid);
764         CHECK_RESULT(result, "ProcessBundleInstallStatus failed %{public}d");
765 
766         it++;
767         hasInstalledInUser_ = true;
768     }
769 
770     InnerBundleInfo bundleInfo;
771     bool isBundleExist = false;
772     if (!GetInnerBundleInfo(bundleInfo, isBundleExist) || !isBundleExist) {
773         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
774     }
775 
776     InnerBundleUserInfo innerBundleUserInfo;
777     if (!bundleInfo.GetInnerBundleUserInfo(userId_, innerBundleUserInfo)) {
778         APP_LOGE("oldInfo do not have user");
779         return ERR_APPEXECFWK_USER_NOT_EXIST;
780     }
781 
782     ScopeGuard userGuard([&] {
783         if (!hasInstalledInUser_ || (!isAppExist_)) {
784             RemoveBundleUserData(oldInfo, false);
785         }
786     });
787 
788     // update haps
789     for (; it != newInfos.end(); ++it) {
790         // install entry module firstly
791         APP_LOGD("update module %{public}s, entry module packageName is %{public}s",
792             it->second.GetCurrentModulePackage().c_str(), entryModuleName_.c_str());
793         if ((result = InstallEntryMoudleFirst(newInfos, bundleInfo, innerBundleUserInfo,
794             installParam)) != ERR_OK) {
795             APP_LOGE("install entry module failed due to error %{public}d", result);
796             break;
797         }
798         if (it->second.GetCurrentModulePackage().compare(entryModuleName_) == 0) {
799             APP_LOGD("enrty has been installed");
800             continue;
801         }
802         modulePath_ = it->first;
803         InnerBundleInfo &newInfo = it->second;
804         newInfo.AddInnerBundleUserInfo(innerBundleUserInfo);
805         bool isReplace = (installParam.installFlag == InstallFlag::REPLACE_EXISTING ||
806             installParam.installFlag == InstallFlag::FREE_INSTALL);
807         // app exist, but module may not
808         if ((result = ProcessBundleUpdateStatus(
809             bundleInfo, newInfo, isReplace, installParam.noSkipsKill)) != ERR_OK) {
810             break;
811         }
812     }
813 
814     if (result == ERR_OK) {
815         userGuard.Dismiss();
816     }
817 
818     uid = bundleInfo.GetUid(userId_);
819     mainAbility_ = bundleInfo.GetMainAbility();
820     return result;
821 }
822 
CheckAppService(const InnerBundleInfo & newInfo,const InnerBundleInfo & oldInfo,bool isAppExist)823 ErrCode BaseBundleInstaller::CheckAppService(
824     const InnerBundleInfo &newInfo, const InnerBundleInfo &oldInfo, bool isAppExist)
825 {
826     if ((newInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK) && !isAppExist) {
827         APP_LOGW("Not alloweded instal appService hap(%{public}s) due to the hsp does not exist.",
828             newInfo.GetBundleName().c_str());
829         return ERR_APP_SERVICE_FWK_INSTALL_TYPE_FAILED;
830     }
831 
832     if (isAppExist) {
833         isAppService_ = oldInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK;
834         if (isAppService_ && oldInfo.GetApplicationBundleType() != newInfo.GetApplicationBundleType()) {
835             APP_LOGW("Bundle(%{public}s) type is not same.", newInfo.GetBundleName().c_str());
836             return ERR_APPEXECFWK_BUNDLE_TYPE_NOT_SAME;
837         }
838     }
839     return ERR_OK;
840 }
841 
CheckSingleton(const InnerBundleInfo & info,const int32_t userId)842 ErrCode BaseBundleInstaller::CheckSingleton(const InnerBundleInfo &info, const int32_t userId)
843 {
844     if (isAppService_) {
845         if (userId != Constants::DEFAULT_USERID) {
846             APP_LOGW("appService(%{public}s) only install U0.", info.GetBundleName().c_str());
847             return ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON;
848         }
849 
850         return ERR_OK;
851     }
852     // singleton app can only be installed in U0 and U0 can only install singleton app.
853     bool isSingleton = info.IsSingleton();
854     if ((isSingleton && (userId != Constants::DEFAULT_USERID)) ||
855         (!isSingleton && (userId == Constants::DEFAULT_USERID))) {
856         APP_LOGW("singleton(%{public}d) app(%{public}s) and user(%{public}d) are not matched.",
857             isSingleton, info.GetBundleName().c_str(), userId);
858         return ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON;
859     }
860 
861     return ERR_OK;
862 }
863 
CreateAccessTokenIdEx(const InnerBundleInfo & info)864 Security::AccessToken::AccessTokenIDEx BaseBundleInstaller::CreateAccessTokenIdEx(const InnerBundleInfo &info)
865 {
866     APP_LOGI("CreateAccessTokenIdEx bundleName: %{public}s, userId: %{public}d",
867         info.GetBundleName().c_str(), userId_);
868     return BundlePermissionMgr::CreateAccessTokenIdEx(info, info.GetBundleName(), userId_);
869 }
870 
GrantRequestPermissions(const InnerBundleInfo & info,const uint32_t tokenId)871 ErrCode BaseBundleInstaller::GrantRequestPermissions(const InnerBundleInfo &info, const uint32_t tokenId)
872 {
873     APP_LOGI("GrantRequestPermissions bundleName: %{public}s, userId: %{public}d",
874         info.GetBundleName().c_str(), userId_);
875     if (!BundlePermissionMgr::GrantRequestPermissions(info, tokenId)) {
876         APP_LOGE("GrantRequestPermissions failed, bundleName: %{public}s", info.GetBundleName().c_str());
877         return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
878     }
879     return ERR_OK;
880 }
881 
ProcessBundleInstall(const std::vector<std::string> & inBundlePaths,const InstallParam & installParam,const Constants::AppType appType,int32_t & uid)882 ErrCode BaseBundleInstaller::ProcessBundleInstall(const std::vector<std::string> &inBundlePaths,
883     const InstallParam &installParam, const Constants::AppType appType, int32_t &uid)
884 {
885     APP_LOGD("ProcessBundleInstall bundlePath install paths=%s, hspPaths=%s",
886         GetJsonStrFromInfo(inBundlePaths).c_str(), GetJsonStrFromInfo(installParam.sharedBundleDirPaths).c_str());
887     if (dataMgr_ == nullptr) {
888         dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
889         if (dataMgr_ == nullptr) {
890             APP_LOGE("Get dataMgr shared_ptr nullptr");
891             return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
892         }
893     }
894 
895     SharedBundleInstaller sharedBundleInstaller(installParam, appType);
896     ErrCode result = sharedBundleInstaller.ParseFiles();
897     CHECK_RESULT(result, "parse cross-app shared bundles failed %{public}d");
898 
899     if (inBundlePaths.empty() && sharedBundleInstaller.NeedToInstall()) {
900         result = sharedBundleInstaller.Install(sysEventInfo_);
901         sync();
902         APP_LOGI("install cross-app shared bundles only, result : %{public}d", result);
903         return result;
904     }
905 
906     userId_ = GetUserId(installParam.userId);
907     result = CheckUserId(userId_);
908     CHECK_RESULT(result, "userId check failed %{public}d");
909 
910     std::vector<std::string> bundlePaths;
911     // check hap paths
912     result = BundleUtil::CheckFilePath(inBundlePaths, bundlePaths);
913     CHECK_RESULT(result, "hap file check failed %{public}d");
914     UpdateInstallerState(InstallerState::INSTALL_BUNDLE_CHECKED);                  // ---- 5%
915 
916     // copy the haps to the dir which cannot be accessed from caller
917     result = CopyHapsToSecurityDir(installParam, bundlePaths);
918     CHECK_RESULT(result, "copy file failed %{public}d");
919 
920     // check syscap
921     result = CheckSysCap(bundlePaths);
922     CHECK_RESULT(result, "hap syscap check failed %{public}d");
923     UpdateInstallerState(InstallerState::INSTALL_SYSCAP_CHECKED);                  // ---- 10%
924 
925     // verify signature info for all haps
926     std::vector<Security::Verify::HapVerifyResult> hapVerifyResults;
927     result = CheckMultipleHapsSignInfo(bundlePaths, installParam, hapVerifyResults);
928     CHECK_RESULT(result, "hap files check signature info failed %{public}d");
929     UpdateInstallerState(InstallerState::INSTALL_SIGNATURE_CHECKED);               // ---- 15%
930 
931     // parse the bundle infos for all haps
932     // key is bundlePath , value is innerBundleInfo
933     std::unordered_map<std::string, InnerBundleInfo> newInfos;
934     result = ParseHapFiles(bundlePaths, installParam, appType, hapVerifyResults, newInfos);
935     CHECK_RESULT(result, "parse haps file failed %{public}d");
936     result = CheckInstallPermission(installParam, hapVerifyResults);
937     CHECK_RESULT(result, "check install permission failed %{public}d");
938     result = CheckInstallCondition(hapVerifyResults, newInfos);
939     CHECK_RESULT(result, "check install condition failed %{public}d");
940     // check the dependencies whether or not exists
941     result = CheckDependency(newInfos, sharedBundleInstaller);
942     CHECK_RESULT(result, "check dependency failed %{public}d");
943     // hapVerifyResults at here will not be empty
944     verifyRes_ = hapVerifyResults[0];
945     UpdateInstallerState(InstallerState::INSTALL_PARSED);                          // ---- 20%
946 
947     userId_ = GetConfirmUserId(userId_, newInfos);
948 
949     // check hap hash param
950     result = CheckHapHashParams(newInfos, installParam.hashParams);
951     CHECK_RESULT(result, "check hap hash param failed %{public}d");
952     UpdateInstallerState(InstallerState::INSTALL_HAP_HASH_PARAM_CHECKED);         // ---- 25%
953 
954     // check overlay installation
955     result = CheckOverlayInstallation(newInfos, userId_);
956     CHECK_RESULT(result, "overlay hap check failed %{public}d");
957     UpdateInstallerState(InstallerState::INSTALL_OVERLAY_CHECKED);                // ---- 30%
958 
959     // check app props in the configuration file
960     result = CheckAppLabelInfo(newInfos);
961     CHECK_RESULT(result, "verisoncode or bundleName is different in all haps %{public}d");
962     UpdateInstallerState(InstallerState::INSTALL_VERSION_AND_BUNDLENAME_CHECKED);  // ---- 35%
963 
964     // check if bundle exists in extension
965     result = CheckBundleInBmsExtension(bundleName_, userId_);
966     CHECK_RESULT(result, "bundle is already existed in bms extension %{public}d");
967 
968     // check native file
969     result = CheckMultiNativeFile(newInfos);
970     CHECK_RESULT(result, "native so is incompatible in all haps %{public}d");
971     UpdateInstallerState(InstallerState::INSTALL_NATIVE_SO_CHECKED);               // ---- 40%
972 
973     // check proxy data
974     result = CheckProxyDatas(newInfos);
975     CHECK_RESULT(result, "proxy data check failed %{public}d");
976     UpdateInstallerState(InstallerState::INSTALL_PROXY_DATA_CHECKED);              // ---- 45%
977 
978     // check hap is allow install by app control
979     result = InstallNormalAppControl((newInfos.begin()->second).GetAppId(), userId_, installParam.isPreInstallApp);
980     CHECK_RESULT(result, "install app control failed %{public}d");
981 
982     auto &mtx = dataMgr_->GetBundleMutex(bundleName_);
983     std::lock_guard lock {mtx};
984 
985     // uninstall all sandbox app before
986     UninstallAllSandboxApps(bundleName_);
987     UpdateInstallerState(InstallerState::INSTALL_REMOVE_SANDBOX_APP);              // ---- 50%
988 
989     // this state should always be set when return
990     ScopeGuard stateGuard([&] {
991         dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_SUCCESS);
992         dataMgr_->EnableBundle(bundleName_);
993     });
994 
995     InnerBundleInfo oldInfo;
996     verifyCodeParams_ = installParam.verifyCodeParams;
997     pgoParams_ = installParam.pgoParams;
998     copyHapToInstallPath_ = installParam.copyHapToInstallPath;
999     result = InnerProcessBundleInstall(newInfos, oldInfo, installParam, uid);
1000     CHECK_RESULT_WITH_ROLLBACK(result, "internal processing failed with result %{public}d", newInfos, oldInfo);
1001     UpdateInstallerState(InstallerState::INSTALL_INFO_SAVED);                      // ---- 80%
1002 
1003     // copy hap or hsp to real install dir
1004     SaveHapPathToRecords(installParam.isPreInstallApp, newInfos);
1005     if (installParam.copyHapToInstallPath) {
1006         APP_LOGD("begin to copy hap to install path");
1007         result = SaveHapToInstallPath(newInfos);
1008         CHECK_RESULT_WITH_ROLLBACK(result, "copy hap to install path failed %{public}d", newInfos, oldInfo);
1009     }
1010     // delete old native library path
1011     if (NeedDeleteOldNativeLib(newInfos, oldInfo)) {
1012         APP_LOGI("Delete old library");
1013         DeleteOldNativeLibraryPath();
1014     }
1015 
1016     // move so file to real installation dir
1017     result = MoveSoFileToRealInstallationDir(newInfos);
1018     CHECK_RESULT_WITH_ROLLBACK(result, "move so file to install path failed %{public}d", newInfos, oldInfo);
1019 
1020     // attention pls, rename operation shoule be almost the last operation to guarantee the rollback operation
1021     // when someone failure occurs in the installation flow
1022     result = RenameAllTempDir(newInfos);
1023     CHECK_RESULT_WITH_ROLLBACK(result, "rename temp dirs failed with result %{public}d", newInfos, oldInfo);
1024     UpdateInstallerState(InstallerState::INSTALL_RENAMED);                         // ---- 90%
1025 
1026     // delete low-version hap or hsp when higher-version hap or hsp installed
1027     if (!uninstallModuleVec_.empty()) {
1028         UninstallLowerVersionFeature(uninstallModuleVec_, installParam.noSkipsKill);
1029     }
1030 
1031     // create data group dir
1032     ScopeGuard groupDirGuard([&] { DeleteGroupDirsForException(); });
1033     result = CreateDataGroupDirs(newInfos, oldInfo);
1034     CHECK_RESULT_WITH_ROLLBACK(result, "create data group dirs failed with result %{public}d", newInfos, oldInfo);
1035 
1036     // install cross-app hsp which has rollback operation in sharedBundleInstaller when some one failure occurs
1037     result = sharedBundleInstaller.Install(sysEventInfo_);
1038     CHECK_RESULT_WITH_ROLLBACK(result, "install cross-app shared bundles failed %{public}d", newInfos, oldInfo);
1039 
1040     std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1041     result = driverInstaller->CopyAllDriverFile(newInfos, oldInfo);
1042     CHECK_RESULT_WITH_ROLLBACK(result, "copy driver files failed due to error %{public}d", newInfos, oldInfo);
1043 
1044     UpdateInstallerState(InstallerState::INSTALL_SUCCESS);                         // ---- 100%
1045     APP_LOGD("finish ProcessBundleInstall bundlePath install touch off aging");
1046     moduleName_ = GetModuleNames(newInfos);
1047 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
1048     if (installParam.installFlag == InstallFlag::FREE_INSTALL) {
1049         DelayedSingleton<BundleMgrService>::GetInstance()->GetAgingMgr()->Start(
1050             BundleAgingMgr::AgingTriggertype::FREE_INSTALL);
1051     }
1052 #endif
1053 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1054     if (needDeleteQuickFixInfo_) {
1055         APP_LOGD("module update, quick fix old patch need to delete, bundleName:%{public}s", bundleName_.c_str());
1056         if (!oldInfo.GetAppQuickFix().deployedAppqfInfo.hqfInfos.empty()) {
1057             APP_LOGD("InnerBundleInfo quickFixInfo need disable, bundleName:%{public}s", bundleName_.c_str());
1058             auto quickFixSwitcher = std::make_unique<QuickFixSwitcher>(bundleName_, false);
1059             quickFixSwitcher->Execute();
1060         }
1061         auto quickFixDeleter = std::make_unique<QuickFixDeleter>(bundleName_);
1062         quickFixDeleter->Execute();
1063     }
1064 #endif
1065     GetInstallEventInfo(sysEventInfo_);
1066     AddAppProvisionInfo(bundleName_, hapVerifyResults[0].GetProvisionInfo(), installParam);
1067     ProcessOldNativeLibraryPath(newInfos, oldInfo.GetVersionCode(), oldInfo.GetNativeLibraryPath());
1068     ProcessAOT(installParam.isOTA, newInfos);
1069     UpdateAppInstallControlled(userId_);
1070     groupDirGuard.Dismiss();
1071     RemoveOldGroupDirs();
1072     /* process quick fix when install new moudle */
1073     ProcessQuickFixWhenInstallNewModule(installParam, newInfos);
1074     BundleResourceHelper::AddResourceInfoByBundleName(bundleName_, userId_);
1075     sync();
1076     return result;
1077 }
1078 
RollBack(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo)1079 void BaseBundleInstaller::RollBack(const std::unordered_map<std::string, InnerBundleInfo> &newInfos,
1080     InnerBundleInfo &oldInfo)
1081 {
1082     APP_LOGD("start rollback due to install failed");
1083     if (!isAppExist_) {
1084         RemoveBundleAndDataDir(newInfos.begin()->second, false);
1085         // delete accessTokenId
1086         if (BundlePermissionMgr::DeleteAccessTokenId(newInfos.begin()->second.GetAccessTokenId(userId_)) !=
1087             AccessToken::AccessTokenKitRet::RET_SUCCESS) {
1088             APP_LOGE("delete accessToken failed");
1089         }
1090 
1091         // remove driver file
1092         std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1093         for (const auto &info : newInfos) {
1094             driverInstaller->RemoveDriverSoFile(info.second, "", false);
1095         }
1096         // remove profile from code signature
1097         RemoveProfileFromCodeSign(bundleName_);
1098         // remove innerBundleInfo
1099         RemoveInfo(bundleName_, "");
1100         return;
1101     }
1102     InnerBundleInfo preInfo;
1103     bool isExist = false;
1104     if (!GetInnerBundleInfo(preInfo, isExist) || !isExist) {
1105         APP_LOGI("finish rollback due to install failed");
1106         return;
1107     }
1108     for (const auto &info : newInfos) {
1109         RollBack(info.second, oldInfo);
1110     }
1111     // need delete definePermissions and requestPermissions
1112     UpdateDefineAndRequestPermissions(preInfo, oldInfo);
1113     APP_LOGD("finish rollback due to install failed");
1114 }
1115 
UpdateDefineAndRequestPermissions(const InnerBundleInfo & oldInfo,InnerBundleInfo & newInfo)1116 ErrCode BaseBundleInstaller::UpdateDefineAndRequestPermissions(const InnerBundleInfo &oldInfo,
1117     InnerBundleInfo &newInfo)
1118 {
1119     APP_LOGD("UpdateDefineAndRequestPermissions %{public}s start", bundleName_.c_str());
1120     auto bundleUserInfos = newInfo.GetInnerBundleUserInfos();
1121     bool needUpdateToken = oldInfo.GetAppType() != newInfo.GetAppType();
1122     for (const auto &uerInfo : bundleUserInfos) {
1123         if (uerInfo.second.accessTokenId == 0) {
1124             continue;
1125         }
1126         std::vector<std::string> newRequestPermName;
1127         Security::AccessToken::AccessTokenIDEx accessTokenIdEx;
1128         accessTokenIdEx.tokenIDEx = uerInfo.second.accessTokenIdEx;
1129         if (accessTokenIdEx.tokenIDEx == 0) {
1130             needUpdateToken = true;
1131             accessTokenIdEx.tokenIDEx = uerInfo.second.accessTokenId;
1132         }
1133         if (!BundlePermissionMgr::UpdateDefineAndRequestPermissions(accessTokenIdEx, oldInfo,
1134             newInfo, newRequestPermName)) {
1135             APP_LOGE("UpdateDefineAndRequestPermissions %{public}s failed", bundleName_.c_str());
1136             return ERR_APPEXECFWK_INSTALL_UPDATE_HAP_TOKEN_FAILED;
1137         }
1138         if (!BundlePermissionMgr::GrantRequestPermissions(newInfo, newRequestPermName, uerInfo.second.accessTokenId)) {
1139             APP_LOGE("BundlePermissionMgr::GrantRequestPermissions failed %{public}s", bundleName_.c_str());
1140             return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
1141         }
1142         if (needUpdateToken) {
1143             newInfo.SetAccessTokenIdEx(accessTokenIdEx, uerInfo.second.bundleUserInfo.userId);
1144         }
1145     }
1146     if (needUpdateToken && !dataMgr_->UpdateInnerBundleInfo(newInfo)) {
1147         APP_LOGE("save UpdateInnerBundleInfo failed");
1148         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1149     }
1150     APP_LOGD("UpdateDefineAndRequestPermissions %{public}s end", bundleName_.c_str());
1151     return ERR_OK;
1152 }
1153 
RollBack(const InnerBundleInfo & info,InnerBundleInfo & oldInfo)1154 void BaseBundleInstaller::RollBack(const InnerBundleInfo &info, InnerBundleInfo &oldInfo)
1155 {
1156     // rollback hap installed
1157     std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1158     auto modulePackage = info.GetCurrentModulePackage();
1159     if (installedModules_[modulePackage]) {
1160         std::string createModulePath = info.GetAppCodePath() + Constants::PATH_SEPARATOR +
1161             modulePackage + Constants::TMP_SUFFIX;
1162         RemoveModuleDir(createModulePath);
1163         oldInfo.SetCurrentModulePackage(modulePackage);
1164         RollBackModuleInfo(bundleName_, oldInfo);
1165         // remove driver file of installed module
1166         driverInstaller->RemoveDriverSoFile(info, info.GetModuleName(modulePackage), true);
1167     } else {
1168         RemoveModuleDir(info.GetModuleDir(modulePackage));
1169         // remove driver file
1170         driverInstaller->RemoveDriverSoFile(info, info.GetModuleName(modulePackage), false);
1171         // remove module info
1172         RemoveInfo(bundleName_, modulePackage);
1173     }
1174 }
1175 
RemoveInfo(const std::string & bundleName,const std::string & packageName)1176 void BaseBundleInstaller::RemoveInfo(const std::string &bundleName, const std::string &packageName)
1177 {
1178     APP_LOGD("remove innerBundleInfo due to rollback");
1179     if (packageName.empty()) {
1180         dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UPDATING_FAIL);
1181     } else {
1182         InnerBundleInfo innerBundleInfo;
1183         bool isExist = false;
1184         if (!GetInnerBundleInfo(innerBundleInfo, isExist) || !isExist) {
1185             APP_LOGI("finish rollback due to install failed");
1186             return;
1187         }
1188         dataMgr_->UpdateBundleInstallState(bundleName, InstallState::ROLL_BACK);
1189         dataMgr_->RemoveModuleInfo(bundleName, packageName, innerBundleInfo);
1190     }
1191     APP_LOGD("finish to remove innerBundleInfo due to rollback");
1192 }
1193 
RollBackModuleInfo(const std::string & bundleName,InnerBundleInfo & oldInfo)1194 void BaseBundleInstaller::RollBackModuleInfo(const std::string &bundleName, InnerBundleInfo &oldInfo)
1195 {
1196     APP_LOGD("rollBackMoudleInfo due to rollback");
1197     InnerBundleInfo innerBundleInfo;
1198     bool isExist = false;
1199     if (!GetInnerBundleInfo(innerBundleInfo, isExist) || !isExist) {
1200         return;
1201     }
1202     dataMgr_->UpdateBundleInstallState(bundleName, InstallState::ROLL_BACK);
1203     dataMgr_->UpdateInnerBundleInfo(bundleName, oldInfo, innerBundleInfo);
1204     APP_LOGD("finsih rollBackMoudleInfo due to rollback");
1205 }
1206 
ProcessBundleUninstall(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)1207 ErrCode BaseBundleInstaller::ProcessBundleUninstall(
1208     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
1209 {
1210     APP_LOGD("start to process %{public}s bundle uninstall", bundleName.c_str());
1211     if (bundleName.empty()) {
1212         APP_LOGE("uninstall bundle name empty");
1213         return ERR_APPEXECFWK_UNINSTALL_INVALID_NAME;
1214     }
1215 
1216     dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1217     if (dataMgr_ == nullptr) {
1218         APP_LOGE("Get dataMgr shared_ptr nullptr");
1219         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
1220     }
1221 
1222     userId_ = GetUserId(installParam.userId);
1223     if (userId_ == Constants::INVALID_USERID) {
1224         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
1225     }
1226 
1227     if (!dataMgr_->HasUserId(userId_)) {
1228         APP_LOGE("The user %{public}d does not exist when uninstall.", userId_);
1229         return ERR_APPEXECFWK_USER_NOT_EXIST;
1230     }
1231 
1232     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
1233     std::lock_guard lock {mtx};
1234     InnerBundleInfo oldInfo;
1235     if (!dataMgr_->GetInnerBundleInfo(bundleName, oldInfo)) {
1236         APP_LOGW("uninstall bundle info missing");
1237         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
1238     }
1239     uninstallBundleAppId_ = oldInfo.GetAppId();
1240     versionCode_ = oldInfo.GetVersionCode();
1241     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); });
1242     if (oldInfo.GetApplicationBundleType() == BundleType::SHARED) {
1243         APP_LOGE("uninstall bundle is shared library.");
1244         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_IS_SHARED_LIBRARY;
1245     }
1246 
1247     InnerBundleUserInfo curInnerBundleUserInfo;
1248     if (!oldInfo.GetInnerBundleUserInfo(userId_, curInnerBundleUserInfo)) {
1249         APP_LOGE("bundle(%{public}s) get user(%{public}d) failed when uninstall.",
1250             oldInfo.GetBundleName().c_str(), userId_);
1251         return ERR_APPEXECFWK_USER_NOT_INSTALL_HAP;
1252     }
1253 
1254     uid = curInnerBundleUserInfo.uid;
1255     if (!installParam.forceExecuted &&
1256         !oldInfo.GetRemovable() && installParam.noSkipsKill) {
1257         APP_LOGE("uninstall system app");
1258         return ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR;
1259     }
1260 
1261     if (!UninstallAppControl(oldInfo.GetAppId(), userId_)) {
1262         APP_LOGE("bundleName: %{public}s is not allow uninstall", bundleName.c_str());
1263         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_UNINSTALL;
1264     }
1265 
1266     // reboot scan case will not kill the bundle
1267     if (installParam.noSkipsKill) {
1268         // kill the bundle process during uninstall.
1269         if (!AbilityManagerHelper::UninstallApplicationProcesses(oldInfo.GetApplicationName(), uid)) {
1270             APP_LOGE("can not kill process, uid : %{public}d", uid);
1271             return ERR_APPEXECFWK_UNINSTALL_KILLING_APP_ERROR;
1272         }
1273     }
1274 
1275     auto res = RemoveDataGroupDirs(oldInfo.GetBundleName(), userId_);
1276     CHECK_RESULT(res, "RemoveDataGroupDirs failed %{public}d");
1277 
1278     if (oldInfo.GetInnerBundleUserInfos().size() > 1) {
1279         APP_LOGD("only delete userinfo %{public}d", userId_);
1280         BundleResourceHelper::DeleteResourceInfo(bundleName, userId_);
1281         return RemoveBundleUserData(oldInfo, installParam.isKeepData);
1282     }
1283 
1284     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START)) {
1285         APP_LOGE("uninstall already start");
1286         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1287     }
1288 
1289     std::string packageName;
1290     oldInfo.SetInstallMark(bundleName, packageName, InstallExceptionStatus::UNINSTALL_BUNDLE_START);
1291     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
1292         APP_LOGE("save install mark failed");
1293         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1294     }
1295 
1296     ErrCode result = RemoveBundle(oldInfo, installParam.isKeepData);
1297     if (result != ERR_OK) {
1298         APP_LOGE("remove whole bundle failed");
1299         return result;
1300     }
1301 
1302     result = DeleteOldArkNativeFile(oldInfo);
1303     if (result != ERR_OK) {
1304         APP_LOGE("delete old arkNativeFile failed");
1305         return result;
1306     }
1307 
1308     result = DeleteArkProfile(bundleName, userId_);
1309     if (result != ERR_OK) {
1310         APP_LOGE("fail to removeArkProfile, error is %{public}d", result);
1311         return result;
1312     }
1313 
1314     if ((result = CleanAsanDirectory(oldInfo)) != ERR_OK) {
1315         APP_LOGE("fail to remove asan log path, error is %{public}d", result);
1316         return result;
1317     }
1318 
1319     enableGuard.Dismiss();
1320 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1321     std::shared_ptr<QuickFixDataMgr> quickFixDataMgr = DelayedSingleton<QuickFixDataMgr>::GetInstance();
1322     if (quickFixDataMgr != nullptr) {
1323         APP_LOGD("DeleteInnerAppQuickFix when bundleName :%{public}s uninstall", bundleName.c_str());
1324         quickFixDataMgr->DeleteInnerAppQuickFix(bundleName);
1325     }
1326 #endif
1327     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->DeleteAppProvisionInfo(bundleName)) {
1328         APP_LOGW("bundleName: %{public}s delete appProvisionInfo failed.", bundleName.c_str());
1329     }
1330 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
1331     std::shared_ptr<AppControlManager> appControlMgr = DelayedSingleton<AppControlManager>::GetInstance();
1332     if (appControlMgr != nullptr) {
1333         APP_LOGD("Delete disposed rule when bundleName :%{public}s uninstall", bundleName.c_str());
1334         appControlMgr->DeleteAllDisposedRuleByBundle(oldInfo.GetAppId(), userId_);
1335     }
1336 #endif
1337     APP_LOGD("finish to process %{public}s bundle uninstall", bundleName.c_str());
1338 
1339     // remove drive so file
1340     std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1341     driverInstaller->RemoveDriverSoFile(oldInfo, "", false);
1342     if (oldInfo.GetIsPreInstallApp()) {
1343         MarkPreInstallState(bundleName, true);
1344     }
1345     BundleResourceHelper::DeleteResourceInfo(bundleName);
1346     // remove profile from code signature
1347     RemoveProfileFromCodeSign(bundleName);
1348     return ERR_OK;
1349 }
1350 
ProcessBundleUninstall(const std::string & bundleName,const std::string & modulePackage,const InstallParam & installParam,int32_t & uid)1351 ErrCode BaseBundleInstaller::ProcessBundleUninstall(
1352     const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam, int32_t &uid)
1353 {
1354     APP_LOGD("start to process %{public}s in %{public}s uninstall", bundleName.c_str(), modulePackage.c_str());
1355     if (bundleName.empty() || modulePackage.empty()) {
1356         APP_LOGE("uninstall bundle name or module name empty");
1357         return ERR_APPEXECFWK_UNINSTALL_INVALID_NAME;
1358     }
1359 
1360     dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1361     if (!dataMgr_) {
1362         APP_LOGE("Get dataMgr shared_ptr nullptr");
1363         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
1364     }
1365 
1366     userId_ = GetUserId(installParam.userId);
1367     if (userId_ == Constants::INVALID_USERID) {
1368         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
1369     }
1370 
1371     if (!dataMgr_->HasUserId(userId_)) {
1372         APP_LOGE("The user %{public}d does not exist when uninstall.", userId_);
1373         return ERR_APPEXECFWK_USER_NOT_EXIST;
1374     }
1375 
1376     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
1377     std::lock_guard lock {mtx};
1378     InnerBundleInfo oldInfo;
1379     if (!dataMgr_->GetInnerBundleInfo(bundleName, oldInfo)) {
1380         APP_LOGW("uninstall bundle info missing");
1381         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
1382     }
1383     uninstallBundleAppId_ = oldInfo.GetAppId();
1384     versionCode_ = oldInfo.GetVersionCode();
1385     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); });
1386     if (oldInfo.GetApplicationBundleType() == BundleType::SHARED) {
1387         APP_LOGE("uninstall bundle is shared library");
1388         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_IS_SHARED_LIBRARY;
1389     }
1390 
1391     InnerBundleUserInfo curInnerBundleUserInfo;
1392     if (!oldInfo.GetInnerBundleUserInfo(userId_, curInnerBundleUserInfo)) {
1393         APP_LOGE("bundle(%{public}s) get user(%{public}d) failed when uninstall.",
1394             oldInfo.GetBundleName().c_str(), userId_);
1395         return ERR_APPEXECFWK_USER_NOT_INSTALL_HAP;
1396     }
1397 
1398     uid = curInnerBundleUserInfo.uid;
1399     if (!installParam.forceExecuted
1400         && !oldInfo.GetRemovable() && installParam.noSkipsKill) {
1401         APP_LOGE("uninstall system app");
1402         return ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR;
1403     }
1404 
1405     bool isModuleExist = oldInfo.FindModule(modulePackage);
1406     if (!isModuleExist) {
1407         APP_LOGE("uninstall bundle info missing");
1408         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_MODULE;
1409     }
1410 
1411     if (!UninstallAppControl(oldInfo.GetAppId(), userId_)) {
1412         APP_LOGD("bundleName: %{public}s is not allow uninstall", bundleName.c_str());
1413         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_UNINSTALL;
1414     }
1415 
1416     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START)) {
1417         APP_LOGE("uninstall already start");
1418         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1419     }
1420 
1421     ScopeGuard stateGuard([&] { dataMgr_->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS); });
1422 
1423     // reboot scan case will not kill the bundle
1424     if (installParam.noSkipsKill) {
1425         // kill the bundle process during uninstall.
1426         if (!AbilityManagerHelper::UninstallApplicationProcesses(oldInfo.GetApplicationName(), uid)) {
1427             APP_LOGE("can not kill process, uid : %{public}d", uid);
1428             return ERR_APPEXECFWK_UNINSTALL_KILLING_APP_ERROR;
1429         }
1430     }
1431 
1432     oldInfo.SetInstallMark(bundleName, modulePackage, InstallExceptionStatus::UNINSTALL_PACKAGE_START);
1433     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
1434         APP_LOGE("save install mark failed");
1435         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1436     }
1437 
1438     bool onlyInstallInUser = oldInfo.GetInnerBundleUserInfos().size() == 1;
1439     ErrCode result = ERR_OK;
1440     // if it is the only module in the bundle
1441     if (oldInfo.IsOnlyModule(modulePackage)) {
1442         APP_LOGI("%{public}s is only module", modulePackage.c_str());
1443         enableGuard.Dismiss();
1444         stateGuard.Dismiss();
1445         if (onlyInstallInUser) {
1446             result = RemoveBundle(oldInfo, installParam.isKeepData);
1447             if (result != ERR_OK) {
1448                 APP_LOGE("remove bundle failed");
1449                 return result;
1450             }
1451             // remove profile from code signature
1452             RemoveProfileFromCodeSign(bundleName);
1453 
1454             result = DeleteOldArkNativeFile(oldInfo);
1455             if (result != ERR_OK) {
1456                 APP_LOGE("delete old arkNativeFile failed");
1457                 return result;
1458             }
1459 
1460             result = DeleteArkProfile(bundleName, userId_);
1461             if (result != ERR_OK) {
1462                 APP_LOGE("fail to removeArkProfile, error is %{public}d", result);
1463                 return result;
1464             }
1465 
1466             if ((result = CleanAsanDirectory(oldInfo)) != ERR_OK) {
1467                 APP_LOGE("fail to remove asan log path, error is %{public}d", result);
1468                 return result;
1469             }
1470 
1471             if (oldInfo.GetIsPreInstallApp()) {
1472                 MarkPreInstallState(bundleName, true);
1473             }
1474 
1475             return ERR_OK;
1476         }
1477         return RemoveBundleUserData(oldInfo, installParam.isKeepData);
1478     }
1479 
1480     if (onlyInstallInUser) {
1481         APP_LOGI("%{public}s is only install at the userId %{public}d", bundleName.c_str(), userId_);
1482         result = RemoveModuleAndDataDir(oldInfo, modulePackage, userId_, installParam.isKeepData);
1483     } else {
1484         if (!installParam.isKeepData) {
1485             result = RemoveModuleDataDir(oldInfo, modulePackage, userId_);
1486         }
1487     }
1488 
1489     if (result != ERR_OK) {
1490         APP_LOGE("remove module dir failed");
1491         return result;
1492     }
1493 
1494     oldInfo.SetInstallMark(bundleName, modulePackage, InstallExceptionStatus::INSTALL_FINISH);
1495     APP_LOGD("start to remove module info of %{public}s in %{public}s ", modulePackage.c_str(), bundleName.c_str());
1496     if (!dataMgr_->RemoveModuleInfo(bundleName, modulePackage, oldInfo)) {
1497         APP_LOGE("RemoveModuleInfo failed");
1498         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1499     }
1500     std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
1501     driverInstaller->RemoveDriverSoFile(oldInfo, oldInfo.GetModuleName(modulePackage), false);
1502     APP_LOGD("finish to process %{public}s in %{public}s uninstall", bundleName.c_str(), modulePackage.c_str());
1503     return ERR_OK;
1504 }
1505 
MarkPreInstallState(const std::string & bundleName,bool isUninstalled)1506 void BaseBundleInstaller::MarkPreInstallState(const std::string &bundleName, bool isUninstalled)
1507 {
1508     if (!dataMgr_) {
1509         APP_LOGE("dataMgr is nullptr");
1510         return;
1511     }
1512 
1513     PreInstallBundleInfo preInstallBundleInfo;
1514     preInstallBundleInfo.SetBundleName(bundleName);
1515     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
1516         APP_LOGI("No PreInstallBundleInfo(%{public}s) in db", bundleName.c_str());
1517         return;
1518     }
1519 
1520     preInstallBundleInfo.SetIsUninstalled(isUninstalled);
1521     dataMgr_->SavePreInstallBundleInfo(bundleName, preInstallBundleInfo);
1522 }
1523 
ProcessInstallBundleByBundleName(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)1524 ErrCode BaseBundleInstaller::ProcessInstallBundleByBundleName(
1525     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
1526 {
1527     APP_LOGD("Process Install Bundle(%{public}s) start", bundleName.c_str());
1528     return InnerProcessInstallByPreInstallInfo(bundleName, installParam, uid);
1529 }
1530 
ProcessRecover(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)1531 ErrCode BaseBundleInstaller::ProcessRecover(
1532     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
1533 {
1534     APP_LOGD("Process Recover Bundle(%{public}s) start", bundleName.c_str());
1535     ErrCode result = InnerProcessInstallByPreInstallInfo(bundleName, installParam, uid);
1536     return result;
1537 }
1538 
InnerProcessInstallByPreInstallInfo(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)1539 ErrCode BaseBundleInstaller::InnerProcessInstallByPreInstallInfo(
1540     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
1541 {
1542     dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1543     if (dataMgr_ == nullptr) {
1544         APP_LOGE("Get dataMgr shared_ptr nullptr.");
1545         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
1546     }
1547 
1548     userId_ = GetUserId(installParam.userId);
1549     if (userId_ == Constants::INVALID_USERID) {
1550         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
1551     }
1552 
1553     if (!dataMgr_->HasUserId(userId_)) {
1554         APP_LOGE("The user %{public}d does not exist.", userId_);
1555         return ERR_APPEXECFWK_USER_NOT_EXIST;
1556     }
1557 
1558     {
1559         auto &mtx = dataMgr_->GetBundleMutex(bundleName);
1560         std::lock_guard lock {mtx};
1561         InnerBundleInfo oldInfo;
1562         bool isAppExist = dataMgr_->GetInnerBundleInfo(bundleName, oldInfo);
1563         if (isAppExist) {
1564             dataMgr_->EnableBundle(bundleName);
1565             if (oldInfo.GetApplicationBundleType() == BundleType::SHARED) {
1566                 APP_LOGD("shared bundle (%{public}s) is irrelevant to user", bundleName.c_str());
1567                 return ERR_OK;
1568             }
1569 
1570             versionCode_ = oldInfo.GetVersionCode();
1571             if (oldInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK) {
1572                 APP_LOGD("Appservice (%{public}s) only install in U0", bundleName.c_str());
1573                 return ERR_OK;
1574             }
1575 
1576             if (oldInfo.HasInnerBundleUserInfo(userId_)) {
1577                 APP_LOGE("App is exist in user(%{public}d).", userId_);
1578                 return ERR_APPEXECFWK_INSTALL_ALREADY_EXIST;
1579             }
1580 
1581             ErrCode ret = InstallNormalAppControl(oldInfo.GetAppId(), userId_, installParam.isPreInstallApp);
1582             if (ret != ERR_OK) {
1583                 APP_LOGE("appid:%{private}s check install app control failed", oldInfo.GetAppId().c_str());
1584                 return ret;
1585             }
1586 
1587             ret = CheckSingleton(oldInfo, userId_);
1588             CHECK_RESULT(ret, "Check singleton failed %{public}d");
1589 
1590             InnerBundleUserInfo curInnerBundleUserInfo;
1591             curInnerBundleUserInfo.bundleUserInfo.userId = userId_;
1592             curInnerBundleUserInfo.bundleName = bundleName;
1593             oldInfo.AddInnerBundleUserInfo(curInnerBundleUserInfo);
1594             ScopeGuard userGuard([&] { RemoveBundleUserData(oldInfo, false); });
1595             auto accessTokenIdEx = CreateAccessTokenIdEx(oldInfo);
1596             accessTokenId_ = accessTokenIdEx.tokenIdExStruct.tokenID;
1597             oldInfo.SetAccessTokenIdEx(accessTokenIdEx, userId_);
1598             ErrCode result = GrantRequestPermissions(oldInfo, accessTokenId_);
1599             if (result != ERR_OK) {
1600                 return result;
1601             }
1602 
1603             result = CreateBundleUserData(oldInfo);
1604             if (result != ERR_OK) {
1605                 return result;
1606             }
1607 
1608             // extract ap file
1609             result = ExtractAllArkProfileFile(oldInfo);
1610             if (result != ERR_OK) {
1611                 return result;
1612             }
1613 
1614             userGuard.Dismiss();
1615             uid = oldInfo.GetUid(userId_);
1616             GetInstallEventInfo(oldInfo, sysEventInfo_);
1617             return ERR_OK;
1618         }
1619     }
1620 
1621     PreInstallBundleInfo preInstallBundleInfo;
1622     preInstallBundleInfo.SetBundleName(bundleName);
1623     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)
1624         || preInstallBundleInfo.GetBundlePaths().empty()) {
1625         APP_LOGE("Get PreInstallBundleInfo faile, bundleName: %{public}s.", bundleName.c_str());
1626         return ERR_APPEXECFWK_RECOVER_INVALID_BUNDLE_NAME;
1627     }
1628 
1629     APP_LOGD("Get preInstall bundlePath success.");
1630     std::vector<std::string> pathVec;
1631     auto innerInstallParam = installParam;
1632     bool isSharedBundle = preInstallBundleInfo.GetBundlePaths().front().find(PRE_INSTALL_HSP_PATH) != std::string::npos;
1633     if (isSharedBundle) {
1634         innerInstallParam.sharedBundleDirPaths = preInstallBundleInfo.GetBundlePaths();
1635     } else {
1636         pathVec = preInstallBundleInfo.GetBundlePaths();
1637     }
1638     innerInstallParam.isPreInstallApp = true;
1639     innerInstallParam.removable = preInstallBundleInfo.GetRemovable();
1640     innerInstallParam.copyHapToInstallPath = false;
1641     return ProcessBundleInstall(pathVec, innerInstallParam, preInstallBundleInfo.GetAppType(), uid);
1642 }
1643 
RemoveBundle(InnerBundleInfo & info,bool isKeepData)1644 ErrCode BaseBundleInstaller::RemoveBundle(InnerBundleInfo &info, bool isKeepData)
1645 {
1646     ErrCode result = RemoveBundleAndDataDir(info, isKeepData);
1647     if (result != ERR_OK) {
1648         APP_LOGE("remove bundle dir failed");
1649         dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::INSTALL_SUCCESS);
1650         return result;
1651     }
1652 
1653     if (!dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::UNINSTALL_SUCCESS)) {
1654         APP_LOGE("delete inner info failed");
1655         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1656     }
1657     accessTokenId_ = info.GetAccessTokenId(userId_);
1658     if (BundlePermissionMgr::DeleteAccessTokenId(accessTokenId_) !=
1659         AccessToken::AccessTokenKitRet::RET_SUCCESS) {
1660         APP_LOGE("delete accessToken failed");
1661     }
1662     return ERR_OK;
1663 }
1664 
ProcessBundleInstallStatus(InnerBundleInfo & info,int32_t & uid)1665 ErrCode BaseBundleInstaller::ProcessBundleInstallStatus(InnerBundleInfo &info, int32_t &uid)
1666 {
1667     modulePackage_ = info.GetCurrentModulePackage();
1668     APP_LOGD("ProcessBundleInstallStatus with bundleName %{public}s and packageName %{public}s",
1669         bundleName_.c_str(), modulePackage_.c_str());
1670     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_START)) {
1671         APP_LOGE("install already start");
1672         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
1673     }
1674     info.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::INSTALL_START);
1675     if (!dataMgr_->SaveInnerBundleInfo(info)) {
1676         APP_LOGE("save install mark to storage failed");
1677         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1678     }
1679     ScopeGuard stateGuard([&] { dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_FAIL); });
1680     ErrCode result = CreateBundleAndDataDir(info);
1681     if (result != ERR_OK) {
1682         APP_LOGE("create bundle and data dir failed");
1683         return result;
1684     }
1685 
1686     // delivery sign profile to code signature
1687     result = DeliveryProfileToCodeSign();
1688     CHECK_RESULT(result, "delivery profile failed %{public}d");
1689 
1690     ScopeGuard bundleGuard([&] { RemoveBundleAndDataDir(info, false); });
1691     std::string modulePath = info.GetAppCodePath() + Constants::PATH_SEPARATOR + modulePackage_;
1692     result = ExtractModule(info, modulePath);
1693     if (result != ERR_OK) {
1694         APP_LOGE("extract module failed");
1695         return result;
1696     }
1697 
1698     info.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::INSTALL_FINISH);
1699     uid = info.GetUid(userId_);
1700     info.SetBundleInstallTime(BundleUtil::GetCurrentTimeMs(), userId_);
1701     auto accessTokenIdEx = CreateAccessTokenIdEx(info);
1702     accessTokenId_ = accessTokenIdEx.tokenIdExStruct.tokenID;
1703     info.SetAccessTokenIdEx(accessTokenIdEx, userId_);
1704     result = GrantRequestPermissions(info, accessTokenId_);
1705     if (result != ERR_OK) {
1706         return result;
1707     }
1708     if (!dataMgr_->AddInnerBundleInfo(bundleName_, info)) {
1709         APP_LOGE("add bundle %{public}s info failed", bundleName_.c_str());
1710         dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_START);
1711         dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_SUCCESS);
1712         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1713     }
1714 
1715     stateGuard.Dismiss();
1716     bundleGuard.Dismiss();
1717 
1718     APP_LOGD("finish to call processBundleInstallStatus");
1719     return ERR_OK;
1720 }
1721 
AllowSingletonChange(const std::string & bundleName)1722 bool BaseBundleInstaller::AllowSingletonChange(const std::string &bundleName)
1723 {
1724     return SINGLETON_WHITE_LIST.find(bundleName) != SINGLETON_WHITE_LIST.end();
1725 }
1726 
ProcessBundleUpdateStatus(InnerBundleInfo & oldInfo,InnerBundleInfo & newInfo,bool isReplace,bool noSkipsKill)1727 ErrCode BaseBundleInstaller::ProcessBundleUpdateStatus(
1728     InnerBundleInfo &oldInfo, InnerBundleInfo &newInfo, bool isReplace, bool noSkipsKill)
1729 {
1730     modulePackage_ = newInfo.GetCurrentModulePackage();
1731     if (modulePackage_.empty()) {
1732         APP_LOGE("get current package failed");
1733         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
1734     }
1735 
1736     if (isFeatureNeedUninstall_) {
1737         uninstallModuleVec_.emplace_back(modulePackage_);
1738     }
1739 
1740     if (oldInfo.IsSingleton() != newInfo.IsSingleton()) {
1741         if ((oldInfo.IsSingleton() && !newInfo.IsSingleton()) && newInfo.GetIsPreInstallApp()
1742             && AllowSingletonChange(newInfo.GetBundleName())) {
1743             APP_LOGI("Singleton %{public}s changed", newInfo.GetBundleName().c_str());
1744             singletonState_ = SingletonState::SINGLETON_TO_NON;
1745         } else {
1746             APP_LOGE("Singleton not allow changed");
1747             return ERR_APPEXECFWK_INSTALL_SINGLETON_INCOMPATIBLE;
1748         }
1749     }
1750 
1751     auto result = CheckOverlayUpdate(oldInfo, newInfo, userId_);
1752     if (result != ERR_OK) {
1753         APP_LOGE("CheckOverlayUpdate failed due to %{public}d", result);
1754         return result;
1755     }
1756 
1757     APP_LOGD("bundleName %{public}s, packageName %{public}s", newInfo.GetBundleName().c_str(), modulePackage_.c_str());
1758     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_START)) {
1759         APP_LOGE("update already start");
1760         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
1761     }
1762 
1763     if (!CheckAppIdentifier(oldInfo, newInfo)) {
1764         return ERR_APPEXECFWK_INSTALL_FAILED_INCONSISTENT_SIGNATURE;
1765     }
1766     APP_LOGD("ProcessBundleUpdateStatus noSkipsKill = %{public}d", noSkipsKill);
1767     // now there are two cases for updating:
1768     // 1. bundle exist, hap exist, update hap
1769     // 2. bundle exist, install new hap
1770     bool isModuleExist = oldInfo.FindModule(modulePackage_);
1771     if (isModuleExist) {
1772         isModuleUpdate_ = true;
1773     }
1774     newInfo.RestoreFromOldInfo(oldInfo);
1775     result = isModuleExist ? ProcessModuleUpdate(newInfo, oldInfo,
1776         isReplace, noSkipsKill) : ProcessNewModuleInstall(newInfo, oldInfo);
1777     if (result != ERR_OK) {
1778         APP_LOGE("install module failed %{public}d", result);
1779         return result;
1780     }
1781 
1782     APP_LOGD("finish to call ProcessBundleUpdateStatus");
1783     return ERR_OK;
1784 }
1785 
CheckAppIdentifier(InnerBundleInfo & oldInfo,InnerBundleInfo & newInfo)1786 bool BaseBundleInstaller::CheckAppIdentifier(InnerBundleInfo &oldInfo, InnerBundleInfo &newInfo)
1787 {
1788     if (!otaInstall_ && oldInfo.GetVersionCode() == newInfo.GetVersionCode()) {
1789         if ((oldInfo.GetAppIdentifier() != newInfo.GetAppIdentifier()) ||
1790             (oldInfo.GetProvisionId() != newInfo.GetProvisionId())) {
1791             APP_LOGE("same versionCode, appIdentifier or appId is not same");
1792             return false;
1793         }
1794     }
1795 
1796     if (oldInfo.GetAppIdentifier().empty() || newInfo.GetAppIdentifier().empty()) {
1797         if (oldInfo.GetProvisionId() != newInfo.GetProvisionId()) {
1798             APP_LOGE("the signature of the new bundle is not the same as old one");
1799             return false;
1800         }
1801         return true;
1802     }
1803     if (oldInfo.GetAppIdentifier() != newInfo.GetAppIdentifier()) {
1804         APP_LOGE("the appIdentifier of the new bundle is not the same as old one");
1805         return false;
1806     }
1807     return true;
1808 }
1809 
ProcessNewModuleInstall(InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo)1810 ErrCode BaseBundleInstaller::ProcessNewModuleInstall(InnerBundleInfo &newInfo, InnerBundleInfo &oldInfo)
1811 {
1812     APP_LOGD("ProcessNewModuleInstall %{public}s, userId: %{public}d.",
1813         newInfo.GetBundleName().c_str(), userId_);
1814     if ((!isFeatureNeedUninstall_ && !otaInstall_) && (newInfo.HasEntry() && oldInfo.HasEntry())) {
1815         APP_LOGE("install more than one entry module");
1816         return ERR_APPEXECFWK_INSTALL_ENTRY_ALREADY_EXIST;
1817     }
1818 
1819     if (bundleInstallChecker_->IsContainModuleName(newInfo, oldInfo)) {
1820         APP_LOGE("moduleName is already existed");
1821         return ERR_APPEXECFWK_INSTALL_NOT_UNIQUE_DISTRO_MODULE_NAME;
1822     }
1823 
1824     // same version need to check app label
1825     ErrCode result = ERR_OK;
1826     if (!otaInstall_ && (oldInfo.GetVersionCode() == newInfo.GetVersionCode())) {
1827         result = CheckAppLabel(oldInfo, newInfo);
1828         if (result != ERR_OK) {
1829             APP_LOGE("CheckAppLabel failed %{public}d", result);
1830             return result;
1831         }
1832         if (!CheckDuplicateProxyData(newInfo, oldInfo)) {
1833             APP_LOGE("CheckDuplicateProxyData with old info failed");
1834             return ERR_APPEXECFWK_INSTALL_CHECK_PROXY_DATA_URI_FAILED;
1835         }
1836     }
1837 
1838     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_NEW_START);
1839     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
1840         APP_LOGE("save install mark failed");
1841         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1842     }
1843     std::string modulePath = newInfo.GetAppCodePath() + Constants::PATH_SEPARATOR + modulePackage_;
1844     result = ExtractModule(newInfo, modulePath);
1845     if (result != ERR_OK) {
1846         APP_LOGE("extract module and rename failed");
1847         return result;
1848     }
1849     ScopeGuard moduleGuard([&] { RemoveModuleDir(modulePath); });
1850     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
1851         APP_LOGE("new moduleupdate state failed");
1852         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1853     }
1854 
1855     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::INSTALL_FINISH);
1856 
1857     auto bundleUserInfos = oldInfo.GetInnerBundleUserInfos();
1858     for (const auto &info : bundleUserInfos) {
1859         if (info.second.accessTokenId == 0) {
1860             continue;
1861         }
1862         Security::AccessToken::AccessTokenIDEx tokenIdEx;
1863         tokenIdEx.tokenIDEx = info.second.accessTokenIdEx;
1864         bool needUpdateToken = false;
1865         if (tokenIdEx.tokenIDEx == 0) {
1866             needUpdateToken = true;
1867             tokenIdEx.tokenIDEx = info.second.accessTokenId;
1868         }
1869         std::vector<std::string> newRequestPermName;
1870         if (!BundlePermissionMgr::AddDefineAndRequestPermissions(tokenIdEx, newInfo, newRequestPermName)) {
1871             APP_LOGE("BundlePermissionMgr::AddDefineAndRequestPermissions failed %{public}s", bundleName_.c_str());
1872             return ERR_APPEXECFWK_INSTALL_UPDATE_HAP_TOKEN_FAILED;
1873         }
1874         if (!BundlePermissionMgr::GrantRequestPermissions(newInfo, newRequestPermName, info.second.accessTokenId)) {
1875             APP_LOGE("BundlePermissionMgr::GrantRequestPermissions failed %{public}s", bundleName_.c_str());
1876             return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
1877         }
1878         if (needUpdateToken) {
1879             oldInfo.SetAccessTokenIdEx(tokenIdEx, info.second.bundleUserInfo.userId);
1880         }
1881     }
1882 
1883     oldInfo.SetBundleUpdateTime(BundleUtil::GetCurrentTimeMs(), userId_);
1884     if ((result = ProcessAsanDirectory(newInfo)) != ERR_OK) {
1885         APP_LOGE("process asan log directory failed!");
1886         return result;
1887     }
1888     if (!dataMgr_->AddNewModuleInfo(bundleName_, newInfo, oldInfo)) {
1889         APP_LOGE(
1890             "add module %{public}s to innerBundleInfo %{public}s failed", modulePackage_.c_str(), bundleName_.c_str());
1891         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1892     }
1893     moduleGuard.Dismiss();
1894     return ERR_OK;
1895 }
1896 
ProcessModuleUpdate(InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo,bool isReplace,bool noSkipsKill)1897 ErrCode BaseBundleInstaller::ProcessModuleUpdate(InnerBundleInfo &newInfo,
1898     InnerBundleInfo &oldInfo, bool isReplace, bool noSkipsKill)
1899 {
1900     APP_LOGD("ProcessModuleUpdate, bundleName : %{public}s, moduleName : %{public}s, userId: %{public}d.",
1901         newInfo.GetBundleName().c_str(), newInfo.GetCurrentModulePackage().c_str(), userId_);
1902     // update module type is forbidden
1903     if ((!isFeatureNeedUninstall_ && !otaInstall_) && (newInfo.HasEntry() && oldInfo.HasEntry())) {
1904         if (!oldInfo.IsEntryModule(modulePackage_)) {
1905             APP_LOGE("install more than one entry module");
1906             return ERR_APPEXECFWK_INSTALL_ENTRY_ALREADY_EXIST;
1907         }
1908     }
1909 
1910     if (!bundleInstallChecker_->IsExistedDistroModule(newInfo, oldInfo)) {
1911         APP_LOGE("moduleName is inconsistent in the updating hap");
1912         return ERR_APPEXECFWK_INSTALL_INCONSISTENT_MODULE_NAME;
1913     }
1914 
1915     ErrCode result = ERR_OK;
1916     if (!otaInstall_ && (versionCode_ == oldInfo.GetVersionCode())) {
1917         if (((result = CheckAppLabel(oldInfo, newInfo)) != ERR_OK)) {
1918             APP_LOGE("CheckAppLabel failed %{public}d", result);
1919             return result;
1920         }
1921 
1922         if (!isReplace) {
1923             if (hasInstalledInUser_) {
1924                 APP_LOGE("fail to install already existing bundle using normal flag");
1925                 return ERR_APPEXECFWK_INSTALL_ALREADY_EXIST;
1926             }
1927 
1928             // app versionCode equals to the old and do not need to update module
1929             // and only need to update userInfo
1930             newInfo.SetOnlyCreateBundleUser(true);
1931             if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
1932                 APP_LOGE("update state failed");
1933                 return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
1934             }
1935             return ERR_OK;
1936         }
1937     }
1938 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
1939     result = OverlayDataMgr::GetInstance()->UpdateOverlayModule(newInfo, oldInfo);
1940     CHECK_RESULT(result, "UpdateOverlayModule failed %{public}d");
1941 #endif
1942 
1943     APP_LOGD("ProcessModuleUpdate noSkipsKill = %{public}d", noSkipsKill);
1944     // reboot scan case will not kill the bundle
1945     if (noSkipsKill) {
1946         // kill the bundle process during updating
1947         if (!AbilityManagerHelper::UninstallApplicationProcesses(
1948             oldInfo.GetApplicationName(), oldInfo.GetUid(userId_))) {
1949             APP_LOGE("fail to kill running application");
1950             return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1951         }
1952     }
1953 
1954     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_EXISTED_START);
1955     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
1956         APP_LOGE("save install mark failed");
1957         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1958     }
1959 
1960     result = CheckArkProfileDir(newInfo, oldInfo);
1961     CHECK_RESULT(result, "CheckArkProfileDir failed %{public}d");
1962 
1963     result = ProcessAsanDirectory(newInfo);
1964     CHECK_RESULT(result, "process asan log directory failed %{public}d");
1965 
1966     moduleTmpDir_ = newInfo.GetAppCodePath() + Constants::PATH_SEPARATOR + modulePackage_ + Constants::TMP_SUFFIX;
1967     result = ExtractModule(newInfo, moduleTmpDir_);
1968     CHECK_RESULT(result, "extract module and rename failed %{public}d");
1969 
1970     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
1971         APP_LOGE("old module update state failed");
1972         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1973     }
1974 
1975     newInfo.RestoreModuleInfo(oldInfo);
1976     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_FINISH);
1977     oldInfo.SetBundleUpdateTime(BundleUtil::GetCurrentTimeMs(), userId_);
1978     auto noUpdateInfo = oldInfo;
1979     if (!dataMgr_->UpdateInnerBundleInfo(bundleName_, newInfo, oldInfo)) {
1980         APP_LOGE("update innerBundleInfo %{public}s failed", bundleName_.c_str());
1981         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1982     }
1983     result = UpdateDefineAndRequestPermissions(noUpdateInfo, oldInfo);
1984     CHECK_RESULT(result, "UpdateDefineAndRequestPermissions failed %{public}d");
1985 
1986     result = SetDirApl(oldInfo);
1987     CHECK_RESULT(result, "SetDirApl failed %{public}d");
1988 
1989     needDeleteQuickFixInfo_ = true;
1990     return ERR_OK;
1991 }
1992 
ProcessQuickFixWhenInstallNewModule(const InstallParam & installParam,const std::unordered_map<std::string,InnerBundleInfo> & newInfos)1993 void BaseBundleInstaller::ProcessQuickFixWhenInstallNewModule(const InstallParam &installParam,
1994     const std::unordered_map<std::string, InnerBundleInfo> &newInfos)
1995 {
1996 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1997     // hqf extract diff file or apply diff patch failed does not affect the hap installation
1998     InnerBundleInfo bundleInfo;
1999     bool isBundleExist = false;
2000     if (!GetInnerBundleInfo(bundleInfo, isBundleExist) || !isBundleExist) {
2001         return;
2002     }
2003     for (auto &info : newInfos) {
2004         modulePackage_ = info.second.GetCurrentModulePackage();
2005         if (!installedModules_[modulePackage_]) {
2006             modulePath_ = info.first;
2007             if (bundleInfo.IsEncryptedMoudle(modulePackage_) && installParam.copyHapToInstallPath) {
2008                 modulePath_ = GetHapPath(info.second);
2009             }
2010             ProcessHqfInfo(bundleInfo, info.second);
2011         }
2012     }
2013 #endif
2014 }
2015 
ProcessHqfInfo(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const2016 void BaseBundleInstaller::ProcessHqfInfo(
2017     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
2018 {
2019 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2020     APP_LOGI("ProcessHqfInfo start, bundleName: %{public}s, moduleName: %{public}s", bundleName_.c_str(),
2021         modulePackage_.c_str());
2022     std::string cpuAbi;
2023     std::string nativeLibraryPath;
2024     if (!newInfo.FetchNativeSoAttrs(modulePackage_, cpuAbi, nativeLibraryPath)) {
2025         APP_LOGI("No native so, bundleName: %{public}s, moduleName: %{public}s", bundleName_.c_str(),
2026             modulePackage_.c_str());
2027         return;
2028     }
2029     auto pos = nativeLibraryPath.rfind(Constants::LIBS);
2030     if (pos != std::string::npos) {
2031         nativeLibraryPath = nativeLibraryPath.substr(pos, nativeLibraryPath.length() - pos);
2032     }
2033 
2034     ErrCode ret = ProcessDeployedHqfInfo(
2035         nativeLibraryPath, cpuAbi, newInfo, oldInfo.GetAppQuickFix());
2036     if (ret != ERR_OK) {
2037         APP_LOGW("ProcessDeployedHqfInfo failed, errcode: %{public}d", ret);
2038         return;
2039     }
2040 
2041     ret = ProcessDeployingHqfInfo(nativeLibraryPath, cpuAbi, newInfo);
2042     if (ret != ERR_OK) {
2043         APP_LOGW("ProcessDeployingHqfInfo failed, errcode: %{public}d", ret);
2044         return;
2045     }
2046 
2047     APP_LOGI("ProcessHqfInfo end");
2048 #endif
2049 }
2050 
ProcessDeployedHqfInfo(const std::string & nativeLibraryPath,const std::string & cpuAbi,const InnerBundleInfo & newInfo,const AppQuickFix & oldAppQuickFix) const2051 ErrCode BaseBundleInstaller::ProcessDeployedHqfInfo(const std::string &nativeLibraryPath,
2052     const std::string &cpuAbi, const InnerBundleInfo &newInfo, const AppQuickFix &oldAppQuickFix) const
2053 {
2054 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2055     APP_LOGI("ProcessDeployedHqfInfo");
2056     auto appQuickFix = oldAppQuickFix;
2057     AppqfInfo &appQfInfo = appQuickFix.deployedAppqfInfo;
2058     if (isFeatureNeedUninstall_ || appQfInfo.hqfInfos.empty()) {
2059         APP_LOGI("No need ProcessDeployedHqfInfo");
2060         return ERR_OK;
2061     }
2062 
2063     ErrCode ret = ProcessDiffFiles(appQfInfo, nativeLibraryPath, cpuAbi);
2064     if (ret != ERR_OK) {
2065         APP_LOGE("ProcessDeployedHqfInfo failed, errcode: %{public}d", ret);
2066         return ret;
2067     }
2068 
2069     std::string newSoPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
2070         Constants::PATH_SEPARATOR + Constants::PATCH_PATH +
2071         std::to_string(appQfInfo.versionCode) + Constants::PATH_SEPARATOR + nativeLibraryPath;
2072     bool isExist = false;
2073     if ((InstalldClient::GetInstance()->IsExistDir(newSoPath, isExist) != ERR_OK) || !isExist) {
2074         APP_LOGW("Patch no diff file");
2075         return ERR_OK;
2076     }
2077 
2078     ret = UpdateLibAttrs(newInfo, cpuAbi, nativeLibraryPath, appQfInfo);
2079     if (ret != ERR_OK) {
2080         APP_LOGE("UpdateModuleLib failed, errcode: %{public}d", ret);
2081         return ret;
2082     }
2083 
2084     InnerBundleInfo innerBundleInfo;
2085     if (!dataMgr_->FetchInnerBundleInfo(bundleName_, innerBundleInfo)) {
2086         APP_LOGE("Fetch bundleInfo(%{public}s) failed.", bundleName_.c_str());
2087         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
2088     }
2089 
2090     innerBundleInfo.SetAppQuickFix(appQuickFix);
2091     if (!dataMgr_->UpdateQuickFixInnerBundleInfo(bundleName_, innerBundleInfo)) {
2092         APP_LOGE("update quickfix innerbundleInfo failed");
2093         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2094     }
2095 #endif
2096     return ERR_OK;
2097 }
2098 
ProcessDeployingHqfInfo(const std::string & nativeLibraryPath,const std::string & cpuAbi,const InnerBundleInfo & newInfo) const2099 ErrCode BaseBundleInstaller::ProcessDeployingHqfInfo(
2100     const std::string &nativeLibraryPath, const std::string &cpuAbi, const InnerBundleInfo &newInfo) const
2101 {
2102 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2103     APP_LOGI("ProcessDeployingHqfInfo");
2104     std::shared_ptr<QuickFixDataMgr> quickFixDataMgr = DelayedSingleton<QuickFixDataMgr>::GetInstance();
2105     if (quickFixDataMgr == nullptr) {
2106         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2107     }
2108 
2109     InnerAppQuickFix innerAppQuickFix;
2110     if (!quickFixDataMgr->QueryInnerAppQuickFix(bundleName_, innerAppQuickFix)) {
2111         return ERR_OK;
2112     }
2113 
2114     auto appQuickFix = innerAppQuickFix.GetAppQuickFix();
2115     AppqfInfo &appQfInfo = appQuickFix.deployingAppqfInfo;
2116     ErrCode ret = ProcessDiffFiles(appQfInfo, nativeLibraryPath, cpuAbi);
2117     if (ret != ERR_OK) {
2118         APP_LOGE("ProcessDeployingHqfInfo failed, errcode: %{public}d", ret);
2119         return ret;
2120     }
2121 
2122     std::string newSoPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
2123         Constants::PATH_SEPARATOR + Constants::PATCH_PATH +
2124         std::to_string(appQfInfo.versionCode) + Constants::PATH_SEPARATOR + nativeLibraryPath;
2125     bool isExist = false;
2126     if ((InstalldClient::GetInstance()->IsExistDir(newSoPath, isExist) != ERR_OK) || !isExist) {
2127         APP_LOGW("Patch no diff file");
2128         return ERR_OK;
2129     }
2130 
2131     ret = UpdateLibAttrs(newInfo, cpuAbi, nativeLibraryPath, appQfInfo);
2132     if (ret != ERR_OK) {
2133         APP_LOGE("UpdateModuleLib failed, errcode: %{public}d", ret);
2134         return ret;
2135     }
2136 
2137     innerAppQuickFix.SetAppQuickFix(appQuickFix);
2138     if (!quickFixDataMgr->SaveInnerAppQuickFix(innerAppQuickFix)) {
2139         APP_LOGE("bundleName: %{public}s, inner app quick fix save failed", bundleName_.c_str());
2140         return ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED;
2141     }
2142 #endif
2143     return ERR_OK;
2144 }
2145 
UpdateLibAttrs(const InnerBundleInfo & newInfo,const std::string & cpuAbi,const std::string & nativeLibraryPath,AppqfInfo & appQfInfo) const2146 ErrCode BaseBundleInstaller::UpdateLibAttrs(const InnerBundleInfo &newInfo,
2147     const std::string &cpuAbi, const std::string &nativeLibraryPath, AppqfInfo &appQfInfo) const
2148 {
2149 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2150     auto newNativeLibraryPath = Constants::PATCH_PATH +
2151         std::to_string(appQfInfo.versionCode) + Constants::PATH_SEPARATOR + nativeLibraryPath;
2152     auto moduleName = newInfo.GetCurModuleName();
2153     bool isLibIsolated = newInfo.IsLibIsolated(moduleName);
2154     if (!isLibIsolated) {
2155         appQfInfo.nativeLibraryPath = newNativeLibraryPath;
2156         appQfInfo.cpuAbi = cpuAbi;
2157         return ERR_OK;
2158     }
2159 
2160     for (auto &hqfInfo : appQfInfo.hqfInfos) {
2161         if (hqfInfo.moduleName != moduleName) {
2162             continue;
2163         }
2164 
2165         hqfInfo.nativeLibraryPath = newNativeLibraryPath;
2166         hqfInfo.cpuAbi = cpuAbi;
2167         if (!BundleUtil::StartWith(appQfInfo.nativeLibraryPath, Constants::PATCH_PATH)) {
2168             appQfInfo.nativeLibraryPath.clear();
2169         }
2170 
2171         return ERR_OK;
2172     }
2173 
2174     return ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST;
2175 #else
2176     return ERR_OK;
2177 #endif
2178 }
2179 
CheckHapLibsWithPatchLibs(const std::string & nativeLibraryPath,const std::string & hqfLibraryPath) const2180 bool BaseBundleInstaller::CheckHapLibsWithPatchLibs(
2181     const std::string &nativeLibraryPath, const std::string &hqfLibraryPath) const
2182 {
2183 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2184     if (!hqfLibraryPath.empty()) {
2185         auto position = hqfLibraryPath.find(Constants::PATH_SEPARATOR);
2186         if (position == std::string::npos) {
2187             return false;
2188         }
2189 
2190         auto newHqfLibraryPath = hqfLibraryPath.substr(position);
2191         if (!BundleUtil::EndWith(nativeLibraryPath, newHqfLibraryPath)) {
2192             APP_LOGE("error: nativeLibraryPath not same, newInfo: %{public}s, hqf: %{public}s",
2193                 nativeLibraryPath.c_str(), newHqfLibraryPath.c_str());
2194             return false;
2195         }
2196     }
2197 #endif
2198     return true;
2199 }
2200 
ExtractSoFiles(const std::string & soPath,const std::string & cpuAbi) const2201 bool BaseBundleInstaller::ExtractSoFiles(const std::string &soPath, const std::string &cpuAbi) const
2202 {
2203     ExtractParam extractParam;
2204     extractParam.extractFileType = ExtractFileType::SO;
2205     extractParam.srcPath = modulePath_;
2206     extractParam.targetPath = soPath;
2207     extractParam.cpuAbi = cpuAbi;
2208     if (InstalldClient::GetInstance()->ExtractFiles(extractParam) != ERR_OK) {
2209         APP_LOGE("bundleName: %{public}s moduleName: %{public}s extract so failed", bundleName_.c_str(),
2210             modulePackage_.c_str());
2211         return false;
2212     }
2213     return true;
2214 }
2215 
ExtractEncryptedSoFiles(const InnerBundleInfo & info,const std::string & tmpSoPath,int32_t uid) const2216 bool BaseBundleInstaller::ExtractEncryptedSoFiles(const InnerBundleInfo &info,
2217     const std::string &tmpSoPath, int32_t uid) const
2218 {
2219     APP_LOGD("start to extract decoded so files to tmp path");
2220     std::string cpuAbi = "";
2221     std::string nativeLibraryPath = "";
2222     bool isSoExisted = info.FetchNativeSoAttrs(info.GetCurrentModulePackage(), cpuAbi, nativeLibraryPath);
2223     if (!isSoExisted) {
2224         APP_LOGD("so is not existed");
2225         return true;
2226     }
2227     std::string realSoFilesPath;
2228     if (info.IsCompressNativeLibs(info.GetCurModuleName())) {
2229         realSoFilesPath.append(Constants::BUNDLE_CODE_DIR).append(Constants::PATH_SEPARATOR)
2230             .append(bundleName_).append(Constants::PATH_SEPARATOR).append(nativeLibraryPath);
2231         if (realSoFilesPath.back() != Constants::PATH_SEPARATOR[0]) {
2232             realSoFilesPath += Constants::PATH_SEPARATOR;
2233         }
2234     }
2235     APP_LOGD("real so files path is %{public}s, tmpSoPath is %{public}s", realSoFilesPath.c_str(), tmpSoPath.c_str());
2236     return InstalldClient::GetInstance()->ExtractEncryptedSoFiles(modulePath_, realSoFilesPath, cpuAbi,
2237         tmpSoPath, uid) == ERR_OK;
2238 }
2239 
ProcessDiffFiles(const AppqfInfo & appQfInfo,const std::string & nativeLibraryPath,const std::string & cpuAbi) const2240 ErrCode BaseBundleInstaller::ProcessDiffFiles(const AppqfInfo &appQfInfo, const std::string &nativeLibraryPath,
2241     const std::string &cpuAbi) const
2242 {
2243 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2244     const std::string moduleName = modulePackage_;
2245     auto iter = find_if(appQfInfo.hqfInfos.begin(), appQfInfo.hqfInfos.end(),
2246         [&moduleName](const auto &hqfInfo) {
2247         return hqfInfo.moduleName == moduleName;
2248     });
2249     if (iter != appQfInfo.hqfInfos.end()) {
2250         std::string oldSoPath = Constants::HAP_COPY_PATH + Constants::PATH_SEPARATOR +
2251             bundleName_ + Constants::TMP_SUFFIX + Constants::LIBS;
2252         ScopeGuard guardRemoveOldSoPath([oldSoPath] {InstalldClient::GetInstance()->RemoveDir(oldSoPath);});
2253 
2254         InnerBundleInfo innerBundleInfo;
2255         if (dataMgr_ == nullptr || !dataMgr_->FetchInnerBundleInfo(bundleName_, innerBundleInfo)) {
2256             APP_LOGE("Fetch bundleInfo(%{public}s) failed.", bundleName_.c_str());
2257             return ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST;
2258         }
2259 
2260         int32_t bundleUid = Constants::INVALID_UID;
2261         if (innerBundleInfo.IsEncryptedMoudle(modulePackage_)) {
2262             InnerBundleUserInfo innerBundleUserInfo;
2263             if (!innerBundleInfo.GetInnerBundleUserInfo(Constants::ALL_USERID, innerBundleUserInfo)) {
2264                 APP_LOGE("no user info of bundle %{public}s", bundleName_.c_str());
2265                 return ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST;
2266             }
2267             bundleUid = innerBundleUserInfo.uid;
2268             if (!ExtractEncryptedSoFiles(innerBundleInfo, oldSoPath, bundleUid)) {
2269                 APP_LOGW("module:%{public}s has no so file", moduleName.c_str());
2270                 return ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED;
2271             }
2272         } else {
2273             if (!ExtractSoFiles(oldSoPath, cpuAbi)) {
2274                 return ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED;
2275             }
2276         }
2277 
2278         const std::string tempDiffPath = Constants::HAP_COPY_PATH + Constants::PATH_SEPARATOR +
2279             bundleName_ + Constants::TMP_SUFFIX;
2280         ScopeGuard removeDiffPath([tempDiffPath] { InstalldClient::GetInstance()->RemoveDir(tempDiffPath); });
2281         ErrCode ret = InstalldClient::GetInstance()->ExtractDiffFiles(iter->hqfFilePath, tempDiffPath, cpuAbi);
2282         if (ret != ERR_OK) {
2283             APP_LOGE("error: ExtractDiffFiles failed errcode :%{public}d", ret);
2284             return ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED;
2285         }
2286 
2287         std::string newSoPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
2288             Constants::PATH_SEPARATOR + Constants::PATCH_PATH +
2289             std::to_string(appQfInfo.versionCode) + Constants::PATH_SEPARATOR + nativeLibraryPath;
2290         ret = InstalldClient::GetInstance()->ApplyDiffPatch(oldSoPath, tempDiffPath, newSoPath, bundleUid);
2291         if (ret != ERR_OK) {
2292             APP_LOGE("error: ApplyDiffPatch failed errcode :%{public}d", ret);
2293             return ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED;
2294         }
2295     }
2296 #endif
2297     return ERR_OK;
2298 }
2299 
SetDirApl(const InnerBundleInfo & info)2300 ErrCode BaseBundleInstaller::SetDirApl(const InnerBundleInfo &info)
2301 {
2302     for (const auto &el : Constants::BUNDLE_EL) {
2303         std::string baseBundleDataDir = Constants::BUNDLE_APP_DATA_BASE_DIR +
2304                                         el +
2305                                         Constants::PATH_SEPARATOR +
2306                                         std::to_string(userId_);
2307         std::string baseDataDir = baseBundleDataDir + Constants::BASE + info.GetBundleName();
2308         bool isExist = true;
2309         ErrCode result = InstalldClient::GetInstance()->IsExistDir(baseDataDir, isExist);
2310         if (result != ERR_OK) {
2311             APP_LOGE("IsExistDir failed, error is %{public}d", result);
2312             return result;
2313         }
2314         if (!isExist) {
2315             APP_LOGD("baseDir: %{public}s is not exist", baseDataDir.c_str());
2316             continue;
2317         }
2318         result = InstalldClient::GetInstance()->SetDirApl(
2319             baseDataDir, info.GetBundleName(), info.GetAppPrivilegeLevel(), info.GetIsPreInstallApp(),
2320             info.GetBaseApplicationInfo().debug);
2321         if (result != ERR_OK) {
2322             APP_LOGE("fail to SetDirApl baseDir dir, error is %{public}d", result);
2323             return result;
2324         }
2325         std::string databaseDataDir = baseBundleDataDir + Constants::DATABASE + info.GetBundleName();
2326         result = InstalldClient::GetInstance()->SetDirApl(
2327             databaseDataDir, info.GetBundleName(), info.GetAppPrivilegeLevel(), info.GetIsPreInstallApp(),
2328             info.GetBaseApplicationInfo().debug);
2329         if (result != ERR_OK) {
2330             APP_LOGE("fail to SetDirApl databaseDir dir, error is %{public}d", result);
2331             return result;
2332         }
2333     }
2334 
2335     return ERR_OK;
2336 }
2337 
CreateBundleAndDataDir(InnerBundleInfo & info) const2338 ErrCode BaseBundleInstaller::CreateBundleAndDataDir(InnerBundleInfo &info) const
2339 {
2340     ErrCode result = CreateBundleCodeDir(info);
2341     if (result != ERR_OK) {
2342         APP_LOGE("fail to create bundle code dir, error is %{public}d", result);
2343         return result;
2344     }
2345     ScopeGuard codePathGuard([&] { InstalldClient::GetInstance()->RemoveDir(info.GetAppCodePath()); });
2346     result = CreateBundleDataDir(info);
2347     if (result != ERR_OK) {
2348         APP_LOGE("fail to create bundle data dir, error is %{public}d", result);
2349         return result;
2350     }
2351     codePathGuard.Dismiss();
2352     return ERR_OK;
2353 }
2354 
CreateBundleCodeDir(InnerBundleInfo & info) const2355 ErrCode BaseBundleInstaller::CreateBundleCodeDir(InnerBundleInfo &info) const
2356 {
2357     auto appCodePath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_;
2358     APP_LOGD("create bundle dir %{public}s", appCodePath.c_str());
2359     ErrCode result = InstalldClient::GetInstance()->CreateBundleDir(appCodePath);
2360     if (result != ERR_OK) {
2361         APP_LOGE("fail to create bundle dir, error is %{public}d", result);
2362         return result;
2363     }
2364 
2365     info.SetAppCodePath(appCodePath);
2366     return ERR_OK;
2367 }
2368 
SendToStorageQuota(const std::string & bundleName,const int uid,const std::string & bundleDataDirPath,const int limitSizeMb)2369 static void SendToStorageQuota(const std::string &bundleName, const int uid,
2370     const std::string &bundleDataDirPath, const int limitSizeMb)
2371 {
2372 #ifdef STORAGE_SERVICE_ENABLE
2373     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2374     if (!systemAbilityManager) {
2375         APP_LOGW("SendToStorageQuota, systemAbilityManager error");
2376         return;
2377     }
2378 
2379     auto remote = systemAbilityManager->CheckSystemAbility(STORAGE_MANAGER_MANAGER_ID);
2380     if (!remote) {
2381         APP_LOGW("SendToStorageQuota, CheckSystemAbility error");
2382         return;
2383     }
2384 
2385     auto proxy = iface_cast<StorageManager::IStorageManager>(remote);
2386     if (!proxy) {
2387         APP_LOGW("SendToStorageQuotactl, proxy get error");
2388         return;
2389     }
2390 
2391     int err = proxy->SetBundleQuota(bundleName, uid, bundleDataDirPath, limitSizeMb);
2392     if (err != ERR_OK) {
2393         APP_LOGW("SendToStorageQuota, SetBundleQuota error, err=%{public}d, uid=%{public}d", err, uid);
2394     }
2395 #endif // STORAGE_SERVICE_ENABLE
2396 }
2397 
PrepareBundleDirQuota(const std::string & bundleName,const int uid,const std::string & bundleDataDirPath)2398 static void PrepareBundleDirQuota(const std::string &bundleName, const int uid, const std::string &bundleDataDirPath)
2399 {
2400     int32_t atomicserviceDatasizeThreshold = ATOMIC_SERVICE_DATASIZE_THRESHOLD_MB_PRESET;
2401 #ifdef STORAGE_SERVICE_ENABLE
2402 #ifdef QUOTA_PARAM_SET_ENABLE
2403     char szAtomicDatasizeThresholdMb[THRESHOLD_VAL_LEN] = {0};
2404     int32_t ret = GetParameter(SYSTEM_PARAM_ATOMICSERVICE_DATASIZE_THRESHOLD.c_str(), "",
2405         szAtomicDatasizeThresholdMb, THRESHOLD_VAL_LEN);
2406     if (ret <= 0) {
2407         APP_LOGI("GetParameter failed");
2408     } else if (strcmp(szAtomicDatasizeThresholdMb, "") != 0) {
2409         atomicserviceDatasizeThreshold = atoi(szAtomicDatasizeThresholdMb);
2410         APP_LOGI("InstalldQuotaUtils init atomicserviceDataThreshold mb success");
2411     }
2412     if (atomicserviceDatasizeThreshold <= 0) {
2413         APP_LOGW("no need to prepare quota");
2414         return;
2415     }
2416 #endif // QUOTA_PARAM_SET_ENABLE
2417 #endif // STORAGE_SERVICE_ENABLE
2418     SendToStorageQuota(bundleName, uid, bundleDataDirPath, atomicserviceDatasizeThreshold);
2419 }
2420 
CreateBundleDataDir(InnerBundleInfo & info) const2421 ErrCode BaseBundleInstaller::CreateBundleDataDir(InnerBundleInfo &info) const
2422 {
2423     InnerBundleUserInfo newInnerBundleUserInfo;
2424     if (!info.GetInnerBundleUserInfo(userId_, newInnerBundleUserInfo)) {
2425         APP_LOGE("bundle(%{public}s) get user(%{public}d) failed.",
2426             info.GetBundleName().c_str(), userId_);
2427         return ERR_APPEXECFWK_USER_NOT_EXIST;
2428     }
2429 
2430     if (!dataMgr_->GenerateUidAndGid(newInnerBundleUserInfo)) {
2431         APP_LOGE("fail to generate uid and gid");
2432         return ERR_APPEXECFWK_INSTALL_GENERATE_UID_ERROR;
2433     }
2434     CreateDirParam createDirParam;
2435     createDirParam.bundleName = info.GetBundleName();
2436     createDirParam.userId = userId_;
2437     createDirParam.uid = newInnerBundleUserInfo.uid;
2438     createDirParam.gid = newInnerBundleUserInfo.uid;
2439     createDirParam.apl = info.GetAppPrivilegeLevel();
2440     createDirParam.isPreInstallApp = info.GetIsPreInstallApp();
2441     createDirParam.debug = info.GetBaseApplicationInfo().debug;
2442 
2443     auto result = InstalldClient::GetInstance()->CreateBundleDataDir(createDirParam);
2444     if (result != ERR_OK) {
2445         APP_LOGE("fail to create bundle data dir, error is %{public}d", result);
2446         return result;
2447     }
2448     if (info.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE) {
2449         std::string bundleDataDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[1] +
2450             Constants::PATH_SEPARATOR + std::to_string(userId_) + Constants::BASE + info.GetBundleName();
2451         PrepareBundleDirQuota(info.GetBundleName(), newInnerBundleUserInfo.uid, bundleDataDir);
2452     }
2453     if (info.GetIsNewVersion()) {
2454         int32_t gid = (info.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG) ?
2455             GetIntParameter(BMS_KEY_SHELL_UID, Constants::SHELL_UID) :
2456             newInnerBundleUserInfo.uid;
2457         result = CreateArkProfile(
2458             info.GetBundleName(), userId_, newInnerBundleUserInfo.uid, gid);
2459         if (result != ERR_OK) {
2460             APP_LOGE("fail to create ark profile, error is %{public}d", result);
2461             return result;
2462         }
2463     }
2464     // create asan log directory when asanEnabled is true
2465     // In update condition, delete asan log directory when asanEnabled is false if directory is exist
2466     if ((result = ProcessAsanDirectory(info)) != ERR_OK) {
2467         APP_LOGE("process asan log directory failed!");
2468         return result;
2469     }
2470 
2471     std::string dataBaseDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[1] +
2472         Constants::DATABASE + info.GetBundleName();
2473     info.SetAppDataBaseDir(dataBaseDir);
2474     info.AddInnerBundleUserInfo(newInnerBundleUserInfo);
2475     return ERR_OK;
2476 }
2477 
CreateDataGroupDirs(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,const InnerBundleInfo & oldInfo)2478 ErrCode BaseBundleInstaller::CreateDataGroupDirs(
2479     const std::unordered_map<std::string, InnerBundleInfo> &newInfos, const InnerBundleInfo &oldInfo)
2480 {
2481     for (auto iter = newInfos.begin(); iter != newInfos.end(); iter++) {
2482         auto result = GetGroupDirsChange(iter->second, oldInfo, isAppExist_);
2483         CHECK_RESULT(result, "GetGroupDirsChange failed %{public}d");
2484     }
2485     auto result = CreateGroupDirs();
2486     CHECK_RESULT(result, "GetGroupDirsChange failed %{public}d");
2487     return ERR_OK;
2488 }
2489 
GetGroupDirsChange(const InnerBundleInfo & info,const InnerBundleInfo & oldInfo,bool oldInfoExisted)2490 ErrCode BaseBundleInstaller::GetGroupDirsChange(const InnerBundleInfo &info,
2491     const InnerBundleInfo &oldInfo, bool oldInfoExisted)
2492 {
2493     if (oldInfoExisted) {
2494         auto result = GetRemoveDataGroupDirs(oldInfo, info);
2495         CHECK_RESULT(result, "GetRemoveDataGroupDirs failed %{public}d");
2496     }
2497     auto result = GetDataGroupCreateInfos(info);
2498     CHECK_RESULT(result, "GetDataGroupCreateInfos failed %{public}d");
2499     return ERR_OK;
2500 }
2501 
GetRemoveDataGroupDirs(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo)2502 ErrCode BaseBundleInstaller::GetRemoveDataGroupDirs(
2503     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo)
2504 {
2505     auto oldDataGroupInfos = oldInfo.GetDataGroupInfos();
2506     auto newDataGroupInfos = newInfo.GetDataGroupInfos();
2507     if (dataMgr_ == nullptr) {
2508         APP_LOGE("dataMgr_ is nullptr");
2509         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
2510     }
2511 
2512     for (auto &item : oldDataGroupInfos) {
2513         if (newDataGroupInfos.find(item.first) == newDataGroupInfos.end() &&
2514             !(dataMgr_->IsShareDataGroupId(item.first, userId_)) && !item.second.empty()) {
2515             std::string dir = Constants::REAL_DATA_PATH + Constants::PATH_SEPARATOR + std::to_string(userId_)
2516                 + Constants::DATA_GROUP_PATH + item.second[0].uuid;
2517             APP_LOGD("remove dir: %{public}s", dir.c_str());
2518             removeGroupDirs_.emplace_back(dir);
2519         }
2520     }
2521     return ERR_OK;
2522 }
2523 
RemoveOldGroupDirs() const2524 ErrCode BaseBundleInstaller::RemoveOldGroupDirs() const
2525 {
2526     for (const std::string &dir : removeGroupDirs_) {
2527         APP_LOGD("RemoveOldGroupDirs %{public}s", dir.c_str());
2528         auto result = InstalldClient::GetInstance()->RemoveDir(dir);
2529         CHECK_RESULT(result, "RemoveDir failed %{public}d");
2530     }
2531     APP_LOGD("RemoveOldGroupDirs success");
2532     return ERR_OK;
2533 }
2534 
CreateGroupDirs() const2535 ErrCode BaseBundleInstaller::CreateGroupDirs() const
2536 {
2537     for (const DataGroupInfo &dataGroupInfo : createGroupDirs_) {
2538         std::string dir = Constants::REAL_DATA_PATH + Constants::PATH_SEPARATOR + std::to_string(userId_)
2539             + Constants::DATA_GROUP_PATH + dataGroupInfo.uuid;
2540         APP_LOGD("create group dir: %{public}s", dir.c_str());
2541         auto result = InstalldClient::GetInstance()->Mkdir(dir,
2542             DATA_GROUP_DIR_MODE, dataGroupInfo.uid, dataGroupInfo.gid);
2543         CHECK_RESULT(result, "make groupDir failed %{public}d");
2544     }
2545     APP_LOGD("CreateGroupDirs success");
2546     return ERR_OK;
2547 }
2548 
GetDataGroupCreateInfos(const InnerBundleInfo & newInfo)2549 ErrCode BaseBundleInstaller::GetDataGroupCreateInfos(const InnerBundleInfo &newInfo)
2550 {
2551     auto newDataGroupInfos = newInfo.GetDataGroupInfos();
2552     for (auto &item : newDataGroupInfos) {
2553         const std::string &dataGroupId = item.first;
2554         if (item.second.empty()) {
2555             APP_LOGE("dataGroupInfos in bundle: %{public}s is empty", newInfo.GetBundleName().c_str());
2556             return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
2557         }
2558         std::string dir = Constants::REAL_DATA_PATH + Constants::PATH_SEPARATOR + std::to_string(userId_)
2559             + Constants::DATA_GROUP_PATH + item.second[0].uuid;
2560         bool dirExist = false;
2561         auto result = InstalldClient::GetInstance()->IsExistDir(dir, dirExist);
2562         CHECK_RESULT(result, "check IsExistDir failed %{public}d");
2563         if (!dirExist) {
2564             APP_LOGD("dir: %{public}s need to be created.", dir.c_str());
2565             createGroupDirs_.emplace_back(item.second[0]);
2566         }
2567     }
2568     return ERR_OK;
2569 }
2570 
DeleteGroupDirsForException() const2571 void BaseBundleInstaller::DeleteGroupDirsForException() const
2572 {
2573     for (const DataGroupInfo &info : createGroupDirs_) {
2574         std::string dir = Constants::REAL_DATA_PATH + Constants::PATH_SEPARATOR + std::to_string(userId_)
2575             + Constants::DATA_GROUP_PATH + info.uuid;
2576         InstalldClient::GetInstance()->RemoveDir(dir);
2577     }
2578 }
2579 
RemoveDataGroupDirs(const std::string & bundleName,int32_t userId) const2580 ErrCode BaseBundleInstaller::RemoveDataGroupDirs(const std::string &bundleName, int32_t userId) const
2581 {
2582     std::vector<DataGroupInfo> infos;
2583     if (dataMgr_ == nullptr) {
2584         APP_LOGE("dataMgr_ is nullptr");
2585         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
2586     }
2587     if (!(dataMgr_->QueryDataGroupInfos(bundleName, userId, infos))) {
2588         return ERR_OK;
2589     }
2590     std::vector<std::string> removeDirs;
2591     for (auto iter = infos.begin(); iter != infos.end(); iter++) {
2592         std::string dir;
2593         if (!(dataMgr_->IsShareDataGroupId(iter->dataGroupId, userId)) &&
2594             dataMgr_->GetGroupDir(iter->dataGroupId, dir, userId)) {
2595             APP_LOGD("dir: %{public}s need to be deleted.", dir.c_str());
2596             removeDirs.emplace_back(dir);
2597         }
2598     }
2599     for (const std::string &dir : removeDirs) {
2600         auto result = InstalldClient::GetInstance()->RemoveDir(dir);
2601         CHECK_RESULT(result, "RemoveDir failed %{public}d");
2602     }
2603     return ERR_OK;
2604 }
2605 
CreateArkProfile(const std::string & bundleName,int32_t userId,int32_t uid,int32_t gid) const2606 ErrCode BaseBundleInstaller::CreateArkProfile(
2607     const std::string &bundleName, int32_t userId, int32_t uid, int32_t gid) const
2608 {
2609     ErrCode result = DeleteArkProfile(bundleName, userId);
2610     if (result != ERR_OK) {
2611         APP_LOGE("fail to removeArkProfile, error is %{public}d", result);
2612         return result;
2613     }
2614 
2615     std::string arkProfilePath;
2616     arkProfilePath.append(ARK_PROFILE_PATH).append(std::to_string(userId))
2617         .append(Constants::PATH_SEPARATOR).append(bundleName);
2618     APP_LOGI("CreateArkProfile %{public}s", arkProfilePath.c_str());
2619     int32_t mode = (uid == gid) ? S_IRWXU : (S_IRWXU | S_IRGRP | S_IXGRP);
2620     return InstalldClient::GetInstance()->Mkdir(arkProfilePath, mode, uid, gid);
2621 }
2622 
DeleteArkProfile(const std::string & bundleName,int32_t userId) const2623 ErrCode BaseBundleInstaller::DeleteArkProfile(const std::string &bundleName, int32_t userId) const
2624 {
2625     std::string arkProfilePath;
2626     arkProfilePath.append(ARK_PROFILE_PATH).append(std::to_string(userId))
2627         .append(Constants::PATH_SEPARATOR).append(bundleName);
2628     APP_LOGI("DeleteArkProfile %{public}s", arkProfilePath.c_str());
2629     return InstalldClient::GetInstance()->RemoveDir(arkProfilePath);
2630 }
2631 
ExtractModule(InnerBundleInfo & info,const std::string & modulePath)2632 ErrCode BaseBundleInstaller::ExtractModule(InnerBundleInfo &info, const std::string &modulePath)
2633 {
2634     auto result = InnerProcessNativeLibs(info, modulePath);
2635     if (result != ERR_OK) {
2636         APP_LOGE("fail to InnerProcessNativeLibs, error is %{public}d", result);
2637         return result;
2638     }
2639     result = ExtractArkNativeFile(info, modulePath);
2640     if (result != ERR_OK) {
2641         APP_LOGE("fail to extractArkNativeFile, error is %{public}d", result);
2642         return result;
2643     }
2644     if (info.GetIsNewVersion()) {
2645         result = CopyPgoFileToArkProfileDir(modulePackage_, modulePath_, info.GetBundleName(), userId_);
2646         if (result != ERR_OK) {
2647             APP_LOGE("fail to CopyPgoFileToArkProfileDir, error is %{public}d", result);
2648             return result;
2649         }
2650     }
2651 
2652     ExtractResourceFiles(info, modulePath);
2653 
2654     result = ExtractResFileDir(modulePath);
2655     if (result != ERR_OK) {
2656         APP_LOGE("fail to ExtractResFileDir, error is %{public}d", result);
2657         return result;
2658     }
2659 
2660     if (info.GetIsPreInstallApp()) {
2661         info.SetModuleHapPath(modulePath_);
2662     } else {
2663         info.SetModuleHapPath(GetHapPath(info));
2664     }
2665 
2666     auto moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
2667     info.AddModuleSrcDir(moduleDir);
2668     info.AddModuleResPath(moduleDir);
2669     return ERR_OK;
2670 }
2671 
ExtractResourceFiles(const InnerBundleInfo & info,const std::string & targetPath) const2672 void BaseBundleInstaller::ExtractResourceFiles(const InnerBundleInfo &info, const std::string &targetPath) const
2673 {
2674     APP_LOGD("ExtractResourceFiles begin");
2675     int32_t apiTargetVersion = info.GetBaseApplicationInfo().apiTargetVersion;
2676     if (info.GetIsPreInstallApp() || apiTargetVersion > Constants::API_VERSION_NINE) {
2677         APP_LOGD("no need to extract resource files");
2678         return;
2679     }
2680     APP_LOGD("apiTargetVersion is %{public}d, extract resource files", apiTargetVersion);
2681     ExtractParam extractParam;
2682     extractParam.srcPath = modulePath_;
2683     extractParam.targetPath = targetPath + Constants::PATH_SEPARATOR;
2684     extractParam.extractFileType = ExtractFileType::RESOURCE;
2685     ErrCode ret = InstalldClient::GetInstance()->ExtractFiles(extractParam);
2686     APP_LOGD("ExtractResourceFiles ret : %{public}d", ret);
2687 }
2688 
ExtractResFileDir(const std::string & modulePath) const2689 ErrCode BaseBundleInstaller::ExtractResFileDir(const std::string &modulePath) const
2690 {
2691     APP_LOGD("ExtractResFileDir begin");
2692     ExtractParam extractParam;
2693     extractParam.srcPath = modulePath_;
2694     extractParam.targetPath = modulePath + Constants::PATH_SEPARATOR + Constants::RES_FILE_PATH;
2695     APP_LOGD("ExtractResFileDir targetPath: %{public}s", extractParam.targetPath.c_str());
2696     extractParam.extractFileType = ExtractFileType::RES_FILE;
2697     ErrCode ret = InstalldClient::GetInstance()->ExtractFiles(extractParam);
2698     if (ret != ERR_OK) {
2699         APP_LOGE("ExtractResFileDir ExtractFiles failed, error is %{public}d", ret);
2700         return ret;
2701     }
2702     APP_LOGD("ExtractResFileDir end");
2703     return ret;
2704 }
2705 
ExtractArkNativeFile(InnerBundleInfo & info,const std::string & modulePath)2706 ErrCode BaseBundleInstaller::ExtractArkNativeFile(InnerBundleInfo &info, const std::string &modulePath)
2707 {
2708     if (!info.GetArkNativeFilePath().empty()) {
2709         APP_LOGD("Module %{public}s no need to extract an", modulePackage_.c_str());
2710         return ERR_OK;
2711     }
2712 
2713     std::string cpuAbi = info.GetArkNativeFileAbi();
2714     if (cpuAbi.empty()) {
2715         APP_LOGD("Module %{public}s no native file", modulePackage_.c_str());
2716         return ERR_OK;
2717     }
2718 
2719     if (Constants::ABI_MAP.find(cpuAbi) == Constants::ABI_MAP.end()) {
2720         APP_LOGE("No support %{public}s abi", cpuAbi.c_str());
2721         return ERR_APPEXECFWK_PARSE_AN_FAILED;
2722     }
2723 
2724     std::string arkNativeFilePath;
2725     arkNativeFilePath.append(Constants::ABI_MAP.at(cpuAbi)).append(Constants::PATH_SEPARATOR);
2726     std::string targetPath;
2727     targetPath.append(ARK_CACHE_PATH).append(info.GetBundleName())
2728         .append(Constants::PATH_SEPARATOR).append(arkNativeFilePath);
2729     APP_LOGD("Begin to extract an file, modulePath : %{public}s, targetPath : %{public}s, cpuAbi : %{public}s",
2730         modulePath.c_str(), targetPath.c_str(), cpuAbi.c_str());
2731     ExtractParam extractParam;
2732     extractParam.srcPath = modulePath_;
2733     extractParam.targetPath = targetPath;
2734     extractParam.cpuAbi = cpuAbi;
2735     extractParam.extractFileType = ExtractFileType::AN;
2736     auto result = InstalldClient::GetInstance()->ExtractFiles(extractParam);
2737     if (result != ERR_OK) {
2738         APP_LOGE("extract files failed, error is %{public}d", result);
2739         return result;
2740     }
2741 
2742     info.SetArkNativeFilePath(arkNativeFilePath);
2743     return ERR_OK;
2744 }
2745 
ExtractAllArkProfileFile(const InnerBundleInfo & oldInfo,bool checkRepeat) const2746 ErrCode BaseBundleInstaller::ExtractAllArkProfileFile(const InnerBundleInfo &oldInfo, bool checkRepeat) const
2747 {
2748     if (!oldInfo.GetIsNewVersion()) {
2749         return ERR_OK;
2750     }
2751     std::string bundleName = oldInfo.GetBundleName();
2752     APP_LOGI("Begin to ExtractAllArkProfileFile, bundleName : %{public}s", bundleName.c_str());
2753     const auto &innerModuleInfos = oldInfo.GetInnerModuleInfos();
2754     for (auto iter = innerModuleInfos.cbegin(); iter != innerModuleInfos.cend(); ++iter) {
2755         if (checkRepeat && installedModules_.find(iter->first) != installedModules_.end()) {
2756             continue;
2757         }
2758 
2759         ErrCode ret = CopyPgoFileToArkProfileDir(iter->second.name, iter->second.hapPath, bundleName, userId_);
2760         if (ret != ERR_OK) {
2761             APP_LOGE("fail to CopyPgoFileToArkProfileDir, error is %{public}d", ret);
2762             return ret;
2763         }
2764     }
2765     APP_LOGD("ExtractAllArkProfileFile succeed, bundleName : %{public}s", bundleName.c_str());
2766     return ERR_OK;
2767 }
2768 
CopyPgoFileToArkProfileDir(const std::string & moduleName,const std::string & modulePath,const std::string & bundleName,int32_t userId) const2769 ErrCode BaseBundleInstaller::CopyPgoFileToArkProfileDir(
2770     const std::string &moduleName,
2771     const std::string &modulePath,
2772     const std::string &bundleName,
2773     int32_t userId) const
2774 {
2775     auto it = pgoParams_.find(moduleName);
2776     if (it != pgoParams_.end()) {
2777         return CopyPgoFile(moduleName, it->second, bundleName, userId);
2778     }
2779     return ExtractArkProfileFile(modulePath, bundleName, userId);
2780 }
2781 
CopyPgoFile(const std::string & moduleName,const std::string & pgoPath,const std::string & bundleName,int32_t userId) const2782 ErrCode BaseBundleInstaller::CopyPgoFile(
2783     const std::string &moduleName,
2784     const std::string &pgoPath,
2785     const std::string &bundleName,
2786     int32_t userId) const
2787 {
2788     std::string targetPath;
2789     targetPath.append(ARK_PROFILE_PATH).append(std::to_string(userId))
2790         .append(Constants::PATH_SEPARATOR).append(bundleName)
2791         .append(Constants::PATH_SEPARATOR).append(moduleName)
2792         .append(Constants::AP_SUFFIX);
2793     if (InstalldClient::GetInstance()->CopyFile(pgoPath, targetPath) != ERR_OK) {
2794         APP_LOGE("copy file from %{public}s to %{public}s failed", pgoPath.c_str(), targetPath.c_str());
2795         return ERR_APPEXECFWK_INSTALL_COPY_HAP_FAILED;
2796     }
2797     return ERR_OK;
2798 }
2799 
ExtractArkProfileFile(const std::string & modulePath,const std::string & bundleName,int32_t userId) const2800 ErrCode BaseBundleInstaller::ExtractArkProfileFile(
2801     const std::string &modulePath,
2802     const std::string &bundleName,
2803     int32_t userId) const
2804 {
2805     std::string targetPath;
2806     targetPath.append(ARK_PROFILE_PATH).append(std::to_string(userId))
2807         .append(Constants::PATH_SEPARATOR).append(bundleName);
2808     APP_LOGD("Begin to extract ap file, modulePath : %{public}s, targetPath : %{public}s",
2809         modulePath.c_str(), targetPath.c_str());
2810     ExtractParam extractParam;
2811     extractParam.srcPath = modulePath;
2812     extractParam.targetPath = targetPath;
2813     extractParam.cpuAbi = Constants::EMPTY_STRING;
2814     extractParam.extractFileType = ExtractFileType::AP;
2815     auto result = InstalldClient::GetInstance()->ExtractFiles(extractParam);
2816     if (result != ERR_OK) {
2817         APP_LOGE("extract ap files failed, error is %{public}d", result);
2818         return result;
2819     }
2820     return ERR_OK;
2821 }
2822 
DeleteOldArkNativeFile(const InnerBundleInfo & oldInfo)2823 ErrCode BaseBundleInstaller::DeleteOldArkNativeFile(const InnerBundleInfo &oldInfo)
2824 {
2825     std::string targetPath;
2826     targetPath.append(ARK_CACHE_PATH).append(oldInfo.GetBundleName());
2827     auto result = InstalldClient::GetInstance()->RemoveDir(targetPath);
2828     if (result != ERR_OK) {
2829         APP_LOGE("fail to remove arkNativeFilePath %{public}s, error is %{public}d",
2830             targetPath.c_str(), result);
2831     }
2832 
2833     return result;
2834 }
2835 
RemoveBundleAndDataDir(const InnerBundleInfo & info,bool isKeepData) const2836 ErrCode BaseBundleInstaller::RemoveBundleAndDataDir(const InnerBundleInfo &info, bool isKeepData) const
2837 {
2838     // remove bundle dir
2839     auto result = RemoveBundleCodeDir(info);
2840     if (result != ERR_OK) {
2841         APP_LOGE("fail to remove bundle dir %{public}s, error is %{public}d", info.GetAppCodePath().c_str(), result);
2842         return result;
2843     }
2844     if (!isKeepData) {
2845         result = RemoveBundleDataDir(info);
2846         if (result != ERR_OK) {
2847             APP_LOGE("fail to remove bundleData dir %{public}s, error is %{public}d",
2848                 info.GetBundleName().c_str(), result);
2849         }
2850     }
2851     return result;
2852 }
2853 
RemoveBundleCodeDir(const InnerBundleInfo & info) const2854 ErrCode BaseBundleInstaller::RemoveBundleCodeDir(const InnerBundleInfo &info) const
2855 {
2856     auto result = InstalldClient::GetInstance()->RemoveDir(info.GetAppCodePath());
2857     if (result != ERR_OK) {
2858         APP_LOGE("fail to remove bundle code dir %{public}s, error is %{public}d",
2859             info.GetAppCodePath().c_str(), result);
2860     }
2861     return result;
2862 }
2863 
RemoveBundleDataDir(const InnerBundleInfo & info) const2864 ErrCode BaseBundleInstaller::RemoveBundleDataDir(const InnerBundleInfo &info) const
2865 {
2866     ErrCode result =
2867         InstalldClient::GetInstance()->RemoveBundleDataDir(info.GetBundleName(), userId_);
2868     CHECK_RESULT(result, "RemoveBundleDataDir failed %{public}d");
2869     return result;
2870 }
2871 
RemoveEmptyDirs(const std::unordered_map<std::string,InnerBundleInfo> & infos) const2872 void BaseBundleInstaller::RemoveEmptyDirs(const std::unordered_map<std::string, InnerBundleInfo> &infos) const
2873 {
2874     for (const auto &item : infos) {
2875         const InnerBundleInfo &info = item.second;
2876         std::string moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
2877         bool isDirEmpty = false;
2878         InstalldClient::GetInstance()->IsDirEmpty(moduleDir, isDirEmpty);
2879         if (isDirEmpty) {
2880             APP_LOGD("remove empty dir : %{public}s", moduleDir.c_str());
2881             InstalldClient::GetInstance()->RemoveDir(moduleDir);
2882         }
2883     }
2884 }
2885 
GetModuleNames(const std::unordered_map<std::string,InnerBundleInfo> & infos) const2886 std::string BaseBundleInstaller::GetModuleNames(const std::unordered_map<std::string, InnerBundleInfo> &infos) const
2887 {
2888     if (infos.empty()) {
2889         return Constants::EMPTY_STRING;
2890     }
2891     std::string moduleNames;
2892     for (const auto &item : infos) {
2893         moduleNames.append(item.second.GetCurrentModulePackage()).append(Constants::MODULE_NAME_SEPARATOR);
2894     }
2895     moduleNames.pop_back();
2896     APP_LOGD("moduleNames : %{public}s", moduleNames.c_str());
2897     return moduleNames;
2898 }
2899 
RemoveModuleAndDataDir(const InnerBundleInfo & info,const std::string & modulePackage,int32_t userId,bool isKeepData) const2900 ErrCode BaseBundleInstaller::RemoveModuleAndDataDir(
2901     const InnerBundleInfo &info, const std::string &modulePackage, int32_t userId, bool isKeepData) const
2902 {
2903     APP_LOGD("RemoveModuleAndDataDir with package name %{public}s", modulePackage.c_str());
2904     auto moduleDir = info.GetModuleDir(modulePackage);
2905     auto result = RemoveModuleDir(moduleDir);
2906     if (result != ERR_OK) {
2907         APP_LOGE("fail to remove module dir, error is %{public}d", result);
2908         return result;
2909     }
2910 
2911     // remove hap
2912     result = RemoveModuleDir(GetHapPath(info, info.GetModuleName(modulePackage)));
2913     if (result != ERR_OK) {
2914         APP_LOGE("fail to remove module hap, error is %{public}d", result);
2915         return result;
2916     }
2917 
2918     if (!isKeepData) {
2919         // uninstall hap remove current userId data dir
2920         if (userId != Constants::UNSPECIFIED_USERID) {
2921             RemoveModuleDataDir(info, modulePackage, userId);
2922             return ERR_OK;
2923         }
2924 
2925         // update hap remove all lower version data dir
2926         for (auto infoItem : info.GetInnerBundleUserInfos()) {
2927             int32_t installedUserId = infoItem.second.bundleUserInfo.userId;
2928             RemoveModuleDataDir(info, modulePackage, installedUserId);
2929         }
2930     }
2931     APP_LOGD("RemoveModuleAndDataDir successfully");
2932     return ERR_OK;
2933 }
2934 
RemoveModuleDir(const std::string & modulePath) const2935 ErrCode BaseBundleInstaller::RemoveModuleDir(const std::string &modulePath) const
2936 {
2937     APP_LOGD("module dir %{public}s to be removed", modulePath.c_str());
2938     return InstalldClient::GetInstance()->RemoveDir(modulePath);
2939 }
2940 
RemoveModuleDataDir(const InnerBundleInfo & info,const std::string & modulePackage,int32_t userId) const2941 ErrCode BaseBundleInstaller::RemoveModuleDataDir(
2942     const InnerBundleInfo &info, const std::string &modulePackage, int32_t userId) const
2943 {
2944     APP_LOGD("RemoveModuleDataDir bundleName: %{public}s  modulePackage: %{public}s",
2945              info.GetBundleName().c_str(),
2946              modulePackage.c_str());
2947     auto hapModuleInfo = info.FindHapModuleInfo(modulePackage);
2948     if (!hapModuleInfo) {
2949         APP_LOGE("fail to findHapModule info modulePackage: %{public}s", modulePackage.c_str());
2950         return ERR_NO_INIT;
2951     }
2952     std::string moduleDataDir = info.GetBundleName() + Constants::HAPS + (*hapModuleInfo).moduleName;
2953     APP_LOGD("RemoveModuleDataDir moduleDataDir: %{public}s", moduleDataDir.c_str());
2954     auto result = InstalldClient::GetInstance()->RemoveModuleDataDir(moduleDataDir, userId);
2955     if (result != ERR_OK) {
2956         APP_LOGE("fail to remove HapModuleData dir, error is %{public}d", result);
2957     }
2958     return result;
2959 }
2960 
ExtractModuleFiles(const InnerBundleInfo & info,const std::string & modulePath,const std::string & targetSoPath,const std::string & cpuAbi)2961 ErrCode BaseBundleInstaller::ExtractModuleFiles(const InnerBundleInfo &info, const std::string &modulePath,
2962     const std::string &targetSoPath, const std::string &cpuAbi)
2963 {
2964     APP_LOGD("extract module to %{public}s", modulePath.c_str());
2965     auto result = InstalldClient::GetInstance()->ExtractModuleFiles(modulePath_, modulePath, targetSoPath, cpuAbi);
2966     if (result != ERR_OK) {
2967         APP_LOGE("extract module files failed, error is %{public}d", result);
2968         return result;
2969     }
2970 
2971     return ERR_OK;
2972 }
2973 
RenameModuleDir(const InnerBundleInfo & info) const2974 ErrCode BaseBundleInstaller::RenameModuleDir(const InnerBundleInfo &info) const
2975 {
2976     auto moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
2977     APP_LOGD("rename module to %{public}s", moduleDir.c_str());
2978     auto result = InstalldClient::GetInstance()->RenameModuleDir(moduleDir + Constants::TMP_SUFFIX, moduleDir);
2979     if (result != ERR_OK) {
2980         APP_LOGE("rename module dir failed, error is %{public}d", result);
2981         return result;
2982     }
2983     return ERR_OK;
2984 }
2985 
CheckSysCap(const std::vector<std::string> & bundlePaths)2986 ErrCode BaseBundleInstaller::CheckSysCap(const std::vector<std::string> &bundlePaths)
2987 {
2988     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2989     return bundleInstallChecker_->CheckSysCap(bundlePaths);
2990 }
2991 
CheckMultipleHapsSignInfo(const std::vector<std::string> & bundlePaths,const InstallParam & installParam,std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)2992 ErrCode BaseBundleInstaller::CheckMultipleHapsSignInfo(
2993     const std::vector<std::string> &bundlePaths,
2994     const InstallParam &installParam,
2995     std::vector<Security::Verify::HapVerifyResult>& hapVerifyRes)
2996 {
2997     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2998     return bundleInstallChecker_->CheckMultipleHapsSignInfo(bundlePaths, hapVerifyRes);
2999 }
3000 
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)3001 ErrCode BaseBundleInstaller::ParseHapFiles(
3002     const std::vector<std::string> &bundlePaths,
3003     const InstallParam &installParam,
3004     const Constants::AppType appType,
3005     std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes,
3006     std::unordered_map<std::string, InnerBundleInfo> &infos)
3007 {
3008     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3009     InstallCheckParam checkParam;
3010     checkParam.isPreInstallApp = installParam.isPreInstallApp;
3011     checkParam.crowdtestDeadline = installParam.crowdtestDeadline;
3012     checkParam.appType = appType;
3013     checkParam.removable = installParam.removable;
3014     ErrCode ret = bundleInstallChecker_->ParseHapFiles(
3015         bundlePaths, checkParam, hapVerifyRes, infos);
3016     if (ret != ERR_OK) {
3017         APP_LOGE("parse hap file failed due to errorCode : %{public}d", ret);
3018         return ret;
3019     }
3020     ProcessDataGroupInfo(bundlePaths, infos, installParam.userId, hapVerifyRes);
3021     isContainEntry_ = bundleInstallChecker_->IsContainEntry();
3022     /* At this place, hapVerifyRes cannot be empty and unnecessary to check it */
3023     isEnterpriseBundle_ = bundleInstallChecker_->CheckEnterpriseBundle(hapVerifyRes[0]);
3024     appIdentifier_ = (hapVerifyRes[0].GetProvisionInfo().type == Security::Verify::ProvisionType::DEBUG) ?
3025         DEBUG_APP_IDENTIFIER : hapVerifyRes[0].GetProvisionInfo().bundleInfo.appIdentifier;
3026     return ret;
3027 }
3028 
ProcessDataGroupInfo(const std::vector<std::string> & bundlePaths,std::unordered_map<std::string,InnerBundleInfo> & infos,int32_t userId,const std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)3029 void BaseBundleInstaller::ProcessDataGroupInfo(const std::vector<std::string> &bundlePaths,
3030     std::unordered_map<std::string, InnerBundleInfo> &infos,
3031     int32_t userId, const std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes)
3032 {
3033     if (hapVerifyRes.size() < bundlePaths.size()) {
3034         APP_LOGE("hapVerifyRes size less than bundlePaths size");
3035         return;
3036     }
3037     for (uint32_t i = 0; i < bundlePaths.size(); ++i) {
3038         Security::Verify::ProvisionInfo provisionInfo = hapVerifyRes[i].GetProvisionInfo();
3039         auto dataGroupGids = provisionInfo.bundleInfo.dataGroupIds;
3040         if (dataGroupGids.empty()) {
3041             APP_LOGD("has no data-group-id in provisionInfo");
3042             return;
3043         }
3044         std::shared_ptr<BundleDataMgr> dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3045         if (dataMgr == nullptr) {
3046             APP_LOGE("Get dataMgr shared_ptr nullptr");
3047             return;
3048         }
3049         dataMgr->GenerateDataGroupInfos(infos[bundlePaths[i]], dataGroupGids, userId);
3050     }
3051 }
3052 
CheckInstallCondition(std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes,std::unordered_map<std::string,InnerBundleInfo> & infos)3053 ErrCode BaseBundleInstaller::CheckInstallCondition(
3054     std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes,
3055     std::unordered_map<std::string, InnerBundleInfo> &infos)
3056 {
3057     ErrCode ret = bundleInstallChecker_->CheckDeviceType(infos);
3058     if (ret != ERR_OK) {
3059         APP_LOGE("CheckDeviceType failed due to errorCode : %{public}d", ret);
3060         return ret;
3061     }
3062     ret = bundleInstallChecker_->CheckIsolationMode(infos);
3063     if (ret != ERR_OK) {
3064         APP_LOGE("CheckIsolationMode failed due to errorCode : %{public}d", ret);
3065         return ret;
3066     }
3067     ret = bundleInstallChecker_->CheckHspInstallCondition(hapVerifyRes);
3068     if (ret != ERR_OK) {
3069         APP_LOGE("CheckInstallCondition failed due to errorCode : %{public}d", ret);
3070         return ret;
3071     }
3072     return ERR_OK;
3073 }
3074 
CheckInstallPermission(const InstallParam & installParam,std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)3075 ErrCode BaseBundleInstaller::CheckInstallPermission(const InstallParam &installParam,
3076     std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes)
3077 {
3078     if ((installParam.installBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
3079         installParam.installEnterpriseBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
3080         installParam.installEtpNormalBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
3081         installParam.installEtpMdmBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS ||
3082         installParam.installUpdateSelfBundlePermissionStatus != PermissionStatus::NOT_VERIFIED_PERMISSION_STATUS) &&
3083         !bundleInstallChecker_->VaildInstallPermission(installParam, hapVerifyRes)) {
3084         // need vaild permission
3085         APP_LOGE("install permission denied");
3086         return ERR_APPEXECFWK_INSTALL_PERMISSION_DENIED;
3087     }
3088     return ERR_OK;
3089 }
3090 
CheckDependency(std::unordered_map<std::string,InnerBundleInfo> & infos,const SharedBundleInstaller & sharedBundleInstaller)3091 ErrCode BaseBundleInstaller::CheckDependency(std::unordered_map<std::string, InnerBundleInfo> &infos,
3092     const SharedBundleInstaller &sharedBundleInstaller)
3093 {
3094     for (const auto &info : infos) {
3095         if (!sharedBundleInstaller.CheckDependency(info.second)) {
3096             APP_LOGE("cross-app dependency check failed");
3097             return ERR_APPEXECFWK_INSTALL_DEPENDENT_MODULE_NOT_EXIST;
3098         }
3099     }
3100 
3101     return bundleInstallChecker_->CheckDependency(infos);
3102 }
3103 
CheckHapHashParams(std::unordered_map<std::string,InnerBundleInfo> & infos,std::map<std::string,std::string> hashParams)3104 ErrCode BaseBundleInstaller::CheckHapHashParams(
3105     std::unordered_map<std::string, InnerBundleInfo> &infos,
3106     std::map<std::string, std::string> hashParams)
3107 {
3108     return bundleInstallChecker_->CheckHapHashParams(infos, hashParams);
3109 }
3110 
CheckAppLabelInfo(const std::unordered_map<std::string,InnerBundleInfo> & infos)3111 ErrCode BaseBundleInstaller::CheckAppLabelInfo(const std::unordered_map<std::string, InnerBundleInfo> &infos)
3112 {
3113     for (const auto &info : infos) {
3114         if (info.second.GetApplicationBundleType() == BundleType::SHARED) {
3115             APP_LOGE("installing cross-app shared library");
3116             return ERR_APPEXECFWK_INSTALL_FILE_IS_SHARED_LIBRARY;
3117         }
3118     }
3119 
3120     ErrCode ret = bundleInstallChecker_->CheckAppLabelInfo(infos);
3121     if (ret != ERR_OK) {
3122         return ret;
3123     }
3124 
3125     if (!CheckApiInfo(infos)) {
3126         APP_LOGE("CheckApiInfo failed.");
3127         return ERR_APPEXECFWK_INSTALL_SDK_INCOMPATIBLE;
3128     }
3129 
3130     bundleName_ = (infos.begin()->second).GetBundleName();
3131     versionCode_ = (infos.begin()->second).GetVersionCode();
3132     return ERR_OK;
3133 }
3134 
CheckApiInfo(const std::unordered_map<std::string,InnerBundleInfo> & infos)3135 bool BaseBundleInstaller::CheckApiInfo(const std::unordered_map<std::string, InnerBundleInfo> &infos)
3136 {
3137     std::string compileSdkType = infos.begin()->second.GetBaseApplicationInfo().compileSdkType;
3138     auto bundleInfo = infos.begin()->second.GetBaseBundleInfo();
3139     if (compileSdkType == COMPILE_SDK_TYPE_OPEN_HARMONY) {
3140         return bundleInfo.compatibleVersion <= static_cast<uint32_t>(GetSdkApiVersion());
3141     }
3142     BmsExtensionDataMgr bmsExtensionDataMgr;
3143     return bmsExtensionDataMgr.CheckApiInfo(infos.begin()->second.GetBaseBundleInfo(),
3144         static_cast<uint32_t>(GetSdkApiVersion()));
3145 }
3146 
CheckMultiNativeFile(std::unordered_map<std::string,InnerBundleInfo> & infos)3147 ErrCode BaseBundleInstaller::CheckMultiNativeFile(
3148     std::unordered_map<std::string, InnerBundleInfo> &infos)
3149 {
3150     return bundleInstallChecker_->CheckMultiNativeFile(infos);
3151 }
3152 
CheckProxyDatas(const std::unordered_map<std::string,InnerBundleInfo> & infos)3153 ErrCode BaseBundleInstaller::CheckProxyDatas(
3154     const std::unordered_map<std::string, InnerBundleInfo> &infos)
3155 {
3156     if (!CheckDuplicateProxyData(infos)) {
3157         APP_LOGE("duplicated uri in proxyDatas");
3158         return ERR_APPEXECFWK_INSTALL_CHECK_PROXY_DATA_URI_FAILED;
3159     }
3160     for (const auto &info : infos) {
3161         ErrCode ret = bundleInstallChecker_->CheckProxyDatas(info.second);
3162         if (ret != ERR_OK) {
3163             return ret;
3164         }
3165     }
3166     return ERR_OK;
3167 }
3168 
CheckMDMUpdateBundleForSelf(const InstallParam & installParam,InnerBundleInfo & oldInfo,const std::unordered_map<std::string,InnerBundleInfo> & newInfos,bool isAppExist)3169 ErrCode BaseBundleInstaller::CheckMDMUpdateBundleForSelf(const InstallParam &installParam,
3170     InnerBundleInfo &oldInfo, const std::unordered_map<std::string, InnerBundleInfo> &newInfos, bool isAppExist)
3171 {
3172     if (!installParam.isSelfUpdate) {
3173         return ERR_OK;
3174     }
3175     if (!OHOS::system::GetBoolParameter(Constants::ALLOW_ENTERPRISE_BUNDLE, false)) {
3176         APP_LOGE("not enterprise device");
3177         return ERR_APPEXECFWK_INSTALL_ENTERPRISE_BUNDLE_NOT_ALLOWED;
3178     }
3179     if (!isAppExist) {
3180         APP_LOGE("not self update");
3181         return ERR_APPEXECFWK_INSTALL_SELF_UPDATE_BUNDLENAME_NOT_SAME;
3182     }
3183     std::string appDistributionType = oldInfo.GetAppDistributionType();
3184     if (appDistributionType != Constants::APP_DISTRIBUTION_TYPE_ENTERPRISE_MDM) {
3185         APP_LOGE("not mdm app");
3186         return ERR_APPEXECFWK_INSTALL_SELF_UPDATE_NOT_MDM;
3187     }
3188     std::string bundleName = oldInfo.GetBundleName();
3189     for (const auto &info : newInfos) {
3190         if (bundleName != info.second.GetBundleName()) {
3191             APP_LOGE("bundleName %{public}s not same", info.second.GetBundleName().c_str());
3192             return ERR_APPEXECFWK_INSTALL_SELF_UPDATE_BUNDLENAME_NOT_SAME;
3193         }
3194     }
3195     return ERR_OK;
3196 }
3197 
GetInnerBundleInfo(InnerBundleInfo & info,bool & isAppExist)3198 bool BaseBundleInstaller::GetInnerBundleInfo(InnerBundleInfo &info, bool &isAppExist)
3199 {
3200     if (dataMgr_ == nullptr) {
3201         dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3202         if (dataMgr_ == nullptr) {
3203             APP_LOGE("Get dataMgr shared_ptr nullptr");
3204             return false;
3205         }
3206     }
3207     isAppExist = dataMgr_->GetInnerBundleInfo(bundleName_, info);
3208     return true;
3209 }
3210 
CheckVersionCompatibility(const InnerBundleInfo & oldInfo)3211 ErrCode BaseBundleInstaller::CheckVersionCompatibility(const InnerBundleInfo &oldInfo)
3212 {
3213     if (oldInfo.GetEntryInstallationFree()) {
3214         return CheckVersionCompatibilityForHmService(oldInfo);
3215     }
3216     return CheckVersionCompatibilityForApplication(oldInfo);
3217 }
3218 
3219 // In the process of hap updating, the version code of the entry hap which is about to be updated must not less the
3220 // version code of the current entry haps in the device; if no-entry hap in the device, the updating haps should
3221 // have same version code with the current version code; if the no-entry haps is to be updated, which should has the
3222 // same version code with that of the entry hap in the device.
CheckVersionCompatibilityForApplication(const InnerBundleInfo & oldInfo)3223 ErrCode BaseBundleInstaller::CheckVersionCompatibilityForApplication(const InnerBundleInfo &oldInfo)
3224 {
3225     APP_LOGD("start to check version compatibility for application");
3226     if (oldInfo.HasEntry()) {
3227         if (isContainEntry_ && versionCode_ < oldInfo.GetVersionCode()) {
3228             APP_LOGE("fail to update lower version bundle");
3229             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
3230         }
3231         if (!isContainEntry_ && versionCode_ > oldInfo.GetVersionCode()) {
3232             APP_LOGE("version code is not compatible");
3233             return ERR_APPEXECFWK_INSTALL_VERSION_NOT_COMPATIBLE;
3234         }
3235         if (!isContainEntry_ && versionCode_ < oldInfo.GetVersionCode()) {
3236             APP_LOGE("version code is not compatible");
3237             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
3238         }
3239     } else {
3240         if (versionCode_ < oldInfo.GetVersionCode()) {
3241             APP_LOGE("fail to update lower version bundle");
3242             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
3243         }
3244     }
3245 
3246     if (versionCode_ > oldInfo.GetVersionCode()) {
3247         if (oldInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK) {
3248             APP_LOGE("Not alloweded instal appService hap(%{public}s) due to the hsp does not exist.",
3249                 oldInfo.GetBundleName().c_str());
3250             return ERR_APP_SERVICE_FWK_INSTALL_TYPE_FAILED;
3251         }
3252         APP_LOGD("need to uninstall lower version feature hap");
3253         isFeatureNeedUninstall_ = true;
3254     }
3255     APP_LOGD("finish to check version compatibility for application");
3256     return ERR_OK;
3257 }
3258 
CheckVersionCompatibilityForHmService(const InnerBundleInfo & oldInfo)3259 ErrCode BaseBundleInstaller::CheckVersionCompatibilityForHmService(const InnerBundleInfo &oldInfo)
3260 {
3261     APP_LOGD("start to check version compatibility for hm service");
3262     if (versionCode_ < oldInfo.GetVersionCode()) {
3263         APP_LOGE("fail to update lower version bundle");
3264         return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
3265     }
3266     if (versionCode_ > oldInfo.GetVersionCode()) {
3267         APP_LOGD("need to uninstall lower version hap");
3268         isFeatureNeedUninstall_ = true;
3269     }
3270     APP_LOGD("finish to check version compatibility for hm service");
3271     return ERR_OK;
3272 }
3273 
UninstallLowerVersionFeature(const std::vector<std::string> & packageVec,bool noSkipsKill)3274 ErrCode BaseBundleInstaller::UninstallLowerVersionFeature(const std::vector<std::string> &packageVec, bool noSkipsKill)
3275 {
3276     APP_LOGD("start to uninstall lower version feature hap");
3277     InnerBundleInfo info;
3278     bool isExist = false;
3279     if (!GetInnerBundleInfo(info, isExist) || !isExist) {
3280         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
3281     }
3282 
3283     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_START)) {
3284         APP_LOGE("uninstall already start");
3285         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
3286     }
3287 
3288     // kill the bundle process during uninstall.
3289     if (noSkipsKill) {
3290         if (!AbilityManagerHelper::UninstallApplicationProcesses(info.GetApplicationName(), info.GetUid(userId_))) {
3291             APP_LOGW("can not kill process");
3292         }
3293     }
3294 
3295     std::vector<std::string> moduleVec = info.GetModuleNameVec();
3296     InnerBundleInfo oldInfo = info;
3297     for (const auto &package : moduleVec) {
3298         if (find(packageVec.begin(), packageVec.end(), package) == packageVec.end()) {
3299             APP_LOGD("uninstall package %{public}s", package.c_str());
3300             ErrCode result = RemoveModuleAndDataDir(info, package, Constants::UNSPECIFIED_USERID, true);
3301             if (result != ERR_OK) {
3302                 APP_LOGE("remove module dir failed");
3303                 return result;
3304             }
3305 
3306             // remove driver file
3307             std::shared_ptr driverInstaller = std::make_shared<DriverInstaller>();
3308             driverInstaller->RemoveDriverSoFile(info, info.GetModuleName(package), false);
3309 
3310             if (!dataMgr_->RemoveModuleInfo(bundleName_, package, info)) {
3311                 APP_LOGE("RemoveModuleInfo failed");
3312                 return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
3313             }
3314         }
3315     }
3316     // need to delete lower version feature hap definePermissions and requestPermissions
3317     APP_LOGD("delete lower version feature hap definePermissions and requestPermissions");
3318     ErrCode ret = UpdateDefineAndRequestPermissions(oldInfo, info);
3319     CHECK_RESULT(ret, "UpdateDefineAndRequestPermissions failed %{public}d");
3320     needDeleteQuickFixInfo_ = true;
3321     APP_LOGD("finish to uninstall lower version feature hap");
3322     return ERR_OK;
3323 }
3324 
GetConfirmUserId(const int32_t & userId,std::unordered_map<std::string,InnerBundleInfo> & newInfos)3325 int32_t BaseBundleInstaller::GetConfirmUserId(
3326     const int32_t &userId, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
3327 {
3328     if (userId != Constants::UNSPECIFIED_USERID || newInfos.size() <= 0) {
3329         return userId;
3330     }
3331 
3332     bool isSingleton = newInfos.begin()->second.IsSingleton();
3333     APP_LOGI("The userId is Unspecified and app is singleton(%{public}d) when install.",
3334         static_cast<int32_t>(isSingleton));
3335     return isSingleton ? Constants::DEFAULT_USERID : AccountHelper::GetCurrentActiveUserId();
3336 }
3337 
CheckUserId(const int32_t & userId) const3338 ErrCode BaseBundleInstaller::CheckUserId(const int32_t &userId) const
3339 {
3340     if (userId == Constants::UNSPECIFIED_USERID) {
3341         return ERR_OK;
3342     }
3343 
3344     if (!dataMgr_->HasUserId(userId)) {
3345         APP_LOGE("The user %{public}d does not exist when install.", userId);
3346         return ERR_APPEXECFWK_USER_NOT_EXIST;
3347     }
3348 
3349     return ERR_OK;
3350 }
3351 
GetUserId(const int32_t & userId) const3352 int32_t BaseBundleInstaller::GetUserId(const int32_t &userId) const
3353 {
3354     if (userId == Constants::UNSPECIFIED_USERID) {
3355         return userId;
3356     }
3357 
3358     if (userId < Constants::DEFAULT_USERID) {
3359         APP_LOGE("userId(%{public}d) is invalid.", userId);
3360         return Constants::INVALID_USERID;
3361     }
3362 
3363     APP_LOGD("BundleInstaller GetUserId, now userId is %{public}d", userId);
3364     return userId;
3365 }
3366 
CreateBundleUserData(InnerBundleInfo & innerBundleInfo)3367 ErrCode BaseBundleInstaller::CreateBundleUserData(InnerBundleInfo &innerBundleInfo)
3368 {
3369     APP_LOGI("CreateNewUserData %{public}s userId: %{public}d.",
3370         innerBundleInfo.GetBundleName().c_str(), userId_);
3371     if (!innerBundleInfo.HasInnerBundleUserInfo(userId_)) {
3372         return ERR_APPEXECFWK_USER_NOT_EXIST;
3373     }
3374 
3375     ErrCode result = CreateBundleDataDir(innerBundleInfo);
3376     if (result != ERR_OK) {
3377         RemoveBundleDataDir(innerBundleInfo);
3378         return result;
3379     }
3380 
3381     innerBundleInfo.SetBundleInstallTime(BundleUtil::GetCurrentTimeMs(), userId_);
3382     InnerBundleUserInfo innerBundleUserInfo;
3383     if (!innerBundleInfo.GetInnerBundleUserInfo(userId_, innerBundleUserInfo)) {
3384         APP_LOGE("oldInfo do not have user");
3385         return ERR_APPEXECFWK_USER_NOT_EXIST;
3386     }
3387 
3388 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
3389     OverlayDataMgr::GetInstance()->AddOverlayModuleStates(innerBundleInfo, innerBundleUserInfo);
3390 #endif
3391 
3392     if (!dataMgr_->AddInnerBundleUserInfo(innerBundleInfo.GetBundleName(), innerBundleUserInfo)) {
3393         APP_LOGE("update bundle user info to db failed %{public}s when createNewUser",
3394             innerBundleInfo.GetBundleName().c_str());
3395         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
3396     }
3397 
3398     return ERR_OK;
3399 }
3400 
UninstallAllSandboxApps(const std::string & bundleName,int32_t userId)3401 ErrCode BaseBundleInstaller::UninstallAllSandboxApps(const std::string &bundleName, int32_t userId)
3402 {
3403     // All sandbox will be uninstalled when the original application is updated or uninstalled
3404     APP_LOGD("UninstallAllSandboxApps begin");
3405     if (bundleName.empty()) {
3406         APP_LOGE("UninstallAllSandboxApps failed due to empty bundle name");
3407         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
3408     }
3409     auto helper = DelayedSingleton<BundleSandboxAppHelper>::GetInstance();
3410     if (helper == nullptr) {
3411         APP_LOGE("UninstallAllSandboxApps failed due to helper nullptr");
3412         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
3413     }
3414     if (helper->UninstallAllSandboxApps(bundleName, userId) != ERR_OK) {
3415         APP_LOGW("UninstallAllSandboxApps failed");
3416         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
3417     }
3418     APP_LOGD("UninstallAllSandboxApps finish");
3419     return ERR_OK;
3420 }
3421 
CheckNativeFileWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)3422 ErrCode BaseBundleInstaller::CheckNativeFileWithOldInfo(
3423     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
3424 {
3425     APP_LOGD("CheckNativeFileWithOldInfo begin");
3426     if (HasAllOldModuleUpdate(oldInfo, newInfos)) {
3427         APP_LOGD("All installed haps will be updated");
3428         return ERR_OK;
3429     }
3430 
3431     ErrCode result = CheckNativeSoWithOldInfo(oldInfo, newInfos);
3432     if (result != ERR_OK) {
3433         APP_LOGE("Check nativeSo with oldInfo failed, result: %{public}d", result);
3434         return result;
3435     }
3436 
3437     result = CheckArkNativeFileWithOldInfo(oldInfo, newInfos);
3438     if (result != ERR_OK) {
3439         APP_LOGE("Check arkNativeFile with oldInfo failed, result: %{public}d", result);
3440         return result;
3441     }
3442 
3443     APP_LOGD("CheckNativeFileWithOldInfo end");
3444     return ERR_OK;
3445 }
3446 
HasAllOldModuleUpdate(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)3447 bool BaseBundleInstaller::HasAllOldModuleUpdate(
3448     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
3449 {
3450     const auto &newInfo = newInfos.begin()->second;
3451     bool allOldModuleUpdate = true;
3452     if (newInfo.GetVersionCode() > oldInfo.GetVersionCode()) {
3453         APP_LOGD("All installed haps will be updated");
3454         DeleteOldArkNativeFile(oldInfo);
3455         return allOldModuleUpdate;
3456     }
3457 
3458     std::vector<std::string> installedModules = oldInfo.GetModuleNameVec();
3459     for (const auto &installedModule : installedModules) {
3460         auto updateModule = std::find_if(std::begin(newInfos), std::end(newInfos),
3461             [ &installedModule ] (const auto &item) { return item.second.FindModule(installedModule); });
3462         if (updateModule == newInfos.end()) {
3463             APP_LOGD("Some installed haps will not be updated");
3464             allOldModuleUpdate = false;
3465             break;
3466         }
3467     }
3468     return allOldModuleUpdate;
3469 }
3470 
CheckArkNativeFileWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)3471 ErrCode BaseBundleInstaller::CheckArkNativeFileWithOldInfo(
3472     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
3473 {
3474     APP_LOGD("CheckArkNativeFileWithOldInfo begin");
3475     std::string oldArkNativeFileAbi = oldInfo.GetArkNativeFileAbi();
3476     if (oldArkNativeFileAbi.empty()) {
3477         APP_LOGD("OldInfo no arkNativeFile");
3478         return ERR_OK;
3479     }
3480 
3481     std::string arkNativeFileAbi = newInfos.begin()->second.GetArkNativeFileAbi();
3482     if (arkNativeFileAbi.empty()) {
3483         APP_LOGD("NewInfos no arkNativeFile");
3484         for (auto& item : newInfos) {
3485             item.second.SetArkNativeFileAbi(oldInfo.GetArkNativeFileAbi());
3486             item.second.SetArkNativeFilePath(oldInfo.GetArkNativeFilePath());
3487         }
3488         return ERR_OK;
3489     } else {
3490         if (arkNativeFileAbi != oldArkNativeFileAbi) {
3491             APP_LOGE("An incompatible in oldInfo and newInfo");
3492             return ERR_APPEXECFWK_INSTALL_AN_INCOMPATIBLE;
3493         }
3494     }
3495 
3496     APP_LOGD("CheckArkNativeFileWithOldInfo end");
3497     return ERR_OK;
3498 }
3499 
CheckNativeSoWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)3500 ErrCode BaseBundleInstaller::CheckNativeSoWithOldInfo(
3501     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
3502 {
3503     APP_LOGD("CheckNativeSoWithOldInfo begin");
3504     bool oldInfoHasSo = !oldInfo.GetNativeLibraryPath().empty();
3505     if (!oldInfoHasSo) {
3506         APP_LOGD("OldInfo does not has so");
3507         return ERR_OK;
3508     }
3509 
3510     const auto &newInfo = newInfos.begin()->second;
3511     bool newInfoHasSo = !newInfo.GetNativeLibraryPath().empty();
3512     if (newInfoHasSo && (oldInfo.GetNativeLibraryPath() != newInfo.GetNativeLibraryPath()
3513         || oldInfo.GetCpuAbi() != newInfo.GetCpuAbi())) {
3514         APP_LOGE("Install failed due to so incompatible in oldInfo and newInfo");
3515         return ERR_APPEXECFWK_INSTALL_SO_INCOMPATIBLE;
3516     }
3517 
3518     if (!newInfoHasSo) {
3519         for (auto& item : newInfos) {
3520             item.second.SetNativeLibraryPath(oldInfo.GetNativeLibraryPath());
3521             item.second.SetCpuAbi(oldInfo.GetCpuAbi());
3522         }
3523     }
3524 
3525     APP_LOGD("CheckNativeSoWithOldInfo end");
3526     return ERR_OK;
3527 }
3528 
CheckAppLabel(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const3529 ErrCode BaseBundleInstaller::CheckAppLabel(const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
3530 {
3531     // check app label for inheritance installation
3532     APP_LOGD("CheckAppLabel begin");
3533     if (oldInfo.GetVersionName() != newInfo.GetVersionName()) {
3534         return ERR_APPEXECFWK_INSTALL_VERSIONNAME_NOT_SAME;
3535     }
3536     if (oldInfo.GetMinCompatibleVersionCode() != newInfo.GetMinCompatibleVersionCode()) {
3537         return ERR_APPEXECFWK_INSTALL_MINCOMPATIBLE_VERSIONCODE_NOT_SAME;
3538     }
3539     if (oldInfo.GetVendor() != newInfo.GetVendor()) {
3540         return ERR_APPEXECFWK_INSTALL_VENDOR_NOT_SAME;
3541     }
3542     if (oldInfo.GetTargetVersion()!= newInfo.GetTargetVersion()) {
3543         return ERR_APPEXECFWK_INSTALL_RELEASETYPE_TARGET_NOT_SAME;
3544     }
3545     if (oldInfo.GetCompatibleVersion() != newInfo.GetCompatibleVersion()) {
3546         return ERR_APPEXECFWK_INSTALL_RELEASETYPE_COMPATIBLE_NOT_SAME;
3547     }
3548     if (oldInfo.GetReleaseType() != newInfo.GetReleaseType()) {
3549         return ERR_APPEXECFWK_INSTALL_RELEASETYPE_NOT_SAME;
3550     }
3551     if (oldInfo.GetAppDistributionType() != newInfo.GetAppDistributionType()) {
3552         return ERR_APPEXECFWK_INSTALL_APP_DISTRIBUTION_TYPE_NOT_SAME;
3553     }
3554     if (oldInfo.GetAppProvisionType() != newInfo.GetAppProvisionType()) {
3555         return ERR_APPEXECFWK_INSTALL_APP_PROVISION_TYPE_NOT_SAME;
3556     }
3557     if (oldInfo.GetAppFeature() != newInfo.GetAppFeature()) {
3558         return ERR_APPEXECFWK_INSTALL_APPTYPE_NOT_SAME;
3559     }
3560     if (oldInfo.GetIsNewVersion() != newInfo.GetIsNewVersion()) {
3561         APP_LOGE("same version update module condition, model type must be the same");
3562         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
3563     }
3564 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
3565     if (oldInfo.GetTargetBundleName() != newInfo.GetTargetBundleName()) {
3566         return ERR_BUNDLEMANAGER_OVERLAY_INSTALLATION_FAILED_TARGET_BUNDLE_NAME_NOT_SAME;
3567     }
3568     if (oldInfo.GetTargetPriority() != newInfo.GetTargetPriority()) {
3569         return ERR_BUNDLEMANAGER_OVERLAY_INSTALLATION_FAILED_TARGET_PRIORITY_NOT_SAME;
3570     }
3571 #endif
3572     if (oldInfo.GetApplicationBundleType() != newInfo.GetApplicationBundleType()) {
3573         return ERR_APPEXECFWK_BUNDLE_TYPE_NOT_SAME;
3574     }
3575 
3576     ErrCode ret = CheckDebugType(oldInfo, newInfo);
3577     APP_LOGD("CheckAppLabel end");
3578     return ret;
3579 }
3580 
CheckDebugType(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const3581 ErrCode BaseBundleInstaller::CheckDebugType(
3582     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
3583 {
3584     if (!oldInfo.HasEntry() && !newInfo.HasEntry()) {
3585         return ERR_OK;
3586     }
3587 
3588     if (oldInfo.HasEntry() && newInfo.HasEntry()) {
3589         if (oldInfo.GetBaseApplicationInfo().debug != newInfo.GetBaseApplicationInfo().debug) {
3590             return ERR_APPEXECFWK_INSTALL_DEBUG_NOT_SAME;
3591         }
3592 
3593         return ERR_OK;
3594     }
3595 
3596     if (oldInfo.HasEntry() && !oldInfo.GetBaseApplicationInfo().debug && newInfo.GetBaseApplicationInfo().debug) {
3597         return ERR_APPEXECFWK_INSTALL_DEBUG_NOT_SAME;
3598     }
3599 
3600     if (newInfo.HasEntry() && !newInfo.GetBaseApplicationInfo().debug && oldInfo.GetBaseApplicationInfo().debug) {
3601         return ERR_APPEXECFWK_INSTALL_DEBUG_NOT_SAME;
3602     }
3603 
3604     return ERR_OK;
3605 }
3606 
RemoveBundleUserData(InnerBundleInfo & innerBundleInfo,bool needRemoveData)3607 ErrCode BaseBundleInstaller::RemoveBundleUserData(InnerBundleInfo &innerBundleInfo, bool needRemoveData)
3608 {
3609     auto bundleName = innerBundleInfo.GetBundleName();
3610     APP_LOGD("remove user(%{public}d) in bundle(%{public}s).", userId_, bundleName.c_str());
3611     if (!innerBundleInfo.HasInnerBundleUserInfo(userId_)) {
3612         return ERR_APPEXECFWK_USER_NOT_EXIST;
3613     }
3614 
3615     ErrCode result = ERR_OK;
3616     if (!needRemoveData) {
3617         result = RemoveBundleDataDir(innerBundleInfo);
3618         if (result != ERR_OK) {
3619             APP_LOGE("remove user data directory failed.");
3620             return result;
3621         }
3622     }
3623 
3624     result = DeleteArkProfile(bundleName, userId_);
3625     if (result != ERR_OK) {
3626         APP_LOGE("fail to removeArkProfile, error is %{public}d", result);
3627         return result;
3628     }
3629 
3630     if ((result = CleanAsanDirectory(innerBundleInfo)) != ERR_OK) {
3631         APP_LOGE("fail to remove asan log path, error is %{public}d", result);
3632         return result;
3633     }
3634 
3635     // delete accessTokenId
3636     accessTokenId_ = innerBundleInfo.GetAccessTokenId(userId_);
3637     if (BundlePermissionMgr::DeleteAccessTokenId(accessTokenId_) !=
3638         AccessToken::AccessTokenKitRet::RET_SUCCESS) {
3639         APP_LOGE("delete accessToken failed");
3640     }
3641 
3642     innerBundleInfo.RemoveInnerBundleUserInfo(userId_);
3643     if (!dataMgr_->RemoveInnerBundleUserInfo(bundleName, userId_)) {
3644         APP_LOGE("update bundle user info to db failed %{public}s when remove user",
3645             bundleName.c_str());
3646         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
3647     }
3648 
3649     return ERR_OK;
3650 }
3651 
CheckInstallationFree(const InnerBundleInfo & innerBundleInfo,const std::unordered_map<std::string,InnerBundleInfo> & infos) const3652 ErrCode BaseBundleInstaller::CheckInstallationFree(const InnerBundleInfo &innerBundleInfo,
3653     const std::unordered_map<std::string, InnerBundleInfo> &infos) const
3654 {
3655     for (const auto &item : infos) {
3656         if (innerBundleInfo.GetEntryInstallationFree() != item.second.GetEntryInstallationFree()) {
3657             APP_LOGE("CheckInstallationFree cannot install application and hm service simultaneously");
3658             return ERR_APPEXECFWK_INSTALL_TYPE_ERROR;
3659         }
3660     }
3661     return ERR_OK;
3662 }
3663 
SaveHapPathToRecords(bool isPreInstallApp,const std::unordered_map<std::string,InnerBundleInfo> & infos)3664 void BaseBundleInstaller::SaveHapPathToRecords(
3665     bool isPreInstallApp, const std::unordered_map<std::string, InnerBundleInfo> &infos)
3666 {
3667     if (isPreInstallApp) {
3668         APP_LOGD("PreInstallApp do not need to save hap path to record");
3669         return;
3670     }
3671 
3672     for (const auto &item : infos) {
3673         auto hapPathIter = hapPathRecords_.find(item.first);
3674         if (hapPathIter == hapPathRecords_.end()) {
3675             std::string tempDir = GetTempHapPath(item.second);
3676             if (tempDir.empty()) {
3677                 APP_LOGW("get temp hap path failed");
3678                 continue;
3679             }
3680             APP_LOGD("tempDir is %{public}s", tempDir.c_str());
3681             hapPathRecords_.emplace(item.first, tempDir);
3682         }
3683 
3684         std::string signatureFileDir = "";
3685         FindSignatureFileDir(item.second.GetCurModuleName(), signatureFileDir);
3686         auto signatureFileIter = signatureFileMap_.find(item.first);
3687         if (signatureFileIter == signatureFileMap_.end()) {
3688             signatureFileMap_.emplace(item.first, signatureFileDir);
3689         }
3690     }
3691 }
3692 
SaveHapToInstallPath(const std::unordered_map<std::string,InnerBundleInfo> & infos)3693 ErrCode BaseBundleInstaller::SaveHapToInstallPath(const std::unordered_map<std::string, InnerBundleInfo> &infos)
3694 {
3695     // size of code signature files should be same with the size of hap and hsp
3696     if (!signatureFileMap_.empty() && (signatureFileMap_.size() != hapPathRecords_.size())) {
3697         APP_LOGE("each hap or hsp needs to be verified code signature");
3698         return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FAILED;
3699     }
3700     // 1. copy hsp or hap file to temp installation dir
3701     ErrCode result = ERR_OK;
3702     for (const auto &hapPathRecord : hapPathRecords_) {
3703         APP_LOGD("Save from(%{public}s) to(%{public}s)", hapPathRecord.first.c_str(), hapPathRecord.second.c_str());
3704         if ((signatureFileMap_.find(hapPathRecord.first) != signatureFileMap_.end()) &&
3705             (!signatureFileMap_.at(hapPathRecord.first).empty())) {
3706             result = InstalldClient::GetInstance()->CopyFile(hapPathRecord.first, hapPathRecord.second,
3707                 signatureFileMap_.at(hapPathRecord.first));
3708             CHECK_RESULT(result, "Copy hap to install path failed or code signature hap failed %{public}d");
3709         } else {
3710             if (InstalldClient::GetInstance()->CopyFile(
3711                 hapPathRecord.first, hapPathRecord.second) != ERR_OK) {
3712                 APP_LOGE("Copy hap to install path failed");
3713                 return ERR_APPEXECFWK_INSTALL_COPY_HAP_FAILED;
3714             }
3715             if (VerifyCodeSignatureForHap(infos, hapPathRecord.first, hapPathRecord.second) != ERR_OK) {
3716                 APP_LOGE("enable code signature failed");
3717                 return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FAILED;
3718             }
3719         }
3720     }
3721     APP_LOGD("copy hap to install path success");
3722 
3723     // 2. check encryption of hap
3724     if ((result = CheckHapEncryption(infos)) != ERR_OK) {
3725         APP_LOGE("check encryption of hap failed %{public}d", result);
3726         return result;
3727     }
3728 
3729     // 3. move file from temp dir to real installation dir
3730     if ((result = MoveFileToRealInstallationDir(infos)) != ERR_OK) {
3731         APP_LOGE("move file to real installation path failed %{public}d", result);
3732         return result;
3733     }
3734     return ERR_OK;
3735 }
3736 
ResetInstallProperties()3737 void BaseBundleInstaller::ResetInstallProperties()
3738 {
3739     bundleInstallChecker_->ResetProperties();
3740     isContainEntry_ = false;
3741     isAppExist_ = false;
3742     hasInstalledInUser_ = false;
3743     isFeatureNeedUninstall_ = false;
3744     versionCode_ = 0;
3745     uninstallModuleVec_.clear();
3746     installedModules_.clear();
3747     state_ = InstallerState::INSTALL_START;
3748     singletonState_ = SingletonState::DEFAULT;
3749     accessTokenId_ = 0;
3750     sysEventInfo_.Reset();
3751     moduleName_.clear();
3752     verifyCodeParams_.clear();
3753     pgoParams_.clear();
3754     otaInstall_ = false;
3755     signatureFileMap_.clear();
3756     hapPathRecords_.clear();
3757     uninstallBundleAppId_.clear();
3758     isModuleUpdate_ = false;
3759     isEntryInstalled_ = false;
3760     entryModuleName_.clear();
3761     isEnterpriseBundle_ = false;
3762     appIdentifier_.clear();
3763     targetSoPathMap_.clear();
3764 }
3765 
OnSingletonChange(bool noSkipsKill)3766 void BaseBundleInstaller::OnSingletonChange(bool noSkipsKill)
3767 {
3768     if (singletonState_ == SingletonState::DEFAULT) {
3769         return;
3770     }
3771 
3772     InnerBundleInfo info;
3773     bool isExist = false;
3774     if (!GetInnerBundleInfo(info, isExist) || !isExist) {
3775         APP_LOGE("Get innerBundleInfo failed when singleton changed");
3776         return;
3777     }
3778 
3779     InstallParam installParam;
3780     installParam.needSendEvent = false;
3781     installParam.forceExecuted = true;
3782     installParam.noSkipsKill = noSkipsKill;
3783     if (singletonState_ == SingletonState::SINGLETON_TO_NON) {
3784         APP_LOGI("Bundle changes from singleton app to non singleton app");
3785         installParam.userId = Constants::DEFAULT_USERID;
3786         UninstallBundle(bundleName_, installParam);
3787         return;
3788     }
3789 
3790     if (singletonState_ == SingletonState::NON_TO_SINGLETON) {
3791         APP_LOGI("Bundle changes from non singleton app to singleton app");
3792         for (auto infoItem : info.GetInnerBundleUserInfos()) {
3793             int32_t installedUserId = infoItem.second.bundleUserInfo.userId;
3794             if (installedUserId == Constants::DEFAULT_USERID) {
3795                 continue;
3796             }
3797 
3798             installParam.userId = installedUserId;
3799             UninstallBundle(bundleName_, installParam);
3800         }
3801     }
3802 }
3803 
SendBundleSystemEvent(const std::string & bundleName,BundleEventType bundleEventType,const InstallParam & installParam,InstallScene preBundleScene,ErrCode errCode)3804 void BaseBundleInstaller::SendBundleSystemEvent(const std::string &bundleName, BundleEventType bundleEventType,
3805     const InstallParam &installParam, InstallScene preBundleScene, ErrCode errCode)
3806 {
3807     sysEventInfo_.bundleName = bundleName;
3808     sysEventInfo_.isPreInstallApp = installParam.isPreInstallApp;
3809     sysEventInfo_.errCode = errCode;
3810     sysEventInfo_.isFreeInstallMode = (installParam.installFlag == InstallFlag::FREE_INSTALL);
3811     sysEventInfo_.userId = userId_;
3812     sysEventInfo_.versionCode = versionCode_;
3813     sysEventInfo_.preBundleScene = preBundleScene;
3814     GetCallingEventInfo(sysEventInfo_);
3815     EventReport::SendBundleSystemEvent(bundleEventType, sysEventInfo_);
3816 }
3817 
GetCallingEventInfo(EventInfo & eventInfo)3818 void BaseBundleInstaller::GetCallingEventInfo(EventInfo &eventInfo)
3819 {
3820     APP_LOGD("GetCallingEventInfo start, bundleName:%{public}s", eventInfo.callingBundleName.c_str());
3821     if (dataMgr_ == nullptr) {
3822         APP_LOGE("Get dataMgr shared_ptr nullptr");
3823         return;
3824     }
3825     if (!dataMgr_->GetBundleNameForUid(eventInfo.callingUid, eventInfo.callingBundleName)) {
3826         APP_LOGW("CallingUid %{public}d is not hap, no bundleName", eventInfo.callingUid);
3827         eventInfo.callingBundleName = Constants::EMPTY_STRING;
3828         return;
3829     }
3830     BundleInfo bundleInfo;
3831     if (!dataMgr_->GetBundleInfo(eventInfo.callingBundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo,
3832         eventInfo.callingUid / Constants::BASE_USER_RANGE)) {
3833         APP_LOGE("GetBundleInfo failed, bundleName: %{public}s", eventInfo.callingBundleName.c_str());
3834         return;
3835     }
3836     eventInfo.callingAppId = bundleInfo.appId;
3837 }
3838 
GetInstallEventInfo(EventInfo & eventInfo)3839 void BaseBundleInstaller::GetInstallEventInfo(EventInfo &eventInfo)
3840 {
3841     APP_LOGD("GetInstallEventInfo start, bundleName:%{public}s", bundleName_.c_str());
3842     InnerBundleInfo info;
3843     bool isExist = false;
3844     if (!GetInnerBundleInfo(info, isExist) || !isExist) {
3845         APP_LOGE("Get innerBundleInfo failed, bundleName: %{public}s", bundleName_.c_str());
3846         return;
3847     }
3848     eventInfo.fingerprint = info.GetCertificateFingerprint();
3849     eventInfo.appDistributionType = info.GetAppDistributionType();
3850     eventInfo.hideDesktopIcon = info.IsHideDesktopIcon();
3851     eventInfo.timeStamp = info.GetBundleUpdateTime(userId_);
3852     // report hapPath and hashValue
3853     for (const auto &innerModuleInfo : info.GetInnerModuleInfos()) {
3854         eventInfo.filePath.push_back(innerModuleInfo.second.hapPath);
3855         eventInfo.hashValue.push_back(innerModuleInfo.second.hashValue);
3856     }
3857 }
3858 
GetInstallEventInfo(const InnerBundleInfo & bundleInfo,EventInfo & eventInfo)3859 void BaseBundleInstaller::GetInstallEventInfo(const InnerBundleInfo &bundleInfo, EventInfo &eventInfo)
3860 {
3861     APP_LOGD("GetInstallEventInfo start, bundleName:%{public}s", bundleInfo.GetBundleName().c_str());
3862     eventInfo.fingerprint = bundleInfo.GetCertificateFingerprint();
3863     eventInfo.appDistributionType = bundleInfo.GetAppDistributionType();
3864     eventInfo.hideDesktopIcon = bundleInfo.IsHideDesktopIcon();
3865     eventInfo.timeStamp = bundleInfo.GetBundleUpdateTime(userId_);
3866     // report hapPath and hashValue
3867     for (const auto &innerModuleInfo : bundleInfo.GetInnerModuleInfos()) {
3868         eventInfo.filePath.push_back(innerModuleInfo.second.hapPath);
3869         eventInfo.hashValue.push_back(innerModuleInfo.second.hashValue);
3870     }
3871 }
3872 
SetCallingUid(int32_t callingUid)3873 void BaseBundleInstaller::SetCallingUid(int32_t callingUid)
3874 {
3875     sysEventInfo_.callingUid = callingUid;
3876 }
3877 
NotifyBundleStatus(const NotifyBundleEvents & installRes)3878 ErrCode BaseBundleInstaller::NotifyBundleStatus(const NotifyBundleEvents &installRes)
3879 {
3880     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
3881     commonEventMgr->NotifyBundleStatus(installRes, dataMgr_);
3882     return ERR_OK;
3883 }
3884 
AddBundleStatus(const NotifyBundleEvents & installRes)3885 void BaseBundleInstaller::AddBundleStatus(const NotifyBundleEvents &installRes)
3886 {
3887     bundleEvents_.emplace_back(installRes);
3888 }
3889 
NotifyAllBundleStatus()3890 bool BaseBundleInstaller::NotifyAllBundleStatus()
3891 {
3892     if (bundleEvents_.empty()) {
3893         APP_LOGE("bundleEvents is empty.");
3894         return false;
3895     }
3896 
3897     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3898     if (!dataMgr) {
3899         APP_LOGE("Get dataMgr shared_ptr nullptr");
3900         return false;
3901     }
3902 
3903     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
3904     for (const auto &bundleEvent : bundleEvents_) {
3905         commonEventMgr->NotifyBundleStatus(bundleEvent, dataMgr);
3906     }
3907     return true;
3908 }
3909 
AddNotifyBundleEvents(const NotifyBundleEvents & notifyBundleEvents)3910 void BaseBundleInstaller::AddNotifyBundleEvents(const NotifyBundleEvents &notifyBundleEvents)
3911 {
3912     auto userMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleUserMgr();
3913     if (userMgr == nullptr) {
3914         APP_LOGE("userMgr is null");
3915         return;
3916     }
3917 
3918     userMgr->AddNotifyBundleEvents(notifyBundleEvents);
3919 }
3920 
CheckOverlayInstallation(std::unordered_map<std::string,InnerBundleInfo> & newInfos,int32_t userId)3921 ErrCode BaseBundleInstaller::CheckOverlayInstallation(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
3922     int32_t userId)
3923 {
3924 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
3925     std::shared_ptr<BundleOverlayInstallChecker> overlayChecker = std::make_shared<BundleOverlayInstallChecker>();
3926     return overlayChecker->CheckOverlayInstallation(newInfos, userId, overlayType_);
3927 #else
3928     APP_LOGD("overlay is not supported");
3929     return ERR_OK;
3930 #endif
3931 }
3932 
CheckOverlayUpdate(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo,int32_t userId) const3933 ErrCode BaseBundleInstaller::CheckOverlayUpdate(const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo,
3934     int32_t userId) const
3935 {
3936 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
3937     std::shared_ptr<BundleOverlayInstallChecker> overlayChecker = std::make_shared<BundleOverlayInstallChecker>();
3938     return overlayChecker->CheckOverlayUpdate(oldInfo, newInfo, userId);
3939 #else
3940     APP_LOGD("overlay is not supported");
3941     return ERR_OK;
3942 #endif
3943 }
3944 
GetNotifyType()3945 NotifyType BaseBundleInstaller::GetNotifyType()
3946 {
3947     if (isAppExist_ && hasInstalledInUser_) {
3948         if (overlayType_ != NON_OVERLAY_TYPE) {
3949             return NotifyType::OVERLAY_UPDATE;
3950         }
3951         return NotifyType::UPDATE;
3952     }
3953 
3954     if (overlayType_ != NON_OVERLAY_TYPE) {
3955         return NotifyType::OVERLAY_INSTALL;
3956     }
3957     return NotifyType::INSTALL;
3958 }
3959 
CheckArkProfileDir(const InnerBundleInfo & newInfo,const InnerBundleInfo & oldInfo) const3960 ErrCode BaseBundleInstaller::CheckArkProfileDir(const InnerBundleInfo &newInfo, const InnerBundleInfo &oldInfo) const
3961 {
3962     if (newInfo.GetVersionCode() > oldInfo.GetVersionCode()) {
3963         const auto userInfos = oldInfo.GetInnerBundleUserInfos();
3964         for (auto iter = userInfos.begin(); iter != userInfos.end(); iter++) {
3965             int32_t userId = iter->second.bundleUserInfo.userId;
3966             int32_t gid = (newInfo.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG) ?
3967                 GetIntParameter(BMS_KEY_SHELL_UID, Constants::SHELL_UID) :
3968                 oldInfo.GetUid(userId);
3969             ErrCode result = newInfo.GetIsNewVersion() ?
3970                 CreateArkProfile(bundleName_, userId, oldInfo.GetUid(userId), gid) :
3971                 DeleteArkProfile(bundleName_, userId);
3972             if (result != ERR_OK) {
3973                 APP_LOGE("bundleName: %{public}s CheckArkProfileDir failed, result:%{public}d",
3974                     bundleName_.c_str(), result);
3975                 return result;
3976             }
3977         }
3978     }
3979     return ERR_OK;
3980 }
3981 
ProcessAsanDirectory(InnerBundleInfo & info) const3982 ErrCode BaseBundleInstaller::ProcessAsanDirectory(InnerBundleInfo &info) const
3983 {
3984     const std::string bundleName = info.GetBundleName();
3985     const std::string asanLogDir = Constants::BUNDLE_ASAN_LOG_DIR + Constants::PATH_SEPARATOR
3986         + std::to_string(userId_) + Constants::PATH_SEPARATOR + bundleName + Constants::PATH_SEPARATOR + LOG;
3987     bool dirExist = false;
3988     ErrCode errCode = InstalldClient::GetInstance()->IsExistDir(asanLogDir, dirExist);
3989     if (errCode != ERR_OK) {
3990         APP_LOGE("check asan log directory failed!");
3991         return errCode;
3992     }
3993     bool asanEnabled = info.GetAsanEnabled();
3994     // create asan log directory if asanEnabled is true
3995     if (!dirExist && asanEnabled) {
3996         InnerBundleUserInfo newInnerBundleUserInfo;
3997         if (!info.GetInnerBundleUserInfo(userId_, newInnerBundleUserInfo)) {
3998             APP_LOGE("bundle(%{public}s) get user(%{public}d) failed.",
3999                 info.GetBundleName().c_str(), userId_);
4000             return ERR_APPEXECFWK_USER_NOT_EXIST;
4001         }
4002 
4003         if (!dataMgr_->GenerateUidAndGid(newInnerBundleUserInfo)) {
4004             APP_LOGE("fail to gererate uid and gid");
4005             return ERR_APPEXECFWK_INSTALL_GENERATE_UID_ERROR;
4006         }
4007         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
4008         if ((errCode = InstalldClient::GetInstance()->Mkdir(asanLogDir, mode,
4009             newInnerBundleUserInfo.uid, newInnerBundleUserInfo.uid)) != ERR_OK) {
4010             APP_LOGE("create asan log directory failed!");
4011             return errCode;
4012         }
4013     }
4014     if (asanEnabled) {
4015         info.SetAsanLogPath(LOG);
4016     }
4017     // clean asan directory
4018     if (dirExist && !asanEnabled) {
4019         if ((errCode = CleanAsanDirectory(info)) != ERR_OK) {
4020             APP_LOGE("clean asan log directory failed!");
4021             return errCode;
4022         }
4023     }
4024     return ERR_OK;
4025 }
4026 
CleanAsanDirectory(InnerBundleInfo & info) const4027 ErrCode BaseBundleInstaller::CleanAsanDirectory(InnerBundleInfo &info) const
4028 {
4029     const std::string bundleName = info.GetBundleName();
4030     const std::string asanLogDir = Constants::BUNDLE_ASAN_LOG_DIR + Constants::PATH_SEPARATOR
4031         + std::to_string(userId_) + Constants::PATH_SEPARATOR + bundleName;
4032     ErrCode errCode =  InstalldClient::GetInstance()->RemoveDir(asanLogDir);
4033     if (errCode != ERR_OK) {
4034         APP_LOGE("clean asan log path failed!");
4035         return errCode;
4036     }
4037     info.SetAsanLogPath("");
4038     return errCode;
4039 }
4040 
AddAppProvisionInfo(const std::string & bundleName,const Security::Verify::ProvisionInfo & provisionInfo,const InstallParam & installParam) const4041 void BaseBundleInstaller::AddAppProvisionInfo(const std::string &bundleName,
4042     const Security::Verify::ProvisionInfo &provisionInfo,
4043     const InstallParam &installParam) const
4044 {
4045     AppProvisionInfo appProvisionInfo = bundleInstallChecker_->ConvertToAppProvisionInfo(provisionInfo);
4046     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->AddAppProvisionInfo(
4047         bundleName, appProvisionInfo)) {
4048         APP_LOGW("bundleName: %{public}s add appProvisionInfo failed.", bundleName.c_str());
4049     }
4050     if (!installParam.specifiedDistributionType.empty()) {
4051         if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->SetSpecifiedDistributionType(
4052             bundleName, installParam.specifiedDistributionType)) {
4053             APP_LOGW("bundleName: %{public}s SetSpecifiedDistributionType failed.", bundleName.c_str());
4054         }
4055     }
4056     if (!installParam.additionalInfo.empty()) {
4057         if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->SetAdditionalInfo(
4058             bundleName, installParam.additionalInfo)) {
4059             APP_LOGW("bundleName: %{public}s SetAdditionalInfo failed.", bundleName.c_str());
4060         }
4061     }
4062 }
4063 
InnerProcessNativeLibs(InnerBundleInfo & info,const std::string & modulePath)4064 ErrCode BaseBundleInstaller::InnerProcessNativeLibs(InnerBundleInfo &info, const std::string &modulePath)
4065 {
4066     std::string targetSoPath;
4067     std::string cpuAbi;
4068     std::string nativeLibraryPath;
4069     bool isCompressNativeLibrary = info.IsCompressNativeLibs(info.GetCurModuleName());
4070     if (info.FetchNativeSoAttrs(modulePackage_, cpuAbi, nativeLibraryPath)) {
4071         if (isCompressNativeLibrary) {
4072             bool isLibIsolated = info.IsLibIsolated(info.GetCurModuleName());
4073             // extract so file: if hap so is not isolated, then extract so to tmp path.
4074             if (isLibIsolated) {
4075                 if (BundleUtil::EndWith(modulePath, Constants::TMP_SUFFIX)) {
4076                     nativeLibraryPath = BuildTempNativeLibraryPath(nativeLibraryPath);
4077                 }
4078             } else {
4079                 nativeLibraryPath = info.GetCurrentModulePackage() + Constants::TMP_SUFFIX +
4080                     Constants::PATH_SEPARATOR + nativeLibraryPath;
4081             }
4082             APP_LOGD("Need extract to temp dir: %{public}s", nativeLibraryPath.c_str());
4083             targetSoPath.append(Constants::BUNDLE_CODE_DIR).append(Constants::PATH_SEPARATOR)
4084                 .append(info.GetBundleName()).append(Constants::PATH_SEPARATOR).append(nativeLibraryPath)
4085                 .append(Constants::PATH_SEPARATOR);
4086             targetSoPathMap_.emplace(info.GetCurModuleName(), targetSoPath);
4087         }
4088     }
4089 
4090     APP_LOGD("begin to extract module files, modulePath : %{public}s, targetSoPath : %{public}s, cpuAbi : %{public}s",
4091         modulePath.c_str(), targetSoPath.c_str(), cpuAbi.c_str());
4092     std::string signatureFileDir = "";
4093     auto ret = FindSignatureFileDir(info.GetCurModuleName(), signatureFileDir);
4094     if (ret != ERR_OK) {
4095         return ret;
4096     }
4097     if (isCompressNativeLibrary) {
4098         auto result = ExtractModuleFiles(info, modulePath, targetSoPath, cpuAbi);
4099         CHECK_RESULT(result, "fail to extract module dir, error is %{public}d");
4100         // verify hap or hsp code signature for compressed so files
4101         result = VerifyCodeSignatureForNativeFiles(info, cpuAbi, targetSoPath, signatureFileDir);
4102         CHECK_RESULT(result, "fail to VerifyCodeSignature, error is %{public}d");
4103         // check whether the hap or hsp is encrypted
4104         result = CheckSoEncryption(info, cpuAbi, targetSoPath);
4105         CHECK_RESULT(result, "fail to CheckSoEncryption, error is %{public}d");
4106     } else {
4107         auto result = InstalldClient::GetInstance()->CreateBundleDir(modulePath);
4108         CHECK_RESULT(result, "fail to create temp bundle dir, error is %{public}d");
4109         std::vector<std::string> fileNames;
4110         result = InstalldClient::GetInstance()->GetNativeLibraryFileNames(modulePath_, cpuAbi, fileNames);
4111         CHECK_RESULT(result, "fail to GetNativeLibraryFileNames, error is %{public}d");
4112         info.SetNativeLibraryFileNames(modulePackage_, fileNames);
4113     }
4114     return ERR_OK;
4115 }
4116 
VerifyCodeSignatureForNativeFiles(InnerBundleInfo & info,const std::string & cpuAbi,const std::string & targetSoPath,const std::string & signatureFileDir) const4117 ErrCode BaseBundleInstaller::VerifyCodeSignatureForNativeFiles(InnerBundleInfo &info, const std::string &cpuAbi,
4118     const std::string &targetSoPath, const std::string &signatureFileDir) const
4119 {
4120     if (copyHapToInstallPath_) {
4121         APP_LOGI("hap will be copied to install path, and native files will be verified code signature later");
4122         return ERR_OK;
4123     }
4124     APP_LOGD("begin to verify code signature for native files");
4125     const std::string compileSdkType = info.GetBaseApplicationInfo().compileSdkType;
4126     CodeSignatureParam codeSignatureParam;
4127     codeSignatureParam.modulePath = modulePath_;
4128     codeSignatureParam.cpuAbi = cpuAbi;
4129     codeSignatureParam.targetSoPath = targetSoPath;
4130     codeSignatureParam.signatureFileDir = signatureFileDir;
4131     codeSignatureParam.isEnterpriseBundle = isEnterpriseBundle_;
4132     codeSignatureParam.appIdentifier = appIdentifier_;
4133     codeSignatureParam.isPreInstalledBundle = info.GetIsPreInstallApp();
4134     codeSignatureParam.isCompileSdkOpenHarmony = (compileSdkType == COMPILE_SDK_TYPE_OPEN_HARMONY);
4135     return InstalldClient::GetInstance()->VerifyCodeSignature(codeSignatureParam);
4136 }
4137 
VerifyCodeSignatureForHap(const std::unordered_map<std::string,InnerBundleInfo> & infos,const std::string & srcHapPath,const std::string & realHapPath)4138 ErrCode BaseBundleInstaller::VerifyCodeSignatureForHap(const std::unordered_map<std::string, InnerBundleInfo> &infos,
4139     const std::string &srcHapPath, const std::string &realHapPath)
4140 {
4141     APP_LOGD("begin to verify code signature for hap or internal hsp");
4142     auto iter = infos.find(srcHapPath);
4143     if (iter == infos.end()) {
4144         return ERR_OK;
4145     }
4146     std::string moduleName = (iter->second).GetCurModuleName();
4147     std::string cpuAbi;
4148     std::string nativeLibraryPath;
4149     (iter->second).FetchNativeSoAttrs((iter->second).GetCurrentModulePackage(), cpuAbi, nativeLibraryPath);
4150     const std::string compileSdkType = (iter->second).GetBaseApplicationInfo().compileSdkType;
4151     std::string signatureFileDir = "";
4152     auto ret = FindSignatureFileDir(moduleName, signatureFileDir);
4153     if (ret != ERR_OK) {
4154         return ret;
4155     }
4156     auto targetSoPath = targetSoPathMap_.find(moduleName);
4157     CodeSignatureParam codeSignatureParam;
4158     if (targetSoPath != targetSoPathMap_.end()) {
4159         codeSignatureParam.targetSoPath = targetSoPath->second;
4160     }
4161     codeSignatureParam.cpuAbi = cpuAbi;
4162     codeSignatureParam.modulePath = realHapPath;
4163     codeSignatureParam.signatureFileDir = signatureFileDir;
4164     codeSignatureParam.isEnterpriseBundle = isEnterpriseBundle_;
4165     codeSignatureParam.appIdentifier = appIdentifier_;
4166     codeSignatureParam.isCompileSdkOpenHarmony = (compileSdkType == COMPILE_SDK_TYPE_OPEN_HARMONY);
4167     codeSignatureParam.isPreInstalledBundle = (iter->second).GetIsPreInstallApp();
4168     return InstalldClient::GetInstance()->VerifyCodeSignatureForHap(codeSignatureParam);
4169 }
4170 
CheckSoEncryption(InnerBundleInfo & info,const std::string & cpuAbi,const std::string & targetSoPath)4171 ErrCode BaseBundleInstaller::CheckSoEncryption(InnerBundleInfo &info, const std::string &cpuAbi,
4172     const std::string &targetSoPath)
4173 {
4174     APP_LOGD("begin to check so encryption");
4175     CheckEncryptionParam param;
4176     param.modulePath = modulePath_;
4177     param.cpuAbi = cpuAbi;
4178     param.targetSoPath = targetSoPath;
4179     int uid = info.GetUid(userId_);
4180     param.bundleId = uid - userId_ * Constants::BASE_USER_RANGE;
4181     param.isCompressNativeLibrary = info.IsCompressNativeLibs(info.GetCurModuleName());
4182     if (info.GetModuleTypeByPackage(modulePackage_) == Profile::MODULE_TYPE_SHARED) {
4183         param.installBundleType = InstallBundleType::INTER_APP_HSP;
4184     }
4185     bool isEncrypted = false;
4186     ErrCode result = InstalldClient::GetInstance()->CheckEncryption(param, isEncrypted);
4187     CHECK_RESULT(result, "fail to CheckSoEncryption, error is %{public}d");
4188     if (isEncrypted) {
4189         APP_LOGD("module %{public}s is encrypted", modulePath_.c_str());
4190         info.SetApplicationReservedFlag(static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION));
4191     }
4192     return ERR_OK;
4193 }
4194 
ProcessOldNativeLibraryPath(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,uint32_t oldVersionCode,const std::string & oldNativeLibraryPath) const4195 void BaseBundleInstaller::ProcessOldNativeLibraryPath(const std::unordered_map<std::string, InnerBundleInfo> &newInfos,
4196     uint32_t oldVersionCode, const std::string &oldNativeLibraryPath) const
4197 {
4198     if (((oldVersionCode >= versionCode_) && !otaInstall_) || oldNativeLibraryPath.empty()) {
4199         return;
4200     }
4201     for (const auto &item : newInfos) {
4202         const auto &moduleInfos = item.second.GetInnerModuleInfos();
4203         for (const auto &moduleItem: moduleInfos) {
4204             if (moduleItem.second.compressNativeLibs) {
4205                 // no need to delete library path
4206                 return;
4207             }
4208         }
4209     }
4210     std::string oldLibPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
4211         Constants::PATH_SEPARATOR + Constants::LIBS;
4212     if (InstalldClient::GetInstance()->RemoveDir(oldLibPath) != ERR_OK) {
4213         APP_LOGW("bundleNmae: %{public}s remove old libs dir failed.", bundleName_.c_str());
4214     }
4215 }
4216 
ProcessAOT(bool isOTA,const std::unordered_map<std::string,InnerBundleInfo> & infos) const4217 void BaseBundleInstaller::ProcessAOT(bool isOTA, const std::unordered_map<std::string, InnerBundleInfo> &infos) const
4218 {
4219     if (isOTA) {
4220         APP_LOGD("is OTA, no need to AOT");
4221         return;
4222     }
4223     AOTHandler::GetInstance().HandleInstall(infos);
4224 }
4225 
CopyHapsToSecurityDir(const InstallParam & installParam,std::vector<std::string> & bundlePaths)4226 ErrCode BaseBundleInstaller::CopyHapsToSecurityDir(const InstallParam &installParam,
4227     std::vector<std::string> &bundlePaths)
4228 {
4229     if (!installParam.withCopyHaps) {
4230         APP_LOGD("no need to copy preInstallApp to secure dir");
4231         return ERR_OK;
4232     }
4233     if (!bundlePaths_.empty()) {
4234         bundlePaths = bundlePaths_;
4235         APP_LOGD("using the existed hap files in security dir");
4236         return ERR_OK;
4237     }
4238     for (size_t index = 0; index < bundlePaths.size(); ++index) {
4239         if (!BundleUtil::CheckSystemSize(bundlePaths[index], APP_INSTALL_PATH)) {
4240             APP_LOGE("install bundle(%{public}s) failed due to insufficient disk memory", bundlePaths[index].c_str());
4241             return ERR_APPEXECFWK_INSTALL_DISK_MEM_INSUFFICIENT;
4242         }
4243         auto destination = BundleUtil::CopyFileToSecurityDir(bundlePaths[index], DirType::STREAM_INSTALL_DIR,
4244             toDeleteTempHapPath_);
4245         if (destination.empty()) {
4246             APP_LOGE("copy file %{public}s to security dir failed", bundlePaths[index].c_str());
4247             return ERR_APPEXECFWK_INSTALL_COPY_HAP_FAILED;
4248         }
4249         if (bundlePaths[index].find(Constants::STREAM_INSTALL_PATH) != std::string::npos) {
4250             BundleUtil::DeleteDir(bundlePaths[index]);
4251         }
4252         bundlePaths[index] = destination;
4253     }
4254     bundlePaths_ = bundlePaths;
4255     return ERR_OK;
4256 }
4257 
RenameAllTempDir(const std::unordered_map<std::string,InnerBundleInfo> & newInfos) const4258 ErrCode BaseBundleInstaller::RenameAllTempDir(const std::unordered_map<std::string, InnerBundleInfo> &newInfos) const
4259 {
4260     APP_LOGD("begin to rename all temp dir");
4261     ErrCode ret = ERR_OK;
4262     for (const auto &info : newInfos) {
4263         if (info.second.GetOnlyCreateBundleUser()) {
4264             continue;
4265         }
4266         if ((ret = RenameModuleDir(info.second)) != ERR_OK) {
4267             APP_LOGE("rename dir failed");
4268             break;
4269         }
4270     }
4271     RemoveEmptyDirs(newInfos);
4272     return ret;
4273 }
4274 
FindSignatureFileDir(const std::string & moduleName,std::string & signatureFileDir)4275 ErrCode BaseBundleInstaller::FindSignatureFileDir(const std::string &moduleName, std::string &signatureFileDir)
4276 {
4277     APP_LOGD("begin to find code signature file of moudle %{public}s", moduleName.c_str());
4278     if (verifyCodeParams_.empty()) {
4279         signatureFileDir = "";
4280         APP_LOGD("verifyCodeParams_ is empty and no need to verify code signature of module %{public}s",
4281             moduleName.c_str());
4282         return ERR_OK;
4283     }
4284     if (signatureFileTmpMap_.find(moduleName) != signatureFileTmpMap_.end()) {
4285         signatureFileDir = signatureFileTmpMap_.at(moduleName);
4286         APP_LOGD("signature file of %{public}s is existed in temp map", moduleName.c_str());
4287         return ERR_OK;
4288     }
4289     auto iterator = verifyCodeParams_.find(moduleName);
4290     if (iterator == verifyCodeParams_.end()) {
4291         APP_LOGE("no signature file dir exist of module %{public}s", moduleName.c_str());
4292         return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FAILED;
4293     }
4294     signatureFileDir = verifyCodeParams_.at(moduleName);
4295 
4296     // check validity of the signature file
4297     auto ret = bundleInstallChecker_->CheckSignatureFileDir(signatureFileDir);
4298     if (ret != ERR_OK) {
4299         APP_LOGE("checkout signature file dir %{public}s failed", signatureFileDir.c_str());
4300         return ret;
4301     }
4302 
4303     // copy code signature file to security dir
4304     if (!BundleUtil::CheckSystemSize(signatureFileDir, APP_INSTALL_PATH)) {
4305         APP_LOGE("copy signature file(%{public}s) failed due to insufficient disk memory", signatureFileDir.c_str());
4306         return ERR_APPEXECFWK_INSTALL_DISK_MEM_INSUFFICIENT;
4307     }
4308     std::string destinationStr =
4309         BundleUtil::CopyFileToSecurityDir(signatureFileDir, DirType::SIG_FILE_DIR, toDeleteTempHapPath_);
4310     if (destinationStr.empty()) {
4311         APP_LOGE("copy file %{public}s to security dir failed", signatureFileDir.c_str());
4312         return ERR_APPEXECFWK_INSTALL_COPY_HAP_FAILED;
4313     }
4314     if (signatureFileDir.find(Constants::SIGNATURE_FILE_PATH) != std::string::npos) {
4315         BundleUtil::DeleteDir(signatureFileDir);
4316     }
4317     signatureFileDir = destinationStr;
4318     signatureFileTmpMap_.emplace(moduleName, destinationStr);
4319     APP_LOGD("signatureFileDir is %{public}s", signatureFileDir.c_str());
4320     return ERR_OK;
4321 }
4322 
GetTempHapPath(const InnerBundleInfo & info)4323 std::string BaseBundleInstaller::GetTempHapPath(const InnerBundleInfo &info)
4324 {
4325     std::string hapPath = GetHapPath(info);
4326     if (hapPath.empty() || (!BundleUtil::EndWith(hapPath, Constants::INSTALL_FILE_SUFFIX) &&
4327         !BundleUtil::EndWith(hapPath, Constants::HSP_FILE_SUFFIX))) {
4328         APP_LOGE("invalid hapPath %{public}s", hapPath.c_str());
4329         return "";
4330     }
4331     auto posOfPathSep = hapPath.rfind(Constants::PATH_SEPARATOR);
4332     if (posOfPathSep == std::string::npos) {
4333         return "";
4334     }
4335 
4336     std::string tempDir = hapPath.substr(0, posOfPathSep + 1) + info.GetCurrentModulePackage();
4337     if (installedModules_[info.GetCurrentModulePackage()]) {
4338         tempDir += Constants::TMP_SUFFIX;
4339     }
4340 
4341     return tempDir.append(hapPath.substr(posOfPathSep));
4342 }
4343 
CheckHapEncryption(const std::unordered_map<std::string,InnerBundleInfo> & infos)4344 ErrCode BaseBundleInstaller::CheckHapEncryption(const std::unordered_map<std::string, InnerBundleInfo> &infos)
4345 {
4346     APP_LOGD("begin to check hap encryption");
4347     InnerBundleInfo oldInfo;
4348     bool isExist = false;
4349     if (!GetInnerBundleInfo(oldInfo, isExist) || !isExist) {
4350         APP_LOGE("Get innerBundleInfo failed, bundleName: %{public}s", bundleName_.c_str());
4351         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
4352     }
4353     for (const auto &info : infos) {
4354         if (hapPathRecords_.find(info.first) == hapPathRecords_.end()) {
4355             APP_LOGE("path %{public}s cannot be found in hapPathRecord", info.first.c_str());
4356             return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
4357         }
4358         std::string hapPath = hapPathRecords_.at(info.first);
4359         CheckEncryptionParam param;
4360         param.modulePath = hapPath;
4361         int uid = info.second.GetUid(userId_);
4362         param.bundleId = uid - userId_ * Constants::BASE_USER_RANGE;
4363         param.isCompressNativeLibrary = info.second.IsCompressNativeLibs(info.second.GetCurModuleName());
4364         if (info.second.GetModuleTypeByPackage(modulePackage_) == Profile::MODULE_TYPE_SHARED) {
4365             param.installBundleType = InstallBundleType::INTER_APP_HSP;
4366         }
4367         bool isEncrypted = false;
4368         ErrCode result = InstalldClient::GetInstance()->CheckEncryption(param, isEncrypted);
4369         CHECK_RESULT(result, "fail to CheckHapEncryption, error is %{public}d");
4370         oldInfo.SetMoudleIsEncrpted(info.second.GetCurrentModulePackage(), isEncrypted);
4371     }
4372     if (oldInfo.IsContainEncryptedModule()) {
4373         APP_LOGD("application contains encrypted module");
4374         oldInfo.SetApplicationReservedFlag(static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION));
4375     } else {
4376         APP_LOGD("application does not contain encrypted module");
4377         oldInfo.ClearApplicationReservedFlag(static_cast<uint32_t>(ApplicationReservedFlag::ENCRYPTED_APPLICATION));
4378     }
4379     if (dataMgr_ == nullptr || !dataMgr_->UpdateInnerBundleInfo(oldInfo)) {
4380         APP_LOGE("save UpdateInnerBundleInfo failed");
4381         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
4382     }
4383     return ERR_OK;
4384 }
4385 
MoveFileToRealInstallationDir(const std::unordered_map<std::string,InnerBundleInfo> & infos)4386 ErrCode BaseBundleInstaller::MoveFileToRealInstallationDir(
4387     const std::unordered_map<std::string, InnerBundleInfo> &infos)
4388 {
4389     APP_LOGD("start to move file to real installation dir");
4390     for (const auto &info : infos) {
4391         if (hapPathRecords_.find(info.first) == hapPathRecords_.end()) {
4392             APP_LOGE("path %{public}s cannot be found in hapPathRecord", info.first.c_str());
4393             return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
4394         }
4395 
4396         std::string realInstallationPath = GetHapPath(info.second);
4397         APP_LOGD("move hsp or hsp file from path %{public}s to path %{public}s",
4398             hapPathRecords_.at(info.first).c_str(), realInstallationPath.c_str());
4399         // 1. move hap or hsp to real installation dir
4400         auto result = InstalldClient::GetInstance()->MoveFile(hapPathRecords_.at(info.first), realInstallationPath);
4401         if (result != ERR_OK) {
4402             APP_LOGE("move file to real path failed %{public}d", result);
4403             return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
4404         }
4405     }
4406     return ERR_OK;
4407 }
4408 
MoveSoFileToRealInstallationDir(const std::unordered_map<std::string,InnerBundleInfo> & infos)4409 ErrCode BaseBundleInstaller::MoveSoFileToRealInstallationDir(
4410     const std::unordered_map<std::string, InnerBundleInfo> &infos)
4411 {
4412     APP_LOGD("start to move so file to real installation dir");
4413     for (const auto &info : infos) {
4414         if (info.second.IsLibIsolated(info.second.GetCurModuleName()) ||
4415             !info.second.IsCompressNativeLibs(info.second.GetCurModuleName())) {
4416             APP_LOGI("so files are isolated or decompressed and no necessary to move so files");
4417             continue;
4418         }
4419         std::string cpuAbi = "";
4420         std::string nativeLibraryPath = "";
4421         bool isSoExisted = info.second.FetchNativeSoAttrs(info.second.GetCurrentModulePackage(), cpuAbi,
4422             nativeLibraryPath);
4423         if (isSoExisted) {
4424             std::string tempSoDir;
4425             tempSoDir.append(Constants::BUNDLE_CODE_DIR).append(Constants::PATH_SEPARATOR)
4426                 .append(info.second.GetBundleName()).append(Constants::PATH_SEPARATOR)
4427                 .append(info.second.GetCurrentModulePackage())
4428                 .append(Constants::TMP_SUFFIX).append(Constants::PATH_SEPARATOR)
4429                 .append(nativeLibraryPath);
4430             bool isDirExisted = false;
4431             auto result = InstalldClient::GetInstance()->IsExistDir(tempSoDir, isDirExisted);
4432             if (result != ERR_OK) {
4433                 APP_LOGE("check if dir existed failed %{public}d", result);
4434                 return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
4435             }
4436             if (!isDirExisted) {
4437                 APP_LOGW("temp so dir %{public}s is not existed and dose not need to be moved", tempSoDir.c_str());
4438                 continue;
4439             }
4440             std::string realSoDir;
4441             realSoDir.append(Constants::BUNDLE_CODE_DIR).append(Constants::PATH_SEPARATOR)
4442                 .append(info.second.GetBundleName()).append(Constants::PATH_SEPARATOR)
4443                 .append(nativeLibraryPath);
4444             APP_LOGD("move so file from path %{public}s to path %{public}s", tempSoDir.c_str(), realSoDir.c_str());
4445             isDirExisted = false;
4446             result = InstalldClient::GetInstance()->IsExistDir(realSoDir, isDirExisted);
4447             if (result != ERR_OK) {
4448                 APP_LOGE("check if dir existed failed %{public}d", result);
4449                 return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
4450             }
4451             if (!isDirExisted) {
4452                 InstalldClient::GetInstance()->CreateBundleDir(realSoDir);
4453             }
4454             result = InstalldClient::GetInstance()->MoveFiles(tempSoDir, realSoDir);
4455             if (result != ERR_OK) {
4456                 APP_LOGE("move file to real path failed %{public}d", result);
4457                 return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
4458             }
4459             RemoveTempSoDir(tempSoDir);
4460             if (!installedModules_[info.second.GetCurrentModulePackage()]) {
4461                 RemoveTempPathOnlyUsedForSo(info.second);
4462             }
4463         }
4464     }
4465     return ERR_OK;
4466 }
4467 
UpdateAppInstallControlled(int32_t userId)4468 void BaseBundleInstaller::UpdateAppInstallControlled(int32_t userId)
4469 {
4470 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
4471     if (!DelayedSingleton<AppControlManager>::GetInstance()->IsAppInstallControlEnabled()) {
4472         APP_LOGD("app control feature is disabled");
4473         return;
4474     }
4475 
4476     if (bundleName_.empty() || dataMgr_ == nullptr) {
4477         APP_LOGW("invalid bundleName_ or dataMgr is nullptr");
4478         return;
4479     }
4480     InnerBundleInfo info;
4481     bool isAppExisted = dataMgr_->QueryInnerBundleInfo(bundleName_, info);
4482     if (!isAppExisted) {
4483         APP_LOGW("bundle %{public}s is not existed", bundleName_.c_str());
4484         return;
4485     }
4486 
4487     InnerBundleUserInfo userInfo;
4488     if (!info.GetInnerBundleUserInfo(userId, userInfo)) {
4489         APP_LOGW("current bundle (%{public}s) is not installed at current userId (%{public}d)",
4490             bundleName_.c_str(), userId);
4491         return;
4492     }
4493 
4494     std::string currentAppId = info.GetAppId();
4495     std::vector<std::string> appIds;
4496     ErrCode ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
4497         AppControlConstants::EDM_CALLING, AppControlConstants::APP_DISALLOWED_UNINSTALL, userId, appIds);
4498     if ((ret == ERR_OK) && (std::find(appIds.begin(), appIds.end(), currentAppId) != appIds.end())) {
4499         APP_LOGW("bundle %{public}s cannot be removed", bundleName_.c_str());
4500         userInfo.isRemovable = false;
4501         dataMgr_->AddInnerBundleUserInfo(bundleName_, userInfo);
4502     }
4503 #else
4504     APP_LOGW("app control is disable");
4505 #endif
4506 }
4507 
UninstallBundleFromBmsExtension(const std::string & bundleName)4508 ErrCode BaseBundleInstaller::UninstallBundleFromBmsExtension(const std::string &bundleName)
4509 {
4510     APP_LOGD("start to uninstall bundle from bms extension");
4511     if (!DelayedSingleton<BundleMgrService>::GetInstance()->IsBrokerServiceStarted()) {
4512         APP_LOGW("broker is not started");
4513         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
4514     }
4515     BmsExtensionDataMgr bmsExtensionDataMgr;
4516     auto ret = bmsExtensionDataMgr.Uninstall(bundleName);
4517     if (ret == ERR_OK) {
4518         APP_LOGD("uninstall bundle(%{public}s) from bms extension successfully", bundleName.c_str());
4519         return ERR_OK;
4520     }
4521     if ((ret == ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE) ||
4522         (ret == ERR_BUNDLE_MANAGER_INSTALL_FAILED_BUNDLE_EXTENSION_NOT_EXISTED)) {
4523         APP_LOGE("uninstall failed due to bundle(%{public}s is not existed)", bundleName.c_str());
4524         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
4525     }
4526     APP_LOGE("uninstall bundle(%{public}s) from bms extension faile due to errcode %{public}d",
4527         bundleName.c_str(), ret);
4528     return ERR_BUNDLE_MANAGER_UNINSTALL_FROM_BMS_EXTENSION_FAILED;
4529 }
4530 
CheckBundleInBmsExtension(const std::string & bundleName,int32_t userId)4531 ErrCode BaseBundleInstaller::CheckBundleInBmsExtension(const std::string &bundleName, int32_t userId)
4532 {
4533     APP_LOGD("start to check bundle(%{public}s) from bms extension", bundleName.c_str());
4534     if (!DelayedSingleton<BundleMgrService>::GetInstance()->IsBrokerServiceStarted()) {
4535         APP_LOGW("broker is not started");
4536         return ERR_OK;
4537     }
4538     BmsExtensionDataMgr bmsExtensionDataMgr;
4539     BundleInfo extensionBundleInfo;
4540     auto ret = bmsExtensionDataMgr.GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, userId,
4541         extensionBundleInfo);
4542     if (ret == ERR_OK) {
4543         APP_LOGE("the bundle(%{public}s) is already existed in the bms extension", bundleName.c_str());
4544         return ERR_APPEXECFWK_INSTALL_ALREADY_EXIST;
4545     }
4546     return ERR_OK;
4547 }
4548 
RemoveTempSoDir(const std::string & tempSoDir)4549 void BaseBundleInstaller::RemoveTempSoDir(const std::string &tempSoDir)
4550 {
4551     auto firstPos = tempSoDir.find(Constants::TMP_SUFFIX);
4552     if (firstPos == std::string::npos) {
4553         APP_LOGW("invalid tempSoDir %{public}s", tempSoDir.c_str());
4554         return;
4555     }
4556     auto secondPos = tempSoDir.find(Constants::PATH_SEPARATOR, firstPos);
4557     if (secondPos == std::string::npos) {
4558         APP_LOGW("invalid tempSoDir %{public}s", tempSoDir.c_str());
4559         return;
4560     }
4561     auto thirdPos = tempSoDir.find(Constants::PATH_SEPARATOR, secondPos + 1);
4562     if (thirdPos == std::string::npos) {
4563         InstalldClient::GetInstance()->RemoveDir(tempSoDir);
4564         return;
4565     }
4566     std::string subTempSoDir = tempSoDir.substr(0, thirdPos);
4567     InstalldClient::GetInstance()->RemoveDir(subTempSoDir);
4568 }
4569 
InstallEntryMoudleFirst(std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & bundleInfo,const InnerBundleUserInfo & innerBundleUserInfo,const InstallParam & installParam)4570 ErrCode BaseBundleInstaller::InstallEntryMoudleFirst(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
4571     InnerBundleInfo &bundleInfo, const InnerBundleUserInfo &innerBundleUserInfo, const InstallParam &installParam)
4572 {
4573     APP_LOGD("start to install entry firstly");
4574     if (!isAppExist_ || isEntryInstalled_) {
4575         APP_LOGD("no need to install entry firstly");
4576         return ERR_OK;
4577     }
4578     ErrCode result = ERR_OK;
4579     for (auto &info : newInfos) {
4580         if (info.second.HasEntry()) {
4581             modulePath_ = info.first;
4582             InnerBundleInfo &newInfo = info.second;
4583             newInfo.AddInnerBundleUserInfo(innerBundleUserInfo);
4584             bool isReplace = (installParam.installFlag == InstallFlag::REPLACE_EXISTING ||
4585                 installParam.installFlag == InstallFlag::FREE_INSTALL);
4586             // app exist, but module may not
4587             result = ProcessBundleUpdateStatus(bundleInfo, newInfo, isReplace, installParam.noSkipsKill);
4588             if (result == ERR_OK) {
4589                 entryModuleName_ = info.second.GetCurrentModulePackage();
4590                 APP_LOGD("entry packageName is %{public}s", entryModuleName_.c_str());
4591             }
4592             break;
4593         }
4594     }
4595     isEntryInstalled_ = true;
4596     return result;
4597 }
4598 
DeliveryProfileToCodeSign() const4599 ErrCode BaseBundleInstaller::DeliveryProfileToCodeSign() const
4600 {
4601     APP_LOGD("start to delivery sign profile to code signature");
4602     Security::Verify::ProvisionInfo provisionInfo = verifyRes_.GetProvisionInfo();
4603     if (provisionInfo.profileBlockLength == 0 || provisionInfo.profileBlock == nullptr) {
4604         APP_LOGD("Emulator does not verify signature");
4605         return ERR_OK;
4606     }
4607     if (provisionInfo.distributionType == Security::Verify::AppDistType::ENTERPRISE ||
4608         provisionInfo.distributionType == Security::Verify::AppDistType::ENTERPRISE_NORMAL ||
4609         provisionInfo.distributionType == Security::Verify::AppDistType::ENTERPRISE_MDM ||
4610         provisionInfo.type == Security::Verify::ProvisionType::DEBUG) {
4611         return InstalldClient::GetInstance()->DeliverySignProfile(provisionInfo.bundleInfo.bundleName,
4612             provisionInfo.profileBlockLength, provisionInfo.profileBlock.get());
4613     }
4614     return ERR_OK;
4615 }
4616 
RemoveProfileFromCodeSign(const std::string & bundleName) const4617 ErrCode BaseBundleInstaller::RemoveProfileFromCodeSign(const std::string &bundleName) const
4618 {
4619     APP_LOGD("start to remove sign profile of bundle %{public}s from code signature", bundleName.c_str());
4620     return InstalldClient::GetInstance()->RemoveSignProfile(bundleName);
4621 }
4622 
DeleteOldNativeLibraryPath() const4623 void BaseBundleInstaller::DeleteOldNativeLibraryPath() const
4624 {
4625     std::string oldLibPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
4626         Constants::PATH_SEPARATOR + Constants::LIBS;
4627     if (InstalldClient::GetInstance()->RemoveDir(oldLibPath) != ERR_OK) {
4628         APP_LOGW("bundleNmae: %{public}s remove old libs dir failed.", bundleName_.c_str());
4629     }
4630 }
4631 
RemoveTempPathOnlyUsedForSo(const InnerBundleInfo & innerBundleInfo) const4632 void BaseBundleInstaller::RemoveTempPathOnlyUsedForSo(const InnerBundleInfo &innerBundleInfo) const
4633 {
4634     APP_LOGD("start");
4635     std::string tempDir;
4636     tempDir.append(Constants::BUNDLE_CODE_DIR).append(Constants::PATH_SEPARATOR)
4637         .append(innerBundleInfo.GetBundleName()).append(Constants::PATH_SEPARATOR)
4638         .append(innerBundleInfo.GetCurrentModulePackage())
4639         .append(Constants::TMP_SUFFIX);
4640     bool isDirEmpty = false;
4641     if (InstalldClient::GetInstance()->IsDirEmpty(tempDir, isDirEmpty) != ERR_OK) {
4642         APP_LOGW("IsDirEmpty failed");
4643     }
4644     if (isDirEmpty && (InstalldClient::GetInstance()->RemoveDir(tempDir) != ERR_OK)) {
4645         APP_LOGW("remove tmp so path:%{public}s failed", tempDir.c_str());
4646     }
4647     APP_LOGD("end");
4648 }
4649 
NeedDeleteOldNativeLib(std::unordered_map<std::string,InnerBundleInfo> & newInfos,const InnerBundleInfo & oldInfo)4650 bool BaseBundleInstaller::NeedDeleteOldNativeLib(
4651     std::unordered_map<std::string, InnerBundleInfo> &newInfos,
4652     const InnerBundleInfo &oldInfo)
4653 {
4654     if (newInfos.empty()) {
4655         APP_LOGD("NewInfos is null");
4656         return false;
4657     }
4658 
4659     if (!isAppExist_) {
4660         APP_LOGD("No old app");
4661         return false;
4662     }
4663 
4664     if (oldInfo.GetNativeLibraryPath().empty()) {
4665         APP_LOGD("Old app no library");
4666         return false;
4667     }
4668 
4669     if ((versionCode_ > oldInfo.GetVersionCode())) {
4670         APP_LOGD("Higher versionCode");
4671         return true;
4672     }
4673 
4674     if (oldInfo.GetApplicationBundleType() == BundleType::APP_SERVICE_FWK) {
4675         APP_LOGD("Appservice not delete library");
4676         return false;
4677     }
4678 
4679     for (const auto &info : newInfos) {
4680         if (info.second.GetOnlyCreateBundleUser()) {
4681             APP_LOGD("Some hap no update module.");
4682             return false;
4683         }
4684     }
4685 
4686     return otaInstall_ || HasAllOldModuleUpdate(oldInfo, newInfos);
4687 }
4688 }  // namespace AppExecFwk
4689 }  // namespace OHOS
4690