• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "bundle_data_mgr.h"
17 
18 #include <algorithm>
19 #include <chrono>
20 #include <cinttypes>
21 
22 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
23 #ifdef ACCOUNT_ENABLE
24 #include "os_account_info.h"
25 #endif
26 #endif
27 #include "account_helper.h"
28 #include "app_log_wrapper.h"
29 #include "app_provision_info_manager.h"
30 #include "bms_extension_data_mgr.h"
31 #include "bundle_constants.h"
32 #include "bundle_data_storage_rdb.h"
33 #include "preinstall_data_storage_rdb.h"
34 #include "bundle_event_callback_death_recipient.h"
35 #include "bundle_mgr_service.h"
36 #include "bundle_permission_mgr.h"
37 #include "bundle_status_callback_death_recipient.h"
38 #include "bundle_util.h"
39 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
40 #include "default_app_mgr.h"
41 #endif
42 #include "installd_client.h"
43 #include "ipc_skeleton.h"
44 #include "json_serializer.h"
45 #ifdef GLOBAL_I18_ENABLE
46 #include "locale_info.h"
47 #endif
48 #include "mime_type_mgr.h"
49 #include "nlohmann/json.hpp"
50 #include "free_install_params.h"
51 #include "parameters.h"
52 #include "singleton.h"
53 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
54 #include "bundle_overlay_data_manager.h"
55 #endif
56 
57 namespace OHOS {
58 namespace AppExecFwk {
59 namespace {
60 constexpr int MAX_EVENT_CALL_BACK_SIZE = 100;
61 constexpr int32_t DATA_GROUP_INDEX_START = 1;
62 constexpr int32_t UUID_LENGTH = 36;
63 constexpr const char* GLOBAL_RESOURCE_BUNDLE_NAME = "ohos.global.systemres";
64 // freeInstall action
65 constexpr const char* FREE_INSTALL_ACTION = "ohos.want.action.hapFreeInstall";
66 // data share
67 constexpr const char* DATA_PROXY_URI_PREFIX = "datashareproxy://";
68 constexpr int32_t DATA_PROXY_URI_PREFIX_LEN = 17;
69 }
70 
BundleDataMgr()71 BundleDataMgr::BundleDataMgr()
72 {
73     InitStateTransferMap();
74     dataStorage_ = std::make_shared<BundleDataStorageRdb>();
75     preInstallDataStorage_ = std::make_shared<PreInstallDataStorageRdb>();
76     sandboxAppHelper_ = DelayedSingleton<BundleSandboxAppHelper>::GetInstance();
77     bundleStateStorage_ = std::make_shared<BundleStateStorage>();
78     baseAppUid_ = system::GetIntParameter<int32_t>("const.product.baseappid", Constants::BASE_APP_UID);
79     if (baseAppUid_ < Constants::BASE_APP_UID || baseAppUid_ >= Constants::MAX_APP_UID) {
80         baseAppUid_ = Constants::BASE_APP_UID;
81     }
82     APP_LOGI("BundleDataMgr instance is created");
83 }
84 
~BundleDataMgr()85 BundleDataMgr::~BundleDataMgr()
86 {
87     APP_LOGI("BundleDataMgr instance is destroyed");
88     installStates_.clear();
89     transferStates_.clear();
90     bundleInfos_.clear();
91 }
92 
LoadDataFromPersistentStorage()93 bool BundleDataMgr::LoadDataFromPersistentStorage()
94 {
95     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
96     // Judge whether bundleState json db exists.
97     // If it does not exist, create it and return the judgment result.
98     bool bundleStateDbExist = bundleStateStorage_->HasBundleUserInfoJsonDb();
99     if (!dataStorage_->LoadAllData(bundleInfos_)) {
100         APP_LOGE("LoadAllData failed");
101         return false;
102     }
103 
104     if (bundleInfos_.empty()) {
105         APP_LOGW("persistent data is empty");
106         return false;
107     }
108 
109     for (const auto &item : bundleInfos_) {
110         std::lock_guard<std::mutex> stateLock(stateMutex_);
111         installStates_.emplace(item.first, InstallState::INSTALL_SUCCESS);
112     }
113 
114     RestoreUidAndGid();
115     if (!bundleStateDbExist) {
116         // Compatible old bundle status in kV db
117         CompatibleOldBundleStateInKvDb();
118     } else {
119         ResetBundleStateData();
120         // Load all bundle status from json db.
121         LoadAllBundleStateDataFromJsonDb();
122     }
123 
124     SetInitialUserFlag(true);
125 
126     RestoreSandboxUidAndGid(bundleIdMap_);
127     return true;
128 }
129 
CompatibleOldBundleStateInKvDb()130 void BundleDataMgr::CompatibleOldBundleStateInKvDb()
131 {
132     for (auto& bundleInfoItem : bundleInfos_) {
133         for (auto& innerBundleUserInfoItem : bundleInfoItem.second.GetInnerBundleUserInfos()) {
134             auto& bundleUserInfo = innerBundleUserInfoItem.second.bundleUserInfo;
135             if (bundleUserInfo.IsInitialState()) {
136                 continue;
137             }
138 
139             // save old bundle state to json db
140             bundleStateStorage_->SaveBundleStateStorage(
141                 bundleInfoItem.first, bundleUserInfo.userId, bundleUserInfo);
142         }
143     }
144 }
145 
LoadAllBundleStateDataFromJsonDb()146 void BundleDataMgr::LoadAllBundleStateDataFromJsonDb()
147 {
148     APP_LOGD("Load all bundle state start");
149     std::map<std::string, std::map<int32_t, BundleUserInfo>> bundleStateInfos;
150     if (!bundleStateStorage_->LoadAllBundleStateData(bundleStateInfos) || bundleStateInfos.empty()) {
151         APP_LOGE("Load all bundle state failed");
152         return;
153     }
154 
155     for (auto& bundleState : bundleStateInfos) {
156         auto infoItem = bundleInfos_.find(bundleState.first);
157         if (infoItem == bundleInfos_.end()) {
158             APP_LOGE("BundleName(%{public}s) not exist in cache", bundleState.first.c_str());
159             continue;
160         }
161 
162         InnerBundleInfo& newInfo = infoItem->second;
163         for (auto& bundleUserState : bundleState.second) {
164             auto& tempUserInfo = bundleUserState.second;
165             newInfo.SetApplicationEnabled(tempUserInfo.enabled, bundleUserState.first);
166             for (auto& disabledAbility : tempUserInfo.disabledAbilities) {
167                 newInfo.SetAbilityEnabled("", disabledAbility, false, bundleUserState.first);
168             }
169         }
170     }
171 
172     APP_LOGD("Load all bundle state end");
173 }
174 
ResetBundleStateData()175 void BundleDataMgr::ResetBundleStateData()
176 {
177     for (auto& bundleInfoItem : bundleInfos_) {
178         bundleInfoItem.second.ResetBundleState(Constants::ALL_USERID);
179     }
180 }
181 
UpdateBundleInstallState(const std::string & bundleName,const InstallState state)182 bool BundleDataMgr::UpdateBundleInstallState(const std::string &bundleName, const InstallState state)
183 {
184     if (bundleName.empty()) {
185         APP_LOGW("update result:fail, reason:bundle name is empty");
186         return false;
187     }
188 
189     // always keep lock bundleInfoMutex_ before locking stateMutex_ to avoid deadlock
190     std::lock_guard<std::mutex> lck(bundleInfoMutex_);
191     std::lock_guard<std::mutex> lock(stateMutex_);
192     auto item = installStates_.find(bundleName);
193     if (item == installStates_.end()) {
194         if (state == InstallState::INSTALL_START) {
195             installStates_.emplace(bundleName, state);
196             APP_LOGD("update result:success, state:INSTALL_START");
197             return true;
198         }
199         APP_LOGW("update result:fail, reason:incorrect state, bundleName: %{public}s", bundleName.c_str());
200         return false;
201     }
202 
203     auto stateRange = transferStates_.equal_range(state);
204     for (auto previousState = stateRange.first; previousState != stateRange.second; ++previousState) {
205         if (item->second == previousState->second) {
206             APP_LOGD("update result:success, current:%{public}d, state:%{public}d", previousState->second, state);
207             if (IsDeleteDataState(state)) {
208                 installStates_.erase(item);
209                 DeleteBundleInfo(bundleName, state);
210                 return true;
211             }
212             item->second = state;
213             return true;
214         }
215     }
216     APP_LOGW("bundleName: %{public}s, update result:fail, reason:incorrect current:%{public}d, state:%{public}d",
217         bundleName.c_str(), item->second, state);
218     return false;
219 }
220 
AddInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & info)221 bool BundleDataMgr::AddInnerBundleInfo(const std::string &bundleName, InnerBundleInfo &info)
222 {
223     APP_LOGD("to save info:%{public}s", info.GetBundleName().c_str());
224     if (bundleName.empty()) {
225         APP_LOGW("save info fail, empty bundle name");
226         return false;
227     }
228 
229     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
230     auto infoItem = bundleInfos_.find(bundleName);
231     if (infoItem != bundleInfos_.end()) {
232         APP_LOGE("bundleName: %{public}s : bundle info already exist", bundleName.c_str());
233         return false;
234     }
235     std::lock_guard<std::mutex> stateLock(stateMutex_);
236     auto statusItem = installStates_.find(bundleName);
237     if (statusItem == installStates_.end()) {
238         APP_LOGE("save info fail, bundleName:%{public}s is not installed", bundleName.c_str());
239         return false;
240     }
241     if (statusItem->second == InstallState::INSTALL_START) {
242         APP_LOGD("save bundle:%{public}s info", bundleName.c_str());
243         if (info.GetBaseApplicationInfo().needAppDetail) {
244             AddAppDetailAbilityInfo(info);
245         }
246 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
247         if (info.GetOverlayType() == OVERLAY_EXTERNAL_BUNDLE) {
248             InnerBundleInfo newInfo = info;
249             std::string targetBundleName = newInfo.GetTargetBundleName();
250             auto targetInfoItem = bundleInfos_.find(targetBundleName);
251             if (targetInfoItem != bundleInfos_.end()) {
252                 OverlayDataMgr::GetInstance()->UpdateExternalOverlayInfo(newInfo, info, targetInfoItem->second);
253                 // storage target bundle info
254                 dataStorage_->SaveStorageBundleInfo(targetInfoItem->second);
255             }
256         }
257         if (info.GetOverlayType() == OVERLAY_INTERNAL_BUNDLE) {
258             info.SetOverlayModuleState(info.GetCurrentModulePackage(), OverlayState::OVERLAY_INVALID,
259                 info.GetUserId());
260         }
261         if (info.GetOverlayType() == NON_OVERLAY_TYPE) {
262             // build overlay connection for external overlay
263             BuildExternalOverlayConnection(info.GetCurrentModulePackage(), info, info.GetUserId());
264         }
265 #endif
266         if (dataStorage_->SaveStorageBundleInfo(info)) {
267             APP_LOGI("write storage success bundle:%{public}s", bundleName.c_str());
268             bundleInfos_.emplace(bundleName, info);
269             return true;
270         }
271     }
272     return false;
273 }
274 
AddNewModuleInfo(const std::string & bundleName,const InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo)275 bool BundleDataMgr::AddNewModuleInfo(
276     const std::string &bundleName, const InnerBundleInfo &newInfo, InnerBundleInfo &oldInfo)
277 {
278     APP_LOGD("add new module info module name %{public}s ", newInfo.GetCurrentModulePackage().c_str());
279     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
280     auto infoItem = bundleInfos_.find(bundleName);
281     if (infoItem == bundleInfos_.end()) {
282         APP_LOGE("bundleName: %{public}s : bundle info not exist", bundleName.c_str());
283         return false;
284     }
285     std::lock_guard<std::mutex> stateLock(stateMutex_);
286     auto statusItem = installStates_.find(bundleName);
287     if (statusItem == installStates_.end()) {
288         APP_LOGE("save info fail, app:%{public}s is not updated", bundleName.c_str());
289         return false;
290     }
291     if (statusItem->second == InstallState::UPDATING_SUCCESS) {
292         APP_LOGD("save bundle:%{public}s info", bundleName.c_str());
293         if (!oldInfo.HasEntry() || oldInfo.GetEntryInstallationFree() || newInfo.HasEntry()) {
294             oldInfo.UpdateBaseBundleInfo(newInfo.GetBaseBundleInfo(), newInfo.HasEntry());
295             oldInfo.UpdateBaseApplicationInfo(newInfo.GetBaseApplicationInfo());
296             oldInfo.UpdateRemovable(
297                 newInfo.IsPreInstallApp(), newInfo.IsRemovable());
298         }
299         oldInfo.SetCertificateFingerprint(newInfo.GetCertificateFingerprint());
300         oldInfo.SetAppPrivilegeLevel(newInfo.GetAppPrivilegeLevel());
301         oldInfo.SetAllowedAcls(newInfo.GetAllowedAcls());
302         oldInfo.UpdateNativeLibAttrs(newInfo.GetBaseApplicationInfo());
303         oldInfo.UpdateArkNativeAttrs(newInfo.GetBaseApplicationInfo());
304         oldInfo.SetAsanLogPath(newInfo.GetAsanLogPath());
305         oldInfo.SetAsanEnabled(newInfo.GetAsanEnabled());
306         oldInfo.SetBundlePackInfo(newInfo.GetBundlePackInfo());
307         oldInfo.AddModuleInfo(newInfo);
308         oldInfo.UpdateAppDetailAbilityAttrs();
309         oldInfo.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
310         oldInfo.SetIsNewVersion(newInfo.GetIsNewVersion());
311 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
312         if ((oldInfo.GetOverlayType() == NON_OVERLAY_TYPE) && (newInfo.GetOverlayType() != NON_OVERLAY_TYPE)) {
313             oldInfo.SetOverlayType(newInfo.GetOverlayType());
314         }
315 
316         if (!UpdateOverlayInfo(newInfo, oldInfo)) {
317             APP_LOGE("bundleName: %{public}s : update overlay info failed", bundleName.c_str());
318             return false;
319         }
320 #endif
321         if (dataStorage_->SaveStorageBundleInfo(oldInfo)) {
322             APP_LOGI("update storage success bundle:%{public}s", bundleName.c_str());
323             bundleInfos_.at(bundleName) = oldInfo;
324             return true;
325         }
326     }
327     return false;
328 }
329 
RemoveModuleInfo(const std::string & bundleName,const std::string & modulePackage,InnerBundleInfo & oldInfo)330 bool BundleDataMgr::RemoveModuleInfo(
331     const std::string &bundleName, const std::string &modulePackage, InnerBundleInfo &oldInfo)
332 {
333     APP_LOGD("remove module info:%{public}s/%{public}s", bundleName.c_str(), modulePackage.c_str());
334     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
335     auto infoItem = bundleInfos_.find(bundleName);
336     if (infoItem == bundleInfos_.end()) {
337         APP_LOGE("bundleName: %{public}s bundle info not exist", bundleName.c_str());
338         return false;
339     }
340     std::lock_guard<std::mutex> stateLock(stateMutex_);
341     auto statusItem = installStates_.find(bundleName);
342     if (statusItem == installStates_.end()) {
343         APP_LOGE("save info fail, app:%{public}s is not updated", bundleName.c_str());
344         return false;
345     }
346     if (statusItem->second == InstallState::UNINSTALL_START || statusItem->second == InstallState::ROLL_BACK) {
347         APP_LOGD("save bundle:%{public}s info", bundleName.c_str());
348 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
349         std::string targetBundleName = oldInfo.GetTargetBundleName();
350         InnerBundleInfo targetInnerBundleInfo;
351         if (bundleInfos_.find(targetBundleName) != bundleInfos_.end()) {
352             targetInnerBundleInfo = bundleInfos_.at(targetBundleName);
353         }
354         OverlayDataMgr::GetInstance()->RemoveOverlayModuleInfo(bundleName, modulePackage, oldInfo,
355             targetInnerBundleInfo);
356         if ((oldInfo.GetOverlayType() == OVERLAY_EXTERNAL_BUNDLE) && !targetInnerBundleInfo.GetBundleName().empty()) {
357             // save target innerBundleInfo
358             if (dataStorage_->SaveStorageBundleInfo(targetInnerBundleInfo)) {
359                 APP_LOGI("update storage success bundle:%{public}s", targetBundleName.c_str());
360                 bundleInfos_.at(targetBundleName) = targetInnerBundleInfo;
361             }
362         }
363         // remove target module and overlay module state will change to OVERLAY_INVALID
364         if (oldInfo.GetOverlayType() == NON_OVERLAY_TYPE) {
365             ResetExternalOverlayModuleState(bundleName, modulePackage);
366         }
367 #endif
368         oldInfo.RemoveModuleInfo(modulePackage);
369         oldInfo.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
370         if (!oldInfo.isExistedOverlayModule()) {
371             oldInfo.SetOverlayType(NON_OVERLAY_TYPE);
372         }
373         if (dataStorage_->SaveStorageBundleInfo(oldInfo)) {
374             APP_LOGI("update storage success bundle:%{public}s", bundleName.c_str());
375             bundleInfos_.at(bundleName) = oldInfo;
376             return true;
377         }
378         APP_LOGD("after delete modulePackage:%{public}s info", modulePackage.c_str());
379     }
380     return true;
381 }
382 
RemoveHspModuleByVersionCode(int32_t versionCode,InnerBundleInfo & info)383 bool BundleDataMgr::RemoveHspModuleByVersionCode(int32_t versionCode, InnerBundleInfo &info)
384 {
385     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
386     std::string bundleName = info.GetBundleName();
387     auto infoItem = bundleInfos_.find(bundleName);
388     if (infoItem == bundleInfos_.end()) {
389         APP_LOGE("bundleName: %{public}s bundle info not exist", bundleName.c_str());
390         return false;
391     }
392     std::lock_guard<std::mutex> stateLock(stateMutex_);
393     auto statusItem = installStates_.find(bundleName);
394     if (statusItem == installStates_.end()) {
395         APP_LOGE("save info fail, app:%{public}s is not updated", bundleName.c_str());
396         return false;
397     }
398     if (statusItem->second == InstallState::UNINSTALL_START || statusItem->second == InstallState::ROLL_BACK) {
399         info.DeleteHspModuleByVersion(versionCode);
400         info.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
401         if (dataStorage_->SaveStorageBundleInfo(info)) {
402             APP_LOGI("update storage success bundle:%{public}s", bundleName.c_str());
403             bundleInfos_.at(bundleName) = info;
404             return true;
405         }
406     }
407     return true;
408 }
409 
AddInnerBundleUserInfo(const std::string & bundleName,const InnerBundleUserInfo & newUserInfo)410 bool BundleDataMgr::AddInnerBundleUserInfo(
411     const std::string &bundleName, const InnerBundleUserInfo& newUserInfo)
412 {
413     APP_LOGD("AddInnerBundleUserInfo:%{public}s", bundleName.c_str());
414     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
415     auto infoItem = bundleInfos_.find(bundleName);
416     if (infoItem == bundleInfos_.end()) {
417         APP_LOGE("bundleName: %{public}s bundle info not exist", bundleName.c_str());
418         return false;
419     }
420 
421     std::lock_guard<std::mutex> stateLock(stateMutex_);
422     auto& info = bundleInfos_.at(bundleName);
423     info.AddInnerBundleUserInfo(newUserInfo);
424     info.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
425     if (!dataStorage_->SaveStorageBundleInfo(info)) {
426         APP_LOGE("update storage failed bundle:%{public}s", bundleName.c_str());
427         return false;
428     }
429     return true;
430 }
431 
RemoveInnerBundleUserInfo(const std::string & bundleName,int32_t userId)432 bool BundleDataMgr::RemoveInnerBundleUserInfo(
433     const std::string &bundleName, int32_t userId)
434 {
435     APP_LOGD("RemoveInnerBundleUserInfo:%{public}s", bundleName.c_str());
436     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
437     auto infoItem = bundleInfos_.find(bundleName);
438     if (infoItem == bundleInfos_.end()) {
439         APP_LOGE("bundleName: %{public}s bundle info not exist", bundleName.c_str());
440         return false;
441     }
442 
443     std::lock_guard<std::mutex> stateLock(stateMutex_);
444     auto& info = bundleInfos_.at(bundleName);
445     info.RemoveInnerBundleUserInfo(userId);
446     info.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
447     if (!dataStorage_->SaveStorageBundleInfo(info)) {
448         APP_LOGE("update storage failed bundle:%{public}s", bundleName.c_str());
449         return false;
450     }
451 
452     bundleStateStorage_->DeleteBundleState(bundleName, userId);
453     return true;
454 }
455 
UpdateInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo)456 bool BundleDataMgr::UpdateInnerBundleInfo(
457     const std::string &bundleName, InnerBundleInfo &newInfo, InnerBundleInfo &oldInfo)
458 {
459     APP_LOGD("UpdateInnerBundleInfo:%{public}s", bundleName.c_str());
460     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
461     auto infoItem = bundleInfos_.find(bundleName);
462     if (infoItem == bundleInfos_.end()) {
463         APP_LOGE("bundleName: %{public}s bundle info not exist", bundleName.c_str());
464         return false;
465     }
466     std::lock_guard<std::mutex> stateLock(stateMutex_);
467     auto statusItem = installStates_.find(bundleName);
468     if (statusItem == installStates_.end()) {
469         APP_LOGE("save info fail, app:%{public}s is not updated", bundleName.c_str());
470         return false;
471     }
472     // ROLL_BACK and USER_CHANGE should not be here
473     if (statusItem->second == InstallState::UPDATING_SUCCESS
474         || statusItem->second == InstallState::ROLL_BACK
475         || statusItem->second == InstallState::USER_CHANGE) {
476         APP_LOGD("begin to update, bundleName : %{public}s, moduleName : %{public}s",
477             bundleName.c_str(), newInfo.GetCurrentModulePackage().c_str());
478         bool needAppDetail = oldInfo.GetBaseApplicationInfo().needAppDetail;
479         bool isOldInfoHasEntry = oldInfo.HasEntry();
480         if (newInfo.GetOverlayType() == NON_OVERLAY_TYPE) {
481             oldInfo.KeepOldOverlayConnection(newInfo);
482         }
483         oldInfo.UpdateModuleInfo(newInfo);
484         // 1.exist entry, update entry.
485         // 2.only exist feature, update feature.
486         if (newInfo.HasEntry() || !isOldInfoHasEntry || oldInfo.GetEntryInstallationFree()) {
487             oldInfo.UpdateBaseBundleInfo(newInfo.GetBaseBundleInfo(), newInfo.HasEntry());
488             oldInfo.UpdateBaseApplicationInfo(newInfo.GetBaseApplicationInfo());
489             oldInfo.UpdateRemovable(
490                 newInfo.IsPreInstallApp(), newInfo.IsRemovable());
491             oldInfo.SetAppType(newInfo.GetAppType());
492             oldInfo.SetAppFeature(newInfo.GetAppFeature());
493         }
494         oldInfo.SetCertificateFingerprint(newInfo.GetCertificateFingerprint());
495         oldInfo.SetAppPrivilegeLevel(newInfo.GetAppPrivilegeLevel());
496         oldInfo.SetAllowedAcls(newInfo.GetAllowedAcls());
497         oldInfo.UpdateAppDetailAbilityAttrs();
498         oldInfo.UpdateDataGroupInfos(newInfo.GetDataGroupInfos());
499         if (!needAppDetail && oldInfo.GetBaseApplicationInfo().needAppDetail) {
500             AddAppDetailAbilityInfo(oldInfo);
501         }
502         oldInfo.UpdateNativeLibAttrs(newInfo.GetBaseApplicationInfo());
503         oldInfo.UpdateArkNativeAttrs(newInfo.GetBaseApplicationInfo());
504         oldInfo.SetAsanLogPath(newInfo.GetAsanLogPath());
505         oldInfo.SetAsanEnabled(newInfo.GetAsanEnabled());
506         oldInfo.SetAppCrowdtestDeadline(newInfo.GetAppCrowdtestDeadline());
507         oldInfo.SetBundlePackInfo(newInfo.GetBundlePackInfo());
508         // clear apply quick fix frequency
509         oldInfo.ResetApplyQuickFixFrequency();
510         oldInfo.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
511         oldInfo.SetIsNewVersion(newInfo.GetIsNewVersion());
512         oldInfo.SetAppProvisionMetadata(newInfo.GetAppProvisionMetadata());
513 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
514         if (newInfo.GetIsNewVersion() && newInfo.GetOverlayType() == NON_OVERLAY_TYPE) {
515             if (!UpdateOverlayInfo(newInfo, oldInfo)) {
516                 APP_LOGE("update overlay info failed");
517                 return false;
518             }
519         }
520 
521         if ((newInfo.GetOverlayType() != NON_OVERLAY_TYPE) && (!UpdateOverlayInfo(newInfo, oldInfo))) {
522             APP_LOGE("update overlay info failed");
523             return false;
524         }
525 #endif
526         if (!dataStorage_->SaveStorageBundleInfo(oldInfo)) {
527             APP_LOGE("update storage failed bundle:%{public}s", bundleName.c_str());
528             return false;
529         }
530         APP_LOGI("update storage success bundle:%{public}s", bundleName.c_str());
531         bundleInfos_.at(bundleName) = oldInfo;
532         return true;
533     }
534     return false;
535 }
536 
QueryAbilityInfo(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,int32_t appIndex) const537 bool BundleDataMgr::QueryAbilityInfo(const Want &want, int32_t flags, int32_t userId, AbilityInfo &abilityInfo,
538     int32_t appIndex) const
539 {
540     int32_t requestUserId = GetUserId(userId);
541     if (requestUserId == Constants::INVALID_USERID) {
542         return false;
543     }
544 
545     ElementName element = want.GetElement();
546     std::string bundleName = element.GetBundleName();
547     std::string abilityName = element.GetAbilityName();
548     APP_LOGD("QueryAbilityInfo bundle name:%{public}s, ability name:%{public}s",
549         bundleName.c_str(), abilityName.c_str());
550     // explicit query
551     if (!bundleName.empty() && !abilityName.empty()) {
552         bool ret = ExplicitQueryAbilityInfo(want, flags, requestUserId, abilityInfo, appIndex);
553         if (!ret) {
554             APP_LOGE("explicit queryAbilityInfo error, bundleName: %{public}s, abilityName: %{public}s",
555                 bundleName.c_str(), abilityName.c_str());
556             return false;
557         }
558         return true;
559     }
560     std::vector<AbilityInfo> abilityInfos;
561     bool ret = ImplicitQueryAbilityInfos(want, flags, requestUserId, abilityInfos, appIndex);
562     if (!ret) {
563         APP_LOGE("implicit queryAbilityInfos error. action:%{public}s, uri:%{private}s, type:%{public}s",
564             want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
565         return false;
566     }
567     if (abilityInfos.size() == 0) {
568         APP_LOGE("no matching abilityInfo. action:%{public}s, uri:%{private}s, type:%{public}s",
569             want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
570         return false;
571     }
572     abilityInfo = abilityInfos[0];
573     return true;
574 }
575 
QueryAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const576 bool BundleDataMgr::QueryAbilityInfos(
577     const Want &want, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos) const
578 {
579     int32_t requestUserId = GetUserId(userId);
580     if (requestUserId == Constants::INVALID_USERID) {
581         return false;
582     }
583 
584     ElementName element = want.GetElement();
585     std::string bundleName = element.GetBundleName();
586     std::string abilityName = element.GetAbilityName();
587     APP_LOGD("QueryAbilityInfos bundle name:%{public}s, ability name:%{public}s",
588         bundleName.c_str(), abilityName.c_str());
589     // explicit query
590     if (!bundleName.empty() && !abilityName.empty()) {
591         AbilityInfo abilityInfo;
592         bool ret = ExplicitQueryAbilityInfo(want, flags, requestUserId, abilityInfo);
593         if (!ret) {
594             APP_LOGE("explicit queryAbilityInfo error, bundleName:%{public}s, abilityName:%{public}s",
595                 bundleName.c_str(), abilityName.c_str());
596             return false;
597         }
598         abilityInfos.emplace_back(abilityInfo);
599         return true;
600     }
601     // implicit query
602     bool ret = ImplicitQueryAbilityInfos(want, flags, requestUserId, abilityInfos);
603     if (!ret) {
604         APP_LOGE("implicit queryAbilityInfos error. action:%{public}s, uri:%{private}s, type:%{public}s",
605             want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
606         return false;
607     }
608     if (abilityInfos.size() == 0) {
609         APP_LOGE("no matching abilityInfo. action:%{public}s, uri:%{private}s, type:%{public}s",
610             want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
611         return false;
612     }
613     return true;
614 }
615 
QueryAbilityInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const616 ErrCode BundleDataMgr::QueryAbilityInfosV9(
617     const Want &want, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos) const
618 {
619     int32_t requestUserId = GetUserId(userId);
620     if (requestUserId == Constants::INVALID_USERID) {
621         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
622     }
623 
624     ElementName element = want.GetElement();
625     std::string bundleName = element.GetBundleName();
626     std::string abilityName = element.GetAbilityName();
627     APP_LOGD("QueryAbilityInfosV9 bundle name:%{public}s, ability name:%{public}s",
628         bundleName.c_str(), abilityName.c_str());
629     // explicit query
630     if (!bundleName.empty() && !abilityName.empty()) {
631         AbilityInfo abilityInfo;
632         ErrCode ret = ExplicitQueryAbilityInfoV9(want, flags, requestUserId, abilityInfo);
633         if (ret != ERR_OK) {
634             APP_LOGE("explicit queryAbilityInfoV9 error bundleName:%{public}s, abilityName:%{public}s",
635                 bundleName.c_str(), abilityName.c_str());
636             return ret;
637         }
638         abilityInfos.emplace_back(abilityInfo);
639         return ERR_OK;
640     }
641     // implicit query
642     ErrCode ret = ImplicitQueryAbilityInfosV9(want, flags, requestUserId, abilityInfos);
643     if (ret != ERR_OK) {
644         APP_LOGE("implicit queryAbilityInfosV9 error. action:%{public}s, uri:%{private}s, type:%{public}s",
645             want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
646         return ret;
647     }
648     if (abilityInfos.empty()) {
649         APP_LOGE("no matching abilityInfo. action:%{public}s, uri:%{private}s, type:%{public}s",
650             want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
651         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
652     }
653     return ERR_OK;
654 }
655 
ExplicitQueryAbilityInfo(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,int32_t appIndex) const656 bool BundleDataMgr::ExplicitQueryAbilityInfo(const Want &want, int32_t flags, int32_t userId,
657     AbilityInfo &abilityInfo, int32_t appIndex) const
658 {
659     ElementName element = want.GetElement();
660     std::string bundleName = element.GetBundleName();
661     std::string abilityName = element.GetAbilityName();
662     std::string moduleName = element.GetModuleName();
663     APP_LOGD("ExplicitQueryAbilityInfo bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
664         bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
665     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
666 
667     int32_t requestUserId = GetUserId(userId);
668     if (requestUserId == Constants::INVALID_USERID) {
669         return false;
670     }
671 
672     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
673     InnerBundleInfo innerBundleInfo;
674     if ((appIndex == 0) && (!GetInnerBundleInfoWithFlags(bundleName, flags, innerBundleInfo, requestUserId))) {
675         APP_LOGE("ExplicitQueryAbilityInfo failed, bundleName:%{public}s", bundleName.c_str());
676         return false;
677     }
678     // explict query from sandbox manager
679     if (appIndex > 0) {
680         if (sandboxAppHelper_ == nullptr) {
681             APP_LOGE("sandboxAppHelper_ is nullptr");
682             return false;
683         }
684         auto ret = sandboxAppHelper_->GetSandboxAppInfo(bundleName, appIndex, requestUserId, innerBundleInfo);
685         if (ret != ERR_OK) {
686             APP_LOGW("obtain innerBundleInfo of sandbox app failed due to errCode %{public}d, bundleName:%{public}s",
687                 ret, bundleName.c_str());
688             return false;
689         }
690     }
691 
692     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
693     auto ability = innerBundleInfo.FindAbilityInfo(moduleName, abilityName, responseUserId);
694     if (!ability) {
695         APP_LOGE("ability not found, bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
696             bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
697         return false;
698     }
699     return QueryAbilityInfoWithFlags(ability, flags, responseUserId, innerBundleInfo, abilityInfo);
700 }
701 
ExplicitQueryAbilityInfoV9(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,int32_t appIndex) const702 ErrCode BundleDataMgr::ExplicitQueryAbilityInfoV9(const Want &want, int32_t flags, int32_t userId,
703     AbilityInfo &abilityInfo, int32_t appIndex) const
704 {
705     ElementName element = want.GetElement();
706     std::string bundleName = element.GetBundleName();
707     std::string abilityName = element.GetAbilityName();
708     std::string moduleName = element.GetModuleName();
709     APP_LOGD("ExplicitQueryAbilityInfoV9 bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
710         bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
711     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
712     int32_t requestUserId = GetUserId(userId);
713     if (requestUserId == Constants::INVALID_USERID) {
714         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
715     }
716     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
717     InnerBundleInfo innerBundleInfo;
718     if (appIndex == 0) {
719         ErrCode ret = GetInnerBundleInfoWithFlagsV9(bundleName, flags, innerBundleInfo, requestUserId);
720         if (ret != ERR_OK) {
721             APP_LOGE("ExplicitQueryAbilityInfoV9 failed, bundleName:%{public}s", bundleName.c_str());
722             return ret;
723         }
724     }
725     // explict query from sandbox manager
726     if (appIndex > 0) {
727         if (sandboxAppHelper_ == nullptr) {
728             APP_LOGE("sandboxAppHelper_ is nullptr");
729             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
730         }
731         auto ret = sandboxAppHelper_->GetSandboxAppInfo(bundleName, appIndex, requestUserId, innerBundleInfo);
732         if (ret != ERR_OK) {
733             APP_LOGW("obtain innerBundleInfo of sandbox app failed due to errCode %{public}d, bundleName:%{public}s",
734                 ret, bundleName.c_str());
735             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
736         }
737     }
738 
739     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
740     auto ability = innerBundleInfo.FindAbilityInfoV9(moduleName, abilityName);
741     if (!ability) {
742         APP_LOGE("ability not found, bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
743             bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
744         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
745     }
746 
747     return QueryAbilityInfoWithFlagsV9(ability, flags, responseUserId, innerBundleInfo, abilityInfo);
748 }
749 
FilterAbilityInfosByModuleName(const std::string & moduleName,std::vector<AbilityInfo> & abilityInfos) const750 void BundleDataMgr::FilterAbilityInfosByModuleName(const std::string &moduleName,
751     std::vector<AbilityInfo> &abilityInfos) const
752 {
753     APP_LOGD("BundleDataMgr::FilterAbilityInfosByModuleName moduleName: %{public}s", moduleName.c_str());
754     if (moduleName.empty()) {
755         return;
756     }
757     for (auto iter = abilityInfos.begin(); iter != abilityInfos.end();) {
758         if (iter->moduleName != moduleName) {
759             iter = abilityInfos.erase(iter);
760         } else {
761             ++iter;
762         }
763     }
764 }
765 
ImplicitQueryAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos,int32_t appIndex) const766 bool BundleDataMgr::ImplicitQueryAbilityInfos(
767     const Want &want, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos, int32_t appIndex) const
768 {
769     int32_t requestUserId = GetUserId(userId);
770     if (requestUserId == Constants::INVALID_USERID) {
771         return false;
772     }
773 
774     if (want.GetAction().empty() && want.GetEntities().empty()
775         && want.GetUriString().empty() && want.GetType().empty()) {
776         APP_LOGE("param invalid");
777         return false;
778     }
779     APP_LOGD("action:%{public}s, uri:%{private}s, type:%{public}s",
780         want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
781     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
782     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
783     if (bundleInfos_.empty()) {
784         APP_LOGE("bundleInfos_ is empty");
785         return false;
786     }
787     std::string bundleName = want.GetElement().GetBundleName();
788     if (!bundleName.empty()) {
789         // query in current bundleName
790         if (!ImplicitQueryCurAbilityInfos(want, flags, requestUserId, abilityInfos, appIndex)) {
791             APP_LOGE("ImplicitQueryCurAbilityInfos failed, bundleName: %{public}s", bundleName.c_str());
792             return false;
793         }
794     } else {
795         // query all
796         ImplicitQueryAllAbilityInfos(want, flags, requestUserId, abilityInfos, appIndex);
797     }
798     // sort by priority, descending order.
799     if (abilityInfos.size() > 1) {
800         std::stable_sort(abilityInfos.begin(), abilityInfos.end(),
801             [](AbilityInfo a, AbilityInfo b) { return a.priority > b.priority; });
802     }
803     return true;
804 }
805 
ImplicitQueryAbilityInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos,int32_t appIndex) const806 ErrCode BundleDataMgr::ImplicitQueryAbilityInfosV9(
807     const Want &want, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos, int32_t appIndex) const
808 {
809     int32_t requestUserId = GetUserId(userId);
810     if (requestUserId == Constants::INVALID_USERID) {
811         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
812     }
813 
814     if (want.GetAction().empty() && want.GetEntities().empty()
815         && want.GetUriString().empty() && want.GetType().empty()) {
816         APP_LOGE("param invalid");
817         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
818     }
819     APP_LOGD("action:%{public}s, uri:%{private}s, type:%{public}s",
820         want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
821     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
822     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
823     if (bundleInfos_.empty()) {
824         APP_LOGE("bundleInfos_ is empty");
825         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
826     }
827     std::string bundleName = want.GetElement().GetBundleName();
828     if (!bundleName.empty()) {
829         // query in current bundleName
830         ErrCode ret = ImplicitQueryCurAbilityInfosV9(want, flags, requestUserId, abilityInfos, appIndex);
831         if (ret != ERR_OK) {
832             APP_LOGE("ImplicitQueryCurAbilityInfosV9 failed, bundleName:%{public}s", bundleName.c_str());
833             return ret;
834         }
835     } else {
836         // query all
837         ImplicitQueryAllAbilityInfosV9(want, flags, requestUserId, abilityInfos, appIndex);
838     }
839     // sort by priority, descending order.
840     if (abilityInfos.size() > 1) {
841         std::stable_sort(abilityInfos.begin(), abilityInfos.end(),
842             [](AbilityInfo a, AbilityInfo b) { return a.priority > b.priority; });
843     }
844     return ERR_OK;
845 }
846 
QueryAbilityInfoWithFlags(const std::optional<AbilityInfo> & option,int32_t flags,int32_t userId,const InnerBundleInfo & innerBundleInfo,AbilityInfo & info) const847 bool BundleDataMgr::QueryAbilityInfoWithFlags(const std::optional<AbilityInfo> &option, int32_t flags, int32_t userId,
848     const InnerBundleInfo &innerBundleInfo, AbilityInfo &info) const
849 {
850     APP_LOGD("begin to QueryAbilityInfoWithFlags.");
851     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_SYSTEMAPP_ONLY) == GET_ABILITY_INFO_SYSTEMAPP_ONLY &&
852         !innerBundleInfo.IsSystemApp()) {
853         APP_LOGE("no system app ability info for this calling");
854         return false;
855     }
856     if (!(static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_DISABLE)) {
857         if (!innerBundleInfo.IsAbilityEnabled((*option), userId)) {
858             APP_LOGE("bundleName:%{public}s, ability:%{public}s is disabled", option->bundleName.c_str(),
859                 option->name.c_str());
860             return false;
861         }
862     }
863     info = (*option);
864     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_PERMISSION) != GET_ABILITY_INFO_WITH_PERMISSION) {
865         info.permissions.clear();
866     }
867     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_METADATA) != GET_ABILITY_INFO_WITH_METADATA) {
868         info.metaData.customizeData.clear();
869         info.metadata.clear();
870     }
871     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_APPLICATION) == GET_ABILITY_INFO_WITH_APPLICATION) {
872         innerBundleInfo.GetApplicationInfo(
873             ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT, userId, info.applicationInfo);
874     }
875     // set uid for NAPI cache use
876     InnerBundleUserInfo innerBundleUserInfo;
877     if (innerBundleInfo.GetInnerBundleUserInfo(userId, innerBundleUserInfo)) {
878         info.uid = innerBundleUserInfo.uid;
879     }
880     return true;
881 }
882 
QueryAbilityInfoWithFlagsV9(const std::optional<AbilityInfo> & option,int32_t flags,int32_t userId,const InnerBundleInfo & innerBundleInfo,AbilityInfo & info) const883 ErrCode BundleDataMgr::QueryAbilityInfoWithFlagsV9(const std::optional<AbilityInfo> &option,
884     int32_t flags, int32_t userId, const InnerBundleInfo &innerBundleInfo, AbilityInfo &info) const
885 {
886     APP_LOGD("begin to QueryAbilityInfoWithFlagsV9.");
887     if ((static_cast<uint32_t>(flags) & static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_ONLY_SYSTEM_APP)) ==
888         static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_ONLY_SYSTEM_APP) &&
889         !innerBundleInfo.IsSystemApp()) {
890         APP_LOGE("target not system app");
891         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
892     }
893     if (!(static_cast<uint32_t>(flags) & static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_DISABLE))) {
894         if (!innerBundleInfo.IsAbilityEnabled((*option), userId)) {
895             APP_LOGE("bundleName:%{public}s, ability:%{public}s is disabled", option->bundleName.c_str(),
896                 option->name.c_str());
897             return ERR_BUNDLE_MANAGER_ABILITY_DISABLED;
898         }
899     }
900     info = (*option);
901     if ((static_cast<uint32_t>(flags) & static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION)) !=
902         static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION)) {
903         info.permissions.clear();
904     }
905     if ((static_cast<uint32_t>(flags) & static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA)) !=
906         static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA)) {
907         info.metaData.customizeData.clear();
908         info.metadata.clear();
909     }
910     if ((static_cast<uint32_t>(flags) & static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION)) ==
911         static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION)) {
912         innerBundleInfo.GetApplicationInfoV9(static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_DEFAULT),
913             userId, info.applicationInfo);
914     }
915     // set uid for NAPI cache use
916     InnerBundleUserInfo innerBundleUserInfo;
917     if (innerBundleInfo.GetInnerBundleUserInfo(userId, innerBundleUserInfo)) {
918         info.uid = innerBundleUserInfo.uid;
919     }
920     return ERR_OK;
921 }
922 
ImplicitQueryCurAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos,int32_t appIndex) const923 bool BundleDataMgr::ImplicitQueryCurAbilityInfos(const Want &want, int32_t flags, int32_t userId,
924     std::vector<AbilityInfo> &abilityInfos, int32_t appIndex) const
925 {
926     APP_LOGD("begin to ImplicitQueryCurAbilityInfos.");
927     std::string bundleName = want.GetElement().GetBundleName();
928     InnerBundleInfo innerBundleInfo;
929     if ((appIndex == 0) && (!GetInnerBundleInfoWithFlags(bundleName, flags, innerBundleInfo, userId))) {
930         APP_LOGE("ImplicitQueryCurAbilityInfos failed, bundleName:%{public}s", bundleName.c_str());
931         return false;
932     }
933     if (appIndex > 0) {
934         if (sandboxAppHelper_ == nullptr) {
935             APP_LOGE("sandboxAppHelper_ is nullptr");
936             return false;
937         }
938         auto ret = sandboxAppHelper_->GetSandboxAppInfo(bundleName, appIndex, userId, innerBundleInfo);
939         if (ret != ERR_OK) {
940             APP_LOGW("obtain innerBundleInfo of sandbox app failed due to errCode %{public}d, bundleName: %{public}s",
941                 ret, bundleName.c_str());
942             return false;
943         }
944     }
945     int32_t responseUserId = innerBundleInfo.GetResponseUserId(userId);
946     GetMatchAbilityInfos(want, flags, innerBundleInfo, responseUserId, abilityInfos);
947     FilterAbilityInfosByModuleName(want.GetElement().GetModuleName(), abilityInfos);
948     return true;
949 }
950 
ImplicitQueryCurAbilityInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos,int32_t appIndex) const951 ErrCode BundleDataMgr::ImplicitQueryCurAbilityInfosV9(const Want &want, int32_t flags, int32_t userId,
952     std::vector<AbilityInfo> &abilityInfos, int32_t appIndex) const
953 {
954     APP_LOGD("begin to ImplicitQueryCurAbilityInfosV9.");
955     std::string bundleName = want.GetElement().GetBundleName();
956     InnerBundleInfo innerBundleInfo;
957     if (appIndex == 0) {
958         ErrCode ret = GetInnerBundleInfoWithFlagsV9(bundleName, flags, innerBundleInfo, userId);
959         if (ret != ERR_OK) {
960             APP_LOGE("ImplicitQueryCurAbilityInfosV9 failed, bundleName:%{public}s", bundleName.c_str());
961             return ret;
962         }
963     }
964     if (appIndex > 0) {
965         if (sandboxAppHelper_ == nullptr) {
966             APP_LOGE("sandboxAppHelper_ is nullptr");
967             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
968         }
969         auto ret = sandboxAppHelper_->GetSandboxAppInfo(bundleName, appIndex, userId, innerBundleInfo);
970         if (ret != ERR_OK) {
971             APP_LOGW("obtain innerBundleInfo of sandbox app failed due to errCode %{public}d, bundleName:%{public}s",
972                 ret, bundleName.c_str());
973             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
974         }
975     }
976     int32_t responseUserId = innerBundleInfo.GetResponseUserId(userId);
977     GetMatchAbilityInfosV9(want, flags, innerBundleInfo, responseUserId, abilityInfos);
978     FilterAbilityInfosByModuleName(want.GetElement().GetModuleName(), abilityInfos);
979     return ERR_OK;
980 }
981 
ImplicitQueryAllAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos,int32_t appIndex) const982 void BundleDataMgr::ImplicitQueryAllAbilityInfos(const Want &want, int32_t flags, int32_t userId,
983     std::vector<AbilityInfo> &abilityInfos, int32_t appIndex) const
984 {
985     APP_LOGD("begin to ImplicitQueryAllAbilityInfos.");
986     int32_t requestUserId = GetUserId(userId);
987     if (requestUserId == Constants::INVALID_USERID) {
988         APP_LOGE("invalid userId");
989         return;
990     }
991 
992     // query from bundleInfos_
993     if (appIndex == 0) {
994         for (const auto &item : bundleInfos_) {
995             const InnerBundleInfo &innerBundleInfo = item.second;
996             int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
997             if (CheckInnerBundleInfoWithFlags(innerBundleInfo, flags, responseUserId) != ERR_OK) {
998                 APP_LOGW("ImplicitQueryAllAbilityInfos failed, bundleName:%{public}s, responseUserId:%{public}d",
999                     innerBundleInfo.GetBundleName().c_str(), responseUserId);
1000                 continue;
1001             }
1002 
1003             GetMatchAbilityInfos(want, flags, innerBundleInfo, responseUserId, abilityInfos);
1004         }
1005     } else {
1006         // query from sandbox manager for sandbox bundle
1007         if (sandboxAppHelper_ == nullptr) {
1008             APP_LOGE("sandboxAppHelper_ is nullptr");
1009             return;
1010         }
1011         auto sandboxMap = sandboxAppHelper_->GetSandboxAppInfoMap();
1012         for (const auto &item : sandboxMap) {
1013             InnerBundleInfo info;
1014             size_t pos = item.first.rfind(Constants::FILE_UNDERLINE);
1015             if (pos == std::string::npos) {
1016                 APP_LOGW("sandbox map contains invalid element");
1017                 continue;
1018             }
1019             std::string innerBundleName = item.first.substr(0, pos);
1020             if (sandboxAppHelper_->GetSandboxAppInfo(innerBundleName, appIndex, userId, info) != ERR_OK) {
1021                 APP_LOGW("obtain innerBundleInfo of sandbox app failed");
1022                 continue;
1023             }
1024 
1025             int32_t responseUserId = info.GetResponseUserId(userId);
1026             GetMatchAbilityInfos(want, flags, info, responseUserId, abilityInfos);
1027         }
1028     }
1029     APP_LOGD("finish to ImplicitQueryAllAbilityInfos.");
1030 }
1031 
ImplicitQueryAllAbilityInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos,int32_t appIndex) const1032 void BundleDataMgr::ImplicitQueryAllAbilityInfosV9(const Want &want, int32_t flags, int32_t userId,
1033     std::vector<AbilityInfo> &abilityInfos, int32_t appIndex) const
1034 {
1035     APP_LOGD("begin to ImplicitQueryAllAbilityInfosV9.");
1036     // query from bundleInfos_
1037     if (appIndex == 0) {
1038         for (const auto &item : bundleInfos_) {
1039             InnerBundleInfo innerBundleInfo;
1040             ErrCode ret = GetInnerBundleInfoWithFlagsV9(item.first, flags, innerBundleInfo, userId);
1041             if (ret != ERR_OK) {
1042                 APP_LOGW("ImplicitQueryAllAbilityInfosV9 failed, bundleName:%{public}s", item.first.c_str());
1043                 continue;
1044             }
1045 
1046             int32_t responseUserId = innerBundleInfo.GetResponseUserId(userId);
1047             GetMatchAbilityInfosV9(want, flags, innerBundleInfo, responseUserId, abilityInfos);
1048         }
1049     } else {
1050         // query from sandbox manager for sandbox bundle
1051         if (sandboxAppHelper_ == nullptr) {
1052             APP_LOGE("sandboxAppHelper_ is nullptr");
1053             return;
1054         }
1055         auto sandboxMap = sandboxAppHelper_->GetSandboxAppInfoMap();
1056         for (const auto &item : sandboxMap) {
1057             InnerBundleInfo info;
1058             size_t pos = item.first.rfind(Constants::FILE_UNDERLINE);
1059             if (pos == std::string::npos) {
1060                 APP_LOGW("sandbox map contains invalid element");
1061                 continue;
1062             }
1063             std::string innerBundleName = item.first.substr(0, pos);
1064             if (sandboxAppHelper_->GetSandboxAppInfo(innerBundleName, appIndex, userId, info) != ERR_OK) {
1065                 APP_LOGW("obtain innerBundleInfo of sandbox app failed");
1066                 continue;
1067             }
1068 
1069             int32_t responseUserId = info.GetResponseUserId(userId);
1070             GetMatchAbilityInfosV9(want, flags, info, responseUserId, abilityInfos);
1071         }
1072     }
1073     APP_LOGD("finish to ImplicitQueryAllAbilityInfosV9.");
1074 }
1075 
GetMatchAbilityInfos(const Want & want,int32_t flags,const InnerBundleInfo & info,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const1076 void BundleDataMgr::GetMatchAbilityInfos(const Want &want, int32_t flags,
1077     const InnerBundleInfo &info, int32_t userId, std::vector<AbilityInfo> &abilityInfos) const
1078 {
1079     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_SYSTEMAPP_ONLY) == GET_ABILITY_INFO_SYSTEMAPP_ONLY &&
1080         !info.IsSystemApp()) {
1081         return;
1082     }
1083     std::map<std::string, std::vector<Skill>> skillInfos = info.GetInnerSkillInfos();
1084     for (const auto &abilityInfoPair : info.GetInnerAbilityInfos()) {
1085         bool isPrivateType = MatchPrivateType(
1086             want, abilityInfoPair.second.supportExtNames, abilityInfoPair.second.supportMimeTypes);
1087         auto skillsPair = skillInfos.find(abilityInfoPair.first);
1088         if (skillsPair == skillInfos.end()) {
1089             continue;
1090         }
1091         for (const Skill &skill : skillsPair->second) {
1092             if (isPrivateType || skill.Match(want)) {
1093                 AbilityInfo abilityinfo = abilityInfoPair.second;
1094                 AddAbilitySkillUrisInfo(flags, skill, abilityinfo);
1095                 if (abilityinfo.name == Constants::APP_DETAIL_ABILITY) {
1096                     continue;
1097                 }
1098                 if (!(static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_DISABLE)) {
1099                     if (!info.IsAbilityEnabled(abilityinfo, GetUserId(userId))) {
1100                         APP_LOGW("GetMatchAbilityInfos %{public}s is disabled", abilityinfo.name.c_str());
1101                         continue;
1102                     }
1103                 }
1104                 if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_APPLICATION) ==
1105                     GET_ABILITY_INFO_WITH_APPLICATION) {
1106                     info.GetApplicationInfo(
1107                         ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT, userId,
1108                         abilityinfo.applicationInfo);
1109                 }
1110                 if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_PERMISSION) !=
1111                     GET_ABILITY_INFO_WITH_PERMISSION) {
1112                     abilityinfo.permissions.clear();
1113                 }
1114                 if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_METADATA) != GET_ABILITY_INFO_WITH_METADATA) {
1115                     abilityinfo.metaData.customizeData.clear();
1116                     abilityinfo.metadata.clear();
1117                 }
1118                 abilityInfos.emplace_back(abilityinfo);
1119                 break;
1120             }
1121         }
1122     }
1123 }
1124 
AddAbilitySkillUrisInfo(int32_t flags,const Skill & skill,AbilityInfo & abilityInfo) const1125 void BundleDataMgr::AddAbilitySkillUrisInfo(int32_t flags, const Skill &skill, AbilityInfo &abilityInfo) const
1126 {
1127     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_SKILL_URI) == GET_ABILITY_INFO_WITH_SKILL_URI) {
1128         std::vector<SkillUriForAbilityAndExtension> skillUriTmp;
1129         for (const SkillUri &uri : skill.uris) {
1130             SkillUriForAbilityAndExtension skillinfo;
1131             skillinfo.scheme = uri.scheme;
1132             skillinfo.host = uri.host;
1133             skillinfo.port = uri.port;
1134             skillinfo.path = uri.path;
1135             skillinfo.pathStartWith = uri.pathStartWith;
1136             skillinfo.pathRegex = uri.pathRegex;
1137             skillinfo.type = uri.type;
1138             skillUriTmp.emplace_back(skillinfo);
1139         }
1140         abilityInfo.skillUri = skillUriTmp;
1141     }
1142 }
1143 
GetMatchAbilityInfosV9(const Want & want,int32_t flags,const InnerBundleInfo & info,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const1144 void BundleDataMgr::GetMatchAbilityInfosV9(const Want &want, int32_t flags,
1145     const InnerBundleInfo &info, int32_t userId, std::vector<AbilityInfo> &abilityInfos) const
1146 {
1147     if ((static_cast<uint32_t>(flags) & static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_ONLY_SYSTEM_APP)) ==
1148         static_cast<int32_t>((GetAbilityInfoFlag::GET_ABILITY_INFO_ONLY_SYSTEM_APP)) && !info.IsSystemApp()) {
1149         APP_LOGE("target not system app");
1150         return;
1151     }
1152     std::map<std::string, std::vector<Skill>> skillInfos = info.GetInnerSkillInfos();
1153     for (const auto &abilityInfoPair : info.GetInnerAbilityInfos()) {
1154         auto skillsPair = skillInfos.find(abilityInfoPair.first);
1155         if (skillsPair == skillInfos.end()) {
1156             continue;
1157         }
1158         bool isPrivateType = MatchPrivateType(
1159             want, abilityInfoPair.second.supportExtNames, abilityInfoPair.second.supportMimeTypes);
1160         for (const Skill &skill : skillsPair->second) {
1161             if (isPrivateType || skill.Match(want)) {
1162                 AbilityInfo abilityinfo = abilityInfoPair.second;
1163                 if (abilityinfo.name == Constants::APP_DETAIL_ABILITY) {
1164                     continue;
1165                 }
1166                 if (!(static_cast<uint32_t>(flags) & static_cast<int32_t>(
1167                     GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_DISABLE))) {
1168                     if (!info.IsAbilityEnabled(abilityinfo, GetUserId(userId))) {
1169                         APP_LOGW("GetMatchAbilityInfos %{public}s is disabled", abilityinfo.name.c_str());
1170                         continue;
1171                     }
1172                 }
1173                 if ((static_cast<uint32_t>(flags) &
1174                     static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION)) ==
1175                     static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION)) {
1176                     info.GetApplicationInfoV9(static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_DEFAULT),
1177                         userId, abilityinfo.applicationInfo);
1178                 }
1179                 if ((static_cast<uint32_t>(flags) &
1180                     static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION)) !=
1181                     static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION)) {
1182                     abilityinfo.permissions.clear();
1183                 }
1184                 if ((static_cast<uint32_t>(flags) &
1185                     static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA)) !=
1186                     static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA)) {
1187                     abilityinfo.metaData.customizeData.clear();
1188                     abilityinfo.metadata.clear();
1189                 }
1190                 abilityInfos.emplace_back(abilityinfo);
1191                 break;
1192             }
1193         }
1194     }
1195 }
1196 
ModifyLauncherAbilityInfo(bool isStage,AbilityInfo & abilityInfo) const1197 void BundleDataMgr::ModifyLauncherAbilityInfo(bool isStage, AbilityInfo &abilityInfo) const
1198 {
1199     if (abilityInfo.labelId == 0) {
1200         if (isStage) {
1201             abilityInfo.labelId = abilityInfo.applicationInfo.labelId;
1202             abilityInfo.label = abilityInfo.applicationInfo.label;
1203         } else {
1204             abilityInfo.applicationInfo.label = abilityInfo.bundleName;
1205             abilityInfo.label = abilityInfo.bundleName;
1206         }
1207     }
1208 
1209     if (abilityInfo.iconId == 0) {
1210         if (isStage) {
1211             abilityInfo.iconId = abilityInfo.applicationInfo.iconId;
1212         } else {
1213             auto iter = bundleInfos_.find(GLOBAL_RESOURCE_BUNDLE_NAME);
1214             if (iter != bundleInfos_.end()) {
1215                 abilityInfo.iconId = iter->second.GetBaseApplicationInfo().iconId;
1216             }
1217         }
1218     }
1219 }
1220 
GetMatchLauncherAbilityInfos(const Want & want,const InnerBundleInfo & info,std::vector<AbilityInfo> & abilityInfos,int64_t installTime,int32_t userId) const1221 void BundleDataMgr::GetMatchLauncherAbilityInfos(const Want& want,
1222     const InnerBundleInfo& info, std::vector<AbilityInfo>& abilityInfos,
1223     int64_t installTime, int32_t userId) const
1224 {
1225     int32_t requestUserId = GetUserId(userId);
1226     if (requestUserId == Constants::INVALID_USERID) {
1227         return;
1228     }
1229     int32_t responseUserId = info.GetResponseUserId(requestUserId);
1230     bool isExist = false;
1231     bool isStage = info.GetIsNewVersion();
1232     std::map<std::string, std::vector<Skill>> skillInfos = info.GetInnerSkillInfos();
1233     for (const auto& abilityInfoPair : info.GetInnerAbilityInfos()) {
1234         auto skillsPair = skillInfos.find(abilityInfoPair.first);
1235         if (skillsPair == skillInfos.end()) {
1236             continue;
1237         }
1238         for (const Skill& skill : skillsPair->second) {
1239             if (skill.MatchLauncher(want) && (abilityInfoPair.second.type == AbilityType::PAGE)) {
1240                 isExist = true;
1241                 AbilityInfo abilityinfo = abilityInfoPair.second;
1242                 info.GetApplicationInfo(ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT,
1243                     responseUserId, abilityinfo.applicationInfo);
1244                 abilityinfo.installTime = installTime;
1245                 // fix labelId or iconId is equal 0
1246                 ModifyLauncherAbilityInfo(isStage, abilityinfo);
1247                 abilityInfos.emplace_back(abilityinfo);
1248                 break;
1249             }
1250         }
1251     }
1252     // add app detail ability
1253     if (!isExist && info.GetBaseApplicationInfo().needAppDetail) {
1254         APP_LOGD("bundleName: %{public}s add detail ability info.", info.GetBundleName().c_str());
1255         std::string moduleName = "";
1256         auto ability = info.FindAbilityInfo(moduleName, Constants::APP_DETAIL_ABILITY, responseUserId);
1257         if (!ability) {
1258             APP_LOGD("bundleName: %{public}s can not find app detail ability.", info.GetBundleName().c_str());
1259             return;
1260         }
1261         if (!info.GetIsNewVersion()) {
1262             ability->applicationInfo.label = info.GetBundleName();
1263         }
1264         ability->installTime = installTime;
1265         abilityInfos.emplace_back(*ability);
1266     }
1267 }
1268 
AddAppDetailAbilityInfo(InnerBundleInfo & info) const1269 void BundleDataMgr::AddAppDetailAbilityInfo(InnerBundleInfo &info) const
1270 {
1271     AbilityInfo appDetailAbility;
1272     appDetailAbility.name = Constants::APP_DETAIL_ABILITY;
1273     appDetailAbility.bundleName = info.GetBundleName();
1274     std::vector<std::string> moduleNameVec;
1275     info.GetModuleNames(moduleNameVec);
1276     if (!moduleNameVec.empty()) {
1277         appDetailAbility.moduleName = moduleNameVec[0];
1278     } else {
1279         APP_LOGE("AddAppDetailAbilityInfo error: %{public}s has no module.", appDetailAbility.bundleName.c_str());
1280     }
1281     appDetailAbility.enabled = true;
1282     appDetailAbility.type = AbilityType::PAGE;
1283     appDetailAbility.package = info.GetCurrentModulePackage();
1284     appDetailAbility.isNativeAbility = true;
1285 
1286     ApplicationInfo applicationInfo = info.GetBaseApplicationInfo();
1287     appDetailAbility.applicationName = applicationInfo.name;
1288     appDetailAbility.labelId = applicationInfo.labelId;
1289     if (!info.GetIsNewVersion()) {
1290         appDetailAbility.labelId = 0;
1291     }
1292     appDetailAbility.iconId = applicationInfo.iconId;
1293     if ((appDetailAbility.iconId == 0) || !info.GetIsNewVersion()) {
1294         APP_LOGD("AddAppDetailAbilityInfo appDetailAbility.iconId is 0.");
1295         // get system resource icon Id
1296         auto iter = bundleInfos_.find(GLOBAL_RESOURCE_BUNDLE_NAME);
1297         if (iter != bundleInfos_.end()) {
1298             APP_LOGD("AddAppDetailAbilityInfo get system resource iconId");
1299             appDetailAbility.iconId = iter->second.GetBaseApplicationInfo().iconId;
1300         } else {
1301             APP_LOGE("AddAppDetailAbilityInfo error: ohos.global.systemres does not exist.");
1302         }
1303     }
1304     // not show in the mission list
1305     appDetailAbility.removeMissionAfterTerminate = true;
1306 
1307     std::string keyName;
1308     keyName.append(appDetailAbility.bundleName).append(".")
1309         .append(appDetailAbility.package).append(".").append(appDetailAbility.name);
1310     info.InsertAbilitiesInfo(keyName, appDetailAbility);
1311 }
1312 
GetAllLauncherAbility(const Want & want,std::vector<AbilityInfo> & abilityInfos,const int32_t userId,const int32_t requestUserId) const1313 void BundleDataMgr::GetAllLauncherAbility(const Want &want, std::vector<AbilityInfo> &abilityInfos,
1314     const int32_t userId, const int32_t requestUserId) const
1315 {
1316     for (const auto &item : bundleInfos_) {
1317         const InnerBundleInfo &info = item.second;
1318         if (info.IsDisabled()) {
1319             APP_LOGI("app %{public}s is disabled", info.GetBundleName().c_str());
1320             continue;
1321         }
1322         if (info.GetBaseApplicationInfo().hideDesktopIcon) {
1323             APP_LOGD("Bundle(%{public}s) hide desktop icon", info.GetBundleName().c_str());
1324             continue;
1325         }
1326         if (info.GetBaseBundleInfo().entryInstallationFree) {
1327             APP_LOGD("Bundle(%{public}s) is atomic service, hide desktop icon", info.GetBundleName().c_str());
1328             continue;
1329         }
1330 
1331         // get installTime from innerBundleUserInfo
1332         int64_t installTime = 0;
1333         std::string userIdKey = info.GetBundleName() + "_" + std::to_string(userId);
1334         std::string userZeroKey = info.GetBundleName() + "_" + std::to_string(0);
1335         auto iter = std::find_if(info.GetInnerBundleUserInfos().begin(), info.GetInnerBundleUserInfos().end(),
1336             [&userIdKey, &userZeroKey](const std::pair<std::string, InnerBundleUserInfo> &infoMap) {
1337             return (infoMap.first == userIdKey || infoMap.first == userZeroKey);
1338         });
1339         if (iter != info.GetInnerBundleUserInfos().end()) {
1340             installTime = iter->second.installTime;
1341         }
1342         GetMatchLauncherAbilityInfos(want, info, abilityInfos, installTime, userId);
1343     }
1344 }
1345 
GetLauncherAbilityByBundleName(const Want & want,std::vector<AbilityInfo> & abilityInfos,const int32_t userId,const int32_t requestUserId) const1346 ErrCode BundleDataMgr::GetLauncherAbilityByBundleName(const Want &want, std::vector<AbilityInfo> &abilityInfos,
1347     const int32_t userId, const int32_t requestUserId) const
1348 {
1349     ElementName element = want.GetElement();
1350     std::string bundleName = element.GetBundleName();
1351     const auto &item = bundleInfos_.find(bundleName);
1352     if (item == bundleInfos_.end()) {
1353         APP_LOGE("no bundleName %{public}s found", bundleName.c_str());
1354         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
1355     }
1356     const InnerBundleInfo &info = item->second;
1357     if (info.IsDisabled()) {
1358         APP_LOGE("app %{public}s is disabled", info.GetBundleName().c_str());
1359         return ERR_BUNDLE_MANAGER_APPLICATION_DISABLED;
1360     }
1361     if (info.GetBaseApplicationInfo().hideDesktopIcon) {
1362         APP_LOGD("Bundle(%{public}s) hide desktop icon", bundleName.c_str());
1363         return ERR_OK;
1364     }
1365     if (info.GetBaseBundleInfo().entryInstallationFree) {
1366         APP_LOGD("Bundle(%{public}s) is atomic service, hide desktop icon", bundleName.c_str());
1367         return ERR_OK;
1368     }
1369     // get installTime from innerBundleUserInfo
1370     int64_t installTime = 0;
1371     std::string userIdKey = info.GetBundleName() + "_" + std::to_string(userId);
1372     std::string userZeroKey = info.GetBundleName() + "_" + std::to_string(0);
1373     auto iter = std::find_if(info.GetInnerBundleUserInfos().begin(), info.GetInnerBundleUserInfos().end(),
1374         [&userIdKey, &userZeroKey](const std::pair<std::string, InnerBundleUserInfo> &infoMap) {
1375         return (infoMap.first == userIdKey || infoMap.first == userZeroKey);
1376     });
1377     if (iter != info.GetInnerBundleUserInfos().end()) {
1378         installTime = iter->second.installTime;
1379     }
1380     GetMatchLauncherAbilityInfos(want, item->second, abilityInfos, installTime, userId);
1381     FilterAbilityInfosByModuleName(element.GetModuleName(), abilityInfos);
1382     return ERR_OK;
1383 }
1384 
QueryLauncherAbilityInfos(const Want & want,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const1385 ErrCode BundleDataMgr::QueryLauncherAbilityInfos(
1386     const Want &want, int32_t userId, std::vector<AbilityInfo> &abilityInfos) const
1387 {
1388     int32_t requestUserId = GetUserId(userId);
1389     if (requestUserId == Constants::INVALID_USERID) {
1390         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1391     }
1392     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1393     if (bundleInfos_.empty()) {
1394         APP_LOGE("bundleInfos_ is empty");
1395         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
1396     }
1397 
1398     ElementName element = want.GetElement();
1399     std::string bundleName = element.GetBundleName();
1400     if (bundleName.empty()) {
1401         // query all launcher ability
1402         GetAllLauncherAbility(want, abilityInfos, userId, requestUserId);
1403         QueryLauncherAbilityFromBmsExtension(want, userId, abilityInfos);
1404         return ERR_OK;
1405     }
1406     // query definite abilities by bundle name
1407     ErrCode ret = GetLauncherAbilityByBundleName(want, abilityInfos, userId, requestUserId);
1408     if (ret == ERR_OK) {
1409         APP_LOGD("ability infos have been found");
1410         return ret;
1411     }
1412 
1413     if (ret == ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST) {
1414         if (QueryLauncherAbilityFromBmsExtension(want, userId, abilityInfos) == ERR_OK) {
1415             APP_LOGD("query launcher abilities from bms extension successfully");
1416             return ERR_OK;
1417         }
1418     }
1419     return ret;
1420 }
1421 
QueryAbilityInfoByUri(const std::string & abilityUri,int32_t userId,AbilityInfo & abilityInfo) const1422 bool BundleDataMgr::QueryAbilityInfoByUri(
1423     const std::string &abilityUri, int32_t userId, AbilityInfo &abilityInfo) const
1424 {
1425     APP_LOGD("abilityUri is %{private}s", abilityUri.c_str());
1426     int32_t requestUserId = GetUserId(userId);
1427     if (requestUserId == Constants::INVALID_USERID) {
1428         return false;
1429     }
1430 
1431     if (abilityUri.empty()) {
1432         return false;
1433     }
1434     if (abilityUri.find(Constants::DATA_ABILITY_URI_PREFIX) == std::string::npos) {
1435         return false;
1436     }
1437     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1438     if (bundleInfos_.empty()) {
1439         APP_LOGE("bundleInfos_ data is empty");
1440         return false;
1441     }
1442     std::string noPpefixUri = abilityUri.substr(strlen(Constants::DATA_ABILITY_URI_PREFIX));
1443     auto posFirstSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR);
1444     if (posFirstSeparator == std::string::npos) {
1445         return false;
1446     }
1447     auto posSecondSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR, posFirstSeparator + 1);
1448     std::string uri;
1449     if (posSecondSeparator == std::string::npos) {
1450         uri = noPpefixUri.substr(posFirstSeparator + 1, noPpefixUri.size() - posFirstSeparator - 1);
1451     } else {
1452         uri = noPpefixUri.substr(posFirstSeparator + 1, posSecondSeparator - posFirstSeparator - 1);
1453     }
1454     for (const auto &item : bundleInfos_) {
1455         const InnerBundleInfo &info = item.second;
1456         if (info.IsDisabled()) {
1457             APP_LOGE("app %{public}s is disabled", info.GetBundleName().c_str());
1458             continue;
1459         }
1460 
1461         int32_t responseUserId = info.GetResponseUserId(requestUserId);
1462         if (!info.GetApplicationEnabled(responseUserId)) {
1463             continue;
1464         }
1465 
1466         auto ability = info.FindAbilityInfoByUri(uri);
1467         if (!ability) {
1468             continue;
1469         }
1470 
1471         abilityInfo = (*ability);
1472         info.GetApplicationInfo(
1473             ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT, responseUserId,
1474             abilityInfo.applicationInfo);
1475         return true;
1476     }
1477 
1478     APP_LOGE("query abilityUri(%{private}s) failed.", abilityUri.c_str());
1479     return false;
1480 }
1481 
QueryAbilityInfosByUri(const std::string & abilityUri,std::vector<AbilityInfo> & abilityInfos)1482 bool BundleDataMgr::QueryAbilityInfosByUri(const std::string &abilityUri, std::vector<AbilityInfo> &abilityInfos)
1483 {
1484     APP_LOGI("abilityUri is %{private}s", abilityUri.c_str());
1485     if (abilityUri.empty()) {
1486         return false;
1487     }
1488     if (abilityUri.find(Constants::DATA_ABILITY_URI_PREFIX) == std::string::npos) {
1489         return false;
1490     }
1491     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1492     if (bundleInfos_.empty()) {
1493         APP_LOGI("bundleInfos_ data is empty");
1494         return false;
1495     }
1496     std::string noPpefixUri = abilityUri.substr(strlen(Constants::DATA_ABILITY_URI_PREFIX));
1497     auto posFirstSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR);
1498     if (posFirstSeparator == std::string::npos) {
1499         return false;
1500     }
1501     auto posSecondSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR, posFirstSeparator + 1);
1502     std::string uri;
1503     if (posSecondSeparator == std::string::npos) {
1504         uri = noPpefixUri.substr(posFirstSeparator + 1, noPpefixUri.size() - posFirstSeparator - 1);
1505     } else {
1506         uri = noPpefixUri.substr(posFirstSeparator + 1, posSecondSeparator - posFirstSeparator - 1);
1507     }
1508 
1509     for (auto &item : bundleInfos_) {
1510         InnerBundleInfo &info = item.second;
1511         if (info.IsDisabled()) {
1512             APP_LOGI("app %{public}s is disabled", info.GetBundleName().c_str());
1513             continue;
1514         }
1515         info.FindAbilityInfosByUri(uri, abilityInfos, GetUserId());
1516     }
1517     if (abilityInfos.size() == 0) {
1518         return false;
1519     }
1520 
1521     return true;
1522 }
1523 
GetApplicationInfo(const std::string & appName,int32_t flags,const int userId,ApplicationInfo & appInfo) const1524 bool BundleDataMgr::GetApplicationInfo(
1525     const std::string &appName, int32_t flags, const int userId, ApplicationInfo &appInfo) const
1526 {
1527     int32_t requestUserId = GetUserId(userId);
1528     if (requestUserId == Constants::INVALID_USERID) {
1529         return false;
1530     }
1531 
1532     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1533     InnerBundleInfo innerBundleInfo;
1534     if (!GetInnerBundleInfoWithFlags(appName, flags, innerBundleInfo, requestUserId)) {
1535         APP_LOGE("GetApplicationInfo failed, bundleName:%{public}s", appName.c_str());
1536         return false;
1537     }
1538 
1539     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
1540     innerBundleInfo.GetApplicationInfo(flags, responseUserId, appInfo);
1541     return true;
1542 }
1543 
GetApplicationInfoV9(const std::string & appName,int32_t flags,int32_t userId,ApplicationInfo & appInfo) const1544 ErrCode BundleDataMgr::GetApplicationInfoV9(
1545     const std::string &appName, int32_t flags, int32_t userId, ApplicationInfo &appInfo) const
1546 {
1547     int32_t requestUserId = GetUserId(userId);
1548     if (requestUserId == Constants::INVALID_USERID) {
1549         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1550     }
1551 
1552     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1553     InnerBundleInfo innerBundleInfo;
1554     int32_t flag = 0;
1555     if ((static_cast<uint32_t>(flags) & static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE))
1556         == static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE)) {
1557         flag = static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE);
1558     }
1559     auto ret = GetInnerBundleInfoWithBundleFlagsV9(appName, flag, innerBundleInfo, requestUserId);
1560     if (ret != ERR_OK) {
1561         APP_LOGE("GetApplicationInfoV9 failed, bundleName:%{public}s, requestUserId:%{public}d",
1562             appName.c_str(), requestUserId);
1563         return ret;
1564     }
1565 
1566     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
1567     ret = innerBundleInfo.GetApplicationInfoV9(flags, responseUserId, appInfo);
1568     if (ret != ERR_OK) {
1569         APP_LOGE("GetApplicationInfoV9 failed, bundleName:%{public}s, responseUserId:%{public}d",
1570             appName.c_str(), responseUserId);
1571         return ret;
1572     }
1573     return ret;
1574 }
1575 
GetApplicationInfoWithResponseId(const std::string & appName,int32_t flags,int32_t & userId,ApplicationInfo & appInfo) const1576 ErrCode BundleDataMgr::GetApplicationInfoWithResponseId(
1577     const std::string &appName, int32_t flags, int32_t &userId, ApplicationInfo &appInfo) const
1578 {
1579     int32_t requestUserId = GetUserId(userId);
1580     if (requestUserId == Constants::INVALID_USERID) {
1581         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1582     }
1583 
1584     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1585     InnerBundleInfo innerBundleInfo;
1586     int32_t flag = 0;
1587     if ((static_cast<uint32_t>(flags) & static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE))
1588         == static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE)) {
1589         flag = static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE);
1590     }
1591     auto ret = GetInnerBundleInfoWithBundleFlagsV9(appName, flag, innerBundleInfo, requestUserId);
1592     if (ret != ERR_OK) {
1593         APP_LOGE("GetApplicationInfoV9 failed, bundleName:%{public}s, requestUserId:%{public}d",
1594             appName.c_str(), requestUserId);
1595         return ret;
1596     }
1597 
1598     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
1599     ret = innerBundleInfo.GetApplicationInfoV9(flags, responseUserId, appInfo);
1600     if (ret != ERR_OK) {
1601         APP_LOGE("GetApplicationInfoV9 failed, bundleName:%{public}s, responseUserId:%{public}d",
1602             appName.c_str(), responseUserId);
1603         return ret;
1604     }
1605     userId = responseUserId;
1606     return ret;
1607 }
1608 
GetApplicationInfos(int32_t flags,const int userId,std::vector<ApplicationInfo> & appInfos) const1609 bool BundleDataMgr::GetApplicationInfos(
1610     int32_t flags, const int userId, std::vector<ApplicationInfo> &appInfos) const
1611 {
1612     int32_t requestUserId = GetUserId(userId);
1613     if (requestUserId == Constants::INVALID_USERID) {
1614         return false;
1615     }
1616 
1617     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1618     if (bundleInfos_.empty()) {
1619         APP_LOGE("bundleInfos_ data is empty");
1620         return false;
1621     }
1622 
1623     bool find = false;
1624     for (const auto &item : bundleInfos_) {
1625         const InnerBundleInfo &info = item.second;
1626         if (info.IsDisabled()) {
1627             APP_LOGE("app %{public}s is disabled", info.GetBundleName().c_str());
1628             continue;
1629         }
1630         int32_t responseUserId = info.GetResponseUserId(requestUserId);
1631         if (!(static_cast<uint32_t>(flags) & GET_APPLICATION_INFO_WITH_DISABLE)
1632             && !info.GetApplicationEnabled(responseUserId)) {
1633             APP_LOGD("bundleName: %{public}s is disabled", info.GetBundleName().c_str());
1634             continue;
1635         }
1636         ApplicationInfo appInfo;
1637         info.GetApplicationInfo(flags, responseUserId, appInfo);
1638         appInfos.emplace_back(appInfo);
1639         find = true;
1640     }
1641     APP_LOGD("get installed bundles success");
1642     return find;
1643 }
1644 
GetApplicationInfosV9(int32_t flags,int32_t userId,std::vector<ApplicationInfo> & appInfos) const1645 ErrCode BundleDataMgr::GetApplicationInfosV9(
1646     int32_t flags, int32_t userId, std::vector<ApplicationInfo> &appInfos) const
1647 {
1648     int32_t requestUserId = GetUserId(userId);
1649     if (requestUserId == Constants::INVALID_USERID) {
1650         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1651     }
1652 
1653     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1654     if (bundleInfos_.empty()) {
1655         APP_LOGE("bundleInfos_ data is empty");
1656         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1657     }
1658     for (const auto &item : bundleInfos_) {
1659         const InnerBundleInfo &info = item.second;
1660         if (info.IsDisabled()) {
1661             APP_LOGE("app %{public}s is disabled", info.GetBundleName().c_str());
1662             continue;
1663         }
1664         int32_t responseUserId = info.GetResponseUserId(requestUserId);
1665         if (!(static_cast<uint32_t>(flags) &
1666             static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE))
1667             && !info.GetApplicationEnabled(responseUserId)) {
1668             APP_LOGD("bundleName: %{public}s is disabled", info.GetBundleName().c_str());
1669             continue;
1670         }
1671         ApplicationInfo appInfo;
1672         if (info.GetApplicationInfoV9(flags, responseUserId, appInfo) != ERR_OK) {
1673             continue;
1674         }
1675         appInfos.emplace_back(appInfo);
1676     }
1677     APP_LOGD("get installed bundles success");
1678     return ERR_OK;
1679 }
1680 
GetBundleInfo(const std::string & bundleName,int32_t flags,BundleInfo & bundleInfo,int32_t userId) const1681 bool BundleDataMgr::GetBundleInfo(
1682     const std::string &bundleName, int32_t flags, BundleInfo &bundleInfo, int32_t userId) const
1683 {
1684     std::vector<InnerBundleUserInfo> innerBundleUserInfos;
1685     if (userId == Constants::ANY_USERID) {
1686         if (!GetInnerBundleUserInfos(bundleName, innerBundleUserInfos)) {
1687             APP_LOGE("no userInfos for this bundle(%{public}s)", bundleName.c_str());
1688             return false;
1689         }
1690         userId = innerBundleUserInfos.begin()->bundleUserInfo.userId;
1691     }
1692 
1693     int32_t requestUserId = GetUserId(userId);
1694     if (requestUserId == Constants::INVALID_USERID) {
1695         return false;
1696     }
1697     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1698     InnerBundleInfo innerBundleInfo;
1699     if (!GetInnerBundleInfoWithFlags(bundleName, flags, innerBundleInfo, requestUserId)) {
1700         APP_LOGE("GetBundleInfo failed, bundleName:%{public}s, requestUserId:%{public}d",
1701             bundleName.c_str(), requestUserId);
1702         return false;
1703     }
1704 
1705     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
1706     innerBundleInfo.GetBundleInfo(flags, bundleInfo, responseUserId);
1707     APP_LOGD("get bundleInfo(%{public}s) successfully in user(%{public}d)", bundleName.c_str(), userId);
1708     return true;
1709 }
1710 
GetBundleInfoV9(const std::string & bundleName,int32_t flags,BundleInfo & bundleInfo,int32_t userId) const1711 ErrCode BundleDataMgr::GetBundleInfoV9(
1712     const std::string &bundleName, int32_t flags, BundleInfo &bundleInfo, int32_t userId) const
1713 {
1714     std::vector<InnerBundleUserInfo> innerBundleUserInfos;
1715     if (userId == Constants::ANY_USERID) {
1716         if (!GetInnerBundleUserInfos(bundleName, innerBundleUserInfos)) {
1717             APP_LOGE("no userInfos for this bundle(%{public}s)", bundleName.c_str());
1718             return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1719         }
1720         userId = innerBundleUserInfos.begin()->bundleUserInfo.userId;
1721     }
1722 
1723     int32_t requestUserId = GetUserId(userId);
1724     if (requestUserId == Constants::INVALID_USERID) {
1725         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1726     }
1727     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1728     InnerBundleInfo innerBundleInfo;
1729 
1730     auto ret = GetInnerBundleInfoWithBundleFlagsV9(bundleName, flags, innerBundleInfo, requestUserId);
1731     if (ret != ERR_OK) {
1732         APP_LOGE("GetBundleInfoV9 failed, error code: %{public}d, bundleName:%{public}s", ret, bundleName.c_str());
1733         return ret;
1734     }
1735 
1736     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
1737     innerBundleInfo.GetBundleInfoV9(flags, bundleInfo, responseUserId);
1738     APP_LOGD("get bundleInfo(%{public}s) successfully in user(%{public}d)", bundleName.c_str(), userId);
1739     return ERR_OK;
1740 }
1741 
GetBaseSharedBundleInfos(const std::string & bundleName,std::vector<BaseSharedBundleInfo> & baseSharedBundleInfos) const1742 ErrCode BundleDataMgr::GetBaseSharedBundleInfos(const std::string &bundleName,
1743     std::vector<BaseSharedBundleInfo> &baseSharedBundleInfos) const
1744 {
1745     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1746     auto infoItem = bundleInfos_.find(bundleName);
1747     if (infoItem == bundleInfos_.end()) {
1748         APP_LOGE("GetBaseSharedBundleInfos get bundleInfo failed, bundleName:%{public}s", bundleName.c_str());
1749         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
1750     }
1751     const InnerBundleInfo &innerBundleInfo = infoItem->second;
1752     std::vector<Dependency> dependencies = innerBundleInfo.GetDependencies();
1753     for (const auto &item : dependencies) {
1754         BaseSharedBundleInfo baseSharedBundleInfo;
1755         if (GetBaseSharedBundleInfo(item, baseSharedBundleInfo)) {
1756             baseSharedBundleInfos.emplace_back(baseSharedBundleInfo);
1757         }
1758     }
1759     APP_LOGD("GetBaseSharedBundleInfos(%{public}s) successfully", bundleName.c_str());
1760     return ERR_OK;
1761 }
1762 
GetBaseSharedBundleInfo(const Dependency & dependency,BaseSharedBundleInfo & baseSharedBundleInfo) const1763 bool BundleDataMgr::GetBaseSharedBundleInfo(const Dependency &dependency,
1764     BaseSharedBundleInfo &baseSharedBundleInfo) const
1765 {
1766     auto infoItem = bundleInfos_.find(dependency.bundleName);
1767     if (infoItem == bundleInfos_.end()) {
1768         APP_LOGE("GetBaseSharedBundleInfo failed, can not find dependency bundle %{public}s",
1769             dependency.bundleName.c_str());
1770         return false;
1771     }
1772     const InnerBundleInfo &innerBundleInfo = infoItem->second;
1773     if (innerBundleInfo.GetApplicationBundleType() == BundleType::SHARED) {
1774         innerBundleInfo.GetMaxVerBaseSharedBundleInfo(dependency.moduleName, baseSharedBundleInfo);
1775     } else {
1776         APP_LOGE("GetBaseSharedBundleInfo failed, can not find bundleType %{public}d",
1777             innerBundleInfo.GetApplicationBundleType());
1778         return false;
1779     }
1780     APP_LOGD("GetBaseSharedBundleInfo(%{public}s) successfully)", dependency.bundleName.c_str());
1781     return true;
1782 }
1783 
DeleteSharedBundleInfo(const std::string & bundleName)1784 bool BundleDataMgr::DeleteSharedBundleInfo(const std::string &bundleName)
1785 {
1786     auto infoItem = bundleInfos_.find(bundleName);
1787     if (infoItem != bundleInfos_.end()) {
1788         APP_LOGD("del bundle name:%{public}s", bundleName.c_str());
1789         const InnerBundleInfo &innerBundleInfo = infoItem->second;
1790         bool ret = dataStorage_->DeleteStorageBundleInfo(innerBundleInfo);
1791         if (!ret) {
1792             APP_LOGW("delete storage error name:%{public}s", bundleName.c_str());
1793         }
1794         bundleInfos_.erase(bundleName);
1795         return ret;
1796     }
1797     return false;
1798 }
1799 
GetBundlePackInfo(const std::string & bundleName,int32_t flags,BundlePackInfo & bundlePackInfo,int32_t userId) const1800 ErrCode BundleDataMgr::GetBundlePackInfo(
1801     const std::string &bundleName, int32_t flags, BundlePackInfo &bundlePackInfo, int32_t userId) const
1802 {
1803     APP_LOGD("Service BundleDataMgr GetBundlePackInfo start");
1804     int32_t requestUserId;
1805     if (userId == Constants::UNSPECIFIED_USERID) {
1806         requestUserId = GetUserIdByCallingUid();
1807     } else {
1808         requestUserId = userId;
1809     }
1810 
1811     if (requestUserId == Constants::INVALID_USERID) {
1812         APP_LOGE("getBundlePackInfo userId is invalid");
1813         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1814     }
1815     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1816     InnerBundleInfo innerBundleInfo;
1817     if (!GetInnerBundleInfoWithFlags(bundleName, flags, innerBundleInfo, requestUserId)) {
1818         APP_LOGE("GetBundlePackInfo failed, bundleName:%{public}s", bundleName.c_str());
1819         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
1820     }
1821     BundlePackInfo innerBundlePackInfo = innerBundleInfo.GetBundlePackInfo();
1822     if (static_cast<uint32_t>(flags) & GET_PACKAGES) {
1823         bundlePackInfo.packages = innerBundlePackInfo.packages;
1824         return ERR_OK;
1825     }
1826     if (static_cast<uint32_t>(flags) & GET_BUNDLE_SUMMARY) {
1827         bundlePackInfo.summary.app = innerBundlePackInfo.summary.app;
1828         bundlePackInfo.summary.modules = innerBundlePackInfo.summary.modules;
1829         return ERR_OK;
1830     }
1831     if (static_cast<uint32_t>(flags) & GET_MODULE_SUMMARY) {
1832         bundlePackInfo.summary.modules = innerBundlePackInfo.summary.modules;
1833         return ERR_OK;
1834     }
1835     bundlePackInfo = innerBundlePackInfo;
1836     return ERR_OK;
1837 }
1838 
GetBundleInfosByMetaData(const std::string & metaData,std::vector<BundleInfo> & bundleInfos) const1839 bool BundleDataMgr::GetBundleInfosByMetaData(
1840     const std::string &metaData, std::vector<BundleInfo> &bundleInfos) const
1841 {
1842     if (metaData.empty()) {
1843         APP_LOGE("bundle name is empty");
1844         return false;
1845     }
1846 
1847     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1848     if (bundleInfos_.empty()) {
1849         APP_LOGE("bundleInfos_ data is empty");
1850         return false;
1851     }
1852 
1853     bool find = false;
1854     int32_t requestUserId = GetUserId();
1855     for (const auto &item : bundleInfos_) {
1856         const InnerBundleInfo &info = item.second;
1857         if (info.IsDisabled()) {
1858             APP_LOGW("app %{public}s is disabled", info.GetBundleName().c_str());
1859             continue;
1860         }
1861         if (info.CheckSpecialMetaData(metaData)) {
1862             BundleInfo bundleInfo;
1863             int32_t responseUserId = info.GetResponseUserId(requestUserId);
1864             info.GetBundleInfo(
1865                 BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, responseUserId);
1866             bundleInfos.emplace_back(bundleInfo);
1867             find = true;
1868         }
1869     }
1870     return find;
1871 }
1872 
GetBundleList(std::vector<std::string> & bundleNames,int32_t userId) const1873 bool BundleDataMgr::GetBundleList(
1874     std::vector<std::string> &bundleNames, int32_t userId) const
1875 {
1876     int32_t requestUserId = GetUserId(userId);
1877     if (requestUserId == Constants::INVALID_USERID) {
1878         return false;
1879     }
1880 
1881     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1882     if (bundleInfos_.empty()) {
1883         APP_LOGE("bundleInfos_ data is empty");
1884         return false;
1885     }
1886 
1887     bool find = false;
1888     for (const auto &infoItem : bundleInfos_) {
1889         const InnerBundleInfo &innerBundleInfo = infoItem.second;
1890         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
1891         if (CheckInnerBundleInfoWithFlags(
1892             innerBundleInfo, BundleFlag::GET_BUNDLE_DEFAULT, responseUserId) != ERR_OK) {
1893             continue;
1894         }
1895 
1896         bundleNames.emplace_back(infoItem.first);
1897         find = true;
1898     }
1899     APP_LOGD("user(%{public}d) get installed bundles list result(%{public}d)", userId, find);
1900     return find;
1901 }
1902 
GetBundleInfos(int32_t flags,std::vector<BundleInfo> & bundleInfos,int32_t userId) const1903 bool BundleDataMgr::GetBundleInfos(
1904     int32_t flags, std::vector<BundleInfo> &bundleInfos, int32_t userId) const
1905 {
1906     if (userId == Constants::ALL_USERID) {
1907         return GetAllBundleInfos(flags, bundleInfos);
1908     }
1909 
1910     int32_t requestUserId = GetUserId(userId);
1911     if (requestUserId == Constants::INVALID_USERID) {
1912         return false;
1913     }
1914 
1915     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1916     if (bundleInfos_.empty()) {
1917         APP_LOGE("bundleInfos_ data is empty");
1918         return false;
1919     }
1920 
1921     bool find = false;
1922     for (const auto &item : bundleInfos_) {
1923         const InnerBundleInfo &innerBundleInfo = item.second;
1924         if (innerBundleInfo.GetApplicationBundleType() == BundleType::SHARED) {
1925             APP_LOGD("app %{public}s is cross-app shared bundle, ignore", innerBundleInfo.GetBundleName().c_str());
1926             continue;
1927         }
1928 
1929         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
1930         if (CheckInnerBundleInfoWithFlags(innerBundleInfo, flags, responseUserId) != ERR_OK) {
1931             continue;
1932         }
1933 
1934         BundleInfo bundleInfo;
1935         if (!innerBundleInfo.GetBundleInfo(flags, bundleInfo, responseUserId)) {
1936             continue;
1937         }
1938 
1939         bundleInfos.emplace_back(bundleInfo);
1940         find = true;
1941     }
1942 
1943     APP_LOGD("get bundleInfos result(%{public}d) in user(%{public}d).", find, userId);
1944     return find;
1945 }
1946 
CheckInnerBundleInfoWithFlags(const InnerBundleInfo & innerBundleInfo,const int32_t flags,int32_t userId) const1947 ErrCode BundleDataMgr::CheckInnerBundleInfoWithFlags(
1948     const InnerBundleInfo &innerBundleInfo, const int32_t flags, int32_t userId) const
1949 {
1950     if (userId == Constants::INVALID_USERID) {
1951         APP_LOGD("userId is invalid");
1952         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1953     }
1954 
1955     if (innerBundleInfo.IsDisabled()) {
1956         APP_LOGE("bundleName: %{public}s status is disabled", innerBundleInfo.GetBundleName().c_str());
1957         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
1958     }
1959 
1960     if (!(static_cast<uint32_t>(flags) & GET_APPLICATION_INFO_WITH_DISABLE)
1961         && !innerBundleInfo.GetApplicationEnabled(userId)) {
1962         APP_LOGE("bundleName: %{public}s is disabled", innerBundleInfo.GetBundleName().c_str());
1963         return ERR_BUNDLE_MANAGER_APPLICATION_DISABLED;
1964     }
1965 
1966     return ERR_OK;
1967 }
1968 
GetAllBundleInfos(int32_t flags,std::vector<BundleInfo> & bundleInfos) const1969 bool BundleDataMgr::GetAllBundleInfos(int32_t flags, std::vector<BundleInfo> &bundleInfos) const
1970 {
1971     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1972     if (bundleInfos_.empty()) {
1973         APP_LOGE("bundleInfos_ data is empty");
1974         return false;
1975     }
1976 
1977     bool find = false;
1978     for (const auto &item : bundleInfos_) {
1979         const InnerBundleInfo &info = item.second;
1980         if (info.IsDisabled()) {
1981             APP_LOGW("app %{public}s is disabled", info.GetBundleName().c_str());
1982             continue;
1983         }
1984         if (info.GetApplicationBundleType() == BundleType::SHARED) {
1985             APP_LOGD("app %{public}s is cross-app shared bundle, ignore", info.GetBundleName().c_str());
1986             continue;
1987         }
1988         BundleInfo bundleInfo;
1989         info.GetBundleInfo(flags, bundleInfo, Constants::ALL_USERID);
1990         bundleInfos.emplace_back(bundleInfo);
1991         find = true;
1992     }
1993 
1994     APP_LOGD("get all bundleInfos result(%{public}d).", find);
1995     return find;
1996 }
1997 
GetBundleInfosV9(int32_t flags,std::vector<BundleInfo> & bundleInfos,int32_t userId) const1998 ErrCode BundleDataMgr::GetBundleInfosV9(int32_t flags, std::vector<BundleInfo> &bundleInfos, int32_t userId) const
1999 {
2000     if (userId == Constants::ALL_USERID) {
2001         return GetAllBundleInfosV9(flags, bundleInfos);
2002     }
2003 
2004     int32_t requestUserId = GetUserId(userId);
2005     if (requestUserId == Constants::INVALID_USERID) {
2006         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
2007     }
2008 
2009     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2010     if (bundleInfos_.empty()) {
2011         APP_LOGE("bundleInfos_ data is empty");
2012         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2013     }
2014 
2015     for (const auto &item : bundleInfos_) {
2016         const InnerBundleInfo &innerBundleInfo = item.second;
2017         if (innerBundleInfo.GetApplicationBundleType() == BundleType::SHARED) {
2018             APP_LOGD("app %{public}s is cross-app shared bundle, ignore", innerBundleInfo.GetBundleName().c_str());
2019             continue;
2020         }
2021 
2022         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2023         auto flag = GET_BASIC_APPLICATION_INFO;
2024         if ((static_cast<uint32_t>(flags) & static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE))
2025             == static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE)) {
2026             flag = GET_APPLICATION_INFO_WITH_DISABLE;
2027         }
2028         if (CheckInnerBundleInfoWithFlags(innerBundleInfo, flag, responseUserId) != ERR_OK) {
2029             continue;
2030         }
2031 
2032         BundleInfo bundleInfo;
2033         if (innerBundleInfo.GetBundleInfoV9(flags, bundleInfo, responseUserId) != ERR_OK) {
2034             continue;
2035         }
2036 
2037         bundleInfos.emplace_back(bundleInfo);
2038     }
2039     return ERR_OK;
2040 }
2041 
GetAllBundleInfosV9(int32_t flags,std::vector<BundleInfo> & bundleInfos) const2042 ErrCode BundleDataMgr::GetAllBundleInfosV9(int32_t flags, std::vector<BundleInfo> &bundleInfos) const
2043 {
2044     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2045     if (bundleInfos_.empty()) {
2046         APP_LOGE("bundleInfos_ data is empty");
2047         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2048     }
2049 
2050     for (const auto &item : bundleInfos_) {
2051         const InnerBundleInfo &info = item.second;
2052         if (info.IsDisabled()) {
2053             APP_LOGW("app %{public}s is disabled", info.GetBundleName().c_str());
2054             continue;
2055         }
2056         if (info.GetApplicationBundleType() == BundleType::SHARED) {
2057             APP_LOGD("app %{public}s is cross-app shared bundle, ignore", info.GetBundleName().c_str());
2058             continue;
2059         }
2060         BundleInfo bundleInfo;
2061         info.GetBundleInfoV9(flags, bundleInfo, Constants::ALL_USERID);
2062         bundleInfos.emplace_back(bundleInfo);
2063     }
2064     return ERR_OK;
2065 }
2066 
GetBundleNameForUid(const int uid,std::string & bundleName) const2067 bool BundleDataMgr::GetBundleNameForUid(const int uid, std::string &bundleName) const
2068 {
2069     InnerBundleInfo innerBundleInfo;
2070     APP_LOGD("GetBundleNameForUid, uid %{public}d, bundleName %{public}s", uid, bundleName.c_str());
2071     if (GetInnerBundleInfoByUid(uid, innerBundleInfo) != ERR_OK) {
2072         if (sandboxAppHelper_ == nullptr) {
2073             return false;
2074         }
2075         if (sandboxAppHelper_->GetInnerBundleInfoByUid(uid, innerBundleInfo) != ERR_OK) {
2076             return false;
2077         }
2078     }
2079 
2080     bundleName = innerBundleInfo.GetBundleName();
2081     return true;
2082 }
2083 
GetInnerBundleInfoByUid(const int uid,InnerBundleInfo & innerBundleInfo) const2084 ErrCode BundleDataMgr::GetInnerBundleInfoByUid(const int uid, InnerBundleInfo &innerBundleInfo) const
2085 {
2086     int32_t userId = GetUserIdByUid(uid);
2087     if (userId == Constants::UNSPECIFIED_USERID || userId == Constants::INVALID_USERID) {
2088         APP_LOGE("the uid %{public}d is illegal when get bundleName by uid.", uid);
2089         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2090     }
2091 
2092     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2093     if (bundleInfos_.empty()) {
2094         APP_LOGE("bundleInfos_ data is empty");
2095         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2096     }
2097 
2098     for (const auto &item : bundleInfos_) {
2099         const InnerBundleInfo &info = item.second;
2100         if (info.IsDisabled()) {
2101             APP_LOGW("app %{public}s is disabled", info.GetBundleName().c_str());
2102             continue;
2103         }
2104         if (info.GetUid(userId) == uid) {
2105             innerBundleInfo = info;
2106             return ERR_OK;
2107         }
2108     }
2109 
2110     APP_LOGD("the uid(%{public}d) is not exists.", uid);
2111     return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2112 }
2113 
HasUserInstallInBundle(const std::string & bundleName,const int32_t userId) const2114 bool BundleDataMgr::HasUserInstallInBundle(
2115     const std::string &bundleName, const int32_t userId) const
2116 {
2117     auto infoItem = bundleInfos_.find(bundleName);
2118     if (infoItem == bundleInfos_.end()) {
2119         return false;
2120     }
2121 
2122     return infoItem->second.HasInnerBundleUserInfo(userId);
2123 }
2124 
GetBundleStats(const std::string & bundleName,const int32_t userId,std::vector<int64_t> & bundleStats) const2125 bool BundleDataMgr::GetBundleStats(
2126     const std::string &bundleName, const int32_t userId, std::vector<int64_t> &bundleStats) const
2127 {
2128     auto infoItem = bundleInfos_.find(bundleName);
2129     if (infoItem == bundleInfos_.end()) {
2130         return false;
2131     }
2132     int32_t responseUserId = infoItem->second.GetResponseUserId(userId);
2133     if (InstalldClient::GetInstance()->GetBundleStats(bundleName, responseUserId, bundleStats) != ERR_OK) {
2134         APP_LOGE("bundle%{public}s GetBundleStats failed ", bundleName.c_str());
2135         return false;
2136     }
2137     if (infoItem->second.IsPreInstallApp() && !bundleStats.empty()) {
2138         for (const auto &innerModuleInfo : infoItem->second.GetInnerModuleInfos()) {
2139             bundleStats[0] += BundleUtil::GetFileSize(innerModuleInfo.second.hapPath);
2140         }
2141     }
2142     return true;
2143 }
2144 
2145 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
GetBundleSpaceSize(const std::string & bundleName) const2146 int64_t BundleDataMgr::GetBundleSpaceSize(const std::string &bundleName) const
2147 {
2148     return GetBundleSpaceSize(bundleName, AccountHelper::GetCurrentActiveUserId());
2149 }
2150 
GetBundleSpaceSize(const std::string & bundleName,int32_t userId) const2151 int64_t BundleDataMgr::GetBundleSpaceSize(const std::string &bundleName, int32_t userId) const
2152 {
2153     int64_t spaceSize = 0;
2154     if (userId != Constants::ALL_USERID) {
2155         std::vector<int64_t> bundleStats;
2156         if (!GetBundleStats(bundleName, userId, bundleStats) || bundleStats.empty()) {
2157             APP_LOGE("GetBundleStats: bundleName: %{public}s failed", bundleName.c_str());
2158             return spaceSize;
2159         }
2160 
2161         spaceSize = std::accumulate(bundleStats.begin(), bundleStats.end(), spaceSize);
2162         return spaceSize;
2163     }
2164 
2165     for (const auto &iterUserId : GetAllUser()) {
2166         std::vector<int64_t> bundleStats;
2167         if (!GetBundleStats(bundleName, iterUserId, bundleStats) || bundleStats.empty()) {
2168             APP_LOGE("GetBundleStats: bundleName: %{public}s failed", bundleName.c_str());
2169             continue;
2170         }
2171 
2172         auto startIter = bundleStats.begin();
2173         auto endIter = bundleStats.end();
2174         if (spaceSize == 0) {
2175             spaceSize = std::accumulate(startIter, endIter, spaceSize);
2176         } else {
2177             spaceSize = std::accumulate(++startIter, endIter, spaceSize);
2178         }
2179     }
2180 
2181     return spaceSize;
2182 }
2183 
GetAllFreeInstallBundleSpaceSize() const2184 int64_t BundleDataMgr::GetAllFreeInstallBundleSpaceSize() const
2185 {
2186     int64_t allSize = 0;
2187     std::map<std::string, std::vector<std::string>> freeInstallModules;
2188     if (!GetFreeInstallModules(freeInstallModules)) {
2189         APP_LOGE("no removable bundles");
2190         return allSize;
2191     }
2192 
2193     for (const auto &iter : freeInstallModules) {
2194         APP_LOGD("%{public}s is freeInstall bundle", iter.first.c_str());
2195         allSize += GetBundleSpaceSize(iter.first, Constants::ALL_USERID);
2196     }
2197 
2198     APP_LOGI("All freeInstall app size:%{public}" PRId64, allSize);
2199     return allSize;
2200 }
2201 
GetFreeInstallModules(std::map<std::string,std::vector<std::string>> & freeInstallModules) const2202 bool BundleDataMgr::GetFreeInstallModules(
2203     std::map<std::string, std::vector<std::string>> &freeInstallModules) const
2204 {
2205     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2206     if (bundleInfos_.empty()) {
2207         APP_LOGE("bundleInfos_ is data is empty.");
2208         return false;
2209     }
2210 
2211     for (const auto &iter : bundleInfos_) {
2212         std::vector<std::string> modules;
2213         if (!iter.second.GetFreeInstallModules(modules)) {
2214             continue;
2215         }
2216 
2217         freeInstallModules.emplace(iter.first, modules);
2218     }
2219 
2220     return !freeInstallModules.empty();
2221 }
2222 #endif
2223 
GetBundlesForUid(const int uid,std::vector<std::string> & bundleNames) const2224 bool BundleDataMgr::GetBundlesForUid(const int uid, std::vector<std::string> &bundleNames) const
2225 {
2226     InnerBundleInfo innerBundleInfo;
2227     if (GetInnerBundleInfoByUid(uid, innerBundleInfo) != ERR_OK) {
2228         APP_LOGE("get innerBundleInfo by uid :%{public}d failed.", uid);
2229         return false;
2230     }
2231 
2232     bundleNames.emplace_back(innerBundleInfo.GetBundleName());
2233     return true;
2234 }
2235 
GetNameForUid(const int uid,std::string & name) const2236 ErrCode BundleDataMgr::GetNameForUid(const int uid, std::string &name) const
2237 {
2238     InnerBundleInfo innerBundleInfo;
2239     ErrCode ret = GetInnerBundleInfoByUid(uid, innerBundleInfo);
2240     if (ret != ERR_OK) {
2241         APP_LOGW("get innerBundleInfo from bundleInfo_ by uid failed.");
2242         if (sandboxAppHelper_ == nullptr) {
2243             APP_LOGE("sandboxAppHelper_ is nullptr");
2244             return ERR_BUNDLE_MANAGER_INVALID_UID;
2245         }
2246         if (sandboxAppHelper_->GetInnerBundleInfoByUid(uid, innerBundleInfo) != ERR_OK) {
2247             return ERR_BUNDLE_MANAGER_INVALID_UID;
2248         }
2249     }
2250 
2251     name = innerBundleInfo.GetBundleName();
2252     return ERR_OK;
2253 }
2254 
GetBundleGids(const std::string & bundleName,std::vector<int> & gids) const2255 bool BundleDataMgr::GetBundleGids(const std::string &bundleName, std::vector<int> &gids) const
2256 {
2257     int32_t requestUserId = GetUserId();
2258     InnerBundleUserInfo innerBundleUserInfo;
2259     if (!GetInnerBundleUserInfoByUserId(bundleName, requestUserId, innerBundleUserInfo)) {
2260         APP_LOGE("the user(%{public}d) is not exists in bundleName(%{public}s) .",
2261             requestUserId, bundleName.c_str());
2262         return false;
2263     }
2264 
2265     gids = innerBundleUserInfo.gids;
2266     return true;
2267 }
2268 
GetBundleGidsByUid(const std::string & bundleName,const int & uid,std::vector<int> & gids) const2269 bool BundleDataMgr::GetBundleGidsByUid(
2270     const std::string &bundleName, const int &uid, std::vector<int> &gids) const
2271 {
2272     return true;
2273 }
2274 
QueryKeepAliveBundleInfos(std::vector<BundleInfo> & bundleInfos) const2275 bool BundleDataMgr::QueryKeepAliveBundleInfos(std::vector<BundleInfo> &bundleInfos) const
2276 {
2277     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2278     if (bundleInfos_.empty()) {
2279         APP_LOGE("bundleInfos_ data is empty");
2280         return false;
2281     }
2282 
2283     int32_t requestUserId = GetUserId();
2284     for (const auto &info : bundleInfos_) {
2285         if (info.second.IsDisabled()) {
2286             APP_LOGW("app %{public}s is disabled", info.second.GetBundleName().c_str());
2287             continue;
2288         }
2289         if (info.second.GetIsKeepAlive()) {
2290             BundleInfo bundleInfo;
2291             int32_t responseUserId = info.second.GetResponseUserId(requestUserId);
2292             info.second.GetBundleInfo(BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, responseUserId);
2293             if (bundleInfo.name == "") {
2294                 continue;
2295             }
2296             bundleInfos.emplace_back(bundleInfo);
2297         }
2298     }
2299     return !(bundleInfos.empty());
2300 }
2301 
GetAbilityLabel(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,std::string & label) const2302 ErrCode BundleDataMgr::GetAbilityLabel(const std::string &bundleName, const std::string &moduleName,
2303     const std::string &abilityName, std::string &label) const
2304 {
2305 #ifdef GLOBAL_RESMGR_ENABLE
2306     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2307     int32_t requestUserId = GetUserId();
2308     if (requestUserId == Constants::INVALID_USERID) {
2309         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
2310     }
2311     InnerBundleInfo innerBundleInfo;
2312     ErrCode ret =
2313         GetInnerBundleInfoWithFlagsV9(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, innerBundleInfo, requestUserId);
2314     if (ret != ERR_OK) {
2315         return ret;
2316     }
2317     AbilityInfo abilityInfo;
2318     ret = FindAbilityInfoInBundleInfo(innerBundleInfo, moduleName, abilityName, abilityInfo);
2319     if (ret != ERR_OK) {
2320         APP_LOGE("Find ability failed. bundleName: %{public}s, moduleName: %{public}s, abilityName: %{public}s",
2321             bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
2322         return ret;
2323     }
2324     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2325     bool isEnable = false;
2326     ret = innerBundleInfo.IsAbilityEnabledV9(abilityInfo, responseUserId, isEnable);
2327     if (ret != ERR_OK) {
2328         return ret;
2329     }
2330     if (!isEnable) {
2331         APP_LOGE("%{public}s ability disabled: %{public}s", bundleName.c_str(), abilityName.c_str());
2332         return ERR_BUNDLE_MANAGER_ABILITY_DISABLED;
2333     }
2334     if (abilityInfo.labelId == 0) {
2335         label = abilityInfo.label;
2336         return ERR_OK;
2337     }
2338     std::shared_ptr<OHOS::Global::Resource::ResourceManager> resourceManager =
2339         GetResourceManager(bundleName, abilityInfo.moduleName, responseUserId);
2340     if (resourceManager == nullptr) {
2341         APP_LOGE("InitResourceManager failed");
2342         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2343     }
2344     auto state = resourceManager->GetStringById(static_cast<uint32_t>(abilityInfo.labelId), label);
2345     if (state != OHOS::Global::Resource::RState::SUCCESS) {
2346         APP_LOGE("ResourceManager GetStringById failed");
2347         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2348     }
2349     return ERR_OK;
2350 #else
2351     APP_LOGW("GLOBAL_RES_MGR_ENABLE is false");
2352     return ERR_BUNDLE_MANAGER_GLOBAL_RES_MGR_ENABLE_DISABLED;
2353 #endif
2354 }
2355 
GetHapModuleInfo(const AbilityInfo & abilityInfo,HapModuleInfo & hapModuleInfo,int32_t userId) const2356 bool BundleDataMgr::GetHapModuleInfo(
2357     const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo, int32_t userId) const
2358 {
2359     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2360     int32_t requestUserId = GetUserId(userId);
2361     if (requestUserId == Constants::INVALID_USERID) {
2362         return false;
2363     }
2364 
2365     if (bundleInfos_.empty()) {
2366         APP_LOGE("bundleInfos_ data is empty");
2367         return false;
2368     }
2369 
2370     APP_LOGD("GetHapModuleInfo bundleName: %{public}s", abilityInfo.bundleName.c_str());
2371     auto infoItem = bundleInfos_.find(abilityInfo.bundleName);
2372     if (infoItem == bundleInfos_.end()) {
2373         return false;
2374     }
2375 
2376     const InnerBundleInfo &innerBundleInfo = infoItem->second;
2377     if (innerBundleInfo.IsDisabled()) {
2378         APP_LOGE("app %{public}s is disabled", innerBundleInfo.GetBundleName().c_str());
2379         return false;
2380     }
2381 
2382     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2383     auto module = innerBundleInfo.FindHapModuleInfo(abilityInfo.package, responseUserId);
2384     if (!module) {
2385         APP_LOGE("can not find module %{public}s, bundleName:%{public}s", abilityInfo.package.c_str(),
2386             abilityInfo.bundleName.c_str());
2387         return false;
2388     }
2389     hapModuleInfo = *module;
2390     return true;
2391 }
2392 
GetLaunchWantForBundle(const std::string & bundleName,Want & want,int32_t userId) const2393 ErrCode BundleDataMgr::GetLaunchWantForBundle(
2394     const std::string &bundleName, Want &want, int32_t userId) const
2395 {
2396     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2397     InnerBundleInfo innerBundleInfo;
2398     ErrCode ret = GetInnerBundleInfoWithFlagsV9(
2399         bundleName, BundleFlag::GET_BUNDLE_DEFAULT, innerBundleInfo, userId);
2400     if (ret != ERR_OK) {
2401         APP_LOGE("GetInnerBundleInfoWithFlagsV9 failed, bundleName:%{public}s", bundleName.c_str());
2402         return ret;
2403     }
2404 
2405     std::string mainAbility = innerBundleInfo.GetMainAbility();
2406     if (mainAbility.empty()) {
2407         APP_LOGE("no main ability in the bundle %{public}s", bundleName.c_str());
2408         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2409     }
2410 
2411     want.SetElementName("", bundleName, mainAbility);
2412     want.SetAction(Constants::ACTION_HOME);
2413     want.AddEntity(Constants::ENTITY_HOME);
2414     return ERR_OK;
2415 }
2416 
CheckIsSystemAppByUid(const int uid) const2417 bool BundleDataMgr::CheckIsSystemAppByUid(const int uid) const
2418 {
2419     // If the value of uid is 0 (ROOT_UID) or 1000 (BMS_UID),
2420     // the uid should be the system uid.
2421     if (uid == Constants::ROOT_UID || uid == Constants::BMS_UID) {
2422         return true;
2423     }
2424 
2425     InnerBundleInfo innerBundleInfo;
2426     if (GetInnerBundleInfoByUid(uid, innerBundleInfo) != ERR_OK) {
2427         return false;
2428     }
2429 
2430     return innerBundleInfo.IsSystemApp();
2431 }
2432 
InitStateTransferMap()2433 void BundleDataMgr::InitStateTransferMap()
2434 {
2435     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::INSTALL_START);
2436     transferStates_.emplace(InstallState::INSTALL_FAIL, InstallState::INSTALL_START);
2437     transferStates_.emplace(InstallState::UNINSTALL_START, InstallState::INSTALL_SUCCESS);
2438     transferStates_.emplace(InstallState::UNINSTALL_START, InstallState::INSTALL_START);
2439     transferStates_.emplace(InstallState::UNINSTALL_START, InstallState::UPDATING_SUCCESS);
2440     transferStates_.emplace(InstallState::UNINSTALL_FAIL, InstallState::UNINSTALL_START);
2441     transferStates_.emplace(InstallState::UNINSTALL_SUCCESS, InstallState::UNINSTALL_START);
2442     transferStates_.emplace(InstallState::UPDATING_START, InstallState::INSTALL_SUCCESS);
2443     transferStates_.emplace(InstallState::UPDATING_SUCCESS, InstallState::UPDATING_START);
2444     transferStates_.emplace(InstallState::UPDATING_FAIL, InstallState::UPDATING_START);
2445     transferStates_.emplace(InstallState::UPDATING_FAIL, InstallState::INSTALL_START);
2446     transferStates_.emplace(InstallState::UPDATING_START, InstallState::INSTALL_START);
2447     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::UPDATING_START);
2448     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::UPDATING_SUCCESS);
2449     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::UNINSTALL_START);
2450     transferStates_.emplace(InstallState::UPDATING_START, InstallState::UPDATING_SUCCESS);
2451     transferStates_.emplace(InstallState::ROLL_BACK, InstallState::UPDATING_START);
2452     transferStates_.emplace(InstallState::ROLL_BACK, InstallState::UPDATING_SUCCESS);
2453     transferStates_.emplace(InstallState::UPDATING_FAIL, InstallState::UPDATING_SUCCESS);
2454     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::ROLL_BACK);
2455     transferStates_.emplace(InstallState::UNINSTALL_START, InstallState::USER_CHANGE);
2456     transferStates_.emplace(InstallState::UPDATING_START, InstallState::USER_CHANGE);
2457     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::USER_CHANGE);
2458     transferStates_.emplace(InstallState::UPDATING_SUCCESS, InstallState::USER_CHANGE);
2459     transferStates_.emplace(InstallState::USER_CHANGE, InstallState::INSTALL_SUCCESS);
2460     transferStates_.emplace(InstallState::USER_CHANGE, InstallState::UPDATING_SUCCESS);
2461     transferStates_.emplace(InstallState::USER_CHANGE, InstallState::UPDATING_START);
2462 }
2463 
IsDeleteDataState(const InstallState state) const2464 bool BundleDataMgr::IsDeleteDataState(const InstallState state) const
2465 {
2466     return (state == InstallState::INSTALL_FAIL || state == InstallState::UNINSTALL_FAIL ||
2467             state == InstallState::UNINSTALL_SUCCESS || state == InstallState::UPDATING_FAIL);
2468 }
2469 
IsDisableState(const InstallState state) const2470 bool BundleDataMgr::IsDisableState(const InstallState state) const
2471 {
2472     if (state == InstallState::UPDATING_START || state == InstallState::UNINSTALL_START) {
2473         return true;
2474     }
2475     return false;
2476 }
2477 
DeleteBundleInfo(const std::string & bundleName,const InstallState state)2478 void BundleDataMgr::DeleteBundleInfo(const std::string &bundleName, const InstallState state)
2479 {
2480     if (InstallState::INSTALL_FAIL == state) {
2481         APP_LOGW("del fail, bundle:%{public}s has no installed info", bundleName.c_str());
2482         return;
2483     }
2484 
2485     auto infoItem = bundleInfos_.find(bundleName);
2486     if (infoItem == bundleInfos_.end()) {
2487         APP_LOGW("create infoItem fail, bundleName:%{public}s", bundleName.c_str());
2488         return;
2489     }
2490 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
2491     // remove external overlay bundle info and connection
2492     RemoveOverlayInfoAndConnection(infoItem->second, bundleName);
2493 #endif
2494     APP_LOGD("del bundle name:%{public}s", bundleName.c_str());
2495     const InnerBundleInfo &innerBundleInfo = infoItem->second;
2496     RecycleUidAndGid(innerBundleInfo);
2497     bool ret = dataStorage_->DeleteStorageBundleInfo(innerBundleInfo);
2498     if (!ret) {
2499         APP_LOGW("delete storage error name:%{public}s", bundleName.c_str());
2500     }
2501     bundleInfos_.erase(bundleName);
2502 }
2503 
IsAppOrAbilityInstalled(const std::string & bundleName) const2504 bool BundleDataMgr::IsAppOrAbilityInstalled(const std::string &bundleName) const
2505 {
2506     if (bundleName.empty()) {
2507         APP_LOGW("IsAppOrAbilityInstalled bundleName empty");
2508         return false;
2509     }
2510 
2511     std::lock_guard<std::mutex> lock(stateMutex_);
2512     auto statusItem = installStates_.find(bundleName);
2513     if (statusItem == installStates_.end()) {
2514         APP_LOGW("name:%{public}s not find", bundleName.c_str());
2515         return false;
2516     }
2517 
2518     if (statusItem->second == InstallState::INSTALL_SUCCESS) {
2519         return true;
2520     }
2521 
2522     APP_LOGW("name:%{public}s not install success", bundleName.c_str());
2523     return false;
2524 }
2525 
GetInnerBundleInfoWithFlags(const std::string & bundleName,const int32_t flags,InnerBundleInfo & info,int32_t userId) const2526 bool BundleDataMgr::GetInnerBundleInfoWithFlags(const std::string &bundleName,
2527     const int32_t flags, InnerBundleInfo &info, int32_t userId) const
2528 {
2529     int32_t requestUserId = GetUserId(userId);
2530     if (requestUserId == Constants::INVALID_USERID) {
2531         return false;
2532     }
2533 
2534     if (bundleInfos_.empty()) {
2535         APP_LOGE("bundleInfos_ data is empty");
2536         return false;
2537     }
2538     APP_LOGD("GetInnerBundleInfoWithFlags: %{public}s", bundleName.c_str());
2539     auto item = bundleInfos_.find(bundleName);
2540     if (item == bundleInfos_.end()) {
2541         APP_LOGE("GetInnerBundleInfoWithFlags: bundleName %{public}s not find", bundleName.c_str());
2542         return false;
2543     }
2544     const InnerBundleInfo &innerBundleInfo = item->second;
2545     if (innerBundleInfo.IsDisabled()) {
2546         APP_LOGE("bundleName: %{public}s status is disabled", innerBundleInfo.GetBundleName().c_str());
2547         return false;
2548     }
2549 
2550     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2551     if (!(static_cast<uint32_t>(flags) & GET_APPLICATION_INFO_WITH_DISABLE)
2552         && !innerBundleInfo.GetApplicationEnabled(responseUserId)) {
2553         APP_LOGE("bundleName: %{public}s is disabled", innerBundleInfo.GetBundleName().c_str());
2554         return false;
2555     }
2556     info = innerBundleInfo;
2557     return true;
2558 }
2559 
GetInnerBundleInfoWithFlagsV9(const std::string & bundleName,const int32_t flags,InnerBundleInfo & info,int32_t userId) const2560 ErrCode BundleDataMgr::GetInnerBundleInfoWithFlagsV9(const std::string &bundleName,
2561     const int32_t flags, InnerBundleInfo &info, int32_t userId) const
2562 {
2563     int32_t requestUserId = GetUserId(userId);
2564     if (requestUserId == Constants::INVALID_USERID) {
2565         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
2566     }
2567 
2568     if (bundleInfos_.empty()) {
2569         APP_LOGE("bundleInfos_ data is empty");
2570         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2571     }
2572     APP_LOGD("GetInnerBundleInfoWithFlagsV9: %{public}s", bundleName.c_str());
2573     auto item = bundleInfos_.find(bundleName);
2574     if (item == bundleInfos_.end()) {
2575         APP_LOGE("GetInnerBundleInfoWithFlagsV9: bundleName %{public}s not find", bundleName.c_str());
2576         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2577     }
2578     const InnerBundleInfo &innerBundleInfo = item->second;
2579     if (innerBundleInfo.IsDisabled()) {
2580         APP_LOGE("bundleName: %{public}s status is disabled", innerBundleInfo.GetBundleName().c_str());
2581         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2582     }
2583 
2584     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2585     bool isEnabled;
2586     auto ret = innerBundleInfo.GetApplicationEnabledV9(responseUserId, isEnabled);
2587     if (ret != ERR_OK) {
2588         return ret;
2589     }
2590     if (!(static_cast<uint32_t>(flags) & static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_DISABLE))
2591         && !isEnabled) {
2592         APP_LOGE("bundleName: %{public}s is disabled", innerBundleInfo.GetBundleName().c_str());
2593         return ERR_BUNDLE_MANAGER_APPLICATION_DISABLED;
2594     }
2595     info = innerBundleInfo;
2596     return ERR_OK;
2597 }
2598 
GetInnerBundleInfoWithBundleFlagsV9(const std::string & bundleName,const int32_t flags,InnerBundleInfo & info,int32_t userId) const2599 ErrCode BundleDataMgr::GetInnerBundleInfoWithBundleFlagsV9(const std::string &bundleName,
2600     const int32_t flags, InnerBundleInfo &info, int32_t userId) const
2601 {
2602     int32_t requestUserId = GetUserId(userId);
2603     if (requestUserId == Constants::INVALID_USERID) {
2604         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
2605     }
2606 
2607     if (bundleInfos_.empty()) {
2608         APP_LOGE("bundleInfos_ data is empty, bundleName: %{public}s", bundleName.c_str());
2609         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2610     }
2611     APP_LOGD("GetInnerBundleInfoWithFlagsV9: %{public}s", bundleName.c_str());
2612     auto item = bundleInfos_.find(bundleName);
2613     if (item == bundleInfos_.end()) {
2614         APP_LOGE("GetInnerBundleInfoWithFlagsV9: bundleName %{public}s not find", bundleName.c_str());
2615         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2616     }
2617     const InnerBundleInfo &innerBundleInfo = item->second;
2618     if (innerBundleInfo.IsDisabled()) {
2619         APP_LOGE("bundleName: %{public}s status is disabled", innerBundleInfo.GetBundleName().c_str());
2620         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2621     }
2622 
2623     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2624     bool isEnabled;
2625     auto ret = innerBundleInfo.GetApplicationEnabledV9(responseUserId, isEnabled);
2626     if (ret != ERR_OK) {
2627         return ret;
2628     }
2629     if (!(static_cast<uint32_t>(flags) & static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE))
2630         && !isEnabled) {
2631         APP_LOGE("bundleName: %{public}s is disabled", innerBundleInfo.GetBundleName().c_str());
2632         return ERR_BUNDLE_MANAGER_APPLICATION_DISABLED;
2633     }
2634     info = innerBundleInfo;
2635     return ERR_OK;
2636 }
2637 
GetInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & info)2638 bool BundleDataMgr::GetInnerBundleInfo(const std::string &bundleName, InnerBundleInfo &info)
2639 {
2640     APP_LOGD("GetInnerBundleInfo %{public}s", bundleName.c_str());
2641     if (bundleName.empty()) {
2642         APP_LOGE("bundleName is empty");
2643         return false;
2644     }
2645 
2646     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2647     auto infoItem = bundleInfos_.find(bundleName);
2648     if (infoItem == bundleInfos_.end()) {
2649         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2650         return false;
2651     }
2652     infoItem->second.SetBundleStatus(InnerBundleInfo::BundleStatus::DISABLED);
2653     info = infoItem->second;
2654     info.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
2655     return true;
2656 }
2657 
DisableBundle(const std::string & bundleName)2658 bool BundleDataMgr::DisableBundle(const std::string &bundleName)
2659 {
2660     APP_LOGD("DisableBundle %{public}s", bundleName.c_str());
2661     if (bundleName.empty()) {
2662         APP_LOGE("bundleName empty");
2663         return false;
2664     }
2665 
2666     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2667     auto infoItem = bundleInfos_.find(bundleName);
2668     if (infoItem == bundleInfos_.end()) {
2669         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2670         return false;
2671     }
2672     infoItem->second.SetBundleStatus(InnerBundleInfo::BundleStatus::DISABLED);
2673     return true;
2674 }
2675 
EnableBundle(const std::string & bundleName)2676 bool BundleDataMgr::EnableBundle(const std::string &bundleName)
2677 {
2678     APP_LOGD("EnableBundle %{public}s", bundleName.c_str());
2679     if (bundleName.empty()) {
2680         APP_LOGE("bundleName empty");
2681         return false;
2682     }
2683 
2684     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2685     auto infoItem = bundleInfos_.find(bundleName);
2686     if (infoItem == bundleInfos_.end()) {
2687         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2688         return false;
2689     }
2690     infoItem->second.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
2691     return true;
2692 }
2693 
IsApplicationEnabled(const std::string & bundleName,bool & isEnabled) const2694 ErrCode BundleDataMgr::IsApplicationEnabled(const std::string &bundleName, bool &isEnabled) const
2695 {
2696     APP_LOGD("IsApplicationEnabled %{public}s", bundleName.c_str());
2697     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2698     auto infoItem = bundleInfos_.find(bundleName);
2699     if (infoItem == bundleInfos_.end()) {
2700         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2701         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2702     }
2703     int32_t responseUserId = infoItem->second.GetResponseUserId(GetUserId());
2704     ErrCode ret = infoItem->second.GetApplicationEnabledV9(responseUserId, isEnabled);
2705     if (ret != ERR_OK) {
2706         APP_LOGE("GetApplicationEnabled failed: %{public}s", bundleName.c_str());
2707     }
2708     return ret;
2709 }
2710 
SetApplicationEnabled(const std::string & bundleName,bool isEnable,int32_t userId)2711 ErrCode BundleDataMgr::SetApplicationEnabled(const std::string &bundleName, bool isEnable, int32_t userId)
2712 {
2713     APP_LOGD("SetApplicationEnabled %{public}s", bundleName.c_str());
2714     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2715     int32_t requestUserId = GetUserId(userId);
2716     if (requestUserId == Constants::INVALID_USERID) {
2717         APP_LOGE("Request userId is invalid, bundleName:%{public}s", bundleName.c_str());
2718         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2719     }
2720     auto infoItem = bundleInfos_.find(bundleName);
2721     if (infoItem == bundleInfos_.end()) {
2722         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2723         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2724     }
2725 
2726     InnerBundleInfo& newInfo = infoItem->second;
2727     auto ret = newInfo.SetApplicationEnabled(isEnable, requestUserId);
2728     if (ret != ERR_OK) {
2729         return ret;
2730     }
2731     InnerBundleUserInfo innerBundleUserInfo;
2732     if (!newInfo.GetInnerBundleUserInfo(requestUserId, innerBundleUserInfo)) {
2733         APP_LOGE("can not find bundleUserInfo in userId: %{public}d", requestUserId);
2734         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2735     }
2736 
2737     if (innerBundleUserInfo.bundleUserInfo.IsInitialState()) {
2738         bundleStateStorage_->DeleteBundleState(bundleName, requestUserId);
2739     } else {
2740         bundleStateStorage_->SaveBundleStateStorage(
2741             bundleName, requestUserId, innerBundleUserInfo.bundleUserInfo);
2742     }
2743     return ERR_OK;
2744 }
2745 
SetModuleRemovable(const std::string & bundleName,const std::string & moduleName,bool isEnable)2746 bool BundleDataMgr::SetModuleRemovable(const std::string &bundleName, const std::string &moduleName, bool isEnable)
2747 {
2748     if (bundleName.empty() || moduleName.empty()) {
2749         APP_LOGE("bundleName or moduleName is empty");
2750         return false;
2751     }
2752     int32_t userId = AccountHelper::GetCurrentActiveUserId();
2753     if (userId == Constants::INVALID_USERID) {
2754         APP_LOGE("get a invalid userid, bundleName: %{public}s", bundleName.c_str());
2755         return false;
2756     }
2757     APP_LOGD("bundleName:%{public}s, moduleName:%{public}s, userId:%{public}d",
2758         bundleName.c_str(), moduleName.c_str(), userId);
2759     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2760     auto infoItem = bundleInfos_.find(bundleName);
2761     if (infoItem == bundleInfos_.end()) {
2762         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2763         return false;
2764     }
2765     InnerBundleInfo newInfo = infoItem->second;
2766     bool ret = newInfo.SetModuleRemovable(moduleName, isEnable, userId);
2767     if (ret && dataStorage_->SaveStorageBundleInfo(newInfo)) {
2768         ret = infoItem->second.SetModuleRemovable(moduleName, isEnable, userId);
2769 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
2770         if (isEnable) {
2771             // call clean task
2772             APP_LOGD("bundle:%{public}s isEnable:%{public}d ret:%{public}d call clean task",
2773                 bundleName.c_str(), isEnable, ret);
2774             DelayedSingleton<BundleMgrService>::GetInstance()->GetAgingMgr()->Start(
2775                 BundleAgingMgr::AgingTriggertype::UPDATE_REMOVABLE_FLAG);
2776         }
2777 #endif
2778         return ret;
2779     } else {
2780         APP_LOGE("bundle:%{public}s SetModuleRemoved failed", bundleName.c_str());
2781         return false;
2782     }
2783 }
2784 
IsModuleRemovable(const std::string & bundleName,const std::string & moduleName,bool & isRemovable) const2785 ErrCode BundleDataMgr::IsModuleRemovable(const std::string &bundleName, const std::string &moduleName,
2786     bool &isRemovable) const
2787 {
2788     if (bundleName.empty() || moduleName.empty()) {
2789         APP_LOGE("bundleName or moduleName is empty");
2790         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
2791     }
2792     int32_t userId = AccountHelper::GetCurrentActiveUserId();
2793     if (userId == Constants::INVALID_USERID) {
2794         APP_LOGE("get a invalid userid, bundleName: %{public}s", bundleName.c_str());
2795         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
2796     }
2797     APP_LOGD("bundleName:%{public}s, moduleName:%{public}s, userId:%{public}d",
2798         bundleName.c_str(), moduleName.c_str(), userId);
2799     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2800     auto infoItem = bundleInfos_.find(bundleName);
2801     if (infoItem == bundleInfos_.end()) {
2802         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2803         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2804     }
2805     InnerBundleInfo newInfo = infoItem->second;
2806     return newInfo.IsModuleRemovable(moduleName, userId, isRemovable);
2807 }
2808 
IsAbilityEnabled(const AbilityInfo & abilityInfo,bool & isEnable) const2809 ErrCode BundleDataMgr::IsAbilityEnabled(const AbilityInfo &abilityInfo, bool &isEnable) const
2810 {
2811     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2812     auto infoItem = bundleInfos_.find(abilityInfo.bundleName);
2813     if (infoItem == bundleInfos_.end()) {
2814         APP_LOGE("can not find bundle %{public}s", abilityInfo.bundleName.c_str());
2815         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2816     }
2817     InnerBundleInfo innerBundleInfo = infoItem->second;
2818     auto ability = innerBundleInfo.FindAbilityInfoV9(
2819         abilityInfo.moduleName, abilityInfo.name);
2820     if (!ability) {
2821         APP_LOGE("ability not found, bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
2822             abilityInfo.bundleName.c_str(), abilityInfo.moduleName.c_str(), abilityInfo.name.c_str());
2823         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
2824     }
2825     int32_t responseUserId = innerBundleInfo.GetResponseUserId(GetUserId());
2826     return innerBundleInfo.IsAbilityEnabledV9((*ability), responseUserId, isEnable);
2827 }
2828 
SetAbilityEnabled(const AbilityInfo & abilityInfo,bool isEnabled,int32_t userId)2829 ErrCode BundleDataMgr::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled, int32_t userId)
2830 {
2831     APP_LOGD("SetAbilityEnabled %{public}s", abilityInfo.name.c_str());
2832     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2833     int32_t requestUserId = GetUserId(userId);
2834     if (requestUserId == Constants::INVALID_USERID) {
2835         APP_LOGE("Request userId is invalid, bundleName:%{public}s, abilityName:%{public}s",
2836             abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
2837         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2838     }
2839     auto infoItem = bundleInfos_.find(abilityInfo.bundleName);
2840     if (infoItem == bundleInfos_.end()) {
2841         APP_LOGE("can not find bundle %{public}s", abilityInfo.bundleName.c_str());
2842         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2843     }
2844     InnerBundleInfo& newInfo = infoItem->second;
2845     ErrCode ret = newInfo.SetAbilityEnabled(
2846         abilityInfo.moduleName, abilityInfo.name, isEnabled, userId);
2847     if (ret != ERR_OK) {
2848         return ret;
2849     }
2850     InnerBundleUserInfo innerBundleUserInfo;
2851     if (!newInfo.GetInnerBundleUserInfo(requestUserId, innerBundleUserInfo)) {
2852         APP_LOGE("can not find bundleUserInfo in userId: %{public}d, bundleName:%{public}s, abilityName:%{public}s",
2853             requestUserId, abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
2854         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2855     }
2856 
2857     if (innerBundleUserInfo.bundleUserInfo.IsInitialState()) {
2858         bundleStateStorage_->DeleteBundleState(abilityInfo.bundleName, requestUserId);
2859     } else {
2860         bundleStateStorage_->SaveBundleStateStorage(
2861             abilityInfo.bundleName, requestUserId, innerBundleUserInfo.bundleUserInfo);
2862     }
2863     return ERR_OK;
2864 }
2865 
GetSandboxAppHelper() const2866 std::shared_ptr<BundleSandboxAppHelper> BundleDataMgr::GetSandboxAppHelper() const
2867 {
2868     return sandboxAppHelper_;
2869 }
2870 
RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> & bundleStatusCallback)2871 bool BundleDataMgr::RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback)
2872 {
2873     APP_LOGD("RegisterBundleStatusCallback %{public}s", bundleStatusCallback->GetBundleName().c_str());
2874     std::unique_lock<std::shared_mutex> lock(callbackMutex_);
2875     callbackList_.emplace_back(bundleStatusCallback);
2876     if (bundleStatusCallback->AsObject() != nullptr) {
2877         sptr<BundleStatusCallbackDeathRecipient> deathRecipient =
2878             new (std::nothrow) BundleStatusCallbackDeathRecipient();
2879         if (deathRecipient == nullptr) {
2880             APP_LOGE("deathRecipient is null");
2881             return false;
2882         }
2883         bundleStatusCallback->AsObject()->AddDeathRecipient(deathRecipient);
2884     }
2885     return true;
2886 }
2887 
RegisterBundleEventCallback(const sptr<IBundleEventCallback> & bundleEventCallback)2888 bool BundleDataMgr::RegisterBundleEventCallback(const sptr<IBundleEventCallback> &bundleEventCallback)
2889 {
2890     if (bundleEventCallback == nullptr) {
2891         APP_LOGE("bundleEventCallback is null");
2892         return false;
2893     }
2894     std::unique_lock<std::shared_mutex> lock(eventCallbackMutex_);
2895     if (eventCallbackList_.size() >= MAX_EVENT_CALL_BACK_SIZE) {
2896         APP_LOGE("eventCallbackList_ reach max size %{public}d", MAX_EVENT_CALL_BACK_SIZE);
2897         return false;
2898     }
2899     if (bundleEventCallback->AsObject() != nullptr) {
2900         sptr<BundleEventCallbackDeathRecipient> deathRecipient =
2901             new (std::nothrow) BundleEventCallbackDeathRecipient();
2902         if (deathRecipient == nullptr) {
2903             APP_LOGE("deathRecipient is null");
2904             return false;
2905         }
2906         bundleEventCallback->AsObject()->AddDeathRecipient(deathRecipient);
2907     }
2908     eventCallbackList_.emplace_back(bundleEventCallback);
2909     return true;
2910 }
2911 
UnregisterBundleEventCallback(const sptr<IBundleEventCallback> & bundleEventCallback)2912 bool BundleDataMgr::UnregisterBundleEventCallback(const sptr<IBundleEventCallback> &bundleEventCallback)
2913 {
2914     APP_LOGD("begin to UnregisterBundleEventCallback");
2915     if (bundleEventCallback == nullptr) {
2916         APP_LOGE("bundleEventCallback is null");
2917         return false;
2918     }
2919     std::unique_lock<std::shared_mutex> lock(eventCallbackMutex_);
2920     eventCallbackList_.erase(std::remove_if(eventCallbackList_.begin(), eventCallbackList_.end(),
2921         [&bundleEventCallback](const sptr<IBundleEventCallback> &callback) {
2922             return callback->AsObject() == bundleEventCallback->AsObject();
2923         }), eventCallbackList_.end());
2924     return true;
2925 }
2926 
NotifyBundleEventCallback(const EventFwk::CommonEventData & eventData) const2927 void BundleDataMgr::NotifyBundleEventCallback(const EventFwk::CommonEventData &eventData) const
2928 {
2929     APP_LOGD("begin to NotifyBundleEventCallback");
2930     std::shared_lock<std::shared_mutex> lock(eventCallbackMutex_);
2931     for (const auto &callback : eventCallbackList_) {
2932         callback->OnReceiveEvent(eventData);
2933     }
2934     APP_LOGD("finish to NotifyBundleEventCallback");
2935 }
2936 
ClearBundleStatusCallback(const sptr<IBundleStatusCallback> & bundleStatusCallback)2937 bool BundleDataMgr::ClearBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback)
2938 {
2939     APP_LOGD("ClearBundleStatusCallback %{public}s", bundleStatusCallback->GetBundleName().c_str());
2940     std::unique_lock<std::shared_mutex> lock(callbackMutex_);
2941     callbackList_.erase(std::remove_if(callbackList_.begin(),
2942         callbackList_.end(),
2943         [&](const sptr<IBundleStatusCallback> &callback) {
2944             return callback->AsObject() == bundleStatusCallback->AsObject();
2945         }),
2946         callbackList_.end());
2947     return true;
2948 }
2949 
UnregisterBundleStatusCallback()2950 bool BundleDataMgr::UnregisterBundleStatusCallback()
2951 {
2952     std::unique_lock<std::shared_mutex> lock(callbackMutex_);
2953     callbackList_.clear();
2954     return true;
2955 }
2956 
GenerateUidAndGid(InnerBundleUserInfo & innerBundleUserInfo)2957 bool BundleDataMgr::GenerateUidAndGid(InnerBundleUserInfo &innerBundleUserInfo)
2958 {
2959     if (innerBundleUserInfo.bundleName.empty()) {
2960         APP_LOGE("bundleName is null.");
2961         return false;
2962     }
2963 
2964     int32_t bundleId = Constants::INVALID_BUNDLEID;
2965     if (!GenerateBundleId(innerBundleUserInfo.bundleName, bundleId)) {
2966         APP_LOGE("Generate bundleId failed, bundleName: %{public}s", innerBundleUserInfo.bundleName.c_str());
2967         return false;
2968     }
2969 
2970     innerBundleUserInfo.uid = innerBundleUserInfo.bundleUserInfo.userId * Constants::BASE_USER_RANGE
2971         + bundleId % Constants::BASE_USER_RANGE;
2972     innerBundleUserInfo.gids.emplace_back(innerBundleUserInfo.uid);
2973     return true;
2974 }
2975 
GenerateBundleId(const std::string & bundleName,int32_t & bundleId)2976 bool BundleDataMgr::GenerateBundleId(const std::string &bundleName, int32_t &bundleId)
2977 {
2978     std::lock_guard<std::mutex> lock(bundleIdMapMutex_);
2979     if (bundleIdMap_.empty()) {
2980         APP_LOGI("first app install");
2981         bundleId = baseAppUid_;
2982         bundleIdMap_.emplace(bundleId, bundleName);
2983         return true;
2984     }
2985 
2986     for (const auto &innerBundleId : bundleIdMap_) {
2987         if (innerBundleId.second == bundleName) {
2988             bundleId = innerBundleId.first;
2989             return true;
2990         }
2991     }
2992 
2993     for (int32_t i = baseAppUid_; i < bundleIdMap_.rbegin()->first; ++i) {
2994         if (bundleIdMap_.find(i) == bundleIdMap_.end()) {
2995             APP_LOGI("the %{public}d app install bundleName:%{public}s", i, bundleName.c_str());
2996             bundleId = i;
2997             bundleIdMap_.emplace(bundleId, bundleName);
2998             BundleUtil::MakeFsConfig(bundleName, bundleId, Constants::HMDFS_CONFIG_PATH);
2999             BundleUtil::MakeFsConfig(bundleName, bundleId, Constants::SHAREFS_CONFIG_PATH);
3000             return true;
3001         }
3002     }
3003 
3004     if (bundleIdMap_.rbegin()->first == Constants::MAX_APP_UID) {
3005         APP_LOGE("the bundleId exceeding the maximum value, bundleName:%{public}s", bundleName.c_str());
3006         return false;
3007     }
3008 
3009     bundleId = bundleIdMap_.rbegin()->first + 1;
3010     bundleIdMap_.emplace(bundleId, bundleName);
3011     BundleUtil::MakeFsConfig(bundleName, bundleId, Constants::HMDFS_CONFIG_PATH);
3012     BundleUtil::MakeFsConfig(bundleName, bundleId, Constants::SHAREFS_CONFIG_PATH);
3013     return true;
3014 }
3015 
SetModuleUpgradeFlag(const std::string & bundleName,const std::string & moduleName,const int32_t upgradeFlag)3016 ErrCode BundleDataMgr::SetModuleUpgradeFlag(const std::string &bundleName,
3017     const std::string &moduleName, const int32_t upgradeFlag)
3018 {
3019     APP_LOGD("SetModuleUpgradeFlag %{public}d", upgradeFlag);
3020     if (bundleName.empty() || moduleName.empty()) {
3021         APP_LOGE("bundleName or moduleName is empty");
3022         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
3023     }
3024     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3025     auto infoItem = bundleInfos_.find(bundleName);
3026     if (infoItem == bundleInfos_.end()) {
3027         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
3028     }
3029     InnerBundleInfo &newInfo = infoItem->second;
3030     ErrCode setFlag = newInfo.SetModuleUpgradeFlag(moduleName, upgradeFlag);
3031     if (setFlag == ERR_OK) {
3032         if (dataStorage_->SaveStorageBundleInfo(newInfo)) {
3033             return ERR_OK;
3034         }
3035         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
3036     }
3037     APP_LOGE("dataStorage SetModuleUpgradeFlag %{public}s failed", bundleName.c_str());
3038     return setFlag;
3039 }
3040 
GetModuleUpgradeFlag(const std::string & bundleName,const std::string & moduleName) const3041 int32_t BundleDataMgr::GetModuleUpgradeFlag(const std::string &bundleName, const std::string &moduleName) const
3042 {
3043     APP_LOGD("bundleName is bundleName:%{public}s, moduleName:%{public}s", bundleName.c_str(), moduleName.c_str());
3044     if (bundleName.empty() || moduleName.empty()) {
3045         APP_LOGE("bundleName or moduleName is empty");
3046         return false;
3047     }
3048     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3049     auto infoItem = bundleInfos_.find(bundleName);
3050     if (infoItem == bundleInfos_.end()) {
3051         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
3052         return false;
3053     }
3054     InnerBundleInfo newInfo = infoItem->second;
3055     return newInfo.GetModuleUpgradeFlag(moduleName);
3056 }
3057 
RecycleUidAndGid(const InnerBundleInfo & info)3058 void BundleDataMgr::RecycleUidAndGid(const InnerBundleInfo &info)
3059 {
3060     auto userInfos = info.GetInnerBundleUserInfos();
3061     if (userInfos.empty()) {
3062         return;
3063     }
3064 
3065     auto innerBundleUserInfo = userInfos.begin()->second;
3066     int32_t bundleId = innerBundleUserInfo.uid -
3067         innerBundleUserInfo.bundleUserInfo.userId * Constants::BASE_USER_RANGE;
3068     std::lock_guard<std::mutex> lock(bundleIdMapMutex_);
3069     auto infoItem = bundleIdMap_.find(bundleId);
3070     if (infoItem == bundleIdMap_.end()) {
3071         return;
3072     }
3073 
3074     bundleIdMap_.erase(bundleId);
3075     BundleUtil::RemoveFsConfig(innerBundleUserInfo.bundleName, Constants::HMDFS_CONFIG_PATH);
3076     BundleUtil::RemoveFsConfig(innerBundleUserInfo.bundleName, Constants::SHAREFS_CONFIG_PATH);
3077 }
3078 
RestoreUidAndGid()3079 bool BundleDataMgr::RestoreUidAndGid()
3080 {
3081     for (const auto &info : bundleInfos_) {
3082         bool onlyInsertOne = false;
3083         for (auto infoItem : info.second.GetInnerBundleUserInfos()) {
3084             auto innerBundleUserInfo = infoItem.second;
3085             AddUserId(innerBundleUserInfo.bundleUserInfo.userId);
3086             if (!onlyInsertOne) {
3087                 onlyInsertOne = true;
3088                 int32_t bundleId = innerBundleUserInfo.uid -
3089                     innerBundleUserInfo.bundleUserInfo.userId * Constants::BASE_USER_RANGE;
3090                 std::lock_guard<std::mutex> lock(bundleIdMapMutex_);
3091                 auto item = bundleIdMap_.find(bundleId);
3092                 if (item == bundleIdMap_.end()) {
3093                     bundleIdMap_.emplace(bundleId, innerBundleUserInfo.bundleName);
3094                 } else {
3095                     bundleIdMap_[bundleId] = innerBundleUserInfo.bundleName;
3096                 }
3097                 BundleUtil::MakeFsConfig(innerBundleUserInfo.bundleName, bundleId, Constants::HMDFS_CONFIG_PATH);
3098                 BundleUtil::MakeFsConfig(innerBundleUserInfo.bundleName, bundleId, Constants::SHAREFS_CONFIG_PATH);
3099             }
3100         }
3101     }
3102     return true;
3103 }
3104 
RestoreSandboxUidAndGid(std::map<int32_t,std::string> & bundleIdMap)3105 void BundleDataMgr::RestoreSandboxUidAndGid(std::map<int32_t, std::string> &bundleIdMap)
3106 {
3107     if (sandboxAppHelper_ != nullptr) {
3108         std::lock_guard<std::mutex> lock(bundleIdMapMutex_);
3109         sandboxAppHelper_->RestoreSandboxUidAndGid(bundleIdMap);
3110     }
3111 }
3112 
GetBundleMutex(const std::string & bundleName)3113 std::mutex &BundleDataMgr::GetBundleMutex(const std::string &bundleName)
3114 {
3115     bundleMutex_.lock_shared();
3116     auto it = bundleMutexMap_.find(bundleName);
3117     if (it == bundleMutexMap_.end()) {
3118         bundleMutex_.unlock_shared();
3119         std::unique_lock lock {bundleMutex_};
3120         return bundleMutexMap_[bundleName];
3121     }
3122     bundleMutex_.unlock_shared();
3123     return it->second;
3124 }
3125 
GetProvisionId(const std::string & bundleName,std::string & provisionId) const3126 bool BundleDataMgr::GetProvisionId(const std::string &bundleName, std::string &provisionId) const
3127 {
3128     APP_LOGD("GetProvisionId %{public}s", bundleName.c_str());
3129     if (bundleName.empty()) {
3130         APP_LOGE("bundleName empty");
3131         return false;
3132     }
3133     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3134     auto infoItem = bundleInfos_.find(bundleName);
3135     if (infoItem == bundleInfos_.end()) {
3136         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
3137         return false;
3138     }
3139     provisionId = infoItem->second.GetProvisionId();
3140     return true;
3141 }
3142 
GetAppFeature(const std::string & bundleName,std::string & appFeature) const3143 bool BundleDataMgr::GetAppFeature(const std::string &bundleName, std::string &appFeature) const
3144 {
3145     APP_LOGD("GetAppFeature %{public}s", bundleName.c_str());
3146     if (bundleName.empty()) {
3147         APP_LOGE("bundleName empty");
3148         return false;
3149     }
3150     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3151     auto infoItem = bundleInfos_.find(bundleName);
3152     if (infoItem == bundleInfos_.end()) {
3153         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
3154         return false;
3155     }
3156     appFeature = infoItem->second.GetAppFeature();
3157     return true;
3158 }
3159 
SetInitialUserFlag(bool flag)3160 void BundleDataMgr::SetInitialUserFlag(bool flag)
3161 {
3162     APP_LOGD("SetInitialUserFlag %{public}d", flag);
3163     if (!initialUserFlag_ && flag && bundlePromise_ != nullptr) {
3164         bundlePromise_->NotifyAllTasksExecuteFinished();
3165     }
3166 
3167     initialUserFlag_ = flag;
3168 }
3169 
GetDataStorage() const3170 std::shared_ptr<IBundleDataStorage> BundleDataMgr::GetDataStorage() const
3171 {
3172     return dataStorage_;
3173 }
3174 
GetAllFormsInfo(std::vector<FormInfo> & formInfos) const3175 bool BundleDataMgr::GetAllFormsInfo(std::vector<FormInfo> &formInfos) const
3176 {
3177     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3178     if (bundleInfos_.empty()) {
3179         APP_LOGE("bundleInfos_ data is empty");
3180         return false;
3181     }
3182     auto result = false;
3183     for (const auto &item : bundleInfos_) {
3184         if (item.second.IsDisabled()) {
3185             APP_LOGW("app %{public}s is disabled", item.second.GetBundleName().c_str());
3186             continue;
3187         }
3188         item.second.GetFormsInfoByApp(formInfos);
3189         result = true;
3190     }
3191     APP_LOGD("all the form infos find success");
3192     return result;
3193 }
3194 
GetFormsInfoByModule(const std::string & bundleName,const std::string & moduleName,std::vector<FormInfo> & formInfos) const3195 bool BundleDataMgr::GetFormsInfoByModule(
3196     const std::string &bundleName, const std::string &moduleName, std::vector<FormInfo> &formInfos) const
3197 {
3198     if (bundleName.empty()) {
3199         APP_LOGW("bundle name is empty");
3200         return false;
3201     }
3202     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3203     if (bundleInfos_.empty()) {
3204         APP_LOGE("bundleInfos_ data is empty");
3205         return false;
3206     }
3207     auto infoItem = bundleInfos_.find(bundleName);
3208     if (infoItem == bundleInfos_.end()) {
3209         APP_LOGE("bundleName %{public}s not exist", bundleName.c_str());
3210         return false;
3211     }
3212     if (infoItem->second.IsDisabled()) {
3213         APP_LOGE("app %{public}s is disabled", infoItem->second.GetBundleName().c_str());
3214         return false;
3215     }
3216     infoItem->second.GetFormsInfoByModule(moduleName, formInfos);
3217     if (formInfos.empty()) {
3218         return false;
3219     }
3220     APP_LOGE("module forminfo find success");
3221     return true;
3222 }
3223 
GetFormsInfoByApp(const std::string & bundleName,std::vector<FormInfo> & formInfos) const3224 bool BundleDataMgr::GetFormsInfoByApp(const std::string &bundleName, std::vector<FormInfo> &formInfos) const
3225 {
3226     if (bundleName.empty()) {
3227         APP_LOGW("bundle name is empty");
3228         return false;
3229     }
3230     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3231     if (bundleInfos_.empty()) {
3232         APP_LOGE("bundleInfos_ data is empty");
3233         return false;
3234     }
3235     auto infoItem = bundleInfos_.find(bundleName);
3236     if (infoItem == bundleInfos_.end()) {
3237         APP_LOGE("bundleName %{public}s not exist", bundleName.c_str());
3238         return false;
3239     }
3240     if (infoItem->second.IsDisabled()) {
3241         APP_LOGE("app %{public}s is disabled", infoItem->second.GetBundleName().c_str());
3242         return false;
3243     }
3244     infoItem->second.GetFormsInfoByApp(formInfos);
3245     APP_LOGD("App forminfo find success");
3246     return true;
3247 }
3248 
GetShortcutInfos(const std::string & bundleName,int32_t userId,std::vector<ShortcutInfo> & shortcutInfos) const3249 bool BundleDataMgr::GetShortcutInfos(
3250     const std::string &bundleName, int32_t userId, std::vector<ShortcutInfo> &shortcutInfos) const
3251 {
3252     int32_t requestUserId = GetUserId(userId);
3253     if (requestUserId == Constants::INVALID_USERID) {
3254         APP_LOGE("input invalid userid, bundleName:%{public}s, userId:%{public}d", bundleName.c_str(), userId);
3255         return false;
3256     }
3257 
3258     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3259     InnerBundleInfo innerBundleInfo;
3260     if (!GetInnerBundleInfoWithFlags(
3261         bundleName, BundleFlag::GET_BUNDLE_DEFAULT, innerBundleInfo, requestUserId)) {
3262         APP_LOGE("GetShortcutInfos failed, bundleName:%{public}s, requestUserId:%{public}d",
3263             bundleName.c_str(), requestUserId);
3264         return false;
3265     }
3266     innerBundleInfo.GetShortcutInfos(shortcutInfos);
3267     return true;
3268 }
3269 
GetShortcutInfoV9(const std::string & bundleName,int32_t userId,std::vector<ShortcutInfo> & shortcutInfos) const3270 ErrCode BundleDataMgr::GetShortcutInfoV9(
3271     const std::string &bundleName, int32_t userId, std::vector<ShortcutInfo> &shortcutInfos) const
3272 {
3273     int32_t requestUserId = GetUserId(userId);
3274     if (requestUserId == Constants::INVALID_USERID) {
3275         APP_LOGE("input invalid userid, bundleName:%{public}s, userId:%{public}d", bundleName.c_str(), userId);
3276         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
3277     }
3278     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3279     InnerBundleInfo innerBundleInfo;
3280     ErrCode ret = GetInnerBundleInfoWithFlagsV9(bundleName,
3281         BundleFlag::GET_BUNDLE_DEFAULT, innerBundleInfo, requestUserId);
3282     if (ret != ERR_OK) {
3283         APP_LOGE("GetInnerBundleInfoWithFlagsV9 failed, bundleName:%{public}s, requestUserId:%{public}d",
3284             bundleName.c_str(), requestUserId);
3285         return ret;
3286     }
3287 
3288     innerBundleInfo.GetShortcutInfos(shortcutInfos);
3289     return ERR_OK;
3290 }
3291 
GetAllCommonEventInfo(const std::string & eventKey,std::vector<CommonEventInfo> & commonEventInfos) const3292 bool BundleDataMgr::GetAllCommonEventInfo(const std::string &eventKey,
3293     std::vector<CommonEventInfo> &commonEventInfos) const
3294 {
3295     if (eventKey.empty()) {
3296         APP_LOGW("event key is empty");
3297         return false;
3298     }
3299     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3300     if (bundleInfos_.empty()) {
3301         APP_LOGI("bundleInfos_ data is empty");
3302         return false;
3303     }
3304     for (const auto &item : bundleInfos_) {
3305         const InnerBundleInfo &info = item.second;
3306         if (info.IsDisabled()) {
3307             APP_LOGI("app %{public}s is disabled", info.GetBundleName().c_str());
3308             continue;
3309         }
3310         info.GetCommonEvents(eventKey, commonEventInfos);
3311     }
3312     if (commonEventInfos.size() == 0) {
3313         APP_LOGE("commonEventInfos is empty");
3314         return false;
3315     }
3316     APP_LOGE("commonEventInfos find success");
3317     return true;
3318 }
3319 
SavePreInstallBundleInfo(const std::string & bundleName,const PreInstallBundleInfo & preInstallBundleInfo)3320 bool BundleDataMgr::SavePreInstallBundleInfo(
3321     const std::string &bundleName, const PreInstallBundleInfo &preInstallBundleInfo)
3322 {
3323     if (preInstallDataStorage_ == nullptr) {
3324         return false;
3325     }
3326 
3327     if (preInstallDataStorage_->SavePreInstallStorageBundleInfo(preInstallBundleInfo)) {
3328         APP_LOGD("write storage success bundle:%{public}s", bundleName.c_str());
3329         return true;
3330     }
3331 
3332     return false;
3333 }
3334 
DeletePreInstallBundleInfo(const std::string & bundleName,const PreInstallBundleInfo & preInstallBundleInfo)3335 bool BundleDataMgr::DeletePreInstallBundleInfo(
3336     const std::string &bundleName, const PreInstallBundleInfo &preInstallBundleInfo)
3337 {
3338     if (preInstallDataStorage_ == nullptr) {
3339         return false;
3340     }
3341 
3342     if (preInstallDataStorage_->DeletePreInstallStorageBundleInfo(preInstallBundleInfo)) {
3343         APP_LOGD("Delete PreInstall Storage success bundle:%{public}s", bundleName.c_str());
3344         return true;
3345     }
3346 
3347     return false;
3348 }
3349 
GetPreInstallBundleInfo(const std::string & bundleName,PreInstallBundleInfo & preInstallBundleInfo)3350 bool BundleDataMgr::GetPreInstallBundleInfo(
3351     const std::string &bundleName, PreInstallBundleInfo &preInstallBundleInfo)
3352 {
3353     if (bundleName.empty()) {
3354         APP_LOGE("bundleName is empty");
3355         return false;
3356     }
3357     if (preInstallDataStorage_ == nullptr) {
3358         return false;
3359     }
3360     if (!preInstallDataStorage_->LoadPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
3361         APP_LOGE("get preInstall bundleInfo failed by bundle(%{public}s).", bundleName.c_str());
3362         return false;
3363     }
3364     return true;
3365 }
3366 
LoadAllPreInstallBundleInfos(std::vector<PreInstallBundleInfo> & preInstallBundleInfos)3367 bool BundleDataMgr::LoadAllPreInstallBundleInfos(std::vector<PreInstallBundleInfo> &preInstallBundleInfos)
3368 {
3369     if (preInstallDataStorage_ == nullptr) {
3370         return false;
3371     }
3372 
3373     if (preInstallDataStorage_->LoadAllPreInstallBundleInfos(preInstallBundleInfos)) {
3374         APP_LOGD("load all storage success");
3375         return true;
3376     }
3377 
3378     return false;
3379 }
3380 
SaveInnerBundleInfo(const InnerBundleInfo & info) const3381 bool BundleDataMgr::SaveInnerBundleInfo(const InnerBundleInfo &info) const
3382 {
3383     APP_LOGD("write install InnerBundleInfo to storage with bundle:%{public}s", info.GetBundleName().c_str());
3384     if (dataStorage_->SaveStorageBundleInfo(info)) {
3385         APP_LOGD("save install InnerBundleInfo successfully");
3386         return true;
3387     }
3388     APP_LOGE("save install InnerBundleInfo failed, bundleName:%{public}s", info.GetBundleName().c_str());
3389     return false;
3390 }
3391 
GetInnerBundleUserInfoByUserId(const std::string & bundleName,int32_t userId,InnerBundleUserInfo & innerBundleUserInfo) const3392 bool BundleDataMgr::GetInnerBundleUserInfoByUserId(const std::string &bundleName,
3393     int32_t userId, InnerBundleUserInfo &innerBundleUserInfo) const
3394 {
3395     APP_LOGD("get user info start: bundleName: (%{public}s)  userId: (%{public}d) ",
3396         bundleName.c_str(), userId);
3397     int32_t requestUserId = GetUserId(userId);
3398     if (requestUserId == Constants::INVALID_USERID) {
3399         return false;
3400     }
3401 
3402     if (bundleName.empty()) {
3403         APP_LOGW("bundle name is empty");
3404         return false;
3405     }
3406 
3407     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3408     if (bundleInfos_.empty()) {
3409         APP_LOGE("bundleInfos data is empty, bundleName:%{public}s", bundleName.c_str());
3410         return false;
3411     }
3412 
3413     auto infoItem = bundleInfos_.find(bundleName);
3414     if (infoItem == bundleInfos_.end()) {
3415         APP_LOGE("bundleName:%{public}s not exist", bundleName.c_str());
3416         return false;
3417     }
3418     if (infoItem->second.IsDisabled()) {
3419         APP_LOGE("app %{public}s is disabled", infoItem->second.GetBundleName().c_str());
3420         return false;
3421     }
3422 
3423     return infoItem->second.GetInnerBundleUserInfo(requestUserId, innerBundleUserInfo);
3424 }
3425 
GetUserId(int32_t userId) const3426 int32_t BundleDataMgr::GetUserId(int32_t userId) const
3427 {
3428     if (userId == Constants::ANY_USERID || userId == Constants::ALL_USERID) {
3429         return userId;
3430     }
3431 
3432     if (userId == Constants::UNSPECIFIED_USERID) {
3433         userId = GetUserIdByCallingUid();
3434     }
3435 
3436     if (!HasUserId(userId)) {
3437         APP_LOGE("user is not existed.");
3438         userId = Constants::INVALID_USERID;
3439     }
3440 
3441     return userId;
3442 }
3443 
GetUserIdByUid(int32_t uid) const3444 int32_t BundleDataMgr::GetUserIdByUid(int32_t uid) const
3445 {
3446     return BundleUtil::GetUserIdByUid(uid);
3447 }
3448 
AddUserId(int32_t userId)3449 void BundleDataMgr::AddUserId(int32_t userId)
3450 {
3451     std::lock_guard<std::mutex> lock(multiUserIdSetMutex_);
3452     auto item = multiUserIdsSet_.find(userId);
3453     if (item != multiUserIdsSet_.end()) {
3454         return;
3455     }
3456 
3457     multiUserIdsSet_.insert(userId);
3458 }
3459 
RemoveUserId(int32_t userId)3460 void BundleDataMgr::RemoveUserId(int32_t userId)
3461 {
3462     std::lock_guard<std::mutex> lock(multiUserIdSetMutex_);
3463     auto item = multiUserIdsSet_.find(userId);
3464     if (item == multiUserIdsSet_.end()) {
3465         return;
3466     }
3467 
3468     multiUserIdsSet_.erase(item);
3469 }
3470 
HasUserId(int32_t userId) const3471 bool BundleDataMgr::HasUserId(int32_t userId) const
3472 {
3473     std::lock_guard<std::mutex> lock(multiUserIdSetMutex_);
3474     return multiUserIdsSet_.find(userId) != multiUserIdsSet_.end();
3475 }
3476 
GetUserIdByCallingUid() const3477 int32_t BundleDataMgr::GetUserIdByCallingUid() const
3478 {
3479     return BundleUtil::GetUserIdByCallingUid();
3480 }
3481 
GetAllUser() const3482 std::set<int32_t> BundleDataMgr::GetAllUser() const
3483 {
3484     std::lock_guard<std::mutex> lock(multiUserIdSetMutex_);
3485     return multiUserIdsSet_;
3486 }
3487 
GetInnerBundleUserInfos(const std::string & bundleName,std::vector<InnerBundleUserInfo> & innerBundleUserInfos) const3488 bool BundleDataMgr::GetInnerBundleUserInfos(
3489     const std::string &bundleName, std::vector<InnerBundleUserInfo> &innerBundleUserInfos) const
3490 {
3491     APP_LOGD("get all user info in bundle(%{public}s)", bundleName.c_str());
3492     if (bundleName.empty()) {
3493         APP_LOGW("bundle name is empty");
3494         return false;
3495     }
3496 
3497     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3498     if (bundleInfos_.empty()) {
3499         APP_LOGE("bundleInfos data is empty, bundleName:%{public}s", bundleName.c_str());
3500         return false;
3501     }
3502 
3503     auto infoItem = bundleInfos_.find(bundleName);
3504     if (infoItem == bundleInfos_.end()) {
3505         APP_LOGE("bundleName:%{public}s not exist", bundleName.c_str());
3506         return false;
3507     }
3508     if (infoItem->second.IsDisabled()) {
3509         APP_LOGE("app %{public}s is disabled", infoItem->second.GetBundleName().c_str());
3510         return false;
3511     }
3512 
3513     for (auto userInfo : infoItem->second.GetInnerBundleUserInfos()) {
3514         innerBundleUserInfos.emplace_back(userInfo.second);
3515     }
3516 
3517     return !innerBundleUserInfos.empty();
3518 }
3519 
GetAppPrivilegeLevel(const std::string & bundleName,int32_t userId)3520 std::string BundleDataMgr::GetAppPrivilegeLevel(const std::string &bundleName, int32_t userId)
3521 {
3522     APP_LOGD("GetAppPrivilegeLevel:%{public}s, userId:%{public}d", bundleName.c_str(), userId);
3523     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3524     InnerBundleInfo info;
3525     if (!GetInnerBundleInfoWithFlags(bundleName, 0, info, userId)) {
3526         return Constants::EMPTY_STRING;
3527     }
3528 
3529     return info.GetAppPrivilegeLevel();
3530 }
3531 
QueryExtensionAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos,int32_t appIndex) const3532 bool BundleDataMgr::QueryExtensionAbilityInfos(const Want &want, int32_t flags, int32_t userId,
3533     std::vector<ExtensionAbilityInfo> &extensionInfos, int32_t appIndex) const
3534 {
3535     int32_t requestUserId = GetUserId(userId);
3536     if (requestUserId == Constants::INVALID_USERID) {
3537         return false;
3538     }
3539 
3540     ElementName element = want.GetElement();
3541     std::string bundleName = element.GetBundleName();
3542     std::string extensionName = element.GetAbilityName();
3543     APP_LOGD("bundle name:%{public}s, extension name:%{public}s",
3544         bundleName.c_str(), extensionName.c_str());
3545     // explicit query
3546     if (!bundleName.empty() && !extensionName.empty()) {
3547         ExtensionAbilityInfo info;
3548         bool ret = ExplicitQueryExtensionInfo(want, flags, requestUserId, info, appIndex);
3549         if (!ret) {
3550             APP_LOGE("explicit queryExtensionInfo error, bundleName:%{public}s, extensionName:%{public}s",
3551                 bundleName.c_str(), extensionName.c_str());
3552             return false;
3553         }
3554         extensionInfos.emplace_back(info);
3555         return true;
3556     }
3557 
3558     bool ret = ImplicitQueryExtensionInfos(want, flags, requestUserId, extensionInfos, appIndex);
3559     if (!ret) {
3560         APP_LOGE("implicit queryExtensionAbilityInfos error, action:%{public}s, uri:%{private}s, type:%{public}s",
3561             want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
3562         return false;
3563     }
3564     if (extensionInfos.size() == 0) {
3565         APP_LOGE("no matching abilityInfo, action:%{public}s, uri:%{private}s, type:%{public}s",
3566             want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
3567         return false;
3568     }
3569     APP_LOGD("query extensionAbilityInfo successfully");
3570     return true;
3571 }
3572 
QueryExtensionAbilityInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos,int32_t appIndex) const3573 ErrCode BundleDataMgr::QueryExtensionAbilityInfosV9(const Want &want, int32_t flags, int32_t userId,
3574     std::vector<ExtensionAbilityInfo> &extensionInfos, int32_t appIndex) const
3575 {
3576     int32_t requestUserId = GetUserId(userId);
3577     if (requestUserId == Constants::INVALID_USERID) {
3578         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
3579     }
3580 
3581     ElementName element = want.GetElement();
3582     std::string bundleName = element.GetBundleName();
3583     std::string extensionName = element.GetAbilityName();
3584     APP_LOGD("bundle name:%{public}s, extension name:%{public}s",
3585         bundleName.c_str(), extensionName.c_str());
3586     // explicit query
3587     if (!bundleName.empty() && !extensionName.empty()) {
3588         ExtensionAbilityInfo info;
3589         ErrCode ret = ExplicitQueryExtensionInfoV9(want, flags, requestUserId, info, appIndex);
3590         if (ret != ERR_OK) {
3591             APP_LOGE("explicit queryExtensionInfo error");
3592             return ret;
3593         }
3594         extensionInfos.emplace_back(info);
3595         return ERR_OK;
3596     }
3597 
3598     ErrCode ret = ImplicitQueryExtensionInfosV9(want, flags, requestUserId, extensionInfos, appIndex);
3599     if (ret != ERR_OK) {
3600         APP_LOGE("ImplicitQueryExtensionInfosV9 error");
3601         return ret;
3602     }
3603     if (extensionInfos.empty()) {
3604         APP_LOGE("no matching abilityInfo");
3605         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3606     }
3607     APP_LOGD("QueryExtensionAbilityInfosV9 success");
3608     return ERR_OK;
3609 }
3610 
ExplicitQueryExtensionInfo(const Want & want,int32_t flags,int32_t userId,ExtensionAbilityInfo & extensionInfo,int32_t appIndex) const3611 bool BundleDataMgr::ExplicitQueryExtensionInfo(const Want &want, int32_t flags, int32_t userId,
3612     ExtensionAbilityInfo &extensionInfo, int32_t appIndex) const
3613 {
3614     ElementName element = want.GetElement();
3615     std::string bundleName = element.GetBundleName();
3616     std::string moduleName = element.GetModuleName();
3617     std::string extensionName = element.GetAbilityName();
3618     APP_LOGD("bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
3619         bundleName.c_str(), moduleName.c_str(), extensionName.c_str());
3620     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
3621     int32_t requestUserId = GetUserId(userId);
3622     if (requestUserId == Constants::INVALID_USERID) {
3623         return false;
3624     }
3625     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3626     InnerBundleInfo innerBundleInfo;
3627     if ((appIndex == 0) && (!GetInnerBundleInfoWithFlags(bundleName, flags, innerBundleInfo, requestUserId))) {
3628         APP_LOGE("ExplicitQueryExtensionInfo failed");
3629         return false;
3630     }
3631     if (appIndex > 0) {
3632         if (sandboxAppHelper_ == nullptr) {
3633             APP_LOGE("sandboxAppHelper_ is nullptr");
3634             return false;
3635         }
3636         auto ret = sandboxAppHelper_->GetSandboxAppInfo(bundleName, appIndex, requestUserId, innerBundleInfo);
3637         if (ret != ERR_OK) {
3638             APP_LOGW("obtain innerBundleInfo of sandbox app failed due to errCode %{public}d", ret);
3639             return false;
3640         }
3641     }
3642     auto extension = innerBundleInfo.FindExtensionInfo(moduleName, extensionName);
3643     if (!extension) {
3644         APP_LOGE("extensionAbility not found or disabled");
3645         return false;
3646     }
3647     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_PERMISSION) != GET_ABILITY_INFO_WITH_PERMISSION) {
3648         extension->permissions.clear();
3649     }
3650     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_METADATA) != GET_ABILITY_INFO_WITH_METADATA) {
3651         extension->metadata.clear();
3652     }
3653     extensionInfo = (*extension);
3654     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_APPLICATION) == GET_ABILITY_INFO_WITH_APPLICATION) {
3655         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
3656         innerBundleInfo.GetApplicationInfo(
3657             ApplicationFlag::GET_BASIC_APPLICATION_INFO |
3658             ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT, responseUserId,
3659             extensionInfo.applicationInfo);
3660     }
3661     return true;
3662 }
3663 
ExplicitQueryExtensionInfoV9(const Want & want,int32_t flags,int32_t userId,ExtensionAbilityInfo & extensionInfo,int32_t appIndex) const3664 ErrCode BundleDataMgr::ExplicitQueryExtensionInfoV9(const Want &want, int32_t flags, int32_t userId,
3665     ExtensionAbilityInfo &extensionInfo, int32_t appIndex) const
3666 {
3667     ElementName element = want.GetElement();
3668     std::string bundleName = element.GetBundleName();
3669     std::string moduleName = element.GetModuleName();
3670     std::string extensionName = element.GetAbilityName();
3671     APP_LOGD("bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
3672         bundleName.c_str(), moduleName.c_str(), extensionName.c_str());
3673     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
3674     int32_t requestUserId = GetUserId(userId);
3675     if (requestUserId == Constants::INVALID_USERID) {
3676         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
3677     }
3678     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3679     InnerBundleInfo innerBundleInfo;
3680     if (appIndex == 0) {
3681         ErrCode ret = GetInnerBundleInfoWithFlagsV9(bundleName, flags, innerBundleInfo, requestUserId);
3682         if (ret != ERR_OK) {
3683             APP_LOGE("ExplicitQueryExtensionInfoV9 failed");
3684             return ret;
3685         }
3686     }
3687     if (appIndex > 0) {
3688         if (sandboxAppHelper_ == nullptr) {
3689             APP_LOGE("sandboxAppHelper_ is nullptr");
3690             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3691         }
3692         auto ret = sandboxAppHelper_->GetSandboxAppInfo(bundleName, appIndex, requestUserId, innerBundleInfo);
3693         if (ret != ERR_OK) {
3694             APP_LOGW("obtain innerBundleInfo of sandbox app failed due to errCode %{public}d", ret);
3695             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3696         }
3697     }
3698     auto extension = innerBundleInfo.FindExtensionInfo(moduleName, extensionName);
3699     if (!extension) {
3700         APP_LOGE("extensionAbility not found or disabled");
3701         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3702     }
3703     if ((static_cast<uint32_t>(flags) &
3704         static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION)) !=
3705         static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION)) {
3706         extension->permissions.clear();
3707     }
3708     if ((static_cast<uint32_t>(flags) &
3709         static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_METADATA)) !=
3710         static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_METADATA)) {
3711         extension->metadata.clear();
3712     }
3713     extensionInfo = (*extension);
3714     if ((static_cast<uint32_t>(flags) &
3715         static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_APPLICATION)) ==
3716         static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_APPLICATION)) {
3717         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
3718         innerBundleInfo.GetApplicationInfoV9(static_cast<int32_t>(
3719             GetApplicationFlag::GET_APPLICATION_INFO_DEFAULT), responseUserId, extensionInfo.applicationInfo);
3720     }
3721     // set uid for NAPI cache use
3722     InnerBundleUserInfo innerBundleUserInfo;
3723     if (innerBundleInfo.GetInnerBundleUserInfo(userId, innerBundleUserInfo)) {
3724         extensionInfo.uid = innerBundleUserInfo.uid;
3725     }
3726     return ERR_OK;
3727 }
3728 
FilterExtensionAbilityInfosByModuleName(const std::string & moduleName,std::vector<ExtensionAbilityInfo> & extensionInfos) const3729 void BundleDataMgr::FilterExtensionAbilityInfosByModuleName(const std::string &moduleName,
3730     std::vector<ExtensionAbilityInfo> &extensionInfos) const
3731 {
3732     APP_LOGD("BundleDataMgr::FilterExtensionAbilityInfosByModuleName moduleName: %{public}s", moduleName.c_str());
3733     if (moduleName.empty()) {
3734         return;
3735     }
3736     for (auto iter = extensionInfos.begin(); iter != extensionInfos.end();) {
3737         if (iter->moduleName != moduleName) {
3738             iter = extensionInfos.erase(iter);
3739         } else {
3740             ++iter;
3741         }
3742     }
3743 }
3744 
ImplicitQueryExtensionInfos(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos,int32_t appIndex) const3745 bool BundleDataMgr::ImplicitQueryExtensionInfos(const Want &want, int32_t flags, int32_t userId,
3746     std::vector<ExtensionAbilityInfo> &extensionInfos, int32_t appIndex) const
3747 {
3748     if (want.GetAction().empty() && want.GetEntities().empty()
3749         && want.GetUriString().empty() && want.GetType().empty()) {
3750         APP_LOGE("param invalid");
3751         return false;
3752     }
3753     APP_LOGD("action:%{public}s, uri:%{private}s, type:%{public}s",
3754         want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
3755     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
3756 
3757     int32_t requestUserId = GetUserId(userId);
3758     if (requestUserId == Constants::INVALID_USERID) {
3759         return false;
3760     }
3761     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3762     std::string bundleName = want.GetElement().GetBundleName();
3763     if (!bundleName.empty()) {
3764         // query in current bundle
3765         if (!ImplicitQueryCurExtensionInfos(want, flags, requestUserId, extensionInfos, appIndex)) {
3766             APP_LOGE("ImplicitQueryCurExtensionInfos failed, bundleName:%{public}s", bundleName.c_str());
3767             return false;
3768         }
3769     } else {
3770         // query all
3771         ImplicitQueryAllExtensionInfos(want, flags, requestUserId, extensionInfos, appIndex);
3772     }
3773     // sort by priority, descending order.
3774     if (extensionInfos.size() > 1) {
3775         std::stable_sort(extensionInfos.begin(), extensionInfos.end(),
3776             [](ExtensionAbilityInfo a, ExtensionAbilityInfo b) { return a.priority > b.priority; });
3777     }
3778     return true;
3779 }
3780 
ImplicitQueryExtensionInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos,int32_t appIndex) const3781 ErrCode BundleDataMgr::ImplicitQueryExtensionInfosV9(const Want &want, int32_t flags, int32_t userId,
3782     std::vector<ExtensionAbilityInfo> &extensionInfos, int32_t appIndex) const
3783 {
3784     if (want.GetAction().empty() && want.GetEntities().empty()
3785         && want.GetUriString().empty() && want.GetType().empty()) {
3786         APP_LOGE("param invalid");
3787         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3788     }
3789     APP_LOGD("action:%{public}s, uri:%{private}s, type:%{public}s",
3790         want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
3791     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
3792 
3793     int32_t requestUserId = GetUserId(userId);
3794     if (requestUserId == Constants::INVALID_USERID) {
3795         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
3796     }
3797     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3798     std::string bundleName = want.GetElement().GetBundleName();
3799     if (!bundleName.empty()) {
3800         // query in current bundle
3801         ErrCode ret = ImplicitQueryCurExtensionInfosV9(want, flags, requestUserId, extensionInfos, appIndex);
3802         if (ret != ERR_OK) {
3803             APP_LOGE("ImplicitQueryCurExtensionInfos failed, bundleName:%{public}s", bundleName.c_str());
3804             return ret;
3805         }
3806     } else {
3807         // query all
3808         ImplicitQueryAllExtensionInfosV9(want, flags, requestUserId, extensionInfos, appIndex);
3809     }
3810     // sort by priority, descending order.
3811     if (extensionInfos.size() > 1) {
3812         std::stable_sort(extensionInfos.begin(), extensionInfos.end(),
3813             [](ExtensionAbilityInfo a, ExtensionAbilityInfo b) { return a.priority > b.priority; });
3814     }
3815     return ERR_OK;
3816 }
3817 
ImplicitQueryCurExtensionInfos(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & infos,int32_t appIndex) const3818 bool BundleDataMgr::ImplicitQueryCurExtensionInfos(const Want &want, int32_t flags, int32_t userId,
3819     std::vector<ExtensionAbilityInfo> &infos, int32_t appIndex) const
3820 {
3821     APP_LOGD("begin to ImplicitQueryCurExtensionInfos");
3822     std::string bundleName = want.GetElement().GetBundleName();
3823     InnerBundleInfo innerBundleInfo;
3824     if ((appIndex == 0) && (!GetInnerBundleInfoWithFlags(bundleName, flags, innerBundleInfo, userId))) {
3825         APP_LOGE("ImplicitQueryExtensionAbilityInfos failed, bundleName:%{public}s", bundleName.c_str());
3826         return false;
3827     }
3828     if (appIndex > 0) {
3829         if (sandboxAppHelper_ == nullptr) {
3830             APP_LOGE("sandboxAppHelper_ is nullptr");
3831             return false;
3832         }
3833         auto ret = sandboxAppHelper_->GetSandboxAppInfo(bundleName, appIndex, userId, innerBundleInfo);
3834         if (ret != ERR_OK) {
3835             APP_LOGW("obtain innerBundleInfo of sandbox app failed due to errCode %{public}d", ret);
3836             return false;
3837         }
3838     }
3839     int32_t responseUserId = innerBundleInfo.GetResponseUserId(userId);
3840     GetMatchExtensionInfos(want, flags, responseUserId, innerBundleInfo, infos);
3841     FilterExtensionAbilityInfosByModuleName(want.GetElement().GetModuleName(), infos);
3842     APP_LOGD("finish to ImplicitQueryCurExtensionInfos");
3843     return true;
3844 }
3845 
ImplicitQueryCurExtensionInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & infos,int32_t appIndex) const3846 ErrCode BundleDataMgr::ImplicitQueryCurExtensionInfosV9(const Want &want, int32_t flags, int32_t userId,
3847     std::vector<ExtensionAbilityInfo> &infos, int32_t appIndex) const
3848 {
3849     APP_LOGD("begin to ImplicitQueryCurExtensionInfosV9");
3850     std::string bundleName = want.GetElement().GetBundleName();
3851     InnerBundleInfo innerBundleInfo;
3852     if (appIndex == 0) {
3853         ErrCode ret = GetInnerBundleInfoWithFlagsV9(bundleName, flags, innerBundleInfo, userId);
3854         if (ret != ERR_OK) {
3855             APP_LOGE("GetInnerBundleInfoWithFlagsV9 failed, bundleName:%{public}s", bundleName.c_str());
3856             return ret;
3857         }
3858     }
3859     if (appIndex > 0) {
3860         if (sandboxAppHelper_ == nullptr) {
3861             APP_LOGE("sandboxAppHelper_ is nullptr");
3862             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3863         }
3864         auto ret = sandboxAppHelper_->GetSandboxAppInfo(bundleName, appIndex, userId, innerBundleInfo);
3865         if (ret != ERR_OK) {
3866             APP_LOGW("obtain innerBundleInfo of sandbox app failed due to errCode %{public}d", ret);
3867             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3868         }
3869     }
3870     int32_t responseUserId = innerBundleInfo.GetResponseUserId(userId);
3871     GetMatchExtensionInfosV9(want, flags, responseUserId, innerBundleInfo, infos);
3872     FilterExtensionAbilityInfosByModuleName(want.GetElement().GetModuleName(), infos);
3873     APP_LOGD("finish to ImplicitQueryCurExtensionInfosV9");
3874     return ERR_OK;
3875 }
3876 
ImplicitQueryAllExtensionInfos(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & infos,int32_t appIndex) const3877 void BundleDataMgr::ImplicitQueryAllExtensionInfos(const Want &want, int32_t flags, int32_t userId,
3878     std::vector<ExtensionAbilityInfo> &infos, int32_t appIndex) const
3879 {
3880     APP_LOGD("begin to ImplicitQueryAllExtensionInfos");
3881     int32_t requestUserId = GetUserId(userId);
3882     if (requestUserId == Constants::INVALID_USERID) {
3883         APP_LOGE("invalid userId, userId:%{public}d", userId);
3884         return;
3885     }
3886 
3887     // query from bundleInfos_
3888     if (appIndex == 0) {
3889         for (const auto &item : bundleInfos_) {
3890             const InnerBundleInfo &innerBundleInfo = item.second;
3891             int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
3892             if (CheckInnerBundleInfoWithFlags(innerBundleInfo, flags, responseUserId) != ERR_OK) {
3893                 continue;
3894             }
3895             GetMatchExtensionInfos(want, flags, responseUserId, innerBundleInfo, infos);
3896         }
3897     } else {
3898         // query from sandbox manager for sandbox bundle
3899         if (sandboxAppHelper_ == nullptr) {
3900             APP_LOGE("sandboxAppHelper_ is nullptr");
3901             return;
3902         }
3903         auto sandboxMap = sandboxAppHelper_->GetSandboxAppInfoMap();
3904         for (const auto &item : sandboxMap) {
3905             InnerBundleInfo info;
3906             size_t pos = item.first.rfind(Constants::FILE_UNDERLINE);
3907             if (pos == std::string::npos) {
3908                 APP_LOGW("sandbox map contains invalid element");
3909                 continue;
3910             }
3911             std::string innerBundleName = item.first.substr(0, pos);
3912             if (sandboxAppHelper_->GetSandboxAppInfo(innerBundleName, appIndex, userId, info) != ERR_OK) {
3913                 APP_LOGW("obtain innerBundleInfo of sandbox app failed");
3914                 continue;
3915             }
3916 
3917             int32_t responseUserId = info.GetResponseUserId(userId);
3918             GetMatchExtensionInfos(want, flags, responseUserId, info, infos);
3919         }
3920     }
3921     APP_LOGD("finish to ImplicitQueryAllExtensionInfos");
3922 }
3923 
ImplicitQueryAllExtensionInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & infos,int32_t appIndex) const3924 void BundleDataMgr::ImplicitQueryAllExtensionInfosV9(const Want &want, int32_t flags, int32_t userId,
3925     std::vector<ExtensionAbilityInfo> &infos, int32_t appIndex) const
3926 {
3927     APP_LOGD("begin to ImplicitQueryAllExtensionInfosV9");
3928     // query from bundleInfos_
3929     if (appIndex == 0) {
3930         for (const auto &item : bundleInfos_) {
3931             InnerBundleInfo innerBundleInfo;
3932             ErrCode ret = GetInnerBundleInfoWithFlagsV9(item.first, flags, innerBundleInfo, userId);
3933             if (ret != ERR_OK) {
3934                 APP_LOGE("ImplicitQueryExtensionAbilityInfos failed, bundleName:%{public}s", item.first.c_str());
3935                 continue;
3936             }
3937             int32_t responseUserId = innerBundleInfo.GetResponseUserId(userId);
3938             GetMatchExtensionInfosV9(want, flags, responseUserId, innerBundleInfo, infos);
3939         }
3940     } else {
3941         // query from sandbox manager for sandbox bundle
3942         if (sandboxAppHelper_ == nullptr) {
3943             APP_LOGE("sandboxAppHelper_ is nullptr");
3944             return;
3945         }
3946         auto sandboxMap = sandboxAppHelper_->GetSandboxAppInfoMap();
3947         for (const auto &item : sandboxMap) {
3948             InnerBundleInfo info;
3949             size_t pos = item.first.rfind(Constants::FILE_UNDERLINE);
3950             if (pos == std::string::npos) {
3951                 APP_LOGW("sandbox map contains invalid element");
3952                 continue;
3953             }
3954             std::string innerBundleName = item.first.substr(0, pos);
3955             if (sandboxAppHelper_->GetSandboxAppInfo(innerBundleName, appIndex, userId, info) != ERR_OK) {
3956                 APP_LOGW("obtain innerBundleInfo of sandbox app failed");
3957                 continue;
3958             }
3959 
3960             int32_t responseUserId = info.GetResponseUserId(userId);
3961             GetMatchExtensionInfosV9(want, flags, responseUserId, info, infos);
3962         }
3963     }
3964     APP_LOGD("finish to ImplicitQueryAllExtensionInfosV9");
3965 }
3966 
GetMatchExtensionInfos(const Want & want,int32_t flags,const int32_t & userId,const InnerBundleInfo & info,std::vector<ExtensionAbilityInfo> & infos) const3967 void BundleDataMgr::GetMatchExtensionInfos(const Want &want, int32_t flags, const int32_t &userId,
3968     const InnerBundleInfo &info, std::vector<ExtensionAbilityInfo> &infos) const
3969 {
3970     auto extensionSkillInfos = info.GetExtensionSkillInfos();
3971     auto extensionInfos = info.GetInnerExtensionInfos();
3972     for (const auto &skillInfos : extensionSkillInfos) {
3973         for (const auto &skill : skillInfos.second) {
3974             if (!skill.Match(want)) {
3975                 continue;
3976             }
3977             if (extensionInfos.find(skillInfos.first) == extensionInfos.end()) {
3978                 APP_LOGW("cannot find the extension info with %{public}s", skillInfos.first.c_str());
3979                 break;
3980             }
3981             ExtensionAbilityInfo extensionInfo = extensionInfos[skillInfos.first];
3982             AddExtensionSkillUrisInfo(flags, skill, extensionInfo);
3983             if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_APPLICATION) ==
3984                 GET_ABILITY_INFO_WITH_APPLICATION) {
3985                 info.GetApplicationInfo(
3986                     ApplicationFlag::GET_BASIC_APPLICATION_INFO |
3987                     ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT, userId,
3988                     extensionInfo.applicationInfo);
3989             }
3990             if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_PERMISSION) !=
3991                 GET_ABILITY_INFO_WITH_PERMISSION) {
3992                 extensionInfo.permissions.clear();
3993             }
3994             if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_METADATA) != GET_ABILITY_INFO_WITH_METADATA) {
3995                 extensionInfo.metadata.clear();
3996             }
3997             infos.emplace_back(extensionInfo);
3998             break;
3999         }
4000     }
4001 }
4002 
AddExtensionSkillUrisInfo(int32_t flags,const Skill & skill,ExtensionAbilityInfo & extensionAbilityInfo) const4003 void BundleDataMgr::AddExtensionSkillUrisInfo(int32_t flags, const Skill &skill,
4004     ExtensionAbilityInfo &extensionAbilityInfo) const
4005 {
4006     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_SKILL_URI) == GET_ABILITY_INFO_WITH_SKILL_URI) {
4007         std::vector<SkillUriForAbilityAndExtension> skillUriTmp;
4008         for (const SkillUri &uri : skill.uris) {
4009             SkillUriForAbilityAndExtension skillinfo;
4010             skillinfo.scheme = uri.scheme;
4011             skillinfo.host = uri.host;
4012             skillinfo.port = uri.port;
4013             skillinfo.path = uri.path;
4014             skillinfo.pathStartWith = uri.pathStartWith;
4015             skillinfo.pathRegex = uri.pathRegex;
4016             skillinfo.type = uri.type;
4017             skillUriTmp.emplace_back(skillinfo);
4018         }
4019         extensionAbilityInfo.skillUri = skillUriTmp;
4020     }
4021 }
4022 
GetMatchExtensionInfosV9(const Want & want,int32_t flags,int32_t userId,const InnerBundleInfo & info,std::vector<ExtensionAbilityInfo> & infos) const4023 void BundleDataMgr::GetMatchExtensionInfosV9(const Want &want, int32_t flags, int32_t userId,
4024     const InnerBundleInfo &info, std::vector<ExtensionAbilityInfo> &infos) const
4025 {
4026     auto extensionSkillInfos = info.GetExtensionSkillInfos();
4027     auto extensionInfos = info.GetInnerExtensionInfos();
4028     for (const auto &skillInfos : extensionSkillInfos) {
4029         for (const auto &skill : skillInfos.second) {
4030             if (!skill.Match(want)) {
4031                 continue;
4032             }
4033             if (extensionInfos.find(skillInfos.first) == extensionInfos.end()) {
4034                 APP_LOGW("cannot find the extension info with %{public}s", skillInfos.first.c_str());
4035                 break;
4036             }
4037             ExtensionAbilityInfo extensionInfo = extensionInfos[skillInfos.first];
4038             if ((static_cast<uint32_t>(flags) &
4039                 static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_APPLICATION)) ==
4040                 static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_APPLICATION)) {
4041                 info.GetApplicationInfoV9(static_cast<int32_t>(
4042                     GetApplicationFlag::GET_APPLICATION_INFO_DEFAULT), userId, extensionInfo.applicationInfo);
4043             }
4044             if ((static_cast<uint32_t>(flags) &
4045                 static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION)) !=
4046                 static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION)) {
4047                 extensionInfo.permissions.clear();
4048             }
4049             if ((static_cast<uint32_t>(flags) &
4050                 static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_METADATA)) !=
4051                 static_cast<int32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_METADATA)) {
4052                 extensionInfo.metadata.clear();
4053             }
4054             infos.emplace_back(extensionInfo);
4055             break;
4056         }
4057     }
4058 }
4059 
QueryExtensionAbilityInfos(const ExtensionAbilityType & extensionType,const int32_t & userId,std::vector<ExtensionAbilityInfo> & extensionInfos) const4060 bool BundleDataMgr::QueryExtensionAbilityInfos(const ExtensionAbilityType &extensionType, const int32_t &userId,
4061     std::vector<ExtensionAbilityInfo> &extensionInfos) const
4062 {
4063     int32_t requestUserId = GetUserId(userId);
4064     if (requestUserId == Constants::INVALID_USERID) {
4065         return false;
4066     }
4067     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4068     for (const auto &item : bundleInfos_) {
4069         const InnerBundleInfo &innerBundleInfo = item.second;
4070         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
4071         if (CheckInnerBundleInfoWithFlags(innerBundleInfo, 0, responseUserId) != ERR_OK) {
4072             continue;
4073         }
4074         auto innerExtensionInfos = innerBundleInfo.GetInnerExtensionInfos();
4075         for (const auto &info : innerExtensionInfos) {
4076             if (info.second.type == extensionType) {
4077                 ExtensionAbilityInfo extensionAbilityInfo = info.second;
4078                 innerBundleInfo.GetApplicationInfo(
4079                     ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT, responseUserId,
4080                     extensionAbilityInfo.applicationInfo);
4081                 extensionInfos.emplace_back(extensionAbilityInfo);
4082             }
4083         }
4084     }
4085     return true;
4086 }
4087 
QueryExtensionAbilityInfoByUri(const std::string & uri,int32_t userId,ExtensionAbilityInfo & extensionAbilityInfo) const4088 bool BundleDataMgr::QueryExtensionAbilityInfoByUri(const std::string &uri, int32_t userId,
4089     ExtensionAbilityInfo &extensionAbilityInfo) const
4090 {
4091     int32_t requestUserId = GetUserId(userId);
4092     if (requestUserId == Constants::INVALID_USERID) {
4093         APP_LOGE("invalid userId -1");
4094         return false;
4095     }
4096     if (uri.empty()) {
4097         APP_LOGE("uri empty");
4098         return false;
4099     }
4100     std::string convertUri = uri;
4101     // example of valid param uri : fileShare:///com.example.FileShare/person/10
4102     // example of convertUri : fileShare://com.example.FileShare
4103     size_t schemePos = uri.find(Constants::PARAM_URI_SEPARATOR);
4104     if (schemePos != uri.npos) {
4105         // 1. cut string
4106         size_t cutPos = uri.find(Constants::SEPARATOR, schemePos + Constants::PARAM_URI_SEPARATOR_LEN);
4107         if (cutPos != uri.npos) {
4108             convertUri = uri.substr(0, cutPos);
4109         }
4110         // 2. replace :/// with ://
4111         convertUri.replace(schemePos, Constants::PARAM_URI_SEPARATOR_LEN, Constants::URI_SEPARATOR);
4112     } else {
4113         if (convertUri.compare(0, DATA_PROXY_URI_PREFIX_LEN, DATA_PROXY_URI_PREFIX) != 0) {
4114             APP_LOGE("invalid uri : %{private}s", uri.c_str());
4115             return false;
4116         }
4117     }
4118     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4119     if (bundleInfos_.empty()) {
4120         APP_LOGE("bundleInfos_ data is empty, uri:%{public}s", uri.c_str());
4121         return false;
4122     }
4123     for (const auto &item : bundleInfos_) {
4124         const InnerBundleInfo &info = item.second;
4125         if (info.IsDisabled()) {
4126             APP_LOGE("app %{public}s is disabled", info.GetBundleName().c_str());
4127             continue;
4128         }
4129 
4130         int32_t responseUserId = info.GetResponseUserId(requestUserId);
4131         if (!info.GetApplicationEnabled(responseUserId)) {
4132             continue;
4133         }
4134 
4135         bool ret = info.FindExtensionAbilityInfoByUri(convertUri, extensionAbilityInfo);
4136         if (!ret) {
4137             continue;
4138         }
4139         info.GetApplicationInfo(
4140             ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT, responseUserId,
4141             extensionAbilityInfo.applicationInfo);
4142         return true;
4143     }
4144     APP_LOGE("QueryExtensionAbilityInfoByUri (%{private}s) failed.", uri.c_str());
4145     return false;
4146 }
4147 
GetAllUriPrefix(std::vector<std::string> & uriPrefixList,int32_t userId,const std::string & excludeModule) const4148 void BundleDataMgr::GetAllUriPrefix(std::vector<std::string> &uriPrefixList, int32_t userId,
4149     const std::string &excludeModule) const
4150 {
4151     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4152     APP_LOGD("begin to GetAllUriPrefix, userId : %{public}d, excludeModule : %{public}s",
4153         userId, excludeModule.c_str());
4154     if (bundleInfos_.empty()) {
4155         APP_LOGE("bundleInfos_ is empty");
4156         return;
4157     }
4158     for (const auto &item : bundleInfos_) {
4159         item.second.GetUriPrefixList(uriPrefixList, userId, excludeModule);
4160         item.second.GetUriPrefixList(uriPrefixList, Constants::DEFAULT_USERID, excludeModule);
4161     }
4162 }
4163 
GetStringById(const std::string & bundleName,const std::string & moduleName,uint32_t resId,int32_t userId,const std::string & localeInfo)4164 std::string BundleDataMgr::GetStringById(const std::string &bundleName, const std::string &moduleName,
4165     uint32_t resId, int32_t userId, const std::string &localeInfo)
4166 {
4167     APP_LOGD("GetStringById:%{public}s , %{public}s, %{public}d", bundleName.c_str(), moduleName.c_str(), resId);
4168 #ifdef GLOBAL_RESMGR_ENABLE
4169     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4170     std::shared_ptr<OHOS::Global::Resource::ResourceManager> resourceManager =
4171         GetResourceManager(bundleName, moduleName, userId);
4172     if (resourceManager == nullptr) {
4173         APP_LOGE("InitResourceManager failed");
4174         return Constants::EMPTY_STRING;
4175     }
4176     std::string label;
4177     OHOS::Global::Resource::RState errValue = resourceManager->GetStringById(resId, label);
4178     if (errValue != OHOS::Global::Resource::RState::SUCCESS) {
4179         APP_LOGE("GetStringById failed, bundleName:%{public}s, id:%{public}d", bundleName.c_str(), resId);
4180         return Constants::EMPTY_STRING;
4181     }
4182     return label;
4183 #else
4184     APP_LOGW("GLOBAL_RESMGR_ENABLE is false");
4185     return Constants::EMPTY_STRING;
4186 #endif
4187 }
4188 
GetIconById(const std::string & bundleName,const std::string & moduleName,uint32_t resId,uint32_t density,int32_t userId)4189 std::string BundleDataMgr::GetIconById(
4190     const std::string &bundleName, const std::string &moduleName, uint32_t resId, uint32_t density, int32_t userId)
4191 {
4192     APP_LOGI("GetIconById bundleName:%{public}s, moduleName:%{public}s, resId:%{public}d, density:%{public}d",
4193         bundleName.c_str(), moduleName.c_str(), resId, density);
4194 #ifdef GLOBAL_RESMGR_ENABLE
4195     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4196     std::shared_ptr<OHOS::Global::Resource::ResourceManager> resourceManager =
4197         GetResourceManager(bundleName, moduleName, userId);
4198     if (resourceManager == nullptr) {
4199         APP_LOGE("InitResourceManager failed");
4200         return Constants::EMPTY_STRING;
4201     }
4202     std::string base64;
4203     OHOS::Global::Resource::RState errValue = resourceManager->GetMediaBase64DataById(resId, base64, density);
4204     if (errValue != OHOS::Global::Resource::RState::SUCCESS) {
4205         APP_LOGE("GetIconById failed, bundleName:%{public}s, id:%{public}d", bundleName.c_str(), resId);
4206         return Constants::EMPTY_STRING;
4207     }
4208     return base64;
4209 #else
4210     APP_LOGW("GLOBAL_RESMGR_ENABLE is false");
4211     return Constants::EMPTY_STRING;
4212 #endif
4213 }
4214 
4215 #ifdef GLOBAL_RESMGR_ENABLE
GetResourceManager(const std::string & bundleName,const std::string & moduleName,int32_t userId,const std::string & localeInfo) const4216 std::shared_ptr<Global::Resource::ResourceManager> BundleDataMgr::GetResourceManager(
4217     const std::string &bundleName, const std::string &moduleName, int32_t userId, const std::string &localeInfo) const
4218 {
4219     InnerBundleInfo innerBundleInfo;
4220     if (!GetInnerBundleInfoWithFlags(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, innerBundleInfo, userId)) {
4221         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
4222         return nullptr;
4223     }
4224     int32_t responseUserId = innerBundleInfo.GetResponseUserId(userId);
4225     BundleInfo bundleInfo;
4226     innerBundleInfo.GetBundleInfo(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, responseUserId);
4227     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
4228     for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
4229         std::string moduleResPath;
4230         if (moduleName.empty() || moduleName == hapModuleInfo.moduleName) {
4231             moduleResPath = hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath;
4232         }
4233         if (!moduleResPath.empty()) {
4234             APP_LOGD("DistributedBms::InitResourceManager, moduleResPath: %{private}s", moduleResPath.c_str());
4235             if (!resourceManager->AddResource(moduleResPath.c_str())) {
4236                 APP_LOGW("DistributedBms::InitResourceManager AddResource failed");
4237             }
4238         }
4239     }
4240 
4241     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
4242 #ifdef GLOBAL_I18_ENABLE
4243     std::map<std::string, std::string> configs;
4244     OHOS::Global::I18n::LocaleInfo locale(localeInfo, configs);
4245     resConfig->SetLocaleInfo(locale.GetLanguage().c_str(), locale.GetScript().c_str(), locale.GetRegion().c_str());
4246 #endif
4247     resourceManager->UpdateResConfig(*resConfig);
4248     return resourceManager;
4249 }
4250 #endif
4251 
GetAllPreInstallBundleInfos()4252 const std::vector<PreInstallBundleInfo> BundleDataMgr::GetAllPreInstallBundleInfos()
4253 {
4254     std::vector<PreInstallBundleInfo> preInstallBundleInfos;
4255     LoadAllPreInstallBundleInfos(preInstallBundleInfos);
4256     return preInstallBundleInfos;
4257 }
4258 
ImplicitQueryInfoByPriority(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,ExtensionAbilityInfo & extensionInfo)4259 bool BundleDataMgr::ImplicitQueryInfoByPriority(const Want &want, int32_t flags, int32_t userId,
4260     AbilityInfo &abilityInfo, ExtensionAbilityInfo &extensionInfo)
4261 {
4262     int32_t requestUserId = GetUserId(userId);
4263     if (requestUserId == Constants::INVALID_USERID) {
4264         APP_LOGE("invalid userId");
4265         return false;
4266     }
4267     std::vector<AbilityInfo> abilityInfos;
4268     bool abilityValid =
4269         ImplicitQueryAbilityInfos(want, flags, requestUserId, abilityInfos) && (abilityInfos.size() > 0);
4270     std::vector<ExtensionAbilityInfo> extensionInfos;
4271     bool extensionValid =
4272         ImplicitQueryExtensionInfos(want, flags, requestUserId, extensionInfos) && (extensionInfos.size() > 0);
4273     if (!abilityValid && !extensionValid) {
4274         // both invalid
4275         APP_LOGE("can't find target AbilityInfo or ExtensionAbilityInfo");
4276         return false;
4277     }
4278     if (abilityValid && extensionValid) {
4279         // both valid
4280         if (abilityInfos[0].priority >= extensionInfos[0].priority) {
4281             APP_LOGD("find target AbilityInfo with higher priority, name : %{public}s", abilityInfos[0].name.c_str());
4282             abilityInfo = abilityInfos[0];
4283         } else {
4284             APP_LOGD("find target ExtensionAbilityInfo with higher priority, name : %{public}s",
4285                 extensionInfos[0].name.c_str());
4286             extensionInfo = extensionInfos[0];
4287         }
4288     } else if (abilityValid) {
4289         // only ability valid
4290         APP_LOGD("find target AbilityInfo, name : %{public}s", abilityInfos[0].name.c_str());
4291         abilityInfo = abilityInfos[0];
4292     } else {
4293         // only extension valid
4294         APP_LOGD("find target ExtensionAbilityInfo, name : %{public}s", extensionInfos[0].name.c_str());
4295         extensionInfo = extensionInfos[0];
4296     }
4297     return true;
4298 }
4299 
ImplicitQueryInfos(const Want & want,int32_t flags,int32_t userId,bool withDefault,std::vector<AbilityInfo> & abilityInfos,std::vector<ExtensionAbilityInfo> & extensionInfos)4300 bool BundleDataMgr::ImplicitQueryInfos(const Want &want, int32_t flags, int32_t userId, bool withDefault,
4301     std::vector<AbilityInfo> &abilityInfos, std::vector<ExtensionAbilityInfo> &extensionInfos)
4302 {
4303     // step1 : find default infos, current only support default file types
4304 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
4305     if (withDefault) {
4306         std::string action = want.GetAction();
4307         std::string uri = want.GetUriString();
4308         std::string type = want.GetType();
4309         APP_LOGD("action : %{public}s, uri : %{public}s, type : %{public}s", action.c_str(), uri.c_str(), type.c_str());
4310         if (action == Constants::ACTION_VIEW_DATA && !type.empty() && want.GetEntities().empty() && uri.empty()) {
4311             BundleInfo bundleInfo;
4312             ErrCode ret = DefaultAppMgr::GetInstance().GetDefaultApplication(userId, type, bundleInfo);
4313             if (ret == ERR_OK && bundleInfo.abilityInfos.size() == 1) {
4314                 abilityInfos = bundleInfo.abilityInfos;
4315                 APP_LOGD("find default ability.");
4316                 return true;
4317             } else if (ret == ERR_OK && bundleInfo.extensionInfos.size() == 1) {
4318                 extensionInfos = bundleInfo.extensionInfos;
4319                 APP_LOGD("find default extension.");
4320                 return true;
4321             } else if (ret == ERR_OK) {
4322                 APP_LOGD("GetDefaultApplication failed.");
4323             }
4324         }
4325     }
4326 #endif
4327     // step2 : implicit query infos
4328     bool abilityRet =
4329         ImplicitQueryAbilityInfos(want, flags, userId, abilityInfos) && (abilityInfos.size() > 0);
4330     APP_LOGD("abilityRet: %{public}d, abilityInfos size: %{public}zu", abilityRet, abilityInfos.size());
4331 
4332     bool extensionRet =
4333         ImplicitQueryExtensionInfos(want, flags, userId, extensionInfos) && (extensionInfos.size() > 0);
4334     APP_LOGD("extensionRet: %{public}d, extensionInfos size: %{public}zu", extensionRet, extensionInfos.size());
4335     return abilityRet || extensionRet;
4336 }
4337 
GetAllDependentModuleNames(const std::string & bundleName,const std::string & moduleName,std::vector<std::string> & dependentModuleNames)4338 bool BundleDataMgr::GetAllDependentModuleNames(const std::string &bundleName, const std::string &moduleName,
4339     std::vector<std::string> &dependentModuleNames)
4340 {
4341     APP_LOGD("GetAllDependentModuleNames bundleName: %{public}s, moduleName: %{public}s",
4342         bundleName.c_str(), moduleName.c_str());
4343     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4344     auto item = bundleInfos_.find(bundleName);
4345     if (item == bundleInfos_.end()) {
4346         APP_LOGE("GetAllDependentModuleNames: bundleName:%{public}s not find", bundleName.c_str());
4347         return false;
4348     }
4349     const InnerBundleInfo &innerBundleInfo = item->second;
4350     return innerBundleInfo.GetAllDependentModuleNames(moduleName, dependentModuleNames);
4351 }
4352 
UpdateRemovable(const std::string & bundleName,bool removable)4353 void BundleDataMgr::UpdateRemovable(
4354     const std::string &bundleName, bool removable)
4355 {
4356     APP_LOGD("UpdateRemovable %{public}s", bundleName.c_str());
4357     if (bundleName.empty()) {
4358         APP_LOGE("bundleName is empty");
4359         return;
4360     }
4361 
4362     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4363     auto infoItem = bundleInfos_.find(bundleName);
4364     if (infoItem == bundleInfos_.end()) {
4365         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
4366         return;
4367     }
4368 
4369     if (infoItem->second.IsRemovable() != removable) {
4370         infoItem->second.UpdateRemovable(true, removable);
4371         SaveInnerBundleInfo(infoItem->second);
4372     }
4373 }
4374 
UpdatePrivilegeCapability(const std::string & bundleName,const ApplicationInfo & appInfo)4375 void BundleDataMgr::UpdatePrivilegeCapability(
4376     const std::string &bundleName, const ApplicationInfo &appInfo)
4377 {
4378     APP_LOGD("UpdatePrivilegeCapability %{public}s", bundleName.c_str());
4379     if (bundleName.empty()) {
4380         APP_LOGE("bundleName is empty");
4381         return;
4382     }
4383 
4384     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4385     auto infoItem = bundleInfos_.find(bundleName);
4386     if (infoItem == bundleInfos_.end()) {
4387         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
4388         return;
4389     }
4390 
4391     infoItem->second.UpdatePrivilegeCapability(appInfo);
4392 }
4393 
FetchInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & innerBundleInfo)4394 bool BundleDataMgr::FetchInnerBundleInfo(
4395     const std::string &bundleName, InnerBundleInfo &innerBundleInfo)
4396 {
4397     APP_LOGD("FetchInnerBundleInfo %{public}s", bundleName.c_str());
4398     if (bundleName.empty()) {
4399         APP_LOGE("bundleName is empty");
4400         return false;
4401     }
4402 
4403     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4404     auto infoItem = bundleInfos_.find(bundleName);
4405     if (infoItem == bundleInfos_.end()) {
4406         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
4407         return false;
4408     }
4409 
4410     innerBundleInfo = infoItem->second;
4411     return true;
4412 }
4413 
4414 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
QueryInfoAndSkillsByElement(int32_t userId,const Element & element,AbilityInfo & abilityInfo,ExtensionAbilityInfo & extensionInfo,std::vector<Skill> & skills) const4415 bool BundleDataMgr::QueryInfoAndSkillsByElement(int32_t userId, const Element& element,
4416     AbilityInfo& abilityInfo, ExtensionAbilityInfo& extensionInfo, std::vector<Skill>& skills) const
4417 {
4418     APP_LOGD("begin to QueryInfoAndSkillsByElement.");
4419     const std::string& bundleName = element.bundleName;
4420     const std::string& moduleName = element.moduleName;
4421     const std::string& abilityName = element.abilityName;
4422     const std::string& extensionName = element.extensionName;
4423     Want want;
4424     ElementName elementName("", bundleName, abilityName, moduleName);
4425     want.SetElement(elementName);
4426     bool isAbility = !element.abilityName.empty();
4427     bool ret = false;
4428     if (isAbility) {
4429         // get ability info
4430         ret = ExplicitQueryAbilityInfo(want, GET_ABILITY_INFO_DEFAULT, userId, abilityInfo);
4431         if (!ret) {
4432             APP_LOGE("ExplicitQueryAbilityInfo failed, abilityName:%{public}s", element.abilityName.c_str());
4433             return false;
4434         }
4435     } else {
4436         // get extension info
4437         elementName.SetAbilityName(extensionName);
4438         want.SetElement(elementName);
4439         ret = ExplicitQueryExtensionInfo(want, GET_EXTENSION_INFO_DEFAULT, userId, extensionInfo);
4440         if (!ret) {
4441             APP_LOGE("ExplicitQueryExtensionInfo failed, extensionName:%{public}s", extensionName.c_str());
4442             return false;
4443         }
4444     }
4445 
4446     // get skills info
4447     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4448     if (bundleInfos_.empty()) {
4449         APP_LOGE("bundleInfos_ is empty.");
4450         return false;
4451     }
4452     auto item = bundleInfos_.find(bundleName);
4453     if (item == bundleInfos_.end()) {
4454         APP_LOGE("can't find bundleName : %{public}s.", bundleName.c_str());
4455         return false;
4456     }
4457     const InnerBundleInfo& innerBundleInfo = item->second;
4458     if (isAbility) {
4459         std::string key;
4460         key.append(bundleName).append(".").append(abilityInfo.package).append(".").append(abilityName);
4461         APP_LOGD("begin to find ability skills, key : %{public}s.", key.c_str());
4462         for (const auto& infoItem : innerBundleInfo.GetInnerSkillInfos()) {
4463             if (infoItem.first == key) {
4464                 skills = infoItem.second;
4465                 APP_LOGD("find ability skills success.");
4466                 break;
4467             }
4468         }
4469     } else {
4470         std::string key;
4471         key.append(bundleName).append(".").append(moduleName).append(".").append(extensionName);
4472         APP_LOGD("begin to find extension skills, key : %{public}s.", key.c_str());
4473         for (const auto& infoItem : innerBundleInfo.GetExtensionSkillInfos()) {
4474             if (infoItem.first == key) {
4475                 skills = infoItem.second;
4476                 APP_LOGD("find extension skills success.");
4477                 break;
4478             }
4479         }
4480     }
4481     APP_LOGD("QueryInfoAndSkillsByElement success.");
4482     return true;
4483 }
4484 
GetElement(int32_t userId,const ElementName & elementName,Element & element) const4485 bool BundleDataMgr::GetElement(int32_t userId, const ElementName& elementName, Element& element) const
4486 {
4487     APP_LOGD("begin to GetElement.");
4488     const std::string& bundleName = elementName.GetBundleName();
4489     const std::string& moduleName = elementName.GetModuleName();
4490     const std::string& abilityName = elementName.GetAbilityName();
4491     if (bundleName.empty() || moduleName.empty() || abilityName.empty()) {
4492         APP_LOGE("bundleName or moduleName or abilityName is empty.");
4493         return false;
4494     }
4495     Want want;
4496     want.SetElement(elementName);
4497     AbilityInfo abilityInfo;
4498     bool ret = ExplicitQueryAbilityInfo(want, GET_ABILITY_INFO_DEFAULT, userId, abilityInfo);
4499     if (ret) {
4500         APP_LOGD("ElementName is ability.");
4501         element.bundleName = bundleName;
4502         element.moduleName = moduleName;
4503         element.abilityName = abilityName;
4504         return true;
4505     }
4506 
4507     ExtensionAbilityInfo extensionInfo;
4508     ret = ExplicitQueryExtensionInfo(want, GET_EXTENSION_INFO_DEFAULT, userId, extensionInfo);
4509     if (ret) {
4510         APP_LOGD("ElementName is extension.");
4511         element.bundleName = bundleName;
4512         element.moduleName = moduleName;
4513         element.extensionName = abilityName;
4514         return true;
4515     }
4516 
4517     APP_LOGE("ElementName doesn't exist.");
4518     return false;
4519 }
4520 #endif
4521 
GetMediaData(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,std::unique_ptr<uint8_t[]> & mediaDataPtr,size_t & len,int32_t userId) const4522 ErrCode BundleDataMgr::GetMediaData(const std::string &bundleName, const std::string &moduleName,
4523     const std::string &abilityName, std::unique_ptr<uint8_t[]> &mediaDataPtr, size_t &len, int32_t userId) const
4524 {
4525     APP_LOGI("begin to GetMediaData.");
4526 #ifdef GLOBAL_RESMGR_ENABLE
4527     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4528     int32_t requestUserId = GetUserId(userId);
4529     if (requestUserId == Constants::INVALID_USERID) {
4530         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
4531     }
4532     InnerBundleInfo innerBundleInfo;
4533     ErrCode errCode = GetInnerBundleInfoWithFlagsV9(
4534         bundleName, BundleFlag::GET_BUNDLE_DEFAULT, innerBundleInfo, requestUserId);
4535     if (errCode != ERR_OK) {
4536         return errCode;
4537     }
4538     AbilityInfo abilityInfo;
4539     errCode = FindAbilityInfoInBundleInfo(innerBundleInfo, moduleName, abilityName, abilityInfo);
4540     if (errCode != ERR_OK) {
4541         return errCode;
4542     }
4543     bool isEnable;
4544     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
4545     errCode = innerBundleInfo.IsAbilityEnabledV9(abilityInfo, responseUserId, isEnable);
4546     if (errCode != ERR_OK) {
4547         return errCode;
4548     }
4549     if (!isEnable) {
4550         APP_LOGE("%{public}s ability disabled: %{public}s", bundleName.c_str(), abilityName.c_str());
4551         return ERR_BUNDLE_MANAGER_ABILITY_DISABLED;
4552     }
4553     std::shared_ptr<Global::Resource::ResourceManager> resourceManager =
4554         GetResourceManager(bundleName, abilityInfo.moduleName, responseUserId);
4555     if (resourceManager == nullptr) {
4556         APP_LOGE("InitResourceManager failed, bundleName:%{public}s", bundleName.c_str());
4557         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4558     }
4559     OHOS::Global::Resource::RState ret =
4560         resourceManager->GetMediaDataById(static_cast<uint32_t>(abilityInfo.iconId), len, mediaDataPtr);
4561     if (ret != OHOS::Global::Resource::RState::SUCCESS || mediaDataPtr == nullptr || len == 0) {
4562         APP_LOGE("GetMediaDataById failed, bundleName:%{public}s", bundleName.c_str());
4563         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4564     }
4565     return ERR_OK;
4566 #else
4567     return ERR_BUNDLE_MANAGER_GLOBAL_RES_MGR_ENABLE_DISABLED;
4568 #endif
4569 }
4570 
GetStatusCallbackMutex()4571 std::shared_mutex &BundleDataMgr::GetStatusCallbackMutex()
4572 {
4573     return callbackMutex_;
4574 }
4575 
GetCallBackList() const4576 std::vector<sptr<IBundleStatusCallback>> BundleDataMgr::GetCallBackList() const
4577 {
4578     return callbackList_;
4579 }
4580 
UpdateQuickFixInnerBundleInfo(const std::string & bundleName,const InnerBundleInfo & innerBundleInfo)4581 bool BundleDataMgr::UpdateQuickFixInnerBundleInfo(const std::string &bundleName,
4582     const InnerBundleInfo &innerBundleInfo)
4583 {
4584     APP_LOGD("to update info:%{public}s", bundleName.c_str());
4585     if (bundleName.empty()) {
4586         APP_LOGE("update info fail, empty bundle name");
4587         return false;
4588     }
4589 
4590     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4591     auto infoItem = bundleInfos_.find(bundleName);
4592     if (infoItem == bundleInfos_.end()) {
4593         APP_LOGE("bundle:%{public}s info is not existed", bundleName.c_str());
4594         return false;
4595     }
4596 
4597     if (dataStorage_->SaveStorageBundleInfo(innerBundleInfo)) {
4598         bundleInfos_.at(bundleName) = innerBundleInfo;
4599         return true;
4600     }
4601     APP_LOGE("to update info:%{public}s failed", bundleName.c_str());
4602     return false;
4603 }
4604 
UpdateInnerBundleInfo(const InnerBundleInfo & innerBundleInfo)4605 bool BundleDataMgr::UpdateInnerBundleInfo(const InnerBundleInfo &innerBundleInfo)
4606 {
4607     std::string bundleName = innerBundleInfo.GetBundleName();
4608     if (bundleName.empty()) {
4609         APP_LOGE("UpdateInnerBundleInfo failed, empty bundle name");
4610         return false;
4611     }
4612     APP_LOGD("UpdateInnerBundleInfo:%{public}s", bundleName.c_str());
4613     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4614     auto infoItem = bundleInfos_.find(bundleName);
4615     if (infoItem == bundleInfos_.end()) {
4616         APP_LOGE("bundle:%{public}s info is not existed", bundleName.c_str());
4617         return false;
4618     }
4619 
4620     if (dataStorage_->SaveStorageBundleInfo(innerBundleInfo)) {
4621         bundleInfos_.at(bundleName) = innerBundleInfo;
4622         return true;
4623     }
4624     APP_LOGE("to update InnerBundleInfo:%{public}s failed", bundleName.c_str());
4625     return false;
4626 }
4627 
QueryOverlayInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & info)4628 bool BundleDataMgr::QueryOverlayInnerBundleInfo(const std::string &bundleName, InnerBundleInfo &info)
4629 {
4630     APP_LOGI("start to query overlay innerBundleInfo");
4631     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4632     if (bundleInfos_.find(bundleName) != bundleInfos_.end()) {
4633         info = bundleInfos_.at(bundleName);
4634         return true;
4635     }
4636 
4637     APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
4638     return false;
4639 }
4640 
SaveOverlayInfo(const std::string & bundleName,InnerBundleInfo & innerBundleInfo)4641 void BundleDataMgr::SaveOverlayInfo(const std::string &bundleName, InnerBundleInfo &innerBundleInfo)
4642 {
4643     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4644     innerBundleInfo.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
4645     if (!dataStorage_->SaveStorageBundleInfo(innerBundleInfo)) {
4646         APP_LOGE("update storage failed bundle:%{public}s", bundleName.c_str());
4647         return;
4648     }
4649     bundleInfos_.at(bundleName) = innerBundleInfo;
4650 }
4651 
GetAppProvisionInfo(const std::string & bundleName,int32_t userId,AppProvisionInfo & appProvisionInfo)4652 ErrCode BundleDataMgr::GetAppProvisionInfo(const std::string &bundleName, int32_t userId,
4653     AppProvisionInfo &appProvisionInfo)
4654 {
4655     if (!HasUserId(userId)) {
4656         APP_LOGE("GetAppProvisionInfo user is not existed. bundleName:%{public}s", bundleName.c_str());
4657         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
4658     }
4659     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4660     auto infoItem = bundleInfos_.find(bundleName);
4661     if (infoItem == bundleInfos_.end()) {
4662         APP_LOGE("bundleName:%{public}s not exist", bundleName.c_str());
4663         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4664     }
4665     if (infoItem->second.GetApplicationBundleType() != BundleType::SHARED) {
4666         int32_t responseUserId = infoItem->second.GetResponseUserId(userId);
4667         if (responseUserId == Constants::INVALID_USERID) {
4668             return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4669         }
4670     }
4671     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->GetAppProvisionInfo(bundleName, appProvisionInfo)) {
4672         APP_LOGE("bundleName:%{public}s GetAppProvisionInfo failed.", bundleName.c_str());
4673         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4674     }
4675     return ERR_OK;
4676 }
4677 
GetProvisionMetadata(const std::string & bundleName,int32_t userId,std::vector<Metadata> & provisionMetadatas) const4678 ErrCode BundleDataMgr::GetProvisionMetadata(const std::string &bundleName, int32_t userId,
4679     std::vector<Metadata> &provisionMetadatas) const
4680 {
4681     // Reserved interface
4682     return ERR_OK;
4683 }
4684 
GetAllSharedBundleInfo(std::vector<SharedBundleInfo> & sharedBundles) const4685 ErrCode BundleDataMgr::GetAllSharedBundleInfo(std::vector<SharedBundleInfo> &sharedBundles) const
4686 {
4687     APP_LOGD("GetAllSharedBundleInfo");
4688     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4689 
4690     for (const auto& [key, innerBundleInfo] : bundleInfos_) {
4691         if (innerBundleInfo.GetApplicationBundleType() != BundleType::SHARED) {
4692             continue;
4693         }
4694         SharedBundleInfo sharedBundleInfo;
4695         innerBundleInfo.GetSharedBundleInfo(sharedBundleInfo);
4696         sharedBundles.emplace_back(sharedBundleInfo);
4697     }
4698 
4699     return ERR_OK;
4700 }
4701 
GetSharedBundleInfo(const std::string & bundleName,const std::string & moduleName,std::vector<SharedBundleInfo> & sharedBundles)4702 ErrCode BundleDataMgr::GetSharedBundleInfo(const std::string &bundleName, const std::string &moduleName,
4703     std::vector<SharedBundleInfo> &sharedBundles)
4704 {
4705     APP_LOGD("GetSharedBundleInfo");
4706     if (bundleName.empty() || moduleName.empty()) {
4707         APP_LOGE("bundleName or moduleName is empty");
4708         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
4709     }
4710 
4711     std::vector<Dependency> dependencies;
4712     ErrCode errCode = GetSharedDependencies(bundleName, moduleName, dependencies);
4713     if (errCode != ERR_OK) {
4714         APP_LOGE("GetSharedDependencies failed errCode is %{public}d, bundleName:%{public}s",
4715             errCode, bundleName.c_str());
4716         return errCode;
4717     }
4718 
4719     for (const auto& dep : dependencies) {
4720         SharedBundleInfo sharedBundleInfo;
4721         errCode = GetSharedBundleInfoBySelf(dep.bundleName, sharedBundleInfo);
4722         if (errCode != ERR_OK) {
4723             APP_LOGE("GetSharedBundleInfoBySelf failed errCode is %{public}d, bundleName:%{public}s",
4724                 errCode, bundleName.c_str());
4725             return errCode;
4726         }
4727         sharedBundles.emplace_back(sharedBundleInfo);
4728     }
4729 
4730     return ERR_OK;
4731 }
4732 
GetSharedBundleInfoBySelf(const std::string & bundleName,SharedBundleInfo & sharedBundleInfo)4733 ErrCode BundleDataMgr::GetSharedBundleInfoBySelf(const std::string &bundleName, SharedBundleInfo &sharedBundleInfo)
4734 {
4735     APP_LOGD("GetSharedBundleInfoBySelf bundleName: %{public}s", bundleName.c_str());
4736     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4737     auto infoItem = bundleInfos_.find(bundleName);
4738     if (infoItem == bundleInfos_.end()) {
4739         APP_LOGE("GetSharedBundleInfoBySelf failed, can not find bundle %{public}s",
4740             bundleName.c_str());
4741         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4742     }
4743     const InnerBundleInfo &innerBundleInfo = infoItem->second;
4744     if (innerBundleInfo.GetApplicationBundleType() != BundleType::SHARED) {
4745         APP_LOGE("GetSharedBundleInfoBySelf failed, the bundle(%{public}s) is not shared library",
4746             bundleName.c_str());
4747         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4748     }
4749     innerBundleInfo.GetSharedBundleInfo(sharedBundleInfo);
4750     APP_LOGD("GetSharedBundleInfoBySelf(%{public}s) successfully)", bundleName.c_str());
4751     return ERR_OK;
4752 }
4753 
GetSharedDependencies(const std::string & bundleName,const std::string & moduleName,std::vector<Dependency> & dependencies)4754 ErrCode BundleDataMgr::GetSharedDependencies(const std::string &bundleName, const std::string &moduleName,
4755     std::vector<Dependency> &dependencies)
4756 {
4757     APP_LOGD("GetSharedDependencies bundleName: %{public}s, moduleName: %{public}s",
4758         bundleName.c_str(), moduleName.c_str());
4759     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4760     auto item = bundleInfos_.find(bundleName);
4761     if (item == bundleInfos_.end()) {
4762         APP_LOGE("GetSharedDependencies failed, can not find bundle %{public}s", bundleName.c_str());
4763         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4764     }
4765     const InnerBundleInfo &innerBundleInfo = item->second;
4766     if (!innerBundleInfo.GetAllSharedDependencies(moduleName, dependencies)) {
4767         APP_LOGE("GetSharedDependencies failed, can not find module %{public}s", moduleName.c_str());
4768         return ERR_BUNDLE_MANAGER_MODULE_NOT_EXIST;
4769     }
4770     APP_LOGD("GetSharedDependencies(bundle %{public}s, module %{public}s) successfully)",
4771         bundleName.c_str(), moduleName.c_str());
4772     return ERR_OK;
4773 }
4774 
CheckHspVersionIsRelied(int32_t versionCode,const InnerBundleInfo & info) const4775 bool BundleDataMgr::CheckHspVersionIsRelied(int32_t versionCode, const InnerBundleInfo &info) const
4776 {
4777     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4778     std::string hspBundleName = info.GetBundleName();
4779     if (versionCode == Constants::ALL_VERSIONCODE) {
4780         // uninstall hsp bundle, check other bundle denpendency
4781         return CheckHspBundleIsRelied(hspBundleName);
4782     }
4783     std::vector<std::string> hspModules = info.GetAllHspModuleNamesForVersion(static_cast<uint32_t>(versionCode));
4784     // check whether has higher version
4785     std::vector<uint32_t> versionCodes = info.GetAllHspVersion();
4786     for (const auto &item : versionCodes) {
4787         if (item > static_cast<uint32_t>(versionCode)) {
4788             return false;
4789         }
4790     }
4791     // check other bundle denpendency
4792     for (const auto &[bundleName, innerBundleInfo] : bundleInfos_) {
4793         if (bundleName == hspBundleName) {
4794             continue;
4795         }
4796         std::vector<Dependency> dependencyList = innerBundleInfo.GetDependencies();
4797         for (const auto &dependencyItem : dependencyList) {
4798             if (dependencyItem.bundleName == hspBundleName &&
4799                 std::find(hspModules.begin(), hspModules.end(), dependencyItem.moduleName) != hspModules.end()) {
4800                 return true;
4801             }
4802         }
4803     }
4804     return false;
4805 }
4806 
CheckHspBundleIsRelied(const std::string & hspBundleName) const4807 bool BundleDataMgr::CheckHspBundleIsRelied(const std::string &hspBundleName) const
4808 {
4809     for (const auto &[bundleName, innerBundleInfo] : bundleInfos_) {
4810         if (bundleName == hspBundleName) {
4811             continue;
4812         }
4813         std::vector<Dependency> dependencyList = innerBundleInfo.GetDependencies();
4814         for (const auto &dependencyItem : dependencyList) {
4815             if (dependencyItem.bundleName == hspBundleName) {
4816                 return true;
4817             }
4818         }
4819     }
4820     return false;
4821 }
4822 
GetSharedBundleInfo(const std::string & bundleName,int32_t flags,BundleInfo & bundleInfo)4823 ErrCode BundleDataMgr::GetSharedBundleInfo(const std::string &bundleName, int32_t flags, BundleInfo &bundleInfo)
4824 {
4825     if (bundleName.empty()) {
4826         APP_LOGE("bundleName is empty");
4827         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
4828     }
4829 
4830     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4831     auto infoItem = bundleInfos_.find(bundleName);
4832     if (infoItem == bundleInfos_.end()) {
4833         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
4834         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4835     }
4836     const InnerBundleInfo &innerBundleInfo = infoItem->second;
4837     innerBundleInfo.GetSharedBundleInfo(flags, bundleInfo);
4838     return ERR_OK;
4839 }
4840 
IsPreInstallApp(const std::string & bundleName)4841 bool BundleDataMgr::IsPreInstallApp(const std::string &bundleName)
4842 {
4843     APP_LOGD("IsPreInstallApp bundleName: %{public}s", bundleName.c_str());
4844     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4845     auto item = bundleInfos_.find(bundleName);
4846     if (item == bundleInfos_.end()) {
4847         APP_LOGE("IsPreInstallApp failed, can not find bundle %{public}s",
4848             bundleName.c_str());
4849         return false;
4850     }
4851     return item->second.IsPreInstallApp();
4852 }
4853 
GetProxyDataInfos(const std::string & bundleName,const std::string & moduleName,int userId,std::vector<ProxyData> & proxyDatas) const4854 ErrCode BundleDataMgr::GetProxyDataInfos(const std::string &bundleName, const std::string &moduleName,
4855     int userId, std::vector<ProxyData> &proxyDatas) const
4856 {
4857     InnerBundleInfo info;
4858     auto ret = GetInnerBundleInfoWithBundleFlagsV9(
4859         bundleName, static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), info, userId);
4860     if (ret != ERR_OK) {
4861         APP_LOGE("GetProxyData failed for GetInnerBundleInfo failed, bundleName:%{public}s", bundleName.c_str());
4862         return ret;
4863     }
4864     return info.GetProxyDataInfos(moduleName, proxyDatas);
4865 }
4866 
GetAllProxyDataInfos(int userId,std::vector<ProxyData> & proxyDatas) const4867 ErrCode BundleDataMgr::GetAllProxyDataInfos(int userId, std::vector<ProxyData> &proxyDatas) const
4868 {
4869     std::vector<BundleInfo> bundleInfos;
4870     auto ret = GetBundleInfosV9(
4871         static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfos, userId);
4872     if (ret != ERR_OK) {
4873         APP_LOGE("GetAllProxyDataInfos failed for GetBundleInfos failed");
4874         return ret;
4875     }
4876     for (const auto &bundleInfo : bundleInfos) {
4877         for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) {
4878             proxyDatas.insert(
4879                 proxyDatas.end(), hapModuleInfo.proxyDatas.begin(), hapModuleInfo.proxyDatas.end());
4880         }
4881     }
4882     return ERR_OK;
4883 }
4884 
GetBundleNameByAppId(const std::string & appId) const4885 std::string BundleDataMgr::GetBundleNameByAppId(const std::string &appId) const
4886 {
4887     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4888     auto it = std::find_if(bundleInfos_.cbegin(), bundleInfos_.cend(), [&appId](const auto &pair) {
4889         return appId == pair.second.GetAppId();
4890     });
4891     if (it == bundleInfos_.cend()) {
4892         APP_LOGW("invalid appId, can't find bundleName");
4893         return Constants::EMPTY_STRING;
4894     }
4895     return it->second.GetBundleName();
4896 }
4897 
SetAOTCompileStatus(const std::string & bundleName,const std::string & moduleName,AOTCompileStatus aotCompileStatus,uint32_t versionCode)4898 void BundleDataMgr::SetAOTCompileStatus(const std::string &bundleName, const std::string &moduleName,
4899     AOTCompileStatus aotCompileStatus, uint32_t versionCode)
4900 {
4901     APP_LOGD("SetAOTCompileStatus, bundleName : %{public}s, moduleName : %{public}s, aotCompileStatus : %{public}d",
4902         bundleName.c_str(), moduleName.c_str(), aotCompileStatus);
4903     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4904     auto item = bundleInfos_.find(bundleName);
4905     if (item == bundleInfos_.end()) {
4906         APP_LOGE("bundleName %{public}s not exist", bundleName.c_str());
4907         (void)InstalldClient::GetInstance()->RemoveDir(Constants::ARK_CACHE_PATH + bundleName);
4908         return;
4909     }
4910     if (item->second.GetVersionCode() != versionCode) {
4911         APP_LOGE("versionCode inconsistent, param : %{public}u, current : %{public}u, bundleName:%{public}s",
4912             versionCode, item->second.GetVersionCode(), bundleName.c_str());
4913         return;
4914     }
4915     item->second.SetAOTCompileStatus(moduleName, aotCompileStatus);
4916     std::string abi;
4917     std::string path;
4918     if (aotCompileStatus == AOTCompileStatus::COMPILE_SUCCESS) {
4919         abi = Constants::ARM64_V8A;
4920         path = Constants::ARM64 + Constants::PATH_SEPARATOR;
4921     }
4922     item->second.SetArkNativeFileAbi(abi);
4923     item->second.SetArkNativeFilePath(path);
4924     if (!dataStorage_->SaveStorageBundleInfo(item->second)) {
4925         APP_LOGE("SaveStorageBundleInfo failed bundleName:%{public}s", bundleName.c_str());
4926     }
4927 }
4928 
ResetAOTFlags()4929 void BundleDataMgr::ResetAOTFlags()
4930 {
4931     APP_LOGI("ResetAOTFlags begin");
4932     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4933     std::for_each(bundleInfos_.begin(), bundleInfos_.end(), [this](auto &item) {
4934         item.second.ResetAOTFlags();
4935         if (!dataStorage_->SaveStorageBundleInfo(item.second)) {
4936             APP_LOGE("SaveStorageBundleInfo failed, bundleName : %{public}s", item.second.GetBundleName().c_str());
4937         }
4938     });
4939     APP_LOGI("ResetAOTFlags end");
4940 }
4941 
GetAllBundleName() const4942 std::vector<std::string> BundleDataMgr::GetAllBundleName() const
4943 {
4944     APP_LOGD("GetAllBundleName begin");
4945     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4946     std::vector<std::string> bundleNames;
4947     bundleNames.reserve(bundleInfos_.size());
4948     std::transform(bundleInfos_.cbegin(), bundleInfos_.cend(), std::back_inserter(bundleNames), [](const auto &item) {
4949         return item.first;
4950     });
4951     return bundleNames;
4952 }
4953 
QueryInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & info) const4954 bool BundleDataMgr::QueryInnerBundleInfo(const std::string &bundleName, InnerBundleInfo &info) const
4955 {
4956     APP_LOGD("QueryInnerBundleInfo begin, bundleName : %{public}s", bundleName.c_str());
4957     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4958     auto item = bundleInfos_.find(bundleName);
4959     if (item == bundleInfos_.end()) {
4960         APP_LOGD("QueryInnerBundleInfo failed, bundleName:%{public}s", bundleName.c_str());
4961         return false;
4962     }
4963     info = item->second;
4964     return true;
4965 }
4966 
GetUserIds(const std::string & bundleName) const4967 std::vector<int32_t> BundleDataMgr::GetUserIds(const std::string &bundleName) const
4968 {
4969     APP_LOGD("GetUserIds begin, bundleName : %{public}s", bundleName.c_str());
4970     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4971     std::vector<int32_t> userIds;
4972     auto infoItem = bundleInfos_.find(bundleName);
4973     if (infoItem == bundleInfos_.end()) {
4974         APP_LOGD("can't find bundleName : %{public}s", bundleName.c_str());
4975         return userIds;
4976     }
4977     auto userInfos = infoItem->second.GetInnerBundleUserInfos();
4978     std::transform(userInfos.cbegin(), userInfos.cend(), std::back_inserter(userIds), [](const auto &item) {
4979         return item.second.bundleUserInfo.userId;
4980     });
4981     return userIds;
4982 }
4983 
GetSpecifiedDistributionType(const std::string & bundleName,std::string & specifiedDistributionType)4984 ErrCode BundleDataMgr::GetSpecifiedDistributionType(
4985     const std::string &bundleName, std::string &specifiedDistributionType)
4986 {
4987     APP_LOGD("GetSpecifiedDistributionType bundleName: %{public}s", bundleName.c_str());
4988     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
4989     auto infoItem = bundleInfos_.find(bundleName);
4990     if (infoItem == bundleInfos_.end()) {
4991         APP_LOGE("bundleName: %{public}s does not exist", bundleName.c_str());
4992         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4993     }
4994     if (infoItem->second.GetApplicationBundleType() != BundleType::SHARED) {
4995         int32_t userId = AccountHelper::GetCurrentActiveUserId();
4996         int32_t responseUserId = infoItem->second.GetResponseUserId(userId);
4997         if (responseUserId == Constants::INVALID_USERID) {
4998             APP_LOGE("bundleName: %{public}s does not exist in current userId", bundleName.c_str());
4999             return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
5000         }
5001     }
5002     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->GetSpecifiedDistributionType(bundleName,
5003         specifiedDistributionType)) {
5004         APP_LOGE("bundleName:%{public}s GetSpecifiedDistributionType failed.", bundleName.c_str());
5005         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5006     }
5007     return ERR_OK;
5008 }
5009 
GetAdditionalInfo(const std::string & bundleName,std::string & additionalInfo)5010 ErrCode BundleDataMgr::GetAdditionalInfo(
5011     const std::string &bundleName, std::string &additionalInfo)
5012 {
5013     APP_LOGD("GetAdditionalInfo bundleName: %{public}s", bundleName.c_str());
5014     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
5015     auto infoItem = bundleInfos_.find(bundleName);
5016     if (infoItem == bundleInfos_.end()) {
5017         APP_LOGE("bundleName: %{public}s does not exist", bundleName.c_str());
5018         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
5019     }
5020     if (infoItem->second.GetApplicationBundleType() != BundleType::SHARED) {
5021         int32_t userId = AccountHelper::GetCurrentActiveUserId();
5022         int32_t responseUserId = infoItem->second.GetResponseUserId(userId);
5023         if (responseUserId == Constants::INVALID_USERID) {
5024             APP_LOGE("bundleName: %{public}s does not exist in current userId", bundleName.c_str());
5025             return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
5026         }
5027     }
5028     if (!DelayedSingleton<AppProvisionInfoManager>::GetInstance()->GetAdditionalInfo(bundleName,
5029         additionalInfo)) {
5030         APP_LOGE("bundleName:%{public}s GetAdditionalInfo failed.", bundleName.c_str());
5031         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5032     }
5033     return ERR_OK;
5034 }
5035 
SetExtNameOrMIMEToApp(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & extName,const std::string & mimeType)5036 ErrCode BundleDataMgr::SetExtNameOrMIMEToApp(const std::string &bundleName, const std::string &moduleName,
5037     const std::string &abilityName, const std::string &extName, const std::string &mimeType)
5038 {
5039     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
5040     auto item = bundleInfos_.find(bundleName);
5041     if (item == bundleInfos_.end()) {
5042         APP_LOGE("bundleName %{public}s not exist", bundleName.c_str());
5043         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
5044     }
5045     ErrCode ret;
5046     if (!extName.empty()) {
5047         ret = item->second.SetExtName(moduleName, abilityName, extName);
5048         if (ret != ERR_OK) {
5049             APP_LOGE("set ext name to app failed, bundleName:%{public}s", bundleName.c_str());
5050             return ret;
5051         }
5052     }
5053     if (!mimeType.empty()) {
5054         ret = item->second.SetMimeType(moduleName, abilityName, mimeType);
5055         if (ret != ERR_OK) {
5056             APP_LOGE("set mime type to app failed, bundleName:%{public}s", bundleName.c_str());
5057             return ret;
5058         }
5059     }
5060     if (!dataStorage_->SaveStorageBundleInfo(item->second)) {
5061         APP_LOGE("SaveStorageBundleInfo failed, bundleName:%{public}s", bundleName.c_str());
5062         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
5063     }
5064     return ERR_OK;
5065 }
5066 
DelExtNameOrMIMEToApp(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & extName,const std::string & mimeType)5067 ErrCode BundleDataMgr::DelExtNameOrMIMEToApp(const std::string &bundleName, const std::string &moduleName,
5068     const std::string &abilityName, const std::string &extName, const std::string &mimeType)
5069 {
5070     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
5071     auto item = bundleInfos_.find(bundleName);
5072     if (item == bundleInfos_.end()) {
5073         APP_LOGE("bundleName %{public}s not exist", bundleName.c_str());
5074         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
5075     }
5076     ErrCode ret;
5077     if (!extName.empty()) {
5078         ret = item->second.DelExtName(moduleName, abilityName, extName);
5079         if (ret != ERR_OK) {
5080             APP_LOGE("delete ext name to app failed, bundleName:%{public}s", bundleName.c_str());
5081             return ret;
5082         }
5083     }
5084     if (!mimeType.empty()) {
5085         ret = item->second.DelMimeType(moduleName, abilityName, mimeType);
5086         if (ret != ERR_OK) {
5087             APP_LOGE("delete mime type to app failed, bundleName:%{public}s", bundleName.c_str());
5088             return ret;
5089         }
5090     }
5091     if (!dataStorage_->SaveStorageBundleInfo(item->second)) {
5092         APP_LOGE("SaveStorageBundleInfo failed, bundleName:%{public}s", bundleName.c_str());
5093         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
5094     }
5095     return ERR_OK;
5096 }
5097 
MatchPrivateType(const Want & want,const std::vector<std::string> & supportExtNames,const std::vector<std::string> & supportMimeTypes) const5098 bool BundleDataMgr::MatchPrivateType(const Want &want,
5099     const std::vector<std::string> &supportExtNames, const std::vector<std::string> &supportMimeTypes) const
5100 {
5101     APP_LOGD("MatchPrivateType, uri is %{public}s", want.GetUriString().c_str());
5102     std::string uri = want.GetUriString();
5103     auto suffixIndex = uri.rfind('.');
5104     if (suffixIndex == std::string::npos) {
5105         return false;
5106     }
5107     std::string suffix = uri.substr(suffixIndex + 1);
5108     bool supportPrivateType = std::any_of(supportExtNames.begin(), supportExtNames.end(), [&](const auto &extName) {
5109         return extName == suffix;
5110     });
5111     if (supportPrivateType) {
5112         APP_LOGI("uri is a supported private-type file");
5113         return true;
5114     }
5115     std::vector<std::string> mimeTypes;
5116     bool ret = MimeTypeMgr::GetMimeTypeByUri(uri, mimeTypes);
5117     if (!ret) {
5118         return false;
5119     }
5120     auto iter = std::find_first_of(
5121         mimeTypes.begin(), mimeTypes.end(), supportMimeTypes.begin(), supportMimeTypes.end());
5122     if (iter != mimeTypes.end()) {
5123         APP_LOGI("uri is a supported mime-type file");
5124         return true;
5125     }
5126     return false;
5127 }
5128 
QueryAppGalleryAbilityName(std::string & bundleName,std::string & abilityName)5129 bool BundleDataMgr::QueryAppGalleryAbilityName(std::string &bundleName, std::string &abilityName)
5130 {
5131     APP_LOGD("QueryAppGalleryAbilityName called");
5132     AbilityInfo abilityInfo;
5133     ExtensionAbilityInfo extensionInfo;
5134     Want want;
5135     want.SetAction(FREE_INSTALL_ACTION);
5136     if (!ImplicitQueryInfoByPriority(
5137         want, 0, Constants::ANY_USERID, abilityInfo, extensionInfo)) {
5138         APP_LOGE("ImplicitQueryInfoByPriority for action %{public}s failed", FREE_INSTALL_ACTION);
5139         return false;
5140     }
5141     if (!abilityInfo.name.empty()) {
5142         bundleName = abilityInfo.bundleName;
5143         abilityName = abilityInfo.name;
5144     } else {
5145         bundleName = extensionInfo.bundleName;
5146         abilityName = extensionInfo.name;
5147     }
5148 
5149     if (bundleName.empty() || abilityName.empty()) {
5150         APP_LOGE("bundleName: %{public}s or abilityName: %{public}s is empty()",
5151             bundleName.c_str(), abilityName.c_str());
5152         return false;
5153     }
5154     APP_LOGD("QueryAppGalleryAbilityName bundleName: %{public}s, abilityName: %{public}s",
5155         bundleName.c_str(), abilityName.c_str());
5156     return true;
5157 }
5158 
QueryDataGroupInfos(const std::string & bundleName,int32_t userId,std::vector<DataGroupInfo> & infos) const5159 bool BundleDataMgr::QueryDataGroupInfos(const std::string &bundleName, int32_t userId,
5160     std::vector<DataGroupInfo> &infos) const
5161 {
5162     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
5163     auto infoItem = bundleInfos_.find(bundleName);
5164     if (infoItem == bundleInfos_.end()) {
5165         APP_LOGE("bundleName: %{public}s is not existed", bundleName.c_str());
5166         return false;
5167     }
5168     auto dataGroupInfos = infoItem->second.GetDataGroupInfos();
5169     for (const auto &item : dataGroupInfos) {
5170         auto dataGroupIter = std::find_if(std::begin(item.second), std::end(item.second),
5171             [userId](const DataGroupInfo &info) {
5172             return info.userId == userId;
5173         });
5174         if (dataGroupIter != std::end(item.second)) {
5175             infos.push_back(*dataGroupIter);
5176         }
5177     }
5178     return true;
5179 }
5180 
GetGroupDir(const std::string & dataGroupId,std::string & dir,int32_t userId) const5181 bool BundleDataMgr::GetGroupDir(const std::string &dataGroupId, std::string &dir, int32_t userId) const
5182 {
5183     if (userId == Constants::UNSPECIFIED_USERID) {
5184         userId = AccountHelper::GetCurrentActiveUserId();
5185     }
5186     std::string uuid;
5187     if (BundlePermissionMgr::VerifyCallingUid()) {
5188         std::lock_guard<std::mutex> lock(bundleInfoMutex_);
5189         for (const auto &item : bundleInfos_) {
5190             const auto &dataGroupInfos = item.second.GetDataGroupInfos();
5191             auto dataGroupInfosIter = dataGroupInfos.find(dataGroupId);
5192             if (dataGroupInfosIter == dataGroupInfos.end()) {
5193                 continue;
5194             }
5195             auto dataInUserIter = std::find_if(std::begin(dataGroupInfosIter->second),
5196                 std::end(dataGroupInfosIter->second),
5197                 [userId](const DataGroupInfo &info) { return info.userId == userId; });
5198             if (dataInUserIter != std::end(dataGroupInfosIter->second)) {
5199                 uuid = dataInUserIter->uuid;
5200                 break;
5201             }
5202         }
5203     } else {
5204         int32_t callingUid = IPCSkeleton::GetCallingUid();
5205         InnerBundleInfo innerBundleInfo;
5206         if (GetInnerBundleInfoByUid(callingUid, innerBundleInfo) != ERR_OK) {
5207             APP_LOGE("verify uid failed, callingUid is %{public}d", callingUid);
5208             return false;
5209         }
5210         const auto &dataGroupInfos = innerBundleInfo.GetDataGroupInfos();
5211         auto dataGroupInfosIter = dataGroupInfos.find(dataGroupId);
5212         if (dataGroupInfosIter == dataGroupInfos.end()) {
5213             APP_LOGE("calling bundle do not have dataGroupId: %{public}s", dataGroupId.c_str());
5214             return false;
5215         }
5216         auto dataGroupIter = std::find_if(std::begin(dataGroupInfosIter->second), std::end(dataGroupInfosIter->second),
5217             [userId](const DataGroupInfo &info) {
5218             return info.userId == userId;
5219         });
5220         if (dataGroupIter != std::end(dataGroupInfosIter->second)) {
5221             uuid = dataGroupIter->uuid;
5222         }
5223     }
5224     if (uuid.empty()) {
5225         APP_LOGE("get uuid by data group id failed");
5226         return false;
5227     }
5228     dir = Constants::REAL_DATA_PATH + Constants::PATH_SEPARATOR + std::to_string(userId)
5229         + Constants::DATA_GROUP_PATH + uuid;
5230     APP_LOGD("groupDir: %{public}s", dir.c_str());
5231     return true;
5232 }
5233 
GenerateDataGroupUuidAndUid(DataGroupInfo & dataGroupInfo,int32_t userId,std::map<std::string,std::pair<int32_t,std::string>> & dataGroupIndexMap) const5234 void BundleDataMgr::GenerateDataGroupUuidAndUid(DataGroupInfo &dataGroupInfo, int32_t userId,
5235     std::map<std::string, std::pair<int32_t, std::string>> &dataGroupIndexMap) const
5236 {
5237     std::set<int32_t> indexList;
5238     for (auto iter = dataGroupIndexMap.begin(); iter != dataGroupIndexMap.end(); iter++) {
5239         indexList.emplace(iter->second.first);
5240     }
5241     int32_t index = DATA_GROUP_INDEX_START;
5242     for (int32_t i = DATA_GROUP_INDEX_START; i < Constants::DATA_GROUP_UID_OFFSET; i++) {
5243         if (indexList.find(i) == indexList.end()) {
5244             index = i;
5245             break;
5246         }
5247     }
5248 
5249     int32_t uid = userId * Constants::BASE_USER_RANGE + index + Constants::DATA_GROUP_UID_OFFSET;
5250     dataGroupInfo.uid = uid;
5251     dataGroupInfo.gid = uid;
5252 
5253     std::string str = BundleUtil::GenerateDataGroupDirName();
5254     dataGroupInfo.uuid = str;
5255     dataGroupIndexMap[dataGroupInfo.dataGroupId] = std::pair<int32_t, std::string>(index, str);
5256 }
5257 
GenerateDataGroupInfos(InnerBundleInfo & innerBundleInfo,const std::vector<std::string> & dataGroupIdList,int32_t userId) const5258 void BundleDataMgr::GenerateDataGroupInfos(InnerBundleInfo &innerBundleInfo,
5259     const std::vector<std::string> &dataGroupIdList, int32_t userId) const
5260 {
5261     APP_LOGD("GenerateDataGroupInfos called for user: %{public}d", userId);
5262     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
5263     if (dataGroupIdList.empty() || bundleInfos_.empty()) {
5264         APP_LOGE("dataGroupIdList or bundleInfos_ data is empty");
5265         return;
5266     }
5267     std::map<std::string, std::pair<int32_t, std::string>> dataGroupIndexMap;
5268     GetDataGroupIndexMap(dataGroupIndexMap);
5269     for (const std::string &groupId : dataGroupIdList) {
5270         DataGroupInfo dataGroupInfo;
5271         dataGroupInfo.dataGroupId = groupId;
5272         dataGroupInfo.userId = userId;
5273         auto iter = dataGroupIndexMap.find(groupId);
5274         if (iter != dataGroupIndexMap.end()) {
5275             dataGroupInfo.uuid = iter->second.second;
5276             int32_t uid = iter->second.first + userId * Constants::BASE_USER_RANGE + Constants::DATA_GROUP_UID_OFFSET;
5277             dataGroupInfo.uid = uid;
5278             dataGroupInfo.gid = uid;
5279             innerBundleInfo.AddDataGroupInfo(groupId, dataGroupInfo);
5280             continue;
5281         }
5282         GenerateDataGroupUuidAndUid(dataGroupInfo, userId, dataGroupIndexMap);
5283         innerBundleInfo.AddDataGroupInfo(groupId, dataGroupInfo);
5284     }
5285 }
5286 
GetDataGroupIndexMap(std::map<std::string,std::pair<int32_t,std::string>> & dataGroupIndexMap) const5287 void BundleDataMgr::GetDataGroupIndexMap(
5288     std::map<std::string, std::pair<int32_t, std::string>> &dataGroupIndexMap) const
5289 {
5290     for (const auto &bundleInfo : bundleInfos_) {
5291         for (const auto &infoItem : bundleInfo.second.GetDataGroupInfos()) {
5292             for_each(std::begin(infoItem.second), std::end(infoItem.second), [&](const DataGroupInfo &dataGroupInfo) {
5293                 int32_t index = dataGroupInfo.uid - dataGroupInfo.userId * Constants::BASE_USER_RANGE
5294                     - Constants::DATA_GROUP_UID_OFFSET;
5295                 dataGroupIndexMap[dataGroupInfo.dataGroupId] =
5296                     std::pair<int32_t, std::string>(index, dataGroupInfo.uuid);
5297             });
5298         }
5299     }
5300 }
5301 
IsShareDataGroupId(const std::string & dataGroupId,int32_t userId) const5302 bool BundleDataMgr::IsShareDataGroupId(const std::string &dataGroupId, int32_t userId) const
5303 {
5304     APP_LOGD("IsShareDataGroupId, dataGroupId is %{public}s", dataGroupId.c_str());
5305     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
5306     int32_t count = 0;
5307     for (const auto &info : bundleInfos_) {
5308         auto dataGroupInfos = info.second.GetDataGroupInfos();
5309         auto iter = dataGroupInfos.find(dataGroupId);
5310         if (iter == dataGroupInfos.end()) {
5311             continue;
5312         }
5313         for (auto dataGroupInfo : iter->second) {
5314             if (dataGroupInfo.userId == userId && ++count > 1) {
5315                 APP_LOGD("dataGroupId: %{public}s is shared", dataGroupId.c_str());
5316                 return true;
5317             }
5318         }
5319     }
5320     return false;
5321 }
5322 
QueryLauncherAbilityFromBmsExtension(const Want & want,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const5323 ErrCode BundleDataMgr::QueryLauncherAbilityFromBmsExtension(const Want &want, int32_t userId,
5324     std::vector<AbilityInfo> &abilityInfos) const
5325 {
5326     APP_LOGD("start to query launcher abilities from bms extension");
5327     BmsExtensionDataMgr bmsExtensionDataMgr;
5328     ErrCode res = bmsExtensionDataMgr.QueryAbilityInfos(want, userId, abilityInfos);
5329     if (res != ERR_OK) {
5330         APP_LOGE("query ability infos failed due to error code %{public}d", res);
5331         return res;
5332     }
5333     for_each(abilityInfos.begin(), abilityInfos.end(), [this](auto &info) {
5334         // fix labelId or iconId is equal 0
5335         ModifyLauncherAbilityInfo(true, info);
5336     });
5337     return ERR_OK;
5338 }
5339 
QueryAbilityInfosFromBmsExtension(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos,bool isNewVersion) const5340 ErrCode BundleDataMgr::QueryAbilityInfosFromBmsExtension(const Want &want, int32_t flags, int32_t userId,
5341     std::vector<AbilityInfo> &abilityInfos, bool isNewVersion) const
5342 {
5343     APP_LOGD("start to query abilityInfos from bms extension");
5344     BmsExtensionDataMgr bmsExtensionDataMgr;
5345     ErrCode res = bmsExtensionDataMgr.QueryAbilityInfosWithFlag(want, flags, userId, abilityInfos, isNewVersion);
5346     if (res != ERR_OK) {
5347         APP_LOGE("query ability infos failed due to error code %{public}d", res);
5348         return res;
5349     }
5350     if (abilityInfos.empty()) {
5351         APP_LOGE("no ability info can be found from bms extension");
5352         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
5353     }
5354     return ERR_OK;
5355 }
5356 
QueryAbilityInfoFromBmsExtension(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,bool isNewVersion) const5357 ErrCode BundleDataMgr::QueryAbilityInfoFromBmsExtension(const Want &want, int32_t flags, int32_t userId,
5358     AbilityInfo &abilityInfo, bool isNewVersion) const
5359 {
5360     APP_LOGD("start to query abilityInfo from bms extension");
5361     std::vector<AbilityInfo> abilityInfos;
5362     ErrCode res = QueryAbilityInfosFromBmsExtension(want, flags, userId, abilityInfos, isNewVersion);
5363     if (res != ERR_OK) {
5364         APP_LOGE("query ability info failed due to error code %{public}d", res);
5365         return res;
5366     }
5367     if (abilityInfos.empty()) {
5368         APP_LOGE("no ability info can be found from bms extension");
5369         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
5370     }
5371 
5372     abilityInfo = abilityInfos[0];
5373     return ERR_OK;
5374 }
5375 
GetBundleInfosFromBmsExtension(int32_t flags,std::vector<BundleInfo> & bundleInfos,int32_t userId,bool isNewVersion) const5376 ErrCode BundleDataMgr::GetBundleInfosFromBmsExtension(
5377     int32_t flags, std::vector<BundleInfo> &bundleInfos, int32_t userId, bool isNewVersion) const
5378 {
5379     APP_LOGD("start to query bundle infos from bms extension");
5380     BmsExtensionDataMgr bmsExtensionDataMgr;
5381     ErrCode res = bmsExtensionDataMgr.GetBundleInfos(flags, bundleInfos, userId, isNewVersion);
5382     if (res != ERR_OK) {
5383         APP_LOGE("query bundle infos failed due to error code %{public}d", res);
5384         return res;
5385     }
5386 
5387     return ERR_OK;
5388 }
5389 
GetBundleInfoFromBmsExtension(const std::string & bundleName,int32_t flags,BundleInfo & bundleInfo,int32_t userId,bool isNewVersion) const5390 ErrCode BundleDataMgr::GetBundleInfoFromBmsExtension(const std::string &bundleName, int32_t flags,
5391     BundleInfo &bundleInfo, int32_t userId, bool isNewVersion) const
5392 {
5393     APP_LOGD("start to query bundle info from bms extension");
5394     BmsExtensionDataMgr bmsExtensionDataMgr;
5395     ErrCode res = bmsExtensionDataMgr.GetBundleInfo(bundleName, flags, userId, bundleInfo, isNewVersion);
5396     if (res != ERR_OK) {
5397         APP_LOGE("query bundle info failed due to error code %{public}d", res);
5398         return res;
5399     }
5400 
5401     return ERR_OK;
5402 }
5403 
FindAbilityInfoInBundleInfo(const InnerBundleInfo & innerBundleInfo,const std::string & moduleName,const std::string & abilityName,AbilityInfo & abilityInfo) const5404 ErrCode BundleDataMgr::FindAbilityInfoInBundleInfo(const InnerBundleInfo &innerBundleInfo,
5405     const std::string &moduleName, const std::string &abilityName, AbilityInfo &abilityInfo) const
5406 {
5407     if (moduleName.empty()) {
5408         auto ability = innerBundleInfo.FindAbilityInfoV9(moduleName, abilityName);
5409         if (!ability) {
5410             return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
5411         }
5412         abilityInfo = *ability;
5413         return ERR_OK;
5414     }
5415 
5416     ErrCode ret = innerBundleInfo.FindAbilityInfo(moduleName, abilityName, abilityInfo);
5417     if (ret != ERR_OK) {
5418         APP_LOGE("%{public}s:FindAbilityInfo failed: %{public}d", innerBundleInfo.GetBundleName().c_str(), ret);
5419     }
5420     return ret;
5421 }
5422 
5423 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
UpdateOverlayInfo(const InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo)5424 bool BundleDataMgr::UpdateOverlayInfo(const InnerBundleInfo &newInfo, InnerBundleInfo &oldInfo)
5425 {
5426     InnerBundleInfo targetInnerBundleInfo;
5427     std::string targetBundleName = newInfo.GetTargetBundleName();
5428     auto targetInfoItem = bundleInfos_.find(targetBundleName);
5429     if (targetInfoItem != bundleInfos_.end()) {
5430         targetInnerBundleInfo = targetInfoItem->second;
5431     }
5432 
5433     if (OverlayDataMgr::GetInstance()->UpdateOverlayInfo(newInfo, oldInfo, targetInnerBundleInfo) != ERR_OK) {
5434         APP_LOGE("update overlay info failed");
5435         return false;
5436     }
5437     // storage target bundle info
5438     if (!targetInnerBundleInfo.GetBundleName().empty() &&
5439         dataStorage_->SaveStorageBundleInfo(targetInnerBundleInfo)) {
5440         bundleInfos_.at(targetInnerBundleInfo.GetBundleName()) = targetInnerBundleInfo;
5441     }
5442     // build overlay connection for external overlay
5443     if (newInfo.GetOverlayType() == NON_OVERLAY_TYPE) {
5444         const auto &moduleInfos = newInfo.GetInnerModuleInfos();
5445         std::string moduleName = (moduleInfos.begin()->second).moduleName;
5446         BuildExternalOverlayConnection(moduleName, oldInfo, newInfo.GetUserId());
5447     }
5448     return true;
5449 }
5450 
ResetExternalOverlayModuleState(const std::string & bundleName,const std::string & modulePackage)5451 void BundleDataMgr::ResetExternalOverlayModuleState(const std::string &bundleName, const std::string &modulePackage)
5452 {
5453     for (auto &info : bundleInfos_) {
5454         if (info.second.GetTargetBundleName() != bundleName) {
5455             continue;
5456         }
5457         const auto &innerModuleInfos = info.second.GetInnerModuleInfos();
5458         for (const auto &moduleInfo : innerModuleInfos) {
5459             if (moduleInfo.second.targetModuleName == modulePackage) {
5460                 info.second.SetOverlayModuleState(moduleInfo.second.moduleName, OverlayState::OVERLAY_INVALID);
5461                 break;
5462             }
5463         }
5464         if (!dataStorage_->SaveStorageBundleInfo(info.second)) {
5465             APP_LOGW("update storage success bundle:%{public}s", info.second.GetBundleName().c_str());
5466         }
5467     }
5468 }
5469 
BuildExternalOverlayConnection(const std::string & moduleName,InnerBundleInfo & oldInfo,int32_t userId)5470 void BundleDataMgr::BuildExternalOverlayConnection(const std::string &moduleName, InnerBundleInfo &oldInfo,
5471     int32_t userId)
5472 {
5473     APP_LOGD("start to update external overlay connection of module %{public}s under user %{public}d",
5474         moduleName.c_str(), userId);
5475     for (auto &info : bundleInfos_) {
5476         if (info.second.GetTargetBundleName() != oldInfo.GetBundleName()) {
5477             continue;
5478         }
5479         // check target bundle is preInstall application
5480         if (!oldInfo.IsPreInstallApp()) {
5481             APP_LOGW("target bundle is not preInstall application");
5482             return;
5483         }
5484 
5485         // check fingerprint of current bundle with target bundle
5486         if (oldInfo.GetCertificateFingerprint() != info.second.GetCertificateFingerprint()) {
5487             APP_LOGW("target bundle has different fingerprint with current bundle");
5488             return;
5489         }
5490         // external overlay does not support FA model
5491         if (!oldInfo.GetIsNewVersion()) {
5492             APP_LOGW("target bundle is not stage model");
5493             return;
5494         }
5495         // external overlay does not support service
5496         if (oldInfo.GetEntryInstallationFree()) {
5497             APP_LOGW("target bundle is service");
5498             return;
5499         }
5500 
5501         const auto &innerModuleInfos = info.second.GetInnerModuleInfos();
5502         std::vector<std::string> overlayModuleVec;
5503         for (const auto &moduleInfo : innerModuleInfos) {
5504             if (moduleInfo.second.targetModuleName != moduleName) {
5505                 continue;
5506             }
5507             OverlayModuleInfo overlayModuleInfo;
5508             overlayModuleInfo.bundleName = info.second.GetBundleName();
5509             overlayModuleInfo.moduleName = moduleInfo.second.moduleName;
5510             overlayModuleInfo.targetModuleName = moduleInfo.second.targetModuleName;
5511             overlayModuleInfo.hapPath = info.second.GetModuleHapPath(moduleInfo.second.moduleName);
5512             overlayModuleInfo.priority = moduleInfo.second.targetPriority;
5513             oldInfo.AddOverlayModuleInfo(overlayModuleInfo);
5514             overlayModuleVec.emplace_back(moduleInfo.second.moduleName);
5515         }
5516         std::string bundleDir;
5517         const std::string &moduleHapPath =
5518             info.second.GetModuleHapPath((innerModuleInfos.begin()->second).moduleName);
5519         OverlayDataMgr::GetInstance()->GetBundleDir(moduleHapPath, bundleDir);
5520         OverlayBundleInfo overlayBundleInfo;
5521         overlayBundleInfo.bundleName = info.second.GetBundleName();
5522         overlayBundleInfo.bundleDir = bundleDir;
5523         overlayBundleInfo.state = info.second.GetOverlayState();
5524         overlayBundleInfo.priority = info.second.GetTargetPriority();
5525         oldInfo.AddOverlayBundleInfo(overlayBundleInfo);
5526         auto userSet = GetAllUser();
5527         for (const auto &innerUserId : userSet) {
5528             for (const auto &overlayModule : overlayModuleVec) {
5529                 int32_t state = OverlayState::OVERLAY_INVALID;
5530                 info.second.GetOverlayModuleState(overlayModule, innerUserId, state);
5531                 if (state == OverlayState::OVERLAY_INVALID) {
5532                     info.second.SetOverlayModuleState(overlayModule, OVERLAY_ENABLE, innerUserId);
5533                 }
5534             }
5535             dataStorage_->SaveStorageBundleInfo(info.second);
5536         }
5537     }
5538 }
5539 
RemoveOverlayInfoAndConnection(const InnerBundleInfo & innerBundleInfo,const std::string & bundleName)5540 void BundleDataMgr::RemoveOverlayInfoAndConnection(const InnerBundleInfo &innerBundleInfo,
5541     const std::string &bundleName)
5542 {
5543     if (innerBundleInfo.GetOverlayType() == OVERLAY_EXTERNAL_BUNDLE) {
5544         std::string targetBundleName = innerBundleInfo.GetTargetBundleName();
5545         auto targetInfoItem = bundleInfos_.find(targetBundleName);
5546         if (targetInfoItem == bundleInfos_.end()) {
5547             APP_LOGW("target bundle(%{public}s) is not installed", targetBundleName.c_str());
5548         } else {
5549             InnerBundleInfo targetInnerBundleInfo = bundleInfos_.at(targetBundleName);
5550             OverlayDataMgr::GetInstance()->RemoveOverlayBundleInfo(bundleName, targetInnerBundleInfo);
5551             if (dataStorage_->SaveStorageBundleInfo(targetInnerBundleInfo)) {
5552                 APP_LOGI("update storage success bundle:%{public}s", bundleName.c_str());
5553                 bundleInfos_.at(targetBundleName) = targetInnerBundleInfo;
5554             }
5555         }
5556     }
5557 
5558     if (innerBundleInfo.GetOverlayType() == NON_OVERLAY_TYPE) {
5559         for (auto &info : bundleInfos_) {
5560             if (info.second.GetTargetBundleName() != bundleName) {
5561                 continue;
5562             }
5563             const auto &innerModuleInfos = info.second.GetInnerModuleInfos();
5564             for (const auto &moduleInfo : innerModuleInfos) {
5565                 info.second.SetOverlayModuleState(moduleInfo.second.moduleName, OverlayState::OVERLAY_INVALID);
5566             }
5567             dataStorage_->SaveStorageBundleInfo(info.second);
5568         }
5569     }
5570 }
5571 #endif
5572 }  // namespace AppExecFwk
5573 }  // namespace OHOS
5574