1 /*
2 * Copyright (c) 2022-2025 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 "bundle_user_mgr_host_impl.h"
17
18 #include <cstring>
19 #include <fcntl.h>
20 #include <sys/ioctl.h>
21 #include "securec.h"
22 #include "aot_handler.h"
23 #include "bms_extension_data_mgr.h"
24 #include "bms_key_event_mgr.h"
25 #include "bundle_hitrace_chain.h"
26 #include "bundle_mgr_service.h"
27 #include "hitrace_meter.h"
28 #include "installd_client.h"
29 #include "ipc_skeleton.h"
30 #include "parameters.h"
31 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
32 #include "default_app_mgr.h"
33 #endif
34 #ifdef WINDOW_ENABLE
35 #include "scene_board_judgement.h"
36 #endif
37 #include "status_receiver_host.h"
38
39 namespace OHOS {
40 namespace AppExecFwk {
41 std::atomic_uint g_installedHapNum = 0;
42 constexpr const char* DATA_PRELOAD_APP = "/data/preload/app/";
43 constexpr uint8_t FACTOR = 8;
44 constexpr uint8_t INTERVAL = 6;
45 constexpr const char* QUICK_FIX_APP_PATH = "/data/update/quickfix/app/temp/cold";
46 constexpr const char* ACCESSTOKEN_PROCESS_NAME = "accesstoken_service";
47 constexpr const char* PRELOAD_APP = "/preload/app/";
48 constexpr const char* MULTIUSER_INSTALL_THIRD_PRELOAD_APP = "const.bms.multiUserInstallThirdPreloadApp";
49
50 struct BootFailProcParam {
51 char padForErrno[16];
52 int bootFailErrno;
53 char padForStage[8];
54 int stage; /* stage saved by bootdetector */
55 char padForSuggest[4];
56 int suggestRecoveryMethod;
57 char padForDetailInfo[28]; /* reserved count */
58 char detailInfo[384]; /* max exception info count */
59 char reserved[572]; /* reserved count */
60 } __attribute((packed));
61
62 #define NATIVE_SUBSYS_FAULT 0x40000009
63 #define NATIVE_STAGE 0x4FFFFFFE
64 #define BOOT_DETECTOR_DEV_PATH "/dev/bbox"
65 #define BOOT_DETECTOR_IOCTL_BASE 'B'
66 #define PROCESS_BOOTFAIL _IOW(BOOT_DETECTOR_IOCTL_BASE, 102, struct BootFailProcParam)
67
68 class UserReceiverImpl : public StatusReceiverHost {
69 public:
UserReceiverImpl(const std::string & bundleName,bool needReInstall)70 UserReceiverImpl(const std::string &bundleName, bool needReInstall)
71 : bundleName_(bundleName), needReInstall_(needReInstall) {};
72 virtual ~UserReceiverImpl() override = default;
73
SetBundlePromise(const std::shared_ptr<BundlePromise> & bundlePromise)74 void SetBundlePromise(const std::shared_ptr<BundlePromise>& bundlePromise)
75 {
76 bundlePromise_ = bundlePromise;
77 }
78
SetTotalHapNum(int32_t totalHapNum)79 void SetTotalHapNum(int32_t totalHapNum)
80 {
81 totalHapNum_ = totalHapNum;
82 }
83
SavePreInstallException(const std::string & bundleName)84 void SavePreInstallException(const std::string &bundleName)
85 {
86 auto preInstallExceptionMgr =
87 DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
88 if (preInstallExceptionMgr == nullptr) {
89 APP_LOGE("preInstallExceptionMgr is nullptr");
90 return;
91 }
92
93 preInstallExceptionMgr->SavePreInstallExceptionBundleName(bundleName);
94 }
95
OnStatusNotify(const int progress)96 virtual void OnStatusNotify(const int progress) override {}
OnFinished(const int32_t resultCode,const std::string & resultMsg)97 virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) override
98 {
99 g_installedHapNum++;
100 APP_LOGI("OnFinished, resultCode : %{public}d, resultMsg : %{public}s, count : %{public}u",
101 resultCode, resultMsg.c_str(), g_installedHapNum.load());
102 if (static_cast<int32_t>(g_installedHapNum) >= totalHapNum_ && bundlePromise_ != nullptr) {
103 bundlePromise_->NotifyAllTasksExecuteFinished();
104 }
105
106 if (resultCode != ERR_OK && resultCode !=
107 ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON && needReInstall_) {
108 APP_LOGI("needReInstall bundleName: %{public}s", bundleName_.c_str());
109 BmsKeyEventMgr::ProcessMainBundleInstallFailed(bundleName_, resultCode);
110 SavePreInstallException(bundleName_);
111 }
112 }
113 private:
114 std::shared_ptr<BundlePromise> bundlePromise_ = nullptr;
115 int32_t totalHapNum_ = INT32_MAX;
116 std::string bundleName_;
117 bool needReInstall_ = false;
118 };
119
SkipThirdPreloadAppInstallation(const int32_t userId,const PreInstallBundleInfo & preInfo)120 bool BundleUserMgrHostImpl::SkipThirdPreloadAppInstallation(const int32_t userId, const PreInstallBundleInfo &preInfo)
121 {
122 if (userId == Constants::START_USERID) {
123 return false;
124 }
125 const std::vector<std::string> bundlePaths = preInfo.GetBundlePaths();
126 if (bundlePaths.empty()) {
127 return false;
128 }
129 const std::string firstBundlePath = bundlePaths.front();
130 if (firstBundlePath.rfind(DATA_PRELOAD_APP, 0) == 0) {
131 APP_LOGI("-n %{public}s -u %{public}d not install data preload app", preInfo.GetBundleName().c_str(), userId);
132 return true;
133 }
134 bool multiUserInstallThirdPreloadApp = OHOS::system::GetBoolParameter(MULTIUSER_INSTALL_THIRD_PRELOAD_APP, true);
135 if (firstBundlePath.rfind(PRELOAD_APP, 0) == 0 && !multiUserInstallThirdPreloadApp) {
136 APP_LOGI("-n %{public}s -u %{public}d not install preload app", preInfo.GetBundleName().c_str(), userId);
137 return true;
138 }
139 return false;
140 }
141
CreateNewUser(int32_t userId,const std::vector<std::string> & disallowList,const std::optional<std::vector<std::string>> & allowList)142 ErrCode BundleUserMgrHostImpl::CreateNewUser(int32_t userId, const std::vector<std::string> &disallowList,
143 const std::optional<std::vector<std::string>> &allowList)
144 {
145 BUNDLE_MANAGER_HITRACE_CHAIN_NAME("CreateNewUser", HITRACE_FLAG_INCLUDE_ASYNC);
146 HITRACE_METER(HITRACE_TAG_APP);
147 EventReport::SendCpuSceneEvent(ACCESSTOKEN_PROCESS_NAME, 1 << 1); // second scene
148 APP_LOGW("CreateNewUser user(%{public}d) start", userId);
149 BmsExtensionDataMgr bmsExtensionDataMgr;
150 bool needToSkipPreBundleInstall = bmsExtensionDataMgr.IsNeedToSkipPreBundleInstall();
151 if (needToSkipPreBundleInstall) {
152 APP_LOGI("need to skip pre bundle install");
153 EventReport::SendUserSysEvent(UserEventType::CREATE_WITH_SKIP_PRE_INSTALL_START, userId);
154 } else {
155 EventReport::SendUserSysEvent(UserEventType::CREATE_START, userId);
156 }
157 std::lock_guard<std::mutex> lock(bundleUserMgrMutex_);
158 if (CheckInitialUser() != ERR_OK) {
159 APP_LOGE("CheckInitialUser failed");
160 return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
161 }
162 BeforeCreateNewUser(userId);
163 OnCreateNewUser(userId, needToSkipPreBundleInstall, disallowList, allowList);
164 UninstallBackupUninstallList(userId, needToSkipPreBundleInstall);
165 AfterCreateNewUser(userId);
166 if (needToSkipPreBundleInstall) {
167 EventReport::SendUserSysEvent(UserEventType::CREATE_WITH_SKIP_PRE_INSTALL_END, userId);
168 } else {
169 EventReport::SendUserSysEvent(UserEventType::CREATE_END, userId);
170 }
171 APP_LOGW("CreateNewUser end userId: (%{public}d)", userId);
172 return ERR_OK;
173 }
174
BeforeCreateNewUser(int32_t userId)175 void BundleUserMgrHostImpl::BeforeCreateNewUser(int32_t userId)
176 {
177 ClearBundleEvents();
178 InstalldClient::GetInstance()->AddUserDirDeleteDfx(userId);
179 CreateArkStartupCacheDir(userId);
180 }
181
OnCreateNewUser(int32_t userId,bool needToSkipPreBundleInstall,const std::vector<std::string> & disallowList,const std::optional<std::vector<std::string>> & allowList)182 void BundleUserMgrHostImpl::OnCreateNewUser(int32_t userId, bool needToSkipPreBundleInstall,
183 const std::vector<std::string> &disallowList, const std::optional<std::vector<std::string>> &allowList)
184 {
185 auto dataMgr = GetDataMgrFromService();
186 if (dataMgr == nullptr) {
187 APP_LOGE("DataMgr is nullptr");
188 return;
189 }
190
191 auto installer = GetBundleInstaller();
192 if (installer == nullptr) {
193 APP_LOGE("installer is nullptr");
194 return;
195 }
196
197 if (dataMgr->HasUserId(userId)) {
198 APP_LOGE("Has create user %{public}d", userId);
199 ErrCode ret = InnerRemoveUser(userId, false); // no need lock
200 if (ret != ERR_OK) {
201 APP_LOGW("remove user %{public}d failed, error %{public}d", userId, ret);
202 }
203 }
204
205 dataMgr->AddUserId(userId);
206 dataMgr->CreateAppInstallDir(userId);
207 std::set<PreInstallBundleInfo> preInstallBundleInfos;
208 if (!GetAllPreInstallBundleInfos(disallowList, userId, needToSkipPreBundleInstall,
209 preInstallBundleInfos, allowList)) {
210 APP_LOGE("GetAllPreInstallBundleInfos failed %{public}d", userId);
211 return;
212 }
213 GetAdditionalBundleInfos(preInstallBundleInfos);
214 g_installedHapNum = 0;
215 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
216 int32_t totalHapNum = static_cast<int32_t>(preInstallBundleInfos.size());
217 std::string identity = IPCSkeleton::ResetCallingIdentity();
218 bool needReinstall = userId == Constants::START_USERID;
219 // Read apps installed by other users that are visible to all users
220 for (const auto &info : preInstallBundleInfos) {
221 InstallParam installParam;
222 installParam.userId = userId;
223 installParam.isPreInstallApp = !info.GetIsAdditionalApp();
224 installParam.installFlag = InstallFlag::NORMAL;
225 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
226 sptr<UserReceiverImpl> userReceiverImpl(
227 new (std::nothrow) UserReceiverImpl(info.GetBundleName(), needReinstall));
228 if (userReceiverImpl == nullptr) {
229 APP_LOGE("userReceiverImpl is nullptr, -n %{public}s", info.GetBundleName().c_str());
230 g_installedHapNum++;
231 if (needReinstall) {
232 SavePreInstallException(info.GetBundleName());
233 }
234 continue;
235 }
236 userReceiverImpl->SetBundlePromise(bundlePromise);
237 userReceiverImpl->SetTotalHapNum(totalHapNum);
238 installer->InstallByBundleName(info.GetBundleName(), installParam, userReceiverImpl);
239 }
240 if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
241 bundlePromise->WaitForAllTasksExecute();
242 APP_LOGI("OnCreateNewUser wait complete");
243 }
244 CheckSystemHspInstallPath();
245 // process keep alive bundle
246 if (userId == Constants::START_USERID) {
247 BMSEventHandler::ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, false);
248 }
249 IPCSkeleton::SetCallingIdentity(identity);
250 }
251
BootFailError(const char * exceptionInfo)252 void BundleUserMgrHostImpl::BootFailError(const char *exceptionInfo)
253 {
254 APP_LOGI("BootFailError start, exceptionInfo is %{public}s", exceptionInfo);
255 struct BootFailProcParam parm;
256 parm.bootFailErrno = NATIVE_SUBSYS_FAULT;
257 parm.stage = NATIVE_STAGE;
258 parm.suggestRecoveryMethod = 0;
259 ErrCode ret = ERR_OK;
260 if (exceptionInfo != NULL) {
261 ret = strncpy_s(parm.detailInfo, sizeof(parm.detailInfo),
262 exceptionInfo, std::min(sizeof(parm.detailInfo) - 1,
263 strlen(exceptionInfo)));
264 if (ret != ERR_OK) {
265 APP_LOGE("strncpy_s failed: %{public}d", ret);
266 return;
267 }
268 }
269 APP_LOGD("parm.detailInfo is %{public}s,bootFailErrno is %{public}d",
270 parm.detailInfo, parm.bootFailErrno);
271 int fd = TEMP_FAILURE_RETRY(open(BOOT_DETECTOR_DEV_PATH, O_WRONLY));
272 if (fd < 0) {
273 APP_LOGE("open file %{public}s failed, errorNo: %{public}d:%{public}s",
274 BOOT_DETECTOR_DEV_PATH, errno, strerror(errno));
275 return;
276 }
277
278 ret = ioctl(fd, PROCESS_BOOTFAIL, &parm); // 1: the order of the cmd
279 if (ret < 0) {
280 APP_LOGE("BootFailError ioctl failed, errorNo: %{public}d, :%{public}s", errno, strerror(errno));
281 }
282 close(fd);
283 return;
284 }
285
CheckSystemHspInstallPath()286 void BundleUserMgrHostImpl::CheckSystemHspInstallPath()
287 {
288 LOG_I(BMS_TAG_DEFAULT, "start");
289 auto dataMgr = GetDataMgrFromService();
290 if (dataMgr == nullptr) {
291 APP_LOGE("DataMgr is nullptr");
292 return;
293 }
294
295 std::vector<std::string> systemHspCodePaths = dataMgr->GetAllSystemHspCodePaths();
296 for (auto &codePath : systemHspCodePaths) {
297 bool isExist = false;
298 ErrCode result = InstalldClient::GetInstance()->IsExistDir(codePath, isExist);
299 if (result != ERR_OK || !isExist) {
300 APP_LOGE("%{public}s not exist, set parameter BOOT_FAIL_ERR false", codePath.c_str());
301 BootFailError("bms boot fail");
302 return;
303 }
304 }
305 }
306
307
GetAllPreInstallBundleInfos(const std::vector<std::string> & disallowList,int32_t userId,bool needToSkipPreBundleInstall,std::set<PreInstallBundleInfo> & preInstallBundleInfos,const std::optional<std::vector<std::string>> & allowList)308 bool BundleUserMgrHostImpl::GetAllPreInstallBundleInfos(
309 const std::vector<std::string> &disallowList,
310 int32_t userId, bool needToSkipPreBundleInstall,
311 std::set<PreInstallBundleInfo> &preInstallBundleInfos,
312 const std::optional<std::vector<std::string>> &allowList)
313 {
314 auto dataMgr = GetDataMgrFromService();
315 if (dataMgr == nullptr) {
316 APP_LOGE("DataMgr is nullptr");
317 return false;
318 }
319
320 bool isStartUser = userId == Constants::START_USERID;
321 std::vector<PreInstallBundleInfo> allPreInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
322 // Scan preset applications and parse package information.
323 std::vector<std::string> allowLst = allowList.value_or(std::vector<std::string>());
324 std::unordered_set<std::string> allowSet = allowLst.empty() ? std::unordered_set<std::string>() :
325 std::unordered_set<std::string>(allowLst.begin(), allowLst.end());
326 std::unordered_set<std::string> disallowSet= disallowList.empty() ? std::unordered_set<std::string>() :
327 std::unordered_set<std::string>(disallowList.begin(), disallowList.end());
328 bool isU1 = (userId == Constants::U1);
329 for (auto &preInfo : allPreInstallBundleInfos) {
330 InnerBundleInfo innerBundleInfo;
331 if (dataMgr->FetchInnerBundleInfo(preInfo.GetBundleName(), innerBundleInfo)
332 && innerBundleInfo.IsSingleton()) {
333 APP_LOGI("BundleName is IsSingleton %{public}s", preInfo.GetBundleName().c_str());
334 continue;
335 }
336
337 if ((isU1 && !preInfo.GetU1Enable()) || (!isU1 && preInfo.GetU1Enable())) {
338 APP_LOGI(" %{public}s u1enable and u1 not matched", preInfo.GetBundleName().c_str());
339 continue;
340 }
341 if (disallowSet.find(preInfo.GetBundleName()) != disallowSet.end()) {
342 APP_LOGI("BundleName is same as black list %{public}s", preInfo.GetBundleName().c_str());
343 continue;
344 }
345 if (allowList.has_value() && allowSet.find(preInfo.GetBundleName()) == allowSet.end()) {
346 APP_LOGI("BundleName is not in white list %{public}s", preInfo.GetBundleName().c_str());
347 continue;
348 }
349 if (needToSkipPreBundleInstall && !preInfo.GetBundlePaths().empty() &&
350 (preInfo.GetBundlePaths().front().find(PRELOAD_APP) == 0)) {
351 APP_LOGI("-n %{public}s -u %{public}d skip install", preInfo.GetBundleName().c_str(), userId);
352 continue;
353 }
354 if (SkipThirdPreloadAppInstallation(userId, preInfo)) {
355 continue;
356 }
357 if (isStartUser) {
358 preInfo.CalculateHapTotalSize();
359 }
360 preInstallBundleInfos.insert(preInfo);
361 }
362
363 return !preInstallBundleInfos.empty();
364 }
365
GetAdditionalBundleInfos(std::set<PreInstallBundleInfo> & preInstallBundleInfos)366 void BundleUserMgrHostImpl::GetAdditionalBundleInfos(std::set<PreInstallBundleInfo> &preInstallBundleInfos)
367 {
368 auto dataMgr = GetDataMgrFromService();
369 if (dataMgr == nullptr) {
370 APP_LOGE("DataMgr is nullptr");
371 return;
372 }
373 // get all non pre-installed driver apps to install for new user
374 std::vector<std::string> bundleNames = dataMgr->GetBundleNamesForNewUser();
375 for (auto &bundleName : bundleNames) {
376 PreInstallBundleInfo preInstallBundleInfo;
377 preInstallBundleInfo.SetBundleName(bundleName);
378 preInstallBundleInfo.SetIsAdditionalApp(true);
379 preInstallBundleInfos.insert(preInstallBundleInfo);
380 }
381 }
382
AfterCreateNewUser(int32_t userId)383 void BundleUserMgrHostImpl::AfterCreateNewUser(int32_t userId)
384 {
385 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
386 DefaultAppMgr::GetInstance().HandleCreateUser(userId);
387 #endif
388 HandleSceneBoard(userId);
389 RdbDataManager::ClearCache();
390 if (userId == Constants::START_USERID) {
391 DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
392 // need process main bundle status
393 BmsKeyEventMgr::ProcessMainBundleStatusFinally();
394 }
395 }
396
RemoveUser(int32_t userId)397 ErrCode BundleUserMgrHostImpl::RemoveUser(int32_t userId)
398 {
399 BUNDLE_MANAGER_HITRACE_CHAIN_NAME("RemoveUser", HITRACE_FLAG_INCLUDE_ASYNC);
400 return InnerRemoveUser(userId, true);
401 }
402
InnerRemoveUser(int32_t userId,bool needLock)403 ErrCode BundleUserMgrHostImpl::InnerRemoveUser(int32_t userId, bool needLock)
404 {
405 HITRACE_METER(HITRACE_TAG_APP);
406 EventReport::SendUserSysEvent(UserEventType::REMOVE_START, userId);
407 EventReport::SendCpuSceneEvent(ACCESSTOKEN_PROCESS_NAME, 1 << 1); // second scene
408 APP_LOGI("RemoveUser user(%{public}d) start needLock %{public}d", userId, needLock);
409 if (needLock) {
410 std::lock_guard<std::mutex> lock(bundleUserMgrMutex_);
411 return ProcessRemoveUser(userId);
412 }
413 return ProcessRemoveUser(userId);
414 }
415
ProcessRemoveUser(int32_t userId)416 ErrCode BundleUserMgrHostImpl::ProcessRemoveUser(int32_t userId)
417 {
418 auto dataMgr = GetDataMgrFromService();
419 if (dataMgr == nullptr) {
420 APP_LOGE("DataMgr is nullptr");
421 return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
422 }
423
424 auto installer = GetBundleInstaller();
425 if (installer == nullptr) {
426 APP_LOGE("installer is nullptr");
427 return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
428 }
429
430 if (!dataMgr->HasUserId(userId)) {
431 APP_LOGE("Has remove user %{public}d", userId);
432 return ERR_APPEXECFWK_USER_NOT_EXIST;
433 }
434
435 std::vector<BundleInfo> bundleInfos;
436 if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, userId)) {
437 APP_LOGE("get all bundle info failed when userId %{public}d", userId);
438 RemoveArkProfile(userId);
439 RemoveAsanLogDirectory(userId);
440 dataMgr->RemoveUserId(userId);
441 dataMgr->RemoveAppInstallDir(userId);
442 dataMgr->DeleteFirstInstallBundleInfo(userId);
443 return ERR_OK;
444 }
445
446 ClearBundleEvents();
447 InnerUninstallBundle(userId, bundleInfos);
448 RemoveArkProfile(userId);
449 RemoveAsanLogDirectory(userId);
450 RemoveSystemOptimizeDir(userId);
451 dataMgr->RemoveUserId(userId);
452 dataMgr->RemoveAppInstallDir(userId);
453 dataMgr->DeleteFirstInstallBundleInfo(userId);
454 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
455 DefaultAppMgr::GetInstance().HandleRemoveUser(userId);
456 #endif
457 EventReport::SendUserSysEvent(UserEventType::REMOVE_END, userId);
458 HandleNotifyBundleEventsAsync();
459 APP_LOGI("RemoveUser end userId: (%{public}d)", userId);
460 return ERR_OK;
461 }
462
RemoveArkProfile(int32_t userId)463 void BundleUserMgrHostImpl::RemoveArkProfile(int32_t userId)
464 {
465 std::string arkProfilePath = AOTHandler::BuildArkProfilePath(userId);
466 APP_LOGI("DeleteArkProfile %{public}s when remove user", arkProfilePath.c_str());
467 InstalldClient::GetInstance()->ClearDir(arkProfilePath);
468 }
469
RemoveAsanLogDirectory(int32_t userId)470 void BundleUserMgrHostImpl::RemoveAsanLogDirectory(int32_t userId)
471 {
472 std::string asanLogDir = std::string(ServiceConstants::BUNDLE_ASAN_LOG_DIR) + ServiceConstants::PATH_SEPARATOR
473 + std::to_string(userId);
474 APP_LOGI("remove asan log directory %{public}s when remove user", asanLogDir.c_str());
475 InstalldClient::GetInstance()->RemoveDir(asanLogDir);
476 }
477
CheckInitialUser()478 ErrCode BundleUserMgrHostImpl::CheckInitialUser()
479 {
480 auto dataMgr = GetDataMgrFromService();
481 if (dataMgr == nullptr) {
482 APP_LOGE("DataMgr is nullptr");
483 return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
484 }
485
486 if (!dataMgr->HasInitialUserCreated()) {
487 APP_LOGI("Bms initial user do not created successfully and wait");
488 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
489 dataMgr->SetBundlePromise(bundlePromise);
490 bundlePromise->WaitForAllTasksExecute();
491 APP_LOGI("Bms initial user created successfully");
492 }
493 return ERR_OK;
494 }
495
GetDataMgrFromService()496 const std::shared_ptr<BundleDataMgr> BundleUserMgrHostImpl::GetDataMgrFromService()
497 {
498 return DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
499 }
500
GetBundleInstaller()501 const sptr<IBundleInstaller> BundleUserMgrHostImpl::GetBundleInstaller()
502 {
503 return DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
504 }
505
InnerUninstallBundle(int32_t userId,const std::vector<BundleInfo> & bundleInfos)506 void BundleUserMgrHostImpl::InnerUninstallBundle(
507 int32_t userId,
508 const std::vector<BundleInfo> &bundleInfos)
509 {
510 APP_LOGI("InnerUninstallBundle for userId: %{public}d start", userId);
511 auto installer = GetBundleInstaller();
512 if (installer == nullptr) {
513 APP_LOGE("InnerUninstallBundle installer is nullptr");
514 return;
515 }
516 std::string identity = IPCSkeleton::ResetCallingIdentity();
517 g_installedHapNum = 0;
518 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
519 int32_t totalHapNum = static_cast<int32_t>(bundleInfos.size());
520 for (const auto &info : bundleInfos) {
521 InstallParam installParam;
522 installParam.userId = userId;
523 installParam.SetForceExecuted(true);
524 installParam.concentrateSendEvent = true;
525 installParam.isPreInstallApp = info.isPreInstallApp;
526 installParam.installFlag = InstallFlag::NORMAL;
527 installParam.isRemoveUser = true;
528 // if user is 100, no need to kill process
529 installParam.SetKillProcess(userId != Constants::START_USERID);
530 sptr<UserReceiverImpl> userReceiverImpl(
531 new (std::nothrow) UserReceiverImpl(info.name, false));
532 if (userReceiverImpl == nullptr) {
533 APP_LOGE("userReceiverImpl is nullptr, -n %{public}s", info.name.c_str());
534 g_installedHapNum++;
535 continue;
536 }
537 userReceiverImpl->SetBundlePromise(bundlePromise);
538 userReceiverImpl->SetTotalHapNum(totalHapNum);
539 installer->Uninstall(info.name, installParam, userReceiverImpl);
540 }
541 if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
542 bundlePromise->WaitForAllTasksExecute();
543 }
544 IPCSkeleton::SetCallingIdentity(identity);
545 APP_LOGI("InnerUninstallBundle for userId: %{public}d end", userId);
546 }
547
ClearBundleEvents()548 void BundleUserMgrHostImpl::ClearBundleEvents()
549 {
550 std::lock_guard<std::mutex> uninstallEventLock(bundleEventMutex_);
551 bundleEvents_.clear();
552 }
553
AddNotifyBundleEvents(const NotifyBundleEvents & notifyBundleEvents)554 void BundleUserMgrHostImpl::AddNotifyBundleEvents(const NotifyBundleEvents ¬ifyBundleEvents)
555 {
556 std::lock_guard<std::mutex> lock(bundleEventMutex_);
557 bundleEvents_.emplace_back(notifyBundleEvents);
558 }
559
HandleNotifyBundleEventsAsync()560 void BundleUserMgrHostImpl::HandleNotifyBundleEventsAsync()
561 {
562 auto task = [this] {
563 HandleNotifyBundleEvents();
564 };
565 std::thread taskThread(task);
566 taskThread.detach();
567 }
568
HandleNotifyBundleEvents()569 void BundleUserMgrHostImpl::HandleNotifyBundleEvents()
570 {
571 APP_LOGI("HandleNotifyBundleEvents");
572 std::vector<NotifyBundleEvents> bundleEvents;
573 {
574 std::lock_guard<std::mutex> lock(bundleEventMutex_);
575 bundleEvents = bundleEvents_;
576 bundleEvents_.clear();
577 }
578 auto dataMgr = GetDataMgrFromService();
579 if (dataMgr == nullptr) {
580 APP_LOGE("DataMgr is nullptr");
581 return;
582 }
583
584 std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
585 for (size_t i = 0; i < bundleEvents.size(); ++i) {
586 commonEventMgr->NotifyBundleStatus(bundleEvents[i], dataMgr);
587 if ((i != 0) && (i % FACTOR == 0)) {
588 std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL));
589 }
590 }
591 }
592
HandleSceneBoard(int32_t userId) const593 void BundleUserMgrHostImpl::HandleSceneBoard(int32_t userId) const
594 {
595 #ifdef WINDOW_ENABLE
596 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
597 if (dataMgr == nullptr) {
598 APP_LOGE("dataMgr is null");
599 return;
600 }
601 bool sceneBoardEnable = Rosen::SceneBoardJudgement::IsSceneBoardEnabled();
602 APP_LOGI("userId : %{public}d, sceneBoardEnable : %{public}d", userId, sceneBoardEnable);
603 dataMgr->SetApplicationEnabled(Constants::SCENE_BOARD_BUNDLE_NAME, 0, sceneBoardEnable,
604 ServiceConstants::CALLER_NAME_BMS, userId);
605 dataMgr->SetApplicationEnabled(ServiceConstants::LAUNCHER_BUNDLE_NAME, 0, !sceneBoardEnable,
606 ServiceConstants::CALLER_NAME_BMS, userId);
607 #endif
608 }
609
InnerProcessSkipPreInstallBundles(const std::set<std::string> & uninstallList,bool needToSkipPreBundleInstall)610 bool BundleUserMgrHostImpl::InnerProcessSkipPreInstallBundles(
611 const std::set<std::string> &uninstallList, bool needToSkipPreBundleInstall)
612 {
613 if (uninstallList.empty() || !needToSkipPreBundleInstall) {
614 return true;
615 }
616 APP_LOGI("process skip pre bundle install start");
617 auto dataMgr = GetDataMgrFromService();
618 if (dataMgr == nullptr) {
619 APP_LOGE("DataMgr is nullptr");
620 return false;
621 }
622 bool ret = true;
623 for (const auto &name : uninstallList) {
624 PreInstallBundleInfo preInfo;
625 preInfo.SetBundleName(name);
626 if (!dataMgr->GetPreInstallBundleInfo(name, preInfo)) {
627 APP_LOGI("no pre bundleInfo %{public}s in db", name.c_str());
628 continue;
629 }
630 if (!preInfo.GetBundlePaths().empty() && (preInfo.GetBundlePaths().front().find(PRELOAD_APP) == 0)) {
631 preInfo.SetIsUninstalled(true);
632 if (!dataMgr->SavePreInstallBundleInfo(name, preInfo)) {
633 APP_LOGE("save pre bundle %{public}s failed", name.c_str());
634 ret = false;
635 }
636 }
637 }
638 APP_LOGI("process skip pre bundle install end");
639 return ret;
640 }
641
UninstallBackupUninstallList(int32_t userId,bool needToSkipPreBundleInstall)642 void BundleUserMgrHostImpl::UninstallBackupUninstallList(int32_t userId, bool needToSkipPreBundleInstall)
643 {
644 BmsExtensionDataMgr bmsExtensionDataMgr;
645 std::set<std::string> uninstallList;
646 bmsExtensionDataMgr.GetBackupUninstallList(userId, uninstallList);
647 if (uninstallList.empty()) {
648 APP_LOGI("userId : %{public}d, back uninstall list is empty", userId);
649 return;
650 }
651 auto installer = GetBundleInstaller();
652 if (installer == nullptr) {
653 APP_LOGE("installer is nullptr");
654 return;
655 }
656
657 std::string identity = IPCSkeleton::ResetCallingIdentity();
658 g_installedHapNum = 0;
659 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
660 int32_t totalHapNum = static_cast<int32_t>(uninstallList.size());
661 for (const auto &bundleName : uninstallList) {
662 InstallParam installParam;
663 installParam.userId = userId;
664 installParam.needSendEvent = false;
665 installParam.isPreInstallApp = true;
666 sptr<UserReceiverImpl> userReceiverImpl(
667 new (std::nothrow) UserReceiverImpl(bundleName, false));
668 if (userReceiverImpl == nullptr) {
669 APP_LOGE("userReceiverImpl is nullptr, -n %{public}s", bundleName.c_str());
670 g_installedHapNum++;
671 continue;
672 }
673 userReceiverImpl->SetBundlePromise(bundlePromise);
674 userReceiverImpl->SetTotalHapNum(totalHapNum);
675 installer->Uninstall(bundleName, installParam, userReceiverImpl);
676 }
677 if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
678 bundlePromise->WaitForAllTasksExecute();
679 }
680 IPCSkeleton::SetCallingIdentity(identity);
681 bmsExtensionDataMgr.ClearBackupUninstallFile(userId);
682 (void)InnerProcessSkipPreInstallBundles(uninstallList, needToSkipPreBundleInstall);
683 }
684
SavePreInstallException(const std::string & bundleName)685 void BundleUserMgrHostImpl::SavePreInstallException(const std::string &bundleName)
686 {
687 auto preInstallExceptionMgr =
688 DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
689 if (preInstallExceptionMgr == nullptr) {
690 APP_LOGE("preInstallExceptionMgr is nullptr, -n %{public}s save failed", bundleName.c_str());
691 return;
692 }
693
694 preInstallExceptionMgr->SavePreInstallExceptionBundleName(bundleName);
695 }
696
CreateArkStartupCacheDir(int32_t userId)697 ErrCode BundleUserMgrHostImpl::CreateArkStartupCacheDir(int32_t userId)
698 {
699 std::string el1ArkStartupCachePath = ServiceConstants::SYSTEM_OPTIMIZE_PATH;
700 el1ArkStartupCachePath = el1ArkStartupCachePath.replace(el1ArkStartupCachePath.find("%"), 1,
701 std::to_string(userId));
702 APP_LOGI("create system optimize directory %{public}s when create user: %{public}d",
703 el1ArkStartupCachePath.c_str(), userId);
704 return InstalldClient::GetInstance()->Mkdir(el1ArkStartupCachePath, ServiceConstants::SYSTEM_OPTIMIZE_MODE, 0, 0);
705 }
706
RemoveSystemOptimizeDir(int32_t userId)707 ErrCode BundleUserMgrHostImpl::RemoveSystemOptimizeDir(int32_t userId)
708 {
709 std::string el1ArkStartupCachePath = ServiceConstants::SYSTEM_OPTIMIZE_PATH;
710 el1ArkStartupCachePath = el1ArkStartupCachePath.replace(el1ArkStartupCachePath.find("%"), 1,
711 std::to_string(userId));
712 APP_LOGI("remove system optimize directory %{public}s when remove user: %{public}d",
713 el1ArkStartupCachePath.c_str(), userId);
714 return InstalldClient::GetInstance()->RemoveDir(el1ArkStartupCachePath);
715 }
716 } // namespace AppExecFwk
717 } // namespace OHOS
718