1 /*
2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "free_install_manager.h"
17
18 #include "ability_manager_service.h"
19 #include "ability_util.h"
20 #include "atomic_service_status_callback.h"
21 #include "distributed_client.h"
22 #include "hitrace_meter.h"
23 #include "insight_intent_execute_manager.h"
24 #include "insight_intent_utils.h"
25 #include "permission_constants.h"
26 #include "utils/app_mgr_util.h"
27 #include "uri_utils.h"
28
29 namespace OHOS {
30 namespace AAFwk {
31 const std::u16string DMS_FREE_INSTALL_CALLBACK_TOKEN = u"ohos.DistributedSchedule.IDmsFreeInstallCallback";
32 const std::string DMS_MISSION_ID = "dmsMissionId";
33 const std::string PARAM_FREEINSTALL_APPID = "ohos.freeinstall.params.callingAppId";
34 const std::string PARAM_FREEINSTALL_BUNDLENAMES = "ohos.freeinstall.params.callingBundleNames";
35 const std::string PARAM_FREEINSTALL_UID = "ohos.freeinstall.params.callingUid";
36 constexpr uint32_t IDMS_CALLBACK_ON_FREE_INSTALL_DONE = 0;
37 constexpr uint32_t UPDATE_ATOMOIC_SERVICE_TASK_TIMER = 24 * 60 * 60 * 1000; /* 24h */
38 constexpr const char* KEY_IS_APP_RUNNING = "com.ohos.param.isAppRunning";
39
FreeInstallManager(const std::weak_ptr<AbilityManagerService> & server)40 FreeInstallManager::FreeInstallManager(const std::weak_ptr<AbilityManagerService> &server)
41 : server_(server)
42 {
43 }
44
IsTopAbility(const sptr<IRemoteObject> & callerToken)45 bool FreeInstallManager::IsTopAbility(const sptr<IRemoteObject> &callerToken)
46 {
47 auto server = server_.lock();
48 CHECK_POINTER_AND_RETURN_LOG(server, false, "Get server failed!");
49 AppExecFwk::ElementName elementName = IN_PROCESS_CALL(server->GetTopAbility());
50 if (elementName.GetBundleName().empty() || elementName.GetAbilityName().empty()) {
51 TAG_LOGE(AAFwkTag::FREE_INSTALL, "GetBundleName or GetAbilityName empty");
52 return false;
53 }
54
55 auto caller = Token::GetAbilityRecordByToken(callerToken);
56 if (caller == nullptr) {
57 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Caller is null");
58 return false;
59 }
60
61 auto type = caller->GetAbilityInfo().type;
62 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
63 return true;
64 }
65
66 AppExecFwk::ElementName callerElementName = caller->GetElementName();
67 std::string callerBundleName = callerElementName.GetBundleName();
68 std::string callerAbilityName = callerElementName.GetAbilityName();
69 std::string callerModuleName = callerElementName.GetModuleName();
70 if (elementName.GetBundleName().compare(callerBundleName) == 0 &&
71 elementName.GetAbilityName().compare(callerAbilityName) == 0 &&
72 elementName.GetModuleName().compare(callerModuleName) == 0) {
73 TAG_LOGI(AAFwkTag::FREE_INSTALL, "ability is top ability");
74 return true;
75 }
76
77 return false;
78 }
79
StartFreeInstall(const Want & want,int32_t userId,int requestCode,const sptr<IRemoteObject> & callerToken,bool isAsync,uint32_t specifyTokenId,bool isOpenAtomicServiceShortUrl,std::shared_ptr<Want> originalWant)80 int FreeInstallManager::StartFreeInstall(const Want &want, int32_t userId, int requestCode,
81 const sptr<IRemoteObject> &callerToken, bool isAsync, uint32_t specifyTokenId, bool isOpenAtomicServiceShortUrl,
82 std::shared_ptr<Want> originalWant)
83 {
84 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
85 if (!VerifyStartFreeInstallPermission(callerToken)) {
86 return NOT_TOP_ABILITY;
87 }
88 FreeInstallInfo info = BuildFreeInstallInfo(want, userId, requestCode, callerToken,
89 isAsync, specifyTokenId, isOpenAtomicServiceShortUrl, originalWant);
90 {
91 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
92 freeInstallList_.push_back(info);
93 }
94 int32_t recordId = GetRecordIdByToken(callerToken);
95 sptr<AtomicServiceStatusCallback> callback = new AtomicServiceStatusCallback(weak_from_this(), isAsync, recordId);
96 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
97 CHECK_POINTER_AND_RETURN(bundleMgrHelper, GET_ABILITY_SERVICE_FAILED);
98 AppExecFwk::AbilityInfo abilityInfo = {};
99 constexpr auto flag = AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION;
100 info.want.SetParam(PARAM_FREEINSTALL_UID, IPCSkeleton::GetCallingUid());
101
102 int result = SetAppRunningState(info.want);
103 if (result != ERR_OK) {
104 TAG_LOGE(AAFwkTag::FREE_INSTALL, "SetAppRunningState failed");
105 return result;
106 }
107
108 if (IN_PROCESS_CALL(bundleMgrHelper->QueryAbilityInfo(info.want, flag, info.userId, abilityInfo, callback))) {
109 TAG_LOGI(AAFwkTag::FREE_INSTALL, "The app has installed");
110 }
111 std::string callingAppId = info.want.GetStringParam(PARAM_FREEINSTALL_APPID);
112 std::vector<std::string> callingBundleNames = info.want.GetStringArrayParam(PARAM_FREEINSTALL_BUNDLENAMES);
113 if (callingAppId.empty() && callingBundleNames.empty()) {
114 TAG_LOGI(AAFwkTag::FREE_INSTALL, "callingAppId and callingBundleNames are empty");
115 }
116 info.want.RemoveParam(PARAM_FREEINSTALL_APPID);
117 info.want.RemoveParam(PARAM_FREEINSTALL_BUNDLENAMES);
118
119 if (isAsync) {
120 return ERR_OK;
121 } else {
122 auto future = info.promise->get_future();
123 std::future_status status = future.wait_for(std::chrono::milliseconds(DELAY_LOCAL_FREE_INSTALL_TIMEOUT));
124 if (status == std::future_status::timeout) {
125 RemoveFreeInstallInfo(info.want.GetElement().GetBundleName(), info.want.GetElement().GetAbilityName(),
126 info.want.GetStringParam(Want::PARAM_RESV_START_TIME));
127 return FREE_INSTALL_TIMEOUT;
128 }
129 return future.get();
130 }
131 }
132
RemoteFreeInstall(const Want & want,int32_t userId,int requestCode,const sptr<IRemoteObject> & callerToken)133 int FreeInstallManager::RemoteFreeInstall(const Want &want, int32_t userId, int requestCode,
134 const sptr<IRemoteObject> &callerToken)
135 {
136 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
137 bool isFromRemote = want.GetBoolParam(FROM_REMOTE_KEY, false);
138 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
139 if (!isSaCall && !isFromRemote && !IsTopAbility(callerToken)) {
140 return NOT_TOP_ABILITY;
141 }
142 FreeInstallInfo info = BuildFreeInstallInfo(want, userId, requestCode, callerToken, false);
143 {
144 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
145 freeInstallList_.push_back(info);
146 }
147 int32_t recordId = GetRecordIdByToken(callerToken);
148 sptr<AtomicServiceStatusCallback> callback = new AtomicServiceStatusCallback(weak_from_this(), false, recordId);
149 int32_t callerUid = IPCSkeleton::GetCallingUid();
150 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
151 UriUtils::GetInstance().FilterUriWithPermissionDms(info.want, accessToken);
152 DistributedClient dmsClient;
153 auto result = dmsClient.StartRemoteFreeInstall(info.want, callerUid, info.requestCode, accessToken, callback);
154 if (result != ERR_NONE) {
155 return result;
156 }
157 auto remoteFuture = info.promise->get_future();
158 std::future_status remoteStatus = remoteFuture.wait_for(std::chrono::milliseconds(
159 DELAY_REMOTE_FREE_INSTALL_TIMEOUT));
160 if (remoteStatus == std::future_status::timeout) {
161 return FREE_INSTALL_TIMEOUT;
162 }
163 return remoteFuture.get();
164 }
165
BuildFreeInstallInfo(const Want & want,int32_t userId,int requestCode,const sptr<IRemoteObject> & callerToken,bool isAsync,uint32_t specifyTokenId,bool isOpenAtomicServiceShortUrl,std::shared_ptr<Want> originalWant)166 FreeInstallInfo FreeInstallManager::BuildFreeInstallInfo(const Want &want, int32_t userId, int requestCode,
167 const sptr<IRemoteObject> &callerToken, bool isAsync, uint32_t specifyTokenId, bool isOpenAtomicServiceShortUrl,
168 std::shared_ptr<Want> originalWant)
169 {
170 FreeInstallInfo info = {
171 .want = want,
172 .userId = userId,
173 .requestCode = requestCode,
174 .callerToken = callerToken,
175 .specifyTokenId = specifyTokenId,
176 .isOpenAtomicServiceShortUrl = isOpenAtomicServiceShortUrl,
177 .originalWant = originalWant
178 };
179 if (!isAsync) {
180 auto promise = std::make_shared<std::promise<int32_t>>();
181 info.promise = promise;
182 }
183 auto identity = IPCSkeleton::ResetCallingIdentity();
184 info.identity = identity;
185 IPCSkeleton::SetCallingIdentity(identity);
186 return info;
187 }
188
StartRemoteFreeInstall(const Want & want,int requestCode,int32_t validUserId,const sptr<IRemoteObject> & callerToken)189 int FreeInstallManager::StartRemoteFreeInstall(const Want &want, int requestCode, int32_t validUserId,
190 const sptr<IRemoteObject> &callerToken)
191 {
192 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
193 if (!want.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
194 TAG_LOGI(AAFwkTag::FREE_INSTALL, "StartAbility freeInstall");
195 return RemoteFreeInstall(want, validUserId, requestCode, callerToken);
196 }
197 int32_t missionId = DelayedSingleton<AbilityManagerService>::GetInstance()->
198 GetMissionIdByAbilityToken(callerToken);
199 if (missionId < 0) {
200 return ERR_INVALID_VALUE;
201 }
202 Want* newWant = const_cast<Want*>(&want);
203 newWant->SetParam(DMS_MISSION_ID, missionId);
204 return RemoteFreeInstall(*newWant, validUserId, requestCode, callerToken);
205 }
206
NotifyDmsCallback(const Want & want,int resultCode)207 int FreeInstallManager::NotifyDmsCallback(const Want &want, int resultCode)
208 {
209 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
210 std::lock_guard<ffrt::mutex> autoLock(distributedFreeInstallLock_);
211 if (dmsFreeInstallCbs_.empty()) {
212 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Has no dms callback");
213 return ERR_INVALID_VALUE;
214 }
215
216 MessageParcel reply;
217 MessageOption option;
218
219 for (auto it = dmsFreeInstallCbs_.begin(); it != dmsFreeInstallCbs_.end();) {
220 std::string abilityName = (*it).want.GetElement().GetAbilityName();
221 if (want.GetElement().GetAbilityName().compare(abilityName) == 0) {
222 TAG_LOGI(AAFwkTag::FREE_INSTALL, "Handle DMS");
223 MessageParcel data;
224 if (!data.WriteInterfaceToken(DMS_FREE_INSTALL_CALLBACK_TOKEN)) {
225 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Write interface token failed");
226 return ERR_INVALID_VALUE;
227 }
228
229 if (!data.WriteInt32(resultCode)) {
230 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Write resultCode error");
231 return ERR_INVALID_VALUE;
232 }
233
234 if (!data.WriteParcelable(&((*it).want))) {
235 TAG_LOGE(AAFwkTag::FREE_INSTALL, "want write failed");
236 return INNER_ERR;
237 }
238
239 if (!data.WriteInt32((*it).requestCode)) {
240 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Write resultCode error");
241 return ERR_INVALID_VALUE;
242 }
243
244 (*it).dmsCallback->SendRequest(IDMS_CALLBACK_ON_FREE_INSTALL_DONE, data, reply, option);
245 it = dmsFreeInstallCbs_.erase(it);
246 } else {
247 it++;
248 }
249 }
250
251 return reply.ReadInt32();
252 }
253
NotifyFreeInstallResult(int32_t recordId,const Want & want,int resultCode,bool isAsync)254 void FreeInstallManager::NotifyFreeInstallResult(int32_t recordId, const Want &want, int resultCode, bool isAsync)
255 {
256 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
257 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
258 if (freeInstallList_.empty()) {
259 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Has no app callback");
260 return;
261 }
262
263 bool isFromRemote = want.GetBoolParam(FROM_REMOTE_KEY, false);
264 for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) {
265 FreeInstallInfo &freeInstallInfo = *it;
266 std::string bundleName = freeInstallInfo.want.GetElement().GetBundleName();
267 std::string abilityName = freeInstallInfo.want.GetElement().GetAbilityName();
268 std::string startTime = freeInstallInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME);
269 std::string url = freeInstallInfo.want.GetUriString();
270 if (want.GetElement().GetBundleName().compare(bundleName) != 0 ||
271 want.GetElement().GetAbilityName().compare(abilityName) != 0 ||
272 want.GetStringParam(Want::PARAM_RESV_START_TIME).compare(startTime) != 0 ||
273 want.GetUriString().compare(url) != 0) {
274 it++;
275 continue;
276 }
277
278 if (!isAsync && freeInstallInfo.promise == nullptr) {
279 it++;
280 continue;
281 }
282 freeInstallInfo.isFreeInstallFinished = true;
283 freeInstallInfo.resultCode = resultCode;
284 HandleFreeInstallResult(recordId, freeInstallInfo, resultCode, isAsync);
285 it = freeInstallList_.erase(it);
286 }
287 }
288
HandleOnFreeInstallSuccess(int32_t recordId,FreeInstallInfo & freeInstallInfo,bool isAsync)289 void FreeInstallManager::HandleOnFreeInstallSuccess(int32_t recordId, FreeInstallInfo &freeInstallInfo, bool isAsync)
290 {
291 freeInstallInfo.isInstalled = true;
292
293 if (isAsync) {
294 std::string startTime = freeInstallInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME);
295 std::string bundleName = freeInstallInfo.want.GetElement().GetBundleName();
296 std::string abilityName = freeInstallInfo.want.GetElement().GetAbilityName();
297 if (freeInstallInfo.isPreStartMissionCalled) {
298 StartAbilityByPreInstall(recordId, freeInstallInfo, bundleName, abilityName, startTime);
299 return;
300 }
301 if (freeInstallInfo.isOpenAtomicServiceShortUrl) {
302 StartAbilityByConvertedWant(freeInstallInfo, startTime);
303 return;
304 }
305 StartAbilityByFreeInstall(freeInstallInfo, bundleName, abilityName, startTime);
306 return;
307 }
308 freeInstallInfo.promise->set_value(ERR_OK);
309 }
310
HandleOnFreeInstallFail(int32_t recordId,FreeInstallInfo & freeInstallInfo,int resultCode,bool isAsync)311 void FreeInstallManager::HandleOnFreeInstallFail(int32_t recordId, FreeInstallInfo &freeInstallInfo, int resultCode,
312 bool isAsync)
313 {
314 freeInstallInfo.isInstalled = false;
315
316 if (isAsync) {
317 if (freeInstallInfo.isPreStartMissionCalled &&
318 freeInstallInfo.want.HasParameter(KEY_SESSION_ID) &&
319 !freeInstallInfo.want.GetStringParam(KEY_SESSION_ID).empty() &&
320 freeInstallInfo.isStartUIAbilityBySCBCalled) {
321 DelayedSingleton<AbilityManagerService>::GetInstance()->NotifySCBToHandleAtomicServiceException(
322 freeInstallInfo.want.GetStringParam(KEY_SESSION_ID),
323 resultCode, "free install failed");
324 }
325 std::string startTime = freeInstallInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME);
326 if (freeInstallInfo.isOpenAtomicServiceShortUrl
327 && resultCode != CONCURRENT_TASKS_WAITING_FOR_RETRY) {
328 StartAbilityByOriginalWant(freeInstallInfo, startTime);
329 return;
330 }
331
332 std::string bundleName = freeInstallInfo.want.GetElement().GetBundleName();
333 std::string abilityName = freeInstallInfo.want.GetElement().GetAbilityName();
334 DelayedSingleton<FreeInstallObserverManager>::GetInstance()->OnInstallFinished(
335 recordId, bundleName, abilityName, startTime, resultCode);
336 return;
337 }
338 freeInstallInfo.promise->set_value(resultCode);
339 }
340
HandleFreeInstallResult(int32_t recordId,FreeInstallInfo & freeInstallInfo,int resultCode,bool isAsync)341 void FreeInstallManager::HandleFreeInstallResult(int32_t recordId, FreeInstallInfo &freeInstallInfo, int resultCode,
342 bool isAsync)
343 {
344 if (resultCode == ERR_OK) {
345 HandleOnFreeInstallSuccess(recordId, freeInstallInfo, isAsync);
346 return;
347 }
348 HandleOnFreeInstallFail(recordId, freeInstallInfo, resultCode, isAsync);
349 }
350
StartAbilityByFreeInstall(FreeInstallInfo & info,std::string & bundleName,std::string & abilityName,std::string & startTime)351 void FreeInstallManager::StartAbilityByFreeInstall(FreeInstallInfo &info, std::string &bundleName,
352 std::string &abilityName, std::string &startTime)
353 {
354 info.want.SetFlags(info.want.GetFlags() ^ Want::FLAG_INSTALL_ON_DEMAND);
355 auto identity = IPCSkeleton::ResetCallingIdentity();
356 IPCSkeleton::SetCallingIdentity(info.identity);
357 int32_t result = ERR_OK;
358 if (info.want.GetElement().GetAbilityName().empty()) {
359 result = UpdateElementName(info.want, info.userId);
360 }
361 if (result == ERR_OK) {
362 result = DelayedSingleton<AbilityManagerService>::GetInstance()->StartAbilityByFreeInstall(info.want,
363 info.callerToken, info.userId, info.requestCode);
364 }
365 IPCSkeleton::SetCallingIdentity(identity);
366 int32_t recordId = GetRecordIdByToken(info.callerToken);
367 TAG_LOGI(AAFwkTag::FREE_INSTALL, "The result is %{public}d", result);
368 DelayedSingleton<FreeInstallObserverManager>::GetInstance()->OnInstallFinished(
369 recordId, bundleName, abilityName, startTime, result);
370 }
371
StartAbilityByPreInstall(int32_t recordId,FreeInstallInfo & info,std::string & bundleName,std::string & abilityName,std::string & startTime)372 void FreeInstallManager::StartAbilityByPreInstall(int32_t recordId, FreeInstallInfo &info, std::string &bundleName,
373 std::string &abilityName, std::string &startTime)
374 {
375 info.want.SetFlags(info.want.GetFlags() ^ Want::FLAG_INSTALL_ON_DEMAND);
376 auto identity = IPCSkeleton::ResetCallingIdentity();
377 IPCSkeleton::SetCallingIdentity(info.identity);
378 int32_t result = ERR_OK;
379 if (info.want.GetElement().GetAbilityName().empty()) {
380 result = UpdateElementName(info.want, info.userId);
381 }
382 if (result == ERR_OK) {
383 result = DelayedSingleton<AbilityManagerService>::GetInstance()->StartUIAbilityByPreInstall(info);
384 }
385 if (result != ERR_OK && info.isStartUIAbilityBySCBCalled) {
386 DelayedSingleton<AbilityManagerService>::GetInstance()->NotifySCBToHandleAtomicServiceException(
387 info.want.GetStringParam(KEY_SESSION_ID),
388 result, "start ability failed");
389 }
390 IPCSkeleton::SetCallingIdentity(identity);
391 DelayedSingleton<FreeInstallObserverManager>::GetInstance()->OnInstallFinished(
392 recordId, bundleName, abilityName, startTime, result);
393 }
394
StartAbilityByConvertedWant(FreeInstallInfo & info,const std::string & startTime)395 void FreeInstallManager::StartAbilityByConvertedWant(FreeInstallInfo &info, const std::string &startTime)
396 {
397 info.want.SetFlags(info.want.GetFlags() ^ Want::FLAG_INSTALL_ON_DEMAND);
398 auto identity = IPCSkeleton::ResetCallingIdentity();
399 IPCSkeleton::SetCallingIdentity(info.identity);
400 int32_t result = ERR_OK;
401 if (info.want.GetElement().GetAbilityName().empty()) {
402 result = UpdateElementName(info.want, info.userId);
403 }
404 if (result == ERR_OK) {
405 result = DelayedSingleton<AbilityManagerService>::GetInstance()->StartAbility(info.want,
406 info.callerToken, info.userId, info.requestCode);
407 }
408 IPCSkeleton::SetCallingIdentity(identity);
409 auto url = info.want.GetUriString();
410 int32_t recordId = GetRecordIdByToken(info.callerToken);
411 DelayedSingleton<FreeInstallObserverManager>::GetInstance()->OnInstallFinishedByUrl(recordId,
412 startTime, url, result);
413 }
414
StartAbilityByOriginalWant(FreeInstallInfo & info,const std::string & startTime)415 void FreeInstallManager::StartAbilityByOriginalWant(FreeInstallInfo &info, const std::string &startTime)
416 {
417 auto identity = IPCSkeleton::ResetCallingIdentity();
418 IPCSkeleton::SetCallingIdentity(info.identity);
419 int result = ERR_INVALID_VALUE;
420 if (info.originalWant) {
421 result = DelayedSingleton<AbilityManagerService>::GetInstance()->StartAbility(*(info.originalWant),
422 info.callerToken, info.userId, info.requestCode);
423 } else {
424 TAG_LOGE(AAFwkTag::FREE_INSTALL, "The original want is nullptr");
425 }
426 IPCSkeleton::SetCallingIdentity(identity);
427 auto url = info.want.GetUriString();
428 int32_t recordId = GetRecordIdByToken(info.callerToken);
429 DelayedSingleton<FreeInstallObserverManager>::GetInstance()->OnInstallFinishedByUrl(recordId,
430 startTime, url, result);
431 }
432
UpdateElementName(Want & want,int32_t userId) const433 int32_t FreeInstallManager::UpdateElementName(Want &want, int32_t userId) const
434 {
435 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
436 CHECK_POINTER_AND_RETURN(bundleMgrHelper, ERR_INVALID_VALUE);
437 Want launchWant;
438 auto errCode = IN_PROCESS_CALL(bundleMgrHelper->GetLaunchWantForBundle(want.GetBundle(), launchWant, userId));
439 if (errCode != ERR_OK) {
440 return errCode;
441 }
442 want.SetElement(launchWant.GetElement());
443 return ERR_OK;
444 }
445
FreeInstallAbilityFromRemote(const Want & want,const sptr<IRemoteObject> & callback,int32_t userId,int requestCode)446 int FreeInstallManager::FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback,
447 int32_t userId, int requestCode)
448 {
449 if (callback == nullptr) {
450 TAG_LOGE(AAFwkTag::FREE_INSTALL, "callback is nullptr");
451 return ERR_INVALID_VALUE;
452 }
453
454 FreeInstallInfo info = {
455 .want = want,
456 .userId = userId,
457 .requestCode = requestCode,
458 .dmsCallback = callback
459 };
460
461 {
462 std::lock_guard<ffrt::mutex> autoLock(distributedFreeInstallLock_);
463 dmsFreeInstallCbs_.push_back(info);
464 }
465
466 auto result = StartFreeInstall(info.want, info.userId, info.requestCode, nullptr);
467 if (result != ERR_OK) {
468 NotifyDmsCallback(info.want, result);
469 }
470 return result;
471 }
472
ConnectFreeInstall(const Want & want,int32_t userId,const sptr<IRemoteObject> & callerToken,const std::string & localDeviceId)473 int FreeInstallManager::ConnectFreeInstall(const Want &want, int32_t userId,
474 const sptr<IRemoteObject> &callerToken, const std::string& localDeviceId)
475 {
476 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
477 CHECK_POINTER_AND_RETURN(bundleMgrHelper, GET_ABILITY_SERVICE_FAILED);
478 std::string wantDeviceId = want.GetElement().GetDeviceID();
479 if (!(localDeviceId == wantDeviceId || wantDeviceId.empty())) {
480 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Failed to get device id");
481 return INVALID_PARAMETERS_ERR;
482 }
483
484 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
485 if (!isSaCall) {
486 std::string wantAbilityName = want.GetElement().GetAbilityName();
487 std::string wantBundleName = want.GetElement().GetBundleName();
488 if (wantBundleName.empty() || wantAbilityName.empty()) {
489 TAG_LOGE(AAFwkTag::FREE_INSTALL, "The wantBundleName or wantAbilityName is empty.");
490 return INVALID_PARAMETERS_ERR;
491 }
492 int callerUid = IPCSkeleton::GetCallingUid();
493 std::string localBundleName;
494 auto res = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callerUid, localBundleName));
495 if (res != ERR_OK || localBundleName != wantBundleName) {
496 TAG_LOGE(AAFwkTag::FREE_INSTALL, "The wantBundleName is not local BundleName");
497 return INVALID_PARAMETERS_ERR;
498 }
499 }
500
501 AppExecFwk::AbilityInfo abilityInfo;
502 std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
503 if (!IN_PROCESS_CALL(bundleMgrHelper->QueryAbilityInfo(
504 want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, userId, abilityInfo)) &&
505 !IN_PROCESS_CALL(bundleMgrHelper->QueryExtensionAbilityInfos(
506 want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, userId, extensionInfos))) {
507 int result = StartFreeInstall(want, userId, DEFAULT_INVAL_VALUE, callerToken);
508 if (result) {
509 TAG_LOGE(AAFwkTag::FREE_INSTALL, "StartFreeInstall error");
510 return result;
511 }
512 }
513 return ERR_OK;
514 }
515
GetTimeStamp()516 std::time_t FreeInstallManager::GetTimeStamp()
517 {
518 std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp =
519 std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
520 std::time_t timestamp = tp.time_since_epoch().count();
521 return timestamp;
522 }
523
OnInstallFinished(int32_t recordId,int resultCode,const Want & want,int32_t userId,bool isAsync)524 void FreeInstallManager::OnInstallFinished(int32_t recordId, int resultCode, const Want &want,
525 int32_t userId, bool isAsync)
526 {
527 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
528
529 if (!InsightIntentExecuteParam::IsInsightIntentExecute(want)) {
530 NotifyDmsCallback(want, resultCode);
531 NotifyFreeInstallResult(recordId, want, resultCode, isAsync);
532 } else {
533 NotifyInsightIntentFreeInstallResult(want, resultCode);
534 }
535
536 PostUpgradeAtomicServiceTask(resultCode, want, userId);
537 }
538
PostUpgradeAtomicServiceTask(int resultCode,const Want & want,int32_t userId)539 void FreeInstallManager::PostUpgradeAtomicServiceTask(int resultCode, const Want &want, int32_t userId)
540 {
541 std::weak_ptr<FreeInstallManager> thisWptr(shared_from_this());
542 if (resultCode == ERR_OK) {
543 auto updateAtmoicServiceTask = [want, userId, thisWptr, &timeStampMap = timeStampMap_]() {
544 auto sptr = thisWptr.lock();
545 TAG_LOGD(AAFwkTag::FREE_INSTALL,
546 "bundleName: %{public}s, moduleName: %{public}s", want.GetElement().GetBundleName().c_str(),
547 want.GetElement().GetModuleName().c_str());
548 std::string nameKey = want.GetElement().GetBundleName() + want.GetElement().GetModuleName();
549 if (timeStampMap.find(nameKey) == timeStampMap.end() ||
550 sptr->GetTimeStamp() - timeStampMap[nameKey] > UPDATE_ATOMOIC_SERVICE_TASK_TIMER) {
551 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
552 CHECK_POINTER(bundleMgrHelper);
553 bundleMgrHelper->UpgradeAtomicService(want, userId);
554 timeStampMap.emplace(nameKey, sptr->GetTimeStamp());
555 }
556 };
557
558 auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
559 CHECK_POINTER_LOG(handler, "Fail to get Ability task handler.");
560 handler->SubmitTask(updateAtmoicServiceTask, "UpdateAtmoicServiceTask");
561 }
562 }
563
OnRemoteInstallFinished(int32_t recordId,int resultCode,const Want & want,int32_t userId)564 void FreeInstallManager::OnRemoteInstallFinished(int32_t recordId, int resultCode, const Want &want, int32_t userId)
565 {
566 NotifyFreeInstallResult(recordId, want, resultCode);
567 }
568
AddFreeInstallObserver(const sptr<IRemoteObject> & callerToken,const sptr<AbilityRuntime::IFreeInstallObserver> & observer)569 int FreeInstallManager::AddFreeInstallObserver(const sptr<IRemoteObject> &callerToken,
570 const sptr<AbilityRuntime::IFreeInstallObserver> &observer)
571 {
572 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
573 if (abilityRecord != nullptr) {
574 return DelayedSingleton<FreeInstallObserverManager>::GetInstance()->AddObserver(abilityRecord->GetRecordId(),
575 observer);
576 }
577 if (AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
578 return DelayedSingleton<FreeInstallObserverManager>::GetInstance()->AddObserver(-1, observer);
579 }
580 return CHECK_PERMISSION_FAILED;
581 }
582
RemoveFreeInstallInfo(const std::string & bundleName,const std::string & abilityName,const std::string & startTime)583 void FreeInstallManager::RemoveFreeInstallInfo(const std::string &bundleName, const std::string &abilityName,
584 const std::string &startTime)
585 {
586 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
587 for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) {
588 if ((*it).want.GetElement().GetBundleName() == bundleName &&
589 (*it).want.GetElement().GetAbilityName() == abilityName &&
590 (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) {
591 it = freeInstallList_.erase(it);
592 } else {
593 it++;
594 }
595 }
596 }
597
VerifyStartFreeInstallPermission(const sptr<IRemoteObject> & callerToken)598 bool FreeInstallManager::VerifyStartFreeInstallPermission(const sptr<IRemoteObject> &callerToken)
599 {
600 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
601 if (isSaCall || IsTopAbility(callerToken)) {
602 return true;
603 }
604
605 if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
606 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
607 return true;
608 }
609
610 return false;
611 }
612
GetRecordIdByToken(const sptr<IRemoteObject> & callerToken)613 int32_t FreeInstallManager::GetRecordIdByToken(const sptr<IRemoteObject> &callerToken)
614 {
615 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
616 int recordId = -1;
617 if (abilityRecord != nullptr) {
618 recordId = abilityRecord->GetRecordId();
619 }
620 return recordId;
621 }
622
SetAppRunningState(Want & want)623 int FreeInstallManager::SetAppRunningState(Want &want)
624 {
625 auto appMgr = AppMgrUtil::GetAppMgr();
626 if (appMgr == nullptr) {
627 TAG_LOGE(AAFwkTag::FREE_INSTALL, "appMgr is nullptr.");
628 return ERR_INVALID_VALUE;
629 }
630
631 bool isAppRunning = appMgr->GetAppRunningStateByBundleName(want.GetElement().GetBundleName());
632 TAG_LOGI(AAFwkTag::FREE_INSTALL, "isAppRunning=%{public}d.", static_cast<int>(isAppRunning));
633 want.SetParam(KEY_IS_APP_RUNNING, isAppRunning);
634 return ERR_OK;
635 }
636
GetFreeInstallTaskInfo(const std::string & bundleName,const std::string & abilityName,const std::string & startTime,FreeInstallInfo & taskInfo)637 bool FreeInstallManager::GetFreeInstallTaskInfo(const std::string& bundleName, const std::string& abilityName,
638 const std::string& startTime, FreeInstallInfo& taskInfo)
639 {
640 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
641 for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) {
642 if ((*it).want.GetElement().GetBundleName() == bundleName &&
643 (*it).want.GetElement().GetAbilityName() == abilityName &&
644 (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) {
645 taskInfo = *it;
646 return true;
647 }
648 it++;
649 }
650 return false;
651 }
652
GetFreeInstallTaskInfo(const std::string & sessionId,FreeInstallInfo & taskInfo)653 bool FreeInstallManager::GetFreeInstallTaskInfo(const std::string& sessionId, FreeInstallInfo& taskInfo)
654 {
655 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
656 for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) {
657 if ((*it).want.GetStringParam(KEY_SESSION_ID) == sessionId) {
658 taskInfo = *it;
659 return true;
660 }
661 it++;
662 }
663 return false;
664 }
665
SetSCBCallStatus(const std::string & bundleName,const std::string & abilityName,const std::string & startTime,bool scbCallStatus)666 void FreeInstallManager::SetSCBCallStatus(const std::string& bundleName, const std::string& abilityName,
667 const std::string& startTime, bool scbCallStatus)
668 {
669 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
670 for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) {
671 if ((*it).want.GetElement().GetBundleName() == bundleName &&
672 (*it).want.GetElement().GetAbilityName() == abilityName &&
673 (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) {
674 (*it).isStartUIAbilityBySCBCalled = scbCallStatus;
675 return;
676 }
677 it++;
678 }
679 }
680
SetPreStartMissionCallStatus(const std::string & bundleName,const std::string & abilityName,const std::string & startTime,bool preStartMissionCallStatus)681 void FreeInstallManager::SetPreStartMissionCallStatus(const std::string& bundleName, const std::string& abilityName,
682 const std::string& startTime, bool preStartMissionCallStatus)
683 {
684 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
685 for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) {
686 if ((*it).want.GetElement().GetBundleName() == bundleName &&
687 (*it).want.GetElement().GetAbilityName() == abilityName &&
688 (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) {
689 (*it).isPreStartMissionCalled = preStartMissionCallStatus;
690 return;
691 }
692 it++;
693 }
694 }
695
SetFreeInstallTaskSessionId(const std::string & bundleName,const std::string & abilityName,const std::string & startTime,const std::string & sessionId)696 void FreeInstallManager::SetFreeInstallTaskSessionId(const std::string& bundleName, const std::string& abilityName,
697 const std::string& startTime, const std::string& sessionId)
698 {
699 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
700 for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) {
701 if ((*it).want.GetElement().GetBundleName() == bundleName &&
702 (*it).want.GetElement().GetAbilityName() == abilityName &&
703 (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) {
704 (*it).want.SetParam(KEY_SESSION_ID, sessionId);
705 return;
706 }
707 it++;
708 }
709 }
710
NotifyInsightIntentFreeInstallResult(const Want & want,int resultCode)711 void FreeInstallManager::NotifyInsightIntentFreeInstallResult(const Want &want, int resultCode)
712 {
713 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
714 if (resultCode != ERR_OK) {
715 RemoveFreeInstallInfo(want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(),
716 want.GetStringParam(Want::PARAM_RESV_START_TIME));
717 NotifyInsightIntentExecuteDone(want, ERR_INVALID_VALUE);
718 return;
719 }
720
721 std::lock_guard<ffrt::mutex> lock(freeInstallListLock_);
722 if (freeInstallList_.empty()) {
723 TAG_LOGI(AAFwkTag::FREE_INSTALL, "Free install list empty.");
724 return;
725 }
726
727 for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) {
728 std::string bundleName = (*it).want.GetElement().GetBundleName();
729 std::string abilityName = (*it).want.GetElement().GetAbilityName();
730 std::string startTime = (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME);
731 if (want.GetElement().GetBundleName().compare(bundleName) != 0 ||
732 want.GetElement().GetAbilityName().compare(abilityName) != 0 ||
733 want.GetStringParam(Want::PARAM_RESV_START_TIME).compare(startTime) != 0) {
734 it++;
735 continue;
736 }
737
738 auto moduleName = (*it).want.GetElement().GetModuleName();
739 auto insightIntentName = (*it).want.GetStringParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_PARAM_NAME);
740 auto executeMode = static_cast<AppExecFwk::ExecuteMode>(
741 it->want.GetIntParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_PARAM_MODE, 0));
742 std::string srcEntry;
743 auto ret = AbilityRuntime::InsightIntentUtils::GetSrcEntry(it->want.GetElement(), insightIntentName,
744 executeMode, srcEntry);
745 if (ret != ERR_OK || srcEntry.empty()) {
746 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Get srcEntry failed after free install. bundleName: %{public}s, "
747 "moduleName: %{public}s, insightIntentName: %{public}s.", bundleName.c_str(), moduleName.c_str(),
748 insightIntentName.c_str());
749 NotifyInsightIntentExecuteDone(want, ERR_INVALID_VALUE);
750 } else {
751 (*it).want.SetParam(AppExecFwk::INSIGHT_INTENT_SRC_ENTRY, srcEntry);
752 StartAbilityByFreeInstall(*it, bundleName, abilityName, startTime);
753 }
754
755 it = freeInstallList_.erase(it);
756 }
757 }
758
NotifyInsightIntentExecuteDone(const Want & want,int resultCode)759 void FreeInstallManager::NotifyInsightIntentExecuteDone(const Want &want, int resultCode)
760 {
761 InsightIntentExecuteParam executeParam;
762 InsightIntentExecuteParam::GenerateFromWant(want, executeParam);
763 AppExecFwk::InsightIntentExecuteResult result;
764 auto ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
765 executeParam.insightIntentId_, resultCode, result);
766 if (ret != ERR_OK) {
767 TAG_LOGE(AAFwkTag::FREE_INSTALL, "Execute intent done failed with %{public}d.", ret);
768 }
769 }
770 } // namespace AAFwk
771 } // namespace OHOS
772