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