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