1 /*
2 * Copyright (c) 2022-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 "device_manager_service.h"
17
18 #include "cJSON.h"
19 #include <dlfcn.h>
20 #include <functional>
21 #include "app_manager.h"
22 #include "dm_constants.h"
23 #include "dm_crypto.h"
24 #include "dm_hidumper.h"
25 #include "dm_softbus_cache.h"
26 #include "parameter.h"
27 #include "permission_manager.h"
28 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
29 #include "common_event_support.h"
30 #include "datetime_ex.h"
31 #include "deviceprofile_connector.h"
32 #include "device_name_manager.h"
33 #include "dm_comm_tool.h"
34 #include "dm_random.h"
35 #include "dm_transport_msg.h"
36 #include "dm_jsonstr_handle.h"
37 #include "ipc_skeleton.h"
38 #include "iservice_registry.h"
39 #include "kv_adapter_manager.h"
40 #include "multiple_user_connector.h"
41 #include "relationship_sync_mgr.h"
42 #include "openssl/sha.h"
43 #include "system_ability_definition.h"
44 #if defined(SUPPORT_POWER_MANAGER)
45 #include "power_mgr_client.h"
46 #endif // SUPPORT_POWER_MANAGER
47 #if defined(SUPPORT_BLUETOOTH)
48 #include "softbus_publish.h"
49 #include "bluetooth_def.h"
50 #include "bluetooth_host.h"
51 #endif // SUPPORT_BLUETOOTH
52 #if defined(SUPPORT_WIFI)
53 #include "softbus_publish.h"
54 #include "wifi_device.h"
55 #include "wifi_msg.h"
56 #endif // SUPPORT_WIFI
57 #endif
58
59 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
60 constexpr const char* LIB_IMPL_NAME = "libdevicemanagerserviceimpl.z.so";
61 using namespace OHOS::EventFwk;
62 #else
63 constexpr const char* LIB_IMPL_NAME = "libdevicemanagerserviceimpl.so";
64 #endif
65 constexpr const char* LIB_DM_ADAPTER_NAME = "libdevicemanageradapter.z.so";
66 constexpr const char* LIB_DM_RESIDENT_NAME = "libdevicemanagerresident.z.so";
67 constexpr const char* LIB_DM_DEVICE_RISK_DETECT_NAME = "libdevicemanagerriskdetect.z.so";
68 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) && !defined(DEVICE_MANAGER_COMMON_FLAG)
69 constexpr const char* LIB_DM_CHECK_API_WHITE_LIST_NAME = "libdm_check_api_whitelist.z.so";
70 #endif
71
72 namespace OHOS {
73 namespace DistributedHardware {
74 DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService);
75 namespace {
76 const int32_t NORMAL = 0;
77 const int32_t SYSTEM_BASIC = 1;
78 const int32_t SYSTEM_CORE = 2;
79 const uint32_t UNBIND_PROXY_ITEM_SIZE = 1;
80 constexpr const char *ALL_PKGNAME = "";
81 constexpr const char *NETWORKID = "NETWORK_ID";
82 constexpr uint32_t INVALIED_BIND_LEVEL = 0;
83 constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1;
84 constexpr uint32_t DM_SHARE = 2;
85 const std::string USERID_CHECKSUM_NETWORKID_KEY = "networkId";
86 const std::string USERID_CHECKSUM_DISCOVER_TYPE_KEY = "discoverType";
87 const std::string DHARD_WARE_PKG_NAME = "ohos.dhardware";
88 const std::string USERID_CHECKSUM_ISCHANGE_KEY = "ischange";
89 constexpr const char* USER_SWITCH_BY_WIFI_TIMEOUT_TASK = "deviceManagerTimer:userSwitchByWifi";
90 constexpr const char* USER_STOP_BY_WIFI_TIMEOUT_TASK = "deviceManagerTimer:userStopByWifi";
91 constexpr const char* APP_UNINSTALL_BY_WIFI_TIMEOUT_TASK = "deviceManagerTimer:appUninstallByWifi";
92 constexpr const char* APP_UNBIND_BY_WIFI_TIMEOUT_TASK = "deviceManagerTimer:appUnbindByWifi";
93 constexpr const char* ACCOUNT_COMMON_EVENT_BY_WIFI_TIMEOUT_TASK = "deviceManagerTimer:accountCommonEventByWifi";
94 const int32_t USER_SWITCH_BY_WIFI_TIMEOUT_S = 2;
95 const int32_t SEND_DELAY_MAX_TIME = 5;
96 const int32_t SEND_DELAY_MIN_TIME = 0;
97 const int32_t DELAY_TIME_SEC_CONVERSION = 1000000; // 1000*1000
98 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) && !defined(DEVICE_MANAGER_COMMON_FLAG)
99 const std::string GET_LOCAL_DEVICE_NAME_API_NAME = "GetLocalDeviceName";
100 #endif
101 constexpr const char* LOCAL_ALL_USERID = "local_all_userId";
102 constexpr const char* LOCAL_FOREGROUND_USERID = "local_foreground_userId";
103 constexpr const char* LOCAL_BACKGROUND_USERID = "local_background_userId";
104 }
105
~DeviceManagerService()106 DeviceManagerService::~DeviceManagerService()
107 {
108 LOGI("DeviceManagerService destructor");
109 UnloadDMServiceImplSo();
110 UnloadDMServiceAdapterResident();
111 UnloadDMDeviceRiskDetect();
112 }
113
Init()114 int32_t DeviceManagerService::Init()
115 {
116 InitSoftbusListener();
117 InitDMServiceListener();
118 LOGI("Init success, dm service single instance initialized.");
119 return DM_OK;
120 }
121
InitSoftbusListener()122 int32_t DeviceManagerService::InitSoftbusListener()
123 {
124 if (softbusListener_ == nullptr) {
125 softbusListener_ = std::make_shared<SoftbusListener>();
126 }
127 SoftbusCache::GetInstance().UpdateDeviceInfoCache();
128 std::vector<DmDeviceInfo> onlineDeviceList;
129 SoftbusCache::GetInstance().GetDeviceInfoFromCache(onlineDeviceList);
130 if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) {
131 dmServiceImpl_->SaveOnlineDeviceInfo(onlineDeviceList);
132 }
133 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
134 #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI)
135 SubscribePublishCommonEvent();
136 QueryDependsSwitchState();
137 #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI
138 SubscribeDataShareCommonEvent();
139 #endif
140 LOGI("SoftbusListener init success.");
141 if (!IsDMServiceAdapterResidentLoad()) {
142 LOGE("load dm service resident failed.");
143 }
144 return DM_OK;
145 }
146
InitHichainListener()147 void DeviceManagerService::InitHichainListener()
148 {
149 LOGI("DeviceManagerService::InitHichainListener Start.");
150 std::lock_guard<std::mutex> lock(hichainListenerLock_);
151 if (hichainListener_ == nullptr) {
152 hichainListener_ = std::make_shared<HichainListener>();
153 }
154 hichainListener_->RegisterDataChangeCb();
155 hichainListener_->RegisterCredentialCb();
156 }
157
158 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
StartDetectDeviceRisk()159 void DeviceManagerService::StartDetectDeviceRisk()
160 {
161 std::lock_guard<std::mutex> lock(detectLock_);
162 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
163 CHECK_NULL_VOID(samgr);
164 if (samgr->CheckSystemAbility(RISK_ANALYSIS_MANAGER_SA_ID) == nullptr) {
165 LOGE("%{public}d sa not start", RISK_ANALYSIS_MANAGER_SA_ID);
166 return;
167 }
168 if (!IsDMDeviceRiskDetectSoLoaded()) {
169 LOGE("load dm device risk detect failed.");
170 return;
171 }
172
173 bool isRisk = dmDeviceRiskDetect_->IsDeviceHasRisk();
174 if (isRisk) {
175 LOGI("device status is Illegal");
176 DelAllRelateShip();
177 }
178 return;
179 }
180
DelAllRelateShip()181 void DeviceManagerService::DelAllRelateShip()
182 {
183 std::lock_guard<std::mutex> lock(hichainListenerLock_);
184 if (hichainListener_ == nullptr) {
185 hichainListener_ = std::make_shared<HichainListener>();
186 }
187 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
188 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
189 std::string localUdid = static_cast<std::string>(localDeviceId);
190 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
191 std::vector<int32_t> currentUserIds;
192 currentUserIds.push_back(userId);
193 hichainListener_->DeleteAllGroup(localUdid, currentUserIds);
194 std::vector<DistributedDeviceProfile::AccessControlProfile> profiles =
195 DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl();
196 for (auto &item : profiles) {
197 std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId();
198 std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId();
199 if (localUdid == acerDeviceId) {
200 int32_t acerUserId = item.GetAccesser().GetAccesserUserId();
201 int32_t acerSkId = item.GetAccesser().GetAccesserSessionKeyId();
202 DeviceProfileConnector::GetInstance().DeleteSessionKey(acerUserId, acerSkId);
203
204 std::string acerCredId = item.GetAccesser().GetAccesserCredentialIdStr();
205 hichainListener_->DeleteCredential(acerUserId, acerCredId);
206 } else if (localUdid == aceeDeviceId) {
207 int32_t aceeUserId = item.GetAccessee().GetAccesseeUserId();
208 int32_t aceeSkId = item.GetAccessee().GetAccesseeSessionKeyId();
209 DeviceProfileConnector::GetInstance().DeleteSessionKey(aceeUserId, aceeSkId);
210
211 std::string aceeCredId = item.GetAccessee().GetAccesseeCredentialIdStr();
212 hichainListener_->DeleteCredential(aceeUserId, aceeCredId);
213 }
214 int32_t aclId = item.GetAccessControlId();
215 DeviceProfileConnector::GetInstance().DeleteAccessControlById(aclId);
216 }
217 }
218 #endif
219
220 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
221 #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI)
SubscribePublishCommonEvent()222 void DeviceManagerService::SubscribePublishCommonEvent()
223 {
224 LOGI("DeviceManagerServiceImpl::SubscribeCommonEvent");
225 if (publshCommonEventManager_ == nullptr) {
226 publshCommonEventManager_ = std::make_shared<DmPublishCommonEventManager>();
227 }
228 PublishEventCallback callback = [=](const auto &arg1, const auto &arg2, const auto &arg3) {
229 OHOS::DistributedHardware::PublishCommonEventCallback(arg1, arg2, arg3);
230 };
231 std::vector<std::string> PublishCommonEventVec;
232 #ifdef SUPPORT_BLUETOOTH
233 PublishCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE);
234 #endif // SUPPORT_BLUETOOTH
235
236 #ifdef SUPPORT_WIFI
237 PublishCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_WIFI_POWER_STATE);
238 #endif // SUPPORT_WIFI
239 PublishCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
240 PublishCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
241 if (publshCommonEventManager_->SubscribePublishCommonEvent(PublishCommonEventVec, callback)) {
242 LOGI("subscribe ble and wifi and screen common event success");
243 }
244 return;
245 }
246 #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI
SubscribeDataShareCommonEvent()247 DM_EXPORT void DeviceManagerService::SubscribeDataShareCommonEvent()
248 {
249 LOGI("DeviceManagerServiceImpl::SubscribeDataShareCommonEvent");
250 if (dataShareCommonEventManager_ == nullptr) {
251 dataShareCommonEventManager_ = std::make_shared<DmDataShareCommonEventManager>();
252 }
253 DataShareEventCallback callback = [=](const auto &arg1, const auto &arg2) {
254 if (arg1 == CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY) {
255 DeviceNameManager::GetInstance().DataShareReady();
256 }
257 if (arg1 == CommonEventSupport::COMMON_EVENT_LOCALE_CHANGED) {
258 DeviceNameManager::GetInstance().InitDeviceNameWhenLanguageOrRegionChanged();
259 }
260 if (arg1 == CommonEventSupport::COMMON_EVENT_CONNECTIVITY_CHANGE) {
261 this->HandleNetworkConnected(arg2);
262 }
263 };
264 std::vector<std::string> commonEventVec;
265 commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY);
266 commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_LOCALE_CHANGED);
267 commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_CONNECTIVITY_CHANGE);
268 if (dataShareCommonEventManager_->SubscribeDataShareCommonEvent(commonEventVec, callback)) {
269 LOGI("subscribe datashare common event success");
270 }
271 }
272 #endif
273
274 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
275 #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI)
QueryDependsSwitchState()276 void DeviceManagerService::QueryDependsSwitchState()
277 {
278 std::shared_ptr<DmPublishEventSubscriber> publishSubScriber = publshCommonEventManager_->GetSubscriber();
279 CHECK_NULL_VOID(publishSubScriber);
280 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
281 CHECK_NULL_VOID(samgr);
282 #ifdef SUPPORT_BLUETOOTH
283 if (samgr->CheckSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID) == nullptr) {
284 publishSubScriber->SetBluetoothState(static_cast<int32_t>(Bluetooth::BTStateID::STATE_TURN_OFF));
285 } else {
286 if (Bluetooth::BluetoothHost::GetDefaultHost().IsBleEnabled()) {
287 publishSubScriber->SetBluetoothState(static_cast<int32_t>(Bluetooth::BTStateID::STATE_TURN_ON));
288 } else {
289 publishSubScriber->SetBluetoothState(static_cast<int32_t>(Bluetooth::BTStateID::STATE_TURN_OFF));
290 }
291 }
292 #endif // SUPPORT_BLUETOOTH
293
294 #ifdef SUPPORT_WIFI
295 if (samgr->CheckSystemAbility(WIFI_DEVICE_SYS_ABILITY_ID) == nullptr) {
296 publishSubScriber->SetWifiState(static_cast<int32_t>(OHOS::Wifi::WifiState::DISABLED));
297 } else {
298 bool isWifiActive = false;
299 auto wifiMgr = Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID);
300 CHECK_NULL_VOID(wifiMgr);
301 wifiMgr->IsWifiActive(isWifiActive);
302 if (isWifiActive) {
303 publishSubScriber->SetWifiState(static_cast<int32_t>(OHOS::Wifi::WifiState::ENABLED));
304 } else {
305 publishSubScriber->SetWifiState(static_cast<int32_t>(OHOS::Wifi::WifiState::DISABLED));
306 }
307 }
308 #endif // SUPPORT_WIFI
309
310 #ifdef SUPPORT_POWER_MANAGER
311 if (samgr->CheckSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr) {
312 publishSubScriber->SetScreenState(DM_SCREEN_OFF);
313 } else {
314 if (OHOS::PowerMgr::PowerMgrClient::GetInstance().IsScreenOn()) {
315 publishSubScriber->SetScreenState(DM_SCREEN_ON);
316 } else {
317 publishSubScriber->SetScreenState(DM_SCREEN_OFF);
318 }
319 }
320 #else
321 publishSubScriber->SetScreenState(DM_SCREEN_ON);
322 #endif // SUPPORT_POWER_MANAGER
323 OHOS::DistributedHardware::PublishCommonEventCallback(publishSubScriber->GetBluetoothState(),
324 publishSubScriber->GetWifiState(), publishSubScriber->GetScreenState());
325 }
326 #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI
327 #endif
328
UninitSoftbusListener()329 void DeviceManagerService::UninitSoftbusListener()
330 {
331 CHECK_NULL_VOID(softbusListener_);
332 softbusListener_->DeleteCacheDeviceInfo();
333 softbusListener_ = nullptr;
334 LOGI("SoftbusListener uninit.");
335 }
336
InitDMServiceListener()337 int32_t DeviceManagerService::InitDMServiceListener()
338 {
339 if (listener_ == nullptr) {
340 listener_ = std::make_shared<DeviceManagerServiceListener>();
341 }
342 if (advertiseMgr_ == nullptr) {
343 advertiseMgr_ = std::make_shared<AdvertiseManager>(softbusListener_);
344 }
345 if (discoveryMgr_ == nullptr) {
346 discoveryMgr_ = std::make_shared<DiscoveryManager>(softbusListener_, listener_);
347 }
348 if (pinHolder_ == nullptr) {
349 pinHolder_ = std::make_shared<PinHolder>(listener_);
350 }
351 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
352 DMCommTool::GetInstance()->Init();
353 int32_t currentUserId = MultipleUserConnector::GetFirstForegroundUserId();
354 if (IsPC() && !MultipleUserConnector::IsUserUnlocked(currentUserId)) {
355 HandleUserStopEvent(currentUserId);
356 }
357 #endif
358 LOGI("Init success.");
359 return DM_OK;
360 }
361
UninitDMServiceListener()362 DM_EXPORT void DeviceManagerService::UninitDMServiceListener()
363 {
364 listener_ = nullptr;
365 advertiseMgr_ = nullptr;
366 discoveryMgr_ = nullptr;
367 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
368 DeviceNameManager::GetInstance().UnInit();
369 KVAdapterManager::GetInstance().UnInit();
370 #endif
371 LOGI("Uninit.");
372 }
373
RegisterCallerAppId(const std::string & pkgName)374 DM_EXPORT void DeviceManagerService::RegisterCallerAppId(const std::string &pkgName)
375 {
376 AppManager::GetInstance().RegisterCallerAppId(pkgName);
377 }
378
UnRegisterCallerAppId(const std::string & pkgName)379 DM_EXPORT void DeviceManagerService::UnRegisterCallerAppId(const std::string &pkgName)
380 {
381 AppManager::GetInstance().UnRegisterCallerAppId(pkgName);
382 }
383
GetTrustedDeviceList(const std::string & pkgName,const std::string & extra,std::vector<DmDeviceInfo> & deviceList)384 int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra,
385 std::vector<DmDeviceInfo> &deviceList)
386 {
387 (void)extra;
388 if (pkgName.empty()) {
389 LOGE("Invalid parameter, pkgName is empty.");
390 return ERR_DM_INPUT_PARA_INVALID;
391 }
392 bool isOnlyShowNetworkId = !(PermissionManager::GetInstance().CheckPermission() ||
393 PermissionManager::GetInstance().CheckNewPermission());
394 std::vector<DmDeviceInfo> onlineDeviceList;
395 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
396 int32_t ret = softbusListener_->GetTrustedDeviceList(onlineDeviceList);
397 if (ret != DM_OK) {
398 LOGE("GetTrustedDeviceList failed");
399 return ret;
400 }
401 if (isOnlyShowNetworkId && !onlineDeviceList.empty()) {
402 for (auto item : onlineDeviceList) {
403 DmDeviceInfo tempInfo;
404 if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, item.networkId, sizeof(item.networkId)) != 0) {
405 LOGE("get networkId: %{public}s failed", GetAnonyString(item.networkId).c_str());
406 return ERR_DM_SECURITY_FUNC_FAILED;
407 }
408 deviceList.push_back(tempInfo);
409 }
410 return DM_OK;
411 }
412 if (!onlineDeviceList.empty() && IsDMServiceImplReady()) {
413 std::unordered_map<std::string, DmAuthForm> udidMap;
414 if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName) ||
415 PermissionManager::GetInstance().CheckProcessValidOnGetTrustedDeviceList()) {
416 udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME));
417 } else {
418 udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName);
419 }
420 for (auto item : onlineDeviceList) {
421 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
422 ConvertUdidHashToAnoyDeviceId(item);
423 #endif
424 std::string udid = "";
425 SoftbusListener::GetUdidByNetworkId(item.networkId, udid);
426 if (udidMap.find(udid) != udidMap.end()) {
427 item.authForm = udidMap[udid];
428 deviceList.push_back(item);
429 }
430 }
431 }
432 return DM_OK;
433 }
434
GetAllTrustedDeviceList(const std::string & pkgName,const std::string & extra,std::vector<DmDeviceInfo> & deviceList)435 int32_t DeviceManagerService::GetAllTrustedDeviceList(const std::string &pkgName, const std::string &extra,
436 std::vector<DmDeviceInfo> &deviceList)
437 {
438 (void)extra;
439 if (pkgName.empty()) {
440 LOGE("Invalid parameter, pkgName or extra is empty.");
441 return ERR_DM_INPUT_PARA_INVALID;
442 }
443 if (!PermissionManager::GetInstance().CheckNewPermission()) {
444 LOGE("The caller: %{public}s does not have permission to call GetAllTrustedDeviceList.", pkgName.c_str());
445 return ERR_DM_NO_PERMISSION;
446 }
447 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
448 int32_t ret = softbusListener_->GetAllTrustedDeviceList(pkgName, extra, deviceList);
449 if (ret != DM_OK) {
450 LOGE("GetAllTrustedDeviceList failed");
451 return ret;
452 }
453 return DM_OK;
454 }
455
ShiftLNNGear(const std::string & pkgName,const std::string & callerId,bool isRefresh,bool isWakeUp)456 int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std::string &callerId, bool isRefresh,
457 bool isWakeUp)
458 {
459 LOGD("Begin for pkgName = %{public}s, callerId = %{public}s, isRefresh ="
460 "%{public}d, isWakeUp = %{public}d", pkgName.c_str(), GetAnonyString(callerId).c_str(), isRefresh, isWakeUp);
461 if (!PermissionManager::GetInstance().CheckNewPermission()) {
462 LOGE("The caller does not have permission to call ShiftLNNGear, pkgName = %{public}s", pkgName.c_str());
463 return ERR_DM_NO_PERMISSION;
464 }
465 if (pkgName.empty() || callerId.empty()) {
466 LOGE("Invalid parameter, parameter is empty.");
467 return ERR_DM_INPUT_PARA_INVALID;
468 }
469 if (isRefresh) {
470 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
471 int32_t ret = softbusListener_->ShiftLNNGear(isWakeUp, callerId);
472 if (ret != DM_OK) {
473 LOGE("ShiftLNNGear error, failed ret: %{public}d", ret);
474 return ret;
475 }
476 }
477 return DM_OK;
478 }
479
GetDeviceInfo(const std::string & networkId,DmDeviceInfo & info)480 int32_t DeviceManagerService::GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info)
481 {
482 LOGI("Begin networkId %{public}s.", GetAnonyString(networkId).c_str());
483 if (!PermissionManager::GetInstance().CheckPermission() &&
484 !PermissionManager::GetInstance().CheckNewPermission()) {
485 LOGE("The caller does not have permission to call GetDeviceInfo.");
486 return ERR_DM_NO_PERMISSION;
487 }
488 if (networkId.empty()) {
489 LOGE("Invalid parameter, networkId is empty.");
490 return ERR_DM_INPUT_PARA_INVALID;
491 }
492 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
493 std::string peerDeviceId = "";
494 SoftbusListener::GetUdidByNetworkId(networkId.c_str(), peerDeviceId);
495 int32_t ret = DM_OK;
496 if (!IsDMServiceImplReady()) {
497 LOGE("GetDeviceInfo failed, instance not init or init failed.");
498 return ERR_DM_NOT_INIT;
499 }
500 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
501 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
502 std::string localUdid = static_cast<std::string>(localDeviceId);
503 if (localUdid == peerDeviceId) {
504 ret = softbusListener_->GetDeviceInfo(networkId, info);
505 if (ret != DM_OK) {
506 LOGE("Get DeviceInfo By NetworkId failed, ret : %{public}d", ret);
507 }
508 return ret;
509 }
510 if (!AppManager::GetInstance().IsSystemSA()) {
511 int32_t permissionRet = dmServiceImpl_->CheckDeviceInfoPermission(localUdid, peerDeviceId);
512 if (permissionRet != DM_OK) {
513 std::string processName = "";
514 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
515 LOGE("Get caller process name failed.");
516 return ret;
517 }
518 if (!PermissionManager::GetInstance().CheckProcessNameValidOnGetDeviceInfo(processName)) {
519 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
520 return ret;
521 }
522 }
523 }
524 ret = softbusListener_->GetDeviceInfo(networkId, info);
525 if (ret != DM_OK) {
526 LOGE("Get DeviceInfo By NetworkId failed, ret : %{public}d", ret);
527 }
528 return ret;
529 }
530
GetLocalDeviceInfo(DmDeviceInfo & info)531 int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info)
532 {
533 LOGD("Begin.");
534 bool isOnlyShowNetworkId = false;
535 if (!PermissionManager::GetInstance().CheckNewPermission()) {
536 LOGE("The caller does not have permission to call GetLocalDeviceInfo.");
537 isOnlyShowNetworkId = true;
538 }
539 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
540 int32_t ret = softbusListener_->GetLocalDeviceInfo(info);
541 if (ret != DM_OK) {
542 LOGE("GetLocalDeviceInfo failed");
543 return ret;
544 }
545 if (isOnlyShowNetworkId) {
546 DmDeviceInfo tempInfo;
547 if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, info.networkId, sizeof(info.networkId)) != 0) {
548 LOGE("get networkId: %{public}s failed", GetAnonyString(info.networkId).c_str());
549 return ERR_DM_FAILED;
550 }
551 info = tempInfo;
552 return DM_OK;
553 }
554 if (localDeviceId_.empty()) {
555 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
556 char udidHash[DEVICE_UUID_LENGTH] = {0};
557 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
558 if (Crypto::GetUdidHash(localDeviceId, reinterpret_cast<uint8_t *>(udidHash)) == DM_OK) {
559 localDeviceId_ = udidHash;
560 }
561 }
562 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
563 std::string udidHashTemp = "";
564 if (ConvertUdidHashToAnoyDeviceId(localDeviceId_, udidHashTemp) == DM_OK) {
565 if (memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) {
566 LOGE("GetLocalDeviceInfo memset_s failed.");
567 return ERR_DM_FAILED;
568 }
569 if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) {
570 LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str());
571 return ERR_DM_FAILED;
572 }
573 return DM_OK;
574 }
575 #endif
576 if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, localDeviceId_.c_str(), localDeviceId_.length()) != 0) {
577 LOGE("get deviceId: %{public}s failed", GetAnonyString(localDeviceId_).c_str());
578 return ERR_DM_FAILED;
579 }
580 return DM_OK;
581 }
582
583 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) && !defined(DEVICE_MANAGER_COMMON_FLAG)
IsCallerInWhiteList()584 bool DeviceManagerService::IsCallerInWhiteList()
585 {
586 if (!IsDMAdapterCheckApiWhiteListLoaded()) {
587 LOGE("DMAdapterCheckApiWhiteListLoad failed.");
588 return false;
589 }
590 std::string callerName;
591 if (AppManager::GetInstance().GetCallerProcessName(callerName) != DM_OK) {
592 LOGE("GetCallerProcessName failed.");
593 return false;
594 }
595 return dmCheckApiWhiteList_->IsCallerInWhiteList(callerName, GET_LOCAL_DEVICE_NAME_API_NAME);
596 }
597
IsDMAdapterCheckApiWhiteListLoaded()598 bool DeviceManagerService::IsDMAdapterCheckApiWhiteListLoaded()
599 {
600 LOGD("Start.");
601 std::lock_guard<std::mutex> lock(isAdapterCheckApiWhiteListLoadedLock_);
602 if (isAdapterCheckApiWhiteListSoLoaded_ && (dmCheckApiWhiteList_ != nullptr)) {
603 return true;
604 }
605 checkApiWhiteListSoHandle_ = dlopen(LIB_DM_CHECK_API_WHITE_LIST_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD);
606 if (checkApiWhiteListSoHandle_ == nullptr) {
607 checkApiWhiteListSoHandle_ = dlopen(LIB_DM_CHECK_API_WHITE_LIST_NAME, RTLD_NOW | RTLD_NODELETE);
608 }
609 if (checkApiWhiteListSoHandle_ == nullptr) {
610 LOGE("load dm check api white list so failed.");
611 return false;
612 }
613 if (dlerror() != nullptr) {
614 dlclose(checkApiWhiteListSoHandle_);
615 checkApiWhiteListSoHandle_ = nullptr;
616 LOGE("open dm check api white list so failed. err: %{public}s", dlerror());
617 return false;
618 }
619 auto func = (CreateDMCheckApiWhiteListFuncPtr)dlsym(checkApiWhiteListSoHandle_, "CreateDMCheckApiWhiteListObject");
620 if (func == nullptr || dlerror() != nullptr) {
621 dlclose(checkApiWhiteListSoHandle_);
622 checkApiWhiteListSoHandle_ = nullptr;
623 LOGE("Create object function is not exist. err: %{public}s", (dlerror() == nullptr ? "null" : dlerror()));
624 return false;
625 }
626 dmCheckApiWhiteList_ = std::shared_ptr<IDMCheckApiWhiteList>(func());
627 isAdapterCheckApiWhiteListSoLoaded_ = true;
628 LOGI("Success.");
629 return true;
630 }
631 #endif
632
GetLocalDeviceNameOld(std::string & deviceName)633 int32_t DeviceManagerService::GetLocalDeviceNameOld(std::string &deviceName)
634 {
635 LOGD("Begin.");
636 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) && !defined(DEVICE_MANAGER_COMMON_FLAG)
637 if (!PermissionManager::GetInstance().CheckNewPermission() && !IsCallerInWhiteList()) {
638 LOGE("The caller does not have permission to call GetLocalDeviceName.");
639 return ERR_DM_NO_PERMISSION;
640 }
641 #else
642 if (!PermissionManager::GetInstance().CheckNewPermission()) {
643 LOGE("The caller does not have permission to call GetLocalDeviceName.");
644 return ERR_DM_NO_PERMISSION;
645 }
646 #endif
647 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
648 DmDeviceInfo info;
649 int32_t ret = softbusListener_->GetLocalDeviceInfo(info);
650 if (ret != DM_OK) {
651 LOGE("GetLocalDeviceInfo failed");
652 return ret;
653 }
654 deviceName = info.deviceName;
655 return DM_OK;
656 }
657
GetUdidByNetworkId(const std::string & pkgName,const std::string & netWorkId,std::string & udid)658 int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId,
659 std::string &udid)
660 {
661 if (!PermissionManager::GetInstance().CheckPermission()) {
662 LOGE("The caller: %{public}s does not have permission to call GetUdidByNetworkId.", pkgName.c_str());
663 return ERR_DM_NO_PERMISSION;
664 }
665 if (pkgName.empty() || netWorkId.empty()) {
666 LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(),
667 GetAnonyString(netWorkId).c_str());
668 return ERR_DM_INPUT_PARA_INVALID;
669 }
670 return SoftbusListener::GetUdidByNetworkId(netWorkId.c_str(), udid);
671 }
672
GetUuidByNetworkId(const std::string & pkgName,const std::string & netWorkId,std::string & uuid)673 int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId,
674 std::string &uuid)
675 {
676 if (!PermissionManager::GetInstance().CheckPermission()) {
677 LOGE("The caller: %{public}s does not have permission to call GetUuidByNetworkId.", pkgName.c_str());
678 return ERR_DM_NO_PERMISSION;
679 }
680 if (pkgName.empty() || netWorkId.empty()) {
681 LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(),
682 GetAnonyString(netWorkId).c_str());
683 return ERR_DM_INPUT_PARA_INVALID;
684 }
685 return SoftbusListener::GetUuidByNetworkId(netWorkId.c_str(), uuid);
686 }
687
PublishDeviceDiscovery(const std::string & pkgName,const DmPublishInfo & publishInfo)688 int32_t DeviceManagerService::PublishDeviceDiscovery(const std::string &pkgName, const DmPublishInfo &publishInfo)
689 {
690 if (!PermissionManager::GetInstance().CheckPermission()) {
691 LOGE("The caller: %{public}s does not have permission to call PublishDeviceDiscovery.", pkgName.c_str());
692 return ERR_DM_NO_PERMISSION;
693 }
694 LOGI("Begin for pkgName = %{public}s", pkgName.c_str());
695 if (pkgName.empty()) {
696 LOGE("Invalid parameter, pkgName is empty.");
697 return ERR_DM_INPUT_PARA_INVALID;
698 }
699
700 std::map<std::string, std::string> advertiseParam;
701 advertiseParam.insert(std::pair<std::string, std::string>(PARAM_KEY_PUBLISH_ID,
702 std::to_string(publishInfo.publishId)));
703 CHECK_NULL_RETURN(advertiseMgr_, ERR_DM_POINT_NULL);
704 return advertiseMgr_->StartAdvertising(pkgName, advertiseParam);
705 }
706
UnPublishDeviceDiscovery(const std::string & pkgName,int32_t publishId)707 int32_t DeviceManagerService::UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId)
708 {
709 if (!PermissionManager::GetInstance().CheckPermission()) {
710 LOGE("The caller: %{public}s does not have permission to call UnPublishDeviceDiscovery.", pkgName.c_str());
711 return ERR_DM_NO_PERMISSION;
712 }
713 if (pkgName.empty()) {
714 LOGE("Invalid parameter, pkgName is empty.");
715 return ERR_DM_INPUT_PARA_INVALID;
716 }
717 CHECK_NULL_RETURN(advertiseMgr_, ERR_DM_POINT_NULL);
718 return advertiseMgr_->StopAdvertising(pkgName, publishId);
719 }
720
AuthenticateDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)721 int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType,
722 const std::string &deviceId, const std::string &extra)
723 {
724 if (!PermissionManager::GetInstance().CheckPermission()) {
725 LOGE("The caller: %{public}s does not have permission to call AuthenticateDevice.", pkgName.c_str());
726 return ERR_DM_NO_PERMISSION;
727 }
728 if (pkgName.empty() || deviceId.empty() || pkgName == std::string(DM_PKG_NAME)) {
729 LOGE("DeviceManagerService::AuthenticateDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
730 return ERR_DM_INPUT_PARA_INVALID;
731 }
732 if (!IsDMServiceImplReady()) {
733 LOGE("AuthenticateDevice failed, instance not init or init failed.");
734 return ERR_DM_NOT_INIT;
735 }
736 std::string queryDeviceId = deviceId;
737 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
738 std::string udidHash = "";
739 if (GetUdidHashByAnoyDeviceId(deviceId, udidHash) == DM_OK) {
740 queryDeviceId = udidHash;
741 }
742 #endif
743 PeerTargetId targetId;
744 ConnectionAddrType addrType;
745 int32_t ret = SoftbusListener::GetTargetInfoFromCache(queryDeviceId, targetId, addrType);
746 if (ret != DM_OK) {
747 LOGE("AuthenticateDevice failed, cannot get target info from cached discovered device map.");
748 return ERR_DM_BIND_INPUT_PARA_INVALID;
749 }
750 std::map<std::string, std::string> bindParam;
751 bindParam.insert(std::pair<std::string, std::string>(PARAM_KEY_AUTH_TYPE, std::to_string(authType)));
752 bindParam.insert(std::pair<std::string, std::string>(PARAM_KEY_BIND_EXTRA_DATA, extra));
753 bindParam.insert(std::pair<std::string, std::string>(PARAM_KEY_CONN_ADDR_TYPE, std::to_string(addrType)));
754 return dmServiceImpl_->BindTarget(pkgName, targetId, bindParam);
755 }
756
UnAuthenticateDevice(const std::string & pkgName,const std::string & networkId)757 int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId)
758 {
759 if (!PermissionManager::GetInstance().CheckPermission()) {
760 LOGE("The caller: %{public}s does not have permission to call UnAuthenticateDevice.", pkgName.c_str());
761 return ERR_DM_NO_PERMISSION;
762 }
763 LOGI("Begin for pkgName = %{public}s, networkId = %{public}s",
764 pkgName.c_str(), GetAnonyString(networkId).c_str());
765 if (pkgName.empty() || networkId.empty()) {
766 LOGE("DeviceManagerService::UnAuthenticateDevice error: Invalid parameter, pkgName: %{public}s",
767 pkgName.c_str());
768 return ERR_DM_INPUT_PARA_INVALID;
769 }
770 std::string udid = "";
771 if (SoftbusListener::GetUdidByNetworkId(networkId.c_str(), udid) != DM_OK) {
772 LOGE("UnAuthenticateDevice GetUdidByNetworkId error: udid: %{public}s", GetAnonyString(udid).c_str());
773 return ERR_DM_FAILED;
774 }
775 char localUdid[DEVICE_UUID_LENGTH] = {0};
776 GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
777 if (!IsDMServiceImplReady()) {
778 LOGE("UnAuthenticateDevice failed, instance not init or init failed.");
779 return ERR_DM_NOT_INIT;
780 }
781 uint64_t tokenId = 0;
782 int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);
783 LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel);
784 if (bindLevel == INVALIED_BIND_LEVEL) {
785 LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel);
786 return ERR_DM_FAILED;
787 }
788 if (dmServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel) != DM_OK) {
789 LOGE("dmServiceImpl_ UnAuthenticateDevice failed.");
790 return ERR_DM_FAILED;
791 }
792 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
793 std::vector<std::string> peerUdids;
794 peerUdids.emplace_back(udid);
795 SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId, bindLevel);
796 #endif
797 return DM_OK;
798 }
799
StopAuthenticateDevice(const std::string & pkgName)800 int32_t DeviceManagerService::StopAuthenticateDevice(const std::string &pkgName)
801 {
802 if (!PermissionManager::GetInstance().CheckPermission()) {
803 LOGE("The caller: %{public}s does not have permission to call StopAuthenticateDevice.", pkgName.c_str());
804 return ERR_DM_NO_PERMISSION;
805 }
806 if (pkgName.empty()) {
807 LOGE("DeviceManagerService::StopAuthenticateDevice error: Invalid parameter, pkgName: %{public}s",
808 pkgName.c_str());
809 return ERR_DM_INPUT_PARA_INVALID;
810 }
811 LOGI("Begin for pkgName = %{public}s", pkgName.c_str());
812 if (!IsDMServiceImplReady()) {
813 LOGE("StopAuthenticateDevice failed, instance not init or init failed.");
814 return ERR_DM_NOT_INIT;
815 }
816 if (dmServiceImpl_->StopAuthenticateDevice(pkgName) != DM_OK) {
817 LOGE("dmServiceImpl_ StopAuthenticateDevice failed.");
818 return ERR_DM_FAILED;
819 }
820 return DM_OK;
821 }
822
BindDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & bindParam)823 int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId,
824 const std::string &bindParam)
825 {
826 if (!PermissionManager::GetInstance().CheckNewPermission()) {
827 LOGE("The caller does not have permission to call BindDevice.");
828 return ERR_DM_NO_PERMISSION;
829 }
830 if (pkgName.empty() || deviceId.empty() || pkgName == std::string(DM_PKG_NAME)) {
831 LOGE("DeviceManagerService::BindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
832 return ERR_DM_INPUT_PARA_INVALID;
833 }
834 if (!IsDMServiceImplReady()) {
835 LOGE("BindDevice failed, instance not init or init failed.");
836 return ERR_DM_NOT_INIT;
837 }
838 std::string queryDeviceId = deviceId;
839 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
840 std::string udidHash = "";
841 if (GetUdidHashByAnoyDeviceId(deviceId, udidHash) == DM_OK) {
842 queryDeviceId = udidHash;
843 }
844 #endif
845 PeerTargetId targetId;
846 std::map<std::string, std::string> bindParamMap;
847 std::string bindParamStr = bindParam;
848 int32_t actionId = 0;
849 SoftbusListener::GetActionId(queryDeviceId, actionId);
850 if (actionId > 0) {
851 targetId.deviceId = queryDeviceId;
852 AddHmlInfoToBindParam(actionId, bindParamStr);
853 } else {
854 ConnectionAddrType addrType;
855 int32_t ret = SoftbusListener::GetTargetInfoFromCache(queryDeviceId, targetId, addrType);
856 if (ret != DM_OK) {
857 LOGE("BindDevice failed, cannot get target info from cached discovered device map.");
858 return ERR_DM_BIND_INPUT_PARA_INVALID;
859 }
860 bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_CONN_ADDR_TYPE, std::to_string(addrType)));
861 }
862 bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_AUTH_TYPE, std::to_string(authType)));
863 bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_BIND_EXTRA_DATA, bindParamStr));
864 return dmServiceImpl_->BindTarget(pkgName, targetId, bindParamMap);
865 }
866
UnBindDevice(const std::string & pkgName,const std::string & udidHash)867 int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std::string &udidHash)
868 {
869 int32_t result = ValidateUnBindDeviceParams(pkgName, udidHash);
870 if (result != DM_OK) {
871 return result;
872 }
873 std::string realDeviceId = udidHash;
874 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
875 std::string udidHashTemp = "";
876 if (GetUdidHashByAnoyDeviceId(udidHash, udidHashTemp) == DM_OK) {
877 realDeviceId = udidHashTemp;
878 }
879 #endif
880 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
881 std::string udid = "";
882 if (softbusListener_->GetUdidFromDp(realDeviceId, udid) != DM_OK) {
883 LOGE("Get udid by udidhash failed.");
884 return ERR_DM_FAILED;
885 }
886 char localUdid[DEVICE_UUID_LENGTH] = {0};
887 GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
888 uint64_t tokenId = 0;
889 int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);
890 LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel);
891 if (bindLevel == INVALIED_BIND_LEVEL) {
892 LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel);
893 return ERR_DM_FAILED;
894 }
895 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
896 std::vector<std::string> peerUdids;
897 peerUdids.emplace_back(udid);
898
899 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
900 std::map<std::string, std::string> wifiDevices;
901 bool isBleActive = false;
902 GetNotifyRemoteUnBindAppWay(userId, tokenId, wifiDevices, isBleActive);
903 if (isBleActive) {
904 SendUnBindBroadCast(peerUdids, userId, tokenId, bindLevel);
905 } else {
906 NotifyRemoteUnBindAppByWifi(userId, tokenId, "", wifiDevices);
907 }
908 #endif
909 if (dmServiceImpl_->UnBindDevice(pkgName, udid, bindLevel) != DM_OK) {
910 LOGE("dmServiceImpl_ UnBindDevice failed.");
911 return ERR_DM_FAILED;
912 }
913 return DM_OK;
914 }
915
916 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
GetProxyInfosByParseExtra(const std::string & pkgName,const std::string & extra,std::vector<std::pair<int64_t,int64_t>> & agentToProxyVec)917 std::set<std::pair<std::string, std::string>> DeviceManagerService::GetProxyInfosByParseExtra(
918 const std::string &pkgName, const std::string &extra,
919 std::vector<std::pair<int64_t, int64_t>> &agentToProxyVec)
920 {
921 std::set<std::pair<std::string, std::string>> proxyInfos;
922 JsonObject jsonObject(extra);
923 if (jsonObject.IsDiscarded()) {
924 proxyInfos.insert(std::pair<std::string, std::string>(pkgName, extra));
925 return proxyInfos;
926 }
927 if (IsString(jsonObject, PARAM_KEY_IS_PROXY_UNBIND) &&
928 jsonObject[PARAM_KEY_IS_PROXY_UNBIND].Get<std::string>() == DM_VAL_TRUE) {
929 if (!IsString(jsonObject, PARAM_KEY_SUBJECT_PROXYED_SUBJECTS)) {
930 return proxyInfos;
931 }
932 } else {
933 if (!jsonObject.Contains(PARAM_KEY_SUBJECT_PROXYED_SUBJECTS)) {
934 proxyInfos.insert(std::pair<std::string, std::string>(pkgName, extra));
935 }
936 return proxyInfos;
937 }
938 if (!AppManager::GetInstance().IsSystemSA()) {
939 LOGE("no proxy permission");
940 return proxyInfos;
941 }
942 std::string subjectProxyAppsStr = jsonObject[PARAM_KEY_SUBJECT_PROXYED_SUBJECTS].Get<std::string>();
943 JsonObject allProxyObj;
944 if (!allProxyObj.Parse(subjectProxyAppsStr) || allProxyObj.Items().size() != UNBIND_PROXY_ITEM_SIZE) {
945 return proxyInfos;
946 }
947 int64_t proxyTokenId = static_cast<int64_t>(IPCSkeleton::GetCallingTokenID());
948 for (auto object : allProxyObj.Items()) {
949 if (!object.Contains(TAG_BUNDLE_NAME) || !IsString(object, TAG_BUNDLE_NAME)) {
950 continue;
951 }
952 if (!object.Contains(TAG_TOKENID) || !IsInt64(object, TAG_TOKENID)) {
953 continue;
954 }
955 std::string bundleName = object[TAG_BUNDLE_NAME].Get<std::string>();
956 int64_t agentTokenId = object[TAG_TOKENID].Get<int64_t>();
957 for (uint32_t i = 0; i < agentToProxyVec.size(); i++) {
958 if (agentTokenId == agentToProxyVec[i].first && proxyTokenId == agentToProxyVec[i].second) {
959 object[PARAM_KEY_IS_PROXY_UNBIND] = DM_VAL_TRUE;
960 proxyInfos.insert(std::pair<std::string, std::string>(bundleName, object.Dump()));
961 break;
962 }
963 }
964 }
965 return proxyInfos;
966 }
967 #endif
968
UnBindDeviceParseExtra(const std::string & pkgName,const std::string & udidHash,const std::string & extra)969 int32_t DeviceManagerService::UnBindDeviceParseExtra(const std::string &pkgName, const std::string &udidHash,
970 const std::string &extra)
971 {
972 int32_t result = ValidateUnBindDeviceParams(pkgName, udidHash, extra);
973 if (result != DM_OK) {
974 return result;
975 }
976 std::string realDeviceId = udidHash;
977 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
978 std::string udidHashTemp = "";
979 if (GetUdidHashByAnoyDeviceId(udidHash, udidHashTemp) == DM_OK) {
980 realDeviceId = udidHashTemp;
981 }
982 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
983 std::string udid = "";
984 if (softbusListener_->GetUdidFromDp(realDeviceId, udid) != DM_OK) {
985 LOGE("Get udid by udidhash failed.");
986 return ERR_DM_FAILED;
987 }
988 char localUdid[DEVICE_UUID_LENGTH] = {0};
989 GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
990 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
991 std::vector<std::pair<int64_t, int64_t>> agentToProxyVec =
992 DeviceProfileConnector::GetInstance().GetAgentToProxyVecFromAclByUserId(
993 std::string(localUdid), udid, userId);
994 std::set<std::pair<std::string, std::string>> proxyInfoSet = GetProxyInfosByParseExtra(
995 pkgName, extra, agentToProxyVec);
996 if (proxyInfoSet.size() != UNBIND_PROXY_ITEM_SIZE) {
997 LOGE("UnBind size error.");
998 return ERR_DM_FAILED;
999 }
1000 auto proxyInfo = proxyInfoSet.begin();
1001 if (proxyInfo->second == "") {
1002 result = UnBindDevice(proxyInfo->first, udidHash);
1003 } else {
1004 result = UnBindDevice(proxyInfo->first, udidHash, proxyInfo->second);
1005 }
1006 #else
1007 if (extra == "") {
1008 result = UnBindDevice(pkgName, udidHash);
1009 } else {
1010 result = UnBindDevice(pkgName, udidHash, extra);
1011 }
1012 #endif
1013 return result;
1014 }
1015
UnBindDevice(const std::string & pkgName,const std::string & udidHash,const std::string & extra)1016 int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std::string &udidHash,
1017 const std::string &extra)
1018 {
1019 int32_t result = ValidateUnBindDeviceParams(pkgName, udidHash, extra);
1020 if (result != DM_OK) {
1021 return result;
1022 }
1023 std::string realDeviceId = udidHash;
1024 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1025 std::string udidHashTemp = "";
1026 if (GetUdidHashByAnoyDeviceId(udidHash, udidHashTemp) == DM_OK) {
1027 realDeviceId = udidHashTemp;
1028 }
1029 #endif
1030 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1031 std::string udid = "";
1032 if (softbusListener_->GetUdidFromDp(realDeviceId, udid) != DM_OK) {
1033 LOGE("Get udid by udidhash failed.");
1034 return ERR_DM_FAILED;
1035 }
1036 char localUdid[DEVICE_UUID_LENGTH] = {0};
1037 GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
1038 uint64_t tokenId = 0;
1039 int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);
1040 LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel);
1041 if (bindLevel == INVALIED_BIND_LEVEL) {
1042 LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel);
1043 return ERR_DM_FAILED;
1044 }
1045 [[maybe_unused]] uint64_t peerTokenId = dmServiceImpl_->GetTokenIdByNameAndDeviceId(extra, udid);
1046 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1047 std::vector<std::string> peerUdids;
1048 peerUdids.emplace_back(udid);
1049 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
1050 std::map<std::string, std::string> wifiDevices;
1051 bool isBleActive = false;
1052 GetNotifyRemoteUnBindAppWay(userId, tokenId, wifiDevices, isBleActive);
1053 if (isBleActive) {
1054 SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId,
1055 bindLevel, peerTokenId);
1056 } else {
1057 NotifyRemoteUnBindAppByWifi(userId, tokenId, extra, wifiDevices);
1058 }
1059 #endif
1060 if (dmServiceImpl_->UnBindDevice(pkgName, udid, bindLevel, extra) != DM_OK) {
1061 LOGE("dmServiceImpl_ UnBindDevice failed.");
1062 return ERR_DM_FAILED;
1063 }
1064 return DM_OK;
1065 }
1066
ValidateUnBindDeviceParams(const std::string & pkgName,const std::string & udidHash)1067 int32_t DeviceManagerService::ValidateUnBindDeviceParams(const std::string &pkgName, const std::string &udidHash)
1068 {
1069 LOGI("DeviceManagerService::ValidateUnBindDeviceParams pkgName: %{public}s, udidHash: %{public}s",
1070 GetAnonyString(pkgName).c_str(), GetAnonyString(udidHash).c_str());
1071 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1072 LOGE("The caller does not have permission to call UnBindDevice.");
1073 return ERR_DM_NO_PERMISSION;
1074 }
1075 if (pkgName.empty() || udidHash.empty() || pkgName == std::string(DM_PKG_NAME)) {
1076 LOGE("DeviceManagerService::UnBindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
1077 return ERR_DM_INPUT_PARA_INVALID;
1078 }
1079 if (!IsDMServiceImplReady()) {
1080 LOGE("UnBindDevice failed, instance not init or init failed.");
1081 return ERR_DM_NOT_INIT;
1082 }
1083 return DM_OK;
1084 }
1085
ValidateUnBindDeviceParams(const std::string & pkgName,const std::string & udidHash,const std::string & extra)1086 int32_t DeviceManagerService::ValidateUnBindDeviceParams(const std::string &pkgName, const std::string &udidHash,
1087 const std::string &extra)
1088 {
1089 LOGI("DeviceManagerService::ValidateUnBindDeviceParams pkgName: %{public}s, udidHash: %{public}s, "
1090 "extra: %{public}s", GetAnonyString(pkgName).c_str(), GetAnonyString(udidHash).c_str(),
1091 GetAnonyString(extra).c_str());
1092 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1093 LOGE("The caller does not have permission to call UnBindDevice.");
1094 return ERR_DM_NO_PERMISSION;
1095 }
1096 if (pkgName.empty() || udidHash.empty() || pkgName == std::string(DM_PKG_NAME)) {
1097 LOGE("DeviceManagerService::UnBindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
1098 return ERR_DM_INPUT_PARA_INVALID;
1099 }
1100 if (!IsDMServiceImplReady()) {
1101 LOGE("UnBindDevice failed, instance not init or init failed.");
1102 return ERR_DM_NOT_INIT;
1103 }
1104 return DM_OK;
1105 }
1106
SetUserOperation(std::string & pkgName,int32_t action,const std::string & params)1107 int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms)
1108 {
1109 if (!PermissionManager::GetInstance().CheckPermission()) {
1110 LOGE("The caller: %{public}s does not have permission to call SetUserOperation.", pkgName.c_str());
1111 return ERR_DM_NO_PERMISSION;
1112 }
1113 if (pkgName.empty() || params.empty()) {
1114 LOGE("DeviceManagerService::SetUserOperation error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
1115 return ERR_DM_INPUT_PARA_INVALID;
1116 }
1117 if (IsDMServiceAdapterSoLoaded()) {
1118 dmServiceImplExtResident_->ReplyUiAction(pkgName, action, params);
1119 }
1120 if (!IsDMServiceImplReady()) {
1121 LOGE("SetUserOperation failed, instance not init or init failed.");
1122 return ERR_DM_NOT_INIT;
1123 }
1124 return dmServiceImpl_->SetUserOperation(pkgName, action, params);
1125 }
1126
HandleDeviceStatusChange(DmDeviceState devState,DmDeviceInfo & devInfo)1127 void DeviceManagerService::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo)
1128 {
1129 LOGD("start, devState = %{public}d", devState);
1130 if (IsDMServiceImplReady()) {
1131 dmServiceImpl_->HandleDeviceStatusChange(devState, devInfo);
1132 }
1133 if (IsDMServiceAdapterResidentLoad()) {
1134 dmServiceImplExtResident_->HandleDeviceStatusChange(devState, devInfo);
1135 }
1136 }
1137
OnSessionOpened(int sessionId,int result)1138 int DeviceManagerService::OnSessionOpened(int sessionId, int result)
1139 {
1140 if (!IsDMServiceImplReady()) {
1141 LOGE("OnSessionOpened failed, instance not init or init failed.");
1142 return ERR_DM_NOT_INIT;
1143 }
1144 return dmServiceImpl_->OnSessionOpened(sessionId, result);
1145 }
1146
OnSessionClosed(int sessionId)1147 void DeviceManagerService::OnSessionClosed(int sessionId)
1148 {
1149 if (!IsDMServiceImplReady()) {
1150 LOGE("OnSessionClosed failed, instance not init or init failed.");
1151 return;
1152 }
1153 dmServiceImpl_->OnSessionClosed(sessionId);
1154 }
1155
OnBytesReceived(int sessionId,const void * data,unsigned int dataLen)1156 void DeviceManagerService::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen)
1157 {
1158 if (!IsDMServiceImplReady()) {
1159 LOGE("OnBytesReceived failed, instance not init or init failed.");
1160 return;
1161 }
1162 dmServiceImpl_->OnBytesReceived(sessionId, data, dataLen);
1163 }
1164
OnPinHolderSessionOpened(int sessionId,int result)1165 int DeviceManagerService::OnPinHolderSessionOpened(int sessionId, int result)
1166 {
1167 return PinHolderSession::OnSessionOpened(sessionId, result);
1168 }
1169
OnPinHolderSessionClosed(int sessionId)1170 void DeviceManagerService::OnPinHolderSessionClosed(int sessionId)
1171 {
1172 CHECK_NULL_VOID(pinHolder_);
1173 pinHolder_->OnSessionClosed(sessionId);
1174 }
1175
OnPinHolderBytesReceived(int sessionId,const void * data,unsigned int dataLen)1176 void DeviceManagerService::OnPinHolderBytesReceived(int sessionId, const void *data, unsigned int dataLen)
1177 {
1178 PinHolderSession::OnBytesReceived(sessionId, data, dataLen);
1179 }
1180
RequestCredential(const std::string & reqJsonStr,std::string & returnJsonStr)1181 int32_t DeviceManagerService::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr)
1182 {
1183 if (!PermissionManager::GetInstance().CheckPermission()) {
1184 LOGE("The caller does not have permission to call RequestCredential.");
1185 return ERR_DM_NO_PERMISSION;
1186 }
1187 if (!IsDMServiceImplReady()) {
1188 LOGE("RequestCredential failed, instance not init or init failed.");
1189 return ERR_DM_NOT_INIT;
1190 }
1191 return dmServiceImpl_->RequestCredential(reqJsonStr, returnJsonStr);
1192 }
1193
ImportCredential(const std::string & pkgName,const std::string & credentialInfo)1194 int32_t DeviceManagerService::ImportCredential(const std::string &pkgName, const std::string &credentialInfo)
1195 {
1196 if (!PermissionManager::GetInstance().CheckPermission()) {
1197 LOGE("The caller: %{public}s does not have permission to call ImportCredential.",
1198 pkgName.c_str());
1199 return ERR_DM_NO_PERMISSION;
1200 }
1201 if (!IsDMServiceImplReady()) {
1202 LOGE("ImportCredential failed, instance not init or init failed.");
1203 return ERR_DM_NOT_INIT;
1204 }
1205 return dmServiceImpl_->ImportCredential(pkgName, credentialInfo);
1206 }
1207
DeleteCredential(const std::string & pkgName,const std::string & deleteInfo)1208 int32_t DeviceManagerService::DeleteCredential(const std::string &pkgName, const std::string &deleteInfo)
1209 {
1210 if (!PermissionManager::GetInstance().CheckPermission()) {
1211 LOGE("The caller: %{public}s does not have permission to call DeleteCredential.",
1212 pkgName.c_str());
1213 return ERR_DM_NO_PERMISSION;
1214 }
1215 if (!IsDMServiceImplReady()) {
1216 LOGE("DeleteCredential failed, instance not init or init failed.");
1217 return ERR_DM_NOT_INIT;
1218 }
1219 return dmServiceImpl_->DeleteCredential(pkgName, deleteInfo);
1220 }
1221
MineRequestCredential(const std::string & pkgName,std::string & returnJsonStr)1222 int32_t DeviceManagerService::MineRequestCredential(const std::string &pkgName, std::string &returnJsonStr)
1223 {
1224 if (!PermissionManager::GetInstance().CheckPermission()) {
1225 LOGE("The caller does not have permission to call RequestCredential.");
1226 return ERR_DM_NO_PERMISSION;
1227 }
1228 if (!IsDMServiceImplReady()) {
1229 LOGE("RequestCredential failed, instance not init or init failed.");
1230 return ERR_DM_NOT_INIT;
1231 }
1232 return dmServiceImpl_->MineRequestCredential(pkgName, returnJsonStr);
1233 }
1234
CheckCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)1235 int32_t DeviceManagerService::CheckCredential(const std::string &pkgName, const std::string &reqJsonStr,
1236 std::string &returnJsonStr)
1237 {
1238 if (!PermissionManager::GetInstance().CheckPermission()) {
1239 LOGE("The caller: %{public}s does not have permission to call CheckCredential.",
1240 pkgName.c_str());
1241 return ERR_DM_NO_PERMISSION;
1242 }
1243 if (!IsDMServiceImplReady()) {
1244 LOGE("CheckCredential failed, instance not init or init failed.");
1245 return ERR_DM_NOT_INIT;
1246 }
1247 return dmServiceImpl_->CheckCredential(pkgName, reqJsonStr, returnJsonStr);
1248 }
1249
ImportCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)1250 int32_t DeviceManagerService::ImportCredential(const std::string &pkgName, const std::string &reqJsonStr,
1251 std::string &returnJsonStr)
1252 {
1253 if (!PermissionManager::GetInstance().CheckPermission()) {
1254 LOGE("The caller: %{public}s does not have permission to call ImportCredential.",
1255 pkgName.c_str());
1256 return ERR_DM_NO_PERMISSION;
1257 }
1258 if (!IsDMServiceImplReady()) {
1259 LOGE("ImportCredential failed, instance not init or init failed.");
1260 return ERR_DM_NOT_INIT;
1261 }
1262 return dmServiceImpl_->ImportCredential(pkgName, reqJsonStr, returnJsonStr);
1263 }
1264
DeleteCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)1265 int32_t DeviceManagerService::DeleteCredential(const std::string &pkgName, const std::string &reqJsonStr,
1266 std::string &returnJsonStr)
1267 {
1268 if (!PermissionManager::GetInstance().CheckPermission()) {
1269 LOGE("The caller: %{public}s does not have permission to call DeleteCredential.",
1270 pkgName.c_str());
1271 return ERR_DM_NO_PERMISSION;
1272 }
1273 if (!IsDMServiceImplReady()) {
1274 LOGE("DeleteCredential failed, instance not init or init failed.");
1275 return ERR_DM_NOT_INIT;
1276 }
1277 return dmServiceImpl_->DeleteCredential(pkgName, reqJsonStr, returnJsonStr);
1278 }
1279
RegisterCredentialCallback(const std::string & pkgName)1280 int32_t DeviceManagerService::RegisterCredentialCallback(const std::string &pkgName)
1281 {
1282 if (!PermissionManager::GetInstance().CheckPermission()) {
1283 LOGE("The caller: %{public}s does not have permission to call RegisterCredentialCallback.", pkgName.c_str());
1284 return ERR_DM_NO_PERMISSION;
1285 }
1286 if (!IsDMServiceImplReady()) {
1287 LOGE("RegisterCredentialCallback failed, instance not init or init failed.");
1288 return ERR_DM_NOT_INIT;
1289 }
1290 return dmServiceImpl_->RegisterCredentialCallback(pkgName);
1291 }
1292
UnRegisterCredentialCallback(const std::string & pkgName)1293 int32_t DeviceManagerService::UnRegisterCredentialCallback(const std::string &pkgName)
1294 {
1295 if (!PermissionManager::GetInstance().CheckPermission()) {
1296 LOGE("The caller: %{public}s does not have permission to call UnRegisterCredentialCallback.",
1297 pkgName.c_str());
1298 return ERR_DM_NO_PERMISSION;
1299 }
1300 if (!IsDMServiceImplReady()) {
1301 LOGE("UnRegisterCredentialCallback failed, instance not init or init failed.");
1302 return ERR_DM_NOT_INIT;
1303 }
1304 return dmServiceImpl_->UnRegisterCredentialCallback(pkgName);
1305 }
1306
RegisterUiStateCallback(const std::string & pkgName)1307 int32_t DeviceManagerService::RegisterUiStateCallback(const std::string &pkgName)
1308 {
1309 if (pkgName.empty()) {
1310 LOGE("DeviceManagerService::RegisterUiStateCallback error: Invalid parameter, pkgName: %{public}s",
1311 pkgName.c_str());
1312 return ERR_DM_INPUT_PARA_INVALID;
1313 }
1314 if (!PermissionManager::GetInstance().CheckPermission()) {
1315 LOGE("The caller: %{public}s does not have permission to call RegisterUiStateCallback.",
1316 GetAnonyString(pkgName).c_str());
1317 return ERR_DM_NO_PERMISSION;
1318 }
1319 if (!IsDMServiceImplReady()) {
1320 LOGE("RegisterUiStateCallback failed, instance not init or init failed.");
1321 return ERR_DM_NOT_INIT;
1322 }
1323 return dmServiceImpl_->RegisterUiStateCallback(pkgName);
1324 }
1325
UnRegisterUiStateCallback(const std::string & pkgName)1326 int32_t DeviceManagerService::UnRegisterUiStateCallback(const std::string &pkgName)
1327 {
1328 if (pkgName.empty()) {
1329 LOGE("DeviceManagerService::UnRegisterUiStateCallback error: Invalid parameter, pkgName: %{public}s",
1330 pkgName.c_str());
1331 return ERR_DM_INPUT_PARA_INVALID;
1332 }
1333 if (!PermissionManager::GetInstance().CheckPermission()) {
1334 LOGE("The caller: %{public}s does not have permission to call UnRegisterUiStateCallback.",
1335 GetAnonyString(pkgName).c_str());
1336 return ERR_DM_NO_PERMISSION;
1337 }
1338 if (!IsDMServiceImplReady()) {
1339 LOGE("UnRegisterUiStateCallback failed, instance not init or init failed.");
1340 return ERR_DM_NOT_INIT;
1341 }
1342 return dmServiceImpl_->UnRegisterUiStateCallback(pkgName);
1343 }
1344
IsDMServiceImplReady()1345 bool DeviceManagerService::IsDMServiceImplReady()
1346 {
1347 std::lock_guard<std::mutex> lock(isImplLoadLock_);
1348 if (isImplsoLoaded_ && (dmServiceImpl_ != nullptr)) {
1349 return true;
1350 }
1351 LOGI("libdevicemanagerserviceimpl start load.");
1352 void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD);
1353 if (so_handle == nullptr) {
1354 so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE);
1355 }
1356 if (so_handle == nullptr) {
1357 LOGE("load libdevicemanagerserviceimpl so failed, errMsg: %{public}s.", dlerror());
1358 return false;
1359 }
1360 dlerror();
1361 auto func = (CreateDMServiceFuncPtr)dlsym(so_handle, "CreateDMServiceObject");
1362 if (dlerror() != nullptr || func == nullptr) {
1363 dlclose(so_handle);
1364 LOGE("Create object function is not exist.");
1365 return false;
1366 }
1367
1368 dmServiceImpl_ = std::shared_ptr<IDeviceManagerServiceImpl>(func());
1369 if (listener_ == nullptr) {
1370 listener_ = std::make_shared<DeviceManagerServiceListener>();
1371 }
1372 if (dmServiceImpl_->Initialize(listener_) != DM_OK) {
1373 dmServiceImpl_ = nullptr;
1374 isImplsoLoaded_ = false;
1375 return false;
1376 }
1377 isImplsoLoaded_ = true;
1378 LOGI("Sussess.");
1379 return true;
1380 }
1381
IsDMImplSoLoaded()1382 bool DeviceManagerService::IsDMImplSoLoaded()
1383 {
1384 std::lock_guard<std::mutex> lock(isImplLoadLock_);
1385 return isImplsoLoaded_;
1386 }
1387
IsDMServiceAdapterSoLoaded()1388 bool DeviceManagerService::IsDMServiceAdapterSoLoaded()
1389 {
1390 std::lock_guard<std::mutex> lock(isAdapterResidentLoadLock_);
1391 if (!isAdapterResidentSoLoaded_ || (dmServiceImplExtResident_ == nullptr)) {
1392 return false;
1393 }
1394 return dmServiceImplExtResident_->IsDMServiceAdapterSoLoaded();
1395 }
1396
DmHiDumper(const std::vector<std::string> & args,std::string & result)1397 int32_t DeviceManagerService::DmHiDumper(const std::vector<std::string>& args, std::string &result)
1398 {
1399 LOGI("HiDump GetTrustedDeviceList");
1400 std::vector<HidumperFlag> dumpflag;
1401 HiDumpHelper::GetInstance().GetArgsType(args, dumpflag);
1402
1403 for (unsigned int i = 0; i < dumpflag.size(); i++) {
1404 if (dumpflag[i] == HidumperFlag::HIDUMPER_GET_TRUSTED_LIST) {
1405 std::vector<DmDeviceInfo> deviceList;
1406 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1407 int32_t ret = softbusListener_->GetTrustedDeviceList(deviceList);
1408 if (ret != DM_OK) {
1409 result.append("HiDumpHelper GetTrustedDeviceList failed");
1410 LOGE("HiDumpHelper GetTrustedDeviceList failed");
1411 return ret;
1412 }
1413
1414 for (unsigned int j = 0; j < deviceList.size(); j++) {
1415 HiDumpHelper::GetInstance().SetNodeInfo(deviceList[j]);
1416 LOGI("DeviceManagerService::DmHiDumper SetNodeInfo.");
1417 }
1418 }
1419 }
1420 HiDumpHelper::GetInstance().HiDump(args, result);
1421 return DM_OK;
1422 }
1423
NotifyEvent(const std::string & pkgName,const int32_t eventId,const std::string & event)1424 int32_t DeviceManagerService::NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event)
1425 {
1426 if (!PermissionManager::GetInstance().CheckPermission()) {
1427 LOGE("The caller: %{public}s does not have permission to call NotifyEvent.", pkgName.c_str());
1428 return ERR_DM_NO_PERMISSION;
1429 }
1430 if (!IsDMServiceImplReady()) {
1431 LOGE("NotifyEvent failed, instance not init or init failed.");
1432 return ERR_DM_NOT_INIT;
1433 }
1434 if (eventId == DM_NOTIFY_EVENT_ON_PINHOLDER_EVENT) {
1435 LOGI("NotifyEvent on pin holder event start.");
1436 CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
1437 return pinHolder_->NotifyPinHolderEvent(pkgName, event);
1438 }
1439 return dmServiceImpl_->NotifyEvent(pkgName, eventId, event);
1440 }
1441
LoadHardwareFwkService()1442 void DeviceManagerService::LoadHardwareFwkService()
1443 {
1444 std::vector<DmDeviceInfo> deviceList;
1445 CHECK_NULL_VOID(softbusListener_);
1446 int32_t ret = GetTrustedDeviceList(DHARD_WARE_PKG_NAME, deviceList);
1447 if (ret != DM_OK) {
1448 LOGE("LoadHardwareFwkService failed, get trusted devicelist failed.");
1449 return;
1450 }
1451 if (deviceList.empty()) {
1452 LOGI("no trusted device.");
1453 return;
1454 }
1455 if (!IsDMServiceImplReady()) {
1456 LOGE("LoadHardwareFwkService failed, instance not init or init failed.");
1457 return;
1458 }
1459 dmServiceImpl_->LoadHardwareFwkService();
1460 }
1461
GetEncryptedUuidByNetworkId(const std::string & pkgName,const std::string & networkId,std::string & uuid)1462 int32_t DeviceManagerService::GetEncryptedUuidByNetworkId(const std::string &pkgName, const std::string &networkId,
1463 std::string &uuid)
1464 {
1465 if (pkgName.empty()) {
1466 LOGE("Invalid parameter, pkgName is empty.");
1467 return ERR_DM_INPUT_PARA_INVALID;
1468 }
1469 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1470 int32_t ret = softbusListener_->GetUuidByNetworkId(networkId.c_str(), uuid);
1471 if (ret != DM_OK) {
1472 LOGE("GetUuidByNetworkId failed, ret : %{public}d", ret);
1473 return ret;
1474 }
1475
1476 std::string appId = Crypto::Sha256(AppManager::GetInstance().GetAppId());
1477 uuid = Crypto::Sha256(appId + "_" + uuid);
1478 LOGI("appId = %{public}s, uuid = %{public}s, encryptedUuid = %{public}s.", GetAnonyString(appId).c_str(),
1479 GetAnonyString(uuid).c_str(), GetAnonyString(uuid).c_str());
1480 return DM_OK;
1481 }
1482
GenerateEncryptedUuid(const std::string & pkgName,const std::string & uuid,const std::string & appId,std::string & encryptedUuid)1483 int32_t DeviceManagerService::GenerateEncryptedUuid(const std::string &pkgName, const std::string &uuid,
1484 const std::string &appId, std::string &encryptedUuid)
1485 {
1486 if (pkgName.empty()) {
1487 LOGE("Invalid parameter, pkgName is empty.");
1488 return ERR_DM_INPUT_PARA_INVALID;
1489 }
1490 encryptedUuid = Crypto::Sha256(appId + "_" + uuid);
1491 LOGI("encryptedUuid = %{public}s.", GetAnonyString(encryptedUuid).c_str());
1492 return DM_OK;
1493 }
1494
CheckApiPermission(int32_t permissionLevel)1495 int32_t DeviceManagerService::CheckApiPermission(int32_t permissionLevel)
1496 {
1497 LOGI("PermissionLevel: %{public}d", permissionLevel);
1498 int32_t ret = ERR_DM_NO_PERMISSION;
1499 switch (permissionLevel) {
1500 case NORMAL:
1501 if (PermissionManager::GetInstance().CheckNewPermission()) {
1502 LOGI("The caller have permission to call");
1503 ret = DM_OK;
1504 }
1505 break;
1506 case SYSTEM_BASIC:
1507 if (PermissionManager::GetInstance().CheckPermission()) {
1508 LOGI("The caller have permission to call");
1509 ret = DM_OK;
1510 }
1511 break;
1512 case SYSTEM_CORE:
1513 if (PermissionManager::GetInstance().CheckMonitorPermission()) {
1514 LOGI("The caller have permission to call");
1515 ret = DM_OK;
1516 }
1517 break;
1518 default:
1519 LOGE("DM have not this permissionLevel.");
1520 break;
1521 }
1522 return ret;
1523 }
1524
GetNetworkTypeByNetworkId(const std::string & pkgName,const std::string & netWorkId,int32_t & networkType)1525 int32_t DeviceManagerService::GetNetworkTypeByNetworkId(const std::string &pkgName, const std::string &netWorkId,
1526 int32_t &networkType)
1527 {
1528 if (!PermissionManager::GetInstance().CheckPermission()) {
1529 LOGE("The caller: %{public}s does not have permission to call GetNetworkTypeByNetworkId.", pkgName.c_str());
1530 return ERR_DM_NO_PERMISSION;
1531 }
1532 if (pkgName.empty() || netWorkId.empty()) {
1533 LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(),
1534 GetAnonyString(netWorkId).c_str());
1535 return ERR_DM_INPUT_PARA_INVALID;
1536 }
1537 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1538 return softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
1539 }
1540
ImportAuthCode(const std::string & pkgName,const std::string & authCode)1541 int32_t DeviceManagerService::ImportAuthCode(const std::string &pkgName, const std::string &authCode)
1542 {
1543 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1544 LOGE("The caller: %{public}s does not have permission to call ImportAuthCode.", pkgName.c_str());
1545 return ERR_DM_NO_PERMISSION;
1546 }
1547 std::string processName = "";
1548 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
1549 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
1550 return ERR_DM_FAILED;
1551 }
1552 if (!PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName)) {
1553 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
1554 return ERR_DM_INPUT_PARA_INVALID;
1555 }
1556 if (authCode.empty() || pkgName.empty()) {
1557 LOGE("Invalid parameter, authCode: %{public}s.", GetAnonyString(authCode).c_str());
1558 return ERR_DM_INPUT_PARA_INVALID;
1559 }
1560 if (!IsDMServiceImplReady()) {
1561 LOGE("ImportAuthCode failed, instance not init or init failed.");
1562 return ERR_DM_NOT_INIT;
1563 }
1564 return dmServiceImpl_->ImportAuthCode(pkgName, authCode);
1565 }
1566
ExportAuthCode(std::string & authCode)1567 int32_t DeviceManagerService::ExportAuthCode(std::string &authCode)
1568 {
1569 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1570 LOGE("The caller does not have permission to call ExportAuthCode.");
1571 return ERR_DM_NO_PERMISSION;
1572 }
1573 std::string processName = "";
1574 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
1575 LOGE("Get caller process name failed, processName: %{public}s.", processName.c_str());
1576 return ERR_DM_FAILED;
1577 }
1578 if (!PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName)) {
1579 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
1580 return ERR_DM_INPUT_PARA_INVALID;
1581 }
1582 if (!IsDMServiceImplReady()) {
1583 LOGE("ExportAuthCode failed, instance not init or init failed.");
1584 return ERR_DM_NOT_INIT;
1585 }
1586 return dmServiceImpl_->ExportAuthCode(authCode);
1587 }
1588
UnloadDMServiceImplSo()1589 void DeviceManagerService::UnloadDMServiceImplSo()
1590 {
1591 LOGI("Start.");
1592 std::lock_guard<std::mutex> lock(isImplLoadLock_);
1593 if (dmServiceImpl_ != nullptr) {
1594 dmServiceImpl_->Release();
1595 }
1596 void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NOLOAD);
1597 if (so_handle != nullptr) {
1598 LOGI("DeviceManagerService so_handle is not nullptr.");
1599 dlclose(so_handle);
1600 }
1601 }
1602
IsDMServiceAdapterResidentLoad()1603 bool DeviceManagerService::IsDMServiceAdapterResidentLoad()
1604 {
1605 if (listener_ == nullptr) {
1606 listener_ = std::make_shared<DeviceManagerServiceListener>();
1607 }
1608 std::lock_guard<std::mutex> lock(isAdapterResidentLoadLock_);
1609 if (isAdapterResidentSoLoaded_ && (dmServiceImplExtResident_ != nullptr)) {
1610 return true;
1611 }
1612 residentSoHandle_ = dlopen(LIB_DM_RESIDENT_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD);
1613 if (residentSoHandle_ == nullptr) {
1614 residentSoHandle_ = dlopen(LIB_DM_RESIDENT_NAME, RTLD_NOW | RTLD_NODELETE);
1615 }
1616 if (residentSoHandle_ == nullptr) {
1617 LOGE("load dm service resident so failed.");
1618 return false;
1619 }
1620 dlerror();
1621 auto func = (CreateDMServiceExtResidentFuncPtr)dlsym(residentSoHandle_, "CreateDMServiceExtResidentObject");
1622 if (dlerror() != nullptr || func == nullptr) {
1623 dlclose(residentSoHandle_);
1624 residentSoHandle_ = nullptr;
1625 LOGE("Create object function is not exist.");
1626 return false;
1627 }
1628
1629 dmServiceImplExtResident_ = std::shared_ptr<IDMServiceImplExtResident>(func());
1630 if (dmServiceImplExtResident_->Initialize(listener_) != DM_OK) {
1631 dlclose(residentSoHandle_);
1632 residentSoHandle_ = nullptr;
1633 dmServiceImplExtResident_ = nullptr;
1634 isAdapterResidentSoLoaded_ = false;
1635 LOGE("dm service impl ext resident init failed.");
1636 return false;
1637 }
1638 isAdapterResidentSoLoaded_ = true;
1639 LOGI("Success.");
1640 return true;
1641 }
1642
UnloadDMServiceAdapterResident()1643 void DeviceManagerService::UnloadDMServiceAdapterResident()
1644 {
1645 LOGI("Start.");
1646 std::lock_guard<std::mutex> lock(isAdapterResidentLoadLock_);
1647 if (dmServiceImplExtResident_ != nullptr) {
1648 dmServiceImplExtResident_->Release();
1649 }
1650 dmServiceImplExtResident_ = nullptr;
1651 if (residentSoHandle_ != nullptr) {
1652 LOGI("dm service resident residentSoHandle_ is not nullptr.");
1653 dlclose(residentSoHandle_);
1654 residentSoHandle_ = nullptr;
1655 }
1656 }
1657
IsDMDeviceRiskDetectSoLoaded()1658 bool DeviceManagerService::IsDMDeviceRiskDetectSoLoaded()
1659 {
1660 std::lock_guard<std::mutex> lock(isDeviceRiskDetectSoLoadLock_);
1661 if (isDeviceRiskDetectSoLoaded_ && (dmDeviceRiskDetect_ != nullptr)) {
1662 return true;
1663 }
1664 deviceRiskDetectSoHandle_ = dlopen(LIB_DM_DEVICE_RISK_DETECT_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD);
1665 if (deviceRiskDetectSoHandle_ == nullptr) {
1666 deviceRiskDetectSoHandle_ = dlopen(LIB_DM_DEVICE_RISK_DETECT_NAME, RTLD_NOW | RTLD_NODELETE);
1667 }
1668 if (deviceRiskDetectSoHandle_ == nullptr) {
1669 LOGE("load dm device risk detect so failed.");
1670 return false;
1671 }
1672 dlerror();
1673 auto func = (CreateDMDeviceRiskDetectFuncPtr)dlsym(deviceRiskDetectSoHandle_, "CreateDMDeviceRiskDetectObject");
1674 if (dlerror() != nullptr || func == nullptr) {
1675 dlclose(deviceRiskDetectSoHandle_);
1676 deviceRiskDetectSoHandle_ = nullptr;
1677 LOGE("Create object function is not exist.");
1678 return false;
1679 }
1680
1681 dmDeviceRiskDetect_ = std::shared_ptr<IDMDeviceRiskDetect>(func());
1682 if (dmDeviceRiskDetect_->Initialize() != DM_OK) {
1683 dlclose(deviceRiskDetectSoHandle_);
1684 deviceRiskDetectSoHandle_ = nullptr;
1685 dmDeviceRiskDetect_ = nullptr;
1686 isDeviceRiskDetectSoLoaded_ = false;
1687 LOGE("dm sdevice risk detect init failed.");
1688 return false;
1689 }
1690 isDeviceRiskDetectSoLoaded_ = true;
1691 LOGI("Success.");
1692 return true;
1693 }
1694
UnloadDMDeviceRiskDetect()1695 void DeviceManagerService::UnloadDMDeviceRiskDetect()
1696 {
1697 LOGI("Start.");
1698 std::lock_guard<std::mutex> lock(isDeviceRiskDetectSoLoadLock_);
1699 if (dmDeviceRiskDetect_ != nullptr) {
1700 dmDeviceRiskDetect_->Release();
1701 dmDeviceRiskDetect_ = nullptr;
1702 }
1703 if (deviceRiskDetectSoHandle_ != nullptr) {
1704 LOGI("dm device risk detect deviceRiskDetectSoHandle_ is not nullptr.");
1705 dlclose(deviceRiskDetectSoHandle_);
1706 deviceRiskDetectSoHandle_ = nullptr;
1707 }
1708 }
1709
StartDiscovering(const std::string & pkgName,const std::map<std::string,std::string> & discoverParam,const std::map<std::string,std::string> & filterOptions)1710 int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName,
1711 const std::map<std::string, std::string> &discoverParam, const std::map<std::string, std::string> &filterOptions)
1712 {
1713 if (!PermissionManager::GetInstance().CheckNewPermission() &&
1714 !PermissionManager::GetInstance().CheckPermission()) {
1715 LOGE("The caller does not have permission to call");
1716 return ERR_DM_NO_PERMISSION;
1717 }
1718 if (pkgName.empty()) {
1719 LOGE("Invalid parameter, pkgName is empty.");
1720 return ERR_DM_INPUT_PARA_INVALID;
1721 }
1722 if (discoverParam.find(PARAM_KEY_META_TYPE) != discoverParam.end()) {
1723 LOGI("StartDiscovering input MetaType = %{public}s", (discoverParam.find(PARAM_KEY_META_TYPE)->second).c_str());
1724 }
1725 CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL);
1726 return discoveryMgr_->StartDiscovering(pkgName, discoverParam, filterOptions);
1727 }
1728
StopDiscovering(const std::string & pkgName,const std::map<std::string,std::string> & discoverParam)1729 int32_t DeviceManagerService::StopDiscovering(const std::string &pkgName,
1730 const std::map<std::string, std::string> &discoverParam)
1731 {
1732 if (!PermissionManager::GetInstance().CheckNewPermission() &&
1733 !PermissionManager::GetInstance().CheckPermission()) {
1734 LOGE("The caller does not have permission to call");
1735 return ERR_DM_NO_PERMISSION;
1736 }
1737 if (pkgName.empty()) {
1738 LOGE("Invalid parameter, pkgName is empty.");
1739 return ERR_DM_INPUT_PARA_INVALID;
1740 }
1741 uint16_t subscribeId = -1;
1742 if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) {
1743 subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str());
1744 }
1745 if (discoverParam.find(PARAM_KEY_META_TYPE) != discoverParam.end()) {
1746 LOGI("StopDiscovering input MetaType = %{public}s", (discoverParam.find(PARAM_KEY_META_TYPE)->second).c_str());
1747 }
1748 CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL);
1749 return discoveryMgr_->StopDiscovering(pkgName, subscribeId);
1750 }
1751
EnableDiscoveryListener(const std::string & pkgName,const std::map<std::string,std::string> & discoverParam,const std::map<std::string,std::string> & filterOptions)1752 int32_t DeviceManagerService::EnableDiscoveryListener(const std::string &pkgName,
1753 const std::map<std::string, std::string> &discoverParam, const std::map<std::string, std::string> &filterOptions)
1754 {
1755 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1756 LOGE("The caller does not have permission to call");
1757 return ERR_DM_NO_PERMISSION;
1758 }
1759 if (pkgName.empty()) {
1760 LOGE("Invalid parameter, pkgName is empty.");
1761 return ERR_DM_INPUT_PARA_INVALID;
1762 }
1763 SoftbusListener::SetHostPkgName(pkgName);
1764 CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL);
1765 return discoveryMgr_->EnableDiscoveryListener(pkgName, discoverParam, filterOptions);
1766 }
1767
DisableDiscoveryListener(const std::string & pkgName,const std::map<std::string,std::string> & extraParam)1768 int32_t DeviceManagerService::DisableDiscoveryListener(const std::string &pkgName,
1769 const std::map<std::string, std::string> &extraParam)
1770 {
1771 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1772 LOGE("The caller does not have permission to call");
1773 return ERR_DM_NO_PERMISSION;
1774 }
1775 if (pkgName.empty()) {
1776 LOGE("Invalid parameter, pkgName is empty.");
1777 return ERR_DM_INPUT_PARA_INVALID;
1778 }
1779 CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL);
1780 return discoveryMgr_->DisableDiscoveryListener(pkgName, extraParam);
1781 }
1782
StartAdvertising(const std::string & pkgName,const std::map<std::string,std::string> & advertiseParam)1783 int32_t DeviceManagerService::StartAdvertising(const std::string &pkgName,
1784 const std::map<std::string, std::string> &advertiseParam)
1785 {
1786 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1787 LOGE("The caller does not have permission to call");
1788 return ERR_DM_NO_PERMISSION;
1789 }
1790 if (pkgName.empty()) {
1791 LOGE("Invalid parameter, pkgName is empty.");
1792 return ERR_DM_INPUT_PARA_INVALID;
1793 }
1794 CHECK_NULL_RETURN(advertiseMgr_, ERR_DM_POINT_NULL);
1795 return advertiseMgr_->StartAdvertising(pkgName, advertiseParam);
1796 }
1797
StopAdvertising(const std::string & pkgName,const std::map<std::string,std::string> & advertiseParam)1798 int32_t DeviceManagerService::StopAdvertising(const std::string &pkgName,
1799 const std::map<std::string, std::string> &advertiseParam)
1800 {
1801 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1802 LOGE("The caller does not have permission to call");
1803 return ERR_DM_NO_PERMISSION;
1804 }
1805 if (pkgName.empty()) {
1806 LOGE("Invalid parameter, pkgName is empty.");
1807 return ERR_DM_INPUT_PARA_INVALID;
1808 }
1809 if (advertiseParam.find(PARAM_KEY_META_TYPE) != advertiseParam.end()) {
1810 LOGI("StopAdvertising input MetaType=%{public}s", (advertiseParam.find(PARAM_KEY_META_TYPE)->second).c_str());
1811 }
1812 int32_t publishId = -1;
1813 if (advertiseParam.find(PARAM_KEY_PUBLISH_ID) != advertiseParam.end()) {
1814 publishId = std::atoi((advertiseParam.find(PARAM_KEY_PUBLISH_ID)->second).c_str());
1815 }
1816 CHECK_NULL_RETURN(advertiseMgr_, ERR_DM_POINT_NULL);
1817 return advertiseMgr_->StopAdvertising(pkgName, publishId);
1818 }
1819
BindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam)1820 int32_t DeviceManagerService::BindTarget(const std::string &pkgName, const PeerTargetId &targetId,
1821 const std::map<std::string, std::string> &bindParam)
1822 {
1823 LOGI("DeviceManagerService::BindTarget");
1824 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1825 LOGE("The caller does not have permission to call");
1826 return ERR_DM_NO_PERMISSION;
1827 }
1828 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1829 if (pkgName.empty() || pkgName == std::string(DM_PKG_NAME)) {
1830 LOGE("Invalid parameter, pkgName is empty.");
1831 return ERR_DM_INPUT_PARA_INVALID;
1832 }
1833 if (bindParam.find(PARAM_KEY_META_TYPE) == bindParam.end()) {
1834 if (!IsDMServiceImplReady()) {
1835 LOGE("BindTarget failed, DMServiceImpl instance not init or init failed.");
1836 return ERR_DM_NOT_INIT;
1837 }
1838 LOGI("BindTarget stardard begin.");
1839 if (targetId.wifiIp.empty() || targetId.wifiIp.length() > IP_STR_MAX_LEN) {
1840 return dmServiceImpl_->BindTarget(pkgName, targetId, bindParam);
1841 }
1842 ConnectionAddrType ipAddrType;
1843 std::map<std::string, std::string> &noConstBindParam =
1844 const_cast<std::map<std::string, std::string> &>(bindParam);
1845 if (SoftbusListener::GetIPAddrTypeFromCache(targetId.deviceId, targetId.wifiIp, ipAddrType) == DM_OK) {
1846 noConstBindParam.insert(std::pair<std::string, std::string>(PARAM_KEY_CONN_ADDR_TYPE,
1847 std::to_string(ipAddrType)));
1848 }
1849 const std::map<std::string, std::string> &constBindParam =
1850 const_cast<const std::map<std::string, std::string> &>(noConstBindParam);
1851 return dmServiceImpl_->BindTarget(pkgName, targetId, constBindParam);
1852 }
1853 if (!AppManager::GetInstance().IsSystemSA() && !AppManager::GetInstance().IsSystemApp()) {
1854 LOGE("The caller does not have permission to call");
1855 return ERR_DM_NO_PERMISSION;
1856 }
1857 if (!IsDMServiceAdapterResidentLoad()) {
1858 LOGE("BindTarget failed, adapter instance not init or init failed.");
1859 return ERR_DM_UNSUPPORTED_METHOD;
1860 }
1861 LOGI("BindTarget unstardard begin.");
1862 return dmServiceImplExtResident_->BindTargetExt(pkgName, targetId, bindParam);
1863 }
1864
UnbindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & unbindParam)1865 int32_t DeviceManagerService::UnbindTarget(const std::string &pkgName, const PeerTargetId &targetId,
1866 const std::map<std::string, std::string> &unbindParam)
1867 {
1868 if (!PermissionManager::GetInstance().CheckNewPermission()) {
1869 LOGE("The caller does not have permission to call");
1870 return ERR_DM_NO_PERMISSION;
1871 }
1872 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1873 if (pkgName.empty() || pkgName == std::string(DM_PKG_NAME)) {
1874 LOGE("Invalid parameter, pkgName is empty.");
1875 return ERR_DM_INPUT_PARA_INVALID;
1876 }
1877 if (!IsDMServiceAdapterResidentLoad()) {
1878 LOGE("UnbindTarget failed, instance not init or init failed.");
1879 return ERR_DM_UNSUPPORTED_METHOD;
1880 }
1881 if (unbindParam.find(PARAM_KEY_META_TYPE) == unbindParam.end()) {
1882 LOGE("input unbind parameter not contains META_TYPE, dm service adapter not supported.");
1883 return ERR_DM_INPUT_PARA_INVALID;
1884 }
1885 if (!AppManager::GetInstance().IsSystemSA() && !AppManager::GetInstance().IsSystemApp()) {
1886 LOGE("The caller does not have permission to call");
1887 return ERR_DM_NO_PERMISSION;
1888 }
1889 std::string realDeviceId = targetId.deviceId;
1890 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1891 std::string udidHashTemp = "";
1892 if (GetUdidHashByAnoyDeviceId(realDeviceId, udidHashTemp) == DM_OK) {
1893 realDeviceId = udidHashTemp;
1894 }
1895 #endif
1896 std::map<std::string, std::string> unbindParamWithUdid(unbindParam);
1897 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1898 std::string udid = "";
1899 if (softbusListener_->GetUdidFromDp(realDeviceId, udid) == DM_OK) {
1900 unbindParamWithUdid.insert(std::pair<std::string, std::string>(UN_BIND_PARAM_UDID_KEY, udid));
1901 }
1902 return dmServiceImplExtResident_->UnbindTargetExt(pkgName, targetId, unbindParamWithUdid);
1903 }
1904
1905 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
InitDPLocalServiceInfo(const DMLocalServiceInfo & serviceInfo,DistributedDeviceProfile::LocalServiceInfo & dpLocalServiceInfo)1906 bool DeviceManagerService::InitDPLocalServiceInfo(const DMLocalServiceInfo &serviceInfo,
1907 DistributedDeviceProfile::LocalServiceInfo &dpLocalServiceInfo)
1908 {
1909 dpLocalServiceInfo.SetBundleName(serviceInfo.bundleName);
1910 dpLocalServiceInfo.SetAuthBoxType(serviceInfo.authBoxType);
1911 dpLocalServiceInfo.SetAuthType(serviceInfo.authType);
1912 dpLocalServiceInfo.SetPinExchangeType(serviceInfo.pinExchangeType);
1913 dpLocalServiceInfo.SetPinCode(serviceInfo.pinCode);
1914 dpLocalServiceInfo.SetDescription(serviceInfo.description);
1915 dpLocalServiceInfo.SetExtraInfo(serviceInfo.extraInfo);
1916 return true;
1917 }
1918
InitServiceInfo(const DistributedDeviceProfile::LocalServiceInfo & dpLocalServiceInfo,DMLocalServiceInfo & serviceInfo)1919 void DeviceManagerService::InitServiceInfo(const DistributedDeviceProfile::LocalServiceInfo &dpLocalServiceInfo,
1920 DMLocalServiceInfo &serviceInfo)
1921 {
1922 serviceInfo.bundleName = dpLocalServiceInfo.GetBundleName();
1923 serviceInfo.authBoxType = dpLocalServiceInfo.GetAuthBoxType();
1924 serviceInfo.authType = dpLocalServiceInfo.GetAuthType();
1925 serviceInfo.pinExchangeType = dpLocalServiceInfo.GetPinExchangeType();
1926 serviceInfo.pinCode = dpLocalServiceInfo.GetPinCode();
1927 serviceInfo.description = dpLocalServiceInfo.GetDescription();
1928 serviceInfo.extraInfo = dpLocalServiceInfo.GetExtraInfo();
1929 }
1930
InitServiceInfos(const std::vector<DistributedDeviceProfile::LocalServiceInfo> & dpLocalServiceInfos,std::vector<DMLocalServiceInfo> & serviceInfos)1931 void DeviceManagerService::InitServiceInfos(
1932 const std::vector<DistributedDeviceProfile::LocalServiceInfo> &dpLocalServiceInfos,
1933 std::vector<DMLocalServiceInfo> &serviceInfos)
1934 {
1935 for (const auto &dpInfoItem : dpLocalServiceInfos) {
1936 DMLocalServiceInfo infoItem;
1937 InitServiceInfo(dpInfoItem, infoItem);
1938 serviceInfos.emplace_back(infoItem);
1939 }
1940 }
1941 #endif
1942
RegisterLocalServiceInfo(const DMLocalServiceInfo & serviceInfo)1943 int32_t DeviceManagerService::RegisterLocalServiceInfo(const DMLocalServiceInfo &serviceInfo)
1944 {
1945 if (!PermissionManager::GetInstance().CheckPermission()) {
1946 LOGE("The caller does not have permission to call RegisterLocalServiceInfo.");
1947 return ERR_DM_NO_PERMISSION;
1948 }
1949 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1950 DistributedDeviceProfile::LocalServiceInfo dpLocalServiceInfo;
1951 bool success = InitDPLocalServiceInfo(serviceInfo, dpLocalServiceInfo);
1952 if (!success) {
1953 LOGE("InitDPLocalServiceInfo failed");
1954 return ERR_DM_FAILED;
1955 }
1956 return DeviceProfileConnector::GetInstance().PutLocalServiceInfo(dpLocalServiceInfo);
1957 #else
1958 (void)serviceInfo;
1959 return ERR_DM_FAILED;
1960 #endif
1961 }
1962
UnRegisterLocalServiceInfo(const std::string & bundleName,int32_t pinExchangeType)1963 int32_t DeviceManagerService::UnRegisterLocalServiceInfo(const std::string &bundleName, int32_t pinExchangeType)
1964 {
1965 if (!PermissionManager::GetInstance().CheckPermission()) {
1966 LOGE("The caller: %{public}s does not have permission to call UnRegisterLocalServiceInfo.",
1967 bundleName.c_str());
1968 return ERR_DM_NO_PERMISSION;
1969 }
1970 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1971 return DeviceProfileConnector::GetInstance().DeleteLocalServiceInfo(bundleName, pinExchangeType);
1972 #else
1973 (void)bundleName;
1974 (void)pinExchangeType;
1975 return ERR_DM_FAILED;
1976 #endif
1977 }
1978
UpdateLocalServiceInfo(const DMLocalServiceInfo & serviceInfo)1979 int32_t DeviceManagerService::UpdateLocalServiceInfo(const DMLocalServiceInfo &serviceInfo)
1980 {
1981 if (!PermissionManager::GetInstance().CheckPermission()) {
1982 LOGE("The caller does not have permission to call UpdateLocalServiceInfo.");
1983 return ERR_DM_NO_PERMISSION;
1984 }
1985 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1986 DistributedDeviceProfile::LocalServiceInfo dpLocalServiceInfo;
1987 bool success = InitDPLocalServiceInfo(serviceInfo, dpLocalServiceInfo);
1988 if (!success) {
1989 LOGE("InitDPLocalServiceInfo failed");
1990 return ERR_DM_FAILED;
1991 }
1992 return DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(dpLocalServiceInfo);
1993 #else
1994 (void)serviceInfo;
1995 return ERR_DM_FAILED;
1996 #endif
1997 }
1998
GetLocalServiceInfoByBundleNameAndPinExchangeType(const std::string & bundleName,int32_t pinExchangeType,DMLocalServiceInfo & serviceInfo)1999 int32_t DeviceManagerService::GetLocalServiceInfoByBundleNameAndPinExchangeType(const std::string &bundleName,
2000 int32_t pinExchangeType, DMLocalServiceInfo &serviceInfo)
2001 {
2002 if (!PermissionManager::GetInstance().CheckPermission()) {
2003 LOGE("The caller: %{public}s does not have permission to call GetLocalServiceInfo.",
2004 bundleName.c_str());
2005 return ERR_DM_NO_PERMISSION;
2006 }
2007 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
2008 DistributedDeviceProfile::LocalServiceInfo dpLocalServiceInfo;
2009 int32_t ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType(bundleName,
2010 pinExchangeType, dpLocalServiceInfo);
2011 if (ret == DM_OK) {
2012 InitServiceInfo(dpLocalServiceInfo, serviceInfo);
2013 }
2014 return ret;
2015 #else
2016 (void)bundleName;
2017 (void)pinExchangeType;
2018 (void)serviceInfo;
2019 return ERR_DM_FAILED;
2020 #endif
2021 }
2022
RegisterPinHolderCallback(const std::string & pkgName)2023 int32_t DeviceManagerService::RegisterPinHolderCallback(const std::string &pkgName)
2024 {
2025 if (!PermissionManager::GetInstance().CheckPermission()) {
2026 LOGE("The caller: %{public}s does not have permission to call ImportAuthCode.", pkgName.c_str());
2027 return ERR_DM_NO_PERMISSION;
2028 }
2029 std::string processName = "";
2030 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
2031 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
2032 return ERR_DM_FAILED;
2033 }
2034 if (!PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName)) {
2035 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
2036 return ERR_DM_INPUT_PARA_INVALID;
2037 }
2038 LOGI("DeviceManagerService::RegisterPinHolderCallback begin.");
2039 if (pkgName.empty()) {
2040 LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str());
2041 return ERR_DM_INPUT_PARA_INVALID;
2042 }
2043 CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
2044 return pinHolder_->RegisterPinHolderCallback(pkgName);
2045 }
2046
CreatePinHolder(const std::string & pkgName,const PeerTargetId & targetId,DmPinType pinType,const std::string & payload)2047 int32_t DeviceManagerService::CreatePinHolder(const std::string &pkgName, const PeerTargetId &targetId,
2048 DmPinType pinType, const std::string &payload)
2049 {
2050 if (!PermissionManager::GetInstance().CheckPermission()) {
2051 LOGE("The caller: %{public}s does not have permission to call CreatePinHolder.", pkgName.c_str());
2052 return ERR_DM_NO_PERMISSION;
2053 }
2054 std::string processName = "";
2055 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
2056 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
2057 return ERR_DM_FAILED;
2058 }
2059 if (!PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName)) {
2060 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
2061 return ERR_DM_INPUT_PARA_INVALID;
2062 }
2063 if (pkgName.empty()) {
2064 LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str());
2065 return ERR_DM_INPUT_PARA_INVALID;
2066 }
2067 CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
2068 return pinHolder_->CreatePinHolder(pkgName, targetId, pinType, payload);
2069 }
2070
DestroyPinHolder(const std::string & pkgName,const PeerTargetId & targetId,DmPinType pinType,const std::string & payload)2071 int32_t DeviceManagerService::DestroyPinHolder(const std::string &pkgName, const PeerTargetId &targetId,
2072 DmPinType pinType, const std::string &payload)
2073 {
2074 if (!PermissionManager::GetInstance().CheckPermission()) {
2075 LOGE("The caller: %{public}s does not have permission to call DestroyPinHolder.", pkgName.c_str());
2076 return ERR_DM_NO_PERMISSION;
2077 }
2078 std::string processName = "";
2079 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
2080 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
2081 return ERR_DM_FAILED;
2082 }
2083 if (!PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName)) {
2084 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
2085 return ERR_DM_INPUT_PARA_INVALID;
2086 }
2087 if (pkgName.empty()) {
2088 LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str());
2089 return ERR_DM_INPUT_PARA_INVALID;
2090 }
2091 CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
2092 return pinHolder_->DestroyPinHolder(pkgName, targetId, pinType, payload);
2093 }
2094
DpAclAdd(const std::string & udid)2095 int32_t DeviceManagerService::DpAclAdd(const std::string &udid)
2096 {
2097 if (!PermissionManager::GetInstance().CheckNewPermission()) {
2098 LOGE("The caller does not have permission to call DpAclAdd.");
2099 return ERR_DM_NO_PERMISSION;
2100 }
2101 if (!IsDMServiceImplReady()) {
2102 LOGE("DpAclAdd failed, instance not init or init failed.");
2103 return ERR_DM_NOT_INIT;
2104 }
2105 dmServiceImpl_->DpAclAdd(udid);
2106 return DM_OK;
2107 }
2108
GetDeviceSecurityLevel(const std::string & pkgName,const std::string & networkId,int32_t & securityLevel)2109 int32_t DeviceManagerService::GetDeviceSecurityLevel(const std::string &pkgName, const std::string &networkId,
2110 int32_t &securityLevel)
2111 {
2112 LOGI("Begin pkgName: %{public}s, networkId: %{public}s",
2113 pkgName.c_str(), GetAnonyString(networkId).c_str());
2114 if (!PermissionManager::GetInstance().CheckPermission()) {
2115 LOGE("The caller: %{public}s does not have permission to call GetDeviceSecurityLevel.", pkgName.c_str());
2116 return ERR_DM_NO_PERMISSION;
2117 }
2118 if (pkgName.empty() || networkId.empty()) {
2119 LOGE("Invalid parameter, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(),
2120 GetAnonyString(networkId).c_str());
2121 return ERR_DM_INPUT_PARA_INVALID;
2122 }
2123 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
2124 int32_t ret = softbusListener_->GetDeviceSecurityLevel(networkId.c_str(), securityLevel);
2125 if (ret != DM_OK) {
2126 LOGE("GetDeviceSecurityLevel failed, ret = %{public}d", ret);
2127 return ret;
2128 }
2129 return DM_OK;
2130 }
2131
IsSameAccount(const std::string & networkId)2132 int32_t DeviceManagerService::IsSameAccount(const std::string &networkId)
2133 {
2134 LOGI("NetworkId %{public}s.", GetAnonyString(networkId).c_str());
2135 if (!PermissionManager::GetInstance().CheckPermission()) {
2136 return ERR_DM_NO_PERMISSION;
2137 }
2138 std::string udid = "";
2139 if (SoftbusListener::GetUdidByNetworkId(networkId.c_str(), udid) != DM_OK) {
2140 LOGE("DeviceManagerService::IsSameAccount error: udid: %{public}s", GetAnonyString(udid).c_str());
2141 return ERR_DM_INPUT_PARA_INVALID;
2142 }
2143 if (!IsDMServiceImplReady()) {
2144 LOGE("IsSameAccount failed, instance not init or init failed.");
2145 return ERR_DM_NOT_INIT;
2146 }
2147 return dmServiceImpl_->IsSameAccount(udid);
2148 }
2149
CheckAccessControl(const DmAccessCaller & caller,const DmAccessCallee & callee)2150 bool DeviceManagerService::CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee)
2151 {
2152 std::string srcUdid = "";
2153 std::string sinkUdid = "";
2154 if (!GetAccessUdidByNetworkId(caller.networkId.c_str(), srcUdid, callee.networkId.c_str(), sinkUdid)) {
2155 LOGE("GetAccessUdidByNetworkId failed.");
2156 return false;
2157 }
2158 return dmServiceImpl_->CheckAccessControl(caller, srcUdid, callee, sinkUdid);
2159 }
2160
CheckIsSameAccount(const DmAccessCaller & caller,const DmAccessCallee & callee)2161 bool DeviceManagerService::CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee)
2162 {
2163 std::string srcUdid = "";
2164 std::string sinkUdid = "";
2165 if (!GetAccessUdidByNetworkId(caller.networkId.c_str(), srcUdid, callee.networkId.c_str(), sinkUdid)) {
2166 LOGE("GetAccessUdidByNetworkId failed.");
2167 return false;
2168 }
2169 return dmServiceImpl_->CheckIsSameAccount(caller, srcUdid, callee, sinkUdid);
2170 }
2171
InitAccountInfo()2172 int32_t DeviceManagerService::InitAccountInfo()
2173 {
2174 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
2175 SubscribeAccountCommonEvent();
2176 LOGI("Success.");
2177 #endif
2178 return DM_OK;
2179 }
2180
InitScreenLockEvent()2181 int32_t DeviceManagerService::InitScreenLockEvent()
2182 {
2183 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
2184 SubscribeScreenLockEvent();
2185 LOGI("Success.");
2186 #endif
2187 return DM_OK;
2188 }
2189
2190 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
SubscribeAccountCommonEvent()2191 void DeviceManagerService::SubscribeAccountCommonEvent()
2192 {
2193 LOGI("Start");
2194 if (accountCommonEventManager_ == nullptr) {
2195 accountCommonEventManager_ = std::make_shared<DmAccountCommonEventManager>();
2196 }
2197 AccountEventCallback callback = [=](const auto &eventType, const auto ¤tUserId, const auto &beforeUserId) {
2198 this->AccountCommonEventCallback(eventType, currentUserId, beforeUserId);
2199 };
2200 std::vector<std::string> AccountCommonEventVec;
2201 AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
2202 AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
2203 AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGOUT);
2204 AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGIN);
2205 AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED);
2206 AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_STOPPED);
2207 AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
2208 if (accountCommonEventManager_->SubscribeAccountCommonEvent(AccountCommonEventVec, callback)) {
2209 LOGI("Success");
2210 }
2211 return;
2212 }
2213
SendShareTypeUnBindBroadCast(const char * credId,const int32_t localUserId,const std::vector<std::string> & peerUdids)2214 void DeviceManagerService::SendShareTypeUnBindBroadCast(const char *credId, const int32_t localUserId,
2215 const std::vector<std::string> &peerUdids)
2216 {
2217 LOGI("Start.");
2218 RelationShipChangeMsg msg;
2219 msg.type = RelationShipChangeType::SHARE_UNBIND;
2220 msg.userId = static_cast<uint32_t>(localUserId);
2221 msg.credId = credId;
2222 msg.peerUdids = peerUdids;
2223 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2224 CHECK_NULL_VOID(softbusListener_);
2225 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2226 }
2227
SubscribeScreenLockEvent()2228 void DeviceManagerService::SubscribeScreenLockEvent()
2229 {
2230 LOGI("Start");
2231 if (screenCommonEventManager_ == nullptr) {
2232 screenCommonEventManager_ = std::make_shared<DmScreenCommonEventManager>();
2233 }
2234 ScreenEventCallback callback = [=](const auto &arg1) { this->ScreenCommonEventCallback(arg1); };
2235 std::vector<std::string> screenEventVec;
2236 screenEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED);
2237 screenEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
2238 if (screenCommonEventManager_->SubscribeScreenCommonEvent(screenEventVec, callback)) {
2239 LOGI("Success");
2240 }
2241 return;
2242 }
2243
AccountCommonEventCallback(const std::string commonEventType,int32_t currentUserId,int32_t beforeUserId)2244 DM_EXPORT void DeviceManagerService::AccountCommonEventCallback(
2245 const std::string commonEventType, int32_t currentUserId, int32_t beforeUserId)
2246 {
2247 if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
2248 HandleUserSwitchEventCallback(commonEventType, currentUserId, beforeUserId);
2249 } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) {
2250 DeviceNameManager::GetInstance().InitDeviceNameWhenLogin();
2251 MultipleUserConnector::SetAccountInfo(currentUserId, MultipleUserConnector::GetCurrentDMAccountInfo());
2252 } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) {
2253 HandleAccountLogoutEventCallback(commonEventType, currentUserId, beforeUserId);
2254 } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_REMOVED) {
2255 HandleUserRemoved(beforeUserId);
2256 MultipleUserConnector::DeleteAccountInfoByUserId(beforeUserId);
2257 MultipleUserConnector::SetAccountInfo(MultipleUserConnector::GetCurrentAccountUserID(),
2258 MultipleUserConnector::GetCurrentDMAccountInfo());
2259 } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED) {
2260 DeviceNameManager::GetInstance().InitDeviceNameWhenNickChange();
2261 } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_STOPPED && IsPC()) {
2262 DMCommTool::GetInstance()->StartCommonEvent(commonEventType,
2263 [this, commonEventType] () {
2264 DeviceManagerService::HandleAccountCommonEvent(commonEventType);
2265 });
2266 } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_UNLOCKED && IsPC()) {
2267 DeviceNameManager::GetInstance().AccountSysReady(beforeUserId);
2268 DMCommTool::GetInstance()->StartCommonEvent(commonEventType,
2269 [this, commonEventType] () {
2270 DeviceManagerService::HandleAccountCommonEvent(commonEventType);
2271 });
2272 } else {
2273 LOGE("Invalied account common event.");
2274 }
2275 return;
2276 }
2277
GetLocalUserIdFromDataBase(std::vector<int32_t> & foregroundUsers,std::vector<int32_t> & backgroundUsers)2278 void DeviceManagerService::GetLocalUserIdFromDataBase(std::vector<int32_t> &foregroundUsers,
2279 std::vector<int32_t> &backgroundUsers)
2280 {
2281 std::string userIdStr;
2282 KVAdapterManager::GetInstance().GetLocalUserIdData(LOCAL_ALL_USERID, userIdStr);
2283 if (userIdStr.empty()) {
2284 LOGE("result is empty");
2285 return;
2286 }
2287 JsonObject userIdJson(userIdStr);
2288 if (userIdJson.IsDiscarded()) {
2289 LOGE("userIdJson parse failed");
2290 return;
2291 }
2292 if (IsArray(userIdJson, LOCAL_FOREGROUND_USERID)) {
2293 userIdJson[LOCAL_FOREGROUND_USERID].Get(foregroundUsers);
2294 }
2295 if (IsArray(userIdJson, LOCAL_BACKGROUND_USERID)) {
2296 userIdJson[LOCAL_BACKGROUND_USERID].Get(backgroundUsers);
2297 }
2298 }
2299
PutLocalUserIdToDataBase(const std::vector<int32_t> & foregroundUsers,const std::vector<int32_t> & backgroundUsers)2300 void DeviceManagerService::PutLocalUserIdToDataBase(const std::vector<int32_t> &foregroundUsers,
2301 const std::vector<int32_t> &backgroundUsers)
2302 {
2303 JsonObject jsonObj;
2304 jsonObj[LOCAL_FOREGROUND_USERID] = foregroundUsers;
2305 jsonObj[LOCAL_BACKGROUND_USERID] = backgroundUsers;
2306 std::string localUserIdStr = jsonObj.Dump();
2307 KVAdapterManager::GetInstance().PutLocalUserIdData(LOCAL_ALL_USERID, localUserIdStr);
2308 }
2309
IsUserStatusChanged(std::vector<int32_t> foregroundUserVec,std::vector<int32_t> backgroundUserVec)2310 bool DeviceManagerService::IsUserStatusChanged(std::vector<int32_t> foregroundUserVec,
2311 std::vector<int32_t> backgroundUserVec)
2312 {
2313 LOGI("foregroundUserVec: %{public}s, backgroundUserVec: %{public}s",
2314 GetIntegerList(foregroundUserVec).c_str(), GetIntegerList(backgroundUserVec).c_str());
2315 std::vector<int32_t> dBForegroundUserIds;
2316 std::vector<int32_t> dBBackgroundUserIds;
2317 GetLocalUserIdFromDataBase(dBForegroundUserIds, dBBackgroundUserIds);
2318 LOGI("dBForegroundUserIds: %{public}s, dBBackgroundUserIds: %{public}s",
2319 GetIntegerList(dBForegroundUserIds).c_str(), GetIntegerList(dBBackgroundUserIds).c_str());
2320 std::sort(foregroundUserVec.begin(), foregroundUserVec.end());
2321 std::sort(backgroundUserVec.begin(), backgroundUserVec.end());
2322 std::sort(dBForegroundUserIds.begin(), dBForegroundUserIds.end());
2323 std::sort(dBBackgroundUserIds.begin(), dBBackgroundUserIds.end());
2324 if (foregroundUserVec == dBForegroundUserIds && backgroundUserVec == dBBackgroundUserIds) {
2325 LOGI("User status has not changed.");
2326 return false;
2327 }
2328 dBForegroundUserIds = foregroundUserVec;
2329 dBBackgroundUserIds = backgroundUserVec;
2330 PutLocalUserIdToDataBase(dBForegroundUserIds, dBBackgroundUserIds);
2331 return true;
2332 }
2333
HandleAccountCommonEvent(const std::string commonEventType)2334 void DeviceManagerService::HandleAccountCommonEvent(const std::string commonEventType)
2335 {
2336 LOGI("commonEventType: %{public}s.", commonEventType.c_str());
2337 std::vector<int32_t> foregroundUserVec;
2338 int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec);
2339 std::vector<int32_t> backgroundUserVec;
2340 int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec);
2341 MultipleUserConnector::ClearLockedUser(foregroundUserVec, backgroundUserVec);
2342 if (retFront != DM_OK || retBack != DM_OK) {
2343 LOGE("retFront: %{public}d, retBack: %{public}d, frontuserids: %{public}s, backuserids: %{public}s",
2344 retFront, retBack, GetIntegerList(foregroundUserVec).c_str(), GetIntegerList(backgroundUserVec).c_str());
2345 return;
2346 }
2347 if (!IsUserStatusChanged(foregroundUserVec, backgroundUserVec)) {
2348 LOGI("User status has not changed.");
2349 return;
2350 }
2351 DeleteHoDevice(foregroundUserVec, backgroundUserVec);
2352 char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2353 GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2354 std::string localUdid = std::string(localUdidTemp);
2355 CHECK_NULL_VOID(discoveryMgr_);
2356 if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
2357 LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
2358 return;
2359 }
2360 if (!discoveryMgr_->GetCommonDependencyObj()->CheckAclStatusAndForegroundNotMatch(localUdid, foregroundUserVec,
2361 backgroundUserVec)) {
2362 LOGI("no unreasonable data.");
2363 return;
2364 }
2365 std::map<std::string, int32_t> curUserDeviceMap =
2366 discoveryMgr_->GetCommonDependencyObj()->GetDeviceIdAndBindLevel(foregroundUserVec, localUdid);
2367 std::map<std::string, int32_t> preUserDeviceMap =
2368 discoveryMgr_->GetCommonDependencyObj()->GetDeviceIdAndBindLevel(backgroundUserVec, localUdid);
2369 std::vector<std::string> peerUdids;
2370 for (const auto &item : curUserDeviceMap) {
2371 peerUdids.push_back(item.first);
2372 }
2373 for (const auto &item : preUserDeviceMap) {
2374 if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) {
2375 peerUdids.push_back(item.first);
2376 }
2377 }
2378 if (peerUdids.empty()) {
2379 return;
2380 }
2381 NotifyRemoteAccountCommonEvent(commonEventType, localUdid, peerUdids, foregroundUserVec, backgroundUserVec);
2382 }
2383
2384 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
NotifyRemoteAccountCommonEvent(const std::string commonEventType,const std::string & localUdid,const std::vector<std::string> & peerUdids,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2385 void DeviceManagerService::NotifyRemoteAccountCommonEvent(const std::string commonEventType,
2386 const std::string &localUdid, const std::vector<std::string> &peerUdids,
2387 const std::vector<int32_t> &foregroundUserIds, const std::vector<int32_t> &backgroundUserIds)
2388 {
2389 LOGI("foregroundUserIds: %{public}s, backgroundUserIds: %{public}s",
2390 GetIntegerList<int32_t>(foregroundUserIds).c_str(), GetIntegerList<int32_t>(backgroundUserIds).c_str());
2391 if (peerUdids.empty()) {
2392 return;
2393 }
2394 if (softbusListener_ == nullptr) {
2395 UpdateAcl(localUdid, peerUdids, foregroundUserIds, backgroundUserIds);
2396 LOGE("softbusListener_ is null");
2397 return;
2398 }
2399 std::vector<std::string> bleUdids;
2400 std::map<std::string, std::string> wifiDevices;
2401 for (const auto &udid : peerUdids) {
2402 std::string netWorkId = "";
2403 SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
2404 if (netWorkId.empty()) {
2405 LOGI("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
2406 bleUdids.push_back(udid);
2407 continue;
2408 }
2409 int32_t networkType = 0;
2410 if (softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType) != DM_OK || networkType <= 0) {
2411 LOGI("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
2412 bleUdids.push_back(udid);
2413 continue;
2414 }
2415 uint32_t addrTypeMask = 1 << NetworkType::BIT_NETWORK_TYPE_BLE;
2416 if ((static_cast<uint32_t>(networkType) & addrTypeMask) != 0x0) {
2417 bleUdids.push_back(udid);
2418 } else {
2419 wifiDevices.insert(std::pair<std::string, std::string>(udid, netWorkId));
2420 }
2421 }
2422 if (!bleUdids.empty()) {
2423 UpdateAcl(localUdid, peerUdids, foregroundUserIds, backgroundUserIds);
2424 if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_UNLOCKED ||
2425 commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
2426 SendCommonEventBroadCast(bleUdids, foregroundUserIds, backgroundUserIds, true);
2427 } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_STOPPED) {
2428 SendCommonEventBroadCast(bleUdids, foregroundUserIds, backgroundUserIds, false);
2429 } else {
2430 LOGE("commonEventType not match");
2431 return;
2432 }
2433 }
2434 if (!wifiDevices.empty()) {
2435 NotifyRemoteAccountCommonEventByWifi(localUdid, wifiDevices, foregroundUserIds, backgroundUserIds);
2436 }
2437 }
2438
NotifyRemoteAccountCommonEventByWifi(const std::string & localUdid,const std::map<std::string,std::string> & wifiDevices,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2439 void DeviceManagerService::NotifyRemoteAccountCommonEventByWifi(const std::string &localUdid,
2440 const std::map<std::string, std::string> &wifiDevices, const std::vector<int32_t> &foregroundUserIds,
2441 const std::vector<int32_t> &backgroundUserIds)
2442 {
2443 for (const auto &it : wifiDevices) {
2444 int32_t result = SendAccountCommonEventByWifi(it.second, foregroundUserIds, backgroundUserIds);
2445 if (result != DM_OK) {
2446 LOGE("by wifi failed: %{public}s", GetAnonyString(it.first).c_str());
2447 std::vector<std::string> updateUdids;
2448 updateUdids.push_back(it.first);
2449 UpdateAcl(localUdid, updateUdids, foregroundUserIds, backgroundUserIds);
2450 continue;
2451 }
2452 if (timer_ == nullptr) {
2453 timer_ = std::make_shared<DmTimer>();
2454 }
2455 std::string udid = it.first;
2456 timer_->StartTimer(std::string(ACCOUNT_COMMON_EVENT_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid),
2457 USER_SWITCH_BY_WIFI_TIMEOUT_S,
2458 [this, localUdid, foregroundUserIds, backgroundUserIds, udid] (std::string name) {
2459 DeviceManagerService::HandleCommonEventTimeout(localUdid, foregroundUserIds, backgroundUserIds, udid);
2460 });
2461 }
2462 }
2463
SendAccountCommonEventByWifi(const std::string & networkId,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2464 int32_t DeviceManagerService::SendAccountCommonEventByWifi(const std::string &networkId,
2465 const std::vector<int32_t> &foregroundUserIds, const std::vector<int32_t> &backgroundUserIds)
2466 {
2467 LOGI("start");
2468 std::vector<uint32_t> foregroundUserIdsUInt;
2469 for (auto const &u : foregroundUserIds) {
2470 foregroundUserIdsUInt.push_back(static_cast<uint32_t>(u));
2471 }
2472 std::vector<uint32_t> backgroundUserIdsUInt;
2473 for (auto const &u : backgroundUserIds) {
2474 backgroundUserIdsUInt.push_back(static_cast<uint32_t>(u));
2475 }
2476 return DMCommTool::GetInstance()->SendUserIds(networkId, foregroundUserIdsUInt, backgroundUserIdsUInt);
2477 }
2478
HandleCommonEventTimeout(const std::string & localUdid,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds,const std::string & udid)2479 void DeviceManagerService::HandleCommonEventTimeout(const std::string &localUdid,
2480 const std::vector<int32_t> &foregroundUserIds, const std::vector<int32_t> &backgroundUserIds,
2481 const std::string &udid)
2482 {
2483 LOGI("start udid: %{public}s", GetAnonyString(udid).c_str());
2484 std::vector<std::string> updateUdids;
2485 updateUdids.push_back(udid);
2486 UpdateAcl(localUdid, updateUdids, foregroundUserIds, backgroundUserIds);
2487 }
2488
UpdateAcl(const std::string & localUdid,const std::vector<std::string> & peerUdids,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2489 void DeviceManagerService::UpdateAcl(const std::string &localUdid,
2490 const std::vector<std::string> &peerUdids, const std::vector<int32_t> &foregroundUserIds,
2491 const std::vector<int32_t> &backgroundUserIds)
2492 {
2493 CHECK_NULL_VOID(discoveryMgr_);
2494 if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
2495 LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
2496 return;
2497 }
2498 discoveryMgr_->GetCommonDependencyObj()->HandleAccountCommonEvent(localUdid, peerUdids, foregroundUserIds,
2499 backgroundUserIds);
2500 }
2501
UpdateAclAndDeleteGroup(const std::string & localUdid,const std::vector<std::string> & deviceVec,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2502 void DeviceManagerService::UpdateAclAndDeleteGroup(const std::string &localUdid,
2503 const std::vector<std::string> &deviceVec, const std::vector<int32_t> &foregroundUserIds,
2504 const std::vector<int32_t> &backgroundUserIds)
2505 {
2506 CHECK_NULL_VOID(discoveryMgr_);
2507 if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
2508 LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
2509 return;
2510 }
2511 discoveryMgr_->GetCommonDependencyObj()->HandleUserSwitched(localUdid, deviceVec,
2512 foregroundUserIds, backgroundUserIds);
2513 }
2514 #endif
2515
HandleAccountLogout(int32_t userId,const std::string & accountId,const std::string & accountName)2516 void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string &accountId,
2517 const std::string &accountName)
2518 {
2519 LOGI("UserId: %{public}d, accountId: %{public}s, accountName: %{public}s", userId,
2520 GetAnonyString(accountId).c_str(), GetAnonyString(accountName).c_str());
2521 if (IsDMServiceAdapterResidentLoad()) {
2522 dmServiceImplExtResident_->ClearCacheWhenLogout(userId, accountId);
2523 } else {
2524 LOGW("ClearCacheWhenLogout fail, adapter instance not init or init failed.");
2525 }
2526 if (!IsDMServiceImplReady()) {
2527 LOGE("Init impl failed.");
2528 return;
2529 }
2530 std::multimap<std::string, int32_t> deviceMap;
2531 std::vector<std::string> peerUdids;
2532 char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2533 GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2534 std::string localUdid = std::string(localUdidTemp);
2535 deviceMap = dmServiceImpl_->GetDeviceIdAndUserId(userId, accountId);
2536 for (const auto &item : deviceMap) {
2537 peerUdids.emplace_back(item.first);
2538 }
2539 if (!peerUdids.empty()) {
2540 //logout notify cast+
2541 if (IsDMServiceAdapterResidentLoad()) {
2542 dmServiceImplExtResident_->AccountIdLogout(userId, accountId, peerUdids);
2543 }
2544 char accountIdHash[DM_MAX_DEVICE_ID_LEN] = {0};
2545 if (Crypto::GetAccountIdHash(accountId, reinterpret_cast<uint8_t *>(accountIdHash)) != DM_OK) {
2546 LOGE("GetAccountHash failed.");
2547 return;
2548 }
2549 NotifyRemoteLocalLogout(peerUdids, std::string(accountIdHash), accountName, userId);
2550 }
2551 for (const auto &item : deviceMap) {
2552 DMAclQuadInfo info = {localUdid, userId, item.first, item.second};
2553 dmServiceImpl_->HandleIdentAccountLogout(info, accountId);
2554 }
2555 }
2556
HandleUserRemoved(int32_t removedUserId)2557 void DeviceManagerService::HandleUserRemoved(int32_t removedUserId)
2558 {
2559 LOGI("PreUserId %{public}d.", removedUserId);
2560 if (!IsDMServiceImplReady()) {
2561 LOGE("Init impl failed.");
2562 return;
2563 }
2564 std::multimap<std::string, int32_t> deviceMap = dmServiceImpl_->GetDeviceIdAndUserId(removedUserId);
2565 std::vector<std::string> peerUdids;
2566 for (const auto &item : deviceMap) {
2567 if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) {
2568 peerUdids.emplace_back(item.first);
2569 }
2570 }
2571 if (!peerUdids.empty()) {
2572 // Send UserId Removed broadcast
2573 SendUserRemovedBroadCast(peerUdids, removedUserId);
2574 dmServiceImpl_->HandleUserRemoved(peerUdids, removedUserId);
2575 }
2576 }
2577
SendUserRemovedBroadCast(const std::vector<std::string> & peerUdids,int32_t userId)2578 void DeviceManagerService::SendUserRemovedBroadCast(const std::vector<std::string> &peerUdids, int32_t userId)
2579 {
2580 LOGI("peerUdids: %{public}s, userId %{public}d.", GetAnonyStringList(peerUdids).c_str(), userId);
2581 RelationShipChangeMsg msg;
2582 msg.type = RelationShipChangeType::DEL_USER;
2583 msg.userId = static_cast<uint32_t>(userId);
2584 msg.peerUdids = peerUdids;
2585 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2586 CHECK_NULL_VOID(softbusListener_);
2587 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2588 }
2589
SendAccountLogoutBroadCast(const std::vector<std::string> & peerUdids,const std::string & accountId,const std::string & accountName,int32_t userId)2590 void DeviceManagerService::SendAccountLogoutBroadCast(const std::vector<std::string> &peerUdids,
2591 const std::string &accountId, const std::string &accountName, int32_t userId)
2592 {
2593 LOGI("accountId %{public}s, accountName %{public}s, userId %{public}d.", GetAnonyString(accountId).c_str(),
2594 GetAnonyString(accountName).c_str(), userId);
2595 RelationShipChangeMsg msg;
2596 msg.type = RelationShipChangeType::ACCOUNT_LOGOUT;
2597 msg.userId = static_cast<uint32_t>(userId);
2598 msg.peerUdids = peerUdids;
2599 msg.accountId = accountId;
2600 msg.accountName = accountName;
2601 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2602 CHECK_NULL_VOID(softbusListener_);
2603 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2604 }
2605
SendUserIdsBroadCast(const std::vector<std::string> & peerUdids,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds,bool isNeedResponse)2606 void DeviceManagerService::SendUserIdsBroadCast(const std::vector<std::string> &peerUdids,
2607 const std::vector<int32_t> &foregroundUserIds, const std::vector<int32_t> &backgroundUserIds, bool isNeedResponse)
2608 {
2609 LOGI("peerUdids: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, isNeedRsp: %{public}s",
2610 GetAnonyStringList(peerUdids).c_str(), GetIntegerList<int32_t>(foregroundUserIds).c_str(),
2611 GetIntegerList<int32_t>(backgroundUserIds).c_str(), isNeedResponse ? "true" : "false");
2612 RelationShipChangeMsg msg;
2613 msg.type = RelationShipChangeType::SYNC_USERID;
2614 msg.peerUdids = peerUdids;
2615 msg.syncUserIdFlag = isNeedResponse;
2616 for (const auto &userId : foregroundUserIds) {
2617 msg.userIdInfos.push_back({ true, static_cast<uint16_t>(userId) });
2618 }
2619 for (auto const &userId : backgroundUserIds) {
2620 msg.userIdInfos.push_back({ false, static_cast<uint16_t>(userId) });
2621 }
2622 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2623 CHECK_NULL_VOID(softbusListener_);
2624 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2625 }
2626
HandleUserIdsBroadCast(const std::vector<UserIdInfo> & remoteUserIdInfos,const std::string & remoteUdid,bool isNeedResponse)2627 void DeviceManagerService::HandleUserIdsBroadCast(const std::vector<UserIdInfo> &remoteUserIdInfos,
2628 const std::string &remoteUdid, bool isNeedResponse)
2629 {
2630 LOGI("rmtUdid: %{public}s, rmtUserIds: %{public}s, isNeedResponse: %{public}s,",
2631 GetAnonyString(remoteUdid).c_str(), GetUserIdInfoList(remoteUserIdInfos).c_str(),
2632 isNeedResponse ? "true" : "false");
2633 if (isNeedResponse) {
2634 std::vector<int32_t> foregroundUserVec;
2635 std::vector<int32_t> backgroundUserVec;
2636 int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec);
2637 int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec);
2638 if (IsPC()) {
2639 MultipleUserConnector::ClearLockedUser(foregroundUserVec, backgroundUserVec);
2640 }
2641 if (retFront != DM_OK || retBack!= DM_OK) {
2642 LOGE("Get userid failed, retFront: %{public}d, retBack: %{public}d, frontUserNum:%{public}d,"
2643 "backUserNum: %{public}d", retFront, retBack, static_cast<int32_t>(foregroundUserVec.size()),
2644 static_cast<int32_t>(backgroundUserVec.size()));
2645 } else {
2646 LOGE("Send back local frontuserids: %{public}s, backuserids: %{public}s",
2647 GetIntegerList(foregroundUserVec).c_str(), GetIntegerList(backgroundUserVec).c_str());
2648 std::vector<std::string> remoteUdids = { remoteUdid };
2649 SendUserIdsBroadCast(remoteUdids, foregroundUserVec, backgroundUserVec, false);
2650 }
2651 }
2652
2653 std::vector<UserIdInfo> foregroundUserIdInfos;
2654 std::vector<UserIdInfo> backgroundUserIdInfos;
2655 GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos);
2656 // Notify received remote foreground userids to dsoftbus
2657 std::vector<uint32_t> foregroundUserIds;
2658 for (const auto &u : foregroundUserIdInfos) {
2659 foregroundUserIds.push_back(static_cast<uint32_t>(u.userId));
2660 }
2661 std::vector<uint32_t> backgroundUserIds;
2662 for (const auto &u : backgroundUserIdInfos) {
2663 backgroundUserIds.push_back(static_cast<uint32_t>(u.userId));
2664 }
2665 if (softbusListener_ != nullptr) {
2666 softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, foregroundUserIds);
2667 }
2668
2669 if (IsDMServiceImplReady()) {
2670 dmServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid, IsPC());
2671 }
2672 }
2673
ProcessSyncUserIds(const std::vector<uint32_t> & foregroundUserIds,const std::vector<uint32_t> & backgroundUserIds,const std::string & remoteUdid)2674 void DeviceManagerService::ProcessSyncUserIds(const std::vector<uint32_t> &foregroundUserIds,
2675 const std::vector<uint32_t> &backgroundUserIds, const std::string &remoteUdid)
2676 {
2677 LOGI("process sync foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, remote udid: %{public}s",
2678 GetIntegerList<uint32_t>(foregroundUserIds).c_str(), GetIntegerList<uint32_t>(backgroundUserIds).c_str(),
2679 GetAnonyString(remoteUdid).c_str());
2680
2681 if (softbusListener_ != nullptr) {
2682 softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, foregroundUserIds);
2683 }
2684 if (timer_ != nullptr) {
2685 timer_->DeleteTimer(std::string(USER_SWITCH_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(remoteUdid));
2686 }
2687 if (IsDMServiceImplReady()) {
2688 dmServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid, IsPC());
2689 }
2690 }
2691
ProcessUninstApp(int32_t userId,int32_t tokenId)2692 void DeviceManagerService::ProcessUninstApp(int32_t userId, int32_t tokenId)
2693 {
2694 LOGI("DeviceManagerService::ProcessUninstApp userId: %{public}s, tokenId: %{public}s",
2695 GetAnonyInt32(userId).c_str(), GetAnonyInt32(tokenId).c_str());
2696 if (IsDMServiceImplReady()) {
2697 dmServiceImpl_->ProcessAppUninstall(userId, tokenId);
2698 }
2699 }
2700
ProcessUnBindApp(int32_t userId,int32_t tokenId,const std::string & extra,const std::string & udid)2701 void DeviceManagerService::ProcessUnBindApp(int32_t userId, int32_t tokenId, const std::string &extra,
2702 const std::string &udid)
2703 {
2704 LOGI("DeviceManagerService::ProcessUnBindApp userId: %{public}s, tokenId: %{public}s, udid: %{public}s",
2705 GetAnonyInt32(userId).c_str(), GetAnonyInt32(tokenId).c_str(), GetAnonyString(udid).c_str());
2706 if (IsDMServiceImplReady()) {
2707 dmServiceImpl_->ProcessUnBindApp(userId, tokenId, extra, udid);
2708 }
2709 }
2710
SendCommonEventBroadCast(const std::vector<std::string> & peerUdids,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds,bool isNeedResponse)2711 void DeviceManagerService::SendCommonEventBroadCast(const std::vector<std::string> &peerUdids,
2712 const std::vector<int32_t> &foregroundUserIds, const std::vector<int32_t> &backgroundUserIds, bool isNeedResponse)
2713 {
2714 LOGI("peerUdids: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, isNeedRsp: %{public}s",
2715 GetAnonyStringList(peerUdids).c_str(), GetIntegerList<int32_t>(foregroundUserIds).c_str(),
2716 GetIntegerList<int32_t>(backgroundUserIds).c_str(), isNeedResponse ? "true" : "false");
2717 RelationShipChangeMsg msg;
2718 msg.type = RelationShipChangeType::SYNC_USERID;
2719 msg.peerUdids = peerUdids;
2720 msg.syncUserIdFlag = isNeedResponse;
2721 msg.isNewEvent = true;
2722 for (const auto &userId : foregroundUserIds) {
2723 msg.userIdInfos.push_back({ true, static_cast<uint16_t>(userId) });
2724 }
2725 for (auto const &userId : backgroundUserIds) {
2726 msg.userIdInfos.push_back({ false, static_cast<uint16_t>(userId) });
2727 }
2728 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2729 CHECK_NULL_VOID(softbusListener_);
2730 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2731 }
2732
HandleCommonEventBroadCast(const std::vector<UserIdInfo> & remoteUserIdInfos,const std::string & remoteUdid,bool isNeedResponse)2733 void DeviceManagerService::HandleCommonEventBroadCast(const std::vector<UserIdInfo> &remoteUserIdInfos,
2734 const std::string &remoteUdid, bool isNeedResponse)
2735 {
2736 LOGI("rmtUdid: %{public}s, rmtUserIds: %{public}s, isNeedResponse: %{public}s,",
2737 GetAnonyString(remoteUdid).c_str(), GetUserIdInfoList(remoteUserIdInfos).c_str(),
2738 isNeedResponse ? "true" : "false");
2739 if (isNeedResponse) {
2740 std::vector<int32_t> foregroundUserVec;
2741 int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec);
2742 std::vector<int32_t> backgroundUserVec;
2743 int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec);
2744 MultipleUserConnector::ClearLockedUser(foregroundUserVec, backgroundUserVec);
2745 if (retFront != DM_OK || retBack!= DM_OK) {
2746 LOGE("retFront: %{public}d, retBack: %{public}d, frontuserids: %{public}s, backuserids: %{public}s",
2747 retFront, retBack, GetIntegerList(foregroundUserVec).c_str(),
2748 GetIntegerList(backgroundUserVec).c_str());
2749 } else {
2750 LOGE("Send back local frontuserids: %{public}s, backuserids: %{public}s",
2751 GetIntegerList(foregroundUserVec).c_str(), GetIntegerList(backgroundUserVec).c_str());
2752 std::vector<std::string> remoteUdids = { remoteUdid };
2753 SendCommonEventBroadCast(remoteUdids, foregroundUserVec, backgroundUserVec, false);
2754 }
2755 }
2756
2757 std::vector<UserIdInfo> foregroundUserIdInfos;
2758 std::vector<UserIdInfo> backgroundUserIdInfos;
2759 GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos);
2760 // Notify received remote foreground userids to dsoftbus
2761 std::vector<uint32_t> foregroundUserIds;
2762 for (const auto &u : foregroundUserIdInfos) {
2763 foregroundUserIds.push_back(static_cast<uint32_t>(u.userId));
2764 }
2765 std::vector<uint32_t> backgroundUserIds;
2766 for (const auto &u : backgroundUserIdInfos) {
2767 backgroundUserIds.push_back(static_cast<uint32_t>(u.userId));
2768 }
2769 if (IsDMServiceImplReady()) {
2770 dmServiceImpl_->HandleCommonEventBroadCast(foregroundUserIds, backgroundUserIds, remoteUdid);
2771 }
2772 }
2773
ProcessCommonUserStatusEvent(const std::vector<uint32_t> & foregroundUserIds,const std::vector<uint32_t> & backgroundUserIds,const std::string & remoteUdid)2774 void DeviceManagerService::ProcessCommonUserStatusEvent(const std::vector<uint32_t> &foregroundUserIds,
2775 const std::vector<uint32_t> &backgroundUserIds, const std::string &remoteUdid)
2776 {
2777 LOGI("foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, remoteUdid: %{public}s",
2778 GetIntegerList<uint32_t>(foregroundUserIds).c_str(), GetIntegerList<uint32_t>(backgroundUserIds).c_str(),
2779 GetAnonyString(remoteUdid).c_str());
2780
2781 if (timer_ != nullptr) {
2782 timer_->DeleteTimer(std::string(ACCOUNT_COMMON_EVENT_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(remoteUdid));
2783 }
2784 if (IsDMServiceImplReady()) {
2785 dmServiceImpl_->HandleCommonEventBroadCast(foregroundUserIds, backgroundUserIds, remoteUdid);
2786 }
2787 }
2788
ScreenCommonEventCallback(std::string commonEventType)2789 void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType)
2790 {
2791 if (IsDMServiceAdapterResidentLoad()) {
2792 bool isLock = commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED;
2793 dmServiceImplExtResident_->HandleScreenLockEvent(isLock);
2794 } else {
2795 LOGE("ScreenCommonEventCallback failed, dmServiceImplExtResident not init or init failed.");
2796 }
2797 if (!IsDMImplSoLoaded()) {
2798 LOGE("ScreenCommonEventCallback failed, instance not init or init failed.");
2799 return;
2800 }
2801 dmServiceImpl_->ScreenCommonEventCallback(commonEventType);
2802 }
2803 #endif
2804
HandleDeviceNotTrust(const std::string & msg)2805 void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg)
2806 {
2807 LOGI("Start.");
2808 if (msg.empty()) {
2809 LOGE("DeviceManagerService::HandleDeviceNotTrust msg is empty.");
2810 return;
2811 }
2812 JsonObject msgJsonObj(msg);
2813 if (msgJsonObj.IsDiscarded()) {
2814 LOGE("HandleDeviceNotTrust msg prase error.");
2815 return;
2816 }
2817 if (!IsString(msgJsonObj, NETWORKID)) {
2818 LOGE("HandleDeviceNotTrust msg not contain networkId.");
2819 return;
2820 }
2821 std::string networkId = msgJsonObj[NETWORKID].Get<std::string>();
2822 std::string udid = "";
2823 SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid);
2824 LOGI("NetworkId: %{public}s, udid: %{public}s.",
2825 GetAnonyString(networkId).c_str(), GetAnonyString(udid).c_str());
2826 if (IsDMServiceImplReady()) {
2827 dmServiceImpl_->HandleDeviceNotTrust(udid);
2828 }
2829 if (IsDMServiceAdapterResidentLoad()) {
2830 dmServiceImplExtResident_->HandleDeviceNotTrust(udid);
2831 }
2832 return;
2833 }
2834
SetDnPolicy(const std::string & pkgName,std::map<std::string,std::string> & policy)2835 int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::map<std::string, std::string> &policy)
2836 {
2837 if (!PermissionManager::GetInstance().CheckPermission()) {
2838 LOGE("The caller does not have permission to call");
2839 return ERR_DM_NO_PERMISSION;
2840 }
2841 std::string processName = "";
2842 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
2843 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
2844 return ERR_DM_FAILED;
2845 }
2846 if (!PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName)) {
2847 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
2848 return ERR_DM_INPUT_PARA_INVALID;
2849 }
2850 if (pkgName.empty()) {
2851 LOGE("Invalid parameter, pkgName is empty.");
2852 return ERR_DM_INPUT_PARA_INVALID;
2853 }
2854 auto policyStrategyIter = policy.find(PARAM_KEY_POLICY_STRATEGY_FOR_BLE);
2855 if (policyStrategyIter == policy.end()) {
2856 LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is empty.");
2857 return ERR_DM_INPUT_PARA_INVALID;
2858 }
2859 auto timeOutIter = policy.find(PARAM_KEY_POLICY_TIME_OUT);
2860 if (timeOutIter == policy.end()) {
2861 LOGE("Invalid parameter, DM_POLICY_TIMEOUT is empty.");
2862 return ERR_DM_INPUT_PARA_INVALID;
2863 }
2864 if (!IsNumberString(policyStrategyIter->second)) {
2865 LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is not number.");
2866 return ERR_DM_INPUT_PARA_INVALID;
2867 }
2868 if (!IsNumberString(timeOutIter->second)) {
2869 LOGE("Invalid parameter, DM_POLICY_TIMEOUT is not number.");
2870 return ERR_DM_INPUT_PARA_INVALID;
2871 }
2872 int32_t policyStrategy = std::atoi(policyStrategyIter->second.c_str());
2873 int32_t timeOut = std::atoi(timeOutIter->second.c_str());
2874 LOGD("strategy: %{public}d, timeOut: %{public}d", policyStrategy, timeOut);
2875 if (!IsDMServiceAdapterResidentLoad()) {
2876 LOGE("SetDnPolicy failed, instance not init or init failed.");
2877 return ERR_DM_UNSUPPORTED_METHOD;
2878 }
2879 return dmServiceImplExtResident_->SetDnPolicy(policyStrategy, timeOut);
2880 }
2881
2882 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
ConvertUdidHashToAnoyDeviceId(DmDeviceInfo & deviceInfo)2883 DM_EXPORT void DeviceManagerService::ConvertUdidHashToAnoyDeviceId(
2884 DmDeviceInfo &deviceInfo)
2885 {
2886 std::string udidHashTemp = "";
2887 if (ConvertUdidHashToAnoyDeviceId(deviceInfo.deviceId, udidHashTemp) == DM_OK) {
2888 if (memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) {
2889 LOGE("ConvertUdidHashToAnoyDeviceId memset_s failed.");
2890 return;
2891 }
2892 if (memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) {
2893 LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str());
2894 return;
2895 }
2896 }
2897 }
2898
ConvertUdidHashToAnoyDeviceId(const std::string & udidHash,std::string & result)2899 DM_EXPORT int32_t DeviceManagerService::ConvertUdidHashToAnoyDeviceId(
2900 const std::string &udidHash, std::string &result)
2901 {
2902 std::string appId = AppManager::GetInstance().GetAppId();
2903 if (appId.empty()) {
2904 LOGD("GetAppId failed");
2905 return ERR_DM_FAILED;
2906 }
2907 DmKVValue kvValue;
2908 int32_t ret = Crypto::ConvertUdidHashToAnoyAndSave(appId, udidHash, kvValue);
2909 if (ret != DM_OK) {
2910 return ERR_DM_FAILED;
2911 }
2912 result = kvValue.anoyDeviceId;
2913 return DM_OK;
2914 }
2915
GetUdidHashByAnoyDeviceId(const std::string & anoyDeviceId,std::string & udidHash)2916 DM_EXPORT int32_t DeviceManagerService::GetUdidHashByAnoyDeviceId(
2917 const std::string &anoyDeviceId, std::string &udidHash)
2918 {
2919 LOGI("anoyDeviceId %{public}s.", GetAnonyString(anoyDeviceId).c_str());
2920 DmKVValue kvValue;
2921 if (KVAdapterManager::GetInstance().Get(anoyDeviceId, kvValue) != DM_OK) {
2922 LOGD("Get kv value from DB failed");
2923 return ERR_DM_FAILED;
2924 }
2925 udidHash = kvValue.udidHash;
2926 LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str());
2927 return DM_OK;
2928 }
2929
SendUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId,int32_t bindLevel)2930 void DeviceManagerService::SendUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
2931 uint64_t tokenId, int32_t bindLevel)
2932 {
2933 LOGI("TokenId %{public}s, bindLevel %{public}d, userId %{public}d.", GetAnonyInt32(tokenId).c_str(),
2934 bindLevel, userId);
2935 if (static_cast<uint32_t>(bindLevel) == USER) {
2936 SendDeviceUnBindBroadCast(peerUdids, userId);
2937 return;
2938 }
2939 if (static_cast<uint32_t>(bindLevel) == APP) {
2940 SendAppUnBindBroadCast(peerUdids, userId, tokenId);
2941 return;
2942 }
2943 if (static_cast<uint32_t>(bindLevel) == SERVICE) {
2944 SendServiceUnBindBroadCast(peerUdids, userId, tokenId);
2945 return;
2946 }
2947 }
2948
SendUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId,int32_t bindLevel,uint64_t peerTokenId)2949 void DeviceManagerService::SendUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
2950 uint64_t tokenId, int32_t bindLevel, uint64_t peerTokenId)
2951 {
2952 if (static_cast<uint32_t>(bindLevel) == USER) {
2953 SendDeviceUnBindBroadCast(peerUdids, userId);
2954 return;
2955 }
2956 if (static_cast<uint32_t>(bindLevel) == APP) {
2957 SendAppUnBindBroadCast(peerUdids, userId, tokenId, peerTokenId);
2958 return;
2959 }
2960 if (static_cast<uint32_t>(bindLevel) == SERVICE) {
2961 SendServiceUnBindBroadCast(peerUdids, userId, tokenId);
2962 return;
2963 }
2964 }
2965
SendDeviceUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId)2966 void DeviceManagerService::SendDeviceUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId)
2967 {
2968 RelationShipChangeMsg msg;
2969 msg.type = RelationShipChangeType::DEVICE_UNBIND;
2970 msg.userId = static_cast<uint32_t>(userId);
2971 msg.peerUdids = peerUdids;
2972 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2973 CHECK_NULL_VOID(softbusListener_);
2974 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2975 }
2976
CalculateBroadCastDelayTime()2977 int32_t DeviceManagerService::CalculateBroadCastDelayTime()
2978 {
2979 int64_t timeDiff = 0;
2980 int32_t delayTime = 0;
2981 int64_t currentTime =
2982 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
2983 {
2984 std::lock_guard<std::mutex> lock(broadCastLock_);
2985 if (SendLastBroadCastTime_ == 0) {
2986 SendLastBroadCastTime_ = currentTime;
2987 }
2988 timeDiff = currentTime - SendLastBroadCastTime_;
2989 delayTime = SEND_DELAY_MAX_TIME - timeDiff + lastDelayTime_;
2990 if (delayTime < SEND_DELAY_MIN_TIME || delayTime == SEND_DELAY_MAX_TIME) {
2991 delayTime = SEND_DELAY_MIN_TIME;
2992 }
2993 SendLastBroadCastTime_ = currentTime;
2994 lastDelayTime_ = delayTime;
2995 }
2996 return delayTime;
2997 }
2998
SendAppUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId)2999 void DeviceManagerService::SendAppUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
3000 uint64_t tokenId)
3001 {
3002 int32_t delayTime = CalculateBroadCastDelayTime();
3003 std::function<void()> task = [=]() {
3004 LOGI("SendAppUnBindBroadCast Start.");
3005 RelationShipChangeMsg msg;
3006 msg.type = RelationShipChangeType::APP_UNBIND;
3007 msg.userId = static_cast<uint32_t>(userId);
3008 msg.peerUdids = peerUdids;
3009 msg.tokenId = tokenId;
3010 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
3011 CHECK_NULL_VOID(softbusListener_);
3012 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
3013 };
3014 ffrt::submit(task, ffrt::task_attr().delay(delayTime * DELAY_TIME_SEC_CONVERSION));
3015 }
3016
SendAppUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId,uint64_t peerTokenId)3017 void DeviceManagerService::SendAppUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
3018 uint64_t tokenId, uint64_t peerTokenId)
3019 {
3020 int32_t delayTime = CalculateBroadCastDelayTime();
3021 std::function<void()> task = [=]() {
3022 LOGI("SendAppUnBindBroadCast Start.");
3023 RelationShipChangeMsg msg;
3024 msg.type = RelationShipChangeType::APP_UNBIND;
3025 msg.userId = static_cast<uint32_t>(userId);
3026 msg.peerUdids = peerUdids;
3027 msg.tokenId = tokenId;
3028 msg.peerTokenId = peerTokenId;
3029 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
3030 CHECK_NULL_VOID(softbusListener_);
3031 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
3032 };
3033 ffrt::submit(task, ffrt::task_attr().delay(delayTime * DELAY_TIME_SEC_CONVERSION));
3034 }
3035
SendAppUnInstallBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId)3036 void DeviceManagerService::SendAppUnInstallBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
3037 uint64_t tokenId)
3038 {
3039 int32_t delayTime = CalculateBroadCastDelayTime();
3040 std::function<void()> task = [=]() {
3041 LOGI("SendAppUnInstallBroadCast Start.");
3042 RelationShipChangeMsg msg;
3043 msg.type = RelationShipChangeType::APP_UNINSTALL;
3044 msg.userId = static_cast<uint32_t>(userId);
3045 msg.peerUdids = peerUdids;
3046 msg.tokenId = tokenId;
3047 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
3048 CHECK_NULL_VOID(softbusListener_);
3049 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
3050 };
3051 ffrt::submit(task, ffrt::task_attr().delay(delayTime * DELAY_TIME_SEC_CONVERSION));
3052 }
3053
SendServiceUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId)3054 void DeviceManagerService::SendServiceUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
3055 uint64_t tokenId)
3056 {
3057 RelationShipChangeMsg msg;
3058 msg.type = RelationShipChangeType::SERVICE_UNBIND;
3059 msg.userId = static_cast<uint32_t>(userId);
3060 msg.peerUdids = peerUdids;
3061 msg.tokenId = tokenId;
3062 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
3063 CHECK_NULL_VOID(softbusListener_);
3064 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
3065 }
3066
HandleCredentialDeleted(const char * credId,const char * credInfo)3067 void DeviceManagerService::HandleCredentialDeleted(const char *credId, const char *credInfo)
3068 {
3069 LOGI("start.");
3070 if (credId == nullptr || credInfo == nullptr) {
3071 LOGE("HandleCredentialDeleted credId or credInfo is nullptr.");
3072 return;
3073 }
3074 char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
3075 GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
3076 std::string localUdid = std::string(localUdidTemp);
3077 if (!IsDMServiceImplReady()) {
3078 LOGE("HandleCredentialDeleted failed, instance not init or init failed.");
3079 return;
3080 }
3081 std::string remoteUdid = "";
3082 bool isSendBroadCast = false;
3083 dmServiceImpl_->HandleCredentialDeleted(credId, credInfo, localUdid, remoteUdid, isSendBroadCast);
3084 if (remoteUdid.empty()) {
3085 LOGE("HandleCredentialDeleted failed, remoteUdid is empty.");
3086 return;
3087 }
3088 if (!isSendBroadCast) {
3089 LOGI("HandleCredentialDeleted not need to send broadcast.");
3090 return;
3091 }
3092 std::vector<std::string> peerUdids;
3093 peerUdids.emplace_back(remoteUdid);
3094 SendShareTypeUnBindBroadCast(credId, MultipleUserConnector::GetCurrentAccountUserID(), peerUdids);
3095 return;
3096 }
3097
HandleDeviceTrustedChange(const std::string & msg)3098 void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg)
3099 {
3100 if (!IsMsgEmptyAndDMServiceImplReady(msg)) {
3101 return;
3102 }
3103 RelationShipChangeMsg relationShipMsg = ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg);
3104 LOGI("Receive trust change msg: %{public}s", relationShipMsg.ToString().c_str());
3105 if (!ReleationShipSyncMgr::GetInstance().IsNewBroadCastId(relationShipMsg)) {
3106 LOGI("is not new broadcast");
3107 return;
3108 }
3109 bool ret = ParseRelationShipChangeType(relationShipMsg);
3110 if (!ret) {
3111 LOGI("ParseRelationShipChangeType failed");
3112 return;
3113 }
3114 return;
3115 }
3116
ParseRelationShipChangeType(const RelationShipChangeMsg & relationShipMsg)3117 bool DeviceManagerService::ParseRelationShipChangeType(const RelationShipChangeMsg &relationShipMsg)
3118 {
3119 switch (relationShipMsg.type) {
3120 case RelationShipChangeType::ACCOUNT_LOGOUT:
3121 dmServiceImpl_->HandleAccountLogoutEvent(relationShipMsg.userId, relationShipMsg.accountId,
3122 relationShipMsg.peerUdid);
3123 break;
3124 case RelationShipChangeType::DEVICE_UNBIND:
3125 dmServiceImpl_->HandleDevUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid);
3126 break;
3127 case RelationShipChangeType::APP_UNBIND:
3128 if (relationShipMsg.peerTokenId != 0) {
3129 dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid,
3130 static_cast<int32_t>(relationShipMsg.peerTokenId),
3131 static_cast<int32_t>(relationShipMsg.tokenId));
3132 } else {
3133 dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid,
3134 static_cast<int32_t>(relationShipMsg.tokenId));
3135 }
3136 break;
3137 case RelationShipChangeType::SERVICE_UNBIND:
3138 dmServiceImpl_->HandleServiceUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid,
3139 static_cast<int32_t>(relationShipMsg.tokenId));
3140 break;
3141 case RelationShipChangeType::SYNC_USERID:
3142 if (relationShipMsg.isNewEvent) {
3143 HandleCommonEventBroadCast(relationShipMsg.userIdInfos,
3144 relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag);
3145 } else {
3146 HandleUserIdsBroadCast(relationShipMsg.userIdInfos,
3147 relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag);
3148 }
3149 break;
3150 case RelationShipChangeType::DEL_USER:
3151 dmServiceImpl_->HandleRemoteUserRemoved(relationShipMsg.userId, relationShipMsg.peerUdid);
3152 break;
3153 case RelationShipChangeType::STOP_USER:
3154 HandleUserStopBroadCast(relationShipMsg.userId, relationShipMsg.peerUdid);
3155 break;
3156 case RelationShipChangeType::SHARE_UNBIND:
3157 HandleShareUnbindBroadCast(relationShipMsg.userId, relationShipMsg.credId);
3158 break;
3159 case RelationShipChangeType::APP_UNINSTALL:
3160 ProcessUninstApp(relationShipMsg.userId, static_cast<int32_t>(relationShipMsg.tokenId));
3161 break;
3162 default:
3163 LOGI("Dm have not this event type.");
3164 return false;
3165 }
3166 return true;
3167 }
3168
IsMsgEmptyAndDMServiceImplReady(const std::string & msg)3169 bool DeviceManagerService::IsMsgEmptyAndDMServiceImplReady(const std::string &msg)
3170 {
3171 if (msg.empty()) {
3172 LOGE("Msg is empty.");
3173 return false;
3174 }
3175 if (!IsDMServiceImplReady()) {
3176 LOGE("Imp instance not init or init failed.");
3177 return false;
3178 }
3179 return true;
3180 }
3181
HandleShareUnbindBroadCast(const int32_t userId,const std::string & credId)3182 void DeviceManagerService::HandleShareUnbindBroadCast(const int32_t userId, const std::string &credId)
3183 {
3184 LOGI("start.");
3185 if (credId == "") {
3186 LOGE("HandleShareUnbindBroadCast credId is null.");
3187 return;
3188 }
3189 char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
3190 GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
3191 std::string localUdid = std::string(localUdidTemp);
3192 if (IsDMServiceImplReady()) {
3193 dmServiceImpl_->HandleShareUnbindBroadCast(credId, userId, localUdid);
3194 }
3195 return;
3196 }
3197
ParseCheckSumMsg(const std::string & msg,std::string & networkId,uint32_t & discoveryType,bool & isChange)3198 int32_t DeviceManagerService::ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType,
3199 bool &isChange)
3200 {
3201 JsonObject msgJsonObj(msg);
3202 if (msgJsonObj.IsDiscarded()) {
3203 LOGE("msg prase error.");
3204 return ERR_DM_FAILED;
3205 }
3206 if (!IsString(msgJsonObj, USERID_CHECKSUM_NETWORKID_KEY)) {
3207 LOGE("msg not contain networkId.");
3208 return ERR_DM_FAILED;
3209 }
3210 if (!IsUint32(msgJsonObj, USERID_CHECKSUM_DISCOVER_TYPE_KEY)) {
3211 LOGE("msg not contain discoveryType.");
3212 return ERR_DM_FAILED;
3213 }
3214 if (!IsBool(msgJsonObj, USERID_CHECKSUM_ISCHANGE_KEY)) {
3215 LOGE("msg not contain ischange.");
3216 return ERR_DM_FAILED;
3217 }
3218 networkId = msgJsonObj[USERID_CHECKSUM_NETWORKID_KEY].Get<std::string>();
3219 discoveryType = msgJsonObj[USERID_CHECKSUM_DISCOVER_TYPE_KEY].Get<uint32_t>();
3220 isChange = msgJsonObj[USERID_CHECKSUM_ISCHANGE_KEY].Get<bool>();
3221 return DM_OK;
3222 }
3223
ProcessCheckSumByWifi(std::string networkId,std::vector<int32_t> foregroundUserIds,std::vector<int32_t> backgroundUserIds)3224 void DeviceManagerService::ProcessCheckSumByWifi(std::string networkId, std::vector<int32_t> foregroundUserIds,
3225 std::vector<int32_t> backgroundUserIds)
3226 {
3227 if (localNetWorkId_ == "") {
3228 DmDeviceInfo deviceInfo;
3229 SoftbusCache::GetInstance().GetLocalDeviceInfo(deviceInfo);
3230 localNetWorkId_ = std::string(deviceInfo.networkId);
3231 }
3232 if (localNetWorkId_ >= networkId) {
3233 LOGI("Local networkid big than remote, no need begin req");
3234 return;
3235 }
3236 // use connection to exchange foreground/background userid
3237 std::vector<uint32_t> foregroundUserIdsUInt;
3238 for (auto const &u : foregroundUserIds) {
3239 foregroundUserIdsUInt.push_back(static_cast<uint32_t>(u));
3240 }
3241 std::vector<uint32_t> backgroundUserIdsUInt;
3242 for (auto const &u : backgroundUserIds) {
3243 backgroundUserIdsUInt.push_back(static_cast<uint32_t>(u));
3244 }
3245 DMCommTool::GetInstance()->SendUserIds(networkId, foregroundUserIdsUInt, backgroundUserIdsUInt);
3246 }
3247
ProcessCheckSumByBT(std::string networkId,std::vector<int32_t> foregroundUserIds,std::vector<int32_t> backgroundUserIds)3248 void DeviceManagerService::ProcessCheckSumByBT(std::string networkId, std::vector<int32_t> foregroundUserIds,
3249 std::vector<int32_t> backgroundUserIds)
3250 {
3251 LOGI("Try send brodcast to exchange foreground userid");
3252 std::string udid = "";
3253 SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid);
3254 if (udid.empty()) {
3255 LOGE("Can not get udid for networkid: %{public}s", GetAnonyString(networkId).c_str());
3256 return;
3257 }
3258
3259 std::vector<std::string> peerUdids = { udid };
3260 if (!foregroundUserIds.empty()) {
3261 LOGI("Send local foreground and background userids");
3262 SendUserIdsBroadCast(peerUdids, foregroundUserIds, backgroundUserIds, true);
3263 } else {
3264 LOGE("local foreground userids empty");
3265 }
3266 }
3267
HandleUserIdCheckSumChange(const std::string & msg)3268 void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg)
3269 {
3270 if (msg.empty()) {
3271 LOGE("Msg is empty.");
3272 return;
3273 }
3274 LOGI("handle user trust change, msg: %{public}s", GetAnonyString(msg).c_str());
3275 std::string remoteNetworkId = "";
3276 uint32_t discoveryType = 0;
3277 bool isPeerUserIdChanged = true;
3278 int32_t ret = ParseCheckSumMsg(msg, remoteNetworkId, discoveryType, isPeerUserIdChanged);
3279 if (ret != DM_OK) {
3280 LOGE("Parse checksum msg error");
3281 return;
3282 }
3283 if (!isPeerUserIdChanged) {
3284 LOGI("Peer foreground userId not change.");
3285 return;
3286 }
3287 std::vector<int32_t> foregroundUserIds;
3288 ret = MultipleUserConnector::GetForegroundUserIds(foregroundUserIds);
3289 if (ret != DM_OK || foregroundUserIds.empty()) {
3290 LOGE("Get foreground userids failed, ret: %{public}d", ret);
3291 return;
3292 }
3293
3294 std::vector<int32_t> backgroundUserIds;
3295 ret = MultipleUserConnector::GetBackgroundUserIds(backgroundUserIds);
3296 if (ret != DM_OK || backgroundUserIds.empty()) {
3297 LOGI("Can not get background userids, ret: %{public}d, background userid num: %{public}d",
3298 ret, static_cast<int32_t>(backgroundUserIds.size()));
3299 }
3300 uint32_t addrTypeMask = 1 << NetworkType::BIT_NETWORK_TYPE_BLE;
3301 if ((discoveryType & addrTypeMask) != 0x0) {
3302 ProcessCheckSumByBT(remoteNetworkId, foregroundUserIds, backgroundUserIds);
3303 } else {
3304 ProcessCheckSumByWifi(remoteNetworkId, foregroundUserIds, backgroundUserIds);
3305 }
3306 }
3307 #endif
3308
ClearDiscoveryCache(const ProcessInfo & processInfo)3309 void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo)
3310 {
3311 LOGI("PkgName: %{public}s, userId: %{public}d", processInfo.pkgName.c_str(), processInfo.userId);
3312 CHECK_NULL_VOID(discoveryMgr_);
3313 discoveryMgr_->ClearDiscoveryCache(processInfo);
3314 }
3315
HandleDeviceScreenStatusChange(DmDeviceInfo & deviceInfo)3316 void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo)
3317 {
3318 if (IsDMServiceImplReady()) {
3319 dmServiceImpl_->HandleDeviceScreenStatusChange(deviceInfo);
3320 }
3321 }
3322
GetDeviceScreenStatus(const std::string & pkgName,const std::string & networkId,int32_t & screenStatus)3323 int32_t DeviceManagerService::GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId,
3324 int32_t &screenStatus)
3325 {
3326 LOGI("Begin pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str());
3327 if (!PermissionManager::GetInstance().CheckPermission()) {
3328 LOGE("The caller: %{public}s does not have permission to call GetDeviceScreenStatus.", pkgName.c_str());
3329 return ERR_DM_NO_PERMISSION;
3330 }
3331 if (pkgName.empty() || networkId.empty()) {
3332 LOGE("Invalid parameter, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(),
3333 GetAnonyString(networkId).c_str());
3334 return ERR_DM_INPUT_PARA_INVALID;
3335 }
3336 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
3337 int32_t ret = softbusListener_->GetDeviceScreenStatus(networkId.c_str(), screenStatus);
3338 if (ret != DM_OK) {
3339 LOGE("GetDeviceScreenStatus failed, ret = %{public}d", ret);
3340 return ret;
3341 }
3342 return DM_OK;
3343 }
3344
GetNetworkIdByUdid(const std::string & pkgName,const std::string & udid,std::string & networkId)3345 int32_t DeviceManagerService::GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid,
3346 std::string &networkId)
3347 {
3348 if (!PermissionManager::GetInstance().CheckPermission()) {
3349 LOGE("The caller: %{public}s does not have permission to call GetNetworkIdByUdid.", pkgName.c_str());
3350 return ERR_DM_NO_PERMISSION;
3351 }
3352 if (pkgName.empty() || udid.empty()) {
3353 LOGE("Invalid parameter, pkgName: %{public}s, udid: %{public}s", pkgName.c_str(), GetAnonyString(udid).c_str());
3354 return ERR_DM_INPUT_PARA_INVALID;
3355 }
3356 return SoftbusListener::GetNetworkIdByUdid(udid, networkId);
3357 }
3358
SubscribePackageCommonEvent()3359 void DeviceManagerService::SubscribePackageCommonEvent()
3360 {
3361 LOGI("Start");
3362 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
3363 if (packageCommonEventManager_ == nullptr) {
3364 packageCommonEventManager_ = std::make_shared<DmPackageCommonEventManager>();
3365 }
3366 PackageEventCallback callback = [=](const auto &arg1, const auto &arg2, const auto &arg3) {
3367 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
3368 NotifyRemoteUninstallApp(userId, arg3);
3369 if (IsDMServiceImplReady()) {
3370 dmServiceImpl_->ProcessAppUnintall(arg1, arg3);
3371 }
3372 KVAdapterManager::GetInstance().AppUnintall(arg1);
3373 };
3374 std::vector<std::string> commonEventVec;
3375 commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
3376 commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED);
3377 if (packageCommonEventManager_->SubscribePackageCommonEvent(commonEventVec, callback)) {
3378 LOGI("Success");
3379 }
3380 #endif
3381 }
3382
SyncLocalAclListProcess(const DevUserInfo & localDevUserInfo,const DevUserInfo & remoteDevUserInfo,std::string remoteAclList)3383 int32_t DeviceManagerService::SyncLocalAclListProcess(const DevUserInfo &localDevUserInfo,
3384 const DevUserInfo &remoteDevUserInfo, std::string remoteAclList)
3385 {
3386 if (IsDMServiceImplReady()) {
3387 return dmServiceImpl_->SyncLocalAclListProcess(localDevUserInfo, remoteDevUserInfo, remoteAclList);
3388 }
3389 return ERR_DM_FAILED;
3390 }
3391
GetAclListHash(const DevUserInfo & localDevUserInfo,const DevUserInfo & remoteDevUserInfo,std::string & aclList)3392 int32_t DeviceManagerService::GetAclListHash(const DevUserInfo &localDevUserInfo,
3393 const DevUserInfo &remoteDevUserInfo, std::string &aclList)
3394 {
3395 if (IsDMServiceImplReady()) {
3396 return dmServiceImpl_->GetAclListHash(localDevUserInfo, remoteDevUserInfo, aclList);
3397 }
3398 return ERR_DM_FAILED;
3399 }
3400
HandleCredentialAuthStatus(const std::string & deviceList,uint16_t deviceTypeId,int32_t errcode)3401 void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId,
3402 int32_t errcode)
3403 {
3404 if (IsDMServiceImplReady()) {
3405 dmServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode);
3406 }
3407 }
3408
RemoveNotifyRecord(const ProcessInfo & processInfo)3409 void DeviceManagerService::RemoveNotifyRecord(const ProcessInfo &processInfo)
3410 {
3411 LOGI("start");
3412 CHECK_NULL_VOID(listener_);
3413 listener_->OnProcessRemove(processInfo);
3414 }
3415
RegDevStateCallbackToService(const std::string & pkgName)3416 int32_t DeviceManagerService::RegDevStateCallbackToService(const std::string &pkgName)
3417 {
3418 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
3419 CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL);
3420 std::vector<DmDeviceInfo> deviceList;
3421 GetTrustedDeviceList(pkgName, deviceList);
3422 if (deviceList.size() == 0) {
3423 return DM_OK;
3424 }
3425 int32_t userId = -1;
3426 MultipleUserConnector::GetCallerUserId(userId);
3427 ProcessInfo processInfo;
3428 processInfo.pkgName = pkgName;
3429 processInfo.userId = userId;
3430 listener_->OnDevStateCallbackAdd(processInfo, deviceList);
3431 #else
3432 (void)pkgName;
3433 #endif
3434 return DM_OK;
3435 }
3436
GetTrustedDeviceList(const std::string & pkgName,std::vector<DmDeviceInfo> & deviceList)3437 int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, std::vector<DmDeviceInfo> &deviceList)
3438 {
3439 LOGI("Begin for pkgName = %{public}s.", pkgName.c_str());
3440 if (pkgName.empty() || pkgName == std::string(DM_PKG_NAME)) {
3441 LOGE("Invalid parameter, pkgName is empty.");
3442 return ERR_DM_INPUT_PARA_INVALID;
3443 }
3444 std::vector<DmDeviceInfo> onlineDeviceList;
3445 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
3446 int32_t ret = softbusListener_->GetTrustedDeviceList(onlineDeviceList);
3447 if (ret != DM_OK) {
3448 LOGE("failed");
3449 return ret;
3450 }
3451 if (!onlineDeviceList.empty() && IsDMServiceImplReady()) {
3452 dmServiceImpl_->DeleteAlwaysAllowTimeOut();
3453 std::unordered_map<std::string, DmAuthForm> udidMap;
3454 if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName)) {
3455 udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME));
3456 } else {
3457 udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName);
3458 }
3459 for (auto item : onlineDeviceList) {
3460 std::string udid = "";
3461 SoftbusListener::GetUdidByNetworkId(item.networkId, udid);
3462 if (udidMap.find(udid) != udidMap.end()) {
3463 item.authForm = udidMap[udid];
3464 deviceList.push_back(item);
3465 }
3466 }
3467 }
3468 return DM_OK;
3469 }
3470
HandleDeviceUnBind(const char * peerUdid,const GroupInformation & groupInfo)3471 void DeviceManagerService::HandleDeviceUnBind(const char *peerUdid, const GroupInformation &groupInfo)
3472 {
3473 LOGI("DeviceManagerService::HandleDeviceUnBind start.");
3474 char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
3475 GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
3476 std::string localUdid = std::string(localUdidTemp);
3477 if (IsDMServiceImplReady()) {
3478 dmServiceImpl_->HandleDeviceUnBind(groupInfo.groupType, std::string(peerUdid),
3479 localUdid, groupInfo.userId, groupInfo.osAccountId);
3480 }
3481 return;
3482 }
3483
GetAnonyLocalUdid(const std::string & pkgName,std::string & anonyUdid)3484 int32_t DeviceManagerService::GetAnonyLocalUdid(const std::string &pkgName, std::string &anonyUdid)
3485 {
3486 (void) pkgName;
3487 if (!PermissionManager::GetInstance().CheckPermission()) {
3488 LOGE("The caller does not have permission to call GetAnonyLocalUdid.");
3489 return ERR_DM_NO_PERMISSION;
3490 }
3491 std::string udid = DmRadarHelper::GetInstance().GetAnonyLocalUdid();
3492 if (udid.empty()) {
3493 LOGE("Anony local udid is empty.");
3494 return ERR_DM_FAILED;
3495 }
3496 anonyUdid = udid;
3497 return DM_OK;
3498 }
3499
3500 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
3501
NotifyRemoteUninstallApp(int32_t userId,int32_t tokenId)3502 void DeviceManagerService::NotifyRemoteUninstallApp(int32_t userId, int32_t tokenId)
3503 {
3504 LOGI("DeviceManagerService::NotifyRemoteUninstallApp userId: %{public}s, tokenId: %{public}s",
3505 GetAnonyInt32(userId).c_str(), GetAnonyInt32(tokenId).c_str());
3506 std::vector<std::string> peerUdids;
3507 int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID();
3508 if (IsDMServiceImplReady()) {
3509 peerUdids = dmServiceImpl_->GetDeviceIdByUserIdAndTokenId(currentUserId, tokenId);
3510 }
3511 if (peerUdids.empty()) {
3512 LOGE("peerUdids is empty");
3513 return;
3514 }
3515 if (softbusListener_ == nullptr) {
3516 LOGE("softbusListener_ is null");
3517 return;
3518 }
3519 std::vector<std::string> bleUdids;
3520 std::map<std::string, std::string> wifiDevices;
3521 for (const auto &udid : peerUdids) {
3522 std::string netWorkId = "";
3523 SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
3524 if (netWorkId.empty()) {
3525 LOGE("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
3526 bleUdids.push_back(udid);
3527 continue;
3528 }
3529 int32_t networkType = 0;
3530 int32_t ret = softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
3531 if (ret != DM_OK || networkType <= 0) {
3532 LOGE("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
3533 bleUdids.push_back(udid);
3534 continue;
3535 }
3536 uint32_t addrTypeMask = 1 << NetworkType::BIT_NETWORK_TYPE_BLE;
3537 if ((static_cast<uint32_t>(networkType) & addrTypeMask) != 0x0) {
3538 bleUdids.push_back(udid);
3539 } else {
3540 wifiDevices.insert(std::pair<std::string, std::string>(udid, netWorkId));
3541 }
3542 }
3543 if (!bleUdids.empty()) {
3544 SendAppUnInstallBroadCast(bleUdids, userId, tokenId);
3545 }
3546 if (!wifiDevices.empty()) {
3547 NotifyRemoteUninstallAppByWifi(userId, tokenId, wifiDevices);
3548 }
3549 }
3550
3551
NotifyRemoteUninstallAppByWifi(int32_t userId,int32_t tokenId,const std::map<std::string,std::string> & wifiDevices)3552 void DeviceManagerService::NotifyRemoteUninstallAppByWifi(int32_t userId, int32_t tokenId,
3553 const std::map<std::string, std::string> &wifiDevices)
3554 {
3555 LOGI("DeviceManagerService::NotifyRemoteUninstallAppByWifi userId: %{public}s, tokenId: %{public}s",
3556 GetAnonyInt32(userId).c_str(), GetAnonyInt32(tokenId).c_str());
3557 for (const auto &it : wifiDevices) {
3558 int32_t result = SendUninstAppByWifi(userId, tokenId, it.second);
3559 if (result != DM_OK) {
3560 LOGE("by wifi failed: %{public}s", GetAnonyString(it.first).c_str());
3561 continue;
3562 }
3563 if (timer_ == nullptr) {
3564 timer_ = std::make_shared<DmTimer>();
3565 }
3566 std::string udid = it.first;
3567 std::string networkId = it.second;
3568 timer_->StartTimer(std::string(APP_UNINSTALL_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid),
3569 USER_SWITCH_BY_WIFI_TIMEOUT_S, [this, networkId] (std::string name) {
3570 DMCommTool::GetInstance()->StopSocket(networkId);
3571 });
3572 }
3573 }
3574
NotifyRemoteUnBindAppByWifi(int32_t userId,int32_t tokenId,std::string extra,const std::map<std::string,std::string> & wifiDevices)3575 void DeviceManagerService::NotifyRemoteUnBindAppByWifi(int32_t userId, int32_t tokenId, std::string extra,
3576 const std::map<std::string, std::string> &wifiDevices)
3577 {
3578 LOGI("DeviceManagerService::NotifyRemoteUnBindAppByWifi userId: %{public}s, tokenId: %{public}s, extra: %{public}s",
3579 GetAnonyInt32(userId).c_str(), GetAnonyInt32(tokenId).c_str(), GetAnonyString(extra).c_str());
3580 for (const auto &it : wifiDevices) {
3581 char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
3582 GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
3583 std::string localUdid = std::string(localUdidTemp);
3584 int32_t result = SendUnBindAppByWifi(userId, tokenId, extra, it.second, localUdid);
3585 if (result != DM_OK) {
3586 LOGE("by wifi failed: %{public}s", GetAnonyString(it.first).c_str());
3587 continue;
3588 }
3589 if (timer_ == nullptr) {
3590 timer_ = std::make_shared<DmTimer>();
3591 }
3592 std::string udid = it.first;
3593 std::string networkId = it.second;
3594 timer_->StartTimer(std::string(APP_UNBIND_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid),
3595 USER_SWITCH_BY_WIFI_TIMEOUT_S, [this, networkId] (std::string name) {
3596 DMCommTool::GetInstance()->StopSocket(networkId);
3597 });
3598 }
3599 }
3600
ProcessReceiveRspAppUninstall(const std::string & remoteUdid)3601 void DeviceManagerService::ProcessReceiveRspAppUninstall(const std::string &remoteUdid)
3602 {
3603 LOGI("ProcessReceiveRspAppUninstall remoteUdid: %{public}s", GetAnonyString(remoteUdid).c_str());
3604 if (timer_ != nullptr && remoteUdid != "") {
3605 timer_->DeleteTimer(std::string(APP_UNINSTALL_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(remoteUdid));
3606 }
3607 }
3608
ProcessReceiveRspAppUnbind(const std::string & remoteUdid)3609 void DeviceManagerService::ProcessReceiveRspAppUnbind(const std::string &remoteUdid)
3610 {
3611 LOGI("ProcessReceiveRspAppUnbind remoteUdid: %{public}s", GetAnonyString(remoteUdid).c_str());
3612 if (timer_ != nullptr && remoteUdid != "") {
3613 timer_->DeleteTimer(std::string(APP_UNBIND_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(remoteUdid));
3614 }
3615 }
3616
SendUninstAppByWifi(int32_t userId,int32_t tokenId,const std::string & networkId)3617 int32_t DeviceManagerService::SendUninstAppByWifi(int32_t userId, int32_t tokenId, const std::string &networkId)
3618 {
3619 LOGE("DeviceManagerService::SendUninstAppByWifi userId: %{public}s, tokenId: %{public}s",
3620 GetAnonyInt32(userId).c_str(), GetAnonyInt32(tokenId).c_str());
3621 return DMCommTool::GetInstance()->SendUninstAppObj(userId, tokenId, networkId);
3622 }
3623
SendUnBindAppByWifi(int32_t userId,int32_t tokenId,std::string extra,const std::string & networkId,const std::string & udid)3624 int32_t DeviceManagerService::SendUnBindAppByWifi(int32_t userId, int32_t tokenId, std::string extra,
3625 const std::string &networkId, const std::string &udid)
3626 {
3627 LOGE("DeviceManagerService::SendUnBindAppByWifi");
3628 return DMCommTool::GetInstance()->SendUnBindAppObj(userId, tokenId, extra, networkId, udid);
3629 }
3630
GetNotifyRemoteUnBindAppWay(int32_t userId,int32_t tokenId,std::map<std::string,std::string> & wifiDevices,bool & isBleWay)3631 void DeviceManagerService::GetNotifyRemoteUnBindAppWay(int32_t userId, int32_t tokenId,
3632 std::map<std::string, std::string> &wifiDevices, bool &isBleWay)
3633 {
3634 std::vector<std::string> peerUdids;
3635 int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID();
3636 std::map<std::string, int32_t> deviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(currentUserId);
3637 for (const auto &item : deviceMap) {
3638 peerUdids.push_back(item.first);
3639 }
3640 if (peerUdids.empty()) {
3641 LOGE("peerUdids is empty");
3642 return;
3643 }
3644 if (softbusListener_ == nullptr) {
3645 LOGE("softbusListener_ is null");
3646 return;
3647 }
3648
3649 std::vector<std::string> bleUdids;
3650 for (const auto &udid : peerUdids) {
3651 std::string netWorkId = "";
3652 SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
3653 if (netWorkId.empty()) {
3654 LOGE("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
3655 bleUdids.push_back(udid);
3656 continue;
3657 }
3658 int32_t networkType = 0;
3659 int32_t ret = softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
3660 if (ret != DM_OK || networkType <= 0) {
3661 LOGE("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
3662 bleUdids.push_back(udid);
3663 continue;
3664 }
3665 uint32_t addrTypeMask = 1 << NetworkType::BIT_NETWORK_TYPE_BLE;
3666 if ((static_cast<uint32_t>(networkType) & addrTypeMask) != 0x0) {
3667 bleUdids.push_back(udid);
3668 } else {
3669 wifiDevices.insert(std::pair<std::string, std::string>(udid, netWorkId));
3670 }
3671 }
3672
3673 if (!bleUdids.empty()) {
3674 isBleWay = true;
3675 } else {
3676 isBleWay = false;
3677 }
3678 }
3679
HandleUserStopEvent(int32_t stopUserId)3680 void DeviceManagerService::HandleUserStopEvent(int32_t stopUserId)
3681 {
3682 LOGI("stopUserId %{public}s.", GetAnonyInt32(stopUserId).c_str());
3683 std::vector<int32_t> foregroundUserVec;
3684 int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec);
3685 std::vector<int32_t> backgroundUserVec;
3686 int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec);
3687 MultipleUserConnector::ClearLockedUser(foregroundUserVec, backgroundUserVec);
3688 if (retFront != DM_OK || retBack != DM_OK) {
3689 LOGE("retFront: %{public}d, retBack: %{public}d, frontuserids: %{public}s, backuserids: %{public}s",
3690 retFront, retBack, GetIntegerList(foregroundUserVec).c_str(), GetIntegerList(backgroundUserVec).c_str());
3691 return;
3692 }
3693 if (!IsUserStatusChanged(foregroundUserVec, backgroundUserVec)) {
3694 LOGI("User status has not changed.");
3695 return;
3696 }
3697 std::vector<int32_t> stopUserVec;
3698 stopUserVec.push_back(stopUserId);
3699 char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
3700 GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
3701 std::string localUdid = std::string(localUdidTemp);
3702 std::map<std::string, int32_t> stopUserDeviceMap;
3703 std::vector<std::string> peerUdids;
3704 CHECK_NULL_VOID(discoveryMgr_);
3705 if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
3706 LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
3707 return;
3708 }
3709 stopUserDeviceMap = discoveryMgr_->GetCommonDependencyObj()->
3710 GetDeviceIdAndBindLevel(stopUserVec, localUdid);
3711 for (const auto &item : stopUserDeviceMap) {
3712 peerUdids.push_back(item.first);
3713 }
3714 if (peerUdids.empty()) {
3715 LOGI("no data to be stoped.");
3716 return;
3717 }
3718 NotifyRemoteLocalUserStop(localUdid, peerUdids, stopUserId);
3719 }
3720
DivideNotifyMethod(const std::vector<std::string> & peerUdids,std::vector<std::string> & bleUdids,std::map<std::string,std::string> & wifiDevices)3721 void DeviceManagerService::DivideNotifyMethod(const std::vector<std::string> &peerUdids,
3722 std::vector<std::string> &bleUdids, std::map<std::string, std::string> &wifiDevices)
3723 {
3724 if (peerUdids.empty()) {
3725 return;
3726 }
3727 if (softbusListener_ == nullptr) {
3728 bleUdids = peerUdids;
3729 LOGI("softbusListener_ is null");
3730 return;
3731 }
3732 for (const auto &udid : peerUdids) {
3733 std::string netWorkId = "";
3734 SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
3735 if (netWorkId.empty()) {
3736 LOGI("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
3737 bleUdids.push_back(udid);
3738 continue;
3739 }
3740 int32_t networkType = 0;
3741 int32_t ret = softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
3742 if (ret != DM_OK || networkType <= 0) {
3743 LOGI("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
3744 bleUdids.push_back(udid);
3745 continue;
3746 }
3747 uint32_t addrTypeMask = 1 << NetworkType::BIT_NETWORK_TYPE_BLE;
3748 if ((static_cast<uint32_t>(networkType) & addrTypeMask) != 0x0) {
3749 bleUdids.push_back(udid);
3750 } else {
3751 wifiDevices.insert(std::pair<std::string, std::string>(udid, netWorkId));
3752 }
3753 }
3754 }
3755
HandleUserStop(int32_t stopUserId,const std::string & stopEventUdid,const std::vector<std::string> & acceptEventUdids)3756 void DeviceManagerService::HandleUserStop(int32_t stopUserId, const std::string &stopEventUdid,
3757 const std::vector<std::string> &acceptEventUdids)
3758 {
3759 if (timer_ != nullptr) {
3760 for (const auto &udid : acceptEventUdids) {
3761 timer_->DeleteTimer(std::string(USER_STOP_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid));
3762 }
3763 }
3764 if (MultipleUserConnector::IsUserUnlocked(stopUserId)) {
3765 LOGE("user has unlocked %{public}s.", GetAnonyInt32(stopUserId).c_str());
3766 return;
3767 }
3768 CHECK_NULL_VOID(discoveryMgr_);
3769 if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
3770 LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
3771 return;
3772 }
3773 discoveryMgr_->GetCommonDependencyObj()->HandleUserStop(stopUserId, stopEventUdid, acceptEventUdids);
3774 }
3775
HandleUserStop(int32_t stopUserId,const std::string & stopEventUdid)3776 void DeviceManagerService::HandleUserStop(int32_t stopUserId, const std::string &stopEventUdid)
3777 {
3778 CHECK_NULL_VOID(discoveryMgr_);
3779 if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
3780 LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
3781 return;
3782 }
3783 discoveryMgr_->GetCommonDependencyObj()->HandleUserStop(stopUserId, stopEventUdid);
3784 }
3785
NotifyRemoteLocalUserStop(const std::string & localUdid,const std::vector<std::string> & peerUdids,int32_t stopUserId)3786 void DeviceManagerService::NotifyRemoteLocalUserStop(const std::string &localUdid,
3787 const std::vector<std::string> &peerUdids, int32_t stopUserId)
3788 {
3789 std::vector<std::string> bleUdids;
3790 std::map<std::string, std::string> wifiDevices;
3791 DivideNotifyMethod(peerUdids, bleUdids, wifiDevices);
3792 if (!bleUdids.empty()) {
3793 HandleUserStop(stopUserId, localUdid, bleUdids);
3794 SendUserStopBroadCast(bleUdids, stopUserId);
3795 }
3796 if (!wifiDevices.empty()) {
3797 NotifyRemoteLocalUserStopByWifi(localUdid, wifiDevices, stopUserId);
3798 }
3799 }
3800
SendUserStopBroadCast(const std::vector<std::string> & peerUdids,int32_t stopUserId)3801 void DeviceManagerService::SendUserStopBroadCast(const std::vector<std::string> &peerUdids, int32_t stopUserId)
3802 {
3803 LOGI("peerUdids: %{public}s", GetAnonyStringList(peerUdids).c_str());
3804 RelationShipChangeMsg msg;
3805 msg.type = RelationShipChangeType::STOP_USER;
3806 msg.userId = static_cast<uint32_t>(stopUserId);
3807 msg.peerUdids = peerUdids;
3808 std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
3809 CHECK_NULL_VOID(softbusListener_);
3810 softbusListener_->SendAclChangedBroadcast(broadCastMsg);
3811 }
3812
HandleUserStopBroadCast(int32_t stopUserId,const std::string & remoteUdid)3813 void DeviceManagerService::HandleUserStopBroadCast(int32_t stopUserId, const std::string &remoteUdid)
3814 {
3815 LOGI("start");
3816 HandleUserStop(stopUserId, remoteUdid);
3817 }
3818
NotifyRemoteLocalUserStopByWifi(const std::string & localUdid,const std::map<std::string,std::string> & wifiDevices,int32_t stopUserId)3819 void DeviceManagerService::NotifyRemoteLocalUserStopByWifi(const std::string &localUdid,
3820 const std::map<std::string, std::string> &wifiDevices, int32_t stopUserId)
3821 {
3822 for (const auto &it : wifiDevices) {
3823 std::vector<std::string> updateUdids;
3824 updateUdids.push_back(it.first);
3825 int32_t result = DMCommTool::GetInstance()->SendUserStop(it.second, stopUserId);
3826 if (result != DM_OK) {
3827 LOGE("by wifi failed: %{public}s", GetAnonyString(it.first).c_str());
3828 HandleUserStop(stopUserId, localUdid, updateUdids);
3829 continue;
3830 }
3831 if (timer_ == nullptr) {
3832 timer_ = std::make_shared<DmTimer>();
3833 }
3834 std::string udid = it.first;
3835 timer_->StartTimer(std::string(USER_STOP_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid),
3836 USER_SWITCH_BY_WIFI_TIMEOUT_S,
3837 [this, stopUserId, localUdid, updateUdids] (std::string name) {
3838 DeviceManagerService::HandleUserStop(stopUserId, localUdid, updateUdids);
3839 });
3840 }
3841 }
3842 #endif
3843
RegisterAuthenticationType(const std::string & pkgName,const std::map<std::string,std::string> & authParam)3844 int32_t DeviceManagerService::RegisterAuthenticationType(const std::string &pkgName,
3845 const std::map<std::string, std::string> &authParam)
3846 {
3847 if (!PermissionManager::GetInstance().CheckPermission()) {
3848 LOGE("The caller does not have permission to call");
3849 return ERR_DM_NO_PERMISSION;
3850 }
3851 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3852 if (pkgName.empty()) {
3853 LOGE("Invalid parameter, pkgName is empty.");
3854 return ERR_DM_INPUT_PARA_INVALID;
3855 }
3856 auto authTypeIter = authParam.find(DM_AUTHENTICATION_TYPE);
3857 if (authTypeIter == authParam.end()) {
3858 LOGE("Invalid parameter, DM_AUTHENTICATION_TYPE is empty.");
3859 return ERR_DM_INPUT_PARA_INVALID;
3860 }
3861 if (!IsNumberString(authTypeIter->second)) {
3862 LOGE("Invalid parameter, DM_AUTHENTICATION_TYPE is not number.");
3863 return ERR_DM_INPUT_PARA_INVALID;
3864 }
3865 int32_t authenticationType = std::atoi(authTypeIter->second.c_str());
3866
3867 if (!IsDMServiceImplReady()) {
3868 LOGE("RegisterAuthenticationType failed, instance not init or init failed.");
3869 return ERR_DM_INIT_FAILED;
3870 }
3871 return dmServiceImpl_->RegisterAuthenticationType(authenticationType);
3872 }
3873
GetDeviceProfileInfoList(const std::string & pkgName,DmDeviceProfileInfoFilterOptions & filterOptions)3874 int32_t DeviceManagerService::GetDeviceProfileInfoList(const std::string &pkgName,
3875 DmDeviceProfileInfoFilterOptions &filterOptions)
3876 {
3877 if (!PermissionManager::GetInstance().CheckPermission()) {
3878 LOGE("The caller does not have permission to call");
3879 return ERR_DM_NO_PERMISSION;
3880 }
3881 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3882 if (!IsDMServiceAdapterResidentLoad()) {
3883 LOGE("GetDeviceProfileInfoList failed, adapter instance not init or init failed.");
3884 return ERR_DM_UNSUPPORTED_METHOD;
3885 }
3886 return dmServiceImplExtResident_->GetDeviceProfileInfoList(pkgName, filterOptions);
3887 }
3888
GetDeviceIconInfo(const std::string & pkgName,DmDeviceIconInfoFilterOptions & filterOptions)3889 int32_t DeviceManagerService::GetDeviceIconInfo(const std::string &pkgName,
3890 DmDeviceIconInfoFilterOptions &filterOptions)
3891 {
3892 if (!PermissionManager::GetInstance().CheckPermission()) {
3893 LOGE("The caller does not have permission to call");
3894 return ERR_DM_NO_PERMISSION;
3895 }
3896 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3897 if (!IsDMServiceAdapterResidentLoad()) {
3898 LOGE("GetDeviceIconInfo failed, adapter instance not init or init failed.");
3899 return ERR_DM_UNSUPPORTED_METHOD;
3900 }
3901 return dmServiceImplExtResident_->GetDeviceIconInfo(pkgName, filterOptions);
3902 }
3903
PutDeviceProfileInfoList(const std::string & pkgName,std::vector<DmDeviceProfileInfo> & deviceProfileInfoList)3904 int32_t DeviceManagerService::PutDeviceProfileInfoList(const std::string &pkgName,
3905 std::vector<DmDeviceProfileInfo> &deviceProfileInfoList)
3906 {
3907 if (!PermissionManager::GetInstance().CheckPermission()) {
3908 LOGE("The caller does not have permission to call");
3909 return ERR_DM_NO_PERMISSION;
3910 }
3911 std::string processName = "";
3912 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
3913 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
3914 return ERR_DM_FAILED;
3915 }
3916 if (!PermissionManager::GetInstance().CheckProcessNameValidPutDeviceProfileInfoList(processName)) {
3917 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
3918 return ERR_DM_NO_PERMISSION;
3919 }
3920 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3921 if (!IsDMServiceAdapterResidentLoad()) {
3922 LOGE("GetDeviceProfileInfoList failed, adapter instance not init or init failed.");
3923 return ERR_DM_UNSUPPORTED_METHOD;
3924 }
3925 return dmServiceImplExtResident_->PutDeviceProfileInfoList(pkgName, deviceProfileInfoList);
3926 }
3927
SetLocalDisplayNameToSoftbus(const std::string & displayName)3928 int32_t DeviceManagerService::SetLocalDisplayNameToSoftbus(const std::string &displayName)
3929 {
3930 LOGI("DeviceManagerService Start SetLocalDisplayName!");
3931 CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
3932 int32_t ret = softbusListener_->SetLocalDisplayName(displayName);
3933 if (ret != DM_OK) {
3934 LOGE("SetLocalDisplayName error, failed ret: %{public}d", ret);
3935 return ret;
3936 }
3937 return DM_OK;
3938 }
3939
GetLocalDisplayDeviceName(const std::string & pkgName,int32_t maxNameLength,std::string & displayName)3940 int32_t DeviceManagerService::GetLocalDisplayDeviceName(const std::string &pkgName, int32_t maxNameLength,
3941 std::string &displayName)
3942 {
3943 if (!PermissionManager::GetInstance().CheckPermission()) {
3944 LOGE("The caller does not have permission to call");
3945 return ERR_DM_NO_PERMISSION;
3946 }
3947 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3948 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
3949 return DeviceNameManager::GetInstance().GetLocalDisplayDeviceName(maxNameLength, displayName);
3950 #endif
3951 return DM_OK;
3952 }
3953
SetLocalDeviceName(const std::string & pkgName,const std::string & deviceName)3954 int32_t DeviceManagerService::SetLocalDeviceName(const std::string &pkgName, const std::string &deviceName)
3955 {
3956 if (!PermissionManager::GetInstance().CheckPermission()) {
3957 LOGE("The caller does not have permission to call");
3958 return ERR_DM_NO_PERMISSION;
3959 }
3960 std::string processName = "";
3961 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
3962 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
3963 return ERR_DM_FAILED;
3964 }
3965 if (!PermissionManager::GetInstance().CheckProcessNameValidModifyLocalDeviceName(processName)) {
3966 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
3967 return ERR_DM_NO_PERMISSION;
3968 }
3969 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3970 if (!IsDMServiceAdapterResidentLoad()) {
3971 LOGE("SetLocalDeviceName failed, adapter instance not init or init failed.");
3972 return ERR_DM_UNSUPPORTED_METHOD;
3973 }
3974 return dmServiceImplExtResident_->SetLocalDeviceName(pkgName, deviceName);
3975 }
3976
SetRemoteDeviceName(const std::string & pkgName,const std::string & deviceId,const std::string & deviceName)3977 int32_t DeviceManagerService::SetRemoteDeviceName(const std::string &pkgName,
3978 const std::string &deviceId, const std::string &deviceName)
3979 {
3980 if (!PermissionManager::GetInstance().CheckPermission()) {
3981 LOGE("The caller does not have permission to call");
3982 return ERR_DM_NO_PERMISSION;
3983 }
3984 std::string processName = "";
3985 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
3986 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
3987 return ERR_DM_FAILED;
3988 }
3989 if (!PermissionManager::GetInstance().CheckProcessNameValidModifyRemoteDeviceName(processName)) {
3990 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
3991 return ERR_DM_NO_PERMISSION;
3992 }
3993 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3994 if (!IsDMServiceAdapterResidentLoad()) {
3995 LOGE("SetRemoteDeviceName failed, adapter instance not init or init failed.");
3996 return ERR_DM_UNSUPPORTED_METHOD;
3997 }
3998 return dmServiceImplExtResident_->SetRemoteDeviceName(pkgName, deviceId, deviceName);
3999 }
4000
GetDeviceNamePrefixs()4001 std::vector<std::string> DeviceManagerService::GetDeviceNamePrefixs()
4002 {
4003 LOGI("In");
4004 if (!IsDMServiceAdapterResidentLoad()) {
4005 LOGE("GetDeviceNamePrefixs failed, adapter instance not init or init failed.");
4006 return {};
4007 }
4008 return dmServiceImplExtResident_->GetDeviceNamePrefixs();
4009 }
4010
HandleNetworkConnected(int32_t networkStatus)4011 void DeviceManagerService::HandleNetworkConnected(int32_t networkStatus)
4012 {
4013 LOGI("In");
4014 if (!IsDMServiceAdapterResidentLoad()) {
4015 LOGE("HandleNetworkConnected failed, adapter instance not init or init failed.");
4016 return;
4017 }
4018 dmServiceImplExtResident_->HandleNetworkConnected(networkStatus);
4019 }
4020
RestoreLocalDeviceName(const std::string & pkgName)4021 int32_t DeviceManagerService::RestoreLocalDeviceName(const std::string &pkgName)
4022 {
4023 LOGI("In");
4024 if (!PermissionManager::GetInstance().CheckPermission()) {
4025 LOGE("The caller does not have permission to call");
4026 return ERR_DM_NO_PERMISSION;
4027 }
4028 std::string processName = "";
4029 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
4030 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
4031 return ERR_DM_FAILED;
4032 }
4033 if (!PermissionManager::GetInstance().CheckProcessNameValidModifyLocalDeviceName(processName)) {
4034 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
4035 return ERR_DM_NO_PERMISSION;
4036 }
4037 if (IsDMServiceAdapterResidentLoad()) {
4038 dmServiceImplExtResident_->RestoreLocalDeviceName();
4039 } else {
4040 LOGW("RestoreLocalDeviceName fail, adapter instance not init or init failed.");
4041 }
4042 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
4043 return DeviceNameManager::GetInstance().RestoreLocalDeviceName();
4044 #endif
4045 return DM_OK;
4046 }
4047
AddHmlInfoToBindParam(int32_t actionId,std::string & bindParam)4048 void DeviceManagerService::AddHmlInfoToBindParam(int32_t actionId, std::string &bindParam)
4049 {
4050 cJSON *bindParamObj = cJSON_Parse(bindParam.c_str());
4051 if (bindParamObj == NULL) {
4052 bindParamObj = cJSON_CreateObject();
4053 if (bindParamObj == NULL) {
4054 LOGE("Create bindParamObj object failed.");
4055 return;
4056 }
4057 }
4058 cJSON_AddStringToObject(bindParamObj, PARAM_KEY_CONN_SESSIONTYPE, CONN_SESSION_TYPE_HML);
4059 cJSON_AddStringToObject(bindParamObj, PARAM_KEY_HML_ACTIONID, std::to_string(actionId).c_str());
4060 char *str = cJSON_PrintUnformatted(bindParamObj);
4061 if (str == nullptr) {
4062 cJSON_Delete(bindParamObj);
4063 return;
4064 }
4065 bindParam = std::string(str);
4066 cJSON_free(str);
4067 cJSON_Delete(bindParamObj);
4068 }
4069
ClearPublishIdCache(const std::string & pkgName)4070 void DeviceManagerService::ClearPublishIdCache(const std::string &pkgName)
4071 {
4072 CHECK_NULL_VOID(advertiseMgr_);
4073 advertiseMgr_->ClearPublishIdCache(pkgName);
4074 }
4075
IsPC()4076 bool DeviceManagerService::IsPC()
4077 {
4078 if (softbusListener_ == nullptr) {
4079 LOGE("softbusListener_ is null.");
4080 return false;
4081 }
4082 DmDeviceInfo info;
4083 GetLocalDeviceInfo(info);
4084 return (info.deviceTypeId == DmDeviceType::DEVICE_TYPE_PC || info.deviceTypeId == DmDeviceType::DEVICE_TYPE_2IN1);
4085 }
4086
GetDeviceNetworkIdList(const std::string & pkgName,const NetworkIdQueryFilter & queryFilter,std::vector<std::string> & networkIds)4087 int32_t DeviceManagerService::GetDeviceNetworkIdList(const std::string &pkgName,
4088 const NetworkIdQueryFilter &queryFilter, std::vector<std::string> &networkIds)
4089 {
4090 if (!PermissionManager::GetInstance().CheckPermission()) {
4091 LOGE("The caller does not have permission to call");
4092 return ERR_DM_NO_PERMISSION;
4093 }
4094 LOGI("Start for pkgName = %{public}s", pkgName.c_str());
4095 if (!IsDMServiceAdapterResidentLoad()) {
4096 LOGE("GetDeviceProfileInfoList failed, adapter instance not init or init failed.");
4097 return ERR_DM_UNSUPPORTED_METHOD;
4098 }
4099 std::vector<DmDeviceProfileInfo> dmDeviceProfileInfos;
4100 int32_t ret = dmServiceImplExtResident_->GetDeviceProfileInfosFromLocalCache(queryFilter, dmDeviceProfileInfos);
4101 if (ret != DM_OK) {
4102 LOGW("GetDeviceProfileInfosFromLocalCache failed, ret = %{public}d.", ret);
4103 return ret;
4104 }
4105 for (const auto &item : dmDeviceProfileInfos) {
4106 std::string networkId = "";
4107 SoftbusCache::GetInstance().GetNetworkIdFromCache(item.deviceId, networkId);
4108 if (!networkId.empty()) {
4109 networkIds.emplace_back(networkId);
4110 }
4111 }
4112 if (networkIds.empty()) {
4113 LOGW("networkIds is empty");
4114 return ERR_DM_FIND_NETWORKID_LIST_EMPTY;
4115 }
4116 return DM_OK;
4117 }
4118
NotifyRemoteLocalLogout(const std::vector<std::string> & peerUdids,const std::string & accountIdHash,const std::string & accountName,int32_t userId)4119 void DeviceManagerService::NotifyRemoteLocalLogout(const std::vector<std::string> &peerUdids,
4120 const std::string &accountIdHash, const std::string &accountName, int32_t userId)
4121 {
4122 LOGI("Start.");
4123 std::vector<std::string> bleUdids;
4124 std::vector<std::string> wifiDevices;
4125 for (const auto &udid : peerUdids) {
4126 std::string netWorkId = "";
4127 SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
4128 if (netWorkId.empty()) {
4129 LOGI("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
4130 bleUdids.push_back(udid);
4131 continue;
4132 }
4133 int32_t networkType = 0;
4134 int32_t ret = softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
4135 if (ret != DM_OK || networkType <= 0) {
4136 LOGI("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
4137 bleUdids.push_back(udid);
4138 continue;
4139 }
4140 uint32_t addrTypeMask = 1 << NetworkType::BIT_NETWORK_TYPE_BLE;
4141 if ((static_cast<uint32_t>(networkType) & addrTypeMask) != 0x0) {
4142 bleUdids.push_back(udid);
4143 } else {
4144 wifiDevices.push_back(netWorkId);
4145 }
4146 }
4147 if (!bleUdids.empty()) {
4148 SendAccountLogoutBroadCast(bleUdids, accountIdHash, accountName, userId);
4149 }
4150 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
4151 for (const auto &it : wifiDevices) {
4152 int32_t ret = DMCommTool::GetInstance()->SendLogoutAccountInfo(it, accountIdHash, userId);
4153 if (ret != DM_OK) {
4154 LOGE("Send LogoutAccount Info error, ret = %{public}d", ret);
4155 }
4156 }
4157 #endif
4158 }
4159
ProcessSyncAccountLogout(const std::string & accountId,const std::string & peerUdid,int32_t userId)4160 void DeviceManagerService::ProcessSyncAccountLogout(const std::string &accountId, const std::string &peerUdid,
4161 int32_t userId)
4162 {
4163 LOGI("Start. process udid: %{public}s", GetAnonyString(peerUdid).c_str());
4164 if (!IsDMServiceImplReady()) {
4165 LOGE("Imp instance not init or init failed.");
4166 return;
4167 }
4168 dmServiceImpl_->HandleAccountLogoutEvent(userId, accountId, peerUdid);
4169 }
4170
OpenAuthSessionWithPara(const std::string & deviceId,int32_t actionId,bool isEnable160m)4171 int32_t DeviceManagerService::OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m)
4172 {
4173 if (!IsDMServiceAdapterResidentLoad()) {
4174 LOGE("failed, adapter instance not init or init failed.");
4175 return ERR_DM_UNSUPPORTED_METHOD;
4176 }
4177 return dmServiceImplExtResident_->OpenAuthSessionWithPara(deviceId, actionId, isEnable160m);
4178 }
4179
UnRegisterPinHolderCallback(const std::string & pkgName)4180 int32_t DeviceManagerService::UnRegisterPinHolderCallback(const std::string &pkgName)
4181 {
4182 if (!PermissionManager::GetInstance().CheckPermission()) {
4183 LOGE("The caller: %{public}s does not have permission to call UnRegisterPinHolderCallback.", pkgName.c_str());
4184 return ERR_DM_NO_PERMISSION;
4185 }
4186 std::string processName = "";
4187 if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
4188 LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
4189 return ERR_DM_FAILED;
4190 }
4191 if (!PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName)) {
4192 LOGE("The caller: %{public}s is not in white list.", processName.c_str());
4193 return ERR_DM_INPUT_PARA_INVALID;
4194 }
4195 LOGI("begin.");
4196 if (pkgName.empty()) {
4197 LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str());
4198 return ERR_DM_INPUT_PARA_INVALID;
4199 }
4200 CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
4201 return pinHolder_->UnRegisterPinHolderCallback(pkgName);
4202 }
4203
GetLocalDeviceName(std::string & deviceName)4204 int32_t DeviceManagerService::GetLocalDeviceName(std::string &deviceName)
4205 {
4206 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
4207 if (PermissionManager::GetInstance().CheckReadLocalDeviceName()) {
4208 return DeviceNameManager::GetInstance().GetLocalDisplayDeviceName(0, deviceName);
4209 } else {
4210 deviceName = DeviceNameManager::GetInstance().GetLocalMarketName();
4211 return DM_OK;
4212 }
4213 #endif
4214 (void) deviceName;
4215 return DM_OK;
4216 }
4217
GetAccessUdidByNetworkId(const std::string & srcNetWorkId,std::string & srcUdid,const std::string & sinkNetWorkId,std::string & sinkUdid)4218 bool DeviceManagerService::GetAccessUdidByNetworkId(const std::string &srcNetWorkId, std::string &srcUdid,
4219 const std::string &sinkNetWorkId, std::string &sinkUdid)
4220 {
4221 LOGI("start srcNetWorkId %{public}s, sinkNetWorkId %{public}s.", GetAnonyString(srcNetWorkId).c_str(),
4222 GetAnonyString(sinkNetWorkId).c_str());
4223 if (!PermissionManager::GetInstance().CheckPermission()) {
4224 LOGE("The caller not have permission to call GetAccessUdidByNetworkId.");
4225 return false;
4226 }
4227 if (!IsDMServiceImplReady()) {
4228 LOGE("GetAccessUdidByNetworkId failed, instance not init or init failed.");
4229 return false;
4230 }
4231 SoftbusListener::GetUdidByNetworkId(srcNetWorkId.c_str(), srcUdid);
4232 SoftbusListener::GetUdidByNetworkId(sinkNetWorkId.c_str(), sinkUdid);
4233 return true;
4234 }
4235
CheckSrcAccessControl(const DmAccessCaller & caller,const DmAccessCallee & callee)4236 bool DeviceManagerService::CheckSrcAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee)
4237 {
4238 std::string srcUdid = "";
4239 std::string sinkUdid = "";
4240 if (!GetAccessUdidByNetworkId(caller.networkId.c_str(), srcUdid, callee.networkId.c_str(), sinkUdid)) {
4241 LOGE("The caller %{public}s GetAccessUdidByNetworkId failed.", caller.pkgName.c_str());
4242 return false;
4243 }
4244 return dmServiceImpl_->CheckSrcAccessControl(caller, srcUdid, callee, sinkUdid);
4245 }
4246
CheckSinkAccessControl(const DmAccessCaller & caller,const DmAccessCallee & callee)4247 bool DeviceManagerService::CheckSinkAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee)
4248 {
4249 std::string srcUdid = "";
4250 std::string sinkUdid = "";
4251 if (!GetAccessUdidByNetworkId(caller.networkId.c_str(), srcUdid, callee.networkId.c_str(), sinkUdid)) {
4252 LOGE("The caller %{public}s GetAccessUdidByNetworkId failed.", caller.pkgName.c_str());
4253 return false;
4254 }
4255 return dmServiceImpl_->CheckSinkAccessControl(caller, srcUdid, callee, sinkUdid);
4256 }
4257
CheckSrcIsSameAccount(const DmAccessCaller & caller,const DmAccessCallee & callee)4258 bool DeviceManagerService::CheckSrcIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee)
4259 {
4260 std::string srcUdid = "";
4261 std::string sinkUdid = "";
4262 if (!GetAccessUdidByNetworkId(caller.networkId.c_str(), srcUdid, callee.networkId.c_str(), sinkUdid)) {
4263 LOGE("The caller %{public}s GetAccessUdidByNetworkId failed.", caller.pkgName.c_str());
4264 return false;
4265 }
4266 return dmServiceImpl_->CheckSrcIsSameAccount(caller, srcUdid, callee, sinkUdid);
4267 }
4268
CheckSinkIsSameAccount(const DmAccessCaller & caller,const DmAccessCallee & callee)4269 bool DeviceManagerService::CheckSinkIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee)
4270 {
4271 std::string srcUdid = "";
4272 std::string sinkUdid = "";
4273 if (!GetAccessUdidByNetworkId(caller.networkId.c_str(), srcUdid, callee.networkId.c_str(), sinkUdid)) {
4274 LOGE("The caller %{public}s GetAccessUdidByNetworkId failed.", caller.pkgName.c_str());
4275 return false;
4276 }
4277 return dmServiceImpl_->CheckSinkIsSameAccount(caller, srcUdid, callee, sinkUdid);
4278 }
4279
4280 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
HandleUserSwitchEventCallback(const std::string & commonEventType,int32_t currentUserId,int32_t beforeUserId)4281 void DeviceManagerService::HandleUserSwitchEventCallback(const std::string &commonEventType, int32_t currentUserId,
4282 int32_t beforeUserId)
4283 {
4284 LOGI("commonEventType %{public}s, currentUserId %{public}d, beforeUserId %{public}d.", commonEventType.c_str(),
4285 currentUserId, beforeUserId);
4286 DeviceNameManager::GetInstance().InitDeviceNameWhenUserSwitch(currentUserId, beforeUserId);
4287 MultipleUserConnector::SetAccountInfo(currentUserId, MultipleUserConnector::GetCurrentDMAccountInfo());
4288 DMCommTool::GetInstance()->StartCommonEvent(commonEventType,
4289 [this, commonEventType] () {
4290 DeviceManagerService::HandleAccountCommonEvent(commonEventType);
4291 });
4292 if (IsDMServiceAdapterResidentLoad()) {
4293 dmServiceImplExtResident_->HandleUserSwitchEvent(currentUserId, beforeUserId);
4294 } else {
4295 LOGW("HandleUserSwitchEvent fail, adapter instance not init or init failed.");
4296 }
4297 }
4298
GetHoOsTypeUdids(std::vector<std::string> & peerUdids)4299 void DeviceManagerService::GetHoOsTypeUdids(std::vector<std::string> &peerUdids)
4300 {
4301 std::vector<std::string> osTypeStrs;
4302 if (KVAdapterManager::GetInstance().GetAllOstypeData(osTypeStrs) != DM_OK) {
4303 LOGE("Get all ostype failed.");
4304 return;
4305 }
4306 for (const auto &item : osTypeStrs) {
4307 JsonObject osTypeObj(item);
4308 if (osTypeObj.IsDiscarded()) {
4309 LOGE("msg prase error.");
4310 continue;
4311 }
4312 if (!IsString(osTypeObj, PEER_UDID) || !IsInt32(osTypeObj, PEER_OSTYPE)) {
4313 LOGE("osTypeObj value invalid.");
4314 continue;
4315 }
4316 if (osTypeObj[PEER_OSTYPE].Get<int32_t>() == OLD_DM_HO_OSTYPE ||
4317 osTypeObj[PEER_OSTYPE].Get<int32_t>() == NEW_DM_HO_OSTYPE) {
4318 peerUdids.push_back(osTypeObj[PEER_UDID].Get<std::string>());
4319 }
4320 }
4321 }
4322
DeleteHoDevice(const std::vector<int32_t> & foreGroundUserIds,const std::vector<int32_t> & backGroundUserIds)4323 void DeviceManagerService::DeleteHoDevice(const std::vector<int32_t> &foreGroundUserIds,
4324 const std::vector<int32_t> &backGroundUserIds)
4325 {
4326 if (foreGroundUserIds.empty() || backGroundUserIds.empty()) {
4327 LOGE("backGroundUserIds %{public}s, foreGroundUserIds %{public}s.", GetIntegerList(backGroundUserIds).c_str(),
4328 GetIntegerList(foreGroundUserIds).c_str());
4329 return;
4330 }
4331 std::vector<std::string> peerUdids;
4332 GetHoOsTypeUdids(peerUdids);
4333 if (peerUdids.empty()) {
4334 LOGE("peerUdids empty.");
4335 return;
4336 }
4337 if (IsDMServiceAdapterResidentLoad()) {
4338 dmServiceImplExtResident_->AccountUserSwitched(MultipleUserConnector::GetCurrentAccountUserID(),
4339 MultipleUserConnector::GetOhosAccountId());
4340 }
4341 if (!IsDMServiceImplReady()) {
4342 LOGE("instance init failed.");
4343 return;
4344 }
4345 for (const auto &item : peerUdids) {
4346 dmServiceImpl_->DeleteHoDevice(item, foreGroundUserIds, backGroundUserIds);
4347 }
4348 }
4349
HandleAccountLogoutEventCallback(const std::string & commonEventType,int32_t currentUserId,int32_t beforeUserId)4350 void DeviceManagerService::HandleAccountLogoutEventCallback(const std::string &commonEventType, int32_t currentUserId,
4351 int32_t beforeUserId)
4352 {
4353 LOGI("commonEventType %{public}s, currentUserId %{public}d, beforeUserId %{public}d.", commonEventType.c_str(),
4354 currentUserId, beforeUserId);
4355 DeviceNameManager::GetInstance().InitDeviceNameWhenLogout();
4356 DMAccountInfo dmAccountInfo = MultipleUserConnector::GetAccountInfoByUserId(beforeUserId);
4357 if (dmAccountInfo.accountId.empty()) {
4358 LOGE("dmAccountInfo accountId empty.");
4359 return;
4360 }
4361 HandleAccountLogout(currentUserId, dmAccountInfo.accountId, dmAccountInfo.accountName);
4362 MultipleUserConnector::DeleteAccountInfoByUserId(currentUserId);
4363 MultipleUserConnector::SetAccountInfo(MultipleUserConnector::GetCurrentAccountUserID(),
4364 MultipleUserConnector::GetCurrentDMAccountInfo());
4365 }
4366 #endif
4367 } // namespace DistributedHardware
4368 } // namespace OHOS
4369