• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 #include "messenger_device_socket_manager.h"
16 
17 #include <pthread.h>
18 #include <stdlib.h>
19 
20 #include "securec.h"
21 #include "socket.h"
22 
23 #include "messenger_device_status_manager.h"
24 #include "messenger_utils.h"
25 #include "utils_dslm_list.h"
26 #include "utils_log.h"
27 #include "utils_mem.h"
28 #include "utils_mutex.h"
29 #include "utils_timer.h"
30 
31 #define MSG_BUFF_MAX_LENGTH (81920 * 4)
32 #define PKG_NAME_LEN 128
33 #define SOCKET_NAME_LEN 128
34 #define WAITING_TIMEOUT_LEN 15000
35 
36 typedef struct DeviceSocketManager {
37     ListHead pendingSendList;
38     ListHead serverSocketList;
39     ListHead clientSocketList;
40     DeviceMessageReceiver messageReceiver;
41     MessageSendResultNotifier sendResultNotifier;
42     const char *pkgName;
43     const char *primarySockName;
44     const char *secondarySockName;
45     int32_t primarySocket;
46     int32_t secondarySocket;
47     WorkQueue *queue;
48     Mutex mutex;
49 } DeviceSocketManager;
50 
51 typedef struct QueueMsgData {
52     DeviceIdentify srcIdentity;
53     uint32_t msgLen;
54     uint8_t msgData[1];
55 } QueueMsgData;
56 
57 typedef struct PendingMsgData {
58     ListNode link;
59     uint32_t transNo;
60     DeviceIdentify destIdentity;
61     uint32_t msgLen;
62     uint8_t msgData[1];
63 } PendingMsgData;
64 
65 typedef struct SocketNodeInfo {
66     ListNode link;
67     int32_t socket;
68     uint32_t maskId;
69     DeviceIdentify identity;
70     TimerHandle timeHandle;
71 } SocketNodeInfo;
72 
GetDeviceSocketManagerInstance(void)73 static DeviceSocketManager *GetDeviceSocketManagerInstance(void)
74 {
75     static DeviceSocketManager manager = {
76         .pendingSendList = INIT_LIST(manager.pendingSendList),
77         .serverSocketList = INIT_LIST(manager.serverSocketList),
78         .clientSocketList = INIT_LIST(manager.clientSocketList),
79         .messageReceiver = NULL,
80         .sendResultNotifier = NULL,
81         .queue = NULL,
82         .mutex = INITED_MUTEX,
83         .pkgName = NULL,
84         .primarySockName = NULL,
85         .secondarySockName = NULL,
86         .primarySocket = 0,
87         .secondarySocket = 0,
88     };
89     return &manager;
90 }
91 
ProcessSocketMessageReceived(const uint8_t * data,uint32_t len)92 static void ProcessSocketMessageReceived(const uint8_t *data, uint32_t len)
93 {
94     if (data == NULL || len == 0) {
95         return;
96     }
97     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
98 
99     QueueMsgData *queueData = (QueueMsgData *)data;
100     if (queueData->msgLen + sizeof(QueueMsgData) != len) {
101         SECURITY_LOG_ERROR("invalid input");
102         FREE(queueData);
103         return;
104     }
105 
106     DeviceMessageReceiver messageReceiver = instance->messageReceiver;
107     if (messageReceiver == NULL) {
108         SECURITY_LOG_ERROR("messageReceiver is null");
109         FREE(queueData);
110         return;
111     }
112     messageReceiver(&queueData->srcIdentity, queueData->msgData, queueData->msgLen);
113     FREE(queueData);
114 }
115 
OnSocketMessageReceived(const DeviceIdentify * devId,const uint8_t * msg,uint32_t msgLen)116 static void OnSocketMessageReceived(const DeviceIdentify *devId, const uint8_t *msg, uint32_t msgLen)
117 {
118     if (devId == NULL || msg == NULL) {
119         return;
120     }
121     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
122 
123     WorkQueue *queue = instance->queue;
124     if (queue == NULL) {
125         SECURITY_LOG_ERROR("queue is null");
126         return;
127     }
128     DeviceMessageReceiver messageReceiver = instance->messageReceiver;
129     if (messageReceiver == NULL) {
130         SECURITY_LOG_ERROR("messageReceiver is null");
131         return;
132     }
133     uint32_t queueDataLen = sizeof(QueueMsgData) + msgLen;
134     QueueMsgData *queueData = MALLOC(queueDataLen);
135     if (queueData == NULL) {
136         SECURITY_LOG_ERROR("malloc result null");
137         return;
138     }
139     uint32_t ret = (uint32_t)memcpy_s(&queueData->srcIdentity, sizeof(DeviceIdentify), devId, sizeof(DeviceIdentify));
140     if (ret != EOK) {
141         SECURITY_LOG_ERROR("memcpy failed");
142         FREE(queueData);
143         return;
144     }
145     ret = (uint32_t)memcpy_s(queueData->msgData, msgLen, msg, msgLen);
146     if (ret != EOK) {
147         SECURITY_LOG_ERROR("memcpy failed");
148         FREE(queueData);
149         return;
150     }
151     queueData->msgLen = msgLen;
152     ret = QueueWork(queue, ProcessSocketMessageReceived, (uint8_t *)queueData, queueDataLen);
153     if (ret != WORK_QUEUE_OK) {
154         SECURITY_LOG_ERROR("QueueWork failed, ret is %{public}u", ret);
155         FREE(queueData);
156         return;
157     }
158 }
159 
RemoveSocketNode(int32_t socket,ShutdownReason reason,bool isServer)160 static void RemoveSocketNode(int32_t socket, ShutdownReason reason, bool isServer)
161 {
162     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
163     ListHead *socketList = isServer ? &instance->serverSocketList : &instance->clientSocketList;
164 
165     LockMutex(&instance->mutex);
166     ListNode *node = NULL;
167     ListNode *temp = NULL;
168     FOREACH_LIST_NODE_SAFE (node, socketList, temp) {
169         SocketNodeInfo *info = LIST_ENTRY(node, SocketNodeInfo, link);
170         if (info->socket == socket) {
171             SECURITY_LOG_INFO("Shutdown reason is %{public}u, device is %{public}x", reason, info->maskId);
172             RemoveListNode(node);
173             FREE(info);
174         }
175     }
176     UnlockMutex(&instance->mutex);
177 }
178 
ServerOnShutdown(int32_t socket,ShutdownReason reason)179 static void ServerOnShutdown(int32_t socket, ShutdownReason reason)
180 {
181     if (socket == 0) {
182         return;
183     }
184     RemoveSocketNode(socket, reason, true);
185 }
186 
ClientOnShutdown(int32_t socket,ShutdownReason reason)187 static void ClientOnShutdown(int32_t socket, ShutdownReason reason)
188 {
189     if (socket == 0) {
190         return;
191     }
192     RemoveSocketNode(socket, reason, false);
193 }
194 
TimerProcessWaitingTimeOut(const void * context)195 static void TimerProcessWaitingTimeOut(const void *context)
196 {
197     if (context == NULL) {
198         return;
199     }
200     uint64_t input;
201     if (memcpy_s(&input, sizeof(input), &context, sizeof(context)) != EOK) {
202         SECURITY_LOG_ERROR("memcpy input error");
203         return;
204     }
205     uint32_t socket = (uint32_t)input;
206 
207     Shutdown(socket);
208     ShutdownReason reason = SHUTDOWN_REASON_LOCAL;
209     ClientOnShutdown(socket, reason);
210     SECURITY_LOG_INFO("SocketClosed, socket is %{public}d", socket);
211 }
212 
CreateOrRestartSocketCloseTimer(int32_t socket)213 static void CreateOrRestartSocketCloseTimer(int32_t socket)
214 {
215     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
216 
217     ListNode *node = NULL;
218     SocketNodeInfo *socketInfo = NULL;
219     FOREACH_LIST_NODE (node, &instance->clientSocketList) {
220         SocketNodeInfo *curr = LIST_ENTRY(node, SocketNodeInfo, link);
221         if (curr->socket == socket) {
222             socketInfo = curr;
223             break;
224         }
225     }
226 
227     if (socketInfo == NULL) {
228         return;
229     }
230 
231     if (socketInfo->timeHandle != 0) {
232         DslmUtilsStopTimerTask(socketInfo->timeHandle);
233     }
234     SECURITY_LOG_INFO("SocketTimerWaiting, socket is %{public}d", socket);
235     socketInfo->timeHandle =
236         DslmUtilsStartOnceTimerTask(WAITING_TIMEOUT_LEN, TimerProcessWaitingTimeOut, (const void *)(uint64_t)socket);
237 }
238 
CreateOrRestartSocketCloseTimerWithLock(int32_t socket)239 static void CreateOrRestartSocketCloseTimerWithLock(int32_t socket)
240 {
241     DeviceSocketManager *inst = GetDeviceSocketManagerInstance();
242 
243     LockMutex(&inst->mutex);
244     CreateOrRestartSocketCloseTimer(socket);
245     UnlockMutex(&inst->mutex);
246 }
247 
GetIdentityBySocketId(int32_t socket,bool isServer,DeviceIdentify * identity)248 static bool GetIdentityBySocketId(int32_t socket, bool isServer, DeviceIdentify *identity)
249 {
250     if (identity == NULL) {
251         return false;
252     }
253 
254     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
255 
256     bool find = false;
257     LockMutex(&instance->mutex);
258     ListNode *node = NULL;
259     SocketNodeInfo *socketInfo;
260     ListHead *socketList = isServer ? &instance->serverSocketList : &instance->clientSocketList;
261 
262     FOREACH_LIST_NODE (node, socketList) {
263         socketInfo = LIST_ENTRY(node, SocketNodeInfo, link);
264         if (socketInfo->socket == socket) {
265             *identity = socketInfo->identity;
266             find = true;
267             break;
268         }
269     }
270     UnlockMutex(&instance->mutex);
271 
272     return find;
273 }
274 
GetIdentityByServerSocket(int32_t socket,DeviceIdentify * identity)275 static bool GetIdentityByServerSocket(int32_t socket, DeviceIdentify *identity)
276 {
277     return GetIdentityBySocketId(socket, true, identity);
278 }
279 
GetIdentityByClientSocket(int32_t socket,DeviceIdentify * identity)280 static bool GetIdentityByClientSocket(int32_t socket, DeviceIdentify *identity)
281 {
282     return GetIdentityBySocketId(socket, false, identity);
283 }
284 
CreateSocketNodeInfo(int32_t socket,const DeviceIdentify * identity)285 static SocketNodeInfo *CreateSocketNodeInfo(int32_t socket, const DeviceIdentify *identity)
286 {
287     if (identity == NULL) {
288         SECURITY_LOG_ERROR("Create socket node info invalid params");
289         return NULL;
290     }
291 
292     uint32_t maskId = MaskDeviceIdentity((const char *)identity->identity, DEVICE_ID_MAX_LEN);
293 
294     SocketNodeInfo *socketInfo = MALLOC(sizeof(SocketNodeInfo));
295     if (socketInfo == NULL) {
296         SECURITY_LOG_ERROR("malloc failed, socketInfo is null");
297         return NULL;
298     }
299     socketInfo->socket = socket;
300     socketInfo->maskId = maskId;
301     socketInfo->timeHandle = 0;
302     socketInfo->identity = *identity;
303     SECURITY_LOG_INFO("Binding device is %{public}x, socket is %{public}d", maskId, socket);
304 
305     return socketInfo;
306 }
307 
ProcessBindDevice(int socket,const DeviceIdentify * devId,bool isServer)308 static void ProcessBindDevice(int socket, const DeviceIdentify *devId, bool isServer)
309 {
310     if (devId == NULL) {
311         SECURITY_LOG_ERROR("client on bind invalid params");
312         return;
313     }
314     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
315 
316     SocketNodeInfo *socketInfo = CreateSocketNodeInfo(socket, devId);
317     if (socketInfo == NULL) {
318         return;
319     }
320 
321     ListHead *socketList = isServer ? &instance->serverSocketList : &instance->clientSocketList;
322 
323     LockMutex(&instance->mutex);
324     AddListNodeBefore(&socketInfo->link, socketList);
325 
326     if (!isServer) {
327         ListNode *node = NULL;
328         ListNode *temp = NULL;
329         FOREACH_LIST_NODE_SAFE (node, &instance->pendingSendList, temp) {
330             PendingMsgData *msgData = LIST_ENTRY(node, PendingMsgData, link);
331             if (!IsSameDevice(&msgData->destIdentity, devId)) {
332                 continue;
333             }
334             RemoveListNode(node);
335 
336             int sent = SendBytes(socket, msgData->msgData, msgData->msgLen);
337             if (sent != 0) {
338                 SECURITY_LOG_ERROR("SendBytes error code = %{public}d", sent);
339             }
340             CreateOrRestartSocketCloseTimer(socket);
341             FREE(msgData);
342         }
343     }
344 
345     UnlockMutex(&instance->mutex);
346     return;
347 }
348 
ServerOnBind(int32_t socket,PeerSocketInfo info)349 static void ServerOnBind(int32_t socket, PeerSocketInfo info)
350 {
351     DeviceIdentify identity = {DEVICE_ID_MAX_LEN, {0}};
352     if (!MessengerGetDeviceIdentifyByNetworkId(info.networkId, &identity)) {
353         SECURITY_LOG_ERROR("MessengerGetDeviceIdentifyByNetworkId failed");
354         return;
355     }
356     ProcessBindDevice(socket, &identity, true);
357 }
358 
ClientOnBind(int socket,const DeviceIdentify * devId)359 static void ClientOnBind(int socket, const DeviceIdentify *devId)
360 {
361     ProcessBindDevice(socket, devId, false);
362 }
363 
ServerOnBytes(int32_t socket,const void * data,unsigned int dataLen)364 static void ServerOnBytes(int32_t socket, const void *data, unsigned int dataLen)
365 {
366     if (data == NULL) {
367         SECURITY_LOG_ERROR("Server on bytes invalid params");
368         return;
369     }
370 
371     SECURITY_LOG_INFO("ServerOnBytes, socket is %{public}d", socket);
372     DeviceIdentify identity = {DEVICE_ID_MAX_LEN, {0}};
373     if (GetIdentityByServerSocket(socket, &identity) == false) {
374         SECURITY_LOG_ERROR("Get identity by server list failed");
375         return;
376     }
377 
378     OnSocketMessageReceived(&identity, (const uint8_t *)data, (uint32_t)dataLen);
379 }
380 
ClientOnBytes(int32_t socket,const void * data,unsigned int dataLen)381 static void ClientOnBytes(int32_t socket, const void *data, unsigned int dataLen)
382 {
383     if (data == NULL) {
384         SECURITY_LOG_ERROR("empty data");
385         return;
386     }
387 
388     SECURITY_LOG_INFO("ClientOnBytes, socket is %{public}d", socket);
389     DeviceIdentify identity = {DEVICE_ID_MAX_LEN, {0}};
390     if (GetIdentityByClientSocket(socket, &identity) == false) {
391         SECURITY_LOG_ERROR("Get identity by server list failed");
392         return;
393     }
394 
395     OnSocketMessageReceived(&identity, (const uint8_t *)data, (uint32_t)dataLen);
396 }
397 
ProcessCreateServer(const char * session,const char * pkg,int32_t * socketId)398 static int32_t ProcessCreateServer(const char *session, const char *pkg, int32_t *socketId)
399 {
400     if (session == NULL || pkg == NULL || socketId == NULL) {
401         SECURITY_LOG_ERROR("invalid params create server");
402         return -1;
403     }
404 
405     char sessionName[SOCKET_NAME_LEN + 1] = {0};
406     char pkgName[PKG_NAME_LEN + 1] = {0};
407     int32_t ret = memcpy_s(sessionName, SOCKET_NAME_LEN, session, SOCKET_NAME_LEN);
408     if (ret != EOK) {
409         SECURITY_LOG_ERROR("memcpy sessionName failed");
410         return ret;
411     }
412     ret = memcpy_s(pkgName, PKG_NAME_LEN, pkg, PKG_NAME_LEN);
413     if (ret != EOK) {
414         SECURITY_LOG_ERROR("memcpy pkgName failed");
415         return ret;
416     }
417     static QosTV serverQos[] = {
418         {.qos = QOS_TYPE_MIN_BW, .value = 8 * 1024},
419         {.qos = QOS_TYPE_MAX_LATENCY, .value = 10000},
420         {.qos = QOS_TYPE_MIN_LATENCY, .value = 2000},
421     };
422     static ISocketListener serverListener = {
423         .OnBind = ServerOnBind,
424         .OnShutdown = ServerOnShutdown,
425         .OnBytes = ServerOnBytes,
426     };
427 
428     SocketInfo socketInfo = {
429         .name = sessionName,
430         .pkgName = pkgName,
431         .dataType = DATA_TYPE_BYTES,
432     };
433 
434     int32_t socket = Socket(socketInfo);
435     if (socket <= 0) {
436         SECURITY_LOG_ERROR("Socket failed");
437         return socket;
438     }
439     ret = Listen(socket, serverQos, sizeof(serverQos) / sizeof(QosTV), &serverListener);
440     SECURITY_LOG_INFO("Listen %{public}s with socket %{public}d ret is %{public}d", sessionName, socket, ret);
441     if (ret != 0) {
442         Shutdown(socket);
443         return ret;
444     }
445 
446     *socketId = socket;
447     return 0;
448 }
449 
CreateServer(DeviceSocketManager * inst)450 static bool CreateServer(DeviceSocketManager *inst)
451 {
452     if (inst == NULL) {
453         SECURITY_LOG_ERROR("Get Device Socket Manager Instance failed");
454         return false;
455     }
456 
457     int32_t socket = 0;
458     if (ProcessCreateServer(inst->primarySockName, inst->pkgName, &socket) == 0) {
459         inst->primarySocket = socket;
460     }
461     if (ProcessCreateServer(inst->secondarySockName, inst->pkgName, &socket) == 0) {
462         inst->secondarySocket = socket;
463     }
464 
465     if (inst->primarySocket == 0 && inst->secondarySocket == 0) {
466         return false;
467     }
468 
469     return true;
470 }
471 
InitDeviceSocketManager(WorkQueue * queue,const MessengerConfig * config)472 bool InitDeviceSocketManager(WorkQueue *queue, const MessengerConfig *config)
473 {
474     if ((queue == NULL) || (config == NULL)) {
475         return false;
476     }
477     DeviceSocketManager *inst = GetDeviceSocketManagerInstance();
478 
479     inst->primarySockName = config->primarySockName;
480     inst->secondarySockName = config->secondarySockName;
481     inst->pkgName = config->pkgName;
482     inst->messageReceiver = config->messageReceiver;
483     inst->sendResultNotifier = config->sendResultNotifier;
484     inst->queue = queue;
485 
486     return CreateServer(inst);
487 }
488 
DeInitDeviceSocketManager(void)489 bool DeInitDeviceSocketManager(void)
490 {
491     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
492 
493     Shutdown(instance->primarySocket);
494     Shutdown(instance->secondarySocket);
495 
496     LockMutex(&instance->mutex);
497     instance->primarySockName = NULL;
498     instance->secondarySockName = NULL;
499     instance->pkgName = NULL;
500     instance->messageReceiver = NULL;
501     instance->sendResultNotifier = NULL;
502     instance->queue = NULL;
503     instance->primarySocket = 0;
504     instance->secondarySocket = 0;
505 
506     ListNode *node = NULL;
507     ListNode *temp = NULL;
508     FOREACH_LIST_NODE_SAFE (node, &instance->pendingSendList, temp) {
509         PendingMsgData *msgData = LIST_ENTRY(node, PendingMsgData, link);
510         RemoveListNode(node);
511         FREE(msgData);
512     }
513 
514     node = NULL;
515     temp = NULL;
516     FOREACH_LIST_NODE_SAFE (node, &instance->serverSocketList, temp) {
517         SocketNodeInfo *serverInfo = LIST_ENTRY(node, SocketNodeInfo, link);
518         RemoveListNode(node);
519         FREE(serverInfo);
520     }
521 
522     node = NULL;
523     temp = NULL;
524     FOREACH_LIST_NODE_SAFE (node, &instance->clientSocketList, temp) {
525         SocketNodeInfo *clientInfo = LIST_ENTRY(node, SocketNodeInfo, link);
526         RemoveListNode(node);
527         FREE(clientInfo);
528     }
529 
530     DestroyWorkQueue(instance->queue);
531     UnlockMutex(&instance->mutex);
532 
533     return true;
534 }
535 
GetSocketBySocketList(const DeviceIdentify * devId,bool isServer,int32_t * socket)536 static bool GetSocketBySocketList(const DeviceIdentify *devId, bool isServer, int32_t *socket)
537 {
538     if (devId == NULL || socket == NULL) {
539         return false;
540     }
541 
542     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
543     ListHead *socketList = isServer ? &instance->serverSocketList : &instance->clientSocketList;
544 
545     bool find = false;
546     LockMutex(&instance->mutex);
547     ListNode *node = NULL;
548     FOREACH_LIST_NODE (node, socketList) {
549         SocketNodeInfo *socketInfo = LIST_ENTRY(node, SocketNodeInfo, link);
550         if (IsSameDevice(&socketInfo->identity, devId)) {
551             *socket = socketInfo->socket;
552             find = true;
553             break;
554         }
555     }
556     UnlockMutex(&instance->mutex);
557 
558     return find;
559 }
560 
GetSocketByClientSocketList(const DeviceIdentify * devId,int32_t * socket)561 static bool GetSocketByClientSocketList(const DeviceIdentify *devId, int32_t *socket)
562 {
563     return GetSocketBySocketList(devId, false, socket);
564 }
565 
PushMsgDataToPendingList(uint32_t transNo,const DeviceIdentify * devId,const uint8_t * msg,uint32_t msgLen)566 static void PushMsgDataToPendingList(uint32_t transNo, const DeviceIdentify *devId, const uint8_t *msg, uint32_t msgLen)
567 {
568     if (devId == NULL || msg == NULL) {
569         SECURITY_LOG_ERROR("Push msg data to pending list invalid params");
570         return;
571     }
572     DeviceSocketManager *instance = GetDeviceSocketManagerInstance();
573 
574     PendingMsgData *data = MALLOC(sizeof(PendingMsgData) + msgLen);
575     if (data == NULL) {
576         SECURITY_LOG_ERROR("MALLOC data failed");
577         return;
578     }
579     data->transNo = transNo;
580     data->msgLen = msgLen;
581     int32_t ret = memcpy_s(&data->destIdentity, sizeof(DeviceIdentify), devId, sizeof(DeviceIdentify));
582     if (ret != EOK) {
583         SECURITY_LOG_ERROR("memcpy failed");
584         FREE(data);
585         return;
586     }
587     ret = memcpy_s(data->msgData, msgLen, msg, msgLen);
588     if (ret != EOK) {
589         SECURITY_LOG_ERROR("memcpy failed");
590         FREE(data);
591         return;
592     }
593 
594     LockMutex(&instance->mutex);
595     AddListNodeBefore(&data->link, &instance->pendingSendList);
596     UnlockMutex(&instance->mutex);
597 }
598 
ClientOnFakeBind(int32_t socket,PeerSocketInfo info)599 static void ClientOnFakeBind(int32_t socket, PeerSocketInfo info)
600 {
601     SECURITY_LOG_INFO("Start FakeBind");
602 }
603 
BindSync(int32_t socket,const DeviceIdentify * devId)604 static bool BindSync(int32_t socket, const DeviceIdentify *devId)
605 {
606     if (devId == NULL) {
607         SECURITY_LOG_ERROR("Bind sync invalid params");
608         return false;
609     }
610     static QosTV clientQos[] = {
611         {.qos = QOS_TYPE_MIN_BW, .value = 8 * 1024},
612         {.qos = QOS_TYPE_MAX_LATENCY, .value = 10000},
613         {.qos = QOS_TYPE_MIN_LATENCY, .value = 2000},
614         {.qos = QOS_TYPE_MAX_IDLE_TIMEOUT, .value = 30000},
615     };
616     static ISocketListener clientListener = {
617         .OnBind = ClientOnFakeBind,
618         .OnShutdown = ClientOnShutdown,
619         .OnBytes = ClientOnBytes,
620     };
621     int32_t ret = Bind(socket, clientQos, sizeof(clientQos) / sizeof(QosTV), &clientListener);
622     SECURITY_LOG_INFO("Bind socket %{public}d ret is %{public}d", socket, ret);
623     if (ret == 0) {
624         ClientOnBind(socket, devId);
625         return true;
626     }
627     Shutdown(socket);
628     return false;
629 }
630 
PrepareBindSocket(const char * socketName,DeviceIdentify * devId,int32_t * socketId)631 static int32_t PrepareBindSocket(const char *socketName, DeviceIdentify *devId, int32_t *socketId)
632 {
633     if (socketName == NULL || devId == NULL || socketId == NULL) {
634         SECURITY_LOG_ERROR("invalid params bind socket");
635         return -1;
636     }
637 
638     DeviceSocketManager *inst = GetDeviceSocketManagerInstance();
639     char NetworkId[DEVICE_ID_MAX_LEN + 1] = {0};
640     if (!MessengerGetNetworkIdByDeviceIdentify(devId, NetworkId, DEVICE_ID_MAX_LEN + 1)) {
641         SECURITY_LOG_ERROR("Get NetworkId Failed");
642         return -1;
643     }
644     uint32_t maskId = MaskDeviceIdentity((const char *)&devId->identity, DEVICE_ID_MAX_LEN);
645     char name[SOCKET_NAME_LEN + 1] = {0};
646     int32_t ret = memcpy_s(name, SOCKET_NAME_LEN, socketName, SOCKET_NAME_LEN);
647     if (ret != EOK) {
648         SECURITY_LOG_ERROR("memcpy name failed");
649         return ret;
650     }
651     char clientName[SOCKET_NAME_LEN + 1] = {0};
652     ret = snprintf_s(clientName, SOCKET_NAME_LEN, SOCKET_NAME_LEN - 1, "device.security.level.%x", maskId);
653     if (ret < 0) {
654         SECURITY_LOG_ERROR("snprintf failed");
655         return ret;
656     }
657 
658     char pkgName[PKG_NAME_LEN + 1] = {0};
659     ret = memcpy_s(pkgName, PKG_NAME_LEN, inst->pkgName, PKG_NAME_LEN);
660     if (ret != EOK) {
661         SECURITY_LOG_ERROR("memcpy pkgName failed");
662         return ret;
663     }
664 
665     SocketInfo socketInfo = {
666         .name = clientName,
667         .pkgName = pkgName,
668         .peerName = name,
669         .peerNetworkId = NetworkId,
670         .dataType = DATA_TYPE_BYTES,
671     };
672     int32_t socket = Socket(socketInfo);
673     SECURITY_LOG_INFO("clientName is %{public}s to socket %{public}s %{public}d", clientName, socketName, socket);
674     if (socket <= 0) {
675         return -1;
676     }
677     *socketId = socket;
678     return 0;
679 }
680 
BindSyncWithPthread(void * arg)681 void *BindSyncWithPthread(void *arg)
682 {
683     pthread_detach(pthread_self());
684     if (arg == NULL) {
685         SECURITY_LOG_ERROR("Bind sync with pthread invalid params");
686         return NULL;
687     }
688     DeviceSocketManager *inst = GetDeviceSocketManagerInstance();
689     DeviceIdentify *devId = (DeviceIdentify *)arg;
690 
691     DeviceIdentify identity = *devId;
692     FREE(devId);
693 
694     int32_t socket = 0;
695     bool succ = false;
696     if (PrepareBindSocket(inst->primarySockName, &identity, &socket) == 0) {
697         succ = BindSync(socket, &identity);
698     }
699 
700     if (succ) {
701         return NULL;
702     }
703 
704     if (PrepareBindSocket(inst->secondarySockName, &identity, &socket) == 0) {
705         (void)BindSync(socket, &identity);
706     }
707     return NULL;
708 }
709 
BindAsync(const DeviceIdentify * devId)710 static void BindAsync(const DeviceIdentify *devId)
711 {
712     if (devId == NULL) {
713         SECURITY_LOG_ERROR("Bind async invalid params");
714         return;
715     }
716     DeviceIdentify *identity = MALLOC(sizeof(DeviceIdentify));
717     if (identity == NULL) {
718         SECURITY_LOG_ERROR("MALLOC identity failed");
719         return;
720     }
721     *identity = *devId;
722 
723     pthread_t id;
724     pthread_create(&id, NULL, BindSyncWithPthread, identity);
725 }
726 
MessengerSendMsgTo(uint64_t transNo,const DeviceIdentify * devId,const uint8_t * msg,uint32_t msgLen)727 void MessengerSendMsgTo(uint64_t transNo, const DeviceIdentify *devId, const uint8_t *msg, uint32_t msgLen)
728 {
729     if (devId == NULL || msg == NULL || msgLen == 0 || msgLen > MSG_BUFF_MAX_LENGTH) {
730         SECURITY_LOG_ERROR("invalid params");
731         return;
732     }
733 
734     static DeviceIdentify self = {0, {0}};
735     uint32_t devType;
736     MessengerGetSelfDeviceIdentify(&self, &devType);
737 
738     if (IsSameDevice(&self, devId)) {
739         SECURITY_LOG_DEBUG("loopback msg");
740         OnSocketMessageReceived(devId, msg, msgLen);
741         return;
742     }
743 
744     int32_t socket = 0;
745     bool find = GetSocketByClientSocketList(devId, &socket);
746     if (find && socket != 0) {
747         int32_t ret = SendBytes(socket, msg, msgLen);
748         if (ret != 0) {
749             SECURITY_LOG_ERROR("SendBytes error code = %{public}d", ret);
750             return;
751         }
752         CreateOrRestartSocketCloseTimerWithLock(socket);
753         return;
754     }
755 
756     PushMsgDataToPendingList(transNo, devId, msg, msgLen);
757     BindAsync(devId);
758 }
759