• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "app_log_wrapper.h"
19 #include "bundle_mgr_service.h"
20 #include "bundle_mgr_service_event_handler.h"
21 #include "bundle_permission_mgr.h"
22 #include "bundle_promise.h"
23 #include "bundle_util.h"
24 #include "event_report.h"
25 #include "hitrace_meter.h"
26 #include "installd_client.h"
27 #include "rdb_data_manager.h"
28 #include "status_receiver_host.h"
29 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
30 #include "default_app_mgr.h"
31 #endif
32 #ifdef WINDOW_ENABLE
33 #include "scene_board_judgement.h"
34 #endif
35 #include "ipc_skeleton.h"
36 
37 namespace OHOS {
38 namespace AppExecFwk {
39 std::atomic_uint g_installedHapNum = 0;
40 const std::string ARK_PROFILE_PATH = "/data/local/ark-profile/";
41 const uint32_t FACTOR = 8;
42 const uint32_t INTERVAL = 6;
43 constexpr const char* QUICK_FIX_APP_PATH = "/data/update/quickfix/app/temp/keepalive";
44 
45 class UserReceiverImpl : public StatusReceiverHost {
46 public:
UserReceiverImpl(const std::string & bundleName,bool needReInstall)47     UserReceiverImpl(const std::string &bundleName, bool needReInstall)
48         : bundleName_(bundleName), needReInstall_(needReInstall) {};
49     virtual ~UserReceiverImpl() override = default;
50 
SetBundlePromise(const std::shared_ptr<BundlePromise> & bundlePromise)51     void SetBundlePromise(const std::shared_ptr<BundlePromise>& bundlePromise)
52     {
53         bundlePromise_ = bundlePromise;
54     }
55 
SetTotalHapNum(int32_t totalHapNum)56     void SetTotalHapNum(int32_t totalHapNum)
57     {
58         totalHapNum_ = totalHapNum;
59     }
60 
SavePreInstallException(const std::string & bundleName)61     void SavePreInstallException(const std::string &bundleName)
62     {
63         auto preInstallExceptionMgr =
64             DelayedSingleton<BundleMgrService>::GetInstance()->GetPreInstallExceptionMgr();
65         if (preInstallExceptionMgr == nullptr) {
66             APP_LOGE("preInstallExceptionMgr is nullptr");
67             return;
68         }
69 
70         preInstallExceptionMgr->SavePreInstallExceptionBundleName(bundleName);
71     }
72 
OnStatusNotify(const int progress)73     virtual void OnStatusNotify(const int progress) override {}
OnFinished(const int32_t resultCode,const std::string & resultMsg)74     virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) override
75     {
76         g_installedHapNum++;
77         APP_LOGI("OnFinished, resultCode : %{public}d, resultMsg : %{public}s, count : %{public}u",
78             resultCode, resultMsg.c_str(), g_installedHapNum.load());
79         if (static_cast<int32_t>(g_installedHapNum) >= totalHapNum_ && bundlePromise_ != nullptr) {
80             bundlePromise_->NotifyAllTasksExecuteFinished();
81         }
82 
83         if (resultCode != ERR_OK && resultCode !=
84             ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON && needReInstall_) {
85             APP_LOGI("needReInstall bundleName: %{public}s", bundleName_.c_str());
86             SavePreInstallException(bundleName_);
87         }
88     }
89 private:
90     std::shared_ptr<BundlePromise> bundlePromise_ = nullptr;
91     int32_t totalHapNum_ = INT32_MAX;
92     std::string bundleName_;
93     bool needReInstall_ = false;
94 };
95 
CreateNewUser(int32_t userId,const std::vector<std::string> & disallowList)96 ErrCode BundleUserMgrHostImpl::CreateNewUser(int32_t userId, const std::vector<std::string> &disallowList)
97 {
98     HITRACE_METER(HITRACE_TAG_APP);
99     EventReport::SendUserSysEvent(UserEventType::CREATE_START, userId);
100     APP_LOGI("CreateNewUser user(%{public}d) start.", userId);
101     std::lock_guard<std::mutex> lock(bundleUserMgrMutex_);
102     if (CheckInitialUser() != ERR_OK) {
103         APP_LOGE("CheckInitialUser failed");
104         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
105     }
106     BeforeCreateNewUser(userId);
107     OnCreateNewUser(userId, disallowList);
108     AfterCreateNewUser(userId);
109     EventReport::SendUserSysEvent(UserEventType::CREATE_END, userId);
110     APP_LOGI("CreateNewUser end userId: (%{public}d)", userId);
111     return ERR_OK;
112 }
113 
BeforeCreateNewUser(int32_t userId)114 void BundleUserMgrHostImpl::BeforeCreateNewUser(int32_t userId)
115 {
116     ClearBundleEvents();
117 }
118 
OnCreateNewUser(int32_t userId,const std::vector<std::string> & disallowList)119 void BundleUserMgrHostImpl::OnCreateNewUser(int32_t userId, const std::vector<std::string> &disallowList)
120 {
121     auto dataMgr = GetDataMgrFromService();
122     if (dataMgr == nullptr) {
123         APP_LOGE("DataMgr is nullptr");
124         return;
125     }
126 
127     auto installer = GetBundleInstaller();
128     if (installer == nullptr) {
129         APP_LOGE("installer is nullptr");
130         return;
131     }
132 
133     if (dataMgr->HasUserId(userId)) {
134         APP_LOGE("Has create user %{public}d.", userId);
135         return;
136     }
137 
138     dataMgr->AddUserId(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.concentrateSendEvent = true;
156         installParam.installFlag = InstallFlag::NORMAL;
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     HandleNotifyBundleEventsAsync();
173 }
174 
GetAllPreInstallBundleInfos(const std::vector<std::string> & disallowList,int32_t userId,std::set<PreInstallBundleInfo> & preInstallBundleInfos)175 bool BundleUserMgrHostImpl::GetAllPreInstallBundleInfos(
176     const std::vector<std::string> &disallowList,
177     int32_t userId,
178     std::set<PreInstallBundleInfo> &preInstallBundleInfos)
179 {
180     auto dataMgr = GetDataMgrFromService();
181     if (dataMgr == nullptr) {
182         APP_LOGE("DataMgr is nullptr");
183         return false;
184     }
185 
186     bool isStartUser = userId == Constants::START_USERID;
187     std::vector<PreInstallBundleInfo> allPreInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
188     // Scan preset applications and parse package information.
189     for (auto &preInfo : allPreInstallBundleInfos) {
190         InnerBundleInfo innerBundleInfo;
191         if (dataMgr->FetchInnerBundleInfo(preInfo.GetBundleName(), innerBundleInfo)
192             && innerBundleInfo.IsSingleton()) {
193             APP_LOGI("BundleName is IsSingleton %{public}s", preInfo.GetBundleName().c_str());
194             continue;
195         }
196         if (std::find(disallowList.begin(), disallowList.end(),
197             preInfo.GetBundleName()) != disallowList.end()) {
198             APP_LOGI("BundleName is same as black list %{public}s", preInfo.GetBundleName().c_str());
199             continue;
200         }
201         if (isStartUser) {
202             preInfo.CalculateHapTotalSize();
203         }
204         preInstallBundleInfos.insert(preInfo);
205     }
206 
207     return !preInstallBundleInfos.empty();
208 }
209 
AfterCreateNewUser(int32_t userId)210 void BundleUserMgrHostImpl::AfterCreateNewUser(int32_t userId)
211 {
212     if (userId == Constants::START_USERID) {
213         DelayedSingleton<BundleMgrService>::GetInstance()->NotifyBundleScanStatus();
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     APP_LOGI("RemoveUser user(%{public}d) start.", userId);
228     std::lock_guard<std::mutex> lock(bundleUserMgrMutex_);
229     auto dataMgr = GetDataMgrFromService();
230     if (dataMgr == nullptr) {
231         APP_LOGE("DataMgr is nullptr");
232         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
233     }
234 
235     auto installer = GetBundleInstaller();
236     if (installer == nullptr) {
237         APP_LOGE("installer is nullptr");
238         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
239     }
240 
241     if (!dataMgr->HasUserId(userId)) {
242         APP_LOGE("Has remove user %{public}d.", userId);
243         return ERR_APPEXECFWK_USER_NOT_EXIST;
244     }
245 
246     std::vector<BundleInfo> bundleInfos;
247     if (!dataMgr->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, userId)) {
248         APP_LOGE("get all bundle info failed when userId is %{public}d.", userId);
249         RemoveArkProfile(userId);
250         RemoveAsanLogDirectory(userId);
251         dataMgr->RemoveUserId(userId);
252         return ERR_OK;
253     }
254 
255     ClearBundleEvents();
256     InnerUninstallBundle(userId, bundleInfos);
257     RemoveArkProfile(userId);
258     RemoveAsanLogDirectory(userId);
259     dataMgr->RemoveUserId(userId);
260 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
261     DefaultAppMgr::GetInstance().HandleRemoveUser(userId);
262 #endif
263     EventReport::SendUserSysEvent(UserEventType::REMOVE_END, userId);
264     HandleNotifyBundleEventsAsync();
265     APP_LOGI("RemoveUser end userId: (%{public}d)", userId);
266     return ERR_OK;
267 }
268 
RemoveArkProfile(int32_t userId)269 void BundleUserMgrHostImpl::RemoveArkProfile(int32_t userId)
270 {
271     std::string arkProfilePath;
272     arkProfilePath.append(ARK_PROFILE_PATH).append(std::to_string(userId));
273     APP_LOGI("DeleteArkProfile %{public}s when remove user", arkProfilePath.c_str());
274     InstalldClient::GetInstance()->RemoveDir(arkProfilePath);
275 }
276 
RemoveAsanLogDirectory(int32_t userId)277 void BundleUserMgrHostImpl::RemoveAsanLogDirectory(int32_t userId)
278 {
279     std::string asanLogDir = Constants::BUNDLE_ASAN_LOG_DIR + Constants::PATH_SEPARATOR
280         + std::to_string(userId);
281     APP_LOGI("remove asan log directory %{public}s when remove user", asanLogDir.c_str());
282     InstalldClient::GetInstance()->RemoveDir(asanLogDir);
283 }
284 
CheckInitialUser()285 ErrCode BundleUserMgrHostImpl::CheckInitialUser()
286 {
287     auto dataMgr = GetDataMgrFromService();
288     if (dataMgr == nullptr) {
289         APP_LOGE("DataMgr is nullptr");
290         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
291     }
292 
293     if (!dataMgr->HasInitialUserCreated()) {
294         APP_LOGI("Bms initial user do not created successfully and wait.");
295         std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
296         dataMgr->SetBundlePromise(bundlePromise);
297         bundlePromise->WaitForAllTasksExecute();
298         APP_LOGI("Bms initial user created successfully.");
299     }
300     return ERR_OK;
301 }
302 
GetDataMgrFromService()303 const std::shared_ptr<BundleDataMgr> BundleUserMgrHostImpl::GetDataMgrFromService()
304 {
305     return DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
306 }
307 
GetBundleInstaller()308 const sptr<IBundleInstaller> BundleUserMgrHostImpl::GetBundleInstaller()
309 {
310     return DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
311 }
312 
InnerUninstallBundle(int32_t userId,const std::vector<BundleInfo> & bundleInfos)313 void BundleUserMgrHostImpl::InnerUninstallBundle(
314     int32_t userId,
315     const std::vector<BundleInfo> &bundleInfos)
316 {
317     APP_LOGI("InnerUninstallBundle for userId: %{public}d start", userId);
318     auto installer = GetBundleInstaller();
319     if (installer == nullptr) {
320         APP_LOGE("InnerUninstallBundle installer is nullptr");
321         return;
322     }
323     std::string identity = IPCSkeleton::ResetCallingIdentity();
324     g_installedHapNum = 0;
325     std::shared_ptr<BundlePromise> bundlePromise = std::make_shared<BundlePromise>();
326     int32_t totalHapNum = static_cast<int32_t>(bundleInfos.size());
327     for (const auto &info : bundleInfos) {
328         InstallParam installParam;
329         installParam.userId = userId;
330         installParam.forceExecuted = true;
331         installParam.concentrateSendEvent = true;
332         installParam.isPreInstallApp = info.isPreInstallApp;
333         installParam.installFlag = InstallFlag::NORMAL;
334         sptr<UserReceiverImpl> userReceiverImpl(
335             new (std::nothrow) UserReceiverImpl(info.name, false));
336         userReceiverImpl->SetBundlePromise(bundlePromise);
337         userReceiverImpl->SetTotalHapNum(totalHapNum);
338         installer->Uninstall(info.name, installParam, userReceiverImpl);
339     }
340     if (static_cast<int32_t>(g_installedHapNum) < totalHapNum) {
341         bundlePromise->WaitForAllTasksExecute();
342     }
343     IPCSkeleton::SetCallingIdentity(identity);
344     APP_LOGI("InnerUninstallBundle for userId: %{public}d end", userId);
345 }
346 
ClearBundleEvents()347 void BundleUserMgrHostImpl::ClearBundleEvents()
348 {
349     std::lock_guard<std::mutex> uninstallEventLock(bundleEventMutex_);
350     bundleEvents_.clear();
351 }
352 
AddNotifyBundleEvents(const NotifyBundleEvents & notifyBundleEvents)353 void BundleUserMgrHostImpl::AddNotifyBundleEvents(const NotifyBundleEvents &notifyBundleEvents)
354 {
355     std::lock_guard<std::mutex> lock(bundleEventMutex_);
356     bundleEvents_.emplace_back(notifyBundleEvents);
357 }
358 
HandleNotifyBundleEventsAsync()359 void BundleUserMgrHostImpl::HandleNotifyBundleEventsAsync()
360 {
361     auto task = [this] {
362         HandleNotifyBundleEvents();
363     };
364     std::thread taskThread(task);
365     taskThread.detach();
366 }
367 
HandleNotifyBundleEvents()368 void BundleUserMgrHostImpl::HandleNotifyBundleEvents()
369 {
370     APP_LOGI("HandleNotifyBundleEvents");
371     std::lock_guard<std::mutex> lock(bundleEventMutex_);
372     auto dataMgr = GetDataMgrFromService();
373     if (dataMgr == nullptr) {
374         APP_LOGE("DataMgr is nullptr");
375         return;
376     }
377 
378     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
379     for (size_t i = 0; i < bundleEvents_.size(); ++i) {
380         commonEventMgr->NotifyBundleStatus(bundleEvents_[i], dataMgr);
381         if ((i != 0) && (i % FACTOR == 0)) {
382             std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL));
383         }
384     }
385 
386     bundleEvents_.clear();
387 }
388 
HandleSceneBoard(int32_t userId) const389 void BundleUserMgrHostImpl::HandleSceneBoard(int32_t userId) const
390 {
391 #ifdef WINDOW_ENABLE
392     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
393     if (dataMgr == nullptr) {
394         APP_LOGE("dataMgr is null");
395         return;
396     }
397     bool sceneBoardEnable = Rosen::SceneBoardJudgement::IsSceneBoardEnabled();
398     APP_LOGI("userId : %{public}d, sceneBoardEnable : %{public}d", userId, sceneBoardEnable);
399     dataMgr->SetApplicationEnabled(Constants::SCENE_BOARD_BUNDLE_NAME, sceneBoardEnable, userId);
400     dataMgr->SetApplicationEnabled(Constants::LAUNCHER_BUNDLE_NAME, !sceneBoardEnable, userId);
401 #endif
402 }
403 }  // namespace AppExecFwk
404 }  // namespace OHOS
405