1 /*
2 * Copyright (c) 2022 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_adapter.h"
17
18 #include "anonymous.h"
19 #include "bundle_mgr_interface.h"
20 #include "dev_manager.h"
21 #include "dms_handler.h"
22 #include "iservice_registry.h"
23 #include "logger.h"
24 #include "securec.h"
25 #include "session.h"
26 #include "softbus_bus_center.h"
27 #include "system_ability_definition.h"
28
29 namespace OHOS {
30 namespace ObjectStore {
31 constexpr int32_t HEAD_SIZE = 3;
32 constexpr int32_t END_SIZE = 3;
33 constexpr int32_t MIN_SIZE = HEAD_SIZE + END_SIZE + 3;
34 constexpr const char *REPLACE_CHAIN = "***";
35 constexpr const char *DEFAULT_ANONYMOUS = "******";
36 constexpr int32_t SOFTBUS_OK = 0;
37 constexpr int32_t INVALID_SOCKET_ID = 0;
38 constexpr size_t TASK_CAPACITY_MAX = 15;
39 constexpr const char *PKG_NAME = "ohos.objectstore";
40 SoftBusAdapter *AppDataListenerWrap::softBusAdapter_;
41 std::shared_ptr<SoftBusAdapter> SoftBusAdapter::instance_;
42
SoftBusAdapter()43 SoftBusAdapter::SoftBusAdapter()
44 {
45 LOG_INFO("begin");
46 taskQueue_ = std::make_shared<TaskScheduler>(TASK_CAPACITY_MAX, "data_object");
47 AppDataListenerWrap::SetDataHandler(this);
48
49 clientListener_.OnShutdown = AppDataListenerWrap::OnClientShutdown;
50 clientListener_.OnBytes = AppDataListenerWrap::OnClientBytesReceived;
51 clientListener_.OnMessage = AppDataListenerWrap::OnClientBytesReceived;
52
53 serverListener_.OnBind = AppDataListenerWrap::OnServerBind;
54 serverListener_.OnShutdown = AppDataListenerWrap::OnServerShutdown;
55 serverListener_.OnBytes = AppDataListenerWrap::OnServerBytesReceived;
56 serverListener_.OnMessage = AppDataListenerWrap::OnServerBytesReceived;
57 }
58
~SoftBusAdapter()59 SoftBusAdapter::~SoftBusAdapter()
60 {
61 if (taskQueue_ != nullptr) {
62 taskQueue_->Clean();
63 taskQueue_ = nullptr;
64 }
65 dataCaches_.clear();
66 sockets_.clear();
67 }
68
StartWatchDeviceChange(const AppDeviceStatusChangeListener * observer,const PipeInfo & pipeInfo)69 Status SoftBusAdapter::StartWatchDeviceChange(
70 const AppDeviceStatusChangeListener *observer, __attribute__((unused)) const PipeInfo &pipeInfo)
71 {
72 LOG_INFO("begin");
73 if (observer == nullptr) {
74 LOG_WARN("observer is null.");
75 return Status::ERROR;
76 }
77 std::lock_guard<std::mutex> lock(deviceChangeMutex_);
78 auto result = listeners_.insert(observer);
79 if (!result.second) {
80 LOG_WARN("Add listener error.");
81 return Status::ERROR;
82 }
83 LOG_INFO("end");
84 return Status::SUCCESS;
85 }
86
StopWatchDeviceChange(const AppDeviceStatusChangeListener * observer,const PipeInfo & pipeInfo)87 Status SoftBusAdapter::StopWatchDeviceChange(
88 const AppDeviceStatusChangeListener *observer, __attribute__((unused)) const PipeInfo &pipeInfo)
89 {
90 LOG_INFO("begin");
91 if (observer == nullptr) {
92 LOG_WARN("observer is null.");
93 return Status::ERROR;
94 }
95 std::lock_guard<std::mutex> lock(deviceChangeMutex_);
96 auto result = listeners_.erase(observer);
97 if (result <= 0) {
98 return Status::ERROR;
99 }
100 LOG_INFO("end");
101 return Status::SUCCESS;
102 }
103
NotifyAll(const DeviceInfo & deviceInfo,const DeviceChangeType & type)104 void SoftBusAdapter::NotifyAll(const DeviceInfo &deviceInfo, const DeviceChangeType &type)
105 {
106 std::thread th = std::thread([this, deviceInfo, type]() {
107 pthread_setname_np(pthread_self(), "Data_Object_NotifyAll");
108 std::vector<const AppDeviceStatusChangeListener *> listeners;
109 {
110 std::lock_guard<std::mutex> lock(deviceChangeMutex_);
111 for (const auto &listener : listeners_) {
112 listeners.push_back(listener);
113 }
114 }
115 LOG_DEBUG("high");
116 std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(deviceInfo.deviceId);
117 LOG_DEBUG("[Notify] to DB from: %{public}s, type:%{public}d", ToBeAnonymous(uuid).c_str(), type);
118 UpdateRelationship(deviceInfo.deviceId, type);
119 for (const auto &device : listeners) {
120 if (device == nullptr) {
121 continue;
122 }
123 if (device->GetChangeLevelType() == ChangeLevelType::HIGH) {
124 DeviceInfo di = { uuid, deviceInfo.deviceName, deviceInfo.deviceType };
125 device->OnDeviceChanged(di, type);
126 break;
127 }
128 }
129 LOG_DEBUG("low");
130 for (const auto &device : listeners) {
131 if (device == nullptr) {
132 continue;
133 }
134 if (device->GetChangeLevelType() == ChangeLevelType::LOW) {
135 DeviceInfo di = { uuid, deviceInfo.deviceName, deviceInfo.deviceType };
136 device->OnDeviceChanged(di, DeviceChangeType::DEVICE_OFFLINE);
137 device->OnDeviceChanged(di, type);
138 }
139 }
140 LOG_DEBUG("min");
141 for (const auto &device : listeners) {
142 if (device == nullptr) {
143 continue;
144 }
145 if (device->GetChangeLevelType() == ChangeLevelType::MIN) {
146 DeviceInfo di = { uuid, deviceInfo.deviceName, deviceInfo.deviceType };
147 device->OnDeviceChanged(di, type);
148 }
149 }
150 });
151 th.detach();
152 }
153
GetDeviceList() const154 std::vector<DeviceInfo> SoftBusAdapter::GetDeviceList() const
155 {
156 std::vector<DistributedSchedule::EventNotify> events;
157 int32_t res = DistributedSchedule::DmsHandler::GetInstance().GetDSchedEventInfo(
158 DistributedSchedule::DMS_COLLABORATION, events);
159 if (res != ERR_OK) {
160 LOG_ERROR("Get collaboration events failed, error code = %{public}d", res);
161 return {};
162 }
163 DevManager::DetailInfo localDevice = DevManager::GetInstance()->GetLocalDevice();
164 std::set<std::string> remoteDevices;
165 for (const auto &event : events) {
166 if (localDevice.networkId == event.srcNetworkId_) {
167 std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(event.dstNetworkId_);
168 remoteDevices.insert(uuid);
169 } else if (localDevice.networkId == event.dstNetworkId_) {
170 std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(event.srcNetworkId_);
171 remoteDevices.insert(uuid);
172 }
173 LOG_DEBUG("Collaboration evnet, srcNetworkId: %{public}s, dstNetworkId: %{public}s",
174 Anonymous::Change(event.srcNetworkId_).c_str(), Anonymous::Change(event.dstNetworkId_).c_str());
175 }
176 std::vector<DeviceInfo> deviceInfos;
177 for (const auto &deviceId : remoteDevices) {
178 DeviceInfo deviceInfo{ deviceId };
179 deviceInfos.push_back(deviceInfo);
180 }
181 LOG_INFO("Collaboration deivces size:%{public}zu", deviceInfos.size());
182 return deviceInfos;
183 }
184
GetLocalDevice()185 DeviceInfo SoftBusAdapter::GetLocalDevice()
186 {
187 std::lock_guard<std::mutex> lock(localDeviceLock_);
188 if (!localInfo_.deviceId.empty()) {
189 return localInfo_;
190 }
191
192 NodeBasicInfo info;
193 int32_t ret = GetLocalNodeDeviceInfo(PKG_NAME, &info);
194 if (ret != SOFTBUS_OK) {
195 LOG_ERROR("GetLocalNodeDeviceInfo error");
196 return DeviceInfo();
197 }
198 std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(info.networkId));
199 LOG_DEBUG("[LocalDevice] id:%{private}s, name:%{private}s, type:%{private}d", ToBeAnonymous(uuid).c_str(),
200 info.deviceName, info.deviceTypeId);
201 localInfo_ = { uuid, std::string(info.deviceName), std::to_string(info.deviceTypeId) };
202 return localInfo_;
203 }
204
GetLocalBasicInfo() const205 DeviceInfo SoftBusAdapter::GetLocalBasicInfo() const
206 {
207 LOG_DEBUG("begin");
208 NodeBasicInfo info;
209 int32_t ret = GetLocalNodeDeviceInfo(PKG_NAME, &info);
210 if (ret != SOFTBUS_OK) {
211 LOG_ERROR("GetLocalNodeDeviceInfo error");
212 return DeviceInfo();
213 }
214 LOG_DEBUG("[LocalBasicInfo] networkId:%{private}s, name:%{private}s, "
215 "type:%{private}d",
216 ToBeAnonymous(std::string(info.networkId)).c_str(), info.deviceName, info.deviceTypeId);
217 DeviceInfo localInfo = { std::string(info.networkId), std::string(info.deviceName),
218 std::to_string(info.deviceTypeId) };
219 return localInfo;
220 }
221
GetRemoteNodesBasicInfo() const222 std::vector<DeviceInfo> SoftBusAdapter::GetRemoteNodesBasicInfo() const
223 {
224 LOG_DEBUG("begin");
225 std::vector<DeviceInfo> dis;
226 NodeBasicInfo *info = nullptr;
227 int32_t infoNum = 0;
228 dis.clear();
229
230 int32_t ret = GetAllNodeDeviceInfo(PKG_NAME, &info, &infoNum);
231 if (ret != SOFTBUS_OK) {
232 LOG_ERROR("GetAllNodeDeviceInfo error");
233 return dis;
234 }
235 LOG_DEBUG("GetAllNodeDeviceInfo success infoNum=%{public}d", infoNum);
236
237 for (int i = 0; i < infoNum; i++) {
238 dis.push_back(
239 { std::string(info[i].networkId), std::string(info[i].deviceName), std::to_string(info[i].deviceTypeId) });
240 }
241 if (info != nullptr) {
242 FreeNodeInfo(info);
243 }
244 return dis;
245 }
246
UpdateRelationship(const std::string & networkId,const DeviceChangeType & type)247 void SoftBusAdapter::UpdateRelationship(const std::string &networkId, const DeviceChangeType &type)
248 {
249 auto uuid = DevManager::GetInstance()->GetUuidByNodeId(networkId);
250 std::lock_guard<std::mutex> lock(networkMutex_);
251 switch (type) {
252 case DeviceChangeType::DEVICE_OFFLINE: {
253 auto size = this->networkId2Uuid_.erase(networkId);
254 if (size == 0) {
255 LOG_WARN("not found id:%{public}s.", Anonymous::Change(networkId).c_str());
256 }
257 break;
258 }
259 case DeviceChangeType::DEVICE_ONLINE: {
260 std::pair<std::string, std::string> value = { networkId, uuid };
261 auto res = this->networkId2Uuid_.insert(std::move(value));
262 if (!res.second) {
263 LOG_WARN("insert failed.");
264 }
265 break;
266 }
267 default: {
268 LOG_WARN("unknown type.");
269 break;
270 }
271 }
272 }
ToNodeID(const std::string & nodeId) const273 std::string SoftBusAdapter::ToNodeID(const std::string &nodeId) const
274 {
275 {
276 std::lock_guard<std::mutex> lock(networkMutex_);
277 for (auto const &e : networkId2Uuid_) {
278 if (nodeId == e.second) { // id is uuid
279 return e.first;
280 }
281 }
282 }
283 std::vector<DeviceInfo> devices;
284 NodeBasicInfo *info = nullptr;
285 int32_t infoNum = 0;
286 std::string networkId;
287 int32_t ret = GetAllNodeDeviceInfo(PKG_NAME, &info, &infoNum);
288 if (ret == SOFTBUS_OK) {
289 std::lock_guard<std::mutex> lock(networkMutex_);
290 for (int i = 0; i < infoNum; i++) {
291 if (networkId2Uuid_.find(info[i].networkId) != networkId2Uuid_.end()) {
292 continue;
293 }
294 auto uuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(info[i].networkId));
295 networkId2Uuid_.insert({ info[i].networkId, uuid });
296 if (uuid == nodeId) {
297 networkId = info[i].networkId;
298 }
299 }
300 }
301 if (info != nullptr) {
302 FreeNodeInfo(info);
303 }
304 return networkId;
305 }
306
ToBeAnonymous(const std::string & name)307 std::string SoftBusAdapter::ToBeAnonymous(const std::string &name)
308 {
309 if (name.length() <= HEAD_SIZE) {
310 return DEFAULT_ANONYMOUS;
311 }
312
313 if (name.length() < MIN_SIZE) {
314 return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN);
315 }
316
317 return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN + name.substr(name.length() - END_SIZE, END_SIZE));
318 }
319
GetInstance()320 std::shared_ptr<SoftBusAdapter> SoftBusAdapter::GetInstance()
321 {
322 static std::once_flag onceFlag;
323 std::call_once(onceFlag, [&] { instance_ = std::make_shared<SoftBusAdapter>(); });
324 return instance_;
325 }
326
StartWatchDataChange(const AppDataChangeListener * observer,const PipeInfo & pipeInfo)327 Status SoftBusAdapter::StartWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo)
328 {
329 LOG_DEBUG("begin");
330 if (observer == nullptr) {
331 return Status::INVALID_ARGUMENT;
332 }
333 std::lock_guard<std::mutex> lock(dataChangeMutex_);
334 auto it = dataChangeListeners_.find(pipeInfo.pipeId);
335 if (it != dataChangeListeners_.end()) {
336 LOG_WARN("Add listener error or repeated adding.");
337 return Status::ERROR;
338 }
339 LOG_DEBUG("current appid %{public}s", pipeInfo.pipeId.c_str());
340 dataChangeListeners_.insert({ pipeInfo.pipeId, observer });
341 return Status::SUCCESS;
342 }
343
StopWatchDataChange(const AppDataChangeListener * observer,const PipeInfo & pipeInfo)344 Status SoftBusAdapter::StopWatchDataChange(
345 __attribute__((unused)) const AppDataChangeListener *observer, const PipeInfo &pipeInfo)
346 {
347 LOG_DEBUG("begin");
348 std::lock_guard<std::mutex> lock(dataChangeMutex_);
349 if (dataChangeListeners_.erase(pipeInfo.pipeId)) {
350 return Status::SUCCESS;
351 }
352 LOG_WARN("stop data observer error, pipeInfo:%{public}s", pipeInfo.pipeId.c_str());
353 return Status::ERROR;
354 }
355
SendData(const PipeInfo & pipeInfo,const DeviceId & deviceId,const DataInfo & dataInfo,uint32_t totalLength,const MessageInfo & info)356 Status SoftBusAdapter::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo,
357 uint32_t totalLength, const MessageInfo &info)
358 {
359 std::lock_guard<std::mutex> lock(sendDataMutex_);
360 auto result = CacheData(deviceId.deviceId, dataInfo);
361 if (result != Status::SUCCESS) {
362 return result;
363 }
364 int clientSocket = GetSocket(pipeInfo, deviceId);
365 if (clientSocket == INVALID_SOCKET_ID) {
366 return Status::ERROR;
367 }
368 DoSend();
369 return Status::SUCCESS;
370 }
371
CacheData(const std::string & deviceId,const DataInfo & dataInfo)372 Status SoftBusAdapter::CacheData(const std::string &deviceId, const DataInfo &dataInfo)
373 {
374 uint8_t *data = new uint8_t[dataInfo.length];
375 if (data == nullptr) {
376 LOG_ERROR("[SendData] create buffer fail.");
377 return Status::INVALID_ARGUMENT;
378 }
379 if (memcpy_s(data, dataInfo.length, dataInfo.data, dataInfo.length) != EOK) {
380 LOG_ERROR("[SendData] memcpy_s fail.");
381 delete[] data;
382 return Status::INVALID_ARGUMENT;
383 }
384 BytesMsg bytesMsg = { data, dataInfo.length };
385 std::lock_guard<std::mutex> lock(deviceDataLock_);
386 auto deviceIdData = dataCaches_.find(deviceId);
387 if (deviceIdData == dataCaches_.end()) {
388 dataCaches_[deviceId] = { bytesMsg };
389 } else {
390 deviceIdData->second.push_back(bytesMsg);
391 if (deviceIdData->second.size() > VECTOR_SIZE_THRESHOLD) {
392 deviceIdData->second.erase(deviceIdData->second.begin());
393 }
394 }
395 return Status::SUCCESS;
396 }
397
GetSocket(const PipeInfo & pipeInfo,const DeviceId & deviceId)398 int SoftBusAdapter::GetSocket(const PipeInfo &pipeInfo, const DeviceId &deviceId)
399 {
400 std::lock_guard<std::mutex> lock(socketLock_);
401 auto it = sockets_.find(deviceId.deviceId);
402 if (it != sockets_.end()) {
403 return it->second;
404 }
405 int socketId = CreateClientSocket(pipeInfo, deviceId);
406 if (socketId == INVALID_SOCKET_ID) {
407 return INVALID_SOCKET_ID;
408 }
409 sockets_[deviceId.deviceId] = socketId;
410 return socketId;
411 }
412
413 // AppId is used only for socket verification. The created socket name does not contain appId.
GetSocketName(const std::string & socketName)414 std::string SoftBusAdapter::GetSocketName(const std::string &socketName)
415 {
416 std::lock_guard<std::mutex> lock(bundleInfoMutex_);
417 if (isSystemApp_) {
418 return socketName;
419 }
420 if (!appId_.empty()) {
421 return socketName + '-' + appId_;
422 }
423 sptr<ISystemAbilityManager> saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
424 if (saManager == nullptr) {
425 LOG_ERROR("Get system ability manager failed");
426 return socketName;
427 }
428 sptr<IRemoteObject> remoteObject = saManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
429 if (remoteObject == nullptr) {
430 LOG_ERROR("Get system ability failed");
431 return socketName;
432 }
433 sptr<AppExecFwk::IBundleMgr> bundleManager = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
434 if (bundleManager == nullptr) {
435 LOG_ERROR("Get bundle manager failed");
436 return socketName;
437 }
438 AppExecFwk::BundleInfo bundleInfo;
439 auto status = bundleManager->GetBundleInfoForSelf(
440 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) |
441 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO), bundleInfo);
442 if (status != 0) {
443 LOG_ERROR("Get bundle info failed, status: %{public}d", status);
444 return socketName;
445 }
446 if (bundleInfo.applicationInfo.isSystemApp) {
447 isSystemApp_ = true;
448 LOG_INFO("System app does not require appId, bundleName: %{public}s", bundleInfo.name.c_str());
449 return socketName;
450 }
451 if (bundleInfo.appId.empty()) {
452 LOG_ERROR("Get appId empty, bundleName: %{public}s", bundleInfo.name.c_str());
453 return socketName;
454 }
455 appId_ = bundleInfo.appId;
456 return socketName + '-' + appId_;
457 }
458
CreateClientSocket(const PipeInfo & pipeInfo,const DeviceId & deviceId)459 int SoftBusAdapter::CreateClientSocket(const PipeInfo &pipeInfo, const DeviceId &deviceId)
460 {
461 SocketInfo socketInfo;
462 std::string socketNameAndAppId = GetSocketName(pipeInfo.pipeId);
463 socketInfo.name = socketNameAndAppId.data();
464 socketInfo.peerName = const_cast<char *>(pipeInfo.pipeId.c_str());
465 std::string networkId = ToNodeID(deviceId.deviceId);
466 socketInfo.peerNetworkId = networkId.data();
467 socketInfo.pkgName = const_cast<char *>(PKG_NAME);
468 socketInfo.dataType = DATA_TYPE_BYTES;
469 int socketId = Socket(socketInfo);
470 if (socketId <= 0) {
471 LOG_ERROR("Create socket failed, error code: %{public}d, name: %{public}s, networkId: %{public}s", socketId,
472 Anonymous::Change(socketNameAndAppId).c_str(), Anonymous::Change(networkId).c_str());
473 return INVALID_SOCKET_ID;
474 }
475 int32_t res = Bind(socketId, Qos, QOS_COUNT, &clientListener_);
476 if (res != 0) {
477 LOG_ERROR("Bind failed, error code: %{public}d, socket: %{public}d, name: %{public}s, networkId: %{public}s",
478 res, socketId, Anonymous::Change(socketNameAndAppId).c_str(), Anonymous::Change(networkId).c_str());
479 Shutdown(socketId);
480 return INVALID_SOCKET_ID;
481 }
482 return socketId;
483 }
484
DoSend()485 void SoftBusAdapter::DoSend()
486 {
487 auto task([this]() {
488 std::lock_guard<std::mutex> lock(socketLock_);
489 for (auto &it : sockets_) {
490 if (it.second <= INVALID_SOCKET_ID) {
491 continue;
492 }
493 std::lock_guard<std::mutex> lock(deviceDataLock_);
494 auto dataCache = dataCaches_.find(it.first);
495 if (dataCache == dataCaches_.end()) {
496 continue;
497 }
498 for (auto msg = dataCache->second.begin(); msg != dataCache->second.end();) {
499 auto &byteMsg = *msg;
500 int32_t ret = SendBytes(it.second, byteMsg.ptr, byteMsg.size);
501 if (ret != SOFTBUS_OK) {
502 LOG_ERROR("[SendBytes] to %{public}d failed, ret:%{public}d.", it.second, ret);
503 }
504 LOG_DEBUG("[SendBytes] delete msgPtr.");
505 delete[] byteMsg.ptr;
506 msg = dataCache->second.erase(msg);
507 }
508 }
509 });
510 taskQueue_->Execute(std::move(task));
511 }
512
OnClientShutdown(int32_t socket)513 void SoftBusAdapter::OnClientShutdown(int32_t socket)
514 {
515 std::lock_guard<std::mutex> lock(socketLock_);
516 for (auto iter = sockets_.begin(); iter != sockets_.end();) {
517 if (iter->second == socket) {
518 iter = sockets_.erase(iter);
519 } else {
520 iter++;
521 }
522 }
523 }
524
IsSameStartedOnPeer(const struct PipeInfo & pipeInfo,const struct DeviceId & peer)525 bool SoftBusAdapter::IsSameStartedOnPeer(
526 const struct PipeInfo &pipeInfo, __attribute__((unused)) const struct DeviceId &peer)
527 {
528 int socket = GetSocket(pipeInfo, peer);
529 return socket != INVALID_SOCKET_ID;
530 }
531
CreateSessionServerAdapter(const std::string & sessionName)532 int SoftBusAdapter::CreateSessionServerAdapter(const std::string &sessionName)
533 {
534 SocketInfo socketInfo;
535 std::string socketNameAndAppId = GetSocketName(sessionName);
536 socketInfo.name = socketNameAndAppId.data();
537 socketInfo.pkgName = const_cast<char *>(PKG_NAME);
538 socketServer_ = Socket(socketInfo);
539 if (socketServer_ <= 0) {
540 LOG_ERROR("Create socket failed, error code: %{public}d, name: %{public}s", socketServer_,
541 Anonymous::Change(socketNameAndAppId).c_str());
542 return static_cast<int>(Status::ERROR);
543 }
544 int res = Listen(socketServer_, Qos, QOS_COUNT, &serverListener_);
545 if (res != SOFTBUS_OK) {
546 LOG_ERROR("Listen socket failed, error code: %{public}d, socket: %{public}d, name: %{public}s", res,
547 socketServer_, Anonymous::Change(socketNameAndAppId).c_str());
548 return static_cast<int>(Status::ERROR);
549 }
550 return SOFTBUS_OK;
551 }
552
RemoveSessionServerAdapter(const std::string & sessionName) const553 int SoftBusAdapter::RemoveSessionServerAdapter(const std::string &sessionName) const
554 {
555 Shutdown(socketServer_);
556 LOG_INFO("Shutdown server socket: %{public}d", socketServer_);
557 return 0;
558 }
559
NotifyDataListeners(const uint8_t * ptr,const int size,const std::string & deviceId,const PipeInfo & pipeInfo)560 void SoftBusAdapter::NotifyDataListeners(
561 const uint8_t *ptr, const int size, const std::string &deviceId, const PipeInfo &pipeInfo)
562 {
563 std::lock_guard<std::mutex> lock(dataChangeMutex_);
564 auto it = dataChangeListeners_.find(pipeInfo.pipeId);
565 if (it != dataChangeListeners_.end()) {
566 LOG_DEBUG("ready to notify, pipeName:%{public}s, deviceId:%{public}s.", pipeInfo.pipeId.c_str(),
567 ToBeAnonymous(deviceId).c_str());
568 DeviceInfo deviceInfo = { deviceId, "", "" };
569 it->second->OnMessage(deviceInfo, ptr, size, pipeInfo);
570 return;
571 }
572 LOG_WARN("no listener %{public}s.", pipeInfo.pipeId.c_str());
573 }
574
GetPeerSocketInfo(int32_t socket,PeerSocketInfo & info)575 bool SoftBusAdapter::GetPeerSocketInfo(int32_t socket, PeerSocketInfo &info)
576 {
577 auto it = peerSocketInfos_.Find(socket);
578 if (it.first) {
579 info = it.second;
580 return true;
581 }
582 return false;
583 }
584
OnBind(int32_t socket,PeerSocketInfo info)585 void SoftBusAdapter::OnBind(int32_t socket, PeerSocketInfo info)
586 {
587 peerSocketInfos_.Insert(socket, info);
588 }
589
OnServerShutdown(int32_t socket)590 void SoftBusAdapter::OnServerShutdown(int32_t socket)
591 {
592 peerSocketInfos_.Erase(socket);
593 }
594
SetDataHandler(SoftBusAdapter * handler)595 void AppDataListenerWrap::SetDataHandler(SoftBusAdapter *handler)
596 {
597 softBusAdapter_ = handler;
598 }
599
OnClientShutdown(int32_t socket,ShutdownReason reason)600 void AppDataListenerWrap::OnClientShutdown(int32_t socket, ShutdownReason reason)
601 {
602 softBusAdapter_->OnClientShutdown(socket);
603 LOG_INFO("Client socket shutdown, socket: %{public}d, reason: %{public}d", socket, reason);
604 }
605
OnClientBytesReceived(int32_t socket,const void * data,uint32_t dataLen)606 void AppDataListenerWrap::OnClientBytesReceived(int32_t socket, const void *data, uint32_t dataLen) {}
607
OnServerBind(int32_t socket,PeerSocketInfo info)608 void AppDataListenerWrap::OnServerBind(int32_t socket, PeerSocketInfo info)
609 {
610 softBusAdapter_->OnBind(socket, info);
611 LOG_INFO("Server on bind, socket: %{public}d, peer networkId: %{public}s", socket,
612 SoftBusAdapter::ToBeAnonymous(info.networkId).c_str());
613 }
614
OnServerShutdown(int32_t socket,ShutdownReason reason)615 void AppDataListenerWrap::OnServerShutdown(int32_t socket, ShutdownReason reason)
616 {
617 softBusAdapter_->OnServerShutdown(socket);
618 LOG_INFO("Server socket shutdown, socket: %{public}d, reason: %{public}d", socket, reason);
619 }
620
OnServerBytesReceived(int32_t socket,const void * data,uint32_t dataLen)621 void AppDataListenerWrap::OnServerBytesReceived(int32_t socket, const void *data, uint32_t dataLen)
622 {
623 PeerSocketInfo info;
624 if (!softBusAdapter_->GetPeerSocketInfo(socket, info)) {
625 LOG_ERROR("Get peer socket info failed, socket: %{public}d", socket);
626 return;
627 };
628 LOG_DEBUG("Server receive bytes, socket: %{public}d, networkId: %{public}s, dataLen: %{public}u", socket,
629 Anonymous::Change(info.networkId).c_str(), dataLen);
630 std::string peerDevUuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(info.networkId));
631 NotifyDataListeners(reinterpret_cast<const uint8_t *>(data), dataLen, peerDevUuid, { info.name });
632 }
633
NotifyDataListeners(const uint8_t * ptr,const int size,const std::string & deviceId,const PipeInfo & pipeInfo)634 void AppDataListenerWrap::NotifyDataListeners(const uint8_t *ptr, const int size, const std::string &deviceId,
635 const PipeInfo &pipeInfo)
636 {
637 softBusAdapter_->NotifyDataListeners(ptr, size, deviceId, pipeInfo);
638 }
639 } // namespace ObjectStore
640 } // namespace OHOS
641