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