• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 <chrono>
19 #include <cinttypes>
20 
21 #include "app_log_wrapper.h"
22 #include "bundle_constants.h"
23 #include "bundle_data_storage_database.h"
24 #include "bundle_event_callback_death_recipient.h"
25 #include "bundle_mgr_service.h"
26 #include "bundle_status_callback_death_recipient.h"
27 #include "common_event_manager.h"
28 #include "common_event_support.h"
29 #include "ipc_skeleton.h"
30 #include "image_source.h"
31 #include "json_serializer.h"
32 #include "nlohmann/json.hpp"
33 #include "permission_changed_death_recipient.h"
34 #include "singleton.h"
35 
36 namespace OHOS {
37 namespace AppExecFwk {
38 namespace {
39 constexpr int MAX_EVENT_CALL_BACK_SIZE = 100;
40 }
BundleDataMgr()41 BundleDataMgr::BundleDataMgr()
42 {
43     InitStateTransferMap();
44     dataStorage_ = std::make_shared<BundleDataStorageDatabase>();
45     usageRecordStorage_ = std::make_shared<ModuleUsageRecordStorage>();
46     // register distributed data process death listener.
47     usageRecordStorage_->RegisterKvStoreDeathListener();
48     preInstallDataStorage_ = std::make_shared<PreInstallDataStorage>();
49     distributedDataStorage_ = std::make_shared<DistributedDataStorage>();
50     APP_LOGI("BundleDataMgr instance is created");
51 }
52 
~BundleDataMgr()53 BundleDataMgr::~BundleDataMgr()
54 {
55     APP_LOGI("BundleDataMgr instance is destroyed");
56     installStates_.clear();
57     transferStates_.clear();
58     bundleInfos_.clear();
59 }
60 
LoadDataFromPersistentStorage()61 bool BundleDataMgr::LoadDataFromPersistentStorage()
62 {
63     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
64     bool ret = dataStorage_->LoadAllData(bundleInfos_);
65     if (ret) {
66         if (bundleInfos_.empty()) {
67             APP_LOGW("persistent data is empty");
68             return false;
69         }
70         for (const auto &item : bundleInfos_) {
71             std::lock_guard<std::mutex> lock(stateMutex_);
72             installStates_.emplace(item.first, InstallState::INSTALL_SUCCESS);
73         }
74 
75         LoadAllPreInstallBundleInfos(preInstallBundleInfos_);
76         RestoreUidAndGid();
77         SetInitialUserFlag(true);
78     }
79     return ret;
80 }
81 
UpdateBundleInstallState(const std::string & bundleName,const InstallState state)82 bool BundleDataMgr::UpdateBundleInstallState(const std::string &bundleName, const InstallState state)
83 {
84     if (bundleName.empty()) {
85         APP_LOGW("update result:fail, reason:bundle name is empty");
86         return false;
87     }
88 
89     // always keep lock bundleInfoMutex_ before locking stateMutex_ to avoid deadlock
90     std::lock_guard<std::mutex> lck(bundleInfoMutex_);
91     std::lock_guard<std::mutex> lock(stateMutex_);
92     auto item = installStates_.find(bundleName);
93     if (item == installStates_.end()) {
94         if (state == InstallState::INSTALL_START) {
95             installStates_.emplace(bundleName, state);
96             APP_LOGD("update result:success, state:INSTALL_START");
97             return true;
98         }
99         APP_LOGW("update result:fail, reason:incorrect state");
100         return false;
101     }
102 
103     auto stateRange = transferStates_.equal_range(state);
104     for (auto previousState = stateRange.first; previousState != stateRange.second; ++previousState) {
105         if (item->second == previousState->second) {
106             APP_LOGD("update result:success, current:%{public}d, state:%{public}d", previousState->second, state);
107             if (IsDeleteDataState(state)) {
108                 installStates_.erase(item);
109                 DeleteBundleInfo(bundleName, state);
110                 return true;
111             }
112             item->second = state;
113             return true;
114         }
115     }
116     APP_LOGW("update result:fail, reason:incorrect current:%{public}d, state:%{public}d", item->second, state);
117     return false;
118 }
119 
AddInnerBundleInfo(const std::string & bundleName,InnerBundleInfo & info)120 bool BundleDataMgr::AddInnerBundleInfo(const std::string &bundleName, InnerBundleInfo &info)
121 {
122     APP_LOGD("to save info:%{public}s", info.GetBundleName().c_str());
123     if (bundleName.empty()) {
124         APP_LOGW("save info fail, empty bundle name");
125         return false;
126     }
127 
128     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
129     auto infoItem = bundleInfos_.find(bundleName);
130     if (infoItem != bundleInfos_.end()) {
131         APP_LOGE("bundle info already exist");
132         return false;
133     }
134     std::lock_guard<std::mutex> stateLock(stateMutex_);
135     auto statusItem = installStates_.find(bundleName);
136     if (statusItem == installStates_.end()) {
137         APP_LOGE("save info fail, app:%{public}s is not installed", bundleName.c_str());
138         return false;
139     }
140     if (statusItem->second == InstallState::INSTALL_START) {
141         APP_LOGD("save bundle:%{public}s info", bundleName.c_str());
142         if (dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, info)) {
143             APP_LOGI("write storage success bundle:%{public}s", bundleName.c_str());
144             std::map<std::string, InnerBundleInfo> infoWithId;
145             infoWithId.emplace(Constants::CURRENT_DEVICE_ID, info);
146             bundleInfos_.emplace(bundleName, infoWithId);
147             DistributedBundleInfo DistributedBundleInfo;
148             info.GetDistributedBundleInfo(DistributedBundleInfo);
149             if (!distributedDataStorage_->SaveStorageDistributeInfo(DistributedBundleInfo)) {
150                 APP_LOGW("write DistributedBundleInfo fail bundle:%{public}s", bundleName.c_str());
151             }
152             return true;
153         }
154     }
155     return false;
156 }
157 
SaveNewInfoToDB(const std::string & bundleName,InnerBundleInfo & info)158 bool BundleDataMgr::SaveNewInfoToDB(const std::string &bundleName, InnerBundleInfo &info)
159 {
160     APP_LOGD("SaveNewInfoToDB start");
161     std::string Newbundlename = info.GetDBKeyBundleName();
162     APP_LOGI("to save clone newinfo to DB info:%{public}s", Newbundlename.c_str());
163     if (bundleName.empty()) {
164         APP_LOGW("clone newinfo save info fail, empty bundle name");
165         return false;
166     }
167 
168     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
169     auto infoItem = bundleInfos_.find(Newbundlename);
170     if (infoItem != bundleInfos_.end()) {
171         APP_LOGE("clone newinfo bundle info already exist");
172         return false;
173     }
174     int64_t time =
175         std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
176     APP_LOGI("the clone newinfo bundle install time is %{public}" PRId64, time);
177     info.SetBundleInstallTime(time);
178     if (dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, info)) {
179         APP_LOGI("clone newinfo write storage success bundle:%{public}s", Newbundlename.c_str());
180         std::map<std::string, InnerBundleInfo> infoWithId;
181         infoWithId.emplace(Constants::CURRENT_DEVICE_ID, info);
182         bundleInfos_.emplace(Newbundlename, infoWithId);
183         DistributedBundleInfo DistributedBundleInfo;
184         info.GetDistributedBundleInfo(DistributedBundleInfo);
185         if (!distributedDataStorage_->SaveStorageDistributeInfo(DistributedBundleInfo)) {
186             APP_LOGW("write DistributedBundleInfo fail bundle:%{public}s", bundleName.c_str());
187         }
188         return true;
189     }
190     APP_LOGD("SaveNewInfoToDB finish");
191     return false;
192 }
193 
AddNewModuleInfo(const std::string & bundleName,const InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo)194 bool BundleDataMgr::AddNewModuleInfo(
195     const std::string &bundleName, const InnerBundleInfo &newInfo, InnerBundleInfo &oldInfo)
196 {
197     APP_LOGD("add new module info module name %{public}s ", newInfo.GetCurrentModulePackage().c_str());
198     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
199     auto infoItem = bundleInfos_.find(bundleName);
200     if (infoItem == bundleInfos_.end()) {
201         APP_LOGE("bundle info not exist");
202         return false;
203     }
204     std::lock_guard<std::mutex> stateLock(stateMutex_);
205     auto statusItem = installStates_.find(bundleName);
206     if (statusItem == installStates_.end()) {
207         APP_LOGE("save info fail, app:%{public}s is not updated", bundleName.c_str());
208         return false;
209     }
210     if (statusItem->second == InstallState::UPDATING_SUCCESS) {
211         APP_LOGD("save bundle:%{public}s info", bundleName.c_str());
212         oldInfo.UpdateBaseBundleInfo(newInfo.GetBaseBundleInfo(), newInfo.HasEntry());
213         oldInfo.updateCommonHapInfo(newInfo);
214         oldInfo.AddModuleInfo(newInfo);
215         oldInfo.SetAppPrivilegeLevel(newInfo.GetAppPrivilegeLevel());
216         oldInfo.SetAllowedAcls(newInfo.GetAllowedAcls());
217         oldInfo.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
218         if (dataStorage_->DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, oldInfo)) {
219             if (dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, oldInfo)) {
220                 APP_LOGI("update storage success bundle:%{public}s", bundleName.c_str());
221                 bundleInfos_.at(bundleName).at(Constants::CURRENT_DEVICE_ID) = oldInfo;
222                 DistributedBundleInfo DistributedBundleInfo;
223                 oldInfo.GetDistributedBundleInfo(DistributedBundleInfo);
224                 bool ret = distributedDataStorage_->SaveStorageDistributeInfo(DistributedBundleInfo);
225                 APP_LOGI("write DistributedBundleInfo bundle:%{public}s result:%{public}d", bundleName.c_str(), ret);
226                 return true;
227             }
228         }
229     }
230     return false;
231 }
232 
RemoveModuleInfo(const std::string & bundleName,const std::string & modulePackage,InnerBundleInfo & oldInfo)233 bool BundleDataMgr::RemoveModuleInfo(
234     const std::string &bundleName, const std::string &modulePackage, InnerBundleInfo &oldInfo)
235 {
236     APP_LOGD("remove module info:%{public}s/%{public}s", bundleName.c_str(), modulePackage.c_str());
237     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
238     auto infoItem = bundleInfos_.find(bundleName);
239     if (infoItem == bundleInfos_.end()) {
240         APP_LOGE("bundle info not exist");
241         return false;
242     }
243     std::lock_guard<std::mutex> stateLock(stateMutex_);
244     auto statusItem = installStates_.find(bundleName);
245     if (statusItem == installStates_.end()) {
246         APP_LOGE("save info fail, app:%{public}s is not updated", bundleName.c_str());
247         return false;
248     }
249     if (statusItem->second == InstallState::UNINSTALL_START || statusItem->second == InstallState::ROLL_BACK) {
250         APP_LOGD("save bundle:%{public}s info", bundleName.c_str());
251         oldInfo.RemoveModuleInfo(modulePackage);
252         oldInfo.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
253         if (dataStorage_->DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, oldInfo)) {
254             if (dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, oldInfo)) {
255                 APP_LOGI("update storage success bundle:%{public}s", bundleName.c_str());
256                 bundleInfos_.at(bundleName).at(Constants::CURRENT_DEVICE_ID) = oldInfo;
257                 DistributedBundleInfo DistributedBundleInfo;
258                 oldInfo.GetDistributedBundleInfo(DistributedBundleInfo);
259                 bool ret = distributedDataStorage_->SaveStorageDistributeInfo(DistributedBundleInfo);
260                 APP_LOGI("write DistributedBundleInfo bundle:%{public}s result:%{public}d", bundleName.c_str(), ret);
261                 return true;
262             }
263         }
264         APP_LOGD("after delete modulePackage:%{public}s info", modulePackage.c_str());
265     }
266     return true;
267 }
268 
AddInnerBundleUserInfo(const std::string & bundleName,const InnerBundleUserInfo & newUserInfo)269 bool BundleDataMgr::AddInnerBundleUserInfo(
270     const std::string &bundleName, const InnerBundleUserInfo& newUserInfo)
271 {
272     APP_LOGD("AddInnerBundleUserInfo:%{public}s", bundleName.c_str());
273     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
274     auto infoItem = bundleInfos_.find(bundleName);
275     if (infoItem == bundleInfos_.end()) {
276         APP_LOGE("bundle info not exist");
277         return false;
278     }
279 
280     std::lock_guard<std::mutex> stateLock(stateMutex_);
281     auto& info = bundleInfos_.at(bundleName).at(Constants::CURRENT_DEVICE_ID);
282     info.AddInnerBundleUserInfo(newUserInfo);
283     info.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
284     if (!dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, info)) {
285         APP_LOGE("update storage failed bundle:%{public}s", bundleName.c_str());
286         return false;
287     }
288 
289     DistributedBundleInfo DistributedBundleInfo;
290     info.GetDistributedBundleInfo(DistributedBundleInfo);
291     bool ret = distributedDataStorage_->SaveStorageDistributeInfo(DistributedBundleInfo);
292     APP_LOGD("write DistributedBundleInfo bundle:%{public}s result:%{public}d", bundleName.c_str(), ret);
293     return true;
294 }
295 
RemoveInnerBundleUserInfo(const std::string & bundleName,int32_t userId)296 bool BundleDataMgr::RemoveInnerBundleUserInfo(
297     const std::string &bundleName, int32_t userId)
298 {
299     APP_LOGD("RemoveInnerBundleUserInfo:%{public}s", bundleName.c_str());
300     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
301     auto infoItem = bundleInfos_.find(bundleName);
302     if (infoItem == bundleInfos_.end()) {
303         APP_LOGE("bundle info not exist");
304         return false;
305     }
306 
307     std::lock_guard<std::mutex> stateLock(stateMutex_);
308     auto& info = bundleInfos_.at(bundleName).at(Constants::CURRENT_DEVICE_ID);
309     info.RemoveInnerBundleUserInfo(userId);
310     info.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
311     if (!dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, info)) {
312         APP_LOGE("update storage failed bundle:%{public}s", bundleName.c_str());
313         return false;
314     }
315 
316     DistributedBundleInfo DistributedBundleInfo;
317     info.GetDistributedBundleInfo(DistributedBundleInfo);
318     bool ret = distributedDataStorage_->SaveStorageDistributeInfo(DistributedBundleInfo);
319     APP_LOGD("write DistributedBundleInfo bundle:%{public}s result:%{public}d", bundleName.c_str(), ret);
320     return true;
321 }
322 
UpdateInnerBundleInfo(const std::string & bundleName,const InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo)323 bool BundleDataMgr::UpdateInnerBundleInfo(
324     const std::string &bundleName, const InnerBundleInfo &newInfo, InnerBundleInfo &oldInfo)
325 {
326     APP_LOGD("UpdateInnerBundleInfo:%{public}s", bundleName.c_str());
327     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
328     auto infoItem = bundleInfos_.find(bundleName);
329     if (infoItem == bundleInfos_.end()) {
330         APP_LOGE("bundle info not exist");
331         return false;
332     }
333     std::lock_guard<std::mutex> stateLock(stateMutex_);
334     auto statusItem = installStates_.find(bundleName);
335     if (statusItem == installStates_.end()) {
336         APP_LOGE("save info fail, app:%{public}s is not updated", bundleName.c_str());
337         return false;
338     }
339     // ROLL_BACK and USER_CHANGE should not be here
340     if (statusItem->second == InstallState::UPDATING_SUCCESS
341         || statusItem->second == InstallState::ROLL_BACK
342         || statusItem->second == InstallState::USER_CHANGE) {
343         APP_LOGD("begin to update, bundleName : %{public}s, moduleName : %{public}s",
344             bundleName.c_str(), newInfo.GetCurrentModulePackage().c_str());
345         // 1.exist entry, update entry.
346         // 2.only exist feature, update feature.
347         if (newInfo.HasEntry() || !oldInfo.HasEntry()) {
348             oldInfo.UpdateBaseBundleInfo(newInfo.GetBaseBundleInfo(), newInfo.HasEntry());
349             oldInfo.UpdateBaseApplicationInfo(newInfo.GetBaseApplicationInfo());
350             oldInfo.SetMainAbility(newInfo.GetMainAbility());
351             oldInfo.SetMainAbilityName(newInfo.GetMainAbilityName());
352             oldInfo.SetAppType(newInfo.GetAppType());
353             oldInfo.SetAppFeature(newInfo.GetAppFeature());
354             oldInfo.SetAppPrivilegeLevel(newInfo.GetAppPrivilegeLevel());
355             oldInfo.SetAllowedAcls(newInfo.GetAllowedAcls());
356         }
357         if (newInfo.HasEntry()) {
358             oldInfo.SetHasEntry(true);
359         }
360         oldInfo.updateCommonHapInfo(newInfo);
361         oldInfo.UpdateModuleInfo(newInfo);
362         oldInfo.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
363         if (dataStorage_->DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, oldInfo)) {
364             if (dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, oldInfo)) {
365                 APP_LOGI("update storage success bundle:%{public}s", bundleName.c_str());
366                 bundleInfos_.at(bundleName).at(Constants::CURRENT_DEVICE_ID) = oldInfo;
367                 DistributedBundleInfo DistributedBundleInfo;
368                 oldInfo.GetDistributedBundleInfo(DistributedBundleInfo);
369                 bool ret = distributedDataStorage_->SaveStorageDistributeInfo(DistributedBundleInfo);
370                 APP_LOGI("write DistributedBundleInfo bundle:%{public}s result:%{public}d", bundleName.c_str(), ret);
371                 return true;
372             }
373         }
374     }
375     return false;
376 }
377 
QueryAbilityInfo(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo) const378 bool BundleDataMgr::QueryAbilityInfo(const Want &want, int32_t flags, int32_t userId, AbilityInfo &abilityInfo) const
379 {
380     int32_t requestUserId = GetUserId(userId);
381     if (requestUserId == Constants::INVALID_USERID) {
382         return false;
383     }
384 
385     // for launcher
386     if (want.HasEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM)) {
387         std::lock_guard<std::mutex> lock(bundleInfoMutex_);
388         for (const auto &item : bundleInfos_) {
389             for (const auto &info : item.second) {
390                 if (HasInitialUserCreated() && info.second.GetIsLauncherApp()) {
391                     APP_LOGI("find launcher app %{public}s", info.second.GetBundleName().c_str());
392                     info.second.GetMainAbilityInfo(abilityInfo);
393                     int32_t responseUserId = info.second.GetResponseUserId(requestUserId);
394                     info.second.GetApplicationInfo(
395                         ApplicationFlag::GET_BASIC_APPLICATION_INFO, responseUserId, abilityInfo.applicationInfo);
396                     return true;
397                 }
398             }
399         }
400         return false;
401     }
402 
403     ElementName element = want.GetElement();
404     std::string bundleName = element.GetBundleName();
405     std::string abilityName = element.GetAbilityName();
406     APP_LOGD("bundle name:%{public}s, ability name:%{public}s", bundleName.c_str(), abilityName.c_str());
407     // explicit query
408     if (!bundleName.empty() && !abilityName.empty()) {
409         bool ret = ExplicitQueryAbilityInfo(bundleName, abilityName, flags, requestUserId, abilityInfo);
410         if (ret == false) {
411             APP_LOGE("explicit queryAbilityInfo error");
412             return false;
413         }
414         return true;
415     }
416     std::vector<AbilityInfo> abilityInfos;
417     bool ret = ImplicitQueryAbilityInfos(want, flags, requestUserId, abilityInfos);
418     if (ret == false) {
419         APP_LOGE("implicit queryAbilityInfos error");
420         return false;
421     }
422     if (abilityInfos.size() == 0) {
423         APP_LOGE("no matching abilityInfo");
424         return false;
425     }
426     abilityInfo = abilityInfos[0];
427     return true;
428 }
429 
QueryAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const430 bool BundleDataMgr::QueryAbilityInfos(
431     const Want &want, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos) const
432 {
433     int32_t requestUserId = GetUserId(userId);
434     if (requestUserId == Constants::INVALID_USERID) {
435         return false;
436     }
437 
438     ElementName element = want.GetElement();
439     std::string bundleName = element.GetBundleName();
440     std::string abilityName = element.GetAbilityName();
441     APP_LOGD("bundle name:%{public}s, ability name:%{public}s", bundleName.c_str(), abilityName.c_str());
442     // explicit query
443     if (!bundleName.empty() && !abilityName.empty()) {
444         AbilityInfo abilityInfo;
445         bool ret = ExplicitQueryAbilityInfo(
446             bundleName, abilityName, flags, requestUserId, abilityInfo);
447         if (ret == false) {
448             APP_LOGE("explicit queryAbilityInfo error");
449             return false;
450         }
451         abilityInfos.emplace_back(abilityInfo);
452         return true;
453     }
454     // implicit query
455     bool ret = ImplicitQueryAbilityInfos(want, flags, requestUserId, abilityInfos);
456     if (ret == false) {
457         APP_LOGE("implicit queryAbilityInfos error");
458         return false;
459     }
460     if (abilityInfos.size() == 0) {
461         APP_LOGE("no matching abilityInfo");
462         return false;
463     }
464     return true;
465 }
466 
ExplicitQueryAbilityInfo(const std::string & bundleName,const std::string & abilityName,int32_t flags,int32_t userId,AbilityInfo & abilityInfo) const467 bool BundleDataMgr::ExplicitQueryAbilityInfo(const std::string &bundleName, const std::string &abilityName,
468     int32_t flags, int32_t userId, AbilityInfo &abilityInfo) const
469 {
470     APP_LOGD("bundleName:%{public}s, abilityName:%{public}s", bundleName.c_str(), abilityName.c_str());
471     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
472     int32_t requestUserId = GetUserId(userId);
473     if (requestUserId == Constants::INVALID_USERID) {
474         return false;
475     }
476 
477     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
478     InnerBundleInfo innerBundleInfo;
479     if (!GetInnerBundleInfoWithFlags(
480         bundleName, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
481         APP_LOGE("ExplicitQueryAbilityInfo failed");
482         return false;
483     }
484 
485     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
486     auto ability = innerBundleInfo.FindAbilityInfo(bundleName, abilityName, responseUserId);
487     if (!ability) {
488         APP_LOGE("ability not found");
489         return false;
490     }
491     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_SYSTEMAPP_ONLY) == GET_ABILITY_INFO_SYSTEMAPP_ONLY &&
492         !innerBundleInfo.IsSystemApp()) {
493         return false;
494     }
495     if (!(static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_DISABLE)) {
496         if (!innerBundleInfo.IsAbilityEnabled((*ability), responseUserId)) {
497             APP_LOGE("ability:%{public}s is disabled", ability->name.c_str());
498             return false;
499         }
500     }
501     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_PERMISSION) != GET_ABILITY_INFO_WITH_PERMISSION) {
502         ability->permissions.clear();
503     }
504     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_METADATA) != GET_ABILITY_INFO_WITH_METADATA) {
505         ability->metaData.customizeData.clear();
506         ability->metadata.clear();
507     }
508     abilityInfo = (*ability);
509     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_APPLICATION) == GET_ABILITY_INFO_WITH_APPLICATION) {
510         innerBundleInfo.GetApplicationInfo(
511             ApplicationFlag::GET_BASIC_APPLICATION_INFO, responseUserId, abilityInfo.applicationInfo);
512     }
513     return true;
514 }
515 
QueryAbilityInfosForClone(const Want & want,std::vector<AbilityInfo> & abilityInfo)516 bool BundleDataMgr::QueryAbilityInfosForClone(const Want &want, std::vector<AbilityInfo> &abilityInfo)
517 {
518     ElementName element = want.GetElement();
519     std::string abilityName = element.GetAbilityName();
520     std::string bundleName = element.GetBundleName();
521     if (bundleName.empty()) {
522         return false;
523     }
524     std::string keyName = bundleName + abilityName;
525     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
526     if (bundleInfos_.empty()) {
527         APP_LOGI("bundleInfos_ is empty");
528         return false;
529     }
530     std::string cloneBundleName = bundleName;
531     std::string name = bundleName + "#";
532     for (auto it = bundleInfos_.begin(); it != bundleInfos_.end();) {
533         if (it->first.find(name) != std::string::npos) {
534             cloneBundleName = it->first;
535             APP_LOGI("new name is %{public}s", cloneBundleName.c_str());
536             break;
537         } else {
538             ++it;
539         }
540     }
541     if (cloneBundleName != bundleName) {
542         auto itemClone = bundleInfos_.find(cloneBundleName);
543         if (itemClone == bundleInfos_.end()) {
544             APP_LOGI("bundle:%{public}s not find", bundleName.c_str());
545             return false;
546         }
547         auto infoWithIdItemClone = itemClone->second.find(Constants::CURRENT_DEVICE_ID);
548         if (infoWithIdItemClone == itemClone->second.end()) {
549             return false;
550         }
551         if (infoWithIdItemClone->second.IsDisabled()) {
552             return false;
553         }
554 
555         int32_t responseUserId = infoWithIdItemClone->second.GetResponseUserId(GetUserId());
556         infoWithIdItemClone->second.FindAbilityInfosForClone(bundleName, abilityName, responseUserId, abilityInfo);
557     }
558 
559     auto item = bundleInfos_.find(bundleName);
560     if (item == bundleInfos_.end()) {
561         APP_LOGI("bundle:%{public}s not find", bundleName.c_str());
562         return false;
563     }
564     auto infoWithIdItem = item->second.find(Constants::CURRENT_DEVICE_ID);
565     int32_t responseUserId = infoWithIdItem->second.GetResponseUserId(GetUserId());
566     infoWithIdItem->second.FindAbilityInfosForClone(bundleName, abilityName, responseUserId, abilityInfo);
567     if (abilityInfo.size() == 0) {
568         return false;
569     }
570     return true;
571 }
572 
ImplicitQueryAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const573 bool BundleDataMgr::ImplicitQueryAbilityInfos(
574     const Want &want, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos) const
575 {
576     int32_t requestUserId = GetUserId(userId);
577     if (requestUserId == Constants::INVALID_USERID) {
578         return false;
579     }
580 
581     if (want.GetAction().empty() && want.GetEntities().empty()
582         && want.GetUriString().empty() && want.GetType().empty()) {
583         APP_LOGE("param invalid");
584         return false;
585     }
586     APP_LOGD("action:%{public}s, uri:%{private}s, type:%{public}s",
587         want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
588     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
589     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
590     if (bundleInfos_.empty()) {
591         APP_LOGE("bundleInfos_ is empty");
592         return false;
593     }
594     std::string bundleName = want.GetElement().GetBundleName();
595     if (!bundleName.empty()) {
596         // query in current bundleName
597         InnerBundleInfo innerBundleInfo;
598         if (!GetInnerBundleInfoWithFlags(
599             bundleName, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
600             APP_LOGE("ImplicitQueryAbilityInfos failed");
601             return false;
602         }
603         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
604         GetMatchAbilityInfos(want, flags, innerBundleInfo, responseUserId, abilityInfos);
605     } else {
606         // query all
607         for (const auto &item : bundleInfos_) {
608             InnerBundleInfo innerBundleInfo;
609             if (!GetInnerBundleInfoWithFlags(
610                 item.first, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
611                 APP_LOGE("ImplicitQueryAbilityInfos failed");
612                 continue;
613             }
614 
615             int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
616             GetMatchAbilityInfos(want, flags, innerBundleInfo, responseUserId, abilityInfos);
617         }
618     }
619     // sort by priority, descending order.
620     if (abilityInfos.size() > 1) {
621         std::stable_sort(abilityInfos.begin(), abilityInfos.end(),
622             [](AbilityInfo a, AbilityInfo b) { return a.priority > b.priority; });
623     }
624     return true;
625 }
626 
GetMatchAbilityInfos(const Want & want,int32_t flags,const InnerBundleInfo & info,int32_t userId,std::vector<AbilityInfo> & abilityInfos) const627 void BundleDataMgr::GetMatchAbilityInfos(const Want &want, int32_t flags,
628     const InnerBundleInfo &info, int32_t userId, std::vector<AbilityInfo> &abilityInfos) const
629 {
630     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_SYSTEMAPP_ONLY) == GET_ABILITY_INFO_SYSTEMAPP_ONLY &&
631         !info.IsSystemApp()) {
632         return;
633     }
634     std::map<std::string, std::vector<Skill>> skillInfos = info.GetInnerSkillInfos();
635     for (const auto &abilityInfoPair : info.GetInnerAbilityInfos()) {
636         auto skillsPair = skillInfos.find(abilityInfoPair.first);
637         if (skillsPair == skillInfos.end()) {
638             continue;
639         }
640         for (const Skill &skill : skillsPair->second) {
641             if (skill.Match(want)) {
642                 AbilityInfo abilityinfo = abilityInfoPair.second;
643                 if (!(static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_DISABLE)) {
644                     if (!info.IsAbilityEnabled(abilityinfo, GetUserId(userId))) {
645                         APP_LOGW("GetMatchAbilityInfos %{public}s is disabled", abilityinfo.name.c_str());
646                         continue;
647                     }
648                 }
649                 if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_APPLICATION) ==
650                     GET_ABILITY_INFO_WITH_APPLICATION) {
651                     info.GetApplicationInfo(
652                         ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, abilityinfo.applicationInfo);
653                 }
654                 if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_PERMISSION) !=
655                     GET_ABILITY_INFO_WITH_PERMISSION) {
656                     abilityinfo.permissions.clear();
657                 }
658                 if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_METADATA) != GET_ABILITY_INFO_WITH_METADATA) {
659                     abilityinfo.metaData.customizeData.clear();
660                     abilityinfo.metadata.clear();
661                 }
662                 abilityInfos.emplace_back(abilityinfo);
663                 break;
664             }
665         }
666     }
667 }
668 
GetMatchLauncherAbilityInfos(const Want & want,const InnerBundleInfo & info,std::vector<AbilityInfo> & abilityInfos,int32_t userId) const669 void BundleDataMgr::GetMatchLauncherAbilityInfos(const Want& want,
670     const InnerBundleInfo& info, std::vector<AbilityInfo>& abilityInfos, int32_t userId) const
671 {
672     int32_t requestUserId = GetUserId(userId);
673     if (requestUserId == Constants::INVALID_USERID) {
674         return;
675     }
676 
677     int32_t responseUserId = info.GetResponseUserId(requestUserId);
678     std::map<std::string, std::vector<Skill>> skillInfos = info.GetInnerSkillInfos();
679     for (const auto& abilityInfoPair : info.GetInnerAbilityInfos()) {
680         auto skillsPair = skillInfos.find(abilityInfoPair.first);
681         if (skillsPair == skillInfos.end()) {
682             continue;
683         }
684         for (const Skill& skill : skillsPair->second) {
685             if (skill.MatchLauncher(want)) {
686                 AbilityInfo abilityinfo = abilityInfoPair.second;
687                 info.GetApplicationInfo(ApplicationFlag::GET_BASIC_APPLICATION_INFO,
688                     responseUserId, abilityinfo.applicationInfo);
689                 abilityInfos.emplace_back(abilityinfo);
690                 break;
691             }
692         }
693     }
694 }
695 
QueryLauncherAbilityInfos(const Want & want,uint32_t userId,std::vector<AbilityInfo> & abilityInfos) const696 bool BundleDataMgr::QueryLauncherAbilityInfos(
697     const Want& want, uint32_t userId, std::vector<AbilityInfo>& abilityInfos) const
698 {
699     int32_t requestUserId = GetUserId(userId);
700     if (requestUserId == Constants::INVALID_USERID) {
701         return false;
702     }
703 
704     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
705     if (bundleInfos_.empty()) {
706         APP_LOGE("bundleInfos_ is empty");
707         return false;
708     }
709 
710     ElementName element = want.GetElement();
711     std::string bundleName = element.GetBundleName();
712     if (bundleName.empty()) {
713         // query all launcher ability
714         for (const auto &item : bundleInfos_) {
715             auto infoWithIdItem = item.second.find(Constants::CURRENT_DEVICE_ID);
716             if (infoWithIdItem != item.second.end() && infoWithIdItem->second.IsDisabled()) {
717                 APP_LOGI("app %{public}s is disabled", infoWithIdItem->second.GetBundleName().c_str());
718                 continue;
719             }
720             if (infoWithIdItem != item.second.end()) {
721                 GetMatchLauncherAbilityInfos(want, infoWithIdItem->second, abilityInfos, requestUserId);
722             }
723         }
724         return true;
725     } else {
726         // query definite abilitys by bundle name
727         auto item = bundleInfos_.find(bundleName);
728         if (item == bundleInfos_.end()) {
729             APP_LOGE("no bundleName %{public}s found", bundleName.c_str());
730             return false;
731         }
732         auto infoWithIdItem = item->second.find(Constants::CURRENT_DEVICE_ID);
733         if (infoWithIdItem != item->second.end()) {
734             GetMatchLauncherAbilityInfos(want, infoWithIdItem->second, abilityInfos, requestUserId);
735         }
736         return true;
737     }
738 }
739 
QueryAbilityInfoByUri(const std::string & abilityUri,int32_t userId,AbilityInfo & abilityInfo) const740 bool BundleDataMgr::QueryAbilityInfoByUri(
741     const std::string &abilityUri, int32_t userId, AbilityInfo &abilityInfo) const
742 {
743     APP_LOGD("abilityUri is %{private}s", abilityUri.c_str());
744     int32_t requestUserId = GetUserId(userId);
745     if (requestUserId == Constants::INVALID_USERID) {
746         return false;
747     }
748 
749     if (abilityUri.empty()) {
750         return false;
751     }
752     if (abilityUri.find(Constants::DATA_ABILITY_URI_PREFIX) == std::string::npos) {
753         return false;
754     }
755     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
756     if (bundleInfos_.empty()) {
757         APP_LOGE("bundleInfos_ data is empty");
758         return false;
759     }
760     std::string noPpefixUri = abilityUri.substr(Constants::DATA_ABILITY_URI_PREFIX.size());
761     auto posFirstSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR);
762     if (posFirstSeparator == std::string::npos) {
763         return false;
764     }
765     auto posSecondSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR, posFirstSeparator + 1);
766     std::string uri;
767     if (posSecondSeparator == std::string::npos) {
768         uri = noPpefixUri.substr(posFirstSeparator + 1, noPpefixUri.size() - posFirstSeparator - 1);
769     } else {
770         uri = noPpefixUri.substr(posFirstSeparator + 1, posSecondSeparator - posFirstSeparator - 1);
771     }
772 
773     std::string deviceId = noPpefixUri.substr(0, posFirstSeparator);
774     if (deviceId.empty()) {
775         deviceId = Constants::CURRENT_DEVICE_ID;
776     }
777 
778     for (const auto &item : bundleInfos_) {
779         auto infoWithIdItem = item.second.find(deviceId);
780         if (infoWithIdItem == item.second.end()) {
781             APP_LOGE("bundle device id:%{public}s not find", deviceId.c_str());
782             continue;
783         }
784 
785         if (infoWithIdItem->second.IsDisabled()) {
786             APP_LOGE("app %{public}s is disabled", infoWithIdItem->second.GetBundleName().c_str());
787             continue;
788         }
789 
790         int32_t responseUserId = infoWithIdItem->second.GetResponseUserId(requestUserId);
791         if (!infoWithIdItem->second.GetApplicationEnabled(responseUserId)) {
792             continue;
793         }
794 
795         auto ability = infoWithIdItem->second.FindAbilityInfoByUri(uri);
796         if (!ability) {
797             continue;
798         }
799 
800         abilityInfo = (*ability);
801         infoWithIdItem->second.GetApplicationInfo(
802             ApplicationFlag::GET_BASIC_APPLICATION_INFO, responseUserId, abilityInfo.applicationInfo);
803         return true;
804     }
805 
806     APP_LOGE("query abilityUri(%{private}s) failed.", abilityUri.c_str());
807     return false;
808 }
809 
QueryAbilityInfosByUri(const std::string & abilityUri,std::vector<AbilityInfo> & abilityInfos)810 bool BundleDataMgr::QueryAbilityInfosByUri(const std::string &abilityUri, std::vector<AbilityInfo> &abilityInfos)
811 {
812     APP_LOGI("abilityUri is %{private}s", abilityUri.c_str());
813     if (abilityUri.empty()) {
814         return false;
815     }
816     if (abilityUri.find(Constants::DATA_ABILITY_URI_PREFIX) == std::string::npos) {
817         return false;
818     }
819     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
820     if (bundleInfos_.empty()) {
821         APP_LOGI("bundleInfos_ data is empty");
822         return false;
823     }
824     std::string noPpefixUri = abilityUri.substr(Constants::DATA_ABILITY_URI_PREFIX.size());
825     auto posFirstSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR);
826     if (posFirstSeparator == std::string::npos) {
827         return false;
828     }
829     auto posSecondSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR, posFirstSeparator + 1);
830     std::string uri;
831     if (posSecondSeparator == std::string::npos) {
832         uri = noPpefixUri.substr(posFirstSeparator + 1, noPpefixUri.size() - posFirstSeparator - 1);
833     } else {
834         uri = noPpefixUri.substr(posFirstSeparator + 1, posSecondSeparator - posFirstSeparator - 1);
835     }
836 
837     std::string deviceId = noPpefixUri.substr(0, posFirstSeparator);
838     if (deviceId.empty()) {
839         deviceId = Constants::CURRENT_DEVICE_ID;
840     }
841     for (auto &item : bundleInfos_) {
842         auto infoWithIdItem = item.second.find(deviceId);
843         if (infoWithIdItem == item.second.end()) {
844             APP_LOGI("bundle device id:%{public}s not find", deviceId.c_str());
845             return false;
846         }
847         if (infoWithIdItem->second.IsDisabled()) {
848             APP_LOGI("app %{public}s is disabled", infoWithIdItem->second.GetBundleName().c_str());
849             continue;
850         }
851         infoWithIdItem->second.FindAbilityInfosByUri(uri, abilityInfos, GetUserId());
852     }
853     if (abilityInfos.size() == 0) {
854         return false;
855     }
856 
857     return true;
858 }
859 
GetApplicationInfo(const std::string & appName,int32_t flags,const int userId,ApplicationInfo & appInfo) const860 bool BundleDataMgr::GetApplicationInfo(
861     const std::string &appName, int32_t flags, const int userId, ApplicationInfo &appInfo) const
862 {
863     int32_t requestUserId = GetUserId(userId);
864     if (requestUserId == Constants::INVALID_USERID) {
865         return false;
866     }
867 
868     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
869     InnerBundleInfo innerBundleInfo;
870     if (!GetInnerBundleInfoWithFlags(
871         appName, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
872         APP_LOGE("GetApplicationInfo failed");
873         return false;
874     }
875 
876     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
877     innerBundleInfo.GetApplicationInfo(flags, responseUserId, appInfo);
878     return true;
879 }
880 
GetApplicationInfos(int32_t flags,const int userId,std::vector<ApplicationInfo> & appInfos) const881 bool BundleDataMgr::GetApplicationInfos(
882     int32_t flags, const int userId, std::vector<ApplicationInfo> &appInfos) const
883 {
884     int32_t requestUserId = GetUserId(userId);
885     if (requestUserId == Constants::INVALID_USERID) {
886         return false;
887     }
888 
889     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
890     if (bundleInfos_.empty()) {
891         APP_LOGE("bundleInfos_ data is empty");
892         return false;
893     }
894 
895     bool find = false;
896     for (const auto &item : bundleInfos_) {
897         for (const auto &info : item.second) {
898             if (info.second.IsDisabled()) {
899                 APP_LOGE("app %{public}s is disabled", info.second.GetBundleName().c_str());
900                 continue;
901             }
902 
903             int32_t responseUserId = info.second.GetResponseUserId(requestUserId);
904             if (!(static_cast<uint32_t>(flags) & GET_APPLICATION_INFO_WITH_DISABLE)
905                 && !info.second.GetApplicationEnabled(responseUserId)) {
906                 APP_LOGD("bundleName: %{public}s is disabled", info.second.GetBundleName().c_str());
907                 continue;
908             }
909 
910             ApplicationInfo appInfo;
911             info.second.GetApplicationInfo(flags, responseUserId, appInfo);
912             appInfos.emplace_back(appInfo);
913             find = true;
914         }
915     }
916     APP_LOGD("get installed bundles success");
917     return find;
918 }
919 
GetBundleInfo(const std::string & bundleName,int32_t flags,BundleInfo & bundleInfo,int32_t userId) const920 bool BundleDataMgr::GetBundleInfo(
921     const std::string &bundleName, int32_t flags, BundleInfo &bundleInfo, int32_t userId) const
922 {
923     std::vector<InnerBundleUserInfo> innerBundleUserInfos;
924     if (userId == Constants::ANY_USERID) {
925         if (!GetInnerBundleUserInfos(bundleName, innerBundleUserInfos)) {
926             APP_LOGE("no userInfos for this bundle(%{public}s)", bundleName.c_str());
927             return false;
928         }
929         userId = innerBundleUserInfos.begin()->bundleUserInfo.userId;
930     }
931 
932     int32_t requestUserId = GetUserId(userId);
933     if (requestUserId == Constants::INVALID_USERID) {
934         return false;
935     }
936     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
937     InnerBundleInfo innerBundleInfo;
938     if (!GetInnerBundleInfoWithFlags(
939         bundleName, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
940         APP_LOGE("GetBundleInfo failed");
941         return false;
942     }
943 
944     int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
945     innerBundleInfo.GetBundleInfo(flags, bundleInfo, responseUserId);
946     APP_LOGD("get bundleInfo(%{public}s) successfully in user(%{public}d)", bundleName.c_str(), userId);
947     return true;
948 }
949 
GetBundleInfosByMetaData(const std::string & metaData,std::vector<BundleInfo> & bundleInfos) const950 bool BundleDataMgr::GetBundleInfosByMetaData(
951     const std::string &metaData, std::vector<BundleInfo> &bundleInfos) const
952 {
953     if (metaData.empty()) {
954         APP_LOGE("bundle name is empty");
955         return false;
956     }
957 
958     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
959     if (bundleInfos_.empty()) {
960         APP_LOGE("bundleInfos_ data is empty");
961         return false;
962     }
963 
964     bool find = false;
965     int32_t requestUserId = GetUserId();
966     for (const auto &item : bundleInfos_) {
967         for (const auto &info : item.second) {
968             if (info.second.IsDisabled()) {
969                 APP_LOGW("app %{public}s is disabled", info.second.GetBundleName().c_str());
970                 continue;
971             }
972             if (info.second.CheckSpecialMetaData(metaData)) {
973                 BundleInfo bundleInfo;
974                 int32_t responseUserId = info.second.GetResponseUserId(requestUserId);
975                 info.second.GetBundleInfo(
976                     BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, responseUserId);
977                 bundleInfos.emplace_back(bundleInfo);
978                 find = true;
979             }
980         }
981     }
982     return find;
983 }
984 
GetBundleList(std::vector<std::string> & bundleNames,int32_t userId) const985 bool BundleDataMgr::GetBundleList(
986     std::vector<std::string> &bundleNames, int32_t userId) const
987 {
988     int32_t requestUserId = GetUserId(userId);
989     if (requestUserId == Constants::INVALID_USERID) {
990         return false;
991     }
992 
993     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
994     if (bundleInfos_.empty()) {
995         APP_LOGE("bundleInfos_ data is empty");
996         return false;
997     }
998 
999     bool find = false;
1000     for (const auto &infoItem : bundleInfos_) {
1001         InnerBundleInfo innerBundleInfo;
1002         if (!GetInnerBundleInfoWithFlags(infoItem.first, BundleFlag::GET_BUNDLE_DEFAULT,
1003             Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
1004             continue;
1005         }
1006 
1007         bundleNames.emplace_back(infoItem.first);
1008         find = true;
1009     }
1010     APP_LOGD("user(%{public}d) get installed bundles list result(%{public}d)", userId, find);
1011     return find;
1012 }
1013 
GetBundleInfos(int32_t flags,std::vector<BundleInfo> & bundleInfos,int32_t userId) const1014 bool BundleDataMgr::GetBundleInfos(
1015     int32_t flags, std::vector<BundleInfo> &bundleInfos, int32_t userId) const
1016 {
1017     if (userId == Constants::ALL_USERID) {
1018         return GetAllBundleInfos(flags, bundleInfos);
1019     }
1020 
1021     int32_t requestUserId = GetUserId(userId);
1022     if (requestUserId == Constants::INVALID_USERID) {
1023         return false;
1024     }
1025 
1026     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1027     if (bundleInfos_.empty()) {
1028         APP_LOGE("bundleInfos_ data is empty");
1029         return false;
1030     }
1031 
1032     bool find = false;
1033     for (const auto &item : bundleInfos_) {
1034         InnerBundleInfo innerBundleInfo;
1035         if (!GetInnerBundleInfoWithFlags(
1036             item.first, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
1037             continue;
1038         }
1039 
1040         BundleInfo bundleInfo;
1041         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
1042         innerBundleInfo.GetBundleInfo(flags, bundleInfo, responseUserId);
1043         bundleInfos.emplace_back(bundleInfo);
1044         find = true;
1045     }
1046     APP_LOGD("get bundleInfos result(%{public}d) in user(%{public}d).", find, userId);
1047     return find;
1048 }
1049 
GetAllBundleInfos(int32_t flags,std::vector<BundleInfo> & bundleInfos) const1050 bool BundleDataMgr::GetAllBundleInfos(
1051     int32_t flags, std::vector<BundleInfo> &bundleInfos) const
1052 {
1053     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1054     if (bundleInfos_.empty()) {
1055         APP_LOGE("bundleInfos_ data is empty");
1056         return false;
1057     }
1058 
1059     bool find = false;
1060     for (const auto &item : bundleInfos_) {
1061         for (const auto &info : item.second) {
1062             if (info.second.IsDisabled()) {
1063                 APP_LOGD("app %{public}s is disabled", info.second.GetBundleName().c_str());
1064                 continue;
1065             }
1066 
1067             BundleInfo bundleInfo;
1068             info.second.GetBundleInfo(flags, bundleInfo, Constants::ALL_USERID);
1069             bundleInfos.emplace_back(bundleInfo);
1070             find = true;
1071         }
1072     }
1073 
1074     APP_LOGD("get all bundleInfos result(%{public}d).", find);
1075     return find;
1076 }
1077 
GetBundleNameForUid(const int uid,std::string & bundleName) const1078 bool BundleDataMgr::GetBundleNameForUid(const int uid, std::string &bundleName) const
1079 {
1080     InnerBundleInfo innerBundleInfo;
1081     if (!GetInnerBundleInfoByUid(uid, innerBundleInfo)) {
1082         APP_LOGE("get innerBundleInfo by uid failed.");
1083         return false;
1084     }
1085 
1086     bundleName = innerBundleInfo.GetBundleName();
1087     return true;
1088 }
1089 
GetInnerBundleInfoByUid(const int uid,InnerBundleInfo & innerBundleInfo) const1090 bool BundleDataMgr::GetInnerBundleInfoByUid(const int uid, InnerBundleInfo &innerBundleInfo) const
1091 {
1092     int32_t userId = GetUserIdByUid(uid);
1093     if (userId == Constants::UNSPECIFIED_USERID || userId == Constants::INVALID_USERID) {
1094         APP_LOGE("the uid %{public}d is illegal when get bundleName by uid.", uid);
1095         return false;
1096     }
1097 
1098     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1099     if (bundleInfos_.empty()) {
1100         APP_LOGE("bundleInfos_ data is empty");
1101         return false;
1102     }
1103 
1104     for (const auto &item : bundleInfos_) {
1105         for (const auto &info : item.second) {
1106             if (info.second.IsDisabled()) {
1107                 APP_LOGW("app %{public}s is disabled", info.second.GetBundleName().c_str());
1108                 continue;
1109             }
1110 
1111             if (info.second.GetUid(userId) == uid) {
1112                 innerBundleInfo = info.second;
1113                 return true;
1114             }
1115         }
1116     }
1117 
1118     APP_LOGD("the uid(%{public}d) is not exists.", uid);
1119     return false;
1120 }
1121 
GetBundlesForUid(const int uid,std::vector<std::string> & bundleNames) const1122 bool BundleDataMgr::GetBundlesForUid(const int uid, std::vector<std::string> &bundleNames) const
1123 {
1124     InnerBundleInfo innerBundleInfo;
1125     if (!GetInnerBundleInfoByUid(uid, innerBundleInfo)) {
1126         APP_LOGE("get innerBundleInfo by uid failed.");
1127         return false;
1128     }
1129 
1130     bundleNames.emplace_back(innerBundleInfo.GetBundleName());
1131     return true;
1132 }
1133 
GetNameForUid(const int uid,std::string & name) const1134 bool BundleDataMgr::GetNameForUid(const int uid, std::string &name) const
1135 {
1136     InnerBundleInfo innerBundleInfo;
1137     if (!GetInnerBundleInfoByUid(uid, innerBundleInfo)) {
1138         APP_LOGE("get innerBundleInfo by uid failed.");
1139         return false;
1140     }
1141 
1142     name = innerBundleInfo.GetBundleName();
1143     return true;
1144 }
1145 
GetBundleGids(const std::string & bundleName,std::vector<int> & gids) const1146 bool BundleDataMgr::GetBundleGids(const std::string &bundleName, std::vector<int> &gids) const
1147 {
1148     int32_t requestUserId = GetUserId();
1149     InnerBundleUserInfo innerBundleUserInfo;
1150     if (!GetInnerBundleUserInfoByUserId(bundleName, requestUserId, innerBundleUserInfo)) {
1151         APP_LOGE("the user(%{public}d) is not exists in bundleName(%{public}s) .",
1152             requestUserId, bundleName.c_str());
1153         return false;
1154     }
1155 
1156     gids = innerBundleUserInfo.gids;
1157     return true;
1158 }
1159 
GetBundleGidsByUid(const std::string & bundleName,const int & uid,std::vector<int> & gids) const1160 bool BundleDataMgr::GetBundleGidsByUid(
1161     const std::string &bundleName, const int &uid, std::vector<int> &gids) const
1162 {
1163     return true;
1164 }
1165 
QueryKeepAliveBundleInfos(std::vector<BundleInfo> & bundleInfos) const1166 bool BundleDataMgr::QueryKeepAliveBundleInfos(std::vector<BundleInfo> &bundleInfos) const
1167 {
1168     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1169     if (bundleInfos_.empty()) {
1170         APP_LOGE("bundleInfos_ data is empty");
1171         return false;
1172     }
1173 
1174     int32_t requestUserId = GetUserId();
1175     for (const auto &item : bundleInfos_) {
1176         for (const auto &info : item.second) {
1177             if (info.second.IsDisabled()) {
1178                 APP_LOGW("app %{public}s is disabled", info.second.GetBundleName().c_str());
1179                 continue;
1180             }
1181             if (info.second.GetIsKeepAlive()) {
1182                 BundleInfo bundleInfo;
1183                 int32_t responseUserId = info.second.GetResponseUserId(requestUserId);
1184                 info.second.GetBundleInfo(BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, responseUserId);
1185                 if (bundleInfo.name == "") {
1186                     continue;
1187                 }
1188                 bundleInfos.emplace_back(bundleInfo);
1189             }
1190         }
1191     }
1192     return !(bundleInfos.empty());
1193 }
1194 
GetAbilityLabel(const std::string & bundleName,const std::string & className) const1195 std::string BundleDataMgr::GetAbilityLabel(const std::string &bundleName, const std::string &className) const
1196 {
1197     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1198     if (bundleInfos_.empty()) {
1199         APP_LOGW("bundleInfos_ data is empty");
1200         return Constants::EMPTY_STRING;
1201     }
1202     APP_LOGI("GetAbilityLabel %{public}s", bundleName.c_str());
1203     auto infoItem = bundleInfos_.find(bundleName);
1204     if (infoItem == bundleInfos_.end()) {
1205         return Constants::EMPTY_STRING;
1206     }
1207     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1208     if (innerBundleInfo == infoItem->second.end()) {
1209         return Constants::EMPTY_STRING;
1210     }
1211     if (innerBundleInfo->second.IsDisabled()) {
1212         APP_LOGW("app %{public}s is disabled", innerBundleInfo->second.GetBundleName().c_str());
1213         return Constants::EMPTY_STRING;
1214     }
1215     auto ability = innerBundleInfo->second.FindAbilityInfo(bundleName, className, GetUserId());
1216     if (!ability) {
1217         return Constants::EMPTY_STRING;
1218     }
1219     if ((*ability).labelId == 0) {
1220         return (*ability).label;
1221     }
1222     std::string abilityLabel;
1223     BundleInfo bundleInfo;
1224     innerBundleInfo->second.GetBundleInfo(0, bundleInfo, GetUserIdByCallingUid());
1225     std::shared_ptr<OHOS::Global::Resource::ResourceManager> resourceManager = GetResourceManager(bundleInfo);
1226     if (resourceManager == nullptr) {
1227         APP_LOGE("InitResourceManager failed");
1228         return Constants::EMPTY_STRING;
1229     }
1230     OHOS::Global::Resource::RState errval =
1231         resourceManager->GetStringById(static_cast<uint32_t>((*ability).labelId), abilityLabel);
1232     if (errval != OHOS::Global::Resource::RState::SUCCESS) {
1233         return Constants::EMPTY_STRING;
1234     } else {
1235         return abilityLabel;
1236     }
1237 }
1238 
GetHapModuleInfo(const AbilityInfo & abilityInfo,HapModuleInfo & hapModuleInfo) const1239 bool BundleDataMgr::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) const
1240 {
1241     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1242     if (bundleInfos_.empty()) {
1243         APP_LOGE("bundleInfos_ data is empty");
1244         return false;
1245     }
1246 
1247     APP_LOGD("GetHapModuleInfo %{public}s", abilityInfo.bundleName.c_str());
1248     auto infoItem = bundleInfos_.find(abilityInfo.bundleName);
1249     if (infoItem == bundleInfos_.end()) {
1250         return false;
1251     }
1252 
1253     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1254     if (innerBundleInfo == infoItem->second.end()) {
1255         return false;
1256     }
1257 
1258     if (innerBundleInfo->second.IsDisabled()) {
1259         APP_LOGE("app %{public}s is disabled", innerBundleInfo->second.GetBundleName().c_str());
1260         return false;
1261     }
1262 
1263     int32_t responseUserId = innerBundleInfo->second.GetResponseUserId(GetUserId());
1264     auto module = innerBundleInfo->second.FindHapModuleInfo(abilityInfo.package, responseUserId);
1265     if (!module) {
1266         APP_LOGE("can not find module %{public}s", abilityInfo.package.c_str());
1267         return false;
1268     }
1269     hapModuleInfo = *module;
1270     return true;
1271 }
1272 
GetLaunchWantForBundle(const std::string & bundleName,Want & want) const1273 bool BundleDataMgr::GetLaunchWantForBundle(const std::string &bundleName, Want &want) const
1274 {
1275     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1276     InnerBundleInfo innerBundleInfo;
1277 
1278     if (!GetInnerBundleInfoWithFlags(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, Constants::CURRENT_DEVICE_ID,
1279         innerBundleInfo, GetUserIdByCallingUid())) {
1280         APP_LOGE("GetLaunchWantForBundle failed");
1281         return false;
1282     }
1283     std::string mainAbility = innerBundleInfo.GetMainAbilityName();
1284     if (mainAbility.empty()) {
1285         APP_LOGE("no main ability in the bundle %{public}s", bundleName.c_str());
1286         return false;
1287     }
1288     want.SetElementName(Constants::CURRENT_DEVICE_ID, bundleName, mainAbility);
1289     want.SetAction(Constants::INTENT_ACTION_HOME);
1290     want.AddEntity(Constants::INTENT_ENTITY_HOME);
1291     return true;
1292 }
1293 
CheckIsSystemAppByUid(const int uid) const1294 bool BundleDataMgr::CheckIsSystemAppByUid(const int uid) const
1295 {
1296     // If the value of uid is 0 (ROOT_UID) or 1000 (BMS_UID),
1297     // the uid should be the system uid.
1298     if (uid == Constants::ROOT_UID || uid == Constants::BMS_UID) {
1299         return true;
1300     }
1301 
1302     InnerBundleInfo innerBundleInfo;
1303     if (!GetInnerBundleInfoByUid(uid, innerBundleInfo)) {
1304         return false;
1305     }
1306 
1307     return innerBundleInfo.IsSystemApp();
1308 }
1309 
InitStateTransferMap()1310 void BundleDataMgr::InitStateTransferMap()
1311 {
1312     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::INSTALL_START);
1313     transferStates_.emplace(InstallState::INSTALL_FAIL, InstallState::INSTALL_START);
1314     transferStates_.emplace(InstallState::UNINSTALL_START, InstallState::INSTALL_SUCCESS);
1315     transferStates_.emplace(InstallState::UNINSTALL_START, InstallState::INSTALL_START);
1316     transferStates_.emplace(InstallState::UNINSTALL_START, InstallState::UPDATING_SUCCESS);
1317     transferStates_.emplace(InstallState::UNINSTALL_FAIL, InstallState::UNINSTALL_START);
1318     transferStates_.emplace(InstallState::UNINSTALL_SUCCESS, InstallState::UNINSTALL_START);
1319     transferStates_.emplace(InstallState::UPDATING_START, InstallState::INSTALL_SUCCESS);
1320     transferStates_.emplace(InstallState::UPDATING_SUCCESS, InstallState::UPDATING_START);
1321     transferStates_.emplace(InstallState::UPDATING_FAIL, InstallState::UPDATING_START);
1322     transferStates_.emplace(InstallState::UPDATING_FAIL, InstallState::INSTALL_START);
1323     transferStates_.emplace(InstallState::UPDATING_START, InstallState::INSTALL_START);
1324     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::UPDATING_START);
1325     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::UPDATING_SUCCESS);
1326     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::UNINSTALL_START);
1327     transferStates_.emplace(InstallState::UPDATING_START, InstallState::UPDATING_SUCCESS);
1328     transferStates_.emplace(InstallState::ROLL_BACK, InstallState::UPDATING_START);
1329     transferStates_.emplace(InstallState::ROLL_BACK, InstallState::UPDATING_SUCCESS);
1330     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::ROLL_BACK);
1331     transferStates_.emplace(InstallState::UNINSTALL_START, InstallState::USER_CHANGE);
1332     transferStates_.emplace(InstallState::UPDATING_START, InstallState::USER_CHANGE);
1333     transferStates_.emplace(InstallState::INSTALL_SUCCESS, InstallState::USER_CHANGE);
1334     transferStates_.emplace(InstallState::UPDATING_SUCCESS, InstallState::USER_CHANGE);
1335     transferStates_.emplace(InstallState::USER_CHANGE, InstallState::INSTALL_SUCCESS);
1336     transferStates_.emplace(InstallState::USER_CHANGE, InstallState::UPDATING_SUCCESS);
1337     transferStates_.emplace(InstallState::USER_CHANGE, InstallState::UPDATING_START);
1338 }
1339 
IsDeleteDataState(const InstallState state) const1340 bool BundleDataMgr::IsDeleteDataState(const InstallState state) const
1341 {
1342     return (state == InstallState::INSTALL_FAIL || state == InstallState::UNINSTALL_FAIL ||
1343             state == InstallState::UNINSTALL_SUCCESS || state == InstallState::UPDATING_FAIL);
1344 }
1345 
IsDisableState(const InstallState state) const1346 bool BundleDataMgr::IsDisableState(const InstallState state) const
1347 {
1348     if (state == InstallState::UPDATING_START || state == InstallState::UNINSTALL_START) {
1349         return true;
1350     }
1351     return false;
1352 }
1353 
DeleteBundleInfo(const std::string & bundleName,const InstallState state)1354 void BundleDataMgr::DeleteBundleInfo(const std::string &bundleName, const InstallState state)
1355 {
1356     if (InstallState::INSTALL_FAIL == state) {
1357         APP_LOGW("del fail, bundle:%{public}s has no installed info", bundleName.c_str());
1358         return;
1359     }
1360 
1361     auto infoItem = bundleInfos_.find(bundleName);
1362     if (infoItem != bundleInfos_.end()) {
1363         APP_LOGD("del bundle name:%{public}s", bundleName.c_str());
1364         const InnerBundleInfo &innerBundleInfo = infoItem->second[Constants::CURRENT_DEVICE_ID];
1365         RecycleUidAndGid(innerBundleInfo);
1366         bool ret = dataStorage_->DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo);
1367         if (!ret) {
1368             APP_LOGW("delete storage error name:%{public}s", bundleName.c_str());
1369         } else {
1370             DistributedBundleInfo DistributedBundleInfo;
1371             if (!distributedDataStorage_->DeleteStorageDistributeInfo(innerBundleInfo.GetBundleName())) {
1372                 APP_LOGW("delete DistributedBundleInfo fail bundle:%{public}s", bundleName.c_str());
1373             }
1374         }
1375         // only delete self-device bundle
1376         infoItem->second.erase(Constants::CURRENT_DEVICE_ID);
1377         if (infoItem->second.empty()) {
1378             APP_LOGD("now only store current device installed info, delete all");
1379             bundleInfos_.erase(bundleName);
1380         }
1381     }
1382 }
1383 
IsAppOrAbilityInstalled(const std::string & bundleName) const1384 bool BundleDataMgr::IsAppOrAbilityInstalled(const std::string &bundleName) const
1385 {
1386     if (bundleName.empty()) {
1387         APP_LOGW("name:%{public}s empty", bundleName.c_str());
1388         return false;
1389     }
1390 
1391     std::lock_guard<std::mutex> lock(stateMutex_);
1392     auto statusItem = installStates_.find(bundleName);
1393     if (statusItem == installStates_.end()) {
1394         APP_LOGW("name:%{public}s not find", bundleName.c_str());
1395         return false;
1396     }
1397 
1398     if (statusItem->second == InstallState::INSTALL_SUCCESS) {
1399         return true;
1400     }
1401 
1402     APP_LOGW("name:%{public}s not install success", bundleName.c_str());
1403     return false;
1404 }
1405 
GetInnerBundleInfoWithFlags(const std::string & bundleName,const int32_t flags,const std::string & deviceId,InnerBundleInfo & info,int32_t userId) const1406 bool BundleDataMgr::GetInnerBundleInfoWithFlags(const std::string &bundleName,
1407     const int32_t flags, const std::string &deviceId, InnerBundleInfo &info, int32_t userId) const
1408 {
1409     int32_t requestUserId = GetUserId(userId);
1410     if (requestUserId == Constants::INVALID_USERID) {
1411         return false;
1412     }
1413 
1414     if (bundleInfos_.empty()) {
1415         APP_LOGE("bundleInfos_ data is empty");
1416         return false;
1417     }
1418     APP_LOGD("GetInnerBundleInfoWithFlags: %{public}s", bundleName.c_str());
1419     auto infoItem = bundleInfos_.find(bundleName);
1420     if (infoItem == bundleInfos_.end()) {
1421         APP_LOGE("GetInnerBundleInfoWithFlags: bundleName not find");
1422         return false;
1423     }
1424     auto innerBundleInfo = infoItem->second.find(deviceId);
1425     if (innerBundleInfo == infoItem->second.end()) {
1426         APP_LOGE("GetInnerBundleInfoWithFlags: deviceid not find");
1427         return false;
1428     }
1429     if (innerBundleInfo->second.IsDisabled()) {
1430         APP_LOGE("bundleName: %{public}s status is disabled", innerBundleInfo->second.GetBundleName().c_str());
1431         return false;
1432     }
1433 
1434     int32_t responseUserId = innerBundleInfo->second.GetResponseUserId(requestUserId);
1435     if (!(static_cast<uint32_t>(flags) & GET_APPLICATION_INFO_WITH_DISABLE)
1436         && !innerBundleInfo->second.GetApplicationEnabled(responseUserId)) {
1437         APP_LOGE("bundleName: %{public}s is disabled", innerBundleInfo->second.GetBundleName().c_str());
1438         return false;
1439     }
1440     info = innerBundleInfo->second;
1441     return true;
1442 }
1443 
GetInnerBundleInfo(const std::string & bundleName,const std::string & deviceId,InnerBundleInfo & info)1444 bool BundleDataMgr::GetInnerBundleInfo(
1445     const std::string &bundleName, const std::string &deviceId, InnerBundleInfo &info)
1446 {
1447     APP_LOGD("GetInnerBundleInfo %{public}s", bundleName.c_str());
1448     if (bundleName.empty() || deviceId.empty()) {
1449         APP_LOGE("bundleName or deviceId empty");
1450         return false;
1451     }
1452 
1453     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1454     auto infoItem = bundleInfos_.find(bundleName);
1455     if (infoItem == bundleInfos_.end()) {
1456         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
1457         return false;
1458     }
1459     auto infoWithIdItem = infoItem->second.find(deviceId);
1460     if (infoWithIdItem == infoItem->second.end()) {
1461         APP_LOGE("bundle:%{public}s device id not find", bundleName.c_str());
1462         return false;
1463     }
1464     infoWithIdItem->second.SetBundleStatus(InnerBundleInfo::BundleStatus::DISABLED);
1465     info = infoWithIdItem->second;
1466     return true;
1467 }
1468 
DisableBundle(const std::string & bundleName)1469 bool BundleDataMgr::DisableBundle(const std::string &bundleName)
1470 {
1471     APP_LOGD("DisableBundle %{public}s", bundleName.c_str());
1472     if (bundleName.empty()) {
1473         APP_LOGE("bundleName empty");
1474         return false;
1475     }
1476 
1477     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1478     auto infoItem = bundleInfos_.find(bundleName);
1479     if (infoItem == bundleInfos_.end()) {
1480         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
1481         return false;
1482     }
1483     auto infoWithIdItem = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1484     if (infoWithIdItem == infoItem->second.end()) {
1485         APP_LOGE("bundle:%{public}s device id not find", bundleName.c_str());
1486         return false;
1487     }
1488     infoWithIdItem->second.SetBundleStatus(InnerBundleInfo::BundleStatus::DISABLED);
1489     return true;
1490 }
1491 
EnableBundle(const std::string & bundleName)1492 bool BundleDataMgr::EnableBundle(const std::string &bundleName)
1493 {
1494     APP_LOGD("EnableBundle %{public}s", bundleName.c_str());
1495     if (bundleName.empty()) {
1496         APP_LOGE("bundleName empty");
1497         return false;
1498     }
1499 
1500     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1501     auto infoItem = bundleInfos_.find(bundleName);
1502     if (infoItem == bundleInfos_.end()) {
1503         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
1504         return false;
1505     }
1506     auto infoWithIdItem = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1507     if (infoWithIdItem == infoItem->second.end()) {
1508         APP_LOGE("bundle:%{public}s device id not find", bundleName.c_str());
1509         return false;
1510     }
1511     infoWithIdItem->second.SetBundleStatus(InnerBundleInfo::BundleStatus::ENABLED);
1512     return true;
1513 }
1514 
IsApplicationEnabled(const std::string & bundleName) const1515 bool BundleDataMgr::IsApplicationEnabled(const std::string &bundleName) const
1516 {
1517     APP_LOGD("IsApplicationEnabled %{public}s", bundleName.c_str());
1518     if (bundleName.empty()) {
1519         APP_LOGE("bundleName empty");
1520         return false;
1521     }
1522 
1523     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1524     auto infoItem = bundleInfos_.find(bundleName);
1525     if (infoItem == bundleInfos_.end()) {
1526         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
1527         return false;
1528     }
1529     auto infoWithIdItem = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1530     if (infoWithIdItem == infoItem->second.end()) {
1531         APP_LOGE("bundle:%{public}s device id not find", bundleName.c_str());
1532         return false;
1533     }
1534 
1535     int32_t responseUserId = infoWithIdItem->second.GetResponseUserId(GetUserId());
1536     return infoWithIdItem->second.GetApplicationEnabled(responseUserId);
1537 }
1538 
SetApplicationEnabled(const std::string & bundleName,bool isEnable,int32_t userId)1539 bool BundleDataMgr::SetApplicationEnabled(const std::string &bundleName, bool isEnable, int32_t userId)
1540 {
1541     APP_LOGD("SetApplicationEnabled %{public}s", bundleName.c_str());
1542     if (bundleName.empty()) {
1543         APP_LOGE("bundleName empty");
1544         return false;
1545     }
1546     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1547     auto infoItem = bundleInfos_.find(bundleName);
1548     if (infoItem == bundleInfos_.end()) {
1549         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
1550         return false;
1551     }
1552     auto infoWithIdItem = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1553     if (infoWithIdItem == infoItem->second.end()) {
1554         APP_LOGE("bundle:%{public}s device id not find", bundleName.c_str());
1555         return false;
1556     }
1557     InnerBundleInfo newInfo = infoWithIdItem->second;
1558     newInfo.SetApplicationEnabled(isEnable, GetUserId(userId));
1559     if (dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, newInfo)) {
1560         infoWithIdItem->second.SetApplicationEnabled(isEnable, GetUserId(userId));
1561         return true;
1562     } else {
1563         APP_LOGE("bundle:%{private}s SetApplicationEnabled failed", bundleName.c_str());
1564         return false;
1565     }
1566 }
1567 
IsAbilityEnabled(const AbilityInfo & abilityInfo) const1568 bool BundleDataMgr::IsAbilityEnabled(const AbilityInfo &abilityInfo) const
1569 {
1570     int32_t flags = GET_ABILITY_INFO_DEFAULT;
1571     AbilityInfo abilityInfoIn;
1572     return ExplicitQueryAbilityInfo(abilityInfo.bundleName, abilityInfo.name, flags, GetUserId(), abilityInfoIn);
1573 }
1574 
SetAbilityEnabled(const AbilityInfo & abilityInfo,bool isEnabled,int32_t userId)1575 bool BundleDataMgr::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled, int32_t userId)
1576 {
1577     APP_LOGD("SetAbilityEnabled %{public}s", abilityInfo.name.c_str());
1578     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1579     if (bundleInfos_.empty()) {
1580         APP_LOGE("bundleInfos_ data is empty");
1581         return false;
1582     }
1583     APP_LOGD("SetAbilityEnabled %{public}s", abilityInfo.bundleName.c_str());
1584     auto infoItem = bundleInfos_.find(abilityInfo.bundleName);
1585     if (infoItem == bundleInfos_.end()) {
1586         return false;
1587     }
1588     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1589     if (innerBundleInfo == infoItem->second.end()) {
1590         return false;
1591     }
1592     InnerBundleInfo newInfo = innerBundleInfo->second;
1593     newInfo.SetAbilityEnabled(abilityInfo.bundleName, abilityInfo.name, isEnabled, GetUserId(userId));
1594     if (dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, newInfo)) {
1595         return innerBundleInfo->second.SetAbilityEnabled(
1596             abilityInfo.bundleName, abilityInfo.name, isEnabled, GetUserId(userId));
1597     }
1598     APP_LOGD("dataStorage SetAbilityEnabled %{public}s failed", abilityInfo.bundleName.c_str());
1599     return false;
1600 }
1601 
GetAbilityIcon(const std::string & bundleName,const std::string & className) const1602 std::string BundleDataMgr::GetAbilityIcon(const std::string &bundleName, const std::string &className) const
1603 {
1604     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1605     if (bundleInfos_.empty()) {
1606         APP_LOGW("bundleInfos_ data is empty");
1607         return Constants::EMPTY_STRING;
1608     }
1609     APP_LOGD("GetAbilityIcon %{public}s", bundleName.c_str());
1610     auto infoItem = bundleInfos_.find(bundleName);
1611     if (infoItem == bundleInfos_.end()) {
1612         return Constants::EMPTY_STRING;
1613     }
1614     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1615     if (innerBundleInfo == infoItem->second.end()) {
1616         return Constants::EMPTY_STRING;
1617     }
1618     auto ability = innerBundleInfo->second.FindAbilityInfo(bundleName, className, GetUserId());
1619     if (!ability) {
1620         return Constants::EMPTY_STRING;
1621     }
1622     return (*ability).iconPath;
1623 }
1624 
1625 #ifdef SUPPORT_GRAPHICS
GetAbilityPixelMapIcon(const std::string & bundleName,const std::string & abilityName) const1626 std::shared_ptr<Media::PixelMap> BundleDataMgr::GetAbilityPixelMapIcon(const std::string &bundleName,
1627     const std::string &abilityName) const
1628 {
1629     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1630     if (bundleInfos_.empty()) {
1631         APP_LOGW("bundleInfos_ data is empty");
1632         return nullptr;
1633     }
1634     APP_LOGD("GetAbilityIcon %{public}s", bundleName.c_str());
1635     auto infoItem = bundleInfos_.find(bundleName);
1636     if (infoItem == bundleInfos_.end()) {
1637         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
1638         return nullptr;
1639     }
1640     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1641     if (innerBundleInfo == infoItem->second.end()) {
1642         APP_LOGE("bundle:%{public}s device id not find", bundleName.c_str());
1643         return nullptr;
1644     }
1645     auto ability = innerBundleInfo->second.FindAbilityInfo(bundleName, abilityName, GetUserId());
1646     if (!ability) {
1647         APP_LOGE("abilityName:%{public}s not find", abilityName.c_str());
1648         return nullptr;
1649     }
1650     BundleInfo bundleInfo;
1651     int32_t flags = 0;
1652     innerBundleInfo->second.GetBundleInfo(flags, bundleInfo, GetUserId());
1653     std::shared_ptr<Global::Resource::ResourceManager> resourceManager = GetResourceManager(bundleInfo);
1654     if (resourceManager == nullptr) {
1655         APP_LOGE("InitResourceManager failed");
1656         return nullptr;
1657     }
1658     std::string iconPath;
1659     OHOS::Global::Resource::RState iconPathErrval =
1660         resourceManager->GetMediaById(static_cast<uint32_t>((*ability).iconId), iconPath);
1661     if (iconPathErrval != OHOS::Global::Resource::RState::SUCCESS) {
1662         APP_LOGE("GetMediaById iconPath failed");
1663         return nullptr;
1664     }
1665     APP_LOGD("GetMediaById iconPath: %{public}s", iconPath.c_str());
1666     auto pixelMapPtr = LoadImageFile(iconPath);
1667     if (!pixelMapPtr) {
1668         APP_LOGE("LoadImageFile failed");
1669         return nullptr;
1670     }
1671     return pixelMapPtr;
1672 }
1673 #endif
1674 
RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> & bundleStatusCallback)1675 bool BundleDataMgr::RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback)
1676 {
1677     APP_LOGD("RegisterBundleStatusCallback %{public}s", bundleStatusCallback->GetBundleName().c_str());
1678     std::lock_guard<std::mutex> lock(callbackMutex_);
1679     callbackList_.emplace_back(bundleStatusCallback);
1680     if (bundleStatusCallback->AsObject() != nullptr) {
1681         sptr<BundleStatusCallbackDeathRecipient> deathRecipient =
1682             new (std::nothrow) BundleStatusCallbackDeathRecipient();
1683         if (deathRecipient == nullptr) {
1684             APP_LOGE("deathRecipient is null");
1685             return false;
1686         }
1687         bundleStatusCallback->AsObject()->AddDeathRecipient(deathRecipient);
1688     }
1689     return true;
1690 }
1691 
RegisterBundleEventCallback(const sptr<IBundleEventCallback> & bundleEventCallback)1692 bool BundleDataMgr::RegisterBundleEventCallback(const sptr<IBundleEventCallback> &bundleEventCallback)
1693 {
1694     if (bundleEventCallback == nullptr) {
1695         APP_LOGE("bundleEventCallback is null");
1696         return false;
1697     }
1698     std::lock_guard<std::mutex> lock(eventCallbackMutex_);
1699     if (eventCallbackList_.size() >= MAX_EVENT_CALL_BACK_SIZE) {
1700         APP_LOGE("eventCallbackList_ reach max size %{public}d", MAX_EVENT_CALL_BACK_SIZE);
1701         return false;
1702     }
1703     if (bundleEventCallback->AsObject() != nullptr) {
1704         sptr<BundleEventCallbackDeathRecipient> deathRecipient =
1705             new (std::nothrow) BundleEventCallbackDeathRecipient();
1706         if (deathRecipient == nullptr) {
1707             APP_LOGE("deathRecipient is null");
1708             return false;
1709         }
1710         bundleEventCallback->AsObject()->AddDeathRecipient(deathRecipient);
1711     }
1712     eventCallbackList_.emplace_back(bundleEventCallback);
1713     return true;
1714 }
1715 
UnregisterBundleEventCallback(const sptr<IBundleEventCallback> & bundleEventCallback)1716 bool BundleDataMgr::UnregisterBundleEventCallback(const sptr<IBundleEventCallback> &bundleEventCallback)
1717 {
1718     APP_LOGD("begin to UnregisterBundleEventCallback");
1719     if (bundleEventCallback == nullptr) {
1720         APP_LOGE("bundleEventCallback is null");
1721         return false;
1722     }
1723     std::lock_guard<std::mutex> lock(eventCallbackMutex_);
1724     eventCallbackList_.erase(std::remove_if(eventCallbackList_.begin(), eventCallbackList_.end(),
1725         [&bundleEventCallback](const sptr<IBundleEventCallback> &callback) {
1726             return callback->AsObject() == bundleEventCallback->AsObject();
1727         }), eventCallbackList_.end());
1728     return true;
1729 }
1730 
NotifyBundleEventCallback(const EventFwk::CommonEventData & eventData) const1731 void BundleDataMgr::NotifyBundleEventCallback(const EventFwk::CommonEventData &eventData) const
1732 {
1733     APP_LOGD("begin to NotifyBundleEventCallback");
1734     std::lock_guard<std::mutex> lock(eventCallbackMutex_);
1735     for (const auto &callback : eventCallbackList_) {
1736         callback->OnReceiveEvent(eventData);
1737     }
1738     APP_LOGD("finish to NotifyBundleEventCallback");
1739 }
1740 
ClearBundleStatusCallback(const sptr<IBundleStatusCallback> & bundleStatusCallback)1741 bool BundleDataMgr::ClearBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback)
1742 {
1743     APP_LOGD("ClearBundleStatusCallback %{public}s", bundleStatusCallback->GetBundleName().c_str());
1744     std::lock_guard<std::mutex> lock(callbackMutex_);
1745     callbackList_.erase(std::remove_if(callbackList_.begin(),
1746         callbackList_.end(),
1747         [&](const sptr<IBundleStatusCallback> &callback) {
1748             return callback->AsObject() == bundleStatusCallback->AsObject();
1749         }),
1750         callbackList_.end());
1751     return true;
1752 }
1753 
UnregisterBundleStatusCallback()1754 bool BundleDataMgr::UnregisterBundleStatusCallback()
1755 {
1756     std::lock_guard<std::mutex> lock(callbackMutex_);
1757     callbackList_.clear();
1758     return true;
1759 }
1760 
GenerateUidAndGid(InnerBundleUserInfo & innerBundleUserInfo)1761 bool BundleDataMgr::GenerateUidAndGid(InnerBundleUserInfo &innerBundleUserInfo)
1762 {
1763     if (innerBundleUserInfo.bundleName.empty()) {
1764         APP_LOGE("bundleName is null.");
1765         return false;
1766     }
1767 
1768     int32_t bundleId = Constants::INVALID_BUNDLEID;
1769     if (!GenerateBundleId(innerBundleUserInfo.bundleName, bundleId)) {
1770         APP_LOGE("Generate bundleId failed.");
1771         return false;
1772     }
1773 
1774     innerBundleUserInfo.uid = innerBundleUserInfo.bundleUserInfo.userId * Constants::BASE_USER_RANGE
1775         + bundleId % Constants::BASE_USER_RANGE;
1776     innerBundleUserInfo.gids.emplace_back(innerBundleUserInfo.uid);
1777     return true;
1778 }
1779 
GenerateBundleId(const std::string & bundleName,int32_t & bundleId)1780 bool BundleDataMgr::GenerateBundleId(const std::string &bundleName, int32_t &bundleId)
1781 {
1782     std::lock_guard<std::mutex> lock(bundleIdMapMutex_);
1783     if (bundleIdMap_.empty()) {
1784         APP_LOGI("first app install");
1785         bundleId = Constants::BASE_APP_UID;
1786         bundleIdMap_.emplace(bundleId, bundleName);
1787         return true;
1788     }
1789 
1790     for (const auto &innerBundleId : bundleIdMap_) {
1791         if (innerBundleId.second == bundleName) {
1792             bundleId = innerBundleId.first;
1793             return true;
1794         }
1795     }
1796 
1797     for (int32_t i = Constants::BASE_APP_UID; i < bundleIdMap_.rbegin()->first; ++i) {
1798         if (bundleIdMap_.find(i) == bundleIdMap_.end()) {
1799             APP_LOGI("the %{public}d app install", i);
1800             bundleId = i;
1801             bundleIdMap_.emplace(bundleId, bundleName);
1802             BundleUtil::MakeHmdfsConfig(bundleName, bundleId);
1803             return true;
1804         }
1805     }
1806 
1807     if (bundleIdMap_.rbegin()->first == Constants::MAX_APP_UID) {
1808         APP_LOGE("the bundleId exceeding the maximum value.");
1809         return false;
1810     }
1811 
1812     bundleId = bundleIdMap_.rbegin()->first + 1;
1813     bundleIdMap_.emplace(bundleId, bundleName);
1814     BundleUtil::MakeHmdfsConfig(bundleName, bundleId);
1815     return true;
1816 }
1817 
RecycleUidAndGid(const InnerBundleInfo & info)1818 void BundleDataMgr::RecycleUidAndGid(const InnerBundleInfo &info)
1819 {
1820     auto userInfos = info.GetInnerBundleUserInfos();
1821     if (userInfos.empty()) {
1822         return;
1823     }
1824 
1825     auto innerBundleUserInfo = userInfos.begin()->second;
1826     int32_t bundleId = innerBundleUserInfo.uid -
1827         innerBundleUserInfo.bundleUserInfo.userId * Constants::BASE_USER_RANGE;
1828     std::lock_guard<std::mutex> lock(bundleIdMapMutex_);
1829     auto infoItem = bundleIdMap_.find(bundleId);
1830     if (infoItem == bundleIdMap_.end()) {
1831         return;
1832     }
1833 
1834     bundleIdMap_.erase(bundleId);
1835     BundleUtil::RemoveHmdfsConfig(innerBundleUserInfo.bundleName);
1836 }
1837 
GenerateCloneUid(InnerBundleInfo & info)1838 bool BundleDataMgr::GenerateCloneUid(InnerBundleInfo &info)
1839 {
1840     return true;
1841 }
1842 
GetUsageRecords(const int32_t maxNum,std::vector<ModuleUsageRecord> & records)1843 bool BundleDataMgr::GetUsageRecords(const int32_t maxNum, std::vector<ModuleUsageRecord> &records)
1844 {
1845     APP_LOGD("GetUsageRecords, maxNum: %{public}d", maxNum);
1846     if ((maxNum <= 0) || (maxNum > ProfileReader::MAX_USAGE_RECORD_SIZE)) {
1847         APP_LOGE("maxNum illegal");
1848         return false;
1849     }
1850     records.clear();
1851     std::vector<ModuleUsageRecord> usageRecords;
1852     bool result = usageRecordStorage_->QueryRecordByNum(maxNum, usageRecords, GetUserId());
1853     if (!result) {
1854         APP_LOGE("GetUsageRecords error");
1855         return false;
1856     }
1857     for (ModuleUsageRecord &item : usageRecords) {
1858         APP_LOGD("GetUsageRecords item:%{public}s,%{public}s,%{public}s",
1859             item.bundleName.c_str(),
1860             item.name.c_str(),
1861             item.abilityName.c_str());
1862 
1863         std::lock_guard<std::mutex> lock(bundleInfoMutex_);
1864         if (bundleInfos_.empty()) {
1865             APP_LOGW("bundleInfos_ data is empty");
1866             break;
1867         }
1868         auto infoItem = bundleInfos_.find(item.bundleName);
1869         if (infoItem == bundleInfos_.end()) {
1870             continue;
1871         }
1872         APP_LOGD("GetUsageRecords %{public}s", infoItem->first.c_str());
1873         auto bundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
1874         if (bundleInfo == infoItem->second.end()) {
1875             continue;
1876         }
1877         if (bundleInfo->second.IsDisabled()) {
1878             APP_LOGW("app %{public}s is disabled", bundleInfo->second.GetBundleName().c_str());
1879             continue;
1880         }
1881         auto innerModuleInfo = bundleInfo->second.GetInnerModuleInfoByModuleName(item.name);
1882         if (!innerModuleInfo) {
1883             continue;
1884         }
1885         item.labelId = innerModuleInfo->labelId;
1886         item.descriptionId = innerModuleInfo->descriptionId;
1887         item.installationFreeSupported = innerModuleInfo->installationFree;
1888         auto appInfo = bundleInfo->second.GetBaseApplicationInfo();
1889         item.appLabelId = static_cast<uint32_t>(appInfo.labelId);
1890         auto ability = bundleInfo->second.FindAbilityInfo(item.bundleName, item.abilityName, GetUserId());
1891         if (!ability) {
1892             APP_LOGW("ability:%{public}s not find", item.abilityName.c_str());
1893             continue;
1894         }
1895         if (ability->type != AbilityType::PAGE) {
1896             APP_LOGW("ability:%{public}s type is not PAGE", item.abilityName.c_str());
1897             continue;
1898         }
1899         item.abilityName = ability->name;
1900         item.abilityLabelId = ability->labelId;
1901         item.abilityDescriptionId = ability->descriptionId;
1902         item.abilityIconId = ability->iconId;
1903         records.emplace_back(item);
1904     }
1905     return true;
1906 }
1907 
RestoreUidAndGid()1908 bool BundleDataMgr::RestoreUidAndGid()
1909 {
1910     for (const auto &item : bundleInfos_) {
1911         for (const auto &info : item.second) {
1912             bool onlyInsertOne = false;
1913             for (auto infoItem : info.second.GetInnerBundleUserInfos()) {
1914                 auto innerBundleUserInfo = infoItem.second;
1915                 AddUserId(innerBundleUserInfo.bundleUserInfo.userId);
1916                 if (!onlyInsertOne) {
1917                     onlyInsertOne = true;
1918                     int32_t bundleId = innerBundleUserInfo.uid -
1919                         innerBundleUserInfo.bundleUserInfo.userId * Constants::BASE_USER_RANGE;
1920                     std::lock_guard<std::mutex> lock(bundleIdMapMutex_);
1921                     auto infoItem = bundleIdMap_.find(bundleId);
1922                     if (infoItem == bundleIdMap_.end()) {
1923                         bundleIdMap_.emplace(bundleId, innerBundleUserInfo.bundleName);
1924                     } else {
1925                         bundleIdMap_[bundleId] = innerBundleUserInfo.bundleName;
1926                     }
1927                     BundleUtil::MakeHmdfsConfig(innerBundleUserInfo.bundleName, bundleId);
1928                 }
1929             }
1930         }
1931     }
1932     return true;
1933 }
1934 
NotifyBundleStatus(const std::string & bundleName,const std::string & modulePackage,const std::string & abilityName,const ErrCode resultCode,const NotifyType type,const int32_t & uid)1935 bool BundleDataMgr::NotifyBundleStatus(const std::string& bundleName, const std::string& modulePackage,
1936     const std::string& abilityName, const ErrCode resultCode, const NotifyType type, const int32_t& uid)
1937 {
1938     APP_LOGD("notify type %{public}d with %{public}d for %{public}s-%{public}s in %{public}s", type, resultCode,
1939         modulePackage.c_str(), abilityName.c_str(), bundleName.c_str());
1940     std::string eventData = [type]() -> std::string {
1941         switch (type) {
1942             case NotifyType::INSTALL:
1943                 return EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED;
1944             case NotifyType::UNINSTALL_BUNDLE:
1945                 return EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED;
1946             case NotifyType::UNINSTALL_MODULE:
1947                 return EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED;
1948             case NotifyType::UPDATE:
1949                 return EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED;
1950             case NotifyType::ABILITY_ENABLE:
1951                 return EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED;
1952             case NotifyType::APPLICATION_ENABLE:
1953                 return EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED;
1954             default:
1955                 APP_LOGE("event type error");
1956                 return EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED;
1957         }
1958     }();
1959     APP_LOGD("will send event data %{public}s", eventData.c_str());
1960     Want want;
1961     want.SetAction(eventData);
1962     ElementName element;
1963     element.SetBundleName(bundleName);
1964     element.SetAbilityName(abilityName);
1965     want.SetElement(element);
1966     want.SetParam(Constants::UID, uid);
1967     want.SetParam(Constants::USER_ID, GetUserIdByUid(uid));
1968     want.SetParam(Constants::ABILTY_NAME.data(), abilityName);
1969     EventFwk::CommonEventData commonData { want };
1970     // trigger BundleEventCallback first
1971     NotifyBundleEventCallback(commonData);
1972 
1973     uint8_t installType = [&]() -> uint8_t {
1974         if ((type == NotifyType::UNINSTALL_BUNDLE) || (type == NotifyType::UNINSTALL_MODULE)) {
1975             return static_cast<uint8_t>(InstallType::UNINSTALL_CALLBACK);
1976         }
1977         return static_cast<uint8_t>(InstallType::INSTALL_CALLBACK);
1978     }();
1979     {
1980         std::lock_guard<std::mutex> lock(callbackMutex_);
1981         for (const auto& callback : callbackList_) {
1982             if (callback->GetBundleName() == bundleName) {
1983                 // if the msg needed, it could convert in the proxy node
1984                 callback->OnBundleStateChanged(installType, resultCode, Constants::EMPTY_STRING, bundleName);
1985             }
1986         }
1987     }
1988 
1989     if (resultCode != ERR_OK) {
1990         return true;
1991     }
1992     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1993     return true;
1994 }
1995 
GetBundleMutex(const std::string & bundleName)1996 std::mutex &BundleDataMgr::GetBundleMutex(const std::string &bundleName)
1997 {
1998     bundleMutex_.lock_shared();
1999     auto it = bundleMutexMap_.find(bundleName);
2000     if (it == bundleMutexMap_.end()) {
2001         bundleMutex_.unlock_shared();
2002         std::unique_lock lock {bundleMutex_};
2003         return bundleMutexMap_[bundleName];
2004     }
2005     bundleMutex_.unlock_shared();
2006     return it->second;
2007 }
2008 
GetProvisionId(const std::string & bundleName,std::string & provisionId) const2009 bool BundleDataMgr::GetProvisionId(const std::string &bundleName, std::string &provisionId) const
2010 {
2011     APP_LOGD("GetProvisionId %{public}s", bundleName.c_str());
2012     if (bundleName.empty()) {
2013         APP_LOGE("bundleName empty");
2014         return false;
2015     }
2016     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2017     auto infoItem = bundleInfos_.find(bundleName);
2018     if (infoItem == bundleInfos_.end()) {
2019         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2020         return false;
2021     }
2022     auto infoWithIdItem = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
2023     if (infoWithIdItem == infoItem->second.end()) {
2024         APP_LOGE("bundle:%{public}s device id not find", bundleName.c_str());
2025         return false;
2026     }
2027     provisionId = infoWithIdItem->second.GetProvisionId();
2028     return true;
2029 }
2030 
GetAppFeature(const std::string & bundleName,std::string & appFeature) const2031 bool BundleDataMgr::GetAppFeature(const std::string &bundleName, std::string &appFeature) const
2032 {
2033     APP_LOGD("GetAppFeature %{public}s", bundleName.c_str());
2034     if (bundleName.empty()) {
2035         APP_LOGE("bundleName empty");
2036         return false;
2037     }
2038     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2039     auto infoItem = bundleInfos_.find(bundleName);
2040     if (infoItem == bundleInfos_.end()) {
2041         APP_LOGE("can not find bundle %{public}s", bundleName.c_str());
2042         return false;
2043     }
2044     auto infoWithIdItem = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
2045     if (infoWithIdItem == infoItem->second.end()) {
2046         APP_LOGE("bundle:%{public}s device id not find", bundleName.c_str());
2047         return false;
2048     }
2049     appFeature = infoWithIdItem->second.GetAppFeature();
2050     return true;
2051 }
2052 
SetInitialUserFlag(bool flag)2053 void BundleDataMgr::SetInitialUserFlag(bool flag)
2054 {
2055     APP_LOGD("SetInitialUserFlag %{public}d", flag);
2056     if (!initialUserFlag_ && flag && bundlePromise_ != nullptr) {
2057         bundlePromise_->NotifyAllTasksExecuteFinished();
2058     }
2059 
2060     initialUserFlag_ = flag;
2061 }
2062 
CheckPublicKeys(const std::string & firstBundleName,const std::string & secondBundleName) const2063 int BundleDataMgr::CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) const
2064 {
2065     APP_LOGD("CheckPublicKeys %{public}s and %{public}s", firstBundleName.c_str(), secondBundleName.c_str());
2066     if (firstBundleName.empty() || secondBundleName.empty()) {
2067         APP_LOGE("bundleName empty");
2068         return Constants::SIGNATURE_UNKNOWN_BUNDLE;
2069     }
2070     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2071     auto firstInfoItem = bundleInfos_.find(firstBundleName);
2072     if (firstInfoItem == bundleInfos_.end()) {
2073         APP_LOGE("can not find bundle %{public}s", firstBundleName.c_str());
2074         return Constants::SIGNATURE_UNKNOWN_BUNDLE;
2075     }
2076     auto secondInfoItem = bundleInfos_.find(secondBundleName);
2077     if (secondInfoItem == bundleInfos_.end()) {
2078         APP_LOGE("can not find bundle %{public}s", secondBundleName.c_str());
2079         return Constants::SIGNATURE_UNKNOWN_BUNDLE;
2080     }
2081     auto firstInfoWithIdItem = firstInfoItem->second.find(Constants::CURRENT_DEVICE_ID);
2082     if (firstInfoWithIdItem == firstInfoItem->second.end()) {
2083         APP_LOGE("bundle:%{public}s device id not find", firstBundleName.c_str());
2084         return Constants::SIGNATURE_UNKNOWN_BUNDLE;
2085     }
2086     auto secondInfoWithIdItem = secondInfoItem->second.find(Constants::CURRENT_DEVICE_ID);
2087     if (secondInfoWithIdItem == secondInfoItem->second.end()) {
2088         APP_LOGE("bundle:%{public}s device id not find", secondBundleName.c_str());
2089         return Constants::SIGNATURE_UNKNOWN_BUNDLE;
2090     }
2091     auto firstProvisionId = secondInfoWithIdItem->second.GetProvisionId();
2092     auto secondProvisionId = secondInfoWithIdItem->second.GetProvisionId();
2093     return (firstProvisionId == secondProvisionId) ? Constants::SIGNATURE_MATCHED : Constants::SIGNATURE_NOT_MATCHED;
2094 }
2095 
GetDataStorage() const2096 std::shared_ptr<IBundleDataStorage> BundleDataMgr::GetDataStorage() const
2097 {
2098     return dataStorage_;
2099 }
2100 
GetAllFormsInfo(std::vector<FormInfo> & formInfos) const2101 bool BundleDataMgr::GetAllFormsInfo(std::vector<FormInfo> &formInfos) const
2102 {
2103     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2104     if (bundleInfos_.empty()) {
2105         APP_LOGE("bundleInfos_ data is empty");
2106         return false;
2107     }
2108     auto result = false;
2109     for (const auto &item : bundleInfos_) {
2110         for (const auto &info : item.second) {
2111             if (info.second.IsDisabled()) {
2112                 APP_LOGW("app %{public}s is disabled", info.second.GetBundleName().c_str());
2113                 continue;
2114             }
2115             info.second.GetFormsInfoByApp(formInfos);
2116             result = true;
2117         }
2118     }
2119     APP_LOGE("all the form infos find success");
2120     return result;
2121 }
2122 
GetFormsInfoByModule(const std::string & bundleName,const std::string & moduleName,std::vector<FormInfo> & formInfos) const2123 bool BundleDataMgr::GetFormsInfoByModule(
2124     const std::string &bundleName, const std::string &moduleName, std::vector<FormInfo> &formInfos) const
2125 {
2126     if (bundleName.empty()) {
2127         APP_LOGW("bundle name is empty");
2128         return false;
2129     }
2130     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2131     if (bundleInfos_.empty()) {
2132         APP_LOGE("bundleInfos_ data is empty");
2133         return false;
2134     }
2135     auto infoItem = bundleInfos_.find(bundleName);
2136     if (infoItem == bundleInfos_.end()) {
2137         return false;
2138     }
2139     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
2140     if (innerBundleInfo == infoItem->second.end()) {
2141         return false;
2142     }
2143     if (innerBundleInfo->second.IsDisabled()) {
2144         APP_LOGE("app %{public}s is disabled", innerBundleInfo->second.GetBundleName().c_str());
2145         return false;
2146     }
2147     innerBundleInfo->second.GetFormsInfoByModule(moduleName, formInfos);
2148     if (formInfos.empty()) {
2149         return false;
2150     }
2151     APP_LOGE("module forminfo find success");
2152     return true;
2153 }
2154 
GetFormsInfoByApp(const std::string & bundleName,std::vector<FormInfo> & formInfos) const2155 bool BundleDataMgr::GetFormsInfoByApp(const std::string &bundleName, std::vector<FormInfo> &formInfos) const
2156 {
2157     if (bundleName.empty()) {
2158         APP_LOGW("bundle name is empty");
2159         return false;
2160     }
2161     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2162     if (bundleInfos_.empty()) {
2163         APP_LOGE("bundleInfos_ data is empty");
2164         return false;
2165     }
2166     auto infoItem = bundleInfos_.find(bundleName);
2167     if (infoItem == bundleInfos_.end()) {
2168         return false;
2169     }
2170     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
2171     if (innerBundleInfo == infoItem->second.end()) {
2172         return false;
2173     }
2174     if (innerBundleInfo->second.IsDisabled()) {
2175         APP_LOGE("app %{public}s is disabled", innerBundleInfo->second.GetBundleName().c_str());
2176         return false;
2177     }
2178     innerBundleInfo->second.GetFormsInfoByApp(formInfos);
2179     APP_LOGE("App forminfo find success");
2180     return true;
2181 }
2182 
NotifyAbilityLifeStatus(const std::string & bundleName,const std::string & abilityName,const int64_t launchTime,const int uid) const2183 bool BundleDataMgr::NotifyAbilityLifeStatus(
2184     const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) const
2185 {
2186     if (bundleName.empty() || abilityName.empty()) {
2187         return false;
2188     }
2189     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2190     if (bundleInfos_.empty()) {
2191         return false;
2192     }
2193 
2194     int userId = GetUserIdByUid(uid);
2195     std::string cloneBundleName = bundleName;
2196     for (auto it = bundleInfos_.begin(); it != bundleInfos_.end();) {
2197         if (it->first.find(cloneBundleName) != std::string::npos) {
2198             auto bundleInfo = it->second.find(Constants::CURRENT_DEVICE_ID);
2199             if (bundleInfo != it->second.end() && bundleInfo->second.GetUid(userId) == uid) {
2200                 cloneBundleName = it->first;
2201                 break;
2202             }
2203             ++it;
2204         } else {
2205             ++it;
2206         }
2207     }
2208     auto infoItem = bundleInfos_.find(cloneBundleName);
2209     if (infoItem == bundleInfos_.end()) {
2210         return false;
2211     }
2212     auto bundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
2213     if (bundleInfo == infoItem->second.end()) {
2214         return false;
2215     }
2216     if (bundleInfo->second.IsDisabled()) {
2217         return false;
2218     }
2219     auto ability = bundleInfo->second.FindAbilityInfo(bundleName, abilityName, GetUserId(userId));
2220     if (!ability) {
2221         return false;
2222     }
2223     if (ability->applicationInfo.isCloned == true) {
2224         userId = Constants::C_UESRID;
2225     }
2226     if (ability->type != AbilityType::PAGE) {
2227         return false;
2228     }
2229     ModuleUsageRecord moduleUsageRecord;
2230     moduleUsageRecord.bundleName = bundleName;
2231     moduleUsageRecord.name = ability->moduleName;
2232     moduleUsageRecord.abilityName = abilityName;
2233     moduleUsageRecord.lastLaunchTime = launchTime;
2234     moduleUsageRecord.launchedCount = 1;
2235     return usageRecordStorage_->AddOrUpdateRecord(moduleUsageRecord, Constants::CURRENT_DEVICE_ID, userId);
2236 }
2237 
UpdateUsageRecordOnBundleRemoved(bool keepUsage,const int userId,const std::string & bundleName) const2238 bool BundleDataMgr::UpdateUsageRecordOnBundleRemoved(
2239     bool keepUsage, const int userId, const std::string &bundleName) const
2240 {
2241     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2242     if (bundleInfos_.empty()) {
2243         APP_LOGE("bundleInfos_ data is empty");
2244         return false;
2245     }
2246     auto infoItem = bundleInfos_.find(bundleName);
2247     if (infoItem == bundleInfos_.end()) {
2248         return false;
2249     }
2250     APP_LOGD("UpdateUsageRecordOnBundleRemoved %{public}s", infoItem->first.c_str());
2251     auto bundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
2252     if (bundleInfo == infoItem->second.end()) {
2253         return false;
2254     }
2255     if (bundleInfo->second.IsDisabled()) {
2256         APP_LOGE("app %{public}s is disabled", bundleInfo->second.GetBundleName().c_str());
2257         return false;
2258     }
2259     std::vector<std::string> moduleNames;
2260     return keepUsage ? usageRecordStorage_->MarkUsageRecordRemoved(bundleInfo->second, GetUserId(userId))
2261                      : usageRecordStorage_->DeleteUsageRecord(bundleInfo->second, GetUserId(userId));
2262 }
2263 
GetShortcutInfos(const std::string & bundleName,int32_t userId,std::vector<ShortcutInfo> & shortcutInfos) const2264 bool BundleDataMgr::GetShortcutInfos(
2265     const std::string &bundleName, int32_t userId, std::vector<ShortcutInfo> &shortcutInfos) const
2266 {
2267     int32_t requestUserId = GetUserId(userId);
2268     if (requestUserId == Constants::INVALID_USERID) {
2269         return false;
2270     }
2271 
2272     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2273     InnerBundleInfo innerBundleInfo;
2274     if (!GetInnerBundleInfoWithFlags(
2275         bundleName, BundleFlag::GET_BUNDLE_DEFAULT, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
2276         APP_LOGE("GetLaunchWantForBundle failed");
2277         return false;
2278     }
2279     innerBundleInfo.GetShortcutInfos(shortcutInfos);
2280     return true;
2281 }
2282 
GetAllCommonEventInfo(const std::string & eventKey,std::vector<CommonEventInfo> & commonEventInfos) const2283 bool BundleDataMgr::GetAllCommonEventInfo(const std::string &eventKey,
2284     std::vector<CommonEventInfo> &commonEventInfos) const
2285 {
2286     if (eventKey.empty()) {
2287         APP_LOGW("event key is empty");
2288         return false;
2289     }
2290     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2291     if (bundleInfos_.empty()) {
2292         APP_LOGI("bundleInfos_ data is empty");
2293         return false;
2294     }
2295     for (auto infoItem : bundleInfos_) {
2296         auto innerBundleInfo = infoItem.second.find(Constants::CURRENT_DEVICE_ID);
2297         if (innerBundleInfo == infoItem.second.end()) {
2298             continue;
2299         }
2300         if (innerBundleInfo->second.IsDisabled()) {
2301             APP_LOGI("app %{public}s is disabled", innerBundleInfo->second.GetBundleName().c_str());
2302             continue;
2303         }
2304         innerBundleInfo->second.GetCommonEvents(eventKey, commonEventInfos);
2305     }
2306     if (commonEventInfos.size() == 0) {
2307         APP_LOGE("commonEventInfos is empty");
2308         return false;
2309     }
2310     APP_LOGE("commonEventInfos find success");
2311     return true;
2312 }
2313 
RegisterAllPermissionsChanged(const sptr<OnPermissionChangedCallback> & callback)2314 bool BundleDataMgr::RegisterAllPermissionsChanged(const sptr<OnPermissionChangedCallback> &callback)
2315 {
2316     if (!callback) {
2317         APP_LOGE("callback is nullptr");
2318         return false;
2319     }
2320     std::lock_guard<std::mutex> lock(allPermissionsChangedLock_);
2321     std::set<sptr<OnPermissionChangedCallback>>::iterator it = allPermissionsCallbacks_.begin();
2322     while (it != allPermissionsCallbacks_.end()) {
2323         if ((*it)->AsObject() == callback->AsObject()) {
2324             break;
2325         }
2326         it++;
2327     }
2328     if (it == allPermissionsCallbacks_.end()) {
2329         allPermissionsCallbacks_.emplace(callback);
2330     }
2331     APP_LOGD("all permissions callbacks size = %{public}zu", allPermissionsCallbacks_.size());
2332     return AddDeathRecipient(callback);
2333 }
2334 
RegisterPermissionsChanged(const std::vector<int> & uids,const sptr<OnPermissionChangedCallback> & callback)2335 bool BundleDataMgr::RegisterPermissionsChanged(
2336     const std::vector<int> &uids, const sptr<OnPermissionChangedCallback> &callback)
2337 {
2338     if (!callback) {
2339         APP_LOGE("callback is nullptr");
2340         return false;
2341     }
2342     std::lock_guard<std::mutex> lock(permissionsChangedLock_);
2343     for (int32_t uid : uids) {
2344         std::set<sptr<OnPermissionChangedCallback>>::iterator it = permissionsCallbacks_[uid].begin();
2345         while (it != permissionsCallbacks_[uid].end()) {
2346             if ((*it)->AsObject() == callback->AsObject()) {
2347                 break;
2348             }
2349             it++;
2350         }
2351         if (it == permissionsCallbacks_[uid].end()) {
2352             permissionsCallbacks_[uid].emplace(callback);
2353         }
2354     }
2355     APP_LOGD("specified permissions callbacks size = %{public}zu", permissionsCallbacks_.size());
2356 
2357     for (const auto &item1 : permissionsCallbacks_) {
2358         APP_LOGD("item1->first = %{public}d", item1.first);
2359         APP_LOGD("item1->second.size() = %{public}zu", item1.second.size());
2360     }
2361     return AddDeathRecipient(callback);
2362 }
2363 
AddDeathRecipient(const sptr<OnPermissionChangedCallback> & callback)2364 bool BundleDataMgr::AddDeathRecipient(const sptr<OnPermissionChangedCallback> &callback)
2365 {
2366     if (!callback) {
2367         APP_LOGE("callback is nullptr");
2368         return false;
2369     }
2370     auto object = callback->AsObject();
2371     if (!object) {
2372         APP_LOGW("callback object is nullptr");
2373         return false;
2374     }
2375     // add callback death recipient.
2376     sptr<PermissionChangedDeathRecipient> deathRecipient = new (std::nothrow) PermissionChangedDeathRecipient();
2377     if (deathRecipient == nullptr) {
2378         APP_LOGE("create PermissionChangedDeathRecipient failed");
2379         return false;
2380     }
2381     object->AddDeathRecipient(deathRecipient);
2382     return true;
2383 }
2384 
UnregisterPermissionsChanged(const sptr<OnPermissionChangedCallback> & callback)2385 bool BundleDataMgr::UnregisterPermissionsChanged(const sptr<OnPermissionChangedCallback> &callback)
2386 {
2387     bool ret = false;
2388     if (!callback) {
2389         APP_LOGE("callback is nullptr");
2390         return ret;
2391     }
2392     {
2393         std::lock_guard<std::mutex> lock(allPermissionsChangedLock_);
2394 
2395         for (auto allPermissionsItem = allPermissionsCallbacks_.begin();
2396              allPermissionsItem != allPermissionsCallbacks_.end();) {
2397             if ((*allPermissionsItem)->AsObject() == callback->AsObject()) {
2398                 allPermissionsItem = allPermissionsCallbacks_.erase(allPermissionsItem);
2399                 APP_LOGI("unregister from all permissions callbacks success!");
2400                 ret = true;
2401                 break;
2402             } else {
2403                 allPermissionsItem++;
2404             }
2405         }
2406     }
2407     {
2408         std::lock_guard<std::mutex> lock(permissionsChangedLock_);
2409         for (auto mapIter = permissionsCallbacks_.begin(); mapIter != permissionsCallbacks_.end();) {
2410             for (auto it = mapIter->second.begin(); it != mapIter->second.end();) {
2411                 if ((*it)->AsObject() == callback->AsObject()) {
2412                     it = mapIter->second.erase(it);
2413                     APP_LOGI("unregister from specific permissions callbacks success!");
2414                     APP_LOGD("mapIter->first = %{public}d", (*mapIter).first);
2415                     APP_LOGD("*mapIter.second.size() = %{public}zu", (*mapIter).second.size());
2416                     ret = true;
2417                 } else {
2418                     it++;
2419                 }
2420             }
2421             if (mapIter->second.empty()) {
2422                 mapIter = permissionsCallbacks_.erase(mapIter);
2423             } else {
2424                 mapIter++;
2425             }
2426         }
2427     }
2428     for (const auto &item1 : permissionsCallbacks_) {
2429         APP_LOGD("item1->first = %{public}d", item1.first);
2430         APP_LOGD("item1->second.size() = %{public}zu", item1.second.size());
2431     }
2432     return ret;
2433 }
NotifyPermissionsChanged(int32_t uid)2434 bool BundleDataMgr::NotifyPermissionsChanged(int32_t uid)
2435 {
2436     if (uid < 0) {
2437         APP_LOGE("uid(%{private}d) is invalid", uid);
2438         return false;
2439     }
2440     APP_LOGD("notify permission changed, uid = %{public}d", uid);
2441     // for all permissions callback.
2442     {
2443         std::lock_guard<std::mutex> lock(allPermissionsChangedLock_);
2444         for (const auto &allPermissionItem : allPermissionsCallbacks_) {
2445             if (!allPermissionItem) {
2446                 APP_LOGE("callback is nullptr");
2447                 return false;
2448             }
2449 
2450             allPermissionItem->OnChanged(uid);
2451             APP_LOGD("all permissions changed callback");
2452         }
2453     }
2454     // for uid permissions callback.
2455     {
2456         std::lock_guard<std::mutex> lock(permissionsChangedLock_);
2457         APP_LOGD("specified permissions callbacks size = %{public}zu", permissionsCallbacks_.size());
2458         for (const auto &item1 : permissionsCallbacks_) {
2459             APP_LOGD("item1->first = %{public}d", item1.first);
2460             APP_LOGD("item1->second.size() = %{public}zu", item1.second.size());
2461         }
2462         auto callbackItem = permissionsCallbacks_.find(uid);
2463         if (callbackItem != permissionsCallbacks_.end()) {
2464             auto callbacks = callbackItem->second;
2465             for (const auto &item : callbacks) {
2466                 if (!item) {
2467                     APP_LOGE("callback is nullptr");
2468                     return false;
2469                 }
2470                 item->OnChanged(uid);
2471                 APP_LOGD("specified permissions changed callback");
2472             }
2473         }
2474     }
2475     return true;
2476 }
2477 
RemoveClonedBundleInfo(const std::string & bundleName)2478 bool BundleDataMgr::RemoveClonedBundleInfo(const std::string &bundleName)
2479 {
2480     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2481     auto infoItem = bundleInfos_.find(bundleName);
2482     if (infoItem != bundleInfos_.end()) {
2483         APP_LOGI("del bundle name:%{public}s", bundleName.c_str());
2484         const InnerBundleInfo &innerBundleInfo = infoItem->second[Constants::CURRENT_DEVICE_ID];
2485         RecycleUidAndGid(innerBundleInfo);
2486         bool ret = dataStorage_->DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo);
2487         if (!ret) {
2488             APP_LOGW("delete storage error name:%{public}s", bundleName.c_str());
2489             return false;
2490         } else {
2491             DistributedBundleInfo DistributedBundleInfo;
2492             if (!distributedDataStorage_->DeleteStorageDistributeInfo(innerBundleInfo.GetBundleName())) {
2493                 APP_LOGW("delete DistributedBundleInfo fail bundle:%{public}s", bundleName.c_str());
2494             }
2495         }
2496         // only delete self-device bundle
2497         infoItem->second.erase(Constants::CURRENT_DEVICE_ID);
2498         if (infoItem->second.empty()) {
2499             APP_LOGI("now only store current device cloned info, delete all");
2500             bundleInfos_.erase(bundleName);
2501         }
2502     }
2503     return true;
2504 }
2505 
GetClonedBundleName(const std::string & bundleName,std::string & newName)2506 bool BundleDataMgr::GetClonedBundleName(const std::string &bundleName, std::string &newName)
2507 {
2508     APP_LOGI("GetCloneBundleName start");
2509     std::string name = bundleName + "#";
2510     for (auto it = bundleInfos_.begin(); it != bundleInfos_.end();) {
2511         if (it->first.find(name) != std::string::npos) {
2512             newName = it->first;
2513             APP_LOGI("new name is %{public}s", newName.c_str());
2514             return true;
2515         } else {
2516             ++it;
2517         }
2518     }
2519     return false;
2520 }
2521 
SavePreInstallBundleInfo(const std::string & bundleName,const PreInstallBundleInfo & preInstallBundleInfo)2522 bool BundleDataMgr::SavePreInstallBundleInfo(
2523     const std::string &bundleName, const PreInstallBundleInfo &preInstallBundleInfo)
2524 {
2525     std::lock_guard<std::mutex> lock(preInstallInfoMutex_);
2526     if (!preInstallDataStorage_) {
2527         return false;
2528     }
2529 
2530     if (preInstallDataStorage_->SavePreInstallStorageBundleInfo(
2531         Constants::PRE_INSTALL_DEVICE_ID, preInstallBundleInfo)) {
2532         auto info = std::find_if(
2533             preInstallBundleInfos_.begin(), preInstallBundleInfos_.end(), preInstallBundleInfo);
2534         if (info != preInstallBundleInfos_.end()) {
2535             *info = preInstallBundleInfo;
2536         } else {
2537             preInstallBundleInfos_.emplace_back(preInstallBundleInfo);
2538         }
2539         APP_LOGD("write storage success bundle:%{public}s", bundleName.c_str());
2540         return true;
2541     }
2542 
2543     return false;
2544 }
2545 
DeletePreInstallBundleInfo(const std::string & bundleName,const PreInstallBundleInfo & preInstallBundleInfo)2546 bool BundleDataMgr::DeletePreInstallBundleInfo(
2547     const std::string &bundleName, const PreInstallBundleInfo &preInstallBundleInfo)
2548 {
2549     std::lock_guard<std::mutex> lock(preInstallInfoMutex_);
2550     if (!preInstallDataStorage_) {
2551         return false;
2552     }
2553 
2554     if (preInstallDataStorage_->DeletePreInstallStorageBundleInfo(
2555         Constants::PRE_INSTALL_DEVICE_ID, preInstallBundleInfo)) {
2556         auto info = std::find_if(
2557             preInstallBundleInfos_.begin(), preInstallBundleInfos_.end(), preInstallBundleInfo);
2558         if (info != preInstallBundleInfos_.end()) {
2559             preInstallBundleInfos_.erase(info);
2560         }
2561         APP_LOGI("Delete PreInstall Storage success bundle:%{public}s", bundleName.c_str());
2562         return true;
2563     }
2564 
2565     return false;
2566 }
2567 
GetPreInstallBundleInfo(const std::string & bundleName,PreInstallBundleInfo & preInstallBundleInfo)2568 bool BundleDataMgr::GetPreInstallBundleInfo(
2569     const std::string &bundleName, PreInstallBundleInfo &preInstallBundleInfo)
2570 {
2571     std::lock_guard<std::mutex> lock(preInstallInfoMutex_);
2572     if (bundleName.empty()) {
2573         APP_LOGE("bundleName or deviceId empty");
2574         return false;
2575     }
2576 
2577     preInstallBundleInfo.SetBundleName(bundleName);
2578     auto info = std::find_if(
2579         preInstallBundleInfos_.begin(), preInstallBundleInfos_.end(), preInstallBundleInfo);
2580     if (info != preInstallBundleInfos_.end()) {
2581         preInstallBundleInfo = *info;
2582         return true;
2583     }
2584 
2585     APP_LOGE("get preInstall bundleInfo failed by bundle(%{public}s).", bundleName.c_str());
2586     return false;
2587 }
2588 
LoadAllPreInstallBundleInfos(std::vector<PreInstallBundleInfo> & preInstallBundleInfos)2589 bool BundleDataMgr::LoadAllPreInstallBundleInfos(
2590     std::vector<PreInstallBundleInfo> &preInstallBundleInfos)
2591 {
2592     if (!preInstallDataStorage_) {
2593         return false;
2594     }
2595 
2596     if (preInstallDataStorage_->LoadAllPreInstallBundleInfos(preInstallBundleInfos)) {
2597         APP_LOGD("load all storage success");
2598         return true;
2599     }
2600 
2601     return false;
2602 }
2603 
SaveInstallMark(const InnerBundleInfo & info,bool isAppExisted) const2604 bool BundleDataMgr::SaveInstallMark(const InnerBundleInfo &info, bool isAppExisted) const
2605 {
2606     APP_LOGD("write install mark to storage with bundle:%{public}s", info.GetBundleName().c_str());
2607     if (!isAppExisted) {
2608         if (dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, info)) {
2609             APP_LOGD("save install mark successfully");
2610             return true;
2611         }
2612         APP_LOGE("save install mark failed!");
2613         return false;
2614     }
2615     if (dataStorage_->DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, info) &&
2616         dataStorage_->SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, info)) {
2617         APP_LOGD("save install mark successfully");
2618         return true;
2619     }
2620     APP_LOGE("save install mark failed!");
2621     return false;
2622 }
2623 
GetInnerBundleUserInfoByUserId(const std::string & bundleName,int32_t userId,InnerBundleUserInfo & innerBundleUserInfo) const2624 bool BundleDataMgr::GetInnerBundleUserInfoByUserId(const std::string &bundleName,
2625     int32_t userId, InnerBundleUserInfo &innerBundleUserInfo) const
2626 {
2627     APP_LOGD("get user info start: bundleName: (%{public}s)  userId: (%{public}d) ",
2628         bundleName.c_str(), userId);
2629     int32_t requestUserId = GetUserId(userId);
2630     if (requestUserId == Constants::INVALID_USERID) {
2631         return false;
2632     }
2633 
2634     if (bundleName.empty()) {
2635         APP_LOGW("bundle name is empty");
2636         return false;
2637     }
2638 
2639     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2640     if (bundleInfos_.empty()) {
2641         APP_LOGE("bundleInfos data is empty");
2642         return false;
2643     }
2644 
2645     auto infoItem = bundleInfos_.find(bundleName);
2646     if (infoItem == bundleInfos_.end()) {
2647         return false;
2648     }
2649 
2650     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
2651     if (innerBundleInfo == infoItem->second.end()) {
2652         return false;
2653     }
2654 
2655     if (innerBundleInfo->second.IsDisabled()) {
2656         APP_LOGE("app %{public}s is disabled", innerBundleInfo->second.GetBundleName().c_str());
2657         return false;
2658     }
2659 
2660     return innerBundleInfo->second.GetInnerBundleUserInfo(requestUserId, innerBundleUserInfo);
2661 }
2662 
GetUserId(int32_t userId) const2663 int32_t BundleDataMgr::GetUserId(int32_t userId) const
2664 {
2665     if (userId == Constants::UNSPECIFIED_USERID) {
2666         userId = GetUserIdByCallingUid();
2667     }
2668 
2669     if (!HasUserId(userId)) {
2670         APP_LOGE("user is not existed.");
2671         userId = Constants::INVALID_USERID;
2672     }
2673 
2674     return userId;
2675 }
2676 
GetUserIdByUid(int32_t uid) const2677 int32_t BundleDataMgr::GetUserIdByUid(int32_t uid) const
2678 {
2679     return BundleUtil::GetUserIdByUid(uid);
2680 }
2681 
AddUserId(int32_t userId)2682 void BundleDataMgr::AddUserId(int32_t userId)
2683 {
2684     std::lock_guard<std::mutex> lock(multiUserIdSetMutex_);
2685     auto item = multiUserIdsSet_.find(userId);
2686     if (item != multiUserIdsSet_.end()) {
2687         return;
2688     }
2689 
2690     multiUserIdsSet_.insert(userId);
2691 }
2692 
RemoveUserId(int32_t userId)2693 void BundleDataMgr::RemoveUserId(int32_t userId)
2694 {
2695     std::lock_guard<std::mutex> lock(multiUserIdSetMutex_);
2696     auto item = multiUserIdsSet_.find(userId);
2697     if (item == multiUserIdsSet_.end()) {
2698         return;
2699     }
2700 
2701     multiUserIdsSet_.erase(item);
2702 }
2703 
HasUserId(int32_t userId) const2704 bool BundleDataMgr::HasUserId(int32_t userId) const
2705 {
2706     std::lock_guard<std::mutex> lock(multiUserIdSetMutex_);
2707     return multiUserIdsSet_.find(userId) != multiUserIdsSet_.end();
2708 }
2709 
GetUserIdByCallingUid() const2710 int32_t BundleDataMgr::GetUserIdByCallingUid() const
2711 {
2712     return BundleUtil::GetUserIdByCallingUid();
2713 }
2714 
GetAllUser() const2715 std::set<int32_t> BundleDataMgr::GetAllUser() const
2716 {
2717     std::lock_guard<std::mutex> lock(multiUserIdSetMutex_);
2718     return multiUserIdsSet_;
2719 }
2720 
GetDistributedBundleInfo(const std::string & networkId,int32_t userId,const std::string & bundleName,DistributedBundleInfo & distributedBundleInfo)2721 bool BundleDataMgr::GetDistributedBundleInfo(
2722     const std::string &networkId, int32_t userId, const std::string &bundleName,
2723     DistributedBundleInfo &distributedBundleInfo)
2724 {
2725     if (userId == Constants::INVALID_USERID) {
2726         return false;
2727     }
2728     return distributedDataStorage_->QueryStroageDistributeInfo(
2729         bundleName, userId, networkId, distributedBundleInfo);
2730 }
2731 
GetInnerBundleUserInfos(const std::string & bundleName,std::vector<InnerBundleUserInfo> & innerBundleUserInfos) const2732 bool BundleDataMgr::GetInnerBundleUserInfos(
2733     const std::string &bundleName, std::vector<InnerBundleUserInfo> &innerBundleUserInfos) const
2734 {
2735     APP_LOGD("get all user info in bundle(%{public}s)", bundleName.c_str());
2736     if (bundleName.empty()) {
2737         APP_LOGW("bundle name is empty");
2738         return false;
2739     }
2740 
2741     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2742     if (bundleInfos_.empty()) {
2743         APP_LOGE("bundleInfos data is empty");
2744         return false;
2745     }
2746 
2747     auto infoItem = bundleInfos_.find(bundleName);
2748     if (infoItem == bundleInfos_.end()) {
2749         return false;
2750     }
2751 
2752     auto innerBundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID);
2753     if (innerBundleInfo == infoItem->second.end()) {
2754         return false;
2755     }
2756 
2757     if (innerBundleInfo->second.IsDisabled()) {
2758         APP_LOGE("app %{public}s is disabled", innerBundleInfo->second.GetBundleName().c_str());
2759         return false;
2760     }
2761 
2762     for (auto userInfo : innerBundleInfo->second.GetInnerBundleUserInfos()) {
2763         innerBundleUserInfos.emplace_back(userInfo.second);
2764     }
2765 
2766     return !innerBundleUserInfos.empty();
2767 }
2768 
GetAppPrivilegeLevel(const std::string & bundleName,int32_t userId)2769 std::string BundleDataMgr::GetAppPrivilegeLevel(const std::string &bundleName, int32_t userId)
2770 {
2771     APP_LOGD("GetAppPrivilegeLevel:%{public}s, userId:%{public}d", bundleName.c_str(), userId);
2772     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2773     InnerBundleInfo info;
2774     if (!GetInnerBundleInfoWithFlags(bundleName, 0, Constants::CURRENT_DEVICE_ID, info, userId)) {
2775         return Constants::EMPTY_STRING;
2776     }
2777 
2778     return info.GetAppPrivilegeLevel();
2779 }
2780 
QueryExtensionAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos) const2781 bool BundleDataMgr::QueryExtensionAbilityInfos(const Want &want, int32_t flags, int32_t userId,
2782     std::vector<ExtensionAbilityInfo> &extensionInfos) const
2783 {
2784     int32_t requestUserId = GetUserId(userId);
2785     if (requestUserId == Constants::INVALID_USERID) {
2786         return false;
2787     }
2788 
2789     ElementName element = want.GetElement();
2790     std::string bundleName = element.GetBundleName();
2791     std::string extensionName = element.GetAbilityName();
2792     APP_LOGD("bundle name:%{public}s, extension name:%{public}s", bundleName.c_str(), extensionName.c_str());
2793     // explicit query
2794     if (!bundleName.empty() && !extensionName.empty()) {
2795         ExtensionAbilityInfo info;
2796         bool ret = ExplicitQueryExtensionInfo(bundleName, extensionName, flags, requestUserId, info);
2797         if (ret == false) {
2798             APP_LOGE("explicit queryExtensionInfo error");
2799             return false;
2800         }
2801         extensionInfos.emplace_back(info);
2802         return true;
2803     }
2804 
2805     bool ret = ImplicitQueryExtensionInfos(want, flags, requestUserId, extensionInfos);
2806     if (ret == false) {
2807         APP_LOGE("implicit queryExtensionAbilityInfos error");
2808         return false;
2809     }
2810     if (extensionInfos.size() == 0) {
2811         APP_LOGE("no matching abilityInfo");
2812         return false;
2813     }
2814     APP_LOGD("query extensionAbilityInfo successfully");
2815     return true;
2816 }
2817 
ExplicitQueryExtensionInfo(const std::string & bundleName,const std::string & extensionName,int32_t flags,int32_t userId,ExtensionAbilityInfo & extensionInfo) const2818 bool BundleDataMgr::ExplicitQueryExtensionInfo(const std::string &bundleName, const std::string &extensionName,
2819     int32_t flags, int32_t userId, ExtensionAbilityInfo &extensionInfo) const
2820 {
2821     APP_LOGD("bundleName:%{public}s, abilityName:%{public}s", bundleName.c_str(), extensionName.c_str());
2822     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
2823     int32_t requestUserId = GetUserId(userId);
2824     if (requestUserId == Constants::INVALID_USERID) {
2825         return false;
2826     }
2827     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2828     InnerBundleInfo innerBundleInfo;
2829     if (!GetInnerBundleInfoWithFlags(
2830         bundleName, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
2831         APP_LOGE("ExplicitQueryExtensionInfo failed");
2832         return false;
2833     }
2834     auto extension = innerBundleInfo.FindExtensionInfo(bundleName, extensionName);
2835     if (!extension) {
2836         APP_LOGE("extensionAbility not found or disabled");
2837         return false;
2838     }
2839     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_PERMISSION) != GET_ABILITY_INFO_WITH_PERMISSION) {
2840         extension->permissions.clear();
2841     }
2842     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_METADATA) != GET_ABILITY_INFO_WITH_METADATA) {
2843         extension->metadata.clear();
2844     }
2845     extensionInfo = (*extension);
2846     if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_APPLICATION) == GET_ABILITY_INFO_WITH_APPLICATION) {
2847         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2848         innerBundleInfo.GetApplicationInfo(
2849             ApplicationFlag::GET_BASIC_APPLICATION_INFO, responseUserId, extensionInfo.applicationInfo);
2850     }
2851     return true;
2852 }
2853 
ImplicitQueryExtensionInfos(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos) const2854 bool BundleDataMgr::ImplicitQueryExtensionInfos(
2855     const Want &want, int32_t flags, int32_t userId, std::vector<ExtensionAbilityInfo> &extensionInfos) const
2856 {
2857     if (want.GetAction().empty() && want.GetEntities().empty()
2858         && want.GetUriString().empty() && want.GetType().empty()) {
2859         APP_LOGE("param invalid");
2860         return false;
2861     }
2862     APP_LOGD("action:%{public}s, uri:%{private}s, type:%{public}s",
2863         want.GetAction().c_str(), want.GetUriString().c_str(), want.GetType().c_str());
2864     APP_LOGD("flags:%{public}d, userId:%{public}d", flags, userId);
2865 
2866     int32_t requestUserId = GetUserId(userId);
2867     if (requestUserId == Constants::INVALID_USERID) {
2868         return false;
2869     }
2870     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2871     std::string bundleName = want.GetElement().GetBundleName();
2872     if (!bundleName.empty()) {
2873         // query in current bundle
2874         InnerBundleInfo innerBundleInfo;
2875         if (!GetInnerBundleInfoWithFlags(
2876             bundleName, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
2877             APP_LOGE("ImplicitQueryExtensionAbilityInfos failed");
2878             return false;
2879         }
2880         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2881         GetMatchExtensionInfos(want, flags, responseUserId, innerBundleInfo, extensionInfos);
2882     } else {
2883         // query all
2884         for (const auto &item : bundleInfos_) {
2885             InnerBundleInfo innerBundleInfo;
2886             if (!GetInnerBundleInfoWithFlags(
2887                 item.first, flags, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
2888                 APP_LOGE("ImplicitQueryExtensionAbilityInfos failed");
2889                 continue;
2890             }
2891             int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2892             GetMatchExtensionInfos(want, flags, responseUserId, innerBundleInfo, extensionInfos);
2893         }
2894     }
2895     // sort by priority, descending order.
2896     if (extensionInfos.size() > 1) {
2897         std::stable_sort(extensionInfos.begin(), extensionInfos.end(),
2898             [](ExtensionAbilityInfo a, ExtensionAbilityInfo b) { return a.priority > b.priority; });
2899     }
2900     return true;
2901 }
2902 
GetMatchExtensionInfos(const Want & want,int32_t flags,const int32_t & userId,const InnerBundleInfo & info,std::vector<ExtensionAbilityInfo> & infos) const2903 void BundleDataMgr::GetMatchExtensionInfos(const Want &want, int32_t flags, const int32_t &userId,
2904     const InnerBundleInfo &info, std::vector<ExtensionAbilityInfo> &infos) const
2905 {
2906     auto extensionSkillInfos = info.GetExtensionSkillInfos();
2907     auto extensionInfos = info.GetInnerExtensionInfos();
2908     for (const auto &skillInfos : extensionSkillInfos) {
2909         for (const auto &skill : skillInfos.second) {
2910             if (!skill.Match(want)) {
2911                 continue;
2912             }
2913             if (extensionInfos.find(skillInfos.first) == extensionInfos.end()) {
2914                 APP_LOGW("cannot find the extension info with %{public}s", skillInfos.first.c_str());
2915                 break;
2916             }
2917             ExtensionAbilityInfo extensionInfo = extensionInfos[skillInfos.first];
2918             if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_APPLICATION) ==
2919                 GET_ABILITY_INFO_WITH_APPLICATION) {
2920                 info.GetApplicationInfo(
2921                     ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, extensionInfo.applicationInfo);
2922             }
2923             if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_PERMISSION) !=
2924                 GET_ABILITY_INFO_WITH_PERMISSION) {
2925                 extensionInfo.permissions.clear();
2926             }
2927             if ((static_cast<uint32_t>(flags) & GET_ABILITY_INFO_WITH_METADATA) != GET_ABILITY_INFO_WITH_METADATA) {
2928                 extensionInfo.metadata.clear();
2929             }
2930             infos.emplace_back(extensionInfo);
2931             break;
2932         }
2933     }
2934 }
2935 
QueryExtensionAbilityInfos(const ExtensionAbilityType & extensionType,const int32_t & userId,std::vector<ExtensionAbilityInfo> & extensionInfos) const2936 bool BundleDataMgr::QueryExtensionAbilityInfos(const ExtensionAbilityType &extensionType, const int32_t &userId,
2937     std::vector<ExtensionAbilityInfo> &extensionInfos) const
2938 {
2939     int32_t requestUserId = GetUserId(userId);
2940     if (requestUserId == Constants::INVALID_USERID) {
2941         return false;
2942     }
2943     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2944     for (const auto &item : bundleInfos_) {
2945         InnerBundleInfo innerBundleInfo;
2946         if (!GetInnerBundleInfoWithFlags(
2947             item.first, 0, Constants::CURRENT_DEVICE_ID, innerBundleInfo, requestUserId)) {
2948             APP_LOGE("QueryExtensionAbilityInfos failed");
2949             continue;
2950         }
2951         auto innerExtensionInfos = innerBundleInfo.GetInnerExtensionInfos();
2952         int32_t responseUserId = innerBundleInfo.GetResponseUserId(requestUserId);
2953         for (const auto &info : innerExtensionInfos) {
2954             if (info.second.type == extensionType) {
2955                 ExtensionAbilityInfo extensionAbilityInfo = info.second;
2956                 innerBundleInfo.GetApplicationInfo(
2957                     ApplicationFlag::GET_BASIC_APPLICATION_INFO, responseUserId, extensionAbilityInfo.applicationInfo);
2958                 extensionInfos.emplace_back(extensionAbilityInfo);
2959             }
2960         }
2961     }
2962     return true;
2963 }
2964 
GetAccessibleAppCodePaths(int32_t userId) const2965 std::vector<std::string> BundleDataMgr::GetAccessibleAppCodePaths(int32_t userId) const
2966 {
2967     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
2968     std::vector<std::string> vec;
2969     if (bundleInfos_.empty()) {
2970         APP_LOGE("bundleInfos_ is empty");
2971         return vec;
2972     }
2973 
2974     for (const auto &info : bundleInfos_) {
2975         auto item = info.second.find(Constants::CURRENT_DEVICE_ID);
2976         if (item == info.second.end()) {
2977             continue;
2978         }
2979 
2980         InnerBundleInfo innerBundleInfo = item->second;
2981         auto userInfoMap = innerBundleInfo.GetInnerBundleUserInfos();
2982         for (const auto &userInfo : userInfoMap) {
2983             auto innerUserId = userInfo.second.bundleUserInfo.userId;
2984             if (((innerUserId == 0) || (innerUserId == userId)) && innerBundleInfo.IsAccessible()) {
2985                 vec.emplace_back(innerBundleInfo.GetAppCodePath());
2986             }
2987         }
2988     }
2989     return vec;
2990 }
2991 
QueryExtensionAbilityInfoByUri(const std::string & uri,int32_t userId,ExtensionAbilityInfo & extensionAbilityInfo) const2992 bool BundleDataMgr::QueryExtensionAbilityInfoByUri(const std::string &uri, int32_t userId,
2993     ExtensionAbilityInfo &extensionAbilityInfo) const
2994 {
2995     int32_t requestUserId = GetUserId(userId);
2996     if (requestUserId == Constants::INVALID_USERID) {
2997         APP_LOGE("invalid userId -1");
2998         return false;
2999     }
3000     if (uri.empty()) {
3001         APP_LOGE("uri empty");
3002         return false;
3003     }
3004     // example of valid param uri : fileShare:///com.example.FileShare/person/10
3005     // example of convertUri : fileShare://com.example.FileShare
3006     size_t schemePos = uri.find(Constants::PARAM_URI_SEPARATOR);
3007     if (schemePos == uri.npos) {
3008         APP_LOGE("uri not include :///, invalid");
3009         return false;
3010     }
3011     size_t cutPos = uri.find(Constants::SEPARATOR, schemePos + Constants::PARAM_URI_SEPARATOR_LEN);
3012     if (cutPos == uri.npos) {
3013         APP_LOGE("uri not include /, invalid");
3014         return false;
3015     }
3016     // 1. cut string
3017     std::string convertUri = uri.substr(0, cutPos);
3018     // 2. replace :/// with ://
3019     convertUri.replace(schemePos, Constants::PARAM_URI_SEPARATOR_LEN,
3020         Constants::URI_SEPARATOR);
3021     APP_LOGD("convertUri : %{private}s", convertUri.c_str());
3022 
3023     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3024     if (bundleInfos_.empty()) {
3025         APP_LOGE("bundleInfos_ data is empty");
3026         return false;
3027     }
3028     std::string deviceId = Constants::CURRENT_DEVICE_ID;
3029     for (const auto &item : bundleInfos_) {
3030         auto infoWithIdItem = item.second.find(deviceId);
3031         if (infoWithIdItem == item.second.end()) {
3032             continue;
3033         }
3034 
3035         if (infoWithIdItem->second.IsDisabled()) {
3036             APP_LOGE("app %{public}s is disabled", infoWithIdItem->second.GetBundleName().c_str());
3037             continue;
3038         }
3039 
3040         int32_t responseUserId = infoWithIdItem->second.GetResponseUserId(requestUserId);
3041         if (!infoWithIdItem->second.GetApplicationEnabled(responseUserId)) {
3042             continue;
3043         }
3044 
3045         bool ret = infoWithIdItem->second.FindExtensionAbilityInfoByUri(convertUri, extensionAbilityInfo);
3046         if (!ret) {
3047             continue;
3048         }
3049         infoWithIdItem->second.GetApplicationInfo(
3050             ApplicationFlag::GET_BASIC_APPLICATION_INFO, responseUserId, extensionAbilityInfo.applicationInfo);
3051         return true;
3052     }
3053     APP_LOGE("QueryExtensionAbilityInfoByUri (%{private}s) failed.", uri.c_str());
3054     return false;
3055 }
3056 
GetAllUriPrefix(std::vector<std::string> & uriPrefixList,int32_t userId,const std::string & excludeModule) const3057 void BundleDataMgr::GetAllUriPrefix(std::vector<std::string> &uriPrefixList, int32_t userId,
3058     const std::string &excludeModule) const
3059 {
3060     std::lock_guard<std::mutex> lock(bundleInfoMutex_);
3061     APP_LOGD("begin to GetAllUriPrefix, userId : %{public}d, excludeModule : %{public}s",
3062         userId, excludeModule.c_str());
3063     if (bundleInfos_.empty()) {
3064         APP_LOGE("bundleInfos_ is empty");
3065         return;
3066     }
3067     for (const auto &item : bundleInfos_) {
3068         auto infoWithIdItem = item.second.find(Constants::CURRENT_DEVICE_ID);
3069         if (infoWithIdItem == item.second.end()) {
3070             continue;
3071         }
3072         infoWithIdItem->second.GetUriPrefixList(uriPrefixList, userId, excludeModule);
3073         infoWithIdItem->second.GetUriPrefixList(uriPrefixList, Constants::DEFAULT_USERID, excludeModule);
3074     }
3075 }
3076 
GetResourceManager(const AppExecFwk::BundleInfo & bundleInfo) const3077 std::shared_ptr<Global::Resource::ResourceManager> BundleDataMgr::GetResourceManager(
3078     const AppExecFwk::BundleInfo &bundleInfo) const
3079 {
3080     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
3081     for (auto moduleResPath : bundleInfo.moduleResPaths) {
3082         if (!moduleResPath.empty()) {
3083             APP_LOGE("DistributedBms::InitResourceManager, moduleResPath: %{public}s", moduleResPath.c_str());
3084             if (!resourceManager->AddResource(moduleResPath.c_str())) {
3085                 APP_LOGE("DistributedBms::InitResourceManager AddResource failed");
3086             }
3087         }
3088     }
3089 
3090     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
3091     resConfig->SetLocaleInfo("zh", "Hans", "CN");
3092     resourceManager->UpdateResConfig(*resConfig);
3093     return resourceManager;
3094 }
3095 
ImplicitQueryInfoByPriority(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,ExtensionAbilityInfo & extensionInfo)3096 bool BundleDataMgr::ImplicitQueryInfoByPriority(const Want &want, int32_t flags, int32_t userId,
3097     AbilityInfo &abilityInfo, ExtensionAbilityInfo &extensionInfo)
3098 {
3099     int32_t requestUserId = GetUserId(userId);
3100     if (requestUserId == Constants::INVALID_USERID) {
3101         APP_LOGE("invalid userId");
3102         return false;
3103     }
3104     std::vector<AbilityInfo> abilityInfos;
3105     bool abilityValid =
3106         ImplicitQueryAbilityInfos(want, flags, requestUserId, abilityInfos) && (abilityInfos.size() > 0);
3107     std::vector<ExtensionAbilityInfo> extensionInfos;
3108     bool extensionValid =
3109         ImplicitQueryExtensionInfos(want, flags, requestUserId, extensionInfos) && (extensionInfos.size() > 0);
3110     if (!abilityValid && !extensionValid) {
3111         // both invalid
3112         APP_LOGE("can't find target AbilityInfo or ExtensionAbilityInfo");
3113         return false;
3114     }
3115     if (abilityValid && extensionValid) {
3116         // both valid
3117         if (abilityInfos[0].priority >= extensionInfos[0].priority) {
3118             APP_LOGD("find target AbilityInfo with higher priority, name : %{public}s", abilityInfos[0].name.c_str());
3119             abilityInfo = abilityInfos[0];
3120         } else {
3121             APP_LOGD("find target ExtensionAbilityInfo with higher priority, name : %{public}s",
3122                 extensionInfos[0].name.c_str());
3123             extensionInfo = extensionInfos[0];
3124         }
3125     } else if (abilityValid) {
3126         // only ability valid
3127         APP_LOGD("find target AbilityInfo, name : %{public}s", abilityInfos[0].name.c_str());
3128         abilityInfo = abilityInfos[0];
3129     } else {
3130         // only extension valid
3131         APP_LOGD("find target ExtensionAbilityInfo, name : %{public}s", extensionInfos[0].name.c_str());
3132         extensionInfo = extensionInfos[0];
3133     }
3134     return true;
3135 }
3136 
3137 #ifdef SUPPORT_GRAPHICS
LoadImageFile(const std::string & path) const3138 std::shared_ptr<Media::PixelMap> BundleDataMgr::LoadImageFile(const std::string &path) const
3139 {
3140     APP_LOGD("BundleDataMgr::LoadImageFile IN");
3141     uint32_t errorCode = 0;
3142     Media::SourceOptions opts;
3143     std::unique_ptr<Media::ImageSource> imageSource = Media::ImageSource::CreateImageSource(path,
3144                                                                                             opts,
3145                                                                                             errorCode);
3146     if (errorCode != 0) {
3147         APP_LOGE("Failed to create image source path %{public}s err %{public}d",
3148             path.c_str(), errorCode);
3149         return nullptr;
3150     }
3151 
3152     Media::DecodeOptions decodeOpts;
3153     auto pixelMapPtr = imageSource->CreatePixelMap(decodeOpts, errorCode);
3154     if (errorCode != 0) {
3155         APP_LOGE("Failed to create pixelmap path %{public}s err %{public}d",
3156             path.c_str(), errorCode);
3157         return nullptr;
3158     }
3159     APP_LOGD("BundleDataMgr::LoadImageFile OUT");
3160     return std::shared_ptr<Media::PixelMap>(std::move(pixelMapPtr));
3161 }
3162 #endif
3163 }  // namespace AppExecFwk
3164 }  // namespace OHOS
3165