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