1 /*
2 * Copyright (c) 2021-2025 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 "distributed_sched_service.h"
17
18 #include <algorithm>
19 #include <cinttypes>
20 #include <dlfcn.h>
21 #include <unistd.h>
22
23 #include "ability_manager_client.h"
24 #include "ability_manager_errors.h"
25 #include "accesstoken_kit.h"
26 #include "bool_wrapper.h"
27 #include "datetime_ex.h"
28 #include "element_name.h"
29 #include "file_ex.h"
30 #include "ipc_skeleton.h"
31 #include "iservice_registry.h"
32 #include "multi_user_manager.h"
33 #include "os_account_manager.h"
34 #include "parameters.h"
35 #include "string_ex.h"
36 #include "system_ability_definition.h"
37 #ifdef SUPPORT_DISTRIBUTEDCOMPONENT_TO_MEMMGR
38 #include "mem_mgr_client.h"
39 #endif
40 #ifdef EFFICIENCY_MANAGER_ENABLE
41 #include "res_type.h"
42 #include "res_sched_client.h"
43 #endif
44
45 #include "ability_connection_wrapper_stub.h"
46 #include "adapter/dnetwork_adapter.h"
47 #include "bundle/bundle_manager_internal.h"
48 #include "connect_death_recipient.h"
49 #include "datashare_manager.h"
50 #include "dfx/distributed_radar.h"
51 #include "dfx/distributed_sched_dumper.h"
52 #include "dfx/distributed_ue.h"
53 #include "dfx/dms_continue_time_dumper.h"
54 #include "distributed_sched_adapter.h"
55 #include "distributed_sched_permission.h"
56 #include "distributed_sched_utils.h"
57 #include "dms_callback_task.h"
58 #include "dms_constant.h"
59 #include "dms_free_install_callback.h"
60 #include "dms_token_callback.h"
61 #include "dms_version_manager.h"
62 #include "dsched_collab_manager.h"
63 #include "dsched_continue_manager.h"
64 #include "dtbschedmgr_device_info_storage.h"
65 #include "dtbschedmgr_log.h"
66 #include "parcel_helper.h"
67 #include "string_wrapper.h"
68 #include "switch_status_dependency.h"
69 #ifdef SUPPORT_COMMON_EVENT_SERVICE
70 #include "common_event_listener.h"
71 #endif
72 #ifdef SUPPORT_DISTRIBUTED_FORM_SHARE
73 #include "form_mgr_death_recipient.h"
74 #endif
75 #ifdef SUPPORT_DISTRIBUTED_MISSION_MANAGER
76 #include "mission/distributed_bm_storage.h"
77 #include "mission/distributed_mission_info.h"
78 #include "mission/dms_continue_condition_manager.h"
79 #include "mission/notification/dms_continue_send_manager.h"
80 #include "mission/notification/dms_continue_recommend_manager.h"
81 #include "mission/notification/dms_continue_recv_manager.h"
82 #include "mission/distributed_sched_mission_manager.h"
83 #include "mission/dsched_sync_e2e.h"
84 #include "mission/wifi_state_listener.h"
85 #include "mission/bluetooth_state_listener.h"
86 #endif
87 #include "caller_info.h"
88 #include "os_account_manager.h"
89 #include "ohos_account_kits.h"
90 #include "distributed_sched_permission.h"
91
92 namespace OHOS {
93 namespace DistributedSchedule {
94 using namespace AAFwk;
95 using namespace AccountSA;
96 using namespace AppExecFwk;
97 using namespace Constants;
98 using namespace DistributedHardware;
99
100 namespace {
101 const std::string TAG = "DistributedSchedService";
102 const std::string DMS_SRC_NETWORK_ID = "dmsSrcNetworkId";
103 const std::string DMS_SRC_BUNDLE_NAMES = "callerbundleNames";
104 const int DEFAULT_REQUEST_CODE = -1;
105 const std::u16string CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.abilityshell.DistributedConnection";
106 const std::u16string COMPONENT_CHANGE_INTERFACE_TOKEN = u"ohos.rms.DistributedComponent";
107 const std::u16string ABILITY_MANAGER_SERVICE_TOKEN = u"ohos.aafwk.AbilityManager";
108 const std::u16string ATOMIC_SERVICE_STATUS_CALLBACK_TOKEN = u"ohos.IAtomicServiceStatusCallback";
109 const std::string BUNDLE_NAME_KEY = "bundleName";
110 const std::string VERSION_CODE_KEY = "version";
111 const std::string PID_KEY = "pid";
112 const std::string UID_KEY = "uid";
113 const std::string COMPONENT_TYPE_KEY = "componentType";
114 const std::string DEVICE_TYPE_KEY = "deviceType";
115 const std::string CHANGE_TYPE_KEY = "changeType";
116 const std::string DMS_HIPLAY_ACTION = "ohos.ability.action.deviceSelect";
117 const std::string DMS_VERSION_ID = "dmsVersion";
118 const std::string DMS_UID_SPEC_BUNDLE_NAME = "dmsCallerUidBundleName";
119 const std::string DMS_CONNECT_TOKEN = "connectToken";
120 const std::string DMS_MISSION_ID = "dmsMissionId";
121 const std::string SUPPORT_CONTINUE_PAGE_STACK_KEY = "ohos.extra.param.key.supportContinuePageStack";
122 const std::string SUPPORT_CONTINUE_SOURCE_EXIT_KEY = "ohos.extra.param.key.supportContinueSourceExit";
123 const std::string SUPPORT_CONTINUE_MODULE_NAME_UPDATE_KEY = "ohos.extra.param.key.supportContinueModuleNameUpdate";
124 const std::string DSCHED_EVENT_KEY = "IDSchedEventListener";
125 const std::string DMSDURATION_SAVETIME = "ohos.dschedule.SaveDataTime";
126 const std::string DMS_CONTINUE_SESSION_ID = "ohos.dms.continueSessionId";
127 const std::string DMS_PERSISTENT_ID = "ohos.dms.persistentId";
128 const std::string DMS_CALLING_UID = "ohos.dms.callingUid";
129 const std::string PKG_NAME = "DBinderBus_Dms_" + std::to_string(getprocpid());
130 const std::string BOOT_COMPLETED_EVENT = "usual.event.BOOT_COMPLETED";
131 const std::string COMMON_EVENT_WIFI_SEMI_STATE = "usual.event.wifi.SEMI_STATE";
132 const std::string COLLABRATION_TYPE = "CollabrationType";
133 const std::string SOURCE_DELEGATEE = "SourceDelegatee";
134 const std::string CONNECT_RPOXY = "VALUE_ABILITY_COLLAB_TYPE_CONNECT_PROXY";
135 constexpr int32_t DEFAULT_DMS_MISSION_ID = -1;
136 constexpr int32_t DEFAULT_DMS_CONNECT_TOKEN = -1;
137 constexpr int32_t BIND_CONNECT_RETRY_TIMES = 3;
138 constexpr int32_t BIND_CONNECT_TIMEOUT = 500; // 500ms
139 constexpr int32_t MAX_DISTRIBUTED_CONNECT_NUM = 600;
140 constexpr int32_t INVALID_CALLER_UID = -1;
141 constexpr int32_t IASS_CALLBACK_ON_REMOTE_FREE_INSTALL_DONE = 1;
142 constexpr int32_t DISTRIBUTED_COMPONENT_ADD = 1;
143 constexpr int32_t DISTRIBUTED_COMPONENT_REMOVE = 2;
144 constexpr int32_t START_PERMISSION = 0;
145 constexpr int32_t CALL_PERMISSION = 1;
146 constexpr int32_t SEND_RESULT_PERMISSION = 2;
147 constexpr int64_t CONTINUATION_TIMEOUT = 20000; // 20s
148 // BundleDistributedManager set timeout to 3s, so we set 1s longer
149 constexpr int64_t CHECK_REMOTE_INSTALL_ABILITY = 40000;
150 constexpr int32_t MAX_TOKEN_NUM = 100000000;
151 constexpr uint32_t MAX_MODULENAME_LEN = 2048;
152 constexpr int32_t DMSDURATION_BEGINTIME = 0;
153 constexpr int32_t DMSDURATION_ENDTIME = 1;
154 constexpr int32_t DMSDURATION_TOTALTIME = 2;
155 constexpr int32_t DMSDURATION_DSTTOSRCRPCTIME = 3;
156 constexpr int32_t DMSDURATION_SRCTODSTRPCTIME = 5;
157 constexpr int32_t DMSDURATION_STARTABILITY = 6;
158 constexpr int32_t HID_HAP = 10000; /* first hap user */
159 constexpr int32_t WINDOW_MANAGER_SERVICE_ID = 4606;
160 constexpr int32_t SEMI_WIFI_ID = 1010;
161 constexpr int32_t DSOFTBUS_UID = 1024;
162 constexpr int32_t WEARLINK_UID = 7259;
163 constexpr int32_t SA_READY_TO_UNLOAD = 0;
164 constexpr int32_t SA_REFUSE_TO_UNLOAD = -1;
165 DataShareManager &dataShareManager = DataShareManager::GetInstance();
166
167 const std::string DEFAULT_HAP_CODE_PATH = "1";
168 const std::string LINUX_HAP_CODE_PATH = "2";
169 const int32_t CONNECT_WAIT_TIME_S = 2; /* 2 second */
170 std::mutex getDistibutedProxyLock_;
171 std::condition_variable getDistibutedProxyCondition_;
172 }
173
174 IMPLEMENT_SINGLE_INSTANCE(DistributedSchedService);
175 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&DistributedSchedService::GetInstance());
176
DistributedSchedService()177 DistributedSchedService::DistributedSchedService() : SystemAbility(DISTRIBUTED_SCHED_SA_ID, true)
178 {
179 }
180
GetBundleManager()181 static sptr<AppExecFwk::IBundleMgr> GetBundleManager()
182 {
183 auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
184 if (saMgr == nullptr) {
185 HILOGE("Failed to get system ability manager");
186 return nullptr;
187 }
188
189 auto bundleObj = saMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
190 if (bundleObj == nullptr) {
191 HILOGE("Failed to get bundle manager service");
192 return nullptr;
193 }
194
195 return iface_cast<AppExecFwk::IBundleMgr>(bundleObj);
196 }
197
GetBundleResourceInfo(std::string & bundleName,AppExecFwk::BundleResourceInfo & bundleResourceInfo)198 static int32_t GetBundleResourceInfo(std::string &bundleName, AppExecFwk::BundleResourceInfo &bundleResourceInfo)
199 {
200 auto bms = GetBundleManager();
201 if (bms == nullptr) {
202 HILOGE("Failed to get bundle manager");
203 return INVALID_PARAMETERS_ERR;
204 }
205 std::string identity = IPCSkeleton::ResetCallingIdentity();
206 sptr<AppExecFwk::IBundleResource> bundleResourceProxy = bms->GetBundleResourceProxy();
207 IPCSkeleton::SetCallingIdentity(identity);
208 if (bundleResourceProxy == nullptr) {
209 HILOGE("Failed to get bundle resource proxy");
210 return INVALID_PARAMETERS_ERR;
211 }
212
213 int32_t flag = static_cast<int32_t>(AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_WITH_LABEL);
214 return bundleResourceProxy->GetBundleResourceInfo(bundleName, flag, bundleResourceInfo);
215 }
216
GetDExtensionName(std::string bundleName,int32_t userId)217 std::string GetDExtensionName(std::string bundleName, int32_t userId)
218 {
219 std::vector<AppExecFwk::BundleInfo> installedBundles;
220 auto bms = GetBundleManager();
221 if (bms == nullptr) {
222 HILOGE("Failed to get bundle manager");
223 return "";
224 }
225
226 if (!bms->GetBundleInfos(AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundles, userId)) {
227 HILOGE("Failed to get bundle infos");
228 return "";
229 }
230
231 for (const auto &installedBundle : installedBundles) {
232 if (installedBundle.applicationInfo.codePath == DEFAULT_HAP_CODE_PATH ||
233 installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) {
234 HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data());
235 continue;
236 }
237
238 for (const auto &ext : installedBundle.extensionInfos) {
239 if (ext.bundleName != bundleName) {
240 continue;
241 }
242
243 if (ext.type != AppExecFwk::ExtensionAbilityType::DISTRIBUTED) {
244 continue;
245 }
246
247 HILOGI("bundleName: %{public}s, find extName: %{public}s", bundleName.c_str(), ext.name.c_str());
248 return ext.name;
249 }
250 }
251
252 HILOGI("bundleName: %{public}s , find extName failed", bundleName.c_str());
253 return "";
254 }
255
GetDExtensionProcess(std::string bundleName,int32_t userId)256 std::string GetDExtensionProcess(std::string bundleName, int32_t userId)
257 {
258 std::vector<AppExecFwk::BundleInfo> installedBundles;
259 auto bms = GetBundleManager();
260 if (bms == nullptr) {
261 HILOGE("Failed to get bundle manager");
262 return "";
263 }
264
265 if (!bms->GetBundleInfos(AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundles, userId)) {
266 HILOGE("Failed to get bundle infos");
267 return "";
268 }
269
270 for (const auto &installedBundle : installedBundles) {
271 if (installedBundle.applicationInfo.codePath == DEFAULT_HAP_CODE_PATH ||
272 installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) {
273 HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data());
274 continue;
275 }
276
277 for (const auto &ext : installedBundle.extensionInfos) {
278 if (ext.bundleName != bundleName) {
279 continue;
280 }
281
282 if (ext.type != AppExecFwk::ExtensionAbilityType::DISTRIBUTED) {
283 continue;
284 }
285
286 HILOGI("bundleName: %{public}s, find process: %{public}s", bundleName.c_str(), ext.process.c_str());
287 return ext.process;
288 }
289 }
290
291 HILOGI("bundleName: %{public}s , find process failed", bundleName.c_str());
292 return "";
293 }
294
GetDistributedConnectDone(std::string & bundleName)295 std::function<void(const std::string &&)> GetDistributedConnectDone(std::string &bundleName)
296 {
297 return [](const std::string &&bundleName) {
298 HILOGI("GetDistributedConnectDone, bundleName: %{public}s", bundleName.c_str());
299 getDistibutedProxyCondition_.notify_one();
300 };
301 }
302
CheckCallingPermission(DExtConnectResultInfo & resultInfo)303 static int32_t CheckCallingPermission(DExtConnectResultInfo& resultInfo)
304 {
305 Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
306 HILOGI("DistributedSchedService::tokenId: %{public}d.", tokenId);
307 Security::AccessToken::ATokenTypeEnum tokenType =
308 Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
309 if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
310 HILOGE("Wrong tokenType");
311 resultInfo.result = DExtConnectResult::PERMISSION_DENIED;
312 return DMS_PERMISSION_DENIED;
313 }
314 int32_t callingUid = IPCSkeleton::GetCallingUid();
315 HILOGI("DistributedSchedService::callingUid: %{public}d.", callingUid);
316 if (callingUid != DSOFTBUS_UID && callingUid != WEARLINK_UID) {
317 HILOGE("Wrong uid");
318 resultInfo.result = DExtConnectResult::PERMISSION_DENIED;
319 return DMS_PERMISSION_DENIED;
320 }
321
322 return ERR_OK;
323 }
324
ValidateAndPrepareConnection(const DExtConnectInfo & connectInfo,DExtConnectResultInfo & resultInfo)325 static int32_t ValidateAndPrepareConnection(const DExtConnectInfo& connectInfo, DExtConnectResultInfo& resultInfo)
326 {
327 if (connectInfo.sinkInfo.IsEmpty()) {
328 return INVALID_PARAMETERS_ERR;
329 }
330
331 int32_t ret = CheckCallingPermission(resultInfo);
332 if (ret != ERR_OK) {
333 return ret;
334 }
335 resultInfo.connectInfo = connectInfo;
336
337 int32_t userId = connectInfo.sinkInfo.userId;
338 if (!MultiUserManager::GetInstance().IsUserForeground(userId)) {
339 HILOGW("The current user is not foreground. userId: %{public}d.", userId);
340 return DMS_NOT_FOREGROUND_USER;
341 }
342 return ERR_OK;
343 }
344
TriggerProxyCallbacks(AAFwk::Want & want,const DExtConnectInfo & connectInfo,DExtConnectResultInfo & resultInfo,const sptr<IDExtension> & proxy)345 static void TriggerProxyCallbacks(AAFwk::Want& want, const DExtConnectInfo& connectInfo,
346 DExtConnectResultInfo& resultInfo, const sptr<IDExtension>& proxy)
347 {
348 if (proxy == nullptr) {
349 resultInfo.result = DExtConnectResult::FAILED;
350 HILOGE("Extension distribute proxy is empty");
351 return;
352 }
353 proxy->TriggerOnCreate(want);
354 AAFwk::WantParams wantParam;
355 wantParam.SetParam(COLLABRATION_TYPE, String::Box(CONNECT_RPOXY));
356 wantParam.SetParam(SOURCE_DELEGATEE, String::Box(connectInfo.delegatee));
357 proxy->TriggerOnCollaborate(wantParam);
358 }
359
ConnectDExtensionFromRemote(const DExtConnectInfo & connectInfo,DExtConnectResultInfo & resultInfo)360 int32_t DistributedSchedService::ConnectDExtensionFromRemote(const DExtConnectInfo& connectInfo,
361 DExtConnectResultInfo& resultInfo)
362 {
363 HILOGI("DistributedSchedService::ConnectDExtensionFromRemote called.");
364 int32_t ret = ValidateAndPrepareConnection(connectInfo, resultInfo);
365 if (ret!= ERR_OK) {
366 HILOGE("Validate and prepare connection failed, ret: %{public}d", ret);
367 resultInfo.errCode = ret;
368 return ret;
369 }
370 int32_t userId = connectInfo.sinkInfo.userId;
371 std::string bundleName = connectInfo.sinkInfo.bundleName;
372 std::string abilityName = connectInfo.sinkInfo.abilityName;
373
374 if (svcDConn_ == nullptr) {
375 svcDConn_ = sptr<SvcDistributedConnection>(new SvcDistributedConnection(bundleName));
376 svcDConn_->RegisterEventListener();
377 }
378 auto callConnected = GetDistributedConnectDone(bundleName);
379 svcDConn_->SetCallback(callConnected);
380 bool isCleanCalled = false;
381 AAFwk::Want want;
382 want.SetElementName(bundleName, abilityName);
383 bool isDelay = false;
384 ret = svcDConn_->ConnectDExtAbility(want, userId, isCleanCalled, connectInfo.delegatee, isDelay);
385 if (ret != ERR_OK) {
386 resultInfo.errCode = ret;
387 return ret;
388 }
389 resultInfo.errCode = ret;
390 std::unique_lock<std::mutex> lock(getDistibutedProxyLock_);
391 getDistibutedProxyCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S));
392 auto proxy = svcDConn_->GetDistributedExtProxy();
393 if (proxy == nullptr) {
394 HILOGE("Extension distribute proxy is empty");
395 return INVALID_PARAMETERS_ERR;
396 }
397 AppExecFwk::BundleResourceInfo bundleResourceInfo;
398 ret = GetBundleResourceInfo(bundleName, bundleResourceInfo);
399 if (ret != ERR_OK) {
400 HILOGE("Get bundle resource info failed, ret: %{public}d", ret);
401 return ret;
402 }
403 svcDConn_->PublishDExtensionNotification(connectInfo.sourceInfo.deviceId, bundleName, userId,
404 connectInfo.sourceInfo.networkId, bundleResourceInfo);
405
406 if (isDelay) {
407 HILOGI("Connect ability again.");
408 return ret;
409 }
410 TriggerProxyCallbacks(want, connectInfo, resultInfo, proxy);
411 resultInfo.result = DExtConnectResult::SUCCESS;
412 return ret;
413 }
414
OnStart(const SystemAbilityOnDemandReason & startReason)415 void DistributedSchedService::OnStart(const SystemAbilityOnDemandReason &startReason)
416 {
417 HILOGI("OnStart reason %{public}s, reasonId_:%{public}d", startReason.GetName().c_str(), startReason.GetId());
418 if (!DoStart()) {
419 HILOGI("OnStart dms service failed.");
420 return;
421 }
422
423 Publish(this);
424 HandleBootStart(startReason);
425 }
426
OnStop(const SystemAbilityOnDemandReason & stopReason)427 void DistributedSchedService::OnStop(const SystemAbilityOnDemandReason &stopReason)
428 {
429 HILOGI("OnStart reason %{public}s, reasonId_:%{public}d", stopReason.GetName().c_str(), stopReason.GetId());
430 #ifdef SUPPORT_DISTRIBUTED_MISSION_MANAGER
431 MultiUserManager::GetInstance().UnInit();
432 RemoveSystemAbilityListener(WINDOW_MANAGER_SERVICE_ID);
433 if (missionFocusedListener_ != nullptr) {
434 missionFocusedListener_->UnInit();
435 }
436 DistributedSchedAdapter::GetInstance().UnRegisterMissionListener(missionFocusedListener_);
437 DmsContinueConditionMgr::GetInstance().UnInit();
438 #endif
439
440 #ifdef DMSFWK_INTERACTIVE_ADAPTER
441 {
442 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
443 dlclose(dllHandle_);
444 dllHandle_ = nullptr;
445 };
446 #endif
447 dataShareManager.UnInit();
448 HILOGI("OnStop dms service end");
449 }
450
OnIdle(const SystemAbilityOnDemandReason & idleReason)451 int32_t DistributedSchedService::OnIdle(const SystemAbilityOnDemandReason& idleReason)
452 {
453 bool isIdle = false;
454 std::vector<DistributedHardware::DmDeviceInfo> dmDeviceInfoList;
455 int32_t errCode = DeviceManager::GetInstance().GetTrustedDeviceList(PKG_NAME, "", dmDeviceInfoList);
456 if (errCode == ERR_OK && dmDeviceInfoList.empty()) {
457 isIdle = true;
458 }
459 HILOGI("OnIdle, idleReason name %{public}s, id %{public}d, value %{public}s, is ready to unload %{public}d",
460 idleReason.GetName().c_str(), idleReason.GetId(), idleReason.GetValue().c_str(), isIdle);
461 return isIdle ? SA_READY_TO_UNLOAD : SA_REFUSE_TO_UNLOAD;
462 }
463
OnActive(const SystemAbilityOnDemandReason & activeReason)464 void DistributedSchedService::OnActive(const SystemAbilityOnDemandReason &activeReason)
465 {
466 HILOGI("OnStart reason %{public}s, reasonId_:%{public}d", activeReason.GetName().c_str(), activeReason.GetId());
467 DoStart();
468 }
469
HandleBootStart(const SystemAbilityOnDemandReason & startReason)470 void DistributedSchedService::HandleBootStart(const SystemAbilityOnDemandReason &startReason)
471 {
472 std::vector<DistributedHardware::DmDeviceInfo> dmDeviceInfoList;
473 int32_t errCode = DeviceManager::GetInstance().GetTrustedDeviceList(PKG_NAME, "", dmDeviceInfoList);
474 if (errCode != ERR_OK) {
475 HILOGE("Get device manager trusted device list fail, errCode %{public}d", errCode);
476 }
477 if (startReason.GetName() == BOOT_COMPLETED_EVENT && dmDeviceInfoList.empty()) {
478 HILOGI("UnloadSystemAbility dms");
479 auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
480 if (samgrProxy == nullptr) {
481 HILOGE("get samgr failed");
482 return;
483 }
484 int32_t ret = samgrProxy->UnloadSystemAbility(DISTRIBUTED_SCHED_SA_ID);
485 if (ret != ERR_OK) {
486 HILOGE("remove system ability failed");
487 return;
488 }
489 HILOGI("UnloadSystemAbility dms ok");
490 }
491 }
492
493 // LCOV_EXCL_START
DoStart()494 bool DistributedSchedService::DoStart()
495 {
496 #ifdef DMS_SERVICE_DISABLE
497 HILOGI("DMS service disabled, exiting.");
498 _exit(0);
499 #endif
500
501 #ifdef DMSFWK_INTERACTIVE_ADAPTER
502 HILOGI("Get dms interactive adapter proxy enter.");
503 int32_t ret = GetDmsInteractiveAdapterProxy();
504 if (ret != ERR_OK) {
505 HILOGE("Get remote dms interactive adapter proxy fail, ret %{public}d.", ret);
506 }
507 #endif
508
509 HILOGI("Dms service DoStart enter.");
510 if (!Init()) {
511 HILOGE("failed to init DistributedSchedService");
512 return false;
513 }
514 FuncContinuationCallback continuationCallback = [this] (int32_t missionId) {
515 HILOGW("continuationCallback timeout.");
516 NotifyContinuationCallbackResult(missionId, CONTINUE_ABILITY_TIMEOUT_ERR);
517 };
518
519 DmsCallbackTaskInitCallbackFunc freeCallback = [this] (int64_t taskId) {
520 HILOGW("DmsCallbackTaskInitCallbackFunc timeout, taskId:%{public}" PRId64 ".", taskId);
521 NotifyCompleteFreeInstallFromRemote(taskId, AAFwk::FREE_INSTALL_TIMEOUT);
522 };
523 dschedContinuation_ = std::make_shared<DSchedContinuation>();
524 collaborateCbMgr_ = std::make_shared<DSchedCollaborationCallbackMgr>();
525 dmsCallbackTask_ = std::make_shared<DmsCallbackTask>();
526 dschedContinuation_->Init(continuationCallback);
527 collaborateCbMgr_->Init();
528 dmsCallbackTask_->Init(freeCallback);
529
530 HILOGI("OnStart dms service success.");
531 return true;
532 }
533 // LCOV_EXCL_STOP
534
Dump(int32_t fd,const std::vector<std::u16string> & args)535 int32_t DistributedSchedService::Dump(int32_t fd, const std::vector<std::u16string>& args)
536 {
537 std::vector<std::string> argsInStr8;
538 for (const auto& arg : args) {
539 argsInStr8.emplace_back(Str16ToStr8(arg));
540 }
541 std::string result;
542 DistributedSchedDumper::Dump(argsInStr8, result);
543
544 if (!SaveStringToFd(fd, result)) {
545 HILOGE("save to fd failed");
546 return DMS_WRITE_FILE_FAILED_ERR;
547 }
548 return ERR_OK;
549 }
550
DeviceOnlineNotify(const std::string & networkId)551 void DistributedSchedService::DeviceOnlineNotify(const std::string& networkId)
552 {
553 DistributedSchedAdapter::GetInstance().DeviceOnline(networkId);
554 #ifdef SUPPORT_DISTRIBUTED_MISSION_MANAGER
555 DistributedSchedMissionManager::GetInstance().DeviceOnlineNotify(networkId);
556 if (!MultiUserManager::GetInstance().CheckRegSoftbusListener() &&
557 DistributedHardware::DeviceManager::GetInstance().IsSameAccount(networkId)) {
558 HILOGI("DMSContinueRecvMgr need init");
559 MultiUserManager::GetInstance().RegisterSoftbusListener();
560 }
561 auto sendMgr = MultiUserManager::GetInstance().GetCurrentSendMgr();
562 CHECK_POINTER_RETURN(sendMgr, "sendMgr");
563 sendMgr->OnDeviceOnline();
564
565 auto recomMgr = MultiUserManager::GetInstance().GetCurrentRecomMgr();
566 CHECK_POINTER_RETURN(recomMgr, "recomMgr");
567 recomMgr->OnDeviceChanged();
568 #endif
569 }
570
DeviceOfflineNotify(const std::string & networkId)571 void DistributedSchedService::DeviceOfflineNotify(const std::string& networkId)
572 {
573 DistributedSchedAdapter::GetInstance().DeviceOffline(networkId);
574 #ifdef SUPPORT_DISTRIBUTED_MISSION_MANAGER
575 auto recvMgr = MultiUserManager::GetInstance().GetCurrentRecvMgr();
576 CHECK_POINTER_RETURN(recvMgr, "recvMgr");
577 recvMgr->NotifyDeviceOffline(networkId);
578 DistributedSchedMissionManager::GetInstance().DeviceOfflineNotify(networkId);
579 #endif
580 }
581
DeviceOfflineNotifyAfterDelete(const std::string & networkId)582 void DistributedSchedService::DeviceOfflineNotifyAfterDelete(const std::string& networkId)
583 {
584 #ifdef SUPPORT_DISTRIBUTED_MISSION_MANAGER
585 auto recomMgr = MultiUserManager::GetInstance().GetCurrentRecomMgr();
586 CHECK_POINTER_RETURN(recomMgr, "recomMgr");
587 recomMgr->OnDeviceChanged();
588 #endif
589 }
590
591 // LCOV_EXCL_START
Init()592 bool DistributedSchedService::Init()
593 {
594 HILOGD("ready to init.");
595 InitDeviceCfg();
596 DmsContinueTime::GetInstance().Init();
597 DnetworkAdapter::GetInstance()->Init();
598 if (!DtbschedmgrDeviceInfoStorage::GetInstance().Init()) {
599 HILOGW("DtbschedmgrDeviceInfoStorage init failed.");
600 }
601 InitDataShareManager();
602 InitMissionManager();
603 DSchedCollabManager::GetInstance().Init();
604 DistributedSchedAdapter::GetInstance().Init();
605 if (SwitchStatusDependency::GetInstance().IsContinueSwitchOn()) {
606 DSchedContinueManager::GetInstance().Init();
607 }
608 connectDeathRecipient_ = sptr<IRemoteObject::DeathRecipient>(new ConnectDeathRecipient());
609 callerDeathRecipient_ = sptr<IRemoteObject::DeathRecipient>(new CallerDeathRecipient());
610 callerDeathRecipientForLocalDevice_ = sptr<IRemoteObject::DeathRecipient>(
611 new CallerDeathRecipient(IDistributedSched::CALLER));
612 if (componentChangeHandler_ == nullptr) {
613 auto runner = AppExecFwk::EventRunner::Create("DmsComponentChange");
614 componentChangeHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
615 }
616 return true;
617 }
618 // LCOV_EXCL_STOP
619
620 // LCOV_EXCL_START
InitMissionManager()621 void DistributedSchedService::InitMissionManager()
622 {
623 #ifdef SUPPORT_DISTRIBUTED_MISSION_MANAGER
624 DmsContinueConditionMgr::GetInstance().Init();
625 if (!AddSystemAbilityListener(WINDOW_MANAGER_SERVICE_ID)) {
626 HILOGE("Add System Ability Listener failed!");
627 }
628 DistributedSchedMissionManager::GetInstance().Init();
629 DistributedSchedMissionManager::GetInstance().InitDataStorage();
630 InitCommonEventListener();
631 InitWifiStateListener();
632 InitWifiSemiStateListener();
633 InitBluetoothStateListener();
634 MultiUserManager::GetInstance().Init();
635 #endif
636 }
637 // LCOV_EXCL_STOP
638
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)639 void DistributedSchedService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
640 {
641 HILOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
642 if (missionFocusedListener_ == nullptr) {
643 HILOGI("missionFocusedListener_ is nullptr.");
644 missionFocusedListener_ = sptr<DistributedMissionFocusedListener>(new DistributedMissionFocusedListener());
645 missionFocusedListener_->Init();
646 }
647 int32_t ret = DistributedSchedAdapter::GetInstance().RegisterMissionListener(missionFocusedListener_);
648 if (ret != ERR_OK) {
649 HILOGE("get RegisterMissionListener failed, ret: %{public}d", ret);
650 }
651 }
652
RegisterDataShareObserver(const std::string & key)653 void DistributedSchedService::RegisterDataShareObserver(const std::string& key)
654 {
655 HILOGI("RegisterObserver start.");
656 DataShareManager::ObserverCallback observerCallback = [this]() {
657 auto sendMgr = MultiUserManager::GetInstance().GetCurrentSendMgr();
658 bool continueSwitch = SwitchStatusDependency::GetInstance().IsContinueSwitchOn();
659 int32_t lastContinuableMissionId = DmsContinueConditionMgr::GetInstance().GetLastContinuableMissionId();
660 if (!continueSwitch) {
661 sendMgr->OnMissionStatusChanged(lastContinuableMissionId, MISSION_EVENT_CONTINUE_SWITCH_OFF);
662 }
663
664 dataShareManager.SetCurrentContinueSwitch(SwitchStatusDependency::GetInstance().IsContinueSwitchOn());
665 HILOGD("dsMgr IsCurrentContinueSwitchOn : %{public}d", dataShareManager.IsCurrentContinueSwitchOn());
666 int32_t missionId = GetCurrentMissionId();
667 if (missionId <= 0) {
668 HILOGW("GetCurrentMissionId failed, init end. ret: %{public}d", missionId);
669 }
670 DmsUE::GetInstance().ChangedSwitchState(dataShareManager.IsCurrentContinueSwitchOn(), ERR_OK);
671 if (dataShareManager.IsCurrentContinueSwitchOn()) {
672 if (sendMgr == nullptr) {
673 HILOGI("GetSendMgr failed.");
674 return;
675 }
676 sendMgr->OnMissionStatusChanged(missionId, MISSION_EVENT_FOCUSED);
677 DSchedContinueManager::GetInstance().Init();
678 } else {
679 if (sendMgr == nullptr) {
680 HILOGI("GetSendMgr failed.");
681 return;
682 }
683 sendMgr->OnMissionStatusChanged(missionId, MISSION_EVENT_UNFOCUSED);
684 auto recvMgr = MultiUserManager::GetInstance().GetCurrentRecvMgr();
685 if (recvMgr == nullptr) {
686 HILOGI("GetRecvMgr failed.");
687 return;
688 }
689 recvMgr->OnContinueSwitchOff();
690 DSchedContinueManager::GetInstance().UnInit();
691 };
692 };
693 dataShareManager.RegisterObserver(key, observerCallback);
694 HILOGI("RegisterObserver end.");
695 }
696
ContinueStateCallbackRegister(int32_t missionId,std::string bundleName,std::string moduleName,std::string abilityName,sptr<IRemoteObject> callback)697 int32_t DistributedSchedService::ContinueStateCallbackRegister(
698 int32_t missionId, std::string bundleName, std::string moduleName,
699 std::string abilityName, sptr<IRemoteObject> callback)
700 {
701 HILOGI("ContinueStateCallbackRegister start. missionId: %{public}d; "
702 "bundleName: %{public}s; moduleName: %{public}s; abilityname: %{public}s;",
703 missionId, bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
704 StateCallbackInfo stateCallbackInfo;
705 stateCallbackInfo.missionId = missionId;
706 stateCallbackInfo.bundleName = bundleName;
707 stateCallbackInfo.moduleName = moduleName;
708 stateCallbackInfo.abilityName = abilityName;
709
710 if (callback == nullptr) {
711 return NO_CONNECT_CALLBACK_ERR;
712 }
713
714 int32_t result = DSchedContinueManager::GetInstance().ContinueStateCallbackRegister(stateCallbackInfo, callback);
715 HILOGI("ContinueStateCallbackRegister end, result: %{public}d", result);
716 return result;
717 }
ContinueStateCallbackUnRegister(int32_t missionId,std::string bundleName,std::string moduleName,std::string abilityName)718 int32_t DistributedSchedService::ContinueStateCallbackUnRegister(
719 int32_t missionId, std::string bundleName, std::string moduleName,
720 std::string abilityName)
721 {
722 HILOGI("ContinueStateCallbackUnRegister start. missionId: %{public}d; "
723 "bundleName: %{public}s; moduleName: %{public}s; abilityname: %{public}s;",
724 missionId, bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
725 StateCallbackInfo stateCallbackInfo;
726 stateCallbackInfo.missionId = missionId;
727 stateCallbackInfo.bundleName = bundleName;
728 stateCallbackInfo.moduleName = moduleName;
729 stateCallbackInfo.abilityName = abilityName;
730
731 int32_t result = DSchedContinueManager::GetInstance().ContinueStateCallbackUnRegister(stateCallbackInfo);
732 HILOGI("ContinueStateCallbackUnRegister end, result: %{public}d", result);
733 return result;
734 }
735
736 // LCOV_EXCL_START
InitDataShareManager()737 void DistributedSchedService::InitDataShareManager()
738 {
739 dataShareManager.SetCurrentContinueSwitch(SwitchStatusDependency::GetInstance().IsContinueSwitchOn());
740 HILOGD("dsMgr IsCurrentContinueSwitchOn : %{public}d", dataShareManager.IsCurrentContinueSwitchOn());
741 RegisterDataShareObserver(SwitchStatusDependency::GetInstance().CONTINUE_SWITCH_STATUS_KEY);
742 DmsUE::GetInstance().OriginalSwitchState(SwitchStatusDependency::GetInstance().IsContinueSwitchOn(), ERR_OK);
743 HILOGI("Init data share manager, register observer end.");
744 }
745
InitCommonEventListener()746 void DistributedSchedService::InitCommonEventListener()
747 {
748 HILOGI("InitCommonEventListener called");
749 #ifdef SUPPORT_COMMON_EVENT_SERVICE
750 DmsBmStorage::GetInstance();
751 EventFwk::MatchingSkills matchingSkills;
752 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED);
753 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
754 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
755 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON);
756 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
757 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED);
758 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
759 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED);
760 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
761 auto applyMonitor = std::make_shared<CommonEventListener>(subscribeInfo);
762 EventFwk::CommonEventManager::SubscribeCommonEvent(applyMonitor);
763 DmsBmStorage::GetInstance()->UpdateDistributedData();
764 if (DmsKvSyncE2E::GetInstance()->CheckDeviceCfg()) {
765 DmsKvSyncE2E::GetInstance()->PushAndPullData();
766 }
767 #endif
768 }
769
InitWifiStateListener()770 void DistributedSchedService::InitWifiStateListener()
771 {
772 HILOGI("InitWifiStateListener called");
773 EventFwk::MatchingSkills matchingSkills;
774 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_POWER_STATE);
775 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
776 auto wifiStateListener = std::make_shared<WifiStateListener>(subscribeInfo);
777 wifiStateListener->InitWifiState();
778 if (!EventFwk::CommonEventManager::SubscribeCommonEvent(wifiStateListener)) {
779 HILOGE("SubscribeCommonEvent wifiStateListener failed!");
780 }
781 }
782 // LCOV_EXCL_STOP
783
InitWifiSemiStateListener()784 void DistributedSchedService::InitWifiSemiStateListener()
785 {
786 HILOGI("InitWifiSemiStateListener called");
787 EventFwk::MatchingSkills matchingSkills;
788 matchingSkills.AddEvent(COMMON_EVENT_WIFI_SEMI_STATE);
789 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
790 subscribeInfo.SetPublisherUid(SEMI_WIFI_ID);
791 auto wifiStateListener = std::make_shared<WifiStateListener>(subscribeInfo);
792 if (!EventFwk::CommonEventManager::SubscribeCommonEvent(wifiStateListener)) {
793 HILOGE("SubscribeCommonEvent wifiSemiStateListener failed!");
794 }
795 }
796
797 // LCOV_EXCL_START
InitBluetoothStateListener()798 void DistributedSchedService::InitBluetoothStateListener()
799 {
800 #ifdef DMS_CHECK_BLUETOOTH
801 HILOGI("InitBluetoothStateListener called");
802 std::shared_ptr<BluetoothStateListener> bluetoothStateListener = BluetoothStateListener::GetInstance();
803 bluetoothStateListener->InitBluetoothState();
804 Bluetooth::BluetoothHost::GetDefaultHost().RegisterObserver(bluetoothStateListener);
805 #endif
806 }
807 // LCOV_EXCL_STOP
808
809 // LCOV_EXCL_START
InitDeviceCfg()810 void DistributedSchedService::InitDeviceCfg()
811 {
812 HILOGI("called");
813 DmsKvSyncE2E::GetInstance()->QueryMDMControl();
814 DmsKvSyncE2E::GetInstance()->SetDeviceCfg();
815 }
816 // LCOV_EXCL_STOP
817
DurationStart(const std::string srcDeviceId,const std::string dstDeviceId)818 void DistributedSchedService::DurationStart(const std::string srcDeviceId, const std::string dstDeviceId)
819 {
820 DmsContinueTime::GetInstance().Init();
821 std::string strBeginTime = DmsContinueTime::GetInstance().GetCurrentTime();
822 DmsContinueTime::GetInstance().SetDurationStrTime(DMSDURATION_BEGINTIME, strBeginTime);
823 DmsContinueTime::GetInstance().SetNetWorkId(srcDeviceId, dstDeviceId);
824 }
825
826 #ifdef DMSFWK_INTERACTIVE_ADAPTER
CheckRemoteOsType(const std::string & netwokId)827 bool DistributedSchedService::CheckRemoteOsType(const std::string& netwokId)
828 {
829 auto devInfo = DtbschedmgrDeviceInfoStorage::GetInstance().GetDeviceInfoById(netwokId);
830 if (devInfo == nullptr) {
831 HILOGE("GetDeviceInfoById failed, netwokId: %{public}s.", GetAnonymStr(netwokId).c_str());
832 return false;
833 }
834
835 HILOGI("Remote device OsType %{public}d, netwokId: %{public}s.", devInfo->GetDeviceOSType(),
836 GetAnonymStr(netwokId).c_str());
837 return (devInfo->GetDeviceOSType() == Constants::HO_OS_TYPE_EX);
838 }
839
GetDmsInteractiveAdapterProxy()840 int32_t DistributedSchedService::GetDmsInteractiveAdapterProxy()
841 {
842 HILOGI("Get remote dms interactive adapter proxy.");
843 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
844 #if (defined(__aarch64__) || defined(__x86_64__))
845 char resolvedPath[100] = "/system/lib64/libdms_interactive_adapter.z.so";
846 #else
847 char resolvedPath[100] = "/system/lib/libdms_interactive_adapter.z.so";
848 #endif
849 int32_t (*GetDmsInteractiveAdapter)(const sptr<IRemoteObject> &callerToken,
850 IDmsInteractiveAdapter &dmsAdpHandle) = nullptr;
851 int32_t (*GetDmsBroadcast)(IDmsBroadcastAdapter &dmsBcHandle) = nullptr;
852
853 dllHandle_ = dlopen(resolvedPath, RTLD_LAZY);
854 if (dllHandle_ == nullptr) {
855 HILOGE("Open dms interactive adapter shared object fail, resolvedPath [%{public}s].", resolvedPath);
856 return NOT_FIND_SERVICE_REGISTRY;
857 }
858
859 int32_t ret = ERR_OK;
860 do {
861 GetDmsInteractiveAdapter = reinterpret_cast<int32_t (*)(const sptr<IRemoteObject> &callerToken,
862 IDmsInteractiveAdapter &dmsAdpHandle)>(dlsym(dllHandle_, "GetDmsInteractiveAdapter"));
863 GetDmsBroadcast = reinterpret_cast<int32_t (*)(IDmsBroadcastAdapter &dmsBcHandle)>(
864 dlsym(dllHandle_, "GetDmsBroadcast"));
865 if (GetDmsInteractiveAdapter == nullptr || GetDmsBroadcast == nullptr) {
866 HILOGE("Link the GetDmsInteractiveAdapter symbol in dms interactive adapter fail.");
867 ret = NOT_FIND_SERVICE_REGISTRY;
868 break;
869 }
870
871 if (GetDmsInteractiveAdapter(this, dmsAdapetr_) || GetDmsBroadcast(
872 SoftbusAdapter::GetInstance().dmsAdapetr_)) {
873 HILOGE("Init remote dms interactive adapter proxy fail, ret %{public}d.", ret);
874 ret = INVALID_PARAMETERS_ERR;
875 break;
876 }
877 HILOGI("Init remote dms interactive adapter proxy success.");
878 ret = ERR_OK;
879 } while (false);
880
881 if (ret != ERR_OK) {
882 HILOGE("Get remote dms interactive adapter proxy fail, dlclose handle.");
883 dlclose(dllHandle_);
884 dllHandle_ = nullptr;
885 }
886 return ret;
887 }
888
StartRemoteAbilityAdapter(const OHOS::AAFwk::Want & want,int32_t callerUid,int32_t requestCode,uint32_t accessToken)889 int32_t DistributedSchedService::StartRemoteAbilityAdapter(const OHOS::AAFwk::Want& want,
890 int32_t callerUid, int32_t requestCode, uint32_t accessToken)
891 {
892 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
893 if (dllHandle_ == nullptr) {
894 HILOGE("Open dms interactive adapter shared object failed");
895 return NOT_FIND_SERVICE_REGISTRY;
896 }
897 if (dmsAdapetr_.StartRemoteAbilityAdapter == nullptr) {
898 HILOGE("Dms interactive start remote ability adapter handle is null.");
899 return INVALID_PARAMETERS_ERR;
900 }
901
902 int32_t ret = dmsAdapetr_.StartRemoteAbilityAdapter(want, callerUid, requestCode, accessToken);
903 if (ret != ERR_OK) {
904 HILOGE("Dms interactive adapter start remote ability adapter fail, ret %{public}d.", ret);
905 }
906 return ret;
907 }
908
ConnectRemoteAbilityAdapter(const OHOS::AAFwk::Want & want,const sptr<IRemoteObject> & connect,int32_t callerUid,int32_t callerPid,uint32_t accessToken)909 int32_t DistributedSchedService::ConnectRemoteAbilityAdapter(const OHOS::AAFwk::Want& want,
910 const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid, uint32_t accessToken)
911 {
912 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
913 if (dllHandle_ == nullptr) {
914 HILOGE("Open dms interactive adapter shared object failed");
915 return NOT_FIND_SERVICE_REGISTRY;
916 }
917 if (dmsAdapetr_.ConnectRemoteAbilityAdapter == nullptr) {
918 HILOGE("Dms interactive connect remote ability adapter handle is null.");
919 return INVALID_PARAMETERS_ERR;
920 }
921
922 int32_t ret = dmsAdapetr_.ConnectRemoteAbilityAdapter(want, connect, callerUid, callerPid, accessToken);
923 if (ret != ERR_OK) {
924 HILOGE("Dms interactive adapter connect remote ability adapter fail, ret %{public}d.", ret);
925 }
926 return ret;
927 }
928
DisconnectRemoteAbilityAdapter(const sptr<IRemoteObject> & connect,int32_t callerUid,uint32_t accessToken)929 int32_t DistributedSchedService::DisconnectRemoteAbilityAdapter(const sptr<IRemoteObject>& connect, int32_t callerUid,
930 uint32_t accessToken)
931 {
932 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
933 if (dllHandle_ == nullptr) {
934 HILOGE("Open dms interactive adapter shared object failed");
935 return NOT_FIND_SERVICE_REGISTRY;
936 }
937 if (dmsAdapetr_.DisconnectRemoteAbilityAdapter == nullptr) {
938 HILOGE("Dms interactive disconnect remote ability adapter handle is null.");
939 return INVALID_PARAMETERS_ERR;
940 }
941
942 int32_t ret = dmsAdapetr_.DisconnectRemoteAbilityAdapter(connect, callerUid, accessToken);
943 if (ret != ERR_OK) {
944 HILOGE("Dms interactive adapter disconnect remote ability adapter fail, ret %{public}d.", ret);
945 }
946 return ret;
947 }
948
StartAbilityFromRemoteAdapter(MessageParcel & data,MessageParcel & reply)949 int32_t DistributedSchedService::StartAbilityFromRemoteAdapter(MessageParcel& data, MessageParcel& reply)
950 {
951 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
952 if (dllHandle_ == nullptr) {
953 HILOGE("Open dms interactive adapter shared object failed");
954 return NOT_FIND_SERVICE_REGISTRY;
955 }
956 if (dmsAdapetr_.StartAbilityFromRemoteAdapter == nullptr) {
957 HILOGE("Dms interactive start ability from remote adapter handle is null.");
958 return INVALID_PARAMETERS_ERR;
959 }
960
961 int32_t ret = dmsAdapetr_.StartAbilityFromRemoteAdapter(data, reply);
962 if (ret != ERR_OK) {
963 HILOGE("Dms interactive adapter start ability from remote adapter fail, ret %{public}d.", ret);
964 }
965 return ret;
966 }
967
StopAbilityFromRemoteAdapter(MessageParcel & data,MessageParcel & reply)968 int32_t DistributedSchedService::StopAbilityFromRemoteAdapter(MessageParcel& data, MessageParcel& reply)
969 {
970 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
971 if (dllHandle_ == nullptr) {
972 HILOGE("Open dms interactive adapter shared object failed");
973 return NOT_FIND_SERVICE_REGISTRY;
974 }
975 if (dmsAdapetr_.StopAbilityFromRemoteAdapter == nullptr) {
976 HILOGE("Dms interactive stop ability from remote adapter handle is null.");
977 return INVALID_PARAMETERS_ERR;
978 }
979
980 int32_t ret = dmsAdapetr_.StopAbilityFromRemoteAdapter(data, reply);
981 if (ret != ERR_OK) {
982 HILOGE("Dms interactive adapter stop ability from remote adapter fail, ret %{public}d.", ret);
983 }
984 return ret;
985 }
986
ConnectAbilityFromRemoteAdapter(MessageParcel & data,MessageParcel & reply)987 int32_t DistributedSchedService::ConnectAbilityFromRemoteAdapter(MessageParcel& data, MessageParcel& reply)
988 {
989 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
990 if (dllHandle_ == nullptr) {
991 HILOGE("Open dms interactive adapter shared object failed");
992 return NOT_FIND_SERVICE_REGISTRY;
993 }
994 if (dmsAdapetr_.ConnectAbilityFromRemoteAdapter == nullptr) {
995 HILOGE("Dms interactive connect ability from remote adapter handle is null.");
996 return INVALID_PARAMETERS_ERR;
997 }
998
999 int32_t ret = dmsAdapetr_.ConnectAbilityFromRemoteAdapter(data, reply);
1000 if (ret != ERR_OK) {
1001 HILOGE("Dms interactive adapter connect ability from remote adapter fail, ret %{public}d.", ret);
1002 }
1003 return ret;
1004 }
1005
DisconnectAbilityFromRemoteAdapter(MessageParcel & data,MessageParcel & reply)1006 int32_t DistributedSchedService::DisconnectAbilityFromRemoteAdapter(MessageParcel& data, MessageParcel& reply)
1007 {
1008 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
1009 if (dllHandle_ == nullptr) {
1010 HILOGE("Open dms interactive adapter shared object failed");
1011 return NOT_FIND_SERVICE_REGISTRY;
1012 }
1013 if (dmsAdapetr_.DisconnectAbilityFromRemoteAdapter == nullptr) {
1014 HILOGE("Dms interactive disconnect ability from remote adapter handle is null.");
1015 return INVALID_PARAMETERS_ERR;
1016 }
1017
1018 int32_t ret = dmsAdapetr_.DisconnectAbilityFromRemoteAdapter(data, reply);
1019 if (ret != ERR_OK) {
1020 HILOGE("Dms interactive adapter disconnect ability from remote adapter fail, ret %{public}d.", ret);
1021 }
1022 return ret;
1023 }
1024
NotifyAbilityLifecycleChangedFromRemoteAdapter(MessageParcel & data,MessageParcel & reply)1025 int32_t DistributedSchedService::NotifyAbilityLifecycleChangedFromRemoteAdapter(MessageParcel& data,
1026 MessageParcel& reply)
1027 {
1028 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
1029 if (dllHandle_ == nullptr) {
1030 HILOGE("Open dms interactive adapter shared object failed");
1031 return NOT_FIND_SERVICE_REGISTRY;
1032 }
1033 if (dmsAdapetr_.NotifyAbilityLifecycleChangedFromRemoteAdapter == nullptr) {
1034 HILOGE("Dms interactive disconnect ability from remote adapter handle is null.");
1035 return INVALID_PARAMETERS_ERR;
1036 }
1037
1038 int32_t ret = dmsAdapetr_.NotifyAbilityLifecycleChangedFromRemoteAdapter(data, reply);
1039 if (ret != ERR_OK) {
1040 HILOGE("Dms interactive adapter disconnect ability from remote adapter fail, ret %{public}d.", ret);
1041 }
1042 return ret;
1043 }
1044
OnDeviceOnlineEx(const OHOS::DistributedHardware::DmDeviceInfo & deviceInfo)1045 void DistributedSchedService::OnDeviceOnlineEx(const OHOS::DistributedHardware::DmDeviceInfo& deviceInfo)
1046 {
1047 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
1048 if (dllHandle_ == nullptr) {
1049 HILOGE("Open dms interactive adapter shared object failed");
1050 return;
1051 }
1052 if (dmsAdapetr_.OnDeviceOnlineEx == nullptr) {
1053 HILOGE("Dms interactive on device online extention handle is null.");
1054 return;
1055 }
1056
1057 dmsAdapetr_.OnDeviceOnlineEx(deviceInfo);
1058 }
1059
OnDeviceOfflineEx(const OHOS::DistributedHardware::DmDeviceInfo & deviceInfo)1060 void DistributedSchedService::OnDeviceOfflineEx(const OHOS::DistributedHardware::DmDeviceInfo& deviceInfo)
1061 {
1062 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
1063 if (dllHandle_ == nullptr) {
1064 HILOGE("Open dms interactive adapter shared object failed");
1065 return;
1066 }
1067 if (dmsAdapetr_.OnDeviceOfflineEx == nullptr) {
1068 HILOGE("Dms interactive on device online extention handle is null.");
1069 return;
1070 }
1071
1072 dmsAdapetr_.OnDeviceOfflineEx(deviceInfo);
1073 }
1074
OnDeviceInfoChangedEx(const OHOS::DistributedHardware::DmDeviceInfo & deviceInfo)1075 void DistributedSchedService::OnDeviceInfoChangedEx(const OHOS::DistributedHardware::DmDeviceInfo& deviceInfo)
1076 {
1077 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
1078 if (dllHandle_ == nullptr) {
1079 HILOGE("Open dms interactive adapter shared object failed");
1080 return;
1081 }
1082 if (dmsAdapetr_.OnDeviceInfoChangedEx == nullptr) {
1083 HILOGE("Dms interactive on device online extention handle is null.");
1084 return;
1085 }
1086
1087 dmsAdapetr_.OnDeviceInfoChangedEx(deviceInfo);
1088 }
1089 #endif // DMSFWK_INTERACTIVE_ADAPTER
1090
OnHAEventAdapter(const std::string & instanceTag,int32_t eventType,const std::string & eventId,const std::unordered_map<std::string,std::string> & properties)1091 int32_t DistributedSchedService::OnHAEventAdapter(const std::string& instanceTag, int32_t eventType,
1092 const std::string& eventId, const std::unordered_map<std::string, std::string>& properties)
1093 {
1094 int32_t result = ERR_OK;
1095 #ifdef DMSFWK_INTERACTIVE_ADAPTER
1096 std::lock_guard<std::mutex> autoLock(dmsAdapetrLock_);
1097 if (dllHandle_ == nullptr) {
1098 HILOGE("Open dms interactive adapter shared object failed");
1099 return ERR_NULL_OBJECT;
1100 }
1101 if (dmsAdapetr_.OnHAEventAdapter == nullptr) {
1102 HILOGE("Dms interactive on device online extention handle is null.");
1103 return ERR_NULL_OBJECT;
1104 }
1105
1106 result = dmsAdapetr_.OnHAEventAdapter(instanceTag, eventType, eventId, properties);
1107 #endif // DMSFWK_INTERACTIVE_ADAPTER
1108 return result;
1109 }
1110
GetCallerInfo(const std::string & localDeviceId,int32_t callerUid,uint32_t accessToken,CallerInfo & callerInfo)1111 int32_t DistributedSchedService::GetCallerInfo(const std::string &localDeviceId, int32_t callerUid,
1112 uint32_t accessToken, CallerInfo &callerInfo)
1113 {
1114 callerInfo.sourceDeviceId = localDeviceId;
1115 callerInfo.uid = callerUid;
1116 callerInfo.accessToken = accessToken;
1117 if (!BundleManagerInternal::GetCallerAppIdFromBms(callerInfo.uid, callerInfo.callerAppId)) {
1118 HILOGE("GetCallerAppIdFromBms failed");
1119 return INVALID_PARAMETERS_ERR;
1120 }
1121 if (!BundleManagerInternal::GetBundleNameListFromBms(callerInfo.uid, callerInfo.bundleNames)) {
1122 HILOGE("GetBundleNameListFromBms failed");
1123 return INVALID_PARAMETERS_ERR;
1124 }
1125 callerInfo.extraInfoJson[DMS_VERSION_ID] = DMS_VERSION;
1126 return ERR_OK;
1127 }
1128
StartRemoteAbility(const OHOS::AAFwk::Want & want,int32_t callerUid,int32_t requestCode,uint32_t accessToken)1129 int32_t DistributedSchedService::StartRemoteAbility(const OHOS::AAFwk::Want& want,
1130 int32_t callerUid, int32_t requestCode, uint32_t accessToken)
1131 {
1132 if (!MultiUserManager::GetInstance().IsCallerForeground(callerUid)) {
1133 HILOGW("The current user is not foreground. callingUid: %{public}d .", callerUid);
1134 return DMS_NOT_FOREGROUND_USER;
1135 }
1136 std::string localDeviceId;
1137 std::string deviceId = want.GetElement().GetDeviceID();
1138 if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) {
1139 HILOGE("check deviceId failed");
1140 return INVALID_PARAMETERS_ERR;
1141 }
1142 #ifdef DMSFWK_INTERACTIVE_ADAPTER
1143 if (CheckRemoteOsType(deviceId)) {
1144 return StartRemoteAbilityAdapter(want, callerUid, requestCode, accessToken);
1145 }
1146 #endif // DMSFWK_INTERACTIVE_ADAPTER
1147
1148 sptr<IDistributedSched> remoteDms = GetRemoteDms(deviceId);
1149 if (remoteDms == nullptr) {
1150 HILOGE("get remoteDms failed");
1151 return INVALID_PARAMETERS_ERR;
1152 }
1153
1154 CallerInfo callerInfo;
1155 int32_t ret = GetCallerInfo(localDeviceId, callerUid, accessToken, callerInfo);
1156 if (ret != ERR_OK) {
1157 return ret;
1158 }
1159 AccountInfo accountInfo;
1160 ret = DistributedSchedPermission::GetInstance().GetAccountInfo(deviceId, callerInfo, accountInfo);
1161 if (ret != ERR_OK) {
1162 return ret;
1163 }
1164 AAFwk::Want* newWant = const_cast<Want*>(&want);
1165 newWant->SetParam(DMS_SRC_NETWORK_ID, localDeviceId);
1166 newWant->SetParam(DMS_SRC_BUNDLE_NAMES, callerInfo.bundleNames);
1167 AppExecFwk::AbilityInfo abilityInfo;
1168 HILOGI("[PerformanceTest] StartRemoteAbility transact begin");
1169 if (!DmsContinueTime::GetInstance().GetPull()) {
1170 int64_t begin = GetTickCount();
1171 DmsContinueTime::GetInstance().SetDurationBegin(DMSDURATION_SRCTODSTRPCTIME, begin);
1172 }
1173 int32_t result = remoteDms->StartAbilityFromRemote(*newWant, abilityInfo, requestCode, callerInfo, accountInfo);
1174 if (!DmsContinueTime::GetInstance().GetPull()) {
1175 int64_t end = GetTickCount();
1176 DmsContinueTime::GetInstance().SetDurationBegin(DMSDURATION_STARTABILITY, end);
1177 DmsContinueTime::GetInstance().SetDurationEnd(DMSDURATION_SRCTODSTRPCTIME, end);
1178 }
1179 HILOGI("[PerformanceTest] StartRemoteAbility transact end");
1180 return result;
1181 }
1182
StartAbilityFromRemote(const OHOS::AAFwk::Want & want,const OHOS::AppExecFwk::AbilityInfo & abilityInfo,int32_t requestCode,const CallerInfo & callerInfo,const AccountInfo & accountInfo)1183 int32_t DistributedSchedService::StartAbilityFromRemote(const OHOS::AAFwk::Want& want,
1184 const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode,
1185 const CallerInfo& callerInfo, const AccountInfo& accountInfo)
1186 {
1187 std::string localDeviceId;
1188 std::string timeInfo;
1189 std::string deviceId = want.GetElement().GetDeviceID();
1190 if (!GetLocalDeviceId(localDeviceId) ||
1191 !CheckDeviceIdFromRemote(localDeviceId, deviceId, callerInfo.sourceDeviceId)) {
1192 HILOGE("check deviceId failed");
1193 return INVALID_REMOTE_PARAMETERS_ERR;
1194 }
1195 if (DmsContinueTime::GetInstance().GetPull()) {
1196 timeInfo = want.GetStringParam(DMSDURATION_SAVETIME);
1197 DmsContinueTime::GetInstance().ReadDurationInfo(timeInfo.c_str());
1198 DmsContinueTime::GetInstance().SetSrcBundleName(want.GetElement().GetBundleName());
1199 DmsContinueTime::GetInstance().SetSrcAbilityName(want.GetElement().GetAbilityName());
1200 }
1201 int32_t result = CheckTargetPermission(want, callerInfo, accountInfo, START_PERMISSION, true);
1202 if (result != ERR_OK) {
1203 HILOGE("CheckTargetPermission failed!!");
1204 return result;
1205 }
1206
1207 return StartAbility(want, requestCode);
1208 }
1209
SendResultFromRemote(OHOS::AAFwk::Want & want,int32_t requestCode,const CallerInfo & callerInfo,const AccountInfo & accountInfo,int32_t resultCode)1210 int32_t DistributedSchedService::SendResultFromRemote(OHOS::AAFwk::Want& want, int32_t requestCode,
1211 const CallerInfo& callerInfo, const AccountInfo& accountInfo, int32_t resultCode)
1212 {
1213 std::string localDeviceId;
1214 std::string deviceId = want.GetStringParam(DMS_SRC_NETWORK_ID);
1215 want.RemoveParam(DMS_SRC_NETWORK_ID);
1216 if (!GetLocalDeviceId(localDeviceId) ||
1217 !CheckDeviceIdFromRemote(localDeviceId, deviceId, callerInfo.sourceDeviceId)) {
1218 HILOGE("check deviceId failed");
1219 return INVALID_REMOTE_PARAMETERS_ERR;
1220 }
1221 if (want.GetElement().GetBundleName().empty() && want.GetElement().GetAbilityName().empty()) {
1222 HILOGW("Remote died abnormal");
1223 int32_t missionId = want.GetIntParam(DMS_MISSION_ID, DEFAULT_DMS_MISSION_ID);
1224 ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->Connect();
1225 if (ret != ERR_OK) {
1226 HILOGE("connect ability server failed %{public}d", ret);
1227 return ret;
1228 }
1229 MissionInfo missionInfo;
1230 ret = AAFwk::AbilityManagerClient::GetInstance()->GetMissionInfo("", missionId, missionInfo);
1231 if (ret != ERR_OK) {
1232 HILOGE("SendResult failed %{public}d", ret);
1233 return ret;
1234 }
1235 std::string bundleName = missionInfo.want.GetElement().GetBundleName();
1236 std::string abilityName = missionInfo.want.GetElement().GetAbilityName();
1237 HILOGD("bundlename: %{public}s, ability is %{public}s", bundleName.c_str(), abilityName.c_str());
1238 ElementName element{"", bundleName, abilityName};
1239 want.SetElement(element);
1240 }
1241 int32_t result = CheckTargetPermission(want, callerInfo, accountInfo, SEND_RESULT_PERMISSION, false);
1242 if (result != ERR_OK) {
1243 HILOGE("CheckTargetPermission failed!!");
1244 return result;
1245 }
1246 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->Connect();
1247 if (err != ERR_OK) {
1248 HILOGE("connect ability server failed %{public}d", err);
1249 return err;
1250 }
1251 err = AAFwk::AbilityManagerClient::GetInstance()->SendResultToAbility(requestCode, resultCode, want);
1252 if (err != ERR_OK) {
1253 HILOGE("SendResult failed %{public}d", err);
1254 }
1255 return err;
1256 }
1257
RemoveContinuationTimeout(int32_t missionId)1258 void DistributedSchedService::RemoveContinuationTimeout(int32_t missionId)
1259 {
1260 if (dschedContinuation_ == nullptr) {
1261 HILOGE("continuation object null!");
1262 return;
1263 }
1264 dschedContinuation_->RemoveTimeOut(missionId);
1265 }
1266
SetContinuationTimeout(int32_t missionId,int32_t timeout)1267 void DistributedSchedService::SetContinuationTimeout(int32_t missionId, int32_t timeout)
1268 {
1269 if (dschedContinuation_ == nullptr) {
1270 HILOGE("continuation object null!");
1271 return;
1272 }
1273 dschedContinuation_->SetTimeOut(missionId, timeout);
1274 }
1275
GetContinuaitonDevice(int32_t missionId)1276 std::string DistributedSchedService::GetContinuaitonDevice(int32_t missionId)
1277 {
1278 if (dschedContinuation_ == nullptr) {
1279 HILOGE("continuation object null!");
1280 return "";
1281 }
1282 return dschedContinuation_->GetTargetDevice(missionId);
1283 }
1284
ContinueLocalMissionDealFreeInstall(OHOS::AAFwk::Want & want,int32_t missionId,const std::string & dstDeviceId,const sptr<IRemoteObject> & callback)1285 int32_t DistributedSchedService::ContinueLocalMissionDealFreeInstall(OHOS::AAFwk::Want& want, int32_t missionId,
1286 const std::string& dstDeviceId, const sptr<IRemoteObject>& callback)
1287 {
1288 bool isFreeInstall = want.GetBoolParam("isFreeInstall", false);
1289 if (!isFreeInstall) {
1290 HILOGE("remote not installed but support freeInstall, try again with freeInstall flag");
1291 return CONTINUE_REMOTE_UNINSTALLED_SUPPORT_FREEINSTALL;
1292 }
1293
1294 if (dschedContinuation_ == nullptr) {
1295 HILOGE("continuation object null!");
1296 return INVALID_PARAMETERS_ERR;
1297 }
1298 dschedContinuation_->PushCallback(missionId, callback, dstDeviceId, true);
1299 SetContinuationTimeout(missionId, CHECK_REMOTE_INSTALL_ABILITY);
1300
1301 want.SetDeviceId(dstDeviceId);
1302 if (!BundleManagerInternal::CheckIfRemoteCanInstall(want, missionId)) {
1303 HILOGE("call CheckIfRemoteCanInstall failed");
1304 RemoveContinuationTimeout(missionId);
1305 dschedContinuation_->PopCallback(missionId);
1306 return INVALID_PARAMETERS_ERR;
1307 }
1308 return ERR_OK;
1309 }
1310
ContinueLocalMission(const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callback,const OHOS::AAFwk::WantParams & wantParams)1311 int32_t DistributedSchedService::ContinueLocalMission(const std::string& dstDeviceId, int32_t missionId,
1312 const sptr<IRemoteObject>& callback, const OHOS::AAFwk::WantParams& wantParams)
1313 {
1314 if (!dataShareManager.IsCurrentContinueSwitchOn()) {
1315 HILOGE("ContinueSwitch status is off");
1316 return DMS_PERMISSION_DENIED;
1317 }
1318 if (dschedContinuation_ == nullptr) {
1319 HILOGE("continuation object null!");
1320 return INVALID_PARAMETERS_ERR;
1321 }
1322 if (dschedContinuation_->IsInContinuationProgress(missionId)) {
1323 HILOGE("ContinueLocalMission already in progress!");
1324 return CONTINUE_ALREADY_IN_PROGRESS;
1325 }
1326 DmsVersion thresholdDmsVersion = {3, 2, 0};
1327 if (DmsVersionManager::IsRemoteDmsVersionLower(dstDeviceId, thresholdDmsVersion)) {
1328 HILOGI("remote dms is low version");
1329 return ContinueAbilityWithTimeout(dstDeviceId, missionId, callback);
1330 }
1331
1332 MissionInfo missionInfo;
1333 int32_t result = AbilityManagerClient::GetInstance()->GetMissionInfo("", missionId, missionInfo);
1334 if (result != ERR_OK) {
1335 HILOGE("get missionInfo failed");
1336 return NO_MISSION_INFO_FOR_MISSION_ID;
1337 }
1338 if (missionInfo.continueState != AAFwk::ContinueState::CONTINUESTATE_ACTIVE) {
1339 HILOGE("Mission continue state set to INACTIVE. Can't continue. Mission id: %{public}d", missionId);
1340 return INVALID_PARAMETERS_ERR;
1341 }
1342 std::string bundleName = missionInfo.want.GetBundle();
1343 if (DmsKvSyncE2E::GetInstance()->CheckMDMCtrlRule(bundleName)) {
1344 HILOGI("Current user is under MDM control.");
1345 return REMOTE_DEVICE_BIND_ABILITY_ERR;
1346 }
1347 missionInfo.want.SetParams(wantParams);
1348 DistributedBundleInfo remoteBundleInfo;
1349 result = BundleManagerInternal::CheckRemoteBundleInfoForContinuation(dstDeviceId,
1350 bundleName, remoteBundleInfo);
1351 if (result == ERR_OK) {
1352 return ContinueAbilityWithTimeout(dstDeviceId, missionId, callback, remoteBundleInfo.versionCode);
1353 }
1354 if (result == CONTINUE_REMOTE_UNINSTALLED_UNSUPPORT_FREEINSTALL) {
1355 HILOGE("remote not installed and app not support free install");
1356 return result;
1357 }
1358
1359 return ContinueLocalMissionDealFreeInstall(missionInfo.want, missionId, dstDeviceId, callback);
1360 }
1361
ContinueAbilityWithTimeout(const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callback,uint32_t remoteBundleVersion)1362 int32_t DistributedSchedService::ContinueAbilityWithTimeout(const std::string& dstDeviceId, int32_t missionId,
1363 const sptr<IRemoteObject>& callback, uint32_t remoteBundleVersion)
1364 {
1365 if (dschedContinuation_ == nullptr) {
1366 HILOGE("continuation object null!");
1367 return INVALID_PARAMETERS_ERR;
1368 }
1369 bool isPushSucceed = dschedContinuation_->PushCallback(missionId, callback, dstDeviceId, false);
1370 if (!isPushSucceed) {
1371 HILOGE("Callback already in progress!");
1372 return CONTINUE_ALREADY_IN_PROGRESS;
1373 }
1374 SetContinuationTimeout(missionId, CONTINUATION_TIMEOUT);
1375 int64_t saveDataBegin = GetTickCount();
1376 DmsContinueTime::GetInstance().SetSaveDataDurationBegin(saveDataBegin);
1377 DmsRadar::GetInstance().SaveDataDmsContinue("ContinueAbility", ERR_OK);
1378 int32_t result = AbilityManagerClient::GetInstance()->ContinueAbility(dstDeviceId, missionId, remoteBundleVersion);
1379 HILOGI("result: %{public}d!", result);
1380 if (result == ERR_INVALID_VALUE) {
1381 return MISSION_FOR_CONTINUING_IS_NOT_ALIVE;
1382 }
1383 return result;
1384 }
1385
ContinueRemoteMission(const std::string & srcDeviceId,const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callback,const OHOS::AAFwk::WantParams & wantParams)1386 int32_t DistributedSchedService::ContinueRemoteMission(const std::string& srcDeviceId, const std::string& dstDeviceId,
1387 int32_t missionId, const sptr<IRemoteObject>& callback, const OHOS::AAFwk::WantParams& wantParams)
1388 {
1389 if (!dataShareManager.IsCurrentContinueSwitchOn()) {
1390 HILOGE("ContinueSwitch status is off");
1391 return DMS_PERMISSION_DENIED;
1392 }
1393 sptr<IDistributedSched> remoteDms = GetRemoteDms(srcDeviceId);
1394 if (remoteDms == nullptr) {
1395 HILOGE("get remote dms null!");
1396 return INVALID_REMOTE_PARAMETERS_ERR;
1397 }
1398
1399 MissionInfo missionInfo;
1400 int32_t ret = AAFwk::AbilityManagerClient::GetInstance()->GetMissionInfo("", missionId, missionInfo);
1401 if (ret != ERR_OK) {
1402 HILOGE("GeGetMissionInfo failed %{public}d", ret);
1403 return ret;
1404 }
1405 std::string bundleName = missionInfo.want.GetElement().GetBundleName();
1406 std::string abilityName = missionInfo.want.GetElement().GetAbilityName();
1407 HILOGD("bundlename: %{public}s, ability is %{public}s", bundleName.c_str(), abilityName.c_str());
1408 DmsUE::GetInstance().TriggerDmsContinue(bundleName, abilityName, srcDeviceId, ERR_OK);
1409
1410 std::string peerUdid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUdidByNetworkId(srcDeviceId);
1411 DmsRadar::GetInstance().ClickIconDmsContinue("ContinueMission", ERR_OK, peerUdid, bundleName, bundleName);
1412 int32_t result = remoteDms->ContinueMission(srcDeviceId, dstDeviceId, missionId, callback, wantParams);
1413 HILOGI("ContinueRemoteMission result: %{public}d!", result);
1414 return result;
1415 }
1416
ContinueRemoteMission(const std::string & srcDeviceId,const std::string & dstDeviceId,const std::string & bundleName,const sptr<IRemoteObject> & callback,const OHOS::AAFwk::WantParams & wantParams)1417 int32_t DistributedSchedService::ContinueRemoteMission(const std::string& srcDeviceId, const std::string& dstDeviceId,
1418 const std::string& bundleName, const sptr<IRemoteObject>& callback, const OHOS::AAFwk::WantParams& wantParams)
1419 {
1420 HILOGI("ContinueRemoteMission srcDeviceId: %{public}s. dstDeviceId: %{public}s. bundleName: %{public}s.",
1421 GetAnonymStr(srcDeviceId).c_str(), GetAnonymStr(dstDeviceId).c_str(), bundleName.c_str());
1422 if (DmsContinueTime::GetInstance().GetPull()) {
1423 int64_t begin = GetTickCount();
1424 DmsContinueTime::GetInstance().SetDurationBegin(DMSDURATION_DSTTOSRCRPCTIME, begin);
1425 DmsContinueTime::GetInstance().SetDurationBegin(DMSDURATION_TOTALTIME, begin);
1426 }
1427
1428 sptr<IDistributedSched> remoteDms = GetRemoteDms(srcDeviceId);
1429 if (remoteDms == nullptr) {
1430 HILOGE("get remote dms null!");
1431 if (dschedContinuation_ == nullptr) {
1432 HILOGE("continuation object null!");
1433 return INVALID_PARAMETERS_ERR;
1434 }
1435 int32_t dSchedEventresult = dschedContinuation_->NotifyDSchedEventResult(INVALID_REMOTE_PARAMETERS_ERR);
1436 HILOGD("NotifyDSchedEventResult result:%{public}d", dSchedEventresult);
1437 return INVALID_REMOTE_PARAMETERS_ERR;
1438 }
1439 int32_t result = remoteDms->ContinueMission(srcDeviceId, dstDeviceId, bundleName, callback, wantParams);
1440 HILOGI("ContinueRemoteMission result: %{public}d!", result);
1441 if (DmsContinueTime::GetInstance().GetPull()) {
1442 int64_t end = GetTickCount();
1443 DmsContinueTime::GetInstance().SetDurationEnd(DMSDURATION_DSTTOSRCRPCTIME, end);
1444 }
1445 if (result != ERR_OK) {
1446 if (dschedContinuation_ == nullptr) {
1447 HILOGE("continuation object null!");
1448 return INVALID_PARAMETERS_ERR;
1449 }
1450 int32_t dSchedEventresult = dschedContinuation_->NotifyDSchedEventResult(result);
1451 HILOGD("NotifyDSchedEventResult result:%{public}d", dSchedEventresult);
1452 }
1453 return result;
1454 }
1455
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callback,const OHOS::AAFwk::WantParams & wantParams)1456 int32_t DistributedSchedService::ContinueMission(const std::string& srcDeviceId, const std::string& dstDeviceId,
1457 int32_t missionId, const sptr<IRemoteObject>& callback, const OHOS::AAFwk::WantParams& wantParams)
1458 {
1459 HILOGI("ContinueMission called");
1460 OHOS::AAFwk::WantParams originWantParams = wantParams;
1461 if (originWantParams.HasParam(DMS_CALLING_UID)) {
1462 originWantParams.Remove(DMS_CALLING_UID);
1463 }
1464 if (srcDeviceId.empty() || dstDeviceId.empty() || callback == nullptr) {
1465 HILOGE("srcDeviceId or dstDeviceId or callback is null!");
1466 return INVALID_PARAMETERS_ERR;
1467 }
1468 std::string localDevId;
1469 if (!GetLocalDeviceId(localDevId)) {
1470 HILOGE("get local deviceId failed!");
1471 return INVALID_PARAMETERS_ERR;
1472 }
1473 DurationStart(srcDeviceId, dstDeviceId);
1474
1475 if (srcDeviceId == localDevId) {
1476 if (DtbschedmgrDeviceInfoStorage::GetInstance().GetDeviceInfoById(dstDeviceId) == nullptr) {
1477 HILOGE("GetDeviceInfoById failed, dstDeviceId: %{public}s.", GetAnonymStr(dstDeviceId).c_str());
1478 return INVALID_REMOTE_PARAMETERS_ERR;
1479 }
1480 return ContinueLocalMission(dstDeviceId, missionId, callback, originWantParams);
1481 } else if (dstDeviceId == localDevId) {
1482 DmsContinueTime::GetInstance().SetPull(true);
1483 if (DtbschedmgrDeviceInfoStorage::GetInstance().GetDeviceInfoById(srcDeviceId) == nullptr) {
1484 HILOGE("GetDeviceInfoById failed, srcDeviceId: %{public}s.", GetAnonymStr(srcDeviceId).c_str());
1485 return INVALID_REMOTE_PARAMETERS_ERR;
1486 }
1487 return ContinueRemoteMission(srcDeviceId, dstDeviceId, missionId, callback, originWantParams);
1488 } else {
1489 HILOGE("source or target device must be local!");
1490 return OPERATION_DEVICE_NOT_INITIATOR_OR_TARGET;
1491 }
1492 }
1493
ProcessContinueLocalMission(const std::string & srcDeviceId,const std::string & dstDeviceId,const std::string & bundleName,const sptr<IRemoteObject> & callback,const OHOS::AAFwk::WantParams & wantParams)1494 int32_t DistributedSchedService::ProcessContinueLocalMission(const std::string& srcDeviceId,
1495 const std::string& dstDeviceId, const std::string& bundleName, const sptr<IRemoteObject>& callback,
1496 const OHOS::AAFwk::WantParams& wantParams)
1497 {
1498 HILOGI("ProcessContinueLocalMission called.");
1499 if (DtbschedmgrDeviceInfoStorage::GetInstance().GetDeviceInfoById(dstDeviceId) == nullptr) {
1500 HILOGE("GetDeviceInfoById failed, dstDeviceId: %{public}s.", GetAnonymStr(dstDeviceId).c_str());
1501 return INVALID_REMOTE_PARAMETERS_ERR;
1502 }
1503
1504 int32_t missionId = 1;
1505 #ifdef SUPPORT_DISTRIBUTED_MISSION_MANAGER
1506 auto sendMgr = MultiUserManager::GetInstance().GetCurrentSendMgr();
1507 if (sendMgr == nullptr) {
1508 HILOGI("GetSendMgr failed.");
1509 return DMS_NOT_GET_MANAGER;
1510 }
1511 int32_t currentAccountId = MultiUserManager::GetInstance().GetForegroundUser();
1512 int32_t ret =
1513 DmsContinueConditionMgr::GetInstance().GetMissionIdByBundleName(currentAccountId, bundleName, missionId);
1514 if (ret != ERR_OK) {
1515 HILOGE("get missionId failed");
1516 return ret;
1517 }
1518 #endif
1519
1520 if (dschedContinuation_ == nullptr) {
1521 HILOGE("continuation object null!");
1522 return INVALID_PARAMETERS_ERR;
1523 }
1524 dschedContinuation_->continueEvent_.srcNetworkId_ = srcDeviceId;
1525 dschedContinuation_->continueEvent_.dstNetworkId_ = dstDeviceId;
1526 return ContinueLocalMission(dstDeviceId, missionId, callback, wantParams);
1527 }
1528
ProcessContinueRemoteMission(const std::string & srcDeviceId,const std::string & dstDeviceId,const std::string & bundleName,const sptr<IRemoteObject> & callback,const OHOS::AAFwk::WantParams & wantParams)1529 int32_t DistributedSchedService::ProcessContinueRemoteMission(const std::string& srcDeviceId,
1530 const std::string& dstDeviceId, const std::string& bundleName, const sptr<IRemoteObject>& callback,
1531 const OHOS::AAFwk::WantParams& wantParams)
1532 {
1533 HILOGI("ProcessContinueRemoteMission start.");
1534 if (DtbschedmgrDeviceInfoStorage::GetInstance().GetDeviceInfoById(srcDeviceId) == nullptr) {
1535 HILOGE("GetDeviceInfoById failed, srcDeviceId: %{public}s.", GetAnonymStr(srcDeviceId).c_str());
1536 return INVALID_REMOTE_PARAMETERS_ERR;
1537 }
1538 if (dschedContinuation_ == nullptr) {
1539 HILOGE("continuation object null!");
1540 return INVALID_PARAMETERS_ERR;
1541 }
1542 dschedContinuation_->continueEvent_.srcNetworkId_ = dstDeviceId;
1543 dschedContinuation_->continueEvent_.dstNetworkId_ = srcDeviceId;
1544 HILOGI("ProcessContinueRemoteMission end.");
1545 return ContinueRemoteMission(srcDeviceId, dstDeviceId, bundleName, callback, wantParams);
1546 }
1547
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,const std::string & bundleName,const sptr<IRemoteObject> & callback,const OHOS::AAFwk::WantParams & wantParams)1548 int32_t DistributedSchedService::ContinueMission(const std::string& srcDeviceId, const std::string& dstDeviceId,
1549 const std::string& bundleName, const sptr<IRemoteObject>& callback, const OHOS::AAFwk::WantParams& wantParams)
1550 {
1551 OHOS::AAFwk::WantParams originWantParams = wantParams;
1552 if (originWantParams.HasParam(DMS_CALLING_UID)) {
1553 originWantParams.Remove(DMS_CALLING_UID);
1554 }
1555 HILOGI("ContinueMission srcDeviceId: %{public}s. dstDeviceId: %{public}s. bundleName: %{public}s.",
1556 GetAnonymStr(srcDeviceId).c_str(), GetAnonymStr(dstDeviceId).c_str(), bundleName.c_str());
1557 if (srcDeviceId.empty() || dstDeviceId.empty() || callback == nullptr) {
1558 HILOGE("srcDeviceId or dstDeviceId or callback is null!");
1559 return INVALID_PARAMETERS_ERR;
1560 }
1561 std::string localDevId;
1562 if (!GetLocalDeviceId(localDevId)) {
1563 HILOGE("get local deviceId failed!");
1564 return INVALID_PARAMETERS_ERR;
1565 }
1566 DurationStart(srcDeviceId, dstDeviceId);
1567
1568 if (srcDeviceId == localDevId) {
1569 return ProcessContinueLocalMission(srcDeviceId, dstDeviceId, bundleName, callback, originWantParams);
1570 } else if (dstDeviceId == localDevId) {
1571 DmsContinueTime::GetInstance().SetPull(true);
1572 return ProcessContinueRemoteMission(srcDeviceId, dstDeviceId, bundleName, callback, originWantParams);
1573 } else {
1574 HILOGE("source or target device must be local!");
1575 return OPERATION_DEVICE_NOT_INITIATOR_OR_TARGET;
1576 }
1577 }
1578
SetWantForContinuation(AAFwk::Want & newWant,int32_t missionId)1579 int32_t DistributedSchedService::SetWantForContinuation(AAFwk::Want& newWant, int32_t missionId)
1580 {
1581 std::string devId;
1582 if (!GetLocalDeviceId(devId)) {
1583 HILOGE("StartContinuation get local deviceId failed!");
1584 return INVALID_REMOTE_PARAMETERS_ERR;
1585 }
1586
1587 newWant.SetParam("sessionId", missionId);
1588 newWant.SetParam("deviceId", devId);
1589 std::string strInfo = DmsContinueTime::GetInstance().WriteDurationInfo(
1590 DmsContinueTime::GetInstance().GetSaveDataDuration());
1591 newWant.SetParam(DMSDURATION_SAVETIME, strInfo);
1592 BundleInfo localBundleInfo;
1593 if (BundleManagerInternal::GetLocalBundleInfo(newWant.GetBundle(), localBundleInfo) != ERR_OK) {
1594 HILOGE("get local bundle info failed");
1595 return INVALID_PARAMETERS_ERR;
1596 }
1597 newWant.SetParam(VERSION_CODE_KEY, static_cast<int32_t>(localBundleInfo.versionCode));
1598
1599 bool isPageStackContinue = newWant.GetBoolParam(SUPPORT_CONTINUE_PAGE_STACK_KEY, true);
1600 std::string moduleName = newWant.GetStringParam(SUPPORT_CONTINUE_MODULE_NAME_UPDATE_KEY);
1601 if (!isPageStackContinue && !moduleName.empty() && moduleName.length() <= MAX_MODULENAME_LEN) {
1602 HILOGD("set application moduleName = %{private}s!", moduleName.c_str());
1603 OHOS::AppExecFwk::ElementName element = newWant.GetElement();
1604 newWant.SetElementName(element.GetDeviceID(), element.GetBundleName(), element.GetAbilityName(), moduleName);
1605 }
1606 HILOGD("local version = %{public}u!", localBundleInfo.versionCode);
1607 return ERR_OK;
1608 }
1609
DealDSchedEventResult(const OHOS::AAFwk::Want & want,int32_t status)1610 int32_t DistributedSchedService::DealDSchedEventResult(const OHOS::AAFwk::Want& want, int32_t status)
1611 {
1612 if (dschedContinuation_ == nullptr) {
1613 HILOGE("continuation object null!");
1614 return INVALID_PARAMETERS_ERR;
1615 }
1616 DmsContinueTime::GetInstance().SetSrcBundleName(want.GetElement().GetBundleName());
1617 DmsContinueTime::GetInstance().SetSrcAbilityName(dschedContinuation_->continueEvent_.srcAbilityName_);
1618 if (status != ERR_OK) {
1619 HILOGD("want deviceId result:%{public}s", GetAnonymStr(want.GetElement().GetDeviceID()).c_str());
1620 std::string deviceId = want.GetElement().GetDeviceID();
1621 sptr<IDistributedSched> remoteDms = GetRemoteDms(deviceId);
1622 if (remoteDms == nullptr) {
1623 HILOGE("NotifyCompleteContinuation get remote dms null!");
1624 return INVALID_REMOTE_PARAMETERS_ERR;
1625 }
1626 int dSchedEventresult = remoteDms->NotifyDSchedEventResultFromRemote(DSCHED_EVENT_KEY, status);
1627 HILOGI("NotifyDSchedEventResultFromRemote result:%{public}d", dSchedEventresult);
1628 }
1629 return ERR_OK;
1630 }
1631
GetIsFreeInstall(int32_t missionId)1632 bool DistributedSchedService::GetIsFreeInstall(int32_t missionId)
1633 {
1634 if (dschedContinuation_ == nullptr) {
1635 return false;
1636 }
1637 return dschedContinuation_->IsFreeInstall(missionId);
1638 }
1639
StartContinuation(const OHOS::AAFwk::Want & want,int32_t missionId,int32_t callerUid,int32_t status,uint32_t accessToken)1640 int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want, int32_t missionId,
1641 int32_t callerUid, int32_t status, uint32_t accessToken)
1642 {
1643 HILOGD("[PerformanceTest] StartContinuation begin");
1644 DealDSchedEventResult(want, status);
1645 if (status != ERR_OK) {
1646 HILOGE("continuation has been rejected, status: %{public}d", status);
1647 NotifyContinuationCallbackResult(missionId, status);
1648 return INVALID_REMOTE_PARAMETERS_ERR;
1649 }
1650 auto flags = want.GetFlags();
1651 if ((flags & AAFwk::Want::FLAG_ABILITY_CONTINUATION) == 0) {
1652 HILOGE("StartContinuation want continuation flags invalid!");
1653 return INVALID_REMOTE_PARAMETERS_ERR;
1654 }
1655 HILOGD("StartContinuation: devId = %{private}s, bundleName = %{private}s, abilityName = %{private}s",
1656 GetAnonymStr(want.GetElement().GetDeviceID()).c_str(), want.GetElement().GetBundleName().c_str(),
1657 want.GetElement().GetAbilityName().c_str());
1658 if (dschedContinuation_ == nullptr) {
1659 HILOGE("StartContinuation continuation object null!");
1660 return INVALID_REMOTE_PARAMETERS_ERR;
1661 }
1662 if (!dschedContinuation_->IsInContinuationProgress(missionId)) {
1663 dschedContinuation_->SetTimeOut(missionId, CONTINUATION_TIMEOUT);
1664 }
1665 AAFwk::Want newWant = want;
1666 int result = SetWantForContinuation(newWant, missionId);
1667 if (result != ERR_OK) {
1668 HILOGE("set new want failed");
1669 return result;
1670 }
1671 bool flag = GetIsFreeInstall(missionId);
1672 SetCleanMissionFlag(want, missionId);
1673 if (flag) {
1674 result = StartRemoteFreeInstall(newWant, callerUid, DEFAULT_REQUEST_CODE, accessToken, nullptr);
1675 if (result != ERR_OK) {
1676 HILOGE("continue free install failed, result = %{public}d", result);
1677 return result;
1678 }
1679 } else {
1680 result = StartRemoteAbility(newWant, callerUid, DEFAULT_REQUEST_CODE, accessToken);
1681 DmsRadar::GetInstance().SaveDataDmsRemoteWant("StartRemoteAbility", result);
1682 if (result != ERR_OK) {
1683 HILOGE("continue ability failed, errorCode = %{public}d", result);
1684 return result;
1685 }
1686 }
1687 HILOGD("[PerformanceTest] StartContinuation end");
1688 return result;
1689 }
1690
NotifyCompleteContinuation(const std::u16string & devId,int32_t sessionId,bool isSuccess)1691 void DistributedSchedService::NotifyCompleteContinuation(const std::u16string& devId,
1692 int32_t sessionId, bool isSuccess)
1693 {
1694 if (!isSuccess) {
1695 HILOGE("NotifyCompleteContinuation failed!");
1696 }
1697 if (sessionId <= 0) {
1698 HILOGE("NotifyCompleteContinuation sessionId invalid!");
1699 return;
1700 }
1701 std::string deviceId = Str16ToStr8(devId);
1702 sptr<IDistributedSched> remoteDms = GetRemoteDms(deviceId);
1703 if (remoteDms == nullptr) {
1704 HILOGE("NotifyCompleteContinuation get remote dms null!");
1705 return;
1706 }
1707 if (dschedContinuation_ == nullptr) {
1708 HILOGE("continuation object null!");
1709 return;
1710 }
1711 int dSchedEventResult = dschedContinuation_->NotifyDSchedEventResult(ERR_OK);
1712 HILOGD("NotifyDSchedEventResult result:%{public}d", dSchedEventResult);
1713
1714 std::string dstInfo("");
1715 if (DmsContinueTime::GetInstance().GetPull()) {
1716 int64_t end = GetTickCount();
1717 std::string strEndTime = DmsContinueTime::GetInstance().GetCurrentTime();
1718 DmsContinueTime::GetInstance().SetDurationEnd(DMSDURATION_STARTABILITY, end);
1719 DmsContinueTime::GetInstance().SetDurationEnd(DMSDURATION_TOTALTIME, end);
1720 DmsContinueTime::GetInstance().SetDurationStrTime(DMSDURATION_ENDTIME, strEndTime);
1721
1722 std::string bundleName = DmsContinueTime::GetInstance().GetDstInfo().bundleName;
1723 std::string abilityName = DmsContinueTime::GetInstance().GetDstInfo().abilityName;
1724 std::string srcNetworkId = dschedContinuation_->continueInfo_.srcNetworkId_;
1725 DmsUE::GetInstance().DmsContinueComplete(bundleName, abilityName, srcNetworkId, dSchedEventResult);
1726
1727 DmsContinueTime::GetInstance().AppendInfo();
1728 DmsContinueTime::GetInstance().SetPull(false);
1729 } else {
1730 dstInfo = DmsContinueTime::GetInstance().WriteDstInfo(DmsContinueTime::GetInstance().GetDstInfo().bundleName,
1731 DmsContinueTime::GetInstance().GetDstInfo().abilityName);
1732 }
1733
1734 remoteDms->NotifyContinuationResultFromRemote(sessionId, isSuccess, dstInfo);
1735 dschedContinuation_->continueInfo_.srcNetworkId_ = "";
1736 dschedContinuation_->continueInfo_.dstNetworkId_ = "";
1737 DmsRadar::GetInstance().ClickIconDmsRecvOver("NotifyContinuationResultFromRemote", dSchedEventResult);
1738 }
1739
NotifyContinuationResultFromRemote(int32_t sessionId,bool isSuccess,const std::string dstInfo)1740 int32_t DistributedSchedService::NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess,
1741 const std::string dstInfo)
1742 {
1743 if (sessionId <= 0) {
1744 HILOGE("NotifyContinuationResultFromRemote sessionId:%{public}d invalid!", sessionId);
1745 return INVALID_REMOTE_PARAMETERS_ERR;
1746 }
1747 if (dstInfo.length() != 0) {
1748 int64_t end = GetTickCount();
1749 DmsContinueTime::GetInstance().SetDurationEnd(DMSDURATION_STARTABILITY, end);
1750 std::string strEndTime = DmsContinueTime::GetInstance().GetCurrentTime();
1751 DmsContinueTime::GetInstance().SetDurationStrTime(DMSDURATION_ENDTIME, strEndTime);
1752 DmsContinueTime::GetInstance().ReadDstInfo(dstInfo.c_str());
1753 DmsContinueTime::GetInstance().AppendInfo();
1754 }
1755
1756 int32_t missionId = sessionId;
1757 NotifyContinuationCallbackResult(missionId, isSuccess ? 0 : NOTIFYCOMPLETECONTINUATION_FAILED);
1758 if (dschedContinuation_ == nullptr) {
1759 HILOGW("continuation object null!");
1760 return ERR_OK;
1761 }
1762 dschedContinuation_->continueInfo_.srcNetworkId_ = "";
1763 dschedContinuation_->continueInfo_.dstNetworkId_ = "";
1764 return ERR_OK;
1765 }
1766
NotifyDSchedEventResultFromRemote(const std::string type,int32_t dSchedEventResult)1767 int32_t DistributedSchedService::NotifyDSchedEventResultFromRemote(const std::string type, int32_t dSchedEventResult)
1768 {
1769 NotifyDSchedEventCallbackResult(dSchedEventResult);
1770 return ERR_OK;
1771 }
1772
1773 #ifdef SUPPORT_DISTRIBUTED_FORM_SHARE
1774 // LCOV_EXCL_START
GetFormMgrProxy()1775 sptr<IFormMgr> DistributedSchedService::GetFormMgrProxy()
1776 {
1777 HILOGD("GetFormMgrProxy begin.");
1778 std::lock_guard<std::mutex> lock(formMgrLock_);
1779 if (formMgrProxy_ != nullptr) {
1780 HILOGD("get fms proxy success.");
1781 return formMgrProxy_;
1782 }
1783
1784 auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1785 if (systemAbilityMgr == nullptr) {
1786 HILOGE("system ability manager is nullptr.");
1787 return nullptr;
1788 }
1789
1790 auto remoteObj = systemAbilityMgr->GetSystemAbility(FORM_MGR_SERVICE_ID);
1791 if (remoteObj == nullptr) {
1792 HILOGE("failed to get form manager service");
1793 return nullptr;
1794 }
1795
1796 formMgrDeathRecipient_ = sptr<IRemoteObject::DeathRecipient>(new FormMgrDeathRecipient());
1797 if (formMgrDeathRecipient_ == nullptr) {
1798 HILOGE("failed to create FormMgrDeathRecipient!");
1799 return nullptr;
1800 }
1801
1802 if ((remoteObj->IsProxyObject()) && (!remoteObj->AddDeathRecipient(formMgrDeathRecipient_))) {
1803 HILOGE("add death recipient to FormMgrService failed.");
1804 return nullptr;
1805 }
1806
1807 formMgrProxy_ = iface_cast<IFormMgr>(remoteObj);
1808 return formMgrProxy_;
1809 }
1810
ProcessFormMgrDied(const wptr<IRemoteObject> & remote)1811 void DistributedSchedService::ProcessFormMgrDied(const wptr<IRemoteObject>& remote)
1812 {
1813 std::lock_guard<std::mutex> lock(formMgrLock_);
1814 if (formMgrProxy_ == nullptr) {
1815 return;
1816 }
1817
1818 auto serviceRemote = formMgrProxy_->AsObject();
1819 if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) {
1820 serviceRemote->RemoveDeathRecipient(formMgrDeathRecipient_);
1821 formMgrProxy_ = nullptr;
1822 }
1823 }
1824 // LCOV_EXCL_STOP
1825 #endif
1826
NotifyContinuationCallbackResult(int32_t missionId,int32_t resultCode)1827 void DistributedSchedService::NotifyContinuationCallbackResult(int32_t missionId, int32_t resultCode)
1828 {
1829 HILOGD("Continuation result is: %{public}d", resultCode);
1830
1831 if (dschedContinuation_ == nullptr) {
1832 HILOGE("continuation object null!");
1833 return;
1834 }
1835
1836 int32_t result = 0;
1837 if (dschedContinuation_->IsInContinuationProgress(missionId)) {
1838 if (resultCode == ERR_OK && dschedContinuation_->IsCleanMission(missionId)) {
1839 result = AbilityManagerClient::GetInstance()->CleanMission(missionId);
1840 HILOGD("clean mission result:%{public}d", result);
1841 }
1842 result = dschedContinuation_->NotifyMissionCenterResult(missionId, resultCode);
1843 } else {
1844 result = AbilityManagerClient::GetInstance()->NotifyContinuationResult(missionId, resultCode);
1845 dschedContinuation_->RemoveTimeOut(missionId);
1846 }
1847 HILOGD("NotifyContinuationCallbackResult result:%{public}d", result);
1848 }
1849
NotifyDSchedEventCallbackResult(int32_t resultCode)1850 void DistributedSchedService::NotifyDSchedEventCallbackResult(int32_t resultCode)
1851 {
1852 HILOGD("Continuation result is: %{public}d", resultCode);
1853 if (dschedContinuation_ == nullptr) {
1854 HILOGE("continuation object null!");
1855 return;
1856 }
1857 int dSchedEventresult = dschedContinuation_->NotifyDSchedEventResult(resultCode);
1858 HILOGD("NotifyDSchedEventResult result:%{public}d", dSchedEventresult);
1859 }
1860
NotifyDSchedEventCallbackResult(int32_t resultCode,const EventNotify & event)1861 void DistributedSchedService::NotifyDSchedEventCallbackResult(int32_t resultCode, const EventNotify& event)
1862 {
1863 HILOGD("Continuation result is: %{public}d", resultCode);
1864 switch (event.dSchedEventType_) {
1865 case DMS_CONTINUE:
1866 NotifyContinuateEventResult(resultCode, event);
1867 break;
1868 case DMS_COLLABORATION:
1869 NotifyCollaborateEventResult(resultCode, event);
1870 break;
1871 default:
1872 HILOGE("Event does not carry specific operation type, eventType %{public}d.", event.dSchedEventType_);
1873 return;
1874 }
1875 }
1876
NotifyContinuateEventResult(int32_t resultCode,const EventNotify & event)1877 void DistributedSchedService::NotifyContinuateEventResult(int32_t resultCode, const EventNotify& event)
1878 {
1879 if (dschedContinuation_ == nullptr) {
1880 HILOGE("continuation object null!");
1881 return;
1882 }
1883 dschedContinuation_->continueEvent_ = event;
1884 int dSchedEventresult = dschedContinuation_->NotifyDSchedEventResult(resultCode);
1885 HILOGD("NotifyDSchedEventResult result:%{public}d", dSchedEventresult);
1886 if (event.state_ == DMS_DSCHED_EVENT_FINISH || resultCode != ERR_OK) {
1887 dschedContinuation_->continueEvent_ = EventNotify();
1888 }
1889 }
1890
NotifyCollaborateEventResult(int32_t resultCode,const EventNotify & event)1891 void DistributedSchedService::NotifyCollaborateEventResult(int32_t resultCode, const EventNotify& event)
1892 {
1893 if (collaborateCbMgr_ == nullptr) {
1894 HILOGE("collaborate callback manager is null.");
1895 return;
1896 }
1897 int32_t collaborateEventRet = collaborateCbMgr_->NotifyDSchedEventResult(resultCode, event);
1898 HILOGD("NotifyDSchedEventResult result: %{public}d", collaborateEventRet);
1899 }
1900
NotifyCollaborateEventWithSessions(const std::list<ConnectAbilitySession> & sessionsList,DSchedEventState state,int32_t ret)1901 void DistributedSchedService::NotifyCollaborateEventWithSessions(
1902 const std::list<ConnectAbilitySession> &sessionsList, DSchedEventState state, int32_t ret)
1903 {
1904 for (const auto &session : sessionsList) {
1905 for (const auto &element : session.GetElementsList()) {
1906 EventNotify tempEvent;
1907 GetCurSrcCollaborateEvent(session.GetCallerInfo(), element, state, ret, tempEvent);
1908 NotifyDSchedEventCallbackResult(ret, tempEvent);
1909 }
1910 }
1911 }
1912
GetCurSrcCollaborateEvent(const CallerInfo & callerInfo,const AppExecFwk::ElementName & element,DSchedEventState state,int32_t ret,EventNotify & event)1913 void DistributedSchedService::GetCurSrcCollaborateEvent(const CallerInfo &callerInfo,
1914 const AppExecFwk::ElementName &element, DSchedEventState state, int32_t ret, EventNotify &event)
1915 {
1916 std::string callingBundleName;
1917 if (!BundleManagerInternal::GetSpecifyBundleNameFromBms(callerInfo.uid, callingBundleName)) {
1918 HILOGE("Get specify bundle name for from Bms fail, connect session caller uid %{public}d.", callerInfo.uid);
1919 }
1920
1921 event.eventResult_ = ret;
1922 event.srcNetworkId_ = callerInfo.sourceDeviceId;
1923 event.dstNetworkId_ = element.GetDeviceID();
1924 event.srcBundleName_ = callingBundleName;
1925 event.srcModuleName_ = "";
1926 event.srcAbilityName_ = "";
1927 event.destBundleName_ = element.GetBundleName();
1928 event.destModuleName_ = element.GetModuleName();
1929 event.destAbilityName_ = element.GetAbilityName();
1930 event.dSchedEventType_ = DMS_COLLABORATION;
1931 event.state_ = state;
1932 }
1933
GetCurDestCollaborateEvent(const CallerInfo & callerInfo,const AppExecFwk::ElementName & element,DSchedEventState state,int32_t ret,EventNotify & event)1934 void DistributedSchedService::GetCurDestCollaborateEvent(const CallerInfo &callerInfo,
1935 const AppExecFwk::ElementName &element, DSchedEventState state, int32_t ret, EventNotify &event)
1936 {
1937 std::string callerBundleName;
1938 if (callerInfo.extraInfoJson.find(DMS_UID_SPEC_BUNDLE_NAME) != callerInfo.extraInfoJson.end() &&
1939 callerInfo.extraInfoJson[DMS_UID_SPEC_BUNDLE_NAME].is_string()) {
1940 callerBundleName = callerInfo.extraInfoJson[DMS_UID_SPEC_BUNDLE_NAME];
1941 }
1942
1943 event.eventResult_ = ret;
1944 event.srcNetworkId_ = callerInfo.sourceDeviceId;
1945 event.dstNetworkId_ = element.GetDeviceID();
1946 event.srcBundleName_ = callerBundleName;
1947 event.srcModuleName_ = "";
1948 event.srcAbilityName_ = "";
1949 event.destBundleName_ = element.GetBundleName();
1950 event.destModuleName_ = element.GetModuleName();
1951 event.destAbilityName_ = element.GetAbilityName();
1952 event.dSchedEventType_ = DMS_COLLABORATION;
1953 event.state_ = state;
1954 }
1955
RemoteConnectAbilityMappingLocked(const sptr<IRemoteObject> & connect,const std::string & localDeviceId,const std::string & remoteDeviceId,const AppExecFwk::ElementName & element,const CallerInfo & callerInfo,TargetComponent targetComponent)1956 void DistributedSchedService::RemoteConnectAbilityMappingLocked(const sptr<IRemoteObject>& connect,
1957 const std::string& localDeviceId, const std::string& remoteDeviceId, const AppExecFwk::ElementName& element,
1958 const CallerInfo& callerInfo, TargetComponent targetComponent)
1959 {
1960 if (connect == nullptr) {
1961 return;
1962 }
1963 auto itConnect = distributedConnectAbilityMap_.find(connect);
1964 if (itConnect == distributedConnectAbilityMap_.end()) {
1965 // add uid's connect number
1966 uint32_t number = ++trackingUidMap_[callerInfo.uid];
1967 HILOGD("uid %{public}d has %{public}u connection(s), targetComponent: %{public}d.",
1968 callerInfo.uid, number, targetComponent);
1969 // new connect, add death recipient
1970 connect->AddDeathRecipient(connectDeathRecipient_);
1971 ReportDistributedComponentChange(callerInfo, DISTRIBUTED_COMPONENT_ADD, IDistributedSched::CONNECT,
1972 IDistributedSched::CALLER);
1973 }
1974 auto& sessionsList = distributedConnectAbilityMap_[connect];
1975 for (auto& session : sessionsList) {
1976 if (remoteDeviceId == session.GetDestinationDeviceId()) {
1977 session.AddElement(element);
1978 // already added session for remote device
1979 return;
1980 }
1981 }
1982 // connect to another remote device, add a new session to list
1983 auto& session = sessionsList.emplace_back(localDeviceId, remoteDeviceId, callerInfo, targetComponent);
1984 session.AddElement(element);
1985 HILOGD("add connection success");
1986 }
1987
CheckDistributedConnectLocked(const CallerInfo & callerInfo) const1988 int32_t DistributedSchedService::CheckDistributedConnectLocked(const CallerInfo& callerInfo) const
1989 {
1990 if (callerInfo.uid < 0) {
1991 HILOGE("uid %{public}d is invalid.", callerInfo.uid);
1992 return BIND_ABILITY_UID_INVALID_ERR;
1993 }
1994 auto it = trackingUidMap_.find(callerInfo.uid);
1995 if (it != trackingUidMap_.end() && it->second >= MAX_DISTRIBUTED_CONNECT_NUM) {
1996 HILOGE("uid %{public}d connected too much abilities, it maybe leak.", callerInfo.uid);
1997 return BIND_ABILITY_LEAK_ERR;
1998 }
1999 return ERR_OK;
2000 }
2001
DecreaseConnectLocked(int32_t uid)2002 void DistributedSchedService::DecreaseConnectLocked(int32_t uid)
2003 {
2004 if (uid < 0) {
2005 HILOGE("DecreaseConnectLocked invalid uid %{public}d", uid);
2006 return;
2007 }
2008 auto it = trackingUidMap_.find(uid);
2009 if (it != trackingUidMap_.end()) {
2010 auto& conns = it->second;
2011 if (conns > 0) {
2012 conns--;
2013 }
2014 if (conns == 0) {
2015 HILOGD("DecreaseConnectLocked uid %{public}d connection(s) is 0", uid);
2016 trackingUidMap_.erase(it);
2017 }
2018 }
2019 }
2020
GetUidLocked(const std::list<ConnectAbilitySession> & sessionsList)2021 int32_t DistributedSchedService::GetUidLocked(const std::list<ConnectAbilitySession>& sessionsList)
2022 {
2023 if (!sessionsList.empty()) {
2024 return sessionsList.front().GetCallerInfo().uid;
2025 }
2026 return INVALID_CALLER_UID;
2027 }
2028
ConnectRemoteAbility(const OHOS::AAFwk::Want & want,const sptr<IRemoteObject> & connect,int32_t callerUid,int32_t callerPid,uint32_t accessToken)2029 int32_t DistributedSchedService::ConnectRemoteAbility(const OHOS::AAFwk::Want& want,
2030 const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid, uint32_t accessToken)
2031 {
2032 if (!MultiUserManager::GetInstance().IsCallerForeground(callerUid)) {
2033 HILOGW("The current user is not foreground. callingUid: %{public}d .", callerUid);
2034 return DMS_NOT_FOREGROUND_USER;
2035 }
2036 std::string localDeviceId;
2037 std::string remoteDeviceId = want.GetElement().GetDeviceID();
2038 if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, remoteDeviceId)) {
2039 HILOGE("ConnectRemoteAbility check deviceId failed");
2040 return INVALID_PARAMETERS_ERR;
2041 }
2042
2043 #ifdef DMSFWK_INTERACTIVE_ADAPTER
2044 if (CheckRemoteOsType(remoteDeviceId)) {
2045 return ConnectRemoteAbilityAdapter(want, connect, callerUid, callerPid, accessToken);
2046 }
2047 #endif // DMSFWK_INTERACTIVE_ADAPTER
2048
2049 CallerInfo callerInfo = { callerUid, callerPid, CALLER_TYPE_HARMONY, localDeviceId };
2050 callerInfo.accessToken = accessToken;
2051 {
2052 std::lock_guard<std::mutex> autoLock(distributedLock_);
2053 int32_t checkResult = CheckDistributedConnectLocked(callerInfo);
2054 if (checkResult != ERR_OK) {
2055 return checkResult;
2056 }
2057 }
2058 if (!BundleManagerInternal::GetCallerAppIdFromBms(callerInfo.uid, callerInfo.callerAppId)) {
2059 HILOGE("GetCallerAppIdFromBms failed");
2060 return INVALID_PARAMETERS_ERR;
2061 }
2062 if (!BundleManagerInternal::GetBundleNameListFromBms(callerInfo.uid, callerInfo.bundleNames)) {
2063 HILOGE("GetBundleNameListFromBms failed");
2064 return INVALID_PARAMETERS_ERR;
2065 }
2066 callerInfo.extraInfoJson[DMS_VERSION_ID] = DMS_VERSION;
2067 AAFwk::Want newWant = Want(want);
2068 newWant.SetParam(DMS_SRC_BUNDLE_NAMES, callerInfo.bundleNames);
2069 HILOGI("[PerformanceTest] ConnectRemoteAbility begin");
2070 int32_t result = TryConnectRemoteAbility(newWant, connect, callerInfo);
2071 if (result != ERR_OK) {
2072 HILOGE("ConnectRemoteAbility result is %{public}d", result);
2073 }
2074 HILOGI("[PerformanceTest] ConnectRemoteAbility end");
2075 return result;
2076 }
2077
TryConnectRemoteAbility(const OHOS::AAFwk::Want & want,const sptr<IRemoteObject> & connect,const CallerInfo & callerInfo)2078 int32_t DistributedSchedService::TryConnectRemoteAbility(const OHOS::AAFwk::Want& want,
2079 const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo)
2080 {
2081 AppExecFwk::AbilityInfo abilityInfo;
2082 AccountInfo accountInfo;
2083 std::string remoteDeviceId = want.GetElement().GetDeviceID();
2084 sptr<IDistributedSched> remoteDms = GetRemoteDms(remoteDeviceId);
2085 if (remoteDms == nullptr || connect == nullptr) {
2086 HILOGE("TryConnectRemoteAbility invalid parameters");
2087 return INVALID_PARAMETERS_ERR;
2088 }
2089 int32_t ret = DistributedSchedPermission::GetInstance().GetAccountInfo(remoteDeviceId, callerInfo, accountInfo);
2090 if (ret != ERR_OK) {
2091 HILOGE("GetAccountInfo failed");
2092 return ret;
2093 }
2094 int32_t retryTimes = BIND_CONNECT_RETRY_TIMES;
2095 int32_t result = REMOTE_DEVICE_BIND_ABILITY_ERR;
2096 while (retryTimes--) {
2097 int64_t start = GetTickCount();
2098 HILOGI("[PerformanceTest] ConnectRemoteAbility begin");
2099 result = remoteDms->ConnectAbilityFromRemote(want, abilityInfo, connect, callerInfo, accountInfo);
2100 HILOGI("[PerformanceTest] ConnectRemoteAbility end");
2101 if (result == ERR_OK) {
2102 std::lock_guard<std::mutex> autoLock(distributedLock_);
2103 RemoteConnectAbilityMappingLocked(connect, callerInfo.sourceDeviceId, remoteDeviceId,
2104 want.GetElement(), callerInfo, TargetComponent::HARMONY_COMPONENT);
2105 break;
2106 }
2107 if (result == INVALID_REMOTE_PARAMETERS_ERR || result == REMOTE_DEVICE_BIND_ABILITY_ERR) {
2108 break;
2109 }
2110 int64_t elapsedTime = GetTickCount() - start;
2111 if (elapsedTime > BIND_CONNECT_TIMEOUT) {
2112 HILOGW("ConnectRemoteAbility timeout, elapsedTime is %{public}" PRId64 " ms", elapsedTime);
2113 break;
2114 }
2115 }
2116 return result;
2117 }
2118
ProcessCallerDied(const sptr<IRemoteObject> & connect,int32_t deviceType)2119 void DistributedSchedService::ProcessCallerDied(const sptr<IRemoteObject>& connect, int32_t deviceType)
2120 {
2121 if (connect == nullptr) {
2122 HILOGE("ProcessCallerDied connect is null");
2123 return;
2124 }
2125 HILOGI("Caller Died DeviceType : %{public}d", deviceType);
2126 if (deviceType == IDistributedSched::CALLER) {
2127 HandleLocalCallerDied(connect);
2128 return;
2129 }
2130 sptr<IRemoteObject> callbackWrapper = connect;
2131 CallerInfo callerInfo;
2132 AppExecFwk::ElementName element;
2133 EventNotify tempEvent;
2134 {
2135 std::lock_guard<std::mutex> autoLock(calleeLock_);
2136 auto itConnect = calleeMap_.find(connect);
2137 if (itConnect != calleeMap_.end()) {
2138 callbackWrapper = itConnect->second.callbackWrapper;
2139 element = itConnect->second.element;
2140 callerInfo = itConnect->second.callerInfo;
2141 ReportDistributedComponentChange(itConnect->second, DISTRIBUTED_COMPONENT_REMOVE,
2142 IDistributedSched::CALL, IDistributedSched::CALLEE);
2143
2144 GetCurDestCollaborateEvent(callerInfo, element, DMS_DSCHED_EVENT_STOP, ERR_OK, tempEvent);
2145 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2146 calleeMap_.erase(itConnect);
2147 } else {
2148 HILOGW("ProcessCallerDied connect not found");
2149 }
2150 }
2151 UnregisterAppStateObserver(callbackWrapper);
2152 int32_t result = DistributedSchedAdapter::GetInstance().ReleaseAbility(callbackWrapper, element);
2153 if (result != ERR_OK) {
2154 HILOGW("ProcessCallerDied failed, error: %{public}d", result);
2155 }
2156 GetCurDestCollaborateEvent(callerInfo, element, DMS_DSCHED_EVENT_FINISH, result, tempEvent);
2157 NotifyDSchedEventCallbackResult(result, tempEvent);
2158 }
2159
HandleLocalCallerDied(const sptr<IRemoteObject> & connect)2160 void DistributedSchedService::HandleLocalCallerDied(const sptr<IRemoteObject>& connect)
2161 {
2162 {
2163 std::lock_guard<std::mutex> autoLock(callerLock_);
2164 auto it = callerMap_.find(connect);
2165 if (it != callerMap_.end()) {
2166 std::list<ConnectAbilitySession> sessionsList = it->second;
2167 if (!sessionsList.empty()) {
2168 ReportDistributedComponentChange(sessionsList.front().GetCallerInfo(), DISTRIBUTED_COMPONENT_REMOVE,
2169 IDistributedSched::CALL, IDistributedSched::CALLER);
2170 }
2171 NotifyCollaborateEventWithSessions(sessionsList, DMS_DSCHED_EVENT_FINISH, ERR_OK);
2172 callerMap_.erase(it);
2173 HILOGI("remove connection success");
2174 } else {
2175 HILOGW("HandleLocalCallerDied connect not found");
2176 }
2177 }
2178 {
2179 std::lock_guard<std::mutex> autoLock(callLock_);
2180 for (auto iter = callMap_.begin(); iter != callMap_.end(); iter++) {
2181 if (iter->first == connect) {
2182 callMap_.erase(iter);
2183 HILOGI("remove callMap_ connect success");
2184 break;
2185 }
2186 }
2187 }
2188 }
2189
ProcessCalleeDied(const sptr<IRemoteObject> & connect)2190 void DistributedSchedService::ProcessCalleeDied(const sptr<IRemoteObject>& connect)
2191 {
2192 if (connect == nullptr) {
2193 HILOGE("ProcessCalleeDied connect is null");
2194 return;
2195 }
2196 sptr<IRemoteObject> callbackWrapper;
2197 CallerInfo callerInfo;
2198 AppExecFwk::ElementName element;
2199 EventNotify tempEvent;
2200 {
2201 std::lock_guard<std::mutex> autoLock(calleeLock_);
2202 auto itConnect = calleeMap_.find(connect);
2203 if (itConnect != calleeMap_.end()) {
2204 ReportDistributedComponentChange(itConnect->second, DISTRIBUTED_COMPONENT_REMOVE,
2205 IDistributedSched::CALL, IDistributedSched::CALLEE);
2206 callbackWrapper = itConnect->second.callbackWrapper;
2207 callerInfo = itConnect->second.callerInfo;
2208 element = itConnect->second.element;
2209 calleeMap_.erase(itConnect);
2210 } else {
2211 HILOGW("ProcessCalleeDied connect not found");
2212 return;
2213 }
2214 }
2215 GetCurDestCollaborateEvent(callerInfo, element, DMS_DSCHED_EVENT_STOP, ERR_OK, tempEvent);
2216 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2217
2218 UnregisterAppStateObserver(callbackWrapper);
2219 GetCurDestCollaborateEvent(callerInfo, element, DMS_DSCHED_EVENT_FINISH, ERR_OK, tempEvent);
2220 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2221 }
2222
ProcessCallResult(const sptr<IRemoteObject> & calleeConnect,const sptr<IRemoteObject> & callerConnect)2223 void DistributedSchedService::ProcessCallResult(const sptr<IRemoteObject>& calleeConnect,
2224 const sptr<IRemoteObject>& callerConnect)
2225 {
2226 sptr<IRemoteObject> token;
2227 AbilityManagerClient::GetInstance()->GetAbilityTokenByCalleeObj(calleeConnect, token);
2228 if (token == nullptr) {
2229 return;
2230 }
2231 std::lock_guard<std::mutex> autoLock(observerLock_);
2232 for (auto iter = observerMap_.begin(); iter != observerMap_.end(); iter++) {
2233 if (iter->second.srcConnect == callerConnect) {
2234 iter->second.token = token;
2235 return;
2236 }
2237 }
2238 HILOGE("observerMap can not find callerConnect");
2239 }
2240
TryStartRemoteAbilityByCall(const OHOS::AAFwk::Want & want,const sptr<IRemoteObject> & connect,const CallerInfo & callerInfo)2241 int32_t DistributedSchedService::TryStartRemoteAbilityByCall(const OHOS::AAFwk::Want& want,
2242 const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo)
2243 {
2244 std::string remoteDeviceId = want.GetElement().GetDeviceID();
2245 HILOGI("[PerformanceTest] TryStartRemoteAbilityByCall get remote DMS");
2246 sptr<IDistributedSched> remoteDms = GetRemoteDms(remoteDeviceId);
2247 if (remoteDms == nullptr) {
2248 HILOGE("TryStartRemoteAbilityByCall get remote DMS failed, remoteDeviceId: %{public}s",
2249 GetAnonymStr(remoteDeviceId).c_str());
2250 return INVALID_PARAMETERS_ERR;
2251 }
2252 HILOGI("[PerformanceTest] TryStartRemoteAbilityByCall RPC begin");
2253 AccountInfo accountInfo;
2254 int32_t ret = DistributedSchedPermission::GetInstance().GetAccountInfo(remoteDeviceId, callerInfo, accountInfo);
2255 if (ret != ERR_OK) {
2256 HILOGE("GetAccountInfo failed");
2257 return ret;
2258 }
2259 AAFwk::Want remoteWant = want;
2260 int32_t connectToken = SaveConnectToken(want, connect);
2261 remoteWant.SetParam(DMS_CONNECT_TOKEN, connectToken);
2262 HILOGI("connectToken is %{public}s", GetAnonymStr(std::to_string(connectToken)).c_str());
2263 int32_t result = remoteDms->StartAbilityByCallFromRemote(remoteWant, connect, callerInfo, accountInfo);
2264 HILOGI("[PerformanceTest] TryStartRemoteAbilityByCall RPC end");
2265 if (result == ERR_OK) {
2266 SaveCallerComponent(want, connect, callerInfo);
2267 } else {
2268 HILOGE("TryStartRemoteAbilityByCall failed, result : %{public}d", result);
2269 }
2270 return result;
2271 }
2272
SaveCallerComponent(const OHOS::AAFwk::Want & want,const sptr<IRemoteObject> & connect,const CallerInfo & callerInfo)2273 void DistributedSchedService::SaveCallerComponent(const OHOS::AAFwk::Want& want,
2274 const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo)
2275 {
2276 if (connect == nullptr) {
2277 HILOGW("connect is nullptr");
2278 return;
2279 }
2280 std::lock_guard<std::mutex> autoLock(callerLock_);
2281 auto itConnect = callerMap_.find(connect);
2282 if (itConnect == callerMap_.end()) {
2283 connect->AddDeathRecipient(callerDeathRecipientForLocalDevice_);
2284 ReportDistributedComponentChange(callerInfo, DISTRIBUTED_COMPONENT_ADD, IDistributedSched::CALL,
2285 IDistributedSched::CALLER);
2286 }
2287 auto& sessionsList = callerMap_[connect];
2288 std::string remoteDeviceId = want.GetElement().GetDeviceID();
2289 for (auto& session : sessionsList) {
2290 if (remoteDeviceId == session.GetDestinationDeviceId()) {
2291 session.AddElement(want.GetElement());
2292 // already added session for remote device
2293 return;
2294 }
2295 }
2296 // connect to another remote device, add a new session to list
2297 auto& session = sessionsList.emplace_back(callerInfo.sourceDeviceId, remoteDeviceId, callerInfo);
2298 session.AddElement(want.GetElement());
2299
2300 HILOGD("add connection success");
2301 EventNotify tempEvent;
2302 GetCurSrcCollaborateEvent(callerInfo, want.GetElement(), DMS_DSCHED_EVENT_PROCESSING, ERR_OK, tempEvent);
2303 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2304 }
2305
RemoveCallerComponent(const sptr<IRemoteObject> & connect)2306 void DistributedSchedService::RemoveCallerComponent(const sptr<IRemoteObject>& connect)
2307 {
2308 if (connect == nullptr) {
2309 HILOGW("connect is nullptr");
2310 return;
2311 }
2312 {
2313 std::lock_guard<std::mutex> autoLock(callerLock_);
2314 auto it = callerMap_.find(connect);
2315 if (it != callerMap_.end()) {
2316 connect->RemoveDeathRecipient(callerDeathRecipientForLocalDevice_);
2317 std::list<ConnectAbilitySession> sessionsList = it->second;
2318 if (!sessionsList.empty()) {
2319 ReportDistributedComponentChange(sessionsList.front().GetCallerInfo(), DISTRIBUTED_COMPONENT_REMOVE,
2320 IDistributedSched::CALL, IDistributedSched::CALLER);
2321 }
2322 NotifyCollaborateEventWithSessions(sessionsList, DMS_DSCHED_EVENT_FINISH, ERR_OK);
2323 callerMap_.erase(it);
2324 HILOGI("remove connection success");
2325 } else {
2326 HILOGW("RemoveCallerComponent connect not found");
2327 }
2328 }
2329 {
2330 std::lock_guard<std::mutex> autoLock(callLock_);
2331 for (auto iter = callMap_.begin(); iter != callMap_.end(); iter++) {
2332 if (iter->first == connect) {
2333 callMap_.erase(iter);
2334 HILOGI("remove callMap_ connect success");
2335 break;
2336 }
2337 }
2338 }
2339 }
2340
ProcessCalleeOffline(const std::string & deviceId)2341 void DistributedSchedService::ProcessCalleeOffline(const std::string& deviceId)
2342 {
2343 {
2344 std::lock_guard<std::mutex> autoLock(callerLock_);
2345 for (auto iter = callerMap_.begin(); iter != callerMap_.end();) {
2346 std::list<ConnectAbilitySession>& sessionsList = iter->second;
2347 auto itSession = std::find_if(sessionsList.begin(), sessionsList.end(), [&deviceId](const auto& session) {
2348 return session.GetDestinationDeviceId() == deviceId;
2349 });
2350 CallerInfo callerInfo;
2351 if (itSession != sessionsList.end()) {
2352 callerInfo = itSession->GetCallerInfo();
2353 for (const auto &element : itSession->GetElementsList()) {
2354 EventNotify tempEvent;
2355 GetCurSrcCollaborateEvent(callerInfo, element, DMS_DSCHED_EVENT_FINISH, ERR_OK, tempEvent);
2356 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2357 }
2358 sessionsList.erase(itSession);
2359 }
2360
2361 if (sessionsList.empty()) {
2362 if (iter->first != nullptr) {
2363 iter->first->RemoveDeathRecipient(callerDeathRecipientForLocalDevice_);
2364 }
2365 ReportDistributedComponentChange(callerInfo, DISTRIBUTED_COMPONENT_REMOVE,
2366 IDistributedSched::CALL, IDistributedSched::CALLER);
2367 iter = callerMap_.erase(iter);
2368 } else {
2369 iter++;
2370 }
2371 }
2372 }
2373 {
2374 std::lock_guard<std::mutex> autoLock(callLock_);
2375 for (auto iter = callMap_.begin(); iter != callMap_.end();) {
2376 if (iter->second.remoteDeviceId == deviceId) {
2377 iter = callMap_.erase(iter);
2378 HILOGI("remove callMap_ connect success");
2379 } else {
2380 iter++;
2381 }
2382 }
2383 }
2384 }
2385
SaveConnectToken(const OHOS::AAFwk::Want & want,const sptr<IRemoteObject> & connect)2386 int32_t DistributedSchedService::SaveConnectToken(const OHOS::AAFwk::Want& want, const sptr<IRemoteObject>& connect)
2387 {
2388 int32_t tToken = -1;
2389 {
2390 std::lock_guard<std::mutex> tokenLock(tokenMutex_);
2391 tToken = token_.load();
2392 if (++tToken > MAX_TOKEN_NUM) {
2393 tToken = 1;
2394 }
2395 token_.store(tToken);
2396 }
2397 {
2398 std::lock_guard<std::mutex> autoLock(callLock_);
2399 callMap_[connect] = {tToken, want.GetElement().GetDeviceID()};
2400 HILOGI("add connect success");
2401 }
2402 return tToken;
2403 }
2404
StartRemoteAbilityByCall(const OHOS::AAFwk::Want & want,const sptr<IRemoteObject> & connect,int32_t callerUid,int32_t callerPid,uint32_t accessToken)2405 int32_t DistributedSchedService::StartRemoteAbilityByCall(const OHOS::AAFwk::Want& want,
2406 const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid, uint32_t accessToken)
2407 {
2408 if (!MultiUserManager::GetInstance().IsCallerForeground(callerUid)) {
2409 HILOGW("The current user is not foreground. callingUid: %{public}d .", callerUid);
2410 return DMS_NOT_FOREGROUND_USER;
2411 }
2412 if (connect == nullptr) {
2413 HILOGE("StartRemoteAbilityByCall connect is null");
2414 return INVALID_PARAMETERS_ERR;
2415 }
2416 std::string localDeviceId;
2417 std::string remoteDeviceId = want.GetElement().GetDeviceID();
2418 if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, remoteDeviceId)) {
2419 HILOGE("StartRemoteAbilityByCall check deviceId failed");
2420 return INVALID_PARAMETERS_ERR;
2421 }
2422 CallerInfo callerInfo = { callerUid, callerPid };
2423 callerInfo.sourceDeviceId = localDeviceId;
2424 callerInfo.accessToken = accessToken;
2425 if (!BundleManagerInternal::GetCallerAppIdFromBms(callerInfo.uid, callerInfo.callerAppId)) {
2426 HILOGE("GetCallerAppIdFromBms failed");
2427 return INVALID_PARAMETERS_ERR;
2428 }
2429 if (!BundleManagerInternal::GetBundleNameListFromBms(callerInfo.uid, callerInfo.bundleNames)) {
2430 HILOGE("GetBundleNameListFromBms failed");
2431 return INVALID_PARAMETERS_ERR;
2432 }
2433 callerInfo.extraInfoJson[DMS_VERSION_ID] = DMS_VERSION;
2434 std::string uidSpecBundleName;
2435 if (!BundleManagerInternal::GetSpecifyBundleNameFromBms(callerInfo.uid, uidSpecBundleName)) {
2436 HILOGE("Get specify bundle name for from Bms fail, connect session caller uid %{public}d.", callerInfo.uid);
2437 }
2438 callerInfo.extraInfoJson[DMS_UID_SPEC_BUNDLE_NAME] = uidSpecBundleName;
2439
2440 EventNotify tempEvent;
2441 GetCurSrcCollaborateEvent(callerInfo, want.GetElement(), DMS_DSCHED_EVENT_START, ERR_OK, tempEvent);
2442 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2443 AAFwk::Want newWant = Want(want);
2444 newWant.SetParam(DMS_SRC_BUNDLE_NAMES, callerInfo.bundleNames);
2445 int32_t ret = TryStartRemoteAbilityByCall(newWant, connect, callerInfo);
2446 if (ret != ERR_OK) {
2447 {
2448 std::lock_guard<std::mutex> autoLock(callLock_);
2449 callMap_.erase(connect);
2450 }
2451 HILOGE("StartRemoteAbilityByCall result is %{public}d", ret);
2452 }
2453 return ret;
2454 }
2455
ReleaseRemoteAbility(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element)2456 int32_t DistributedSchedService::ReleaseRemoteAbility(const sptr<IRemoteObject>& connect,
2457 const AppExecFwk::ElementName &element)
2458 {
2459 if (connect == nullptr) {
2460 HILOGE("ReleaseRemoteAbility connect is null");
2461 return INVALID_PARAMETERS_ERR;
2462 }
2463 if (element.GetDeviceID().empty()) {
2464 HILOGE("ReleaseRemoteAbility remote deviceId empty");
2465 return INVALID_PARAMETERS_ERR;
2466 }
2467 sptr<IDistributedSched> remoteDms = GetRemoteDms(element.GetDeviceID());
2468 if (remoteDms == nullptr) {
2469 HILOGE("ReleaseRemoteAbility get remote dms failed, devId: %{public}s",
2470 GetAnonymStr(element.GetDeviceID()).c_str());
2471 return INVALID_PARAMETERS_ERR;
2472 }
2473 CallerInfo callerInfo;
2474 if (!GetLocalDeviceId(callerInfo.sourceDeviceId)) {
2475 HILOGE("ReleaseRemoteAbility get local deviceId failed");
2476 return INVALID_PARAMETERS_ERR;
2477 }
2478 int32_t result = remoteDms->ReleaseAbilityFromRemote(connect, element, callerInfo);
2479 if (result == ERR_OK) {
2480 RemoveCallerComponent(connect);
2481 } else {
2482 HILOGE("ReleaseRemoteAbility result is %{public}d", result);
2483 }
2484 return result;
2485 }
2486
StartAbilityByCallFromRemote(const OHOS::AAFwk::Want & want,const sptr<IRemoteObject> & connect,const CallerInfo & callerInfo,const AccountInfo & accountInfo)2487 int32_t DistributedSchedService::StartAbilityByCallFromRemote(const OHOS::AAFwk::Want& want,
2488 const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo)
2489 {
2490 HILOGI("[PerformanceTest] DistributedSchedService StartAbilityByCallFromRemote begin");
2491 if (connect == nullptr) {
2492 HILOGE("StartAbilityByCallFromRemote connect is null");
2493 return INVALID_REMOTE_PARAMETERS_ERR;
2494 }
2495
2496 EventNotify tempEvent;
2497 GetCurDestCollaborateEvent(callerInfo, want.GetElement(), DMS_DSCHED_EVENT_START, ERR_OK, tempEvent);
2498 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2499
2500 std::string localDeviceId;
2501 std::string destinationDeviceId = want.GetElement().GetDeviceID();
2502 if (!GetLocalDeviceId(localDeviceId) ||
2503 !CheckDeviceIdFromRemote(localDeviceId, destinationDeviceId, callerInfo.sourceDeviceId)) {
2504 HILOGE("StartAbilityByCallFromRemote check deviceId failed");
2505 return INVALID_REMOTE_PARAMETERS_ERR;
2506 }
2507 int32_t result = CheckTargetPermission(want, callerInfo, accountInfo, CALL_PERMISSION, false);
2508 if (result != ERR_OK) {
2509 HILOGE("CheckTargetPermission failed!!");
2510 return result;
2511 }
2512
2513 sptr<IRemoteObject> callbackWrapper;
2514 {
2515 std::lock_guard<std::mutex> autoLock(calleeLock_);
2516 auto itConnect = calleeMap_.find(connect);
2517 if (itConnect != calleeMap_.end()) {
2518 callbackWrapper = itConnect->second.callbackWrapper;
2519 } else {
2520 callbackWrapper = new AbilityConnectionWrapperStub(connect, localDeviceId);
2521 }
2522 }
2523 int32_t errCode = DistributedSchedAdapter::GetInstance().StartAbilityByCall(want, callbackWrapper, this);
2524 HILOGI("[PerformanceTest] StartAbilityByCallFromRemote end");
2525 if (errCode == ERR_OK) {
2526 {
2527 std::lock_guard<std::mutex> autoLock(calleeLock_);
2528 ConnectInfo connectInfo {callerInfo, callbackWrapper, want.GetElement()};
2529 ReportDistributedComponentChange(connectInfo, DISTRIBUTED_COMPONENT_ADD,
2530 IDistributedSched::CALL, IDistributedSched::CALLEE);
2531 calleeMap_.emplace(connect, connectInfo);
2532 }
2533 connect->AddDeathRecipient(callerDeathRecipient_);
2534 if (!RegisterAppStateObserver(want, callerInfo, connect, callbackWrapper)) {
2535 HILOGE("RegisterAppStateObserver failed");
2536 }
2537 }
2538
2539 GetCurDestCollaborateEvent(callerInfo, want.GetElement(), DMS_DSCHED_EVENT_PROCESSING, ERR_OK, tempEvent);
2540 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2541 return errCode;
2542 }
2543
ReleaseAbilityFromRemote(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element,const CallerInfo & callerInfo)2544 int32_t DistributedSchedService::ReleaseAbilityFromRemote(const sptr<IRemoteObject>& connect,
2545 const AppExecFwk::ElementName &element, const CallerInfo& callerInfo)
2546 {
2547 if (connect == nullptr) {
2548 HILOGE("ReleaseAbilityFromRemote connect is null");
2549 return INVALID_REMOTE_PARAMETERS_ERR;
2550 }
2551 EventNotify tempEvent;
2552 GetCurDestCollaborateEvent(callerInfo, element, DMS_DSCHED_EVENT_STOP, ERR_OK, tempEvent);
2553 NotifyDSchedEventCallbackResult(ERR_OK, tempEvent);
2554
2555 HILOGD("[PerformanceTest] ReleaseAbilityFromRemote begin");
2556 std::string localDeviceId;
2557 if (!GetLocalDeviceId(localDeviceId) || localDeviceId.empty() ||
2558 callerInfo.sourceDeviceId.empty() || localDeviceId == callerInfo.sourceDeviceId) {
2559 HILOGE("ReleaseAbilityFromRemote check deviceId failed");
2560 return INVALID_REMOTE_PARAMETERS_ERR;
2561 }
2562
2563 sptr<IRemoteObject> callbackWrapper;
2564 {
2565 std::lock_guard<std::mutex> autoLock(calleeLock_);
2566 auto itConnect = calleeMap_.find(connect);
2567 if (itConnect == calleeMap_.end()) {
2568 HILOGE("ReleaseAbilityFromRemote callee not found");
2569 return INVALID_REMOTE_PARAMETERS_ERR;
2570 }
2571 callbackWrapper = itConnect->second.callbackWrapper;
2572 ReportDistributedComponentChange(itConnect->second, DISTRIBUTED_COMPONENT_REMOVE,
2573 IDistributedSched::CALL, IDistributedSched::CALLEE);
2574 calleeMap_.erase(itConnect);
2575 connect->RemoveDeathRecipient(callerDeathRecipient_);
2576 }
2577 UnregisterAppStateObserver(callbackWrapper);
2578 int32_t result = DistributedSchedAdapter::GetInstance().ReleaseAbility(callbackWrapper, element);
2579 HILOGD("[PerformanceTest] ReleaseAbilityFromRemote end");
2580 if (result != ERR_OK) {
2581 HILOGE("ReleaseAbilityFromRemote failed, error: %{public}d", result);
2582 }
2583 GetCurDestCollaborateEvent(callerInfo, element, DMS_DSCHED_EVENT_FINISH, result, tempEvent);
2584 NotifyDSchedEventCallbackResult(result, tempEvent);
2585 return result;
2586 }
2587
2588 #ifdef SUPPORT_DISTRIBUTED_FORM_SHARE
StartRemoteShareForm(const std::string & remoteDeviceId,const OHOS::AppExecFwk::FormShareInfo & formShareInfo)2589 int32_t DistributedSchedService::StartRemoteShareForm(const std::string& remoteDeviceId,
2590 const OHOS::AppExecFwk::FormShareInfo& formShareInfo)
2591 {
2592 HILOGD("SHAREFORM:: func call");
2593
2594 if (remoteDeviceId.empty()) {
2595 HILOGE("StartRemoteShareForm input params error");
2596 return INVALID_PARAMETERS_ERR;
2597 }
2598
2599 sptr<IDistributedSched> remoteDms = GetRemoteDms(remoteDeviceId);
2600 if (remoteDms == nullptr) {
2601 HILOGE("StartRemoteShareForm get remote DMS failed, remoteDeviceId: %{public}s",
2602 GetAnonymStr(remoteDeviceId).c_str());
2603 return GET_REMOTE_DMS_FAIL;
2604 }
2605 std::string localDeviceId = "";
2606 GetLocalDeviceId(localDeviceId);
2607 OHOS::AppExecFwk::FormShareInfo formShareInfoCopy;
2608 formShareInfoCopy.formId = formShareInfo.formId;
2609 formShareInfoCopy.formName = formShareInfo.formName;
2610 formShareInfoCopy.bundleName = formShareInfo.bundleName;
2611 formShareInfoCopy.moduleName = formShareInfo.moduleName;
2612 formShareInfoCopy.abilityName = formShareInfo.abilityName;
2613 formShareInfoCopy.formTempFlag = formShareInfo.formTempFlag;
2614 formShareInfoCopy.dimensionId = formShareInfo.dimensionId;
2615 formShareInfoCopy.providerShareData = formShareInfo.providerShareData;
2616 formShareInfoCopy.deviceId = localDeviceId;
2617 int32_t result = remoteDms->StartShareFormFromRemote(remoteDeviceId, formShareInfoCopy);
2618 HILOGD("[PerformanceTest] StartRemoteShareForm RPC end");
2619 if (result != ERR_OK) {
2620 HILOGE("StartRemoteShareForm failed, result : %{public}d", result);
2621 }
2622 return result;
2623 }
2624
StartShareFormFromRemote(const std::string & remoteDeviceId,const OHOS::AppExecFwk::FormShareInfo & formShareInfo)2625 int32_t DistributedSchedService::StartShareFormFromRemote(
2626 const std::string& remoteDeviceId, const OHOS::AppExecFwk::FormShareInfo& formShareInfo)
2627 {
2628 HILOGD("SHAREFORM:: func call begin");
2629 std::string localDeviceId = "";
2630 GetLocalDeviceId(localDeviceId);
2631 if (CheckDeviceId(localDeviceId, remoteDeviceId)) {
2632 HILOGE("localId is %{public}s != %{public}s", GetAnonymStr(localDeviceId).c_str(),
2633 GetAnonymStr(remoteDeviceId).c_str());
2634 return INVALID_REMOTE_PARAMETERS_ERR;
2635 }
2636
2637 auto formMgr = GetFormMgrProxy();
2638 if (formMgr == nullptr) {
2639 HILOGE("get form mgr proxy failed.");
2640 return NOT_FIND_SERVICE_PROXY;
2641 }
2642
2643 auto result = formMgr->RecvFormShareInfoFromRemote(formShareInfo);
2644 HILOGD("SHAREFORM:: func call end");
2645 return result;
2646 }
2647 #endif
2648
GetDistributedComponentList(std::vector<std::string> & distributedComponents)2649 int32_t DistributedSchedService::GetDistributedComponentList(std::vector<std::string>& distributedComponents)
2650 {
2651 GetConnectComponentList(distributedComponents);
2652 GetCallComponentList(distributedComponents);
2653 return ERR_OK;
2654 }
2655
GetConnectComponentList(std::vector<std::string> & distributedComponents)2656 void DistributedSchedService::GetConnectComponentList(std::vector<std::string>& distributedComponents)
2657 {
2658 {
2659 std::lock_guard<std::mutex> autoLock(distributedLock_);
2660 for (const auto& iter : distributedConnectAbilityMap_) {
2661 if (iter.second.empty()) {
2662 continue;
2663 }
2664 CallerInfo callerInfo = iter.second.front().GetCallerInfo();
2665 nlohmann::json componentInfoJson;
2666 componentInfoJson[PID_KEY] = callerInfo.pid;
2667 componentInfoJson[UID_KEY] = callerInfo.uid;
2668 componentInfoJson[BUNDLE_NAME_KEY] =
2669 callerInfo.bundleNames.empty() ? std::string() : callerInfo.bundleNames.front();
2670 componentInfoJson[COMPONENT_TYPE_KEY] = IDistributedSched::CONNECT;
2671 componentInfoJson[DEVICE_TYPE_KEY] = IDistributedSched::CALLER;
2672 std::string componentInfo = componentInfoJson.dump();
2673 distributedComponents.emplace_back(componentInfo);
2674 }
2675 }
2676 {
2677 std::lock_guard<std::mutex> autoLock(connectLock_);
2678 for (const auto& iter : connectAbilityMap_) {
2679 ConnectInfo connectInfo = iter.second;
2680 nlohmann::json componentInfoJson;
2681 componentInfoJson[UID_KEY] = BundleManagerInternal::GetUidFromBms(connectInfo.element.GetBundleName());
2682 componentInfoJson[BUNDLE_NAME_KEY] = connectInfo.element.GetBundleName();
2683 componentInfoJson[COMPONENT_TYPE_KEY] = IDistributedSched::CONNECT;
2684 componentInfoJson[DEVICE_TYPE_KEY] = IDistributedSched::CALLEE;
2685 std::string componentInfo = componentInfoJson.dump();
2686 distributedComponents.emplace_back(componentInfo);
2687 }
2688 }
2689 }
2690
GetCallComponentList(std::vector<std::string> & distributedComponents)2691 void DistributedSchedService::GetCallComponentList(std::vector<std::string>& distributedComponents)
2692 {
2693 {
2694 std::lock_guard<std::mutex> autoLock(callerLock_);
2695 for (const auto& iter : callerMap_) {
2696 if (iter.second.empty()) {
2697 continue;
2698 }
2699 CallerInfo callerInfo = iter.second.front().GetCallerInfo();
2700 nlohmann::json componentInfoJson;
2701 componentInfoJson[PID_KEY] = callerInfo.pid;
2702 componentInfoJson[UID_KEY] = callerInfo.uid;
2703 componentInfoJson[BUNDLE_NAME_KEY] =
2704 callerInfo.bundleNames.empty() ? std::string() : callerInfo.bundleNames.front();
2705 componentInfoJson[COMPONENT_TYPE_KEY] = IDistributedSched::CALL;
2706 componentInfoJson[DEVICE_TYPE_KEY] = IDistributedSched::CALLER;
2707 std::string componentInfo = componentInfoJson.dump();
2708 distributedComponents.emplace_back(componentInfo);
2709 }
2710 }
2711 {
2712 std::lock_guard<std::mutex> autoLock(calleeLock_);
2713 for (const auto& iter : calleeMap_) {
2714 ConnectInfo connectInfo = iter.second;
2715 nlohmann::json componentInfoJson;
2716 componentInfoJson[UID_KEY] = BundleManagerInternal::GetUidFromBms(connectInfo.element.GetBundleName());
2717 componentInfoJson[BUNDLE_NAME_KEY] = connectInfo.element.GetBundleName();
2718 componentInfoJson[COMPONENT_TYPE_KEY] = IDistributedSched::CALL;
2719 componentInfoJson[DEVICE_TYPE_KEY] = IDistributedSched::CALLEE;
2720 std::string componentInfo = componentInfoJson.dump();
2721 distributedComponents.emplace_back(componentInfo);
2722 }
2723 }
2724 }
2725
ReportDistributedComponentChange(const CallerInfo & callerInfo,int32_t changeType,int32_t componentType,int32_t deviceType)2726 void DistributedSchedService::ReportDistributedComponentChange(const CallerInfo& callerInfo, int32_t changeType,
2727 int32_t componentType, int32_t deviceType)
2728 {
2729 #if defined(EFFICIENCY_MANAGER_ENABLE) || defined(SUPPORT_DISTRIBUTEDCOMPONENT_TO_MEMMGR)
2730 HILOGI("caller report");
2731 auto func = [this, callerInfo, changeType, componentType, deviceType]() {
2732 #ifdef EFFICIENCY_MANAGER_ENABLE
2733 std::unordered_map<std::string, std::string> payload;
2734 payload[PID_KEY] = std::to_string(callerInfo.pid);
2735 payload[UID_KEY] = std::to_string(callerInfo.uid);
2736 payload[BUNDLE_NAME_KEY] =
2737 callerInfo.bundleNames.empty() ? std::string() : callerInfo.bundleNames.front();
2738 payload[COMPONENT_TYPE_KEY] = std::to_string(componentType);
2739 payload[DEVICE_TYPE_KEY] = std::to_string(deviceType);
2740 payload[CHANGE_TYPE_KEY] = std::to_string(changeType);
2741 uint32_t type = ResourceSchedule::ResType::RES_TYPE_REPORT_DISTRIBUTE_COMPONENT_CHANGE;
2742 ResourceSchedule::ResSchedClient::GetInstance().ReportData(type, 0, payload);
2743 #endif
2744 #ifdef SUPPORT_DISTRIBUTEDCOMPONENT_TO_MEMMGR
2745 Memory::MemMgrClient::GetInstance().NotifyDistDevStatus(callerInfo.pid, callerInfo.uid,
2746 callerInfo.bundleNames.empty() ? std::string() : callerInfo.bundleNames.front(),
2747 changeType == DISTRIBUTED_COMPONENT_ADD);
2748 #endif
2749 };
2750 if (componentChangeHandler_ != nullptr) {
2751 componentChangeHandler_->PostTask(func);
2752 return;
2753 }
2754 HILOGE("HandleDistributedComponentChange handler postTask failed");
2755 #endif
2756 }
2757
ReportDistributedComponentChange(const ConnectInfo & connectInfo,int32_t changeType,int32_t componentType,int32_t deviceType)2758 void DistributedSchedService::ReportDistributedComponentChange(const ConnectInfo& connectInfo, int32_t changeType,
2759 int32_t componentType, int32_t deviceType)
2760 {
2761 #ifdef EFFICIENCY_MANAGER_ENABLE
2762 HILOGI("callee report");
2763 auto func = [this, connectInfo, changeType, componentType, deviceType]() {
2764 std::unordered_map<std::string, std::string> payload;
2765 payload[UID_KEY] = std::to_string(BundleManagerInternal::GetUidFromBms(connectInfo.element.GetBundleName()));
2766 payload[BUNDLE_NAME_KEY] = connectInfo.element.GetBundleName();
2767 payload[COMPONENT_TYPE_KEY] = std::to_string(componentType);
2768 payload[DEVICE_TYPE_KEY] = std::to_string(deviceType);
2769 payload[CHANGE_TYPE_KEY] = std::to_string(changeType);
2770 uint32_t type = ResourceSchedule::ResType::RES_TYPE_REPORT_DISTRIBUTE_COMPONENT_CHANGE;
2771 ResourceSchedule::ResSchedClient::GetInstance().ReportData(type, 0, payload);
2772 };
2773 if (componentChangeHandler_ != nullptr) {
2774 componentChangeHandler_->PostTask(func);
2775 return;
2776 }
2777 HILOGE("HandleDistributedComponentChange handler postTask failed");
2778 #endif
2779 }
2780
GetRemoteDms(const std::string & remoteDeviceId)2781 sptr<IDistributedSched> DistributedSchedService::GetRemoteDms(const std::string& remoteDeviceId)
2782 {
2783 if (remoteDeviceId.empty()) {
2784 HILOGE("GetRemoteDms remoteDeviceId is empty");
2785 return nullptr;
2786 }
2787 HILOGD("GetRemoteDms connect deviceid is %s", GetAnonymStr(remoteDeviceId).c_str());
2788 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2789 if (samgr == nullptr) {
2790 HILOGE("GetRemoteDms failed to connect to systemAbilityMgr!");
2791 return nullptr;
2792 }
2793 HILOGI("[PerformanceTest] GetRemoteDms begin");
2794 auto object = samgr->CheckSystemAbility(DISTRIBUTED_SCHED_SA_ID, remoteDeviceId);
2795 HILOGI("[PerformanceTest] GetRemoteDms end");
2796 if (object == nullptr) {
2797 HILOGE("GetRemoteDms failed to get remote DistributedSched %{private}s", GetAnonymStr(remoteDeviceId).c_str());
2798 return nullptr;
2799 }
2800 return iface_cast<IDistributedSched>(object);
2801 }
2802
GetLocalDeviceId(std::string & localDeviceId)2803 bool DistributedSchedService::GetLocalDeviceId(std::string& localDeviceId)
2804 {
2805 if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(localDeviceId)) {
2806 HILOGE("GetLocalDeviceId failed");
2807 return false;
2808 }
2809 return true;
2810 }
2811
CheckDeviceId(const std::string & localDeviceId,const std::string & remoteDeviceId)2812 bool DistributedSchedService::CheckDeviceId(const std::string& localDeviceId, const std::string& remoteDeviceId)
2813 {
2814 // remoteDeviceId must not same with localDeviceId
2815 if (localDeviceId.empty() || remoteDeviceId.empty() || localDeviceId == remoteDeviceId) {
2816 HILOGE("check deviceId failed");
2817 return false;
2818 }
2819 return true;
2820 }
2821
CheckDeviceIdFromRemote(const std::string & localDeviceId,const std::string & destinationDeviceId,const std::string & sourceDeviceId)2822 bool DistributedSchedService::CheckDeviceIdFromRemote(const std::string& localDeviceId,
2823 const std::string& destinationDeviceId, const std::string& sourceDeviceId)
2824 {
2825 if (localDeviceId.empty() || destinationDeviceId.empty() || sourceDeviceId.empty()) {
2826 HILOGE("CheckDeviceIdFromRemote failed");
2827 return false;
2828 }
2829 // destinationDeviceId set by remote must be same with localDeviceId
2830 if (localDeviceId != destinationDeviceId) {
2831 HILOGE("destinationDeviceId is not same with localDeviceId");
2832 return false;
2833 }
2834 HILOGD("CheckDeviceIdFromRemote sourceDeviceId %s", GetAnonymStr(sourceDeviceId).c_str());
2835 HILOGD("CheckDeviceIdFromRemote localDeviceId %s", GetAnonymStr(localDeviceId).c_str());
2836 HILOGD("CheckDeviceIdFromRemote destinationDeviceId %s", GetAnonymStr(destinationDeviceId).c_str());
2837
2838 if (sourceDeviceId == destinationDeviceId || sourceDeviceId == localDeviceId) {
2839 HILOGE("destinationDeviceId is different with localDeviceId and destinationDeviceId");
2840 return false;
2841 }
2842
2843 if (sourceDeviceId != IPCSkeleton::GetCallingDeviceID()) {
2844 HILOGE("sourceDeviceId is not correct");
2845 return false;
2846 }
2847 return true;
2848 }
2849
ConnectAbilityFromRemote(const OHOS::AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo,const sptr<IRemoteObject> & connect,const CallerInfo & callerInfo,const AccountInfo & accountInfo)2850 int32_t DistributedSchedService::ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want,
2851 const AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& connect,
2852 const CallerInfo& callerInfo, const AccountInfo& accountInfo)
2853 {
2854 HILOGI("[PerformanceTest] DistributedSchedService ConnectAbilityFromRemote begin");
2855 if (connect == nullptr) {
2856 HILOGE("ConnectAbilityFromRemote connect is null");
2857 return INVALID_REMOTE_PARAMETERS_ERR;
2858 }
2859 HILOGI("ConnectAbilityFromRemote uid is %{public}d, pid is %{public}d, AccessTokenID is %{public}s",
2860 callerInfo.uid, callerInfo.pid, GetAnonymStr(std::to_string(callerInfo.accessToken)).c_str());
2861 std::string localDeviceId;
2862 std::string destinationDeviceId = want.GetElement().GetDeviceID();
2863 if (!GetLocalDeviceId(localDeviceId) ||
2864 !CheckDeviceIdFromRemote(localDeviceId, destinationDeviceId, callerInfo.sourceDeviceId)) {
2865 HILOGE("ConnectAbilityFromRemote check deviceId failed");
2866 return INVALID_REMOTE_PARAMETERS_ERR;
2867 }
2868 int32_t result = CheckTargetPermission(want, callerInfo, accountInfo, START_PERMISSION, true);
2869 if (result != ERR_OK) {
2870 HILOGE("CheckTargetPermission failed!!");
2871 return result;
2872 }
2873
2874 HILOGI("ConnectAbilityFromRemote callerType is %{public}d", callerInfo.callerType);
2875 sptr<IRemoteObject> callbackWrapper = connect;
2876 std::map<sptr<IRemoteObject>, ConnectInfo>::iterator itConnect;
2877 if (callerInfo.callerType == CALLER_TYPE_HARMONY) {
2878 std::lock_guard<std::mutex> autoLock(connectLock_);
2879 itConnect = connectAbilityMap_.find(connect);
2880 if (itConnect != connectAbilityMap_.end()) {
2881 callbackWrapper = itConnect->second.callbackWrapper;
2882 } else {
2883 callbackWrapper = new AbilityConnectionWrapperStub(connect);
2884 }
2885 }
2886 int32_t errCode = DistributedSchedAdapter::GetInstance().ConnectAbility(want, callbackWrapper, this);
2887 HILOGI("[PerformanceTest] ConnectAbilityFromRemote end");
2888 if (errCode == ERR_OK) {
2889 std::lock_guard<std::mutex> autoLock(connectLock_);
2890 if (itConnect == connectAbilityMap_.end()) {
2891 ConnectInfo connectInfo {callerInfo, callbackWrapper, want.GetElement()};
2892 ReportDistributedComponentChange(connectInfo, DISTRIBUTED_COMPONENT_ADD,
2893 IDistributedSched::CONNECT, IDistributedSched::CALLEE);
2894 connectAbilityMap_.emplace(connect, connectInfo);
2895 }
2896 }
2897 return errCode;
2898 }
2899
DisconnectEachRemoteAbilityLocked(const std::string & localDeviceId,const std::string & remoteDeviceId,const sptr<IRemoteObject> & connect)2900 int32_t DistributedSchedService::DisconnectEachRemoteAbilityLocked(const std::string& localDeviceId,
2901 const std::string& remoteDeviceId, const sptr<IRemoteObject>& connect)
2902 {
2903 sptr<IDistributedSched> remoteDms = GetRemoteDms(remoteDeviceId);
2904 if (remoteDms == nullptr) {
2905 HILOGE("DisconnectRemoteAbility get remote dms failed");
2906 return INVALID_PARAMETERS_ERR;
2907 }
2908 int32_t result = remoteDms->DisconnectAbilityFromRemote(connect, IPCSkeleton::GetCallingUid(), localDeviceId);
2909 if (result != ERR_OK) {
2910 HILOGE("DisconnectEachRemoteAbilityLocked result is %{public}d", result);
2911 }
2912 return result;
2913 }
2914
DisconnectRemoteAbility(const sptr<IRemoteObject> & connect,int32_t callerUid,uint32_t accessToken)2915 int32_t DistributedSchedService::DisconnectRemoteAbility(const sptr<IRemoteObject>& connect, int32_t callerUid,
2916 uint32_t accessToken)
2917 {
2918 if (connect == nullptr) {
2919 HILOGE("DisconnectRemoteAbility connect is null");
2920 return INVALID_PARAMETERS_ERR;
2921 }
2922
2923 std::list<ConnectAbilitySession> sessionsList;
2924 {
2925 std::lock_guard<std::mutex> autoLock(distributedLock_);
2926 auto it = distributedConnectAbilityMap_.find(connect);
2927 if (it != distributedConnectAbilityMap_.end()) {
2928 sessionsList = it->second;
2929 int32_t uid = GetUidLocked(sessionsList);
2930 // also decrease number when erase connect
2931 DecreaseConnectLocked(uid);
2932 connect->RemoveDeathRecipient(connectDeathRecipient_);
2933 if (!sessionsList.empty()) {
2934 ReportDistributedComponentChange(sessionsList.front().GetCallerInfo(), DISTRIBUTED_COMPONENT_REMOVE,
2935 IDistributedSched::CONNECT, IDistributedSched::CALLER);
2936 }
2937 distributedConnectAbilityMap_.erase(it);
2938 HILOGI("remove connection success");
2939 } else {
2940 #ifdef DMSFWK_INTERACTIVE_ADAPTER
2941 return DisconnectRemoteAbilityAdapter(connect, callerUid, accessToken);
2942 #endif // DMSFWK_INTERACTIVE_ADAPTER
2943 }
2944 }
2945 if (!sessionsList.empty()) {
2946 for (const auto& session : sessionsList) {
2947 if (session.GetTargetComponent() == TargetComponent::HARMONY_COMPONENT) {
2948 DisconnectEachRemoteAbilityLocked(session.GetSourceDeviceId(),
2949 session.GetDestinationDeviceId(), connect);
2950 } else {
2951 HILOGW("DisconnectRemoteAbility non-harmony component");
2952 }
2953 }
2954 return ERR_OK;
2955 }
2956 return NO_CONNECT_CALLBACK_ERR;
2957 }
2958
DisconnectAbilityFromRemote(const sptr<IRemoteObject> & connect,int32_t uid,const std::string & sourceDeviceId)2959 int32_t DistributedSchedService::DisconnectAbilityFromRemote(const sptr<IRemoteObject>& connect,
2960 int32_t uid, const std::string& sourceDeviceId)
2961 {
2962 if (connect == nullptr) {
2963 HILOGE("DisconnectAbilityFromRemote connect is null");
2964 return INVALID_REMOTE_PARAMETERS_ERR;
2965 }
2966
2967 HILOGD("[PerformanceTest] DisconnectAbilityFromRemote begin");
2968 std::string localDeviceId;
2969 AppExecFwk::AbilityInfo abilityInfo;
2970 if (!GetLocalDeviceId(localDeviceId) || localDeviceId.empty() ||
2971 sourceDeviceId.empty() || localDeviceId == sourceDeviceId) {
2972 HILOGE("DisconnectAbilityFromRemote check deviceId failed");
2973 return INVALID_REMOTE_PARAMETERS_ERR;
2974 }
2975
2976 sptr<IRemoteObject> callbackWrapper = connect;
2977 {
2978 std::lock_guard<std::mutex> autoLock(connectLock_);
2979 auto itConnect = connectAbilityMap_.find(connect);
2980 if (itConnect != connectAbilityMap_.end()) {
2981 callbackWrapper = itConnect->second.callbackWrapper;
2982 ReportDistributedComponentChange(itConnect->second, DISTRIBUTED_COMPONENT_REMOVE,
2983 IDistributedSched::CONNECT, IDistributedSched::CALLEE);
2984 connectAbilityMap_.erase(itConnect);
2985 } else {
2986 if (!IPCSkeleton::IsLocalCalling()) {
2987 HILOGE("DisconnectAbilityFromRemote connect not found");
2988 return INVALID_REMOTE_PARAMETERS_ERR;
2989 }
2990 }
2991 }
2992 int32_t result = DistributedSchedAdapter::GetInstance().DisconnectAbility(callbackWrapper);
2993 HILOGD("[PerformanceTest] DisconnectAbilityFromRemote end");
2994 return result;
2995 }
2996
NotifyProcessDiedFromRemote(const CallerInfo & callerInfo)2997 int32_t DistributedSchedService::NotifyProcessDiedFromRemote(const CallerInfo& callerInfo)
2998 {
2999 HILOGI("NotifyProcessDiedFromRemote called");
3000 int32_t errCode = ERR_OK;
3001 {
3002 std::lock_guard<std::mutex> autoLock(connectLock_);
3003 for (auto iter = connectAbilityMap_.begin(); iter != connectAbilityMap_.end();) {
3004 ConnectInfo& connectInfo = iter->second;
3005 if (callerInfo.sourceDeviceId == connectInfo.callerInfo.sourceDeviceId
3006 && callerInfo.uid == connectInfo.callerInfo.uid
3007 && callerInfo.pid == connectInfo.callerInfo.pid
3008 && callerInfo.callerType == connectInfo.callerInfo.callerType) {
3009 HILOGI("NotifyProcessDiedFromRemote erase connection success");
3010 int32_t ret = DistributedSchedAdapter::GetInstance().DisconnectAbility(connectInfo.callbackWrapper);
3011 if (ret != ERR_OK) {
3012 errCode = ret;
3013 }
3014 ReportDistributedComponentChange(connectInfo, DISTRIBUTED_COMPONENT_REMOVE,
3015 IDistributedSched::CONNECT, IDistributedSched::CALLEE);
3016 iter = connectAbilityMap_.erase(iter);
3017 } else {
3018 iter++;
3019 }
3020 }
3021 }
3022 return errCode;
3023 }
3024
RemoveConnectAbilityInfo(const std::string & deviceId)3025 void DistributedSchedService::RemoveConnectAbilityInfo(const std::string& deviceId)
3026 {
3027 {
3028 std::lock_guard<std::mutex> autoLock(distributedLock_);
3029 for (auto iter = distributedConnectAbilityMap_.begin(); iter != distributedConnectAbilityMap_.end();) {
3030 std::list<ConnectAbilitySession>& sessionsList = iter->second;
3031 int32_t uid = GetUidLocked(sessionsList);
3032 auto itSession = std::find_if(sessionsList.begin(), sessionsList.end(), [&deviceId](const auto& session) {
3033 return session.GetDestinationDeviceId() == deviceId;
3034 });
3035 CallerInfo callerInfo;
3036 if (itSession != sessionsList.end()) {
3037 NotifyDeviceOfflineToAppLocked(iter->first, *itSession);
3038 callerInfo = itSession->GetCallerInfo();
3039 sessionsList.erase(itSession);
3040 }
3041
3042 if (sessionsList.empty()) {
3043 if (iter->first != nullptr) {
3044 iter->first->RemoveDeathRecipient(connectDeathRecipient_);
3045 }
3046 DecreaseConnectLocked(uid);
3047 ReportDistributedComponentChange(callerInfo, DISTRIBUTED_COMPONENT_REMOVE,
3048 IDistributedSched::CONNECT, IDistributedSched::CALLER);
3049 iter = distributedConnectAbilityMap_.erase(iter);
3050 } else {
3051 iter++;
3052 }
3053 }
3054 }
3055
3056 {
3057 std::lock_guard<std::mutex> autoLock(connectLock_);
3058 for (auto iter = connectAbilityMap_.begin(); iter != connectAbilityMap_.end();) {
3059 ConnectInfo& connectInfo = iter->second;
3060 if (deviceId == connectInfo.callerInfo.sourceDeviceId) {
3061 DistributedSchedAdapter::GetInstance().DisconnectAbility(connectInfo.callbackWrapper);
3062 ReportDistributedComponentChange(connectInfo, DISTRIBUTED_COMPONENT_REMOVE,
3063 IDistributedSched::CONNECT, IDistributedSched::CALLEE);
3064 connectAbilityMap_.erase(iter++);
3065 HILOGI("ProcessDeviceOffline erase connection success");
3066 } else {
3067 iter++;
3068 }
3069 }
3070 }
3071 }
3072
QueryOsAccount(int32_t & activeAccountId)3073 ErrCode DistributedSchedService::QueryOsAccount(int32_t& activeAccountId)
3074 {
3075 #ifdef OS_ACCOUNT_PART
3076 std::vector<int32_t> ids;
3077 ErrCode err = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
3078 if (err != ERR_OK || ids.empty()) {
3079 HILOGE("QueryActiveOsAccountIds passing param invalid or return error!, err : %{public}d", err);
3080 return INVALID_PARAMETERS_ERR;
3081 }
3082 activeAccountId = ids[0];
3083 #endif
3084 return ERR_OK;
3085 }
3086
ProcessDeviceOffline(const std::string & deviceId)3087 void DistributedSchedService::ProcessDeviceOffline(const std::string& deviceId)
3088 {
3089 HILOGI("ProcessDeviceOffline called");
3090 std::string localDeviceId;
3091 if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) {
3092 HILOGE("ProcessDeviceOffline check deviceId failed");
3093 return;
3094 }
3095 DistributedSchedMissionManager::GetInstance().NotifyNetDisconnectOffline();
3096 RemoveConnectAbilityInfo(deviceId);
3097 ProcessCalleeOffline(deviceId);
3098 ProcessFreeInstallOffline(deviceId);
3099 }
3100
ProcessFreeInstallOffline(const std::string & deviceId)3101 void DistributedSchedService::ProcessFreeInstallOffline(const std::string& deviceId)
3102 {
3103 if (dmsCallbackTask_ == nullptr) {
3104 HILOGE("callbackTask object null!");
3105 return;
3106 }
3107 dmsCallbackTask_->NotifyDeviceOffline(deviceId);
3108 }
3109
NotifyDeviceOfflineToAppLocked(const sptr<IRemoteObject> & connect,const ConnectAbilitySession & session)3110 void DistributedSchedService::NotifyDeviceOfflineToAppLocked(const sptr<IRemoteObject>& connect,
3111 const ConnectAbilitySession& session)
3112 {
3113 std::list<AppExecFwk::ElementName> elementsList = session.GetElementsList();
3114 for (const auto& element : elementsList) {
3115 int32_t errCode = NotifyApp(connect, element, DEVICE_OFFLINE_ERR);
3116 if (errCode != ERR_NONE) {
3117 HILOGW("ProcessDeviceOffline notify failed, errCode = %{public}d", errCode);
3118 }
3119 }
3120 }
3121
NotifyApp(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element,int32_t errCode)3122 int32_t DistributedSchedService::NotifyApp(const sptr<IRemoteObject>& connect,
3123 const AppExecFwk::ElementName& element, int32_t errCode)
3124 {
3125 if (connect == nullptr) {
3126 return OBJECT_NULL;
3127 }
3128 MessageParcel data;
3129 if (!data.WriteInterfaceToken(CONNECTION_CALLBACK_INTERFACE_TOKEN)) {
3130 return ERR_FLATTEN_OBJECT;
3131 }
3132 PARCEL_WRITE_HELPER(data, Parcelable, &element);
3133 PARCEL_WRITE_HELPER(data, Int32, errCode);
3134 MessageParcel reply;
3135 MessageOption option;
3136 return connect->SendRequest(IAbilityConnection::ON_ABILITY_DISCONNECT_DONE, data, reply, option);
3137 }
3138
ProcessConnectDied(const sptr<IRemoteObject> & connect)3139 void DistributedSchedService::ProcessConnectDied(const sptr<IRemoteObject>& connect)
3140 {
3141 if (connect == nullptr) {
3142 HILOGE("ProcessConnectDied connect is null");
3143 return;
3144 }
3145
3146 std::list<ProcessDiedNotifyInfo> notifyList;
3147 {
3148 std::lock_guard<std::mutex> autoLock(distributedLock_);
3149 auto it = distributedConnectAbilityMap_.find(connect);
3150 if (it == distributedConnectAbilityMap_.end()) {
3151 return;
3152 }
3153 std::list<ConnectAbilitySession>& connectSessionsList = it->second;
3154 if (connectSessionsList.empty()) {
3155 return;
3156 }
3157 CallerInfo callerInfo = connectSessionsList.front().GetCallerInfo();
3158 std::set<std::string> processedDeviceSet;
3159 // to reduce the number of communications between devices, clean all the died process's connections
3160 for (auto iter = distributedConnectAbilityMap_.begin(); iter != distributedConnectAbilityMap_.end();) {
3161 std::list<ConnectAbilitySession>& sessionsList = iter->second;
3162 if (!sessionsList.empty() && sessionsList.front().IsSameCaller(callerInfo)) {
3163 for (const auto& session : sessionsList) {
3164 std::string remoteDeviceId = session.GetDestinationDeviceId();
3165 TargetComponent targetComponent = session.GetTargetComponent();
3166 // the same session can connect different types component on the same device
3167 std::string key = remoteDeviceId + std::to_string(static_cast<int32_t>(targetComponent));
3168 // just notify one time for same remote device
3169 auto [_, isSuccess] = processedDeviceSet.emplace(key);
3170 if (isSuccess) {
3171 ProcessDiedNotifyInfo notifyInfo = { remoteDeviceId, callerInfo, targetComponent };
3172 notifyList.push_back(notifyInfo);
3173 }
3174 }
3175 DecreaseConnectLocked(callerInfo.uid);
3176 if (iter->first != nullptr) {
3177 iter->first->RemoveDeathRecipient(connectDeathRecipient_);
3178 }
3179 ReportDistributedComponentChange(callerInfo, DISTRIBUTED_COMPONENT_REMOVE,
3180 IDistributedSched::CONNECT, IDistributedSched::CALLER);
3181 iter = distributedConnectAbilityMap_.erase(iter);
3182 } else {
3183 iter++;
3184 }
3185 }
3186 }
3187 NotifyProcessDiedAll(notifyList);
3188 }
3189
NotifyProcessDiedAll(const std::list<ProcessDiedNotifyInfo> & notifyList)3190 void DistributedSchedService::NotifyProcessDiedAll(const std::list<ProcessDiedNotifyInfo>& notifyList)
3191 {
3192 for (auto it = notifyList.begin(); it != notifyList.end(); ++it) {
3193 NotifyProcessDied(it->remoteDeviceId, it->callerInfo, it->targetComponent);
3194 }
3195 }
3196
NotifyProcessDied(const std::string & remoteDeviceId,const CallerInfo & callerInfo,TargetComponent targetComponent)3197 void DistributedSchedService::NotifyProcessDied(const std::string& remoteDeviceId,
3198 const CallerInfo& callerInfo, TargetComponent targetComponent)
3199 {
3200 if (targetComponent != TargetComponent::HARMONY_COMPONENT) {
3201 HILOGD("NotifyProcessDied not harmony component, no need to notify");
3202 return;
3203 }
3204
3205 sptr<IDistributedSched> remoteDms = GetRemoteDms(remoteDeviceId);
3206 if (remoteDms == nullptr) {
3207 HILOGE("NotifyProcessDied get remote dms failed");
3208 return;
3209 }
3210 int32_t result = remoteDms->NotifyProcessDiedFromRemote(callerInfo);
3211 HILOGI("NotifyProcessDied result is %{public}d", result);
3212 }
3213
ConnectAbilitySession(const std::string & sourceDeviceId,const std::string & destinationDeviceId,const CallerInfo & callerInfo,TargetComponent targetComponent)3214 ConnectAbilitySession::ConnectAbilitySession(const std::string& sourceDeviceId, const std::string& destinationDeviceId,
3215 const CallerInfo& callerInfo, TargetComponent targetComponent)
3216 : sourceDeviceId_(sourceDeviceId),
3217 destinationDeviceId_(destinationDeviceId),
3218 callerInfo_(callerInfo),
3219 targetComponent_(targetComponent)
3220 {
3221 }
3222
AddElement(const AppExecFwk::ElementName & element)3223 void ConnectAbilitySession::AddElement(const AppExecFwk::ElementName& element)
3224 {
3225 for (const auto& elementName : elementsList_) {
3226 if (elementName == element) {
3227 return;
3228 }
3229 }
3230 elementsList_.emplace_back(element);
3231 }
3232
IsSameCaller(const CallerInfo & callerInfo)3233 bool ConnectAbilitySession::IsSameCaller(const CallerInfo& callerInfo)
3234 {
3235 return (callerInfo.uid == callerInfo_.uid &&
3236 callerInfo.pid == callerInfo_.pid &&
3237 callerInfo.sourceDeviceId == callerInfo_.sourceDeviceId &&
3238 callerInfo.callerType == callerInfo_.callerType);
3239 }
3240
DumpConnectInfo(std::string & info)3241 void DistributedSchedService::DumpConnectInfo(std::string& info)
3242 {
3243 std::lock_guard<std::mutex> autoLock(distributedLock_);
3244 info += "connected remote abilities:\n";
3245 if (!distributedConnectAbilityMap_.empty()) {
3246 for (const auto& distributedConnect : distributedConnectAbilityMap_) {
3247 const std::list<ConnectAbilitySession> sessionsList = distributedConnect.second;
3248 DumpSessionsLocked(sessionsList, info);
3249 }
3250 } else {
3251 info += " <none info>\n";
3252 }
3253 }
3254
DumpSessionsLocked(const std::list<ConnectAbilitySession> & sessionsList,std::string & info)3255 void DistributedSchedService::DumpSessionsLocked(const std::list<ConnectAbilitySession>& sessionsList,
3256 std::string& info)
3257 {
3258 for (const auto& session : sessionsList) {
3259 info += " ";
3260 info += "SourceDeviceId: ";
3261 info += session.GetSourceDeviceId();
3262 info += ", ";
3263 info += "DestinationDeviceId: ";
3264 info += session.GetDestinationDeviceId();
3265 info += ", ";
3266 info += "CallerUid: ";
3267 info += std::to_string(session.GetCallerInfo().uid);
3268 info += ", ";
3269 info += "CallerPid: ";
3270 info += std::to_string(session.GetCallerInfo().pid);
3271 info += ", ";
3272 info += "CallerType: ";
3273 info += std::to_string(session.GetCallerInfo().callerType);
3274 DumpElementLocked(session.GetElementsList(), info);
3275 info += "\n";
3276 }
3277 }
3278
DumpElementLocked(const std::list<AppExecFwk::ElementName> & elementsList,std::string & info)3279 void DistributedSchedService::DumpElementLocked(const std::list<AppExecFwk::ElementName>& elementsList,
3280 std::string& info)
3281 {
3282 for (const auto& element : elementsList) {
3283 info += ", ";
3284 info += "BundleName: ";
3285 info += element.GetBundleName();
3286 info += ", ";
3287 info += "AbilityName: ";
3288 info += element.GetAbilityName();
3289 }
3290 }
3291
3292 #ifdef SUPPORT_DISTRIBUTED_MISSION_MANAGER
GetMissionInfos(const std::string & deviceId,int32_t numMissions,std::vector<MissionInfo> & missionInfos)3293 int32_t DistributedSchedService::GetMissionInfos(const std::string& deviceId, int32_t numMissions,
3294 std::vector<MissionInfo>& missionInfos)
3295 {
3296 return DistributedSchedMissionManager::GetInstance().GetMissionInfos(deviceId, numMissions, missionInfos);
3297 }
3298
NotifyMissionsChangedFromRemote(const std::vector<DstbMissionInfo> & missionInfos,const CallerInfo & callerInfo)3299 int32_t DistributedSchedService::NotifyMissionsChangedFromRemote(const std::vector<DstbMissionInfo>& missionInfos,
3300 const CallerInfo& callerInfo)
3301 {
3302 return DistributedSchedMissionManager::GetInstance()
3303 .NotifyMissionsChangedFromRemote(callerInfo, missionInfos);
3304 }
3305
GetRemoteMissionSnapshotInfo(const std::string & networkId,int32_t missionId,std::unique_ptr<MissionSnapshot> & missionSnapshot)3306 int32_t DistributedSchedService::GetRemoteMissionSnapshotInfo(const std::string& networkId, int32_t missionId,
3307 std::unique_ptr<MissionSnapshot>& missionSnapshot)
3308 {
3309 return DistributedSchedMissionManager::GetInstance()
3310 .GetRemoteMissionSnapshotInfo(networkId, missionId, missionSnapshot);
3311 }
3312
RegisterMissionListener(const std::u16string & devId,const sptr<IRemoteObject> & obj,int32_t callingUid)3313 int32_t DistributedSchedService::RegisterMissionListener(const std::u16string& devId,
3314 const sptr<IRemoteObject>& obj, int32_t callingUid)
3315 {
3316 if (!MultiUserManager::GetInstance().IsCallerForeground(callingUid)) {
3317 HILOGW("The current user is not foreground. callingUid: %{public}d.", callingUid);
3318 return DMS_NOT_FOREGROUND_USER;
3319 }
3320 return DistributedSchedMissionManager::GetInstance().RegisterMissionListener(devId, obj);
3321 }
3322
RegisterOnListener(const std::string & type,const sptr<IRemoteObject> & obj,int32_t callingUid)3323 int32_t DistributedSchedService::RegisterOnListener(const std::string& type,
3324 const sptr<IRemoteObject>& obj, int32_t callingUid)
3325 {
3326 return MultiUserManager::GetInstance().OnRegisterOnListener(type, obj, callingUid);
3327 }
3328
RegisterOffListener(const std::string & type,const sptr<IRemoteObject> & obj,int32_t callingUid)3329 int32_t DistributedSchedService::RegisterOffListener(const std::string& type,
3330 const sptr<IRemoteObject>& obj, int32_t callingUid)
3331 {
3332 return MultiUserManager::GetInstance().OnRegisterOffListener(type, obj, callingUid);
3333 }
3334
UnRegisterMissionListener(const std::u16string & devId,const sptr<IRemoteObject> & obj)3335 int32_t DistributedSchedService::UnRegisterMissionListener(const std::u16string& devId,
3336 const sptr<IRemoteObject>& obj)
3337 {
3338 return DistributedSchedMissionManager::GetInstance().UnRegisterMissionListener(devId, obj);
3339 }
3340
StartSyncRemoteMissions(const std::string & devId,bool fixConflict,int64_t tag,int32_t callingUid,uint32_t callingTokenId)3341 int32_t DistributedSchedService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag,
3342 int32_t callingUid, uint32_t callingTokenId)
3343 {
3344 if (!MultiUserManager::GetInstance().IsCallerForeground(callingUid)) {
3345 HILOGW("The current user is not foreground. callingUid: %{public}d.", callingUid);
3346 return DMS_NOT_FOREGROUND_USER;
3347 }
3348 return DistributedSchedMissionManager::GetInstance().StartSyncRemoteMissions(devId, fixConflict,
3349 tag, callingTokenId);
3350 }
3351
StopSyncRemoteMissions(const std::string & devId,int32_t callingUid)3352 int32_t DistributedSchedService::StopSyncRemoteMissions(const std::string& devId, int32_t callingUid)
3353 {
3354 if (!MultiUserManager::GetInstance().IsCallerForeground(callingUid)) {
3355 HILOGW("The current user is not foreground. callingUid: %{public}d.", callingUid);
3356 return DMS_NOT_FOREGROUND_USER;
3357 }
3358 return DistributedSchedMissionManager::GetInstance().StopSyncRemoteMissions(devId, false, true);
3359 }
3360
StartSyncMissionsFromRemote(const CallerInfo & callerInfo,std::vector<DstbMissionInfo> & missionInfos)3361 int32_t DistributedSchedService::StartSyncMissionsFromRemote(const CallerInfo& callerInfo,
3362 std::vector<DstbMissionInfo>& missionInfos)
3363 {
3364 return DistributedSchedMissionManager::GetInstance().StartSyncMissionsFromRemote(callerInfo, missionInfos);
3365 }
3366
StopSyncMissionsFromRemote(const CallerInfo & callerInfo)3367 int32_t DistributedSchedService::StopSyncMissionsFromRemote(const CallerInfo& callerInfo)
3368 {
3369 DistributedSchedMissionManager::GetInstance().StopSyncMissionsFromRemote(callerInfo.sourceDeviceId);
3370 return ERR_NONE;
3371 }
3372
SetMissionContinueState(int32_t missionId,const AAFwk::ContinueState & state,int32_t callingUid)3373 int32_t DistributedSchedService::SetMissionContinueState(int32_t missionId, const AAFwk::ContinueState &state,
3374 int32_t callingUid)
3375 {
3376 if (!MultiUserManager::GetInstance().IsCallerForeground(callingUid)) {
3377 HILOGW("The current user is not foreground. callingUid: %{public}d.", callingUid);
3378 return DMS_NOT_FOREGROUND_USER;
3379 }
3380
3381 auto event = (state == AAFwk::ContinueState::CONTINUESTATE_ACTIVE) ?
3382 MISSION_EVENT_ACTIVE: MISSION_EVENT_INACTIVE;
3383 int32_t currentAccountId = MultiUserManager::GetInstance().GetForegroundUser();
3384 DmsContinueConditionMgr::GetInstance().UpdateMissionStatus(currentAccountId, missionId, event);
3385
3386 auto sendMgr = MultiUserManager::GetInstance().GetCurrentSendMgr();
3387 CHECK_POINTER_RETURN_VALUE(sendMgr, DMS_NOT_GET_MANAGER, "sendMgr");
3388 sendMgr->OnMissionStatusChanged(missionId, event);
3389
3390 auto recomMgr = MultiUserManager::GetInstance().GetCurrentRecomMgr();
3391 CHECK_POINTER_RETURN_VALUE(recomMgr, DMS_NOT_GET_MANAGER, "recomMgr");
3392 recomMgr->OnMissionStatusChanged(missionId, event);
3393 return ERR_OK;
3394 }
3395 #endif
3396
RegisterDSchedEventListener(const DSchedEventType & type,const sptr<IRemoteObject> & callback)3397 int32_t DistributedSchedService::RegisterDSchedEventListener(const DSchedEventType& type,
3398 const sptr<IRemoteObject>& callback)
3399 {
3400 if (dschedContinuation_ == nullptr || collaborateCbMgr_ == nullptr) {
3401 HILOGE("object null!");
3402 return INVALID_PARAMETERS_ERR;
3403 }
3404 bool ret = false;
3405 switch (type) {
3406 case DMS_CONTINUE:
3407 ret = dschedContinuation_->PushCallback(callback);
3408 break;
3409 case DMS_COLLABORATION:
3410 ret = collaborateCbMgr_->PushCallback(callback);
3411 break;
3412 case DMS_ALL:
3413 ret = dschedContinuation_->PushCallback(callback) && collaborateCbMgr_->PushCallback(callback);
3414 break;
3415 default:
3416 HILOGE("Not support register Dms event listener with event type: %{public}d.", type);
3417 return INVALID_PARAMETERS_ERR;
3418 }
3419
3420 if (!ret) {
3421 HILOGE("The callback does not exist, type: %{public}d", type);
3422 return CALLBACK_HAS_NOT_REGISTERED;
3423 }
3424 HILOGD("Push %{public}d callback success.", type);
3425 return ERR_OK;
3426 }
3427
UnRegisterDSchedEventListener(const DSchedEventType & type,const sptr<IRemoteObject> & callback)3428 int32_t DistributedSchedService::UnRegisterDSchedEventListener(const DSchedEventType& type,
3429 const sptr<IRemoteObject>& callback)
3430 {
3431 if (dschedContinuation_ == nullptr || collaborateCbMgr_ == nullptr) {
3432 HILOGE("object null!");
3433 return INVALID_PARAMETERS_ERR;
3434 }
3435 bool result = 0;
3436 switch (type) {
3437 case DMS_CONTINUE:
3438 result = dschedContinuation_->CleanupCallback(callback);
3439 break;
3440 case DMS_COLLABORATION:
3441 result = collaborateCbMgr_->CleanupCallback(callback);
3442 break;
3443 case DMS_ALL:
3444 result = dschedContinuation_->CleanupCallback(callback) && collaborateCbMgr_->CleanupCallback(callback);
3445 break;
3446 default:
3447 break;
3448 }
3449
3450 if (!result) {
3451 HILOGI("The callback does not exist,type: %{public}d", type);
3452 } else {
3453 HILOGI("Clearing the callback succeeded.");
3454 }
3455 return 0;
3456 }
3457
GetContinueInfo(std::string & dstNetworkId,std::string & srcNetworkId)3458 int32_t DistributedSchedService::GetContinueInfo(std::string& dstNetworkId, std::string& srcNetworkId)
3459 {
3460 HILOGI("GetContinueInfo called");
3461 if (dschedContinuation_ == nullptr) {
3462 HILOGE("continuation object null!");
3463 return INVALID_PARAMETERS_ERR;
3464 }
3465 dstNetworkId = dschedContinuation_->continueInfo_.dstNetworkId_;
3466 srcNetworkId = dschedContinuation_->continueInfo_.srcNetworkId_;
3467 HILOGI("GetContinueInfo dstNetworkId: %{public}s, srcNetworkId: %{public}s",
3468 GetAnonymStr(dstNetworkId).c_str(), GetAnonymStr(srcNetworkId).c_str());
3469 return 0;
3470 }
3471
GetDSchedEventInfo(const DSchedEventType & type,std::vector<EventNotify> & events)3472 int32_t DistributedSchedService::GetDSchedEventInfo(const DSchedEventType &type, std::vector<EventNotify> &events)
3473 {
3474 int32_t callingUid = CheckCallingUid() ? DEFAULT_REQUEST_CODE : IPCSkeleton::GetCallingUid();
3475 HILOGI("GetDSchedEventInfo called, uid %{public}d, dms eventType %{public}d.", callingUid, type);
3476 switch (type) {
3477 case DMS_CONTINUE:
3478 GetContinueEventInfo(callingUid, events);
3479 break;
3480 case DMS_COLLABORATION:
3481 GetCollaborateEventInfo(callingUid, events);
3482 break;
3483 case DMS_ALL:
3484 GetContinueEventInfo(callingUid, events);
3485 GetCollaborateEventInfo(callingUid, events);
3486 break;
3487 default:
3488 HILOGI("Get dms event info not support eventType %{public}d.", type);
3489 return INVALID_PARAMETERS_ERR;
3490 }
3491 HILOGI("GetDSchedEventInfo end, uid %{public}d, eventType %{public}d, events size %{public}zu.",
3492 callingUid, type, events.size());
3493 return ERR_OK;
3494 }
3495
CheckCallingUid()3496 bool DistributedSchedService::CheckCallingUid()
3497 {
3498 // never allow non-system uid for distributed request
3499 auto callingUid = IPCSkeleton::GetCallingUid();
3500 return callingUid < HID_HAP;
3501 }
3502
GetContinueEventInfo(int32_t callingUid,std::vector<EventNotify> & events)3503 void DistributedSchedService::GetContinueEventInfo(int32_t callingUid, std::vector<EventNotify> &events)
3504 {
3505 if (callingUid == DEFAULT_REQUEST_CODE && dschedContinuation_ != nullptr) {
3506 events.emplace_back(dschedContinuation_->continueEvent_);
3507 return;
3508 }
3509
3510 std::vector<std::string> bundleNames;
3511 if (!BundleManagerInternal::GetBundleNameListFromBms(callingUid, bundleNames)) {
3512 HILOGE("Get bundle name from Bms failed");
3513 return;
3514 }
3515 for (const auto &bundleName : bundleNames) {
3516 HILOGD("Get bundle name %{public}s from Bms.", bundleName.c_str());
3517 if (bundleName == dschedContinuation_->continueEvent_.srcBundleName_ ||
3518 bundleName == dschedContinuation_->continueEvent_.destBundleName_) {
3519 events.emplace_back(dschedContinuation_->continueEvent_);
3520 }
3521 }
3522 }
3523
GetCollaborateEventInfo(int32_t callingUid,std::vector<EventNotify> & events)3524 void DistributedSchedService::GetCollaborateEventInfo(int32_t callingUid, std::vector<EventNotify> &events)
3525 {
3526 if (callingUid == DEFAULT_REQUEST_CODE) {
3527 GetCollaborateEventsByCallers(callingUid, "", events);
3528 GetCollaborateEventsByCallees(callingUid, "", events);
3529 return;
3530 }
3531
3532 std::string callingBundleName;
3533 if (!BundleManagerInternal::GetSpecifyBundleNameFromBms(callingUid, callingBundleName)) {
3534 HILOGE("Get specify bundle name for from Bms fail, uid %{public}d.", callingUid);
3535 return;
3536 }
3537 GetCollaborateEventsByCallers(callingUid, callingBundleName, events);
3538 GetCollaborateEventsByCallees(callingUid, callingBundleName, events);
3539 }
3540
GetCollaborateEventsByCallers(int32_t callingUid,const std::string & callingBundleName,std::vector<EventNotify> & events)3541 void DistributedSchedService::GetCollaborateEventsByCallers(int32_t callingUid, const std::string &callingBundleName,
3542 std::vector<EventNotify> &events)
3543 {
3544 std::lock_guard<std::mutex> autoLock(callerLock_);
3545 for (const auto &iter : callerMap_) {
3546 for (const auto &connectSession : iter.second) {
3547 auto bundleNames = connectSession.GetCallerInfo().bundleNames;
3548 if (callingUid != DEFAULT_REQUEST_CODE && callingUid != connectSession.GetCallerInfo().uid &&
3549 std::count(bundleNames.begin(), bundleNames.end(), callingBundleName) == 0) {
3550 HILOGE("Connect session callerInfo uid %{public}d is different from callingUid %{public}d, "
3551 "callingbundle %{public}s.", connectSession.GetCallerInfo().uid,
3552 callingUid, callingBundleName.c_str());
3553 continue;
3554 }
3555 for (const auto &element : connectSession.GetElementsList()) {
3556 EventNotify tempEvent;
3557 GetCurSrcCollaborateEvent(connectSession.GetCallerInfo(), element,
3558 DMS_DSCHED_EVENT_PROCESSING, ERR_OK, tempEvent);
3559 events.emplace_back(tempEvent);
3560 }
3561 }
3562 }
3563 }
3564
GetCollaborateEventsByCallees(int32_t callingUid,const std::string & callingBundleName,std::vector<EventNotify> & events)3565 void DistributedSchedService::GetCollaborateEventsByCallees(int32_t callingUid, const std::string &callingBundleName,
3566 std::vector<EventNotify> &events)
3567 {
3568 std::lock_guard<std::mutex> autoLock(calleeLock_);
3569 for (const auto &iter : calleeMap_) {
3570 if (callingUid != DEFAULT_REQUEST_CODE && callingBundleName != iter.second.element.GetBundleName()) {
3571 HILOGE("Connect session calleeInfo destBundleName %{public}s is different from "
3572 "callingBundleName %{public}s, callingUid %{public}d.", iter.second.element.GetBundleName().c_str(),
3573 callingBundleName.c_str(), callingUid);
3574 continue;
3575 }
3576
3577 EventNotify tempEvent;
3578 GetCurDestCollaborateEvent(iter.second.callerInfo, iter.second.element,
3579 DMS_DSCHED_EVENT_PROCESSING, ERR_OK, tempEvent);
3580 events.emplace_back(tempEvent);
3581 }
3582 }
3583
OnRemoteDied(const wptr<IRemoteObject> & remote)3584 void CallerDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
3585 {
3586 HILOGI("CallerDeathRecipient OnRemoteDied called");
3587 DistributedSchedAdapter::GetInstance().ProcessCallerDied(remote.promote(), deviceType_);
3588 }
3589
SetCallerInfo(int32_t callerUid,std::string localDeviceId,uint32_t accessToken,CallerInfo & callerInfo)3590 int32_t DistributedSchedService::SetCallerInfo(
3591 int32_t callerUid, std::string localDeviceId, uint32_t accessToken, CallerInfo& callerInfo)
3592 {
3593 callerInfo.uid = callerUid;
3594 callerInfo.callerType = CALLER_TYPE_HARMONY;
3595 callerInfo.sourceDeviceId = localDeviceId;
3596 callerInfo.accessToken = accessToken;
3597 if (!BundleManagerInternal::GetCallerAppIdFromBms(callerInfo.uid, callerInfo.callerAppId)) {
3598 HILOGE("GetCallerAppIdFromBms failed");
3599 return INVALID_PARAMETERS_ERR;
3600 }
3601 if (!BundleManagerInternal::GetBundleNameListFromBms(callerInfo.uid, callerInfo.bundleNames)) {
3602 HILOGE("GetBundleNameListFromBms failed");
3603 return INVALID_PARAMETERS_ERR;
3604 }
3605 callerInfo.extraInfoJson[DMS_VERSION_ID] = DMS_VERSION;
3606 return ERR_OK;
3607 }
3608
StartRemoteFreeInstall(const OHOS::AAFwk::Want & want,int32_t callerUid,int32_t requestCode,uint32_t accessToken,const sptr<IRemoteObject> & callback)3609 int32_t DistributedSchedService::StartRemoteFreeInstall(const OHOS::AAFwk::Want& want, int32_t callerUid,
3610 int32_t requestCode, uint32_t accessToken, const sptr<IRemoteObject>& callback)
3611 {
3612 HILOGI("called");
3613 std::string localDeviceId;
3614 std::string deviceId = want.GetElement().GetDeviceID();
3615 if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) {
3616 HILOGE("check deviceId failed");
3617 return INVALID_PARAMETERS_ERR;
3618 }
3619 sptr<IDistributedSched> remoteDms = GetRemoteDms(deviceId);
3620 if (remoteDms == nullptr) {
3621 HILOGE("get remoteDms failed");
3622 return INVALID_PARAMETERS_ERR;
3623 }
3624 if (dmsCallbackTask_ == nullptr) {
3625 HILOGE("callbackTask object null!");
3626 return INVALID_REMOTE_PARAMETERS_ERR;
3627 }
3628 int64_t taskId = dmsCallbackTask_->GenerateTaskId();
3629 LaunchType launchType = LaunchType::FREEINSTALL_START;
3630 if (((want.GetFlags() & AAFwk::Want::FLAG_ABILITY_CONTINUATION) != 0)) {
3631 launchType = LaunchType::FREEINSTALL_CONTINUE;
3632 }
3633 if (dmsCallbackTask_->PushCallback(taskId, callback, deviceId, launchType, want) != ERR_OK) {
3634 HILOGE("Push callback failed!");
3635 return INVALID_REMOTE_PARAMETERS_ERR;
3636 }
3637 if (launchType == LaunchType::FREEINSTALL_CONTINUE) {
3638 dmsCallbackTask_->SetContinuationMissionMap(taskId, want.GetIntParam("sessionId", -1));
3639 }
3640
3641 CallerInfo callerInfo;
3642 if (SetCallerInfo(callerUid, localDeviceId, accessToken, callerInfo) != ERR_OK) {
3643 HILOGE("SetCallerInfo failed");
3644 return INVALID_PARAMETERS_ERR;
3645 }
3646 AccountInfo accountInfo = {};
3647 if ((DistributedSchedPermission::GetInstance().GetAccountInfo(deviceId, callerInfo, accountInfo)) != ERR_OK) {
3648 HILOGE("GetAccountInfo failed");
3649 return INVALID_PARAMETERS_ERR;
3650 }
3651 AAFwk::Want* newWant = const_cast<Want*>(&want);
3652 newWant->SetParam(DMS_SRC_NETWORK_ID, localDeviceId);
3653 FreeInstallInfo info = {*newWant, requestCode, callerInfo, accountInfo};
3654 int32_t result = remoteDms->StartFreeInstallFromRemote(info, taskId);
3655 if (result != ERR_OK) {
3656 HILOGE("result = %{public}d", result);
3657 CallbackTaskItem item = dmsCallbackTask_->PopCallback(taskId);
3658 NotifyFreeInstallResult(item, result);
3659 }
3660 return result;
3661 }
3662
StartFreeInstallFromRemote(const FreeInstallInfo & info,int64_t taskId)3663 int32_t DistributedSchedService::StartFreeInstallFromRemote(const FreeInstallInfo& info, int64_t taskId)
3664 {
3665 HILOGI("begin taskId : %{public} " PRId64 ". ", taskId);
3666 std::string localDeviceId;
3667 std::string deviceId = info.want.GetElement().GetDeviceID();
3668 if (!GetLocalDeviceId(localDeviceId) ||
3669 !CheckDeviceIdFromRemote(localDeviceId, deviceId, info.callerInfo.sourceDeviceId)) {
3670 HILOGE("check deviceId failed");
3671 return INVALID_REMOTE_PARAMETERS_ERR;
3672 }
3673 if (DistributedSchedPermission::GetInstance().IsHigherAclVersion(info.callerInfo)) {
3674 bool result = CheckSinkAccessControlUser(info);
3675 if (!result) {
3676 HILOGE("Check sink access control failed.");
3677 return INVALID_PARAMETERS_ERR;
3678 }
3679 }
3680 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->Connect();
3681 if (err != ERR_OK) {
3682 HILOGE("connect ability server failed %{public}d", err);
3683 return err;
3684 }
3685 int32_t activeAccountId = -1;
3686 err = QueryOsAccount(activeAccountId);
3687 if (err != ERR_OK) {
3688 return err;
3689 }
3690
3691 sptr<DmsFreeInstallCallback> callback(new DmsFreeInstallCallback(taskId, info));
3692 err = AAFwk::AbilityManagerClient::GetInstance()->FreeInstallAbilityFromRemote(
3693 info.want, callback, activeAccountId, info.requestCode);
3694 if (err != ERR_OK) {
3695 HILOGE("FreeInstallAbilityFromRemote failed %{public}d", err);
3696 }
3697 return err;
3698 }
3699
CheckSinkAccessControlUser(const FreeInstallInfo & info)3700 bool DistributedSchedService::CheckSinkAccessControlUser(const FreeInstallInfo& info)
3701 {
3702 DmAccessCaller dmSrcCaller = {
3703 .accountId = info.accountInfo.activeAccountId,
3704 .networkId = info.callerInfo.sourceDeviceId,
3705 .userId = info.accountInfo.userId,
3706 };
3707 AccountInfo dstAccountInfo;
3708 if (!DistributedSchedMissionManager::GetInstance().GetOsAccountData(dstAccountInfo)) {
3709 HILOGE("Get Os accountId and userId fail.");
3710 return false;
3711 }
3712 std::string dstNetworkId;
3713 if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(dstNetworkId)) {
3714 HILOGE("GetLocalDeviceId failed");
3715 return false;
3716 }
3717
3718 DmAccessCallee dmDstCallee = {
3719 .accountId = dstAccountInfo.activeAccountId,
3720 .networkId = dstNetworkId,
3721 .userId = dstAccountInfo.userId,
3722 };
3723 return DeviceManager::GetInstance().CheckSinkAccessControl(dmSrcCaller, dmDstCallee);
3724 }
3725
NotifyCompleteFreeInstall(const FreeInstallInfo & info,int64_t taskId,int32_t resultCode)3726 int32_t DistributedSchedService::NotifyCompleteFreeInstall(
3727 const FreeInstallInfo& info, int64_t taskId, int32_t resultCode)
3728 {
3729 HILOGI("taskId = %{public}" PRId64 ".", taskId);
3730 if (taskId <= 0) {
3731 HILOGE("taskId invalid!");
3732 return INVALID_PARAMETERS_ERR;
3733 }
3734 if (resultCode != ERR_OK) {
3735 HILOGE("free install failed, resultCode : %{public}d", resultCode);
3736 return HandleRemoteNotify(info, taskId, resultCode);
3737 }
3738 int32_t result = StartLocalAbility(info, taskId, resultCode);
3739 return HandleRemoteNotify(info, taskId, result);
3740 }
3741
StartLocalAbility(const FreeInstallInfo & info,int64_t taskId,int32_t resultCode)3742 int32_t DistributedSchedService::StartLocalAbility(const FreeInstallInfo& info, int64_t taskId, int32_t resultCode)
3743 {
3744 std::string localDeviceId;
3745 if (!GetLocalDeviceId(localDeviceId)) {
3746 HILOGE("get local deviceId failed");
3747 return INVALID_REMOTE_PARAMETERS_ERR;
3748 }
3749 int32_t result = CheckTargetPermission(info.want, info.callerInfo, info.accountInfo, START_PERMISSION, true);
3750 if (result != ERR_OK) {
3751 HILOGE("CheckTargetPermission failed!!");
3752 return result;
3753 }
3754
3755 AAFwk::Want* want = const_cast<Want*>(&info.want);
3756 want->RemoveFlags(OHOS::AAFwk::Want::FLAG_INSTALL_ON_DEMAND);
3757 return StartAbility(*want, info.requestCode);
3758 }
3759
StartAbility(const OHOS::AAFwk::Want & want,int32_t requestCode)3760 int32_t DistributedSchedService::StartAbility(const OHOS::AAFwk::Want& want, int32_t requestCode)
3761 {
3762 if ((want.GetFlags() & AAFwk::Want::FLAG_ABILITY_CONTINUATION) != 0 &&
3763 !dataShareManager.IsCurrentContinueSwitchOn()) {
3764 HILOGE("ContinueSwitch status is off");
3765 return DMS_PERMISSION_DENIED;
3766 }
3767 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->Connect();
3768 if (err != ERR_OK) {
3769 HILOGE("connect ability server failed %{public}d", err);
3770 return err;
3771 }
3772 int32_t activeAccountId = -1;
3773 err = QueryOsAccount(activeAccountId);
3774 if (err != ERR_OK) {
3775 return err;
3776 }
3777 if (want.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
3778 HILOGI("StartAbilityForResult start, flag is %{public}d", want.GetFlags());
3779 sptr<IRemoteObject> dmsTokenCallback(new DmsTokenCallback());
3780 err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, dmsTokenCallback, requestCode,
3781 activeAccountId);
3782 } else {
3783 HILOGI("StartAbility start, flag is %{public}d", want.GetFlags());
3784 if (DmsContinueTime::GetInstance().GetPull()) {
3785 int64_t begin = GetTickCount();
3786 DmsContinueTime::GetInstance().SetDurationBegin(DMSDURATION_STARTABILITY, begin);
3787 }
3788 DmsContinueTime::GetInstance().SetDstAbilityName(want.GetElement().GetAbilityName());
3789 DmsContinueTime::GetInstance().SetDstBundleName(want.GetElement().GetBundleName());
3790 DmsRadar::GetInstance().ClickIconDmsStartAbility("StartAbility", err);
3791 err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, requestCode, activeAccountId);
3792 }
3793 if (err != ERR_OK) {
3794 HILOGE("StartAbility failed %{public}d", err);
3795 }
3796 return err;
3797 }
3798
HandleRemoteNotify(const FreeInstallInfo & info,int64_t taskId,int32_t resultCode)3799 int32_t DistributedSchedService::HandleRemoteNotify(const FreeInstallInfo& info, int64_t taskId, int32_t resultCode)
3800 {
3801 HILOGI("begin taskId = %{public}" PRId64 ", resultCode = %{public}d", taskId, resultCode);
3802 sptr<IDistributedSched> remoteDms = GetRemoteDms(info.callerInfo.sourceDeviceId);
3803 if (remoteDms == nullptr) {
3804 HILOGE("get remote dms null!");
3805 return INVALID_PARAMETERS_ERR;
3806 }
3807 if (taskId <= 0) {
3808 HILOGE("taskId invalid!");
3809 return INVALID_PARAMETERS_ERR;
3810 }
3811 return remoteDms->NotifyCompleteFreeInstallFromRemote(taskId, resultCode);
3812 }
3813
NotifyCompleteFreeInstallFromRemote(int64_t taskId,int32_t resultCode)3814 int32_t DistributedSchedService::NotifyCompleteFreeInstallFromRemote(int64_t taskId, int32_t resultCode)
3815 {
3816 HILOGI("begin taskId = %{public}" PRId64 ", resultCode = %{public}d", taskId, resultCode);
3817 if (dmsCallbackTask_ == nullptr || dschedContinuation_ == nullptr) {
3818 HILOGE("callbackTask object null!");
3819 return INVALID_REMOTE_PARAMETERS_ERR;
3820 }
3821
3822 LaunchType launchType = dmsCallbackTask_->GetLaunchType(taskId);
3823 CallbackTaskItem item = dmsCallbackTask_->PopCallback(taskId);
3824 if (launchType == LaunchType::FREEINSTALL_START) {
3825 return NotifyFreeInstallResult(item, resultCode);
3826 }
3827
3828 if (resultCode == ERR_OK) {
3829 HILOGD("continue free install success, waiting for continue result callback.");
3830 dmsCallbackTask_->PopContinuationMissionMap(taskId);
3831 return ERR_OK;
3832 }
3833
3834 int32_t missionId = dmsCallbackTask_->GetContinuaionMissionId(taskId);
3835 NotifyContinuationCallbackResult(missionId, CONTINUE_FREE_INSTALL_FAILED);
3836 dmsCallbackTask_->PopContinuationMissionMap(taskId);
3837 return ERR_OK;
3838 }
3839
NotifyFreeInstallResult(const CallbackTaskItem item,int32_t resultCode)3840 int32_t DistributedSchedService::NotifyFreeInstallResult(const CallbackTaskItem item, int32_t resultCode)
3841 {
3842 HILOGI("taskId : %{public} " PRId64 ". ", item.taskId);
3843 if (item.callback == nullptr) {
3844 HILOGE("item callback null!");
3845 return INVALID_REMOTE_PARAMETERS_ERR;
3846 }
3847 MessageParcel data;
3848 if (!data.WriteInterfaceToken(ATOMIC_SERVICE_STATUS_CALLBACK_TOKEN)) {
3849 HILOGE("Write interface token failed.");
3850 return INVALID_REMOTE_PARAMETERS_ERR;
3851 }
3852
3853 if (!data.WriteInt32(resultCode)) {
3854 HILOGE("Write resultCode error.");
3855 return INVALID_REMOTE_PARAMETERS_ERR;
3856 }
3857
3858 if (!data.WriteParcelable(&item.want)) {
3859 HILOGE("Write want error.");
3860 return INVALID_REMOTE_PARAMETERS_ERR;
3861 }
3862
3863 int32_t userId = 0;
3864 if (!data.WriteInt32(userId)) {
3865 HILOGE("Write userId error.");
3866 return INVALID_REMOTE_PARAMETERS_ERR;
3867 }
3868
3869 MessageParcel reply;
3870 MessageOption option;
3871 return item.callback->SendRequest(IASS_CALLBACK_ON_REMOTE_FREE_INSTALL_DONE, data, reply, option);
3872 }
3873
RegisterAppStateObserver(const OHOS::AAFwk::Want & want,const CallerInfo & callerInfo,const sptr<IRemoteObject> & srcConnect,const sptr<IRemoteObject> & callbackWrapper)3874 bool DistributedSchedService::RegisterAppStateObserver(const OHOS::AAFwk::Want& want, const CallerInfo& callerInfo,
3875 const sptr<IRemoteObject>& srcConnect, const sptr<IRemoteObject>& callbackWrapper)
3876 {
3877 HILOGD("register app state observer called");
3878 int32_t connectToken = want.GetIntParam(DMS_CONNECT_TOKEN, DEFAULT_DMS_CONNECT_TOKEN);
3879 HILOGD("Get connectToken = %{private}s", GetAnonymStr(std::to_string(connectToken)).c_str());
3880 if (connectToken == DEFAULT_DMS_CONNECT_TOKEN) {
3881 return false;
3882 }
3883 sptr<AppExecFwk::IAppMgr> appObject = GetAppManager();
3884 if (appObject == nullptr) {
3885 HILOGE("failed to get app manager service");
3886 return false;
3887 }
3888 sptr<AppStateObserver> appStateObserver;
3889 std::string bundleName = want.GetElement().GetBundleName();
3890 {
3891 std::lock_guard<std::mutex> autoLock(registerMutex_);
3892 if (!bundleNameMap_.count(bundleName)) {
3893 std::vector<std::string> bundleNameList = {bundleName};
3894 appStateObserver = sptr<AppStateObserver>(new (std::nothrow) AppStateObserver());
3895 bundleNameMap_[bundleName] = appStateObserver;
3896 int ret = appObject->RegisterApplicationStateObserver(appStateObserver, bundleNameList);
3897 if (ret != ERR_OK) {
3898 HILOGE("failed to register application state observer, ret = %{public}d", ret);
3899 return false;
3900 }
3901 }
3902 appStateObserver = bundleNameMap_[bundleName];
3903 }
3904 HILOGI("register application state observer success");
3905 {
3906 std::lock_guard<std::mutex> autoLock(observerLock_);
3907 Want* newWant = const_cast<Want*>(&want);
3908 newWant->RemoveParam(DMS_MISSION_ID);
3909 newWant->RemoveParam(DMS_CONNECT_TOKEN);
3910 observerMap_[callbackWrapper] = {appStateObserver, callerInfo.sourceDeviceId, connectToken,
3911 want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(), srcConnect};
3912 HILOGI("add observerMap_ success");
3913 }
3914 return true;
3915 }
3916
UnregisterAppStateObserver(const sptr<IRemoteObject> & callbackWrapper)3917 void DistributedSchedService::UnregisterAppStateObserver(const sptr<IRemoteObject>& callbackWrapper)
3918 {
3919 HILOGD("unregister app state observer called");
3920 if (callbackWrapper == nullptr) {
3921 HILOGD("callbackWrapper is nullptr");
3922 return;
3923 }
3924 bool unRegisterFlag = true;
3925 std::string bundleName;
3926 sptr<AppStateObserver> appStateObserver;
3927 {
3928 std::lock_guard<std::mutex> autoLock(observerLock_);
3929 auto it = observerMap_.find(callbackWrapper);
3930 if (it == observerMap_.end()) {
3931 HILOGE("state observer not found");
3932 return;
3933 }
3934 appStateObserver = it->second.appStateObserver;
3935 bundleName = it->second.dstBundleName;
3936 observerMap_.erase(it);
3937 for (auto iter = observerMap_.begin(); iter != observerMap_.end(); iter++) {
3938 if (iter->second.dstBundleName == bundleName) {
3939 unRegisterFlag = false;
3940 break;
3941 }
3942 }
3943 HILOGI("remove app state observer success");
3944 }
3945 if (unRegisterFlag) {
3946 {
3947 std::lock_guard<std::mutex> autoLock(registerMutex_);
3948 bundleNameMap_.erase(bundleName);
3949 }
3950 sptr<AppExecFwk::IAppMgr> appObject = GetAppManager();
3951 if (appObject == nullptr) {
3952 HILOGE("failed to get app manager service");
3953 return;
3954 }
3955 int ret = appObject->UnregisterApplicationStateObserver(appStateObserver);
3956 if (ret != ERR_OK) {
3957 HILOGE("failed to unregister application state observer, ret = %{public}d", ret);
3958 return;
3959 }
3960 }
3961 HILOGI("unregister application state observer success");
3962 }
3963
3964 // LCOV_EXCL_START
GetAppManager()3965 sptr<AppExecFwk::IAppMgr> DistributedSchedService::GetAppManager()
3966 {
3967 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
3968 if (samgr == nullptr) {
3969 HILOGE("system ability manager is nullptr.");
3970 return nullptr;
3971 }
3972
3973 sptr<AppExecFwk::IAppMgr> appObject =
3974 iface_cast<AppExecFwk::IAppMgr>(samgr->GetSystemAbility(APP_MGR_SERVICE_ID));
3975 if (appObject == nullptr) {
3976 HILOGE("failed to get app manager service");
3977 return nullptr;
3978 }
3979 return appObject;
3980 }
3981 // LCOV_EXCL_STOP
3982
NotifyStateChanged(int32_t abilityState,AppExecFwk::ElementName & element,const sptr<IRemoteObject> & token)3983 int32_t DistributedSchedService::NotifyStateChanged(int32_t abilityState, AppExecFwk::ElementName& element,
3984 const sptr<IRemoteObject>& token)
3985 {
3986 std::string srcDeviceId = "";
3987 int32_t connectToken = 0;
3988 {
3989 std::lock_guard<std::mutex> autoLock(observerLock_);
3990 for (auto iter = observerMap_.begin(); iter != observerMap_.end(); iter++) {
3991 if (iter->second.dstBundleName == element.GetBundleName() &&
3992 iter->second.dstAbilityName == element.GetAbilityName() && token == iter->second.token) {
3993 srcDeviceId = iter->second.srcDeviceId;
3994 connectToken = iter->second.connectToken;
3995 HILOGD("get srcDeviceId and missionId success");
3996 break;
3997 }
3998 }
3999 }
4000 HILOGD("Get connectToken = %{private}s", GetAnonymStr(std::to_string(connectToken)).c_str());
4001 std::string localDeviceId;
4002 if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, srcDeviceId)) {
4003 HILOGE("check deviceId failed");
4004 return INVALID_PARAMETERS_ERR;
4005 }
4006 sptr<IDistributedSched> remoteDms = GetRemoteDms(srcDeviceId);
4007 if (remoteDms == nullptr) {
4008 HILOGE("get remoteDms failed");
4009 return INVALID_PARAMETERS_ERR;
4010 }
4011 element.SetDeviceID(localDeviceId);
4012 return remoteDms->NotifyStateChangedFromRemote(abilityState, connectToken, element);
4013 }
4014
NotifyStateChangedFromRemote(int32_t abilityState,int32_t connectToken,const AppExecFwk::ElementName & element)4015 int32_t DistributedSchedService::NotifyStateChangedFromRemote(int32_t abilityState, int32_t connectToken,
4016 const AppExecFwk::ElementName& element)
4017 {
4018 HILOGD("Get connectToken = %{private}s", GetAnonymStr(std::to_string(connectToken)).c_str());
4019 sptr<IRemoteObject> connect;
4020 {
4021 std::lock_guard<std::mutex> autoLock(callLock_);
4022 for (auto iter = callMap_.begin(); iter != callMap_.end(); iter++) {
4023 if (iter->second.connectToken == connectToken) {
4024 connect = iter->first;
4025 break;
4026 }
4027 }
4028 HILOGD("get connect success");
4029 }
4030 if (connect == nullptr) {
4031 HILOGE("NotifyStateChangedFromRemote connect is null");
4032 return INVALID_PARAMETERS_ERR;
4033 }
4034 MessageParcel data;
4035 if (!data.WriteInterfaceToken(CONNECTION_CALLBACK_INTERFACE_TOKEN)) {
4036 HILOGE("Write interface token failed.");
4037 return INVALID_PARAMETERS_ERR;
4038 }
4039 PARCEL_WRITE_HELPER(data, Parcelable, &element);
4040 PARCEL_WRITE_HELPER(data, Int32, abilityState);
4041 MessageParcel reply;
4042 MessageOption option(MessageOption::TF_ASYNC);
4043 HILOGD("ON_REMOTE_STATE_CHANGED start");
4044 int32_t result = connect->SendRequest(IAbilityConnection::ON_REMOTE_STATE_CHANGED, data, reply, option);
4045 HILOGD("ON_REMOTE_STATE_CHANGED end, %{public}d", result);
4046 return ERR_OK;
4047 }
4048
CheckTargetPermission(const OHOS::AAFwk::Want & want,const CallerInfo & callerInfo,const AccountInfo & accountInfo,int32_t flag,bool needQueryExtension)4049 int32_t DistributedSchedService::CheckTargetPermission(const OHOS::AAFwk::Want& want,
4050 const CallerInfo& callerInfo, const AccountInfo& accountInfo, int32_t flag,
4051 bool needQueryExtension)
4052 {
4053 DistributedSchedPermission& permissionInstance = DistributedSchedPermission::GetInstance();
4054 AppExecFwk::AbilityInfo targetAbility;
4055 bool result = permissionInstance.GetTargetAbility(want, targetAbility, needQueryExtension);
4056 if (!result) {
4057 HILOGE("GetTargetAbility can not find the target ability");
4058 return INVALID_PARAMETERS_ERR;
4059 }
4060 HILOGD("target ability info bundleName:%{public}s abilityName:%{public}s visible:%{public}d",
4061 targetAbility.bundleName.c_str(), targetAbility.name.c_str(), targetAbility.visible);
4062 if (targetAbility.type == AppExecFwk::AbilityType::EXTENSION &&
4063 targetAbility.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DISTRIBUTED) {
4064 HILOGE("Dont have the permission to start DExtension.");
4065 return DMS_PERMISSION_DENIED;
4066 }
4067 HILOGD("callerType:%{public}d accountType:%{public}d callerUid:%{public}d AccessTokenID:%{public}s",
4068 callerInfo.callerType, accountInfo.accountType, callerInfo.uid,
4069 GetAnonymStr(std::to_string(callerInfo.accessToken)).c_str());
4070 if (flag == START_PERMISSION) {
4071 HILOGD("start CheckStartPermission");
4072 return permissionInstance.CheckStartPermission(want, callerInfo, accountInfo, targetAbility, true);
4073 } else if (flag == CALL_PERMISSION) {
4074 HILOGD("Collaboration start check get caller permission");
4075 return permissionInstance.CheckGetCallerPermission(want, callerInfo, accountInfo, targetAbility);
4076 } else if (flag == SEND_RESULT_PERMISSION) {
4077 HILOGD("Collaboration start check send result permission");
4078 return permissionInstance.CheckSendResultPermission(want, callerInfo, accountInfo, targetAbility);
4079 }
4080 HILOGE("CheckTargetPermission denied!!");
4081 return DMS_PERMISSION_DENIED;
4082 }
4083
CheckTargetPermission4DiffBundle(const OHOS::AAFwk::Want & want,const CallerInfo & callerInfo,const AccountInfo & accountInfo,int32_t flag,bool needQueryExtension)4084 int32_t DistributedSchedService::CheckTargetPermission4DiffBundle(const OHOS::AAFwk::Want& want,
4085 const CallerInfo& callerInfo, const AccountInfo& accountInfo, int32_t flag,
4086 bool needQueryExtension)
4087 {
4088 DistributedSchedPermission& permissionInstance = DistributedSchedPermission::GetInstance();
4089 AppExecFwk::AbilityInfo targetAbility;
4090 bool result = permissionInstance.GetTargetAbility(want, targetAbility, needQueryExtension);
4091 if (!result) {
4092 HILOGE("GetTargetAbility can not find the target ability");
4093 return INVALID_PARAMETERS_ERR;
4094 }
4095 HILOGD("target ability info bundleName:%{public}s abilityName:%{public}s visible:%{public}d",
4096 targetAbility.bundleName.c_str(), targetAbility.name.c_str(), targetAbility.visible);
4097 HILOGD("callerType:%{public}d accountType:%{public}d callerUid:%{public}d AccessTokenID:%{public}s",
4098 callerInfo.callerType, accountInfo.accountType, callerInfo.uid,
4099 GetAnonymStr(std::to_string(callerInfo.accessToken)).c_str());
4100 if (flag == START_PERMISSION) {
4101 HILOGD("start CheckStartPermission");
4102 return permissionInstance.CheckStartPermission(want, callerInfo, accountInfo, targetAbility, false);
4103 } else if (flag == CALL_PERMISSION) {
4104 HILOGD("Collaboration start check get caller permission");
4105 return permissionInstance.CheckGetCallerPermission(want, callerInfo, accountInfo, targetAbility);
4106 } else if (flag == SEND_RESULT_PERMISSION) {
4107 HILOGD("Collaboration start check send result permission");
4108 return permissionInstance.CheckSendResultPermission(want, callerInfo, accountInfo, targetAbility);
4109 }
4110 HILOGE("CheckTargetPermission denied!!");
4111 return DMS_PERMISSION_DENIED;
4112 }
4113
CheckCollabStartPermission(const OHOS::AAFwk::Want & want,const CallerInfo & callerInfo,const AccountInfo & accountInfo,bool needQueryExtension)4114 int32_t DistributedSchedService::CheckCollabStartPermission(const OHOS::AAFwk::Want& want,
4115 const CallerInfo& callerInfo, const AccountInfo& accountInfo, bool needQueryExtension)
4116 {
4117 DistributedSchedPermission& permissionInstance = DistributedSchedPermission::GetInstance();
4118 AppExecFwk::AbilityInfo targetAbility;
4119 bool result = permissionInstance.GetTargetAbility(want, targetAbility, needQueryExtension);
4120 if (!result) {
4121 HILOGE("GetTargetAbility can not find the target ability");
4122 return INVALID_PARAMETERS_ERR;
4123 }
4124 HILOGD("target ability info bundleName:%{public}s abilityName:%{public}s visible:%{public}d",
4125 targetAbility.bundleName.c_str(), targetAbility.name.c_str(), targetAbility.visible);
4126 HILOGD("callerType:%{public}d accountType:%{public}d callerUid:%{public}d AccessTokenID:%{public}s",
4127 callerInfo.callerType, accountInfo.accountType, callerInfo.uid,
4128 GetAnonymStr(std::to_string(callerInfo.accessToken)).c_str());
4129 HILOGD("start CheckStartPermission");
4130 return permissionInstance.CheckCollabStartPermission(want, callerInfo, accountInfo, targetAbility);
4131 }
4132
StopRemoteExtensionAbility(const OHOS::AAFwk::Want & want,int32_t callerUid,uint32_t accessToken,int32_t extensionType)4133 int32_t DistributedSchedService::StopRemoteExtensionAbility(const OHOS::AAFwk::Want& want, int32_t callerUid,
4134 uint32_t accessToken, int32_t extensionType)
4135 {
4136 std::string localDeviceId;
4137 std::string deviceId = want.GetDeviceId();
4138 if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) {
4139 HILOGE("CheckDeviceId failed");
4140 return INVALID_PARAMETERS_ERR;
4141 }
4142 sptr<IDistributedSched> remoteDms = GetRemoteDms(deviceId);
4143 if (remoteDms == nullptr) {
4144 HILOGE("GetRemoteDms failed");
4145 return INVALID_PARAMETERS_ERR;
4146 }
4147 CallerInfo callerInfo;
4148 callerInfo.sourceDeviceId = localDeviceId;
4149 callerInfo.uid = callerUid;
4150 callerInfo.accessToken = accessToken;
4151 if (!BundleManagerInternal::GetCallerAppIdFromBms(callerInfo.uid, callerInfo.callerAppId)) {
4152 HILOGE("GetCallerAppIdFromBms failed");
4153 return INVALID_PARAMETERS_ERR;
4154 }
4155 if (!BundleManagerInternal::GetBundleNameListFromBms(callerInfo.uid, callerInfo.bundleNames)) {
4156 HILOGE("GetBundleNameListFromBms failed");
4157 return INVALID_PARAMETERS_ERR;
4158 }
4159 AccountInfo accountInfo = {};
4160 if ((DistributedSchedPermission::GetInstance().GetAccountInfo(deviceId, callerInfo, accountInfo)) != ERR_OK) {
4161 HILOGE("GetAccountInfo failed");
4162 return INVALID_PARAMETERS_ERR;
4163 }
4164 AAFwk::Want remoteWant = want;
4165 remoteWant.SetParam(DMS_SRC_BUNDLE_NAMES, callerInfo.bundleNames);
4166 remoteWant.SetParam(DMS_SRC_NETWORK_ID, localDeviceId);
4167 return remoteDms->StopExtensionAbilityFromRemote(remoteWant, callerInfo, accountInfo, extensionType);
4168 }
4169
StopExtensionAbilityFromRemote(const OHOS::AAFwk::Want & remoteWant,const CallerInfo & callerInfo,const AccountInfo & accountInfo,int32_t extensionType)4170 int32_t DistributedSchedService::StopExtensionAbilityFromRemote(const OHOS::AAFwk::Want& remoteWant,
4171 const CallerInfo& callerInfo, const AccountInfo& accountInfo, int32_t extensionType)
4172 {
4173 std::string localDeviceId;
4174 std::string destinationDeviceId = remoteWant.GetElement().GetDeviceID();
4175 if (!GetLocalDeviceId(localDeviceId) ||
4176 !CheckDeviceIdFromRemote(localDeviceId, destinationDeviceId, callerInfo.sourceDeviceId)) {
4177 HILOGE("check deviceId failed");
4178 return INVALID_REMOTE_PARAMETERS_ERR;
4179 }
4180
4181 int32_t permissionValid = CheckTargetPermission(remoteWant, callerInfo, accountInfo, START_PERMISSION, true);
4182 if (permissionValid != ERR_OK) {
4183 HILOGE("CheckTargetPermission failed!!");
4184 return DMS_PERMISSION_DENIED;
4185 }
4186 Want want = remoteWant;
4187 want.RemoveParam(DMS_SRC_NETWORK_ID);
4188 sptr<IRemoteObject> callerToken(new DmsTokenCallback());
4189
4190 int32_t activeAccountId = -1;
4191 ErrCode err = QueryOsAccount(activeAccountId);
4192 if (err != ERR_OK) {
4193 return err;
4194 }
4195
4196 return AAFwk::AbilityManagerClient::GetInstance()->StopExtensionAbility(
4197 want, callerToken, activeAccountId, static_cast<AppExecFwk::ExtensionAbilityType>(extensionType));
4198 }
4199
SetCleanMissionFlag(const OHOS::AAFwk::Want & want,int32_t missionId)4200 void DistributedSchedService::SetCleanMissionFlag(const OHOS::AAFwk::Want& want, int32_t missionId)
4201 {
4202 auto value = want.GetParams().GetParam(SUPPORT_CONTINUE_SOURCE_EXIT_KEY);
4203 IBoolean *ao = IBoolean::Query(value);
4204 bool isCleanMission = true;
4205 if (ao != nullptr) {
4206 isCleanMission = AAFwk::Boolean::Unbox(ao);
4207 }
4208 if (dschedContinuation_ == nullptr) {
4209 HILOGW("continuation object null!");
4210 return;
4211 }
4212 dschedContinuation_->SetCleanMissionFlag(missionId, isCleanMission);
4213 }
4214 } // namespace DistributedSchedule
4215 } // namespace OHOS
4216