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