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