• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 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_mgr_host_impl.h"
17 
18 #include "account_helper.h"
19 #include "app_log_tag_wrapper.h"
20 #include "app_mgr_interface.h"
21 #include "aot/aot_handler.h"
22 #include "bms_extension_client.h"
23 #include "bms_extension_data_mgr.h"
24 #include "bundle_hitrace_chain.h"
25 #include "bundle_parser.h"
26 #include "bundle_permission_mgr.h"
27 #ifdef BUNDLE_FRAMEWORK_BUNDLE_RESOURCE
28 #include "bundle_resource_manager.h"
29 #endif
30 #include "bundle_service_constants.h"
31 #include "bundle_resource_helper.h"
32 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
33 #include "distributed_bms_proxy.h"
34 #endif
35 #include "hitrace_meter.h"
36 #include "installd_client.h"
37 #include "ipc_skeleton.h"
38 #include "iservice_registry.h"
39 #include "on_demand_install_data_mgr.h"
40 #include "system_ability_helper.h"
41 #include "inner_bundle_clone_common.h"
42 #ifdef DEVICE_USAGE_STATISTICS_ENABLED
43 #include "bundle_active_client.h"
44 #include "bundle_active_period_stats.h"
45 #endif
46 #include "directory_ex.h"
47 #ifdef BMS_USER_AUTH_FRAMEWORK_ENABLED
48 #include "migrate_data_user_auth_callback.h"
49 #endif
50 #include "parameters.h"
51 #include "system_ability_definition.h"
52 #include "scope_guard.h"
53 #ifdef BMS_USER_AUTH_FRAMEWORK_ENABLED
54 #include "user_auth_client_impl.h"
55 #endif
56 #include "xcollie_helper.h"
57 
58 namespace OHOS {
59 namespace AppExecFwk {
60 namespace {
61 constexpr const char* SYSTEM_APP = "system";
62 constexpr const char* THIRD_PARTY_APP = "third-party";
63 constexpr const char* APP_LINKING = "applinking";
64 constexpr const char* EMPTY_ABILITY_NAME = "";
65 const std::string FUNCTION_GET_NAME_FOR_UID = "BundleMgrHostImpl::GetNameForUid";
66 const std::string FUNCTION_GET_OVERLAY_MANAGER_PROXY = "BundleMgrHostImpl::GetOverlayManagerProxy";
67 const std::string FUNCTION_GET_BUNDLE_RESOURCE_PROXY = "BundleMgrHostImpl::GetBundleResourceProxy";
68 const std::string FUNCTION_VERIFY_SYSTEM_API = "BundleMgrHostImpl::VerifySystemApi";
69 const std::string FUNCTION_VERIFY_CALLING_PERMISSION = "BundleMgrHostImpl::VerifyCallingPermission";
70 const std::string FUNCTION_GET_CLONE_BUNDLE_INFO = "BundleMgrHostImpl::GetCloneBundleInfo";
71 const std::string FUNCTION_GET_CLONE_BUNDLE_INFO_Ext = "BundleMgrHostImpl::GetCloneBundleInfoExt";
72 const std::string FUNCTION_GET_SHARED_BUNDLE_INFO_BY_SELF = "BundleMgrHostImpl::GetSharedBundleInfoBySelf";
73 const std::string FUNCTION_GET_HAP_MODULE_INFO = "BundleMgrHostImpl::GetHapModuleInfo";
74 const std::string FUNCTION_BATCH_BUNDLE_INFO = "BundleMgrHostImpl::BatchGetBundleInfo";
75 const std::string FUNCTION_GET_BUNDLE_INFO = "BundleMgrHostImpl::GetBundleInfo";
76 const std::string FUNCTION_GET_BUNDLE_INFO_V9 = "BundleMgrHostImpl::GetBundleInfoV9";
77 const std::string FUNCTION_GET_BUNDLE_INFO_FOR_SELF = "BundleMgrHostImpl::GetBundleInfoForSelf";
78 const std::string FUNCTION_GREAT_OR_EQUAL_API_TARGET_VERSION = "BundleMgrHostImpl::GreatOrEqualTargetAPIVersion";
79 const std::string CLONE_APP_DIR_PREFIX = "+clone-";
80 const std::u16string ATOMIC_SERVICE_STATUS_CALLBACK_TOKEN = u"ohos.IAtomicServiceStatusCallback";
81 const std::string PLUS = "+";
82 const std::string AUTH_TITLE = "      ";
83 const std::string BUNDLE_NAME = "bundleName";
84 const std::string LABEL = "label";
85 const std::string NEW_LINE = "\n";
86 const std::string RESOURCE_NOT_SUPPORT =
87     "warning: dump label failed due to the device not supporting bundle resource!";
88 const uint8_t JSON_INDENTATION = 4;
89 const uint64_t BAD_CONTEXT_ID = 0;
90 const uint64_t VECTOR_SIZE_MAX = 200;
91 const size_t MAX_QUERY_EVENT_REPORT_ONCE = 100;
92 const int64_t ONE_DAY =  86400;
93 const std::unordered_map<std::string, int32_t> QUERY_FUNC_MAP = {
94     {"GetNameForUid", 1},
95     {"GetBundleNameForUid", 2},
96     {"GetBundleInfoV9", 3},
97     {"GetBundleInfo", 4},
98     {"GetAppProvisionInfo", 5}
99 };
100 const std::vector<int32_t> QUERY_EXPECTED_ERR = {
101     ERR_OK,
102     ERR_BUNDLE_MANAGER_PERMISSION_DENIED,
103     ERR_BUNDLE_MANAGER_INVALID_USER_ID,
104     ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST,
105     ERR_BUNDLE_MANAGER_BUNDLE_DISABLED,
106     ERR_BUNDLE_MANAGER_APPLICATION_DISABLED,
107     ERR_BUNDLE_MANAGER_INVALID_UID,
108     ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED,
109 };
110 }
111 
112 std::shared_mutex g_queryEventMutex;
113 std::unordered_map<int32_t, std::vector<QueryEventInfo>> g_queryEventList;
114 
InsertQueryEventInfo(int32_t errCode,const QueryEventInfo & info)115 bool InsertQueryEventInfo(int32_t errCode, const QueryEventInfo& info)
116 {
117     std::vector<QueryEventInfo> infos;
118     std::unique_lock<std::shared_mutex> lock(g_queryEventMutex);
119     if (g_queryEventList.find(errCode) == g_queryEventList.end()) {
120         g_queryEventList[errCode].push_back(info);
121         g_queryEventList[errCode][0].lastReportEventTime = BundleUtil::GetCurrentTime();
122         APP_LOGD("init record for -e: %{public}d", errCode);
123         return true;
124     }
125     if (std::find(g_queryEventList[errCode].begin(), g_queryEventList[errCode].end(), info) ==
126         g_queryEventList[errCode].end()) {
127         g_queryEventList[errCode].push_back(info);
128         APP_LOGD("add new record for -e:%{public}d",
129             errCode);
130         return true;
131     }
132     return false;
133 }
134 
TransQueryEventInfo(const std::vector<QueryEventInfo> & infos,EventInfo & report)135 bool TransQueryEventInfo(const std::vector<QueryEventInfo> &infos, EventInfo &report)
136 {
137     if (infos.empty()) {
138         APP_LOGW("no query info to transform");
139         return false;
140     }
141     report.errCode = infos[0].errCode;
142     for (auto queryInfo: infos) {
143         report.funcIdList.push_back(queryInfo.funcId);
144         report.userIdList.push_back(queryInfo.userId);
145         report.uidList.push_back(queryInfo.uid);
146         report.appIndexList.push_back(queryInfo.appIndex);
147         report.flagList.push_back(queryInfo.flag);
148         report.bundleNameList.push_back(queryInfo.bundleName);
149         report.callingUidList.push_back(queryInfo.callingUid);
150         report.callingBundleNameList.push_back(queryInfo.callingBundleName);
151         report.callingAppIdList.push_back(queryInfo.callingAppId);
152     }
153     return true;
154 }
155 
ClearGlobalQueryEventInfo()156 void ClearGlobalQueryEventInfo()
157 {
158     std::unique_lock<std::shared_mutex> queryEventMutex(g_queryEventMutex);
159     g_queryEventList.clear();
160 }
161 
EraseQueryEventInfo(ErrCode error)162 void EraseQueryEventInfo(ErrCode error)
163 {
164     std::unique_lock<std::shared_mutex> queryEventMutex(g_queryEventMutex);
165     g_queryEventList.erase(error);
166 }
167 
GetQueryEventInfo(ErrCode error)168 std::vector<QueryEventInfo> GetQueryEventInfo(ErrCode error)
169 {
170     std::vector<QueryEventInfo> infos;
171     std::unique_lock<std::shared_mutex> queryEventMutex(g_queryEventMutex);
172     if (g_queryEventList.find(error) != g_queryEventList.end()) {
173         return g_queryEventList[error];
174     }
175     return infos;
176 }
177 
PrepareQueryEvent(ErrCode errCode,const std::string & bundleName,const std::string & func,int32_t uid,int32_t userId,int32_t appIndex,int32_t flags)178 QueryEventInfo PrepareQueryEvent(ErrCode errCode, const std::string &bundleName, const std::string &func,
179     int32_t uid, int32_t userId, int32_t appIndex, int32_t flags)
180 {
181     QueryEventInfo info;
182     info.errCode = errCode;
183     info.funcId = QUERY_FUNC_MAP.at(func);
184     info.uid = uid;
185     info.userId = userId;
186     info.appIndex = appIndex;
187     info.flag = flags;
188     info.bundleName = bundleName;
189     return info;
190 }
191 
GetApplicationInfo(const std::string & appName,const ApplicationFlag flag,const int userId,ApplicationInfo & appInfo)192 bool BundleMgrHostImpl::GetApplicationInfo(
193     const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo)
194 {
195     return GetApplicationInfo(appName, static_cast<int32_t>(flag), userId, appInfo);
196 }
197 
GetApplicationInfo(const std::string & appName,int32_t flags,int32_t userId,ApplicationInfo & appInfo)198 bool BundleMgrHostImpl::GetApplicationInfo(
199     const std::string &appName, int32_t flags, int32_t userId, ApplicationInfo &appInfo)
200 {
201     LOG_D(BMS_TAG_QUERY, "GetApplicationInfo bundleName:%{public}s flags:%{public}d userId:%{public}d",
202         appName.c_str(), flags, userId);
203     if (!BundlePermissionMgr::IsSystemApp() &&
204         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
205         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
206         return true;
207     }
208     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
209         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
210         !BundlePermissionMgr::IsBundleSelfCalling(appName)) {
211         LOG_E(BMS_TAG_QUERY, "verify permission failed");
212         return false;
213     }
214     auto dataMgr = GetDataMgrFromService();
215     if (dataMgr == nullptr) {
216         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
217         return false;
218     }
219     return dataMgr->GetApplicationInfo(appName, flags, userId, appInfo);
220 }
221 
GetApplicationInfoV9(const std::string & appName,int32_t flags,int32_t userId,ApplicationInfo & appInfo)222 ErrCode BundleMgrHostImpl::GetApplicationInfoV9(
223     const std::string &appName, int32_t flags, int32_t userId, ApplicationInfo &appInfo)
224 {
225     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
226     LOG_D(BMS_TAG_QUERY, "GetApplicationInfoV9 bundleName:%{public}s flags:%{public}d userId:%{public}d",
227         appName.c_str(), flags, userId);
228     if (!BundlePermissionMgr::IsSystemApp()) {
229         LOG_E(BMS_TAG_QUERY, "non-system app calling system api");
230         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
231     }
232     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
233         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
234         !BundlePermissionMgr::IsBundleSelfCalling(appName)) {
235         LOG_E(BMS_TAG_QUERY, "permission denied");
236         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
237     }
238     auto dataMgr = GetDataMgrFromService();
239     if (dataMgr == nullptr) {
240         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
241         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
242     }
243     return dataMgr->GetApplicationInfoV9(appName, flags, userId, appInfo);
244 }
245 
GetApplicationInfos(const ApplicationFlag flag,const int userId,std::vector<ApplicationInfo> & appInfos)246 bool BundleMgrHostImpl::GetApplicationInfos(
247     const ApplicationFlag flag, const int userId, std::vector<ApplicationInfo> &appInfos)
248 {
249     return GetApplicationInfos(static_cast<int32_t>(flag), userId, appInfos);
250 }
251 
GetApplicationInfos(int32_t flags,int32_t userId,std::vector<ApplicationInfo> & appInfos)252 bool BundleMgrHostImpl::GetApplicationInfos(
253     int32_t flags, int32_t userId, std::vector<ApplicationInfo> &appInfos)
254 {
255     if (!BundlePermissionMgr::IsSystemApp() &&
256         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
257         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
258         return true;
259     }
260     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
261         LOG_E(BMS_TAG_QUERY, "verify permission failed");
262         return false;
263     }
264     if (!BundlePermissionMgr::IsNativeTokenType() &&
265         (BundlePermissionMgr::GetHapApiVersion() >= ServiceConstants::API_VERSION_NINE)) {
266         LOG_D(BMS_TAG_QUERY,
267             "GetApplicationInfos return empty, not support target level greater than or equal to api9");
268         return true;
269     }
270     APP_LOGI_NOFUNC("GetApplicationInfos -p:%{public}d, -f:%{public}d, -u:%{public}d",
271         IPCSkeleton::GetCallingPid(), flags, userId);
272     auto dataMgr = GetDataMgrFromService();
273     if (dataMgr == nullptr) {
274         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
275         return false;
276     }
277     return dataMgr->GetApplicationInfos(flags, userId, appInfos);
278 }
279 
GetApplicationInfosV9(int32_t flags,int32_t userId,std::vector<ApplicationInfo> & appInfos)280 ErrCode BundleMgrHostImpl::GetApplicationInfosV9(
281     int32_t flags, int32_t userId, std::vector<ApplicationInfo> &appInfos)
282 {
283     if (!BundlePermissionMgr::IsSystemApp()) {
284         LOG_E(BMS_TAG_QUERY, "non-system app calling system api");
285         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
286     }
287     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST)) {
288         LOG_E(BMS_TAG_QUERY, "verify permission failed");
289         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
290     }
291     APP_LOGI_NOFUNC("GetApplicationInfosV9 -p:%{public}d, -f:%{public}d, -u:%{public}d",
292         IPCSkeleton::GetCallingPid(), flags, userId);
293     auto dataMgr = GetDataMgrFromService();
294     if (dataMgr == nullptr) {
295         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
296         BundlePermissionMgr::AddPermissionUsedRecord(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST, 0, 1);
297         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
298     }
299     auto ret = dataMgr->GetApplicationInfosV9(flags, userId, appInfos);
300     if (ret == ERR_OK) {
301         BundlePermissionMgr::AddPermissionUsedRecord(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST, 1, 0);
302     } else {
303         BundlePermissionMgr::AddPermissionUsedRecord(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST, 0, 1);
304     }
305     return ret;
306 }
307 
GetBundleInfo(const std::string & bundleName,const BundleFlag flag,BundleInfo & bundleInfo,int32_t userId)308 bool BundleMgrHostImpl::GetBundleInfo(
309     const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId)
310 {
311     return GetBundleInfo(bundleName, static_cast<int32_t>(flag), bundleInfo, userId);
312 }
313 
GetBundleInfo(const std::string & bundleName,int32_t flags,BundleInfo & bundleInfo,int32_t userId)314 bool BundleMgrHostImpl::GetBundleInfo(
315     const std::string &bundleName, int32_t flags, BundleInfo &bundleInfo, int32_t userId)
316 {
317     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
318     LOG_D(BMS_TAG_QUERY,
319         "start GetBundleInfo, bundleName : %{public}s, flags : %{public}d, userId : %{public}d",
320         bundleName.c_str(), flags, userId);
321     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_BUNDLE_INFO);
322     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
323     // API9 need to be system app
324     int64_t intervalTime = ONE_DAY;
325     if (!BundlePermissionMgr::IsSystemApp() &&
326         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
327         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
328         return true;
329     }
330     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
331         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
332         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
333         LOG_E(BMS_TAG_QUERY, "verify permission failed");
334         return false;
335     }
336     LOG_D(BMS_TAG_QUERY, "verify permission success, begin to GetBundleInfo");
337     auto dataMgr = GetDataMgrFromService();
338     if (dataMgr == nullptr) {
339         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
340         QueryEventInfo info = PrepareQueryEvent(ERR_BUNDLE_MANAGER_INTERNAL_ERROR, bundleName,
341             "GetBundleInfo", -1, userId, 0, flags);
342         SendQueryBundleInfoEvent(info, intervalTime, true);
343         return false;
344     }
345     bool res = dataMgr->GetBundleInfo(bundleName, flags, bundleInfo, userId);
346     if (!res) {
347         if (isBrokerServiceExisted_) {
348             auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
349             return bmsExtensionClient->GetBundleInfo(bundleName, flags, bundleInfo, userId) == ERR_OK;
350         }
351     }
352     return res;
353 }
354 
GetBaseSharedBundleInfos(const std::string & bundleName,std::vector<BaseSharedBundleInfo> & baseSharedBundleInfos,GetDependentBundleInfoFlag flag)355 ErrCode BundleMgrHostImpl::GetBaseSharedBundleInfos(const std::string &bundleName,
356     std::vector<BaseSharedBundleInfo> &baseSharedBundleInfos, GetDependentBundleInfoFlag flag)
357 {
358     APP_LOGD("start GetBaseSharedBundleInfos, bundleName : %{public}s", bundleName.c_str());
359     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
360         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
361         APP_LOGE("verify permission failed");
362         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
363     }
364     auto dataMgr = GetDataMgrFromService();
365     if (dataMgr == nullptr) {
366         APP_LOGE("DataMgr is nullptr");
367         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
368     }
369     return dataMgr->GetBaseSharedBundleInfos(bundleName, baseSharedBundleInfos, flag);
370 }
371 
GetBundleInfoV9(const std::string & bundleName,int32_t flags,BundleInfo & bundleInfo,int32_t userId)372 ErrCode BundleMgrHostImpl::GetBundleInfoV9(
373     const std::string &bundleName, int32_t flags, BundleInfo &bundleInfo, int32_t userId)
374 {
375     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
376     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_BUNDLE_INFO_V9);
377     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
378     LOG_D(BMS_TAG_QUERY, "GetBundleInfoV9, bundleName:%{public}s, flags:%{public}d, userId:%{public}d",
379         bundleName.c_str(), flags, userId);
380     bool permissionVerify = [bundleName]() {
381         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
382             return true;
383         }
384         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO) &&
385             BundlePermissionMgr::IsSystemApp()) {
386             return true;
387         }
388         if (BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
389             return true;
390         }
391         return false;
392     }();
393     if (!permissionVerify) {
394         APP_LOGE("verify permission failed");
395         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
396     }
397     LOG_D(BMS_TAG_QUERY, "verify permission success, begin to GetBundleInfoV9");
398     int64_t intervalTime = ONE_DAY;
399     auto dataMgr = GetDataMgrFromService();
400     if (dataMgr == nullptr) {
401         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
402         QueryEventInfo info = PrepareQueryEvent(ERR_BUNDLE_MANAGER_INTERNAL_ERROR, bundleName,
403             "GetBundleInfoV9", -1, userId, 0, flags);
404         SendQueryBundleInfoEvent(info, intervalTime, true);
405         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
406     }
407     auto res = dataMgr->GetBundleInfoV9(bundleName, flags, bundleInfo, userId);
408     if (res != ERR_OK) {
409         if (isBrokerServiceExisted_) {
410             auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
411             if (bmsExtensionClient->GetBundleInfo(bundleName, flags, bundleInfo, userId, true) == ERR_OK) {
412                 return ERR_OK;
413             }
414         }
415         QueryEventInfo info = PrepareQueryEvent(res, bundleName, "GetBundleInfoV9", -1, userId, 0, flags);
416         SendQueryBundleInfoEvent(info, intervalTime, false);
417     }
418     return res;
419 }
420 
BatchGetBundleInfo(const std::vector<std::string> & bundleNames,int32_t flags,std::vector<BundleInfo> & bundleInfos,int32_t userId)421 ErrCode BundleMgrHostImpl::BatchGetBundleInfo(const std::vector<std::string> &bundleNames, int32_t flags,
422     std::vector<BundleInfo> &bundleInfos, int32_t userId)
423 {
424     APP_LOGI("start BatchGetBundleInfo, bundleName : %{public}s, flags : %{public}d, userId : %{public}d",
425         BundleUtil::ToString(bundleNames).c_str(), flags, userId);
426     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_BATCH_BUNDLE_INFO);
427     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
428     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED})) {
429         APP_LOGE("verify permission failed");
430         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
431     }
432     APP_LOGD("verify permission success, begin to BatchGetBundleInfo");
433     auto dataMgr = GetDataMgrFromService();
434     if (dataMgr == nullptr) {
435         APP_LOGE("DataMgr is nullptr");
436         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
437     }
438     dataMgr->BatchGetBundleInfo(bundleNames, flags, bundleInfos, userId);
439     if (bundleInfos.size() == bundleNames.size()) {
440         return ERR_OK;
441     }
442     if (isBrokerServiceExisted_) {
443         auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
444         bmsExtensionClient->BatchGetBundleInfo(bundleNames, flags, bundleInfos, userId, true);
445     }
446     return bundleInfos.empty() ? ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST : ERR_OK;
447 }
448 
GetBundleInfoForSelf(int32_t flags,BundleInfo & bundleInfo)449 ErrCode BundleMgrHostImpl::GetBundleInfoForSelf(int32_t flags, BundleInfo &bundleInfo)
450 {
451     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
452     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_BUNDLE_INFO_FOR_SELF);
453     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
454     auto dataMgr = GetDataMgrFromService();
455     if (dataMgr == nullptr) {
456         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
457         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
458     }
459     return dataMgr->GetBundleInfoForSelf(flags, bundleInfo);
460 }
461 
GetDependentBundleInfo(const std::string & sharedBundleName,BundleInfo & sharedBundleInfo,GetDependentBundleInfoFlag flag)462 ErrCode BundleMgrHostImpl::GetDependentBundleInfo(const std::string &sharedBundleName,
463     BundleInfo &sharedBundleInfo, GetDependentBundleInfoFlag flag)
464 {
465     auto dataMgr = GetDataMgrFromService();
466     if (dataMgr == nullptr) {
467         APP_LOGE("DataMgr is nullptr");
468         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
469     }
470 
471     int32_t bundleInfoFlags = static_cast<uint32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) |
472         static_cast<uint32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION);
473     switch (flag) {
474         case GetDependentBundleInfoFlag::GET_APP_CROSS_HSP_BUNDLE_INFO: {
475             if (!VerifyDependency(sharedBundleName)) {
476                 APP_LOGE("failed");
477                 return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
478             }
479             return dataMgr->GetSharedBundleInfo(sharedBundleName, bundleInfoFlags, sharedBundleInfo);
480         }
481         case GetDependentBundleInfoFlag::GET_APP_SERVICE_HSP_BUNDLE_INFO: {
482             // no need to check permission for app service hsp
483             return dataMgr->GetAppServiceHspBundleInfo(sharedBundleName, sharedBundleInfo);
484         }
485         case GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO: {
486             if (dataMgr->GetAppServiceHspBundleInfo(sharedBundleName, sharedBundleInfo) == ERR_OK) {
487                 return ERR_OK;
488             }
489             if (!VerifyDependency(sharedBundleName)) {
490                 APP_LOGE("failed");
491                 return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
492             }
493             return dataMgr->GetSharedBundleInfo(sharedBundleName, bundleInfoFlags, sharedBundleInfo);
494         }
495         default:
496             return ERR_BUNDLE_MANAGER_PARAM_ERROR;
497     }
498 }
499 
GetBundlePackInfo(const std::string & bundleName,const BundlePackFlag flag,BundlePackInfo & bundlePackInfo,int32_t userId)500 ErrCode BundleMgrHostImpl::GetBundlePackInfo(
501     const std::string &bundleName, const BundlePackFlag flag, BundlePackInfo &bundlePackInfo, int32_t userId)
502 {
503     return GetBundlePackInfo(bundleName, static_cast<int32_t>(flag), bundlePackInfo, userId);
504 }
505 
GetBundlePackInfo(const std::string & bundleName,int32_t flags,BundlePackInfo & bundlePackInfo,int32_t userId)506 ErrCode BundleMgrHostImpl::GetBundlePackInfo(
507     const std::string &bundleName, int32_t flags, BundlePackInfo &bundlePackInfo, int32_t userId)
508 {
509     // check permission
510     if (!BundlePermissionMgr::IsSystemApp()) {
511         APP_LOGE("non-system app calling system api");
512         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
513     }
514     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
515         APP_LOGE("GetBundlePackInfo failed due to lack of permission");
516         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
517     }
518     auto dataMgr = GetDataMgrFromService();
519     if (dataMgr == nullptr) {
520         APP_LOGE("DataMgr is nullptr");
521         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
522     }
523     return dataMgr->GetBundlePackInfo(bundleName, flags, bundlePackInfo, userId);
524 }
525 
GetBundleUserInfo(const std::string & bundleName,int32_t userId,InnerBundleUserInfo & innerBundleUserInfo)526 bool BundleMgrHostImpl::GetBundleUserInfo(
527     const std::string &bundleName, int32_t userId, InnerBundleUserInfo &innerBundleUserInfo)
528 {
529     auto dataMgr = GetDataMgrFromService();
530     if (dataMgr == nullptr) {
531         APP_LOGE("DataMgr is nullptr");
532         return false;
533     }
534     return dataMgr->GetInnerBundleUserInfoByUserId(bundleName, userId, innerBundleUserInfo);
535 }
536 
GetBundleUserInfos(const std::string & bundleName,std::vector<InnerBundleUserInfo> & innerBundleUserInfos)537 bool BundleMgrHostImpl::GetBundleUserInfos(
538     const std::string &bundleName, std::vector<InnerBundleUserInfo> &innerBundleUserInfos)
539 {
540     auto dataMgr = GetDataMgrFromService();
541     if (dataMgr == nullptr) {
542         APP_LOGE("DataMgr is nullptr");
543         return false;
544     }
545     return dataMgr->GetInnerBundleUserInfos(bundleName, innerBundleUserInfos);
546 }
547 
GetBundleInfos(const BundleFlag flag,std::vector<BundleInfo> & bundleInfos,int32_t userId)548 bool BundleMgrHostImpl::GetBundleInfos(const BundleFlag flag, std::vector<BundleInfo> &bundleInfos, int32_t userId)
549 {
550     return GetBundleInfos(static_cast<int32_t>(flag), bundleInfos, userId);
551 }
552 
GetBundleInfos(int32_t flags,std::vector<BundleInfo> & bundleInfos,int32_t userId)553 bool BundleMgrHostImpl::GetBundleInfos(int32_t flags, std::vector<BundleInfo> &bundleInfos, int32_t userId)
554 {
555     // API9 need to be system app
556     if (!BundlePermissionMgr::IsSystemApp() &&
557         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
558         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
559         return true;
560     }
561     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
562         LOG_E(BMS_TAG_QUERY, "verify permission failed");
563         return false;
564     }
565     APP_LOGI_NOFUNC("GetBundleInfos -p:%{public}d, -f:%{public}d, -u:%{public}d",
566         IPCSkeleton::GetCallingPid(), flags, userId);
567     if (!BundlePermissionMgr::IsNativeTokenType() &&
568         (BundlePermissionMgr::GetHapApiVersion() >= ServiceConstants::API_VERSION_NINE)) {
569         LOG_D(BMS_TAG_QUERY,
570             "GetBundleInfos return empty, not support target level greater than or equal to api9");
571         return true;
572     }
573     auto dataMgr = GetDataMgrFromService();
574     if (dataMgr == nullptr) {
575         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
576         return false;
577     }
578     dataMgr->GetBundleInfos(flags, bundleInfos, userId);
579     if (isBrokerServiceExisted_) {
580         auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
581         bmsExtensionClient->GetBundleInfos(flags, bundleInfos, userId);
582     }
583     APP_LOGI_NOFUNC("GetBundleInfos size:%{public}zu", bundleInfos.size());
584     return !bundleInfos.empty();
585 }
586 
GetBundleInfosV9(int32_t flags,std::vector<BundleInfo> & bundleInfos,int32_t userId)587 ErrCode BundleMgrHostImpl::GetBundleInfosV9(int32_t flags, std::vector<BundleInfo> &bundleInfos, int32_t userId)
588 {
589     if (!BundlePermissionMgr::IsSystemApp()) {
590         LOG_E(BMS_TAG_QUERY, "non-system app calling system api");
591         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
592     }
593     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST)) {
594         LOG_E(BMS_TAG_QUERY, "permission denied");
595         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
596     }
597     APP_LOGI_NOFUNC("GetBundleInfosV9 -p:%{public}d, -f:%{public}d, -u:%{public}d",
598         IPCSkeleton::GetCallingPid(), flags, userId);
599     auto dataMgr = GetDataMgrFromService();
600     if (dataMgr == nullptr) {
601         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
602         BundlePermissionMgr::AddPermissionUsedRecord(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST, 0, 1);
603         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
604     }
605     auto res = dataMgr->GetBundleInfosV9(flags, bundleInfos, userId);
606     // menu profile is currently not supported in BrokerService
607     bool getMenu = ((static_cast<uint32_t>(flags) &
608         static_cast<uint32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_MENU))
609         == static_cast<uint32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_MENU));
610     bool getCloud = (static_cast<uint32_t>(flags) &
611         static_cast<uint32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_CLOUD_KIT))
612         == static_cast<uint32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_CLOUD_KIT);
613     if (isBrokerServiceExisted_ && !getMenu && !getCloud) {
614         auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
615         if (bmsExtensionClient->GetBundleInfos(flags, bundleInfos, userId, true) == ERR_OK) {
616             LOG_D(BMS_TAG_QUERY, "query bundle infos from bms extension successfully");
617             BundlePermissionMgr::AddPermissionUsedRecord(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST, 1, 0);
618             APP_LOGI_NOFUNC("GetBundleInfosV9 size:%{public}zu", bundleInfos.size());
619             return ERR_OK;
620         }
621     }
622     if (res == ERR_OK) {
623         BundlePermissionMgr::AddPermissionUsedRecord(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST, 1, 0);
624     } else {
625         BundlePermissionMgr::AddPermissionUsedRecord(Constants::PERMISSION_GET_INSTALLED_BUNDLE_LIST, 0, 1);
626     }
627     APP_LOGI_NOFUNC("GetBundleInfosV9 size:%{public}zu", bundleInfos.size());
628     return res;
629 }
630 
GetBundleNameForUid(const int uid,std::string & bundleName)631 bool BundleMgrHostImpl::GetBundleNameForUid(const int uid, std::string &bundleName)
632 {
633     APP_LOGD("start GetBundleNameForUid, uid : %{public}d", uid);
634     int64_t intervalTime = ONE_DAY;
635     if (!BundlePermissionMgr::IsSystemApp() &&
636         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
637         APP_LOGE("non-system app calling system api");
638         return false;
639     }
640     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
641         Constants::PERMISSION_GET_BUNDLE_INFO})) {
642         APP_LOGE("verify query permission failed");
643         return false;
644     }
645     auto dataMgr = GetDataMgrFromService();
646     if (dataMgr == nullptr) {
647         APP_LOGE("DataMgr is nullptr");
648         QueryEventInfo info = PrepareQueryEvent(ERR_BUNDLE_MANAGER_INTERNAL_ERROR, "None",
649             "GetBundleNameForUid", uid, -1, 0, -1);
650         SendQueryBundleInfoEvent(info, intervalTime, true);
651         return false;
652     }
653     bool res = dataMgr->GetBundleNameForUid(uid, bundleName);
654     if (!res) {
655         APP_LOGD("GetBundleNameForUid failed, -u: %{public}d", uid);
656         QueryEventInfo info = PrepareQueryEvent(ERR_BUNDLE_MANAGER_INVALID_UID, "None",
657             "GetBundleNameForUid", uid, -1, 0, -1);
658         SendQueryBundleInfoEvent(info, intervalTime, false);
659     }
660     return res;
661 }
662 
GetBundlesForUid(const int uid,std::vector<std::string> & bundleNames)663 bool BundleMgrHostImpl::GetBundlesForUid(const int uid, std::vector<std::string> &bundleNames)
664 {
665     APP_LOGD("start GetBundlesForUid, uid : %{public}d", uid);
666     if (!BundlePermissionMgr::IsSystemApp()) {
667         APP_LOGE("non-system app calling system api");
668         return false;
669     }
670     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
671         Constants::PERMISSION_GET_BUNDLE_INFO})) {
672         APP_LOGE("verify permission failed");
673         return false;
674     }
675     auto dataMgr = GetDataMgrFromService();
676     if (dataMgr == nullptr) {
677         APP_LOGE("DataMgr is nullptr");
678         return false;
679     }
680     return dataMgr->GetBundlesForUid(uid, bundleNames);
681 }
682 
GetNameForUid(const int uid,std::string & name)683 ErrCode BundleMgrHostImpl::GetNameForUid(const int uid, std::string &name)
684 {
685     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
686     APP_LOGD("start GetNameForUid, uid : %{public}d", uid);
687     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_NAME_FOR_UID);
688     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
689     bool permissionVerify = []() {
690         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
691             return true;
692         }
693         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO) &&
694             (BundlePermissionMgr::IsSystemApp() ||
695             BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE))) {
696             return true;
697         }
698         return false;
699     }();
700     if (!permissionVerify) {
701         APP_LOGE("verify permission failed");
702         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
703     }
704     int64_t intervalTime = ONE_DAY;
705     auto dataMgr = GetDataMgrFromService();
706     if (dataMgr == nullptr) {
707         APP_LOGE("DataMgr is nullptr");
708         QueryEventInfo info = PrepareQueryEvent(ERR_BUNDLE_MANAGER_INTERNAL_ERROR, "None",
709             "GetNameForUid", uid, -1, 0, -1);
710         SendQueryBundleInfoEvent(info, intervalTime, true);
711         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
712     }
713     auto ret = dataMgr->GetNameForUid(uid, name);
714     if (ret != ERR_OK && isBrokerServiceExisted_) {
715         auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
716         ret = bmsExtensionClient->GetBundleNameByUid(uid, name);
717         if (ret != ERR_OK) {
718             QueryEventInfo info = PrepareQueryEvent(ret, "None",
719                 "GetNameForUid", uid, -1, 0, -1);
720             SendQueryBundleInfoEvent(info, intervalTime, false);
721             return ERR_BUNDLE_MANAGER_INVALID_UID;
722         }
723     }
724     if (ret != ERR_OK) {
725         QueryEventInfo info = PrepareQueryEvent(ret, "None",
726             "GetNameForUid", uid, -1, 0, -1);
727         SendQueryBundleInfoEvent(info, intervalTime, false);
728     }
729     return ret;
730 }
731 
GetNameAndIndexForUid(const int uid,std::string & bundleName,int32_t & appIndex)732 ErrCode BundleMgrHostImpl::GetNameAndIndexForUid(const int uid, std::string &bundleName, int32_t &appIndex)
733 {
734     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
735     APP_LOGD("start GetNameAndIndexForUid, uid : %{public}d", uid);
736     bool permissionVerify = []() {
737         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
738             return true;
739         }
740         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO) &&
741             BundlePermissionMgr::IsSystemApp()) {
742             return true;
743         }
744         return false;
745     }();
746     if (!permissionVerify) {
747         APP_LOGW("verify permission failed");
748         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
749     }
750     auto dataMgr = GetDataMgrFromService();
751     if (dataMgr == nullptr) {
752         APP_LOGE("DataMgr is nullptr");
753         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
754     }
755     return dataMgr->GetBundleNameAndIndexForUid(uid, bundleName, appIndex);
756 }
757 
GetAppIdentifierAndAppIndex(const uint32_t accessTokenId,std::string & appIdentifier,int32_t & appIndex)758 ErrCode BundleMgrHostImpl::GetAppIdentifierAndAppIndex(const uint32_t accessTokenId,
759     std::string &appIdentifier, int32_t &appIndex)
760 {
761     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
762     APP_LOGD("start GetAppIdentifierAndAppIndex, accessTokenId : %{public}d", accessTokenId);
763     bool permissionVerify = []() {
764         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
765             return true;
766         }
767         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO) &&
768             BundlePermissionMgr::IsSystemApp()) {
769             return true;
770         }
771         return false;
772     }();
773     if (!permissionVerify) {
774         APP_LOGE("verify permission failed");
775         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
776     }
777     auto dataMgr = GetDataMgrFromService();
778     if (dataMgr == nullptr) {
779         APP_LOGE("DataMgr is nullptr");
780         return ERR_APPEXECFWK_NULL_PTR;
781     }
782     return dataMgr->GetAppIdentifierAndAppIndex(accessTokenId, appIdentifier, appIndex);
783 }
784 
GetSimpleAppInfoForUid(const std::vector<std::int32_t> & uids,std::vector<SimpleAppInfo> & simpleAppInfo)785 ErrCode BundleMgrHostImpl::GetSimpleAppInfoForUid(
786     const std::vector<std::int32_t> &uids, std::vector<SimpleAppInfo> &simpleAppInfo)
787 {
788     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
789     APP_LOGD("start GetSimpleAppInfoForUid");
790     bool permissionVerify = []() {
791         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
792             return true;
793         }
794         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO) &&
795             BundlePermissionMgr::IsSystemApp()) {
796             return true;
797         }
798         return false;
799     }();
800     if (!permissionVerify) {
801         APP_LOGE("verify permission failed");
802         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
803     }
804     auto dataMgr = GetDataMgrFromService();
805     if (dataMgr == nullptr) {
806         APP_LOGE("DataMgr is nullptr");
807         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
808     }
809 
810     SimpleAppInfo info;
811     for (size_t i = 0; i < uids.size(); i++) {
812         auto ret = dataMgr->GetBundleNameAndIndexForUid(uids[i], info.bundleName, info.appIndex);
813         if (ret != ERR_OK) {
814             APP_LOGW("get name and index for uid failed, uid : %{public}d ret : %{public}d", uids[i], ret);
815             info.bundleName = "";
816             info.appIndex = -1;
817         }
818         info.uid = uids[i];
819         info.ret = ret;
820         simpleAppInfo.emplace_back(info);
821     }
822     return ERR_OK;
823 }
824 
GetBundleGids(const std::string & bundleName,std::vector<int> & gids)825 bool BundleMgrHostImpl::GetBundleGids(const std::string &bundleName, std::vector<int> &gids)
826 {
827     APP_LOGD("start GetBundleGids, bundleName : %{public}s", bundleName.c_str());
828     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
829         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
830         APP_LOGE("verify token type failed");
831         return false;
832     }
833     auto dataMgr = GetDataMgrFromService();
834     if (dataMgr == nullptr) {
835         APP_LOGE("DataMgr is nullptr");
836         return false;
837     }
838     return dataMgr->GetBundleGids(bundleName, gids);
839 }
840 
GetBundleGidsByUid(const std::string & bundleName,const int & uid,std::vector<int> & gids)841 bool BundleMgrHostImpl::GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector<int> &gids)
842 {
843     APP_LOGD("start GetBundleGidsByUid, bundleName : %{public}s, uid : %{public}d", bundleName.c_str(), uid);
844     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
845         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
846         APP_LOGE("verify token type failed");
847         return false;
848     }
849     auto dataMgr = GetDataMgrFromService();
850     if (dataMgr == nullptr) {
851         APP_LOGE("DataMgr is nullptr");
852         return false;
853     }
854     return dataMgr->GetBundleGidsByUid(bundleName, uid, gids);
855 }
856 
CheckIsSystemAppByUid(const int uid)857 bool BundleMgrHostImpl::CheckIsSystemAppByUid(const int uid)
858 {
859     APP_LOGD("start CheckIsSystemAppByUid, uid : %{public}d", uid);
860     if (!BundlePermissionMgr::IsSystemApp()) {
861         APP_LOGE("non-system app calling system api");
862         return false;
863     }
864     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
865         APP_LOGE("verify permission failed");
866         return false;
867     }
868     auto dataMgr = GetDataMgrFromService();
869     if (dataMgr == nullptr) {
870         APP_LOGE("DataMgr is nullptr");
871         return false;
872     }
873     return dataMgr->CheckIsSystemAppByUid(uid);
874 }
875 
GetBundleInfosByMetaData(const std::string & metaData,std::vector<BundleInfo> & bundleInfos)876 bool BundleMgrHostImpl::GetBundleInfosByMetaData(const std::string &metaData, std::vector<BundleInfo> &bundleInfos)
877 {
878     APP_LOGD("start GetBundleInfosByMetaData, metaData : %{public}s", metaData.c_str());
879     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
880         APP_LOGE("verify permission failed");
881         return false;
882     }
883     auto dataMgr = GetDataMgrFromService();
884     if (dataMgr == nullptr) {
885         APP_LOGE("DataMgr is nullptr");
886         return false;
887     }
888     return dataMgr->GetBundleInfosByMetaData(metaData, bundleInfos);
889 }
890 
QueryAbilityInfo(const Want & want,AbilityInfo & abilityInfo)891 bool BundleMgrHostImpl::QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo)
892 {
893     return QueryAbilityInfo(want, GET_ABILITY_INFO_WITH_APPLICATION, Constants::UNSPECIFIED_USERID, abilityInfo);
894 }
895 
QueryAbilityInfo(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,const sptr<IRemoteObject> & callBack)896 bool BundleMgrHostImpl::QueryAbilityInfo(const Want &want, int32_t flags, int32_t userId,
897     AbilityInfo &abilityInfo, const sptr<IRemoteObject> &callBack)
898 {
899     if (!BundlePermissionMgr::IsSystemApp()) {
900         LOG_E(BMS_TAG_QUERY, "check is system app failed");
901         return false;
902     }
903     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
904         Constants::PERMISSION_GET_BUNDLE_INFO})) {
905         LOG_E(BMS_TAG_QUERY, "verify permission failed");
906         return false;
907     }
908 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
909     auto connectAbilityMgr = GetConnectAbilityMgrFromService();
910     if (connectAbilityMgr == nullptr) {
911         LOG_E(BMS_TAG_QUERY, "connectAbilityMgr is nullptr");
912         return false;
913     }
914     return connectAbilityMgr->QueryAbilityInfo(want, flags, userId, abilityInfo, callBack);
915 #else
916     auto dataMgr = GetDataMgrFromService();
917     if (dataMgr == nullptr) {
918         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
919         return false;
920     }
921     if (dataMgr->IsObtainAbilityInfo(want, userId, abilityInfo)) {
922         CallAbilityManager(ERR_OK, want, userId, callBack);
923         return true;
924     }
925     CallAbilityManager(ERR_APPEXECFWK_FREE_INSTALL_NOT_SUPPORT, want, userId, callBack);
926     return false;
927 #endif
928 }
929 
930 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
SilentInstall(const Want & want,int32_t userId,const sptr<IRemoteObject> & callBack)931 bool BundleMgrHostImpl::SilentInstall(const Want &want, int32_t userId, const sptr<IRemoteObject> &callBack)
932 {
933     APP_LOGD("SilentInstall in");
934     auto dataMgr = GetDataMgrFromService();
935     if (dataMgr == nullptr) {
936         APP_LOGE("dataMgr is null");
937         return false;
938     }
939     std::string callingBundleName;
940     int32_t callingUid = IPCSkeleton::GetCallingUid();
941     ErrCode ret = dataMgr->GetNameForUid(callingUid, callingBundleName);
942     if (ret != ERR_OK) {
943         APP_LOGE("get bundleName failed %{public}d %{public}d", ret, callingUid);
944         return false;
945     }
946     ElementName element = want.GetElement();
947     std::string packageName = element.GetBundleName();
948     if (packageName != callingBundleName) {
949         APP_LOGE("callingBundleName vaild fail %{public}s %{public}s",
950             packageName.c_str(), callingBundleName.c_str());
951         return false;
952     }
953     auto connectMgr = GetConnectAbilityMgrFromService();
954     if (connectMgr == nullptr) {
955         APP_LOGE("connectMgr is nullptr");
956         return false;
957     }
958     return connectMgr->SilentInstall(want, userId, callBack);
959 }
960 
UpgradeAtomicService(const Want & want,int32_t userId)961 void BundleMgrHostImpl::UpgradeAtomicService(const Want &want, int32_t userId)
962 {
963     if (!BundlePermissionMgr::IsSystemApp()) {
964         APP_LOGE("check is system app failed");
965         return;
966     }
967 
968     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
969         APP_LOGE("verify permission failed");
970         return;
971     }
972     auto connectAbilityMgr = GetConnectAbilityMgrFromService();
973     if (connectAbilityMgr == nullptr) {
974         APP_LOGE("connectAbilityMgr is nullptr");
975         return;
976     }
977     connectAbilityMgr->UpgradeAtomicService(want, userId);
978 }
979 
CheckAbilityEnableInstall(const Want & want,int32_t missionId,int32_t userId,const sptr<IRemoteObject> & callback)980 bool BundleMgrHostImpl::CheckAbilityEnableInstall(
981     const Want &want, int32_t missionId, int32_t userId, const sptr<IRemoteObject> &callback)
982 {
983     if (!BundlePermissionMgr::IsSystemApp()) {
984         APP_LOGE("check is system app failed");
985         return false;
986     }
987 
988     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
989         APP_LOGE("verify permission failed");
990         return false;
991     }
992     auto elementName = want.GetElement();
993     if (elementName.GetDeviceID().empty() || elementName.GetBundleName().empty() ||
994         elementName.GetAbilityName().empty()) {
995         APP_LOGE("check ability install parameter is invalid");
996         return false;
997     }
998     auto bundleDistributedManager = DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleDistributedManager();
999     if (bundleDistributedManager == nullptr) {
1000         APP_LOGE("bundleDistributedManager failed");
1001         return false;
1002     }
1003     return bundleDistributedManager->CheckAbilityEnableInstall(want, missionId, userId, callback);
1004 }
1005 
ProcessPreload(const Want & want)1006 bool BundleMgrHostImpl::ProcessPreload(const Want &want)
1007 {
1008     if (!BundlePermissionMgr::VerifyPreload(want)) {
1009         APP_LOGE("ProcessPreload verify failed");
1010         return false;
1011     }
1012     APP_LOGD("begin to process preload");
1013     auto connectAbilityMgr = GetConnectAbilityMgrFromService();
1014     if (connectAbilityMgr == nullptr) {
1015         APP_LOGE("connectAbilityMgr is nullptr");
1016         return false;
1017     }
1018     return connectAbilityMgr->ProcessPreload(want);
1019 }
1020 #endif
1021 
QueryAbilityInfo(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo)1022 bool BundleMgrHostImpl::QueryAbilityInfo(const Want &want, int32_t flags, int32_t userId, AbilityInfo &abilityInfo)
1023 {
1024     LOG_D(BMS_TAG_QUERY, "start QueryAbilityInfo, flags : %{public}d, userId : %{public}d", flags, userId);
1025     if (!BundlePermissionMgr::IsSystemApp() &&
1026         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1027         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
1028         return true;
1029     }
1030     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
1031         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
1032         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
1033         LOG_E(BMS_TAG_QUERY, "verify permission failed");
1034         return false;
1035     }
1036     APP_LOGD("verify permission success, begin to QueryAbilityInfo");
1037     auto dataMgr = GetDataMgrFromService();
1038     if (dataMgr == nullptr) {
1039         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1040         return false;
1041     }
1042     bool res = dataMgr->QueryAbilityInfo(want, flags, userId, abilityInfo);
1043     if (!res) {
1044         if (!IsAppLinking(flags) && isBrokerServiceExisted_) {
1045             auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
1046             return (bmsExtensionClient->QueryAbilityInfo(want, flags, userId, abilityInfo) == ERR_OK);
1047         }
1048     }
1049     return res;
1050 }
1051 
QueryAbilityInfos(const Want & want,std::vector<AbilityInfo> & abilityInfos)1052 bool BundleMgrHostImpl::QueryAbilityInfos(const Want &want, std::vector<AbilityInfo> &abilityInfos)
1053 {
1054     return QueryAbilityInfos(
1055         want, GET_ABILITY_INFO_WITH_APPLICATION, Constants::UNSPECIFIED_USERID, abilityInfos);
1056 }
1057 
QueryAbilityInfos(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos)1058 bool BundleMgrHostImpl::QueryAbilityInfos(
1059     const Want &want, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos)
1060 {
1061     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
1062     LOG_D(BMS_TAG_QUERY, "start QueryAbilityInfos, flags : %{public}d, userId : %{public}d", flags, userId);
1063     if (!BundlePermissionMgr::IsSystemApp() &&
1064         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1065         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
1066         return true;
1067     }
1068     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
1069         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
1070         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
1071         LOG_E(BMS_TAG_QUERY, "verify permission failed");
1072         return false;
1073     }
1074     auto dataMgr = GetDataMgrFromService();
1075     if (dataMgr == nullptr) {
1076         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1077         return false;
1078     }
1079     dataMgr->QueryAbilityInfos(want, flags, userId, abilityInfos);
1080     if (!IsAppLinking(flags) && isBrokerServiceExisted_) {
1081         auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
1082         bmsExtensionClient->QueryAbilityInfos(want, flags, userId, abilityInfos);
1083     }
1084     return !abilityInfos.empty();
1085 }
1086 
QueryAbilityInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos)1087 ErrCode BundleMgrHostImpl::QueryAbilityInfosV9(
1088     const Want &want, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos)
1089 {
1090     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
1091     LOG_D(BMS_TAG_QUERY, "start QueryAbilityInfosV9, flags : %{public}d, userId : %{public}d", flags, userId);
1092     if (!BundlePermissionMgr::IsSystemApp()) {
1093         LOG_E(BMS_TAG_QUERY, "non-system app calling system api");
1094         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1095     }
1096     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
1097         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
1098         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
1099         LOG_E(BMS_TAG_QUERY, "verify permission failed");
1100         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1101     }
1102     auto dataMgr = GetDataMgrFromService();
1103     if (dataMgr == nullptr) {
1104         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1105         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1106     }
1107     auto res = dataMgr->QueryAbilityInfosV9(want, flags, userId, abilityInfos);
1108     auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
1109     if (!IsAppLinking(flags) && isBrokerServiceExisted_ &&
1110         bmsExtensionClient->QueryAbilityInfos(want, flags, userId, abilityInfos, true) == ERR_OK) {
1111         LOG_D(BMS_TAG_QUERY, "query ability infos from bms extension successfully");
1112         return ERR_OK;
1113     }
1114     return res;
1115 }
1116 
GetAbilityInfos(const std::string & uri,uint32_t flags,std::vector<AbilityInfo> & abilityInfos)1117 ErrCode BundleMgrHostImpl::GetAbilityInfos(
1118     const std::string &uri, uint32_t flags, std::vector<AbilityInfo> &abilityInfos)
1119 {
1120     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
1121     LOG_D(BMS_TAG_QUERY, "start GetAbilityInfos, uri : %{public}s, flags : %{public}d",
1122         uri.c_str(), flags);
1123     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_ABILITY_INFO)) {
1124         LOG_E(BMS_TAG_QUERY, "verify permission failed");
1125         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1126     }
1127     auto dataMgr = GetDataMgrFromService();
1128     if (dataMgr == nullptr) {
1129         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1130         return ERR_APPEXECFWK_NULL_PTR;
1131     }
1132     Want want;
1133     want.SetUri(uri);
1134     auto uid = IPCSkeleton::GetCallingUid();
1135     auto res = dataMgr->QueryAbilityInfosV9(want, flags, BundleUtil::GetUserIdByUid(uid), abilityInfos);
1136     if (res != ERR_OK) {
1137         APP_LOGE("GetAbilityInfos failed %{public}d", res);
1138         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
1139     }
1140     GetAbilityLabelInfo(abilityInfos);
1141     GetApplicationLabelInfo(abilityInfos);
1142     return res;
1143 }
1144 
BatchQueryAbilityInfos(const std::vector<Want> & wants,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos)1145 ErrCode BundleMgrHostImpl::BatchQueryAbilityInfos(
1146     const std::vector<Want> &wants, int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos)
1147 {
1148     APP_LOGD("start BatchQueryAbilityInfos, flags : %{public}d, userId : %{public}d", flags, userId);
1149     if (!BundlePermissionMgr::IsSystemApp()) {
1150         APP_LOGE("non-system app calling system api");
1151         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1152     }
1153     bool callingPermission = BundlePermissionMgr::VerifyCallingPermissionsForAll(
1154         { Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED, Constants::PERMISSION_GET_BUNDLE_INFO });
1155     for (size_t i = 0; i < wants.size(); i++) {
1156         if (!callingPermission && !BundlePermissionMgr::IsBundleSelfCalling(wants[i].GetElement().GetBundleName())) {
1157             APP_LOGE("verify is bundle self calling failed");
1158             return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1159         }
1160     }
1161     APP_LOGD("verify permission success, begin to BatchQueryAbilityInfos");
1162     auto dataMgr = GetDataMgrFromService();
1163     if (dataMgr == nullptr) {
1164         APP_LOGE("DataMgr is nullptr");
1165         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1166     }
1167     auto res = dataMgr->BatchQueryAbilityInfos(wants, flags, userId, abilityInfos);
1168     auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
1169     if (!IsAppLinking(flags) && isBrokerServiceExisted_ &&
1170         bmsExtensionClient->BatchQueryAbilityInfos(wants, flags, userId, abilityInfos, true) == ERR_OK) {
1171         APP_LOGD("query ability infos from bms extension successfully");
1172         return ERR_OK;
1173     }
1174     return res;
1175 }
1176 
QueryLauncherAbilityInfos(const Want & want,int32_t userId,std::vector<AbilityInfo> & abilityInfos)1177 ErrCode BundleMgrHostImpl::QueryLauncherAbilityInfos(
1178     const Want &want, int32_t userId, std::vector<AbilityInfo> &abilityInfos)
1179 {
1180     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
1181     LOG_D(BMS_TAG_QUERY, "start QueryLauncherAbilityInfos, userId : %{public}d", userId);
1182     if (!BundlePermissionMgr::IsSystemApp()) {
1183         LOG_E(BMS_TAG_QUERY, "non-system app calling system api");
1184         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1185     }
1186     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
1187         LOG_E(BMS_TAG_QUERY, "verify permission failed");
1188         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1189     }
1190     APP_LOGD("verify permission success, begin to QueryLauncherAbilityInfos");
1191     auto dataMgr = GetDataMgrFromService();
1192     if (dataMgr == nullptr) {
1193         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1194         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1195     }
1196 
1197     auto ret = dataMgr->QueryLauncherAbilityInfos(want, userId, abilityInfos);
1198     auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
1199     if (bmsExtensionClient->QueryLauncherAbility(want, userId, abilityInfos) == ERR_OK) {
1200         LOG_D(BMS_TAG_QUERY, "query launcher ability infos from bms extension successfully");
1201         return ERR_OK;
1202     }
1203     return ret;
1204 }
1205 
GetLauncherAbilityInfoSync(const std::string & bundleName,int32_t userId,std::vector<AbilityInfo> & abilityInfos)1206 ErrCode BundleMgrHostImpl::GetLauncherAbilityInfoSync(
1207     const std::string &bundleName, int32_t userId, std::vector<AbilityInfo> &abilityInfos)
1208 {
1209     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
1210     LOG_D(BMS_TAG_QUERY, "start GetLauncherAbilityInfoSync, userId : %{public}d", userId);
1211 
1212     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
1213         LOG_E(BMS_TAG_QUERY, "verify permission failed");
1214         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1215     }
1216     APP_LOGD("verify permission success, begin to GetLauncherAbilityInfoSync");
1217     auto dataMgr = GetDataMgrFromService();
1218     if (dataMgr == nullptr) {
1219         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1220         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1221     }
1222     if (bundleName.empty()) {
1223         LOG_E(BMS_TAG_QUERY, "no bundleName %{public}s found", bundleName.c_str());
1224         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
1225     }
1226     Want want;
1227     want.SetAction(Want::ACTION_HOME);
1228     want.AddEntity(Want::ENTITY_HOME);
1229     ElementName elementName;
1230     elementName.SetBundleName(bundleName);
1231     want.SetElement(elementName);
1232 
1233     auto ret = dataMgr->GetLauncherAbilityInfoSync(want, userId, abilityInfos);
1234     auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
1235     if (bmsExtensionClient->QueryLauncherAbility(want, userId, abilityInfos) == ERR_OK) {
1236         LOG_D(BMS_TAG_QUERY, "query launcher ability infos from bms extension successfully");
1237         return ERR_OK;
1238     }
1239     return ret;
1240 }
1241 
QueryAllAbilityInfos(const Want & want,int32_t userId,std::vector<AbilityInfo> & abilityInfos)1242 bool BundleMgrHostImpl::QueryAllAbilityInfos(const Want &want, int32_t userId, std::vector<AbilityInfo> &abilityInfos)
1243 {
1244     LOG_D(BMS_TAG_QUERY, "start QueryAllAbilityInfos, userId : %{public}d", userId);
1245     if (!BundlePermissionMgr::IsSystemApp() &&
1246         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1247         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
1248         return true;
1249     }
1250     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
1251         LOG_E(BMS_TAG_QUERY, "verify permission failed");
1252         return false;
1253     }
1254     APP_LOGD("verify permission success, begin to QueryAllAbilityInfos");
1255     auto dataMgr = GetDataMgrFromService();
1256     if (dataMgr == nullptr) {
1257         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1258         return false;
1259     }
1260     bool res = dataMgr->QueryLauncherAbilityInfos(want, userId, abilityInfos) == ERR_OK;
1261     auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
1262     if (bmsExtensionClient->QueryLauncherAbility(want, userId, abilityInfos) == ERR_OK) {
1263         LOG_D(BMS_TAG_QUERY, "query launcher ability infos from bms extension successfully");
1264         return true;
1265     }
1266     return res;
1267 }
1268 
QueryAbilityInfoByUri(const std::string & abilityUri,AbilityInfo & abilityInfo)1269 bool BundleMgrHostImpl::QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo)
1270 {
1271     LOG_D(BMS_TAG_QUERY, "start QueryAbilityInfoByUri, uri : %{private}s", abilityUri.c_str());
1272     // API9 need to be system app, otherwise return empty data
1273     if (!BundlePermissionMgr::IsSystemApp() &&
1274         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1275         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
1276         return true;
1277     }
1278     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
1279         Constants::PERMISSION_GET_BUNDLE_INFO})) {
1280         LOG_E(BMS_TAG_QUERY, "verify query permission failed");
1281         return false;
1282     }
1283     auto dataMgr = GetDataMgrFromService();
1284     if (dataMgr == nullptr) {
1285         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1286         return false;
1287     }
1288     return dataMgr->QueryAbilityInfoByUri(abilityUri, Constants::UNSPECIFIED_USERID, abilityInfo);
1289 }
1290 
QueryAbilityInfosByUri(const std::string & abilityUri,std::vector<AbilityInfo> & abilityInfos)1291 bool BundleMgrHostImpl::QueryAbilityInfosByUri(const std::string &abilityUri, std::vector<AbilityInfo> &abilityInfos)
1292 {
1293     LOG_D(BMS_TAG_QUERY, "start QueryAbilityInfosByUri, uri : %{private}s", abilityUri.c_str());
1294     // API9 need to be system app, otherwise return empty data
1295     if (!BundlePermissionMgr::IsSystemApp() &&
1296         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1297         return true;
1298     }
1299     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
1300         LOG_E(BMS_TAG_QUERY, "verify permission failed");
1301         return false;
1302     }
1303     auto dataMgr = GetDataMgrFromService();
1304     if (dataMgr == nullptr) {
1305         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1306         return false;
1307     }
1308     return dataMgr->QueryAbilityInfosByUri(abilityUri, abilityInfos);
1309 }
1310 
QueryAbilityInfoByUri(const std::string & abilityUri,int32_t userId,AbilityInfo & abilityInfo)1311 bool BundleMgrHostImpl::QueryAbilityInfoByUri(
1312     const std::string &abilityUri, int32_t userId, AbilityInfo &abilityInfo)
1313 {
1314     LOG_D(BMS_TAG_QUERY, "start QueryAbilityInfoByUri, uri : %{private}s, userId : %{public}d",
1315         abilityUri.c_str(), userId);
1316     if (!BundlePermissionMgr::IsSystemApp() &&
1317         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1318         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
1319         return true;
1320     }
1321     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO,
1322         Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED})) {
1323         LOG_E(BMS_TAG_QUERY, "verify query permission failed");
1324         return false;
1325     }
1326     auto dataMgr = GetDataMgrFromService();
1327     if (dataMgr == nullptr) {
1328         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
1329         return false;
1330     }
1331     return dataMgr->QueryAbilityInfoByUri(abilityUri, userId, abilityInfo);
1332 }
1333 
QueryKeepAliveBundleInfos(std::vector<BundleInfo> & bundleInfos)1334 bool BundleMgrHostImpl::QueryKeepAliveBundleInfos(std::vector<BundleInfo> &bundleInfos)
1335 {
1336     auto dataMgr = GetDataMgrFromService();
1337     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
1338         APP_LOGE("verify permission failed");
1339         return false;
1340     }
1341     if (dataMgr == nullptr) {
1342         APP_LOGE("DataMgr is nullptr");
1343         return false;
1344     }
1345     return dataMgr->QueryKeepAliveBundleInfos(bundleInfos);
1346 }
1347 
GetAbilityLabel(const std::string & bundleName,const std::string & abilityName)1348 std::string BundleMgrHostImpl::GetAbilityLabel(const std::string &bundleName, const std::string &abilityName)
1349 {
1350     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
1351     APP_LOGD("start GetAbilityLabel, bundleName : %{public}s, abilityName : %{public}s",
1352         bundleName.c_str(), abilityName.c_str());
1353     // API9 need to be system app otherwise return empty data
1354     if (!BundlePermissionMgr::IsSystemApp() &&
1355         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1356         APP_LOGD("non-system calling system");
1357         return Constants::EMPTY_STRING;
1358     }
1359     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
1360         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
1361         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
1362         APP_LOGE("verify permission failed");
1363         return Constants::EMPTY_STRING;
1364     }
1365     auto dataMgr = GetDataMgrFromService();
1366     if (dataMgr == nullptr) {
1367         APP_LOGE("DataMgr is nullptr");
1368         return Constants::EMPTY_STRING;
1369     }
1370     std::string label;
1371     ErrCode ret = dataMgr->GetAbilityLabel(bundleName, Constants::EMPTY_STRING, abilityName, label);
1372     if (ret != ERR_OK) {
1373         return Constants::EMPTY_STRING;
1374     }
1375     return label;
1376 }
1377 
GetAbilityLabel(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,std::string & label)1378 ErrCode BundleMgrHostImpl::GetAbilityLabel(const std::string &bundleName, const std::string &moduleName,
1379     const std::string &abilityName, std::string &label)
1380 {
1381     if (!BundlePermissionMgr::IsSystemApp()) {
1382         APP_LOGE("non-system app calling system api");
1383         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1384     }
1385     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
1386         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
1387         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
1388         APP_LOGE("verify permission failed");
1389         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1390     }
1391     auto dataMgr = GetDataMgrFromService();
1392     if (dataMgr == nullptr) {
1393         APP_LOGE("DataMgr is nullptr");
1394         return ERR_APPEXECFWK_SERVICE_NOT_READY;
1395     }
1396     return dataMgr->GetAbilityLabel(bundleName, moduleName, abilityName, label);
1397 }
1398 
GetBundleArchiveInfo(const std::string & hapFilePath,const BundleFlag flag,BundleInfo & bundleInfo)1399 bool BundleMgrHostImpl::GetBundleArchiveInfo(
1400     const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo)
1401 {
1402     return GetBundleArchiveInfo(hapFilePath, static_cast<int32_t>(flag), bundleInfo);
1403 }
1404 
GetBundleArchiveInfo(const std::string & hapFilePath,int32_t flags,BundleInfo & bundleInfo)1405 bool BundleMgrHostImpl::GetBundleArchiveInfo(
1406     const std::string &hapFilePath, int32_t flags, BundleInfo &bundleInfo)
1407 {
1408     APP_LOGD("start GetBundleArchiveInfo, hapFilePath : %{private}s, flags : %{public}d",
1409         hapFilePath.c_str(), flags);
1410     if (!BundlePermissionMgr::IsSystemApp() &&
1411         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1412         APP_LOGD("non-system app calling system api");
1413         return true;
1414     }
1415     if (hapFilePath.find(ServiceConstants::RELATIVE_PATH) != std::string::npos) {
1416         APP_LOGE("invalid hapFilePath");
1417         return false;
1418     }
1419     if (hapFilePath.find(ServiceConstants::SANDBOX_DATA_PATH) == std::string::npos &&
1420         hapFilePath.find(ServiceConstants::APP_INSTALL_SANDBOX_PATH) == std::string::npos) {
1421         std::string realPath;
1422         auto ret = BundleUtil::CheckFilePath(hapFilePath, realPath);
1423         if (ret != ERR_OK) {
1424             APP_LOGE("GetBundleArchiveInfo file path %{private}s invalid", hapFilePath.c_str());
1425             return false;
1426         }
1427 
1428         InnerBundleInfo info;
1429         BundleParser bundleParser;
1430         ret = bundleParser.Parse(realPath, info);
1431         if (ret != ERR_OK) {
1432             APP_LOGE("parse bundle info failed, error: %{public}d", ret);
1433             return false;
1434         }
1435         APP_LOGD("verify permission success, begin to GetBundleArchiveInfo");
1436         SetProvisionInfoToInnerBundleInfo(realPath, info);
1437         info.GetBundleInfo(flags, bundleInfo, ServiceConstants::NOT_EXIST_USERID);
1438         return true;
1439     } else {
1440         return GetBundleArchiveInfoBySandBoxPath(hapFilePath, flags, bundleInfo) == ERR_OK;
1441     }
1442 }
1443 
GetBundleArchiveInfoV9(const std::string & hapFilePath,int32_t flags,BundleInfo & bundleInfo)1444 ErrCode BundleMgrHostImpl::GetBundleArchiveInfoV9(
1445     const std::string &hapFilePath, int32_t flags, BundleInfo &bundleInfo)
1446 {
1447     APP_LOGD("start GetBundleArchiveInfoV9, hapFilePath : %{private}s, flags : %{public}d",
1448         hapFilePath.c_str(), flags);
1449     if (!BundlePermissionMgr::IsSystemApp()) {
1450         APP_LOGE("non-system app calling system api");
1451         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1452     }
1453     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
1454         APP_LOGE("verify permission failed");
1455         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1456     }
1457     if (hapFilePath.find(ServiceConstants::RELATIVE_PATH) != std::string::npos) {
1458         APP_LOGD("invalid hapFilePath");
1459         return ERR_BUNDLE_MANAGER_INVALID_HAP_PATH;
1460     }
1461     if (hapFilePath.find(ServiceConstants::SANDBOX_DATA_PATH) == 0 ||
1462         hapFilePath.find(ServiceConstants::APP_INSTALL_SANDBOX_PATH) == 0) {
1463         APP_LOGD("sandbox path");
1464         return GetBundleArchiveInfoBySandBoxPath(hapFilePath, flags, bundleInfo, true);
1465     }
1466     std::string realPath;
1467     ErrCode ret = BundleUtil::CheckFilePath(hapFilePath, realPath);
1468     if (ret != ERR_OK) {
1469         APP_LOGE("GetBundleArchiveInfoV9 file path %{private}s invalid", hapFilePath.c_str());
1470         return ERR_BUNDLE_MANAGER_INVALID_HAP_PATH;
1471     }
1472     InnerBundleInfo info;
1473     BundleParser bundleParser;
1474     ret = bundleParser.Parse(realPath, info);
1475     if (ret != ERR_OK) {
1476         APP_LOGE("parse bundle info failed, error: %{public}d", ret);
1477         return ERR_BUNDLE_MANAGER_INVALID_HAP_PATH;
1478     }
1479     if ((static_cast<uint32_t>(flags) & static_cast<uint32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO))
1480         == static_cast<uint32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO)) {
1481         SetProvisionInfoToInnerBundleInfo(realPath, info);
1482     }
1483     info.GetBundleInfoV9(flags, bundleInfo, ServiceConstants::NOT_EXIST_USERID);
1484     return ERR_OK;
1485 }
1486 
GetBundleArchiveInfoBySandBoxPath(const std::string & hapFilePath,int32_t flags,BundleInfo & bundleInfo,bool fromV9)1487 ErrCode BundleMgrHostImpl::GetBundleArchiveInfoBySandBoxPath(const std::string &hapFilePath,
1488     int32_t flags, BundleInfo &bundleInfo, bool fromV9)
1489 {
1490     std::string bundleName;
1491     int32_t apiVersion = fromV9 ? Constants::INVALID_API_VERSION : ServiceConstants::API_VERSION_NINE;
1492     if (!BundlePermissionMgr::IsSystemApp() && !BundlePermissionMgr::VerifyCallingBundleSdkVersion(apiVersion)) {
1493         APP_LOGE("non-system app calling system api");
1494         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1495     }
1496     if (!ObtainCallingBundleName(bundleName)) {
1497         APP_LOGE("get calling bundleName failed");
1498         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1499     }
1500     if (hapFilePath.find(ServiceConstants::APP_INSTALL_SANDBOX_PATH) == 0 &&
1501         !BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_ACCESS_APP_INSTALL_DIR)) {
1502         APP_LOGE("verify ACCESS_APP_INSTALL_DIR failed");
1503         return ERR_BUNDLE_MANAGER_INVALID_HAP_PATH;
1504     }
1505     std::string hapRealPath;
1506     if (!BundleUtil::RevertToRealPath(hapFilePath, bundleName, hapRealPath)) {
1507         APP_LOGE("GetBundleArchiveInfo RevertToRealPath failed");
1508         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1509     }
1510     std::string tempHapPath = std::string(ServiceConstants::BUNDLE_MANAGER_SERVICE_PATH) +
1511         ServiceConstants::PATH_SEPARATOR + std::to_string(BundleUtil::GetCurrentTimeNs());
1512     if (!BundleUtil::CreateDir(tempHapPath)) {
1513         APP_LOGE("GetBundleArchiveInfo make temp dir failed");
1514         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1515     }
1516     std::string hapName = hapFilePath.substr(hapFilePath.find_last_of("//") + 1);
1517     std::string tempHapFile = tempHapPath + ServiceConstants::PATH_SEPARATOR + hapName;
1518     if (InstalldClient::GetInstance()->CopyFile(hapRealPath, tempHapFile) != ERR_OK) {
1519         APP_LOGE("GetBundleArchiveInfo copy hap file failed");
1520         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1521     }
1522     std::string realPath;
1523     auto ret = BundleUtil::CheckFilePath(tempHapFile, realPath);
1524     if (ret != ERR_OK) {
1525         APP_LOGE("CheckFilePath failed");
1526         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1527     }
1528     InnerBundleInfo info;
1529     BundleParser bundleParser;
1530     ret = bundleParser.Parse(realPath, info);
1531     if (ret != ERR_OK) {
1532         APP_LOGE("parse bundle info failed, error: %{public}d", ret);
1533         BundleUtil::DeleteDir(tempHapPath);
1534         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1535     }
1536     SetProvisionInfoToInnerBundleInfo(realPath, info);
1537     BundleUtil::DeleteDir(tempHapPath);
1538     if (fromV9) {
1539         info.GetBundleInfoV9(flags, bundleInfo, ServiceConstants::NOT_EXIST_USERID);
1540     } else {
1541         info.GetBundleInfo(flags, bundleInfo, ServiceConstants::NOT_EXIST_USERID);
1542     }
1543     return ERR_OK;
1544 }
1545 
GetHapModuleInfo(const AbilityInfo & abilityInfo,HapModuleInfo & hapModuleInfo)1546 bool BundleMgrHostImpl::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo)
1547 {
1548     APP_LOGD("start GetHapModuleInfo");
1549     return GetHapModuleInfo(abilityInfo, Constants::UNSPECIFIED_USERID, hapModuleInfo);
1550 }
1551 
GetHapModuleInfo(const AbilityInfo & abilityInfo,int32_t userId,HapModuleInfo & hapModuleInfo)1552 bool BundleMgrHostImpl::GetHapModuleInfo(const AbilityInfo &abilityInfo, int32_t userId, HapModuleInfo &hapModuleInfo)
1553 {
1554     APP_LOGD("start GetHapModuleInfo with bundleName %{public}s and userId: %{public}d",
1555         abilityInfo.bundleName.c_str(), userId);
1556     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_HAP_MODULE_INFO);
1557     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
1558     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
1559         !BundlePermissionMgr::IsBundleSelfCalling(abilityInfo.bundleName)) {
1560         APP_LOGE("verify permission failed");
1561         return false;
1562     }
1563     if (abilityInfo.bundleName.empty() || abilityInfo.package.empty()) {
1564         APP_LOGE("fail to GetHapModuleInfo due to params empty");
1565         return false;
1566     }
1567     auto dataMgr = GetDataMgrFromService();
1568     if (dataMgr == nullptr) {
1569         APP_LOGE("DataMgr is nullptr");
1570         return false;
1571     }
1572     return dataMgr->GetHapModuleInfo(abilityInfo, hapModuleInfo, userId);
1573 }
1574 
GetLaunchWantForBundle(const std::string & bundleName,Want & want,int32_t userId)1575 ErrCode BundleMgrHostImpl::GetLaunchWantForBundle(const std::string &bundleName, Want &want, int32_t userId)
1576 {
1577     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
1578     APP_LOGD("start GetLaunchWantForBundle, bundleName : %{public}s", bundleName.c_str());
1579     if (!BundlePermissionMgr::IsSystemApp() &&
1580         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
1581         APP_LOGE("non-system app calling system api");
1582         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1583     }
1584     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
1585         APP_LOGE("verify permission failed");
1586         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1587     }
1588 
1589     APP_LOGD("verify permission success, begin to GetLaunchWantForBundle");
1590     auto dataMgr = GetDataMgrFromService();
1591     if (dataMgr == nullptr) {
1592         APP_LOGE("DataMgr is nullptr");
1593         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
1594     }
1595 
1596     return dataMgr->GetLaunchWantForBundle(bundleName, want, userId);
1597 }
1598 
GetPermissionDef(const std::string & permissionName,PermissionDef & permissionDef)1599 ErrCode BundleMgrHostImpl::GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef)
1600 {
1601     if (!BundlePermissionMgr::IsSystemApp()) {
1602         APP_LOGE("non-system app calling system api");
1603         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1604     }
1605     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
1606         APP_LOGE("verify GET_BUNDLE_INFO_PRIVILEGED failed");
1607         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1608     }
1609     if (permissionName.empty()) {
1610         APP_LOGW("fail to GetPermissionDef due to params empty");
1611         return ERR_BUNDLE_MANAGER_QUERY_PERMISSION_DEFINE_FAILED;
1612     }
1613     return BundlePermissionMgr::GetPermissionDef(permissionName, permissionDef);
1614 }
1615 
CleanBundleCacheFilesAutomatic(uint64_t cacheSize)1616 ErrCode BundleMgrHostImpl::CleanBundleCacheFilesAutomatic(uint64_t cacheSize)
1617 {
1618     if (cacheSize == 0) {
1619         APP_LOGE("parameter error, cache size must be greater than 0");
1620         return ERR_BUNDLE_MANAGER_INVALID_PARAMETER;
1621     }
1622 
1623     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_REMOVECACHEFILE)) {
1624         APP_LOGE("ohos.permission.REMOVE_CACHE_FILES permission denied");
1625         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1626     }
1627 
1628     // Get current active userId
1629     int32_t currentUserId = AccountHelper::GetCurrentActiveUserId();
1630     APP_LOGI("current active userId is %{public}d", currentUserId);
1631     if (currentUserId == Constants::INVALID_USERID) {
1632         APP_LOGE("currentUserId %{public}d is invalid", currentUserId);
1633         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1634     }
1635 
1636     // Get apps use time under the current active user
1637     int64_t startTime = 0;
1638     int64_t endTime = BundleUtil::GetCurrentTimeMs();
1639     const int32_t PERIOD_ANNUALLY = 4; // 4 is the number of the period ANN
1640     uint32_t notRunningSum = 0; // The total amount of application that is not running
1641 #ifdef DEVICE_USAGE_STATISTICS_ENABLED
1642     std::vector<DeviceUsageStats::BundleActivePackageStats> useStats;
1643     DeviceUsageStats::BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(
1644         useStats, PERIOD_ANNUALLY, startTime, endTime, currentUserId);
1645 
1646     if (useStats.empty()) {
1647         APP_LOGE("useStats under the current active user is empty");
1648         return ERR_BUNDLE_MANAGER_DEVICE_USAGE_STATS_EMPTY;
1649     }
1650 
1651     // Sort apps use time from small to large under the current active user
1652     std::sort(useStats.begin(), useStats.end(),
1653         [](DeviceUsageStats::BundleActivePackageStats a,
1654         DeviceUsageStats::BundleActivePackageStats b) {
1655             return a.totalInFrontTime_ < b.totalInFrontTime_;
1656         });
1657 
1658     // Get all running apps
1659     sptr<IAppMgr> appMgrProxy =
1660         iface_cast<IAppMgr>(SystemAbilityHelper::GetSystemAbility(APP_MGR_SERVICE_ID));
1661     if (appMgrProxy == nullptr) {
1662         APP_LOGE("fail to find the app mgr service to check app is running");
1663         return ERR_BUNDLE_MANAGER_GET_SYSTEM_ABILITY_FAILED;
1664     }
1665 
1666     std::vector<RunningProcessInfo> runningList;
1667     int result = appMgrProxy->GetAllRunningProcesses(runningList);
1668     if (result != ERR_OK) {
1669         APP_LOGE("GetAllRunningProcesses failed");
1670         return ERR_BUNDLE_MANAGER_GET_ALL_RUNNING_PROCESSES_FAILED;
1671     }
1672 
1673     std::unordered_set<std::string> runningSet;
1674     for (const auto &info : runningList) {
1675         runningSet.insert(info.bundleNames.begin(), info.bundleNames.end());
1676     }
1677 
1678     uint64_t cleanCacheSum = 0; // The total amount of application cache currently cleaned
1679     for (auto useStat : useStats) {
1680         if (runningSet.find(useStat.bundleName_) == runningSet.end()) {
1681             notRunningSum++;
1682             uint64_t cleanCacheSize = 0; // The cache size of a single application cleaned up
1683             ErrCode ret = CleanBundleCacheFilesGetCleanSize(useStat.bundleName_, currentUserId, cleanCacheSize);
1684             if (ret != ERR_OK) {
1685                 APP_LOGE("CleanBundleCacheFilesGetCleanSize failed,"
1686                     "bundleName: %{public}s, currentUserId: %{public}d, ret: %{public}d",
1687                     useStat.bundleName_.c_str(), currentUserId, ret);
1688                 continue;
1689             }
1690             APP_LOGI("bundleName : %{public}s, cleanCacheSize: %{public}" PRIu64 "",
1691                 useStat.bundleName_.c_str(), cleanCacheSize);
1692             if (cleanCacheSum <= std::numeric_limits<uint64_t>::max() - cleanCacheSize) {
1693                 cleanCacheSum += cleanCacheSize;
1694             } else {
1695                 APP_LOGE("add overflow cleanCacheSum: %{public}" PRIu64 ", cleanCacheSize: %{public}" PRIu64 "",
1696                     cleanCacheSum, cleanCacheSize);
1697             }
1698             if (cleanCacheSum >= cacheSize) {
1699                 return ERR_OK;
1700             }
1701         }
1702     }
1703 #endif
1704     if (notRunningSum == 0) {
1705         APP_LOGE("All apps are running under the current active user");
1706         return ERR_BUNDLE_MANAGER_ALL_BUNDLES_ARE_RUNNING;
1707     }
1708 
1709     return ERR_OK;
1710 }
1711 
CleanBundleCacheFilesGetCleanSize(const std::string & bundleName,int32_t userId,uint64_t & cleanCacheSize)1712 ErrCode BundleMgrHostImpl::CleanBundleCacheFilesGetCleanSize(const std::string &bundleName,
1713     int32_t userId, uint64_t &cleanCacheSize)
1714 {
1715     APP_LOGI("start CleanBundleCacheFilesGetCleanSize, bundleName : %{public}s, userId : %{public}d",
1716         bundleName.c_str(), userId);
1717 
1718     if (!BundlePermissionMgr::IsSystemApp()) {
1719         APP_LOGE("non-system app calling system api");
1720         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1721     }
1722     auto dataMgr = GetDataMgrFromService();
1723     int32_t callingUid =  IPCSkeleton::GetCallingUid();
1724     std::string callingBundleName;
1725     if (dataMgr == nullptr) {
1726         APP_LOGE("DataMgr is nullptr");
1727         EventReport::SendCleanCacheSysEvent(bundleName, userId, true, true, callingUid, callingBundleName);
1728         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
1729     }
1730     (void)dataMgr->GetBundleNameForUid(callingUid, callingBundleName);
1731     if (userId < 0) {
1732         APP_LOGE("userId is invalid");
1733         EventReport::SendCleanCacheSysEvent(bundleName, userId, true, true, callingUid, callingBundleName);
1734         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1735     }
1736 
1737     if (bundleName.empty()) {
1738         APP_LOGE("the bundleName empty");
1739         EventReport::SendCleanCacheSysEvent(bundleName, userId, true, true, callingUid, callingBundleName);
1740         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
1741     }
1742 
1743     ApplicationInfo applicationInfo;
1744 
1745     auto ret = dataMgr->GetApplicationInfoWithResponseId(bundleName,
1746         static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE), userId, applicationInfo);
1747     if (ret != ERR_OK) {
1748         APP_LOGE("can not get application info of %{public}s", bundleName.c_str());
1749         EventReport::SendCleanCacheSysEvent(bundleName, userId, true, true, callingUid, callingBundleName);
1750         return ret;
1751     }
1752 
1753     if (!applicationInfo.userDataClearable) {
1754         APP_LOGE("can not clean cacheFiles of %{public}s due to userDataClearable is false", bundleName.c_str());
1755         EventReport::SendCleanCacheSysEvent(bundleName, userId, true, true, callingUid, callingBundleName);
1756         return ERR_BUNDLE_MANAGER_CAN_NOT_CLEAR_USER_DATA;
1757     }
1758 
1759     CleanBundleCacheTaskGetCleanSize(bundleName, userId, cleanCacheSize, callingUid, callingBundleName);
1760     return ERR_OK;
1761 }
1762 
CleanBundleCacheTaskGetCleanSize(const std::string & bundleName,int32_t userId,uint64_t & cleanCacheSize,int32_t callingUid,const std::string & callingBundleName)1763 void BundleMgrHostImpl::CleanBundleCacheTaskGetCleanSize(const std::string &bundleName,
1764     int32_t userId, uint64_t &cleanCacheSize, int32_t callingUid, const std::string &callingBundleName)
1765 {
1766     InnerBundleInfo info;
1767     auto dataMgr = GetDataMgrFromService();
1768     if (!dataMgr->FetchInnerBundleInfo(bundleName, info)) {
1769         APP_LOGE("can not get bundleinfo of %{public}s", bundleName.c_str());
1770         EventReport::SendCleanCacheSysEvent(bundleName, userId, true, true, callingUid, callingBundleName);
1771         return;
1772     }
1773     std::vector<std::tuple<std::string, std::vector<std::string>, std::vector<int32_t>>> validBundles;
1774     dataMgr->GetBundleCacheInfo([](std::string &bundleName, std::vector<int32_t> &allidx) {
1775             return allidx;
1776         }, info, validBundles, userId, false);
1777     uint64_t cleanSize;
1778     BundleCacheMgr().GetBundleCacheSize(validBundles, userId, cleanSize);
1779     auto ret = BundleCacheMgr().CleanBundleCache(validBundles, userId);
1780     if (ret != ERR_OK) {
1781         APP_LOGE("can not get CleanBundleCache of %{public}s", bundleName.c_str());
1782         EventReport::SendCleanCacheSysEvent(bundleName, userId, true, true, callingUid, callingBundleName);
1783         return;
1784     }
1785     cleanCacheSize = cleanSize;
1786     bool succeed = true;
1787 
1788     EventReport::SendCleanCacheSysEvent(bundleName, userId, true, !succeed, callingUid, callingBundleName);
1789     APP_LOGI("CleanBundleCacheFiles with succeed %{public}d", succeed);
1790     InnerBundleUserInfo innerBundleUserInfo;
1791     if (!this->GetBundleUserInfo(bundleName, userId, innerBundleUserInfo)) {
1792         APP_LOGE("Get calling userInfo in bundle(%{public}s) failed", bundleName.c_str());
1793         return;
1794     }
1795     NotifyBundleEvents installRes = {
1796         .type = NotifyType::BUNDLE_CACHE_CLEARED,
1797         .resultCode = ERR_OK,
1798         .accessTokenId = innerBundleUserInfo.accessTokenId,
1799         .uid = innerBundleUserInfo.uid,
1800         .bundleName = bundleName
1801     };
1802     NotifyBundleStatus(installRes);
1803 }
1804 
CheckAppIndex(const std::string & bundleName,int32_t userId,int32_t appIndex)1805 bool BundleMgrHostImpl::CheckAppIndex(const std::string &bundleName, int32_t userId, int32_t appIndex)
1806 {
1807     if (appIndex == 0) {
1808         return true;
1809     }
1810     if (appIndex < 0) {
1811         APP_LOGE("appIndex is invalid");
1812         return false;
1813     }
1814     auto dataMgr = GetDataMgrFromService();
1815     if (dataMgr == nullptr) {
1816         APP_LOGE("DataMgr is nullptr");
1817         return false;
1818     }
1819     std::vector<int32_t> appIndexes = dataMgr->GetCloneAppIndexes(bundleName, userId);
1820     bool isAppIndexValid = std::find(appIndexes.cbegin(), appIndexes.cend(), appIndex) == appIndexes.cend();
1821     if (isAppIndexValid) {
1822         APP_LOGE("appIndex is not in the installed appIndexes range");
1823         return false;
1824     }
1825     return true;
1826 }
1827 
CleanBundleCacheFiles(const std::string & bundleName,const sptr<ICleanCacheCallback> cleanCacheCallback,int32_t userId,int32_t appIndex)1828 ErrCode BundleMgrHostImpl::CleanBundleCacheFiles(
1829     const std::string &bundleName, const sptr<ICleanCacheCallback> cleanCacheCallback,
1830     int32_t userId, int32_t appIndex)
1831 {
1832     BUNDLE_MANAGER_HITRACE_CHAIN_NAME("CleanBundleCacheFiles", HITRACE_FLAG_INCLUDE_ASYNC);
1833     if (userId == Constants::UNSPECIFIED_USERID) {
1834         userId = BundleUtil::GetUserIdByCallingUid();
1835     }
1836     APP_LOGI("start -n %{public}s -u %{public}d -i %{public}d", bundleName.c_str(), userId, appIndex);
1837     if (!BundlePermissionMgr::IsSystemApp()) {
1838         APP_LOGE("non-system app calling system api");
1839         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
1840     }
1841     auto dataMgr = GetDataMgrFromService();
1842     int32_t callingUid =  IPCSkeleton::GetCallingUid();
1843     std::string callingBundleName;
1844     if (dataMgr == nullptr) {
1845         APP_LOGE("DataMgr is nullptr");
1846         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, true, true,
1847             callingUid, callingBundleName);
1848         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
1849     }
1850     (void)dataMgr->GetBundleNameForUid(callingUid, callingBundleName);
1851     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_REMOVECACHEFILE) &&
1852         !BundlePermissionMgr::IsBundleSelfCalling(bundleName, appIndex)) {
1853         APP_LOGE("ohos.permission.REMOVE_CACHE_FILES permission denied");
1854         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, true, true,
1855             callingUid, callingBundleName);
1856         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1857     }
1858     if (!BundlePermissionMgr::CheckUserFromShell(userId)) {
1859         LOG_E(BMS_TAG_INSTALLER, "check shell user fail");
1860         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
1861     }
1862     if (userId < 0) {
1863         APP_LOGE("userId is invalid");
1864         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, true, true,
1865             callingUid, callingBundleName);
1866         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
1867     }
1868     if (bundleName.empty() || !cleanCacheCallback) {
1869         APP_LOGE("the cleanCacheCallback is nullptr or bundleName empty");
1870         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, true, true,
1871             callingUid, callingBundleName);
1872         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
1873     }
1874 
1875     if (isBrokerServiceExisted_ && !IsBundleExist(bundleName)) {
1876         return ClearCache(bundleName, cleanCacheCallback, userId, callingUid, callingBundleName);
1877     }
1878 
1879     ApplicationInfo applicationInfo;
1880 
1881     auto ret = dataMgr->GetApplicationInfoWithResponseId(bundleName,
1882         static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE), userId, applicationInfo);
1883     if (ret != ERR_OK) {
1884         APP_LOGE("can not get application info of %{public}s", bundleName.c_str());
1885         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, true, true,
1886             callingUid, callingBundleName);
1887         return ret;
1888     }
1889 
1890     if (!CheckAppIndex(bundleName, userId, appIndex)) {
1891         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, true, true,
1892             callingUid, callingBundleName);
1893         return ERR_APPEXECFWK_APP_INDEX_OUT_OF_RANGE;
1894     }
1895 
1896     if (!applicationInfo.userDataClearable) {
1897         APP_LOGE("can not clean cacheFiles of %{public}s due to userDataClearable is false", bundleName.c_str());
1898         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, true, true,
1899             callingUid, callingBundleName);
1900         return ERR_BUNDLE_MANAGER_CAN_NOT_CLEAR_USER_DATA;
1901     }
1902 
1903     CleanBundleCacheTask(bundleName, cleanCacheCallback, dataMgr, userId, appIndex);
1904     return ERR_OK;
1905 }
1906 
CleanBundleCacheTask(const std::string & bundleName,const sptr<ICleanCacheCallback> cleanCacheCallback,const std::shared_ptr<BundleDataMgr> & dataMgr,int32_t userId,int32_t appIndex)1907 void BundleMgrHostImpl::CleanBundleCacheTask(const std::string &bundleName,
1908     const sptr<ICleanCacheCallback> cleanCacheCallback,
1909     const std::shared_ptr<BundleDataMgr> &dataMgr,
1910     int32_t userId, int32_t appIndex)
1911 {
1912     std::vector<std::string> rootDir;
1913     std::vector<std::string> moduleNameList;
1914     dataMgr->GetBundleModuleNames(bundleName, moduleNameList);
1915     int32_t callingUid =  IPCSkeleton::GetCallingUid();
1916     std::string callingBundleName;
1917     (void)dataMgr->GetBundleNameForUid(callingUid, callingBundleName);
1918     rootDir = BundleCacheMgr().GetBundleCachePath(bundleName, userId, appIndex, moduleNameList);
1919     auto traceId = HiviewDFX::HiTraceChain::GetId();
1920     auto cleanCache = [bundleName, userId, rootDir, dataMgr, cleanCacheCallback, appIndex, traceId,
1921         this, callingUid, callingBundleName]() {
1922         BUNDLE_MANAGER_TASK_CHAIN_ID(traceId);
1923         std::vector<std::string> caches = rootDir;
1924         std::string shaderCachePath;
1925         shaderCachePath.append(ServiceConstants::SHADER_CACHE_PATH).append(bundleName);
1926         caches.push_back(shaderCachePath);
1927         bool succeed = true;
1928         if (!caches.empty()) {
1929             for (const auto& cache : caches) {
1930                 ErrCode ret = InstalldClient::GetInstance()->CleanBundleDataDir(cache);
1931                 if (ret != ERR_OK) {
1932                     APP_LOGE("CleanBundleDataDir failed, path: %{private}s", cache.c_str());
1933                     succeed = false;
1934                 }
1935             }
1936         }
1937 
1938         EventReport::SendCleanCacheSysEvent(bundleName, userId, true, !succeed, callingUid, callingBundleName);
1939         APP_LOGD("CleanBundleCacheFiles with succeed %{public}d", succeed);
1940         cleanCacheCallback->OnCleanCacheFinished(succeed);
1941         InnerBundleUserInfo innerBundleUserInfo;
1942         if (!this->GetBundleUserInfo(bundleName, userId, innerBundleUserInfo)) {
1943             APP_LOGW("Get calling userInfo in bundle(%{public}s) failed", bundleName.c_str());
1944             return;
1945         }
1946         NotifyBundleEvents installRes;
1947         if (appIndex > 0) {
1948             std::map<std::string, InnerBundleCloneInfo> cloneInfos = innerBundleUserInfo.cloneInfos;
1949             auto cloneInfoIter = cloneInfos.find(std::to_string(appIndex));
1950             if (cloneInfoIter == cloneInfos.end()) {
1951                 APP_LOGW("Get calling userCloneInfo in bundle(%{public}s) failed, appIndex:%{public}d",
1952                     bundleName.c_str(), appIndex);
1953                 return;
1954             }
1955             int32_t uid = cloneInfoIter->second.uid;
1956             installRes = {
1957                 .type = NotifyType::BUNDLE_CACHE_CLEARED,
1958                 .resultCode = ERR_OK,
1959                 .accessTokenId = innerBundleUserInfo.accessTokenId,
1960                 .uid = uid,
1961                 .appIndex = appIndex,
1962                 .bundleName = bundleName
1963             };
1964             NotifyBundleStatus(installRes);
1965             return;
1966         }
1967         installRes = {
1968             .type = NotifyType::BUNDLE_CACHE_CLEARED,
1969             .resultCode = ERR_OK,
1970             .accessTokenId = innerBundleUserInfo.accessTokenId,
1971             .uid = innerBundleUserInfo.uid,
1972             .bundleName = bundleName
1973         };
1974         NotifyBundleStatus(installRes);
1975     };
1976     ffrt::submit(cleanCache);
1977 }
1978 
CleanBundleDataFiles(const std::string & bundleName,const int userId,const int appIndex,const int callerUid)1979 bool BundleMgrHostImpl::CleanBundleDataFiles(const std::string &bundleName, const int userId,
1980     const int appIndex, const int callerUid)
1981 {
1982     APP_LOGI("start CleanBundleDataFiles, bundleName : %{public}s, userId:%{public}d, appIndex:%{public}d",
1983         bundleName.c_str(), userId, appIndex);
1984     auto dataMgr = GetDataMgrFromService();
1985     if (dataMgr == nullptr) {
1986         APP_LOGE("DataMgr is nullptr");
1987         return false;
1988     }
1989     int32_t callingUid = callerUid;
1990     if (callerUid == -1) {
1991         callingUid =  IPCSkeleton::GetCallingUid();
1992     }
1993     std::string callingBundleName;
1994     (void)dataMgr->GetBundleNameForUid(callingUid, callingBundleName);
1995     if (!BundlePermissionMgr::IsSystemApp()) {
1996         APP_LOGE("ohos.permission.REMOVE_CACHE_FILES system api denied");
1997         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
1998             callingUid, callingBundleName);
1999         return false;
2000     }
2001     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_REMOVECACHEFILE)) {
2002         APP_LOGE("ohos.permission.REMOVE_CACHE_FILES permission denied");
2003         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2004             callingUid, callingBundleName);
2005         return false;
2006     }
2007     if (!BundlePermissionMgr::CheckUserFromShell(userId)) {
2008         LOG_E(BMS_TAG_INSTALLER, "check shell user fail");
2009         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2010             callingUid, callingBundleName);
2011         return false;
2012     }
2013     if (bundleName.empty() || userId < 0) {
2014         APP_LOGE("the  bundleName empty or invalid userid");
2015         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2016             callingUid, callingBundleName);
2017         return false;
2018     }
2019     if (!CheckAppIndex(bundleName, userId, appIndex)) {
2020         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2021             callingUid, callingBundleName);
2022         return false;
2023     }
2024     if (isBrokerServiceExisted_ && !IsBundleExist(bundleName)) {
2025         auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
2026         ErrCode ret = bmsExtensionClient->ClearData(bundleName, userId);
2027         APP_LOGI("ret : %{public}d", ret);
2028         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, ret != ERR_OK,
2029             callingUid, callingBundleName);
2030         return ret == ERR_OK;
2031     }
2032     ApplicationInfo applicationInfo;
2033     if (dataMgr->GetApplicationInfoV9(bundleName,
2034         static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE),
2035         userId, applicationInfo, appIndex) != ERR_OK) {
2036         APP_LOGE("can not get application info of %{public}s", bundleName.c_str());
2037         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2038             callingUid, callingBundleName);
2039         return false;
2040     }
2041 
2042     if (!applicationInfo.userDataClearable) {
2043         APP_LOGE("can not clean dataFiles of %{public}s due to userDataClearable is false", bundleName.c_str());
2044         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2045             callingUid, callingBundleName);
2046         return false;
2047     }
2048     InnerBundleUserInfo innerBundleUserInfo;
2049     if (!GetBundleUserInfo(bundleName, userId, innerBundleUserInfo)) {
2050         APP_LOGE("%{public}s, userId:%{public}d, GetBundleUserInfo failed", bundleName.c_str(), userId);
2051         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2052             callingUid, callingBundleName);
2053         return false;
2054     }
2055     if (BundlePermissionMgr::ClearUserGrantedPermissionState(applicationInfo.accessTokenId)) {
2056         APP_LOGE("%{public}s, ClearUserGrantedPermissionState failed", bundleName.c_str());
2057         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2058             callingUid, callingBundleName);
2059         return false;
2060     }
2061     if (InstalldClient::GetInstance()->CleanBundleDataDirByName(bundleName, userId, appIndex) != ERR_OK) {
2062         APP_LOGE("%{public}s, CleanBundleDataDirByName failed", bundleName.c_str());
2063         EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, true,
2064             callingUid, callingBundleName);
2065         return false;
2066     }
2067     EventReport::SendCleanCacheSysEventWithIndex(bundleName, userId, appIndex, false, false,
2068         callingUid, callingBundleName);
2069     return true;
2070 }
2071 
RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> & bundleStatusCallback)2072 bool BundleMgrHostImpl::RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback)
2073 {
2074     APP_LOGD("start RegisterBundleStatusCallback");
2075     if ((!bundleStatusCallback) || (bundleStatusCallback->GetBundleName().empty())) {
2076         APP_LOGE("the bundleStatusCallback is nullptr or bundleName empty");
2077         return false;
2078     }
2079     // check permission
2080     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::LISTEN_BUNDLE_CHANGE)) {
2081         APP_LOGE("register bundle status callback failed due to lack of permission");
2082         return false;
2083     }
2084 
2085     auto dataMgr = GetDataMgrFromService();
2086     if (dataMgr == nullptr) {
2087         APP_LOGE("DataMgr is nullptr");
2088         return false;
2089     }
2090     return dataMgr->RegisterBundleStatusCallback(bundleStatusCallback);
2091 }
2092 
RegisterBundleEventCallback(const sptr<IBundleEventCallback> & bundleEventCallback)2093 bool BundleMgrHostImpl::RegisterBundleEventCallback(const sptr<IBundleEventCallback> &bundleEventCallback)
2094 {
2095     APP_LOGD("begin to RegisterBundleEventCallback");
2096     if (bundleEventCallback == nullptr) {
2097         APP_LOGE("bundleEventCallback is null");
2098         return false;
2099     }
2100     auto uid = IPCSkeleton::GetCallingUid();
2101     if (uid != Constants::FOUNDATION_UID) {
2102         APP_LOGE("verify calling uid failed, uid : %{public}d", uid);
2103         return false;
2104     }
2105     auto dataMgr = GetDataMgrFromService();
2106     if (dataMgr == nullptr) {
2107         APP_LOGE("DataMgr is nullptr");
2108         return false;
2109     }
2110     return dataMgr->RegisterBundleEventCallback(bundleEventCallback);
2111 }
2112 
UnregisterBundleEventCallback(const sptr<IBundleEventCallback> & bundleEventCallback)2113 bool BundleMgrHostImpl::UnregisterBundleEventCallback(const sptr<IBundleEventCallback> &bundleEventCallback)
2114 {
2115     APP_LOGD("begin to UnregisterBundleEventCallback");
2116     if (bundleEventCallback == nullptr) {
2117         APP_LOGE("bundleEventCallback is null");
2118         return false;
2119     }
2120     auto uid = IPCSkeleton::GetCallingUid();
2121     if (uid != Constants::FOUNDATION_UID) {
2122         APP_LOGE("verify calling uid failed, uid : %{public}d", uid);
2123         return false;
2124     }
2125     auto dataMgr = GetDataMgrFromService();
2126     if (dataMgr == nullptr) {
2127         APP_LOGE("DataMgr is nullptr");
2128         return false;
2129     }
2130     return dataMgr->UnregisterBundleEventCallback(bundleEventCallback);
2131 }
2132 
ClearBundleStatusCallback(const sptr<IBundleStatusCallback> & bundleStatusCallback)2133 bool BundleMgrHostImpl::ClearBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback)
2134 {
2135     APP_LOGD("start ClearBundleStatusCallback");
2136     if (!bundleStatusCallback) {
2137         APP_LOGE("the bundleStatusCallback is nullptr");
2138         return false;
2139     }
2140 
2141     // check permission
2142     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::LISTEN_BUNDLE_CHANGE)) {
2143         APP_LOGE("register bundle status callback failed due to lack of permission");
2144         return false;
2145     }
2146 
2147     auto dataMgr = GetDataMgrFromService();
2148     if (dataMgr == nullptr) {
2149         APP_LOGE("DataMgr is nullptr");
2150         return false;
2151     }
2152     return dataMgr->ClearBundleStatusCallback(bundleStatusCallback);
2153 }
2154 
UnregisterBundleStatusCallback()2155 bool BundleMgrHostImpl::UnregisterBundleStatusCallback()
2156 {
2157     APP_LOGD("start UnregisterBundleStatusCallback");
2158     // check permission
2159     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::LISTEN_BUNDLE_CHANGE)) {
2160         APP_LOGE("register bundle status callback failed due to lack of permission");
2161         return false;
2162     }
2163 
2164     auto dataMgr = GetDataMgrFromService();
2165     if (dataMgr == nullptr) {
2166         APP_LOGE("DataMgr is nullptr");
2167         return false;
2168     }
2169     return dataMgr->UnregisterBundleStatusCallback();
2170 }
2171 
CompileProcessAOT(const std::string & bundleName,const std::string & compileMode,bool isAllBundle,std::vector<std::string> & compileResults)2172 ErrCode BundleMgrHostImpl::CompileProcessAOT(const std::string &bundleName, const std::string &compileMode,
2173     bool isAllBundle, std::vector<std::string> &compileResults)
2174 {
2175     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2176         APP_LOGE("verify permission failed");
2177         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2178     }
2179     return AOTHandler::GetInstance().HandleCompile(bundleName, compileMode, isAllBundle, compileResults);
2180 }
2181 
CompileReset(const std::string & bundleName,bool isAllBundle)2182 ErrCode BundleMgrHostImpl::CompileReset(const std::string &bundleName, bool isAllBundle)
2183 {
2184     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2185         APP_LOGE("verify permission failed");
2186         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2187     }
2188     AOTHandler::GetInstance().HandleResetAOT(bundleName, isAllBundle);
2189     return ERR_OK;
2190 }
2191 
ResetAllAOT()2192 ErrCode BundleMgrHostImpl::ResetAllAOT()
2193 {
2194     int32_t uid = OHOS::IPCSkeleton::GetCallingUid();
2195     if (uid != Constants::CODE_SIGN_UID) {
2196         APP_LOGE("uid: %{public}d not code_sign", uid);
2197         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2198     }
2199     AOTHandler::GetInstance().HandleResetAllAOT();
2200     return ERR_OK;
2201 }
2202 
CopyAp(const std::string & bundleName,bool isAllBundle,std::vector<std::string> & results)2203 ErrCode BundleMgrHostImpl::CopyAp(const std::string &bundleName, bool isAllBundle, std::vector<std::string> &results)
2204 {
2205     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2206         APP_LOGE("verify permission failed");
2207         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2208     }
2209     return AOTHandler::GetInstance().HandleCopyAp(bundleName, isAllBundle, results);
2210 }
2211 
DumpInfos(const DumpFlag flag,const std::string & bundleName,int32_t userId,std::string & result)2212 bool BundleMgrHostImpl::DumpInfos(
2213     const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result)
2214 {
2215     if (!BundlePermissionMgr::CheckUserFromShell(userId)) {
2216         LOG_E(BMS_TAG_INSTALLER, "check shell user fail");
2217         return false;
2218     }
2219     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2220         APP_LOGE("verify permission failed");
2221         return false;
2222     }
2223     bool ret = false;
2224     switch (flag) {
2225         case DumpFlag::DUMP_BUNDLE_LIST: {
2226             ret = DumpAllBundleInfoNames(userId, result);
2227             break;
2228         }
2229         case DumpFlag::DUMP_DEBUG_BUNDLE_LIST: {
2230             ret = DumpDebugBundleInfoNames(userId, result);
2231             break;
2232         }
2233         case DumpFlag::DUMP_BUNDLE_INFO: {
2234             ret = DumpBundleInfo(bundleName, userId, result);
2235             break;
2236         }
2237         case DumpFlag::DUMP_SHORTCUT_INFO: {
2238             ret = DumpShortcutInfo(bundleName, userId, result);
2239             break;
2240         }
2241         case DumpFlag::DUMP_BUNDLE_LABEL: {
2242             ret = GetLabelByBundleName(bundleName, userId, result);
2243             break;
2244         }
2245         case DumpFlag::DUMP_LABEL_LIST: {
2246             ret = GetAllBundleLabel(userId, result);
2247             break;
2248         }
2249         default:
2250             APP_LOGE("dump flag error");
2251             return false;
2252     }
2253     return ret;
2254 }
2255 
DumpAllBundleInfoNames(int32_t userId,std::string & result)2256 bool BundleMgrHostImpl::DumpAllBundleInfoNames(int32_t userId, std::string &result)
2257 {
2258     APP_LOGD("DumpAllBundleInfoNames begin");
2259     if (userId != Constants::ALL_USERID) {
2260         return DumpAllBundleInfoNamesByUserId(userId, result);
2261     }
2262 
2263     auto userIds = GetExistsCommonUserIs();
2264     for (auto userId : userIds) {
2265         DumpAllBundleInfoNamesByUserId(userId, result);
2266     }
2267 
2268     APP_LOGD("DumpAllBundleInfoNames success");
2269     return true;
2270 }
2271 
DumpAllBundleInfoNamesByUserId(int32_t userId,std::string & result)2272 bool BundleMgrHostImpl::DumpAllBundleInfoNamesByUserId(int32_t userId, std::string &result)
2273 {
2274     APP_LOGI("DumpAllBundleInfoNamesByUserId begin");
2275     auto dataMgr = GetDataMgrFromService();
2276     if (dataMgr == nullptr) {
2277         APP_LOGE("DataMgr is nullptr");
2278         return false;
2279     }
2280 
2281     std::vector<std::string> bundleNames;
2282     if (!dataMgr->GetBundleList(bundleNames, userId)) {
2283         APP_LOGE("get bundle list failed by userId(%{public}d)", userId);
2284         return false;
2285     }
2286 
2287     result.append("ID: ");
2288     result.append(std::to_string(userId));
2289     result.append(":\n");
2290     for (const auto &name : bundleNames) {
2291         result.append("\t");
2292         result.append(name);
2293         result.append("\n");
2294     }
2295     APP_LOGI("DumpAllBundleInfoNamesByUserId successfully");
2296     return true;
2297 }
2298 
DumpDebugBundleInfoNames(int32_t userId,std::string & result)2299 bool BundleMgrHostImpl::DumpDebugBundleInfoNames(int32_t userId, std::string &result)
2300 {
2301     APP_LOGD("DumpDebugBundleInfoNames begin");
2302     if (userId != Constants::ALL_USERID) {
2303         return DumpDebugBundleInfoNamesByUserId(userId, result);
2304     }
2305 
2306     auto userIds = GetExistsCommonUserIs();
2307     for (auto userId : userIds) {
2308         DumpDebugBundleInfoNamesByUserId(userId, result);
2309     }
2310 
2311     APP_LOGD("DumpDebugBundleInfoNames success");
2312     return true;
2313 }
2314 
DumpDebugBundleInfoNamesByUserId(int32_t userId,std::string & result)2315 bool BundleMgrHostImpl::DumpDebugBundleInfoNamesByUserId(int32_t userId, std::string &result)
2316 {
2317     APP_LOGD("DumpDebugBundleInfoNamesByUserId begin");
2318     auto dataMgr = GetDataMgrFromService();
2319     if (dataMgr == nullptr) {
2320         APP_LOGE("DataMgr is nullptr");
2321         return false;
2322     }
2323 
2324     std::vector<std::string> bundleNames;
2325     if (!dataMgr->GetDebugBundleList(bundleNames, userId)) {
2326         APP_LOGE("get debug bundle list failed by userId(%{public}d)", userId);
2327         return false;
2328     }
2329 
2330     result.append("ID: ");
2331     result.append(std::to_string(userId));
2332     result.append(":\n");
2333     for (const auto &name : bundleNames) {
2334         result.append("\t");
2335         result.append(name);
2336         result.append("\n");
2337     }
2338     APP_LOGD("DumpDebugBundleInfoNamesByUserId successfully");
2339     return true;
2340 }
2341 
DumpBundleInfo(const std::string & bundleName,int32_t userId,std::string & result)2342 bool BundleMgrHostImpl::DumpBundleInfo(
2343     const std::string &bundleName, int32_t userId, std::string &result)
2344 {
2345     APP_LOGD("DumpBundleInfo begin");
2346     std::vector<InnerBundleUserInfo> innerBundleUserInfos;
2347     InnerBundleUserInfo innerBundleUserInfo;
2348     if (!GetBundleUserInfo(bundleName, userId, innerBundleUserInfo) &&
2349         !GetBundleUserInfo(bundleName, Constants::DEFAULT_USERID, innerBundleUserInfo) &&
2350         !GetBundleUserInfo(bundleName, Constants::U1, innerBundleUserInfo)) {
2351         APP_LOGE("get all userInfos in bundle(%{public}s) failed", bundleName.c_str());
2352         return false;
2353     }
2354     innerBundleUserInfos.emplace_back(innerBundleUserInfo);
2355     std::unordered_map<std::string, PluginBundleInfo> pluginBundleInfos;
2356     if (!GetPluginBundleInfo(bundleName, userId, pluginBundleInfos) &&
2357         !GetPluginBundleInfo(bundleName, Constants::DEFAULT_USERID, pluginBundleInfos) &&
2358         !GetPluginBundleInfo(bundleName, Constants::U1, pluginBundleInfos)) {
2359         APP_LOGE("get plugin info in bundle(%{public}s) failed", bundleName.c_str());
2360     }
2361     BundleInfo bundleInfo;
2362     if (!GetBundleInfo(bundleName,
2363         BundleFlag::GET_BUNDLE_WITH_ABILITIES |
2364         BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION |
2365         BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO |
2366         BundleFlag::GET_BUNDLE_WITH_HASH_VALUE |
2367         BundleFlag::GET_BUNDLE_WITH_MENU |
2368         BundleFlag::GET_BUNDLE_WITH_ROUTER_MAP, bundleInfo, userId)) {
2369         APP_LOGE("get bundleInfo(%{public}s) failed", bundleName.c_str());
2370         return false;
2371     }
2372 
2373     result.append(bundleName);
2374     result.append(":\n");
2375     nlohmann::json jsonObject = bundleInfo;
2376     jsonObject.erase("abilityInfos");
2377     jsonObject.erase("signatureInfo");
2378     jsonObject.erase("extensionAbilityInfo");
2379     jsonObject["applicationInfo"] = bundleInfo.applicationInfo;
2380     jsonObject["userInfo"] = innerBundleUserInfos;
2381     jsonObject["appIdentifier"] = bundleInfo.signatureInfo.appIdentifier;
2382     jsonObject["pluginBundleInfos"] = pluginBundleInfos;
2383     try {
2384         result.append(jsonObject.dump(Constants::DUMP_INDENT));
2385     } catch (const nlohmann::json::type_error &e) {
2386         APP_LOGE("dump[%{public}s] failed: %{public}s", bundleName.c_str(), e.what());
2387         return false;
2388     }
2389     result.append("\n");
2390     APP_LOGD("DumpBundleInfo success with bundleName %{public}s", bundleName.c_str());
2391     return true;
2392 }
2393 
DumpShortcutInfo(const std::string & bundleName,int32_t userId,std::string & result)2394 bool BundleMgrHostImpl::DumpShortcutInfo(
2395     const std::string &bundleName, int32_t userId, std::string &result)
2396 {
2397     APP_LOGD("DumpShortcutInfo begin");
2398     std::vector<ShortcutInfo> shortcutInfos;
2399     if (userId == Constants::ALL_USERID) {
2400         std::vector<InnerBundleUserInfo> innerBundleUserInfos;
2401         if (!GetBundleUserInfos(bundleName, innerBundleUserInfos)) {
2402             APP_LOGE("get all userInfos in bundle(%{public}s) failed", bundleName.c_str());
2403             return false;
2404         }
2405         userId = innerBundleUserInfos.begin()->bundleUserInfo.userId;
2406     }
2407 
2408     if (!GetShortcutInfos(bundleName, userId, shortcutInfos)) {
2409         APP_LOGE("get all shortcut info by bundle(%{public}s) failed", bundleName.c_str());
2410         return false;
2411     }
2412 
2413     result.append("shortcuts");
2414     result.append(":\n");
2415     for (const auto &info : shortcutInfos) {
2416         result.append("\"shortcut\"");
2417         result.append(":\n");
2418         nlohmann::json jsonObject = info;
2419         try {
2420             result.append(jsonObject.dump(Constants::DUMP_INDENT));
2421         } catch (const nlohmann::json::type_error &e) {
2422             APP_LOGE("dump shortcut failed: %{public}s", e.what());
2423             return false;
2424         }
2425         result.append("\n");
2426     }
2427     APP_LOGD("DumpShortcutInfo success with bundleName %{public}s", bundleName.c_str());
2428     return true;
2429 }
2430 
IsModuleRemovable(const std::string & bundleName,const std::string & moduleName,bool & isRemovable)2431 ErrCode BundleMgrHostImpl::IsModuleRemovable(const std::string &bundleName, const std::string &moduleName,
2432     bool &isRemovable)
2433 {
2434     // check permission
2435     if (!BundlePermissionMgr::IsSystemApp()) {
2436         APP_LOGE("non-system app calling system api");
2437         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2438     }
2439     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2440         APP_LOGE("IsModuleRemovable failed due to lack of permission");
2441         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2442     }
2443     auto dataMgr = GetDataMgrFromService();
2444     if (dataMgr == nullptr) {
2445         APP_LOGE("DataMgr is nullptr");
2446         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
2447     }
2448     return dataMgr->IsModuleRemovable(bundleName, moduleName, isRemovable);
2449 }
2450 
SetModuleRemovable(const std::string & bundleName,const std::string & moduleName,bool isEnable)2451 bool BundleMgrHostImpl::SetModuleRemovable(const std::string &bundleName, const std::string &moduleName, bool isEnable)
2452 {
2453     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2454         APP_LOGE("SetModuleRemovable failed due to lack of permission");
2455         return false;
2456     }
2457     auto dataMgr = GetDataMgrFromService();
2458     if (dataMgr == nullptr) {
2459         APP_LOGE("DataMgr is nullptr");
2460         return false;
2461     }
2462     return dataMgr->SetModuleRemovable(bundleName, moduleName, isEnable);
2463 }
2464 
GetModuleUpgradeFlag(const std::string & bundleName,const std::string & moduleName)2465 bool BundleMgrHostImpl::GetModuleUpgradeFlag(const std::string &bundleName, const std::string &moduleName)
2466 {
2467     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_INSTALL_BUNDLE)) {
2468         APP_LOGE("GetModuleUpgradeFlag failed due to lack of permission");
2469         return false;
2470     }
2471     auto dataMgr = GetDataMgrFromService();
2472     if (dataMgr == nullptr) {
2473         APP_LOGE("DataMgr is nullptr");
2474         return false;
2475     }
2476     return dataMgr->GetModuleUpgradeFlag(bundleName, moduleName);
2477 }
2478 
SetModuleUpgradeFlag(const std::string & bundleName,const std::string & moduleName,int32_t upgradeFlag)2479 ErrCode BundleMgrHostImpl::SetModuleUpgradeFlag(const std::string &bundleName,
2480     const std::string &moduleName, int32_t upgradeFlag)
2481 {
2482     // check permission
2483     if (!BundlePermissionMgr::IsSystemApp()) {
2484         APP_LOGE("non-system app calling system api");
2485         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2486     }
2487     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_INSTALL_BUNDLE)) {
2488         APP_LOGE("SetModuleUpgradeFlag failed due to lack of permission");
2489         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2490     }
2491     auto dataMgr = GetDataMgrFromService();
2492     if (dataMgr == nullptr) {
2493         APP_LOGE("DataMgr is nullptr");
2494         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
2495     }
2496     return dataMgr->SetModuleUpgradeFlag(bundleName, moduleName, upgradeFlag);
2497 }
2498 
IsApplicationEnabled(const std::string & bundleName,bool & isEnable)2499 ErrCode BundleMgrHostImpl::IsApplicationEnabled(const std::string &bundleName, bool &isEnable)
2500 {
2501     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
2502     APP_LOGD("start IsApplicationEnabled, bundleName : %{public}s", bundleName.c_str());
2503     if (!BundlePermissionMgr::IsSystemApp() &&
2504         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
2505         APP_LOGE("non-system app calling system api");
2506         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2507     }
2508     auto dataMgr = GetDataMgrFromService();
2509     if (dataMgr == nullptr) {
2510         APP_LOGE("DataMgr is nullptr");
2511         return ERR_APPEXECFWK_SERVICE_NOT_READY;
2512     }
2513     return dataMgr->IsApplicationEnabled(bundleName, 0, isEnable);
2514 }
2515 
IsCloneApplicationEnabled(const std::string & bundleName,int32_t appIndex,bool & isEnable)2516 ErrCode BundleMgrHostImpl::IsCloneApplicationEnabled(const std::string &bundleName, int32_t appIndex, bool &isEnable)
2517 {
2518     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
2519     APP_LOGD("start IsCloneApplicationEnabled, bundleName: %{public}s appIndex: %{public}d",
2520         bundleName.c_str(), appIndex);
2521     if (!BundlePermissionMgr::IsSystemApp()) {
2522         APP_LOGE("non-system app calling system api");
2523         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2524     }
2525     auto dataMgr = GetDataMgrFromService();
2526     if (dataMgr == nullptr) {
2527         APP_LOGE("DataMgr is nullptr");
2528         return ERR_APPEXECFWK_SERVICE_NOT_READY;
2529     }
2530     return dataMgr->IsApplicationEnabled(bundleName, appIndex, isEnable);
2531 }
2532 
SetApplicationEnabled(const std::string & bundleName,bool isEnable,int32_t userId)2533 ErrCode BundleMgrHostImpl::SetApplicationEnabled(const std::string &bundleName, bool isEnable, int32_t userId)
2534 {
2535     BUNDLE_MANAGER_HITRACE_CHAIN_NAME("SetApplicationEnabled", HITRACE_FLAG_INCLUDE_ASYNC);
2536     std::string caller = GetCallerName();
2537     APP_LOGW_NOFUNC("SetApplicationEnabled %{public}s %{public}d %{public}d caller:%{public}s",
2538         bundleName.c_str(), isEnable, userId, caller.c_str());
2539     if (userId == Constants::UNSPECIFIED_USERID) {
2540         userId = BundleUtil::GetUserIdByCallingUid();
2541     }
2542     if (!BundlePermissionMgr::IsSystemApp()) {
2543         APP_LOGE("non-system app calling system api");
2544         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2545     }
2546     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_CHANGE_ABILITY_ENABLED_STATE)) {
2547         APP_LOGE("verify permission failed");
2548         EventReport::SendComponentStateSysEventForException(bundleName, "", userId, isEnable, 0, caller);
2549         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2550     }
2551     if (!BundlePermissionMgr::CheckUserFromShell(userId)) {
2552         LOG_E(BMS_TAG_INSTALLER, "check shell user fail");
2553         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2554     }
2555     if (!CheckCanSetEnable(bundleName)) {
2556         APP_LOGE("bundle in white-list");
2557         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2558     }
2559     auto dataMgr = GetDataMgrFromService();
2560     if (dataMgr == nullptr) {
2561         APP_LOGE("DataMgr is nullptr");
2562         EventReport::SendComponentStateSysEventForException(bundleName, "", userId, isEnable, 0, caller);
2563         return ERR_APPEXECFWK_SERVICE_NOT_READY;
2564     }
2565 
2566     auto ret = dataMgr->SetApplicationEnabled(bundleName, 0, isEnable, caller, userId);
2567     if (ret != ERR_OK) {
2568         APP_LOGE("Set application(%{public}s) enabled value faile", bundleName.c_str());
2569         EventReport::SendComponentStateSysEventForException(bundleName, "", userId, isEnable, 0, caller);
2570         return ret;
2571     }
2572 
2573     EventReport::SendComponentStateSysEvent(bundleName, "", userId, isEnable, 0, caller);
2574     InnerBundleUserInfo innerBundleUserInfo;
2575     if (!GetBundleUserInfo(bundleName, userId, innerBundleUserInfo)) {
2576         APP_LOGE("Get calling userInfo in bundle(%{public}s) failed", bundleName.c_str());
2577         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2578     }
2579 
2580     NotifyBundleEvents installRes = {
2581         .type = NotifyType::APPLICATION_ENABLE,
2582         .resultCode = ERR_OK,
2583         .accessTokenId = innerBundleUserInfo.accessTokenId,
2584         .uid = innerBundleUserInfo.uid,
2585         .bundleName = bundleName
2586     };
2587     std::string identity = IPCSkeleton::ResetCallingIdentity();
2588     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
2589     commonEventMgr->NotifyBundleStatus(installRes, dataMgr);
2590     IPCSkeleton::SetCallingIdentity(identity);
2591     return ERR_OK;
2592 }
2593 
SetCloneApplicationEnabled(const std::string & bundleName,int32_t appIndex,bool isEnable,int32_t userId)2594 ErrCode BundleMgrHostImpl::SetCloneApplicationEnabled(
2595     const std::string &bundleName, int32_t appIndex, bool isEnable, int32_t userId)
2596 {
2597     BUNDLE_MANAGER_HITRACE_CHAIN_NAME("SetCloneApplicationEnabled", HITRACE_FLAG_INCLUDE_ASYNC);
2598     std::string caller = GetCallerName();
2599     APP_LOGW_NOFUNC("SetCloneApplicationEnabled param %{public}s %{public}d %{public}d %{public}d caller:%{public}s",
2600         bundleName.c_str(), appIndex, isEnable, userId, caller.c_str());
2601     if (!BundlePermissionMgr::IsSystemApp()) {
2602         APP_LOGE("non-system app calling system api");
2603         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2604     }
2605     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_CHANGE_ABILITY_ENABLED_STATE)) {
2606         APP_LOGE("verify permission failed");
2607         EventReport::SendComponentStateSysEventForException(bundleName, "", userId, isEnable, appIndex, caller);
2608         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2609     }
2610     if (userId == Constants::UNSPECIFIED_USERID) {
2611         userId = BundleUtil::GetUserIdByCallingUid();
2612     }
2613     APP_LOGD("verify permission success, begin to SetCloneApplicationEnabled");
2614     auto dataMgr = GetDataMgrFromService();
2615     if (dataMgr == nullptr) {
2616         APP_LOGE("DataMgr is nullptr");
2617         EventReport::SendComponentStateSysEventForException(bundleName, "", userId, isEnable, appIndex, caller);
2618         return ERR_APPEXECFWK_SERVICE_NOT_READY;
2619     }
2620     auto ret = dataMgr->SetApplicationEnabled(bundleName, appIndex, isEnable, caller, userId);
2621     if (ret != ERR_OK) {
2622         APP_LOGE("Set application(%{public}s) enabled value fail", bundleName.c_str());
2623         EventReport::SendComponentStateSysEventForException(bundleName, "", userId, isEnable, appIndex, caller);
2624         return ret;
2625     }
2626 
2627     EventReport::SendComponentStateSysEvent(bundleName, "", userId, isEnable, appIndex, caller);
2628     InnerBundleUserInfo innerBundleUserInfo;
2629     if (!GetBundleUserInfo(bundleName, userId, innerBundleUserInfo)) {
2630         APP_LOGE("Get calling userInfo in bundle(%{public}s) failed", bundleName.c_str());
2631         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2632     }
2633 
2634     NotifyBundleEvents installRes = {
2635         .type = NotifyType::APPLICATION_ENABLE,
2636         .resultCode = ERR_OK,
2637         .accessTokenId = innerBundleUserInfo.accessTokenId,
2638         .uid = innerBundleUserInfo.uid,
2639         .appIndex = appIndex,
2640         .bundleName = bundleName
2641     };
2642     NotifyBundleStatus(installRes);
2643     APP_LOGD("SetCloneApplicationEnabled finish");
2644     return ERR_OK;
2645 }
2646 
IsAbilityEnabled(const AbilityInfo & abilityInfo,bool & isEnable)2647 ErrCode BundleMgrHostImpl::IsAbilityEnabled(const AbilityInfo &abilityInfo, bool &isEnable)
2648 {
2649     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
2650     APP_LOGD("start IsAbilityEnabled");
2651     if (!BundlePermissionMgr::IsSystemApp() &&
2652         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
2653         APP_LOGE("non-system app calling system api");
2654         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2655     }
2656     auto dataMgr = GetDataMgrFromService();
2657     if (dataMgr == nullptr) {
2658         APP_LOGE("DataMgr is nullptr");
2659         return ERR_APPEXECFWK_SERVICE_NOT_READY;
2660     }
2661     return dataMgr->IsAbilityEnabled(abilityInfo, 0, isEnable);
2662 }
2663 
IsCloneAbilityEnabled(const AbilityInfo & abilityInfo,int32_t appIndex,bool & isEnable)2664 ErrCode BundleMgrHostImpl::IsCloneAbilityEnabled(const AbilityInfo &abilityInfo, int32_t appIndex, bool &isEnable)
2665 {
2666     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
2667     APP_LOGD("start IsCloneAbilityEnabled");
2668     if (!BundlePermissionMgr::IsSystemApp()) {
2669         APP_LOGE("non-system app calling system api");
2670         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2671     }
2672     auto dataMgr = GetDataMgrFromService();
2673     if (dataMgr == nullptr) {
2674         APP_LOGE("DataMgr is nullptr");
2675         return ERR_APPEXECFWK_SERVICE_NOT_READY;
2676     }
2677     return dataMgr->IsAbilityEnabled(abilityInfo, appIndex, isEnable);
2678 }
2679 
SetAbilityEnabled(const AbilityInfo & abilityInfo,bool isEnabled,int32_t userId)2680 ErrCode BundleMgrHostImpl::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled, int32_t userId)
2681 {
2682     BUNDLE_MANAGER_HITRACE_CHAIN_NAME("SetAbilityEnabled", HITRACE_FLAG_INCLUDE_ASYNC);
2683     std::string caller = GetCallerName();
2684     APP_LOGW_NOFUNC("SetAbilityEnabled %{public}s %{public}d %{public}d caller:%{public}s",
2685         abilityInfo.name.c_str(), isEnabled, userId, caller.c_str());
2686     if (userId == Constants::UNSPECIFIED_USERID) {
2687         userId = BundleUtil::GetUserIdByCallingUid();
2688     }
2689     if (!BundlePermissionMgr::IsSystemApp()) {
2690         APP_LOGE("non-system app calling system api");
2691         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2692     }
2693     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_CHANGE_ABILITY_ENABLED_STATE)) {
2694         APP_LOGE("verify permission failed");
2695         EventReport::SendComponentStateSysEventForException(abilityInfo.bundleName, abilityInfo.name,
2696             userId, isEnabled, 0, caller);
2697         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2698     }
2699     if (!BundlePermissionMgr::CheckUserFromShell(userId)) {
2700         LOG_E(BMS_TAG_INSTALLER, "check shell user fail");
2701         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2702     }
2703     if (!CheckCanSetEnable(abilityInfo.bundleName)) {
2704         APP_LOGE("bundle in white-list");
2705         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2706     }
2707     auto dataMgr = GetDataMgrFromService();
2708     if (dataMgr == nullptr) {
2709         APP_LOGE("DataMgr is nullptr");
2710         EventReport::SendComponentStateSysEventForException(abilityInfo.bundleName, abilityInfo.name,
2711             userId, isEnabled, 0, caller);
2712         return ERR_APPEXECFWK_SERVICE_NOT_READY;
2713     }
2714     auto ret = dataMgr->SetAbilityEnabled(abilityInfo, 0, isEnabled, userId);
2715     if (ret != ERR_OK) {
2716         APP_LOGE("Set ability(%{public}s) enabled value failed", abilityInfo.bundleName.c_str());
2717         EventReport::SendComponentStateSysEventForException(abilityInfo.bundleName, abilityInfo.name,
2718             userId, isEnabled, 0, caller);
2719         return ret;
2720     }
2721     EventReport::SendComponentStateSysEvent(abilityInfo.bundleName, abilityInfo.name, userId, isEnabled, 0, caller);
2722     InnerBundleUserInfo innerBundleUserInfo;
2723     if (!GetBundleUserInfo(abilityInfo.bundleName, userId, innerBundleUserInfo)) {
2724         APP_LOGE("Get calling userInfo in bundle(%{public}s) failed", abilityInfo.bundleName.c_str());
2725         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2726     }
2727     NotifyBundleEvents installRes = {
2728         .type = NotifyType::APPLICATION_ENABLE,
2729         .resultCode = ERR_OK,
2730         .accessTokenId = innerBundleUserInfo.accessTokenId,
2731         .uid = innerBundleUserInfo.uid,
2732         .bundleName = abilityInfo.bundleName,
2733         .abilityName = abilityInfo.name
2734     };
2735     NotifyBundleStatus(installRes);
2736     return ERR_OK;
2737 }
2738 
SetCloneAbilityEnabled(const AbilityInfo & abilityInfo,int32_t appIndex,bool isEnabled,int32_t userId)2739 ErrCode BundleMgrHostImpl::SetCloneAbilityEnabled(const AbilityInfo &abilityInfo,
2740     int32_t appIndex, bool isEnabled, int32_t userId)
2741 {
2742     BUNDLE_MANAGER_HITRACE_CHAIN_NAME("SetCloneAbilityEnabled", HITRACE_FLAG_INCLUDE_ASYNC);
2743     std::string caller = GetCallerName();
2744     APP_LOGW_NOFUNC("SetCloneAbilityEnabled %{public}s %{public}d %{public}d %{public}d caller:%{public}s",
2745         abilityInfo.name.c_str(), appIndex, isEnabled, userId, caller.c_str());
2746     if (!BundlePermissionMgr::IsSystemApp()) {
2747         APP_LOGE("non-system app calling system api");
2748         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2749     }
2750     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_CHANGE_ABILITY_ENABLED_STATE)) {
2751         APP_LOGE("verify permission failed");
2752         EventReport::SendComponentStateSysEventForException(abilityInfo.bundleName, abilityInfo.name,
2753             userId, isEnabled, appIndex, caller);
2754         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2755     }
2756     if (userId == Constants::UNSPECIFIED_USERID) {
2757         userId = BundleUtil::GetUserIdByCallingUid();
2758     }
2759     auto dataMgr = GetDataMgrFromService();
2760     if (dataMgr == nullptr) {
2761         APP_LOGE("DataMgr is nullptr");
2762         EventReport::SendComponentStateSysEventForException(abilityInfo.bundleName, abilityInfo.name,
2763             userId, isEnabled, appIndex, caller);
2764         return ERR_APPEXECFWK_SERVICE_NOT_READY;
2765     }
2766     auto ret = dataMgr->SetAbilityEnabled(abilityInfo, appIndex, isEnabled, userId);
2767     if (ret != ERR_OK) {
2768         APP_LOGE("Set ability(%{public}s) enabled value failed", abilityInfo.bundleName.c_str());
2769         EventReport::SendComponentStateSysEventForException(abilityInfo.bundleName, abilityInfo.name,
2770             userId, isEnabled, appIndex, caller);
2771         return ret;
2772     }
2773     EventReport::SendComponentStateSysEvent(
2774         abilityInfo.bundleName, abilityInfo.name, userId, isEnabled, appIndex, caller);
2775     InnerBundleUserInfo innerBundleUserInfo;
2776     if (!GetBundleUserInfo(abilityInfo.bundleName, userId, innerBundleUserInfo)) {
2777         APP_LOGE("Get calling userInfo in bundle(%{public}s) failed", abilityInfo.bundleName.c_str());
2778         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
2779     }
2780     NotifyBundleEvents installRes = {
2781         .type = NotifyType::APPLICATION_ENABLE,
2782         .resultCode = ERR_OK,
2783         .accessTokenId = innerBundleUserInfo.accessTokenId,
2784         .uid = innerBundleUserInfo.uid,
2785         .appIndex = appIndex,
2786         .bundleName = abilityInfo.bundleName,
2787         .abilityName = abilityInfo.name
2788     };
2789     NotifyBundleStatus(installRes);
2790     return ERR_OK;
2791 }
2792 
GetBundleInstaller()2793 sptr<IBundleInstaller> BundleMgrHostImpl::GetBundleInstaller()
2794 {
2795     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
2796     APP_LOGD("start GetBundleInstaller");
2797     if (!VerifySystemApi()) {
2798         APP_LOGE("non-system app calling system api");
2799         return nullptr;
2800     }
2801     return DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleInstaller();
2802 }
2803 
GetBundleUserMgr()2804 sptr<IBundleUserMgr> BundleMgrHostImpl::GetBundleUserMgr()
2805 {
2806     int32_t callingUid = IPCSkeleton::GetCallingUid();
2807     if (callingUid != ServiceConstants::ACCOUNT_UID) {
2808         APP_LOGE("invalid calling uid %{public}d to GetbundleUserMgr", callingUid);
2809         return nullptr;
2810     }
2811     return DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleUserMgr();
2812 }
2813 
GetVerifyManager()2814 sptr<IVerifyManager> BundleMgrHostImpl::GetVerifyManager()
2815 {
2816     return DelayedSingleton<BundleMgrService>::GetInstance()->GetVerifyManager();
2817 }
2818 
GetExtendResourceManager()2819 sptr<IExtendResourceManager> BundleMgrHostImpl::GetExtendResourceManager()
2820 {
2821     return DelayedSingleton<BundleMgrService>::GetInstance()->GetExtendResourceManager();
2822 }
2823 
GetAllFormsInfo(std::vector<FormInfo> & formInfos)2824 bool BundleMgrHostImpl::GetAllFormsInfo(std::vector<FormInfo> &formInfos)
2825 {
2826     APP_LOGD("start GetAllFormsInfo");
2827     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2828         APP_LOGE("verify permission failed");
2829         return false;
2830     }
2831     auto dataMgr = GetDataMgrFromService();
2832     if (dataMgr == nullptr) {
2833         APP_LOGE("DataMgr is nullptr");
2834         return false;
2835     }
2836     return dataMgr->GetAllFormsInfo(formInfos);
2837 }
2838 
GetFormsInfoByApp(const std::string & bundleName,std::vector<FormInfo> & formInfos)2839 bool BundleMgrHostImpl::GetFormsInfoByApp(const std::string &bundleName, std::vector<FormInfo> &formInfos)
2840 {
2841     APP_LOGD("start GetFormsInfoByApp, bundleName : %{public}s", bundleName.c_str());
2842     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
2843         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
2844         APP_LOGE("verify permission failed");
2845         return false;
2846     }
2847     auto dataMgr = GetDataMgrFromService();
2848     if (dataMgr == nullptr) {
2849         APP_LOGE("DataMgr is nullptr");
2850         return false;
2851     }
2852     return dataMgr->GetFormsInfoByApp(bundleName, formInfos);
2853 }
2854 
GetFormsInfoByModule(const std::string & bundleName,const std::string & moduleName,std::vector<FormInfo> & formInfos)2855 bool BundleMgrHostImpl::GetFormsInfoByModule(
2856     const std::string &bundleName, const std::string &moduleName, std::vector<FormInfo> &formInfos)
2857 {
2858     APP_LOGD("start GetFormsInfoByModule, bundleName : %{public}s, moduleName : %{public}s",
2859         bundleName.c_str(), moduleName.c_str());
2860     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
2861         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
2862         APP_LOGE("verify permission failed");
2863         return false;
2864     }
2865     auto dataMgr = GetDataMgrFromService();
2866     if (dataMgr == nullptr) {
2867         APP_LOGE("DataMgr is nullptr");
2868         return false;
2869     }
2870     return dataMgr->GetFormsInfoByModule(bundleName, moduleName, formInfos);
2871 }
2872 
GetShortcutInfos(const std::string & bundleName,std::vector<ShortcutInfo> & shortcutInfos)2873 bool BundleMgrHostImpl::GetShortcutInfos(
2874     const std::string &bundleName, std::vector<ShortcutInfo> &shortcutInfos)
2875 {
2876     int32_t currentUserId = AccountHelper::GetCurrentActiveUserId();
2877     APP_LOGD("current active userId is %{public}d", currentUserId);
2878     if (currentUserId == Constants::INVALID_USERID) {
2879         APP_LOGW("current userId is invalid");
2880         return false;
2881     }
2882 
2883     return GetShortcutInfos(bundleName, currentUserId, shortcutInfos);
2884 }
2885 
GetShortcutInfos(const std::string & bundleName,int32_t userId,std::vector<ShortcutInfo> & shortcutInfos)2886 bool BundleMgrHostImpl::GetShortcutInfos(
2887     const std::string &bundleName, int32_t userId, std::vector<ShortcutInfo> &shortcutInfos)
2888 {
2889     APP_LOGD("start GetShortcutInfos, bundleName : %{public}s, userId : %{public}d", bundleName.c_str(), userId);
2890     // API9 need to be system app otherwise return empty data
2891     if (!BundlePermissionMgr::IsSystemApp() &&
2892         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
2893         APP_LOGD("non-system app calling system api");
2894         return true;
2895     }
2896     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2897         APP_LOGE("verify permission failed");
2898         return false;
2899     }
2900     APP_LOGD("verify permission success, begin to GetShortcutInfos");
2901     auto dataMgr = GetDataMgrFromService();
2902     if (dataMgr == nullptr) {
2903         APP_LOGE("DataMgr is nullptr");
2904         return false;
2905     }
2906     return dataMgr->GetShortcutInfos(bundleName, userId, shortcutInfos);
2907 }
2908 
GetShortcutInfoV9(const std::string & bundleName,std::vector<ShortcutInfo> & shortcutInfos,int32_t userId)2909 ErrCode BundleMgrHostImpl::GetShortcutInfoV9(const std::string &bundleName,
2910     std::vector<ShortcutInfo> &shortcutInfos, int32_t userId)
2911 {
2912     if (!BundlePermissionMgr::IsSystemApp()) {
2913         APP_LOGE("non-system app calling system api");
2914         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2915     }
2916     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
2917         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
2918         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
2919         APP_LOGE("verify permission failed");
2920         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2921     }
2922     auto dataMgr = GetDataMgrFromService();
2923     if (dataMgr == nullptr) {
2924         APP_LOGE("DataMgr is nullptr");
2925         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
2926     }
2927     return dataMgr->GetShortcutInfoV9(bundleName, userId, shortcutInfos);
2928 }
2929 
GetShortcutInfoByAppIndex(const std::string & bundleName,const int32_t appIndex,std::vector<ShortcutInfo> & shortcutInfos)2930 ErrCode BundleMgrHostImpl::GetShortcutInfoByAppIndex(const std::string &bundleName, const int32_t appIndex,
2931     std::vector<ShortcutInfo> &shortcutInfos)
2932 {
2933     if (!BundlePermissionMgr::IsSystemApp()) {
2934         APP_LOGE("non-system app calling system api");
2935         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
2936     }
2937     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
2938         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
2939         APP_LOGE("verify permission failed");
2940         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
2941     }
2942     auto dataMgr = GetDataMgrFromService();
2943     if (dataMgr == nullptr) {
2944         APP_LOGE("DataMgr is nullptr");
2945         return ERR_APPEXECFWK_NULL_PTR;
2946     }
2947     return dataMgr->GetShortcutInfoByAppIndex(bundleName, appIndex, shortcutInfos);
2948 }
2949 
GetAllCommonEventInfo(const std::string & eventKey,std::vector<CommonEventInfo> & commonEventInfos)2950 bool BundleMgrHostImpl::GetAllCommonEventInfo(const std::string &eventKey,
2951     std::vector<CommonEventInfo> &commonEventInfos)
2952 {
2953     APP_LOGD("start GetAllCommonEventInfo, eventKey : %{public}s", eventKey.c_str());
2954     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
2955         APP_LOGE("verify permission failed");
2956         return false;
2957     }
2958     auto dataMgr = GetDataMgrFromService();
2959     if (dataMgr == nullptr) {
2960         APP_LOGE("DataMgr is nullptr");
2961         return false;
2962     }
2963     return dataMgr->GetAllCommonEventInfo(eventKey, commonEventInfos);
2964 }
2965 
GetDistributedBundleInfo(const std::string & networkId,const std::string & bundleName,DistributedBundleInfo & distributedBundleInfo)2966 bool BundleMgrHostImpl::GetDistributedBundleInfo(const std::string &networkId, const std::string &bundleName,
2967     DistributedBundleInfo &distributedBundleInfo)
2968 {
2969     APP_LOGD("start GetDistributedBundleInfo, bundleName : %{public}s", bundleName.c_str());
2970 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
2971     if (!BundlePermissionMgr::IsSystemApp()) {
2972         APP_LOGE("Non-system app calling system api");
2973         return false;
2974     }
2975     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
2976         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
2977         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
2978         APP_LOGE("verify permission failed");
2979         return false;
2980     }
2981     auto distributedBundleMgr = GetDistributedBundleMgrService();
2982     if (distributedBundleMgr == nullptr) {
2983         APP_LOGE("DistributedBundleMgrService is nullptr");
2984         return false;
2985     }
2986     return distributedBundleMgr->GetDistributedBundleInfo(networkId, bundleName, distributedBundleInfo);
2987 #else
2988     APP_LOGW("DISTRIBUTED_BUNDLE_FRAMEWORK is false");
2989     return false;
2990 #endif
2991 }
2992 
QueryExtensionAbilityInfos(const Want & want,const int32_t & flag,const int32_t & userId,std::vector<ExtensionAbilityInfo> & extensionInfos)2993 bool BundleMgrHostImpl::QueryExtensionAbilityInfos(const Want &want, const int32_t &flag, const int32_t &userId,
2994     std::vector<ExtensionAbilityInfo> &extensionInfos)
2995 {
2996     LOG_D(BMS_TAG_QUERY, "QueryExtensionAbilityInfos without type begin");
2997     // API9 need to be system app, otherwise return empty data
2998     if (!BundlePermissionMgr::IsSystemApp() &&
2999         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
3000         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
3001         return true;
3002     }
3003     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3004         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3005         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
3006         LOG_E(BMS_TAG_QUERY, "verify permission failed");
3007         return false;
3008     }
3009     LOG_D(BMS_TAG_QUERY, "want uri is %{private}s", want.GetUriString().c_str());
3010     auto dataMgr = GetDataMgrFromService();
3011     if (dataMgr == nullptr) {
3012         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
3013         return false;
3014     }
3015     (void)dataMgr->QueryExtensionAbilityInfos(want, flag, userId, extensionInfos);
3016     dataMgr->QueryAllCloneExtensionInfos(want, flag, userId, extensionInfos);
3017     if (extensionInfos.empty()) {
3018         LOG_W(BMS_TAG_QUERY, "no valid extension info can be inquired");
3019         return false;
3020     }
3021     return true;
3022 }
3023 
QueryExtensionAbilityInfosV9(const Want & want,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos)3024 ErrCode BundleMgrHostImpl::QueryExtensionAbilityInfosV9(const Want &want, int32_t flags, int32_t userId,
3025     std::vector<ExtensionAbilityInfo> &extensionInfos)
3026 {
3027     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
3028     LOG_D(BMS_TAG_QUERY, "QueryExtensionAbilityInfosV9 without type begin");
3029     if (!BundlePermissionMgr::IsSystemApp()) {
3030         LOG_E(BMS_TAG_QUERY, "non-system app calling system api");
3031         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3032     }
3033     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3034         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3035         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
3036         LOG_E(BMS_TAG_QUERY, "verify permission failed");
3037         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3038     }
3039     LOG_D(BMS_TAG_QUERY, "want uri is %{private}s", want.GetUriString().c_str());
3040     auto dataMgr = GetDataMgrFromService();
3041     if (dataMgr == nullptr) {
3042         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
3043         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
3044     }
3045     ErrCode ret = dataMgr->QueryExtensionAbilityInfosV9(want, flags, userId, extensionInfos);
3046     dataMgr->QueryAllCloneExtensionInfosV9(want, flags, userId, extensionInfos);
3047 
3048     if (extensionInfos.empty()) {
3049         if (ret != ERR_OK) {
3050             LOG_E(BMS_TAG_QUERY, "query extension ability fail, %{public}d", ret);
3051             return ret;
3052         }
3053         LOG_W(BMS_TAG_QUERY, "no valid extension info can be inquired");
3054         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3055     }
3056     return ERR_OK;
3057 }
3058 
QueryExtensionAbilityInfos(const Want & want,const ExtensionAbilityType & extensionType,const int32_t & flag,const int32_t & userId,std::vector<ExtensionAbilityInfo> & extensionInfos)3059 bool BundleMgrHostImpl::QueryExtensionAbilityInfos(const Want &want, const ExtensionAbilityType &extensionType,
3060     const int32_t &flag, const int32_t &userId, std::vector<ExtensionAbilityInfo> &extensionInfos)
3061 {
3062     LOG_D(BMS_TAG_QUERY, "QueryExtensionAbilityInfos begin");
3063     // API9 need to be system app, otherwise return empty data
3064     if (!BundlePermissionMgr::IsSystemApp() &&
3065         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
3066         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
3067         return true;
3068     }
3069     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3070         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3071         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
3072         LOG_E(BMS_TAG_QUERY, "verify permission failed");
3073         return false;
3074     }
3075     auto dataMgr = GetDataMgrFromService();
3076     if (dataMgr == nullptr) {
3077         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
3078         return false;
3079     }
3080     std::vector<ExtensionAbilityInfo> infos;
3081     (void)dataMgr->QueryExtensionAbilityInfos(want, flag, userId, infos);
3082     dataMgr->QueryAllCloneExtensionInfos(want, flag, userId, infos);
3083 
3084     for_each(infos.begin(), infos.end(), [&extensionType, &extensionInfos](const auto &info)->decltype(auto) {
3085         LOG_D(BMS_TAG_QUERY, "QueryExtensionAbilityInfos extensionType:%{public}d info.type:%{public}d",
3086             static_cast<int32_t>(extensionType), static_cast<int32_t>(info.type));
3087         if (extensionType == info.type) {
3088             extensionInfos.emplace_back(info);
3089         }
3090     });
3091     if (extensionInfos.empty()) {
3092         LOG_W(BMS_TAG_QUERY, "no valid extension info can be inquired");
3093         return false;
3094     }
3095     return true;
3096 }
3097 
QueryExtensionAbilityInfosV9(const Want & want,const ExtensionAbilityType & extensionType,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos)3098 ErrCode BundleMgrHostImpl::QueryExtensionAbilityInfosV9(const Want &want, const ExtensionAbilityType &extensionType,
3099     int32_t flags, int32_t userId, std::vector<ExtensionAbilityInfo> &extensionInfos)
3100 {
3101     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
3102     LOG_D(BMS_TAG_QUERY, "QueryExtensionAbilityInfosV9 begin");
3103     if (!BundlePermissionMgr::IsSystemApp()) {
3104         LOG_E(BMS_TAG_QUERY, "non-system app calling system api");
3105         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3106     }
3107     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3108         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3109         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
3110         LOG_E(BMS_TAG_QUERY, "verify permission failed");
3111         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3112     }
3113     auto dataMgr = GetDataMgrFromService();
3114     if (dataMgr == nullptr) {
3115         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
3116         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
3117     }
3118     std::vector<ExtensionAbilityInfo> infos;
3119     ErrCode ret = dataMgr->QueryExtensionAbilityInfosV9(want, flags, userId, infos);
3120     dataMgr->QueryAllCloneExtensionInfosV9(want, flags, userId, infos);
3121     for_each(infos.begin(), infos.end(), [&extensionType, &extensionInfos](const auto &info)->decltype(auto) {
3122         LOG_D(BMS_TAG_QUERY, "QueryExtensionAbilityInfosV9 extensionType:%{public}d info.type:%{public}d",
3123             static_cast<int32_t>(extensionType), static_cast<int32_t>(info.type));
3124         if (extensionType == info.type) {
3125             extensionInfos.emplace_back(info);
3126         }
3127     });
3128     if (extensionInfos.empty()) {
3129         if (ret != ERR_OK) {
3130             LOG_E(BMS_TAG_QUERY, "query extension ability fail, %{public}d", ret);
3131             return ret;
3132         }
3133         LOG_W(BMS_TAG_QUERY, "no valid extension info can be inquired");
3134         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
3135     }
3136     return ERR_OK;
3137 }
3138 
QueryExtensionAbilityInfos(const ExtensionAbilityType & extensionType,const int32_t & userId,std::vector<ExtensionAbilityInfo> & extensionInfos)3139 bool BundleMgrHostImpl::QueryExtensionAbilityInfos(const ExtensionAbilityType &extensionType, const int32_t &userId,
3140     std::vector<ExtensionAbilityInfo> &extensionInfos)
3141 {
3142     LOG_D(BMS_TAG_QUERY, "QueryExtensionAbilityInfos with type begin");
3143     // API9 need to be system app, otherwise return empty data
3144     if (!BundlePermissionMgr::IsSystemApp() &&
3145         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
3146         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
3147         return true;
3148     }
3149     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3150         Constants::PERMISSION_GET_BUNDLE_INFO})) {
3151         LOG_E(BMS_TAG_QUERY, "verify permission failed");
3152         return false;
3153     }
3154     auto dataMgr = GetDataMgrFromService();
3155     if (dataMgr == nullptr) {
3156         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
3157         return false;
3158     }
3159     bool ret = dataMgr->QueryExtensionAbilityInfos(extensionType, userId, extensionInfos);
3160     if (!ret) {
3161         LOG_E(BMS_TAG_QUERY, "QueryExtensionAbilityInfos is failed, errno: %{public}d", ret);
3162         return false;
3163     }
3164 
3165     if (extensionInfos.empty()) {
3166         LOG_W(BMS_TAG_QUERY, "no valid extension info can be inquired");
3167         return false;
3168     }
3169     return true;
3170 }
3171 
GetDataMgrFromService()3172 const std::shared_ptr<BundleDataMgr> BundleMgrHostImpl::GetDataMgrFromService()
3173 {
3174     return DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
3175 }
3176 
3177 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
GetDistributedBundleMgrService()3178 const OHOS::sptr<IDistributedBms> BundleMgrHostImpl::GetDistributedBundleMgrService()
3179 {
3180     auto saMgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
3181     if (saMgr == nullptr) {
3182         APP_LOGE("saMgr is nullptr");
3183         return nullptr;
3184     }
3185     OHOS::sptr<OHOS::IRemoteObject> remoteObject =
3186         saMgr->CheckSystemAbility(OHOS::DISTRIBUTED_BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
3187     return OHOS::iface_cast<IDistributedBms>(remoteObject);
3188 }
3189 #endif
3190 
3191 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
GetConnectAbilityMgrFromService()3192 const std::shared_ptr<BundleConnectAbilityMgr> BundleMgrHostImpl::GetConnectAbilityMgrFromService()
3193 {
3194     int32_t currentUserId = AccountHelper::GetCurrentActiveUserId();
3195     return DelayedSingleton<BundleMgrService>::GetInstance()->GetConnectAbility(currentUserId);
3196 }
3197 #endif
3198 
GetExistsCommonUserIs()3199 std::set<int32_t> BundleMgrHostImpl::GetExistsCommonUserIs()
3200 {
3201     std::set<int32_t> userIds;
3202     auto dataMgr = GetDataMgrFromService();
3203     if (dataMgr == nullptr) {
3204         APP_LOGE("Get dataMgr shared_ptr nullptr");
3205         return userIds;
3206     }
3207 
3208     for (auto userId : dataMgr->GetAllUser()) {
3209         if (userId >= Constants::START_USERID) {
3210             userIds.insert(userId);
3211         }
3212     }
3213     return userIds;
3214 }
3215 
GetAppPrivilegeLevel(const std::string & bundleName,int32_t userId)3216 std::string BundleMgrHostImpl::GetAppPrivilegeLevel(const std::string &bundleName, int32_t userId)
3217 {
3218     APP_LOGD("start GetAppPrivilegeLevel");
3219     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
3220         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3221         APP_LOGE("verify permission failed");
3222         return Constants::EMPTY_STRING;
3223     }
3224     auto dataMgr = GetDataMgrFromService();
3225     if (dataMgr == nullptr) {
3226         APP_LOGE("DataMgr is nullptr");
3227         return Constants::EMPTY_STRING;
3228     }
3229     return dataMgr->GetAppPrivilegeLevel(bundleName, userId);
3230 }
3231 
VerifyCallingPermission(const std::string & permission)3232 bool BundleMgrHostImpl::VerifyCallingPermission(const std::string &permission)
3233 {
3234     APP_LOGD("VerifyCallingPermission begin");
3235     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_VERIFY_CALLING_PERMISSION);
3236     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
3237     return BundlePermissionMgr::VerifyCallingPermissionForAll(permission);
3238 }
3239 
QueryExtensionAbilityInfoByUri(const std::string & uri,int32_t userId,ExtensionAbilityInfo & extensionAbilityInfo)3240 bool BundleMgrHostImpl::QueryExtensionAbilityInfoByUri(const std::string &uri, int32_t userId,
3241     ExtensionAbilityInfo &extensionAbilityInfo)
3242 {
3243     LOG_I(BMS_TAG_QUERY, "uri:%{private}s -u %{public}d", uri.c_str(), userId);
3244     // API9 need to be system app, otherwise return empty data
3245     if (!BundlePermissionMgr::IsSystemApp() &&
3246         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
3247         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
3248         return true;
3249     }
3250     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3251         Constants::PERMISSION_GET_BUNDLE_INFO})) {
3252         LOG_E(BMS_TAG_QUERY, "verify query permission failed");
3253         return false;
3254     }
3255     auto dataMgr = GetDataMgrFromService();
3256     if (dataMgr == nullptr) {
3257         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
3258         return false;
3259     }
3260     return dataMgr->QueryExtensionAbilityInfoByUri(uri, userId, extensionAbilityInfo);
3261 }
3262 
GetAppIdByBundleName(const std::string & bundleName,const int userId)3263 std::string BundleMgrHostImpl::GetAppIdByBundleName(const std::string &bundleName, const int userId)
3264 {
3265     APP_LOGD("bundleName : %{public}s, userId : %{public}d", bundleName.c_str(), userId);
3266     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
3267         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3268         APP_LOGE("verify query permission failed");
3269         return Constants::EMPTY_STRING;
3270     }
3271     auto dataMgr = GetDataMgrFromService();
3272     if (dataMgr == nullptr) {
3273         APP_LOGE("DataMgr is nullptr");
3274         return Constants::EMPTY_STRING;
3275     }
3276     int32_t requestUserId = dataMgr->GetUserId(userId);
3277     if (requestUserId == Constants::INVALID_USERID) {
3278         APP_LOGE("invalid user %{public}d", userId);
3279         return Constants::EMPTY_STRING;
3280     }
3281     std::string appId;
3282     if (dataMgr->GetAppIdByBundleName(bundleName, appId) != ERR_OK) {
3283         APP_LOGD("GetAppIdByBundleName failed");
3284         return Constants::EMPTY_STRING;
3285     }
3286     APP_LOGD("appId is %{private}s", appId.c_str());
3287     return appId;
3288 }
3289 
GetAppType(const std::string & bundleName)3290 std::string BundleMgrHostImpl::GetAppType(const std::string &bundleName)
3291 {
3292     APP_LOGD("bundleName : %{public}s", bundleName.c_str());
3293     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
3294         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3295         APP_LOGE("verify permission failed");
3296         return Constants::EMPTY_STRING;
3297     }
3298     auto dataMgr = GetDataMgrFromService();
3299     if (dataMgr == nullptr) {
3300         APP_LOGE("DataMgr is nullptr");
3301         return Constants::EMPTY_STRING;
3302     }
3303     bool isSystemApp;
3304     if (dataMgr->IsSystemApp(bundleName, isSystemApp) != ERR_OK) {
3305         APP_LOGE("IsSystemApp failed");
3306         return Constants::EMPTY_STRING;
3307     }
3308     std::string appType = isSystemApp ? SYSTEM_APP : THIRD_PARTY_APP;
3309     APP_LOGD("appType is %{public}s", appType.c_str());
3310     return appType;
3311 }
3312 
GetUidByBundleName(const std::string & bundleName,const int32_t userId)3313 int32_t BundleMgrHostImpl::GetUidByBundleName(const std::string &bundleName, const int32_t userId)
3314 {
3315     return GetUidByBundleName(bundleName, userId, 0);
3316 }
3317 
GetUidByBundleName(const std::string & bundleName,const int32_t userId,int32_t appIndex)3318 int32_t BundleMgrHostImpl::GetUidByBundleName(const std::string &bundleName, const int32_t userId, int32_t appIndex)
3319 {
3320     APP_LOGD("bundleName : %{public}s, userId : %{public}d", bundleName.c_str(), userId);
3321     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
3322         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3323         APP_LOGE("verify token type failed");
3324         return Constants::INVALID_UID;
3325     }
3326     auto dataMgr = GetDataMgrFromService();
3327     if (dataMgr == nullptr) {
3328         APP_LOGE("DataMgr is nullptr");
3329         return Constants::INVALID_UID;
3330     }
3331     return dataMgr->GetUidByBundleName(bundleName, userId, appIndex);
3332 }
3333 
GetUidByDebugBundleName(const std::string & bundleName,const int userId)3334 int BundleMgrHostImpl::GetUidByDebugBundleName(const std::string &bundleName, const int userId)
3335 {
3336     APP_LOGD("bundleName : %{public}s, userId : %{public}d", bundleName.c_str(), userId);
3337     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3338         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3339         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3340         APP_LOGE("verify token type failed");
3341         return Constants::INVALID_UID;
3342     }
3343     auto dataMgr = GetDataMgrFromService();
3344     if (dataMgr == nullptr) {
3345         APP_LOGE("DataMgr is nullptr");
3346         return Constants::INVALID_UID;
3347     }
3348     ApplicationInfo appInfo;
3349     int32_t uid = Constants::INVALID_UID;
3350     bool ret = dataMgr->GetApplicationInfo(bundleName, GET_BUNDLE_DEFAULT, userId, appInfo);
3351     if (ret && appInfo.debug) {
3352         uid = appInfo.uid;
3353         APP_LOGD("get debug bundle uid success, uid is %{public}d", uid);
3354     } else {
3355         APP_LOGE("can not get bundleInfo's uid");
3356     }
3357     return uid;
3358 }
3359 
GetAbilityInfo(const std::string & bundleName,const std::string & abilityName,AbilityInfo & abilityInfo)3360 bool BundleMgrHostImpl::GetAbilityInfo(
3361     const std::string &bundleName, const std::string &abilityName, AbilityInfo &abilityInfo)
3362 {
3363     LOG_D(BMS_TAG_QUERY, "start GetAbilityInfo, bundleName:%{public}s abilityName:%{public}s",
3364         bundleName.c_str(), abilityName.c_str());
3365     ElementName elementName("", bundleName, abilityName);
3366     Want want;
3367     want.SetElement(elementName);
3368     return QueryAbilityInfo(want, abilityInfo);
3369 }
3370 
GetAbilityInfo(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,AbilityInfo & abilityInfo)3371 bool BundleMgrHostImpl::GetAbilityInfo(
3372     const std::string &bundleName, const std::string &moduleName,
3373     const std::string &abilityName, AbilityInfo &abilityInfo)
3374 {
3375     LOG_D(BMS_TAG_QUERY,
3376         "start GetAbilityInfo bundleName:%{public}s moduleName:%{public}s abilityName:%{public}s",
3377         bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
3378     if (!VerifySystemApi(ServiceConstants::API_VERSION_NINE)) {
3379         LOG_D(BMS_TAG_QUERY, "non-system app calling system api");
3380         return true;
3381     }
3382     ElementName elementName("", bundleName, abilityName, moduleName);
3383     Want want;
3384     want.SetElement(elementName);
3385     return QueryAbilityInfo(want, abilityInfo);
3386 }
3387 
ImplicitQueryInfoByPriority(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,ExtensionAbilityInfo & extensionInfo)3388 bool BundleMgrHostImpl::ImplicitQueryInfoByPriority(const Want &want, int32_t flags, int32_t userId,
3389     AbilityInfo &abilityInfo, ExtensionAbilityInfo &extensionInfo)
3390 {
3391     APP_LOGD("start ImplicitQueryInfoByPriority, flags : %{public}d, userId : %{public}d", flags, userId);
3392     if (!BundlePermissionMgr::IsSystemApp() &&
3393         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
3394         APP_LOGD("non-system app calling system api");
3395         return true;
3396     }
3397     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3398         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3399         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
3400         APP_LOGE("verify permission failed");
3401         return false;
3402     }
3403     auto dataMgr = GetDataMgrFromService();
3404     if (dataMgr == nullptr) {
3405         APP_LOGE("DataMgr is nullptr");
3406         return false;
3407     }
3408     return dataMgr->ImplicitQueryInfoByPriority(want, flags, userId, abilityInfo, extensionInfo);
3409 }
3410 
ImplicitQueryInfos(const Want & want,int32_t flags,int32_t userId,bool withDefault,std::vector<AbilityInfo> & abilityInfos,std::vector<ExtensionAbilityInfo> & extensionInfos,bool & findDefaultApp)3411 bool BundleMgrHostImpl::ImplicitQueryInfos(const Want &want, int32_t flags, int32_t userId,  bool withDefault,
3412     std::vector<AbilityInfo> &abilityInfos, std::vector<ExtensionAbilityInfo> &extensionInfos, bool &findDefaultApp)
3413 {
3414     APP_LOGD("begin to ImplicitQueryInfos, flags : %{public}d, userId : %{public}d", flags, userId);
3415     if (!BundlePermissionMgr::IsSystemApp() &&
3416         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
3417         APP_LOGD("non-system app calling system api");
3418         return true;
3419     }
3420     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3421         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3422         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
3423         APP_LOGE("verify permission failed");
3424         return false;
3425     }
3426     auto dataMgr = GetDataMgrFromService();
3427     if (dataMgr == nullptr) {
3428         APP_LOGE("DataMgr is nullptr");
3429         return false;
3430     }
3431     findDefaultApp = false;
3432     auto ret = dataMgr->ImplicitQueryInfos(
3433         want, flags, userId, withDefault, abilityInfos, extensionInfos, findDefaultApp);
3434     if (ret && findDefaultApp) {
3435         APP_LOGD("default app has been found and unnecessary to find from bms extension");
3436         return ret;
3437     }
3438     auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
3439     if (!IsAppLinking(flags) && isBrokerServiceExisted_ &&
3440         bmsExtensionClient->ImplicitQueryAbilityInfos(want, flags, userId, abilityInfos, false) == ERR_OK) {
3441         APP_LOGD("implicitly query from bms extension successfully");
3442         FilterAbilityInfos(abilityInfos);
3443         APP_LOGI_NOFUNC("ImplicitQueryInfos ret a.size:%{public}zu e.size:%{public}zu",
3444             abilityInfos.size(), extensionInfos.size());
3445         return true;
3446     }
3447     APP_LOGI_NOFUNC("ImplicitQueryInfos ret a.size:%{public}zu e.size:%{public}zu",
3448         abilityInfos.size(), extensionInfos.size());
3449     return ret;
3450 }
3451 
FilterAbilityInfos(std::vector<AbilityInfo> & abilityInfos)3452 void BundleMgrHostImpl::FilterAbilityInfos(std::vector<AbilityInfo> &abilityInfos)
3453 {
3454     AbilityInfo appLinkingAbility;
3455     bool hasAppLinking = false;
3456     for (const auto& ability : abilityInfos) {
3457         if (ability.kind == APP_LINKING) {
3458             appLinkingAbility = ability;
3459             hasAppLinking = true;
3460             break;
3461         }
3462     }
3463     if (hasAppLinking) {
3464         abilityInfos.clear();
3465         abilityInfos.push_back(appLinkingAbility);
3466     }
3467 }
3468 
Dump(int fd,const std::vector<std::u16string> & args)3469 int BundleMgrHostImpl::Dump(int fd, const std::vector<std::u16string> &args)
3470 {
3471     std::string result;
3472     std::vector<std::string> argsStr;
3473     for (auto item : args) {
3474         argsStr.emplace_back(Str16ToStr8(item));
3475     }
3476 
3477     if (!DelayedSingleton<BundleMgrService>::GetInstance()->Hidump(argsStr, result)) {
3478         APP_LOGE("Hidump error");
3479         return ERR_APPEXECFWK_HIDUMP_ERROR;
3480     }
3481 
3482     int ret = dprintf(fd, "%s\n", result.c_str());
3483     if (ret < 0) {
3484         APP_LOGE("dprintf error");
3485         return ERR_APPEXECFWK_HIDUMP_ERROR;
3486     }
3487 
3488     return ERR_OK;
3489 }
3490 
GetAllDependentModuleNames(const std::string & bundleName,const std::string & moduleName,std::vector<std::string> & dependentModuleNames)3491 bool BundleMgrHostImpl::GetAllDependentModuleNames(const std::string &bundleName, const std::string &moduleName,
3492     std::vector<std::string> &dependentModuleNames)
3493 {
3494     APP_LOGD("GetAllDependentModuleNames: bundleName: %{public}s, moduleName: %{public}s",
3495         bundleName.c_str(), moduleName.c_str());
3496     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3497         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3498         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3499         APP_LOGE("verify permission failed");
3500         return false;
3501     }
3502     auto dataMgr = GetDataMgrFromService();
3503     if (dataMgr == nullptr) {
3504         APP_LOGE("DataMgr is nullptr");
3505         return false;
3506     }
3507     return dataMgr->GetAllDependentModuleNames(bundleName, moduleName, dependentModuleNames);
3508 }
3509 
GetSandboxBundleInfo(const std::string & bundleName,int32_t appIndex,int32_t userId,BundleInfo & info)3510 ErrCode BundleMgrHostImpl::GetSandboxBundleInfo(
3511     const std::string &bundleName, int32_t appIndex, int32_t userId, BundleInfo &info)
3512 {
3513     APP_LOGD("start GetSandboxBundleInfo, bundleName : %{public}s, appIndex : %{public}d, userId : %{public}d",
3514         bundleName.c_str(), appIndex, userId);
3515     // check bundle name
3516     if (bundleName.empty()) {
3517         APP_LOGE("GetSandboxBundleInfo failed due to empty bundleName");
3518         return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR;
3519     }
3520     // check appIndex
3521     if (appIndex <= Constants::INITIAL_SANDBOX_APP_INDEX || appIndex > Constants::MAX_SANDBOX_APP_INDEX) {
3522         APP_LOGE("the appIndex %{public}d is invalid", appIndex);
3523         return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR;
3524     }
3525     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3526         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3527         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3528         APP_LOGE("verify permission failed");
3529         return ERR_APPEXECFWK_PERMISSION_DENIED;
3530     }
3531     auto dataMgr = GetDataMgrFromService();
3532     if (dataMgr == nullptr) {
3533         APP_LOGE("DataMgr is nullptr");
3534         return ERR_APPEXECFWK_SANDBOX_INSTALL_INTERNAL_ERROR;
3535     }
3536     auto sandboxAppHelper = dataMgr->GetSandboxAppHelper();
3537     if (sandboxAppHelper == nullptr) {
3538         APP_LOGE("sandboxAppHelper is nullptr");
3539         return ERR_APPEXECFWK_SANDBOX_INSTALL_INTERNAL_ERROR;
3540     }
3541     int32_t requestUserId = dataMgr->GetUserId(userId);
3542     if (requestUserId == Constants::INVALID_USERID) {
3543         return ERR_APPEXECFWK_SANDBOX_QUERY_INVALID_USER_ID;
3544     }
3545     return sandboxAppHelper->GetSandboxAppBundleInfo(bundleName, appIndex, requestUserId, info);
3546 }
3547 
ObtainCallingBundleName(std::string & bundleName)3548 bool BundleMgrHostImpl::ObtainCallingBundleName(std::string &bundleName)
3549 {
3550     auto dataMgr = GetDataMgrFromService();
3551     if (dataMgr == nullptr) {
3552         APP_LOGE("DataMgr is nullptr");
3553         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
3554     }
3555     bool ret = dataMgr->GetBundleNameForUid(IPCSkeleton::GetCallingUid(), bundleName);
3556     if (!ret) {
3557         APP_LOGE("query calling bundle name failed");
3558         return ret;
3559     }
3560     APP_LOGD("calling bundleName is : %{public}s", bundleName.c_str());
3561     return ret;
3562 }
3563 
GetBundleStats(const std::string & bundleName,int32_t userId,std::vector<int64_t> & bundleStats,int32_t appIndex,uint32_t statFlag)3564 bool BundleMgrHostImpl::GetBundleStats(const std::string &bundleName, int32_t userId,
3565     std::vector<int64_t> &bundleStats, int32_t appIndex, uint32_t statFlag)
3566 {
3567     bool permissionVerify = [bundleName]() {
3568         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
3569             return true;
3570         }
3571         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO) &&
3572             BundlePermissionMgr::IsSystemApp()) {
3573             return true;
3574         }
3575         if (BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3576             return true;
3577         }
3578         return false;
3579     }();
3580     if (!permissionVerify) {
3581         APP_LOGE("verify permission failed");
3582         return false;
3583     }
3584     if (bundleName.empty()) {
3585         APP_LOGE("bundleName empty");
3586         return false;
3587     }
3588     if (!CheckAppIndex(bundleName, userId, appIndex)) {
3589         return false;
3590     }
3591     auto dataMgr = GetDataMgrFromService();
3592     if (dataMgr == nullptr) {
3593         APP_LOGE("DataMgr is nullptr");
3594         return false;
3595     }
3596     if (isBrokerServiceExisted_ && !IsBundleExist(bundleName)) {
3597         auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
3598         ErrCode ret = bmsExtensionClient->GetBundleStats(bundleName, userId, bundleStats);
3599         APP_LOGI("ret : %{public}d", ret);
3600         return ret == ERR_OK;
3601     }
3602     return dataMgr->GetBundleStats(bundleName, userId, bundleStats, appIndex, statFlag);
3603 }
3604 
BatchGetBundleStats(const std::vector<std::string> & bundleNames,int32_t userId,std::vector<BundleStorageStats> & bundleStats)3605 ErrCode BundleMgrHostImpl::BatchGetBundleStats(const std::vector<std::string> &bundleNames, int32_t userId,
3606     std::vector<BundleStorageStats> &bundleStats)
3607 {
3608     if (!BundlePermissionMgr::IsSystemApp()) {
3609         APP_LOGE("non-system app calling system api");
3610         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3611     }
3612     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3613         Constants::PERMISSION_GET_BUNDLE_INFO})) {
3614         APP_LOGE("verify permission failed");
3615         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3616     }
3617     std::set<std::string> uniqueSet(bundleNames.begin(), bundleNames.end());
3618     std::vector<std::string> finalBundleNames(uniqueSet.begin(), uniqueSet.end());
3619     if (finalBundleNames.size() == 0) {
3620         APP_LOGE("bundleNames empty");
3621         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
3622     }
3623     auto dataMgr = GetDataMgrFromService();
3624     if (dataMgr == nullptr) {
3625         APP_LOGE("DataMgr is nullptr");
3626         return ERR_APPEXECFWK_NULL_PTR;
3627     }
3628     return dataMgr->BatchGetBundleStats(finalBundleNames, userId, bundleStats);
3629 }
3630 
GetAllBundleStats(int32_t userId,std::vector<int64_t> & bundleStats)3631 bool BundleMgrHostImpl::GetAllBundleStats(int32_t userId, std::vector<int64_t> &bundleStats)
3632 {
3633     if (!BundlePermissionMgr::IsSystemApp()) {
3634         APP_LOGE("non-system app calling system api");
3635         return false;
3636     }
3637     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3638         Constants::PERMISSION_GET_BUNDLE_INFO})) {
3639         APP_LOGE("verify permission failed");
3640         return false;
3641     }
3642     auto dataMgr = GetDataMgrFromService();
3643     if (dataMgr == nullptr) {
3644         APP_LOGE("DataMgr is nullptr");
3645         return false;
3646     }
3647     return dataMgr->GetAllBundleStats(userId, bundleStats);
3648 }
3649 
GetAllBundleCacheStat(const sptr<IProcessCacheCallback> processCacheCallback)3650 ErrCode BundleMgrHostImpl::GetAllBundleCacheStat(const sptr<IProcessCacheCallback> processCacheCallback)
3651 {
3652     if (!BundlePermissionMgr::IsSystemApp()) {
3653         APP_LOGE("non-system app calling system api");
3654         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3655     }
3656     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
3657         APP_LOGE("ohos.permission.PERMISSION_GET_BUNDLE_INFO_PRIVILEGED permission denied");
3658         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3659     }
3660 
3661     if (processCacheCallback == nullptr) {
3662         APP_LOGE("the processCacheCallback is nullptr");
3663         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
3664     }
3665     return BundleCacheMgr().GetAllBundleCacheStat(processCacheCallback);
3666 }
3667 
CleanAllBundleCache(const sptr<IProcessCacheCallback> processCacheCallback)3668 ErrCode BundleMgrHostImpl::CleanAllBundleCache(const sptr<IProcessCacheCallback> processCacheCallback)
3669 {
3670     if (!BundlePermissionMgr::IsSystemApp()) {
3671         APP_LOGE("non-system app calling system api");
3672         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3673     }
3674     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_REMOVECACHEFILE)) {
3675         APP_LOGE("ohos.permission.PERMISSION_REMOVECACHEFILE permission denied");
3676         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3677     }
3678 
3679     if (processCacheCallback == nullptr) {
3680         APP_LOGE("the processCacheCallback is nullptr");
3681         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
3682     }
3683     return BundleCacheMgr().CleanAllBundleCache(processCacheCallback);
3684 }
3685 
GetStringById(const std::string & bundleName,const std::string & moduleName,uint32_t resId,int32_t userId,const std::string & localeInfo)3686 std::string BundleMgrHostImpl::GetStringById(const std::string &bundleName, const std::string &moduleName,
3687     uint32_t resId, int32_t userId, const std::string &localeInfo)
3688 {
3689     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3690         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3691         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3692         APP_LOGE("verify token type failed");
3693         return Constants::EMPTY_STRING;
3694     }
3695     auto dataMgr = GetDataMgrFromService();
3696     if (dataMgr == nullptr) {
3697         APP_LOGE("DataMgr is nullptr");
3698         return Constants::EMPTY_STRING;
3699     }
3700     return dataMgr->GetStringById(bundleName, moduleName, resId, userId, localeInfo);
3701 }
3702 
GetIconById(const std::string & bundleName,const std::string & moduleName,uint32_t resId,uint32_t density,int32_t userId)3703 std::string BundleMgrHostImpl::GetIconById(
3704     const std::string &bundleName, const std::string &moduleName, uint32_t resId, uint32_t density, int32_t userId)
3705 {
3706     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3707         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3708         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3709         APP_LOGE("verify token type failed");
3710         return Constants::EMPTY_STRING;
3711     }
3712     auto dataMgr = GetDataMgrFromService();
3713     if (dataMgr == nullptr) {
3714         APP_LOGE("DataMgr is nullptr");
3715         return Constants::EMPTY_STRING;
3716     }
3717     return dataMgr->GetIconById(bundleName, moduleName, resId, density, userId);
3718 }
3719 
3720 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
GetDefaultAppProxy()3721 sptr<IDefaultApp> BundleMgrHostImpl::GetDefaultAppProxy()
3722 {
3723     return DelayedSingleton<BundleMgrService>::GetInstance()->GetDefaultAppProxy();
3724 }
3725 #endif
3726 
3727 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
GetAppControlProxy()3728 sptr<IAppControlMgr> BundleMgrHostImpl::GetAppControlProxy()
3729 {
3730     return DelayedSingleton<BundleMgrService>::GetInstance()->GetAppControlProxy();
3731 }
3732 #endif
3733 
GetBundleMgrExtProxy()3734 sptr<IBundleMgrExt> BundleMgrHostImpl::GetBundleMgrExtProxy()
3735 {
3736     return DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleMgrExtProxy();
3737 }
3738 
GetQuickFixManagerProxy()3739 sptr<IQuickFixManager> BundleMgrHostImpl::GetQuickFixManagerProxy()
3740 {
3741 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3742     return DelayedSingleton<BundleMgrService>::GetInstance()->GetQuickFixManagerProxy();
3743 #else
3744     return nullptr;
3745 #endif
3746 }
3747 
GetOverlayManagerProxy()3748 sptr<IOverlayManager> BundleMgrHostImpl::GetOverlayManagerProxy()
3749 {
3750 #ifdef BUNDLE_FRAMEWORK_OVERLAY_INSTALLATION
3751     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_OVERLAY_MANAGER_PROXY);
3752     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
3753     return DelayedSingleton<BundleMgrService>::GetInstance()->GetOverlayManagerProxy();
3754 #else
3755     return nullptr;
3756 #endif
3757 }
3758 
GetSandboxAbilityInfo(const Want & want,int32_t appIndex,int32_t flags,int32_t userId,AbilityInfo & info)3759 ErrCode BundleMgrHostImpl::GetSandboxAbilityInfo(const Want &want, int32_t appIndex, int32_t flags, int32_t userId,
3760     AbilityInfo &info)
3761 {
3762     APP_LOGD("start GetSandboxAbilityInfo appIndex : %{public}d, userId : %{public}d", appIndex, userId);
3763     // check appIndex
3764     if (appIndex <= Constants::INITIAL_SANDBOX_APP_INDEX || appIndex > Constants::MAX_SANDBOX_APP_INDEX) {
3765         APP_LOGE("the appIndex %{public}d is invalid", appIndex);
3766         return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR;
3767     }
3768     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3769         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3770         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
3771         APP_LOGE("verify permission failed");
3772         return ERR_APPEXECFWK_PERMISSION_DENIED;
3773     }
3774     auto dataMgr = GetDataMgrFromService();
3775     if (dataMgr == nullptr) {
3776         APP_LOGE("DataMgr is nullptr");
3777         return ERR_APPEXECFWK_SANDBOX_QUERY_INTERNAL_ERROR;
3778     }
3779 
3780     if (!(dataMgr->QueryAbilityInfo(want, flags, userId, info, appIndex)
3781         || dataMgr->QueryAbilityInfo(want, flags, Constants::DEFAULT_USERID, info, appIndex)
3782         || dataMgr->QueryAbilityInfo(want, flags, Constants::U1, info, appIndex))) {
3783         APP_LOGE("query ability info failed");
3784         return ERR_APPEXECFWK_SANDBOX_QUERY_INTERNAL_ERROR;
3785     }
3786     return ERR_OK;
3787 }
3788 
GetSandboxExtAbilityInfos(const Want & want,int32_t appIndex,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & infos)3789 ErrCode BundleMgrHostImpl::GetSandboxExtAbilityInfos(const Want &want, int32_t appIndex, int32_t flags,
3790     int32_t userId, std::vector<ExtensionAbilityInfo> &infos)
3791 {
3792     APP_LOGD("start GetSandboxExtAbilityInfos appIndex : %{public}d, userId : %{public}d", appIndex, userId);
3793     // check appIndex
3794     if (appIndex <= Constants::INITIAL_SANDBOX_APP_INDEX || appIndex > Constants::MAX_SANDBOX_APP_INDEX) {
3795         APP_LOGE("the appIndex %{public}d is invalid", appIndex);
3796         return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR;
3797     }
3798     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3799         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3800         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
3801         APP_LOGE("verify permission failed");
3802         return ERR_APPEXECFWK_PERMISSION_DENIED;
3803     }
3804     auto dataMgr = GetDataMgrFromService();
3805     if (dataMgr == nullptr) {
3806         APP_LOGE("DataMgr is nullptr");
3807         return ERR_APPEXECFWK_SANDBOX_QUERY_INTERNAL_ERROR;
3808     }
3809 
3810     if (!(dataMgr->QueryExtensionAbilityInfos(want, flags, userId, infos, appIndex)
3811         || dataMgr->QueryExtensionAbilityInfos(want, flags, Constants::DEFAULT_USERID, infos, appIndex)
3812         || dataMgr->QueryExtensionAbilityInfos(want, flags, Constants::U1, infos, appIndex))) {
3813         APP_LOGE("query extension ability info failed");
3814         return ERR_APPEXECFWK_SANDBOX_QUERY_INTERNAL_ERROR;
3815     }
3816     return ERR_OK;
3817 }
3818 
GetSandboxHapModuleInfo(const AbilityInfo & abilityInfo,int32_t appIndex,int32_t userId,HapModuleInfo & info)3819 ErrCode BundleMgrHostImpl::GetSandboxHapModuleInfo(const AbilityInfo &abilityInfo, int32_t appIndex, int32_t userId,
3820     HapModuleInfo &info)
3821 {
3822     APP_LOGD("start GetSandboxHapModuleInfo appIndex : %{public}d, userId : %{public}d", appIndex, userId);
3823     // check appIndex
3824     if (appIndex <= Constants::INITIAL_SANDBOX_APP_INDEX || appIndex > Constants::MAX_SANDBOX_APP_INDEX) {
3825         APP_LOGE("the appIndex %{public}d is invalid", appIndex);
3826         return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR;
3827     }
3828     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3829         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3830         !BundlePermissionMgr::IsBundleSelfCalling(abilityInfo.bundleName)) {
3831         APP_LOGE("verify permission failed");
3832         return ERR_APPEXECFWK_PERMISSION_DENIED;
3833     }
3834     auto dataMgr = GetDataMgrFromService();
3835     if (dataMgr == nullptr) {
3836         APP_LOGE("DataMgr is nullptr");
3837         return ERR_APPEXECFWK_SANDBOX_QUERY_INTERNAL_ERROR;
3838     }
3839     auto sandboxAppHelper = dataMgr->GetSandboxAppHelper();
3840     if (sandboxAppHelper == nullptr) {
3841         APP_LOGE("sandboxAppHelper is nullptr");
3842         return ERR_APPEXECFWK_SANDBOX_QUERY_INTERNAL_ERROR;
3843     }
3844     int32_t requestUserId = dataMgr->GetUserId(userId);
3845     if (requestUserId == Constants::INVALID_USERID) {
3846         return ERR_APPEXECFWK_SANDBOX_QUERY_INVALID_USER_ID;
3847     }
3848     return sandboxAppHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, requestUserId, info);
3849 }
3850 
GetMediaData(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,std::unique_ptr<uint8_t[]> & mediaDataPtr,size_t & len,int32_t userId)3851 ErrCode BundleMgrHostImpl::GetMediaData(const std::string &bundleName, const std::string &moduleName,
3852     const std::string &abilityName, std::unique_ptr<uint8_t[]> &mediaDataPtr, size_t &len, int32_t userId)
3853 {
3854     // API9 need to be system app, otherwise return empty data
3855     if (!BundlePermissionMgr::IsSystemApp() &&
3856         !BundlePermissionMgr::VerifyCallingBundleSdkVersion(ServiceConstants::API_VERSION_NINE)) {
3857         APP_LOGE("non-system app calling system api");
3858         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3859     }
3860     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
3861         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
3862         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3863         APP_LOGE("verify permission failed");
3864         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3865     }
3866     auto dataMgr = GetDataMgrFromService();
3867     if (dataMgr == nullptr) {
3868         APP_LOGE("DataMgr is nullptr");
3869         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
3870     }
3871     return dataMgr->GetMediaData(bundleName, moduleName, abilityName, mediaDataPtr, len, userId);
3872 }
3873 
NotifyBundleStatus(const NotifyBundleEvents & installRes)3874 void BundleMgrHostImpl::NotifyBundleStatus(const NotifyBundleEvents &installRes)
3875 {
3876     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
3877     commonEventMgr->NotifyBundleStatus(installRes, nullptr);
3878 }
3879 
SetDebugMode(bool isDebug)3880 ErrCode BundleMgrHostImpl::SetDebugMode(bool isDebug)
3881 {
3882     int32_t callingUid = IPCSkeleton::GetCallingUid();
3883     if (callingUid != Constants::ROOT_UID && callingUid != ServiceConstants::BMS_UID) {
3884         APP_LOGE("invalid calling uid %{public}d to set debug mode", callingUid);
3885         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED;
3886     }
3887     if (isDebug) {
3888         BundleVerifyMgr::EnableDebug();
3889     } else {
3890         BundleVerifyMgr::DisableDebug();
3891     }
3892     return ERR_OK;
3893 }
3894 
VerifySystemApi(int32_t beginApiVersion)3895 bool BundleMgrHostImpl::VerifySystemApi(int32_t beginApiVersion)
3896 {
3897     APP_LOGD("begin to verify system app");
3898     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_VERIFY_SYSTEM_API);
3899     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
3900     return BundlePermissionMgr::VerifySystemApp(beginApiVersion);
3901 }
3902 
GetAppProvisionInfo(const std::string & bundleName,int32_t userId,AppProvisionInfo & appProvisionInfo)3903 ErrCode BundleMgrHostImpl::GetAppProvisionInfo(const std::string &bundleName, int32_t userId,
3904     AppProvisionInfo &appProvisionInfo)
3905 {
3906     APP_LOGD("begin to GetAppProvisionInfo bundleName: %{public}s, userId: %{public}d", bundleName.c_str(),
3907         userId);
3908     if (!BundlePermissionMgr::IsSystemApp()) {
3909         APP_LOGE("non-system app calling system api");
3910         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3911     }
3912     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
3913         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3914         APP_LOGE("verify permission failed");
3915         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3916     }
3917     int64_t intervalTime = ONE_DAY;
3918     auto dataMgr = GetDataMgrFromService();
3919     if (dataMgr == nullptr) {
3920         APP_LOGE("DataMgr is nullptr");
3921         QueryEventInfo info = PrepareQueryEvent(ERR_BUNDLE_MANAGER_INTERNAL_ERROR, bundleName,
3922             "GetAppProvisionInfo", -1, userId, 0, -1);
3923         SendQueryBundleInfoEvent(info, intervalTime, true);
3924         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
3925     }
3926     ErrCode ret = dataMgr->GetAppProvisionInfo(bundleName, userId, appProvisionInfo);
3927     if (ret != ERR_OK) {
3928         QueryEventInfo info = PrepareQueryEvent(ret, bundleName, "GetAppProvisionInfo", -1, userId, 0, -1);
3929         SendQueryBundleInfoEvent(info, intervalTime, false);
3930     }
3931     return ret;
3932 }
3933 
GetProvisionMetadata(const std::string & bundleName,int32_t userId,std::vector<Metadata> & provisionMetadatas)3934 ErrCode BundleMgrHostImpl::GetProvisionMetadata(const std::string &bundleName, int32_t userId,
3935     std::vector<Metadata> &provisionMetadatas)
3936 {
3937     bool permissionVerify = [bundleName]() {
3938         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
3939             return true;
3940         }
3941         if (BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO) &&
3942             BundlePermissionMgr::IsSystemApp()) {
3943             return true;
3944         }
3945         if (BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3946             return true;
3947         }
3948         return false;
3949     }();
3950     if (!permissionVerify) {
3951         APP_LOGE("verify permission failed");
3952         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3953     }
3954     auto dataMgr = GetDataMgrFromService();
3955     if (dataMgr == nullptr) {
3956         APP_LOGE("DataMgr is nullptr");
3957         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
3958     }
3959     return dataMgr->GetProvisionMetadata(bundleName, userId, provisionMetadatas);
3960 }
3961 
GetAllSharedBundleInfo(std::vector<SharedBundleInfo> & sharedBundles)3962 ErrCode BundleMgrHostImpl::GetAllSharedBundleInfo(std::vector<SharedBundleInfo> &sharedBundles)
3963 {
3964     APP_LOGD("begin to GetAllSharedBundleInfo");
3965     if (!BundlePermissionMgr::IsSystemApp()) {
3966         APP_LOGE("non-system app calling system api");
3967         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3968     }
3969     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
3970         APP_LOGE("verify permission failed");
3971         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3972     }
3973 
3974     auto dataMgr = GetDataMgrFromService();
3975     if (dataMgr == nullptr) {
3976         APP_LOGE("dataMgr is nullptr");
3977         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
3978     }
3979     return dataMgr->GetAllSharedBundleInfo(sharedBundles);
3980 }
3981 
GetSharedBundleInfo(const std::string & bundleName,const std::string & moduleName,std::vector<SharedBundleInfo> & sharedBundles)3982 ErrCode BundleMgrHostImpl::GetSharedBundleInfo(const std::string &bundleName, const std::string &moduleName,
3983     std::vector<SharedBundleInfo> &sharedBundles)
3984 {
3985     APP_LOGD("GetSharedBundleInfo: bundleName: %{public}s, moduleName: %{public}s",
3986         bundleName.c_str(), moduleName.c_str());
3987     if (!BundlePermissionMgr::IsSystemApp()) {
3988         APP_LOGE("non-system app calling system api");
3989         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
3990     }
3991     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
3992         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
3993         APP_LOGE("verify permission failed");
3994         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
3995     }
3996 
3997     auto dataMgr = GetDataMgrFromService();
3998     if (dataMgr == nullptr) {
3999         APP_LOGE("dataMgr is nullptr");
4000         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4001     }
4002     return dataMgr->GetSharedBundleInfo(bundleName, moduleName, sharedBundles);
4003 }
4004 
GetSharedBundleInfoBySelf(const std::string & bundleName,SharedBundleInfo & sharedBundleInfo)4005 ErrCode BundleMgrHostImpl::GetSharedBundleInfoBySelf(const std::string &bundleName,
4006     SharedBundleInfo &sharedBundleInfo)
4007 {
4008     APP_LOGD("begin to GetSharedBundleInfoBySelf bundleName: %{public}s", bundleName.c_str());
4009     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_SHARED_BUNDLE_INFO_BY_SELF);
4010     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
4011     if (!BundlePermissionMgr::IsSystemApp()) {
4012         APP_LOGE("non-system app calling system api");
4013         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4014     }
4015     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
4016         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
4017         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
4018         APP_LOGE("verify permission failed");
4019         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4020     }
4021 
4022     auto dataMgr = GetDataMgrFromService();
4023     if (dataMgr == nullptr) {
4024         APP_LOGE("DataMgr is nullptr");
4025         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4026     }
4027     return dataMgr->GetSharedBundleInfoBySelf(bundleName, sharedBundleInfo);
4028 }
4029 
GetSharedDependencies(const std::string & bundleName,const std::string & moduleName,std::vector<Dependency> & dependencies)4030 ErrCode BundleMgrHostImpl::GetSharedDependencies(const std::string &bundleName, const std::string &moduleName,
4031     std::vector<Dependency> &dependencies)
4032 {
4033     APP_LOGD("GetSharedDependencies: bundleName: %{public}s, moduleName: %{public}s",
4034         bundleName.c_str(), moduleName.c_str());
4035     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
4036         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
4037         APP_LOGE("verify permission failed");
4038         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4039     }
4040     auto dataMgr = GetDataMgrFromService();
4041     if (dataMgr == nullptr) {
4042         APP_LOGE("DataMgr is nullptr");
4043         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4044     }
4045     return dataMgr->GetSharedDependencies(bundleName, moduleName, dependencies);
4046 }
4047 
VerifyDependency(const std::string & sharedBundleName)4048 bool BundleMgrHostImpl::VerifyDependency(const std::string &sharedBundleName)
4049 {
4050     auto dataMgr = GetDataMgrFromService();
4051     if (dataMgr == nullptr) {
4052         APP_LOGE("DataMgr is nullptr");
4053         return false;
4054     }
4055 
4056     std::string callingBundleName;
4057     bool ret = dataMgr->GetBundleNameForUid(IPCSkeleton::GetCallingUid(), callingBundleName);
4058     if (!ret) {
4059         APP_LOGE("GetBundleNameForUid failed");
4060         return false;
4061     }
4062 
4063     InnerBundleInfo callingBundleInfo;
4064     if (!dataMgr->FetchInnerBundleInfo(callingBundleName, callingBundleInfo)) {
4065         APP_LOGE("get %{public}s failed", callingBundleName.c_str());
4066         return false;
4067     }
4068 
4069     // check whether callingBundleName is dependent on sharedBundleName
4070     const auto& dependencies = callingBundleInfo.GetDependencies();
4071     auto iter = std::find_if(dependencies.begin(), dependencies.end(), [&sharedBundleName](const auto &dependency) {
4072         return dependency.bundleName == sharedBundleName;
4073     });
4074     if (iter == dependencies.end()) {
4075         APP_LOGE("%{public}s is not dependent on %{public}s", callingBundleName.c_str(), sharedBundleName.c_str());
4076         return false;
4077     }
4078     APP_LOGD("verify dependency successfully");
4079     return true;
4080 }
4081 
IsPreInstallApp(const std::string & bundleName)4082 bool BundleMgrHostImpl::IsPreInstallApp(const std::string &bundleName)
4083 {
4084     auto dataMgr = GetDataMgrFromService();
4085     if (dataMgr == nullptr) {
4086         APP_LOGE("DataMgr is nullptr");
4087         return false;
4088     }
4089     return dataMgr->IsPreInstallApp(bundleName);
4090 }
4091 
GetProxyDataInfos(const std::string & bundleName,const std::string & moduleName,std::vector<ProxyData> & proxyDatas,int32_t userId)4092 ErrCode BundleMgrHostImpl::GetProxyDataInfos(const std::string &bundleName, const std::string &moduleName,
4093     std::vector<ProxyData> &proxyDatas, int32_t userId)
4094 {
4095     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4096         APP_LOGE("verify token type failed");
4097         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4098     }
4099     auto dataMgr = GetDataMgrFromService();
4100     if (dataMgr == nullptr) {
4101         APP_LOGE("DataMgr is nullptr");
4102         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4103     }
4104     return dataMgr->GetProxyDataInfos(bundleName, moduleName, userId, proxyDatas);
4105 }
4106 
GetAllProxyDataInfos(std::vector<ProxyData> & proxyDatas,int32_t userId)4107 ErrCode BundleMgrHostImpl::GetAllProxyDataInfos(std::vector<ProxyData> &proxyDatas, int32_t userId)
4108 {
4109     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4110         APP_LOGE("verify token type failed");
4111         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4112     }
4113     auto dataMgr = GetDataMgrFromService();
4114     if (dataMgr == nullptr) {
4115         APP_LOGE("DataMgr is nullptr");
4116         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4117     }
4118     return dataMgr->GetAllProxyDataInfos(userId, proxyDatas);
4119 }
4120 
GetSpecifiedDistributionType(const std::string & bundleName,std::string & specifiedDistributionType)4121 ErrCode BundleMgrHostImpl::GetSpecifiedDistributionType(const std::string &bundleName,
4122     std::string &specifiedDistributionType)
4123 {
4124     APP_LOGD("GetSpecifiedDistributionType bundleName: %{public}s", bundleName.c_str());
4125     if (!BundlePermissionMgr::IsSystemApp()) {
4126         APP_LOGE("non-system app calling system api");
4127         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4128     }
4129     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED) &&
4130         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
4131         APP_LOGE("verify permission failed");
4132         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4133     }
4134 
4135     auto dataMgr = GetDataMgrFromService();
4136     if (dataMgr == nullptr) {
4137         APP_LOGE("dataMgr is nullptr");
4138         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4139     }
4140     return dataMgr->GetSpecifiedDistributionType(bundleName, specifiedDistributionType);
4141 }
4142 
BatchGetSpecifiedDistributionType(const std::vector<std::string> & bundleNames,std::vector<BundleDistributionType> & specifiedDistributionTypes)4143 ErrCode BundleMgrHostImpl::BatchGetSpecifiedDistributionType(const std::vector<std::string> &bundleNames,
4144     std::vector<BundleDistributionType> &specifiedDistributionTypes)
4145 {
4146     if (!BundlePermissionMgr::IsSystemApp()) {
4147         APP_LOGE("non-system app calling system api");
4148         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4149     }
4150     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4151         APP_LOGE("verify permission failed");
4152         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4153     }
4154     auto dataMgr = GetDataMgrFromService();
4155     if (dataMgr == nullptr) {
4156         APP_LOGE("dataMgr is nullptr");
4157         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4158     }
4159 
4160     for (const std::string &bundleName : bundleNames) {
4161         AppExecFwk::BundleDistributionType specifiedDistributionType;
4162         if (bundleName.empty()) {
4163             specifiedDistributionType.errCode = ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4164             specifiedDistributionTypes.emplace_back(specifiedDistributionType);
4165             continue;
4166         }
4167         ErrCode ret = dataMgr->GetSpecifiedDistributionType(bundleName, specifiedDistributionType.distributionType);
4168         specifiedDistributionType.bundleName = bundleName;
4169         specifiedDistributionType.errCode = ret;
4170         specifiedDistributionTypes.emplace_back(specifiedDistributionType);
4171     }
4172 
4173     return ERR_OK;
4174 }
4175 
GetAdditionalInfo(const std::string & bundleName,std::string & additionalInfo)4176 ErrCode BundleMgrHostImpl::GetAdditionalInfo(const std::string &bundleName,
4177     std::string &additionalInfo)
4178 {
4179     APP_LOGD("GetAdditionalInfo bundleName: %{public}s", bundleName.c_str());
4180     if (!BundlePermissionMgr::IsSystemApp()) {
4181         APP_LOGE("non-system app calling system api");
4182         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4183     }
4184     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4185         APP_LOGE("verify permission failed");
4186         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4187     }
4188 
4189     auto dataMgr = GetDataMgrFromService();
4190     if (dataMgr == nullptr) {
4191         APP_LOGE("dataMgr is nullptr");
4192         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4193     }
4194     return dataMgr->GetAdditionalInfo(bundleName, additionalInfo);
4195 }
4196 
BatchGetAdditionalInfo(const std::vector<std::string> & bundleNames,std::vector<BundleAdditionalInfo> & additionalInfos)4197 ErrCode BundleMgrHostImpl::BatchGetAdditionalInfo(const std::vector<std::string> &bundleNames,
4198     std::vector<BundleAdditionalInfo> &additionalInfos)
4199 {
4200     if (!BundlePermissionMgr::IsSystemApp()) {
4201         APP_LOGE("non-system app calling system api");
4202         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4203     }
4204     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4205         APP_LOGE("verify permission failed");
4206         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4207     }
4208     auto dataMgr = GetDataMgrFromService();
4209     if (dataMgr == nullptr) {
4210         APP_LOGE("dataMgr is nullptr");
4211         return ERR_APPEXECFWK_NULL_PTR;
4212     }
4213 
4214     for (const std::string &bundleName : bundleNames) {
4215         AppExecFwk::BundleAdditionalInfo additionalInfo;
4216         if (bundleName.empty()) {
4217             additionalInfo.errCode = ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4218             additionalInfos.emplace_back(additionalInfo);
4219             continue;
4220         }
4221         ErrCode ret = dataMgr->GetAdditionalInfo(bundleName, additionalInfo.additionalInfo);
4222         additionalInfo.bundleName = bundleName;
4223         additionalInfo.errCode = ret;
4224         additionalInfos.emplace_back(additionalInfo);
4225     }
4226 
4227     return ERR_OK;
4228 }
4229 
GetAdditionalInfoForAllUser(const std::string & bundleName,std::string & additionalInfo)4230 ErrCode BundleMgrHostImpl::GetAdditionalInfoForAllUser(const std::string &bundleName,
4231     std::string &additionalInfo)
4232 {
4233     APP_LOGD("GetAdditionalInfo bundleName: %{public}s", bundleName.c_str());
4234     int32_t uid = OHOS::IPCSkeleton::GetCallingUid();
4235     if (uid != Constants::FOUNDATION_UID) {
4236         LOG_E(BMS_TAG_DEFAULT, "uid: %{public}d not foundation", uid);
4237         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4238     }
4239 
4240     auto dataMgr = GetDataMgrFromService();
4241     if (dataMgr == nullptr) {
4242         APP_LOGE("dataMgr is nullptr");
4243         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4244     }
4245     return dataMgr->GetAdditionalInfoForAllUser(bundleName, additionalInfo);
4246 }
4247 
SetExtNameOrMIMEToApp(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & extName,const std::string & mimeType)4248 ErrCode BundleMgrHostImpl::SetExtNameOrMIMEToApp(const std::string &bundleName, const std::string &moduleName,
4249     const std::string &abilityName, const std::string &extName, const std::string &mimeType)
4250 {
4251     APP_LOGD("SetExtNameOrMIMEToApp bundleName: %{public}s, moduleName: %{public}s, \
4252         abilityName: %{public}s, extName: %{public}s, mimeType: %{public}s",
4253         bundleName.c_str(), moduleName.c_str(), abilityName.c_str(), extName.c_str(), mimeType.c_str());
4254     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4255         APP_LOGE("verify permission failed");
4256         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4257     }
4258     auto dataMgr = GetDataMgrFromService();
4259     if (dataMgr == nullptr) {
4260         APP_LOGE("dataMgr is nullptr");
4261         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4262     }
4263     return dataMgr->SetExtNameOrMIMEToApp(bundleName, moduleName, abilityName, extName, mimeType);
4264 }
4265 
DelExtNameOrMIMEToApp(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & extName,const std::string & mimeType)4266 ErrCode BundleMgrHostImpl::DelExtNameOrMIMEToApp(const std::string &bundleName, const std::string &moduleName,
4267     const std::string &abilityName, const std::string &extName, const std::string &mimeType)
4268 {
4269     APP_LOGD("DelExtNameOrMIMEToApp bundleName: %{public}s, moduleName: %{public}s, \
4270         abilityName: %{public}s, extName: %{public}s, mimeType: %{public}s",
4271         bundleName.c_str(), moduleName.c_str(), abilityName.c_str(), extName.c_str(), mimeType.c_str());
4272     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4273         APP_LOGE("verify permission failed");
4274         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4275     }
4276     auto dataMgr = GetDataMgrFromService();
4277     if (dataMgr == nullptr) {
4278         APP_LOGE("dataMgr is nullptr");
4279         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4280     }
4281     return dataMgr->DelExtNameOrMIMEToApp(bundleName, moduleName, abilityName, extName, mimeType);
4282 }
4283 
QueryDataGroupInfos(const std::string & bundleName,int32_t userId,std::vector<DataGroupInfo> & infos)4284 bool BundleMgrHostImpl::QueryDataGroupInfos(const std::string &bundleName, int32_t userId,
4285     std::vector<DataGroupInfo> &infos)
4286 {
4287     APP_LOGD("QueryDataGroupInfos bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId);
4288     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4289         APP_LOGE("verify permission failed");
4290         return false;
4291     }
4292     auto dataMgr = GetDataMgrFromService();
4293     if (dataMgr == nullptr) {
4294         APP_LOGE("dataMgr is nullptr");
4295         return false;
4296     }
4297     return dataMgr->QueryDataGroupInfos(bundleName, userId, infos);
4298 }
4299 
GetGroupDir(const std::string & dataGroupId,std::string & dir)4300 bool BundleMgrHostImpl::GetGroupDir(const std::string &dataGroupId, std::string &dir)
4301 {
4302     APP_LOGD("GetGroupDir dataGroupId: %{public}s", dataGroupId.c_str());
4303     auto dataMgr = GetDataMgrFromService();
4304     if (dataMgr == nullptr) {
4305         APP_LOGE("dataMgr is nullptr");
4306         return false;
4307     }
4308     return dataMgr->GetGroupDir(dataGroupId, dir);
4309 }
4310 
SetBrokerServiceStatus(bool isServiceExisted)4311 void BundleMgrHostImpl::SetBrokerServiceStatus(bool isServiceExisted)
4312 {
4313     APP_LOGD("broker service status is %{public}d", isServiceExisted);
4314     isBrokerServiceExisted_ = isServiceExisted;
4315 }
4316 
QueryAppGalleryBundleName(std::string & bundleName)4317 bool BundleMgrHostImpl::QueryAppGalleryBundleName(std::string &bundleName)
4318 {
4319     APP_LOGD("QueryAppGalleryBundleName in bundle host impl start");
4320     bundleName = OHOS::system::GetParameter(ServiceConstants::CLOUD_SHADER_OWNER, "");
4321     if (bundleName.empty()) {
4322         APP_LOGW("AppGallery GetParameter is empty");
4323         return false;
4324     }
4325     APP_LOGD("bundleName is %{public}s", bundleName.c_str());
4326     return  true;
4327 }
4328 
GetLabelByBundleName(const std::string & bundleName,int32_t userId,std::string & result)4329 bool BundleMgrHostImpl::GetLabelByBundleName(const std::string &bundleName, int32_t userId, std::string &result)
4330 {
4331     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
4332     APP_LOGI("GetLabelByBundleName -n %{public}s -u %{public}d", bundleName.c_str(), userId);
4333     if (!BundlePermissionMgr::IsSystemApp()) {
4334         APP_LOGE("Non-system app calling system api");
4335         return false;
4336     }
4337 
4338     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4339         APP_LOGE("Verify permission failed");
4340         return false;
4341     }
4342 #ifdef BUNDLE_FRAMEWORK_BUNDLE_RESOURCE
4343     auto dataMgr = GetDataMgrFromService();
4344     if (dataMgr == nullptr) {
4345         APP_LOGE("dataMgr is nullptr");
4346         return false;
4347     }
4348 
4349     if (!dataMgr->HasAppOrAtomicServiceInUser(bundleName, userId)) {
4350         APP_LOGE("find fail");
4351         return false;
4352     }
4353     auto manager = DelayedSingleton<BundleResourceManager>::GetInstance();
4354     if (manager == nullptr) {
4355         APP_LOGE("manager nullptr, bundleName %{public}s", bundleName.c_str());
4356         return false;
4357     }
4358 
4359     BundleResourceInfo bundleResourceInfo;
4360     uint32_t flags = static_cast<uint32_t>(ResourceFlag::GET_RESOURCE_INFO_WITH_LABEL);
4361     if (!manager->GetBundleResourceInfo(bundleName, flags, bundleResourceInfo)) {
4362         APP_LOGE_NOFUNC("get resource failed -n %{public}s -f %{public}u", bundleName.c_str(), flags);
4363         return false;
4364     }
4365     result.append(bundleResourceInfo.label);
4366     result.append(NEW_LINE);
4367 #else
4368     APP_LOGI("bundle resurce not support");
4369     result.append(RESOURCE_NOT_SUPPORT);
4370 #endif
4371     return true;
4372 }
4373 
GetAllBundleLabel(int32_t userId,std::string & labels)4374 bool BundleMgrHostImpl::GetAllBundleLabel(int32_t userId, std::string &labels)
4375 {
4376     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
4377     APP_LOGI("GetAllBundleLabel -u %{public}d", userId);
4378     if (!BundlePermissionMgr::IsSystemApp()) {
4379         APP_LOGE("Non-system app calling system api");
4380         return false;
4381     }
4382     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4383         APP_LOGE("Verify permission failed");
4384         return false;
4385     }
4386 #ifdef BUNDLE_FRAMEWORK_BUNDLE_RESOURCE
4387     auto dataMgr = GetDataMgrFromService();
4388     if (dataMgr == nullptr) {
4389         APP_LOGE("dataMgr is nullptr");
4390         return false;
4391     }
4392     std::vector<std::string> bundleList;
4393     if (!dataMgr->GetAllAppAndAtomicServiceInUser(userId, bundleList)) {
4394         APP_LOGE("get failed user %{public}d", userId);
4395         return false;
4396     }
4397     auto manager = DelayedSingleton<BundleResourceManager>::GetInstance();
4398     if (manager == nullptr) {
4399         APP_LOGE("manager nullptr");
4400         return false;
4401     }
4402     nlohmann::json jsonArray = nlohmann::json::array();
4403     for (const std::string &bundleName : bundleList) {
4404         BundleResourceInfo bundleResourceInfo;
4405         uint32_t flags = static_cast<uint32_t>(ResourceFlag::GET_RESOURCE_INFO_WITH_LABEL);
4406         if (!manager->GetBundleResourceInfo(bundleName, flags, bundleResourceInfo)) {
4407             APP_LOGE_NOFUNC("get resource failed -n %{public}s -f %{public}u", bundleName.c_str(), flags);
4408             continue;
4409         }
4410         nlohmann::json entry;
4411         entry[BUNDLE_NAME] = bundleResourceInfo.bundleName;
4412         entry[LABEL] = bundleResourceInfo.label;
4413         jsonArray.push_back(entry);
4414     }
4415     labels.append(jsonArray.dump(JSON_INDENTATION));
4416     labels.append(NEW_LINE);
4417 #else
4418     APP_LOGI("bundle resurce not support");
4419     labels.append(RESOURCE_NOT_SUPPORT);
4420 #endif
4421     return true;
4422 }
4423 
QueryExtensionAbilityInfosWithTypeName(const Want & want,const std::string & typeName,int32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos)4424 ErrCode BundleMgrHostImpl::QueryExtensionAbilityInfosWithTypeName(const Want &want, const std::string &typeName,
4425     int32_t flags, int32_t userId, std::vector<ExtensionAbilityInfo> &extensionInfos)
4426 {
4427     if (!BundlePermissionMgr::IsSystemApp()) {
4428         LOG_E(BMS_TAG_QUERY, "Non-system app calling system api");
4429         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4430     }
4431     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
4432         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
4433         !BundlePermissionMgr::IsBundleSelfCalling(want.GetElement().GetBundleName())) {
4434         LOG_E(BMS_TAG_QUERY, "Verify permission failed");
4435         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4436     }
4437     auto dataMgr = GetDataMgrFromService();
4438     if (dataMgr == nullptr) {
4439         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
4440         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4441     }
4442     std::vector<ExtensionAbilityInfo> infos;
4443     ErrCode ret = dataMgr->QueryExtensionAbilityInfosV9(want, flags, userId, infos);
4444     dataMgr->QueryAllCloneExtensionInfosV9(want, flags, userId, infos);
4445     if (infos.empty()) {
4446         if (ret != ERR_OK) {
4447             LOG_E(BMS_TAG_QUERY,
4448                 "QueryExtensionAbilityInfosV9 is failed, -type %{public}s, -f %{public}d -u %{public}d ret: %{public}d",
4449                 typeName.c_str(), flags, userId, ret);
4450             return ret;
4451         }
4452         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
4453     }
4454     if (typeName.empty()) {
4455         extensionInfos = infos;
4456     } else {
4457         for_each(infos.begin(), infos.end(), [&typeName, &extensionInfos](const auto &info)->decltype(auto) {
4458             APP_LOGD("Input typeName is %{public}s, info.type is %{public}s",
4459                 typeName.c_str(), info.extensionTypeName.c_str());
4460             if (typeName == info.extensionTypeName) {
4461                 extensionInfos.emplace_back(info);
4462             }
4463         });
4464     }
4465     if (extensionInfos.empty()) {
4466         LOG_W(BMS_TAG_QUERY, "No valid extension info can be inquired");
4467         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
4468     }
4469     return ERR_OK;
4470 }
4471 
QueryExtensionAbilityInfosOnlyWithTypeName(const std::string & typeName,uint32_t flags,int32_t userId,std::vector<ExtensionAbilityInfo> & extensionInfos)4472 ErrCode BundleMgrHostImpl::QueryExtensionAbilityInfosOnlyWithTypeName(const std::string &typeName,
4473     uint32_t flags, int32_t userId, std::vector<ExtensionAbilityInfo> &extensionInfos)
4474 {
4475     if (!BundlePermissionMgr::IsSystemApp()) {
4476         APP_LOGE("Non-system app calling system api");
4477         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4478     }
4479     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
4480         Constants::PERMISSION_GET_BUNDLE_INFO})) {
4481         APP_LOGE("Verify permission failed");
4482         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4483     }
4484     auto dataMgr = GetDataMgrFromService();
4485     if (dataMgr == nullptr) {
4486         APP_LOGE("DataMgr is nullptr");
4487         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4488     }
4489     if (typeName.empty()) {
4490         APP_LOGE("Input typeName is empty");
4491         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
4492     }
4493     std::vector<ExtensionAbilityInfo> infos;
4494     ErrCode ret = dataMgr->QueryExtensionAbilityInfosByExtensionTypeName(typeName, flags, userId, infos);
4495     if (ret != ERR_OK) {
4496         APP_LOGE("QueryExtensionAbilityInfosByExtensionTypeName is failed");
4497         return ret;
4498     }
4499     if ((flags &
4500         static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_BY_TYPE_NAME)) ==
4501         static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_BY_TYPE_NAME)) {
4502         extensionInfos = infos;
4503         return ret;
4504     }
4505     for_each(infos.begin(), infos.end(), [&typeName, &extensionInfos](const auto &info)->decltype(auto) {
4506         APP_LOGD("Input typeName is %{public}s, info.type is %{public}s",
4507             typeName.c_str(), info.extensionTypeName.c_str());
4508         if (typeName == info.extensionTypeName) {
4509             extensionInfos.emplace_back(info);
4510         }
4511     });
4512     if (extensionInfos.empty()) {
4513         APP_LOGW("No valid extension info can be inquired");
4514         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
4515     }
4516     return ERR_OK;
4517 }
4518 
ResetAOTCompileStatus(const std::string & bundleName,const std::string & moduleName,int32_t triggerMode)4519 ErrCode BundleMgrHostImpl::ResetAOTCompileStatus(const std::string &bundleName, const std::string &moduleName,
4520     int32_t triggerMode)
4521 {
4522     APP_LOGD("ResetAOTCompileStatus begin");
4523     auto dataMgr = GetDataMgrFromService();
4524     if (dataMgr == nullptr) {
4525         APP_LOGE("dataMgr is null");
4526         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4527     }
4528     std::string callingBundleName;
4529     ErrCode ret = dataMgr->GetNameForUid(IPCSkeleton::GetCallingUid(), callingBundleName);
4530     if (ret != ERR_OK || bundleName != callingBundleName) {
4531         APP_LOGE("verify permission failed");
4532         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4533     }
4534     return dataMgr->ResetAOTCompileStatus(bundleName, moduleName, triggerMode);
4535 }
4536 
GetJsonProfile(ProfileType profileType,const std::string & bundleName,const std::string & moduleName,std::string & profile,int32_t userId)4537 ErrCode BundleMgrHostImpl::GetJsonProfile(ProfileType profileType, const std::string &bundleName,
4538     const std::string &moduleName, std::string &profile, int32_t userId)
4539 {
4540     APP_LOGD("GetJsonProfile profileType: %{public}d, bundleName: %{public}s, moduleName: %{public}s"
4541         "userId: %{public}d", profileType, bundleName.c_str(), moduleName.c_str(), userId);
4542     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED,
4543         Constants::PERMISSION_GET_BUNDLE_INFO}) &&
4544         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
4545         APP_LOGE("verify permission failed");
4546         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4547     }
4548     if (!BundlePermissionMgr::IsSystemApp() &&
4549         profileType != ProfileType::NETWORK_PROFILE &&
4550         profileType != ProfileType::PKG_CONTEXT_PROFILE) {
4551         APP_LOGE("non-system app calling system api");
4552         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4553     }
4554     auto dataMgr = GetDataMgrFromService();
4555     if (dataMgr == nullptr) {
4556         APP_LOGE("dataMgr is nullptr");
4557         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4558     }
4559     return dataMgr->GetJsonProfile(profileType, bundleName, moduleName, profile, userId);
4560 }
4561 
SetAdditionalInfo(const std::string & bundleName,const std::string & additionalInfo)4562 ErrCode BundleMgrHostImpl::SetAdditionalInfo(const std::string &bundleName, const std::string &additionalInfo)
4563 {
4564     APP_LOGD("Called. BundleName: %{public}s", bundleName.c_str());
4565     if (!BundlePermissionMgr::IsSystemApp()) {
4566         APP_LOGE("Non-system app calling system api");
4567         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4568     }
4569 
4570     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4571         APP_LOGE("Verify permission failed");
4572         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4573     }
4574 
4575     std::string appGalleryBundleName;
4576     QueryAppGalleryBundleName(appGalleryBundleName);
4577 
4578     std::string callingBundleName;
4579     ObtainCallingBundleName(callingBundleName);
4580 
4581     if (appGalleryBundleName.empty() || callingBundleName.empty() || appGalleryBundleName != callingBundleName) {
4582         APP_LOGE("Failed, appGalleryBundleName: %{public}s. callingBundleName: %{public}s",
4583             appGalleryBundleName.c_str(), callingBundleName.c_str());
4584         return ERR_BUNDLE_MANAGER_NOT_APP_GALLERY_CALL;
4585     }
4586 
4587     auto dataMgr = GetDataMgrFromService();
4588     if (dataMgr == nullptr) {
4589         APP_LOGE("DataMgr is nullptr");
4590         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4591     }
4592     return dataMgr->SetAdditionalInfo(bundleName, additionalInfo);
4593 }
4594 
CreateBundleDataDir(int32_t userId)4595 ErrCode BundleMgrHostImpl::CreateBundleDataDir(int32_t userId)
4596 {
4597     if (!BundlePermissionMgr::IsCallingUidValid(Constants::ROOT_UID)) {
4598         APP_LOGE("IsCallingUidValid failed");
4599         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4600     }
4601 
4602     auto dataMgr = GetDataMgrFromService();
4603     if (dataMgr == nullptr) {
4604         APP_LOGE("DataMgr is nullptr");
4605         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4606     }
4607     return dataMgr->CreateBundleDataDir(userId);
4608 }
4609 
CreateBundleDataDirWithEl(int32_t userId,DataDirEl dirEl)4610 ErrCode BundleMgrHostImpl::CreateBundleDataDirWithEl(int32_t userId, DataDirEl dirEl)
4611 {
4612     if (!BundlePermissionMgr::IsCallingUidValid(Constants::ROOT_UID)) {
4613         APP_LOGE("IsCallingUidValid failed");
4614         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4615     }
4616 
4617     auto dataMgr = GetDataMgrFromService();
4618     if (dataMgr == nullptr) {
4619         APP_LOGE("DataMgr is nullptr");
4620         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4621     }
4622     return dataMgr->CreateBundleDataDirWithEl(userId, dirEl);
4623 }
4624 
UpdateAppEncryptedStatus(const std::string & bundleName,bool isExisted,int32_t appIndex)4625 ErrCode BundleMgrHostImpl::UpdateAppEncryptedStatus(const std::string &bundleName, bool isExisted, int32_t appIndex)
4626 {
4627     if (!BundlePermissionMgr::IsCallingUidValid(Constants::CODE_PROTECT_UID)) {
4628         APP_LOGE("IsCallingUidValid failed");
4629         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4630     }
4631 
4632     auto dataMgr = GetDataMgrFromService();
4633     if (dataMgr == nullptr) {
4634         APP_LOGE("DataMgr is nullptr");
4635         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4636     }
4637     return dataMgr->UpdateAppEncryptedStatus(bundleName, isExisted, appIndex);
4638 }
4639 
MigrateData(const std::vector<std::string> & sourcePaths,const std::string & destinationPath)4640 ErrCode BundleMgrHostImpl::MigrateData(const std::vector<std::string> &sourcePaths, const std::string &destinationPath)
4641 {
4642     APP_LOGI("MigrateData start");
4643     if (!BundlePermissionMgr::IsSystemApp()) {
4644         APP_LOGE("Non-system app calling system api");
4645         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4646     }
4647 
4648     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_MIGRATE_DATA)) {
4649         APP_LOGE("Verify permission failed");
4650         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4651     }
4652 
4653     std::vector<std::string> filteredSourcePaths = sourcePaths;
4654     std::string filteredDestPath = destinationPath;
4655     auto result = MigrateDataParameterCheck(filteredSourcePaths, filteredDestPath);
4656     if (result != ERR_OK) {
4657         APP_LOGE("migrate data parameter check err:%{public}d", result);
4658         return result;
4659     }
4660 
4661     result = MigrateDataUserAuthentication();
4662     if (result != ERR_OK) {
4663         APP_LOGE("migrate data user authentication err:%{public}d", result);
4664         return result;
4665     }
4666 
4667     auto installdClient = InstalldClient::GetInstance();
4668     if (installdClient == nullptr) {
4669         APP_LOGE("get install client err");
4670         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_OTHER_REASON_FAILED;
4671     }
4672 
4673     result = installdClient->MigrateData(filteredSourcePaths, filteredDestPath);
4674     if (result != ERR_OK) {
4675         APP_LOGE("migrate data filesd, errcode:%{public}d", result);
4676     }
4677     APP_LOGI("MigrateData end");
4678     return result;
4679 }
4680 
MigrateDataParameterCheck(std::vector<std::string> & sourcePaths,std::string & destinationPath)4681 ErrCode BundleMgrHostImpl::MigrateDataParameterCheck(
4682     std::vector<std::string> &sourcePaths, std::string &destinationPath)
4683 {
4684     if (sourcePaths.size() > VECTOR_SIZE_MAX) {
4685         APP_LOGE("source paths size out of range");
4686         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_SOURCE_PATH_INVALID;
4687     }
4688     auto checkPath = [](const auto &path) { return path.find(ServiceConstants::RELATIVE_PATH) != std::string::npos; };
4689     if (sourcePaths.empty() || std::any_of(sourcePaths.begin(), sourcePaths.end(), checkPath)) {
4690         APP_LOGE("source paths check err");
4691         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_SOURCE_PATH_INVALID;
4692     }
4693     if (destinationPath.empty() || checkPath(destinationPath)) {
4694         APP_LOGE("destinationPath err: %{private}s", destinationPath.c_str());
4695         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_DESTINATION_PATH_INVALID;
4696     }
4697     return CheckSandboxPath(sourcePaths, destinationPath);
4698 }
4699 
CheckSandboxPath(std::vector<std::string> & sourcePaths,std::string & destinationPath)4700 ErrCode BundleMgrHostImpl::CheckSandboxPath(std::vector<std::string> &sourcePaths, std::string &destinationPath)
4701 {
4702     bool sourcePathCheck = std::any_of(
4703         sourcePaths.begin(), sourcePaths.end(), [](const auto &path) { return BundleUtil::IsSandBoxPath(path); });
4704     if (!sourcePathCheck && !BundleUtil::IsSandBoxPath(destinationPath)) {
4705         APP_LOGD("the current paths does not involve sandbox path");
4706         return ERR_OK;
4707     }
4708     auto dataMgr = GetDataMgrFromService();
4709     if (dataMgr == nullptr) {
4710         APP_LOGE("DataMgr is nullptr");
4711         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_OTHER_REASON_FAILED;
4712     }
4713     auto uid = IPCSkeleton::GetCallingUid();
4714     std::string bundleName;
4715     if (!dataMgr->GetBundleNameForUid(uid, bundleName)) {
4716         APP_LOGE("GetBundleNameForUid failed uid:%{public}d", uid);
4717         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_OTHER_REASON_FAILED;
4718     }
4719     std::string realPath{ "" };
4720     for (size_t index = 0; index < sourcePaths.size(); ++index) {
4721         if (!BundleUtil::IsSandBoxPath(sourcePaths[index])) {
4722             continue;
4723         }
4724         if (BundleUtil::RevertToRealPath(sourcePaths[index], bundleName, realPath)) {
4725             APP_LOGD("convert source sandbox path[%{public}s] to read path[%{public}s]", sourcePaths[index].c_str(),
4726                 realPath.c_str());
4727             sourcePaths[index] = realPath;
4728         }
4729     }
4730     if (BundleUtil::IsSandBoxPath(destinationPath)) {
4731         if (BundleUtil::RevertToRealPath(destinationPath, bundleName, realPath)) {
4732             APP_LOGD("convert destination sandbox path[%{public}s] to read path[%{public}s]", destinationPath.c_str(),
4733                 realPath.c_str());
4734             destinationPath = realPath;
4735         } else {
4736             APP_LOGE("destination path[%{public}s] revert to real path invalid", destinationPath.c_str());
4737             return ERR_BUNDLE_MANAGER_MIGRATE_DATA_DESTINATION_PATH_INVALID;
4738         }
4739     }
4740     return ERR_OK;
4741 }
4742 
MigrateDataUserAuthentication()4743 ErrCode BundleMgrHostImpl::MigrateDataUserAuthentication()
4744 {
4745 #ifdef BMS_USER_AUTH_FRAMEWORK_ENABLED
4746     int32_t userId = AccountHelper::GetCurrentActiveUserId();
4747     if (userId == Constants::INVALID_USERID) {
4748         APP_LOGE("userId %{public}d is invalid", userId);
4749         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
4750     }
4751     std::vector<UserIam::UserAuth::AuthType> authTypes{ UserIam::UserAuth::AuthType::PIN,
4752         UserIam::UserAuth::AuthType::FACE, UserIam::UserAuth::AuthType::FINGERPRINT };
4753     u_int8_t keyLength{ 32 };
4754     u_int8_t keyMinValue{ 0 };
4755     u_int8_t keyMaxValue{ 9 };
4756 
4757     UserIam::UserAuth::WidgetAuthParam authParam;
4758     authParam.userId = userId;
4759     authParam.challenge = BundleUtil::GenerateRandomNumbers(keyLength, keyMinValue, keyMaxValue);
4760     authParam.authTypes = authTypes;
4761     authParam.authTrustLevel = UserIam::UserAuth::AuthTrustLevel::ATL3;
4762 
4763     UserIam::UserAuth::WidgetParam widgetInfo;
4764     widgetInfo.title = AUTH_TITLE;
4765     widgetInfo.windowMode = UserIam::UserAuth::WindowModeType::UNKNOWN_WINDOW_MODE;
4766 
4767     std::shared_ptr<MigrateDataUserAuthCallback> userAuthaCallback = std::make_shared<MigrateDataUserAuthCallback>();
4768     if (userAuthaCallback == nullptr) {
4769         APP_LOGE("make shared err!");
4770         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_USER_AUTHENTICATION_FAILED;
4771     }
4772     auto contextId =
4773         UserIam::UserAuth::UserAuthClientImpl::GetInstance().BeginWidgetAuth(authParam, widgetInfo, userAuthaCallback);
4774     if (contextId == BAD_CONTEXT_ID) {
4775         APP_LOGE("begin user auth err!");
4776         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_USER_AUTHENTICATION_FAILED;
4777     }
4778     auto result = userAuthaCallback->GetUserAuthResult();
4779     if (result != ERR_OK) {
4780         APP_LOGE("user auth err:%{public}d", result);
4781         if (result == ERR_BUNDLE_MANAGER_MIGRATE_DATA_USER_AUTHENTICATION_TIME_OUT) {
4782             UserIam::UserAuth::UserAuthClientImpl::GetInstance().CancelAuthentication(contextId);
4783             return result;
4784         }
4785         return ERR_BUNDLE_MANAGER_MIGRATE_DATA_USER_AUTHENTICATION_FAILED;
4786     }
4787     return ERR_OK;
4788 #else
4789     APP_LOGE("user auth framework is not enabled");
4790     return ERR_BUNDLE_MANAGER_MIGRATE_DATA_USER_AUTHENTICATION_FAILED;
4791 #endif
4792 }
4793 
GetBundleResourceProxy()4794 sptr<IBundleResource> BundleMgrHostImpl::GetBundleResourceProxy()
4795 {
4796 #ifdef BUNDLE_FRAMEWORK_BUNDLE_RESOURCE
4797     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_BUNDLE_RESOURCE_PROXY);
4798     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
4799     return DelayedSingleton<BundleMgrService>::GetInstance()->GetBundleResourceProxy();
4800 #else
4801     return nullptr;
4802 #endif
4803 }
4804 
GetPreferableBundleInfoFromHapPaths(const std::vector<std::string> & hapPaths,BundleInfo & bundleInfo)4805 bool BundleMgrHostImpl::GetPreferableBundleInfoFromHapPaths(const std::vector<std::string> &hapPaths,
4806     BundleInfo &bundleInfo)
4807 {
4808     if (hapPaths.empty()) {
4809         return false;
4810     }
4811     for (auto hapPath: hapPaths) {
4812         BundleInfo resultBundleInfo;
4813         if (!GetBundleArchiveInfo(hapPath, GET_BUNDLE_DEFAULT, resultBundleInfo)) {
4814             return false;
4815         }
4816         bundleInfo = resultBundleInfo;
4817         if (!bundleInfo.hapModuleInfos.empty()) {
4818             bundleInfo.hapModuleInfos[0].hapPath = hapPath;
4819             if (bundleInfo.hapModuleInfos[0].moduleType == ModuleType::ENTRY) {
4820                 return true;
4821             }
4822         }
4823     }
4824     return true;
4825 }
4826 
GetRecoverableApplicationInfo(std::vector<RecoverableApplicationInfo> & recoverableApplicaitons)4827 ErrCode BundleMgrHostImpl::GetRecoverableApplicationInfo(
4828     std::vector<RecoverableApplicationInfo> &recoverableApplicaitons)
4829 {
4830     APP_LOGD("begin to GetRecoverableApplicationInfo");
4831     if (!BundlePermissionMgr::IsSystemApp()) {
4832         APP_LOGE("non-system app calling system api");
4833         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4834     }
4835     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4836         APP_LOGE("verify permission failed");
4837         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4838     }
4839     auto dataMgr = GetDataMgrFromService();
4840     if (dataMgr == nullptr) {
4841         APP_LOGE("dataMgr is nullptr");
4842         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4843     }
4844     int32_t userId = AccountHelper::GetCurrentActiveUserId();
4845     if (userId == Constants::INVALID_USERID) {
4846         APP_LOGE("userId %{public}d is invalid", userId);
4847         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
4848     }
4849     BmsExtensionDataMgr bmsExtensionDataMgr;
4850     std::vector<PreInstallBundleInfo> recoverableBundleInfos = dataMgr->GetRecoverablePreInstallBundleInfos();
4851     for (auto recoverableBundleInfo: recoverableBundleInfos) {
4852         std::string bundleName = recoverableBundleInfo.GetBundleName();
4853         if (bmsExtensionDataMgr.IsAppInBlocklist(bundleName, userId)) {
4854             APP_LOGI("recover app %{public}s is in blocklist", bundleName.c_str());
4855             continue;
4856         }
4857         RecoverableApplicationInfo recoverableApplication;
4858         recoverableApplication.bundleName = bundleName;
4859         recoverableApplication.labelId = recoverableBundleInfo.GetLabelId();
4860         recoverableApplication.iconId = recoverableBundleInfo.GetIconId();
4861         recoverableApplication.systemApp = recoverableBundleInfo.GetSystemApp();
4862         recoverableApplication.codePaths = recoverableBundleInfo.GetBundlePaths();
4863         recoverableApplication.moduleName = recoverableBundleInfo.GetModuleName();
4864         recoverableApplication.bundleType = recoverableBundleInfo.GetBundleType();
4865         recoverableApplicaitons.emplace_back(recoverableApplication);
4866     }
4867     return ERR_OK;
4868 }
4869 
GetUninstalledBundleInfo(const std::string bundleName,BundleInfo & bundleInfo)4870 ErrCode BundleMgrHostImpl::GetUninstalledBundleInfo(const std::string bundleName, BundleInfo &bundleInfo)
4871 {
4872     APP_LOGD("begin to GetUninstalledBundleInfo");
4873     if (!BundlePermissionMgr::IsSystemApp()) {
4874         APP_LOGE("non-system app calling system api");
4875         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4876     }
4877     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4878         APP_LOGE("verify permission failed");
4879         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4880     }
4881     auto dataMgr = GetDataMgrFromService();
4882     if (dataMgr == nullptr) {
4883         APP_LOGE("dataMgr is nullptr");
4884         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4885     }
4886     int32_t userId = AccountHelper::GetCurrentActiveUserId();
4887     if (userId == Constants::INVALID_USERID) {
4888         APP_LOGE("userId %{public}d is invalid", userId);
4889         return ERR_BUNDLE_MANAGER_INVALID_USER_ID;
4890     }
4891     if (dataMgr->HasUserInstallInBundle(bundleName, Constants::DEFAULT_USERID) ||
4892         dataMgr->HasUserInstallInBundle(bundleName, Constants::U1) ||
4893         dataMgr->HasUserInstallInBundle(bundleName, userId)) {
4894         APP_LOGE("bundle has installed");
4895         return ERR_APPEXECFWK_FAILED_GET_BUNDLE_INFO;
4896     }
4897     PreInstallBundleInfo preInstallBundleInfo;
4898     if (!dataMgr->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)) {
4899         APP_LOGE("get preinstallBundleInfo failed");
4900         return ERR_APPEXECFWK_FAILED_GET_BUNDLE_INFO;
4901     }
4902     if (!GetPreferableBundleInfoFromHapPaths(
4903         preInstallBundleInfo.GetBundlePaths(), bundleInfo)) {
4904         APP_LOGE("prefect bundle is not found");
4905         return ERR_APPEXECFWK_FAILED_GET_BUNDLE_INFO;
4906     }
4907     return ERR_OK;
4908 }
4909 
IsBundleExist(const std::string & bundleName)4910 bool BundleMgrHostImpl::IsBundleExist(const std::string &bundleName)
4911 {
4912     auto dataMgr = GetDataMgrFromService();
4913     if (dataMgr == nullptr) {
4914         APP_LOGE("Mgr is nullptr");
4915         return false;
4916     }
4917     return dataMgr->IsBundleExist(bundleName);
4918 }
4919 
ClearCache(const std::string & bundleName,const sptr<ICleanCacheCallback> cleanCacheCallback,int32_t userId,int32_t callingUid,const std::string & callingBundleName)4920 ErrCode BundleMgrHostImpl::ClearCache(const std::string &bundleName,
4921     const sptr<ICleanCacheCallback> cleanCacheCallback, int32_t userId,
4922     int32_t callingUid, const std::string &callingBundleName)
4923 {
4924     auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
4925     ErrCode ret = bmsExtensionClient->ClearCache(bundleName, cleanCacheCallback->AsObject(), userId);
4926     APP_LOGI("ret : %{public}d", ret);
4927     if (ret != ERR_OK) {
4928         ret = ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
4929     }
4930     EventReport::SendCleanCacheSysEvent(bundleName, userId, true, ret != ERR_OK, callingUid, callingBundleName);
4931     return ret;
4932 }
4933 
CanOpenLink(const std::string & link,bool & canOpen)4934 ErrCode BundleMgrHostImpl::CanOpenLink(
4935     const std::string &link, bool &canOpen)
4936 {
4937     APP_LOGD("start CanOpenLink, link : %{public}s", link.c_str());
4938     auto dataMgr = GetDataMgrFromService();
4939     if (dataMgr == nullptr) {
4940         APP_LOGE("DataMgr is nullptr");
4941         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4942     }
4943     return dataMgr->CanOpenLink(link, canOpen);
4944 }
4945 
GetOdid(std::string & odid)4946 ErrCode BundleMgrHostImpl::GetOdid(std::string &odid)
4947 {
4948     APP_LOGD("start GetOdid");
4949     auto dataMgr = GetDataMgrFromService();
4950     if (dataMgr == nullptr) {
4951         APP_LOGE("DataMgr is nullptr");
4952         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4953     }
4954     return dataMgr->GetOdid(odid);
4955 }
4956 
GetAllPreinstalledApplicationInfos(std::vector<PreinstalledApplicationInfo> & preinstalledApplicationInfos)4957 ErrCode BundleMgrHostImpl::GetAllPreinstalledApplicationInfos(
4958     std::vector<PreinstalledApplicationInfo> &preinstalledApplicationInfos)
4959 {
4960     if (!BundlePermissionMgr::IsSystemApp()) {
4961         APP_LOGE("Non-system app calling system api");
4962         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4963     }
4964     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4965         APP_LOGE("Verify permission failed");
4966         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4967     }
4968     auto dataMgr = GetDataMgrFromService();
4969     if (dataMgr == nullptr) {
4970         APP_LOGE("DataMgr is nullptr");
4971         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
4972     }
4973     std::vector<PreInstallBundleInfo> preInstallBundleInfos = dataMgr->GetAllPreInstallBundleInfos();
4974     for (auto &preInstallBundleInfo: preInstallBundleInfos) {
4975         AddPreinstalledApplicationInfo(preInstallBundleInfo, preinstalledApplicationInfos);
4976     }
4977     std::vector<PreInstallBundleInfo> onDemandBundleInfos;
4978     OnDemandInstallDataMgr::GetInstance().GetAllOnDemandInstallBundleInfos(onDemandBundleInfos);
4979     for (auto &onDemandBundleInfo: onDemandBundleInfos) {
4980         AddPreinstalledApplicationInfo(onDemandBundleInfo, preinstalledApplicationInfos);
4981     }
4982     return ERR_OK;
4983 }
4984 
GetAllBundleInfoByDeveloperId(const std::string & developerId,std::vector<BundleInfo> & bundleInfos,int32_t userId)4985 ErrCode BundleMgrHostImpl::GetAllBundleInfoByDeveloperId(const std::string &developerId,
4986     std::vector<BundleInfo> &bundleInfos, int32_t userId)
4987 {
4988     APP_LOGI("start GetAllBundleInfoByDeveloperId for developerId: %{public}s with user: %{public}d",
4989         developerId.c_str(), userId);
4990     if (!BundlePermissionMgr::IsSystemApp()) {
4991         APP_LOGE("non-system app calling system api");
4992         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
4993     }
4994     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
4995         APP_LOGE("verify permission failed");
4996         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
4997     }
4998     APP_LOGI("verify permission success, begin to GetAllBundleInfoByDeveloperId");
4999     auto dataMgr = GetDataMgrFromService();
5000     if (dataMgr == nullptr) {
5001         APP_LOGE("DataMgr is nullptr");
5002         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5003     }
5004     return dataMgr->GetAllBundleInfoByDeveloperId(developerId, bundleInfos, userId);
5005 }
5006 
GetDeveloperIds(const std::string & appDistributionType,std::vector<std::string> & developerIdList,int32_t userId)5007 ErrCode BundleMgrHostImpl::GetDeveloperIds(const std::string &appDistributionType,
5008     std::vector<std::string> &developerIdList, int32_t userId)
5009 {
5010     APP_LOGI("start GetDeveloperIds for appDistributionType: %{public}s with user: %{public}d",
5011         appDistributionType.c_str(), userId);
5012     if (!BundlePermissionMgr::IsSystemApp()) {
5013         APP_LOGE("non-system app calling system api");
5014         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5015     }
5016     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5017         APP_LOGE("verify permission failed");
5018         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5019     }
5020     APP_LOGI("verify permission success, begin to GetDeveloperIds");
5021     auto dataMgr = GetDataMgrFromService();
5022     if (dataMgr == nullptr) {
5023         APP_LOGE("DataMgr is nullptr");
5024         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5025     }
5026     return dataMgr->GetDeveloperIds(appDistributionType, developerIdList, userId);
5027 }
5028 
SwitchUninstallState(const std::string & bundleName,const bool & state,bool isNeedSendNotify)5029 ErrCode BundleMgrHostImpl::SwitchUninstallState(const std::string &bundleName, const bool &state,
5030     bool isNeedSendNotify)
5031 {
5032     APP_LOGD("start SwitchUninstallState, bundleName : %{public}s, state : %{public}d", bundleName.c_str(), state);
5033     if (!BundlePermissionMgr::IsSystemApp()) {
5034         APP_LOGE("non-system app calling system api");
5035         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5036     }
5037     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(
5038         ServiceConstants::PERMISSION_CHANGE_BUNDLE_UNINSTALL_STATE)) {
5039         APP_LOGE("verify permission failed");
5040         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5041     }
5042     APP_LOGD("verify permission success, begin to SwitchUninstallState");
5043     auto dataMgr = GetDataMgrFromService();
5044     if (dataMgr == nullptr) {
5045         APP_LOGE("DataMgr is nullptr");
5046         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5047     }
5048     bool stateChange = false;
5049     auto resCode = dataMgr->SwitchUninstallState(bundleName, state, isNeedSendNotify, stateChange);
5050     if (resCode != ERR_OK) {
5051         APP_LOGE("set status fail");
5052         return resCode;
5053     }
5054     if (!isNeedSendNotify || !stateChange) {
5055         APP_LOGI("no need notify %{public}s %{public}d %{public}d",
5056             bundleName.c_str(), isNeedSendNotify, stateChange);
5057         return resCode;
5058     }
5059     InnerBundleInfo innerBundleInfo;
5060     bool isSuccess = dataMgr->FetchInnerBundleInfo(bundleName, innerBundleInfo);
5061     if (!isSuccess) {
5062         APP_LOGE("get innerBundleInfo fail");
5063         return resCode;
5064     }
5065     AbilityInfo mainAbilityInfo;
5066     int32_t currentActiveUserId = AccountHelper::GetCurrentActiveUserId();
5067     innerBundleInfo.GetMainAbilityInfo(mainAbilityInfo);
5068     NotifyBundleEvents installRes = {
5069         .isModuleUpdate = false,
5070         .type = NotifyType::UNINSTALL_STATE,
5071         .resultCode = ERR_OK,
5072         .accessTokenId = innerBundleInfo.GetAccessTokenId(currentActiveUserId),
5073         .uid = innerBundleInfo.GetUid(currentActiveUserId),
5074         .bundleType = static_cast<int32_t>(innerBundleInfo.GetApplicationBundleType()),
5075         .bundleName = innerBundleInfo.GetBundleName(),
5076         .modulePackage = innerBundleInfo.GetModuleNameVec()[0],
5077         .abilityName = mainAbilityInfo.name,
5078         .appDistributionType = innerBundleInfo.GetAppDistributionType(),
5079     };
5080     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
5081     commonEventMgr->NotifyBundleStatus(installRes, dataMgr);
5082     return resCode;
5083 }
5084 
SetProvisionInfoToInnerBundleInfo(const std::string & hapPath,InnerBundleInfo & info)5085 void BundleMgrHostImpl::SetProvisionInfoToInnerBundleInfo(const std::string &hapPath, InnerBundleInfo &info)
5086 {
5087     Security::Verify::HapVerifyResult hapVerifyResult;
5088     ErrCode verifyRes = BundleVerifyMgr::HapVerify(hapPath, hapVerifyResult);
5089     if (verifyRes != ERR_OK) {
5090         return;
5091     }
5092     Security::Verify::ProvisionInfo provisionInfo = hapVerifyResult.GetProvisionInfo();
5093     bool isSystemApp = provisionInfo.bundleInfo.appFeature == ServiceConstants::HOS_SYSTEM_APP;
5094     info.SetAppType(isSystemApp ? Constants::AppType::SYSTEM_APP : Constants::AppType::THIRD_PARTY_APP);
5095     info.SetProvisionId(provisionInfo.appId);
5096     info.SetCertificateFingerprint(provisionInfo.fingerprint);
5097     info.SetAppIdentifier(provisionInfo.bundleInfo.appIdentifier);
5098     if (provisionInfo.type == Security::Verify::ProvisionType::DEBUG) {
5099         info.SetCertificate(provisionInfo.bundleInfo.developmentCertificate);
5100     } else {
5101         info.SetCertificate(provisionInfo.bundleInfo.distributionCertificate);
5102     }
5103     info.SetAppPrivilegeLevel(provisionInfo.bundleInfo.apl);
5104     bool isDebug = provisionInfo.type == Security::Verify::ProvisionType::DEBUG;
5105     info.SetAppProvisionType(isDebug ? Constants::APP_PROVISION_TYPE_DEBUG : Constants::APP_PROVISION_TYPE_RELEASE);
5106     std::string distributionType;
5107     auto typeIter = APP_DISTRIBUTION_TYPE_MAPS.find(provisionInfo.distributionType);
5108     if (typeIter == APP_DISTRIBUTION_TYPE_MAPS.end()) {
5109         distributionType = Constants::APP_DISTRIBUTION_TYPE_NONE;
5110     } else {
5111         distributionType = typeIter->second;
5112     }
5113     info.SetAppDistributionType(distributionType);
5114 }
5115 
QueryAbilityInfoByContinueType(const std::string & bundleName,const std::string & continueType,AbilityInfo & abilityInfo,int32_t userId)5116 ErrCode BundleMgrHostImpl::QueryAbilityInfoByContinueType(const std::string &bundleName,
5117     const std::string &continueType, AbilityInfo &abilityInfo, int32_t userId)
5118 {
5119     APP_LOGD("QueryAbilityInfoByContinueType, bundleName : %{public}s, continueType : %{public}s, userId: %{public}d",
5120         bundleName.c_str(), continueType.c_str(), userId);
5121     if (!BundlePermissionMgr::IsSystemApp()) {
5122         APP_LOGE("non-system app calling system api");
5123         EventReport::SendQueryAbilityInfoByContinueTypeSysEvent(bundleName, EMPTY_ABILITY_NAME,
5124             ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED, userId, continueType);
5125         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5126     }
5127     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED}) &&
5128         !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
5129         APP_LOGE("verify permission failed");
5130         EventReport::SendQueryAbilityInfoByContinueTypeSysEvent(bundleName, EMPTY_ABILITY_NAME,
5131             ERR_BUNDLE_MANAGER_PERMISSION_DENIED, userId, continueType);
5132         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5133     }
5134     APP_LOGD("verify permission success, begin to QueryAbilityInfoByContinueType");
5135     auto dataMgr = GetDataMgrFromService();
5136     if (dataMgr == nullptr) {
5137         APP_LOGE("DataMgr is nullptr");
5138         EventReport::SendQueryAbilityInfoByContinueTypeSysEvent(bundleName, EMPTY_ABILITY_NAME,
5139             ERR_BUNDLE_MANAGER_INTERNAL_ERROR, userId, continueType);
5140         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5141     }
5142     ErrCode res = dataMgr->QueryAbilityInfoByContinueType(bundleName, continueType, abilityInfo, userId);
5143     std::string abilityName;
5144     if (res == ERR_OK) {
5145         abilityName = abilityInfo.name;
5146     }
5147     EventReport::SendQueryAbilityInfoByContinueTypeSysEvent(bundleName, abilityName, res, userId, continueType);
5148     return res;
5149 }
5150 
QueryCloneAbilityInfo(const ElementName & element,int32_t flags,int32_t appIndex,AbilityInfo & abilityInfo,int32_t userId)5151 ErrCode BundleMgrHostImpl::QueryCloneAbilityInfo(const ElementName &element,
5152     int32_t flags, int32_t appIndex, AbilityInfo &abilityInfo, int32_t userId)
5153 {
5154     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
5155     std::string bundleName = element.GetBundleName();
5156     std::string abilityName = element.GetAbilityName();
5157     LOG_D(BMS_TAG_QUERY,
5158         "flags : %{public}d, userId : %{public}d, bundleName: %{public}s, abilityName: %{public}s",
5159         flags, userId, bundleName.c_str(), abilityName.c_str());
5160 
5161     if (bundleName.empty() || abilityName.empty()) {
5162         LOG_E(BMS_TAG_QUERY, "invalid params");
5163         return ERR_APPEXECFWK_CLONE_QUERY_PARAM_ERROR;
5164     }
5165     if (!BundlePermissionMgr::IsSystemApp()) {
5166         LOG_E(BMS_TAG_QUERY, "non-system app calling system api");
5167         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5168     }
5169     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED})
5170         && !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
5171         LOG_E(BMS_TAG_QUERY, "verify permission failed");
5172         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5173     }
5174     auto dataMgr = GetDataMgrFromService();
5175     if (dataMgr == nullptr) {
5176         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
5177         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5178     }
5179     auto res = dataMgr->QueryCloneAbilityInfo(element, flags, userId, appIndex, abilityInfo);
5180     if (res != ERR_OK) {
5181         LOG_E(BMS_TAG_QUERY, "QueryCloneAbilityInfo fail, err: %{public}d", res);
5182         return res;
5183     }
5184     return ERR_OK;
5185 }
5186 
GetCloneBundleInfo(const std::string & bundleName,int32_t flags,int32_t appIndex,BundleInfo & bundleInfo,int32_t userId)5187 ErrCode BundleMgrHostImpl::GetCloneBundleInfo(const std::string &bundleName, int32_t flags,
5188     int32_t appIndex, BundleInfo &bundleInfo, int32_t userId)
5189 {
5190     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_CLONE_BUNDLE_INFO);
5191     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
5192     if (!BundlePermissionMgr::IsSystemApp()) {
5193         APP_LOGE("non-system app calling system api");
5194         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5195     }
5196     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)
5197         && !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
5198         APP_LOGE("verify permission failed");
5199         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5200     }
5201     APP_LOGD("verify permission success, begin to GetCloneBundleInfo");
5202     auto dataMgr = GetDataMgrFromService();
5203     if (dataMgr == nullptr) {
5204         APP_LOGE("DataMgr is nullptr");
5205         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5206     }
5207     auto res = dataMgr->GetCloneBundleInfo(bundleName, flags, appIndex, bundleInfo, userId);
5208     if (res != ERR_OK) {
5209         APP_LOGW_NOFUNC("GetCloneBundleInfo fail -n %{public}s -u %{public}d -i %{public}d -f %{public}d"
5210             " err:%{public}d", bundleName.c_str(), userId, appIndex, flags, res);
5211         return res;
5212     }
5213     return ERR_OK;
5214 }
5215 
GetCloneBundleInfoExt(const std::string & bundleName,uint32_t flags,int32_t appIndex,int32_t userId,BundleInfo & bundleInfo)5216 ErrCode BundleMgrHostImpl::GetCloneBundleInfoExt(const std::string &bundleName, uint32_t flags,
5217     int32_t appIndex, int32_t userId, BundleInfo &bundleInfo)
5218 {
5219     int32_t timerId = XCollieHelper::SetRecoveryTimer(FUNCTION_GET_CLONE_BUNDLE_INFO_Ext);
5220     ScopeGuard cancelTimerIdGuard([timerId] { XCollieHelper::CancelTimer(timerId); });
5221     APP_LOGD("verify permission success, begin to GetCloneBundleInfoExt");
5222     int32_t uid = OHOS::IPCSkeleton::GetCallingUid();
5223     if (uid != Constants::FOUNDATION_UID) {
5224         LOG_E(BMS_TAG_DEFAULT, "uid: %{public}d not foundation", uid);
5225         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5226     }
5227     auto dataMgr = GetDataMgrFromService();
5228     if (dataMgr == nullptr) {
5229         APP_LOGE("DataMgr is nullptr");
5230         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5231     }
5232     auto res = dataMgr->GetCloneBundleInfo(bundleName, flags, appIndex, bundleInfo, userId);
5233     if (res != ERR_OK) {
5234         if (isBrokerServiceExisted_) {
5235             auto bmsExtensionClient = std::make_shared<BmsExtensionClient>();
5236             if (bmsExtensionClient->GetBundleInfo(bundleName, flags, bundleInfo, userId, true) == ERR_OK) {
5237                 return ERR_OK;
5238             }
5239         }
5240         APP_LOGE_NOFUNC("GetCloneBundleInfoExt fail -n %{public}s -u %{public}d -i %{public}d -f %{public}d"
5241             " err:%{public}d", bundleName.c_str(), userId, appIndex, flags, res);
5242     }
5243     return res;
5244 }
5245 
GetCloneAppIndexes(const std::string & bundleName,std::vector<int32_t> & appIndexes,int32_t userId)5246 ErrCode BundleMgrHostImpl::GetCloneAppIndexes(const std::string &bundleName, std::vector<int32_t> &appIndexes,
5247     int32_t userId)
5248 {
5249     APP_LOGD("start GetCloneAppIndexes bundleName = %{public}s, userId = %{public}d", bundleName.c_str(), userId);
5250     if (!BundlePermissionMgr::IsSystemApp()) {
5251         APP_LOGE("non-system app calling system api");
5252         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5253     }
5254     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)
5255         && !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
5256         APP_LOGE("verify permission failed");
5257         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5258     }
5259     APP_LOGD("verify permission success, begin to GetCloneAppIndexes");
5260     auto dataMgr = GetDataMgrFromService();
5261     if (dataMgr == nullptr) {
5262         APP_LOGE("DataMgr is nullptr");
5263         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5264     }
5265     appIndexes = dataMgr->GetCloneAppIndexes(bundleName, userId);
5266     return ERR_OK;
5267 }
5268 
GetLaunchWant(Want & want)5269 ErrCode BundleMgrHostImpl::GetLaunchWant(Want &want)
5270 {
5271     APP_LOGD("start GetLaunchWant");
5272     auto dataMgr = GetDataMgrFromService();
5273     if (dataMgr == nullptr) {
5274         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
5275         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5276     }
5277     auto uid = IPCSkeleton::GetCallingUid();
5278     std::string bundleName;
5279     auto ret = dataMgr->GetBundleNameForUid(uid, bundleName);
5280     if (!ret) {
5281         LOG_NOFUNC_W(BMS_TAG_QUERY, "GetBundleNameForUid failed uid:%{public}d", uid);
5282         return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST;
5283     }
5284     int32_t userId = AccountHelper::GetOsAccountLocalIdFromUid(uid);
5285     return dataMgr->GetLaunchWantForBundle(bundleName, want, userId);
5286 }
5287 
QueryCloneExtensionAbilityInfoWithAppIndex(const ElementName & element,int32_t flags,int32_t appIndex,ExtensionAbilityInfo & extensionAbilityInfo,int32_t userId)5288 ErrCode BundleMgrHostImpl::QueryCloneExtensionAbilityInfoWithAppIndex(const ElementName &element, int32_t flags,
5289     int32_t appIndex, ExtensionAbilityInfo &extensionAbilityInfo, int32_t userId)
5290 {
5291     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
5292     LOG_D(BMS_TAG_QUERY, "QueryCloneExtensionAbilityInfoWithAppIndex without type begin");
5293     if (!BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED})) {
5294         LOG_E(BMS_TAG_QUERY, "verify permission failed");
5295         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5296     }
5297     auto dataMgr = GetDataMgrFromService();
5298     if (dataMgr == nullptr) {
5299         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
5300         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5301     }
5302     std::string bundleName = element.GetBundleName();
5303     std::string extensionName = element.GetAbilityName();
5304     if (bundleName.empty() || extensionName.empty()) {
5305         LOG_E(BMS_TAG_QUERY,
5306             "QueryCloneExtensionAbilityInfoWithAppIndex is failed, bundleName:%{public}s, extensionName:%{public}s",
5307             bundleName.c_str(), extensionName.c_str());
5308         return ERR_BUNDLE_MANAGER_PARAM_ERROR;
5309     }
5310 
5311     Want want;
5312     want.SetElement(element);
5313     ErrCode ret = dataMgr->ExplicitQueryExtensionInfoV9(want, flags, userId, extensionAbilityInfo, appIndex);
5314     if (ret != ERR_OK) {
5315         LOG_D(BMS_TAG_QUERY, "explicit queryExtensionInfo error");
5316         return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST;
5317     }
5318     return ERR_OK;
5319 }
5320 
GetSignatureInfoByBundleName(const std::string & bundleName,SignatureInfo & signatureInfo)5321 ErrCode BundleMgrHostImpl::GetSignatureInfoByBundleName(const std::string &bundleName, SignatureInfo &signatureInfo)
5322 {
5323     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
5324     int32_t uid = OHOS::IPCSkeleton::GetCallingUid();
5325     if (uid != Constants::FOUNDATION_UID) {
5326         LOG_E(BMS_TAG_DEFAULT, "uid: %{public}d not foundation", uid);
5327         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5328     }
5329     auto dataMgr = GetDataMgrFromService();
5330     if (dataMgr == nullptr) {
5331         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
5332         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5333     }
5334     return dataMgr->GetSignatureInfoByBundleName(bundleName, signatureInfo);
5335 }
5336 
GetSignatureInfoByUid(const int32_t uid,SignatureInfo & signatureInfo)5337 ErrCode BundleMgrHostImpl::GetSignatureInfoByUid(const int32_t uid, SignatureInfo &signatureInfo)
5338 {
5339     HITRACE_METER_NAME_EX(HITRACE_LEVEL_INFO, HITRACE_TAG_APP, __PRETTY_FUNCTION__, nullptr);
5340     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_SIGNATURE_INFO)) {
5341         LOG_E(BMS_TAG_QUERY, "verify permission failed");
5342         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5343     }
5344     auto dataMgr = GetDataMgrFromService();
5345     if (dataMgr == nullptr) {
5346         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
5347         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5348     }
5349     return dataMgr->GetSignatureInfoByUid(uid, signatureInfo);
5350 }
5351 
CheckCanSetEnable(const std::string & bundleName)5352 bool BundleMgrHostImpl::CheckCanSetEnable(const std::string &bundleName)
5353 {
5354     std::vector<std::string> noDisablingList;
5355     std::string configPath = BundleUtil::GetNoDisablingConfigPath();
5356     ErrCode ret = BundleParser::ParseNoDisablingList(configPath, noDisablingList);
5357     if (ret != ERR_OK) {
5358         LOG_W(BMS_TAG_DEFAULT, "GetNoDisablingList failed");
5359         return true;
5360     }
5361     auto it = std::find(noDisablingList.begin(), noDisablingList.end(), bundleName);
5362     if (it == noDisablingList.end()) {
5363         return true;
5364     }
5365     return false;
5366 }
5367 
AddDesktopShortcutInfo(const ShortcutInfo & shortcutInfo,int32_t userId)5368 ErrCode BundleMgrHostImpl::AddDesktopShortcutInfo(const ShortcutInfo &shortcutInfo, int32_t userId)
5369 {
5370     if (!BundlePermissionMgr::IsSystemApp()) {
5371         APP_LOGE("Non-system app calling system api");
5372         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5373     }
5374     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_MANAGER_SHORTCUT)) {
5375         APP_LOGE("Verify permission failed");
5376         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5377     }
5378     auto dataMgr = GetDataMgrFromService();
5379     if (dataMgr == nullptr) {
5380         APP_LOGE("DataMgr is nullptr");
5381         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5382     }
5383     return dataMgr->AddDesktopShortcutInfo(shortcutInfo, userId);
5384 }
5385 
DeleteDesktopShortcutInfo(const ShortcutInfo & shortcutInfo,int32_t userId)5386 ErrCode BundleMgrHostImpl::DeleteDesktopShortcutInfo(const ShortcutInfo &shortcutInfo, int32_t userId)
5387 {
5388     if (!BundlePermissionMgr::IsSystemApp()) {
5389         APP_LOGE("Non-system app calling system api");
5390         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5391     }
5392     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_MANAGER_SHORTCUT)) {
5393         APP_LOGE("Verify permission failed");
5394         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5395     }
5396     auto dataMgr = GetDataMgrFromService();
5397     if (dataMgr == nullptr) {
5398         APP_LOGE("DataMgr is nullptr");
5399         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5400     }
5401     return dataMgr->DeleteDesktopShortcutInfo(shortcutInfo, userId);
5402 }
5403 
GetAllDesktopShortcutInfo(int32_t userId,std::vector<ShortcutInfo> & shortcutInfos)5404 ErrCode BundleMgrHostImpl::GetAllDesktopShortcutInfo(int32_t userId, std::vector<ShortcutInfo> &shortcutInfos)
5405 {
5406     if (!BundlePermissionMgr::IsSystemApp()) {
5407         APP_LOGE("Non-system app calling system api");
5408         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5409     }
5410     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_MANAGER_SHORTCUT)) {
5411         APP_LOGE("Verify permission failed");
5412         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5413     }
5414     auto dataMgr = GetDataMgrFromService();
5415     if (dataMgr == nullptr) {
5416         APP_LOGE("DataMgr is nullptr");
5417         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5418     }
5419     return dataMgr->GetAllDesktopShortcutInfo(userId, shortcutInfos);
5420 }
5421 
IsAppLinking(int32_t flags) const5422 bool BundleMgrHostImpl::IsAppLinking(int32_t flags) const
5423 {
5424     if ((static_cast<uint32_t>(flags) &
5425         static_cast<uint32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_APP_LINKING)) ==
5426         static_cast<uint32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_APP_LINKING)) {
5427         APP_LOGI("contains app linking flag, no need to query from bms extension");
5428         return true;
5429     }
5430     return false;
5431 }
5432 
GetOdidByBundleName(const std::string & bundleName,std::string & odid)5433 ErrCode BundleMgrHostImpl::GetOdidByBundleName(const std::string &bundleName, std::string &odid)
5434 {
5435     APP_LOGD("start GetOdidByBundleName");
5436     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5437         APP_LOGE("Verify permission failed");
5438         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5439     }
5440     auto dataMgr = GetDataMgrFromService();
5441     if (dataMgr == nullptr) {
5442         APP_LOGE("DataMgr is nullptr");
5443         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5444     }
5445     return dataMgr->GetOdidByBundleName(bundleName, odid);
5446 }
5447 
GetBundleInfosForContinuation(int32_t flags,std::vector<BundleInfo> & bundleInfos,int32_t userId)5448 bool BundleMgrHostImpl::GetBundleInfosForContinuation(int32_t flags, std::vector<BundleInfo> &bundleInfos,
5449     int32_t userId)
5450 {
5451     GetBundleInfos(flags, bundleInfos, userId);
5452     auto dataMgr = GetDataMgrFromService();
5453     dataMgr->GetBundleInfosForContinuation(bundleInfos);
5454     return !bundleInfos.empty();
5455 }
5456 
GetContinueBundleNames(const std::string & continueBundleName,std::vector<std::string> & bundleNames,int32_t userId)5457 ErrCode BundleMgrHostImpl::GetContinueBundleNames(
5458     const std::string &continueBundleName, std::vector<std::string> &bundleNames, int32_t userId)
5459 {
5460     if (continueBundleName.empty()) {
5461         return ERR_BUNDLE_MANAGER_INVALID_PARAMETER;
5462     }
5463 
5464     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5465         APP_LOGE("Verify permission failed");
5466         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5467     }
5468 
5469     auto dataMgr = GetDataMgrFromService();
5470     if (dataMgr == nullptr) {
5471         APP_LOGE("DataMgr is nullptr");
5472         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5473     }
5474     return dataMgr->GetContinueBundleNames(continueBundleName, bundleNames, userId);
5475 }
5476 
IsBundleInstalled(const std::string & bundleName,int32_t userId,int32_t appIndex,bool & isInstalled)5477 ErrCode BundleMgrHostImpl::IsBundleInstalled(const std::string &bundleName, int32_t userId,
5478     int32_t appIndex, bool &isInstalled)
5479 {
5480     APP_LOGD("IsBundleInstalled -n %{public}s -u %{public}d -i %{public}d", bundleName.c_str(), userId, appIndex);
5481     if (!BundlePermissionMgr::IsSystemApp()) {
5482         APP_LOGE("Non-system app calling system api");
5483         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5484     }
5485     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5486         APP_LOGE("Verify permission failed");
5487         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5488     }
5489 
5490     auto dataMgr = GetDataMgrFromService();
5491     if (dataMgr == nullptr) {
5492         APP_LOGE("DataMgr is nullptr");
5493         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5494     }
5495     return dataMgr->IsBundleInstalled(bundleName, userId, appIndex, isInstalled);
5496 }
5497 
GetCompatibleDeviceTypeNative(std::string & deviceType)5498 ErrCode BundleMgrHostImpl::GetCompatibleDeviceTypeNative(std::string &deviceType)
5499 {
5500     APP_LOGD("start GetCompatibleDeviceTypeNative");
5501     auto dataMgr = GetDataMgrFromService();
5502     if (dataMgr == nullptr) {
5503         APP_LOGE("DataMgr is nullptr");
5504         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5505     }
5506     std::string bundleName;
5507     dataMgr->GetBundleNameForUid(IPCSkeleton::GetCallingUid(), bundleName);
5508     BmsExtensionDataMgr bmsExtensionDataMgr;
5509     deviceType = bmsExtensionDataMgr.GetCompatibleDeviceType(bundleName);
5510     APP_LOGI("deviceType : %{public}s", deviceType.c_str());
5511     return ERR_OK;
5512 }
5513 
GetCompatibleDeviceType(const std::string & bundleName,std::string & deviceType)5514 ErrCode BundleMgrHostImpl::GetCompatibleDeviceType(const std::string &bundleName, std::string &deviceType)
5515 {
5516     APP_LOGD("start GetCompatibleDeviceType");
5517     if (!BundlePermissionMgr::IsSystemApp()) {
5518         APP_LOGE("non-system app calling system api");
5519         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5520     }
5521     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5522         APP_LOGE("Verify permission failed");
5523         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5524     }
5525 
5526     auto dataMgr = GetDataMgrFromService();
5527     if (dataMgr == nullptr) {
5528         APP_LOGE("DataMgr is nullptr");
5529         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5530     }
5531     BmsExtensionDataMgr bmsExtensionDataMgr;
5532     deviceType = bmsExtensionDataMgr.GetCompatibleDeviceType(bundleName);
5533     APP_LOGI("deviceType : %{public}s", deviceType.c_str());
5534     return ERR_OK;
5535 }
5536 
GetAllPluginInfo(const std::string & hostBundleName,int32_t userId,std::vector<PluginBundleInfo> & pluginBundleInfos)5537 ErrCode BundleMgrHostImpl::GetAllPluginInfo(const std::string &hostBundleName, int32_t userId,
5538     std::vector<PluginBundleInfo> &pluginBundleInfos)
5539 {
5540     APP_LOGD("start GetAllPluginInfo");
5541     if (!BundlePermissionMgr::IsSystemApp()) {
5542         APP_LOGE("non-system app calling system api");
5543         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5544     }
5545     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5546         APP_LOGE("Verify permission failed");
5547         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5548     }
5549     auto dataMgr = GetDataMgrFromService();
5550     if (dataMgr == nullptr) {
5551         APP_LOGE("DataMgr is nullptr");
5552         return ERR_APPEXECFWK_NULL_PTR;
5553     }
5554     return dataMgr->GetAllPluginInfo(hostBundleName, userId, pluginBundleInfos);
5555 }
5556 
GetPluginInfosForSelf(std::vector<PluginBundleInfo> & pluginBundleInfos)5557 ErrCode BundleMgrHostImpl::GetPluginInfosForSelf(std::vector<PluginBundleInfo> &pluginBundleInfos)
5558 {
5559     APP_LOGD("start GetPluginInfosForSelf");
5560     auto dataMgr = GetDataMgrFromService();
5561     if (dataMgr == nullptr) {
5562         APP_LOGE("DataMgr is nullptr");
5563         return ERR_APPEXECFWK_NULL_PTR;
5564     }
5565     std::string callingBundleName;
5566     int32_t uid = IPCSkeleton::GetCallingUid();
5567     ErrCode ret = dataMgr->GetNameForUid(uid, callingBundleName);
5568     if (ret != ERR_OK) {
5569         APP_LOGE("get bundleName failed %{public}d %{public}d", ret, uid);
5570         return ERR_BUNDLE_MANAGER_INVALID_UID;
5571     }
5572     return dataMgr->GetAllPluginInfo(callingBundleName, BundleUtil::GetUserIdByUid(uid), pluginBundleInfos);
5573 }
5574 
GetBundleNameByAppId(const std::string & appId,std::string & bundleName)5575 ErrCode BundleMgrHostImpl::GetBundleNameByAppId(const std::string &appId, std::string &bundleName)
5576 {
5577     APP_LOGD("start GetBundleNameByAppId");
5578     if (!BundlePermissionMgr::IsSystemApp()) {
5579         APP_LOGE("non-system app calling system api");
5580         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5581     }
5582     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5583         APP_LOGE("Verify permission failed");
5584         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5585     }
5586     auto dataMgr = GetDataMgrFromService();
5587     if (dataMgr == nullptr) {
5588         APP_LOGE("DataMgr is nullptr");
5589         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5590     }
5591     auto ret = dataMgr->GetBundleNameByAppId(appId, bundleName);
5592     if (ret != ERR_OK) {
5593         APP_LOGW("get bundleName by appId %{private}s failed %{public}d", appId.c_str(), ret);
5594         return ret;
5595     }
5596     APP_LOGI("appId: %{private}s bundleName : %{public}s", appId.c_str(), bundleName.c_str());
5597     return ERR_OK;
5598 }
5599 
GetCallerName()5600 std::string BundleMgrHostImpl::GetCallerName()
5601 {
5602     auto dataMgr = GetDataMgrFromService();
5603     if (dataMgr == nullptr) {
5604         APP_LOGE("DataMgr is nullptr");
5605         return Constants::EMPTY_STRING;
5606     }
5607     std::string callerName;
5608     int32_t uid = IPCSkeleton::GetCallingUid();
5609     auto ret = dataMgr->GetNameForUid(uid, callerName);
5610     if (ret != ERR_OK) {
5611         callerName = std::to_string(uid);
5612     }
5613     return callerName;
5614 }
5615 
GetDirForApp(const std::string & bundleName,const int32_t appIndex,std::string & dataDir)5616 ErrCode GetDirForApp(const std::string &bundleName, const int32_t appIndex, std::string &dataDir)
5617 {
5618     APP_LOGD("start GetDirForApp");
5619     if (appIndex < 0) {
5620         return ERR_BUNDLE_MANAGER_GET_DIR_INVALID_APP_INDEX;
5621     } else if (appIndex == 0) {
5622         dataDir = bundleName;
5623     } else {
5624         dataDir = CLONE_APP_DIR_PREFIX + std::to_string(appIndex) + PLUS + bundleName;
5625     }
5626     return ERR_OK;
5627 }
5628 
GetDirByBundleNameAndAppIndex(const std::string & bundleName,const int32_t appIndex,std::string & dataDir)5629 ErrCode BundleMgrHostImpl::GetDirByBundleNameAndAppIndex(const std::string &bundleName, const int32_t appIndex,
5630     std::string &dataDir)
5631 {
5632     APP_LOGD("start GetDirByBundleNameAndAppIndex");
5633     auto dataMgr = GetDataMgrFromService();
5634     if (dataMgr == nullptr) {
5635         APP_LOGE("DataMgr is nullptr");
5636         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5637     }
5638 
5639     BundleType type;
5640     dataMgr->GetBundleType(bundleName, type);
5641     if (type != BundleType::ATOMIC_SERVICE) {
5642         return GetDirForApp(bundleName, appIndex, dataDir);
5643     }
5644 
5645     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)
5646         && !BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
5647         APP_LOGE("Verify permission failed");
5648         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5649     }
5650     return dataMgr->GetDirByBundleNameAndAppIndex(bundleName, appIndex, dataDir);
5651 }
5652 
GetAllBundleDirs(int32_t userId,std::vector<BundleDir> & bundleDirs)5653 ErrCode BundleMgrHostImpl::GetAllBundleDirs(int32_t userId, std::vector<BundleDir> &bundleDirs)
5654 {
5655     if (!BundlePermissionMgr::IsSystemApp()) {
5656         APP_LOGE("non-system app calling system api");
5657         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5658     }
5659     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5660         APP_LOGE("Verify permission failed");
5661         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5662     }
5663     auto dataMgr = GetDataMgrFromService();
5664     if (dataMgr == nullptr) {
5665         APP_LOGE("DataMgr is nullptr");
5666         return ERR_BUNDLE_MANAGER_INTERNAL_ERROR;
5667     }
5668     return dataMgr->GetAllBundleDirs(userId, bundleDirs);
5669 }
5670 
SetAppDistributionTypes(std::set<AppDistributionTypeEnum> & appDistributionTypeEnums)5671 ErrCode BundleMgrHostImpl::SetAppDistributionTypes(std::set<AppDistributionTypeEnum> &appDistributionTypeEnums)
5672 {
5673     if (!BundlePermissionMgr::IsSystemApp()) {
5674         APP_LOGE("non-system app calling system api");
5675         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5676     }
5677     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(ServiceConstants::PERMISSION_MANAGE_EDM_POLICY)) {
5678         APP_LOGE("Verify permission failed");
5679         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5680     }
5681     auto bmsPara = DelayedSingleton<BundleMgrService>::GetInstance()->GetBmsParam();
5682     if (bmsPara == nullptr) {
5683         APP_LOGE("bmsPara is nullptr");
5684         return ERR_APPEXECFWK_NULL_PTR;
5685     }
5686     if (appDistributionTypeEnums.empty()) {
5687         if (!bmsPara->DeleteBmsParam(Constants::APP_DISTRIBUTION_TYPE_WHITE_LIST)) {
5688             APP_LOGE("DeleteBmsParam failed");
5689             return ERR_BMS_PARAM_DELETE_PARAM_ERROR;
5690         }
5691         APP_LOGI("delete bms param success");
5692         return ERR_OK;
5693     }
5694     std::string value = "";
5695     for (auto it = appDistributionTypeEnums.begin(); it != appDistributionTypeEnums.end(); ++it) {
5696         if (it == appDistributionTypeEnums.begin()) {
5697             value += std::to_string(static_cast<int>(*it));
5698         } else {
5699             value += Constants::SUPPORT_APP_TYPES_SEPARATOR + std::to_string(static_cast<int>(*it));
5700         }
5701     }
5702     if (!bmsPara->SaveBmsParam(Constants::APP_DISTRIBUTION_TYPE_WHITE_LIST, value)) {
5703         APP_LOGE("SaveBmsParam failed");
5704         return ERR_BMS_PARAM_SET_PARAM_ERROR;
5705     }
5706     APP_LOGI("save bms param success %{public}s", value.c_str());
5707     return ERR_OK;
5708 }
5709 
CallAbilityManager(int32_t resultCode,const Want & want,int32_t userId,const sptr<IRemoteObject> & callBack)5710 void BundleMgrHostImpl::CallAbilityManager(
5711     int32_t resultCode, const Want &want, int32_t userId, const sptr<IRemoteObject> &callBack)
5712 {
5713     if (callBack == nullptr) {
5714         APP_LOGI("callBack is nullptr");
5715         return;
5716     }
5717     MessageParcel data;
5718     MessageParcel reply;
5719     MessageOption option;
5720     if (!data.WriteInterfaceToken(ATOMIC_SERVICE_STATUS_CALLBACK_TOKEN)) {
5721         APP_LOGE("Write interface token failed");
5722         return;
5723     }
5724     if (!data.WriteInt32(resultCode)) {
5725         APP_LOGE("Write result code failed");
5726         return;
5727     }
5728     if (!data.WriteParcelable(&want)) {
5729         APP_LOGE("Write want failed");
5730         return;
5731     }
5732     if (!data.WriteInt32(userId)) {
5733         APP_LOGE("Write userId failed");
5734         return;
5735     }
5736 
5737     if (callBack->SendRequest(ERR_OK, data, reply, option) != ERR_OK) {
5738         APP_LOGE("SendRequest failed");
5739     }
5740 }
5741 
GetPluginBundleInfo(const std::string & bundleName,const int32_t userId,std::unordered_map<std::string,PluginBundleInfo> & pluginBundleInfos)5742 bool BundleMgrHostImpl::GetPluginBundleInfo(const std::string &bundleName, const int32_t userId,
5743     std::unordered_map<std::string, PluginBundleInfo> &pluginBundleInfos)
5744 {
5745     auto dataMgr = GetDataMgrFromService();
5746     if (dataMgr == nullptr) {
5747         APP_LOGE("DataMgr is nullptr");
5748         return false;
5749     }
5750     InnerBundleInfo info;
5751     if (!dataMgr->FetchInnerBundleInfo(bundleName, info)) {
5752         APP_LOGE("can not get bundleinfo of %{public}s", bundleName.c_str());
5753         return false;
5754     }
5755     return info.GetPluginBundleInfos(userId, pluginBundleInfos);
5756 }
5757 
GetPluginAbilityInfo(const std::string & hostBundleName,const std::string & pluginBundleName,const std::string & pluginModuleName,const std::string & pluginAbilityName,const int32_t userId,AbilityInfo & abilityInfo)5758 ErrCode BundleMgrHostImpl::GetPluginAbilityInfo(const std::string &hostBundleName, const std::string &pluginBundleName,
5759     const std::string &pluginModuleName, const std::string &pluginAbilityName,
5760     const int32_t userId, AbilityInfo &abilityInfo)
5761 {
5762     LOG_D(BMS_TAG_QUERY,
5763         "start GetPluginAbilityInfo bundleName:%{public}s pluginName:%{public}s abilityName:%{public}s",
5764         hostBundleName.c_str(), pluginBundleName.c_str(), pluginAbilityName.c_str());
5765     if (!BundlePermissionMgr::IsBundleSelfCalling(hostBundleName)) {
5766         if (!BundlePermissionMgr::IsSystemApp()) {
5767             APP_LOGE("non-system app calling system api");
5768             return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5769         }
5770         if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5771             APP_LOGE("Verify permission failed");
5772             return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5773         }
5774     }
5775     auto dataMgr = GetDataMgrFromService();
5776     if (dataMgr == nullptr) {
5777         APP_LOGE("DataMgr is nullptr");
5778         return ERR_APPEXECFWK_NULL_PTR;
5779     }
5780     return dataMgr->GetPluginAbilityInfo(hostBundleName,
5781         pluginBundleName, pluginModuleName, pluginAbilityName, userId, abilityInfo);
5782 }
5783 
GetPluginHapModuleInfo(const std::string & hostBundleName,const std::string & pluginBundleName,const std::string & pluginModuleName,const int32_t userId,HapModuleInfo & hapModuleInfo)5784 ErrCode BundleMgrHostImpl::GetPluginHapModuleInfo(const std::string &hostBundleName,
5785     const std::string &pluginBundleName, const std::string &pluginModuleName,
5786     const int32_t userId, HapModuleInfo &hapModuleInfo)
5787 {
5788     LOG_D(BMS_TAG_QUERY,
5789         "start GetPluginHapModuleInfo bundleName:%{public}s pluginName:%{public}s moduleName:%{public}s",
5790         hostBundleName.c_str(), pluginBundleName.c_str(), pluginModuleName.c_str());
5791     if (!BundlePermissionMgr::IsBundleSelfCalling(hostBundleName)) {
5792         if (!BundlePermissionMgr::IsSystemApp()) {
5793             APP_LOGE("non-system app calling system api");
5794             return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5795         }
5796         if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5797             APP_LOGE("Verify permission failed");
5798             return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5799         }
5800     }
5801     auto dataMgr = GetDataMgrFromService();
5802     if (dataMgr == nullptr) {
5803         APP_LOGE("DataMgr is nullptr");
5804         return ERR_APPEXECFWK_NULL_PTR;
5805     }
5806     return dataMgr->GetPluginHapModuleInfo(hostBundleName, pluginBundleName, pluginModuleName, userId, hapModuleInfo);
5807 }
5808 
RegisterPluginEventCallback(const sptr<IBundleEventCallback> & pluginEventCallback)5809 ErrCode BundleMgrHostImpl::RegisterPluginEventCallback(const sptr<IBundleEventCallback> &pluginEventCallback)
5810 {
5811     APP_LOGD("begin");
5812     if (pluginEventCallback == nullptr) {
5813         APP_LOGE("pluginEventCallback is null");
5814         return ERR_APPEXECFWK_NULL_PTR;
5815     }
5816     auto uid = IPCSkeleton::GetCallingUid();
5817     if (uid != Constants::FOUNDATION_UID) {
5818         APP_LOGE("verify calling uid failed, uid : %{public}d", uid);
5819         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5820     }
5821     auto dataMgr = GetDataMgrFromService();
5822     if (dataMgr == nullptr) {
5823         APP_LOGE("DataMgr is nullptr");
5824         return ERR_APPEXECFWK_NULL_PTR;
5825     }
5826     return dataMgr->RegisterPluginEventCallback(pluginEventCallback);
5827 }
5828 
UnregisterPluginEventCallback(const sptr<IBundleEventCallback> & pluginEventCallback)5829 ErrCode BundleMgrHostImpl::UnregisterPluginEventCallback(const sptr<IBundleEventCallback> &pluginEventCallback)
5830 {
5831     APP_LOGD("begin");
5832     if (pluginEventCallback == nullptr) {
5833         APP_LOGE("pluginEventCallback is null");
5834         return ERR_APPEXECFWK_NULL_PTR;
5835     }
5836     auto uid = IPCSkeleton::GetCallingUid();
5837     if (uid != Constants::FOUNDATION_UID) {
5838         APP_LOGE("verify calling uid failed, uid : %{public}d", uid);
5839         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5840     }
5841     auto dataMgr = GetDataMgrFromService();
5842     if (dataMgr == nullptr) {
5843         APP_LOGE("DataMgr is nullptr");
5844         return ERR_APPEXECFWK_NULL_PTR;
5845     }
5846     return dataMgr->UnregisterPluginEventCallback(pluginEventCallback);
5847 }
5848 
GetSandboxDataDir(const std::string & bundleName,int32_t appIndex,std::string & sandboxDataDir)5849 ErrCode BundleMgrHostImpl::GetSandboxDataDir(
5850     const std::string &bundleName, int32_t appIndex, std::string &sandboxDataDir)
5851 {
5852     APP_LOGD("start GetSandboxDataDir");
5853     if (!BundlePermissionMgr::IsSystemApp()) {
5854         APP_LOGE("non-system app calling system api");
5855         return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
5856     }
5857 
5858     if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
5859         APP_LOGE("Verify permission failed");
5860         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
5861     }
5862 
5863     auto dataMgr = GetDataMgrFromService();
5864     if (dataMgr == nullptr) {
5865         APP_LOGE("DataMgr is nullptr");
5866         return ERR_APPEXECFWK_NULL_PTR;
5867     }
5868 
5869     return dataMgr->GetDirByBundleNameAndAppIndex(bundleName, appIndex, sandboxDataDir);
5870 }
5871 
AddPreinstalledApplicationInfo(PreInstallBundleInfo & preInstallBundleInfo,std::vector<PreinstalledApplicationInfo> & preinstalledApplicationInfos)5872 void BundleMgrHostImpl::AddPreinstalledApplicationInfo(PreInstallBundleInfo &preInstallBundleInfo,
5873     std::vector<PreinstalledApplicationInfo> &preinstalledApplicationInfos)
5874 {
5875     PreinstalledApplicationInfo preinstalledApplicationInfo;
5876     preinstalledApplicationInfo.bundleName = preInstallBundleInfo.GetBundleName();
5877     preinstalledApplicationInfo.moduleName = preInstallBundleInfo.GetModuleName();
5878     preinstalledApplicationInfo.labelId = preInstallBundleInfo.GetLabelId();
5879     preinstalledApplicationInfo.iconId = preInstallBundleInfo.GetIconId();
5880     preinstalledApplicationInfos.emplace_back(preinstalledApplicationInfo);
5881 }
5882 
GetAbilityLabelInfo(std::vector<AbilityInfo> & abilityInfos)5883 void BundleMgrHostImpl::GetAbilityLabelInfo(std::vector<AbilityInfo> &abilityInfos)
5884 {
5885     uint32_t flags = static_cast<uint32_t>(ResourceFlag::GET_RESOURCE_INFO_WITH_LABEL);
5886     std::unordered_map<std::string, std::vector<LauncherAbilityResourceInfo>> resourceCache;
5887     for (auto &abilityInfo : abilityInfos) {
5888         std::string cacheKey = abilityInfo.bundleName + "_" + std::to_string(abilityInfo.appIndex);
5889         if (GetLabelFromCache(cacheKey, abilityInfo.name, resourceCache, abilityInfo.label)) {
5890             continue;
5891         }
5892         std::vector<LauncherAbilityResourceInfo> launcherResources;
5893         if (!BundleResourceHelper::GetLauncherAbilityResourceInfo(abilityInfo.bundleName, flags,
5894             launcherResources, abilityInfo.appIndex)) {
5895             APP_LOGW("get launcher resource failed -n %{public}s -f %{public}u",
5896                 abilityInfo.bundleName.c_str(), flags);
5897             abilityInfo.label = abilityInfo.bundleName;
5898             continue;
5899         }
5900         resourceCache[cacheKey] = launcherResources;
5901         for (const auto& resource : launcherResources) {
5902             if (resource.abilityName == abilityInfo.name) {
5903                 abilityInfo.label = resource.label;
5904                 break;
5905             }
5906         }
5907     }
5908 }
5909 
GetApplicationLabelInfo(std::vector<AbilityInfo> & abilityInfos)5910 void BundleMgrHostImpl::GetApplicationLabelInfo(std::vector<AbilityInfo> &abilityInfos)
5911 {
5912     uint32_t flags = static_cast<uint32_t>(ResourceFlag::GET_RESOURCE_INFO_WITH_LABEL);
5913     for (auto &abilityInfo : abilityInfos) {
5914         if (abilityInfo.applicationInfo.name.empty()) {
5915             continue;
5916         }
5917         BundleResourceInfo bundleResourceInfo;
5918         if (!BundleResourceHelper::GetBundleResourceInfo(abilityInfo.applicationInfo.bundleName, flags,
5919             bundleResourceInfo, abilityInfo.applicationInfo.appIndex)) {
5920             APP_LOGW("get resource failed -n %{public}s -f %{public}u",
5921                 abilityInfo.applicationInfo.bundleName.c_str(), flags);
5922             abilityInfo.applicationInfo.label = abilityInfo.applicationInfo.bundleName;
5923             continue;
5924         }
5925         abilityInfo.applicationInfo.label = bundleResourceInfo.label;
5926     }
5927 }
5928 
GetLabelFromCache(const std::string & cacheKey,const std::string & abilityName,const std::unordered_map<std::string,std::vector<LauncherAbilityResourceInfo>> & resourceCache,std::string & label)5929 bool BundleMgrHostImpl::GetLabelFromCache(const std::string &cacheKey, const std::string &abilityName,
5930     const std::unordered_map<std::string, std::vector<LauncherAbilityResourceInfo>> &resourceCache, std::string &label)
5931 {
5932     auto cacheIter = resourceCache.find(cacheKey);
5933     if (cacheIter != resourceCache.end()) {
5934         for (const auto& resource : cacheIter->second) {
5935             if (resource.abilityName == abilityName) {
5936                 label = resource.label;
5937                 return true;
5938             }
5939         }
5940     }
5941     return false;
5942 }
5943 
SetShortcutVisibleForSelf(const std::string & shortcutId,bool visible)5944 ErrCode BundleMgrHostImpl::SetShortcutVisibleForSelf(const std::string &shortcutId, bool visible)
5945 {
5946     // The application itself is the caller, so there is no need for permission control.
5947     APP_LOGD("SetShortcutVisibleForSelf begin");
5948     auto dataMgr = GetDataMgrFromService();
5949     if (dataMgr == nullptr) {
5950         APP_LOGE("DataMgr is nullptr");
5951         return ERR_APPEXECFWK_NULL_PTR;
5952     }
5953     return dataMgr->SetShortcutVisibleForSelf(shortcutId, visible);
5954 }
5955 
GetAllShortcutInfoForSelf(std::vector<ShortcutInfo> & shortcutInfos)5956 ErrCode BundleMgrHostImpl::GetAllShortcutInfoForSelf(std::vector<ShortcutInfo> &shortcutInfos)
5957 {
5958     // The application itself is the caller, so there is no need for permission control.
5959     auto dataMgr = GetDataMgrFromService();
5960     if (dataMgr == nullptr) {
5961         APP_LOGE("DataMgr is nullptr");
5962         return ERR_APPEXECFWK_NULL_PTR;
5963     }
5964     return dataMgr->GetAllShortcutInfoForSelf(shortcutInfos);
5965 }
5966 
5967 // Internal interface. The application compares the API version number saved in the package management.
5968 //No permission control is required
GreatOrEqualTargetAPIVersion(const int32_t platformVersion,const int32_t minorVersion,const int32_t patchVersion)5969 bool BundleMgrHostImpl::GreatOrEqualTargetAPIVersion(const int32_t platformVersion, const int32_t minorVersion,
5970     const int32_t patchVersion)
5971 {
5972     APP_LOGD("GreatOrEqualTargetAPIVersion begin");
5973     auto dataMgr = GetDataMgrFromService();
5974     if (dataMgr == nullptr) {
5975         APP_LOGE("DataMgr is nullptr");
5976         return false;
5977     }
5978     return dataMgr->GreatOrEqualTargetAPIVersion(platformVersion, minorVersion, patchVersion);
5979 }
5980 
GetCallingInfo(int32_t callingUid,std::string & callingBundleName,std::string & callingAppId)5981 bool BundleMgrHostImpl::GetCallingInfo(int32_t callingUid, std::string &callingBundleName, std::string &callingAppId)
5982 {
5983     auto dataMgr = GetDataMgrFromService();
5984     if (dataMgr == nullptr) {
5985         LOG_E(BMS_TAG_QUERY, "DataMgr is nullptr");
5986         return false;
5987     }
5988     if (!dataMgr->GetBundleNameForUid(callingUid, callingBundleName)) {
5989         LOG_D(BMS_TAG_INSTALLER, "CallingUid %{public}d is not hap, no bundleName", callingUid);
5990         return false;
5991     }
5992 
5993     std::string appIdentifier;
5994     ErrCode ret = dataMgr->GetAppIdAndAppIdentifierByBundleName(callingBundleName, callingAppId, appIdentifier);
5995     if (ret != ERR_OK) {
5996         LOG_W(BMS_TAG_DEFAULT, "GetAppIdAndAppIdentifierByBundleName failed");
5997         return false;
5998     }
5999     LOG_D(BMS_TAG_INSTALLER, "get callingBundleName: %{public}s, callingAppId:%{public}s",
6000         callingBundleName.c_str(), callingAppId.c_str());
6001     return true;
6002 }
6003 
SendQueryBundleInfoEvent(QueryEventInfo & query,int64_t intervalTime,bool reportNow)6004 bool BundleMgrHostImpl::SendQueryBundleInfoEvent(
6005     QueryEventInfo &query, int64_t intervalTime, bool reportNow)
6006 {
6007     ErrCode errCode = query.errCode;
6008     if (std::find(QUERY_EXPECTED_ERR.begin(), QUERY_EXPECTED_ERR.end(), errCode) != QUERY_EXPECTED_ERR.end()) {
6009         APP_LOGD("No need report for -e:%{public}d", errCode);
6010         return false;
6011     }
6012     int32_t callingUid = IPCSkeleton::GetCallingUid();
6013     APP_LOGD("start, -f:%{public}d, -c:%{public}d, -e:%{public}d",
6014         query.funcId, callingUid, errCode);
6015     // get calling bundle info
6016     std::string callingBundleName = Constants::EMPTY_STRING;
6017     std::string callingAppId = Constants::EMPTY_STRING;
6018     GetCallingInfo(callingUid, callingBundleName, callingAppId);
6019     query.callingUid = callingUid;
6020     query.callingBundleName = callingBundleName;
6021     query.callingAppId = callingAppId;
6022 
6023     InsertQueryEventInfo(errCode, query);
6024     auto infos = GetQueryEventInfo(errCode);
6025     // check report now
6026     if (reportNow) {
6027         EventInfo report;
6028         TransQueryEventInfo(infos, report);
6029         APP_LOGD("SendSystemEvent now");
6030         EventReport::SendSystemEvent(BMSEventType::QUERY_BUNDLE_INFO, report);
6031         EraseQueryEventInfo(errCode);
6032         return true;
6033     }
6034 
6035     size_t infoSize = infos.size();
6036     int32_t lastReportEventTime = infos[0].lastReportEventTime;
6037     if (infoSize >= MAX_QUERY_EVENT_REPORT_ONCE ||
6038         (BundleUtil::GetCurrentTime() - lastReportEventTime) >= intervalTime) {
6039         APP_LOGD("SendSystemEvent for :%{public}d", errCode);
6040         EventInfo report;
6041         TransQueryEventInfo(infos, report);
6042         EventReport::SendSystemEvent(BMSEventType::QUERY_BUNDLE_INFO, report);
6043         EraseQueryEventInfo(errCode);
6044         return true;
6045     }
6046     return false;
6047 }
6048 
GetPluginInfo(const std::string & hostBundleName,const std::string & pluginBundleName,const int32_t userId,PluginBundleInfo & pluginBundleInfo)6049 ErrCode BundleMgrHostImpl::GetPluginInfo(const std::string &hostBundleName, const std::string &pluginBundleName,
6050     const int32_t userId, PluginBundleInfo &pluginBundleInfo)
6051 {
6052     APP_LOGD("start GetPluginInfo");
6053     if (!BundlePermissionMgr::IsBundleSelfCalling(hostBundleName)) {
6054         if (!BundlePermissionMgr::IsSystemApp()) {
6055             APP_LOGE("non-system app calling system api");
6056             return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED;
6057         }
6058         if (!BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) {
6059             APP_LOGE("Verify permission failed");
6060             return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
6061         }
6062     }
6063     auto dataMgr = GetDataMgrFromService();
6064     if (dataMgr == nullptr) {
6065         APP_LOGE("DataMgr is nullptr");
6066         return ERR_APPEXECFWK_NULL_PTR;
6067     }
6068     return dataMgr->GetPluginInfo(hostBundleName, pluginBundleName, userId, pluginBundleInfo);
6069 }
6070 
GetTestRunner(const std::string & bundleName,const std::string & moduleName,ModuleTestRunner & testRunner)6071 ErrCode BundleMgrHostImpl::GetTestRunner(const std::string &bundleName, const std::string &moduleName,
6072     ModuleTestRunner &testRunner)
6073 {
6074     APP_LOGD("GetTestRunner -n: %{public}s -m %{public}s", bundleName.c_str(), moduleName.c_str());
6075     if (!BundlePermissionMgr::IsBundleSelfCalling(bundleName)) {
6076         LOG_E(BMS_TAG_DEFAULT, "not self calling");
6077         return ERR_BUNDLE_MANAGER_PERMISSION_DENIED;
6078     }
6079 
6080     auto dataMgr = GetDataMgrFromService();
6081     if (dataMgr == nullptr) {
6082         APP_LOGE("dataMgr is nullptr");
6083         return ERR_APPEXECFWK_NULL_PTR;
6084     }
6085     return dataMgr->GetTestRunner(bundleName, moduleName, testRunner);
6086 }
6087 }  // namespace AppExecFwk
6088 }  // namespace OHOS
6089