1 /*
2 * Copyright (c) 2022-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 "bundle_user_mgr_host_impl.h"
17
18 #include "bms_extension_data_mgr.h"
19 #include "bms_key_event_mgr.h"
20 #include "bundle_mgr_service.h"
21 #include "hitrace_meter.h"
22 #include "installd_client.h"
23 #include "ipc_skeleton.h"
24 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
25 #include "default_app_mgr.h"
26 #endif
27 #ifdef WINDOW_ENABLE
28 #include "scene_board_judgement.h"
29 #endif
30 #include "status_receiver_host.h"
31
32 namespace OHOS {
33 namespace AppExecFwk {
34 std::atomic_uint g_installedHapNum = 0;
35 const std::string ARK_PROFILE_PATH = "/data/local/ark-profile/";
36 const uint32_t FACTOR = 8;
37 const uint32_t INTERVAL = 6;
38 constexpr const char* QUICK_FIX_APP_PATH = "/data/update/quickfix/app/temp/cold";
39 constexpr const char* ACCESSTOKEN_PROCESS_NAME = "accesstoken_service";
40
41 class UserReceiverImpl : public StatusReceiverHost {
42 public:
UserReceiverImpl(const std::string & bundleName,bool needReInstall)43 UserReceiverImpl(const std::string &bundleName, bool needReInstall)
44 : bundleName_(bundleName), needReInstall_(needReInstall) {};
45 virtual ~UserReceiverImpl() override = default;
46
SetBundlePromise(const std::shared_ptr<BundlePromise> & bundlePromise)47 void SetBundlePromise(const std::shared_ptr<BundlePromise>& bundlePromise)
48 {
49 bundlePromise_ = bundlePromise;
50 }
51
SetTotalHapNum(int32_t totalHapNum)52 void SetTotalHapNum(int32_t totalHapNum)
53 {
54 totalHapNum_ = totalHapNum;
55 }
56
SavePreInstallException(const std::string & bundleName)57 void SavePreInstallException(const std::string &bundleName)
58 {
59 auto preInstallExceptionMgr =
60 DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
61 if (preInstallExceptionMgr == nullptr) {
62 APP_LOGE("preInstallExceptionMgr is nullptr");
63 return;
64 }
65
66 preInstallExceptionMgr->SavePreInstallExceptionBundleName(bundleName);
67 }
68
OnStatusNotify(const int progress)69 virtual void OnStatusNotify(const int progress) override {}
OnFinished(const int32_t resultCode,const std::string & resultMsg)70 virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) override
71 {
72 g_installedHapNum++;
73 APP_LOGI("OnFinished, resultCode : %{public}d, resultMsg : %{public}s, count : %{public}u",
74 resultCode, resultMsg.c_str(), g_installedHapNum.load());
75 if (static_cast<int32_t>(g_installedHapNum) >= totalHapNum_ && bundlePromise_ != nullptr) {
76 bundlePromise_->NotifyAllTasksExecuteFinished();
77 }
78
79 if (resultCode != ERR_OK && resultCode !=
80 ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON && needReInstall_) {
81 APP_LOGI("needReInstall bundleName: %{public}s", bundleName_.c_str());
82 BmsKeyEventMgr::ProcessMainBundleInstallFailed(bundleName_, resultCode);
83 SavePreInstallException(bundleName_);
84 }
85 }
86 private:
87 std::shared_ptr<BundlePromise> bundlePromise_ = nullptr;
88 int32_t totalHapNum_ = INT32_MAX;
89 std::string bundleName_;
90 bool needReInstall_ = false;
91 };
92
CreateNewUser(int32_t userId,const std::vector<std::string> & disallowList)93 ErrCode BundleUserMgrHostImpl::CreateNewUser(int32_t userId, const std::vector<std::string> &disallowList)
94 {
95 HITRACE_METER(HITRACE_TAG_APP);
96 EventReport::SendUserSysEvent(UserEventType::CREATE_START, userId);
97 EventReport::SendCpuSceneEvent(ACCESSTOKEN_PROCESS_NAME, 1 << 1); // second scene
98 APP_LOGI("CreateNewUser user(%{public}d) start", userId);
99 std::lock_guard<std::mutex> lock(bundleUserMgrMutex_);
100 if (CheckInitialUser() != ERR_OK) {
101 APP_LOGE("CheckInitialUser failed");
102 return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
103 }
104 BeforeCreateNewUser(userId);
105 OnCreateNewUser(userId, disallowList);
106 UninstallBackupUninstallList(userId);
107 AfterCreateNewUser(userId);
108 EventReport::SendUserSysEvent(UserEventType::CREATE_END, userId);
109 APP_LOGI("CreateNewUser end userId: (%{public}d)", userId);
110 return ERR_OK;
111 }
112
BeforeCreateNewUser(int32_t userId)113 void BundleUserMgrHostImpl::BeforeCreateNewUser(int32_t userId)
114 {
115 ClearBundleEvents();
116 }
117
OnCreateNewUser(int32_t userId,const std::vector<std::string> & disallowList)118 void BundleUserMgrHostImpl::OnCreateNewUser(int32_t userId, const std::vector<std::string> &disallowList)
119 {
120 auto dataMgr = GetDataMgrFromService();
121 if (dataMgr == nullptr) {
122 APP_LOGE("DataMgr is nullptr");
123 return;
124 }
125
126 auto installer = GetBundleInstaller();
127 if (installer == nullptr) {
128 APP_LOGE("installer is nullptr");
129 return;
130 }
131
132 if (dataMgr->HasUserId(userId)) {
133 APP_LOGE("Has create user %{public}d", userId);
134 return;
135 }
136
137 dataMgr->AddUserId(userId);
138 std::set<PreInstallBundleInfo> preInstallBundleInfos;
139 if (!GetAllPreInstallBundleInfos(disallowList, userId, preInstallBundleInfos)) {
140 APP_LOGE("GetAllPreInstallBundleInfos failed %{public}d", userId);
141 return;
142 }
143
144 g_installedHapNum = 0;
145 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
146 int32_t totalHapNum = static_cast<int32_t>(preInstallBundleInfos.size());
147 std::string identity = IPCSkeleton::ResetCallingIdentity();
148 bool needReinstall = userId == Constants::START_USERID;
149 // Read apps installed by other users that are visible to all users
150 for (const auto &info : preInstallBundleInfos) {
151 InstallParam installParam;
152 installParam.userId = userId;
153 installParam.isPreInstallApp = true;
154 installParam.installFlag = InstallFlag::NORMAL;
155 installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
156 sptr<UserReceiverImpl> userReceiverImpl(
157 new (std::nothrow) UserReceiverImpl(info.GetBundleName(), needReinstall));
158 userReceiverImpl->SetBundlePromise(bundlePromise);
159 userReceiverImpl->SetTotalHapNum(totalHapNum);
160 installer->InstallByBundleName(info.GetBundleName(), installParam, userReceiverImpl);
161 }
162 if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
163 bundlePromise->WaitForAllTasksExecute();
164 APP_LOGI("OnCreateNewUser wait complete");
165 }
166 // process keep alive bundle
167 if (userId == Constants::START_USERID) {
168 BMSEventHandler::ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, false);
169 }
170 IPCSkeleton::SetCallingIdentity(identity);
171 }
172
GetAllPreInstallBundleInfos(const std::vector<std::string> & disallowList,int32_t userId,std::set<PreInstallBundleInfo> & preInstallBundleInfos)173 bool BundleUserMgrHostImpl::GetAllPreInstallBundleInfos(
174 const std::vector<std::string> &disallowList,
175 int32_t userId,
176 std::set<PreInstallBundleInfo> &preInstallBundleInfos)
177 {
178 auto dataMgr = GetDataMgrFromService();
179 if (dataMgr == nullptr) {
180 APP_LOGE("DataMgr is nullptr");
181 return false;
182 }
183
184 bool isStartUser = userId == Constants::START_USERID;
185 std::vector<PreInstallBundleInfo> allPreInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
186 // Scan preset applications and parse package information.
187 for (auto &preInfo : allPreInstallBundleInfos) {
188 InnerBundleInfo innerBundleInfo;
189 if (dataMgr->FetchInnerBundleInfo(preInfo.GetBundleName(), innerBundleInfo)
190 && innerBundleInfo.IsSingleton()) {
191 APP_LOGI("BundleName is IsSingleton %{public}s", preInfo.GetBundleName().c_str());
192 continue;
193 }
194 if (std::find(disallowList.begin(), disallowList.end(),
195 preInfo.GetBundleName()) != disallowList.end()) {
196 APP_LOGI("BundleName is same as black list %{public}s", preInfo.GetBundleName().c_str());
197 continue;
198 }
199 if (isStartUser) {
200 preInfo.CalculateHapTotalSize();
201 }
202 preInstallBundleInfos.insert(preInfo);
203 }
204
205 return !preInstallBundleInfos.empty();
206 }
207
AfterCreateNewUser(int32_t userId)208 void BundleUserMgrHostImpl::AfterCreateNewUser(int32_t userId)
209 {
210 if (userId == Constants::START_USERID) {
211 DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
212 // need process main bundle status
213 BmsKeyEventMgr::ProcessMainBundleStatusFinally();
214 }
215
216 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
217 DefaultAppMgr::GetInstance().HandleCreateUser(userId);
218 #endif
219 HandleSceneBoard(userId);
220 RdbDataManager::ClearCache();
221 }
222
RemoveUser(int32_t userId)223 ErrCode BundleUserMgrHostImpl::RemoveUser(int32_t userId)
224 {
225 HITRACE_METER(HITRACE_TAG_APP);
226 EventReport::SendUserSysEvent(UserEventType::REMOVE_START, userId);
227 EventReport::SendCpuSceneEvent(ACCESSTOKEN_PROCESS_NAME, 1 << 1); // second scene
228 APP_LOGI("RemoveUser user(%{public}d) start", userId);
229 std::lock_guard<std::mutex> lock(bundleUserMgrMutex_);
230 auto dataMgr = GetDataMgrFromService();
231 if (dataMgr == nullptr) {
232 APP_LOGE("DataMgr is nullptr");
233 return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
234 }
235
236 auto installer = GetBundleInstaller();
237 if (installer == nullptr) {
238 APP_LOGE("installer is nullptr");
239 return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
240 }
241
242 if (!dataMgr->HasUserId(userId)) {
243 APP_LOGE("Has remove user %{public}d", userId);
244 return ERR_APPEXECFWK_USER_NOT_EXIST;
245 }
246
247 std::vector<BundleInfo> bundleInfos;
248 if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, userId)) {
249 APP_LOGE("get all bundle info failed when userId %{public}d", userId);
250 RemoveArkProfile(userId);
251 RemoveAsanLogDirectory(userId);
252 dataMgr->RemoveUserId(userId);
253 return ERR_OK;
254 }
255
256 ClearBundleEvents();
257 InnerUninstallBundle(userId, bundleInfos);
258 RemoveArkProfile(userId);
259 RemoveAsanLogDirectory(userId);
260 dataMgr->RemoveUserId(userId);
261 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
262 DefaultAppMgr::GetInstance().HandleRemoveUser(userId);
263 #endif
264 EventReport::SendUserSysEvent(UserEventType::REMOVE_END, userId);
265 HandleNotifyBundleEventsAsync();
266 APP_LOGI("RemoveUser end userId: (%{public}d)", userId);
267 return ERR_OK;
268 }
269
RemoveArkProfile(int32_t userId)270 void BundleUserMgrHostImpl::RemoveArkProfile(int32_t userId)
271 {
272 std::string arkProfilePath;
273 arkProfilePath.append(ARK_PROFILE_PATH).append(std::to_string(userId));
274 APP_LOGI("DeleteArkProfile %{public}s when remove user", arkProfilePath.c_str());
275 InstalldClient::GetInstance()->RemoveDir(arkProfilePath);
276 }
277
RemoveAsanLogDirectory(int32_t userId)278 void BundleUserMgrHostImpl::RemoveAsanLogDirectory(int32_t userId)
279 {
280 std::string asanLogDir = ServiceConstants::BUNDLE_ASAN_LOG_DIR + ServiceConstants::PATH_SEPARATOR
281 + std::to_string(userId);
282 APP_LOGI("remove asan log directory %{public}s when remove user", asanLogDir.c_str());
283 InstalldClient::GetInstance()->RemoveDir(asanLogDir);
284 }
285
CheckInitialUser()286 ErrCode BundleUserMgrHostImpl::CheckInitialUser()
287 {
288 auto dataMgr = GetDataMgrFromService();
289 if (dataMgr == nullptr) {
290 APP_LOGE("DataMgr is nullptr");
291 return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
292 }
293
294 if (!dataMgr->HasInitialUserCreated()) {
295 APP_LOGI("Bms initial user do not created successfully and wait");
296 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
297 dataMgr->SetBundlePromise(bundlePromise);
298 bundlePromise->WaitForAllTasksExecute();
299 APP_LOGI("Bms initial user created successfully");
300 }
301 return ERR_OK;
302 }
303
GetDataMgrFromService()304 const std::shared_ptr<BundleDataMgr> BundleUserMgrHostImpl::GetDataMgrFromService()
305 {
306 return DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
307 }
308
GetBundleInstaller()309 const sptr<IBundleInstaller> BundleUserMgrHostImpl::GetBundleInstaller()
310 {
311 return DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
312 }
313
InnerUninstallBundle(int32_t userId,const std::vector<BundleInfo> & bundleInfos)314 void BundleUserMgrHostImpl::InnerUninstallBundle(
315 int32_t userId,
316 const std::vector<BundleInfo> &bundleInfos)
317 {
318 APP_LOGI("InnerUninstallBundle for userId: %{public}d start", userId);
319 auto installer = GetBundleInstaller();
320 if (installer == nullptr) {
321 APP_LOGE("InnerUninstallBundle installer is nullptr");
322 return;
323 }
324 std::string identity = IPCSkeleton::ResetCallingIdentity();
325 g_installedHapNum = 0;
326 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
327 int32_t totalHapNum = static_cast<int32_t>(bundleInfos.size());
328 for (const auto &info : bundleInfos) {
329 InstallParam installParam;
330 installParam.userId = userId;
331 installParam.SetForceExecuted(true);
332 installParam.concentrateSendEvent = true;
333 installParam.isPreInstallApp = info.isPreInstallApp;
334 installParam.installFlag = InstallFlag::NORMAL;
335 sptr<UserReceiverImpl> userReceiverImpl(
336 new (std::nothrow) UserReceiverImpl(info.name, false));
337 userReceiverImpl->SetBundlePromise(bundlePromise);
338 userReceiverImpl->SetTotalHapNum(totalHapNum);
339 installer->Uninstall(info.name, installParam, userReceiverImpl);
340 }
341 if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
342 bundlePromise->WaitForAllTasksExecute();
343 }
344 IPCSkeleton::SetCallingIdentity(identity);
345 APP_LOGI("InnerUninstallBundle for userId: %{public}d end", userId);
346 }
347
ClearBundleEvents()348 void BundleUserMgrHostImpl::ClearBundleEvents()
349 {
350 std::lock_guard<std::mutex> uninstallEventLock(bundleEventMutex_);
351 bundleEvents_.clear();
352 }
353
AddNotifyBundleEvents(const NotifyBundleEvents & notifyBundleEvents)354 void BundleUserMgrHostImpl::AddNotifyBundleEvents(const NotifyBundleEvents ¬ifyBundleEvents)
355 {
356 std::lock_guard<std::mutex> lock(bundleEventMutex_);
357 bundleEvents_.emplace_back(notifyBundleEvents);
358 }
359
HandleNotifyBundleEventsAsync()360 void BundleUserMgrHostImpl::HandleNotifyBundleEventsAsync()
361 {
362 auto task = [this] {
363 HandleNotifyBundleEvents();
364 };
365 std::thread taskThread(task);
366 taskThread.detach();
367 }
368
HandleNotifyBundleEvents()369 void BundleUserMgrHostImpl::HandleNotifyBundleEvents()
370 {
371 APP_LOGI("HandleNotifyBundleEvents");
372 std::lock_guard<std::mutex> lock(bundleEventMutex_);
373 auto dataMgr = GetDataMgrFromService();
374 if (dataMgr == nullptr) {
375 APP_LOGE("DataMgr is nullptr");
376 return;
377 }
378
379 std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
380 for (size_t i = 0; i < bundleEvents_.size(); ++i) {
381 commonEventMgr->NotifyBundleStatus(bundleEvents_[i], dataMgr);
382 if ((i != 0) && (i % FACTOR == 0)) {
383 std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL));
384 }
385 }
386
387 bundleEvents_.clear();
388 }
389
HandleSceneBoard(int32_t userId) const390 void BundleUserMgrHostImpl::HandleSceneBoard(int32_t userId) const
391 {
392 #ifdef WINDOW_ENABLE
393 auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
394 if (dataMgr == nullptr) {
395 APP_LOGE("dataMgr is null");
396 return;
397 }
398 bool sceneBoardEnable = Rosen::SceneBoardJudgement::IsSceneBoardEnabled();
399 APP_LOGI("userId : %{public}d, sceneBoardEnable : %{public}d", userId, sceneBoardEnable);
400 dataMgr->SetApplicationEnabled(Constants::SCENE_BOARD_BUNDLE_NAME, 0, sceneBoardEnable,
401 ServiceConstants::CALLER_NAME_BMS, userId);
402 dataMgr->SetApplicationEnabled(ServiceConstants::LAUNCHER_BUNDLE_NAME, 0, !sceneBoardEnable,
403 ServiceConstants::CALLER_NAME_BMS, userId);
404 #endif
405 }
406
UninstallBackupUninstallList(int32_t userId)407 void BundleUserMgrHostImpl::UninstallBackupUninstallList(int32_t userId)
408 {
409 BmsExtensionDataMgr bmsExtensionDataMgr;
410 std::set<std::string> uninstallList;
411 bmsExtensionDataMgr.GetBackupUninstallList(userId, uninstallList);
412 if (uninstallList.empty()) {
413 APP_LOGI("userId : %{public}d, back uninstall list is empty", userId);
414 return;
415 }
416 auto installer = GetBundleInstaller();
417 if (installer == nullptr) {
418 APP_LOGE("installer is nullptr");
419 return;
420 }
421
422 std::string identity = IPCSkeleton::ResetCallingIdentity();
423 g_installedHapNum = 0;
424 std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
425 int32_t totalHapNum = static_cast<int32_t>(uninstallList.size());
426 for (const auto &bundleName : uninstallList) {
427 InstallParam installParam;
428 installParam.userId = userId;
429 installParam.needSendEvent = false;
430 installParam.isPreInstallApp = true;
431 sptr<UserReceiverImpl> userReceiverImpl(
432 new (std::nothrow) UserReceiverImpl(bundleName, false));
433 userReceiverImpl->SetBundlePromise(bundlePromise);
434 userReceiverImpl->SetTotalHapNum(totalHapNum);
435 installer->Uninstall(bundleName, installParam, userReceiverImpl);
436 }
437 if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
438 bundlePromise->WaitForAllTasksExecute();
439 }
440 IPCSkeleton::SetCallingIdentity(identity);
441 bmsExtensionDataMgr.ClearBackupUninstallFile(userId);
442 }
443 } // namespace AppExecFwk
444 } // namespace OHOS
445