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