• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2025 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 "auth_tcp_connection.h"
17 
18 #include <securec.h>
19 
20 #include "auth_channel.h"
21 #include "auth_common.h"
22 #include "auth_log.h"
23 #include "bus_center_manager.h"
24 #include "g_enhance_lnn_func.h"
25 #include "g_enhance_auth_func.h"
26 #include "g_enhance_auth_func_pack.h"
27 #include "softbus_adapter_mem.h"
28 #include "softbus_adapter_socket.h"
29 #include "softbus_base_listener.h"
30 #include "softbus_def.h"
31 #include "softbus_socket.h"
32 #include "softbus_tcp_socket.h"
33 #include "softbus_init_common.h"
34 #include "trans_lane_manager.h"
35 
36 #define MAGIC_NUMBER             0xBABEFACE
37 #define AUTH_PKT_HEAD_LEN        24
38 #define AUTH_SOCKET_MAX_DATA_LEN (64 * 1024)
39 #define TCP_KEEPALIVE_TOS_VAL    180
40 #define RECV_DATA_TIMEOUT        (2 * 1000 * 1000)
41 
42 typedef struct {
43     int32_t keepaliveIdle;
44     int32_t keepaliveIntvl;
45     int32_t keepaliveCount;
46     uint32_t userTimeout;
47 } TcpKeepaliveOption;
48 
49 typedef struct {
50     int32_t module;
51     AuthChannelListener listener;
52 } InnerChannelListener;
53 
54 static InnerChannelListener g_listener[] = {
55     {
56         .module = MODULE_AUTH_CHANNEL,
57         .listener = { NULL, NULL },
58     },
59     {
60         .module = MODULE_AUTH_MSG,
61         .listener = { NULL, NULL },
62     },
63 };
64 
65 static SocketCallback g_callback = { NULL, NULL, NULL };
66 static ListNode g_authTcpConnFdList  = { &g_authTcpConnFdList, &g_authTcpConnFdList };
67 static SoftBusMutex g_authTcpConnFdListLock;
68 
69 static void NotifyChannelDisconnected(int32_t channelId);
70 static void NotifyChannelDataReceived(int32_t channelId, const SocketPktHead *head, const uint8_t *data);
71 static void SetSessionKeyListenerModule(int32_t fd);
RouteBuildServerAuthManager(int32_t cfd,const ConnectOption * clientAddr)72 int32_t __attribute__((weak)) RouteBuildServerAuthManager(int32_t cfd, const ConnectOption *clientAddr)
73 {
74     (void)cfd;
75     (void)clientAddr;
76     return SOFTBUS_OK;
77 }
78 
GetSocketPktSize(uint32_t len)79 static uint32_t GetSocketPktSize(uint32_t len)
80 {
81     return AUTH_PKT_HEAD_LEN + len;
82 }
83 
PackSocketPkt(const SocketPktHead * pktHead,const uint8_t * data,uint8_t * buf,uint32_t size)84 static int32_t PackSocketPkt(const SocketPktHead *pktHead, const uint8_t *data, uint8_t *buf, uint32_t size)
85 {
86     if (size < GetSocketPktSize(pktHead->len)) {
87         AUTH_LOGE(AUTH_CONN, "buffer not enough.");
88         return SOFTBUS_NO_ENOUGH_DATA;
89     }
90     uint32_t offset = 0;
91     *(uint32_t *)buf = SoftBusHtoLl((uint32_t)pktHead->magic);
92     offset += sizeof(uint32_t);
93     *(uint32_t *)(buf + offset) = SoftBusHtoLl((uint32_t)pktHead->module);
94     offset += sizeof(uint32_t);
95     *(uint64_t *)(buf + offset) = SoftBusHtoLll((uint64_t)pktHead->seq);
96     offset += sizeof(uint64_t);
97     *(uint32_t *)(buf + offset) = SoftBusHtoLl((uint32_t)pktHead->flag);
98     offset += sizeof(uint32_t);
99     *(uint32_t *)(buf + offset) = SoftBusHtoLl(pktHead->len);
100     offset += sizeof(uint32_t);
101     if (memcpy_s(buf + offset, size - offset, data, pktHead->len) != EOK) {
102         AUTH_LOGE(AUTH_CONN, "pack fail.");
103         return SOFTBUS_MEM_ERR;
104     }
105     return SOFTBUS_OK;
106 }
107 
UnpackSocketPkt(const uint8_t * data,uint32_t len,SocketPktHead * head)108 static int32_t UnpackSocketPkt(const uint8_t *data, uint32_t len, SocketPktHead *head)
109 {
110     if (len < GetSocketPktSize(0)) {
111         AUTH_LOGE(AUTH_CONN, "head not enough.");
112         return SOFTBUS_NO_ENOUGH_DATA;
113     }
114     uint32_t offset = 0;
115     head->magic = (int32_t)SoftBusLtoHl(*(uint32_t *)data);
116     offset += sizeof(uint32_t);
117     head->module = (int32_t)SoftBusLtoHl(*(uint32_t *)(data + offset));
118     offset += sizeof(uint32_t);
119     head->seq = (int64_t)SoftBusLtoHll(*(uint64_t *)(data + offset));
120     offset += sizeof(uint64_t);
121     head->flag = (int32_t)SoftBusLtoHl(*(uint32_t *)(data + offset));
122     offset += sizeof(uint32_t);
123     head->len = SoftBusLtoHl(*(uint32_t *)(data + offset));
124     return SOFTBUS_OK;
125 }
126 
NotifyConnected(ListenerModule module,int32_t fd,bool isClient)127 static void NotifyConnected(ListenerModule module, int32_t fd, bool isClient)
128 {
129     if (g_callback.onConnected != NULL) {
130         g_callback.onConnected(module, fd, isClient);
131     }
132 }
133 
NotifyDisconnected(ListenerModule module,int32_t fd)134 static void NotifyDisconnected(ListenerModule module, int32_t fd)
135 {
136     if (g_callback.onDisconnected != NULL) {
137         g_callback.onDisconnected(module, fd);
138     }
139     NotifyChannelDisconnected(fd);
140 }
141 
ModuleToDataType(int32_t module)142 static uint32_t ModuleToDataType(int32_t module)
143 {
144     switch (module) {
145         case MODULE_TRUST_ENGINE:
146             return DATA_TYPE_DEVICE_ID;
147         case MODULE_AUTH_SDK:
148             return DATA_TYPE_AUTH;
149         case MODULE_AUTH_CONNECTION:
150             return DATA_TYPE_DEVICE_INFO;
151         case MODULE_AUTH_CANCEL:
152             return DATA_TYPE_CANCEL_AUTH;
153         case MODULE_APPLY_KEY_CONNECTION:
154             return DATA_TYPE_APPLY_KEY_CONNECTION;
155         default:
156             break;
157     }
158     return DATA_TYPE_CONNECTION;
159 }
160 
SessionNotifyDataReceived(ListenerModule module,int32_t fd,uint32_t len,const uint8_t * data)161 static void SessionNotifyDataReceived(ListenerModule module, int32_t fd,
162     uint32_t len, const uint8_t *data)
163 {
164     AuthDataHead head = {0};
165     const uint8_t *body = UnpackAuthData(data, len, &head);
166     if (body == NULL) {
167         AUTH_LOGE(AUTH_CONN, "unpack auth data fail.");
168         return;
169     }
170     if (g_callback.onDataReceived != NULL) {
171         g_callback.onDataReceived(module, fd, &head, body);
172     }
173 }
174 
SessionKeyNotifyDataReceived(ListenerModule module,int32_t fd,uint32_t len,const uint8_t * data)175 static void SessionKeyNotifyDataReceived(ListenerModule module, int32_t fd,
176     uint32_t len, const uint8_t *data)
177 {
178     AuthDataHead head = {0};
179     const uint8_t *body = UnpackAuthData(data, len, &head);
180     if (body == NULL) {
181         AUTH_LOGE(AUTH_CONN, "unpack auth data fail.");
182         return;
183     }
184     if (g_callback.onDataReceived != NULL) {
185         g_callback.onDataReceived(module, fd, &head, body);
186     }
187 }
188 
NotifyDataReceived(ListenerModule module,int32_t fd,const SocketPktHead * pktHead,const uint8_t * data)189 static void NotifyDataReceived(ListenerModule module, int32_t fd,
190     const SocketPktHead *pktHead, const uint8_t *data)
191 {
192     if (pktHead->module == MODULE_AUTH_CHANNEL || pktHead->module == MODULE_AUTH_MSG) {
193         NotifyChannelDataReceived(fd, pktHead, data);
194         return;
195     }
196     if (pktHead->module == MODULE_META_AUTH) {
197         AuthMetaNotifyDataReceivedPacked(fd, pktHead, data);
198         return;
199     }
200     if (pktHead->module == MODULE_SESSION_AUTH) {
201         SessionNotifyDataReceived(module, fd, pktHead->len, data);
202         return;
203     }
204     if (pktHead->module == MODULE_SESSION_KEY_AUTH) {
205         if (module != AUTH_SESSION_KEY) {
206             SetSessionKeyListenerModule(fd);
207         }
208         SessionKeyNotifyDataReceived(module, fd, pktHead->len, data);
209         return;
210     }
211     AuthDataHead head = {
212         .dataType = ModuleToDataType(pktHead->module),
213         .module = pktHead->module,
214         .seq = pktHead->seq,
215         .flag = pktHead->flag,
216         .len = pktHead->len,
217     };
218     if (g_callback.onDataReceived != NULL) {
219         g_callback.onDataReceived(module, fd, &head, data);
220     }
221 }
222 
RecvPacketHead(ListenerModule module,int32_t fd,SocketPktHead * head)223 static int32_t RecvPacketHead(ListenerModule module, int32_t fd, SocketPktHead *head)
224 {
225     uint8_t buf[AUTH_PKT_HEAD_LEN] = { 0 };
226     uint32_t offset = 0;
227     while (offset < AUTH_PKT_HEAD_LEN) {
228         ssize_t recvLen =
229             ConnRecvSocketData(fd, (char *)&buf[offset], (size_t)(sizeof(buf) - offset), RECV_DATA_TIMEOUT);
230         if (recvLen < 0) {
231             AUTH_LOGE(AUTH_CONN, "recv head fail.");
232             return SOFTBUS_INVALID_DATA_HEAD;
233         }
234         offset += (uint32_t)recvLen;
235     }
236     return UnpackSocketPkt(buf, offset, head);
237 }
238 
RecvPacketData(int32_t fd,uint32_t len)239 static uint8_t *RecvPacketData(int32_t fd, uint32_t len)
240 {
241     uint8_t *data = (uint8_t *)SoftBusCalloc(len);
242     if (data == NULL) {
243         AUTH_LOGE(AUTH_CONN, "malloc data buf fail.");
244         return NULL;
245     }
246     uint32_t offset = 0;
247     while (offset < len) {
248         ssize_t recvLen = ConnRecvSocketData(fd, (char *)(data + offset), (size_t)(len - offset), 0);
249         if (recvLen < 0) {
250             AUTH_LOGE(AUTH_CONN, "recv data fail.");
251             SoftBusFree(data);
252             return NULL;
253         }
254         offset += (uint32_t)recvLen;
255     }
256     return data;
257 }
258 
259 typedef struct {
260     ListNode node;
261     ListenerModule module;
262     int32_t fd;
263 } AuthTcpConnInstance;
264 
RequireAuthTcpConnFdListLock(void)265 bool RequireAuthTcpConnFdListLock(void)
266 {
267     if (SoftBusMutexLock(&g_authTcpConnFdListLock) != SOFTBUS_OK) {
268         AUTH_LOGE(AUTH_CONN, "authTcpConnFdList lock fail");
269         return false;
270     }
271     return true;
272 }
273 
ReleaseAuthTcpConnFdListLock(void)274 void ReleaseAuthTcpConnFdListLock(void)
275 {
276     if (SoftBusMutexUnlock(&g_authTcpConnFdListLock) != SOFTBUS_OK) {
277         AUTH_LOGE(AUTH_CONN, "authTcpConnFdList unlock fail");
278     }
279 }
280 
AddAuthTcpConnFdItem(int32_t fd,ListenerModule module)281 static int32_t AddAuthTcpConnFdItem(int32_t fd, ListenerModule module)
282 {
283     if (!RequireAuthTcpConnFdListLock()) {
284         AUTH_LOGE(AUTH_CONN, "RequireAuthTcpConnFdListLock fail");
285         return SOFTBUS_LOCK_ERR;
286     }
287     AuthTcpConnInstance *item = NULL;
288     LIST_FOR_EACH_ENTRY(item, &g_authTcpConnFdList, AuthTcpConnInstance, node) {
289         if (item->fd != fd) {
290             continue;
291         }
292         AUTH_LOGE(AUTH_CONN, "fd already exist.");
293         ReleaseAuthTcpConnFdListLock();
294         return SOFTBUS_OK;
295     }
296 
297     AuthTcpConnInstance *connItem = (AuthTcpConnInstance *)SoftBusCalloc(sizeof(AuthTcpConnInstance));
298     if (connItem == NULL) {
299         AUTH_LOGE(AUTH_CONN, "malloc connItem fail");
300         ReleaseAuthTcpConnFdListLock();
301         return SOFTBUS_MEM_ERR;
302     }
303     connItem->fd = fd;
304     connItem->module = module;
305     ListNodeInsert(&g_authTcpConnFdList, &connItem->node);
306     AUTH_LOGI(AUTH_CONN, "add auth tcp conn fd item. fd=%{public}d", fd);
307     ReleaseAuthTcpConnFdListLock();
308     return SOFTBUS_OK;
309 }
310 
IsExistAuthTcpConnFdItemByConnId(int32_t fd)311 bool IsExistAuthTcpConnFdItemByConnId(int32_t fd)
312 {
313     if (!RequireAuthTcpConnFdListLock()) {
314         AUTH_LOGE(AUTH_CONN, "RequireAuthTcpConnFdListLock fail");
315         return false;
316     }
317     AuthTcpConnInstance *item = NULL;
318     LIST_FOR_EACH_ENTRY(item, &g_authTcpConnFdList, AuthTcpConnInstance, node) {
319         if (item->fd != fd) {
320             continue;
321         }
322         ReleaseAuthTcpConnFdListLock();
323         return true;
324     }
325     AUTH_LOGE(AUTH_CONN, "auth tcp conn fd item is not found. fd=%{public}d", fd);
326     ReleaseAuthTcpConnFdListLock();
327     return false;
328 }
329 
IsExistAuthTcpConnFdItemWithoutLock(int32_t fd)330 bool IsExistAuthTcpConnFdItemWithoutLock(int32_t fd)
331 {
332     AuthTcpConnInstance *item = NULL;
333     LIST_FOR_EACH_ENTRY(item, &g_authTcpConnFdList, AuthTcpConnInstance, node) {
334         if (item->fd != fd) {
335             continue;
336         }
337         return true;
338     }
339     AUTH_LOGE(AUTH_CONN, "auth tcp conn fd item is not found. fd=%{public}d", fd);
340     return false;
341 }
342 
IsExistMetaAuthTcpConnFdItemWithoutLock(int32_t fd)343 bool IsExistMetaAuthTcpConnFdItemWithoutLock(int32_t fd)
344 {
345     AuthTcpConnInstance *item = NULL;
346     LIST_FOR_EACH_ENTRY(item, &g_authTcpConnFdList, AuthTcpConnInstance, node) {
347         if (item->fd != fd || (item->module != AUTH_RAW_P2P_SERVER && item->module != AUTH_RAW_P2P_CLIENT)) {
348             continue;
349         }
350         return true;
351     }
352     AUTH_LOGE(AUTH_CONN, "auth tcp conn fd item is not found. fd=%{public}d", fd);
353     return false;
354 }
355 
DeleteAuthTcpConnFdItemByConnId(int32_t fd)356 void DeleteAuthTcpConnFdItemByConnId(int32_t fd)
357 {
358     if (!RequireAuthTcpConnFdListLock()) {
359         AUTH_LOGE(AUTH_CONN, "RequireAuthTcpConnFdListLock fail");
360         return;
361     }
362     AuthTcpConnInstance *item = NULL;
363     LIST_FOR_EACH_ENTRY(item, &g_authTcpConnFdList, AuthTcpConnInstance, node) {
364         if (item->fd != fd) {
365             continue;
366         }
367         AUTH_LOGI(AUTH_CONN, "delete auth tcp conn fd item. fd=%{public}d", fd);
368         ListDelete(&item->node);
369         SoftBusFree(item);
370         break;
371     }
372     ReleaseAuthTcpConnFdListLock();
373 }
374 
IsNeededFdControl(ListenerModule module)375 static bool IsNeededFdControl(ListenerModule module)
376 {
377     return (module == AUTH || module == AUTH_USB || module == AUTH_RAW_P2P_CLIENT ||
378         module == AUTH_RAW_P2P_SERVER || module == AUTH_SESSION_KEY);
379 }
380 
ProcessSocketOutEvent(ListenerModule module,int32_t fd)381 static int32_t ProcessSocketOutEvent(ListenerModule module, int32_t fd)
382 {
383     AUTH_LOGI(AUTH_CONN, "socket client connect succ: fd=%{public}d.", fd);
384     (void)DelTrigger(module, fd, WRITE_TRIGGER);
385     if (AddTrigger(module, fd, READ_TRIGGER) != SOFTBUS_OK) {
386         AUTH_LOGE(AUTH_CONN, "AddTrigger fail.");
387         goto FAIL;
388     }
389     if (ConnToggleNonBlockMode(fd, true) != SOFTBUS_OK) {
390         AUTH_LOGE(AUTH_CONN, "set none block mode fail.");
391         goto FAIL;
392     }
393     if (IsNeededFdControl(module) && AddAuthTcpConnFdItem(fd, module) != SOFTBUS_OK) {
394         AUTH_LOGE(AUTH_CONN, "insert auth tcp conn fd item fail.");
395         goto FAIL;
396     }
397     NotifyConnected(module, fd, true);
398     return SOFTBUS_OK;
399 
400 FAIL:
401     (void)DelTrigger(module, fd, READ_TRIGGER);
402     ConnShutdownSocket(fd);
403     NotifyDisconnected(module, fd);
404     return SOFTBUS_AUTH_SOCKET_EVENT_INVALID;
405 }
406 
ProcessSocketInEvent(ListenerModule module,int32_t fd)407 static int32_t ProcessSocketInEvent(ListenerModule module, int32_t fd)
408 {
409     AUTH_CHECK_AND_RETURN_RET_LOGE(RequireAuthTcpConnFdListLock(), SOFTBUS_LOCK_ERR, AUTH_CONN,
410         "RequireAuthTcpConnFdListLock fail");
411     if (IsNeededFdControl(module) && !IsExistAuthTcpConnFdItemWithoutLock(fd)) {
412         AUTH_LOGE(AUTH_CONN, "fd=%{public}d not exist, ignore", fd);
413         ReleaseAuthTcpConnFdListLock();
414         return SOFTBUS_INVALID_PARAM;
415     }
416     SocketPktHead head = { 0 };
417     int32_t ret = RecvPacketHead(module, fd, &head);
418     if (ret != SOFTBUS_OK) {
419         ReleaseAuthTcpConnFdListLock();
420         if (ret == SOFTBUS_INVALID_DATA_HEAD) {
421             (void)DelTrigger(module, fd, READ_TRIGGER);
422             NotifyDisconnected(module, fd);
423         }
424         return ret;
425     }
426     AUTH_LOGI(AUTH_CONN,
427         "RecvSocketData: fd=%{public}d, module=%{public}d, seq=%{public}" PRId64 ", flag=%{public}d, len=%{public}u.",
428         fd, head.module, head.seq, head.flag, head.len);
429     if (head.len == 0 || head.len > AUTH_SOCKET_MAX_DATA_LEN) {
430         AUTH_LOGW(AUTH_CONN, "data is out of size, abandon it.");
431         ReleaseAuthTcpConnFdListLock();
432         return SOFTBUS_INVALID_DATA_HEAD;
433     }
434     if (head.magic != (int32_t)MAGIC_NUMBER) {
435         AUTH_LOGE(AUTH_CONN, "magic number not match.");
436         ReleaseAuthTcpConnFdListLock();
437         return SOFTBUS_INVALID_DATA_HEAD;
438     }
439     uint8_t *data = RecvPacketData(fd, head.len);
440     if (data == NULL) {
441         ReleaseAuthTcpConnFdListLock();
442         return SOFTBUS_DATA_NOT_ENOUGH;
443     }
444     ReleaseAuthTcpConnFdListLock();
445     NotifyDataReceived(module, fd, &head, data);
446     SoftBusFree(data);
447     return SOFTBUS_OK;
448 }
449 
IsEnhanceP2pModuleId(ListenerModule moduleId)450 static bool IsEnhanceP2pModuleId(ListenerModule moduleId)
451 {
452     if (moduleId >= AUTH_ENHANCED_P2P_START && moduleId <= AUTH_ENHANCED_P2P_END) {
453         return true;
454     }
455     return false;
456 }
457 
OnConnectEvent(ListenerModule module,int32_t cfd,const ConnectOption * clientAddr)458 static int32_t OnConnectEvent(ListenerModule module, int32_t cfd, const ConnectOption *clientAddr)
459 {
460     if (cfd < 0) {
461         AUTH_LOGE(AUTH_CONN, "invalid param.");
462         return SOFTBUS_INVALID_PARAM;
463     }
464     if (ConnSetTcpKeepalive(cfd, (int32_t)DEFAULT_FREQ_CYCLE, TCP_KEEPALIVE_INTERVAL, TCP_KEEPALIVE_DEFAULT_COUNT) !=
465         SOFTBUS_OK) {
466         AUTH_LOGE(AUTH_CONN, "set keepalive fail!");
467         ConnShutdownSocket(cfd);
468         return SOFTBUS_NETWORK_SET_KEEPALIVE_OPTION_FAIL;
469     }
470     int32_t ipTos = TCP_KEEPALIVE_TOS_VAL;
471     if (module == AUTH) {
472         if (SoftBusSocketSetOpt(cfd, SOFTBUS_IPPROTO_IP_, SOFTBUS_IP_TOS_, &ipTos, sizeof(ipTos)) !=
473             SOFTBUS_ADAPTER_OK) {
474             AUTH_LOGE(AUTH_CONN, "set option fail!");
475             ConnShutdownSocket(cfd);
476             return SOFTBUS_NETWORK_SET_KEEPALIVE_OPTION_FAIL;
477         }
478     }
479     if (IsNeededFdControl(module) && AddAuthTcpConnFdItem(cfd, module) != SOFTBUS_OK) {
480         AUTH_LOGE(AUTH_CONN, "insert auth tcp conn fd item fail.");
481         ConnShutdownSocket(cfd);
482         return SOFTBUS_MEM_ERR;
483     }
484     if (AddTrigger(module, cfd, READ_TRIGGER) != SOFTBUS_OK) {
485         AUTH_LOGE(AUTH_CONN, "AddTrigger fail.");
486         DeleteAuthTcpConnFdItemByConnId(cfd);
487         ConnShutdownSocket(cfd);
488         return SOFTBUS_AUTH_ADD_TRIGGER_FAIL;
489     }
490     if (module != AUTH && module != AUTH_USB && module != AUTH_P2P && module != AUTH_RAW_P2P_CLIENT &&
491         !IsEnhanceP2pModuleId(module)) {
492         AUTH_LOGI(AUTH_CONN, "newip auth process");
493         if (RouteBuildServerAuthManager(cfd, clientAddr) != SOFTBUS_OK) {
494             AUTH_LOGE(AUTH_CONN, "build auth manager fail.");
495             (void)DelTrigger(module, cfd, READ_TRIGGER);
496             DeleteAuthTcpConnFdItemByConnId(cfd);
497             ConnShutdownSocket(cfd);
498             return SOFTBUS_AUTH_MANAGER_BUILD_FAIL;
499         }
500         return SOFTBUS_OK;
501     }
502     NotifyConnected(module, cfd, false);
503     return SOFTBUS_OK;
504 }
505 
OnDataEvent(ListenerModule module,int32_t events,int32_t fd)506 static int32_t OnDataEvent(ListenerModule module, int32_t events, int32_t fd)
507 {
508     if (events == SOFTBUS_SOCKET_OUT) {
509         return ProcessSocketOutEvent(module, fd);
510     } else if (events == SOFTBUS_SOCKET_IN) {
511         return ProcessSocketInEvent(module, fd);
512     }
513     return SOFTBUS_AUTH_SOCKET_EVENT_INVALID;
514 }
515 
SetSocketCallback(const SocketCallback * cb)516 int32_t SetSocketCallback(const SocketCallback *cb)
517 {
518     CHECK_NULL_PTR_RETURN_VALUE(cb, SOFTBUS_INVALID_PARAM);
519     if (memcpy_s(&g_callback, sizeof(SocketCallback), cb, sizeof(SocketCallback)) != EOK) {
520         AUTH_LOGE(AUTH_CONN, "set SocketCallback fail.");
521         return SOFTBUS_MEM_ERR;
522     }
523     return SOFTBUS_OK;
524 }
525 
UnsetSocketCallback(void)526 void UnsetSocketCallback(void)
527 {
528     (void)memset_s(&g_callback, sizeof(SocketCallback), 0, sizeof(SocketCallback));
529 }
530 
StartSocketListening(ListenerModule module,const LocalListenerInfo * info)531 int32_t StartSocketListening(ListenerModule module, const LocalListenerInfo *info)
532 {
533     SoftbusBaseListener listener = {
534         .onConnectEvent = OnConnectEvent,
535         .onDataEvent = OnDataEvent,
536     };
537     int32_t port = StartBaseListener(info, &listener);
538     if (port <= 0) {
539         AUTH_LOGE(AUTH_CONN, "StartBaseListener fail. port=%{public}d", port);
540         return port;
541     }
542     return port;
543 }
544 
StopSocketListening(ListenerModule moduleId)545 void StopSocketListening(ListenerModule moduleId)
546 {
547     AUTH_LOGI(AUTH_CONN, "stop socket listening. moduleId=%{public}d", moduleId);
548     if (StopBaseListener(moduleId) != SOFTBUS_OK) {
549         AUTH_LOGE(AUTH_CONN, "StopBaseListener fail.");
550     }
551 }
552 
AuthTcpCreateListener(ListenerModule module,int32_t fd,TriggerType trigger)553 static int32_t AuthTcpCreateListener(ListenerModule module, int32_t fd, TriggerType trigger)
554 {
555     if (!IsListenerNodeExist(module)) {
556         SoftbusBaseListener listener = {
557             .onConnectEvent = OnConnectEvent,
558             .onDataEvent = OnDataEvent,
559         };
560         if (StartBaseClient(module, &listener) != SOFTBUS_OK) {
561             AUTH_LOGE(AUTH_CONN, "StartBaseClient fail.");
562         }
563     }
564     return AddTrigger(module, fd, trigger);
565 }
566 
SocketConnectInner(const char * localIp,const char * peerIp,int32_t port,ListenerModule module,bool isBlockMode)567 static int32_t SocketConnectInner(
568     const char *localIp, const char *peerIp, int32_t port, ListenerModule module, bool isBlockMode)
569 {
570     if (localIp == NULL || peerIp == NULL) {
571         AUTH_LOGE(AUTH_CONN, "ip is invalid param.");
572         return AUTH_INVALID_FD;
573     }
574     ConnectOption option = {
575         .type = CONNECT_TCP,
576         .socketOption = { .addr = "", .port = port, .moduleId = module, .protocol = LNN_PROTOCOL_IP }
577     };
578     if (strcpy_s(option.socketOption.addr, sizeof(option.socketOption.addr), peerIp) != EOK) {
579         AUTH_LOGE(AUTH_CONN, "copy remote ip fail.");
580         return AUTH_INVALID_FD;
581     }
582     int32_t ret = ConnOpenClientSocket(&option, localIp, !isBlockMode);
583     if (ret < 0) {
584         AUTH_LOGE(AUTH_CONN, "ConnOpenClientSocket fail, error=%{public}d", ret);
585         return ret;
586     }
587     int32_t fd = ret;
588     TriggerType triggerMode = isBlockMode ? READ_TRIGGER : WRITE_TRIGGER;
589     if (isBlockMode && IsNeededFdControl(module) && AddAuthTcpConnFdItem(fd, module) != SOFTBUS_OK) {
590         AUTH_LOGE(AUTH_CONN, "insert auth tcp conn fd item fail.");
591         ConnShutdownSocket(fd);
592         return AUTH_INVALID_FD;
593     }
594     if (AuthTcpCreateListener(module, fd, triggerMode) != SOFTBUS_OK) {
595         AUTH_LOGE(AUTH_CONN, "AddTrigger fail.");
596         DeleteAuthTcpConnFdItemByConnId(fd);
597         ConnShutdownSocket(fd);
598         return AUTH_INVALID_FD;
599     }
600     if (ConnSetTcpKeepalive(fd, (int32_t)DEFAULT_FREQ_CYCLE, TCP_KEEPALIVE_INTERVAL, TCP_KEEPALIVE_DEFAULT_COUNT) !=
601         SOFTBUS_OK) {
602         AUTH_LOGE(AUTH_CONN, "set tcp keep alive fail.");
603         (void)DelTrigger(module, fd, triggerMode);
604         DeleteAuthTcpConnFdItemByConnId(fd);
605         ConnShutdownSocket(fd);
606         return AUTH_INVALID_FD;
607     }
608     return fd;
609 }
610 
SocketConnectDeviceWithAllIp(const char * localIp,const char * peerIp,int32_t port,bool isBlockMode)611 int32_t SocketConnectDeviceWithAllIp(const char *localIp, const char *peerIp, int32_t port, bool isBlockMode)
612 {
613     return SocketConnectInner(localIp, peerIp, port, AUTH_RAW_P2P_CLIENT, isBlockMode);
614 }
615 
SocketSetDevice(int32_t fd,bool isBlockMode)616 int32_t SocketSetDevice(int32_t fd, bool isBlockMode)
617 {
618     if (fd < 0) {
619         AUTH_LOGE(AUTH_CONN, "ConnOpenClientSocket fail, fd=%{public}d", fd);
620         return SOFTBUS_INVALID_FD;
621     }
622     TriggerType triggerMode = isBlockMode ? READ_TRIGGER : WRITE_TRIGGER;
623     SoftbusBaseListener listener = {
624         .onConnectEvent = OnConnectEvent,
625         .onDataEvent = OnDataEvent,
626     };
627     if (StartBaseClient(AUTH_SESSION_KEY, &listener) != SOFTBUS_OK) {
628         AUTH_LOGE(AUTH_CONN, "StartBaseClient fail.");
629     }
630     if (DelTrigger(AUTH_RAW_P2P_CLIENT, fd, RW_TRIGGER) != SOFTBUS_OK) {
631         AUTH_LOGE(AUTH_CONN, "DelTrigger fail.");
632         ConnShutdownSocket(fd);
633         return SOFTBUS_INVALID_FD;
634     }
635     if (AddTrigger(AUTH_SESSION_KEY, fd, triggerMode) != SOFTBUS_OK) {
636         AUTH_LOGE(AUTH_CONN, "AddTrigger fail.");
637         ConnShutdownSocket(fd);
638         return SOFTBUS_INVALID_FD;
639     }
640     if (ConnSetTcpKeepalive(fd, (int32_t)DEFAULT_FREQ_CYCLE, TCP_KEEPALIVE_INTERVAL, TCP_KEEPALIVE_DEFAULT_COUNT) !=
641         SOFTBUS_OK) {
642         AUTH_LOGE(AUTH_CONN, "set tcp keep alive fail.");
643         (void)DelTrigger(AUTH, fd, triggerMode);
644         ConnShutdownSocket(fd);
645         return SOFTBUS_INVALID_FD;
646     }
647     int32_t ipTos = TCP_KEEPALIVE_TOS_VAL;
648     if (SoftBusSocketSetOpt(fd, SOFTBUS_IPPROTO_IP_, SOFTBUS_IP_TOS_, &ipTos, sizeof(ipTos)) != SOFTBUS_ADAPTER_OK) {
649         AUTH_LOGE(AUTH_CONN, "set option fail.");
650         (void)DelTrigger(AUTH, fd, triggerMode);
651         ConnShutdownSocket(fd);
652         return SOFTBUS_INVALID_FD;
653     }
654     return SOFTBUS_OK;
655 }
656 
GetConnectOptionByIfname(int32_t ifnameIdx,int32_t port)657 static ConnectOption GetConnectOptionByIfname(int32_t ifnameIdx, int32_t port)
658 {
659     ConnectOption option = {
660         .type = CONNECT_TCP, .socketOption = { .addr = "", .port = port, .moduleId = AUTH, .protocol = LNN_PROTOCOL_IP }
661     };
662     if (ifnameIdx == USB_IF) {
663         option.socketOption.moduleId = AUTH_USB;
664         option.socketOption.protocol = LNN_PROTOCOL_USB;
665     }
666     return option;
667 }
668 
SetTcpKeepaliveAndIpTos(bool isBlockMode,int32_t ifnameIdx,TriggerType triggerMode,ListenerModule module,int32_t fd)669 static int32_t SetTcpKeepaliveAndIpTos(bool isBlockMode, int32_t ifnameIdx, TriggerType triggerMode,
670     ListenerModule module, int32_t fd)
671 {
672     int32_t ret = SOFTBUS_OK;
673     ret = ConnSetTcpKeepalive(fd, (int32_t)DEFAULT_FREQ_CYCLE, TCP_KEEPALIVE_INTERVAL, TCP_KEEPALIVE_DEFAULT_COUNT);
674     if (ret != SOFTBUS_OK) {
675         AUTH_LOGE(AUTH_CONN, "set tcp keep alive fail.");
676         return ret;
677     }
678     int32_t ipTos = TCP_KEEPALIVE_TOS_VAL;
679     ret = SoftBusSocketSetOpt(fd, SOFTBUS_IPPROTO_IP_, SOFTBUS_IP_TOS_, &ipTos, sizeof(ipTos));
680     if (ret != SOFTBUS_ADAPTER_OK) {
681         AUTH_LOGE(AUTH_CONN, "set option fail.");
682         return SOFTBUS_NETWORK_SET_KEEPALIVE_OPTION_FAIL;
683     }
684     return SOFTBUS_OK;
685 }
686 
SocketConnectDevice(const char * ip,int32_t port,bool isBlockMode,int32_t ifnameIdx)687 int32_t SocketConnectDevice(const char *ip, int32_t port, bool isBlockMode, int32_t ifnameIdx)
688 {
689     CHECK_NULL_PTR_RETURN_VALUE(ip, AUTH_INVALID_FD);
690     char localIp[MAX_ADDR_LEN] = { 0 };
691     if (LnnGetLocalStrInfoByIfnameIdx(STRING_KEY_IP, localIp, MAX_ADDR_LEN, ifnameIdx) != SOFTBUS_OK) {
692         AUTH_LOGE(AUTH_CONN, "get local ip fail.");
693         return AUTH_INVALID_FD;
694     }
695     ConnectOption option = GetConnectOptionByIfname(ifnameIdx, port);
696     if (ifnameIdx == USB_IF) {
697         if (LnnGetLocalStrInfoByIfnameIdx(STRING_KEY_IP6_WITH_IF, localIp, MAX_ADDR_LEN, USB_IF) != SOFTBUS_OK) {
698             AUTH_LOGE(AUTH_CONN, "get local ip failed");
699             return SOFTBUS_NETWORK_GET_NODE_INFO_ERR;
700         }
701     }
702     if (strcpy_s(option.socketOption.addr, sizeof(option.socketOption.addr), ip) != EOK) {
703         AUTH_LOGE(AUTH_CONN, "copy remote ip fail.");
704         return AUTH_INVALID_FD;
705     }
706     int32_t ret = ConnOpenClientSocket(&option, localIp, !isBlockMode);
707     if (ret < 0) {
708         AUTH_LOGE(AUTH_CONN, "ConnOpenClientSocket fail, error=%{public}d", ret);
709         return ret;
710     }
711     int32_t fd = ret;
712     TriggerType triggerMode = isBlockMode ? READ_TRIGGER : WRITE_TRIGGER;
713     ListenerModule module = (ifnameIdx == USB_IF) ? AUTH_USB : AUTH;
714     if (isBlockMode && AddAuthTcpConnFdItem(fd, module) != SOFTBUS_OK) {
715         AUTH_LOGE(AUTH_CONN, "insert auth tcp conn fd item fail.");
716         ConnShutdownSocket(fd);
717         return AUTH_INVALID_FD;
718     }
719     if (AddTrigger(module, fd, triggerMode) != SOFTBUS_OK) {
720         AUTH_LOGE(AUTH_CONN, "AddTrigger fail.");
721         DeleteAuthTcpConnFdItemByConnId(fd);
722         ConnShutdownSocket(fd);
723         return AUTH_INVALID_FD;
724     }
725     if (SetTcpKeepaliveAndIpTos(isBlockMode, ifnameIdx, triggerMode, module, fd) != SOFTBUS_OK) {
726         AUTH_LOGE(AUTH_CONN, "SetTcpKeepaliveAndIpTos fail.");
727         (void)DelTrigger(module, fd, triggerMode);
728         DeleteAuthTcpConnFdItemByConnId(fd);
729         ConnShutdownSocket(fd);
730         return AUTH_INVALID_FD;
731     }
732     return fd;
733 }
734 
NipSocketConnectDevice(ListenerModule module,const char * addr,int32_t port,bool isBlockMode)735 int32_t NipSocketConnectDevice(ListenerModule module, const char *addr, int32_t port, bool isBlockMode)
736 {
737     if (addr == NULL) {
738         AUTH_LOGE(AUTH_CONN, "addr is invalid param.");
739         return AUTH_INVALID_FD;
740     }
741     ConnectOption option = {
742         .type = CONNECT_TCP,
743         .socketOption = { .addr = "", .port = port, .moduleId = module, .protocol = LNN_PROTOCOL_NIP }
744     };
745     if (strcpy_s(option.socketOption.addr, sizeof(option.socketOption.addr), addr) != EOK) {
746         AUTH_LOGE(AUTH_CONN, "copy remote ip fail.");
747         return AUTH_INVALID_FD;
748     }
749     int32_t fd = ConnOpenClientSocket(&option, BIND_ADDR_ALL, !isBlockMode);
750     if (fd < 0) {
751         AUTH_LOGE(AUTH_CONN, "ConnOpenClientSocket fail.");
752         return AUTH_INVALID_FD;
753     }
754     TriggerType triggerMode = isBlockMode ? READ_TRIGGER : WRITE_TRIGGER;
755     if (AddTrigger(module, fd, triggerMode) != SOFTBUS_OK) {
756         AUTH_LOGE(AUTH_CONN, "AddTrigger fail.");
757         ConnShutdownSocket(fd);
758         return AUTH_INVALID_FD;
759     }
760     if (ConnSetTcpKeepalive(fd, (int32_t)DEFAULT_FREQ_CYCLE, TCP_KEEPALIVE_INTERVAL, TCP_KEEPALIVE_DEFAULT_COUNT) !=
761         SOFTBUS_OK) {
762         AUTH_LOGE(AUTH_CONN, "set tcp keep alive fail.");
763         (void)DelTrigger(module, fd, triggerMode);
764         ConnShutdownSocket(fd);
765         return AUTH_INVALID_FD;
766     }
767     return fd;
768 }
769 
SocketDisconnectDevice(ListenerModule module,int32_t fd)770 void SocketDisconnectDevice(ListenerModule module, int32_t fd)
771 {
772     if (fd < 0) {
773         AUTH_LOGD(AUTH_CONN, "invalid fd, maybe has shutdown. fd=%{public}d", fd);
774         return;
775     }
776     (void)DelTrigger(module, fd, RW_TRIGGER);
777     ConnShutdownSocket(fd);
778 }
779 
SocketPostBytes(int32_t fd,const AuthDataHead * head,const uint8_t * data)780 int32_t SocketPostBytes(int32_t fd, const AuthDataHead *head, const uint8_t *data)
781 {
782     CHECK_NULL_PTR_RETURN_VALUE(head, SOFTBUS_INVALID_PARAM);
783     CHECK_NULL_PTR_RETURN_VALUE(data, SOFTBUS_INVALID_PARAM);
784     uint32_t size = GetSocketPktSize(head->len);
785     uint8_t *buf = (uint8_t *)SoftBusCalloc(size);
786     if (buf == NULL) {
787         AUTH_LOGE(AUTH_CONN, "malloc pkt err.");
788         return SOFTBUS_MALLOC_ERR;
789     }
790     SocketPktHead pktHead = {
791         .magic = MAGIC_NUMBER,
792         .module = head->module,
793         .seq = head->seq,
794         .flag = head->flag,
795         .len = head->len,
796     };
797     if (PackSocketPkt(&pktHead, data, buf, size) != SOFTBUS_OK) {
798         AUTH_LOGE(AUTH_CONN, "pack socket pkt fail.");
799         SoftBusFree(buf);
800         return SOFTBUS_AUTH_PACK_SOCKET_PKT_FAIL;
801     }
802     if (!RequireAuthTcpConnFdListLock()) {
803         AUTH_LOGE(AUTH_CONN, "RequireAuthTcpConnFdListLock fail");
804         SoftBusFree(buf);
805         return SOFTBUS_LOCK_ERR;
806     }
807     if (IsNeededFdControl((ListenerModule)pktHead.module) && !IsExistAuthTcpConnFdItemWithoutLock(fd)) {
808         AUTH_LOGE(AUTH_CONN, "fd=%{public}d not exist, ignore", fd);
809         ReleaseAuthTcpConnFdListLock();
810         SoftBusFree(buf);
811         return SOFTBUS_INVALID_PARAM;
812     }
813     AUTH_LOGI(AUTH_CONN, "fd=%{public}d, module=%{public}d, seq=%{public}" PRId64 ", flag=%{public}d, len=%{public}u.",
814         fd, pktHead.module, pktHead.seq, pktHead.flag, pktHead.len);
815     ssize_t ret = ConnSendSocketData(fd, (const char *)buf, (size_t)size, 0);
816     ReleaseAuthTcpConnFdListLock();
817     SoftBusFree(buf);
818     if (ret != (ssize_t)size) {
819         AUTH_LOGE(AUTH_CONN, "fail. ret=%{public}zd", ret);
820         return SOFTBUS_TCP_SOCKET_ERR;
821     }
822     return SOFTBUS_OK;
823 }
824 
SocketGetConnInfo(int32_t fd,AuthConnInfo * connInfo,bool * isServer,int32_t ifnameIdx)825 int32_t SocketGetConnInfo(int32_t fd, AuthConnInfo *connInfo, bool *isServer, int32_t ifnameIdx)
826 {
827     CHECK_NULL_PTR_RETURN_VALUE(connInfo, SOFTBUS_INVALID_PARAM);
828     CHECK_NULL_PTR_RETURN_VALUE(isServer, SOFTBUS_INVALID_PARAM);
829     SocketAddr socket;
830     if (ifnameIdx == USB_IF) {
831         if (ConnGetPeerSocketAddr6(fd, &socket) != SOFTBUS_OK) {
832             AUTH_LOGE(AUTH_CONN, "fail, fd=%{public}d.", fd);
833             return SOFTBUS_AUTH_GET_PEER_SOCKET_ADDR_FAIL;
834         }
835     } else {
836         if (ConnGetPeerSocketAddr(fd, &socket) != SOFTBUS_OK) {
837             AUTH_LOGE(AUTH_CONN, "fail, fd=%{public}d.", fd);
838             return SOFTBUS_AUTH_GET_PEER_SOCKET_ADDR_FAIL;
839         }
840     }
841     int32_t localPort = ConnGetLocalSocketPort(fd);
842     if (localPort <= 0) {
843         AUTH_LOGE(AUTH_CONN, "fail, fd=%{public}d.", fd);
844         return SOFTBUS_INVALID_PORT;
845     }
846     connInfo->type = AUTH_LINK_TYPE_WIFI;
847     if (ifnameIdx == USB_IF) {
848         connInfo->type = AUTH_LINK_TYPE_USB;
849     }
850     if (strcpy_s(connInfo->info.ipInfo.ip, sizeof(connInfo->info.ipInfo.ip), socket.addr) != EOK) {
851         AUTH_LOGE(AUTH_CONN, "copy ip fail, fd=%{public}d.", fd);
852         return SOFTBUS_MEM_ERR;
853     }
854     connInfo->info.ipInfo.port = socket.port;
855     int32_t serverPort = 0;
856     if (LnnGetLocalNumInfoByIfnameIdx(NUM_KEY_AUTH_PORT, &serverPort, ifnameIdx) != SOFTBUS_OK) {
857         AUTH_LOGE(AUTH_CONN, "get local auth port fail.");
858     }
859     *isServer = (serverPort != localPort);
860     return SOFTBUS_OK;
861 }
862 
863 /* Auth Channel */
NotifyChannelDataReceived(int32_t channelId,const SocketPktHead * head,const uint8_t * data)864 static void NotifyChannelDataReceived(int32_t channelId, const SocketPktHead *head, const uint8_t *data)
865 {
866     uint32_t i;
867     AuthChannelListener *listener = NULL;
868     for (i = 0; i < sizeof(g_listener) / sizeof(InnerChannelListener); i++) {
869         if (g_listener[i].module == head->module) {
870             listener = &g_listener[i].listener;
871             break;
872         }
873     }
874     if (listener == NULL || listener->onDataReceived == NULL) {
875         AUTH_LOGE(AUTH_CONN, "AuthChannelListener not set.");
876         return;
877     }
878 
879     AuthChannelData channelData = { 0 };
880     channelData.module = head->module;
881     channelData.seq = head->seq;
882     channelData.flag = head->flag;
883     channelData.len = head->len;
884     channelData.data = data;
885     listener->onDataReceived(channelId, &channelData);
886 }
887 
NotifyChannelDisconnected(int32_t channelId)888 static void NotifyChannelDisconnected(int32_t channelId)
889 {
890     uint32_t i;
891     for (i = 0; i < sizeof(g_listener) / sizeof(InnerChannelListener); i++) {
892         if (g_listener[i].listener.onDisconnected != NULL) {
893             g_listener[i].listener.onDisconnected(channelId);
894         }
895     }
896 }
897 
RegAuthChannelListener(int32_t module,const AuthChannelListener * listener)898 int32_t RegAuthChannelListener(int32_t module, const AuthChannelListener *listener)
899 {
900     if (listener == NULL || listener->onDataReceived == NULL) {
901         AUTH_LOGE(AUTH_CONN, "invalid listener.");
902         return SOFTBUS_INVALID_PARAM;
903     }
904     uint32_t i;
905     for (i = 0; i < sizeof(g_listener) / sizeof(InnerChannelListener); i++) {
906         if (g_listener[i].module == module) {
907             g_listener[i].listener.onDataReceived = listener->onDataReceived;
908             g_listener[i].listener.onDisconnected = listener->onDisconnected;
909             return SOFTBUS_OK;
910         }
911     }
912     AUTH_LOGE(AUTH_CONN, "unknown module. module=%{public}d", module);
913     return SOFTBUS_INVALID_PARAM;
914 }
915 
UnregAuthChannelListener(int32_t module)916 void UnregAuthChannelListener(int32_t module)
917 {
918     uint32_t i;
919     for (i = 0; i < sizeof(g_listener) / sizeof(InnerChannelListener); i++) {
920         if (g_listener[i].module == module) {
921             g_listener[i].listener.onDataReceived = NULL;
922             g_listener[i].listener.onDisconnected = NULL;
923             return;
924         }
925     }
926 }
927 
AuthOpenChannelWithAllIp(const char * localIp,const char * remoteIp,int32_t port)928 int32_t AuthOpenChannelWithAllIp(const char *localIp, const char *remoteIp, int32_t port)
929 {
930     if (localIp == NULL || remoteIp == NULL || port <= 0) {
931         AUTH_LOGE(AUTH_CONN, "invalid param.");
932         return SOFTBUS_INVALID_PARAM;
933     }
934     int32_t fd = SocketConnectDeviceWithAllIp(localIp, remoteIp, port, true);
935     if (fd < 0) {
936         AUTH_LOGE(AUTH_CONN, "connect fail.");
937         return INVALID_CHANNEL_ID;
938     }
939     AUTH_LOGI(AUTH_CONN, "open auth channel succ, channelId=%{public}d.", fd);
940     return fd;
941 }
942 
AuthOpenChannel(const char * ip,int32_t port,int32_t ifnameIdx)943 int32_t AuthOpenChannel(const char *ip, int32_t port, int32_t ifnameIdx)
944 {
945     if (ip == NULL || port <= 0) {
946         AUTH_LOGE(AUTH_CONN, "invalid param.");
947         return INVALID_CHANNEL_ID;
948     }
949     int32_t fd = SocketConnectDevice(ip, port, true, ifnameIdx);
950     if (fd < 0) {
951         AUTH_LOGE(AUTH_CONN, "connect fail.");
952         return INVALID_CHANNEL_ID;
953     }
954     AUTH_LOGI(AUTH_CONN, "open auth channel succ, channelId=%{public}d.", fd);
955     return fd;
956 }
957 
AuthCloseChannel(int32_t channelId,int32_t moduleId)958 void AuthCloseChannel(int32_t channelId, int32_t moduleId)
959 {
960     AUTH_LOGI(AUTH_CONN, "close auth channel, moduleId=%{public}d, id=%{public}d.", moduleId, channelId);
961     if (IsNeededFdControl((ListenerModule)moduleId)) {
962         DeleteAuthTcpConnFdItemByConnId(channelId);
963     }
964     SocketDisconnectDevice((ListenerModule)moduleId, channelId);
965 }
966 
AuthPostChannelData(int32_t channelId,const AuthChannelData * data)967 int32_t AuthPostChannelData(int32_t channelId, const AuthChannelData *data)
968 {
969     if (channelId < 0 || data == NULL || data->data == NULL || data->len == 0) {
970         AUTH_LOGE(AUTH_CONN, "invalid param, channelId=%{public}d.", channelId);
971         return SOFTBUS_INVALID_PARAM;
972     }
973     AuthDataHead head = {
974         .dataType = DATA_TYPE_CONNECTION,
975         .module = data->module,
976         .seq = data->seq,
977         .flag = data->flag,
978         .len = data->len,
979     };
980     return SocketPostBytes(channelId, &head, data->data);
981 }
982 
GetTcpKeepaliveOptionByCycle(ModeCycle cycle,TcpKeepaliveOption * tcpKeepaliveOption)983 static int32_t GetTcpKeepaliveOptionByCycle(ModeCycle cycle, TcpKeepaliveOption *tcpKeepaliveOption)
984 {
985     if (tcpKeepaliveOption == NULL) {
986         AUTH_LOGE(AUTH_CONN, "invalid param");
987         return SOFTBUS_INVALID_PARAM;
988     }
989     switch (cycle) {
990         case HIGH_FREQ_CYCLE:
991             tcpKeepaliveOption->keepaliveCount = TCP_KEEPALIVE_HIGH_COUNT;
992             tcpKeepaliveOption->userTimeout = TCP_KEEPALIVE_HIGH_USER_TIMEOUT;
993             break;
994         case MID_FREQ_CYCLE:
995             tcpKeepaliveOption->keepaliveCount = TCP_KEEPALIVE_MID_COUNT;
996             tcpKeepaliveOption->userTimeout = TCP_KEEPALIVE_MID_USER_TIMEOUT;
997             break;
998         case LOW_FREQ_CYCLE:
999             tcpKeepaliveOption->keepaliveCount = TCP_KEEPALIVE_LOW_COUNT;
1000             tcpKeepaliveOption->userTimeout = TCP_KEEPALIVE_LOW_USER_TIMEOUT;
1001             break;
1002         case DEFAULT_FREQ_CYCLE:
1003             tcpKeepaliveOption->keepaliveCount = TCP_KEEPALIVE_DEFAULT_COUNT;
1004             tcpKeepaliveOption->userTimeout = TCP_KEEPALIVE_DEFAULT_USER_TIMEOUT;
1005             break;
1006         default:
1007             AUTH_LOGE(AUTH_CONN, "no match cycle, cycle=%{public}d", cycle);
1008             return SOFTBUS_INVALID_PARAM;
1009     }
1010     tcpKeepaliveOption->keepaliveIdle = (int32_t)cycle;
1011     tcpKeepaliveOption->keepaliveIntvl = TCP_KEEPALIVE_INTERVAL;
1012     return SOFTBUS_OK;
1013 }
1014 
AuthSetTcpKeepaliveOption(int32_t fd,ModeCycle cycle)1015 int32_t AuthSetTcpKeepaliveOption(int32_t fd, ModeCycle cycle)
1016 {
1017     if (fd <= 0 || cycle < HIGH_FREQ_CYCLE || cycle > DEFAULT_FREQ_CYCLE) {
1018         AUTH_LOGE(AUTH_CONN, "invalid param");
1019         return SOFTBUS_INVALID_PARAM;
1020     }
1021     TcpKeepaliveOption tcpKeepaliveOption = { 0 };
1022     int32_t ret = GetTcpKeepaliveOptionByCycle(cycle, &tcpKeepaliveOption);
1023     if (ret != SOFTBUS_OK) {
1024         AUTH_LOGE(AUTH_CONN, "get tcp keepalive option by cycle fail");
1025         return ret;
1026     }
1027     if (ConnSetTcpUserTimeOut(fd, tcpKeepaliveOption.userTimeout) != SOFTBUS_OK) {
1028         AUTH_LOGE(AUTH_CONN, "set TCP_USER_TIMEOUT fail, fd=%{public}d", fd);
1029         return SOFTBUS_ADAPTER_ERR;
1030     }
1031     if (ConnSetTcpKeepalive(fd, tcpKeepaliveOption.keepaliveIdle, tcpKeepaliveOption.keepaliveIntvl,
1032             tcpKeepaliveOption.keepaliveCount) != SOFTBUS_OK) {
1033         AUTH_LOGE(AUTH_CONN, "set tcp keepalive fail, fd=%{public}d", fd);
1034         return SOFTBUS_ADAPTER_ERR;
1035     }
1036 
1037     AUTH_LOGI(AUTH_CONN,
1038         "set tcp keepalive successful, fd=%{public}d, keepaliveIdle=%{public}d, keepaliveIntvl=%{public}d, "
1039         "keepaliveCount=%{public}d, userTimeout=%{public}u",
1040         fd, tcpKeepaliveOption.keepaliveIdle, tcpKeepaliveOption.keepaliveIntvl, tcpKeepaliveOption.keepaliveCount,
1041         tcpKeepaliveOption.userTimeout);
1042     return SOFTBUS_OK;
1043 }
1044 
AuthTcpConnFdLockInit(void)1045 int32_t AuthTcpConnFdLockInit(void)
1046 {
1047     if (SoftBusMutexInit(&g_authTcpConnFdListLock, NULL) != SOFTBUS_OK) {
1048         AUTH_LOGE(AUTH_CONN, "authTcpConnFdList mutex init fail");
1049         return SOFTBUS_LOCK_ERR;
1050     }
1051     return SOFTBUS_OK;
1052 }
1053 
AuthTcpConnFdLockDeinit(void)1054 void AuthTcpConnFdLockDeinit(void)
1055 {
1056     if (SoftBusMutexDestroy(&g_authTcpConnFdListLock) != SOFTBUS_OK) {
1057         AUTH_LOGE(AUTH_CONN, "authTcpConnFdList mutex destroy fail");
1058     }
1059 }
1060 
SetSessionKeyListenerModule(int32_t fd)1061 static void SetSessionKeyListenerModule(int32_t fd)
1062 {
1063     if (fd < 0) {
1064         AUTH_LOGE(AUTH_CONN, "fd invalid, fd=%{public}d", fd);
1065         return;
1066     }
1067     AUTH_LOGI(AUTH_CONN, "Update session key listener module, fd=%{public}d", fd);
1068     SoftbusBaseListener listener = {
1069         .onConnectEvent = OnConnectEvent,
1070         .onDataEvent = OnDataEvent,
1071     };
1072     if (StartBaseClient(AUTH_SESSION_KEY, &listener) != SOFTBUS_OK) {
1073         AUTH_LOGE(AUTH_CONN, "StartBaseClient fail.");
1074     }
1075     if (DelTrigger(AUTH_RAW_P2P_SERVER, fd, RW_TRIGGER) != SOFTBUS_OK) {
1076         AUTH_LOGE(AUTH_CONN, "DelTrigger fail.");
1077     }
1078     if (AddTrigger(AUTH_SESSION_KEY, fd, READ_TRIGGER) != SOFTBUS_OK) {
1079         AUTH_LOGE(AUTH_CONN, "AddTrigger fail.");
1080     }
1081 }
1082 
StopSessionKeyListening(int32_t fd)1083 void StopSessionKeyListening(int32_t fd)
1084 {
1085     if (fd < 0) {
1086         AUTH_LOGE(AUTH_CONN, "fd invalid, fd=%{public}d", fd);
1087         return;
1088     }
1089     (void)DelTrigger(AUTH_SESSION_KEY, fd, RW_TRIGGER);
1090     StopSocketListening(AUTH_SESSION_KEY);
1091 }