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