• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_crypto.h"
23 #include "dm_hidumper.h"
24 #include "dm_softbus_cache.h"
25 #include "parameter.h"
26 #include "permission_manager.h"
27 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
28 #include "common_event_support.h"
29 #include "datetime_ex.h"
30 #include "deviceprofile_connector.h"
31 #include "device_name_manager.h"
32 #include "dm_comm_tool.h"
33 #include "dm_random.h"
34 #include "dm_transport_msg.h"
35 #include "ipc_skeleton.h"
36 #include "iservice_registry.h"
37 #include "kv_adapter_manager.h"
38 #include "multiple_user_connector.h"
39 #include "relationship_sync_mgr.h"
40 #include "openssl/sha.h"
41 #if defined(SUPPORT_POWER_MANAGER)
42 #include "power_mgr_client.h"
43 #endif // SUPPORT_POWER_MANAGER
44 #if defined(SUPPORT_BLUETOOTH)
45 #include "softbus_publish.h"
46 #include "bluetooth_def.h"
47 #include "bluetooth_host.h"
48 #endif // SUPPORT_BLUETOOTH
49 #if defined(SUPPORT_WIFI)
50 #include "softbus_publish.h"
51 #include "wifi_device.h"
52 #include "wifi_msg.h"
53 #endif // SUPPORT_WIFI
54 #endif
55 
56 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
57 constexpr const char* LIB_IMPL_NAME = "libdevicemanagerserviceimpl.z.so";
58 using namespace OHOS::EventFwk;
59 #else
60 constexpr const char* LIB_IMPL_NAME = "libdevicemanagerserviceimpl.so";
61 #endif
62 constexpr const char* LIB_DM_ADAPTER_NAME = "libdevicemanageradapter.z.so";
63 constexpr const char* LIB_DM_RESIDENT_NAME = "libdevicemanagerresident.z.so";
64 
65 namespace OHOS {
66 namespace DistributedHardware {
67 DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService);
68 namespace {
69     const int32_t NORMAL = 0;
70     const int32_t SYSTEM_BASIC = 1;
71     const int32_t SYSTEM_CORE = 2;
72     constexpr const char *ALL_PKGNAME = "";
73     constexpr const char *NETWORKID = "NETWORK_ID";
74     constexpr uint32_t INVALIED_BIND_LEVEL = 0;
75     constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1;
76     const std::string USERID_CHECKSUM_NETWORKID_KEY = "networkId";
77     const std::string USERID_CHECKSUM_DISCOVER_TYPE_KEY = "discoverType";
78     constexpr uint32_t USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK = 0b0010;
79     constexpr uint32_t USERID_SYNC_DISCOVERY_TYPE_BLE_MASK = 0b0100;
80     const std::string DHARD_WARE_PKG_NAME = "ohos.dhardware";
81     const std::string USERID_CHECKSUM_ISCHANGE_KEY = "ischange";
82     constexpr const char* USER_SWITCH_BY_WIFI_TIMEOUT_TASK = "deviceManagerTimer:userSwitchByWifi";
83     constexpr const char* USER_STOP_BY_WIFI_TIMEOUT_TASK = "deviceManagerTimer:userStopByWifi";
84     const int32_t USER_SWITCH_BY_WIFI_TIMEOUT_S = 2;
85 }
86 
~DeviceManagerService()87 DeviceManagerService::~DeviceManagerService()
88 {
89     LOGI("DeviceManagerService destructor");
90     UnloadDMServiceImplSo();
91     UnloadDMServiceAdapterResident();
92 }
93 
Init()94 int32_t DeviceManagerService::Init()
95 {
96     InitSoftbusListener();
97     InitDMServiceListener();
98     LOGI("Init success, dm service single instance initialized.");
99     return DM_OK;
100 }
101 
InitSoftbusListener()102 int32_t DeviceManagerService::InitSoftbusListener()
103 {
104     if (softbusListener_ == nullptr) {
105         softbusListener_ = std::make_shared<SoftbusListener>();
106     }
107     SoftbusCache::GetInstance().UpdateDeviceInfoCache();
108     std::vector<DmDeviceInfo> onlineDeviceList;
109     SoftbusCache::GetInstance().GetDeviceInfoFromCache(onlineDeviceList);
110     if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) {
111         dmServiceImpl_->SaveOnlineDeviceInfo(onlineDeviceList);
112     }
113 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
114 #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI)
115     SubscribePublishCommonEvent();
116     QueryDependsSwitchState();
117 #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI
118     SubscribeDataShareCommonEvent();
119 #endif
120     LOGI("SoftbusListener init success.");
121     if (!IsDMServiceAdapterResidentLoad()) {
122         LOGE("load dm service resident failed.");
123     }
124     return DM_OK;
125 }
126 
InitHichainListener()127 void DeviceManagerService::InitHichainListener()
128 {
129     LOGI("DeviceManagerService::InitHichainListener Start.");
130     std::lock_guard<std::mutex> lock(hichainListenerLock_);
131     if (hichainListener_ == nullptr) {
132         hichainListener_ = std::make_shared<HichainListener>();
133     }
134     hichainListener_->RegisterDataChangeCb();
135 }
136 
137 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
138 #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI)
SubscribePublishCommonEvent()139 void DeviceManagerService::SubscribePublishCommonEvent()
140 {
141     LOGI("DeviceManagerServiceImpl::SubscribeCommonEvent");
142     if (publshCommonEventManager_ == nullptr) {
143         publshCommonEventManager_ = std::make_shared<DmPublishCommonEventManager>();
144     }
145     PublishEventCallback callback = [=](const auto &arg1, const auto &arg2, const auto &arg3) {
146         OHOS::DistributedHardware::PublishCommonEventCallback(arg1, arg2, arg3);
147     };
148     std::vector<std::string> PublishCommonEventVec;
149 #ifdef SUPPORT_BLUETOOTH
150     PublishCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE);
151 #endif // SUPPORT_BLUETOOTH
152 
153 #ifdef SUPPORT_WIFI
154     PublishCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_WIFI_POWER_STATE);
155 #endif // SUPPORT_WIFI
156     PublishCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
157     PublishCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
158     if (publshCommonEventManager_->SubscribePublishCommonEvent(PublishCommonEventVec, callback)) {
159         LOGI("subscribe ble and wifi and screen common event success");
160     }
161     return;
162 }
163 #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI
SubscribeDataShareCommonEvent()164 void DeviceManagerService::SubscribeDataShareCommonEvent()
165 {
166     LOGI("DeviceManagerServiceImpl::SubscribeDataShareCommonEvent");
167     if (dataShareCommonEventManager_ == nullptr) {
168         dataShareCommonEventManager_ = std::make_shared<DmDataShareCommonEventManager>();
169     }
170     DataShareEventCallback callback = [=](const auto &arg1) {
171         if (arg1 == CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY) {
172             DeviceNameManager::GetInstance().DataShareReady();
173         }
174         if (arg1 == CommonEventSupport::COMMON_EVENT_LOCALE_CHANGED) {
175             DeviceNameManager::GetInstance().InitDeviceNameWhenLanguageOrRegionChanged();
176         }
177     };
178     std::vector<std::string> commonEventVec;
179     commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY);
180     commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_LOCALE_CHANGED);
181     if (dataShareCommonEventManager_->SubscribeDataShareCommonEvent(commonEventVec, callback)) {
182         LOGI("subscribe datashare common event success");
183     }
184 }
185 #endif
186 
187 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
188 #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI)
QueryDependsSwitchState()189 void DeviceManagerService::QueryDependsSwitchState()
190 {
191     LOGI("DeviceManagerService::QueryDependsSwitchState start.");
192     std::shared_ptr<DmPublishEventSubscriber> publishSubScriber = publshCommonEventManager_->GetSubscriber();
193     CHECK_NULL_VOID(publishSubScriber);
194     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
195     CHECK_NULL_VOID(samgr);
196 #ifdef SUPPORT_BLUETOOTH
197     if (samgr->CheckSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID) == nullptr) {
198         publishSubScriber->SetBluetoothState(static_cast<int32_t>(Bluetooth::BTStateID::STATE_TURN_OFF));
199     } else {
200         if (Bluetooth::BluetoothHost::GetDefaultHost().IsBleEnabled()) {
201             publishSubScriber->SetBluetoothState(static_cast<int32_t>(Bluetooth::BTStateID::STATE_TURN_ON));
202         } else {
203             publishSubScriber->SetBluetoothState(static_cast<int32_t>(Bluetooth::BTStateID::STATE_TURN_OFF));
204         }
205     }
206 #endif // SUPPORT_BLUETOOTH
207 
208 #ifdef SUPPORT_WIFI
209     if (samgr->CheckSystemAbility(WIFI_DEVICE_SYS_ABILITY_ID) == nullptr) {
210         publishSubScriber->SetWifiState(static_cast<int32_t>(OHOS::Wifi::WifiState::DISABLED));
211     } else {
212         bool isWifiActive = false;
213         auto wifiMgr = Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID);
214         CHECK_NULL_VOID(wifiMgr);
215         wifiMgr->IsWifiActive(isWifiActive);
216         if (isWifiActive) {
217             publishSubScriber->SetWifiState(static_cast<int32_t>(OHOS::Wifi::WifiState::ENABLED));
218         } else {
219             publishSubScriber->SetWifiState(static_cast<int32_t>(OHOS::Wifi::WifiState::DISABLED));
220         }
221     }
222 #endif // SUPPORT_WIFI
223 
224 #ifdef SUPPORT_POWER_MANAGER
225     if (samgr->CheckSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr) {
226         publishSubScriber->SetScreenState(DM_SCREEN_OFF);
227     } else {
228         if (OHOS::PowerMgr::PowerMgrClient::GetInstance().IsScreenOn()) {
229             publishSubScriber->SetScreenState(DM_SCREEN_ON);
230         } else {
231             publishSubScriber->SetScreenState(DM_SCREEN_OFF);
232         }
233     }
234 #else
235     publishSubScriber->SetScreenState(DM_SCREEN_ON);
236 #endif // SUPPORT_POWER_MANAGER
237     OHOS::DistributedHardware::PublishCommonEventCallback(publishSubScriber->GetBluetoothState(),
238         publishSubScriber->GetWifiState(), publishSubScriber->GetScreenState());
239 }
240 #endif // SUPPORT_BLUETOOTH  SUPPORT_WIFI
241 #endif
242 
UninitSoftbusListener()243 void DeviceManagerService::UninitSoftbusListener()
244 {
245     CHECK_NULL_VOID(softbusListener_);
246     softbusListener_->DeleteCacheDeviceInfo();
247     softbusListener_ = nullptr;
248     LOGI("SoftbusListener uninit.");
249 }
250 
InitDMServiceListener()251 int32_t DeviceManagerService::InitDMServiceListener()
252 {
253     if (listener_ == nullptr) {
254         listener_ = std::make_shared<DeviceManagerServiceListener>();
255     }
256     if (advertiseMgr_ == nullptr) {
257         advertiseMgr_ = std::make_shared<AdvertiseManager>(softbusListener_);
258     }
259     if (discoveryMgr_ == nullptr) {
260         discoveryMgr_ = std::make_shared<DiscoveryManager>(softbusListener_, listener_);
261     }
262     if (pinHolder_ == nullptr) {
263         pinHolder_ = std::make_shared<PinHolder>(listener_);
264     }
265 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
266     DMCommTool::GetInstance()->Init();
267     int32_t currentUserId = MultipleUserConnector::GetFirstForegroundUserId();
268     if (IsPC() && !MultipleUserConnector::IsUserUnlocked(currentUserId)) {
269         HandleUserStopEvent(currentUserId);
270     }
271 #endif
272     LOGI("Init success.");
273     return DM_OK;
274 }
275 
UninitDMServiceListener()276 void DeviceManagerService::UninitDMServiceListener()
277 {
278     listener_ = nullptr;
279     advertiseMgr_ = nullptr;
280     discoveryMgr_ = nullptr;
281 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
282     DeviceNameManager::GetInstance().UnInit();
283     KVAdapterManager::GetInstance().UnInit();
284 #endif
285     LOGI("Uninit.");
286 }
287 
RegisterCallerAppId(const std::string & pkgName)288 void DeviceManagerService::RegisterCallerAppId(const std::string &pkgName)
289 {
290     AppManager::GetInstance().RegisterCallerAppId(pkgName);
291 }
292 
UnRegisterCallerAppId(const std::string & pkgName)293 void DeviceManagerService::UnRegisterCallerAppId(const std::string &pkgName)
294 {
295     AppManager::GetInstance().UnRegisterCallerAppId(pkgName);
296 }
297 
GetTrustedDeviceList(const std::string & pkgName,const std::string & extra,std::vector<DmDeviceInfo> & deviceList)298 int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra,
299                                                    std::vector<DmDeviceInfo> &deviceList)
300 {
301     (void)extra;
302     LOGI("Begin for pkgName = %{public}s.", pkgName.c_str());
303     if (pkgName.empty()) {
304         LOGE("Invalid parameter, pkgName is empty.");
305         return ERR_DM_INPUT_PARA_INVALID;
306     }
307     bool isOnlyShowNetworkId = !(PermissionManager::GetInstance().CheckPermission() ||
308         PermissionManager::GetInstance().CheckNewPermission());
309     std::vector<DmDeviceInfo> onlineDeviceList;
310     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
311     int32_t ret = softbusListener_->GetTrustedDeviceList(onlineDeviceList);
312     if (ret != DM_OK) {
313         LOGE("GetTrustedDeviceList failed");
314         return ret;
315     }
316     if (isOnlyShowNetworkId && !onlineDeviceList.empty()) {
317         for (auto item : onlineDeviceList) {
318             DmDeviceInfo tempInfo;
319             if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, item.networkId, sizeof(item.networkId)) != 0) {
320                 LOGE("get networkId: %{public}s failed", GetAnonyString(item.networkId).c_str());
321                 return ERR_DM_SECURITY_FUNC_FAILED;
322             }
323             deviceList.push_back(tempInfo);
324         }
325         return DM_OK;
326     }
327     if (!onlineDeviceList.empty() && IsDMServiceImplReady()) {
328         std::unordered_map<std::string, DmAuthForm> udidMap;
329         if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName)) {
330             udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME));
331         } else {
332             udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName);
333         }
334         for (auto item : onlineDeviceList) {
335 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
336             ConvertUdidHashToAnoyDeviceId(item);
337 #endif
338             std::string udid = "";
339             SoftbusListener::GetUdidByNetworkId(item.networkId, udid);
340             if (udidMap.find(udid) != udidMap.end()) {
341                 item.authForm = udidMap[udid];
342                 deviceList.push_back(item);
343             }
344         }
345     }
346     return DM_OK;
347 }
348 
GetAllTrustedDeviceList(const std::string & pkgName,const std::string & extra,std::vector<DmDeviceInfo> & deviceList)349 int32_t DeviceManagerService::GetAllTrustedDeviceList(const std::string &pkgName, const std::string &extra,
350                                                       std::vector<DmDeviceInfo> &deviceList)
351 {
352     (void)extra;
353     LOGI("Begin for pkgName = %{public}s.", pkgName.c_str());
354     if (pkgName.empty()) {
355         LOGE("Invalid parameter, pkgName or extra is empty.");
356         return ERR_DM_INPUT_PARA_INVALID;
357     }
358     if (!PermissionManager::GetInstance().CheckNewPermission()) {
359         LOGE("The caller: %{public}s does not have permission to call GetAllTrustedDeviceList.", pkgName.c_str());
360         return ERR_DM_NO_PERMISSION;
361     }
362     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
363     int32_t ret = softbusListener_->GetAllTrustedDeviceList(pkgName, extra, deviceList);
364     if (ret != DM_OK) {
365         LOGE("GetAllTrustedDeviceList failed");
366         return ret;
367     }
368     return DM_OK;
369 }
370 
ShiftLNNGear(const std::string & pkgName,const std::string & callerId,bool isRefresh,bool isWakeUp)371 int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std::string &callerId, bool isRefresh,
372                                            bool isWakeUp)
373 {
374     LOGD("Begin for pkgName = %{public}s, callerId = %{public}s, isRefresh ="
375         "%{public}d, isWakeUp = %{public}d", pkgName.c_str(), GetAnonyString(callerId).c_str(), isRefresh, isWakeUp);
376     if (!PermissionManager::GetInstance().CheckNewPermission()) {
377         LOGE("The caller does not have permission to call ShiftLNNGear, pkgName = %{public}s", pkgName.c_str());
378         return ERR_DM_NO_PERMISSION;
379     }
380     if (pkgName.empty() || callerId.empty()) {
381         LOGE("Invalid parameter, parameter is empty.");
382         return ERR_DM_INPUT_PARA_INVALID;
383     }
384     if (isRefresh) {
385         CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
386         int32_t ret = softbusListener_->ShiftLNNGear(isWakeUp, callerId);
387         if (ret != DM_OK) {
388             LOGE("ShiftLNNGear error, failed ret: %{public}d", ret);
389             return ret;
390         }
391     }
392     return DM_OK;
393 }
394 
GetDeviceInfo(const std::string & networkId,DmDeviceInfo & info)395 int32_t DeviceManagerService::GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info)
396 {
397     LOGI("Begin networkId %{public}s.", GetAnonyString(networkId).c_str());
398     if (!PermissionManager::GetInstance().CheckPermission() &&
399         !PermissionManager::GetInstance().CheckNewPermission()) {
400         LOGE("The caller does not have permission to call GetDeviceInfo.");
401         return ERR_DM_NO_PERMISSION;
402     }
403     if (networkId.empty()) {
404         LOGE("Invalid parameter, networkId is empty.");
405         return ERR_DM_INPUT_PARA_INVALID;
406     }
407     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
408     std::string peerDeviceId = "";
409     SoftbusListener::GetUdidByNetworkId(networkId.c_str(), peerDeviceId);
410     int32_t ret = DM_OK;
411     if (!IsDMServiceImplReady()) {
412         LOGE("GetDeviceInfo failed, instance not init or init failed.");
413         return ERR_DM_NOT_INIT;
414     }
415     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
416     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
417     std::string localUdid = static_cast<std::string>(localDeviceId);
418     if (localUdid == peerDeviceId) {
419         ret = softbusListener_->GetDeviceInfo(networkId, info);
420         if (ret != DM_OK) {
421             LOGE("Get DeviceInfo By NetworkId failed, ret : %{public}d", ret);
422         }
423         return ret;
424     }
425     int32_t permissionRet = dmServiceImpl_->CheckDeviceInfoPermission(localUdid, peerDeviceId);
426     if (permissionRet != DM_OK) {
427         std::string processName = "";
428         if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
429             LOGE("Get caller process name failed.");
430             return ret;
431         }
432         if (!PermissionManager::GetInstance().CheckProcessNameValidOnGetDeviceInfo(processName)) {
433             LOGE("The caller: %{public}s is not in white list.", processName.c_str());
434             return ret;
435         }
436     }
437     ret = softbusListener_->GetDeviceInfo(networkId, info);
438     if (ret != DM_OK) {
439         LOGE("Get DeviceInfo By NetworkId failed, ret : %{public}d", ret);
440     }
441     return ret;
442 }
443 
GetLocalDeviceInfo(DmDeviceInfo & info)444 int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info)
445 {
446     LOGD("Begin.");
447     bool isOnlyShowNetworkId = false;
448     if (!PermissionManager::GetInstance().CheckNewPermission()) {
449         LOGE("The caller does not have permission to call GetLocalDeviceInfo.");
450         isOnlyShowNetworkId = true;
451     }
452     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
453     int32_t ret = softbusListener_->GetLocalDeviceInfo(info);
454     if (ret != DM_OK) {
455         LOGE("GetLocalDeviceInfo failed");
456         return ret;
457     }
458     if (isOnlyShowNetworkId) {
459         DmDeviceInfo tempInfo;
460         if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, info.networkId, sizeof(info.networkId)) != 0) {
461             LOGE("get networkId: %{public}s failed", GetAnonyString(info.networkId).c_str());
462             return ERR_DM_FAILED;
463         }
464         info = tempInfo;
465         return DM_OK;
466     }
467     if (localDeviceId_.empty()) {
468         char localDeviceId[DEVICE_UUID_LENGTH] = {0};
469         char udidHash[DEVICE_UUID_LENGTH] = {0};
470         GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
471         if (Crypto::GetUdidHash(localDeviceId, reinterpret_cast<uint8_t *>(udidHash)) == DM_OK) {
472             localDeviceId_ = udidHash;
473         }
474     }
475 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
476     std::string udidHashTemp = "";
477     if (ConvertUdidHashToAnoyDeviceId(localDeviceId_, udidHashTemp) == DM_OK) {
478         if (memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) {
479             LOGE("GetLocalDeviceInfo memset_s failed.");
480             return ERR_DM_FAILED;
481         }
482         if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) {
483             LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str());
484             return ERR_DM_FAILED;
485         }
486         return DM_OK;
487     }
488 #endif
489     if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, localDeviceId_.c_str(), localDeviceId_.length()) != 0) {
490         LOGE("get deviceId: %{public}s failed", GetAnonyString(localDeviceId_).c_str());
491         return ERR_DM_FAILED;
492     }
493     return DM_OK;
494 }
495 
GetUdidByNetworkId(const std::string & pkgName,const std::string & netWorkId,std::string & udid)496 int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId,
497                                                  std::string &udid)
498 {
499     if (!PermissionManager::GetInstance().CheckPermission()) {
500         LOGE("The caller: %{public}s does not have permission to call GetUdidByNetworkId.", pkgName.c_str());
501         return ERR_DM_NO_PERMISSION;
502     }
503     if (pkgName.empty() || netWorkId.empty()) {
504         LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(),
505             GetAnonyString(netWorkId).c_str());
506         return ERR_DM_INPUT_PARA_INVALID;
507     }
508     return SoftbusListener::GetUdidByNetworkId(netWorkId.c_str(), udid);
509 }
510 
GetUuidByNetworkId(const std::string & pkgName,const std::string & netWorkId,std::string & uuid)511 int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId,
512                                                  std::string &uuid)
513 {
514     if (!PermissionManager::GetInstance().CheckPermission()) {
515         LOGE("The caller: %{public}s does not have permission to call GetUuidByNetworkId.", pkgName.c_str());
516         return ERR_DM_NO_PERMISSION;
517     }
518     if (pkgName.empty() || netWorkId.empty()) {
519         LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(),
520             GetAnonyString(netWorkId).c_str());
521         return ERR_DM_INPUT_PARA_INVALID;
522     }
523     return SoftbusListener::GetUuidByNetworkId(netWorkId.c_str(), uuid);
524 }
525 
PublishDeviceDiscovery(const std::string & pkgName,const DmPublishInfo & publishInfo)526 int32_t DeviceManagerService::PublishDeviceDiscovery(const std::string &pkgName, const DmPublishInfo &publishInfo)
527 {
528     if (!PermissionManager::GetInstance().CheckPermission()) {
529         LOGE("The caller: %{public}s does not have permission to call PublishDeviceDiscovery.", pkgName.c_str());
530         return ERR_DM_NO_PERMISSION;
531     }
532     LOGI("Begin for pkgName = %{public}s", pkgName.c_str());
533     if (pkgName.empty()) {
534         LOGE("Invalid parameter, pkgName is empty.");
535         return ERR_DM_INPUT_PARA_INVALID;
536     }
537 
538     std::map<std::string, std::string> advertiseParam;
539     advertiseParam.insert(std::pair<std::string, std::string>(PARAM_KEY_PUBLISH_ID,
540         std::to_string(publishInfo.publishId)));
541     CHECK_NULL_RETURN(advertiseMgr_, ERR_DM_POINT_NULL);
542     return advertiseMgr_->StartAdvertising(pkgName, advertiseParam);
543 }
544 
UnPublishDeviceDiscovery(const std::string & pkgName,int32_t publishId)545 int32_t DeviceManagerService::UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId)
546 {
547     if (!PermissionManager::GetInstance().CheckPermission()) {
548         LOGE("The caller: %{public}s does not have permission to call UnPublishDeviceDiscovery.", pkgName.c_str());
549         return ERR_DM_NO_PERMISSION;
550     }
551     if (pkgName.empty()) {
552         LOGE("Invalid parameter, pkgName is empty.");
553         return ERR_DM_INPUT_PARA_INVALID;
554     }
555     CHECK_NULL_RETURN(advertiseMgr_, ERR_DM_POINT_NULL);
556     return advertiseMgr_->StopAdvertising(pkgName, publishId);
557 }
558 
AuthenticateDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)559 int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType,
560                                                  const std::string &deviceId, const std::string &extra)
561 {
562     if (!PermissionManager::GetInstance().CheckPermission()) {
563         LOGE("The caller: %{public}s does not have permission to call AuthenticateDevice.", pkgName.c_str());
564         return ERR_DM_NO_PERMISSION;
565     }
566     if (pkgName.empty() || deviceId.empty()) {
567         LOGE("DeviceManagerService::AuthenticateDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
568         return ERR_DM_INPUT_PARA_INVALID;
569     }
570     if (!IsDMServiceImplReady()) {
571         LOGE("AuthenticateDevice failed, instance not init or init failed.");
572         return ERR_DM_NOT_INIT;
573     }
574     std::string queryDeviceId = deviceId;
575 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
576     std::string udidHash = "";
577     if (GetUdidHashByAnoyDeviceId(deviceId, udidHash) == DM_OK) {
578         queryDeviceId = udidHash;
579     }
580 #endif
581     PeerTargetId targetId;
582     ConnectionAddrType addrType;
583     int32_t ret = SoftbusListener::GetTargetInfoFromCache(queryDeviceId, targetId, addrType);
584     if (ret != DM_OK) {
585         LOGE("AuthenticateDevice failed, cannot get target info from cached discovered device map.");
586         return ERR_DM_BIND_INPUT_PARA_INVALID;
587     }
588     std::map<std::string, std::string> bindParam;
589     bindParam.insert(std::pair<std::string, std::string>(PARAM_KEY_AUTH_TYPE, std::to_string(authType)));
590     bindParam.insert(std::pair<std::string, std::string>(PARAM_KEY_BIND_EXTRA_DATA, extra));
591     bindParam.insert(std::pair<std::string, std::string>(PARAM_KEY_CONN_ADDR_TYPE, std::to_string(addrType)));
592     return dmServiceImpl_->BindTarget(pkgName, targetId, bindParam);
593 }
594 
UnAuthenticateDevice(const std::string & pkgName,const std::string & networkId)595 int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId)
596 {
597     if (!PermissionManager::GetInstance().CheckPermission()) {
598         LOGE("The caller: %{public}s does not have permission to call UnAuthenticateDevice.", pkgName.c_str());
599         return ERR_DM_NO_PERMISSION;
600     }
601     LOGI("Begin for pkgName = %{public}s, networkId = %{public}s",
602         pkgName.c_str(), GetAnonyString(networkId).c_str());
603     if (pkgName.empty() || networkId.empty()) {
604         LOGE("DeviceManagerService::UnAuthenticateDevice error: Invalid parameter, pkgName: %{public}s",
605             pkgName.c_str());
606         return ERR_DM_INPUT_PARA_INVALID;
607     }
608     std::string udid = "";
609     if (SoftbusListener::GetUdidByNetworkId(networkId.c_str(), udid) != DM_OK) {
610         LOGE("UnAuthenticateDevice GetUdidByNetworkId error: udid: %{public}s", GetAnonyString(udid).c_str());
611         return ERR_DM_FAILED;
612     }
613     char localUdid[DEVICE_UUID_LENGTH] = {0};
614     GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
615     if (!IsDMServiceImplReady()) {
616         LOGE("UnAuthenticateDevice failed, instance not init or init failed.");
617         return ERR_DM_NOT_INIT;
618     }
619     uint64_t tokenId = 0;
620     int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);
621     LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel);
622     if (bindLevel == INVALIED_BIND_LEVEL) {
623         LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel);
624         return ERR_DM_FAILED;
625     }
626     if (dmServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel) != DM_OK) {
627         LOGE("dmServiceImpl_ UnAuthenticateDevice failed.");
628         return ERR_DM_FAILED;
629     }
630 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
631     std::vector<std::string> peerUdids;
632     peerUdids.emplace_back(udid);
633     SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId, bindLevel);
634 #endif
635     return DM_OK;
636 }
637 
StopAuthenticateDevice(const std::string & pkgName)638 int32_t DeviceManagerService::StopAuthenticateDevice(const std::string &pkgName)
639 {
640     if (!PermissionManager::GetInstance().CheckPermission()) {
641         LOGE("The caller: %{public}s does not have permission to call StopAuthenticateDevice.", pkgName.c_str());
642         return ERR_DM_NO_PERMISSION;
643     }
644     if (pkgName.empty()) {
645         LOGE("DeviceManagerService::StopAuthenticateDevice error: Invalid parameter, pkgName: %{public}s",
646             pkgName.c_str());
647         return ERR_DM_INPUT_PARA_INVALID;
648     }
649     LOGI("Begin for pkgName = %{public}s", pkgName.c_str());
650     if (!IsDMServiceImplReady()) {
651         LOGE("StopAuthenticateDevice failed, instance not init or init failed.");
652         return ERR_DM_NOT_INIT;
653     }
654     if (dmServiceImpl_->StopAuthenticateDevice(pkgName) != DM_OK) {
655         LOGE("dmServiceImpl_ StopAuthenticateDevice failed.");
656         return ERR_DM_FAILED;
657     }
658     return DM_OK;
659 }
660 
BindDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & bindParam)661 int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId,
662     const std::string &bindParam)
663 {
664     if (!PermissionManager::GetInstance().CheckNewPermission()) {
665         LOGE("The caller does not have permission to call BindDevice.");
666         return ERR_DM_NO_PERMISSION;
667     }
668     if (pkgName.empty() || deviceId.empty()) {
669         LOGE("DeviceManagerService::BindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
670         return ERR_DM_INPUT_PARA_INVALID;
671     }
672     if (!IsDMServiceImplReady()) {
673         LOGE("BindDevice failed, instance not init or init failed.");
674         return ERR_DM_NOT_INIT;
675     }
676     std::string queryDeviceId = deviceId;
677 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
678     std::string udidHash = "";
679     if (GetUdidHashByAnoyDeviceId(deviceId, udidHash) == DM_OK) {
680         queryDeviceId = udidHash;
681     }
682 #endif
683     PeerTargetId targetId;
684     std::map<std::string, std::string> bindParamMap;
685     std::string bindParamStr = bindParam;
686     int32_t actionId = 0;
687     SoftbusListener::GetActionId(queryDeviceId, actionId);
688     if (actionId > 0) {
689         targetId.deviceId = queryDeviceId;
690         AddHmlInfoToBindParam(actionId, bindParamStr);
691     } else {
692         ConnectionAddrType addrType;
693         int32_t ret = SoftbusListener::GetTargetInfoFromCache(queryDeviceId, targetId, addrType);
694         if (ret != DM_OK) {
695             LOGE("BindDevice failed, cannot get target info from cached discovered device map.");
696             return ERR_DM_BIND_INPUT_PARA_INVALID;
697         }
698         bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_CONN_ADDR_TYPE, std::to_string(addrType)));
699     }
700     bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_AUTH_TYPE, std::to_string(authType)));
701     bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_BIND_EXTRA_DATA, bindParamStr));
702     return dmServiceImpl_->BindTarget(pkgName, targetId, bindParamMap);
703 }
704 
UnBindDevice(const std::string & pkgName,const std::string & udidHash)705 int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std::string &udidHash)
706 {
707     if (!PermissionManager::GetInstance().CheckNewPermission()) {
708         LOGE("The caller does not have permission to call UnBindDevice.");
709         return ERR_DM_NO_PERMISSION;
710     }
711     LOGI("Begin for pkgName = %{public}s, udidHash = %{public}s", pkgName.c_str(), GetAnonyString(udidHash).c_str());
712     if (pkgName.empty() || udidHash.empty()) {
713         LOGE("DeviceManagerService::UnBindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
714         return ERR_DM_INPUT_PARA_INVALID;
715     }
716     if (!IsDMServiceImplReady()) {
717         LOGE("UnBindDevice failed, instance not init or init failed.");
718         return ERR_DM_NOT_INIT;
719     }
720     std::string realDeviceId = udidHash;
721 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
722     std::string udidHashTemp = "";
723     if (GetUdidHashByAnoyDeviceId(udidHash, udidHashTemp) == DM_OK) {
724         realDeviceId = udidHashTemp;
725     }
726 #endif
727     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
728     std::string udid = "";
729     if (softbusListener_->GetUdidFromDp(realDeviceId, udid) != DM_OK) {
730         LOGE("Get udid by udidhash failed.");
731         return ERR_DM_FAILED;
732     }
733     char localUdid[DEVICE_UUID_LENGTH] = {0};
734     GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
735     uint64_t tokenId = 0;
736     int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);
737     LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel);
738     if (bindLevel == INVALIED_BIND_LEVEL) {
739         LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel);
740         return ERR_DM_FAILED;
741     }
742     if (dmServiceImpl_->UnBindDevice(pkgName, udid, bindLevel) != DM_OK) {
743         LOGE("dmServiceImpl_ UnBindDevice failed.");
744         return ERR_DM_FAILED;
745     }
746 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
747     std::vector<std::string> peerUdids;
748     peerUdids.emplace_back(udid);
749     SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId, bindLevel);
750 #endif
751     return DM_OK;
752 }
753 
UnBindDevice(const std::string & pkgName,const std::string & udidHash,const std::string & extra)754 int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std::string &udidHash,
755     const std::string &extra)
756 {
757     if (!PermissionManager::GetInstance().CheckNewPermission()) {
758         LOGE("The caller does not have permission to call UnBindDevice.");
759         return ERR_DM_NO_PERMISSION;
760     }
761     LOGI("Begin for pkgName = %{public}s, udidHash = %{public}s", pkgName.c_str(), GetAnonyString(udidHash).c_str());
762     if (pkgName.empty() || udidHash.empty()) {
763         LOGE("DeviceManagerService::UnBindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
764         return ERR_DM_INPUT_PARA_INVALID;
765     }
766     if (!IsDMServiceImplReady()) {
767         LOGE("UnBindDevice failed, instance not init or init failed.");
768         return ERR_DM_NOT_INIT;
769     }
770     std::string realDeviceId = udidHash;
771 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
772     std::string udidHashTemp = "";
773     if (GetUdidHashByAnoyDeviceId(udidHash, udidHashTemp) == DM_OK) {
774         realDeviceId = udidHashTemp;
775     }
776 #endif
777     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
778     std::string udid = "";
779     if (softbusListener_->GetUdidFromDp(realDeviceId, udid) != DM_OK) {
780         LOGE("Get udid by udidhash failed.");
781         return ERR_DM_FAILED;
782     }
783     char localUdid[DEVICE_UUID_LENGTH] = {0};
784     GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
785     uint64_t tokenId = 0;
786     int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);
787     LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel);
788     if (bindLevel == INVALIED_BIND_LEVEL) {
789         LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel);
790         return ERR_DM_FAILED;
791     }
792     [[maybe_unused]] uint64_t peerTokenId = dmServiceImpl_->GetTokenIdByNameAndDeviceId(extra, udid);
793     if (dmServiceImpl_->UnBindDevice(pkgName, udid, bindLevel, extra) != DM_OK) {
794         LOGE("dmServiceImpl_ UnBindDevice failed.");
795         return ERR_DM_FAILED;
796     }
797 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
798     std::vector<std::string> peerUdids;
799     peerUdids.emplace_back(udid);
800     SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId,
801         bindLevel, peerTokenId);
802 #endif
803     return DM_OK;
804 }
805 
SetUserOperation(std::string & pkgName,int32_t action,const std::string & params)806 int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action, const std::string &params)
807 {
808     if (!PermissionManager::GetInstance().CheckPermission()) {
809         LOGE("The caller: %{public}s does not have permission to call SetUserOperation.", pkgName.c_str());
810         return ERR_DM_NO_PERMISSION;
811     }
812     if (pkgName.empty() || params.empty()) {
813         LOGE("DeviceManagerService::SetUserOperation error: Invalid parameter, pkgName: %{public}s", pkgName.c_str());
814         return ERR_DM_INPUT_PARA_INVALID;
815     }
816     if (IsDMServiceAdapterSoLoaded()) {
817         dmServiceImplExtResident_->ReplyUiAction(pkgName, action, params);
818     }
819     if (!IsDMServiceImplReady()) {
820         LOGE("SetUserOperation failed, instance not init or init failed.");
821         return ERR_DM_NOT_INIT;
822     }
823     return dmServiceImpl_->SetUserOperation(pkgName, action, params);
824 }
825 
HandleDeviceStatusChange(DmDeviceState devState,DmDeviceInfo & devInfo)826 void DeviceManagerService::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo)
827 {
828     LOGI("DeviceManagerService::HandleDeviceStatusChange start, devState = %{public}d", devState);
829     if (IsDMServiceImplReady()) {
830         dmServiceImpl_->HandleDeviceStatusChange(devState, devInfo);
831     }
832     if (IsDMServiceAdapterResidentLoad()) {
833         dmServiceImplExtResident_->HandleDeviceStatusChange(devState, devInfo);
834     }
835 }
836 
OnSessionOpened(int sessionId,int result)837 int DeviceManagerService::OnSessionOpened(int sessionId, int result)
838 {
839     if (!IsDMServiceImplReady()) {
840         LOGE("OnSessionOpened failed, instance not init or init failed.");
841         return ERR_DM_NOT_INIT;
842     }
843     return dmServiceImpl_->OnSessionOpened(sessionId, result);
844 }
845 
OnSessionClosed(int sessionId)846 void DeviceManagerService::OnSessionClosed(int sessionId)
847 {
848     if (!IsDMServiceImplReady()) {
849         LOGE("OnSessionClosed failed, instance not init or init failed.");
850         return;
851     }
852     dmServiceImpl_->OnSessionClosed(sessionId);
853 }
854 
OnBytesReceived(int sessionId,const void * data,unsigned int dataLen)855 void DeviceManagerService::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen)
856 {
857     if (!IsDMServiceImplReady()) {
858         LOGE("OnBytesReceived failed, instance not init or init failed.");
859         return;
860     }
861     dmServiceImpl_->OnBytesReceived(sessionId, data, dataLen);
862 }
863 
OnPinHolderSessionOpened(int sessionId,int result)864 int DeviceManagerService::OnPinHolderSessionOpened(int sessionId, int result)
865 {
866     LOGI("In");
867     return PinHolderSession::OnSessionOpened(sessionId, result);
868 }
869 
OnPinHolderSessionClosed(int sessionId)870 void DeviceManagerService::OnPinHolderSessionClosed(int sessionId)
871 {
872     LOGI("In");
873     PinHolderSession::OnSessionClosed(sessionId);
874 }
875 
OnPinHolderBytesReceived(int sessionId,const void * data,unsigned int dataLen)876 void DeviceManagerService::OnPinHolderBytesReceived(int sessionId, const void *data, unsigned int dataLen)
877 {
878     LOGI("In");
879     PinHolderSession::OnBytesReceived(sessionId, data, dataLen);
880 }
881 
RequestCredential(const std::string & reqJsonStr,std::string & returnJsonStr)882 int32_t DeviceManagerService::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr)
883 {
884     if (!PermissionManager::GetInstance().CheckPermission()) {
885         LOGE("The caller does not have permission to call RequestCredential.");
886         return ERR_DM_NO_PERMISSION;
887     }
888     if (!IsDMServiceImplReady()) {
889         LOGE("RequestCredential failed, instance not init or init failed.");
890         return ERR_DM_NOT_INIT;
891     }
892     return dmServiceImpl_->RequestCredential(reqJsonStr, returnJsonStr);
893 }
894 
ImportCredential(const std::string & pkgName,const std::string & credentialInfo)895 int32_t DeviceManagerService::ImportCredential(const std::string &pkgName, const std::string &credentialInfo)
896 {
897     if (!PermissionManager::GetInstance().CheckPermission()) {
898         LOGE("The caller: %{public}s does not have permission to call ImportCredential.",
899             pkgName.c_str());
900         return ERR_DM_NO_PERMISSION;
901     }
902     if (!IsDMServiceImplReady()) {
903         LOGE("ImportCredential failed, instance not init or init failed.");
904         return ERR_DM_NOT_INIT;
905     }
906     return dmServiceImpl_->ImportCredential(pkgName, credentialInfo);
907 }
908 
DeleteCredential(const std::string & pkgName,const std::string & deleteInfo)909 int32_t DeviceManagerService::DeleteCredential(const std::string &pkgName, const std::string &deleteInfo)
910 {
911     if (!PermissionManager::GetInstance().CheckPermission()) {
912         LOGE("The caller: %{public}s does not have permission to call DeleteCredential.",
913             pkgName.c_str());
914         return ERR_DM_NO_PERMISSION;
915     }
916     if (!IsDMServiceImplReady()) {
917         LOGE("DeleteCredential failed, instance not init or init failed.");
918         return ERR_DM_NOT_INIT;
919     }
920     return dmServiceImpl_->DeleteCredential(pkgName, deleteInfo);
921 }
922 
MineRequestCredential(const std::string & pkgName,std::string & returnJsonStr)923 int32_t DeviceManagerService::MineRequestCredential(const std::string &pkgName, std::string &returnJsonStr)
924 {
925     if (!PermissionManager::GetInstance().CheckPermission()) {
926         LOGE("The caller does not have permission to call RequestCredential.");
927         return ERR_DM_NO_PERMISSION;
928     }
929     if (!IsDMServiceImplReady()) {
930         LOGE("RequestCredential failed, instance not init or init failed.");
931         return ERR_DM_NOT_INIT;
932     }
933     return dmServiceImpl_->MineRequestCredential(pkgName, returnJsonStr);
934 }
935 
CheckCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)936 int32_t DeviceManagerService::CheckCredential(const std::string &pkgName, const std::string &reqJsonStr,
937     std::string &returnJsonStr)
938 {
939     if (!PermissionManager::GetInstance().CheckPermission()) {
940         LOGE("The caller: %{public}s does not have permission to call CheckCredential.",
941             pkgName.c_str());
942         return ERR_DM_NO_PERMISSION;
943     }
944     if (!IsDMServiceImplReady()) {
945         LOGE("CheckCredential failed, instance not init or init failed.");
946         return ERR_DM_NOT_INIT;
947     }
948     return dmServiceImpl_->CheckCredential(pkgName, reqJsonStr, returnJsonStr);
949 }
950 
ImportCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)951 int32_t DeviceManagerService::ImportCredential(const std::string &pkgName, const std::string &reqJsonStr,
952     std::string &returnJsonStr)
953 {
954     if (!PermissionManager::GetInstance().CheckPermission()) {
955         LOGE("The caller: %{public}s does not have permission to call ImportCredential.",
956             pkgName.c_str());
957         return ERR_DM_NO_PERMISSION;
958     }
959     if (!IsDMServiceImplReady()) {
960         LOGE("ImportCredential failed, instance not init or init failed.");
961         return ERR_DM_NOT_INIT;
962     }
963     return dmServiceImpl_->ImportCredential(pkgName, reqJsonStr, returnJsonStr);
964 }
965 
DeleteCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)966 int32_t DeviceManagerService::DeleteCredential(const std::string &pkgName, const std::string &reqJsonStr,
967     std::string &returnJsonStr)
968 {
969     if (!PermissionManager::GetInstance().CheckPermission()) {
970         LOGE("The caller: %{public}s does not have permission to call DeleteCredential.",
971             pkgName.c_str());
972         return ERR_DM_NO_PERMISSION;
973     }
974     if (!IsDMServiceImplReady()) {
975         LOGE("DeleteCredential failed, instance not init or init failed.");
976         return ERR_DM_NOT_INIT;
977     }
978     return dmServiceImpl_->DeleteCredential(pkgName, reqJsonStr, returnJsonStr);
979 }
980 
RegisterCredentialCallback(const std::string & pkgName)981 int32_t DeviceManagerService::RegisterCredentialCallback(const std::string &pkgName)
982 {
983     if (!PermissionManager::GetInstance().CheckPermission()) {
984         LOGE("The caller: %{public}s does not have permission to call RegisterCredentialCallback.", pkgName.c_str());
985         return ERR_DM_NO_PERMISSION;
986     }
987     if (!IsDMServiceImplReady()) {
988         LOGE("RegisterCredentialCallback failed, instance not init or init failed.");
989         return ERR_DM_NOT_INIT;
990     }
991     return dmServiceImpl_->RegisterCredentialCallback(pkgName);
992 }
993 
UnRegisterCredentialCallback(const std::string & pkgName)994 int32_t DeviceManagerService::UnRegisterCredentialCallback(const std::string &pkgName)
995 {
996     if (!PermissionManager::GetInstance().CheckPermission()) {
997         LOGE("The caller: %{public}s does not have permission to call UnRegisterCredentialCallback.",
998             pkgName.c_str());
999         return ERR_DM_NO_PERMISSION;
1000     }
1001     if (!IsDMServiceImplReady()) {
1002         LOGE("UnRegisterCredentialCallback failed, instance not init or init failed.");
1003         return ERR_DM_NOT_INIT;
1004     }
1005     return dmServiceImpl_->UnRegisterCredentialCallback(pkgName);
1006 }
1007 
RegisterUiStateCallback(const std::string & pkgName)1008 int32_t DeviceManagerService::RegisterUiStateCallback(const std::string &pkgName)
1009 {
1010     if (pkgName.empty()) {
1011         LOGE("DeviceManagerService::RegisterUiStateCallback error: Invalid parameter, pkgName: %{public}s",
1012             pkgName.c_str());
1013         return ERR_DM_INPUT_PARA_INVALID;
1014     }
1015     if (!PermissionManager::GetInstance().CheckPermission()) {
1016         LOGE("The caller: %{public}s does not have permission to call RegisterUiStateCallback.",
1017             GetAnonyString(pkgName).c_str());
1018         return ERR_DM_NO_PERMISSION;
1019     }
1020     if (!IsDMServiceImplReady()) {
1021         LOGE("RegisterUiStateCallback failed, instance not init or init failed.");
1022         return ERR_DM_NOT_INIT;
1023     }
1024     return dmServiceImpl_->RegisterUiStateCallback(pkgName);
1025 }
1026 
UnRegisterUiStateCallback(const std::string & pkgName)1027 int32_t DeviceManagerService::UnRegisterUiStateCallback(const std::string &pkgName)
1028 {
1029     if (pkgName.empty()) {
1030         LOGE("DeviceManagerService::UnRegisterUiStateCallback error: Invalid parameter, pkgName: %{public}s",
1031             pkgName.c_str());
1032         return ERR_DM_INPUT_PARA_INVALID;
1033     }
1034     if (!PermissionManager::GetInstance().CheckPermission()) {
1035         LOGE("The caller: %{public}s does not have permission to call UnRegisterUiStateCallback.",
1036             GetAnonyString(pkgName).c_str());
1037         return ERR_DM_NO_PERMISSION;
1038     }
1039     if (!IsDMServiceImplReady()) {
1040         LOGE("UnRegisterUiStateCallback failed, instance not init or init failed.");
1041         return ERR_DM_NOT_INIT;
1042     }
1043     return dmServiceImpl_->UnRegisterUiStateCallback(pkgName);
1044 }
1045 
IsDMServiceImplReady()1046 bool DeviceManagerService::IsDMServiceImplReady()
1047 {
1048     std::lock_guard<std::mutex> lock(isImplLoadLock_);
1049     if (isImplsoLoaded_ && (dmServiceImpl_ != nullptr)) {
1050         return true;
1051     }
1052     void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD);
1053     if (so_handle == nullptr) {
1054         so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE);
1055     }
1056     if (so_handle == nullptr) {
1057         LOGE("load libdevicemanagerserviceimpl so failed, errMsg: %{public}s.", dlerror());
1058         return false;
1059     }
1060     dlerror();
1061     auto func = (CreateDMServiceFuncPtr)dlsym(so_handle, "CreateDMServiceObject");
1062     if (dlerror() != nullptr || func == nullptr) {
1063         dlclose(so_handle);
1064         LOGE("Create object function is not exist.");
1065         return false;
1066     }
1067 
1068     dmServiceImpl_ = std::shared_ptr<IDeviceManagerServiceImpl>(func());
1069     if (listener_ == nullptr) {
1070         listener_ = std::make_shared<DeviceManagerServiceListener>();
1071     }
1072     if (dmServiceImpl_->Initialize(listener_) != DM_OK) {
1073         dmServiceImpl_ = nullptr;
1074         isImplsoLoaded_ = false;
1075         return false;
1076     }
1077     isImplsoLoaded_ = true;
1078     LOGI("Sussess.");
1079     return true;
1080 }
1081 
IsDMImplSoLoaded()1082 bool DeviceManagerService::IsDMImplSoLoaded()
1083 {
1084     LOGI("In");
1085     std::lock_guard<std::mutex> lock(isImplLoadLock_);
1086     return isImplsoLoaded_;
1087 }
1088 
IsDMServiceAdapterSoLoaded()1089 bool DeviceManagerService::IsDMServiceAdapterSoLoaded()
1090 {
1091     LOGI("In");
1092     std::lock_guard<std::mutex> lock(isAdapterResidentLoadLock_);
1093     if (!isAdapterResidentSoLoaded_ || (dmServiceImplExtResident_ == nullptr)) {
1094         return false;
1095     }
1096     return dmServiceImplExtResident_->IsDMServiceAdapterSoLoaded();
1097 }
1098 
DmHiDumper(const std::vector<std::string> & args,std::string & result)1099 int32_t DeviceManagerService::DmHiDumper(const std::vector<std::string>& args, std::string &result)
1100 {
1101     LOGI("HiDump GetTrustedDeviceList");
1102     std::vector<HidumperFlag> dumpflag;
1103     HiDumpHelper::GetInstance().GetArgsType(args, dumpflag);
1104 
1105     for (unsigned int i = 0; i < dumpflag.size(); i++) {
1106         if (dumpflag[i] == HidumperFlag::HIDUMPER_GET_TRUSTED_LIST) {
1107             std::vector<DmDeviceInfo> deviceList;
1108             CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1109             int32_t ret = softbusListener_->GetTrustedDeviceList(deviceList);
1110             if (ret != DM_OK) {
1111                 result.append("HiDumpHelper GetTrustedDeviceList failed");
1112                 LOGE("HiDumpHelper GetTrustedDeviceList failed");
1113                 return ret;
1114             }
1115 
1116             for (unsigned int j = 0; j < deviceList.size(); j++) {
1117                 HiDumpHelper::GetInstance().SetNodeInfo(deviceList[j]);
1118                 LOGI("DeviceManagerService::DmHiDumper SetNodeInfo.");
1119             }
1120         }
1121     }
1122     HiDumpHelper::GetInstance().HiDump(args, result);
1123     return DM_OK;
1124 }
1125 
NotifyEvent(const std::string & pkgName,const int32_t eventId,const std::string & event)1126 int32_t DeviceManagerService::NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event)
1127 {
1128     if (!PermissionManager::GetInstance().CheckPermission()) {
1129         LOGE("The caller: %{public}s does not have permission to call NotifyEvent.", pkgName.c_str());
1130         return ERR_DM_NO_PERMISSION;
1131     }
1132     if (!IsDMServiceImplReady()) {
1133         LOGE("NotifyEvent failed, instance not init or init failed.");
1134         return ERR_DM_NOT_INIT;
1135     }
1136     if (eventId == DM_NOTIFY_EVENT_ON_PINHOLDER_EVENT) {
1137         LOGI("NotifyEvent on pin holder event start.");
1138         CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
1139         return pinHolder_->NotifyPinHolderEvent(pkgName, event);
1140     }
1141     return dmServiceImpl_->NotifyEvent(pkgName, eventId, event);
1142 }
1143 
LoadHardwareFwkService()1144 void DeviceManagerService::LoadHardwareFwkService()
1145 {
1146     std::vector<DmDeviceInfo> deviceList;
1147     CHECK_NULL_VOID(softbusListener_);
1148     int32_t ret = GetTrustedDeviceList(DHARD_WARE_PKG_NAME, deviceList);
1149     if (ret != DM_OK) {
1150         LOGE("LoadHardwareFwkService failed, get trusted devicelist failed.");
1151         return;
1152     }
1153     if (deviceList.empty()) {
1154         LOGI("no trusted device.");
1155         return;
1156     }
1157     if (!IsDMServiceImplReady()) {
1158         LOGE("LoadHardwareFwkService failed, instance not init or init failed.");
1159         return;
1160     }
1161     dmServiceImpl_->LoadHardwareFwkService();
1162 }
1163 
GetEncryptedUuidByNetworkId(const std::string & pkgName,const std::string & networkId,std::string & uuid)1164 int32_t DeviceManagerService::GetEncryptedUuidByNetworkId(const std::string &pkgName, const std::string &networkId,
1165     std::string &uuid)
1166 {
1167     if (pkgName.empty()) {
1168         LOGE("Invalid parameter, pkgName is empty.");
1169         return ERR_DM_INPUT_PARA_INVALID;
1170     }
1171     LOGI("PkgName = %{public}s", pkgName.c_str());
1172     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1173     int32_t ret = softbusListener_->GetUuidByNetworkId(networkId.c_str(), uuid);
1174     if (ret != DM_OK) {
1175         LOGE("GetUuidByNetworkId failed, ret : %{public}d", ret);
1176         return ret;
1177     }
1178 
1179     std::string appId = Crypto::Sha256(AppManager::GetInstance().GetAppId());
1180     LOGI("appId = %{public}s, uuid = %{public}s.", GetAnonyString(appId).c_str(), GetAnonyString(uuid).c_str());
1181     uuid = Crypto::Sha256(appId + "_" + uuid);
1182     LOGI("encryptedUuid = %{public}s.", GetAnonyString(uuid).c_str());
1183     return DM_OK;
1184 }
1185 
GenerateEncryptedUuid(const std::string & pkgName,const std::string & uuid,const std::string & appId,std::string & encryptedUuid)1186 int32_t DeviceManagerService::GenerateEncryptedUuid(const std::string &pkgName, const std::string &uuid,
1187     const std::string &appId, std::string &encryptedUuid)
1188 {
1189     if (pkgName.empty()) {
1190         LOGE("Invalid parameter, pkgName is empty.");
1191         return ERR_DM_INPUT_PARA_INVALID;
1192     }
1193     encryptedUuid = Crypto::Sha256(appId + "_" + uuid);
1194     LOGI("encryptedUuid = %{public}s.", GetAnonyString(encryptedUuid).c_str());
1195     return DM_OK;
1196 }
1197 
CheckApiPermission(int32_t permissionLevel)1198 int32_t DeviceManagerService::CheckApiPermission(int32_t permissionLevel)
1199 {
1200     LOGI("PermissionLevel: %{public}d", permissionLevel);
1201     int32_t ret = ERR_DM_NO_PERMISSION;
1202     switch (permissionLevel) {
1203         case NORMAL:
1204             if (PermissionManager::GetInstance().CheckNewPermission()) {
1205                 LOGI("The caller have permission to call");
1206                 ret = DM_OK;
1207             }
1208             break;
1209         case SYSTEM_BASIC:
1210             if (PermissionManager::GetInstance().CheckPermission()) {
1211                 LOGI("The caller have permission to call");
1212                 ret = DM_OK;
1213             }
1214             break;
1215         case SYSTEM_CORE:
1216             if (PermissionManager::GetInstance().CheckMonitorPermission()) {
1217                 LOGI("The caller have permission to call");
1218                 ret = DM_OK;
1219             }
1220             break;
1221         default:
1222             LOGE("DM have not this permissionLevel.");
1223             break;
1224     }
1225     return ret;
1226 }
1227 
GetNetworkTypeByNetworkId(const std::string & pkgName,const std::string & netWorkId,int32_t & networkType)1228 int32_t DeviceManagerService::GetNetworkTypeByNetworkId(const std::string &pkgName, const std::string &netWorkId,
1229                                                         int32_t &networkType)
1230 {
1231     if (!PermissionManager::GetInstance().CheckPermission()) {
1232         LOGE("The caller: %{public}s does not have permission to call GetNetworkTypeByNetworkId.", pkgName.c_str());
1233         return ERR_DM_NO_PERMISSION;
1234     }
1235     LOGI("Begin for pkgName = %{public}s", pkgName.c_str());
1236     if (pkgName.empty() || netWorkId.empty()) {
1237         LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(),
1238             GetAnonyString(netWorkId).c_str());
1239         return ERR_DM_INPUT_PARA_INVALID;
1240     }
1241     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1242     return softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
1243 }
1244 
ImportAuthCode(const std::string & pkgName,const std::string & authCode)1245 int32_t DeviceManagerService::ImportAuthCode(const std::string &pkgName, const std::string &authCode)
1246 {
1247     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1248         LOGE("The caller: %{public}s does not have permission to call ImportAuthCode.", pkgName.c_str());
1249         return ERR_DM_NO_PERMISSION;
1250     }
1251     std::string processName = "";
1252     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
1253         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
1254         return ERR_DM_FAILED;
1255     }
1256     if (!PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName)) {
1257         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
1258         return ERR_DM_INPUT_PARA_INVALID;
1259     }
1260     LOGI("DeviceManagerService::ImportAuthCode begin.");
1261     if (authCode.empty() || pkgName.empty()) {
1262         LOGE("Invalid parameter, authCode: %{public}s.", GetAnonyString(authCode).c_str());
1263         return ERR_DM_INPUT_PARA_INVALID;
1264     }
1265     if (!IsDMServiceImplReady()) {
1266         LOGE("ImportAuthCode failed, instance not init or init failed.");
1267         return ERR_DM_NOT_INIT;
1268     }
1269     return dmServiceImpl_->ImportAuthCode(pkgName, authCode);
1270 }
1271 
ExportAuthCode(std::string & authCode)1272 int32_t DeviceManagerService::ExportAuthCode(std::string &authCode)
1273 {
1274     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1275         LOGE("The caller does not have permission to call ExportAuthCode.");
1276         return ERR_DM_NO_PERMISSION;
1277     }
1278     std::string processName = "";
1279     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
1280         LOGE("Get caller process name failed, processName: %{public}s.", processName.c_str());
1281         return ERR_DM_FAILED;
1282     }
1283     if (!PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName)) {
1284         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
1285         return ERR_DM_INPUT_PARA_INVALID;
1286     }
1287     if (!IsDMServiceImplReady()) {
1288         LOGE("ExportAuthCode failed, instance not init or init failed.");
1289         return ERR_DM_NOT_INIT;
1290     }
1291     LOGI("DeviceManagerService::ExportAuthCode begin.");
1292     return dmServiceImpl_->ExportAuthCode(authCode);
1293 }
1294 
UnloadDMServiceImplSo()1295 void DeviceManagerService::UnloadDMServiceImplSo()
1296 {
1297     LOGI("Start.");
1298     std::lock_guard<std::mutex> lock(isImplLoadLock_);
1299     if (dmServiceImpl_ != nullptr) {
1300         dmServiceImpl_->Release();
1301     }
1302     void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NOLOAD);
1303     if (so_handle != nullptr) {
1304         LOGI("DeviceManagerService so_handle is not nullptr.");
1305         dlclose(so_handle);
1306     }
1307 }
1308 
IsDMServiceAdapterResidentLoad()1309 bool DeviceManagerService::IsDMServiceAdapterResidentLoad()
1310 {
1311     LOGI("Start.");
1312     if (listener_ == nullptr) {
1313         listener_ = std::make_shared<DeviceManagerServiceListener>();
1314     }
1315     std::lock_guard<std::mutex> lock(isAdapterResidentLoadLock_);
1316     if (isAdapterResidentSoLoaded_ && (dmServiceImplExtResident_ != nullptr)) {
1317         return true;
1318     }
1319     residentSoHandle_ = dlopen(LIB_DM_RESIDENT_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD);
1320     if (residentSoHandle_ == nullptr) {
1321         residentSoHandle_ = dlopen(LIB_DM_RESIDENT_NAME, RTLD_NOW | RTLD_NODELETE);
1322     }
1323     if (residentSoHandle_ == nullptr) {
1324         LOGE("load dm service resident so failed.");
1325         return false;
1326     }
1327     dlerror();
1328     auto func = (CreateDMServiceExtResidentFuncPtr)dlsym(residentSoHandle_, "CreateDMServiceExtResidentObject");
1329     if (dlerror() != nullptr || func == nullptr) {
1330         dlclose(residentSoHandle_);
1331         residentSoHandle_ = nullptr;
1332         LOGE("Create object function is not exist.");
1333         return false;
1334     }
1335 
1336     dmServiceImplExtResident_ = std::shared_ptr<IDMServiceImplExtResident>(func());
1337     if (dmServiceImplExtResident_->Initialize(listener_) != DM_OK) {
1338         dlclose(residentSoHandle_);
1339         residentSoHandle_ = nullptr;
1340         dmServiceImplExtResident_ = nullptr;
1341         isAdapterResidentSoLoaded_ = false;
1342         LOGE("dm service impl ext resident init failed.");
1343         return false;
1344     }
1345     isAdapterResidentSoLoaded_ = true;
1346     LOGI("Success.");
1347     return true;
1348 }
1349 
UnloadDMServiceAdapterResident()1350 void DeviceManagerService::UnloadDMServiceAdapterResident()
1351 {
1352     LOGI("Start.");
1353     std::lock_guard<std::mutex> lock(isAdapterResidentLoadLock_);
1354     if (dmServiceImplExtResident_ != nullptr) {
1355         dmServiceImplExtResident_->Release();
1356     }
1357     dmServiceImplExtResident_ = nullptr;
1358     if (residentSoHandle_ != nullptr) {
1359         LOGI("dm service resident residentSoHandle_ is not nullptr.");
1360         dlclose(residentSoHandle_);
1361         residentSoHandle_ = nullptr;
1362     }
1363 }
1364 
StartDiscovering(const std::string & pkgName,const std::map<std::string,std::string> & discoverParam,const std::map<std::string,std::string> & filterOptions)1365 int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName,
1366     const std::map<std::string, std::string> &discoverParam, const std::map<std::string, std::string> &filterOptions)
1367 {
1368     if (!PermissionManager::GetInstance().CheckNewPermission() &&
1369         !PermissionManager::GetInstance().CheckPermission()) {
1370         LOGE("The caller does not have permission to call");
1371         return ERR_DM_NO_PERMISSION;
1372     }
1373     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1374     if (pkgName.empty()) {
1375         LOGE("Invalid parameter, pkgName is empty.");
1376         return ERR_DM_INPUT_PARA_INVALID;
1377     }
1378     if (discoverParam.find(PARAM_KEY_META_TYPE) != discoverParam.end()) {
1379         LOGI("StartDiscovering input MetaType = %{public}s", (discoverParam.find(PARAM_KEY_META_TYPE)->second).c_str());
1380     }
1381     CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL);
1382     return discoveryMgr_->StartDiscovering(pkgName, discoverParam, filterOptions);
1383 }
1384 
StopDiscovering(const std::string & pkgName,const std::map<std::string,std::string> & discoverParam)1385 int32_t DeviceManagerService::StopDiscovering(const std::string &pkgName,
1386     const std::map<std::string, std::string> &discoverParam)
1387 {
1388     if (!PermissionManager::GetInstance().CheckNewPermission() &&
1389         !PermissionManager::GetInstance().CheckPermission()) {
1390         LOGE("The caller does not have permission to call");
1391         return ERR_DM_NO_PERMISSION;
1392     }
1393     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1394     if (pkgName.empty()) {
1395         LOGE("Invalid parameter, pkgName is empty.");
1396         return ERR_DM_INPUT_PARA_INVALID;
1397     }
1398     uint16_t subscribeId = -1;
1399     if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) {
1400         subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str());
1401     }
1402     if (discoverParam.find(PARAM_KEY_META_TYPE) != discoverParam.end()) {
1403         LOGI("StopDiscovering input MetaType = %{public}s", (discoverParam.find(PARAM_KEY_META_TYPE)->second).c_str());
1404     }
1405     CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL);
1406     return discoveryMgr_->StopDiscovering(pkgName, subscribeId);
1407 }
1408 
EnableDiscoveryListener(const std::string & pkgName,const std::map<std::string,std::string> & discoverParam,const std::map<std::string,std::string> & filterOptions)1409 int32_t DeviceManagerService::EnableDiscoveryListener(const std::string &pkgName,
1410     const std::map<std::string, std::string> &discoverParam, const std::map<std::string, std::string> &filterOptions)
1411 {
1412     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1413         LOGE("The caller does not have permission to call");
1414         return ERR_DM_NO_PERMISSION;
1415     }
1416     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1417     if (pkgName.empty()) {
1418         LOGE("Invalid parameter, pkgName is empty.");
1419         return ERR_DM_INPUT_PARA_INVALID;
1420     }
1421     SoftbusListener::SetHostPkgName(pkgName);
1422     CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL);
1423     return discoveryMgr_->EnableDiscoveryListener(pkgName, discoverParam, filterOptions);
1424 }
1425 
DisableDiscoveryListener(const std::string & pkgName,const std::map<std::string,std::string> & extraParam)1426 int32_t DeviceManagerService::DisableDiscoveryListener(const std::string &pkgName,
1427     const std::map<std::string, std::string> &extraParam)
1428 {
1429     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1430         LOGE("The caller does not have permission to call");
1431         return ERR_DM_NO_PERMISSION;
1432     }
1433     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1434     if (pkgName.empty()) {
1435         LOGE("Invalid parameter, pkgName is empty.");
1436         return ERR_DM_INPUT_PARA_INVALID;
1437     }
1438     CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL);
1439     return discoveryMgr_->DisableDiscoveryListener(pkgName, extraParam);
1440 }
1441 
StartAdvertising(const std::string & pkgName,const std::map<std::string,std::string> & advertiseParam)1442 int32_t DeviceManagerService::StartAdvertising(const std::string &pkgName,
1443     const std::map<std::string, std::string> &advertiseParam)
1444 {
1445     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1446         LOGE("The caller does not have permission to call");
1447         return ERR_DM_NO_PERMISSION;
1448     }
1449     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1450     if (pkgName.empty()) {
1451         LOGE("Invalid parameter, pkgName is empty.");
1452         return ERR_DM_INPUT_PARA_INVALID;
1453     }
1454     CHECK_NULL_RETURN(advertiseMgr_, ERR_DM_POINT_NULL);
1455     return advertiseMgr_->StartAdvertising(pkgName, advertiseParam);
1456 }
1457 
StopAdvertising(const std::string & pkgName,const std::map<std::string,std::string> & advertiseParam)1458 int32_t DeviceManagerService::StopAdvertising(const std::string &pkgName,
1459     const std::map<std::string, std::string> &advertiseParam)
1460 {
1461     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1462         LOGE("The caller does not have permission to call");
1463         return ERR_DM_NO_PERMISSION;
1464     }
1465     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1466     if (pkgName.empty()) {
1467         LOGE("Invalid parameter, pkgName is empty.");
1468         return ERR_DM_INPUT_PARA_INVALID;
1469     }
1470     if (advertiseParam.find(PARAM_KEY_META_TYPE) != advertiseParam.end()) {
1471         LOGI("StopAdvertising input MetaType=%{public}s", (advertiseParam.find(PARAM_KEY_META_TYPE)->second).c_str());
1472     }
1473     int32_t publishId = -1;
1474     if (advertiseParam.find(PARAM_KEY_PUBLISH_ID) != advertiseParam.end()) {
1475         publishId = std::atoi((advertiseParam.find(PARAM_KEY_PUBLISH_ID)->second).c_str());
1476     }
1477     CHECK_NULL_RETURN(advertiseMgr_, ERR_DM_POINT_NULL);
1478     return advertiseMgr_->StopAdvertising(pkgName, publishId);
1479 }
1480 
BindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam)1481 int32_t DeviceManagerService::BindTarget(const std::string &pkgName, const PeerTargetId &targetId,
1482     const std::map<std::string, std::string> &bindParam)
1483 {
1484     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1485         LOGE("The caller does not have permission to call");
1486         return ERR_DM_NO_PERMISSION;
1487     }
1488     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1489     if (pkgName.empty()) {
1490         LOGE("Invalid parameter, pkgName is empty.");
1491         return ERR_DM_INPUT_PARA_INVALID;
1492     }
1493     if (bindParam.find(PARAM_KEY_META_TYPE) == bindParam.end()) {
1494         if (!IsDMServiceImplReady()) {
1495             LOGE("BindTarget failed, DMServiceImpl instance not init or init failed.");
1496             return ERR_DM_NOT_INIT;
1497         }
1498         LOGI("BindTarget stardard begin.");
1499         if (targetId.wifiIp.empty() || targetId.wifiIp.length() > IP_STR_MAX_LEN) {
1500             return dmServiceImpl_->BindTarget(pkgName, targetId, bindParam);
1501         }
1502         ConnectionAddrType ipAddrType;
1503         std::map<std::string, std::string> &noConstBindParam =
1504             const_cast<std::map<std::string, std::string> &>(bindParam);
1505         if (SoftbusListener::GetIPAddrTypeFromCache(targetId.deviceId, targetId.wifiIp, ipAddrType) == DM_OK) {
1506             noConstBindParam.insert(std::pair<std::string, std::string>(PARAM_KEY_CONN_ADDR_TYPE,
1507                 std::to_string(ipAddrType)));
1508         }
1509         const std::map<std::string, std::string> &constBindParam =
1510             const_cast<const std::map<std::string, std::string> &>(noConstBindParam);
1511         return dmServiceImpl_->BindTarget(pkgName, targetId, constBindParam);
1512     }
1513     if (!IsDMServiceAdapterResidentLoad()) {
1514         LOGE("BindTarget failed, adapter instance not init or init failed.");
1515         return ERR_DM_UNSUPPORTED_METHOD;
1516     }
1517     LOGI("BindTarget unstardard begin.");
1518     return dmServiceImplExtResident_->BindTargetExt(pkgName, targetId, bindParam);
1519 }
1520 
UnbindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & unbindParam)1521 int32_t DeviceManagerService::UnbindTarget(const std::string &pkgName, const PeerTargetId &targetId,
1522     const std::map<std::string, std::string> &unbindParam)
1523 {
1524     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1525         LOGE("The caller does not have permission to call");
1526         return ERR_DM_NO_PERMISSION;
1527     }
1528     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
1529     if (pkgName.empty()) {
1530         LOGE("Invalid parameter, pkgName is empty.");
1531         return ERR_DM_INPUT_PARA_INVALID;
1532     }
1533     if (!IsDMServiceAdapterResidentLoad()) {
1534         LOGE("UnbindTarget failed, instance not init or init failed.");
1535         return ERR_DM_UNSUPPORTED_METHOD;
1536     }
1537     if (unbindParam.find(PARAM_KEY_META_TYPE) == unbindParam.end()) {
1538         LOGE("input unbind parameter not contains META_TYPE, dm service adapter not supported.");
1539         return ERR_DM_INPUT_PARA_INVALID;
1540     }
1541     return dmServiceImplExtResident_->UnbindTargetExt(pkgName, targetId, unbindParam);
1542 }
1543 
1544 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
InitDPLocalServiceInfo(const DMLocalServiceInfo & serviceInfo,DistributedDeviceProfile::LocalServiceInfo & dpLocalServiceInfo)1545 bool DeviceManagerService::InitDPLocalServiceInfo(const DMLocalServiceInfo &serviceInfo,
1546     DistributedDeviceProfile::LocalServiceInfo &dpLocalServiceInfo)
1547 {
1548     dpLocalServiceInfo.SetBundleName(serviceInfo.bundleName);
1549     dpLocalServiceInfo.SetAuthBoxType(serviceInfo.authBoxType);
1550     dpLocalServiceInfo.SetAuthType(serviceInfo.authType);
1551     dpLocalServiceInfo.SetPinExchangeType(serviceInfo.pinExchangeType);
1552     dpLocalServiceInfo.SetPinCode(serviceInfo.pinCode);
1553     dpLocalServiceInfo.SetDescription(serviceInfo.description);
1554     dpLocalServiceInfo.SetExtraInfo(serviceInfo.extraInfo);
1555     return true;
1556 }
1557 
InitServiceInfo(const DistributedDeviceProfile::LocalServiceInfo & dpLocalServiceInfo,DMLocalServiceInfo & serviceInfo)1558 void DeviceManagerService::InitServiceInfo(const DistributedDeviceProfile::LocalServiceInfo &dpLocalServiceInfo,
1559     DMLocalServiceInfo &serviceInfo)
1560 {
1561     serviceInfo.bundleName = dpLocalServiceInfo.GetBundleName();
1562     serviceInfo.authBoxType = dpLocalServiceInfo.GetAuthBoxType();
1563     serviceInfo.authType = dpLocalServiceInfo.GetAuthType();
1564     serviceInfo.pinExchangeType = dpLocalServiceInfo.GetPinExchangeType();
1565     serviceInfo.pinCode = dpLocalServiceInfo.GetPinCode();
1566     serviceInfo.description = dpLocalServiceInfo.GetDescription();
1567     serviceInfo.extraInfo = dpLocalServiceInfo.GetExtraInfo();
1568 }
1569 
InitServiceInfos(const std::vector<DistributedDeviceProfile::LocalServiceInfo> & dpLocalServiceInfos,std::vector<DMLocalServiceInfo> & serviceInfos)1570 void DeviceManagerService::InitServiceInfos(
1571     const std::vector<DistributedDeviceProfile::LocalServiceInfo> &dpLocalServiceInfos,
1572     std::vector<DMLocalServiceInfo> &serviceInfos)
1573 {
1574     for (const auto &dpInfoItem : dpLocalServiceInfos) {
1575         DMLocalServiceInfo infoItem;
1576         InitServiceInfo(dpInfoItem, infoItem);
1577         serviceInfos.emplace_back(infoItem);
1578     }
1579 }
1580 #endif
1581 
RegisterLocalServiceInfo(const DMLocalServiceInfo & serviceInfo)1582 int32_t DeviceManagerService::RegisterLocalServiceInfo(const DMLocalServiceInfo &serviceInfo)
1583 {
1584 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1585     DistributedDeviceProfile::LocalServiceInfo dpLocalServiceInfo;
1586     bool success = InitDPLocalServiceInfo(serviceInfo, dpLocalServiceInfo);
1587     if (!success) {
1588         LOGE("InitDPLocalServiceInfo failed");
1589         return ERR_DM_FAILED;
1590     }
1591     return DeviceProfileConnector::GetInstance().PutLocalServiceInfo(dpLocalServiceInfo);
1592 #else
1593     (void)serviceInfo;
1594     return ERR_DM_FAILED;
1595 #endif
1596 }
1597 
UnRegisterLocalServiceInfo(const std::string & bundleName,int32_t pinExchangeType)1598 int32_t DeviceManagerService::UnRegisterLocalServiceInfo(const std::string &bundleName, int32_t pinExchangeType)
1599 {
1600 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1601     return DeviceProfileConnector::GetInstance().DeleteLocalServiceInfo(bundleName, pinExchangeType);
1602 #else
1603     (void)bundleName;
1604     (void)pinExchangeType;
1605     return ERR_DM_FAILED;
1606 #endif
1607 }
1608 
UpdateLocalServiceInfo(const DMLocalServiceInfo & serviceInfo)1609 int32_t DeviceManagerService::UpdateLocalServiceInfo(const DMLocalServiceInfo &serviceInfo)
1610 {
1611 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1612     DistributedDeviceProfile::LocalServiceInfo dpLocalServiceInfo;
1613     bool success = InitDPLocalServiceInfo(serviceInfo, dpLocalServiceInfo);
1614     if (!success) {
1615         LOGE("InitDPLocalServiceInfo failed");
1616         return ERR_DM_FAILED;
1617     }
1618     return DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(dpLocalServiceInfo);
1619 #else
1620     (void)serviceInfo;
1621     return ERR_DM_FAILED;
1622 #endif
1623 }
1624 
GetLocalServiceInfoByBundleNameAndPinExchangeType(const std::string & bundleName,int32_t pinExchangeType,DMLocalServiceInfo & serviceInfo)1625 int32_t DeviceManagerService::GetLocalServiceInfoByBundleNameAndPinExchangeType(const std::string &bundleName,
1626     int32_t pinExchangeType, DMLocalServiceInfo &serviceInfo)
1627 {
1628 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1629     DistributedDeviceProfile::LocalServiceInfo dpLocalServiceInfo;
1630     int32_t ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType(bundleName,
1631         pinExchangeType, dpLocalServiceInfo);
1632     if (ret == DM_OK) {
1633         InitServiceInfo(dpLocalServiceInfo, serviceInfo);
1634     }
1635     return ret;
1636 #else
1637     (void)bundleName;
1638     (void)pinExchangeType;
1639     (void)serviceInfo;
1640     return ERR_DM_FAILED;
1641 #endif
1642 }
1643 
RegisterPinHolderCallback(const std::string & pkgName)1644 int32_t DeviceManagerService::RegisterPinHolderCallback(const std::string &pkgName)
1645 {
1646     if (!PermissionManager::GetInstance().CheckPermission()) {
1647         LOGE("The caller: %{public}s does not have permission to call ImportAuthCode.", pkgName.c_str());
1648         return ERR_DM_NO_PERMISSION;
1649     }
1650     std::string processName = "";
1651     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
1652         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
1653         return ERR_DM_FAILED;
1654     }
1655     if (!PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName)) {
1656         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
1657         return ERR_DM_INPUT_PARA_INVALID;
1658     }
1659     LOGI("DeviceManagerService::RegisterPinHolderCallback begin.");
1660     if (pkgName.empty()) {
1661         LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str());
1662         return ERR_DM_INPUT_PARA_INVALID;
1663     }
1664     CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
1665     return pinHolder_->RegisterPinHolderCallback(pkgName);
1666 }
1667 
CreatePinHolder(const std::string & pkgName,const PeerTargetId & targetId,DmPinType pinType,const std::string & payload)1668 int32_t DeviceManagerService::CreatePinHolder(const std::string &pkgName, const PeerTargetId &targetId,
1669     DmPinType pinType, const std::string &payload)
1670 {
1671     if (!PermissionManager::GetInstance().CheckPermission()) {
1672         LOGE("The caller: %{public}s does not have permission to call CreatePinHolder.", pkgName.c_str());
1673         return ERR_DM_NO_PERMISSION;
1674     }
1675     std::string processName = "";
1676     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
1677         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
1678         return ERR_DM_FAILED;
1679     }
1680     if (!PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName)) {
1681         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
1682         return ERR_DM_INPUT_PARA_INVALID;
1683     }
1684     LOGI("DeviceManagerService::CreatePinHolder begin.");
1685     if (pkgName.empty()) {
1686         LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str());
1687         return ERR_DM_INPUT_PARA_INVALID;
1688     }
1689     CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
1690     return pinHolder_->CreatePinHolder(pkgName, targetId, pinType, payload);
1691 }
1692 
DestroyPinHolder(const std::string & pkgName,const PeerTargetId & targetId,DmPinType pinType,const std::string & payload)1693 int32_t DeviceManagerService::DestroyPinHolder(const std::string &pkgName, const PeerTargetId &targetId,
1694     DmPinType pinType, const std::string &payload)
1695 {
1696     if (!PermissionManager::GetInstance().CheckPermission()) {
1697         LOGE("The caller: %{public}s does not have permission to call DestroyPinHolder.", pkgName.c_str());
1698         return ERR_DM_NO_PERMISSION;
1699     }
1700     std::string processName = "";
1701     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
1702         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
1703         return ERR_DM_FAILED;
1704     }
1705     if (!PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName)) {
1706         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
1707         return ERR_DM_INPUT_PARA_INVALID;
1708     }
1709     LOGI("Begin.");
1710     if (pkgName.empty()) {
1711         LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str());
1712         return ERR_DM_INPUT_PARA_INVALID;
1713     }
1714     CHECK_NULL_RETURN(pinHolder_, ERR_DM_POINT_NULL);
1715     return pinHolder_->DestroyPinHolder(pkgName, targetId, pinType, payload);
1716 }
1717 
DpAclAdd(const std::string & udid)1718 int32_t DeviceManagerService::DpAclAdd(const std::string &udid)
1719 {
1720     if (!PermissionManager::GetInstance().CheckNewPermission()) {
1721         LOGE("The caller does not have permission to call DpAclAdd.");
1722         return ERR_DM_NO_PERMISSION;
1723     }
1724     LOGI("Start.");
1725     if (!IsDMServiceImplReady()) {
1726         LOGE("DpAclAdd failed, instance not init or init failed.");
1727         return ERR_DM_NOT_INIT;
1728     }
1729     dmServiceImpl_->DpAclAdd(udid);
1730     LOGI("DeviceManagerService::DpAclAdd completed");
1731     return DM_OK;
1732 }
1733 
GetDeviceSecurityLevel(const std::string & pkgName,const std::string & networkId,int32_t & securityLevel)1734 int32_t DeviceManagerService::GetDeviceSecurityLevel(const std::string &pkgName, const std::string &networkId,
1735                                                      int32_t &securityLevel)
1736 {
1737     LOGI("Begin pkgName: %{public}s, networkId: %{public}s",
1738         pkgName.c_str(), GetAnonyString(networkId).c_str());
1739     if (!PermissionManager::GetInstance().CheckPermission()) {
1740         LOGE("The caller: %{public}s does not have permission to call GetDeviceSecurityLevel.", pkgName.c_str());
1741         return ERR_DM_NO_PERMISSION;
1742     }
1743     if (pkgName.empty() || networkId.empty()) {
1744         LOGE("Invalid parameter, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(),
1745             GetAnonyString(networkId).c_str());
1746         return ERR_DM_INPUT_PARA_INVALID;
1747     }
1748     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
1749     int32_t ret = softbusListener_->GetDeviceSecurityLevel(networkId.c_str(), securityLevel);
1750     if (ret != DM_OK) {
1751         LOGE("GetDeviceSecurityLevel failed, ret = %{public}d", ret);
1752         return ret;
1753     }
1754     return DM_OK;
1755 }
1756 
IsSameAccount(const std::string & networkId)1757 int32_t DeviceManagerService::IsSameAccount(const std::string &networkId)
1758 {
1759     LOGI("NetworkId %{public}s.", GetAnonyString(networkId).c_str());
1760     if (!PermissionManager::GetInstance().CheckPermission()) {
1761         return ERR_DM_NO_PERMISSION;
1762     }
1763     std::string udid = "";
1764     if (SoftbusListener::GetUdidByNetworkId(networkId.c_str(), udid) != DM_OK) {
1765         LOGE("DeviceManagerService::IsSameAccount error: udid: %{public}s", GetAnonyString(udid).c_str());
1766         return ERR_DM_INPUT_PARA_INVALID;
1767     }
1768     if (!IsDMServiceImplReady()) {
1769         LOGE("IsSameAccount failed, instance not init or init failed.");
1770         return ERR_DM_NOT_INIT;
1771     }
1772     return dmServiceImpl_->IsSameAccount(udid);
1773 }
1774 
CheckAccessControl(const DmAccessCaller & caller,const DmAccessCallee & callee)1775 bool DeviceManagerService::CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee)
1776 {
1777     if (!PermissionManager::GetInstance().CheckPermission()) {
1778         LOGE("The caller: %{public}s does not have permission to call CheckAccessControl.", caller.pkgName.c_str());
1779         return false;
1780     }
1781     if (!IsDMServiceImplReady()) {
1782         LOGE("CheckAccessControl failed, instance not init or init failed.");
1783         return false;
1784     }
1785     std::string srcUdid = "";
1786     SoftbusListener::GetUdidByNetworkId(caller.networkId.c_str(), srcUdid);
1787     std::string sinkUdid = "";
1788     SoftbusListener::GetUdidByNetworkId(callee.networkId.c_str(), sinkUdid);
1789     return dmServiceImpl_->CheckAccessControl(caller, srcUdid, callee, sinkUdid);
1790 }
1791 
CheckIsSameAccount(const DmAccessCaller & caller,const DmAccessCallee & callee)1792 bool DeviceManagerService::CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee)
1793 {
1794     if (!PermissionManager::GetInstance().CheckPermission()) {
1795         LOGE("The caller: %{public}s does not have permission to call CheckIsSameAccount.", caller.pkgName.c_str());
1796         return false;
1797     }
1798     if (!IsDMServiceImplReady()) {
1799         LOGE("CheckIsSameAccount failed, instance not init or init failed.");
1800         return false;
1801     }
1802     std::string srcUdid = "";
1803     SoftbusListener::GetUdidByNetworkId(caller.networkId.c_str(), srcUdid);
1804     std::string sinkUdid = "";
1805     SoftbusListener::GetUdidByNetworkId(callee.networkId.c_str(), sinkUdid);
1806     return dmServiceImpl_->CheckIsSameAccount(caller, srcUdid, callee, sinkUdid);
1807 }
1808 
InitAccountInfo()1809 int32_t DeviceManagerService::InitAccountInfo()
1810 {
1811 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1812     SubscribeAccountCommonEvent();
1813     LOGI("Success.");
1814 #endif
1815     return DM_OK;
1816 }
1817 
InitScreenLockEvent()1818 int32_t DeviceManagerService::InitScreenLockEvent()
1819 {
1820 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1821     SubscribeScreenLockEvent();
1822     LOGI("Success.");
1823 #endif
1824     return DM_OK;
1825 }
1826 
1827 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
SubscribeAccountCommonEvent()1828 void DeviceManagerService::SubscribeAccountCommonEvent()
1829 {
1830     LOGI("Start");
1831     if (accountCommonEventManager_ == nullptr) {
1832         accountCommonEventManager_ = std::make_shared<DmAccountCommonEventManager>();
1833     }
1834     AccountEventCallback callback = [=](const auto &eventType, const auto &currentUserId, const auto &beforeUserId) {
1835         this->AccountCommonEventCallback(eventType, currentUserId, beforeUserId);
1836     };
1837     std::vector<std::string> AccountCommonEventVec;
1838     AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
1839     AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
1840     AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGOUT);
1841     AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGIN);
1842     AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED);
1843     AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_STOPPED);
1844     AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
1845     if (accountCommonEventManager_->SubscribeAccountCommonEvent(AccountCommonEventVec, callback)) {
1846         LOGI("Success");
1847     }
1848     return;
1849 }
1850 
SubscribeScreenLockEvent()1851 void DeviceManagerService::SubscribeScreenLockEvent()
1852 {
1853     LOGI("Start");
1854     if (screenCommonEventManager_ == nullptr) {
1855         screenCommonEventManager_ = std::make_shared<DmScreenCommonEventManager>();
1856     }
1857     ScreenEventCallback callback = [=](const auto &arg1) { this->ScreenCommonEventCallback(arg1); };
1858     std::vector<std::string> screenEventVec;
1859     screenEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED);
1860     if (screenCommonEventManager_->SubscribeScreenCommonEvent(screenEventVec, callback)) {
1861         LOGI("Success");
1862     }
1863     return;
1864 }
1865 
AccountCommonEventCallback(const std::string commonEventType,int32_t currentUserId,int32_t beforeUserId)1866 void DeviceManagerService::AccountCommonEventCallback(const std::string commonEventType, int32_t currentUserId,
1867     int32_t beforeUserId)
1868 {
1869     LOGI("CommonEventType: %{public}s, currentUserId: %{public}d, beforeUserId: %{public}d", commonEventType.c_str(),
1870         currentUserId, beforeUserId);
1871     if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
1872         HandleUserSwitchedEvent(currentUserId, beforeUserId);
1873     } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) {
1874         DeviceNameManager::GetInstance().InitDeviceNameWhenLogin();
1875         MultipleUserConnector::SetAccountInfo(currentUserId, MultipleUserConnector::GetCurrentDMAccountInfo());
1876     } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) {
1877         DeviceNameManager::GetInstance().InitDeviceNameWhenLogout();
1878         DMAccountInfo dmAccountInfo = MultipleUserConnector::GetAccountInfoByUserId(beforeUserId);
1879         if (dmAccountInfo.accountId.empty()) {
1880             return;
1881         }
1882         HandleAccountLogout(currentUserId, dmAccountInfo.accountId, dmAccountInfo.accountName);
1883         MultipleUserConnector::DeleteAccountInfoByUserId(currentUserId);
1884         MultipleUserConnector::SetAccountInfo(MultipleUserConnector::GetCurrentAccountUserID(),
1885             MultipleUserConnector::GetCurrentDMAccountInfo());
1886     } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_REMOVED) {
1887         HandleUserRemoved(beforeUserId);
1888         MultipleUserConnector::DeleteAccountInfoByUserId(beforeUserId);
1889         MultipleUserConnector::SetAccountInfo(MultipleUserConnector::GetCurrentAccountUserID(),
1890             MultipleUserConnector::GetCurrentDMAccountInfo());
1891     } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED) {
1892         DeviceNameManager::GetInstance().InitDeviceNameWhenNickChange();
1893     } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_STOPPED && IsPC()) {
1894         HandleUserStopEvent(beforeUserId);
1895     } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_UNLOCKED) {
1896         DeviceNameManager::GetInstance().AccountSysReady(beforeUserId);
1897         if (IsPC()) {
1898             HandleUserSwitched();
1899             if (IsDMServiceAdapterResidentLoad()) {
1900                 dmServiceImplExtResident_->AccountUserSwitched(currentUserId,
1901                     MultipleUserConnector::GetOhosAccountId());
1902             }
1903         }
1904     } else {
1905         LOGE("Invalied account common event.");
1906     }
1907     return;
1908 }
1909 
HandleUserSwitched()1910 void DeviceManagerService::HandleUserSwitched()
1911 {
1912     LOGI("onStart, HandleUserSwitched.");
1913     std::vector<int32_t> foregroundUserVec;
1914     int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec);
1915     std::vector<int32_t> backgroundUserVec;
1916     int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec);
1917     if (retFront != DM_OK || retBack != DM_OK || foregroundUserVec.empty()) {
1918         LOGE("Get userids failed, retFront: %{public}d, retBack: %{public}d, foreground user num: %{public}d",
1919             retFront, retBack, static_cast<int32_t>(foregroundUserVec.size()));
1920         return;
1921     }
1922     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
1923     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
1924     std::string localUdid = std::string(localUdidTemp);
1925     CHECK_NULL_VOID(discoveryMgr_);
1926     if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
1927         LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
1928         return;
1929     }
1930     if (!discoveryMgr_->GetCommonDependencyObj()->CheckAclStatusAndForegroundNotMatch(localUdid,
1931         foregroundUserVec, backgroundUserVec)) {
1932         LOGI("no unreasonable data.");
1933         return;
1934     }
1935     std::map<std::string, int32_t> curUserDeviceMap =
1936         discoveryMgr_->GetCommonDependencyObj()->GetDeviceIdAndBindLevel(foregroundUserVec, localUdid);
1937     std::map<std::string, int32_t> preUserDeviceMap =
1938         discoveryMgr_->GetCommonDependencyObj()->GetDeviceIdAndBindLevel(backgroundUserVec, localUdid);
1939     std::vector<std::string> peerUdids;
1940     for (const auto &item : curUserDeviceMap) {
1941         peerUdids.push_back(item.first);
1942     }
1943     for (const auto &item : preUserDeviceMap) {
1944         if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) {
1945             peerUdids.push_back(item.first);
1946         }
1947     }
1948     if (peerUdids.empty()) {
1949         return;
1950     }
1951     NotifyRemoteLocalUserSwitch(localUdid, peerUdids, foregroundUserVec, backgroundUserVec);
1952 }
1953 
1954 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
NotifyRemoteLocalUserSwitch(const std::string & localUdid,const std::vector<std::string> & peerUdids,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)1955 void DeviceManagerService::NotifyRemoteLocalUserSwitch(const std::string &localUdid,
1956     const std::vector<std::string> &peerUdids, const std::vector<int32_t> &foregroundUserIds,
1957     const std::vector<int32_t> &backgroundUserIds)
1958 {
1959     LOGI("onstart UserSwitch, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s",
1960         GetIntegerList<int32_t>(foregroundUserIds).c_str(), GetIntegerList<int32_t>(backgroundUserIds).c_str());
1961     if (peerUdids.empty()) {
1962         return;
1963     }
1964     if (softbusListener_ == nullptr) {
1965         UpdateAclAndDeleteGroup(localUdid, peerUdids, foregroundUserIds, backgroundUserIds);
1966         LOGE("softbusListener_ is null");
1967         return;
1968     }
1969     std::vector<std::string> bleUdids;
1970     std::map<std::string, std::string> wifiDevices;
1971     for (const auto &udid : peerUdids) {
1972         std::string netWorkId = "";
1973         SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
1974         if (netWorkId.empty()) {
1975             LOGI("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
1976             bleUdids.push_back(udid);
1977             continue;
1978         }
1979         int32_t networkType = 0;
1980         int32_t ret = softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
1981         if (ret != DM_OK || networkType <= 0) {
1982             LOGI("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
1983             bleUdids.push_back(udid);
1984             continue;
1985         }
1986         if ((static_cast<uint32_t>(networkType) & USERID_SYNC_DISCOVERY_TYPE_BLE_MASK) != 0x0) {
1987             bleUdids.push_back(udid);
1988         } else {
1989             wifiDevices.insert(std::pair<std::string, std::string>(udid, netWorkId));
1990         }
1991     }
1992     if (!bleUdids.empty()) {
1993         UpdateAclAndDeleteGroup(localUdid, peerUdids, foregroundUserIds, backgroundUserIds);
1994         SendUserIdsBroadCast(bleUdids, foregroundUserIds, backgroundUserIds, true);
1995     }
1996     if (!wifiDevices.empty()) {
1997         NotifyRemoteLocalUserSwitchByWifi(localUdid, wifiDevices, foregroundUserIds, backgroundUserIds);
1998     }
1999 }
2000 
NotifyRemoteLocalUserSwitchByWifi(const std::string & localUdid,const std::map<std::string,std::string> & wifiDevices,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2001 void DeviceManagerService::NotifyRemoteLocalUserSwitchByWifi(const std::string &localUdid,
2002     const std::map<std::string, std::string> &wifiDevices, const std::vector<int32_t> &foregroundUserIds,
2003     const std::vector<int32_t> &backgroundUserIds)
2004 {
2005     for (const auto &it : wifiDevices) {
2006         int32_t result = SendUserIdsByWifi(it.second, foregroundUserIds, backgroundUserIds);
2007         if (result != DM_OK) {
2008             LOGE("by wifi failed: %{public}s", GetAnonyString(it.first).c_str());
2009             std::vector<std::string> updateUdids;
2010             updateUdids.push_back(it.first);
2011             UpdateAclAndDeleteGroup(localUdid, updateUdids, foregroundUserIds, backgroundUserIds);
2012             continue;
2013         }
2014         if (timer_ == nullptr) {
2015             timer_ = std::make_shared<DmTimer>();
2016         }
2017         std::string udid = it.first;
2018         timer_->StartTimer(std::string(USER_SWITCH_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid),
2019             USER_SWITCH_BY_WIFI_TIMEOUT_S,
2020             [this, localUdid, foregroundUserIds, backgroundUserIds, udid] (std::string name) {
2021                 DeviceManagerService::HandleUserSwitchTimeout(localUdid, foregroundUserIds, backgroundUserIds, udid);
2022             });
2023     }
2024 }
2025 
HandleUserSwitchTimeout(const std::string & localUdid,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds,const std::string & udid)2026 void DeviceManagerService::HandleUserSwitchTimeout(const std::string &localUdid,
2027     const std::vector<int32_t> &foregroundUserIds, const std::vector<int32_t> &backgroundUserIds,
2028     const std::string &udid)
2029 {
2030     LOGI("start udid: %{public}s", GetAnonyString(udid).c_str());
2031     std::vector<std::string> updateUdids;
2032     updateUdids.push_back(udid);
2033     UpdateAclAndDeleteGroup(localUdid, updateUdids, foregroundUserIds, backgroundUserIds);
2034 }
2035 
UpdateAclAndDeleteGroup(const std::string & localUdid,const std::vector<std::string> & deviceVec,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2036 void DeviceManagerService::UpdateAclAndDeleteGroup(const std::string &localUdid,
2037     const std::vector<std::string> &deviceVec, const std::vector<int32_t> &foregroundUserIds,
2038     const std::vector<int32_t> &backgroundUserIds)
2039 {
2040     CHECK_NULL_VOID(discoveryMgr_);
2041     if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
2042         LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
2043         return;
2044     }
2045     discoveryMgr_->GetCommonDependencyObj()->HandleUserSwitched(localUdid, deviceVec,
2046         foregroundUserIds, backgroundUserIds);
2047     //delete group
2048     CHECK_NULL_VOID(hichainListener_);
2049     hichainListener_->DeleteAllGroup(localUdid, backgroundUserIds);
2050 }
2051 #endif
2052 
HandleAccountLogout(int32_t userId,const std::string & accountId,const std::string & accountName)2053 void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string &accountId,
2054     const std::string &accountName)
2055 {
2056     LOGI("UserId: %{public}d, accountId: %{public}s, accountName: %{public}s", userId,
2057         GetAnonyString(accountId).c_str(), GetAnonyString(accountName).c_str());
2058     if (IsDMServiceAdapterResidentLoad()) {
2059         dmServiceImplExtResident_->AccountIdLogout(userId, accountId);
2060     }
2061     if (!IsDMServiceImplReady()) {
2062         LOGE("Init impl failed.");
2063         return;
2064     }
2065     std::multimap<std::string, int32_t> deviceMap;
2066     std::vector<std::string> peerUdids;
2067     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2068     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2069     std::string localUdid = std::string(localUdidTemp);
2070     deviceMap = dmServiceImpl_->GetDeviceIdAndUserId(userId, accountId);
2071     for (const auto &item : deviceMap) {
2072         peerUdids.emplace_back(item.first);
2073     }
2074     if (!peerUdids.empty()) {
2075         char accountIdHash[DM_MAX_DEVICE_ID_LEN] = {0};
2076         if (Crypto::GetAccountIdHash(accountId, reinterpret_cast<uint8_t *>(accountIdHash)) != DM_OK) {
2077             LOGE("GetAccountHash failed.");
2078             return;
2079         }
2080         NotifyRemoteLocalLogout(peerUdids, std::string(accountIdHash), accountName, userId);
2081     }
2082     for (const auto &item : deviceMap) {
2083         dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second);
2084     }
2085 }
2086 
HandleUserSwitched(int32_t curUserId,int32_t preUserId)2087 void DeviceManagerService::HandleUserSwitched(int32_t curUserId, int32_t preUserId)
2088 {
2089     LOGI("currentUserId: %{public}d. previousUserId: %{public}d", curUserId, preUserId);
2090     if (!IsDMServiceImplReady()) {
2091         LOGE("Init impl failed.");
2092         return;
2093     }
2094     std::map<std::string, int32_t> curUserDeviceMap;
2095     std::map<std::string, int32_t> preUserDeviceMap;
2096     std::vector<std::string> peerUdids;
2097     curUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(curUserId);
2098     preUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(preUserId);
2099     for (const auto &item : curUserDeviceMap) {
2100         peerUdids.push_back(item.first);
2101     }
2102     for (const auto &item : preUserDeviceMap) {
2103         if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) {
2104             peerUdids.push_back(item.first);
2105         }
2106     }
2107     if (peerUdids.empty()) {
2108         return;
2109     }
2110     std::vector<int32_t> foregroundUserVec;
2111     int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec);
2112     std::vector<int32_t> backgroundUserVec;
2113     int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec);
2114     if (retFront != DM_OK || retBack != DM_OK || foregroundUserVec.empty()) {
2115         LOGE("Get userids failed, retFront: %{public}d, retBack: %{public}d, foreground user num: %{public}d",
2116             retFront, retBack, static_cast<int32_t>(foregroundUserVec.size()));
2117         return;
2118     }
2119     NotifyRemoteLocalUserSwitch(curUserId, preUserId, peerUdids, foregroundUserVec, backgroundUserVec);
2120 }
2121 
HandleUserRemoved(int32_t removedUserId)2122 void DeviceManagerService::HandleUserRemoved(int32_t removedUserId)
2123 {
2124     LOGI("PreUserId %{public}d.", removedUserId);
2125     if (!IsDMServiceImplReady()) {
2126         LOGE("Init impl failed.");
2127         return;
2128     }
2129     std::multimap<std::string, int32_t> deviceMap = dmServiceImpl_->GetDeviceIdAndUserId(removedUserId);
2130     std::vector<std::string> peerUdids;
2131     for (const auto &item : deviceMap) {
2132         if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) {
2133             peerUdids.emplace_back(item.first);
2134         }
2135     }
2136     if (!peerUdids.empty()) {
2137         // Send UserId Removed broadcast
2138         SendUserRemovedBroadCast(peerUdids, removedUserId);
2139     }
2140     dmServiceImpl_->HandleUserRemoved(removedUserId);
2141 }
2142 
SendUserRemovedBroadCast(const std::vector<std::string> & peerUdids,int32_t userId)2143 void DeviceManagerService::SendUserRemovedBroadCast(const std::vector<std::string> &peerUdids, int32_t userId)
2144 {
2145     LOGI("peerUdids: %{public}s, userId %{public}d.", GetAnonyStringList(peerUdids).c_str(), userId);
2146     RelationShipChangeMsg msg;
2147     msg.type = RelationShipChangeType::DEL_USER;
2148     msg.userId = static_cast<uint32_t>(userId);
2149     msg.peerUdids = peerUdids;
2150     std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2151     CHECK_NULL_VOID(softbusListener_);
2152     softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2153 }
2154 
SendAccountLogoutBroadCast(const std::vector<std::string> & peerUdids,const std::string & accountId,const std::string & accountName,int32_t userId)2155 void DeviceManagerService::SendAccountLogoutBroadCast(const std::vector<std::string> &peerUdids,
2156     const std::string &accountId, const std::string &accountName, int32_t userId)
2157 {
2158     LOGI("accountId %{public}s, accountName %{public}s, userId %{public}d.", GetAnonyString(accountId).c_str(),
2159         GetAnonyString(accountName).c_str(), userId);
2160     RelationShipChangeMsg msg;
2161     msg.type = RelationShipChangeType::ACCOUNT_LOGOUT;
2162     msg.userId = static_cast<uint32_t>(userId);
2163     msg.peerUdids = peerUdids;
2164     msg.accountId = accountId;
2165     msg.accountName = accountName;
2166     std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2167     CHECK_NULL_VOID(softbusListener_);
2168     softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2169 }
2170 
SendUserIdsBroadCast(const std::vector<std::string> & peerUdids,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds,bool isNeedResponse)2171 void DeviceManagerService::SendUserIdsBroadCast(const std::vector<std::string> &peerUdids,
2172     const std::vector<int32_t> &foregroundUserIds, const std::vector<int32_t> &backgroundUserIds, bool isNeedResponse)
2173 {
2174     LOGI("peerUdids: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, isNeedRsp: %{public}s",
2175         GetAnonyStringList(peerUdids).c_str(), GetIntegerList<int32_t>(foregroundUserIds).c_str(),
2176         GetIntegerList<int32_t>(backgroundUserIds).c_str(), isNeedResponse ? "true" : "false");
2177     RelationShipChangeMsg msg;
2178     msg.type = RelationShipChangeType::SYNC_USERID;
2179     msg.peerUdids = peerUdids;
2180     msg.syncUserIdFlag = isNeedResponse;
2181     for (const auto &userId : foregroundUserIds) {
2182         msg.userIdInfos.push_back({ true, static_cast<uint16_t>(userId) });
2183     }
2184     for (auto const &userId : backgroundUserIds) {
2185         msg.userIdInfos.push_back({ false, static_cast<uint16_t>(userId) });
2186     }
2187     std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2188     CHECK_NULL_VOID(softbusListener_);
2189     softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2190 }
2191 
HandleUserIdsBroadCast(const std::vector<UserIdInfo> & remoteUserIdInfos,const std::string & remoteUdid,bool isNeedResponse)2192 void DeviceManagerService::HandleUserIdsBroadCast(const std::vector<UserIdInfo> &remoteUserIdInfos,
2193     const std::string &remoteUdid, bool isNeedResponse)
2194 {
2195     LOGI("rmtUdid: %{public}s, rmtUserIds: %{public}s, isNeedResponse: %{public}s,",
2196         GetAnonyString(remoteUdid).c_str(), GetUserIdInfoList(remoteUserIdInfos).c_str(),
2197         isNeedResponse ? "true" : "false");
2198     if (isNeedResponse) {
2199         std::vector<int32_t> foregroundUserVec;
2200         std::vector<int32_t> backgroundUserVec;
2201         int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec);
2202         int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec);
2203         if (IsPC()) {
2204             MultipleUserConnector::ClearLockedUser(foregroundUserVec, backgroundUserVec);
2205         }
2206         if (retFront != DM_OK || retBack!= DM_OK) {
2207             LOGE("Get userid failed, retFront: %{public}d, retBack: %{public}d, frontUserNum:%{public}d,"
2208                  "backUserNum: %{public}d", retFront, retBack, static_cast<int32_t>(foregroundUserVec.size()),
2209                  static_cast<int32_t>(backgroundUserVec.size()));
2210         } else {
2211             LOGE("Send back local frontuserids: %{public}s, backuserids: %{public}s",
2212                 GetIntegerList(foregroundUserVec).c_str(), GetIntegerList(backgroundUserVec).c_str());
2213             std::vector<std::string> remoteUdids = { remoteUdid };
2214             SendUserIdsBroadCast(remoteUdids, foregroundUserVec, backgroundUserVec, false);
2215         }
2216     }
2217 
2218     std::vector<UserIdInfo> foregroundUserIdInfos;
2219     std::vector<UserIdInfo> backgroundUserIdInfos;
2220     GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos);
2221     LOGI("process foreground and background userids");
2222     // Notify received remote foreground userids to dsoftbus
2223     std::vector<uint32_t> foregroundUserIds;
2224     for (const auto &u : foregroundUserIdInfos) {
2225         foregroundUserIds.push_back(static_cast<uint32_t>(u.userId));
2226     }
2227     std::vector<uint32_t> backgroundUserIds;
2228     for (const auto &u : backgroundUserIdInfos) {
2229         backgroundUserIds.push_back(static_cast<uint32_t>(u.userId));
2230     }
2231     if (softbusListener_ != nullptr) {
2232         softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, foregroundUserIds);
2233     }
2234 
2235     if (IsDMServiceImplReady()) {
2236         dmServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid, IsPC());
2237     }
2238 }
2239 
ProcessSyncUserIds(const std::vector<uint32_t> & foregroundUserIds,const std::vector<uint32_t> & backgroundUserIds,const std::string & remoteUdid)2240 void DeviceManagerService::ProcessSyncUserIds(const std::vector<uint32_t> &foregroundUserIds,
2241     const std::vector<uint32_t> &backgroundUserIds, const std::string &remoteUdid)
2242 {
2243     LOGI("process sync foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, remote udid: %{public}s",
2244         GetIntegerList<uint32_t>(foregroundUserIds).c_str(), GetIntegerList<uint32_t>(backgroundUserIds).c_str(),
2245         GetAnonyString(remoteUdid).c_str());
2246 
2247     if (softbusListener_ != nullptr) {
2248         softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, foregroundUserIds);
2249     }
2250     if (timer_ != nullptr) {
2251         timer_->DeleteTimer(std::string(USER_SWITCH_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(remoteUdid));
2252     }
2253     if (IsDMServiceImplReady()) {
2254         dmServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid, IsPC());
2255     }
2256 }
2257 
ScreenCommonEventCallback(std::string commonEventType)2258 void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType)
2259 {
2260     if (!IsDMImplSoLoaded()) {
2261         LOGE("ScreenCommonEventCallback failed, instance not init or init failed.");
2262         return;
2263     }
2264     dmServiceImpl_->ScreenCommonEventCallback(commonEventType);
2265 }
2266 #endif
2267 
HandleDeviceNotTrust(const std::string & msg)2268 void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg)
2269 {
2270     LOGI("Start.");
2271     if (msg.empty()) {
2272         LOGE("DeviceManagerService::HandleDeviceNotTrust msg is empty.");
2273         return;
2274     }
2275     JsonObject msgJsonObj(msg);
2276     if (msgJsonObj.IsDiscarded()) {
2277         LOGE("HandleDeviceNotTrust msg prase error.");
2278         return;
2279     }
2280     if (!IsString(msgJsonObj, NETWORKID)) {
2281         LOGE("HandleDeviceNotTrust msg not contain networkId.");
2282         return;
2283     }
2284     std::string networkId = msgJsonObj[NETWORKID].Get<std::string>();
2285     std::string udid = "";
2286     SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid);
2287     LOGI("NetworkId: %{public}s, udid: %{public}s.",
2288         GetAnonyString(networkId).c_str(), GetAnonyString(udid).c_str());
2289     if (IsDMServiceImplReady()) {
2290         dmServiceImpl_->HandleDeviceNotTrust(udid);
2291     }
2292     if (IsDMServiceAdapterResidentLoad()) {
2293         dmServiceImplExtResident_->HandleDeviceNotTrust(udid);
2294     }
2295     return;
2296 }
2297 
SetDnPolicy(const std::string & pkgName,std::map<std::string,std::string> & policy)2298 int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::map<std::string, std::string> &policy)
2299 {
2300     if (!PermissionManager::GetInstance().CheckPermission()) {
2301         LOGE("The caller does not have permission to call");
2302         return ERR_DM_NO_PERMISSION;
2303     }
2304     std::string processName = "";
2305     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
2306         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
2307         return ERR_DM_FAILED;
2308     }
2309     if (!PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName)) {
2310         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
2311         return ERR_DM_INPUT_PARA_INVALID;
2312     }
2313     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
2314     if (pkgName.empty()) {
2315         LOGE("Invalid parameter, pkgName is empty.");
2316         return ERR_DM_INPUT_PARA_INVALID;
2317     }
2318     auto policyStrategyIter = policy.find(PARAM_KEY_POLICY_STRATEGY_FOR_BLE);
2319     if (policyStrategyIter == policy.end()) {
2320         LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is empty.");
2321         return ERR_DM_INPUT_PARA_INVALID;
2322     }
2323     auto timeOutIter = policy.find(PARAM_KEY_POLICY_TIME_OUT);
2324     if (timeOutIter == policy.end()) {
2325         LOGE("Invalid parameter, DM_POLICY_TIMEOUT is empty.");
2326         return ERR_DM_INPUT_PARA_INVALID;
2327     }
2328     if (!IsNumberString(policyStrategyIter->second)) {
2329         LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is not number.");
2330         return ERR_DM_INPUT_PARA_INVALID;
2331     }
2332     if (!IsNumberString(timeOutIter->second)) {
2333         LOGE("Invalid parameter, DM_POLICY_TIMEOUT is not number.");
2334         return ERR_DM_INPUT_PARA_INVALID;
2335     }
2336     int32_t policyStrategy = std::atoi(policyStrategyIter->second.c_str());
2337     int32_t timeOut = std::atoi(timeOutIter->second.c_str());
2338     LOGD("strategy: %{public}d, timeOut: %{public}d", policyStrategy, timeOut);
2339     if (!IsDMServiceAdapterResidentLoad()) {
2340         LOGE("SetDnPolicy failed, instance not init or init failed.");
2341         return ERR_DM_UNSUPPORTED_METHOD;
2342     }
2343     return dmServiceImplExtResident_->SetDnPolicy(policyStrategy, timeOut);
2344 }
2345 
2346 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
ConvertUdidHashToAnoyDeviceId(DmDeviceInfo & deviceInfo)2347 void DeviceManagerService::ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInfo)
2348 {
2349     std::string udidHashTemp = "";
2350     if (ConvertUdidHashToAnoyDeviceId(deviceInfo.deviceId, udidHashTemp) == DM_OK) {
2351         if (memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) {
2352             LOGE("ConvertUdidHashToAnoyDeviceId memset_s failed.");
2353             return;
2354         }
2355         if (memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) {
2356             LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str());
2357             return;
2358         }
2359     }
2360 }
2361 
ConvertUdidHashToAnoyDeviceId(const std::string & udidHash,std::string & result)2362 int32_t DeviceManagerService::ConvertUdidHashToAnoyDeviceId(const std::string &udidHash, std::string &result)
2363 {
2364     LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str());
2365     std::string appId = AppManager::GetInstance().GetAppId();
2366     if (appId.empty()) {
2367         LOGD("GetAppId failed");
2368         return ERR_DM_FAILED;
2369     }
2370     DmKVValue kvValue;
2371     int32_t ret = Crypto::ConvertUdidHashToAnoyAndSave(appId, udidHash, kvValue);
2372     if (ret != DM_OK) {
2373         return ERR_DM_FAILED;
2374     }
2375     result = kvValue.anoyDeviceId;
2376     return DM_OK;
2377 }
2378 
GetUdidHashByAnoyDeviceId(const std::string & anoyDeviceId,std::string & udidHash)2379 int32_t DeviceManagerService::GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash)
2380 {
2381     LOGI("anoyDeviceId %{public}s.", GetAnonyString(anoyDeviceId).c_str());
2382     DmKVValue kvValue;
2383     if (KVAdapterManager::GetInstance().Get(anoyDeviceId, kvValue) != DM_OK) {
2384         LOGD("Get kv value from DB failed");
2385         return ERR_DM_FAILED;
2386     }
2387     udidHash = kvValue.udidHash;
2388     LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str());
2389     return DM_OK;
2390 }
2391 
SendUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId,int32_t bindLevel)2392 void DeviceManagerService::SendUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
2393     uint64_t tokenId, int32_t bindLevel)
2394 {
2395     LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId);
2396     if (bindLevel == DEVICE) {
2397         SendDeviceUnBindBroadCast(peerUdids, userId);
2398         return;
2399     }
2400     if (bindLevel == APP) {
2401         SendAppUnBindBroadCast(peerUdids, userId, tokenId);
2402         return;
2403     }
2404     if (bindLevel == SERVICE) {
2405         SendServiceUnBindBroadCast(peerUdids, userId, tokenId);
2406         return;
2407     }
2408 }
2409 
SendUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId,int32_t bindLevel,uint64_t peerTokenId)2410 void DeviceManagerService::SendUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
2411     uint64_t tokenId, int32_t bindLevel, uint64_t peerTokenId)
2412 {
2413     if (bindLevel == DEVICE) {
2414         SendDeviceUnBindBroadCast(peerUdids, userId);
2415         return;
2416     }
2417     if (bindLevel == APP) {
2418         SendAppUnBindBroadCast(peerUdids, userId, tokenId, peerTokenId);
2419         return;
2420     }
2421     if (bindLevel == SERVICE) {
2422         SendServiceUnBindBroadCast(peerUdids, userId, tokenId);
2423         return;
2424     }
2425 }
2426 
SendDeviceUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId)2427 void DeviceManagerService::SendDeviceUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId)
2428 {
2429     RelationShipChangeMsg msg;
2430     msg.type = RelationShipChangeType::DEVICE_UNBIND;
2431     msg.userId = static_cast<uint32_t>(userId);
2432     msg.peerUdids = peerUdids;
2433     std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2434     CHECK_NULL_VOID(softbusListener_);
2435     softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2436 }
2437 
SendAppUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId)2438 void DeviceManagerService::SendAppUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
2439     uint64_t tokenId)
2440 {
2441     RelationShipChangeMsg msg;
2442     msg.type = RelationShipChangeType::APP_UNBIND;
2443     msg.userId = static_cast<uint32_t>(userId);
2444     msg.peerUdids = peerUdids;
2445     msg.tokenId = tokenId;
2446     std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2447     CHECK_NULL_VOID(softbusListener_);
2448     softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2449 }
2450 
SendAppUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId,uint64_t peerTokenId)2451 void DeviceManagerService::SendAppUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
2452     uint64_t tokenId, uint64_t peerTokenId)
2453 {
2454     RelationShipChangeMsg msg;
2455     msg.type = RelationShipChangeType::APP_UNBIND;
2456     msg.userId = static_cast<uint32_t>(userId);
2457     msg.peerUdids = peerUdids;
2458     msg.tokenId = tokenId;
2459     msg.peerTokenId = peerTokenId;
2460     std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2461     CHECK_NULL_VOID(softbusListener_);
2462     softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2463 }
2464 
SendServiceUnBindBroadCast(const std::vector<std::string> & peerUdids,int32_t userId,uint64_t tokenId)2465 void DeviceManagerService::SendServiceUnBindBroadCast(const std::vector<std::string> &peerUdids, int32_t userId,
2466     uint64_t tokenId)
2467 {
2468     RelationShipChangeMsg msg;
2469     msg.type = RelationShipChangeType::SERVICE_UNBIND;
2470     msg.userId = static_cast<uint32_t>(userId);
2471     msg.peerUdids = peerUdids;
2472     msg.tokenId = tokenId;
2473     std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
2474     CHECK_NULL_VOID(softbusListener_);
2475     softbusListener_->SendAclChangedBroadcast(broadCastMsg);
2476 }
2477 
HandleDeviceTrustedChange(const std::string & msg)2478 void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg)
2479 {
2480     if (msg.empty()) {
2481         LOGE("Msg is empty.");
2482         return;
2483     }
2484     RelationShipChangeMsg relationShipMsg =
2485         ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg);
2486     LOGI("Receive trust change msg: %{public}s", relationShipMsg.ToString().c_str());
2487     if (!IsDMServiceImplReady()) {
2488         LOGE("Imp instance not init or init failed.");
2489         return;
2490     }
2491     switch (relationShipMsg.type) {
2492         case RelationShipChangeType::ACCOUNT_LOGOUT:
2493             dmServiceImpl_->HandleAccountLogoutEvent(relationShipMsg.userId, relationShipMsg.accountId,
2494                 relationShipMsg.peerUdid);
2495             break;
2496         case RelationShipChangeType::DEVICE_UNBIND:
2497             dmServiceImpl_->HandleDevUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid);
2498             break;
2499         case RelationShipChangeType::APP_UNBIND:
2500             if (relationShipMsg.peerTokenId != 0) {
2501                     dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid,
2502                         static_cast<int32_t>(relationShipMsg.tokenId),
2503                         static_cast<int32_t>(relationShipMsg.peerTokenId));
2504             } else {
2505                 dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid,
2506                     static_cast<int32_t>(relationShipMsg.tokenId));
2507             }
2508             break;
2509         case RelationShipChangeType::SYNC_USERID:
2510             HandleUserIdsBroadCast(relationShipMsg.userIdInfos,
2511                 relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag);
2512             break;
2513         case RelationShipChangeType::DEL_USER:
2514             dmServiceImpl_->HandleRemoteUserRemoved(relationShipMsg.userId, relationShipMsg.peerUdid);
2515             break;
2516         case RelationShipChangeType::STOP_USER:
2517             HandleUserStopBroadCast(relationShipMsg.userId, relationShipMsg.peerUdid);
2518             break;
2519         default:
2520             LOGI("Dm have not this event type.");
2521             break;
2522     }
2523     return;
2524 }
2525 
ParseCheckSumMsg(const std::string & msg,std::string & networkId,uint32_t & discoveryType,bool & isChange)2526 int32_t DeviceManagerService::ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType,
2527     bool &isChange)
2528 {
2529     JsonObject msgJsonObj(msg);
2530     if (msgJsonObj.IsDiscarded()) {
2531         LOGE("msg prase error.");
2532         return ERR_DM_FAILED;
2533     }
2534     if (!IsString(msgJsonObj, USERID_CHECKSUM_NETWORKID_KEY)) {
2535         LOGE("msg not contain networkId.");
2536         return ERR_DM_FAILED;
2537     }
2538     if (!IsUint32(msgJsonObj, USERID_CHECKSUM_DISCOVER_TYPE_KEY)) {
2539         LOGE("msg not contain discoveryType.");
2540         return ERR_DM_FAILED;
2541     }
2542     if (!IsBool(msgJsonObj, USERID_CHECKSUM_ISCHANGE_KEY)) {
2543         LOGE("msg not contain ischange.");
2544         return ERR_DM_FAILED;
2545     }
2546     networkId = msgJsonObj[USERID_CHECKSUM_NETWORKID_KEY].Get<std::string>();
2547     discoveryType = msgJsonObj[USERID_CHECKSUM_DISCOVER_TYPE_KEY].Get<uint32_t>();
2548     isChange = msgJsonObj[USERID_CHECKSUM_ISCHANGE_KEY].Get<bool>();
2549     return DM_OK;
2550 }
2551 
ProcessCheckSumByWifi(std::string networkId,std::vector<int32_t> foregroundUserIds,std::vector<int32_t> backgroundUserIds)2552 void DeviceManagerService::ProcessCheckSumByWifi(std::string networkId, std::vector<int32_t> foregroundUserIds,
2553     std::vector<int32_t> backgroundUserIds)
2554 {
2555     if (localNetWorkId_ == "") {
2556         DmDeviceInfo deviceInfo;
2557         SoftbusCache::GetInstance().GetLocalDeviceInfo(deviceInfo);
2558         localNetWorkId_ = std::string(deviceInfo.networkId);
2559     }
2560     if (localNetWorkId_ >= networkId) {
2561         LOGI("Local networkid big than remote, no need begin req");
2562         return;
2563     }
2564     // use connection to exchange foreground/background userid
2565     LOGI("Try open softbus session to exchange foreground/background userid");
2566     std::vector<uint32_t> foregroundUserIdsUInt;
2567     for (auto const &u : foregroundUserIds) {
2568         foregroundUserIdsUInt.push_back(static_cast<uint32_t>(u));
2569     }
2570     std::vector<uint32_t> backgroundUserIdsUInt;
2571     for (auto const &u : backgroundUserIds) {
2572         backgroundUserIdsUInt.push_back(static_cast<uint32_t>(u));
2573     }
2574     DMCommTool::GetInstance()->SendUserIds(networkId, foregroundUserIdsUInt, backgroundUserIdsUInt);
2575 }
2576 
ProcessCheckSumByBT(std::string networkId,std::vector<int32_t> foregroundUserIds,std::vector<int32_t> backgroundUserIds)2577 void DeviceManagerService::ProcessCheckSumByBT(std::string networkId, std::vector<int32_t> foregroundUserIds,
2578     std::vector<int32_t> backgroundUserIds)
2579 {
2580     LOGI("Try send brodcast to exchange foreground userid");
2581     std::string udid = "";
2582     SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid);
2583     if (udid.empty()) {
2584         LOGE("Can not get udid for networkid: %{public}s", GetAnonyString(networkId).c_str());
2585         return;
2586     }
2587 
2588     std::vector<std::string> peerUdids = { udid };
2589     if (!foregroundUserIds.empty()) {
2590         LOGI("Send local foreground and background userids");
2591         SendUserIdsBroadCast(peerUdids, foregroundUserIds, backgroundUserIds, true);
2592     } else {
2593         LOGE("local foreground userids empty");
2594     }
2595 }
2596 
HandleUserIdCheckSumChange(const std::string & msg)2597 void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg)
2598 {
2599     if (msg.empty()) {
2600         LOGE("Msg is empty.");
2601         return;
2602     }
2603     LOGI("handle user trust change, msg: %{public}s", GetAnonyString(msg).c_str());
2604     std::string remoteNetworkId = "";
2605     uint32_t discoveryType = 0;
2606     bool isPeerUserIdChanged = true;
2607     int32_t ret = ParseCheckSumMsg(msg, remoteNetworkId, discoveryType, isPeerUserIdChanged);
2608     if (ret != DM_OK) {
2609         LOGE("Parse checksum msg error");
2610         return;
2611     }
2612     if (!isPeerUserIdChanged) {
2613         LOGI("Peer foreground userId not change.");
2614         return;
2615     }
2616     std::vector<int32_t> foregroundUserIds;
2617     ret = MultipleUserConnector::GetForegroundUserIds(foregroundUserIds);
2618     if (ret != DM_OK || foregroundUserIds.empty()) {
2619         LOGE("Get foreground userids failed, ret: %{public}d", ret);
2620         return;
2621     }
2622 
2623     std::vector<int32_t> backgroundUserIds;
2624     ret = MultipleUserConnector::GetBackgroundUserIds(backgroundUserIds);
2625     if (ret != DM_OK || backgroundUserIds.empty()) {
2626         LOGI("Can not get background userids, ret: %{public}d, background userid num: %{public}d",
2627             ret, static_cast<int32_t>(backgroundUserIds.size()));
2628     }
2629 
2630     if ((discoveryType & USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK) != 0x0) {
2631         ProcessCheckSumByWifi(remoteNetworkId, foregroundUserIds, backgroundUserIds);
2632     } else {
2633         ProcessCheckSumByBT(remoteNetworkId, foregroundUserIds, backgroundUserIds);
2634     }
2635 }
2636 #endif
2637 
ClearDiscoveryCache(const ProcessInfo & processInfo)2638 void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo)
2639 {
2640     LOGI("PkgName: %{public}s, userId: %{public}d", processInfo.pkgName.c_str(), processInfo.userId);
2641     CHECK_NULL_VOID(discoveryMgr_);
2642     discoveryMgr_->ClearDiscoveryCache(processInfo);
2643 }
2644 
HandleDeviceScreenStatusChange(DmDeviceInfo & deviceInfo)2645 void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo)
2646 {
2647     if (IsDMServiceImplReady()) {
2648         dmServiceImpl_->HandleDeviceScreenStatusChange(deviceInfo);
2649     }
2650 }
2651 
GetDeviceScreenStatus(const std::string & pkgName,const std::string & networkId,int32_t & screenStatus)2652 int32_t DeviceManagerService::GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId,
2653     int32_t &screenStatus)
2654 {
2655     LOGI("Begin pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str());
2656     if (!PermissionManager::GetInstance().CheckPermission()) {
2657         LOGE("The caller: %{public}s does not have permission to call GetDeviceScreenStatus.", pkgName.c_str());
2658         return ERR_DM_NO_PERMISSION;
2659     }
2660     if (pkgName.empty() || networkId.empty()) {
2661         LOGE("Invalid parameter, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(),
2662             GetAnonyString(networkId).c_str());
2663         return ERR_DM_INPUT_PARA_INVALID;
2664     }
2665     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
2666     int32_t ret = softbusListener_->GetDeviceScreenStatus(networkId.c_str(), screenStatus);
2667     if (ret != DM_OK) {
2668         LOGE("GetDeviceScreenStatus failed, ret = %{public}d", ret);
2669         return ret;
2670     }
2671     return DM_OK;
2672 }
2673 
GetNetworkIdByUdid(const std::string & pkgName,const std::string & udid,std::string & networkId)2674 int32_t DeviceManagerService::GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid,
2675                                                  std::string &networkId)
2676 {
2677     if (!PermissionManager::GetInstance().CheckPermission()) {
2678         LOGE("The caller: %{public}s does not have permission to call GetNetworkIdByUdid.", pkgName.c_str());
2679         return ERR_DM_NO_PERMISSION;
2680     }
2681     if (pkgName.empty() || udid.empty()) {
2682         LOGE("Invalid parameter, pkgName: %{public}s, udid: %{public}s", pkgName.c_str(), GetAnonyString(udid).c_str());
2683         return ERR_DM_INPUT_PARA_INVALID;
2684     }
2685     return SoftbusListener::GetNetworkIdByUdid(udid, networkId);
2686 }
2687 
SubscribePackageCommonEvent()2688 void DeviceManagerService::SubscribePackageCommonEvent()
2689 {
2690     LOGI("Start");
2691 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
2692     if (packageCommonEventManager_ == nullptr) {
2693         packageCommonEventManager_ = std::make_shared<DmPackageCommonEventManager>();
2694     }
2695     PackageEventCallback callback = [=](const auto &arg1, const auto &arg2, const auto &arg3) {
2696         if (IsDMServiceImplReady()) {
2697             dmServiceImpl_->ProcessAppUnintall(arg1, arg3);
2698         }
2699         KVAdapterManager::GetInstance().AppUnintall(arg1);
2700     };
2701     std::vector<std::string> commonEventVec;
2702     commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
2703     commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED);
2704     if (packageCommonEventManager_->SubscribePackageCommonEvent(commonEventVec, callback)) {
2705         LOGI("Success");
2706     }
2707 #endif
2708 }
2709 
HandleCredentialAuthStatus(const std::string & deviceList,uint16_t deviceTypeId,int32_t errcode)2710 void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId,
2711                                                       int32_t errcode)
2712 {
2713     if (IsDMServiceImplReady()) {
2714         dmServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode);
2715     }
2716 }
2717 
RemoveNotifyRecord(const ProcessInfo & processInfo)2718 void DeviceManagerService::RemoveNotifyRecord(const ProcessInfo &processInfo)
2719 {
2720     LOGI("start");
2721     CHECK_NULL_VOID(listener_);
2722     listener_->OnProcessRemove(processInfo);
2723 }
2724 
RegDevStateCallbackToService(const std::string & pkgName)2725 int32_t DeviceManagerService::RegDevStateCallbackToService(const std::string &pkgName)
2726 {
2727 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
2728     CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL);
2729     std::vector<DmDeviceInfo> deviceList;
2730     GetTrustedDeviceList(pkgName, deviceList);
2731     if (deviceList.size() == 0) {
2732         return DM_OK;
2733     }
2734     int32_t userId = -1;
2735     MultipleUserConnector::GetCallerUserId(userId);
2736     ProcessInfo processInfo;
2737     processInfo.pkgName = pkgName;
2738     processInfo.userId = userId;
2739     listener_->OnDevStateCallbackAdd(processInfo, deviceList);
2740 #else
2741     (void)pkgName;
2742 #endif
2743     return DM_OK;
2744 }
2745 
GetTrustedDeviceList(const std::string & pkgName,std::vector<DmDeviceInfo> & deviceList)2746 int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, std::vector<DmDeviceInfo> &deviceList)
2747 {
2748     LOGI("Begin for pkgName = %{public}s.", pkgName.c_str());
2749     if (pkgName.empty()) {
2750         LOGE("Invalid parameter, pkgName is empty.");
2751         return ERR_DM_INPUT_PARA_INVALID;
2752     }
2753     std::vector<DmDeviceInfo> onlineDeviceList;
2754     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
2755     int32_t ret = softbusListener_->GetTrustedDeviceList(onlineDeviceList);
2756     if (ret != DM_OK) {
2757         LOGE("failed");
2758         return ret;
2759     }
2760     if (!onlineDeviceList.empty() && IsDMServiceImplReady()) {
2761         dmServiceImpl_->DeleteAlwaysAllowTimeOut();
2762         std::unordered_map<std::string, DmAuthForm> udidMap;
2763         if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName)) {
2764             udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME));
2765         } else {
2766             udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName);
2767         }
2768         for (auto item : onlineDeviceList) {
2769             std::string udid = "";
2770             SoftbusListener::GetUdidByNetworkId(item.networkId, udid);
2771             if (udidMap.find(udid) != udidMap.end()) {
2772                 item.authForm = udidMap[udid];
2773                 deviceList.push_back(item);
2774             }
2775         }
2776     }
2777     return DM_OK;
2778 }
2779 
HandleDeviceUnBind(const char * peerUdid,const GroupInformation & groupInfo)2780 void DeviceManagerService::HandleDeviceUnBind(const char *peerUdid, const GroupInformation &groupInfo)
2781 {
2782     LOGI("DeviceManagerService::HandleDeviceUnBind start.");
2783     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2784     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2785     std::string localUdid = std::string(localUdidTemp);
2786     if (IsDMServiceImplReady()) {
2787         dmServiceImpl_->HandleDeviceUnBind(groupInfo.groupType, std::string(peerUdid),
2788             localUdid, groupInfo.userId, groupInfo.osAccountId);
2789     }
2790     return;
2791 }
2792 
GetAnonyLocalUdid(const std::string & pkgName,std::string & anonyUdid)2793 int32_t DeviceManagerService::GetAnonyLocalUdid(const std::string &pkgName, std::string &anonyUdid)
2794 {
2795     (void) pkgName;
2796     if (!PermissionManager::GetInstance().CheckPermission()) {
2797         LOGE("The caller does not have permission to call GetAnonyLocalUdid.");
2798         return ERR_DM_NO_PERMISSION;
2799     }
2800     std::string udid = DmRadarHelper::GetInstance().GetAnonyLocalUdid();
2801     if (udid.empty()) {
2802         LOGE("Anony local udid is empty.");
2803         return ERR_DM_FAILED;
2804     }
2805     anonyUdid = udid;
2806     return DM_OK;
2807 }
2808 
2809 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
NotifyRemoteLocalUserSwitch(int32_t curUserId,int32_t preUserId,const std::vector<std::string> & peerUdids,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2810 void DeviceManagerService::NotifyRemoteLocalUserSwitch(int32_t curUserId, int32_t preUserId,
2811     const std::vector<std::string> &peerUdids, const std::vector<int32_t> &foregroundUserIds,
2812     const std::vector<int32_t> &backgroundUserIds)
2813 {
2814     LOGI("Send local foreground and background userids");
2815     if (peerUdids.empty()) {
2816         return;
2817     }
2818     if (softbusListener_ == nullptr) {
2819         dmServiceImpl_->HandleUserSwitched(peerUdids, curUserId, preUserId);
2820         LOGE("softbusListener_ is null");
2821         return;
2822     }
2823     std::vector<std::string> bleUdids;
2824     std::map<std::string, std::string> wifiDevices;
2825     for (const auto &udid : peerUdids) {
2826         std::string netWorkId = "";
2827         SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
2828         if (netWorkId.empty()) {
2829             LOGI("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
2830             bleUdids.push_back(udid);
2831             continue;
2832         }
2833         int32_t networkType = 0;
2834         int32_t ret = softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
2835         if (ret != DM_OK || networkType <= 0) {
2836             LOGI("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
2837             bleUdids.push_back(udid);
2838             continue;
2839         }
2840         if ((static_cast<uint32_t>(networkType) & USERID_SYNC_DISCOVERY_TYPE_BLE_MASK) != 0x0) {
2841             bleUdids.push_back(udid);
2842         } else {
2843             wifiDevices.insert(std::pair<std::string, std::string>(udid, netWorkId));
2844         }
2845     }
2846     if (!bleUdids.empty()) {
2847         dmServiceImpl_->HandleUserSwitched(bleUdids, curUserId, preUserId);
2848         SendUserIdsBroadCast(bleUdids, foregroundUserIds, backgroundUserIds, true);
2849     }
2850     if (!wifiDevices.empty()) {
2851         NotifyRemoteLocalUserSwitchByWifi(curUserId, preUserId, wifiDevices, foregroundUserIds, backgroundUserIds);
2852     }
2853 }
2854 
NotifyRemoteLocalUserSwitchByWifi(int32_t curUserId,int32_t preUserId,const std::map<std::string,std::string> & wifiDevices,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2855 void DeviceManagerService::NotifyRemoteLocalUserSwitchByWifi(int32_t curUserId, int32_t preUserId,
2856     const std::map<std::string, std::string> &wifiDevices, const std::vector<int32_t> &foregroundUserIds,
2857     const std::vector<int32_t> &backgroundUserIds)
2858 {
2859     for (const auto &it : wifiDevices) {
2860         int32_t result = SendUserIdsByWifi(it.second, foregroundUserIds, backgroundUserIds);
2861         if (result != DM_OK) {
2862             LOGE("by wifi failed: %{public}s", GetAnonyString(it.first).c_str());
2863             std::vector<std::string> updateUdids;
2864             updateUdids.push_back(it.first);
2865             dmServiceImpl_->HandleUserSwitched(updateUdids, curUserId, preUserId);
2866             continue;
2867         }
2868         if (timer_ == nullptr) {
2869             timer_ = std::make_shared<DmTimer>();
2870         }
2871         std::string udid = it.first;
2872         timer_->StartTimer(std::string(USER_SWITCH_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid),
2873             USER_SWITCH_BY_WIFI_TIMEOUT_S, [this, curUserId, preUserId, udid] (std::string name) {
2874                 DeviceManagerService::HandleUserSwitchTimeout(curUserId, preUserId, udid);
2875             });
2876     }
2877 }
2878 
SendUserIdsByWifi(const std::string & networkId,const std::vector<int32_t> & foregroundUserIds,const std::vector<int32_t> & backgroundUserIds)2879 int32_t DeviceManagerService::SendUserIdsByWifi(const std::string &networkId,
2880     const std::vector<int32_t> &foregroundUserIds, const std::vector<int32_t> &backgroundUserIds)
2881 {
2882     LOGI("Try open softbus session to exchange foreground/background userid");
2883     std::vector<uint32_t> foregroundUserIdsUInt;
2884     for (auto const &u : foregroundUserIds) {
2885         foregroundUserIdsUInt.push_back(static_cast<uint32_t>(u));
2886     }
2887     std::vector<uint32_t> backgroundUserIdsUInt;
2888     for (auto const &u : backgroundUserIds) {
2889         backgroundUserIdsUInt.push_back(static_cast<uint32_t>(u));
2890     }
2891     return DMCommTool::GetInstance()->SendUserIds(networkId, foregroundUserIdsUInt, backgroundUserIdsUInt);
2892 }
2893 
HandleUserSwitchTimeout(int32_t curUserId,int32_t preUserId,const std::string & udid)2894 void DeviceManagerService::HandleUserSwitchTimeout(int32_t curUserId, int32_t preUserId, const std::string &udid)
2895 {
2896     LOGI("start udid: %{public}s", GetAnonyString(udid).c_str());
2897     std::vector<std::string> updateUdids;
2898     updateUdids.push_back(udid);
2899     dmServiceImpl_->HandleUserSwitched(updateUdids, curUserId, preUserId);
2900 }
2901 
HandleUserSwitchedEvent(int32_t currentUserId,int32_t beforeUserId)2902 void DeviceManagerService::HandleUserSwitchedEvent(int32_t currentUserId, int32_t beforeUserId)
2903 {
2904     DeviceNameManager::GetInstance().InitDeviceNameWhenUserSwitch(currentUserId, beforeUserId);
2905     CheckRegisterInfoWithWise(currentUserId);
2906     if (IsPC()) {
2907         return;
2908     }
2909     MultipleUserConnector::SetAccountInfo(currentUserId, MultipleUserConnector::GetCurrentDMAccountInfo());
2910     if (beforeUserId == -1 || currentUserId == -1) {
2911         HandleUserSwitched();
2912         return;
2913     }
2914     if (beforeUserId != -1 && currentUserId != -1) {
2915         HandleUserSwitched(currentUserId, beforeUserId);
2916     }
2917     if (IsDMServiceAdapterResidentLoad()) {
2918         dmServiceImplExtResident_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId());
2919     }
2920 }
2921 
HandleUserStopEvent(int32_t stopUserId)2922 void DeviceManagerService::HandleUserStopEvent(int32_t stopUserId)
2923 {
2924     LOGI("onStart, HandleUserStopEvent %{public}s.", GetAnonyInt32(stopUserId).c_str());
2925     std::vector<int32_t> stopUserVec;
2926     stopUserVec.push_back(stopUserId);
2927     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2928     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2929     std::string localUdid = std::string(localUdidTemp);
2930     std::map<std::string, int32_t> stopUserDeviceMap;
2931     std::vector<std::string> peerUdids;
2932     CHECK_NULL_VOID(discoveryMgr_);
2933     if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
2934         LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
2935         return;
2936     }
2937     stopUserDeviceMap = discoveryMgr_->GetCommonDependencyObj()->
2938         GetDeviceIdAndBindLevel(stopUserVec, localUdid);
2939     for (const auto &item : stopUserDeviceMap) {
2940         peerUdids.push_back(item.first);
2941     }
2942     if (peerUdids.empty()) {
2943         LOGI("no data to be stoped.");
2944         return;
2945     }
2946     NotifyRemoteLocalUserStop(localUdid, peerUdids, stopUserId);
2947 }
2948 
DivideNotifyMethod(const std::vector<std::string> & peerUdids,std::vector<std::string> & bleUdids,std::map<std::string,std::string> & wifiDevices)2949 void DeviceManagerService::DivideNotifyMethod(const std::vector<std::string> &peerUdids,
2950     std::vector<std::string> &bleUdids, std::map<std::string, std::string> &wifiDevices)
2951 {
2952     if (peerUdids.empty()) {
2953         return;
2954     }
2955     if (softbusListener_ == nullptr) {
2956         bleUdids = peerUdids;
2957         LOGI("softbusListener_ is null");
2958         return;
2959     }
2960     for (const auto &udid : peerUdids) {
2961         std::string netWorkId = "";
2962         SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
2963         if (netWorkId.empty()) {
2964             LOGI("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
2965             bleUdids.push_back(udid);
2966             continue;
2967         }
2968         int32_t networkType = 0;
2969         int32_t ret = softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
2970         if (ret != DM_OK || networkType <= 0) {
2971             LOGI("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
2972             bleUdids.push_back(udid);
2973             continue;
2974         }
2975         if ((static_cast<uint32_t>(networkType) & USERID_SYNC_DISCOVERY_TYPE_BLE_MASK) != 0x0) {
2976             bleUdids.push_back(udid);
2977         } else {
2978             wifiDevices.insert(std::pair<std::string, std::string>(udid, netWorkId));
2979         }
2980     }
2981 }
2982 
HandleUserStop(int32_t stopUserId,const std::string & stopEventUdid,const std::vector<std::string> & acceptEventUdids)2983 void DeviceManagerService::HandleUserStop(int32_t stopUserId, const std::string &stopEventUdid,
2984     const std::vector<std::string> &acceptEventUdids)
2985 {
2986     if (timer_ != nullptr) {
2987         for (const auto &udid : acceptEventUdids) {
2988             timer_->DeleteTimer(std::string(USER_STOP_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid));
2989         }
2990     }
2991     if (MultipleUserConnector::IsUserUnlocked(stopUserId)) {
2992         LOGE("user has unlocked %{public}s.", GetAnonyInt32(stopUserId).c_str());
2993         return;
2994     }
2995     CHECK_NULL_VOID(discoveryMgr_);
2996     if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
2997         LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
2998         return;
2999     }
3000     discoveryMgr_->GetCommonDependencyObj()->HandleUserStop(stopUserId, stopEventUdid, acceptEventUdids);
3001 }
3002 
HandleUserStop(int32_t stopUserId,const std::string & stopEventUdid)3003 void DeviceManagerService::HandleUserStop(int32_t stopUserId, const std::string &stopEventUdid)
3004 {
3005     CHECK_NULL_VOID(discoveryMgr_);
3006     if (!discoveryMgr_->IsCommonDependencyReady() || discoveryMgr_->GetCommonDependencyObj() == nullptr) {
3007         LOGE("IsCommonDependencyReady failed or GetCommonDependencyObj() is nullptr.");
3008         return;
3009     }
3010     discoveryMgr_->GetCommonDependencyObj()->HandleUserStop(stopUserId, stopEventUdid);
3011 }
3012 
NotifyRemoteLocalUserStop(const std::string & localUdid,const std::vector<std::string> & peerUdids,int32_t stopUserId)3013 void DeviceManagerService::NotifyRemoteLocalUserStop(const std::string &localUdid,
3014     const std::vector<std::string> &peerUdids, int32_t stopUserId)
3015 {
3016     std::vector<std::string> bleUdids;
3017     std::map<std::string, std::string> wifiDevices;
3018     DivideNotifyMethod(peerUdids, bleUdids, wifiDevices);
3019     if (!bleUdids.empty()) {
3020         HandleUserStop(stopUserId, localUdid, bleUdids);
3021         SendUserStopBroadCast(bleUdids, stopUserId);
3022     }
3023     if (!wifiDevices.empty()) {
3024         NotifyRemoteLocalUserStopByWifi(localUdid, wifiDevices, stopUserId);
3025     }
3026 }
3027 
SendUserStopBroadCast(const std::vector<std::string> & peerUdids,int32_t stopUserId)3028 void DeviceManagerService::SendUserStopBroadCast(const std::vector<std::string> &peerUdids, int32_t stopUserId)
3029 {
3030     LOGI("peerUdids: %{public}s", GetAnonyStringList(peerUdids).c_str());
3031     RelationShipChangeMsg msg;
3032     msg.type = RelationShipChangeType::STOP_USER;
3033     msg.userId = static_cast<uint32_t>(stopUserId);
3034     msg.peerUdids = peerUdids;
3035     std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg);
3036     CHECK_NULL_VOID(softbusListener_);
3037     softbusListener_->SendAclChangedBroadcast(broadCastMsg);
3038 }
3039 
HandleUserStopBroadCast(int32_t stopUserId,const std::string & remoteUdid)3040 void DeviceManagerService::HandleUserStopBroadCast(int32_t stopUserId, const std::string &remoteUdid)
3041 {
3042     LOGI("start");
3043     HandleUserStop(stopUserId, remoteUdid);
3044 }
3045 
NotifyRemoteLocalUserStopByWifi(const std::string & localUdid,const std::map<std::string,std::string> & wifiDevices,int32_t stopUserId)3046 void DeviceManagerService::NotifyRemoteLocalUserStopByWifi(const std::string &localUdid,
3047     const std::map<std::string, std::string> &wifiDevices, int32_t stopUserId)
3048 {
3049     for (const auto &it : wifiDevices) {
3050         std::vector<std::string> updateUdids;
3051         updateUdids.push_back(it.first);
3052         int32_t result = DMCommTool::GetInstance()->SendUserStop(it.second, stopUserId);
3053         if (result != DM_OK) {
3054             LOGE("by wifi failed: %{public}s", GetAnonyString(it.first).c_str());
3055             HandleUserStop(stopUserId, localUdid, updateUdids);
3056             continue;
3057         }
3058         if (timer_ == nullptr) {
3059             timer_ = std::make_shared<DmTimer>();
3060         }
3061         std::string udid = it.first;
3062         timer_->StartTimer(std::string(USER_STOP_BY_WIFI_TIMEOUT_TASK) + Crypto::Sha256(udid),
3063             USER_SWITCH_BY_WIFI_TIMEOUT_S,
3064             [this, stopUserId, localUdid, updateUdids] (std::string name) {
3065                 DeviceManagerService::HandleUserStop(stopUserId, localUdid, updateUdids);
3066             });
3067     }
3068 }
3069 #endif
3070 
RegisterAuthenticationType(const std::string & pkgName,const std::map<std::string,std::string> & authParam)3071 int32_t DeviceManagerService::RegisterAuthenticationType(const std::string &pkgName,
3072     const std::map<std::string, std::string> &authParam)
3073 {
3074     if (!PermissionManager::GetInstance().CheckPermission()) {
3075         LOGE("The caller does not have permission to call");
3076         return ERR_DM_NO_PERMISSION;
3077     }
3078     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3079     if (pkgName.empty()) {
3080         LOGE("Invalid parameter, pkgName is empty.");
3081         return ERR_DM_INPUT_PARA_INVALID;
3082     }
3083     auto authTypeIter = authParam.find(DM_AUTHENTICATION_TYPE);
3084     if (authTypeIter == authParam.end()) {
3085         LOGE("Invalid parameter, DM_AUTHENTICATION_TYPE is empty.");
3086         return ERR_DM_INPUT_PARA_INVALID;
3087     }
3088     if (!IsNumberString(authTypeIter->second)) {
3089         LOGE("Invalid parameter, DM_AUTHENTICATION_TYPE is not number.");
3090         return ERR_DM_INPUT_PARA_INVALID;
3091     }
3092     int32_t authenticationType = std::atoi(authTypeIter->second.c_str());
3093 
3094     if (!IsDMServiceImplReady()) {
3095         LOGE("RegisterAuthenticationType failed, instance not init or init failed.");
3096         return ERR_DM_INIT_FAILED;
3097     }
3098     return dmServiceImpl_->RegisterAuthenticationType(authenticationType);
3099 }
3100 
GetDeviceProfileInfoList(const std::string & pkgName,DmDeviceProfileInfoFilterOptions & filterOptions)3101 int32_t DeviceManagerService::GetDeviceProfileInfoList(const std::string &pkgName,
3102     DmDeviceProfileInfoFilterOptions &filterOptions)
3103 {
3104     if (!PermissionManager::GetInstance().CheckPermission()) {
3105         LOGE("The caller does not have permission to call");
3106         return ERR_DM_NO_PERMISSION;
3107     }
3108     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3109     if (!IsDMServiceAdapterResidentLoad()) {
3110         LOGE("GetDeviceProfileInfoList failed, adapter instance not init or init failed.");
3111         return ERR_DM_UNSUPPORTED_METHOD;
3112     }
3113     return dmServiceImplExtResident_->GetDeviceProfileInfoList(pkgName, filterOptions);
3114 }
3115 
GetDeviceIconInfo(const std::string & pkgName,DmDeviceIconInfoFilterOptions & filterOptions)3116 int32_t DeviceManagerService::GetDeviceIconInfo(const std::string &pkgName,
3117     DmDeviceIconInfoFilterOptions &filterOptions)
3118 {
3119     if (!PermissionManager::GetInstance().CheckPermission()) {
3120         LOGE("The caller does not have permission to call");
3121         return ERR_DM_NO_PERMISSION;
3122     }
3123     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3124     if (!IsDMServiceAdapterResidentLoad()) {
3125         LOGE("GetDeviceIconInfo failed, adapter instance not init or init failed.");
3126         return ERR_DM_UNSUPPORTED_METHOD;
3127     }
3128     return dmServiceImplExtResident_->GetDeviceIconInfo(pkgName, filterOptions);
3129 }
3130 
PutDeviceProfileInfoList(const std::string & pkgName,std::vector<DmDeviceProfileInfo> & deviceProfileInfoList)3131 int32_t DeviceManagerService::PutDeviceProfileInfoList(const std::string &pkgName,
3132     std::vector<DmDeviceProfileInfo> &deviceProfileInfoList)
3133 {
3134     if (!PermissionManager::GetInstance().CheckPermission()) {
3135         LOGE("The caller does not have permission to call");
3136         return ERR_DM_NO_PERMISSION;
3137     }
3138     std::string processName = "";
3139     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
3140         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
3141         return ERR_DM_FAILED;
3142     }
3143     if (!PermissionManager::GetInstance().CheckProcessNameValidPutDeviceProfileInfoList(processName)) {
3144         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
3145         return ERR_DM_NO_PERMISSION;
3146     }
3147     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3148     if (!IsDMServiceAdapterResidentLoad()) {
3149         LOGE("GetDeviceProfileInfoList failed, adapter instance not init or init failed.");
3150         return ERR_DM_UNSUPPORTED_METHOD;
3151     }
3152     return dmServiceImplExtResident_->PutDeviceProfileInfoList(pkgName, deviceProfileInfoList);
3153 }
3154 
SetLocalDisplayNameToSoftbus(const std::string & displayName)3155 int32_t DeviceManagerService::SetLocalDisplayNameToSoftbus(const std::string &displayName)
3156 {
3157     LOGI("DeviceManagerService Start SetLocalDisplayName!");
3158     CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL);
3159     int32_t ret = softbusListener_->SetLocalDisplayName(displayName);
3160     if (ret != DM_OK) {
3161         LOGE("SetLocalDisplayName error, failed ret: %{public}d", ret);
3162         return ret;
3163     }
3164     return DM_OK;
3165 }
3166 
GetLocalDisplayDeviceName(const std::string & pkgName,int32_t maxNameLength,std::string & displayName)3167 int32_t DeviceManagerService::GetLocalDisplayDeviceName(const std::string &pkgName, int32_t maxNameLength,
3168     std::string &displayName)
3169 {
3170     if (!PermissionManager::GetInstance().CheckPermission()) {
3171         LOGE("The caller does not have permission to call");
3172         return ERR_DM_NO_PERMISSION;
3173     }
3174     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3175 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
3176     return DeviceNameManager::GetInstance().GetLocalDisplayDeviceName(maxNameLength, displayName);
3177 #endif
3178     return DM_OK;
3179 }
3180 
SetLocalDeviceName(const std::string & pkgName,const std::string & deviceName)3181 int32_t DeviceManagerService::SetLocalDeviceName(const std::string &pkgName, const std::string &deviceName)
3182 {
3183     if (!PermissionManager::GetInstance().CheckPermission()) {
3184         LOGE("The caller does not have permission to call");
3185         return ERR_DM_NO_PERMISSION;
3186     }
3187     std::string processName = "";
3188     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
3189         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
3190         return ERR_DM_FAILED;
3191     }
3192     if (!PermissionManager::GetInstance().CheckProcessNameValidModifyLocalDeviceName(processName)) {
3193         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
3194         return ERR_DM_NO_PERMISSION;
3195     }
3196     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3197     if (!IsDMServiceAdapterResidentLoad()) {
3198         LOGE("SetLocalDeviceName failed, adapter instance not init or init failed.");
3199         return ERR_DM_UNSUPPORTED_METHOD;
3200     }
3201     return dmServiceImplExtResident_->SetLocalDeviceName(pkgName, deviceName);
3202 }
3203 
SetRemoteDeviceName(const std::string & pkgName,const std::string & deviceId,const std::string & deviceName)3204 int32_t DeviceManagerService::SetRemoteDeviceName(const std::string &pkgName,
3205     const std::string &deviceId, const std::string &deviceName)
3206 {
3207     if (!PermissionManager::GetInstance().CheckPermission()) {
3208         LOGE("The caller does not have permission to call");
3209         return ERR_DM_NO_PERMISSION;
3210     }
3211     std::string processName = "";
3212     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
3213         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
3214         return ERR_DM_FAILED;
3215     }
3216     if (!PermissionManager::GetInstance().CheckProcessNameValidModifyRemoteDeviceName(processName)) {
3217         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
3218         return ERR_DM_NO_PERMISSION;
3219     }
3220     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3221     if (!IsDMServiceAdapterResidentLoad()) {
3222         LOGE("SetRemoteDeviceName failed, adapter instance not init or init failed.");
3223         return ERR_DM_UNSUPPORTED_METHOD;
3224     }
3225     return dmServiceImplExtResident_->SetRemoteDeviceName(pkgName, deviceId, deviceName);
3226 }
3227 
GetDeviceNamePrefixs()3228 std::vector<std::string> DeviceManagerService::GetDeviceNamePrefixs()
3229 {
3230     LOGI("In");
3231     if (!IsDMServiceAdapterResidentLoad()) {
3232         LOGE("GetDeviceNamePrefixs failed, adapter instance not init or init failed.");
3233         return {};
3234     }
3235     return dmServiceImplExtResident_->GetDeviceNamePrefixs();
3236 }
3237 
CheckRegisterInfoWithWise(int32_t curUserId)3238 void DeviceManagerService::CheckRegisterInfoWithWise(int32_t curUserId)
3239 {
3240     LOGI("In curUserId:%{public}d", curUserId);
3241     if (curUserId == -1) {
3242         return;
3243     }
3244     if (!IsDMServiceAdapterResidentLoad()) {
3245         LOGE("CheckRegisterInfoWithWise failed, adapter instance not init or init failed.");
3246         return;
3247     }
3248     dmServiceImplExtResident_->CheckRegisterInfoWithWise();
3249 }
3250 
RestoreLocalDeviceName(const std::string & pkgName)3251 int32_t DeviceManagerService::RestoreLocalDeviceName(const std::string &pkgName)
3252 {
3253     LOGI("In");
3254     if (!PermissionManager::GetInstance().CheckPermission()) {
3255         LOGE("The caller does not have permission to call");
3256         return ERR_DM_NO_PERMISSION;
3257     }
3258     std::string processName = "";
3259     if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) {
3260         LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str());
3261         return ERR_DM_FAILED;
3262     }
3263     if (!PermissionManager::GetInstance().CheckProcessNameValidModifyLocalDeviceName(processName)) {
3264         LOGE("The caller: %{public}s is not in white list.", processName.c_str());
3265         return ERR_DM_NO_PERMISSION;
3266     }
3267 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
3268     return DeviceNameManager::GetInstance().RestoreLocalDeviceName();
3269 #endif
3270     return DM_OK;
3271 }
3272 
AddHmlInfoToBindParam(int32_t actionId,std::string & bindParam)3273 void DeviceManagerService::AddHmlInfoToBindParam(int32_t actionId, std::string &bindParam)
3274 {
3275     cJSON *bindParamObj = cJSON_Parse(bindParam.c_str());
3276     if (bindParamObj == NULL) {
3277         bindParamObj = cJSON_CreateObject();
3278         if (bindParamObj == NULL) {
3279             LOGE("Create bindParamObj object failed.");
3280             return;
3281         }
3282     }
3283     cJSON_AddStringToObject(bindParamObj, PARAM_KEY_CONN_SESSIONTYPE, CONN_SESSION_TYPE_HML);
3284     cJSON_AddStringToObject(bindParamObj, PARAM_KEY_HML_ACTIONID, std::to_string(actionId).c_str());
3285     char *str = cJSON_PrintUnformatted(bindParamObj);
3286     if (str == nullptr) {
3287         cJSON_Delete(bindParamObj);
3288         return;
3289     }
3290     bindParam = std::string(str);
3291     cJSON_free(str);
3292     cJSON_Delete(bindParamObj);
3293 }
3294 
ClearPulishIdCache(const std::string & pkgName)3295 void DeviceManagerService::ClearPulishIdCache(const std::string &pkgName)
3296 {
3297     CHECK_NULL_VOID(advertiseMgr_);
3298     advertiseMgr_->ClearPulishIdCache(pkgName);
3299 }
3300 
IsPC()3301 bool DeviceManagerService::IsPC()
3302 {
3303     if (softbusListener_ == nullptr) {
3304         LOGE("softbusListener_ is null.");
3305         return false;
3306     }
3307     DmDeviceInfo info;
3308     GetLocalDeviceInfo(info);
3309     return (info.deviceTypeId == DmDeviceType::DEVICE_TYPE_PC || info.deviceTypeId == DmDeviceType::DEVICE_TYPE_2IN1);
3310 }
3311 
GetDeviceNetworkIdList(const std::string & pkgName,const NetworkIdQueryFilter & queryFilter,std::vector<std::string> & networkIds)3312 int32_t DeviceManagerService::GetDeviceNetworkIdList(const std::string &pkgName,
3313     const NetworkIdQueryFilter &queryFilter, std::vector<std::string> &networkIds)
3314 {
3315     if (!PermissionManager::GetInstance().CheckPermission()) {
3316         LOGE("The caller does not have permission to call");
3317         return ERR_DM_NO_PERMISSION;
3318     }
3319     LOGI("Start for pkgName = %{public}s", pkgName.c_str());
3320     if (!IsDMServiceAdapterResidentLoad()) {
3321         LOGE("GetDeviceProfileInfoList failed, adapter instance not init or init failed.");
3322         return ERR_DM_UNSUPPORTED_METHOD;
3323     }
3324     std::vector<DmDeviceProfileInfo> dmDeviceProfileInfos;
3325     int32_t ret = dmServiceImplExtResident_->GetDeviceProfileInfosFromLocalCache(queryFilter, dmDeviceProfileInfos);
3326     if (ret != DM_OK) {
3327         LOGW("GetDeviceProfileInfosFromLocalCache failed, ret = %{public}d.", ret);
3328         return ret;
3329     }
3330     for (const auto &item : dmDeviceProfileInfos) {
3331         std::string networkId = "";
3332         SoftbusCache::GetInstance().GetNetworkIdFromCache(item.deviceId, networkId);
3333         if (!networkId.empty()) {
3334             networkIds.emplace_back(networkId);
3335         }
3336     }
3337     if (networkIds.empty()) {
3338         LOGW("networkIds is empty");
3339         return ERR_DM_FIND_NETWORKID_LIST_EMPTY;
3340     }
3341     return DM_OK;
3342 }
3343 
NotifyRemoteLocalLogout(const std::vector<std::string> & peerUdids,const std::string & accountIdHash,const std::string & accountName,int32_t userId)3344 void DeviceManagerService::NotifyRemoteLocalLogout(const std::vector<std::string> &peerUdids,
3345     const std::string &accountIdHash, const std::string &accountName, int32_t userId)
3346 {
3347     LOGI("Start.");
3348     std::vector<std::string> bleUdids;
3349     std::vector<std::string> wifiDevices;
3350     for (const auto &udid : peerUdids) {
3351         std::string netWorkId = "";
3352         SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, netWorkId);
3353         if (netWorkId.empty()) {
3354             LOGI("netWorkId is empty: %{public}s", GetAnonyString(udid).c_str());
3355             bleUdids.push_back(udid);
3356             continue;
3357         }
3358         int32_t networkType = 0;
3359         int32_t ret = softbusListener_->GetNetworkTypeByNetworkId(netWorkId.c_str(), networkType);
3360         if (ret != DM_OK || networkType <= 0) {
3361             LOGI("get networkType failed: %{public}s", GetAnonyString(udid).c_str());
3362             bleUdids.push_back(udid);
3363             continue;
3364         }
3365         if ((static_cast<uint32_t>(networkType) & USERID_SYNC_DISCOVERY_TYPE_BLE_MASK) != 0x0) {
3366             bleUdids.push_back(udid);
3367         } else {
3368             wifiDevices.push_back(netWorkId);
3369         }
3370     }
3371     if (!bleUdids.empty()) {
3372         SendAccountLogoutBroadCast(bleUdids, accountIdHash, accountName, userId);
3373     }
3374 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
3375     for (const auto &it : wifiDevices) {
3376         int32_t ret = DMCommTool::GetInstance()->SendLogoutAccountInfo(it, accountIdHash, userId);
3377         if (ret != DM_OK) {
3378             LOGE("Send LogoutAccount Info error, ret = %{public}d", ret);
3379         }
3380     }
3381 #endif
3382 }
3383 
ProcessSyncAccountLogout(const std::string & accountId,const std::string & peerUdid,int32_t userId)3384 void DeviceManagerService::ProcessSyncAccountLogout(const std::string &accountId, const std::string &peerUdid,
3385     int32_t userId)
3386 {
3387     LOGI("Start. process udid: %{public}s", GetAnonyString(peerUdid).c_str());
3388     if (!IsDMServiceImplReady()) {
3389         LOGE("Imp instance not init or init failed.");
3390         return;
3391     }
3392     dmServiceImpl_->HandleAccountLogoutEvent(userId, accountId, peerUdid);
3393 }
3394 } // namespace DistributedHardware
3395 } // namespace OHOS
3396