• 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 "softbus_listener.h"
17 
18 #include <dlfcn.h>
19 #include <mutex>
20 #include <pthread.h>
21 #include <securec.h>
22 #include <thread>
23 #include <unistd.h>
24 
25 #include "device_manager_service.h"
26 #include "dm_crypto.h"
27 #include "dm_constants.h"
28 #include "dm_device_info.h"
29 #include "dm_log.h"
30 #include "dm_softbus_cache.h"
31 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
32 #include "dm_transport_msg.h"
33 #include "ffrt.h"
34 #endif
35 #include "ipc_skeleton.h"
36 #include "parameter.h"
37 #include "system_ability_definition.h"
38 
39 namespace OHOS {
40 namespace DistributedHardware {
41 
42 const int32_t SOFTBUS_CHECK_INTERVAL = 100000; // 100ms
43 const int32_t SOFTBUS_SUBSCRIBE_ID_MASK = 0x0000FFFF;
44 const int32_t MAX_CACHED_DISCOVERED_DEVICE_SIZE = 100;
45 const int32_t MAX_SOFTBUS_MSG_LEN = 2000;
46 #if (defined(__LITEOS_M__) || defined(LITE_DEVICE))
47 constexpr const char* DEVICE_ONLINE = "deviceOnLine";
48 constexpr const char* DEVICE_OFFLINE = "deviceOffLine";
49 constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange";
50 constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust";
51 constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange";
52 constexpr const char* CREDENTIAL_AUTH_STATUS = "credentialAuthStatus";
53 #endif
54 constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so";
55 constexpr static char HEX_ARRAY[] = "0123456789ABCDEF";
56 constexpr static uint8_t BYTE_MASK = 0x0F;
57 constexpr static uint16_t ARRAY_DOUBLE_SIZE = 2;
58 constexpr static uint16_t BIN_HIGH_FOUR_NUM = 4;
59 constexpr uint32_t SOFTBUS_MAX_RETRY_TIME = 10;
60 
61 constexpr const char* CUSTOM_DATA_ACTIONID = "actionId";
62 constexpr const char* CUSTOM_DATA_NETWORKID = "networkId";
63 constexpr const char* CUSTOM_DATA_DISPLAY_NAME = "displayName";
64 
65 static std::mutex g_deviceMapMutex;
66 static std::mutex g_lnnCbkMapMutex;
67 static std::mutex g_radarLoadLock;
68 static std::mutex g_onlineDeviceNumLock;
69 static std::mutex g_lockDeviceTrustedChange;
70 static std::mutex g_lockUserIdCheckSumChange;
71 static std::mutex g_lockDeviceOnLine;
72 static std::mutex g_lockDeviceOffLine;
73 static std::mutex g_lockDevInfoChange;
74 static std::mutex g_lockDeviceIdSet;
75 static std::mutex g_lockDevScreenStatusChange;
76 static std::mutex g_credentialAuthStatus;
77 static std::map<std::string,
78     std::vector<std::pair<ConnectionAddrType, std::shared_ptr<DeviceInfo>>>> discoveredDeviceMap;
79 static std::map<std::string, std::shared_ptr<ISoftbusDiscoveringCallback>> lnnOpsCbkMap;
80 static std::map<std::string, int32_t> discoveredDeviceActionIdMap;
81 static std::set<std::string> deviceIdSet;
82 bool SoftbusListener::isRadarSoLoad_ = false;
83 IDmRadarHelper* SoftbusListener::dmRadarHelper_ = nullptr;
84 void* SoftbusListener::radarHandle_ = nullptr;
85 std::string SoftbusListener::hostName_ = "";
86 int32_t g_onlineDeviceNum = 0;
87 
OnSessionOpened(int sessionId,int result)88 static int OnSessionOpened(int sessionId, int result)
89 {
90     return DeviceManagerService::GetInstance().OnSessionOpened(sessionId, result);
91 }
92 
OnSessionClosed(int sessionId)93 static void OnSessionClosed(int sessionId)
94 {
95     DeviceManagerService::GetInstance().OnSessionClosed(sessionId);
96 }
97 
OnBytesReceived(int sessionId,const void * data,unsigned int dataLen)98 static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen)
99 {
100     DeviceManagerService::GetInstance().OnBytesReceived(sessionId, data, dataLen);
101 }
102 
OnPinHolderSessionOpened(int sessionId,int result)103 static int OnPinHolderSessionOpened(int sessionId, int result)
104 {
105     return DeviceManagerService::GetInstance().OnPinHolderSessionOpened(sessionId, result);
106 }
107 
OnPinHolderSessionClosed(int sessionId)108 static void OnPinHolderSessionClosed(int sessionId)
109 {
110     DeviceManagerService::GetInstance().OnPinHolderSessionClosed(sessionId);
111 }
112 
OnPinHolderBytesReceived(int sessionId,const void * data,unsigned int dataLen)113 static void OnPinHolderBytesReceived(int sessionId, const void *data, unsigned int dataLen)
114 {
115     DeviceManagerService::GetInstance().OnPinHolderBytesReceived(sessionId, data, dataLen);
116 }
117 
118 static IPublishCb softbusPublishCallback_ = {
119     .OnPublishResult = SoftbusListener::OnSoftbusPublishResult,
120 };
121 
122 static INodeStateCb softbusNodeStateCb_ = {
123     .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED |
124         EVENT_NODE_STATUS_CHANGED | EVENT_NODE_HICHAIN_PROOF_EXCEPTION,
125     .onNodeOnline = SoftbusListener::OnSoftbusDeviceOnline,
126     .onNodeOffline = SoftbusListener::OnSoftbusDeviceOffline,
127     .onNodeBasicInfoChanged = SoftbusListener::OnSoftbusDeviceInfoChanged,
128     .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange,
129     .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange,
130     .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged,
131     .onHichainProofException = SoftbusListener::OnCredentialAuthStatus,
132 };
133 
134 static IRefreshCallback softbusRefreshCallback_ = {
135     .OnDeviceFound = SoftbusListener::OnSoftbusDeviceFound,
136     .OnDiscoverResult = SoftbusListener::OnSoftbusDiscoveryResult,
137 };
138 
DeviceOnLine(DmDeviceInfo deviceInfo)139 void SoftbusListener::DeviceOnLine(DmDeviceInfo deviceInfo)
140 {
141     std::lock_guard<std::mutex> lock(g_lockDeviceOnLine);
142     DeviceManagerService::GetInstance().HandleDeviceStatusChange(DEVICE_STATE_ONLINE, deviceInfo);
143 }
144 
DeviceOffLine(DmDeviceInfo deviceInfo)145 void SoftbusListener::DeviceOffLine(DmDeviceInfo deviceInfo)
146 {
147     std::lock_guard<std::mutex> lock(g_lockDeviceOffLine);
148     DeviceManagerService::GetInstance().HandleDeviceStatusChange(DEVICE_STATE_OFFLINE, deviceInfo);
149 }
150 
DeviceNameChange(DmDeviceInfo deviceInfo)151 void SoftbusListener::DeviceNameChange(DmDeviceInfo deviceInfo)
152 {
153     std::lock_guard<std::mutex> lock(g_lockDevInfoChange);
154     DeviceManagerService::GetInstance().HandleDeviceStatusChange(DEVICE_INFO_CHANGED, deviceInfo);
155 }
156 
DeviceNotTrust(const std::string & msg)157 void SoftbusListener::DeviceNotTrust(const std::string &msg)
158 {
159     std::lock_guard<std::mutex> lock(g_lockDeviceTrustedChange);
160     DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg);
161 }
162 
DeviceTrustedChange(const std::string & msg)163 void SoftbusListener::DeviceTrustedChange(const std::string &msg)
164 {
165 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
166     std::lock_guard<std::mutex> lock(g_lockDeviceTrustedChange);
167     DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg);
168 #else
169     (void)msg;
170 #endif
171 }
172 
DeviceUserIdCheckSumChange(const std::string & msg)173 void SoftbusListener::DeviceUserIdCheckSumChange(const std::string &msg)
174 {
175 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
176     std::lock_guard<std::mutex> lock(g_lockUserIdCheckSumChange);
177     DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg);
178 #else
179     (void)msg;
180 #endif
181 }
182 
DeviceScreenStatusChange(DmDeviceInfo deviceInfo)183 void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo)
184 {
185     std::lock_guard<std::mutex> lock(g_lockDevScreenStatusChange);
186     DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo);
187 }
188 
CredentialAuthStatusProcess(std::string deviceList,uint16_t deviceTypeId,int32_t errcode)189 void SoftbusListener::CredentialAuthStatusProcess(std::string deviceList, uint16_t deviceTypeId, int32_t errcode)
190 {
191     std::lock_guard<std::mutex> lock(g_credentialAuthStatus);
192     DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode);
193 }
194 
OnCredentialAuthStatus(const char * deviceList,uint32_t deviceListLen,uint16_t deviceTypeId,int32_t errcode)195 void SoftbusListener::OnCredentialAuthStatus(const char *deviceList, uint32_t deviceListLen,
196                                              uint16_t deviceTypeId, int32_t errcode)
197 {
198     LOGI("received credential auth status callback from softbus.");
199     if (deviceListLen > MAX_SOFTBUS_MSG_LEN) {
200         LOGE("[SOFTBUS]received invaild deviceList value.");
201         return;
202     }
203     std::string deviceListStr;
204     if (deviceList != nullptr) {
205         deviceListStr = std::string(deviceList, deviceListLen);
206     }
207 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
208     ffrt::submit([=]() { CredentialAuthStatusProcess(deviceListStr, deviceTypeId, errcode); });
209 #else
210     std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(deviceListStr, deviceTypeId, errcode); });
211     if (pthread_setname_np(credentialAuthStatus.native_handle(), CREDENTIAL_AUTH_STATUS) != DM_OK) {
212         LOGE("credentialAuthStatus setname failed.");
213     }
214     credentialAuthStatus.detach();
215 #endif
216 }
217 
OnDeviceScreenStatusChanged(NodeStatusType type,NodeStatus * status)218 void SoftbusListener::OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status)
219 {
220     LOGI("received device screen status change callback from softbus.");
221     if (status == nullptr) {
222         LOGE("[SOFTBUS]status is nullptr, type = %{public}d", static_cast<int32_t>(type));
223         return;
224     }
225     LOGI("screenStatusChanged networkId: %{public}s, screenStatus: %{public}d",
226         GetAnonyString(status->basicInfo.networkId).c_str(), static_cast<int32_t>(status->reserved[0]));
227     if (type != NodeStatusType::TYPE_SCREEN_STATUS) {
228         LOGE("type is not matching.");
229         return;
230     }
231     DmDeviceInfo dmDeviceInfo;
232     int32_t devScreenStatus = static_cast<int32_t>(status->reserved[0]);
233     ConvertScreenStatusToDmDevice(status->basicInfo, devScreenStatus, dmDeviceInfo);
234     #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
235         ffrt::submit([=]() { DeviceScreenStatusChange(dmDeviceInfo); });
236     #else
237         std::thread devScreenStatusChange([=]() { DeviceScreenStatusChange(dmDeviceInfo); });
238         if (pthread_setname_np(devScreenStatusChange.native_handle(), DEVICE_SCREEN_STATUS_CHANGE) != DM_OK) {
239             LOGE("devScreenStatusChange setname failed.");
240         }
241         devScreenStatusChange.detach();
242     #endif
243 }
244 
OnSoftbusDeviceOnline(NodeBasicInfo * info)245 void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info)
246 {
247     LOGI("received device online callback from softbus.");
248     if (info == nullptr) {
249         LOGE("NodeBasicInfo is nullptr.");
250         return;
251     }
252     DmDeviceInfo dmDeviceInfo;
253     ConvertNodeBasicInfoToDmDevice(*info, dmDeviceInfo);
254     LOGI("device online networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str());
255     SoftbusCache::GetInstance().SaveDeviceInfo(dmDeviceInfo);
256     SoftbusCache::GetInstance().SaveDeviceSecurityLevel(dmDeviceInfo.networkId);
257     SoftbusCache::GetInstance().SaveLocalDeviceInfo();
258     UpdateDeviceName(info);
259     {
260         std::lock_guard<std::mutex> lock(g_onlineDeviceNumLock);
261         g_onlineDeviceNum++;
262     }
263 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
264     ffrt::submit([=]() { DeviceOnLine(dmDeviceInfo); });
265 #else
266     std::thread deviceOnLine([=]() { DeviceOnLine(dmDeviceInfo); });
267     int32_t ret = pthread_setname_np(deviceOnLine.native_handle(), DEVICE_ONLINE);
268     if (ret != DM_OK) {
269         LOGE("deviceOnLine setname failed.");
270     }
271     deviceOnLine.detach();
272 #endif
273     {
274         std::string peerUdid;
275         GetUdidByNetworkId(info->networkId, peerUdid);
276         struct RadarInfo radarInfo = {
277             .funcName = "OnSoftbusDeviceOnline",
278             .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
279             .bizState = static_cast<int32_t>(BizState::BIZ_STATE_START),
280             .isTrust = static_cast<int32_t>(TrustStatus::IS_TRUST),
281             .peerNetId = info->networkId,
282             .peerUdid = peerUdid,
283         };
284         if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
285             if (!GetDmRadarHelperObj()->ReportNetworkOnline(radarInfo)) {
286                 LOGE("ReportNetworkOnline failed");
287             }
288         }
289     }
290 }
291 
OnSoftbusDeviceOffline(NodeBasicInfo * info)292 void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info)
293 {
294     LOGI("received device offline callback from softbus.");
295     if (info == nullptr) {
296         LOGE("NodeBasicInfo is nullptr.");
297         return;
298     }
299     DmDeviceInfo dmDeviceInfo;
300     ConvertNodeBasicInfoToDmDevice(*info, dmDeviceInfo);
301     SoftbusCache::GetInstance().DeleteDeviceInfo(dmDeviceInfo);
302     SoftbusCache::GetInstance().DeleteDeviceSecurityLevel(dmDeviceInfo.networkId);
303     {
304         std::lock_guard<std::mutex> lock(g_onlineDeviceNumLock);
305         g_onlineDeviceNum--;
306         if (g_onlineDeviceNum == 0) {
307             SoftbusCache::GetInstance().DeleteLocalDeviceInfo();
308         }
309     }
310     LOGI("device offline networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str());
311 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
312     ffrt::submit([=]() { DeviceOffLine(dmDeviceInfo); });
313 #else
314     std::thread deviceOffLine([=]() { DeviceOffLine(dmDeviceInfo); });
315     int32_t ret = pthread_setname_np(deviceOffLine.native_handle(), DEVICE_OFFLINE);
316     if (ret != DM_OK) {
317         LOGE("deviceOffLine setname failed.");
318     }
319     deviceOffLine.detach();
320 #endif
321     {
322         std::string peerUdid;
323         GetUdidByNetworkId(info->networkId, peerUdid);
324         struct RadarInfo radarInfo = {
325             .funcName = "OnSoftbusDeviceOffline",
326             .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
327             .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
328             .peerNetId = info->networkId,
329             .peerUdid = peerUdid,
330         };
331         if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
332             if (!GetDmRadarHelperObj()->ReportNetworkOffline(radarInfo)) {
333                 LOGE("ReportNetworkOffline failed");
334             }
335         }
336     }
337 }
338 
UpdateDeviceName(NodeBasicInfo * info)339 void SoftbusListener::UpdateDeviceName(NodeBasicInfo *info)
340 {
341 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
342     if (info == nullptr) {
343         LOGE("NodeBasicInfo is nullptr, not update device name");
344         return;
345     }
346     std::string udid = "";
347     if (GetUdidByNetworkId(info->networkId, udid) != DM_OK) {
348         LOGE("GetUdidByNetworkId failed, not update device name");
349         return;
350     }
351     LOGI("UpdateDeviceName, info->deviceName: %{public}s.", GetAnonyString(info->deviceName).c_str());
352     DeviceProfileConnector::GetInstance().UpdateAclDeviceName(udid, info->deviceName);
353 #endif
354 }
355 
OnSoftbusDeviceInfoChanged(NodeBasicInfoType type,NodeBasicInfo * info)356 void SoftbusListener::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info)
357 {
358     LOGI("received device info change from softbus.");
359     if (info == nullptr) {
360         LOGE("NodeBasicInfo is nullptr.");
361         return;
362     }
363     if (type == NodeBasicInfoType::TYPE_DEVICE_NAME || type == NodeBasicInfoType::TYPE_NETWORK_INFO) {
364         LOGI("DeviceInfo %{public}d change.", type);
365         DmDeviceInfo dmDeviceInfo;
366         int32_t networkType = -1;
367         if (type == NodeBasicInfoType::TYPE_NETWORK_INFO) {
368             if (GetNodeKeyInfo(DM_PKG_NAME, info->networkId, NodeDeviceInfoKey::NODE_KEY_NETWORK_TYPE,
369                 reinterpret_cast<uint8_t *>(&networkType), LNN_COMMON_LEN) != DM_OK) {
370                 LOGE("[SOFTBUS]GetNodeKeyInfo networkType failed.");
371                 return;
372             }
373             LOGI("OnSoftbusDeviceInfoChanged NetworkType %{public}d.", networkType);
374         }
375         if (type == NodeBasicInfoType::TYPE_DEVICE_NAME) {
376             UpdateDeviceName(info);
377         }
378         ConvertNodeBasicInfoToDmDevice(*info, dmDeviceInfo);
379         LOGI("device changed networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str());
380         dmDeviceInfo.networkType = networkType;
381         SoftbusCache::GetInstance().ChangeDeviceInfo(dmDeviceInfo);
382     #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
383         ffrt::submit([=]() { DeviceNameChange(dmDeviceInfo); });
384     #else
385         std::thread deviceInfoChange([=]() { DeviceNameChange(dmDeviceInfo); });
386         if (pthread_setname_np(deviceInfoChange.native_handle(), DEVICE_NAME_CHANGE) != DM_OK) {
387             LOGE("DeviceNameChange setname failed.");
388         }
389         deviceInfoChange.detach();
390     #endif
391     }
392 }
393 
OnLocalDevInfoChange()394 void SoftbusListener::OnLocalDevInfoChange()
395 {
396     LOGI("SoftbusListener::OnLocalDevInfoChange");
397     SoftbusCache::GetInstance().UpDataLocalDevInfo();
398 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
399     NodeBasicInfo nodeBasicInfo;
400     int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME, &nodeBasicInfo);
401     if (ret != DM_OK) {
402         LOGE("[SOFTBUS]GetLocalNodeDeviceInfo failed, not update deviceName ret: %{public}d.", ret);
403         return;
404     }
405     std::string udid = "";
406     ret = GetUdidByNetworkId(nodeBasicInfo.networkId, udid);
407     if (ret != DM_OK) {
408         LOGE("GetUdidByNetworkId failed, not update deviceName ret: %{public}d.", ret);
409         return;
410     }
411     DeviceProfileConnector::GetInstance().UpdateAclDeviceName(udid, nodeBasicInfo.deviceName);
412 #endif
413 }
414 
OnDeviceTrustedChange(TrustChangeType type,const char * msg,uint32_t msgLen)415 void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen)
416 {
417     LOGI("OnDeviceTrustedChange.");
418     if (msg == nullptr || msgLen > MAX_SOFTBUS_MSG_LEN || strlen(msg) != msgLen) {
419         LOGE("OnDeviceTrustedChange msg invalied.");
420         return;
421     }
422     std::string softbusMsg = std::string(msg, msgLen);
423 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
424     if (type == TrustChangeType::DEVICE_NOT_TRUSTED) {
425         ffrt::submit([=]() { DeviceNotTrust(softbusMsg); });
426     } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) {
427         ffrt::submit([=]() { DeviceTrustedChange(softbusMsg); });
428     } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) {
429         ffrt::submit([=]() { DeviceUserIdCheckSumChange(softbusMsg); });
430     } else {
431         LOGE("Invalied trust change type.");
432     }
433 #else
434     if (type == TrustChangeType::DEVICE_NOT_TRUSTED) {
435         std::thread deviceNotTrust([=]() { DeviceNotTrust(softbusMsg); });
436         int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST);
437         if (ret != DM_OK) {
438             LOGE("deviceNotTrust setname failed.");
439         }
440         deviceNotTrust.detach();
441     } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) {
442         std::thread deviceTrustedChange([=]() { DeviceTrustedChange(softbusMsg); });
443         int32_t ret = pthread_setname_np(deviceTrustedChange.native_handle(), DEVICE_NOT_TRUST);
444         if (ret != DM_OK) {
445             LOGE("deviceTrustedChange setname failed.");
446         }
447         deviceTrustedChange.detach();
448     } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) {
449         std::thread deviceUserIdCheckSumChange([=]() { DeviceUserIdCheckSumChange(softbusMsg); });
450         int32_t ret = pthread_setname_np(deviceUserIdCheckSumChange.native_handle(), DEVICE_NOT_TRUST);
451         if (ret != DM_OK) {
452             LOGE("deviceUserIdCheckSumChange setname failed.");
453         }
454         deviceUserIdCheckSumChange.detach();
455     } else {
456         LOGE("Invalied trust change type.");
457     }
458 #endif
459 }
460 
OnSoftbusDeviceFound(const DeviceInfo * device)461 void SoftbusListener::OnSoftbusDeviceFound(const DeviceInfo *device)
462 {
463     if (device == nullptr) {
464         LOGE("[SOFTBUS]device is null.");
465         return;
466     }
467     DmDeviceInfo dmDevInfo;
468     ConvertDeviceInfoToDmDevice(*device, dmDevInfo);
469     {
470         std::lock_guard<std::mutex> lock(g_lockDeviceIdSet);
471         if (deviceIdSet.find(std::string(dmDevInfo.deviceId)) == deviceIdSet.end()) {
472             deviceIdSet.insert(std::string(dmDevInfo.deviceId));
473             struct RadarInfo info = {
474                 .funcName = "OnSoftbusDeviceFound",
475                 .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
476                 .peerNetId = "",
477                 .peerUdid = std::string(dmDevInfo.deviceId),
478             };
479             if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
480                 if (!GetDmRadarHelperObj()->ReportDiscoverResCallback(info)) {
481                     LOGE("ReportDiscoverResCallback failed");
482                 }
483             }
484         }
485     }
486     LOGD("DevId=%{public}s, devName=%{public}s, devType=%{public}d, range=%{public}d,"
487         "isOnline=%{public}d, capability=%{public}u", GetAnonyString(dmDevInfo.deviceId).c_str(),
488         GetAnonyString(dmDevInfo.deviceName).c_str(), dmDevInfo.deviceTypeId, dmDevInfo.range,
489         device->isOnline, device->capabilityBitmap[0]);
490     int32_t actionId = 0;
491     int32_t ret = GetAttrFromExtraData(dmDevInfo, actionId);
492     if (ret != DM_OK) {
493         LOGE("GetAttrFromExtraData failed");
494         return;
495     }
496     std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
497     discoveredDeviceActionIdMap[dmDevInfo.deviceId] = actionId;
498     CacheDiscoveredDevice(device);
499     for (auto &iter : lnnOpsCbkMap) {
500         iter.second->OnDeviceFound(iter.first, dmDevInfo, device->isOnline);
501     }
502 }
503 
OnSoftbusDiscoveryResult(int subscribeId,RefreshResult result)504 void SoftbusListener::OnSoftbusDiscoveryResult(int subscribeId, RefreshResult result)
505 {
506     uint16_t originId = static_cast<uint16_t>((static_cast<uint32_t>(subscribeId)) & SOFTBUS_SUBSCRIBE_ID_MASK);
507     std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
508     for (auto &iter : lnnOpsCbkMap) {
509         iter.second->OnDiscoveringResult(iter.first, originId, result);
510     }
511 }
512 
OnSoftbusPublishResult(int publishId,PublishResult result)513 void SoftbusListener::OnSoftbusPublishResult(int publishId, PublishResult result)
514 {
515     LOGD("OnSoftbusPublishResult, publishId: %{public}d, result: %{public}d.", publishId, result);
516 }
517 
SoftbusListener()518 SoftbusListener::SoftbusListener()
519 {
520     ISessionListener sessionListener = {
521         .OnSessionOpened = OnSessionOpened,
522         .OnSessionClosed = OnSessionClosed,
523         .OnBytesReceived = OnBytesReceived,
524         .OnMessageReceived = nullptr,
525         .OnStreamReceived = nullptr
526     };
527     LOGD("SoftbusListener constructor.");
528 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
529     int32_t ret = CreateSessionServer(DM_PKG_NAME, DM_SESSION_NAME, &sessionListener);
530     if (ret != DM_OK) {
531         LOGE("[SOFTBUS]CreateSessionServer failed, ret: %{public}d.", ret);
532     }
533     ISessionListener pinHolderSessionListener = {
534         .OnSessionOpened = OnPinHolderSessionOpened,
535         .OnSessionClosed = OnPinHolderSessionClosed,
536         .OnBytesReceived = OnPinHolderBytesReceived,
537         .OnMessageReceived = nullptr,
538         .OnStreamReceived = nullptr
539     };
540     ret = CreateSessionServer(DM_PKG_NAME, DM_PIN_HOLDER_SESSION_NAME, &pinHolderSessionListener);
541     if (ret != DM_OK) {
542         LOGE("[SOFTBUS]CreateSessionServer pin holder failed, ret: %{public}d.", ret);
543     }
544 #endif
545     InitSoftbusListener();
546     ClearDiscoveredDevice();
547 }
548 
~SoftbusListener()549 SoftbusListener::~SoftbusListener()
550 {
551 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
552     RemoveSessionServer(DM_PKG_NAME, DM_SESSION_NAME);
553     RemoveSessionServer(DM_PKG_NAME, DM_PIN_HOLDER_SESSION_NAME);
554 #endif
555     LOGD("SoftbusListener destructor.");
556 }
557 
InitSoftbusListener()558 int32_t SoftbusListener::InitSoftbusListener()
559 {
560     int32_t ret;
561     uint32_t retryTimes = 0;
562 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
563     do {
564         ret = RegNodeDeviceStateCb(DM_PKG_NAME, &softbusNodeStateCb_);
565         if (ret != DM_OK) {
566             ++retryTimes;
567             LOGE("[SOFTBUS]RegNodeDeviceStateCb failed with ret: %{public}d, retryTimes: %{public}u.", ret, retryTimes);
568             usleep(SOFTBUS_CHECK_INTERVAL);
569         }
570     } while (ret != DM_OK && retryTimes < SOFTBUS_MAX_RETRY_TIME);
571 #endif
572     return InitSoftPublishLNN();
573 }
574 
InitSoftPublishLNN()575 int32_t SoftbusListener::InitSoftPublishLNN()
576 {
577     int32_t ret = DM_OK;
578 #if (defined(__LITEOS_M__) || defined(LITE_DEVICE))
579     PublishInfo publishInfo;
580     publishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID;
581     publishInfo.mode = DiscoverMode::DISCOVER_MODE_PASSIVE;
582     publishInfo.medium = ExchangeMedium::AUTO;
583     publishInfo.freq = ExchangeFreq::LOW;
584     publishInfo.capability = DM_CAPABILITY_OSD;
585     publishInfo.ranging = false;
586     LOGI("InitSoftPublishLNN begin, publishId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:"
587         "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.publishId, publishInfo.mode,
588         publishInfo.medium, publishInfo.capability, publishInfo.ranging, publishInfo.freq);
589 
590     ret = PublishLNN(DM_PKG_NAME, &publishInfo, &softbusPublishCallback_);
591     if (ret == DM_OK) {
592         LOGI("[SOFTBUS]PublishLNN successed, ret: %{public}d", ret);
593     }
594 #endif
595     return ret;
596 }
597 
RefreshSoftbusLNN(const char * pkgName,const DmSubscribeInfo & dmSubInfo,const std::string & customData)598 int32_t SoftbusListener::RefreshSoftbusLNN(const char *pkgName, const DmSubscribeInfo &dmSubInfo,
599     const std::string &customData)
600 {
601     LOGI("RefreshSoftbusLNN begin, subscribeId: %{public}d.", dmSubInfo.subscribeId);
602     SubscribeInfo subscribeInfo;
603     if (memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)) != DM_OK) {
604         LOGE("RefreshSoftbusLNN memset_s failed.");
605         return ERR_DM_FAILED;
606     }
607 
608     subscribeInfo.subscribeId = dmSubInfo.subscribeId;
609     subscribeInfo.mode = static_cast<DiscoverMode>(dmSubInfo.mode);
610     subscribeInfo.medium = static_cast<ExchangeMedium>(dmSubInfo.medium);
611     subscribeInfo.freq = static_cast<ExchangeFreq>(dmSubInfo.freq);
612     subscribeInfo.isSameAccount = dmSubInfo.isSameAccount;
613     subscribeInfo.isWakeRemote = dmSubInfo.isWakeRemote;
614     subscribeInfo.capability = dmSubInfo.capability;
615     subscribeInfo.capabilityData =
616         const_cast<unsigned char *>(reinterpret_cast<const unsigned char *>(customData.c_str()));
617     subscribeInfo.dataLen = customData.size();
618     LOGI("RefreshSoftbusLNN begin, subscribeId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:"
619         "%{public}s, freq: %{public}d.", subscribeInfo.subscribeId, subscribeInfo.mode, subscribeInfo.medium,
620         subscribeInfo.capability, subscribeInfo.freq);
621     int32_t ret = ::RefreshLNN(pkgName, &subscribeInfo, &softbusRefreshCallback_);
622     struct RadarInfo info = {
623         .funcName = "RefreshSoftbusLNN",
624         .toCallPkg = "dsoftbus",
625         .hostName = GetHostPkgName(),
626         .stageRes = (ret == DM_OK) ?
627             static_cast<int32_t>(StageRes::STAGE_IDLE) : static_cast<int32_t>(StageRes::STAGE_FAIL),
628         .bizState = (ret == DM_OK) ?
629             static_cast<int32_t>(BizState::BIZ_STATE_START) : static_cast<int32_t>(BizState::BIZ_STATE_END),
630         .commServ = static_cast<int32_t>(CommServ::USE_SOFTBUS),
631         .errCode = ret,
632     };
633     if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
634         if (!GetDmRadarHelperObj()->ReportDiscoverRegCallback(info)) {
635             LOGE("ReportDiscoverRegCallback failed");
636         }
637     }
638     if (ret != DM_OK) {
639         LOGE("[SOFTBUS]RefreshLNN failed, ret: %{public}d.", ret);
640         return ret;
641     }
642     return DM_OK;
643 }
644 
StopRefreshSoftbusLNN(uint16_t subscribeId)645 int32_t SoftbusListener::StopRefreshSoftbusLNN(uint16_t subscribeId)
646 {
647     LOGI("StopRefreshSoftbusLNN begin, subscribeId: %{public}d.", (int32_t)subscribeId);
648     {
649         std::lock_guard<std::mutex> lock(g_lockDeviceIdSet);
650         deviceIdSet.clear();
651     }
652     int32_t ret = ::StopRefreshLNN(DM_PKG_NAME, subscribeId);
653     struct RadarInfo info = {
654         .funcName = "StopRefreshSoftbusLNN",
655         .hostName = SOFTBUSNAME,
656         .stageRes = (ret == DM_OK) ?
657             static_cast<int32_t>(StageRes::STAGE_CANCEL) : static_cast<int32_t>(StageRes::STAGE_FAIL),
658         .bizState = (ret == DM_OK) ?
659             static_cast<int32_t>(BizState::BIZ_STATE_CANCEL) : static_cast<int32_t>(BizState::BIZ_STATE_END),
660         .errCode = ret,
661     };
662     if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
663         if (!GetDmRadarHelperObj()->ReportDiscoverUserRes(info)) {
664             LOGE("ReportDiscoverUserRes failed");
665         }
666     }
667     if (ret != DM_OK) {
668         LOGE("[SOFTBUS]StopRefreshLNN failed, ret: %{public}d.", ret);
669         return ret;
670     }
671     return DM_OK;
672 }
673 
PublishSoftbusLNN(const DmPublishInfo & dmPubInfo,const std::string & capability,const std::string & customData)674 int32_t SoftbusListener::PublishSoftbusLNN(const DmPublishInfo &dmPubInfo, const std::string &capability,
675     const std::string &customData)
676 {
677     LOGI("Begin, publishId: %{public}d.", dmPubInfo.publishId);
678     PublishInfo publishInfo;
679     publishInfo.publishId = dmPubInfo.publishId;
680     publishInfo.mode = static_cast<DiscoverMode>(dmPubInfo.mode);
681     if (capability == DM_CAPABILITY_APPROACH) {
682         publishInfo.medium = ExchangeMedium::BLE;
683     } else {
684         publishInfo.medium = static_cast<ExchangeMedium>(dmPubInfo.medium);
685     }
686     publishInfo.freq = static_cast<ExchangeFreq>(dmPubInfo.freq);
687     publishInfo.capability = capability.c_str();
688     publishInfo.capabilityData = const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(customData.c_str()));
689     publishInfo.dataLen = customData.length();
690     publishInfo.ranging = dmPubInfo.ranging;
691 
692     LOGI("Begin, mode: 0x%{public}x, medium: %{public}d, capability:"
693         "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.mode,
694         publishInfo.medium, publishInfo.capability, publishInfo.ranging, publishInfo.freq);
695 
696     int32_t ret = ::PublishLNN(DM_PKG_NAME, &publishInfo, &softbusPublishCallback_);
697     if (ret != DM_OK) {
698         LOGE("[SOFTBUS]PublishLNN failed, ret: %{public}d.", ret);
699         return ret;
700     }
701     return DM_OK;
702 }
703 
StopPublishSoftbusLNN(int32_t publishId)704 int32_t SoftbusListener::StopPublishSoftbusLNN(int32_t publishId)
705 {
706     LOGI("Begin, publishId: %{public}d.", publishId);
707     int32_t ret = ::StopPublishLNN(DM_PKG_NAME, publishId);
708     if (ret != DM_OK) {
709         LOGE("[SOFTBUS]StopPublishLNN failed, ret: %{public}d.", ret);
710         return ret;
711     }
712     return DM_OK;
713 }
714 
RegisterSoftbusLnnOpsCbk(const std::string & pkgName,const std::shared_ptr<ISoftbusDiscoveringCallback> callback)715 int32_t SoftbusListener::RegisterSoftbusLnnOpsCbk(const std::string &pkgName,
716     const std::shared_ptr<ISoftbusDiscoveringCallback> callback)
717 {
718     if (callback == nullptr) {
719         LOGE("RegisterSoftbusDiscoveringCbk failed, input callback is null.");
720         return ERR_DM_POINT_NULL;
721     }
722     std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
723     lnnOpsCbkMap.erase(pkgName);
724     lnnOpsCbkMap.emplace(pkgName, callback);
725     return DM_OK;
726 }
727 
UnRegisterSoftbusLnnOpsCbk(const std::string & pkgName)728 int32_t SoftbusListener::UnRegisterSoftbusLnnOpsCbk(const std::string &pkgName)
729 {
730     std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
731     lnnOpsCbkMap.erase(pkgName);
732     return DM_OK;
733 }
734 
GetTrustedDeviceList(std::vector<DmDeviceInfo> & deviceInfoList)735 int32_t SoftbusListener::GetTrustedDeviceList(std::vector<DmDeviceInfo> &deviceInfoList)
736 {
737     int32_t ret = SoftbusCache::GetInstance().GetDeviceInfoFromCache(deviceInfoList);
738     size_t deviceCount = deviceInfoList.size();
739     LOGI("Success from cache deviceInfoList size is %{public}zu.", deviceCount);
740     return ret;
741 }
742 
GetDeviceInfo(const std::string & networkId,DmDeviceInfo & info)743 int32_t SoftbusListener::GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info)
744 {
745     return SoftbusCache::GetInstance().GetDevInfoByNetworkId(networkId, info);
746 }
747 
GetLocalDeviceInfo(DmDeviceInfo & deviceInfo)748 int32_t SoftbusListener::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo)
749 {
750     return SoftbusCache::GetInstance().GetLocalDeviceInfo(deviceInfo);
751 }
752 
GetUdidByNetworkId(const char * networkId,std::string & udid)753 int32_t SoftbusListener::GetUdidByNetworkId(const char *networkId, std::string &udid)
754 {
755     return SoftbusCache::GetInstance().GetUdidFromCache(networkId, udid);
756 }
757 
GetUuidByNetworkId(const char * networkId,std::string & uuid)758 int32_t SoftbusListener::GetUuidByNetworkId(const char *networkId, std::string &uuid)
759 {
760     return SoftbusCache::GetInstance().GetUuidFromCache(networkId, uuid);
761 }
762 
GetNetworkIdByUdid(const std::string & udid,std::string & networkId)763 int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string &networkId)
764 {
765     return SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, networkId);
766 }
767 
GetDeviceNameByUdid(const std::string & udid,std::string & deviceName)768 int32_t SoftbusListener::GetDeviceNameByUdid(const std::string &udid, std::string &deviceName)
769 {
770     return SoftbusCache::GetInstance().GetDeviceNameFromCache(udid, deviceName);
771 }
772 
ShiftLNNGear(bool isWakeUp,const std::string & callerId)773 int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId)
774 {
775     if (callerId.empty()) {
776         LOGE("Invalid parameter, callerId is empty.");
777         return ERR_DM_INPUT_PARA_INVALID;
778     }
779     LOGD("Begin for callerId = %{public}s", GetAnonyString(callerId).c_str());
780     GearMode mode = {
781         .cycle = HIGH_FREQ_CYCLE,
782         .duration = DEFAULT_DURATION,
783         .wakeupFlag = isWakeUp,
784     };
785     int32_t ret = ::ShiftLNNGear(DM_PKG_NAME, callerId.c_str(), nullptr, &mode);
786     if (ret != DM_OK) {
787         LOGE("[SOFTBUS]ShiftLNNGear error, failed ret: %{public}d", ret);
788         return ret;
789     }
790     return DM_OK;
791 }
792 
ConvertScreenStatusToDmDevice(const NodeBasicInfo & nodeInfo,const int32_t devScreenStatus,DmDeviceInfo & devInfo)793 int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus,
794     DmDeviceInfo &devInfo)
795 {
796     if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) {
797         LOGE("ConvertNodeBasicInfoToDmDevice memset failed.");
798         return ERR_DM_FAILED;
799     }
800     if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId,
801                  std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) {
802         LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed.");
803         return ERR_DM_FAILED;
804     }
805 
806     if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName,
807                  std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) {
808         LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed.");
809         return ERR_DM_FAILED;
810     }
811     devInfo.deviceTypeId = nodeInfo.deviceTypeId;
812     JsonObject extraJson;
813     extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType;
814     extraJson[PARAM_KEY_OS_VERSION] = ConvertCharArray2String(nodeInfo.osVersion, OS_VERSION_BUF_LEN);
815     extraJson[DEVICE_SCREEN_STATUS] = devScreenStatus;
816     devInfo.extraData = ToString(extraJson);
817     return DM_OK;
818 }
819 
ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo & nodeInfo,DmDeviceInfo & devInfo)820 int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo)
821 {
822     LOGI("Begin, osType : %{public}d", nodeInfo.osType);
823     if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) {
824         LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed.");
825         return ERR_DM_FAILED;
826     }
827     if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId,
828                  std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != EOK) {
829         LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed.");
830         return ERR_DM_FAILED;
831     }
832 
833     if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName,
834                  std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != EOK) {
835         LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed.");
836         return ERR_DM_FAILED;
837     }
838     devInfo.deviceTypeId = nodeInfo.deviceTypeId;
839     JsonObject extraJson;
840     extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType;
841     extraJson[PARAM_KEY_OS_VERSION] = ConvertCharArray2String(nodeInfo.osVersion, OS_VERSION_BUF_LEN);
842     devInfo.extraData = ToString(extraJson);
843     return DM_OK;
844 }
845 
ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo & nodeInfo,DmDeviceBasicInfo & devInfo)846 int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceBasicInfo &devInfo)
847 {
848     if (memset_s(&devInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) {
849         LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed.");
850         return ERR_DM_FAILED;
851     }
852 
853     if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId,
854                  std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != EOK) {
855         LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed.");
856         return ERR_DM_FAILED;
857     }
858 
859     if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName,
860                  std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != EOK) {
861         LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed.");
862         return ERR_DM_FAILED;
863     }
864 
865     devInfo.deviceTypeId = nodeInfo.deviceTypeId;
866     return DM_OK;
867 }
868 
ConvertBytesToUpperCaseHexString(const uint8_t arr[],const size_t size)869 std::string SoftbusListener::ConvertBytesToUpperCaseHexString(const uint8_t arr[], const size_t size)
870 {
871     char result[size * ARRAY_DOUBLE_SIZE + 1];
872     int index = 0;
873     for (size_t i = 0; i < size; i++) {
874         uint8_t num = arr[i];
875         result[index++] = HEX_ARRAY[(num >> BIN_HIGH_FOUR_NUM) & BYTE_MASK];
876         result[index++] = HEX_ARRAY[num & BYTE_MASK];
877     }
878     result[index] = '\0';
879     return result;
880 }
881 
FillDeviceInfo(const DeviceInfo & device,DmDeviceInfo & dmDevice)882 int32_t SoftbusListener::FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice)
883 {
884     if (memset_s(&dmDevice, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) {
885         LOGE("ConvertDeviceInfoToDmDevice memset_s failed.");
886         return ERR_DM_FAILED;
887     }
888 
889     if (memcpy_s(dmDevice.deviceId, sizeof(dmDevice.deviceId), device.devId,
890                  std::min(sizeof(dmDevice.deviceId), sizeof(device.devId))) != DM_OK) {
891         LOGE("ConvertDeviceInfoToDmDevice: copy device id failed.");
892         return ERR_DM_FAILED;
893     }
894 
895     if (memcpy_s(dmDevice.deviceName, sizeof(dmDevice.deviceName), device.devName,
896                  std::min(sizeof(dmDevice.deviceName), sizeof(device.devName))) != DM_OK) {
897         LOGE("ConvertDeviceInfoToDmDevice: copy device name failed.");
898         return ERR_DM_FAILED;
899     }
900 
901     return DM_OK;
902 }
903 
ConvertDeviceInfoToDmDevice(const DeviceInfo & device,DmDeviceInfo & dmDevice)904 void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice)
905 {
906     if (FillDeviceInfo(device, dmDevice) != DM_OK) {
907         LOGE("FillDeviceInfo failed.");
908         return;
909     }
910 
911     dmDevice.deviceTypeId = device.devType;
912     dmDevice.range = device.range;
913 
914     JsonObject jsonObj;
915     std::string customData = ConvertCharArray2String(device.custData, DISC_MAX_CUST_DATA_LEN);
916     jsonObj[PARAM_KEY_CUSTOM_DATA] = customData;
917 
918     const ConnectionAddr *addrInfo = &(device.addr)[0];
919     if (addrInfo == nullptr) {
920         LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr.");
921         dmDevice.extraData = SafetyDump(jsonObj);
922         return;
923     }
924     jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0];
925     ParseConnAddrInfo(addrInfo, jsonObj);
926     dmDevice.extraData = SafetyDump(jsonObj);
927 }
928 
ParseConnAddrInfo(const ConnectionAddr * addrInfo,JsonObject & jsonObj)929 void SoftbusListener::ParseConnAddrInfo(const ConnectionAddr *addrInfo, JsonObject &jsonObj)
930 {
931     if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) {
932         std::string wifiIp((addrInfo->info).ip.ip);
933         jsonObj[PARAM_KEY_WIFI_IP] = wifiIp;
934         jsonObj[PARAM_KEY_WIFI_PORT] = (addrInfo->info).ip.port;
935         jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_ETH_IP;
936     } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) {
937         std::string wifiIp((addrInfo->info).ip.ip);
938         jsonObj[PARAM_KEY_WIFI_IP] = wifiIp;
939         jsonObj[PARAM_KEY_WIFI_PORT] = (addrInfo->info).ip.port;
940         jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_WLAN_IP;
941     } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BR) {
942         std::string brMac((addrInfo->info).br.brMac);
943         jsonObj[PARAM_KEY_BR_MAC] = brMac;
944         jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_BR;
945     } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) {
946         std::string bleMac((addrInfo->info).ble.bleMac);
947         jsonObj[PARAM_KEY_BLE_MAC] = bleMac;
948         jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_BLE;
949         std::string udidHash(ConvertBytesToUpperCaseHexString((addrInfo->info).ble.udidHash,
950             sizeof((addrInfo->info).ble.udidHash) / sizeof(*((addrInfo->info).ble.udidHash))));
951         jsonObj[PARAM_KEY_BLE_UDID_HASH] = udidHash;
952     } else if (addrInfo->type == CONNECTION_ADDR_USB) {
953         std::string usbIp((addrInfo->info).ip.ip);
954         jsonObj[PARAM_KEY_USB_IP] = usbIp;
955         jsonObj[PARAM_KEY_USB_PORT] = (addrInfo->info).ip.port;
956         jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_USB;
957     } else {
958         LOGI("Unknown connection address type: %{public}d.", addrInfo->type);
959     }
960 }
961 
GetNetworkTypeByNetworkId(const char * networkId,int32_t & networkType)962 int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType)
963 {
964     int32_t tempNetworkType = -1;
965     int32_t ret = GetNodeKeyInfo(DM_PKG_NAME, networkId, NodeDeviceInfoKey::NODE_KEY_NETWORK_TYPE,
966         reinterpret_cast<uint8_t *>(&tempNetworkType), LNN_COMMON_LEN);
967     if (ret != DM_OK) {
968         LOGE("[SOFTBUS]GetNodeKeyInfo networkType failed.");
969         return ret;
970     }
971     networkType = tempNetworkType;
972     LOGI("GetNetworkTypeByNetworkId networkType %{public}d.", tempNetworkType);
973     return DM_OK;
974 }
975 
GetDeviceSecurityLevel(const char * networkId,int32_t & securityLevel)976 int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel)
977 {
978     return SoftbusCache::GetInstance().GetSecurityDeviceLevel(networkId, securityLevel);
979 }
980 
CacheDiscoveredDevice(const DeviceInfo * device)981 void SoftbusListener::CacheDiscoveredDevice(const DeviceInfo *device)
982 {
983     std::shared_ptr<DeviceInfo> infoPtr = std::make_shared<DeviceInfo>();
984     if (memcpy_s(infoPtr.get(), sizeof(DeviceInfo), device, sizeof(DeviceInfo)) != DM_OK) {
985         LOGE("CacheDiscoveredDevice error, copy device info failed.");
986         return;
987     }
988 
989     std::lock_guard<std::mutex> lock(g_deviceMapMutex);
990     if (discoveredDeviceMap.size() == MAX_CACHED_DISCOVERED_DEVICE_SIZE) {
991         discoveredDeviceMap.erase(discoveredDeviceMap.begin());
992     }
993     CacheDeviceInfo(device->devId, infoPtr);
994 }
995 
GetTargetInfoFromCache(const std::string & deviceId,PeerTargetId & targetId,ConnectionAddrType & addrType)996 int32_t SoftbusListener::GetTargetInfoFromCache(const std::string &deviceId, PeerTargetId &targetId,
997     ConnectionAddrType &addrType)
998 {
999     std::lock_guard<std::mutex> lock(g_deviceMapMutex);
1000     auto iter = discoveredDeviceMap.find(deviceId);
1001     if (iter == discoveredDeviceMap.end()) {
1002         LOGE("GetTargetInfoFromCache failed, cannot found device in cached discovered map.");
1003         return ERR_DM_BIND_INPUT_PARA_INVALID;
1004     }
1005     auto deviceVectorIter = iter->second;
1006     if (deviceVectorIter.size() == 0) {
1007         LOGE("GetTargetInfoFromCache failed, cannot found deviceVectorIter in cached discovered map.");
1008         return ERR_DM_BIND_INPUT_PARA_INVALID;
1009     }
1010     const ConnectionAddr *addrInfo = &((--deviceVectorIter.end())->second->addr)[0];
1011     if (addrInfo == nullptr) {
1012         LOGE("GetTargetInfoFromCache failed, connection address of discovered device is nullptr.");
1013         return ERR_DM_BIND_COMMON_FAILED;
1014     }
1015 
1016     addrType = addrInfo->type;
1017     if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) {
1018         std::string wifiIp((addrInfo->info).ip.ip);
1019         targetId.wifiIp = wifiIp;
1020         targetId.wifiPort = (addrInfo->info).ip.port;
1021     } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) {
1022         std::string wifiIp((addrInfo->info).ip.ip);
1023         targetId.wifiIp = wifiIp;
1024         targetId.wifiPort = (addrInfo->info).ip.port;
1025     } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BR) {
1026         std::string brMac((addrInfo->info).br.brMac);
1027         targetId.brMac = brMac;
1028     } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) {
1029         std::string bleMac((addrInfo->info).ble.bleMac);
1030         targetId.bleMac = bleMac;
1031     } else {
1032         LOGI("Unknown connection address type: %{public}d.", addrInfo->type);
1033         return ERR_DM_BIND_COMMON_FAILED;
1034     }
1035     targetId.deviceId = deviceId;
1036     return DM_OK;
1037 }
1038 
ClearDiscoveredDevice()1039 void SoftbusListener::ClearDiscoveredDevice()
1040 {
1041     std::lock_guard<std::mutex> lock(g_deviceMapMutex);
1042     discoveredDeviceMap.clear();
1043 }
1044 
GetDmRadarHelperObj()1045 IDmRadarHelper* SoftbusListener::GetDmRadarHelperObj()
1046 {
1047     return dmRadarHelper_;
1048 }
1049 
IsDmRadarHelperReady()1050 bool SoftbusListener::IsDmRadarHelperReady()
1051 {
1052     std::lock_guard<std::mutex> lock(g_radarLoadLock);
1053     if (isRadarSoLoad_ && (dmRadarHelper_ != nullptr) && (radarHandle_ != nullptr)) {
1054         LOGD("IsDmRadarHelperReady alReady.");
1055         return true;
1056     }
1057     radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW | RTLD_NOLOAD);
1058     if (radarHandle_ == nullptr) {
1059         radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW);
1060     }
1061     if (radarHandle_ == nullptr) {
1062         LOGE("load libdevicemanagerradar so failed.");
1063         return false;
1064     }
1065     dlerror();
1066     auto func = (CreateDmRadarFuncPtr)dlsym(radarHandle_, "CreateDmRadarInstance");
1067     if (dlerror() != nullptr || func == nullptr) {
1068         dlclose(radarHandle_);
1069         LOGE("Create object function is not exist.");
1070         return false;
1071     }
1072     LOGI("IsDmRadarHelperReady ready success.");
1073     isRadarSoLoad_ = true;
1074     dmRadarHelper_ = func();
1075     return true;
1076 }
1077 
CloseDmRadarHelperObj(std::string name)1078 bool SoftbusListener::CloseDmRadarHelperObj(std::string name)
1079 {
1080     (void)name;
1081     LOGI("SoftbusListener::CloseDmRadarHelperObj start.");
1082     std::lock_guard<std::mutex> lock(g_radarLoadLock);
1083     if (!isRadarSoLoad_ && (dmRadarHelper_ == nullptr) && (radarHandle_ == nullptr)) {
1084         return true;
1085     }
1086 
1087     int32_t ret = dlclose(radarHandle_);
1088     if (ret != 0) {
1089         LOGE("close libdevicemanagerradar failed ret = %{public}d.", ret);
1090         return false;
1091     }
1092     isRadarSoLoad_ = false;
1093     dmRadarHelper_ = nullptr;
1094     radarHandle_ = nullptr;
1095     LOGI("close libdevicemanagerradar so success.");
1096     return true;
1097 }
1098 
CacheDeviceInfo(const std::string deviceId,std::shared_ptr<DeviceInfo> infoPtr)1099 void SoftbusListener::CacheDeviceInfo(const std::string deviceId, std::shared_ptr<DeviceInfo> infoPtr)
1100 {
1101     if (deviceId.empty()) {
1102         return;
1103     }
1104     if (infoPtr->addrNum <= 0) {
1105         LOGE("CacheDeviceInfo failed, infoPtr->addr is empty.");
1106         return;
1107     }
1108     ConnectionAddrType addrType;
1109     const ConnectionAddr *addrInfo = &(infoPtr->addr)[0];
1110     if (addrInfo == nullptr) {
1111         LOGE("CacheDeviceInfo failed, connection address of discovered device is nullptr.");
1112         return;
1113     }
1114     addrType = addrInfo->type;
1115     std::vector<std::pair<ConnectionAddrType, std::shared_ptr<DeviceInfo>>> deviceVec;
1116     auto iter = discoveredDeviceMap.find(deviceId);
1117     if (iter != discoveredDeviceMap.end()) {
1118         deviceVec = iter->second;
1119         for (auto it = deviceVec.begin(); it != deviceVec.end();) {
1120             if (it->first == addrType) {
1121                 it = deviceVec.erase(it);
1122                 continue;
1123             } else {
1124                 it++;
1125             }
1126         }
1127         discoveredDeviceMap.erase(deviceId);
1128     }
1129     deviceVec.push_back(std::pair<ConnectionAddrType, std::shared_ptr<DeviceInfo>>(addrType, infoPtr));
1130     discoveredDeviceMap.insert(std::pair<std::string,
1131         std::vector<std::pair<ConnectionAddrType, std::shared_ptr<DeviceInfo>>>>(deviceId, deviceVec));
1132 }
1133 
GetIPAddrTypeFromCache(const std::string & deviceId,const std::string & ip,ConnectionAddrType & addrType)1134 int32_t SoftbusListener::GetIPAddrTypeFromCache(const std::string &deviceId, const std::string &ip,
1135     ConnectionAddrType &addrType)
1136 {
1137     std::lock_guard<std::mutex> lock(g_deviceMapMutex);
1138     auto iter = discoveredDeviceMap.find(deviceId);
1139     if (iter == discoveredDeviceMap.end()) {
1140         LOGE("GetIPAddrTypeFromCache failed, cannot found device in cached discovered map.");
1141         return ERR_DM_BIND_INPUT_PARA_INVALID;
1142     }
1143     auto deviceVectorIter = iter->second;
1144     if (deviceVectorIter.size() == 0) {
1145         LOGE("GetTargetInfoFromCache failed, cannot found deviceVectorIter in cached discovered map.");
1146         return ERR_DM_BIND_INPUT_PARA_INVALID;
1147     }
1148     for (auto it = deviceVectorIter.begin(); it != deviceVectorIter.end(); ++it) {
1149         const ConnectionAddr *addrInfo = &((it->second)->addr)[0];
1150         if (addrInfo == nullptr) {
1151             continue;
1152         }
1153         if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH ||
1154             addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) {
1155             std::string cacheIp((addrInfo->info).ip.ip);
1156             if (cacheIp == ip) {
1157                 addrType = addrInfo->type;
1158                 return DM_OK;
1159             }
1160         }
1161     }
1162     return ERR_DM_BIND_INPUT_PARA_INVALID;
1163 }
1164 
SetHostPkgName(const std::string hostName)1165 void SoftbusListener::SetHostPkgName(const std::string hostName)
1166 {
1167     hostName_ = hostName;
1168 }
1169 
GetHostPkgName()1170 std::string SoftbusListener::GetHostPkgName()
1171 {
1172     return hostName_;
1173 }
1174 
SendAclChangedBroadcast(const std::string & msg)1175 void SoftbusListener::SendAclChangedBroadcast(const std::string &msg)
1176 {
1177     LOGI("SendAclChangedBroadcast");
1178     if (SyncTrustedRelationShip(DM_PKG_NAME, msg.c_str(), msg.length()) != DM_OK) {
1179         LOGE("SyncTrustedRelationShip failed.");
1180     }
1181 }
1182 
GetSoftbusRefreshCb()1183 IRefreshCallback &SoftbusListener::GetSoftbusRefreshCb()
1184 {
1185     return softbusRefreshCallback_;
1186 }
1187 
GetDeviceScreenStatus(const char * networkId,int32_t & screenStatus)1188 int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus)
1189 {
1190     int32_t devScreenStatus = -1;
1191     int32_t ret = GetNodeKeyInfo(DM_PKG_NAME, networkId, NodeDeviceInfoKey::NODE_KEY_DEVICE_SCREEN_STATUS,
1192         reinterpret_cast<uint8_t *>(&devScreenStatus), LNN_COMMON_LEN);
1193     if (ret != DM_OK) {
1194         LOGE("[SOFTBUS]GetNodeKeyInfo screenStatus failed.");
1195         return ret;
1196     }
1197     screenStatus = devScreenStatus;
1198     LOGI("GetDeviceScreenStatus screenStatus: %{public}d.", devScreenStatus);
1199     return DM_OK;
1200 }
1201 
SetForegroundUserIdsToDSoftBus(const std::string & remoteUdid,const std::vector<uint32_t> & userIds)1202 int32_t SoftbusListener::SetForegroundUserIdsToDSoftBus(const std::string &remoteUdid,
1203     const std::vector<uint32_t> &userIds)
1204 {
1205 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1206     NotifyUserIds notifyUserIds(remoteUdid, userIds);
1207     std::string msg = notifyUserIds.ToString();
1208     LOGI("Notify remote userid to dsoftbus, msg: %{public}s", GetAnonyString(msg).c_str());
1209     return DM_OK;
1210 #else
1211     (void)remoteUdid;
1212     (void)userIds;
1213 #endif
1214     return DM_OK;
1215 }
1216 
DeleteCacheDeviceInfo()1217 void SoftbusListener::DeleteCacheDeviceInfo()
1218 {
1219     LOGI("DeleteCacheDeviceInfo start.");
1220     std::vector<DmDeviceInfo> onlineDevInfoVec;
1221     SoftbusCache::GetInstance().GetDeviceInfoFromCache(onlineDevInfoVec);
1222     if (onlineDevInfoVec.empty()) {
1223         LOGE("onlineDevInfoVec is empty");
1224         return;
1225     }
1226     SoftbusCache::GetInstance().DeleteDeviceInfo();
1227     for (auto it : onlineDevInfoVec) {
1228         LOGI("networkId: %{public}s", GetAnonyString(it.networkId).c_str());
1229         DeviceOffLine(it);
1230     }
1231 }
1232 
SetLocalDisplayName(const std::string & displayName)1233 int32_t SoftbusListener::SetLocalDisplayName(const std::string &displayName)
1234 {
1235     LOGI("SoftbusListener Start SetLocalDisplayName!");
1236     uint32_t len = static_cast<uint32_t>(displayName.size());
1237     int32_t ret = ::SetDisplayName(DM_PKG_NAME, displayName.c_str(), len);
1238     if (ret != DM_OK) {
1239         LOGE("SoftbusListener SetLocalDisplayName failed!");
1240     }
1241     return DM_OK;
1242 }
1243 
1244 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
ConvertAclToDeviceInfo(DistributedDeviceProfile::AccessControlProfile & profile,DmDeviceInfo & deviceInfo)1245 void SoftbusListener::ConvertAclToDeviceInfo(DistributedDeviceProfile::AccessControlProfile &profile,
1246     DmDeviceInfo &deviceInfo)
1247 {
1248     char udidHash[DM_MAX_DEVICE_ID_LEN] = {0};
1249     if (Crypto::GetUdidHash(profile.GetTrustDeviceId(), reinterpret_cast<uint8_t *>(udidHash)) != DM_OK) {
1250         LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(profile.GetTrustDeviceId()).c_str());
1251         return;
1252     }
1253 
1254     if (memcpy_s(deviceInfo.deviceId, sizeof(deviceInfo.deviceId), udidHash,
1255                  std::min(sizeof(deviceInfo.deviceId), sizeof(udidHash))) != DM_OK) {
1256         LOGE("GetAllTrustedDeviceList copy deviceId failed.");
1257         return;
1258     }
1259 
1260     std::string networkId = "";
1261     if (GetNetworkIdByUdid(profile.GetTrustDeviceId(), networkId) == DM_OK) {
1262         if (memcpy_s(deviceInfo.networkId, sizeof(deviceInfo.networkId), networkId.c_str(),
1263                      std::min(sizeof(deviceInfo.networkId), networkId.size())) != DM_OK) {
1264             LOGE("GetAllTrustedDeviceList copy networkId data failed.");
1265             return;
1266         }
1267     }
1268 
1269     std::string deviceName = "";
1270     if (GetDeviceNameByUdid(profile.GetTrustDeviceId(), deviceName) == DM_OK) {
1271         if (memcpy_s(deviceInfo.deviceName, sizeof(deviceInfo.deviceName), deviceName.c_str(),
1272                      std::min(sizeof(deviceInfo.deviceName), deviceName.size())) != DM_OK) {
1273             LOGE("GetAllTrustedDeviceList copy deviceName data failed.");
1274             return;
1275         }
1276     } else {
1277         if (profile.GetTrustDeviceId() == profile.GetAccessee().GetAccesseeDeviceId()) {
1278             deviceName = profile.GetAccessee().GetAccesseeDeviceName();
1279         } else if (profile.GetTrustDeviceId() == profile.GetAccesser().GetAccesserDeviceId()) {
1280             deviceName = profile.GetAccesser().GetAccesserDeviceName();
1281         }
1282         if (memcpy_s(deviceInfo.deviceName, sizeof(deviceInfo.deviceName), deviceName.c_str(),
1283                      std::min(sizeof(deviceInfo.deviceName), deviceName.size())) != DM_OK) {
1284             LOGE("GetAllTrustedDeviceList copy deviceName data from dp failed.");
1285         }
1286     }
1287 }
1288 #endif
1289 
GetAllTrustedDeviceList(const std::string & pkgName,const std::string & extra,std::vector<DmDeviceInfo> & deviceList)1290 int32_t SoftbusListener::GetAllTrustedDeviceList(const std::string &pkgName, const std::string &extra,
1291     std::vector<DmDeviceInfo> &deviceList)
1292 {
1293 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1294     (void)extra;
1295     uint32_t tokenId = static_cast<uint32_t>(OHOS::IPCSkeleton::GetCallingTokenID());
1296     std::vector<DistributedDeviceProfile::AccessControlProfile> allProfile =
1297         DeviceProfileConnector::GetInstance().GetAllAccessControlProfile();
1298     for (DistributedDeviceProfile::AccessControlProfile profile : allProfile) {
1299         if (profile.GetBindType() == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP) {
1300             continue;
1301         }
1302         DistributedDeviceProfile::Accesser acer = profile.GetAccesser();
1303         if (pkgName == acer.GetAccesserBundleName() && tokenId == acer.GetAccesserTokenId()) {
1304             DmDeviceInfo deviceinfo;
1305             ConvertAclToDeviceInfo(profile, deviceinfo);
1306             deviceList.push_back(deviceinfo);
1307             continue;
1308         }
1309         DistributedDeviceProfile::Accessee acee = profile.GetAccessee();
1310         if (pkgName == acee.GetAccesseeBundleName() && tokenId == acee.GetAccesseeTokenId()) {
1311             DmDeviceInfo deviceinfo;
1312             ConvertAclToDeviceInfo(profile, deviceinfo);
1313             deviceList.push_back(deviceinfo);
1314             continue;
1315         }
1316     }
1317 #endif
1318     return DM_OK;
1319 }
1320 
GetUdidFromDp(const std::string & udidHash,std::string & udid)1321 int32_t SoftbusListener::GetUdidFromDp(const std::string &udidHash, std::string &udid)
1322 {
1323 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
1324     std::vector<DistributedDeviceProfile::AccessControlProfile> allProfile =
1325         DeviceProfileConnector::GetInstance().GetAllAccessControlProfile();
1326     for (DistributedDeviceProfile::AccessControlProfile profile : allProfile) {
1327         if (profile.GetBindType() == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP) {
1328             continue;
1329         }
1330         char udidHashTemp[DM_MAX_DEVICE_ID_LEN] = {0};
1331         if (Crypto::GetUdidHash(profile.GetTrustDeviceId(), reinterpret_cast<uint8_t *>(udidHashTemp)) != DM_OK) {
1332             LOGE("get udidHash by udid: %{public}s failed.", GetAnonyString(profile.GetTrustDeviceId()).c_str());
1333             continue;
1334         }
1335         if (udidHash == std::string(udidHashTemp)) {
1336             udid = profile.GetTrustDeviceId();
1337             return DM_OK;
1338         }
1339     }
1340 #endif
1341     return ERR_DM_FAILED;
1342 }
1343 
GetAttrFromExtraData(DmDeviceInfo & dmDevInfo,int32_t & actionId)1344 int32_t SoftbusListener::GetAttrFromExtraData(DmDeviceInfo &dmDevInfo, int32_t &actionId)
1345 {
1346     cJSON *extraDataJsonObj = cJSON_Parse(dmDevInfo.extraData.c_str());
1347     if (extraDataJsonObj == NULL) {
1348         return DM_OK;
1349     }
1350     cJSON *customData = cJSON_GetObjectItem(extraDataJsonObj, PARAM_KEY_CUSTOM_DATA);
1351     if (customData == NULL) {
1352         cJSON_Delete(extraDataJsonObj);
1353         return DM_OK;
1354     }
1355     cJSON *customDataJson = cJSON_Parse(customData->valuestring);
1356     if (customDataJson == NULL) {
1357         cJSON_Delete(extraDataJsonObj);
1358         return DM_OK;
1359     }
1360     int32_t ret = GetAttrFromCustomData(customDataJson, dmDevInfo, actionId);
1361     cJSON_Delete(customDataJson);
1362     cJSON_Delete(extraDataJsonObj);
1363     return ret;
1364 }
1365 
GetAttrFromCustomData(const cJSON * const customDataJson,DmDeviceInfo & dmDevInfo,int32_t & actionId)1366 int32_t SoftbusListener::GetAttrFromCustomData(const cJSON *const customDataJson, DmDeviceInfo &dmDevInfo,
1367     int32_t &actionId)
1368 {
1369     cJSON *actionIdJson = cJSON_GetObjectItem(customDataJson, CUSTOM_DATA_ACTIONID);
1370     if (actionIdJson == NULL || !cJSON_IsNumber(actionIdJson)) {
1371         return DM_OK;
1372     }
1373     actionId = actionIdJson->valueint;
1374     cJSON *networkIdJson = cJSON_GetObjectItem(customDataJson, CUSTOM_DATA_NETWORKID);
1375     if (networkIdJson == NULL || !cJSON_IsString(networkIdJson)) {
1376         return DM_OK;
1377     }
1378     std::string networkId = networkIdJson->valuestring;
1379     if (memcpy_s(dmDevInfo.deviceId, sizeof(dmDevInfo.deviceId), networkId.c_str(),
1380         std::min(sizeof(dmDevInfo.deviceId), sizeof(networkId))) != DM_OK) {
1381         LOGE("copy deviceId failed.");
1382         return ERR_DM_FAILED;
1383     }
1384     if (memcpy_s(dmDevInfo.networkId, sizeof(dmDevInfo.networkId), networkId.c_str(),
1385         std::min(sizeof(dmDevInfo.networkId), sizeof(networkId))) != DM_OK) {
1386         LOGE("copy networkId failed.");
1387         return ERR_DM_FAILED;
1388     }
1389     cJSON *displayNameJson = cJSON_GetObjectItem(customDataJson, CUSTOM_DATA_DISPLAY_NAME);
1390     if (displayNameJson == NULL || !cJSON_IsString(displayNameJson)) {
1391         return DM_OK;
1392     }
1393     std::string displayName = displayNameJson->valuestring;
1394     if (memcpy_s(dmDevInfo.deviceName, sizeof(dmDevInfo.deviceName), displayName.c_str(),
1395         std::min(sizeof(dmDevInfo.deviceName), sizeof(displayName))) != DM_OK) {
1396         LOGE("copy deviceName failed.");
1397         return ERR_DM_FAILED;
1398     }
1399     return DM_OK;
1400 }
1401 
GetActionId(const std::string & deviceId,int32_t & actionId)1402 void SoftbusListener::GetActionId(const std::string &deviceId, int32_t &actionId)
1403 {
1404     std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
1405     if (discoveredDeviceActionIdMap.find(deviceId) == discoveredDeviceActionIdMap.end()) {
1406         return;
1407     }
1408     actionId = discoveredDeviceActionIdMap.find(deviceId)->second;
1409 }
1410 } // namespace DistributedHardware
1411 } // namespace OHOS