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