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     dataMgr->CreateAppInstallDir(userId);
139     std::set<PreInstallBundleInfo> preInstallBundleInfos;
140     if (!GetAllPreInstallBundleInfos(disallowList, userId, preInstallBundleInfos)) {
141         APP_LOGE("GetAllPreInstallBundleInfos failed %{public}d", userId);
142         return;
143     }
144 
145     g_installedHapNum = 0;
146     std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
147     int32_t totalHapNum = static_cast<int32_t>(preInstallBundleInfos.size());
148     std::string identity = IPCSkeleton::ResetCallingIdentity();
149     bool needReinstall = userId == Constants::START_USERID;
150     // Read apps installed by other users that are visible to all users
151     for (const auto &info : preInstallBundleInfos) {
152         InstallParam installParam;
153         installParam.userId = userId;
154         installParam.isPreInstallApp = true;
155         installParam.installFlag = InstallFlag::NORMAL;
156         installParam.preinstallSourceFlag = ApplicationInfoFlag::FLAG_BOOT_INSTALLED;
157         sptr<UserReceiverImpl> userReceiverImpl(
158             new (std::nothrow) UserReceiverImpl(info.GetBundleName(), needReinstall));
159         userReceiverImpl->SetBundlePromise(bundlePromise);
160         userReceiverImpl->SetTotalHapNum(totalHapNum);
161         installer->InstallByBundleName(info.GetBundleName(), installParam, userReceiverImpl);
162     }
163     if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
164         bundlePromise->WaitForAllTasksExecute();
165         APP_LOGI("OnCreateNewUser wait complete");
166     }
167     // process keep alive bundle
168     if (userId == Constants::START_USERID) {
169         BMSEventHandler::ProcessRebootQuickFixBundleInstall(QUICK_FIX_APP_PATH, false);
170     }
171     IPCSkeleton::SetCallingIdentity(identity);
172 }
173 
GetAllPreInstallBundleInfos(const std::vector<std::string> & disallowList,int32_t userId,std::set<PreInstallBundleInfo> & preInstallBundleInfos)174 bool BundleUserMgrHostImpl::GetAllPreInstallBundleInfos(
175     const std::vector<std::string> &disallowList,
176     int32_t userId,
177     std::set<PreInstallBundleInfo> &preInstallBundleInfos)
178 {
179     auto dataMgr = GetDataMgrFromService();
180     if (dataMgr == nullptr) {
181         APP_LOGE("DataMgr is nullptr");
182         return false;
183     }
184 
185     bool isStartUser = userId == Constants::START_USERID;
186     std::vector<PreInstallBundleInfo> allPreInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
187     // Scan preset applications and parse package information.
188     for (auto &preInfo : allPreInstallBundleInfos) {
189         InnerBundleInfo innerBundleInfo;
190         if (dataMgr->FetchInnerBundleInfo(preInfo.GetBundleName(), innerBundleInfo)
191             && innerBundleInfo.IsSingleton()) {
192             APP_LOGI("BundleName is IsSingleton %{public}s", preInfo.GetBundleName().c_str());
193             continue;
194         }
195         if (std::find(disallowList.begin(), disallowList.end(),
196             preInfo.GetBundleName()) != disallowList.end()) {
197             APP_LOGI("BundleName is same as black list %{public}s", preInfo.GetBundleName().c_str());
198             continue;
199         }
200         if (isStartUser) {
201             preInfo.CalculateHapTotalSize();
202         }
203         preInstallBundleInfos.insert(preInfo);
204     }
205 
206     return !preInstallBundleInfos.empty();
207 }
208 
AfterCreateNewUser(int32_t userId)209 void BundleUserMgrHostImpl::AfterCreateNewUser(int32_t userId)
210 {
211     if (userId == Constants::START_USERID) {
212         DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
213         // need process main bundle status
214         BmsKeyEventMgr::ProcessMainBundleStatusFinally();
215     }
216 
217 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
218     DefaultAppMgr::GetInstance().HandleCreateUser(userId);
219 #endif
220     HandleSceneBoard(userId);
221     RdbDataManager::ClearCache();
222 }
223 
RemoveUser(int32_t userId)224 ErrCode BundleUserMgrHostImpl::RemoveUser(int32_t userId)
225 {
226     HITRACE_METER(HITRACE_TAG_APP);
227     EventReport::SendUserSysEvent(UserEventType::REMOVE_START, userId);
228     EventReport::SendCpuSceneEvent(ACCESSTOKEN_PROCESS_NAME, 1 << 1); // second scene
229     APP_LOGI("RemoveUser user(%{public}d) start", userId);
230     std::lock_guard<std::mutex> lock(bundleUserMgrMutex_);
231     auto dataMgr = GetDataMgrFromService();
232     if (dataMgr == nullptr) {
233         APP_LOGE("DataMgr is nullptr");
234         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
235     }
236 
237     auto installer = GetBundleInstaller();
238     if (installer == nullptr) {
239         APP_LOGE("installer is nullptr");
240         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
241     }
242 
243     if (!dataMgr->HasUserId(userId)) {
244         APP_LOGE("Has remove user %{public}d", userId);
245         return ERR_APPEXECFWK_USER_NOT_EXIST;
246     }
247 
248     std::vector<BundleInfo> bundleInfos;
249     if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, userId)) {
250         APP_LOGE("get all bundle info failed when userId %{public}d", userId);
251         RemoveArkProfile(userId);
252         RemoveAsanLogDirectory(userId);
253         dataMgr->RemoveUserId(userId);
254         dataMgr->RemoveAppInstallDir(userId);
255         return ERR_OK;
256     }
257 
258     ClearBundleEvents();
259     InnerUninstallBundle(userId, bundleInfos);
260     RemoveArkProfile(userId);
261     RemoveAsanLogDirectory(userId);
262     dataMgr->RemoveUserId(userId);
263     dataMgr->RemoveAppInstallDir(userId);
264 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
265     DefaultAppMgr::GetInstance().HandleRemoveUser(userId);
266 #endif
267     EventReport::SendUserSysEvent(UserEventType::REMOVE_END, userId);
268     HandleNotifyBundleEventsAsync();
269     APP_LOGI("RemoveUser end userId: (%{public}d)", userId);
270     return ERR_OK;
271 }
272 
RemoveArkProfile(int32_t userId)273 void BundleUserMgrHostImpl::RemoveArkProfile(int32_t userId)
274 {
275     std::string arkProfilePath;
276     arkProfilePath.append(ARK_PROFILE_PATH).append(std::to_string(userId));
277     APP_LOGI("DeleteArkProfile %{public}s when remove user", arkProfilePath.c_str());
278     InstalldClient::GetInstance()->RemoveDir(arkProfilePath);
279 }
280 
RemoveAsanLogDirectory(int32_t userId)281 void BundleUserMgrHostImpl::RemoveAsanLogDirectory(int32_t userId)
282 {
283     std::string asanLogDir = ServiceConstants::BUNDLE_ASAN_LOG_DIR + ServiceConstants::PATH_SEPARATOR
284         + std::to_string(userId);
285     APP_LOGI("remove asan log directory %{public}s when remove user", asanLogDir.c_str());
286     InstalldClient::GetInstance()->RemoveDir(asanLogDir);
287 }
288 
CheckInitialUser()289 ErrCode BundleUserMgrHostImpl::CheckInitialUser()
290 {
291     auto dataMgr = GetDataMgrFromService();
292     if (dataMgr == nullptr) {
293         APP_LOGE("DataMgr is nullptr");
294         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
295     }
296 
297     if (!dataMgr->HasInitialUserCreated()) {
298         APP_LOGI("Bms initial user do not created successfully and wait");
299         std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
300         dataMgr->SetBundlePromise(bundlePromise);
301         bundlePromise->WaitForAllTasksExecute();
302         APP_LOGI("Bms initial user created successfully");
303     }
304     return ERR_OK;
305 }
306 
GetDataMgrFromService()307 const std::shared_ptr<BundleDataMgr> BundleUserMgrHostImpl::GetDataMgrFromService()
308 {
309     return DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
310 }
311 
GetBundleInstaller()312 const sptr<IBundleInstaller> BundleUserMgrHostImpl::GetBundleInstaller()
313 {
314     return DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
315 }
316 
InnerUninstallBundle(int32_t userId,const std::vector<BundleInfo> & bundleInfos)317 void BundleUserMgrHostImpl::InnerUninstallBundle(
318     int32_t userId,
319     const std::vector<BundleInfo> &bundleInfos)
320 {
321     APP_LOGI("InnerUninstallBundle for userId: %{public}d start", userId);
322     auto installer = GetBundleInstaller();
323     if (installer == nullptr) {
324         APP_LOGE("InnerUninstallBundle installer is nullptr");
325         return;
326     }
327     std::string identity = IPCSkeleton::ResetCallingIdentity();
328     g_installedHapNum = 0;
329     std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
330     int32_t totalHapNum = static_cast<int32_t>(bundleInfos.size());
331     for (const auto &info : bundleInfos) {
332         InstallParam installParam;
333         installParam.userId = userId;
334         installParam.SetForceExecuted(true);
335         installParam.concentrateSendEvent = true;
336         installParam.isPreInstallApp = info.isPreInstallApp;
337         installParam.installFlag = InstallFlag::NORMAL;
338         installParam.isRemoveUser = true;
339         sptr<UserReceiverImpl> userReceiverImpl(
340             new (std::nothrow) UserReceiverImpl(info.name, false));
341         userReceiverImpl->SetBundlePromise(bundlePromise);
342         userReceiverImpl->SetTotalHapNum(totalHapNum);
343         installer->Uninstall(info.name, installParam, userReceiverImpl);
344     }
345     if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
346         bundlePromise->WaitForAllTasksExecute();
347     }
348     IPCSkeleton::SetCallingIdentity(identity);
349     APP_LOGI("InnerUninstallBundle for userId: %{public}d end", userId);
350 }
351 
ClearBundleEvents()352 void BundleUserMgrHostImpl::ClearBundleEvents()
353 {
354     std::lock_guard<std::mutex> uninstallEventLock(bundleEventMutex_);
355     bundleEvents_.clear();
356 }
357 
AddNotifyBundleEvents(const NotifyBundleEvents & notifyBundleEvents)358 void BundleUserMgrHostImpl::AddNotifyBundleEvents(const NotifyBundleEvents &notifyBundleEvents)
359 {
360     std::lock_guard<std::mutex> lock(bundleEventMutex_);
361     bundleEvents_.emplace_back(notifyBundleEvents);
362 }
363 
HandleNotifyBundleEventsAsync()364 void BundleUserMgrHostImpl::HandleNotifyBundleEventsAsync()
365 {
366     auto task = [this] {
367         HandleNotifyBundleEvents();
368     };
369     std::thread taskThread(task);
370     taskThread.detach();
371 }
372 
HandleNotifyBundleEvents()373 void BundleUserMgrHostImpl::HandleNotifyBundleEvents()
374 {
375     APP_LOGI("HandleNotifyBundleEvents");
376     std::lock_guard<std::mutex> lock(bundleEventMutex_);
377     auto dataMgr = GetDataMgrFromService();
378     if (dataMgr == nullptr) {
379         APP_LOGE("DataMgr is nullptr");
380         return;
381     }
382 
383     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
384     for (size_t i = 0; i < bundleEvents_.size(); ++i) {
385         commonEventMgr->NotifyBundleStatus(bundleEvents_[i], dataMgr);
386         if ((i != 0) && (i % FACTOR == 0)) {
387             std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL));
388         }
389     }
390 
391     bundleEvents_.clear();
392 }
393 
HandleSceneBoard(int32_t userId) const394 void BundleUserMgrHostImpl::HandleSceneBoard(int32_t userId) const
395 {
396 #ifdef WINDOW_ENABLE
397     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
398     if (dataMgr == nullptr) {
399         APP_LOGE("dataMgr is null");
400         return;
401     }
402     bool sceneBoardEnable = Rosen::SceneBoardJudgement::IsSceneBoardEnabled();
403     APP_LOGI("userId : %{public}d, sceneBoardEnable : %{public}d", userId, sceneBoardEnable);
404     dataMgr->SetApplicationEnabled(Constants::SCENE_BOARD_BUNDLE_NAME, 0, sceneBoardEnable,
405         ServiceConstants::CALLER_NAME_BMS, userId);
406     dataMgr->SetApplicationEnabled(ServiceConstants::LAUNCHER_BUNDLE_NAME, 0, !sceneBoardEnable,
407         ServiceConstants::CALLER_NAME_BMS, userId);
408 #endif
409 }
410 
UninstallBackupUninstallList(int32_t userId)411 void BundleUserMgrHostImpl::UninstallBackupUninstallList(int32_t userId)
412 {
413     BmsExtensionDataMgr bmsExtensionDataMgr;
414     std::set<std::string> uninstallList;
415     bmsExtensionDataMgr.GetBackupUninstallList(userId, uninstallList);
416     if (uninstallList.empty()) {
417         APP_LOGI("userId : %{public}d, back uninstall list is empty", userId);
418         return;
419     }
420     auto installer = GetBundleInstaller();
421     if (installer == nullptr) {
422         APP_LOGE("installer is nullptr");
423         return;
424     }
425 
426     std::string identity = IPCSkeleton::ResetCallingIdentity();
427     g_installedHapNum = 0;
428     std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
429     int32_t totalHapNum = static_cast<int32_t>(uninstallList.size());
430     for (const auto &bundleName : uninstallList) {
431         InstallParam installParam;
432         installParam.userId = userId;
433         installParam.needSendEvent = false;
434         installParam.isPreInstallApp = true;
435         sptr<UserReceiverImpl> userReceiverImpl(
436             new (std::nothrow) UserReceiverImpl(bundleName, false));
437         userReceiverImpl->SetBundlePromise(bundlePromise);
438         userReceiverImpl->SetTotalHapNum(totalHapNum);
439         installer->Uninstall(bundleName, installParam, userReceiverImpl);
440     }
441     if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
442         bundlePromise->WaitForAllTasksExecute();
443     }
444     IPCSkeleton::SetCallingIdentity(identity);
445     bmsExtensionDataMgr.ClearBackupUninstallFile(userId);
446 }
447 }  // namespace AppExecFwk
448 }  // namespace OHOS
449