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