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