1 /*
2 * Copyright (c) 2022-2024 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_anonymous.h"
27 #include "dm_crypto.h"
28 #include "dm_constants.h"
29 #include "dm_device_info.h"
30 #include "dm_log.h"
31 #include "dm_softbus_cache.h"
32 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
33 #include "dm_thread_manager.h"
34 #endif
35 #include "parameter.h"
36 #include "system_ability_definition.h"
37 #include "softbus_adapter.cpp"
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 constexpr const char* DEVICE_ONLINE = "deviceOnLine";
47 constexpr const char* DEVICE_OFFLINE = "deviceOffLine";
48 constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange";
49 constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so";
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 constexpr static char HEX_ARRAY[] = "0123456789ABCDEF";
54 constexpr static uint8_t BYTE_MASK = 0x0F;
55 constexpr static uint16_t ARRAY_DOUBLE_SIZE = 2;
56 constexpr static uint16_t BIN_HIGH_FOUR_NUM = 4;
57 constexpr uint32_t SOFTBUS_MAX_RETRY_TIME = 10;
58
59 static std::mutex g_deviceMapMutex;
60 static std::mutex g_lnnCbkMapMutex;
61 static std::mutex g_radarLoadLock;
62 static std::mutex g_onlineDeviceNumLock;
63 static std::mutex g_lockDeviceNotTrust;
64 static std::mutex g_lockDeviceOnLine;
65 static std::mutex g_lockDeviceOffLine;
66 static std::mutex g_lockDevInfoChange;
67 static std::mutex g_lockDeviceIdSet;
68 static std::mutex g_lockDevScreenStatusChange;
69 static std::mutex g_credentialAuthStatus;
70 static std::map<std::string,
71 std::vector<std::pair<ConnectionAddrType, std::shared_ptr<DeviceInfo>>>> discoveredDeviceMap;
72 static std::map<std::string, std::shared_ptr<ISoftbusDiscoveringCallback>> lnnOpsCbkMap;
73 static std::set<std::string> deviceIdSet;
74 bool SoftbusListener::isRadarSoLoad_ = false;
75 IDmRadarHelper* SoftbusListener::dmRadarHelper_ = nullptr;
76 void* SoftbusListener::radarHandle_ = nullptr;
77 std::string SoftbusListener::hostName_ = "";
78 int32_t g_onlineDeviceNum = 0;
79
OnSessionOpened(int sessionId,int result)80 static int OnSessionOpened(int sessionId, int result)
81 {
82 return DeviceManagerService::GetInstance().OnSessionOpened(sessionId, result);
83 }
84
OnSessionClosed(int sessionId)85 static void OnSessionClosed(int sessionId)
86 {
87 DeviceManagerService::GetInstance().OnSessionClosed(sessionId);
88 }
89
OnBytesReceived(int sessionId,const void * data,unsigned int dataLen)90 static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen)
91 {
92 DeviceManagerService::GetInstance().OnBytesReceived(sessionId, data, dataLen);
93 }
94
OnPinHolderSessionOpened(int sessionId,int result)95 static int OnPinHolderSessionOpened(int sessionId, int result)
96 {
97 return DeviceManagerService::GetInstance().OnPinHolderSessionOpened(sessionId, result);
98 }
99
OnPinHolderSessionClosed(int sessionId)100 static void OnPinHolderSessionClosed(int sessionId)
101 {
102 DeviceManagerService::GetInstance().OnPinHolderSessionClosed(sessionId);
103 }
104
OnPinHolderBytesReceived(int sessionId,const void * data,unsigned int dataLen)105 static void OnPinHolderBytesReceived(int sessionId, const void *data, unsigned int dataLen)
106 {
107 DeviceManagerService::GetInstance().OnPinHolderBytesReceived(sessionId, data, dataLen);
108 }
109
110 static IPublishCb softbusPublishCallback_ = {
111 .OnPublishResult = SoftbusListener::OnSoftbusPublishResult,
112 };
113
114 static INodeStateCb softbusNodeStateCb_ = {
115 .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED |
116 EVENT_NODE_STATUS_CHANGED | EVENT_NODE_HICHAIN_PROOF_EXCEPTION,
117 .onNodeOnline = SoftbusListener::OnSoftbusDeviceOnline,
118 .onNodeOffline = SoftbusListener::OnSoftbusDeviceOffline,
119 .onNodeBasicInfoChanged = SoftbusListener::OnSoftbusDeviceInfoChanged,
120 .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange,
121 .onNodeDeviceNotTrusted = SoftbusListener::OnDeviceNotTrusted,
122 .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged,
123 .onHichainProofException = SoftbusListener::OnCredentialAuthStatus,
124 };
125
126 static IRefreshCallback softbusRefreshCallback_ = {
127 .OnDeviceFound = SoftbusListener::OnSoftbusDeviceFound,
128 .OnDiscoverResult = SoftbusListener::OnSoftbusDiscoveryResult,
129 };
130
DeviceOnLine(DmDeviceInfo deviceInfo)131 void SoftbusListener::DeviceOnLine(DmDeviceInfo deviceInfo)
132 {
133 std::lock_guard<std::mutex> lock(g_lockDeviceOnLine);
134 DeviceManagerService::GetInstance().HandleDeviceStatusChange(DEVICE_STATE_ONLINE, deviceInfo);
135 }
136
DeviceOffLine(DmDeviceInfo deviceInfo)137 void SoftbusListener::DeviceOffLine(DmDeviceInfo deviceInfo)
138 {
139 std::lock_guard<std::mutex> lock(g_lockDeviceOffLine);
140 DeviceManagerService::GetInstance().HandleDeviceStatusChange(DEVICE_STATE_OFFLINE, deviceInfo);
141 }
142
DeviceNameChange(DmDeviceInfo deviceInfo)143 void SoftbusListener::DeviceNameChange(DmDeviceInfo deviceInfo)
144 {
145 std::lock_guard<std::mutex> lock(g_lockDevInfoChange);
146 DeviceManagerService::GetInstance().HandleDeviceStatusChange(DEVICE_INFO_CHANGED, deviceInfo);
147 }
148
DeviceNotTrust(const std::string & msg)149 void SoftbusListener::DeviceNotTrust(const std::string &msg)
150 {
151 std::lock_guard<std::mutex> lock(g_lockDeviceNotTrust);
152 DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg);
153 }
154
DeviceScreenStatusChange(DmDeviceInfo deviceInfo)155 void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo)
156 {
157 std::lock_guard<std::mutex> lock(g_lockDevScreenStatusChange);
158 DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo);
159 }
160
CredentialAuthStatusProcess(std::string proofInfo,uint16_t deviceTypeId,int32_t errcode)161 void SoftbusListener::CredentialAuthStatusProcess(std::string proofInfo, uint16_t deviceTypeId, int32_t errcode)
162 {
163 std::lock_guard<std::mutex> lock(g_credentialAuthStatus);
164 DeviceManagerService::GetInstance().HandleCredentialAuthStatus(proofInfo, deviceTypeId, errcode);
165 }
166
OnCredentialAuthStatus(const char * proofInfo,uint32_t proofLen,uint16_t deviceTypeId,int32_t errcode)167 void SoftbusListener::OnCredentialAuthStatus(const char *proofInfo, uint32_t proofLen,
168 uint16_t deviceTypeId, int32_t errcode)
169 {
170 LOGI("received credential auth status callback from softbus.");
171 if (proofLen > MAX_SOFTBUS_MSG_LEN) {
172 LOGE("[SOFTBUS]received invaild proofInfo value.");
173 return;
174 }
175 std::string proofInfoStr;
176 if (proofInfo != nullptr) {
177 proofInfoStr = std::string(proofInfo, proofLen);
178 }
179 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
180 ffrt::submit([=]() { CredentialAuthStatusProcess(proofInfoStr, deviceTypeId, errcode); });
181 #else
182 std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(proofInfoStr, deviceTypeId, errcode); });
183 if (pthread_setname_np(credentialAuthStatus.native_handle(), CREDENTIAL_AUTH_STATUS) != DM_OK) {
184 LOGE("credentialAuthStatus setname failed.");
185 }
186 credentialAuthStatus.detach();
187 #endif
188 }
189
OnDeviceScreenStatusChanged(NodeStatusType type,NodeStatus * status)190 void SoftbusListener::OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status)
191 {
192 LOGI("received device screen status change callback from softbus.");
193 if (status == nullptr) {
194 LOGE("[SOFTBUS]status is nullptr, type = %{public}d", static_cast<int32_t>(type));
195 return;
196 }
197 LOGI("screenStatusChanged networkId: %{public}s, screenStatus: %{public}d",
198 GetAnonyString(status->basicInfo.networkId).c_str(), static_cast<int32_t>(status->reserved[0]));
199 if (type != NodeStatusType::TYPE_SCREEN_STATUS) {
200 LOGE("type is not matching.");
201 return;
202 }
203 DmDeviceInfo dmDeviceInfo;
204 int32_t devScreenStatus = static_cast<int32_t>(status->reserved[0]);
205 ConvertScreenStatusToDmDevice(status->basicInfo, devScreenStatus, dmDeviceInfo);
206 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
207 ThreadManager::GetInstance().Submit(
208 DEVICE_SCREEN_STATUS_CHANGE, [=]() { DeviceScreenStatusChange(dmDeviceInfo); });
209 #else
210 std::thread devScreenStatusChange([=]() { DeviceScreenStatusChange(dmDeviceInfo); });
211 if (pthread_setname_np(devScreenStatusChange.native_handle(), DEVICE_SCREEN_STATUS_CHANGE) != DM_OK) {
212 LOGE("devScreenStatusChange setname failed.");
213 }
214 devScreenStatusChange.detach();
215 #endif
216 }
217
OnSoftbusDeviceOnline(NodeBasicInfo * info)218 void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info)
219 {
220 LOGI("received device online callback from softbus.");
221 if (info == nullptr) {
222 LOGE("NodeBasicInfo is nullptr.");
223 return;
224 }
225 DmDeviceInfo dmDeviceInfo;
226 ConvertNodeBasicInfoToDmDevice(*info, dmDeviceInfo);
227 LOGI("device online networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str());
228 SoftbusCache::GetInstance().SaveDeviceInfo(dmDeviceInfo);
229 SoftbusCache::GetInstance().SaveDeviceSecurityLevel(dmDeviceInfo.networkId);
230 SoftbusCache::GetInstance().SaveLocalDeviceInfo();
231 {
232 std::lock_guard<std::mutex> lock(g_onlineDeviceNumLock);
233 g_onlineDeviceNum++;
234 }
235 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
236 ThreadManager::GetInstance().Submit(DEVICE_ONLINE, [=]() { DeviceOnLine(dmDeviceInfo); });
237 #else
238 std::thread deviceOnLine([=]() { DeviceOnLine(dmDeviceInfo); });
239 int32_t ret = pthread_setname_np(deviceOnLine.native_handle(), DEVICE_ONLINE);
240 if (ret != DM_OK) {
241 LOGE("deviceOnLine setname failed.");
242 }
243 deviceOnLine.detach();
244 #endif
245 {
246 std::string peerUdid;
247 GetUdidByNetworkId(info->networkId, peerUdid);
248 struct RadarInfo radarInfo = {
249 .funcName = "OnSoftbusDeviceOnline",
250 .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
251 .bizState = static_cast<int32_t>(BizState::BIZ_STATE_START),
252 .isTrust = static_cast<int32_t>(TrustStatus::IS_TRUST),
253 .peerNetId = info->networkId,
254 .peerUdid = peerUdid,
255 };
256 if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
257 if (!GetDmRadarHelperObj()->ReportNetworkOnline(radarInfo)) {
258 LOGE("ReportNetworkOnline failed");
259 }
260 }
261 }
262 }
263
OnSoftbusDeviceOffline(NodeBasicInfo * info)264 void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info)
265 {
266 LOGI("received device offline callback from softbus.");
267 if (info == nullptr) {
268 LOGE("NodeBasicInfo is nullptr.");
269 return;
270 }
271 DmDeviceInfo dmDeviceInfo;
272 ConvertNodeBasicInfoToDmDevice(*info, dmDeviceInfo);
273 SoftbusCache::GetInstance().DeleteDeviceInfo(dmDeviceInfo);
274 SoftbusCache::GetInstance().DeleteDeviceSecurityLevel(dmDeviceInfo.networkId);
275 {
276 std::lock_guard<std::mutex> lock(g_onlineDeviceNumLock);
277 g_onlineDeviceNum--;
278 if (g_onlineDeviceNum == 0) {
279 SoftbusCache::GetInstance().DeleteLocalDeviceInfo();
280 }
281 }
282 LOGI("device offline networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str());
283 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
284 ThreadManager::GetInstance().Submit(DEVICE_OFFLINE, [=]() { DeviceOffLine(dmDeviceInfo); });
285 #else
286 std::thread deviceOffLine([=]() { DeviceOffLine(dmDeviceInfo); });
287 int32_t ret = pthread_setname_np(deviceOffLine.native_handle(), DEVICE_OFFLINE);
288 if (ret != DM_OK) {
289 LOGE("deviceOffLine setname failed.");
290 }
291 deviceOffLine.detach();
292 #endif
293 {
294 std::string peerUdid;
295 GetUdidByNetworkId(info->networkId, peerUdid);
296 struct RadarInfo radarInfo = {
297 .funcName = "OnSoftbusDeviceOffline",
298 .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
299 .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
300 .peerNetId = info->networkId,
301 .peerUdid = peerUdid,
302 };
303 if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
304 if (!GetDmRadarHelperObj()->ReportNetworkOffline(radarInfo)) {
305 LOGE("ReportNetworkOffline failed");
306 }
307 }
308 }
309 }
310
OnSoftbusDeviceInfoChanged(NodeBasicInfoType type,NodeBasicInfo * info)311 void SoftbusListener::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info)
312 {
313 LOGI("received device info change from softbus.");
314 if (info == nullptr) {
315 LOGE("NodeBasicInfo is nullptr.");
316 return;
317 }
318 if (type == NodeBasicInfoType::TYPE_DEVICE_NAME || type == NodeBasicInfoType::TYPE_NETWORK_INFO) {
319 LOGI("DeviceInfo %{public}d change.", type);
320 DmDeviceInfo dmDeviceInfo;
321 int32_t networkType = -1;
322 if (type == NodeBasicInfoType::TYPE_NETWORK_INFO) {
323 if (GetNodeKeyInfo(DM_PKG_NAME, info->networkId, NodeDeviceInfoKey::NODE_KEY_NETWORK_TYPE,
324 reinterpret_cast<uint8_t *>(&networkType), LNN_COMMON_LEN) != DM_OK) {
325 LOGE("[SOFTBUS]GetNodeKeyInfo networkType failed.");
326 return;
327 }
328 LOGI("OnSoftbusDeviceInfoChanged NetworkType %{public}d.", networkType);
329 }
330 ConvertNodeBasicInfoToDmDevice(*info, dmDeviceInfo);
331 LOGI("device changed networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str());
332 dmDeviceInfo.networkType = networkType;
333 SoftbusCache::GetInstance().ChangeDeviceInfo(dmDeviceInfo);
334 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
335 ThreadManager::GetInstance().Submit(DEVICE_NAME_CHANGE, [=]() { DeviceNameChange(dmDeviceInfo); });
336 #else
337 std::thread deviceInfoChange([=]() { DeviceNameChange(dmDeviceInfo); });
338 if (pthread_setname_np(deviceInfoChange.native_handle(), DEVICE_NAME_CHANGE) != DM_OK) {
339 LOGE("DeviceNameChange setname failed.");
340 }
341 deviceInfoChange.detach();
342 #endif
343 }
344 }
345
OnLocalDevInfoChange()346 void SoftbusListener::OnLocalDevInfoChange()
347 {
348 LOGI("SoftbusListener::OnLocalDevInfoChange");
349 SoftbusCache::GetInstance().UpDataLocalDevInfo();
350 }
351
OnDeviceNotTrusted(const char * msg)352 void SoftbusListener::OnDeviceNotTrusted(const char *msg)
353 {
354 LOGI("SoftbusListener::OnDeviceNotTrusted.");
355
356 if (msg == nullptr || strlen(msg) > MAX_SOFTBUS_MSG_LEN) {
357 LOGE("OnDeviceNotTrusted msg invalied.");
358 return;
359 }
360 std::string softbusMsg = std::string(msg);
361 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
362 ThreadManager::GetInstance().Submit(DEVICE_NOT_TRUST, [=]() { DeviceNotTrust(softbusMsg); });
363 #else
364 std::thread deviceNotTrust([=]() { DeviceNotTrust(softbusMsg); });
365 int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST);
366 if (ret != DM_OK) {
367 LOGE("deviceNotTrust setname failed.");
368 }
369 deviceNotTrust.detach();
370 #endif
371 }
372
OnSoftbusDeviceFound(const DeviceInfo * device)373 void SoftbusListener::OnSoftbusDeviceFound(const DeviceInfo *device)
374 {
375 if (device == nullptr) {
376 LOGE("[SOFTBUS]device is null.");
377 return;
378 }
379 DmDeviceInfo dmDevInfo;
380 ConvertDeviceInfoToDmDevice(*device, dmDevInfo);
381 {
382 std::lock_guard<std::mutex> lock(g_lockDeviceIdSet);
383 if (deviceIdSet.find(std::string(dmDevInfo.deviceId)) == deviceIdSet.end()) {
384 deviceIdSet.insert(std::string(dmDevInfo.deviceId));
385 struct RadarInfo info = {
386 .funcName = "OnSoftbusDeviceFound",
387 .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
388 .peerNetId = "",
389 .peerUdid = std::string(dmDevInfo.deviceId),
390 };
391 if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
392 if (!GetDmRadarHelperObj()->ReportDiscoverResCallback(info)) {
393 LOGE("ReportDiscoverResCallback failed");
394 }
395 }
396 }
397 }
398 LOGI("DevId=%{public}s, devName=%{public}s, devType=%{public}d, range=%{public}d,"
399 "isOnline=%{public}d", GetAnonyString(dmDevInfo.deviceId).c_str(),
400 GetAnonyString(dmDevInfo.deviceName).c_str(), dmDevInfo.deviceTypeId, dmDevInfo.range, device->isOnline);
401
402 std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
403 CacheDiscoveredDevice(device);
404 for (auto &iter : lnnOpsCbkMap) {
405 iter.second->OnDeviceFound(iter.first, dmDevInfo, device->isOnline);
406 }
407 }
408
OnSoftbusDiscoveryResult(int subscribeId,RefreshResult result)409 void SoftbusListener::OnSoftbusDiscoveryResult(int subscribeId, RefreshResult result)
410 {
411 uint16_t originId = static_cast<uint16_t>((static_cast<uint32_t>(subscribeId)) & SOFTBUS_SUBSCRIBE_ID_MASK);
412 std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
413 for (auto &iter : lnnOpsCbkMap) {
414 iter.second->OnDiscoveringResult(iter.first, originId, result);
415 }
416 }
417
OnSoftbusPublishResult(int publishId,PublishResult result)418 void SoftbusListener::OnSoftbusPublishResult(int publishId, PublishResult result)
419 {
420 LOGD("OnSoftbusPublishResult, publishId: %{public}d, result: %{public}d.", publishId, result);
421 }
422
SoftbusListener()423 SoftbusListener::SoftbusListener()
424 {
425 ISessionListener sessionListener = {
426 .OnSessionOpened = OnSessionOpened,
427 .OnSessionClosed = OnSessionClosed,
428 .OnBytesReceived = OnBytesReceived,
429 .OnMessageReceived = nullptr,
430 .OnStreamReceived = nullptr
431 };
432 LOGD("SoftbusListener constructor.");
433 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
434 int32_t ret = CreateSessionServer(DM_PKG_NAME, DM_SESSION_NAME, &sessionListener);
435 if (ret != DM_OK) {
436 LOGE("[SOFTBUS]CreateSessionServer failed, ret: %{public}d.", ret);
437 }
438 ISessionListener pinHolderSessionListener = {
439 .OnSessionOpened = OnPinHolderSessionOpened,
440 .OnSessionClosed = OnPinHolderSessionClosed,
441 .OnBytesReceived = OnPinHolderBytesReceived,
442 .OnMessageReceived = nullptr,
443 .OnStreamReceived = nullptr
444 };
445 ret = CreateSessionServer(DM_PKG_NAME, DM_PIN_HOLDER_SESSION_NAME, &pinHolderSessionListener);
446 if (ret != DM_OK) {
447 LOGE("[SOFTBUS]CreateSessionServer pin holder failed, ret: %{public}d.", ret);
448 }
449 SoftbusAdapter::GetInstance().CreateSoftbusSessionServer(DM_PKG_NAME, DM_UNBIND_SESSION_NAME);
450 #endif
451 InitSoftbusListener();
452 ClearDiscoveredDevice();
453 }
454
~SoftbusListener()455 SoftbusListener::~SoftbusListener()
456 {
457 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
458 RemoveSessionServer(DM_PKG_NAME, DM_SESSION_NAME);
459 RemoveSessionServer(DM_PKG_NAME, DM_PIN_HOLDER_SESSION_NAME);
460 SoftbusAdapter::GetInstance().RemoveSoftbusSessionServer(DM_PKG_NAME, DM_UNBIND_SESSION_NAME);
461 #endif
462 LOGD("SoftbusListener destructor.");
463 }
464
InitSoftbusListener()465 int32_t SoftbusListener::InitSoftbusListener()
466 {
467 int32_t ret;
468 uint32_t retryTimes = 0;
469 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
470 do {
471 ret = RegNodeDeviceStateCb(DM_PKG_NAME, &softbusNodeStateCb_);
472 if (ret != DM_OK) {
473 ++retryTimes;
474 LOGE("[SOFTBUS]RegNodeDeviceStateCb failed with ret: %{public}d, retryTimes: %{public}u.", ret, retryTimes);
475 usleep(SOFTBUS_CHECK_INTERVAL);
476 }
477 } while (ret != DM_OK && retryTimes < SOFTBUS_MAX_RETRY_TIME);
478 #endif
479 return InitSoftPublishLNN();
480 }
481
InitSoftPublishLNN()482 int32_t SoftbusListener::InitSoftPublishLNN()
483 {
484 int32_t ret = DM_OK;
485 #if (defined(__LITEOS_M__) || defined(LITE_DEVICE))
486 PublishInfo publishInfo;
487 publishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID;
488 publishInfo.mode = DiscoverMode::DISCOVER_MODE_PASSIVE;
489 publishInfo.medium = ExchangeMedium::AUTO;
490 publishInfo.freq = ExchangeFreq::LOW;
491 publishInfo.capability = DM_CAPABILITY_OSD;
492 publishInfo.ranging = false;
493 LOGI("InitSoftPublishLNN begin, publishId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:"
494 "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.publishId, publishInfo.mode,
495 publishInfo.medium, publishInfo.capability, publishInfo.ranging, publishInfo.freq);
496
497 ret = PublishLNN(DM_PKG_NAME, &publishInfo, &softbusPublishCallback_);
498 if (ret == DM_OK) {
499 LOGI("[SOFTBUS]PublishLNN successed, ret: %{public}d", ret);
500 }
501 #endif
502 return ret;
503 }
504
RefreshSoftbusLNN(const char * pkgName,const DmSubscribeInfo & dmSubInfo,const std::string & customData)505 int32_t SoftbusListener::RefreshSoftbusLNN(const char *pkgName, const DmSubscribeInfo &dmSubInfo,
506 const std::string &customData)
507 {
508 LOGI("RefreshSoftbusLNN begin, subscribeId: %{public}d.", dmSubInfo.subscribeId);
509 SubscribeInfo subscribeInfo;
510 (void)memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo));
511 subscribeInfo.subscribeId = dmSubInfo.subscribeId;
512 subscribeInfo.mode = static_cast<DiscoverMode>(dmSubInfo.mode);
513 subscribeInfo.medium = static_cast<ExchangeMedium>(dmSubInfo.medium);
514 subscribeInfo.freq = static_cast<ExchangeFreq>(dmSubInfo.freq);
515 subscribeInfo.isSameAccount = dmSubInfo.isSameAccount;
516 subscribeInfo.isWakeRemote = dmSubInfo.isWakeRemote;
517 subscribeInfo.capability = dmSubInfo.capability;
518 subscribeInfo.capabilityData =
519 const_cast<unsigned char *>(reinterpret_cast<const unsigned char *>(customData.c_str()));
520 subscribeInfo.dataLen = customData.size();
521 LOGI("RefreshSoftbusLNN begin, subscribeId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:"
522 "%{public}s, freq: %{public}d.", subscribeInfo.subscribeId, subscribeInfo.mode, subscribeInfo.medium,
523 subscribeInfo.capability, subscribeInfo.freq);
524 int32_t ret = ::RefreshLNN(pkgName, &subscribeInfo, &softbusRefreshCallback_);
525 struct RadarInfo info = {
526 .funcName = "RefreshSoftbusLNN",
527 .toCallPkg = "dsoftbus",
528 .hostName = GetHostPkgName(),
529 .stageRes = (ret == DM_OK) ?
530 static_cast<int32_t>(StageRes::STAGE_IDLE) : static_cast<int32_t>(StageRes::STAGE_FAIL),
531 .bizState = (ret == DM_OK) ?
532 static_cast<int32_t>(BizState::BIZ_STATE_START) : static_cast<int32_t>(BizState::BIZ_STATE_END),
533 .commServ = static_cast<int32_t>(CommServ::USE_SOFTBUS),
534 .errCode = ret,
535 };
536 if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
537 if (!GetDmRadarHelperObj()->ReportDiscoverRegCallback(info)) {
538 LOGE("ReportDiscoverRegCallback failed");
539 }
540 }
541 if (ret != DM_OK) {
542 LOGE("[SOFTBUS]RefreshLNN failed, ret: %{public}d.", ret);
543 return ret;
544 }
545 return DM_OK;
546 }
547
StopRefreshSoftbusLNN(uint16_t subscribeId)548 int32_t SoftbusListener::StopRefreshSoftbusLNN(uint16_t subscribeId)
549 {
550 LOGI("StopRefreshSoftbusLNN begin, subscribeId: %{public}d.", (int32_t)subscribeId);
551 {
552 std::lock_guard<std::mutex> lock(g_lockDeviceIdSet);
553 deviceIdSet.clear();
554 }
555 int32_t ret = ::StopRefreshLNN(DM_PKG_NAME, subscribeId);
556 struct RadarInfo info = {
557 .funcName = "StopRefreshSoftbusLNN",
558 .hostName = SOFTBUSNAME,
559 .stageRes = (ret == DM_OK) ?
560 static_cast<int32_t>(StageRes::STAGE_CANCEL) : static_cast<int32_t>(StageRes::STAGE_FAIL),
561 .bizState = (ret == DM_OK) ?
562 static_cast<int32_t>(BizState::BIZ_STATE_CANCEL) : static_cast<int32_t>(BizState::BIZ_STATE_END),
563 .errCode = ret,
564 };
565 if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
566 if (!GetDmRadarHelperObj()->ReportDiscoverUserRes(info)) {
567 LOGE("ReportDiscoverUserRes failed");
568 }
569 }
570 if (ret != DM_OK) {
571 LOGE("[SOFTBUS]StopRefreshLNN failed, ret: %{public}d.", ret);
572 return ret;
573 }
574 return DM_OK;
575 }
576
PublishSoftbusLNN(const DmPublishInfo & dmPubInfo,const std::string & capability,const std::string & customData)577 int32_t SoftbusListener::PublishSoftbusLNN(const DmPublishInfo &dmPubInfo, const std::string &capability,
578 const std::string &customData)
579 {
580 LOGI("Begin, publishId: %{public}d.", dmPubInfo.publishId);
581 PublishInfo publishInfo;
582 publishInfo.publishId = dmPubInfo.publishId;
583 publishInfo.mode = static_cast<DiscoverMode>(dmPubInfo.mode);
584 publishInfo.medium = (capability == DM_CAPABILITY_APPROACH) ? ExchangeMedium::BLE : ExchangeMedium::AUTO;
585 publishInfo.freq = static_cast<ExchangeFreq>(dmPubInfo.freq);
586 publishInfo.capability = capability.c_str();
587 publishInfo.capabilityData = const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(customData.c_str()));
588 publishInfo.dataLen = customData.length();
589 publishInfo.ranging = dmPubInfo.ranging;
590
591 LOGI("Begin, mode: 0x%{public}x, medium: %{public}d, capability:"
592 "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.mode,
593 publishInfo.medium, publishInfo.capability, publishInfo.ranging, publishInfo.freq);
594
595 int32_t ret = ::PublishLNN(DM_PKG_NAME, &publishInfo, &softbusPublishCallback_);
596 if (ret != DM_OK) {
597 LOGE("[SOFTBUS]PublishLNN failed, ret: %{public}d.", ret);
598 return ret;
599 }
600 return DM_OK;
601 }
602
StopPublishSoftbusLNN(int32_t publishId)603 int32_t SoftbusListener::StopPublishSoftbusLNN(int32_t publishId)
604 {
605 LOGI("Begin, publishId: %{public}d.", publishId);
606 int32_t ret = ::StopPublishLNN(DM_PKG_NAME, publishId);
607 if (ret != DM_OK) {
608 LOGE("[SOFTBUS]StopPublishLNN failed, ret: %{public}d.", ret);
609 return ret;
610 }
611 return DM_OK;
612 }
613
RegisterSoftbusLnnOpsCbk(const std::string & pkgName,const std::shared_ptr<ISoftbusDiscoveringCallback> callback)614 int32_t SoftbusListener::RegisterSoftbusLnnOpsCbk(const std::string &pkgName,
615 const std::shared_ptr<ISoftbusDiscoveringCallback> callback)
616 {
617 if (callback == nullptr) {
618 LOGE("RegisterSoftbusDiscoveringCbk failed, input callback is null.");
619 return ERR_DM_POINT_NULL;
620 }
621 std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
622 lnnOpsCbkMap.erase(pkgName);
623 lnnOpsCbkMap.emplace(pkgName, callback);
624 return DM_OK;
625 }
626
UnRegisterSoftbusLnnOpsCbk(const std::string & pkgName)627 int32_t SoftbusListener::UnRegisterSoftbusLnnOpsCbk(const std::string &pkgName)
628 {
629 std::lock_guard<std::mutex> lock(g_lnnCbkMapMutex);
630 lnnOpsCbkMap.erase(pkgName);
631 return DM_OK;
632 }
633
GetTrustedDeviceList(std::vector<DmDeviceInfo> & deviceInfoList)634 int32_t SoftbusListener::GetTrustedDeviceList(std::vector<DmDeviceInfo> &deviceInfoList)
635 {
636 int32_t ret = SoftbusCache::GetInstance().GetDeviceInfoFromCache(deviceInfoList);
637 static size_t radarDeviceCount = 0;
638 size_t deviceCount = deviceInfoList.size();
639 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
640 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
641 struct RadarInfo radarInfo = {
642 .localUdid = std::string(localDeviceId),
643 };
644 radarInfo.stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC);
645 if (radarDeviceCount != deviceCount && deviceCount > 0
646 && IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) {
647 radarDeviceCount = deviceCount;
648 radarInfo.discoverDevList = GetDmRadarHelperObj()->GetDeviceInfoList(deviceInfoList);
649 if (!GetDmRadarHelperObj()->ReportGetTrustDeviceList(radarInfo)) {
650 LOGE("ReportGetTrustDeviceList failed");
651 }
652 }
653 LOGI("Success from cache deviceInfoList size is %{public}zu.", deviceCount);
654 return ret;
655 }
656
GetDeviceInfo(const std::string & networkId,DmDeviceInfo & info)657 int32_t SoftbusListener::GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info)
658 {
659 return SoftbusCache::GetInstance().GetDevInfoByNetworkId(networkId, info);
660 }
661
GetLocalDeviceInfo(DmDeviceInfo & deviceInfo)662 int32_t SoftbusListener::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo)
663 {
664 return SoftbusCache::GetInstance().GetLocalDeviceInfo(deviceInfo);
665 }
666
GetUdidByNetworkId(const char * networkId,std::string & udid)667 int32_t SoftbusListener::GetUdidByNetworkId(const char *networkId, std::string &udid)
668 {
669 return SoftbusCache::GetInstance().GetUdidFromCache(networkId, udid);
670 }
671
GetUuidByNetworkId(const char * networkId,std::string & uuid)672 int32_t SoftbusListener::GetUuidByNetworkId(const char *networkId, std::string &uuid)
673 {
674 return SoftbusCache::GetInstance().GetUuidFromCache(networkId, uuid);
675 }
676
GetNetworkIdByUdid(const std::string & udid,std::string & networkId)677 int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string &networkId)
678 {
679 return SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, networkId);
680 }
681
ShiftLNNGear(bool isWakeUp,const std::string & callerId)682 int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId)
683 {
684 if (callerId.empty()) {
685 LOGE("Invalid parameter, callerId is empty.");
686 return ERR_DM_INPUT_PARA_INVALID;
687 }
688 LOGD("Begin for callerId = %{public}s", GetAnonyString(callerId).c_str());
689 GearMode mode = {
690 .cycle = HIGH_FREQ_CYCLE,
691 .duration = DEFAULT_DURATION,
692 .wakeupFlag = isWakeUp,
693 };
694 int32_t ret = ::ShiftLNNGear(DM_PKG_NAME, callerId.c_str(), nullptr, &mode);
695 if (ret != DM_OK) {
696 LOGE("[SOFTBUS]ShiftLNNGear error, failed ret: %{public}d", ret);
697 return ret;
698 }
699 return DM_OK;
700 }
701
ConvertScreenStatusToDmDevice(const NodeBasicInfo & nodeInfo,const int32_t devScreenStatus,DmDeviceInfo & devInfo)702 int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus,
703 DmDeviceInfo &devInfo)
704 {
705 (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo));
706 if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId,
707 std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) {
708 LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed.");
709 }
710
711 if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName,
712 std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) {
713 LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed.");
714 }
715 devInfo.deviceTypeId = nodeInfo.deviceTypeId;
716 nlohmann::json extraJson;
717 extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType;
718 extraJson[PARAM_KEY_OS_VERSION] = ConvertCharArray2String(nodeInfo.osVersion, OS_VERSION_BUF_LEN);
719 extraJson[DEVICE_SCREEN_STATUS] = devScreenStatus;
720 devInfo.extraData = to_string(extraJson);
721 return DM_OK;
722 }
723
ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo & nodeInfo,DmDeviceInfo & devInfo)724 int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo)
725 {
726 (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo));
727 if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId,
728 std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) {
729 LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed.");
730 }
731
732 if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName,
733 std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) {
734 LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed.");
735 }
736 devInfo.deviceTypeId = nodeInfo.deviceTypeId;
737 nlohmann::json extraJson;
738 extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType;
739 extraJson[PARAM_KEY_OS_VERSION] = ConvertCharArray2String(nodeInfo.osVersion, OS_VERSION_BUF_LEN);
740 devInfo.extraData = to_string(extraJson);
741 return DM_OK;
742 }
743
ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo & nodeInfo,DmDeviceBasicInfo & devInfo)744 int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceBasicInfo &devInfo)
745 {
746 (void)memset_s(&devInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo));
747 if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId,
748 std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) {
749 LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed.");
750 }
751
752 if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName,
753 std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) {
754 LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed.");
755 }
756 devInfo.deviceTypeId = nodeInfo.deviceTypeId;
757 return DM_OK;
758 }
759
ConvertBytesToUpperCaseHexString(const uint8_t arr[],const size_t size)760 std::string SoftbusListener::ConvertBytesToUpperCaseHexString(const uint8_t arr[], const size_t size)
761 {
762 char result[size * ARRAY_DOUBLE_SIZE + 1];
763 int index = 0;
764 for (size_t i = 0; i < size; i++) {
765 uint8_t num = arr[i];
766 result[index++] = HEX_ARRAY[(num >> BIN_HIGH_FOUR_NUM) & BYTE_MASK];
767 result[index++] = HEX_ARRAY[num & BYTE_MASK];
768 }
769 result[index] = '\0';
770 return result;
771 }
772
ConvertDeviceInfoToDmDevice(const DeviceInfo & device,DmDeviceInfo & dmDevice)773 void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice)
774 {
775 (void)memset_s(&dmDevice, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo));
776
777 if (memcpy_s(dmDevice.deviceId, sizeof(dmDevice.deviceId), device.devId,
778 std::min(sizeof(dmDevice.deviceId), sizeof(device.devId))) != DM_OK) {
779 LOGE("ConvertDeviceInfoToDmDevice: copy device id failed.");
780 }
781
782 if (memcpy_s(dmDevice.deviceName, sizeof(dmDevice.deviceName), device.devName,
783 std::min(sizeof(dmDevice.deviceName), sizeof(device.devName))) != DM_OK) {
784 LOGE("ConvertDeviceInfoToDmDevice: copy device name failed.");
785 }
786
787 dmDevice.deviceTypeId = device.devType;
788 dmDevice.range = device.range;
789
790 nlohmann::json jsonObj;
791 std::string customData = ConvertCharArray2String(device.custData, DISC_MAX_CUST_DATA_LEN);
792 jsonObj[PARAM_KEY_CUSTOM_DATA] = customData;
793
794 const ConnectionAddr *addrInfo = &(device.addr)[0];
795 if (addrInfo == nullptr) {
796 LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr.");
797 dmDevice.extraData = jsonObj.dump();
798 return;
799 }
800 jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0];
801 if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) {
802 std::string wifiIp((addrInfo->info).ip.ip);
803 jsonObj[PARAM_KEY_WIFI_IP] = wifiIp;
804 jsonObj[PARAM_KEY_WIFI_PORT] = (addrInfo->info).ip.port;
805 jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_ETH_IP;
806 } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) {
807 std::string wifiIp((addrInfo->info).ip.ip);
808 jsonObj[PARAM_KEY_WIFI_IP] = wifiIp;
809 jsonObj[PARAM_KEY_WIFI_PORT] = (addrInfo->info).ip.port;
810 jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_WLAN_IP;
811 } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BR) {
812 std::string brMac((addrInfo->info).br.brMac);
813 jsonObj[PARAM_KEY_BR_MAC] = brMac;
814 jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_BR;
815 } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) {
816 std::string bleMac((addrInfo->info).ble.bleMac);
817 jsonObj[PARAM_KEY_BLE_MAC] = bleMac;
818 jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_BLE;
819 std::string udidHash(ConvertBytesToUpperCaseHexString((addrInfo->info).ble.udidHash,
820 sizeof((addrInfo->info).ble.udidHash) / sizeof(*((addrInfo->info).ble.udidHash))));
821 jsonObj[PARAM_KEY_BLE_UDID_HASH] = udidHash;
822 } else {
823 LOGI("Unknown connection address type: %{public}d.", addrInfo->type);
824 }
825 dmDevice.extraData = jsonObj.dump();
826 }
827
GetNetworkTypeByNetworkId(const char * networkId,int32_t & networkType)828 int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType)
829 {
830 int32_t tempNetworkType = -1;
831 int32_t ret = GetNodeKeyInfo(DM_PKG_NAME, networkId, NodeDeviceInfoKey::NODE_KEY_NETWORK_TYPE,
832 reinterpret_cast<uint8_t *>(&tempNetworkType), LNN_COMMON_LEN);
833 if (ret != DM_OK) {
834 LOGE("[SOFTBUS]GetNodeKeyInfo networkType failed.");
835 return ret;
836 }
837 networkType = tempNetworkType;
838 LOGI("GetNetworkTypeByNetworkId networkType %{public}d.", tempNetworkType);
839 return DM_OK;
840 }
841
GetDeviceSecurityLevel(const char * networkId,int32_t & securityLevel)842 int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel)
843 {
844 return SoftbusCache::GetInstance().GetSecurityDeviceLevel(networkId, securityLevel);
845 }
846
CacheDiscoveredDevice(const DeviceInfo * device)847 void SoftbusListener::CacheDiscoveredDevice(const DeviceInfo *device)
848 {
849 std::shared_ptr<DeviceInfo> infoPtr = std::make_shared<DeviceInfo>();
850 if (memcpy_s(infoPtr.get(), sizeof(DeviceInfo), device, sizeof(DeviceInfo)) != DM_OK) {
851 LOGE("CacheDiscoveredDevice error, copy device info failed.");
852 return;
853 }
854
855 std::lock_guard<std::mutex> lock(g_deviceMapMutex);
856 if (discoveredDeviceMap.size() == MAX_CACHED_DISCOVERED_DEVICE_SIZE) {
857 discoveredDeviceMap.erase(discoveredDeviceMap.begin());
858 }
859 CacheDeviceInfo(device->devId, infoPtr);
860 }
861
GetTargetInfoFromCache(const std::string & deviceId,PeerTargetId & targetId,ConnectionAddrType & addrType)862 int32_t SoftbusListener::GetTargetInfoFromCache(const std::string &deviceId, PeerTargetId &targetId,
863 ConnectionAddrType &addrType)
864 {
865 std::lock_guard<std::mutex> lock(g_deviceMapMutex);
866 auto iter = discoveredDeviceMap.find(deviceId);
867 if (iter == discoveredDeviceMap.end()) {
868 LOGE("GetTargetInfoFromCache failed, cannot found device in cached discovered map.");
869 return ERR_DM_BIND_INPUT_PARA_INVALID;
870 }
871 auto deviceVectorIter = iter->second;
872 if (deviceVectorIter.size() == 0) {
873 LOGE("GetTargetInfoFromCache failed, cannot found deviceVectorIter in cached discovered map.");
874 return ERR_DM_BIND_INPUT_PARA_INVALID;
875 }
876 const ConnectionAddr *addrInfo = &((--deviceVectorIter.end())->second->addr)[0];
877 if (addrInfo == nullptr) {
878 LOGE("GetTargetInfoFromCache failed, connection address of discovered device is nullptr.");
879 return ERR_DM_BIND_COMMON_FAILED;
880 }
881
882 addrType = addrInfo->type;
883 if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) {
884 std::string wifiIp((addrInfo->info).ip.ip);
885 targetId.wifiIp = wifiIp;
886 targetId.wifiPort = (addrInfo->info).ip.port;
887 } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) {
888 std::string wifiIp((addrInfo->info).ip.ip);
889 targetId.wifiIp = wifiIp;
890 targetId.wifiPort = (addrInfo->info).ip.port;
891 } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BR) {
892 std::string brMac((addrInfo->info).br.brMac);
893 targetId.brMac = brMac;
894 } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) {
895 std::string bleMac((addrInfo->info).ble.bleMac);
896 targetId.bleMac = bleMac;
897 } else {
898 LOGI("Unknown connection address type: %{public}d.", addrInfo->type);
899 return ERR_DM_BIND_COMMON_FAILED;
900 }
901 targetId.deviceId = deviceId;
902 return DM_OK;
903 }
904
ClearDiscoveredDevice()905 void SoftbusListener::ClearDiscoveredDevice()
906 {
907 std::lock_guard<std::mutex> lock(g_deviceMapMutex);
908 discoveredDeviceMap.clear();
909 }
910
GetDmRadarHelperObj()911 IDmRadarHelper* SoftbusListener::GetDmRadarHelperObj()
912 {
913 return dmRadarHelper_;
914 }
915
IsDmRadarHelperReady()916 bool SoftbusListener::IsDmRadarHelperReady()
917 {
918 std::lock_guard<std::mutex> lock(g_radarLoadLock);
919 if (isRadarSoLoad_ && (dmRadarHelper_ != nullptr) && (radarHandle_ != nullptr)) {
920 LOGD("IsDmRadarHelperReady alReady.");
921 return true;
922 }
923 radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW);
924 if (radarHandle_ == nullptr) {
925 LOGE("load libdevicemanagerradar so failed.");
926 return false;
927 }
928 dlerror();
929 auto func = (CreateDmRadarFuncPtr)dlsym(radarHandle_, "CreateDmRadarInstance");
930 if (dlerror() != nullptr || func == nullptr) {
931 dlclose(radarHandle_);
932 LOGE("Create object function is not exist.");
933 return false;
934 }
935 LOGI("IsDmRadarHelperReady ready success.");
936 isRadarSoLoad_ = true;
937 dmRadarHelper_ = func();
938 return true;
939 }
940
CloseDmRadarHelperObj(std::string name)941 bool SoftbusListener::CloseDmRadarHelperObj(std::string name)
942 {
943 (void)name;
944 LOGI("SoftbusListener::CloseDmRadarHelperObj start.");
945 std::lock_guard<std::mutex> lock(g_radarLoadLock);
946 if (!isRadarSoLoad_ && (dmRadarHelper_ == nullptr) && (radarHandle_ == nullptr)) {
947 return true;
948 }
949
950 int32_t ret = dlclose(radarHandle_);
951 if (ret != 0) {
952 LOGE("close libdevicemanagerradar failed ret = %{public}d.", ret);
953 return false;
954 }
955 isRadarSoLoad_ = false;
956 dmRadarHelper_ = nullptr;
957 radarHandle_ = nullptr;
958 LOGI("close libdevicemanagerradar so success.");
959 return true;
960 }
961
CacheDeviceInfo(const std::string deviceId,std::shared_ptr<DeviceInfo> infoPtr)962 void SoftbusListener::CacheDeviceInfo(const std::string deviceId, std::shared_ptr<DeviceInfo> infoPtr)
963 {
964 if (deviceId.empty()) {
965 return;
966 }
967 if (infoPtr->addrNum <= 0) {
968 LOGE("CacheDeviceInfo failed, infoPtr->addr is empty.");
969 return;
970 }
971 ConnectionAddrType addrType;
972 const ConnectionAddr *addrInfo = &(infoPtr->addr)[0];
973 if (addrInfo == nullptr) {
974 LOGE("CacheDeviceInfo failed, connection address of discovered device is nullptr.");
975 return;
976 }
977 addrType = addrInfo->type;
978 std::vector<std::pair<ConnectionAddrType, std::shared_ptr<DeviceInfo>>> deviceVec;
979 auto iter = discoveredDeviceMap.find(deviceId);
980 if (iter != discoveredDeviceMap.end()) {
981 deviceVec = iter->second;
982 for (auto it = deviceVec.begin(); it != deviceVec.end();) {
983 if (it->first == addrType) {
984 it = deviceVec.erase(it);
985 continue;
986 } else {
987 it++;
988 }
989 }
990 discoveredDeviceMap.erase(deviceId);
991 }
992 deviceVec.push_back(std::pair<ConnectionAddrType, std::shared_ptr<DeviceInfo>>(addrType, infoPtr));
993 discoveredDeviceMap.insert(std::pair<std::string,
994 std::vector<std::pair<ConnectionAddrType, std::shared_ptr<DeviceInfo>>>>(deviceId, deviceVec));
995 }
996
GetIPAddrTypeFromCache(const std::string & deviceId,const std::string & ip,ConnectionAddrType & addrType)997 int32_t SoftbusListener::GetIPAddrTypeFromCache(const std::string &deviceId, const std::string &ip,
998 ConnectionAddrType &addrType)
999 {
1000 std::lock_guard<std::mutex> lock(g_deviceMapMutex);
1001 auto iter = discoveredDeviceMap.find(deviceId);
1002 if (iter == discoveredDeviceMap.end()) {
1003 LOGE("GetIPAddrTypeFromCache failed, cannot found device in cached discovered map.");
1004 return ERR_DM_BIND_INPUT_PARA_INVALID;
1005 }
1006 auto deviceVectorIter = iter->second;
1007 if (deviceVectorIter.size() == 0) {
1008 LOGE("GetTargetInfoFromCache failed, cannot found deviceVectorIter in cached discovered map.");
1009 return ERR_DM_BIND_INPUT_PARA_INVALID;
1010 }
1011 for (auto it = deviceVectorIter.begin(); it != deviceVectorIter.end(); ++it) {
1012 const ConnectionAddr *addrInfo = &((it->second)->addr)[0];
1013 if (addrInfo == nullptr) {
1014 continue;
1015 }
1016 if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH ||
1017 addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) {
1018 std::string cacheIp((addrInfo->info).ip.ip);
1019 if (cacheIp == ip) {
1020 addrType = addrInfo->type;
1021 return DM_OK;
1022 }
1023 }
1024 }
1025 return ERR_DM_BIND_INPUT_PARA_INVALID;
1026 }
1027
SetHostPkgName(const std::string hostName)1028 void SoftbusListener::SetHostPkgName(const std::string hostName)
1029 {
1030 hostName_ = hostName;
1031 LOGI("SetHostPkgName::hostName_ :%s.", hostName_.c_str());
1032 }
1033
GetHostPkgName()1034 std::string SoftbusListener::GetHostPkgName()
1035 {
1036 LOGI("GetHostPkgName::hostName_ :%s.", hostName_.c_str());
1037 return hostName_;
1038 }
1039
GetSoftbusRefreshCb()1040 IRefreshCallback &SoftbusListener::GetSoftbusRefreshCb()
1041 {
1042 return softbusRefreshCallback_;
1043 }
1044
GetDeviceScreenStatus(const char * networkId,int32_t & screenStatus)1045 int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus)
1046 {
1047 int32_t devScreenStatus = -1;
1048 int32_t ret = GetNodeKeyInfo(DM_PKG_NAME, networkId, NodeDeviceInfoKey::NODE_KEY_DEVICE_SCREEN_STATUS,
1049 reinterpret_cast<uint8_t *>(&devScreenStatus), LNN_COMMON_LEN);
1050 if (ret != DM_OK) {
1051 LOGE("[SOFTBUS]GetNodeKeyInfo screenStatus failed.");
1052 return ret;
1053 }
1054 screenStatus = devScreenStatus;
1055 LOGI("GetDeviceScreenStatus screenStatus: %{public}d.", devScreenStatus);
1056 return DM_OK;
1057 }
1058 } // namespace DistributedHardware
1059 } // namespace OHOS