1 /*
2  * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "bundle_connect_ability_mgr.h"
17 
18 #include "ability_manager_client.h"
19 #include "app_log_tag_wrapper.h"
20 #include "bundle_memory_guard.h"
21 #include "bundle_mgr_service.h"
22 #include "ffrt_inner.h"
23 #include "hitrace_meter.h"
24 #include "service_center_connection.h"
25 #include "service_center_status_callback.h"
26 #include "system_ability_load_callback_stub.h"
27 
28 namespace OHOS {
29 namespace AppExecFwk {
30 namespace {
31 const std::string PARAM_FREEINSTALL_APPID = "ohos.freeinstall.params.callingAppId";
32 const std::string PARAM_FREEINSTALL_BUNDLENAMES = "ohos.freeinstall.params.callingBundleNames";
33 const std::string PARAM_SUB_PACKAGE_NAME = "ohos.param.atomicservice.subpackageName";
34 const std::string PARAM_FREEINSTALL_TARGET_APP_DIST_TYPE = "send_to_erms_targetAppDistType";
35 const std::string PARAM_FREEINSTALL_EMBEDDED = "send_to_erms_embedded";
36 const std::string PARAM_FREEINSTALL_TARGET_APP_PROVISION_TYPE = "send_to_erms_targetAppProvisionType";
37 const std::string PARAM_FREEINSTALL_UID = "ohos.freeinstall.params.callingUid";
38 const std::string DISCONNECT_DELAY_TASK = "DisconnectDelayTask";
39 const std::string DEFAULT_VERSION = "1";
40 const std::string CONNECT_ABILITY_QUEUE = "ConnectAbilityQueue";
41 constexpr uint32_t CALLING_TYPE_HARMONY = 2;
42 constexpr uint32_t BIT_ZERO_COMPATIBLE = 0;
43 constexpr uint32_t BIT_ONE_FRONT_MODE = 0;
44 constexpr uint32_t BIT_ONE_BACKGROUND_MODE = 1;
45 constexpr uint32_t BIT_TWO_CUSTOM = 0;
46 constexpr uint32_t BIT_THREE_ZERO = 0;
47 constexpr uint32_t BIT_FOUR_AZ_DEVICE = 0;
48 constexpr uint32_t BIT_FIVE_SAME_BUNDLE_NAME = 0;
49 constexpr uint32_t BIT_SIX_SAME_BUNDLE = 0;
50 constexpr uint32_t BIT_ONE = 2;
51 constexpr uint32_t BIT_TWO = 4;
52 constexpr uint32_t BIT_THREE = 8;
53 constexpr uint32_t BIT_FOUR = 16;
54 constexpr uint32_t BIT_FIVE = 32;
55 constexpr uint32_t BIT_SIX = 64;
56 constexpr uint32_t DISCONNECT_DELAY = 20000;
57 constexpr uint32_t OUT_TIME = 30000;
58 const std::u16string ATOMIC_SERVICE_STATUS_CALLBACK_TOKEN = u"ohos.IAtomicServiceStatusCallback";
59 const std::u16string SERVICE_CENTER_TOKEN = u"abilitydispatcherhm.openapi.hapinstall.IHapInstall";
60 constexpr uint32_t FREE_INSTALL_DONE = 0;
61 constexpr uint32_t TYPE_HARMONEY_INVALID = 0;
62 constexpr uint32_t TYPE_HARMONEY_APP = 1;
63 constexpr uint32_t TYPE_HARMONEY_SERVICE = 2;
64 constexpr uint32_t DEFAULT_VALUE = -1;
65 constexpr uint32_t DEFAULT_EMBEDDED_VALUE = 0;
66 constexpr int32_t DMS_UID = 5522;
67 // sa id
68 constexpr int32_t DOWNLOAD_SERVICE_SA_ID = 3706;
69 // replace want int ecological rule
70 constexpr const char* PARAM_REPLACE_WANT = "ohos.extra.param.key.replace_want";
71 
SendSysEvent(int32_t resultCode,const AAFwk::Want & want,int32_t userId)72 void SendSysEvent(int32_t resultCode, const AAFwk::Want &want, int32_t userId)
73 {
74     EventInfo sysEventInfo;
75     ElementName element = want.GetElement();
76     sysEventInfo.bundleName = element.GetBundleName();
77     sysEventInfo.moduleName = element.GetModuleName();
78     sysEventInfo.abilityName = element.GetAbilityName();
79     sysEventInfo.isFreeInstallMode = true;
80     sysEventInfo.userId = userId;
81     sysEventInfo.errCode = resultCode;
82     EventReport::SendSystemEvent(BMSEventType::BUNDLE_INSTALL_EXCEPTION, sysEventInfo);
83 }
84 }
85 
BundleConnectAbilityMgr()86 BundleConnectAbilityMgr::BundleConnectAbilityMgr()
87 {
88     LOG_D(BMS_TAG_DEFAULT, "create BundleConnectAbilityMgr");
89     serialQueue_ = std::make_shared<SerialQueue>(CONNECT_ABILITY_QUEUE);
90 }
91 
~BundleConnectAbilityMgr()92 BundleConnectAbilityMgr::~BundleConnectAbilityMgr()
93 {
94     LOG_D(BMS_TAG_DEFAULT, "destroy BundleConnectAbilityMgr");
95 }
96 
ProcessPreloadCheck(const TargetAbilityInfo & targetAbilityInfo)97 bool BundleConnectAbilityMgr::ProcessPreloadCheck(const TargetAbilityInfo &targetAbilityInfo)
98 {
99     LOG_D(BMS_TAG_DEFAULT, "ProcessPreloadCheck");
100     auto preloadCheckFunc = [this, targetAbilityInfo]() {
101         BundleMemoryGuard memoryGuard;
102         int32_t flag = ServiceCenterFunction::CONNECT_PRELOAD_INSTALL;
103         this->ProcessPreloadRequestToServiceCenter(flag, targetAbilityInfo);
104     };
105     ffrt::submit(preloadCheckFunc);
106     return true;
107 }
108 
ProcessPreloadRequestToServiceCenter(int32_t flag,const TargetAbilityInfo & targetAbilityInfo)109 void BundleConnectAbilityMgr::ProcessPreloadRequestToServiceCenter(int32_t flag,
110     const TargetAbilityInfo &targetAbilityInfo)
111 {
112     LOG_D(BMS_TAG_DEFAULT, "ProcessPreloadRequestToServiceCenter");
113     std::shared_ptr<BundleMgrService> bms = DelayedSingleton<BundleMgrService>::GetInstance();
114     std::shared_ptr<BundleDataMgr> bundleDataMgr_ = bms->GetDataMgr();
115     if (bundleDataMgr_ == nullptr) {
116         LOG_E(BMS_TAG_DEFAULT, "GetDataMgr failed, bundleDataMgr_ is nullptr");
117         return;
118     }
119     std::string bundleName;
120     std::string abilityName;
121     if (!(bundleDataMgr_->QueryAppGalleryAbilityName(bundleName, abilityName))) {
122         LOG_E(BMS_TAG_DEFAULT, "Fail to query ServiceCenter ability and bundle name");
123         return;
124     }
125     auto task = [ owner = weak_from_this() ] {
126         auto mgr = owner.lock();
127         if (mgr == nullptr) {
128             LOG_E(BMS_TAG_DEFAULT, "BundleConnectAbilityMgr is nullptr");
129             return;
130         }
131         mgr->LoadDownloadService();
132     };
133     std::thread loadServiceThread(task);
134     loadServiceThread.detach();
135     Want serviceCenterWant;
136     serviceCenterWant.SetElementName(bundleName, abilityName);
137     bool isConnectSuccess = ConnectAbility(serviceCenterWant, nullptr);
138     if (!isConnectSuccess) {
139         LOG_E(BMS_TAG_DEFAULT, "Fail to connect ServiceCenter");
140         return;
141     } else {
142         PreloadRequest(flag, targetAbilityInfo);
143         return;
144     }
145 }
146 
PreloadRequest(int32_t flag,const TargetAbilityInfo & targetAbilityInfo)147 void BundleConnectAbilityMgr::PreloadRequest(int32_t flag, const TargetAbilityInfo &targetAbilityInfo)
148 {
149     MessageParcel data;
150     MessageParcel reply;
151     MessageOption option(MessageOption::TF_ASYNC);
152     if (!data.WriteInterfaceToken(SERVICE_CENTER_TOKEN)) {
153         LOG_E(BMS_TAG_DEFAULT, "failed to WriteInterfaceToken");
154         return;
155     }
156     const std::string dataString = GetJsonStrFromInfo(targetAbilityInfo);
157     LOG_I(BMS_TAG_DEFAULT, "TargetAbilityInfo to JsonString : %{public}s", dataString.c_str());
158     if (!data.WriteString16(Str8ToStr16(dataString))) {
159         LOG_E(BMS_TAG_DEFAULT, "failed to WriteParcelable targetAbilityInfo");
160         return;
161     }
162     sptr<ServiceCenterStatusCallback> callback = new(std::nothrow) ServiceCenterStatusCallback(weak_from_this());
163     if (callback == nullptr) {
164         LOG_E(BMS_TAG_DEFAULT, "callback is nullptr");
165         return;
166     }
167     if (!data.WriteRemoteObject(callback)) {
168         LOG_E(BMS_TAG_DEFAULT, "failed to WriteRemoteObject callbcak");
169         return;
170     }
171     serviceCenterRemoteObject_ = serviceCenterConnection_->GetRemoteObject();
172     if (serviceCenterRemoteObject_ == nullptr) {
173         LOG_E(BMS_TAG_DEFAULT, "failed to get remote object");
174         return;
175     }
176     sptr<FreeInstallParams> freeInstallParams = new(std::nothrow) FreeInstallParams();
177     if (freeInstallParams == nullptr) {
178         LOG_E(BMS_TAG_DEFAULT, "freeInstallParams is nullptr");
179         return;
180     }
181     freeInstallParams->serviceCenterFunction = ServiceCenterFunction::CONNECT_PRELOAD_INSTALL;
182     std::unique_lock<std::mutex> lock(mapMutex_);
183     auto emplaceResult = freeInstallParamsMap_.emplace(targetAbilityInfo.targetInfo.transactId, *freeInstallParams);
184     LOG_I(BMS_TAG_DEFAULT, "emplace map size = %{public}zu, transactId = %{public}s",
185         freeInstallParamsMap_.size(), targetAbilityInfo.targetInfo.transactId.c_str());
186     if (!emplaceResult.second) {
187         LOG_E(BMS_TAG_DEFAULT, "freeInstallParamsMap emplace error");
188         return;
189     }
190     lock.unlock();
191     int32_t result = serviceCenterRemoteObject_->SendRequest(flag, data, reply, option);
192     if (result != ERR_OK) {
193         LOG_E(BMS_TAG_DEFAULT, "Failed to sendRequest, result = %{public}d", result);
194     }
195     LOG_D(BMS_TAG_DEFAULT, "sendRequest to service center success");
196 }
197 
GetPreloadFlag()198 int32_t BundleConnectAbilityMgr::GetPreloadFlag()
199 {
200     int32_t flagZero = BIT_ZERO_COMPATIBLE;
201     int32_t flagOne = BIT_ONE_BACKGROUND_MODE * BIT_ONE;
202     int32_t flagTwo = BIT_TWO_CUSTOM * BIT_TWO;
203     int32_t flagThree = BIT_THREE_ZERO * BIT_THREE;
204     int32_t flagFour = BIT_FOUR_AZ_DEVICE * BIT_FOUR;
205     int32_t flagFive = BIT_FIVE_SAME_BUNDLE_NAME * BIT_FIVE;
206     int32_t flagSix = BIT_SIX_SAME_BUNDLE * BIT_SIX;
207     return flagZero + flagOne + flagTwo + flagThree + flagFour + flagFive + flagSix;
208 }
209 
GetPreloadList(const std::string & bundleName,const std::string & moduleName,int32_t userId,sptr<TargetAbilityInfo> & targetAbilityInfo)210 bool BundleConnectAbilityMgr::GetPreloadList(const std::string &bundleName, const std::string &moduleName,
211     int32_t userId, sptr<TargetAbilityInfo> &targetAbilityInfo)
212 {
213     std::shared_ptr<BundleMgrService> bms = DelayedSingleton<BundleMgrService>::GetInstance();
214     std::shared_ptr<BundleDataMgr> bundleDataMgr_ = bms->GetDataMgr();
215     if (bundleDataMgr_ == nullptr) {
216         LOG_E(BMS_TAG_DEFAULT, "GetDataMgr failed, bundleDataMgr_ is nullptr");
217         return false;
218     }
219     InnerBundleInfo innerBundleInfo;
220     int32_t flag = ApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE;
221     auto ret = bundleDataMgr_->GetInnerBundleInfoWithBundleFlagsAndLock(bundleName, flag, innerBundleInfo, userId);
222     if (!ret) {
223         LOG_E(BMS_TAG_DEFAULT, "GetInnerBundleInfoWithBundleFlagsAndLock failed");
224         return false;
225     }
226     if (innerBundleInfo.GetBaseApplicationInfo().bundleType != BundleType::ATOMIC_SERVICE) {
227         return false;
228     }
229     if (moduleName.empty()) {
230         LOG_E(BMS_TAG_DEFAULT, "moduleName is empty");
231         return false;
232     }
233     std::set<std::string> preloadModuleNames;
234     auto moduleInfoMap = innerBundleInfo.GetInnerModuleInfos();
235     if (moduleInfoMap.find(moduleName) == moduleInfoMap.end()) {
236         LOG_E(BMS_TAG_DEFAULT, "get moduleInfo from innerBundleInfo failed");
237         return false;
238     }
239     auto preloadItems = moduleInfoMap[moduleName].preloads;
240     if (preloadItems.empty()) {
241         return false;
242     }
243     for (const auto &item : preloadItems) {
244         preloadModuleNames.insert(item);
245     }
246     for (const auto &it : moduleInfoMap) {
247         auto iter = preloadModuleNames.find(it.first);
248         if (iter != preloadModuleNames.end()) {
249             preloadModuleNames.erase(iter);
250         }
251     }
252     if (preloadModuleNames.empty()) {
253         LOG_D(BMS_TAG_DEFAULT, "All preload modules exist locally");
254         return false;
255     }
256     targetAbilityInfo->targetInfo.callingAppIds.emplace_back(innerBundleInfo.GetBaseBundleInfo().appId);
257     for (const auto &item : preloadModuleNames) {
258         targetAbilityInfo->targetInfo.preloadModuleNames.emplace_back(item);
259     }
260     return true;
261 }
262 
ProcessPreload(const Want & want)263 bool BundleConnectAbilityMgr::ProcessPreload(const Want &want)
264 {
265     LOG_D(BMS_TAG_DEFAULT, "BundleConnectAbilityMgr::ProcessPreload is called");
266     std::string bundleName = want.GetElement().GetBundleName();
267     std::string moduleName = want.GetElement().GetModuleName();
268     std::string abilityName = want.GetElement().GetAbilityName();
269     int32_t uid = want.GetIntParam("uid", 0);
270     int32_t userId = uid / Constants::BASE_USER_RANGE;
271     sptr<TargetAbilityInfo> targetAbilityInfo = new(std::nothrow) TargetAbilityInfo();
272     if (targetAbilityInfo == nullptr) {
273         LOG_E(BMS_TAG_DEFAULT, "targetAbilityInfo is nullptr");
274         return false;
275     }
276     sptr<TargetInfo> targetInfo = new(std::nothrow) TargetInfo();
277     if (targetInfo == nullptr) {
278         LOG_E(BMS_TAG_DEFAULT, "targetInfo is nullptr");
279         return false;
280     }
281     sptr<TargetExtSetting> targetExtSetting = new(std::nothrow) TargetExtSetting();
282     if (targetExtSetting == nullptr) {
283         LOG_E(BMS_TAG_DEFAULT, "targetExtSetting is nullptr");
284         return false;
285     }
286     targetAbilityInfo->targetInfo = *targetInfo;
287     targetAbilityInfo->targetExtSetting = *targetExtSetting;
288     targetAbilityInfo->version = DEFAULT_VERSION;
289 
290     if (!GetPreloadList(bundleName, moduleName, userId, targetAbilityInfo)) {
291         LOG_D(BMS_TAG_DEFAULT, "the module have no preload module");
292         return false;
293     }
294     targetAbilityInfo->targetInfo.transactId = std::to_string(this->GetTransactId());
295     targetAbilityInfo->targetInfo.bundleName = bundleName;
296     targetAbilityInfo->targetInfo.moduleName = moduleName;
297     targetAbilityInfo->targetInfo.abilityName = abilityName;
298     targetAbilityInfo->targetInfo.action = want.GetAction();
299     targetAbilityInfo->targetInfo.uri = want.GetUriString();
300     targetAbilityInfo->targetInfo.type = want.GetType();
301     targetAbilityInfo->targetInfo.flags = GetPreloadFlag();
302     targetAbilityInfo->targetInfo.callingUid = uid;
303     targetAbilityInfo->targetInfo.callingAppType = CALLING_TYPE_HARMONY;
304     targetAbilityInfo->targetInfo.callingBundleNames.emplace_back(bundleName);
305     if (!ProcessPreloadCheck(*targetAbilityInfo)) {
306         LOG_E(BMS_TAG_DEFAULT, "ProcessPreloadCheck failed");
307         return false;
308     }
309     return true;
310 }
311 
SilentInstall(TargetAbilityInfo & targetAbilityInfo,const Want & want,const FreeInstallParams & freeInstallParams,int32_t userId)312 bool BundleConnectAbilityMgr::SilentInstall(TargetAbilityInfo &targetAbilityInfo, const Want &want,
313     const FreeInstallParams &freeInstallParams, int32_t userId)
314 {
315     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
316     LOG_I(BMS_TAG_DEFAULT, "SilentInstall");
317     if (!CheckIsOnDemandLoad(targetAbilityInfo)) {
318         ErmsCallerInfo callerInfo;
319         GetEcologicalCallerInfo(want, callerInfo, userId);
320         BmsExperienceRule rule;
321         bool ret = CheckEcologicalRule(want, callerInfo, rule);
322         if (!ret) {
323             LOG_E(BMS_TAG_DEFAULT, "check ecological rule failed, skip");
324         } else if (rule.isAllow) {
325             LOG_I(BMS_TAG_DEFAULT, "ecological rule is allow, keep going");
326         } else if (rule.replaceWant != nullptr) {
327             LOG_I(BMS_TAG_DEFAULT, "ecological rule is replace want");
328             targetAbilityInfo.targetExtSetting.extValues.emplace(PARAM_REPLACE_WANT,
329                 rule.replaceWant->ToUri());
330         } else {
331             LOG_W(BMS_TAG_DEFAULT, "ecological rule is not allowed, return");
332             CallAbilityManager(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId, freeInstallParams.callback);
333             return false;
334         }
335     }
336 
337     auto silentInstallFunc = [this, targetAbilityInfo, want, userId, freeInstallParams]() {
338         BundleMemoryGuard memoryGuard;
339         int32_t flag = ServiceCenterFunction::CONNECT_SILENT_INSTALL;
340         this->SendRequestToServiceCenter(flag, targetAbilityInfo, want, userId, freeInstallParams);
341     };
342     ffrt::submit(silentInstallFunc, {}, {}, ffrt::task_attr().qos(ffrt::qos_deadline_request));
343     return true;
344 }
345 
UpgradeCheck(const TargetAbilityInfo & targetAbilityInfo,const Want & want,const FreeInstallParams & freeInstallParams,int32_t userId)346 bool BundleConnectAbilityMgr::UpgradeCheck(const TargetAbilityInfo &targetAbilityInfo, const Want &want,
347     const FreeInstallParams &freeInstallParams, int32_t userId)
348 {
349     LOG_I(BMS_TAG_DEFAULT, "UpgradeCheck");
350     auto upgradeCheckFunc = [this, targetAbilityInfo, want, userId, freeInstallParams]() {
351         BundleMemoryGuard memoryGuard;
352         int32_t flag = ServiceCenterFunction::CONNECT_UPGRADE_CHECK;
353         this->SendRequestToServiceCenter(flag, targetAbilityInfo, want, userId, freeInstallParams);
354     };
355     ffrt::submit(upgradeCheckFunc);
356     return true;
357 }
358 
UpgradeInstall(const TargetAbilityInfo & targetAbilityInfo,const Want & want,const FreeInstallParams & freeInstallParams,int32_t userId)359 bool BundleConnectAbilityMgr::UpgradeInstall(const TargetAbilityInfo &targetAbilityInfo, const Want &want,
360     const FreeInstallParams &freeInstallParams, int32_t userId)
361 {
362     LOG_I(BMS_TAG_DEFAULT, "UpgradeInstall");
363     auto upgradeInstallFunc = [this, targetAbilityInfo, want, userId, freeInstallParams]() {
364         BundleMemoryGuard memoryGuard;
365         int32_t flag = ServiceCenterFunction::CONNECT_UPGRADE_INSTALL;
366         this->SendRequestToServiceCenter(flag, targetAbilityInfo, want, userId, freeInstallParams);
367     };
368     ffrt::submit(upgradeInstallFunc);
369     return true;
370 }
371 
SendRequestToServiceCenter(int32_t flag,const TargetAbilityInfo & targetAbilityInfo,const Want & want,int32_t userId,const FreeInstallParams & freeInstallParams)372 bool BundleConnectAbilityMgr::SendRequestToServiceCenter(int32_t flag, const TargetAbilityInfo &targetAbilityInfo,
373     const Want &want, int32_t userId, const FreeInstallParams &freeInstallParams)
374 {
375     LOG_I(BMS_TAG_DEFAULT, "SendRequestToServiceCenter");
376     std::shared_ptr<BundleMgrService> bms = DelayedSingleton<BundleMgrService>::GetInstance();
377     std::shared_ptr<BundleDataMgr> bundleDataMgr_ = bms->GetDataMgr();
378     if (bundleDataMgr_ == nullptr) {
379         LOG_E(BMS_TAG_DEFAULT, "GetDataMgr failed, bundleDataMgr_ is nullptr");
380         CallAbilityManager(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId, freeInstallParams.callback);
381         return false;
382     }
383     std::string bundleName;
384     std::string abilityName;
385     if (!(bundleDataMgr_->QueryAppGalleryAbilityName(bundleName, abilityName))) {
386         LOG_E(BMS_TAG_DEFAULT, "Fail to query ServiceCenter ability and bundle name");
387         CallAbilityManager(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId, freeInstallParams.callback);
388         return false;
389     }
390     Want serviceCenterWant;
391     serviceCenterWant.SetElementName(bundleName, abilityName);
392     auto task = [ owner = weak_from_this() ] {
393         auto mgr = owner.lock();
394         if (mgr == nullptr) {
395             LOG_E(BMS_TAG_DEFAULT, "BundleConnectAbilityMgr is nullptr");
396             return;
397         }
398         mgr->LoadDownloadService();
399     };
400     std::thread loadServiceThread(task);
401     loadServiceThread.detach();
402     bool isConnectSuccess = ConnectAbility(serviceCenterWant, nullptr);
403     if (!isConnectSuccess) {
404         if (freeInstallParams.serviceCenterFunction == ServiceCenterFunction::CONNECT_UPGRADE_INSTALL) {
405             LOG_E(BMS_TAG_DEFAULT, "Fail to connect ServiceCenter, but freeinstall upgrade return ok");
406             CallAbilityManager(ServiceCenterResultCode::FREE_INSTALL_OK, want, userId, freeInstallParams.callback);
407         } else {
408             LOG_E(BMS_TAG_DEFAULT, "Fail to connect ServiceCenter");
409             CallAbilityManager(FreeInstallErrorCode::CONNECT_ERROR, want, userId, freeInstallParams.callback);
410         }
411         SendSysEvent(FreeInstallErrorCode::CONNECT_ERROR, want, userId);
412         return false;
413     } else {
414         SendRequest(flag, targetAbilityInfo, want, userId, freeInstallParams);
415         return true;
416     }
417 }
418 
LoadDownloadService() const419 void BundleConnectAbilityMgr::LoadDownloadService() const
420 {
421     LOG_I(BMS_TAG_DEFAULT, "LoadDownloadService start");
422     auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
423     if (systemAbilityMgr == nullptr) {
424         LOG_E(BMS_TAG_DEFAULT, "Failed to get SystemAbilityManager");
425         return;
426     }
427     sptr<SystemAbilityLoadCallbackStub> loadCallback = new (std::nothrow) SystemAbilityLoadCallbackStub();
428     if (loadCallback == nullptr) {
429         LOG_E(BMS_TAG_DEFAULT, "Create load callback failed");
430         return;
431     }
432     auto ret = systemAbilityMgr->LoadSystemAbility(DOWNLOAD_SERVICE_SA_ID, loadCallback);
433     if (ret != 0) {
434         LOG_E(BMS_TAG_DEFAULT, "Load system ability %{public}d failed with %{public}d",
435             DOWNLOAD_SERVICE_SA_ID, ret);
436         return;
437     }
438     LOG_I(BMS_TAG_DEFAULT, "LoadDownloadService end");
439 }
440 
DisconnectAbility()441 void BundleConnectAbilityMgr::DisconnectAbility()
442 {
443     if (serviceCenterConnection_ != nullptr) {
444         LOG_I(BMS_TAG_DEFAULT, "DisconnectAbility");
445         int result = AbilityManagerClient::GetInstance()->DisconnectAbility(serviceCenterConnection_);
446         if (result != ERR_OK) {
447             LOG_E(BMS_TAG_DEFAULT, "disconnect fail, resultCode: %{public}d", result);
448         }
449     }
450 }
451 
WaitFromConnecting(std::unique_lock<std::mutex> & lock)452 void BundleConnectAbilityMgr::WaitFromConnecting(std::unique_lock<std::mutex> &lock)
453 {
454     LOG_I(BMS_TAG_DEFAULT, "ConnectAbility await start CONNECTING");
455     while (connectState_ == ServiceCenterConnectState::CONNECTING) {
456         cv_.wait(lock);
457     }
458     LOG_I(BMS_TAG_DEFAULT, "ConnectAbility await end CONNECTING");
459 }
460 
WaitFromConnected(std::unique_lock<std::mutex> & lock)461 void BundleConnectAbilityMgr::WaitFromConnected(std::unique_lock<std::mutex> &lock)
462 {
463     LOG_I(BMS_TAG_DEFAULT, "ConnectAbility await start CONNECTED");
464     while (connectState_ != ServiceCenterConnectState::CONNECTED) {
465         if (connectState_ == ServiceCenterConnectState::DISCONNECTED) {
466             break;
467         }
468         cv_.wait(lock);
469     }
470     LOG_I(BMS_TAG_DEFAULT, "ConnectAbility await end CONNECTED");
471 }
472 
ConnectAbility(const Want & want,const sptr<IRemoteObject> & callerToken)473 bool BundleConnectAbilityMgr::ConnectAbility(const Want &want, const sptr<IRemoteObject> &callerToken)
474 {
475     LOG_I(BMS_TAG_DEFAULT, "ConnectAbility start target bundle = %{public}s", want.GetBundle().c_str());
476     std::unique_lock<std::mutex> lock(mutex_);
477     serialQueue_->CancelDelayTask(DISCONNECT_DELAY_TASK);
478     if (connectState_ == ServiceCenterConnectState::CONNECTING) {
479         WaitFromConnecting(lock);
480     } else if (connectState_ == ServiceCenterConnectState::DISCONNECTED) {
481         connectState_ = ServiceCenterConnectState::CONNECTING;
482         serviceCenterConnection_ = new (std::nothrow) ServiceCenterConnection(connectState_,
483             cv_, weak_from_this());
484         if (serviceCenterConnection_ == nullptr) {
485             LOG_E(BMS_TAG_DEFAULT, "ServiceCenterConnection is nullptr");
486             connectState_ = ServiceCenterConnectState::DISCONNECTED;
487             cv_.notify_all();
488             return false;
489         }
490         LOG_I(BMS_TAG_DEFAULT, "ConnectAbility start");
491         int result = AbilityManagerClient::GetInstance()->ConnectAbility(want, serviceCenterConnection_, callerToken);
492         if (result == ERR_OK) {
493             if (connectState_ != ServiceCenterConnectState::CONNECTED) {
494                 WaitFromConnected(lock);
495             }
496             serviceCenterRemoteObject_ = serviceCenterConnection_->GetRemoteObject();
497         } else {
498             LOG_E(BMS_TAG_DEFAULT, "ConnectAbility fail result = %{public}d", result);
499         }
500     }
501 
502     LOG_I(BMS_TAG_DEFAULT, "ConnectAbility end");
503     if (connectState_ == ServiceCenterConnectState::CONNECTED) {
504         return true;
505     } else {
506         LOG_E(BMS_TAG_DEFAULT, "ConnectAbility fail");
507         connectState_ = ServiceCenterConnectState::DISCONNECTED;
508         return false;
509     }
510 }
511 
DisconnectDelay()512 void BundleConnectAbilityMgr::DisconnectDelay()
513 {
514     auto disconnectFunc = [connect = shared_from_this()]() {
515         LOG_I(BMS_TAG_DEFAULT, "disconnectFunc Disconnect Ability");
516         BundleMemoryGuard memoryGuard;
517         if (connect) {
518             connect->DisconnectAbility();
519         }
520     };
521     serialQueue_->ScheduleDelayTask(DISCONNECT_DELAY_TASK, DISCONNECT_DELAY, disconnectFunc);
522 }
523 
SendCallBack(int32_t resultCode,const AAFwk::Want & want,int32_t userId,const std::string & transactId)524 void BundleConnectAbilityMgr::SendCallBack(
525     int32_t resultCode, const AAFwk::Want &want, int32_t userId, const std::string &transactId)
526 {
527     LOG_I(BMS_TAG_DEFAULT, "SendCallBack");
528     sptr<IRemoteObject> amsCallBack = GetAbilityManagerServiceCallBack(transactId);
529     if (amsCallBack == nullptr) {
530         LOG_E(BMS_TAG_DEFAULT, "Abilitity manager callback is null");
531         return;
532     }
533 
534     std::unique_lock<std::mutex> lock(mapMutex_);
535     if (freeInstallParamsMap_[transactId].serviceCenterFunction == ServiceCenterFunction::CONNECT_UPGRADE_INSTALL &&
536         resultCode != ServiceCenterResultCode::FREE_INSTALL_OK) {
537         LOG_E(BMS_TAG_DEFAULT, "SendCallBack, freeinstall upgrade return ok");
538         resultCode = ServiceCenterResultCode::FREE_INSTALL_OK;
539     }
540     freeInstallParamsMap_.erase(transactId);
541     LOG_I(BMS_TAG_DEFAULT, "erase map size = %{public}zu, transactId = %{public}s",
542         freeInstallParamsMap_.size(), transactId.c_str());
543     if (freeInstallParamsMap_.size() == 0) {
544         if (connectState_ == ServiceCenterConnectState::CONNECTED) {
545             LOG_I(BMS_TAG_DEFAULT, "DisconnectDelay");
546             DisconnectDelay();
547         }
548     }
549     lock.unlock();
550 
551     MessageParcel data;
552     if (!data.WriteInterfaceToken(ATOMIC_SERVICE_STATUS_CALLBACK_TOKEN)) {
553         LOG_E(BMS_TAG_DEFAULT, "Write interface token failed");
554         return;
555     }
556     if (!data.WriteInt32(resultCode)) {
557         LOG_E(BMS_TAG_DEFAULT, "Write result code failed");
558         return;
559     }
560     if (!data.WriteParcelable(&want)) {
561         LOG_E(BMS_TAG_DEFAULT, "Write want failed");
562         return;
563     }
564     if (!data.WriteInt32(userId)) {
565         LOG_E(BMS_TAG_DEFAULT, "Write userId failed");
566         return;
567     }
568     MessageParcel reply;
569     MessageOption option;
570 
571     if (amsCallBack->SendRequest(FREE_INSTALL_DONE, data, reply, option) != ERR_OK) {
572         LOG_E(BMS_TAG_DEFAULT, "BundleConnectAbilityMgr::SendCallBack SendRequest failed");
573     }
574 }
575 
SendCallBack(const std::string & transactId,const FreeInstallParams & freeInstallParams)576 void BundleConnectAbilityMgr::SendCallBack(const std::string &transactId, const FreeInstallParams &freeInstallParams)
577 {
578     if (freeInstallParams.callback == nullptr) {
579         LOG_E(BMS_TAG_DEFAULT, "freeInstallParams.callback is null");
580         return;
581     }
582 
583     MessageParcel data;
584     if (!data.WriteInterfaceToken(ATOMIC_SERVICE_STATUS_CALLBACK_TOKEN)) {
585         LOG_E(BMS_TAG_DEFAULT, "Write interface token failed");
586         return;
587     }
588     if (!data.WriteInt32(FreeInstallErrorCode::SERVICE_CENTER_CRASH)) {
589         LOG_E(BMS_TAG_DEFAULT, "Write result code error");
590         return;
591     }
592     if (!data.WriteParcelable(&(freeInstallParams.want))) {
593         LOG_E(BMS_TAG_DEFAULT, "Write want failed");
594         return;
595     }
596     if (!data.WriteInt32(freeInstallParams.userId)) {
597         LOG_E(BMS_TAG_DEFAULT, "Write userId error");
598         return;
599     }
600     MessageParcel reply;
601     MessageOption option;
602     if (freeInstallParams.callback->SendRequest(FREE_INSTALL_DONE, data, reply, option) != ERR_OK) {
603         LOG_E(BMS_TAG_DEFAULT, "BundleConnectAbilityMgr::SendCallBack SendRequest failed");
604     }
605 }
606 
DeathRecipientSendCallback()607 void BundleConnectAbilityMgr::DeathRecipientSendCallback()
608 {
609     LOG_I(BMS_TAG_DEFAULT, "DeathRecipientSendCallback start");
610     std::unique_lock<std::mutex> lock(mapMutex_);
611     LOG_I(BMS_TAG_DEFAULT, "freeInstallParamsMap size = %{public}zu", freeInstallParamsMap_.size());
612     for (auto &it : freeInstallParamsMap_) {
613         SendCallBack(it.first, it.second);
614     }
615     freeInstallParamsMap_.clear();
616     lock.unlock();
617 
618     connectState_ = ServiceCenterConnectState::DISCONNECTED;
619     serviceCenterRemoteObject_ = nullptr;
620     cv_.notify_all();
621 
622     LOG_I(BMS_TAG_DEFAULT, "DeathRecipientSendCallback end");
623 }
624 
OnServiceCenterCall(std::string installResultStr)625 void BundleConnectAbilityMgr::OnServiceCenterCall(std::string installResultStr)
626 {
627     LOG_I(BMS_TAG_DEFAULT, "OnServiceCenterCall start, installResultStr = %{public}s", installResultStr.c_str());
628     InstallResult installResult;
629     if (!ParseInfoFromJsonStr(installResultStr.c_str(), installResult)) {
630         LOG_E(BMS_TAG_DEFAULT, "Parse info from json fail");
631         return;
632     }
633     LOG_I(BMS_TAG_DEFAULT, "OnServiceCenterCall, retCode = %{public}d", installResult.result.retCode);
634     FreeInstallParams freeInstallParams;
635     std::unique_lock<std::mutex> lock(mapMutex_);
636     auto node = freeInstallParamsMap_.find(installResult.result.transactId);
637     if (node == freeInstallParamsMap_.end()) {
638         LOG_E(BMS_TAG_DEFAULT, "Can not find node");
639         return;
640     }
641     serialQueue_->CancelDelayTask(installResult.result.transactId);
642     freeInstallParams = node->second;
643     lock.unlock();
644     if (installResult.result.retCode == ServiceCenterResultCode::FREE_INSTALL_DOWNLOADING) {
645         LOG_I(BMS_TAG_DEFAULT, "ServiceCenter is downloading, downloadSize = %{public}d, totalSize = %{public}d",
646             installResult.progress.downloadSize, installResult.progress.totalSize);
647         return;
648     }
649     LOG_I(BMS_TAG_DEFAULT, "serviceCenterFunction = %{public}d", freeInstallParams.serviceCenterFunction);
650     if (freeInstallParams.serviceCenterFunction == ServiceCenterFunction::CONNECT_UPGRADE_INSTALL &&
651         installResult.result.retCode != ServiceCenterResultCode::FREE_INSTALL_OK) {
652         LOG_E(BMS_TAG_DEFAULT, "freeinstall upgrade return ok");
653         installResult.result.retCode = ServiceCenterResultCode::FREE_INSTALL_OK;
654     }
655     SendCallBack(installResult.result.retCode, freeInstallParams.want, freeInstallParams.userId,
656         installResult.result.transactId);
657     LOG_I(BMS_TAG_DEFAULT, "OnServiceCenterCall end");
658 }
659 
OnDelayedHeartbeat(std::string installResultStr)660 void BundleConnectAbilityMgr::OnDelayedHeartbeat(std::string installResultStr)
661 {
662     LOG_I(BMS_TAG_DEFAULT, "OnDelayedHeartbeat start, installResultStr = %{public}s", installResultStr.c_str());
663     InstallResult installResult;
664     if (!ParseInfoFromJsonStr(installResultStr.c_str(), installResult)) {
665         LOG_E(BMS_TAG_DEFAULT, "Parse info from json fail");
666         return;
667     }
668     LOG_I(BMS_TAG_DEFAULT, "OnDelayedHeartbeat, retCode = %{public}d", installResult.result.retCode);
669     FreeInstallParams freeInstallParams;
670     std::unique_lock<std::mutex> lock(mapMutex_);
671     auto node = freeInstallParamsMap_.find(installResult.result.transactId);
672     if (node == freeInstallParamsMap_.end()) {
673         LOG_E(BMS_TAG_DEFAULT, "Can not find node");
674         return;
675     }
676     serialQueue_->CancelDelayTask(installResult.result.transactId);
677     lock.unlock();
678     OutTimeMonitor(installResult.result.transactId);
679     LOG_I(BMS_TAG_DEFAULT, "OnDelayedHeartbeat end");
680 }
681 
OnServiceCenterReceived(std::string installResultStr)682 void BundleConnectAbilityMgr::OnServiceCenterReceived(std::string installResultStr)
683 {
684     LOG_I(BMS_TAG_DEFAULT, "installResultStr = %{public}s", installResultStr.c_str());
685     InstallResult installResult;
686     if (!ParseInfoFromJsonStr(installResultStr.c_str(), installResult)) {
687         LOG_E(BMS_TAG_DEFAULT, "Parse info from json fail");
688         return;
689     }
690     FreeInstallParams freeInstallParams;
691     std::unique_lock<std::mutex> lock(mapMutex_);
692     auto node = freeInstallParamsMap_.find(installResult.result.transactId);
693     if (node == freeInstallParamsMap_.end()) {
694         LOG_E(BMS_TAG_DEFAULT, "Can not find node");
695         return;
696     }
697     if (DISCONNECT_ABILITY_FUNC.find(node->second.serviceCenterFunction) == DISCONNECT_ABILITY_FUNC.end()) {
698         LOG_E(BMS_TAG_DEFAULT, "%{public}d not in DISCONNECT_ABILITY_FUNC", node->second.serviceCenterFunction);
699         return;
700     }
701     freeInstallParamsMap_.erase(installResult.result.transactId);
702     LOG_I(BMS_TAG_DEFAULT, "erase map size = %{public}zu, transactId = %{public}s",
703         freeInstallParamsMap_.size(), installResult.result.transactId.c_str());
704     if (freeInstallParamsMap_.size() == 0) {
705         if (connectState_ == ServiceCenterConnectState::CONNECTED) {
706             LOG_I(BMS_TAG_DEFAULT, "DisconnectDelay");
707             DisconnectDelay();
708         }
709     }
710 }
711 
OutTimeMonitor(std::string transactId)712 void BundleConnectAbilityMgr::OutTimeMonitor(std::string transactId)
713 {
714     LOG_I(BMS_TAG_DEFAULT, "BundleConnectAbilityMgr::OutTimeMonitor");
715     FreeInstallParams freeInstallParams;
716     std::unique_lock<std::mutex> lock(mapMutex_);
717     auto node = freeInstallParamsMap_.find(transactId);
718     if (node == freeInstallParamsMap_.end()) {
719         LOG_E(BMS_TAG_DEFAULT, "Can not find node");
720         return;
721     }
722     freeInstallParams = node->second;
723     lock.unlock();
724     auto RegisterEventListenerFunc = [this, freeInstallParams, transactId]() {
725         LOG_I(BMS_TAG_DEFAULT, "RegisterEventListenerFunc");
726         BundleMemoryGuard memoryGuard;
727         this->SendCallBack(FreeInstallErrorCode::SERVICE_CENTER_TIMEOUT,
728             freeInstallParams.want, freeInstallParams.userId, transactId);
729     };
730     serialQueue_->ScheduleDelayTask(transactId, OUT_TIME, RegisterEventListenerFunc);
731 }
732 
SendRequest(int32_t flag,const TargetAbilityInfo & targetAbilityInfo,const Want & want,int32_t userId,const FreeInstallParams & freeInstallParams)733 void BundleConnectAbilityMgr::SendRequest(int32_t flag, const TargetAbilityInfo &targetAbilityInfo, const Want &want,
734     int32_t userId, const FreeInstallParams &freeInstallParams)
735 {
736     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
737     MessageParcel data;
738     MessageParcel reply;
739     MessageOption option(MessageOption::TF_ASYNC);
740     if (!data.WriteInterfaceToken(SERVICE_CENTER_TOKEN)) {
741         LOG_E(BMS_TAG_DEFAULT, "failed to WriteInterfaceToken");
742         CallAbilityManager(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId, freeInstallParams.callback);
743         SendSysEvent(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId);
744         return;
745     }
746     const std::string dataString = GetJsonStrFromInfo(targetAbilityInfo);
747     LOG_I(BMS_TAG_DEFAULT, "TargetAbilityInfo to JsonString : %{public}s", dataString.c_str());
748     if (!data.WriteString16(Str8ToStr16(dataString))) {
749         LOG_E(BMS_TAG_DEFAULT, "failed to WriteParcelable targetAbilityInfo");
750         CallAbilityManager(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId, freeInstallParams.callback);
751         SendSysEvent(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId);
752         return;
753     }
754     sptr<ServiceCenterStatusCallback> callback = new(std::nothrow) ServiceCenterStatusCallback(weak_from_this());
755     if (callback == nullptr) {
756         LOG_E(BMS_TAG_DEFAULT, "callback is nullptr");
757         return;
758     }
759     if (!data.WriteRemoteObject(callback)) {
760         LOG_E(BMS_TAG_DEFAULT, "failed to WriteRemoteObject callbcak");
761         CallAbilityManager(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId, freeInstallParams.callback);
762         SendSysEvent(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId);
763         return;
764     }
765     serviceCenterRemoteObject_ = serviceCenterConnection_->GetRemoteObject();
766     if (serviceCenterRemoteObject_ == nullptr) {
767         LOG_E(BMS_TAG_DEFAULT, "failed to get remote object");
768         CallAbilityManager(FreeInstallErrorCode::CONNECT_ERROR, want, userId, freeInstallParams.callback);
769         SendSysEvent(FreeInstallErrorCode::CONNECT_ERROR, want, userId);
770         return;
771     }
772     std::unique_lock<std::mutex> lock(mapMutex_);
773     auto emplaceResult = freeInstallParamsMap_.emplace(targetAbilityInfo.targetInfo.transactId, freeInstallParams);
774     LOG_I(BMS_TAG_DEFAULT, "emplace map size = %{public}zu, transactId = %{public}s",
775         freeInstallParamsMap_.size(), targetAbilityInfo.targetInfo.transactId.c_str());
776     if (!emplaceResult.second) {
777         LOG_E(BMS_TAG_DEFAULT, "freeInstallParamsMap emplace error");
778         CallAbilityManager(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId, freeInstallParams.callback);
779         return;
780     }
781     lock.unlock();
782     int32_t result = serviceCenterRemoteObject_->SendRequest(flag, data, reply, option);
783     if (result != ERR_OK) {
784         LOG_E(BMS_TAG_DEFAULT, "Failed to sendRequest, result = %{public}d", result);
785         SendCallBack(FreeInstallErrorCode::CONNECT_ERROR, want, userId, targetAbilityInfo.targetInfo.transactId);
786         SendSysEvent(FreeInstallErrorCode::CONNECT_ERROR, want, userId);
787         return;
788     }
789     OutTimeMonitor(targetAbilityInfo.targetInfo.transactId);
790 }
791 
SendRequest(int32_t code,MessageParcel & data,MessageParcel & reply)792 bool BundleConnectAbilityMgr::SendRequest(int32_t code, MessageParcel &data, MessageParcel &reply)
793 {
794     LOG_I(BMS_TAG_DEFAULT, "BundleConnectAbilityMgr::SendRequest to service center");
795     serviceCenterRemoteObject_ = serviceCenterConnection_->GetRemoteObject();
796     if (serviceCenterRemoteObject_ == nullptr) {
797         LOG_E(BMS_TAG_DEFAULT, "failed to get remote object");
798         return false;
799     }
800     MessageOption option(MessageOption::TF_ASYNC);
801     int32_t result = serviceCenterRemoteObject_->SendRequest(code, data, reply, option);
802     if (result != ERR_OK) {
803         LOG_E(BMS_TAG_DEFAULT, "failed to send request code:%{public}d", code);
804         return false;
805     }
806     return true;
807 }
808 
GetAbilityManagerServiceCallBack(std::string transactId)809 sptr<IRemoteObject> BundleConnectAbilityMgr::GetAbilityManagerServiceCallBack(std::string transactId)
810 {
811     LOG_I(BMS_TAG_DEFAULT, "GetAbilityManagerServiceCallBack");
812     FreeInstallParams freeInstallParams;
813     std::unique_lock<std::mutex> lock(mapMutex_);
814     auto node = freeInstallParamsMap_.find(transactId);
815     if (node == freeInstallParamsMap_.end()) {
816         LOG_E(BMS_TAG_DEFAULT, "Can not find node transactId = %{public}s", transactId.c_str());
817         return nullptr;
818     }
819     freeInstallParams = node->second;
820     lock.unlock();
821     return freeInstallParams.callback;
822 }
823 
GetCallingInfo(int32_t userId,int32_t callingUid,std::vector<std::string> & bundleNames,std::vector<std::string> & callingAppIds)824 void BundleConnectAbilityMgr::GetCallingInfo(int32_t userId, int32_t callingUid,
825     std::vector<std::string> &bundleNames, std::vector<std::string> &callingAppIds)
826 {
827     LOG_I(BMS_TAG_DEFAULT, "enter");
828     std::shared_ptr<BundleMgrService> bms = DelayedSingleton<BundleMgrService>::GetInstance();
829     std::shared_ptr<BundleDataMgr> bundleDataMgr_ = bms->GetDataMgr();
830     if (bundleDataMgr_ == nullptr) {
831         LOG_E(BMS_TAG_DEFAULT, "GetDataMgr failed, bundleDataMgr_ is nullptr");
832         return;
833     }
834     std::string bundleName;
835     if (bundleDataMgr_->GetBundleNameForUid(callingUid, bundleName)) {
836         bundleNames.emplace_back(bundleName);
837     } else {
838         LOG_E(BMS_TAG_DEFAULT, "GetBundleNameForUid failed");
839     }
840     BundleInfo bundleInfo;
841     if (bundleDataMgr_->GetBundleInfo(bundleName, GET_BUNDLE_DEFAULT, bundleInfo, userId)) {
842         callingAppIds.emplace_back(bundleInfo.appId);
843     } else {
844         LOG_E(BMS_TAG_DEFAULT, "GetBundleInfo failed");
845     }
846 }
847 
ExistBundleNameInCallingBundles(const std::string & bundleName,const std::vector<std::string> & callingBundleNames)848 bool ExistBundleNameInCallingBundles(const std::string &bundleName, const std::vector<std::string> &callingBundleNames)
849 {
850     for (const auto &bundleNameItem : callingBundleNames) {
851         if (bundleNameItem == bundleName) {
852             return true;
853         }
854     }
855     return false;
856 }
857 
GetTargetInfoFlag(const Want & want,const std::string & deviceId,const std::string & bundleName,const std::vector<std::string> & callingBundleNames)858 int32_t GetTargetInfoFlag(const Want &want, const std::string &deviceId, const std::string &bundleName,
859     const std::vector<std::string> &callingBundleNames)
860 {
861     // make int from bits.
862     int32_t flagZero = BIT_ZERO_COMPATIBLE;
863     int32_t flagOne = 0;
864     if ((want.GetFlags() & Want::FLAG_INSTALL_WITH_BACKGROUND_MODE) == 0) {
865         flagOne = BIT_ONE_FRONT_MODE * BIT_ONE;
866     } else {
867         flagOne = BIT_ONE_BACKGROUND_MODE * BIT_ONE;
868     }
869     int32_t flagTwo = BIT_TWO_CUSTOM * BIT_TWO;
870     int32_t flagThree = !deviceId.empty() * BIT_THREE;
871     int32_t flagFour = BIT_FOUR_AZ_DEVICE * BIT_FOUR;
872     int32_t flagFive = !ExistBundleNameInCallingBundles(bundleName, callingBundleNames) * BIT_FIVE;
873     int32_t flagSix = BIT_SIX_SAME_BUNDLE * BIT_SIX;
874     return flagZero + flagOne + flagTwo + flagThree + flagFour + flagFive + flagSix;
875 }
876 
GetTargetAbilityInfo(const Want & want,int32_t userId,const InnerBundleInfo & innerBundleInfo,sptr<TargetAbilityInfo> & targetAbilityInfo)877 void BundleConnectAbilityMgr::GetTargetAbilityInfo(const Want &want, int32_t userId,
878     const InnerBundleInfo &innerBundleInfo, sptr<TargetAbilityInfo> &targetAbilityInfo)
879 {
880     if (targetAbilityInfo == nullptr) {
881         LOG_E(BMS_TAG_DEFAULT, "targetability info is nullptr");
882         return;
883     }
884     ElementName element = want.GetElement();
885     std::string bundleName = element.GetBundleName();
886     std::string moduleName = element.GetModuleName();
887     if (!GetModuleName(innerBundleInfo, want, moduleName)) {
888         LOG_W(BMS_TAG_DEFAULT, "GetModuleName failed");
889     }
890     std::string abilityName = element.GetAbilityName();
891     std::string deviceId = element.GetDeviceID();
892     std::vector<std::string> callingBundleNames;
893     std::vector<std::string> callingAppids;
894     auto wantParams = want.GetParams();
895     std::map<std::string, std::string> extValues;
896     for (auto it : wantParams.GetParams()) {
897         int typeId = WantParams::GetDataType(it.second);
898         auto info = wantParams.GetParam(it.first);
899         std::string value = wantParams.GetStringByType(info, typeId);
900         extValues.emplace(it.first, value);
901     }
902     auto callingUid = want.GetIntParam(PARAM_FREEINSTALL_UID, IPCSkeleton::GetCallingUid());
903 
904     targetAbilityInfo->targetExtSetting.extValues = extValues;
905     targetAbilityInfo->targetInfo.transactId = std::to_string(this->GetTransactId());
906     targetAbilityInfo->targetInfo.bundleName = bundleName;
907     targetAbilityInfo->targetInfo.moduleName = moduleName;
908     targetAbilityInfo->targetInfo.abilityName = abilityName;
909     targetAbilityInfo->targetInfo.action = want.GetAction();
910     targetAbilityInfo->targetInfo.uri = want.GetUriString();
911     targetAbilityInfo->targetInfo.type = want.GetType();
912     targetAbilityInfo->targetInfo.callingUid = callingUid;
913     targetAbilityInfo->targetInfo.callingAppType = CALLING_TYPE_HARMONY;
914     if (callingUid == DMS_UID) {
915         callingAppids.push_back(want.GetStringParam(PARAM_FREEINSTALL_APPID));
916         callingBundleNames = want.GetStringArrayParam(PARAM_FREEINSTALL_BUNDLENAMES);
917     } else {
918         this->GetCallingInfo(userId, callingUid, callingBundleNames, callingAppids);
919     }
920     targetAbilityInfo->targetInfo.callingBundleNames = callingBundleNames;
921     targetAbilityInfo->targetInfo.flags = GetTargetInfoFlag(want, deviceId, bundleName, callingBundleNames);
922     targetAbilityInfo->targetInfo.reasonFlag = static_cast<int32_t>(innerBundleInfo.GetModuleUpgradeFlag(moduleName));
923     targetAbilityInfo->targetInfo.embedded = want.GetIntParam(PARAM_FREEINSTALL_EMBEDDED, DEFAULT_EMBEDDED_VALUE);
924     targetAbilityInfo->targetInfo.callingAppIds = callingAppids;
925 }
926 
CheckSubPackageName(const InnerBundleInfo & innerBundleInfo,const Want & want)927 bool BundleConnectAbilityMgr::CheckSubPackageName(const InnerBundleInfo &innerBundleInfo, const Want &want)
928 {
929     std::string subPackageName = want.GetStringParam(PARAM_SUB_PACKAGE_NAME);
930     if (subPackageName.empty()) {
931         return true;
932     }
933     std::vector<std::string> moduleNameList;
934     innerBundleInfo.GetModuleNames(moduleNameList);
935     auto it = std::find(moduleNameList.begin(), moduleNameList.end(), subPackageName);
936     if (it == moduleNameList.end()) {
937         LOG_I(BMS_TAG_DEFAULT, "check subPackageName %{public}s failed",  subPackageName.c_str());
938         return false;
939     }
940     LOG_I(BMS_TAG_DEFAULT, "check subPackageName %{public}s success",  subPackageName.c_str());
941     return true;
942 }
943 
CallAbilityManager(int32_t resultCode,const Want & want,int32_t userId,const sptr<IRemoteObject> & callBack)944 void BundleConnectAbilityMgr::CallAbilityManager(
945     int32_t resultCode, const Want &want, int32_t userId, const sptr<IRemoteObject> &callBack)
946 {
947     if (callBack == nullptr) {
948         LOG_E(BMS_TAG_DEFAULT, "callBack is nullptr");
949         return;
950     }
951     MessageParcel data;
952     MessageParcel reply;
953     MessageOption option;
954     if (!data.WriteInterfaceToken(ATOMIC_SERVICE_STATUS_CALLBACK_TOKEN)) {
955         LOG_E(BMS_TAG_DEFAULT, "Write interface token failed");
956         return;
957     }
958     if (!data.WriteInt32(resultCode)) {
959         LOG_E(BMS_TAG_DEFAULT, "Write result code failed");
960         return;
961     }
962     if (!data.WriteParcelable(&want)) {
963         LOG_E(BMS_TAG_DEFAULT, "Write want failed");
964         return;
965     }
966     if (!data.WriteInt32(userId)) {
967         LOG_E(BMS_TAG_DEFAULT, "Write userId failed");
968         return;
969     }
970 
971     if (callBack->SendRequest(FREE_INSTALL_DONE, data, reply, option) != ERR_OK) {
972         LOG_E(BMS_TAG_DEFAULT, "BundleConnectAbilityMgr::CallAbilityManager SendRequest failed");
973     }
974 }
975 
CheckIsModuleNeedUpdate(InnerBundleInfo & innerBundleInfo,const Want & want,int32_t userId,const sptr<IRemoteObject> & callBack)976 bool BundleConnectAbilityMgr::CheckIsModuleNeedUpdate(
977     InnerBundleInfo &innerBundleInfo, const Want &want, int32_t userId, const sptr<IRemoteObject> &callBack)
978 {
979     LOG_I(BMS_TAG_DEFAULT, "CheckIsModuleNeedUpdate called");
980     std::string moduleName = want.GetModuleName();
981     if (!GetModuleName(innerBundleInfo, want, moduleName)) {
982         LOG_W(BMS_TAG_DEFAULT, "GetModuleName failed");
983     }
984     if (innerBundleInfo.GetModuleUpgradeFlag(moduleName) != 0) {
985         sptr<TargetAbilityInfo> targetAbilityInfo = new(std::nothrow) TargetAbilityInfo();
986         if (targetAbilityInfo == nullptr) {
987             LOG_E(BMS_TAG_DEFAULT, "targetAbilityInfo is nullptr");
988             return false;
989         }
990         sptr<TargetInfo> targetInfo = new(std::nothrow) TargetInfo();
991         if (targetInfo == nullptr) {
992             LOG_E(BMS_TAG_DEFAULT, "targetInfo is nullptr");
993             return false;
994         }
995         sptr<TargetExtSetting> targetExtSetting = new(std::nothrow) TargetExtSetting();
996         if (targetExtSetting == nullptr) {
997             LOG_E(BMS_TAG_DEFAULT, "targetExtSetting is nullptr");
998             return false;
999         }
1000         targetAbilityInfo->targetInfo = *targetInfo;
1001         targetAbilityInfo->targetExtSetting = *targetExtSetting;
1002         targetAbilityInfo->version = DEFAULT_VERSION;
1003         this->GetTargetAbilityInfo(want, userId, innerBundleInfo, targetAbilityInfo);
1004         if (targetAbilityInfo->targetInfo.moduleName.empty()) {
1005             targetAbilityInfo->targetInfo.moduleName = moduleName;
1006         }
1007         sptr<FreeInstallParams> freeInstallParams = new(std::nothrow) FreeInstallParams();
1008         if (freeInstallParams == nullptr) {
1009             LOG_E(BMS_TAG_DEFAULT, "freeInstallParams is nullptr");
1010             return false;
1011         }
1012         freeInstallParams->callback = callBack;
1013         freeInstallParams->want = want;
1014         freeInstallParams->userId = userId;
1015         freeInstallParams->serviceCenterFunction = ServiceCenterFunction::CONNECT_UPGRADE_INSTALL;
1016         this->UpgradeInstall(*targetAbilityInfo, want, *freeInstallParams, userId);
1017         return true;
1018     }
1019     LOG_I(BMS_TAG_DEFAULT, "Module is not need update");
1020     return false;
1021 }
1022 
IsObtainAbilityInfo(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,const sptr<IRemoteObject> & callBack,InnerBundleInfo & innerBundleInfo)1023 bool BundleConnectAbilityMgr::IsObtainAbilityInfo(const Want &want, int32_t flags, int32_t userId,
1024     AbilityInfo &abilityInfo, const sptr<IRemoteObject> &callBack, InnerBundleInfo &innerBundleInfo)
1025 {
1026     LOG_D(BMS_TAG_DEFAULT, "IsObtainAbilityInfo");
1027     std::string bundleName = want.GetElement().GetBundleName();
1028     std::string abilityName = want.GetElement().GetAbilityName();
1029     std::string moduleName = want.GetElement().GetModuleName();
1030     if (bundleName == "") {
1031         CallAbilityManager(FreeInstallErrorCode::UNDEFINED_ERROR, want, userId, callBack);
1032         LOG_E(BMS_TAG_DEFAULT, "bundle name or ability name is null");
1033         return false;
1034     }
1035     std::shared_ptr<BundleMgrService> bms = DelayedSingleton<BundleMgrService>::GetInstance();
1036     std::shared_ptr<BundleDataMgr> bundleDataMgr_ = bms->GetDataMgr();
1037     if (bundleDataMgr_ == nullptr) {
1038         LOG_E(BMS_TAG_DEFAULT, "GetDataMgr failed, bundleDataMgr_ is nullptr");
1039         return false;
1040     }
1041     bool innerBundleInfoResult = bundleDataMgr_->GetInnerBundleInfoWithBundleFlagsAndLock(bundleName,
1042         flags, innerBundleInfo, userId);
1043     EventReport::SendFreeInstallEvent(bundleName, abilityName, moduleName, innerBundleInfoResult,
1044         BundleUtil::GetCurrentTime());
1045     if (!innerBundleInfoResult) {
1046         APP_LOGE("GetInnerBundleInfoWithBundleFlagsAndLock failed");
1047         return false;
1048     }
1049     if (abilityName.empty()) {
1050         Want launchWant;
1051         auto launchWantResult = bundleDataMgr_->GetLaunchWantForBundle(bundleName, launchWant, userId);
1052         if (launchWantResult == ERR_OK) {
1053             (const_cast<Want &>(want)).SetModuleName(launchWant.GetModuleName());
1054         }
1055         return CheckIsModuleNeedUpdateWrap(innerBundleInfo, want, userId, callBack);
1056     }
1057     bool abilityInfoResult = bundleDataMgr_->QueryAbilityInfo(want, flags, userId, abilityInfo);
1058     if (!abilityInfoResult) {
1059         std::vector<ExtensionAbilityInfo> extensionInfos;
1060         abilityInfoResult = bundleDataMgr_->QueryExtensionAbilityInfos(want, flags, userId, extensionInfos);
1061         if (abilityInfoResult && moduleName.empty()) {
1062             moduleName = extensionInfos[0].moduleName;
1063         }
1064     } else {
1065         if (moduleName.empty()) {
1066             moduleName = abilityInfo.moduleName;
1067         }
1068     }
1069     if (abilityInfoResult) {
1070         if (!CheckSubPackageName(innerBundleInfo, want)) {
1071             return false;
1072         }
1073         return CheckIsModuleNeedUpdateWrap(innerBundleInfo, want, userId, callBack);
1074     }
1075     return false;
1076 }
1077 
CheckIsModuleNeedUpdateWrap(InnerBundleInfo & innerBundleInfo,const Want & want,int32_t userId,const sptr<IRemoteObject> & callBack)1078 bool BundleConnectAbilityMgr::CheckIsModuleNeedUpdateWrap(InnerBundleInfo &innerBundleInfo, const Want &want,
1079     int32_t userId, const sptr<IRemoteObject> &callBack)
1080 {
1081     bool isModuleNeedUpdate = CheckIsModuleNeedUpdate(innerBundleInfo, want, userId, callBack);
1082     if (!isModuleNeedUpdate) {
1083         CallAbilityManager(ServiceCenterResultCode::FREE_INSTALL_OK, want, userId, callBack);
1084     }
1085     return true;
1086 }
1087 
QueryAbilityInfo(const Want & want,int32_t flags,int32_t userId,AbilityInfo & abilityInfo,const sptr<IRemoteObject> & callBack)1088 bool BundleConnectAbilityMgr::QueryAbilityInfo(const Want &want, int32_t flags,
1089     int32_t userId, AbilityInfo &abilityInfo, const sptr<IRemoteObject> &callBack)
1090 {
1091     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1092     LOG_D(BMS_TAG_DEFAULT, "QueryAbilityInfo");
1093     InnerBundleInfo innerBundleInfo;
1094     if (IsObtainAbilityInfo(want, flags, userId, abilityInfo, callBack, innerBundleInfo)) {
1095         return true;
1096     }
1097     sptr<TargetAbilityInfo> targetAbilityInfo = new(std::nothrow) TargetAbilityInfo();
1098     if (targetAbilityInfo == nullptr) {
1099         LOG_E(BMS_TAG_DEFAULT, "targetAbilityInfo is nullptr");
1100         return false;
1101     }
1102     sptr<TargetInfo> targetInfo = new(std::nothrow) TargetInfo();
1103     if (targetInfo == nullptr) {
1104         LOG_E(BMS_TAG_DEFAULT, "targetInfo is nullptr");
1105         return false;
1106     }
1107     sptr<TargetExtSetting> targetExtSetting = new(std::nothrow) TargetExtSetting();
1108     if (targetExtSetting == nullptr) {
1109         LOG_E(BMS_TAG_DEFAULT, "targetExtSetting is nullptr");
1110         return false;
1111     }
1112     targetAbilityInfo->targetInfo = *targetInfo;
1113     targetAbilityInfo->targetExtSetting = *targetExtSetting;
1114     targetAbilityInfo->version = DEFAULT_VERSION;
1115     this->GetTargetAbilityInfo(want, userId, innerBundleInfo, targetAbilityInfo);
1116     sptr<FreeInstallParams> freeInstallParams = new(std::nothrow) FreeInstallParams();
1117     if (freeInstallParams == nullptr) {
1118         LOG_E(BMS_TAG_DEFAULT, "freeInstallParams is nullptr");
1119         return false;
1120     }
1121     freeInstallParams->callback = callBack;
1122     freeInstallParams->want = want;
1123     freeInstallParams->userId = userId;
1124     freeInstallParams->serviceCenterFunction = ServiceCenterFunction::CONNECT_SILENT_INSTALL;
1125 
1126     this->SilentInstall(*targetAbilityInfo, want, *freeInstallParams, userId);
1127     return false;
1128 }
1129 
SilentInstall(const Want & want,int32_t userId,const sptr<IRemoteObject> & callBack)1130 bool BundleConnectAbilityMgr::SilentInstall(const Want &want, int32_t userId, const sptr<IRemoteObject> &callBack)
1131 {
1132     LOG_D(BMS_TAG_DEFAULT, "SilentInstall");
1133     sptr<TargetAbilityInfo> targetAbilityInfo = new(std::nothrow) TargetAbilityInfo();
1134     if (targetAbilityInfo == nullptr) {
1135         LOG_E(BMS_TAG_DEFAULT, "targetAbilityInfo is nullptr");
1136         return false;
1137     }
1138     sptr<TargetInfo> targetInfo = new(std::nothrow) TargetInfo();
1139     if (targetInfo == nullptr) {
1140         LOG_E(BMS_TAG_DEFAULT, "targetInfo is nullptr");
1141         return false;
1142     }
1143     sptr<TargetExtSetting> targetExtSetting = new(std::nothrow) TargetExtSetting();
1144     if (targetExtSetting == nullptr) {
1145         LOG_E(BMS_TAG_DEFAULT, "targetExtSetting is nullptr");
1146         return false;
1147     }
1148 
1149     targetAbilityInfo->targetInfo = *targetInfo;
1150     targetAbilityInfo->targetExtSetting = *targetExtSetting;
1151     targetAbilityInfo->version = DEFAULT_VERSION;
1152     InnerBundleInfo innerBundleInfo;
1153     GetTargetAbilityInfo(want, userId, innerBundleInfo, targetAbilityInfo);
1154     auto callingUid = IPCSkeleton::GetCallingUid();
1155     std::vector<std::string> callingBundleNames;
1156     std::vector<std::string> callingAppids;
1157     GetCallingInfo(userId, callingUid, callingBundleNames, callingAppids);
1158     targetAbilityInfo->targetInfo.callingUid = callingUid;
1159     targetAbilityInfo->targetInfo.callingBundleNames = callingBundleNames;
1160     targetAbilityInfo->targetInfo.callingAppIds = callingAppids;
1161     sptr<FreeInstallParams> freeInstallParams = new(std::nothrow) FreeInstallParams();
1162     if (freeInstallParams == nullptr) {
1163         LOG_E(BMS_TAG_DEFAULT, "freeInstallParams is nullptr");
1164         return false;
1165     }
1166 
1167     freeInstallParams->callback = callBack;
1168     freeInstallParams->want = want;
1169     freeInstallParams->userId = userId;
1170     freeInstallParams->serviceCenterFunction = ServiceCenterFunction::CONNECT_SILENT_INSTALL;
1171     SilentInstall(*targetAbilityInfo, want, *freeInstallParams, userId);
1172     return true;
1173 }
1174 
UpgradeAtomicService(const Want & want,int32_t userId)1175 void BundleConnectAbilityMgr::UpgradeAtomicService(const Want &want, int32_t userId)
1176 {
1177     LOG_I(BMS_TAG_DEFAULT, "UpgradeAtomicService");
1178     std::shared_ptr<BundleMgrService> bms = DelayedSingleton<BundleMgrService>::GetInstance();
1179     std::shared_ptr<BundleDataMgr> bundleDataMgr_ = bms->GetDataMgr();
1180     if (bundleDataMgr_ == nullptr) {
1181         LOG_E(BMS_TAG_DEFAULT, "GetDataMgr failed, bundleDataMgr_ is nullptr");
1182         return;
1183     }
1184     std::string bundleName = want.GetElement().GetBundleName();
1185     InnerBundleInfo innerBundleInfo;
1186     bundleDataMgr_->GetInnerBundleInfoWithBundleFlagsAndLock(bundleName, want.GetFlags(), innerBundleInfo, userId);
1187     if (!innerBundleInfo.GetEntryInstallationFree()) {
1188         LOG_I(BMS_TAG_DEFAULT, "bundleName:%{public}s is atomic application", bundleName.c_str());
1189         return;
1190     }
1191     LOG_I(BMS_TAG_DEFAULT, "bundleName:%{public}s is atomic service", bundleName.c_str());
1192     sptr<TargetAbilityInfo> targetAbilityInfo = new(std::nothrow) TargetAbilityInfo();
1193     if (targetAbilityInfo == nullptr) {
1194         LOG_E(BMS_TAG_DEFAULT, "targetAbilityInfo is nullptr");
1195         return;
1196     }
1197     sptr<TargetInfo> targetInfo = new(std::nothrow) TargetInfo();
1198     if (targetInfo == nullptr) {
1199         LOG_E(BMS_TAG_DEFAULT, "targetInfo is nullptr");
1200         return;
1201     }
1202     sptr<TargetExtSetting> targetExtSetting = new(std::nothrow) TargetExtSetting();
1203     if (targetExtSetting == nullptr) {
1204         LOG_E(BMS_TAG_DEFAULT, "targetExtSetting is nullptr");
1205         return;
1206     }
1207     targetAbilityInfo->targetInfo = *targetInfo;
1208     targetAbilityInfo->targetExtSetting = *targetExtSetting;
1209     targetAbilityInfo->version = DEFAULT_VERSION;
1210     this->GetTargetAbilityInfo(want, userId, innerBundleInfo, targetAbilityInfo);
1211     if (!GetModuleName(innerBundleInfo, want, targetAbilityInfo->targetInfo.moduleName)) {
1212         LOG_W(BMS_TAG_DEFAULT, "GetModuleName failed");
1213     }
1214 
1215     sptr<FreeInstallParams> freeInstallParams = new(std::nothrow) FreeInstallParams();
1216     if (freeInstallParams == nullptr) {
1217         LOG_E(BMS_TAG_DEFAULT, "freeInstallParams is nullptr");
1218         return;
1219     }
1220     freeInstallParams->want = want;
1221     freeInstallParams->userId = userId;
1222     freeInstallParams->serviceCenterFunction = ServiceCenterFunction::CONNECT_UPGRADE_CHECK;
1223     this->UpgradeCheck(*targetAbilityInfo, want, *freeInstallParams, userId);
1224 }
1225 
CheckEcologicalRule(const Want & want,ErmsCallerInfo & callerInfo,BmsExperienceRule & rule)1226 bool BundleConnectAbilityMgr::CheckEcologicalRule(const Want &want, ErmsCallerInfo &callerInfo, BmsExperienceRule &rule)
1227 {
1228     sptr<BmsEcologicalRuleMgrServiceClient> instance_ =
1229         BmsEcologicalRuleMgrServiceClient::GetInstance();
1230     if (instance_ == nullptr) {
1231         LOG_E(BMS_TAG_DEFAULT, "Failed to get instance from erms");
1232         return false;
1233     }
1234     int ret = instance_->QueryFreeInstallExperience(want, callerInfo, rule);
1235     if (ret != ERR_OK) {
1236         LOG_E(BMS_TAG_DEFAULT, "Failed to query free install experience from erms");
1237         return false;
1238     }
1239     return true;
1240 }
1241 
GetEcologicalCallerInfo(const Want & want,ErmsCallerInfo & callerInfo,int32_t userId)1242 void BundleConnectAbilityMgr::GetEcologicalCallerInfo(const Want &want, ErmsCallerInfo &callerInfo, int32_t userId)
1243 {
1244     callerInfo.packageName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
1245     callerInfo.uid = want.GetIntParam(PARAM_FREEINSTALL_UID, IPCSkeleton::GetCallingUid());
1246     callerInfo.pid = want.GetIntParam(Want::PARAM_RESV_CALLER_PID, DEFAULT_VALUE);
1247     callerInfo.targetAppType = TYPE_HARMONEY_SERVICE;
1248     callerInfo.callerAppType = TYPE_HARMONEY_INVALID;
1249     callerInfo.targetAppDistType = want.GetStringParam(PARAM_FREEINSTALL_TARGET_APP_DIST_TYPE);
1250     callerInfo.embedded = want.GetIntParam(PARAM_FREEINSTALL_EMBEDDED, DEFAULT_EMBEDDED_VALUE);
1251     callerInfo.targetAppProvisionType = want.GetStringParam(PARAM_FREEINSTALL_TARGET_APP_PROVISION_TYPE);
1252     std::shared_ptr<BundleMgrService> bms = DelayedSingleton<BundleMgrService>::GetInstance();
1253     std::shared_ptr<BundleDataMgr> bundleDataMgr_ = bms->GetDataMgr();
1254     if (bundleDataMgr_ == nullptr) {
1255         LOG_E(BMS_TAG_DEFAULT, "GetDataMgr failed, bundleDataMgr_ is nullptr");
1256         return;
1257     }
1258     std::string callerBundleName;
1259     ErrCode err = bundleDataMgr_->GetNameForUid(callerInfo.uid, callerBundleName);
1260     if (err != ERR_OK) {
1261         LOG_E(BMS_TAG_DEFAULT, "Get callerBundleName failed");
1262         return;
1263     }
1264     AppExecFwk::ApplicationInfo callerAppInfo;
1265     bool getCallerResult = bundleDataMgr_->GetApplicationInfo(callerBundleName,
1266         AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, callerAppInfo);
1267     if (!getCallerResult) {
1268         LOG_E(BMS_TAG_DEFAULT, "Get callerAppInfo failed");
1269         return;
1270     }
1271     callerInfo.callerAppProvisionType = callerAppInfo.appProvisionType;
1272     InnerBundleInfo info;
1273     bool getInnerBundleInfoRes = bundleDataMgr_->GetInnerBundleInfoWithBundleFlagsAndLock(callerBundleName,
1274         AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, info, userId);
1275     if (!getInnerBundleInfoRes) {
1276         APP_LOGW("Get callerInnerBundleInfo failed");
1277         return;
1278     }
1279     callerInfo.callerModelType = BmsCallerInfo::MODEL_FA;
1280     if (info.GetIsNewVersion()) {
1281         callerInfo.callerModelType = BmsCallerInfo::MODEL_STAGE;
1282     }
1283     if (callerAppInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
1284         LOG_D(BMS_TAG_DEFAULT, "the caller type is atomic service");
1285         callerInfo.callerAppType = TYPE_HARMONEY_SERVICE;
1286     } else if (callerAppInfo.bundleType == AppExecFwk::BundleType::APP) {
1287         LOG_D(BMS_TAG_DEFAULT, "the caller type is app");
1288         callerInfo.callerAppType = TYPE_HARMONEY_APP;
1289     } else {
1290         LOG_D(BMS_TAG_DEFAULT, "the caller type is invalid type");
1291     }
1292 }
1293 
CheckIsOnDemandLoad(const TargetAbilityInfo & targetAbilityInfo) const1294 bool BundleConnectAbilityMgr::CheckIsOnDemandLoad(const TargetAbilityInfo &targetAbilityInfo) const
1295 {
1296     if (targetAbilityInfo.targetInfo.callingBundleNames.empty()) {
1297         LOG_D(BMS_TAG_DEFAULT, "callingBundleNames in targetAbilityInfo is empty");
1298         return false;
1299     }
1300     if (targetAbilityInfo.targetInfo.callingBundleNames[0] != targetAbilityInfo.targetInfo.bundleName) {
1301         LOG_D(BMS_TAG_DEFAULT, "callingBundleName is different with target bundleName");
1302         return false;
1303     }
1304     std::shared_ptr<BundleMgrService> bms = DelayedSingleton<BundleMgrService>::GetInstance();
1305     if (bms == nullptr) {
1306         LOG_E(BMS_TAG_DEFAULT, "BundleMgrService GetInstance failed");
1307         return false;
1308     }
1309     std::shared_ptr<BundleDataMgr> bundleDataMgr_ = bms->GetDataMgr();
1310     if (bundleDataMgr_ == nullptr) {
1311         LOG_E(BMS_TAG_DEFAULT, "GetDataMgr failed, bundleDataMgr_ is nullptr");
1312         return false;
1313     }
1314     BundleInfo bundleInfo;
1315     if (bundleDataMgr_->GetBundleInfo(
1316         targetAbilityInfo.targetInfo.bundleName, GET_BUNDLE_DEFAULT, bundleInfo, Constants::ANY_USERID)) {
1317         return bundleInfo.applicationInfo.bundleType == BundleType::ATOMIC_SERVICE;
1318     }
1319     return false;
1320 }
1321 
GetModuleName(const InnerBundleInfo & innerBundleInfo,const Want & want,std::string & moduleName) const1322 bool BundleConnectAbilityMgr::GetModuleName(const InnerBundleInfo &innerBundleInfo,
1323     const Want &want, std::string &moduleName) const
1324 {
1325     if (!moduleName.empty()) {
1326         return true;
1327     }
1328     auto baseAbilitiesInfo = innerBundleInfo.GetInnerAbilityInfos();
1329     ElementName element = want.GetElement();
1330     std::string abilityName = element.GetAbilityName();
1331     for (const auto& info : baseAbilitiesInfo) {
1332         if (info.second.name == abilityName) {
1333             moduleName = info.second.moduleName;
1334             return true;
1335         }
1336     }
1337     std::string wantModuleName = element.GetModuleName();
1338     if (abilityName.empty() && wantModuleName.empty()) {
1339         moduleName = innerBundleInfo.GetEntryModuleName();
1340         LOG_I(BMS_TAG_DEFAULT, "get entry module name %{public}s", moduleName.c_str());
1341         return !moduleName.empty();
1342     }
1343     LOG_E(BMS_TAG_DEFAULT, "GetModuleName failed, ability(%{public}s) is not existed in bundle(%{public}s)",
1344         abilityName.c_str(), innerBundleInfo.GetBundleName().c_str());
1345     return false;
1346 }
1347 }  // namespace AppExecFwk
1348 }  // namespace OHOS
1349