1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "trans_tcp_direct_message.h"
17 
18 #include <securec.h>
19 #include <string.h>
20 
21 #include "access_control.h"
22 #include "anonymizer.h"
23 #include "auth_interface.h"
24 #include "bus_center_manager.h"
25 #include "cJSON.h"
26 #include "data_bus_native.h"
27 #include "lnn_distributed_net_ledger.h"
28 #include "lnn_lane_link.h"
29 #include "lnn_net_builder.h"
30 #include "softbus_adapter_crypto.h"
31 #include "softbus_adapter_mem.h"
32 #include "softbus_adapter_socket.h"
33 #include "softbus_adapter_thread.h"
34 #include "softbus_app_info.h"
35 #include "softbus_errcode.h"
36 #include "softbus_feature_config.h"
37 #include "softbus_hisysevt_transreporter.h"
38 #include "softbus_message_open_channel.h"
39 #include "softbus_socket.h"
40 #include "softbus_tcp_socket.h"
41 #include "trans_channel_common.h"
42 #include "trans_event.h"
43 #include "trans_lane_manager.h"
44 #include "trans_log.h"
45 #include "trans_tcp_direct_callback.h"
46 #include "trans_tcp_direct_manager.h"
47 #include "trans_tcp_direct_sessionconn.h"
48 #include "wifi_direct_manager.h"
49 
50 #define MAX_PACKET_SIZE (64 * 1024)
51 #define MIN_META_LEN 6
52 #define META_SESSION "IShare"
53 #define MAX_ERRDESC_LEN 128
54 
55 typedef struct {
56     ListNode node;
57     int32_t channelId;
58     int32_t fd;
59     uint32_t size;
60     char *data;
61     char *w;
62 } ServerDataBuf;
63 
64 typedef struct {
65     int32_t channelType;
66     int32_t businessType;
67     ConfigType configType;
68 } ConfigTypeMap;
69 
70 static SoftBusList *g_tcpSrvDataList = NULL;
71 
PackTdcPacketHead(TdcPacketHead * data)72 static void PackTdcPacketHead(TdcPacketHead *data)
73 {
74     data->magicNumber = SoftBusHtoLl(data->magicNumber);
75     data->module = SoftBusHtoLl(data->module);
76     data->seq = SoftBusHtoLll(data->seq);
77     data->flags = SoftBusHtoLl(data->flags);
78     data->dataLen = SoftBusHtoLl(data->dataLen);
79 }
80 
UnpackTdcPacketHead(TdcPacketHead * data)81 static void UnpackTdcPacketHead(TdcPacketHead *data)
82 {
83     data->magicNumber = SoftBusLtoHl(data->magicNumber);
84     data->module = SoftBusLtoHl(data->module);
85     data->seq = SoftBusLtoHll(data->seq);
86     data->flags = SoftBusLtoHl(data->flags);
87     data->dataLen = SoftBusLtoHl(data->dataLen);
88 }
89 
TransSrvDataListInit(void)90 int32_t TransSrvDataListInit(void)
91 {
92     if (g_tcpSrvDataList != NULL) {
93         return SOFTBUS_OK;
94     }
95     g_tcpSrvDataList = CreateSoftBusList();
96     if (g_tcpSrvDataList == NULL) {
97         TRANS_LOGE(TRANS_CTRL, "creat list failed");
98         return SOFTBUS_MALLOC_ERR;
99     }
100     return SOFTBUS_OK;
101 }
102 
TransSrvDestroyDataBuf(void)103 static void TransSrvDestroyDataBuf(void)
104 {
105     if (g_tcpSrvDataList ==  NULL) {
106         return;
107     }
108 
109     ServerDataBuf *item = NULL;
110     ServerDataBuf *next = NULL;
111     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
112         return;
113     }
114     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_tcpSrvDataList->list, ServerDataBuf, node) {
115         ListDelete(&item->node);
116         SoftBusFree(item->data);
117         SoftBusFree(item);
118         g_tcpSrvDataList->cnt--;
119     }
120     SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
121 
122     return;
123 }
124 
TransSrvDataListDeinit(void)125 void TransSrvDataListDeinit(void)
126 {
127     if (g_tcpSrvDataList == NULL) {
128         return;
129     }
130     TransSrvDestroyDataBuf();
131     DestroySoftBusList(g_tcpSrvDataList);
132     g_tcpSrvDataList = NULL;
133 }
134 
TransSrvAddDataBufNode(int32_t channelId,int32_t fd)135 int32_t TransSrvAddDataBufNode(int32_t channelId, int32_t fd)
136 {
137     #define MAX_DATA_BUF 4096
138     ServerDataBuf *node = (ServerDataBuf *)SoftBusCalloc(sizeof(ServerDataBuf));
139     if (node == NULL) {
140         TRANS_LOGE(TRANS_CTRL, "create server data buf node fail.");
141         return SOFTBUS_MALLOC_ERR;
142     }
143     node->channelId = channelId;
144     node->fd = fd;
145     node->size = MAX_DATA_BUF;
146     node->data = (char *)SoftBusCalloc(MAX_DATA_BUF);
147     if (node->data == NULL) {
148         TRANS_LOGE(TRANS_CTRL, "create server data buf fail.");
149         SoftBusFree(node);
150         return SOFTBUS_MALLOC_ERR;
151     }
152     node->w = node->data;
153 
154     if (SoftBusMutexLock(&(g_tcpSrvDataList->lock)) != SOFTBUS_OK) {
155         SoftBusFree(node->data);
156         SoftBusFree(node);
157         return SOFTBUS_LOCK_ERR;
158     }
159     ListInit(&node->node);
160     ListTailInsert(&g_tcpSrvDataList->list, &node->node);
161     g_tcpSrvDataList->cnt++;
162     SoftBusMutexUnlock(&(g_tcpSrvDataList->lock));
163 
164     return SOFTBUS_OK;
165 }
166 
TransSrvDelDataBufNode(int32_t channelId)167 void TransSrvDelDataBufNode(int32_t channelId)
168 {
169     if (g_tcpSrvDataList ==  NULL) {
170         return;
171     }
172 
173     ServerDataBuf *item = NULL;
174     ServerDataBuf *next = NULL;
175     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
176         return;
177     }
178     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_tcpSrvDataList->list, ServerDataBuf, node) {
179         if (item->channelId == channelId) {
180             ListDelete(&item->node);
181             TRANS_LOGI(TRANS_BYTES, "delete channelId=%{public}d", item->channelId);
182             SoftBusFree(item->data);
183             SoftBusFree(item);
184             g_tcpSrvDataList->cnt--;
185             break;
186         }
187     }
188     SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
189 }
190 
SwitchCipherTypeToAuthLinkType(uint32_t cipherFlag)191 static AuthLinkType SwitchCipherTypeToAuthLinkType(uint32_t cipherFlag)
192 {
193     if (cipherFlag & FLAG_BR) {
194         return AUTH_LINK_TYPE_BR;
195     }
196 
197     if (cipherFlag & FLAG_BLE) {
198         return AUTH_LINK_TYPE_BLE;
199     }
200 
201     if (cipherFlag & FLAG_P2P) {
202         return AUTH_LINK_TYPE_P2P;
203     }
204     if (cipherFlag & FLAG_ENHANCE_P2P) {
205         return AUTH_LINK_TYPE_ENHANCED_P2P;
206     }
207     return AUTH_LINK_TYPE_WIFI;
208 }
209 
PackBytes(int32_t channelId,const char * data,TdcPacketHead * packetHead,char * buffer,uint32_t bufLen)210 static int32_t PackBytes(int32_t channelId, const char *data, TdcPacketHead *packetHead,
211     char *buffer, uint32_t bufLen)
212 {
213     AuthHandle authHandle = { 0 };
214     if (GetAuthHandleByChanId(channelId, &authHandle) != SOFTBUS_OK ||
215         authHandle.authId == AUTH_INVALID_ID) {
216         TRANS_LOGE(TRANS_BYTES, "PackBytes get auth id fail");
217         return SOFTBUS_NOT_FIND;
218     }
219 
220     uint8_t *encData = (uint8_t *)buffer + DC_MSG_PACKET_HEAD_SIZE;
221     uint32_t encDataLen = bufLen - DC_MSG_PACKET_HEAD_SIZE;
222     if (AuthEncrypt(&authHandle, (const uint8_t *)data, packetHead->dataLen, encData, &encDataLen) != SOFTBUS_OK) {
223         TRANS_LOGE(TRANS_BYTES, "PackBytes encrypt fail");
224         return SOFTBUS_ENCRYPT_ERR;
225     }
226     packetHead->dataLen = encDataLen;
227 
228     TRANS_LOGI(TRANS_BYTES, "PackBytes: flag=%{public}u, seq=%{public}" PRIu64,
229         packetHead->flags, packetHead->seq);
230     PackTdcPacketHead(packetHead);
231     if (memcpy_s(buffer, bufLen, packetHead, sizeof(TdcPacketHead)) != EOK) {
232         TRANS_LOGE(TRANS_BYTES, "memcpy_s buffer fail");
233         return SOFTBUS_MEM_ERR;
234     }
235     return SOFTBUS_OK;
236 }
237 
SendFailToFlushDevice(SessionConn * conn)238 static void SendFailToFlushDevice(SessionConn *conn)
239 {
240     if (conn->appInfo.routeType == WIFI_STA) {
241         char *tmpId = NULL;
242         Anonymize(conn->appInfo.peerData.deviceId, &tmpId);
243         TRANS_LOGE(TRANS_CTRL, "send data fail, do Authflushdevice deviceId=%{public}s", tmpId);
244         AnonymizeFree(tmpId);
245         if (AuthFlushDevice(conn->appInfo.peerData.deviceId) != SOFTBUS_OK) {
246             TRANS_LOGE(TRANS_CTRL, "tcp flush failed, wifi will offline");
247             LnnRequestLeaveSpecific(conn->appInfo.peerNetWorkId, CONNECTION_ADDR_WLAN);
248         }
249     }
250 }
251 
TransTdcPostBytes(int32_t channelId,TdcPacketHead * packetHead,const char * data)252 int32_t TransTdcPostBytes(int32_t channelId, TdcPacketHead *packetHead, const char *data)
253 {
254     if (data == NULL || packetHead == NULL || packetHead->dataLen == 0) {
255         TRANS_LOGE(TRANS_BYTES, "Invalid para.");
256         return SOFTBUS_INVALID_PARAM;
257     }
258     AuthHandle authHandle = { 0 };
259     if (GetAuthHandleByChanId(channelId, &authHandle) != SOFTBUS_OK ||
260         authHandle.authId == AUTH_INVALID_ID) {
261         TRANS_LOGE(TRANS_BYTES, "get auth id fail, channelId=%{public}d", channelId);
262         return SOFTBUS_TRANS_TCP_GET_AUTHID_FAILED;
263     }
264     uint32_t bufferLen = AuthGetEncryptSize(authHandle.authId, packetHead->dataLen) + DC_MSG_PACKET_HEAD_SIZE;
265     char *buffer = (char *)SoftBusCalloc(bufferLen);
266     if (buffer == NULL) {
267         TRANS_LOGE(TRANS_BYTES, "buffer malloc error.");
268         return SOFTBUS_MALLOC_ERR;
269     }
270     if (PackBytes(channelId, data, packetHead, buffer, bufferLen) != SOFTBUS_OK) {
271         TRANS_LOGE(TRANS_BYTES, "Pack Bytes error.");
272         SoftBusFree(buffer);
273         return SOFTBUS_ENCRYPT_ERR;
274     }
275     SessionConn *conn = (SessionConn *)SoftBusCalloc(sizeof(SessionConn));
276     if (conn == NULL) {
277         TRANS_LOGE(TRANS_BYTES, "malloc conn fail");
278         SoftBusFree(buffer);
279         return SOFTBUS_MALLOC_ERR;
280     }
281     if (GetSessionConnById(channelId, conn) != SOFTBUS_OK) {
282         TRANS_LOGE(TRANS_BYTES, "Get SessionConn fail");
283         SoftBusFree(buffer);
284         SoftBusFree(conn);
285         return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED;
286     }
287     (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
288     int fd = conn->appInfo.fd;
289     SetIpTos(fd, FAST_MESSAGE_TOS);
290     if (ConnSendSocketData(fd, buffer, bufferLen, 0) != (int)bufferLen) {
291         SendFailToFlushDevice(conn);
292         SoftBusFree(buffer);
293         SoftBusFree(conn);
294         return SOFTBUS_TCP_SOCKET_ERR;
295     }
296     SoftBusFree(conn);
297     SoftBusFree(buffer);
298     return SOFTBUS_OK;
299 }
300 
GetChannelInfoFromConn(ChannelInfo * info,SessionConn * conn,int32_t channelId)301 static void GetChannelInfoFromConn(ChannelInfo *info, SessionConn *conn, int32_t channelId)
302 {
303     info->channelId = channelId;
304     info->channelType = CHANNEL_TYPE_TCP_DIRECT;
305     info->isServer = conn->serverSide;
306     info->isEnabled = true;
307     info->fd = conn->appInfo.fd;
308     info->sessionKey = conn->appInfo.sessionKey;
309     info->myHandleId = conn->appInfo.myHandleId;
310     info->peerHandleId = conn->appInfo.peerHandleId;
311     info->peerSessionName = conn->appInfo.peerData.sessionName;
312     info->groupId = conn->appInfo.groupId;
313     info->isEncrypt = true;
314     info->keyLen = SESSION_KEY_LENGTH;
315     info->peerUid = conn->appInfo.peerData.uid;
316     info->peerPid = conn->appInfo.peerData.pid;
317     info->routeType = conn->appInfo.routeType;
318     info->businessType = conn->appInfo.businessType;
319     info->autoCloseTime = conn->appInfo.autoCloseTime;
320     info->peerIp = conn->appInfo.peerData.addr;
321     info->peerPort = conn->appInfo.peerData.port;
322     info->linkType = conn->appInfo.linkType;
323     info->dataConfig = conn->appInfo.myData.dataConfig;
324 }
325 
GetServerSideIpInfo(const AppInfo * appInfo,char * ip,uint32_t len)326 static int32_t GetServerSideIpInfo(const AppInfo *appInfo, char *ip, uint32_t len)
327 {
328     char myIp[IP_LEN] = { 0 };
329     if (appInfo->routeType == WIFI_STA) {
330         if (LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, myIp, sizeof(myIp)) != SOFTBUS_OK) {
331             TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get local ip fail");
332             return SOFTBUS_TRANS_GET_LOCAL_IP_FAILED;
333         }
334     } else if (appInfo->routeType == WIFI_P2P) {
335         struct WifiDirectManager *mgr = GetWifiDirectManager();
336         if (mgr == NULL || mgr->getLocalIpByRemoteIp == NULL) {
337             TRANS_LOGE(TRANS_CTRL, "GetWifiDirectManager failed");
338             return SOFTBUS_WIFI_DIRECT_INIT_FAILED;
339         }
340 
341         int32_t ret = mgr->getLocalIpByRemoteIp(appInfo->peerData.addr, myIp, sizeof(myIp));
342         if (ret != SOFTBUS_OK) {
343             TRANS_LOGE(TRANS_CTRL, "get Local Ip fail, ret=%{public}d", ret);
344             return SOFTBUS_TRANS_GET_P2P_INFO_FAILED;
345         }
346 
347         if (LnnSetLocalStrInfo(STRING_KEY_P2P_IP, myIp) != SOFTBUS_OK) {
348             TRANS_LOGW(TRANS_CTRL, "ServerSide set local p2p ip fail");
349         }
350         if (LnnSetDLP2pIp(appInfo->peerData.deviceId, CATEGORY_UUID, appInfo->peerData.addr) != SOFTBUS_OK) {
351             TRANS_LOGW(TRANS_CTRL, "ServerSide set peer p2p ip fail");
352         }
353     }
354     if (strcpy_s(ip, len, myIp) != EOK) {
355         TRANS_LOGE(TRANS_CTRL, "copy str failed");
356         return SOFTBUS_STRCPY_ERR;
357     }
358     return SOFTBUS_OK;
359 }
360 
GetClientSideIpInfo(const AppInfo * appInfo,char * ip,uint32_t len)361 static int32_t GetClientSideIpInfo(const AppInfo *appInfo, char *ip, uint32_t len)
362 {
363     if (appInfo->routeType == WIFI_P2P) {
364         if (LnnSetLocalStrInfo(STRING_KEY_P2P_IP, appInfo->myData.addr) != SOFTBUS_OK) {
365             TRANS_LOGW(TRANS_CTRL, "Client set local p2p ip fail");
366         }
367         if (LnnSetDLP2pIp(appInfo->peerData.deviceId, CATEGORY_UUID, appInfo->peerData.addr) != SOFTBUS_OK) {
368             TRANS_LOGW(TRANS_CTRL, "Client set peer p2p ip fail");
369         }
370     }
371     if (strcpy_s(ip, len, appInfo->myData.addr) != EOK) {
372         TRANS_LOGE(TRANS_CTRL, "copy str failed");
373         return SOFTBUS_STRCPY_ERR;
374     }
375     return SOFTBUS_OK;
376 }
377 
NotifyChannelOpened(int32_t channelId)378 static int32_t NotifyChannelOpened(int32_t channelId)
379 {
380     SessionConn conn;
381     if (GetSessionConnById(channelId, &conn) != SOFTBUS_OK) {
382         TRANS_LOGE(TRANS_CTRL, "notify channel open failed, get tdcInfo is null");
383         return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED;
384     }
385     ChannelInfo info = { 0 };
386     GetChannelInfoFromConn(&info, &conn, channelId);
387     char myIp[IP_LEN] = { 0 };
388     int32_t ret = conn.serverSide ? GetServerSideIpInfo(&conn.appInfo, myIp, IP_LEN)
389                                   : GetClientSideIpInfo(&conn.appInfo, myIp, IP_LEN);
390     if (ret != SOFTBUS_OK) {
391         TRANS_LOGE(TRANS_CTRL, "get ip failed, ret = %{public}d.", ret);
392         (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
393         return ret;
394     }
395     info.myIp = myIp;
396 
397     char buf[NETWORK_ID_BUF_LEN] = { 0 };
398     ret = LnnGetNetworkIdByUuid(conn.appInfo.peerData.deviceId, buf, NETWORK_ID_BUF_LEN);
399     if (ret != SOFTBUS_OK) {
400         TRANS_LOGE(TRANS_CTRL, "get networkId failed, ret = %{public}d", ret);
401         (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
402         return ret;
403     }
404     info.peerDeviceId = buf;
405     info.timeStart = conn.appInfo.timeStart;
406     info.linkType = conn.appInfo.linkType;
407     info.connectType = conn.appInfo.connectType;
408     info.osType = conn.appInfo.osType;
409     char pkgName[PKG_NAME_SIZE_MAX] = { 0 };
410     ret = TransTdcGetPkgName(conn.appInfo.myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
411     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get pkg name fail.");
412 
413     int32_t uid = 0;
414     int32_t pid = 0;
415     if (TransTdcGetUidAndPid(conn.appInfo.myData.sessionName, &uid, &pid) != SOFTBUS_OK) {
416         TRANS_LOGE(TRANS_CTRL, "get uid and pid fail.");
417         (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
418         return SOFTBUS_TRANS_GET_PID_FAILED;
419     }
420     if (conn.appInfo.fastTransDataSize > 0) {
421         info.isFastData = true;
422     }
423     TransGetLaneIdByChannelId(channelId, &info.laneId);
424     GetOsTypeByNetworkId(info.peerDeviceId, &info.osType);
425     ret = TransTdcOnChannelOpened(pkgName, pid, conn.appInfo.myData.sessionName, &info);
426     (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
427     conn.status = TCP_DIRECT_CHANNEL_STATUS_CONNECTED;
428     SetSessionConnStatusById(channelId, conn.status);
429     return ret;
430 }
431 
NotifyChannelBind(int32_t channelId)432 static int32_t NotifyChannelBind(int32_t channelId)
433 {
434     SessionConn conn;
435     if (GetSessionConnById(channelId, &conn) != SOFTBUS_OK) {
436         TRANS_LOGE(TRANS_CTRL, "notify channel bind, get tdcInfo is null channelId=%{public}d", channelId);
437         return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED;
438     }
439     (void)memset_s(&conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
440 
441     char pkgName[PKG_NAME_SIZE_MAX] = {0};
442     int32_t ret = TransTdcGetPkgName(conn.appInfo.myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
443     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get pkg name fail.");
444 
445     ret = TransTdcOnChannelBind(pkgName, conn.appInfo.myData.pid, channelId);
446     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, ret=%{public}d", channelId, ret);
447     return ret;
448 }
449 
NotifyChannelClosed(const AppInfo * appInfo,int32_t channelId)450 static int32_t NotifyChannelClosed(const AppInfo *appInfo, int32_t channelId)
451 {
452     AppInfoData myData = appInfo->myData;
453     char pkgName[PKG_NAME_SIZE_MAX] = { 0 };
454     int32_t ret = TransTdcGetPkgName(myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
455     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get pkg name fail.");
456     ret = TransTdcOnChannelClosed(pkgName, myData.pid, channelId);
457     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, ret=%{public}d", channelId, ret);
458     return ret;
459 }
460 
NotifyChannelOpenFailedBySessionConn(const SessionConn * conn,int32_t errCode)461 int32_t NotifyChannelOpenFailedBySessionConn(const SessionConn *conn, int32_t errCode)
462 {
463     TRANS_CHECK_AND_RETURN_RET_LOGE(conn != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, "invalid param.");
464     int64_t timeStart = conn->appInfo.timeStart;
465     int64_t timeDiff = GetSoftbusRecordTimeMillis() - timeStart;
466     char localUdid[UDID_BUF_LEN] = { 0 };
467     (void)LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, sizeof(localUdid));
468     TransEventExtra extra = {
469         .calleePkg = NULL,
470         .callerPkg = conn->appInfo.myData.pkgName,
471         .channelId = conn->channelId,
472         .peerNetworkId = conn->appInfo.peerNetWorkId,
473         .socketName = conn->appInfo.myData.sessionName,
474         .linkType = conn->appInfo.connectType,
475         .costTime = timeDiff,
476         .errcode = errCode,
477         .osType = (conn->appInfo.osType < 0) ? UNKNOW_OS_TYPE : (conn->appInfo.osType),
478         .localUdid = localUdid,
479         .peerUdid = conn->appInfo.peerUdid,
480         .peerDevVer = conn->appInfo.peerVersion,
481         .result = EVENT_STAGE_RESULT_FAILED
482     };
483     extra.deviceState = TransGetDeviceState(conn->appInfo.peerNetWorkId);
484     int32_t sceneCommand = conn->serverSide ? EVENT_SCENE_OPEN_CHANNEL_SERVER : EVENT_SCENE_OPEN_CHANNEL;
485     TRANS_EVENT(sceneCommand, EVENT_STAGE_OPEN_CHANNEL_END, extra);
486     TransAlarmExtra extraAlarm = {
487         .conflictName = NULL,
488         .conflictedName = NULL,
489         .occupyedName = NULL,
490         .permissionName = NULL,
491         .linkType = conn->appInfo.linkType,
492         .errcode = errCode,
493         .sessionName = conn->appInfo.myData.sessionName,
494     };
495     TRANS_ALARM(OPEN_SESSION_FAIL_ALARM, CONTROL_ALARM_TYPE, extraAlarm);
496     SoftbusRecordOpenSessionKpi(conn->appInfo.myData.pkgName,
497         conn->appInfo.linkType, SOFTBUS_EVT_OPEN_SESSION_FAIL, timeDiff);
498     char pkgName[PKG_NAME_SIZE_MAX] = { 0 };
499     int32_t ret = TransTdcGetPkgName(conn->appInfo.myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
500     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get pkg name fail.");
501     if (!(conn->serverSide)) {
502         ret = TransTdcOnChannelOpenFailed(
503             conn->appInfo.myData.pkgName, conn->appInfo.myData.pid, conn->channelId, errCode);
504         TRANS_LOGW(TRANS_CTRL, "channelId=%{public}d, ret=%{public}d", conn->channelId, ret);
505         return ret;
506     }
507     return SOFTBUS_OK;
508 }
509 
NotifyChannelOpenFailed(int32_t channelId,int32_t errCode)510 int32_t NotifyChannelOpenFailed(int32_t channelId, int32_t errCode)
511 {
512     SessionConn conn;
513     if (GetSessionConnById(channelId, &conn) != SOFTBUS_OK) {
514         TRANS_LOGE(TRANS_CTRL, "notify channel open failed, get tdcInfo is null");
515         return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED;
516     }
517 
518     (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
519     return NotifyChannelOpenFailedBySessionConn(&conn, errCode);
520 }
521 
TransTdcPostFastData(SessionConn * conn)522 static int32_t TransTdcPostFastData(SessionConn *conn)
523 {
524     TRANS_LOGI(TRANS_CTRL, "enter.");
525     uint32_t outLen;
526     char *buf = TransTdcPackFastData(&(conn->appInfo), &outLen);
527     if (buf == NULL) {
528         TRANS_LOGE(TRANS_CTRL, "failed to pack bytes.");
529         return SOFTBUS_ENCRYPT_ERR;
530     }
531     if (outLen != conn->appInfo.fastTransDataSize + FAST_TDC_EXT_DATA_SIZE) {
532         TRANS_LOGE(TRANS_CTRL, "pack bytes len error, outLen=%{public}d", outLen);
533         SoftBusFree(buf);
534         return SOFTBUS_ENCRYPT_ERR;
535     }
536     uint32_t tos = (conn->appInfo.businessType == BUSINESS_TYPE_BYTE) ? FAST_BYTE_TOS : FAST_MESSAGE_TOS;
537     if (SetIpTos(conn->appInfo.fd, tos) != SOFTBUS_OK) {
538         SoftBusFree(buf);
539         return SOFTBUS_TCP_SOCKET_ERR;
540     }
541     ssize_t ret = ConnSendSocketData(conn->appInfo.fd, buf, outLen, 0);
542     if (ret != (ssize_t)outLen) {
543         TRANS_LOGE(TRANS_CTRL, "failed to send tcp data. ret=%{public}zd", ret);
544         SoftBusFree(buf);
545         return SOFTBUS_TRANS_SEND_TCP_DATA_FAILED;
546     }
547     SoftBusFree(buf);
548     buf = NULL;
549     return SOFTBUS_OK;
550 }
551 
552 static const ConfigTypeMap g_configTypeMap[] = {
553     {CHANNEL_TYPE_TCP_DIRECT, BUSINESS_TYPE_BYTE, SOFTBUS_INT_MAX_BYTES_NEW_LENGTH},
554     {CHANNEL_TYPE_TCP_DIRECT, BUSINESS_TYPE_MESSAGE, SOFTBUS_INT_MAX_MESSAGE_NEW_LENGTH},
555 };
556 
FindConfigType(int32_t channelType,int32_t businessType)557 static int32_t FindConfigType(int32_t channelType, int32_t businessType)
558 {
559     for (uint32_t i = 0; i < sizeof(g_configTypeMap) / sizeof(ConfigTypeMap); i++) {
560         if ((g_configTypeMap[i].channelType == channelType) &&
561             (g_configTypeMap[i].businessType == businessType)) {
562             return g_configTypeMap[i].configType;
563         }
564     }
565     return SOFTBUS_CONFIG_TYPE_MAX;
566 }
567 
TransGetLocalConfig(int32_t channelType,int32_t businessType,uint32_t * len)568 static int32_t TransGetLocalConfig(int32_t channelType, int32_t businessType, uint32_t *len)
569 {
570     ConfigType configType = (ConfigType)FindConfigType(channelType, businessType);
571     if (configType == SOFTBUS_CONFIG_TYPE_MAX) {
572         TRANS_LOGE(TRANS_CTRL, "Invalid channelType=%{public}d, businessType=%{public}d",
573             channelType, businessType);
574         return SOFTBUS_INVALID_PARAM;
575     }
576     uint32_t maxLen;
577     if (SoftbusGetConfig(configType, (unsigned char *)&maxLen, sizeof(maxLen)) != SOFTBUS_OK) {
578         TRANS_LOGE(TRANS_CTRL, "get config failed, configType=%{public}d.", configType);
579         return SOFTBUS_GET_CONFIG_VAL_ERR;
580     }
581 
582     *len = maxLen;
583     TRANS_LOGI(TRANS_CTRL, "get local config len=%{public}d.", *len);
584     return SOFTBUS_OK;
585 }
586 
TransTdcProcessDataConfig(AppInfo * appInfo)587 static int32_t TransTdcProcessDataConfig(AppInfo *appInfo)
588 {
589     if (appInfo == NULL) {
590         TRANS_LOGE(TRANS_CTRL, "appInfo is null");
591         return SOFTBUS_INVALID_PARAM;
592     }
593     if (appInfo->businessType != BUSINESS_TYPE_MESSAGE && appInfo->businessType != BUSINESS_TYPE_BYTE) {
594         TRANS_LOGI(TRANS_CTRL, "invalid businessType=%{public}d", appInfo->businessType);
595         return SOFTBUS_OK;
596     }
597     if (appInfo->peerData.dataConfig != 0) {
598         appInfo->myData.dataConfig = MIN(appInfo->myData.dataConfig, appInfo->peerData.dataConfig);
599         TRANS_LOGI(TRANS_CTRL, "process dataConfig succ. dataConfig=%{public}u", appInfo->myData.dataConfig);
600         return SOFTBUS_OK;
601     }
602     ConfigType configType = appInfo->businessType == BUSINESS_TYPE_BYTE ?
603         SOFTBUS_INT_MAX_BYTES_LENGTH : SOFTBUS_INT_MAX_MESSAGE_LENGTH;
604     int32_t ret = SoftbusGetConfig(configType, (unsigned char *)&appInfo->myData.dataConfig,
605         sizeof(appInfo->myData.dataConfig));
606     if (ret != SOFTBUS_OK) {
607         TRANS_LOGE(TRANS_CTRL, "get config failed, configType=%{public}d", configType);
608         return ret;
609     }
610     TRANS_LOGI(TRANS_CTRL, "process dataConfig=%{public}d", appInfo->myData.dataConfig);
611     return SOFTBUS_OK;
612 }
613 
614 // the channel open failed while be notified when function OpenDataBusReply return ERR
OpenDataBusReply(int32_t channelId,uint64_t seq,const cJSON * reply)615 static int32_t OpenDataBusReply(int32_t channelId, uint64_t seq, const cJSON *reply)
616 {
617     (void)seq;
618     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, seq=%{public}" PRIu64, channelId, seq);
619     SessionConn conn;
620     (void)memset_s(&conn, sizeof(SessionConn), 0, sizeof(SessionConn));
621     TRANS_CHECK_AND_RETURN_RET_LOGE(GetSessionConnById(channelId, &conn) == SOFTBUS_OK,
622         SOFTBUS_TRANS_GET_SESSION_CONN_FAILED, TRANS_CTRL, "notify channel open failed, get tdcInfo is null");
623     int32_t errCode = SOFTBUS_OK;
624     if (UnpackReplyErrCode(reply, &errCode) == SOFTBUS_OK) {
625         TRANS_LOGE(TRANS_CTRL,
626             "receive err reply msg channelId=%{public}d, errCode=%{public}d, seq=%{public}" PRIu64,
627             channelId, errCode, seq);
628         return errCode;
629     }
630 
631     uint16_t fastDataSize = 0;
632     TRANS_CHECK_AND_RETURN_RET_LOGE(UnpackReply(reply, &conn.appInfo, &fastDataSize) == SOFTBUS_OK,
633         SOFTBUS_TRANS_UNPACK_REPLY_FAILED, TRANS_CTRL, "UnpackReply failed");
634 
635     int32_t ret = TransTdcProcessDataConfig(&conn.appInfo);
636     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "Trans Tdc process data config failed.");
637 
638     ret = SetAppInfoById(channelId, &conn.appInfo);
639     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "set app info by id failed.");
640 
641     if ((fastDataSize > 0 && (conn.appInfo.fastTransDataSize == fastDataSize)) || conn.appInfo.fastTransDataSize == 0) {
642         ret = NotifyChannelOpened(channelId);
643         (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
644         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "notify channel open failed");
645     } else {
646         ret = TransTdcPostFastData(&conn);
647         (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
648         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "tdc send fast data failed");
649         ret = NotifyChannelOpened(channelId);
650         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "notify channel open failed");
651     }
652     TransEventExtra extra = {
653         .socketName = NULL,
654         .peerNetworkId = NULL,
655         .calleePkg = NULL,
656         .callerPkg = NULL,
657         .channelId = channelId,
658         .result = EVENT_STAGE_RESULT_OK
659     };
660     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_HANDSHAKE_REPLY, extra);
661     TRANS_LOGD(TRANS_CTRL, "ok");
662     return SOFTBUS_OK;
663 }
664 
TransTdcPostReplyMsg(int32_t channelId,uint64_t seq,uint32_t flags,char * reply)665 static inline int32_t TransTdcPostReplyMsg(int32_t channelId, uint64_t seq, uint32_t flags, char *reply)
666 {
667     TdcPacketHead packetHead = {
668         .magicNumber = MAGIC_NUMBER,
669         .module = MODULE_SESSION,
670         .seq = seq,
671         .flags = (FLAG_REPLY | flags),
672         .dataLen = strlen(reply),
673     };
674     return TransTdcPostBytes(channelId, &packetHead, reply);
675 }
676 
OpenDataBusRequestReply(const AppInfo * appInfo,int32_t channelId,uint64_t seq,uint32_t flags)677 static int32_t OpenDataBusRequestReply(const AppInfo *appInfo, int32_t channelId, uint64_t seq, uint32_t flags)
678 {
679     char *reply = PackReply(appInfo);
680     if (reply == NULL) {
681         TRANS_LOGE(TRANS_CTRL, "get pack reply err");
682         return SOFTBUS_TRANS_GET_PACK_REPLY_FAILED;
683     }
684 
685     int32_t ret = TransTdcPostReplyMsg(channelId, seq, flags, reply);
686     cJSON_free(reply);
687     return ret;
688 }
689 
OpenDataBusRequestError(int32_t channelId,uint64_t seq,char * errDesc,int32_t errCode,uint32_t flags)690 static int32_t OpenDataBusRequestError(int32_t channelId, uint64_t seq, char *errDesc, int32_t errCode, uint32_t flags)
691 {
692     char *reply = PackError(errCode, errDesc);
693     if (reply == NULL) {
694         TRANS_LOGE(TRANS_CTRL, "get pack reply err");
695         return SOFTBUS_TRANS_GET_PACK_REPLY_FAILED;
696     }
697 
698     int32_t ret = TransTdcPostReplyMsg(channelId, seq, flags, reply);
699     cJSON_free(reply);
700     return ret;
701 }
702 
GetUuidByChanId(int32_t channelId,char * uuid,uint32_t len)703 static int32_t GetUuidByChanId(int32_t channelId, char *uuid, uint32_t len)
704 {
705     int64_t authId = GetAuthIdByChanId(channelId);
706     if (authId == AUTH_INVALID_ID) {
707         TRANS_LOGE(TRANS_CTRL, "get authId fail");
708         return SOFTBUS_TRANS_GET_AUTH_ID_FAILED;
709     }
710     return AuthGetDeviceUuid(authId, uuid, len);
711 }
712 
OpenDataBusRequestOutSessionName(const char * mySessionName,const char * peerSessionName)713 static void OpenDataBusRequestOutSessionName(const char *mySessionName, const char *peerSessionName)
714 {
715     char *tmpMyName = NULL;
716     char *tmpPeerName = NULL;
717     Anonymize(mySessionName, &tmpMyName);
718     Anonymize(peerSessionName, &tmpPeerName);
719     TRANS_LOGI(TRANS_CTRL, "OpenDataBusRequest: mySessionName=%{public}s, peerSessionName=%{public}s",
720         tmpMyName, tmpPeerName);
721     AnonymizeFree(tmpMyName);
722     AnonymizeFree(tmpPeerName);
723 }
724 
GetSessionConnFromDataBusRequest(int32_t channelId,const cJSON * request)725 static SessionConn* GetSessionConnFromDataBusRequest(int32_t channelId, const cJSON *request)
726 {
727     SessionConn *conn = (SessionConn *)SoftBusCalloc(sizeof(SessionConn));
728     if (conn == NULL) {
729         return NULL;
730     }
731     if (GetSessionConnById(channelId, conn) != SOFTBUS_OK) {
732         SoftBusFree(conn);
733         return NULL;
734     }
735     if (UnpackRequest(request, &conn->appInfo) != SOFTBUS_OK) {
736         (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
737         SoftBusFree(conn);
738         TRANS_LOGE(TRANS_CTRL, "UnpackRequest error");
739         return NULL;
740     }
741     return conn;
742 }
743 
NotifyFastDataRecv(SessionConn * conn,int32_t channelId)744 static void NotifyFastDataRecv(SessionConn *conn, int32_t channelId)
745 {
746     TRANS_LOGI(TRANS_CTRL, "enter.");
747     TransReceiveData receiveData;
748     receiveData.data = (void*)conn->appInfo.fastTransData;
749     receiveData.dataLen = conn->appInfo.fastTransDataSize + FAST_TDC_EXT_DATA_SIZE;
750     if (conn->appInfo.businessType == BUSINESS_TYPE_MESSAGE) {
751         receiveData.dataType = TRANS_SESSION_MESSAGE;
752     } else {
753         receiveData.dataType = TRANS_SESSION_BYTES;
754     }
755     if (TransTdcOnMsgReceived(conn->appInfo.myData.pkgName, conn->appInfo.myData.pid,
756         channelId, &receiveData) != SOFTBUS_OK) {
757         conn->appInfo.fastTransDataSize = 0;
758         TRANS_LOGE(TRANS_CTRL, "err");
759         return;
760     }
761     TRANS_LOGD(TRANS_CTRL, "ok");
762     return;
763 }
764 
TransTdcFillDataConfig(AppInfo * appInfo)765 static int32_t TransTdcFillDataConfig(AppInfo *appInfo)
766 {
767     if (appInfo == NULL) {
768         TRANS_LOGE(TRANS_CTRL, "appInfo is null");
769         return SOFTBUS_INVALID_PARAM;
770     }
771     if (appInfo->businessType != BUSINESS_TYPE_BYTE && appInfo->businessType != BUSINESS_TYPE_MESSAGE) {
772         TRANS_LOGI(TRANS_CTRL, "invalid businessType=%{public}d", appInfo->businessType);
773         return SOFTBUS_OK;
774     }
775     if (appInfo->peerData.dataConfig != 0) {
776         uint32_t localDataConfig = 0;
777         int32_t ret = TransGetLocalConfig(CHANNEL_TYPE_TCP_DIRECT, appInfo->businessType, &localDataConfig);
778         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get local config fail");
779         appInfo->myData.dataConfig = MIN(localDataConfig, appInfo->peerData.dataConfig);
780         TRANS_LOGI(TRANS_CTRL, "fill dataConfig succ. dataConfig=%{public}u", appInfo->myData.dataConfig);
781         return SOFTBUS_OK;
782     }
783     ConfigType configType = appInfo->businessType == BUSINESS_TYPE_BYTE ?
784         SOFTBUS_INT_MAX_BYTES_LENGTH : SOFTBUS_INT_MAX_MESSAGE_LENGTH;
785     int32_t ret = SoftbusGetConfig(configType, (unsigned char *)&appInfo->myData.dataConfig,
786         sizeof(appInfo->myData.dataConfig));
787     if (ret != SOFTBUS_OK) {
788         TRANS_LOGE(TRANS_CTRL, "get config failed, configType=%{public}d", configType);
789         return ret;
790     }
791     TRANS_LOGI(TRANS_CTRL, "fill dataConfig=%{public}d", appInfo->myData.dataConfig);
792     return SOFTBUS_OK;
793 }
794 
IsMetaSession(const char * sessionName)795 static bool IsMetaSession(const char *sessionName)
796 {
797     if (strlen(sessionName) < MIN_META_LEN || strncmp(sessionName, META_SESSION, MIN_META_LEN)) {
798         return false;
799     }
800     return true;
801 }
802 
ReleaseSessionConn(SessionConn * chan)803 static void ReleaseSessionConn(SessionConn *chan)
804 {
805     if (chan == NULL) {
806         return;
807     }
808     if (chan->appInfo.fastTransData != NULL) {
809         SoftBusFree((void*)chan->appInfo.fastTransData);
810     }
811     SoftBusFree(chan);
812 }
813 
ReportTransEventExtra(TransEventExtra * extra,int32_t channelId,SessionConn * conn,NodeInfo * nodeInfo,char * peerUuid)814 static void ReportTransEventExtra(
815     TransEventExtra *extra, int32_t channelId, SessionConn *conn, NodeInfo *nodeInfo, char *peerUuid)
816 {
817     extra->socketName = conn->appInfo.myData.sessionName;
818     extra->calleePkg = NULL;
819     extra->callerPkg = NULL;
820     extra->channelId = channelId;
821     extra->peerChannelId = conn->appInfo.peerData.channelId;
822     extra->socketFd = conn->appInfo.fd;
823     extra->result = EVENT_STAGE_RESULT_OK;
824     bool peerRet = GetUuidByChanId(channelId, peerUuid, DEVICE_ID_SIZE_MAX) == SOFTBUS_OK &&
825         LnnGetRemoteNodeInfoById(peerUuid, CATEGORY_UUID, nodeInfo) == SOFTBUS_OK;
826     if (peerRet) {
827         extra->peerUdid = nodeInfo->deviceInfo.deviceUdid;
828         extra->peerDevVer = nodeInfo->deviceInfo.deviceVersion;
829     }
830     if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, nodeInfo->masterUdid, UDID_BUF_LEN) == SOFTBUS_OK) {
831         extra->localUdid = nodeInfo->masterUdid;
832     }
833     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL_SERVER, EVENT_STAGE_HANDSHAKE_START, *extra);
834 }
835 
CheckServerPermission(AppInfo * appInfo,char * ret)836 static int32_t CheckServerPermission(AppInfo *appInfo, char *ret)
837 {
838     if (appInfo->callingTokenId != TOKENID_NOT_SET &&
839         TransCheckServerAccessControl(appInfo->callingTokenId) != SOFTBUS_OK) {
840         ret = (char *)"Server check acl failed";
841         return SOFTBUS_TRANS_CHECK_ACL_FAILED;
842     }
843 
844     if (CheckSecLevelPublic(appInfo->myData.sessionName, appInfo->peerData.sessionName) != SOFTBUS_OK) {
845         ret = (char *)"Server check session name failed";
846         return SOFTBUS_PERMISSION_SERVER_DENIED;
847     }
848 
849     return SOFTBUS_OK;
850 }
851 
TransTdcFillAppInfoAndNotifyChannel(AppInfo * appInfo,int32_t channelId,char * errDesc)852 static int32_t TransTdcFillAppInfoAndNotifyChannel(AppInfo *appInfo, int32_t channelId, char *errDesc)
853 {
854     char *ret = NULL;
855     int32_t errCode = SOFTBUS_OK;
856     errCode = CheckServerPermission(appInfo, ret);
857     if (errCode != SOFTBUS_OK) {
858         goto ERR_EXIT;
859     }
860 
861     if (TransTdcGetUidAndPid(appInfo->myData.sessionName, &appInfo->myData.uid, &appInfo->myData.pid) != SOFTBUS_OK) {
862         errCode = SOFTBUS_TRANS_PEER_SESSION_NOT_CREATED;
863         ret = (char *)"Peer Device Session Not Create";
864         goto ERR_EXIT;
865     }
866 
867     errCode = GetUuidByChanId(channelId, appInfo->peerData.deviceId, DEVICE_ID_SIZE_MAX);
868     if (errCode != SOFTBUS_OK) {
869         TRANS_LOGE(TRANS_CTRL, "Auth: Get Uuid By ChanId failed.");
870         ret = (char *)"Get Uuid By ChanId failed";
871         goto ERR_EXIT;
872     }
873 
874     errCode = TransTdcFillDataConfig(appInfo);
875     if (errCode != SOFTBUS_OK) {
876         TRANS_LOGE(TRANS_CTRL, "fill data config failed.");
877         ret = (char *)"fill data config failed";
878         goto ERR_EXIT;
879     }
880     appInfo->myHandleId = 0;
881     errCode = SetAppInfoById(channelId, appInfo);
882     if (errCode != SOFTBUS_OK) {
883         TRANS_LOGE(TRANS_CTRL, "set app info by id failed.");
884         ret = (char *)"Set App Info By Id Failed";
885         goto ERR_EXIT;
886     }
887 
888     OpenDataBusRequestOutSessionName(appInfo->myData.sessionName, appInfo->peerData.sessionName);
889     TRANS_LOGI(TRANS_CTRL, "OpenDataBusRequest: myPid=%{public}d, peerPid=%{public}d",
890         appInfo->myData.pid, appInfo->peerData.pid);
891 
892     errCode = NotifyChannelOpened(channelId);
893     if (errCode != SOFTBUS_OK) {
894         TRANS_LOGE(TRANS_CTRL, "Notify App Channel Opened Failed");
895         ret = (char *)"Notify App Channel Opened Failed";
896         goto ERR_EXIT;
897     }
898 
899     return SOFTBUS_OK;
900 ERR_EXIT:
901     if (strcpy_s(errDesc, MAX_ERRDESC_LEN, ret) != EOK) {
902         TRANS_LOGW(TRANS_CTRL, "strcpy failed");
903     }
904     return errCode;
905 }
906 
HandleDataBusReply(SessionConn * conn,int32_t channelId,TransEventExtra * extra,uint32_t flags,uint64_t seq)907 static int32_t HandleDataBusReply(
908     SessionConn *conn, int32_t channelId, TransEventExtra *extra, uint32_t flags, uint64_t seq)
909 {
910     int32_t ret = OpenDataBusRequestReply(&conn->appInfo, channelId, seq, flags);
911     if (ret != SOFTBUS_OK) {
912         TRANS_LOGE(TRANS_CTRL, "OpenDataBusRequest reply err");
913         (void)NotifyChannelClosed(&conn->appInfo, channelId);
914         return ret;
915     } else {
916         extra->result = EVENT_STAGE_RESULT_OK;
917         TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL_SERVER, EVENT_STAGE_HANDSHAKE_REPLY, *extra);
918     }
919 
920     if (conn->appInfo.routeType == WIFI_P2P) {
921         if (LnnGetNetworkIdByUuid(conn->appInfo.peerData.deviceId,
922             conn->appInfo.peerNetWorkId, DEVICE_ID_SIZE_MAX) == SOFTBUS_OK) {
923             LaneUpdateP2pAddressByIp(conn->appInfo.peerData.addr, conn->appInfo.peerNetWorkId);
924         }
925     }
926     return SOFTBUS_OK;
927 }
928 
OpenDataBusRequest(int32_t channelId,uint32_t flags,uint64_t seq,const cJSON * request)929 static int32_t OpenDataBusRequest(int32_t channelId, uint32_t flags, uint64_t seq, const cJSON *request)
930 {
931     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, seq=%{public}" PRIu64, channelId, seq);
932     SessionConn *conn = GetSessionConnFromDataBusRequest(channelId, request);
933     TRANS_CHECK_AND_RETURN_RET_LOGE(conn != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, "conn is null");
934 
935     TransEventExtra extra;
936     char peerUuid[DEVICE_ID_SIZE_MAX] = { 0 };
937     NodeInfo nodeInfo;
938     (void)memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
939     ReportTransEventExtra(&extra, channelId, conn, &nodeInfo, peerUuid);
940 
941     if ((flags & FLAG_AUTH_META) != 0 && !IsMetaSession(conn->appInfo.myData.sessionName)) {
942         char *tmpName = NULL;
943         Anonymize(conn->appInfo.myData.sessionName, &tmpName);
944         TRANS_LOGI(TRANS_CTRL,
945             "Request denied: session is not a meta session. sessionName=%{public}s", tmpName);
946         AnonymizeFree(tmpName);
947         (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
948         ReleaseSessionConn(conn);
949         return SOFTBUS_TRANS_NOT_META_SESSION;
950     }
951     char errDesc[MAX_ERRDESC_LEN] = { 0 };
952     int32_t errCode = TransTdcFillAppInfoAndNotifyChannel(&conn->appInfo, channelId, errDesc);
953     if (errCode != SOFTBUS_OK) {
954         if (OpenDataBusRequestError(channelId, seq, errDesc, errCode, flags) != SOFTBUS_OK) {
955             TRANS_LOGE(TRANS_CTRL, "OpenDataBusRequestError error");
956         }
957         (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
958         ReleaseSessionConn(conn);
959         return errCode;
960     }
961 
962     if (conn->appInfo.fastTransDataSize > 0 && conn->appInfo.fastTransData != NULL) {
963         NotifyFastDataRecv(conn, channelId);
964     }
965 
966     errCode = HandleDataBusReply(conn, channelId, &extra, flags, seq);
967     if (errCode != SOFTBUS_OK) {
968         (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
969         (void)TransDelTcpChannelInfoByChannelId(channelId);
970         ReleaseSessionConn(conn);
971         return errCode;
972     }
973 
974     errCode = NotifyChannelBind(channelId);
975     (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
976     if (errCode != SOFTBUS_OK) {
977         (void)TransDelTcpChannelInfoByChannelId(channelId);
978     }
979     ReleaseSessionConn(conn);
980     return errCode;
981 }
982 
ProcessMessage(int32_t channelId,uint32_t flags,uint64_t seq,const char * msg)983 static int32_t ProcessMessage(int32_t channelId, uint32_t flags, uint64_t seq, const char *msg)
984 {
985     int32_t ret;
986     cJSON *json = cJSON_Parse(msg);
987     if (json == NULL) {
988         TRANS_LOGE(TRANS_CTRL, "json parse failed.");
989         return SOFTBUS_PARSE_JSON_ERR;
990     }
991     if (flags & FLAG_REPLY) {
992         ret = OpenDataBusReply(channelId, seq, json);
993     } else {
994         ret = OpenDataBusRequest(channelId, flags, seq, json);
995     }
996     cJSON_Delete(json);
997     AppInfo appInfo;
998     TRANS_CHECK_AND_RETURN_RET_LOGE(GetAppInfoById(channelId, &appInfo) == SOFTBUS_OK, ret,
999         TRANS_CTRL, "get appInfo fail");
1000     char *tmpNetWorkId = NULL;
1001     char *tmpUdid = NULL;
1002     Anonymize(appInfo.peerNetWorkId, &tmpNetWorkId);
1003     Anonymize(appInfo.peerUdid, &tmpUdid);
1004     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, peerNetWorkId=%{public}s, peerUdid=%{public}s, ret=%{public}d",
1005         channelId, tmpNetWorkId, tmpUdid, ret);
1006     AnonymizeFree(tmpNetWorkId);
1007     AnonymizeFree(tmpUdid);
1008     return ret;
1009 }
1010 
TransSrvGetDataBufNodeById(int32_t channelId)1011 static ServerDataBuf *TransSrvGetDataBufNodeById(int32_t channelId)
1012 {
1013     if (g_tcpSrvDataList ==  NULL) {
1014         return NULL;
1015     }
1016 
1017     ServerDataBuf *item = NULL;
1018     LIST_FOR_EACH_ENTRY(item, &(g_tcpSrvDataList->list), ServerDataBuf, node) {
1019         if (item->channelId == channelId) {
1020             return item;
1021         }
1022     }
1023     TRANS_LOGE(TRANS_CTRL, "srv tcp direct channelId=%{public}d not exist.", channelId);
1024     return NULL;
1025 }
1026 
GetAuthIdByChannelInfo(int32_t channelId,uint64_t seq,uint32_t cipherFlag,AuthHandle * authHandle)1027 static int32_t GetAuthIdByChannelInfo(int32_t channelId, uint64_t seq, uint32_t cipherFlag, AuthHandle *authHandle)
1028 {
1029     if (authHandle == NULL) {
1030         TRANS_LOGE(TRANS_CTRL, "authHandle is null");
1031         return SOFTBUS_INVALID_PARAM;
1032     }
1033     if (GetAuthHandleByChanId(channelId, authHandle) == SOFTBUS_OK && authHandle->authId != AUTH_INVALID_ID) {
1034         TRANS_LOGI(TRANS_CTRL, "authId=%{public}" PRId64 " is not AUTH_INVALID_ID", authHandle->authId);
1035         return SOFTBUS_OK;
1036     }
1037 
1038     AppInfo appInfo;
1039     int32_t ret = GetAppInfoById(channelId, &appInfo);
1040     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get appInfo fail");
1041 
1042     bool fromAuthServer = ((seq & AUTH_CONN_SERVER_SIDE) != 0);
1043     char uuid[UUID_BUF_LEN] = {0};
1044     struct WifiDirectManager *mgr = GetWifiDirectManager();
1045     if (mgr == NULL || mgr->getRemoteUuidByIp == NULL) {
1046         TRANS_LOGE(TRANS_CTRL, "GetWifiDirectManager failed");
1047         return SOFTBUS_WIFI_DIRECT_INIT_FAILED;
1048     }
1049     ret = mgr->getRemoteUuidByIp(appInfo.peerData.addr, uuid, sizeof(uuid));
1050     (void)memset_s(appInfo.sessionKey, sizeof(appInfo.sessionKey), 0, sizeof(appInfo.sessionKey));
1051     if (ret != SOFTBUS_OK) {
1052         AuthConnInfo connInfo;
1053         connInfo.type = AUTH_LINK_TYPE_WIFI;
1054         if (strcpy_s(connInfo.info.ipInfo.ip, IP_LEN, appInfo.peerData.addr) != EOK) {
1055             TRANS_LOGE(TRANS_CTRL, "copy ip addr fail");
1056             return SOFTBUS_MEM_ERR;
1057         }
1058         char *tmpPeerIp = NULL;
1059         Anonymize(appInfo.peerData.addr, &tmpPeerIp);
1060         TRANS_LOGE(TRANS_CTRL, "channelId=%{public}d get remote uuid by Ip=%{public}s failed", channelId, tmpPeerIp);
1061         AnonymizeFree(tmpPeerIp);
1062         authHandle->type = connInfo.type;
1063         authHandle->authId = AuthGetIdByConnInfo(&connInfo, !fromAuthServer, false);
1064         return SOFTBUS_OK;
1065     }
1066 
1067     AuthLinkType linkType = SwitchCipherTypeToAuthLinkType(cipherFlag);
1068     TRANS_LOGI(TRANS_CTRL, "get auth linkType=%{public}d, flag=0x%{public}x", linkType, cipherFlag);
1069     bool isAuthMeta = (cipherFlag & FLAG_AUTH_META) ? true : false;
1070     authHandle->type = linkType;
1071     authHandle->authId = AuthGetIdByUuid(uuid, linkType, !fromAuthServer, isAuthMeta);
1072     return SOFTBUS_OK;
1073 }
1074 
DecryptMessage(int32_t channelId,const TdcPacketHead * pktHead,const uint8_t * pktData,uint8_t ** outData,uint32_t * outDataLen)1075 static int32_t DecryptMessage(int32_t channelId, const TdcPacketHead *pktHead, const uint8_t *pktData,
1076     uint8_t **outData, uint32_t *outDataLen)
1077 {
1078     AuthHandle authHandle = { .authId = AUTH_INVALID_ID };
1079     int32_t ret = GetAuthIdByChannelInfo(channelId, pktHead->seq, pktHead->flags, &authHandle);
1080     if (ret != SOFTBUS_OK || (authHandle.authId == AUTH_INVALID_ID && pktHead->flags == FLAG_P2P)) {
1081         TRANS_LOGW(TRANS_CTRL, "get p2p authId fail, peer device may be legacyOs, retry hml");
1082         // we don't know peer device is legacyOs or not, so retry hml when flag is p2p and get auth failed
1083         ret = GetAuthIdByChannelInfo(channelId, pktHead->seq, FLAG_ENHANCE_P2P, &authHandle);
1084     }
1085     if (ret != SOFTBUS_OK || authHandle.authId == AUTH_INVALID_ID) {
1086         TRANS_LOGE(TRANS_CTRL, "srv process recv data: get authId fail.");
1087         return SOFTBUS_NOT_FIND;
1088     }
1089     ret = SetAuthHandleByChanId(channelId, &authHandle);
1090     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "srv process recv data: set authId fail.");
1091 
1092     uint32_t decDataLen = AuthGetDecryptSize(pktHead->dataLen) + 1;
1093     uint8_t *decData = (uint8_t *)SoftBusCalloc(decDataLen);
1094     if (decData == NULL) {
1095         TRANS_LOGE(TRANS_CTRL, "srv process recv data: malloc fail.");
1096         return SOFTBUS_MALLOC_ERR;
1097     }
1098     if (AuthDecrypt(&authHandle, pktData, pktHead->dataLen, decData, &decDataLen) != SOFTBUS_OK) {
1099         TRANS_LOGE(TRANS_CTRL, "srv process recv data: decrypt fail.");
1100         SoftBusFree(decData);
1101         return SOFTBUS_DECRYPT_ERR;
1102     }
1103     *outData = decData;
1104     *outDataLen = decDataLen;
1105     return SOFTBUS_OK;
1106 }
1107 
ProcessReceivedData(int32_t channelId,int32_t type)1108 static int32_t ProcessReceivedData(int32_t channelId, int32_t type)
1109 {
1110     uint64_t seq;
1111     uint32_t flags;
1112     uint8_t *data = NULL;
1113     uint32_t dataLen = 0;
1114 
1115     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
1116         TRANS_LOGE(TRANS_CTRL, "lock failed.");
1117         return SOFTBUS_LOCK_ERR;
1118     }
1119     ServerDataBuf *node = TransSrvGetDataBufNodeById(channelId);
1120     if (node == NULL || node->data == NULL) {
1121         TRANS_LOGE(TRANS_CTRL, "node is null.");
1122         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1123         return SOFTBUS_TRANS_NODE_IS_NULL;
1124     }
1125     TdcPacketHead *pktHead = (TdcPacketHead *)(node->data);
1126     uint8_t *pktData = (uint8_t *)(node->data + sizeof(TdcPacketHead));
1127     if (pktHead->module != MODULE_SESSION) {
1128         TRANS_LOGE(TRANS_CTRL, "srv process recv data: illegal module.");
1129         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1130         return SOFTBUS_TRANS_ILLEGAL_MODULE;
1131     }
1132     seq = pktHead->seq;
1133     flags = pktHead->flags;
1134 
1135     TRANS_LOGI(TRANS_CTRL,
1136         "recv tdc packet. channelId=%{public}d, flags=%{public}d, seq=%{public}" PRIu64,
1137         channelId, flags, seq);
1138     if (DecryptMessage(channelId, pktHead, pktData, &data, &dataLen) != SOFTBUS_OK) {
1139         TRANS_LOGE(TRANS_CTRL, "srv process recv data: decrypt fail.");
1140         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1141         return SOFTBUS_DECRYPT_ERR;
1142     }
1143 
1144     char *end = node->data + sizeof(TdcPacketHead) + pktHead->dataLen;
1145     if (memmove_s(node->data, node->size, end, node->w - end) != EOK) {
1146         SoftBusFree(data);
1147         TRANS_LOGE(TRANS_CTRL, "memmove fail.");
1148         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1149         return SOFTBUS_MEM_ERR;
1150     }
1151     node->w = node->w - sizeof(TdcPacketHead) - pktHead->dataLen;
1152     SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1153 
1154     int32_t ret = ProcessMessage(channelId, flags, seq, (char *)data);
1155     SoftBusFree(data);
1156     return ret;
1157 }
1158 
TransTdcSrvProcData(ListenerModule module,int32_t channelId,int32_t type)1159 static int32_t TransTdcSrvProcData(ListenerModule module, int32_t channelId, int32_t type)
1160 {
1161     TRANS_CHECK_AND_RETURN_RET_LOGE(g_tcpSrvDataList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_tcpSrvDataList is NULL");
1162     int32_t ret = SoftBusMutexLock(&g_tcpSrvDataList->lock);
1163     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock failed.");
1164 
1165     ServerDataBuf *node = TransSrvGetDataBufNodeById(channelId);
1166     if (node == NULL) {
1167         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1168         TRANS_LOGE(TRANS_CTRL,
1169             "srv can not get buf node. listenerModule=%{public}d, "
1170             "channelId=%{public}d, type=%{public}d", (int32_t)module, channelId, type);
1171         return SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED;
1172     }
1173 
1174     uint32_t bufLen = node->w - node->data;
1175     if (bufLen < DC_MSG_PACKET_HEAD_SIZE) {
1176         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1177         TRANS_LOGE(TRANS_CTRL,
1178             "srv head not enough, recv next time. listenerModule=%{public}d, bufLen=%{public}u "
1179             "channelId=%{public}d, type=%{public}d", (int32_t)module, bufLen, channelId, type);
1180         return SOFTBUS_DATA_NOT_ENOUGH;
1181     }
1182 
1183     TdcPacketHead *pktHead = (TdcPacketHead *)(node->data);
1184     UnpackTdcPacketHead(pktHead);
1185     if (pktHead->magicNumber != MAGIC_NUMBER) {
1186         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1187         TRANS_LOGE(TRANS_CTRL,
1188             "srv recv invalid packet head listenerModule=%{public}d, "
1189             "channelId=%{public}d, type=%{public}d", (int32_t)module, channelId, type);
1190         return SOFTBUS_TRANS_UNPACK_PACKAGE_HEAD_FAILED;
1191     }
1192 
1193     uint32_t dataLen = pktHead->dataLen;
1194     if (dataLen > node->size - DC_MSG_PACKET_HEAD_SIZE) {
1195         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1196         TRANS_LOGE(TRANS_CTRL,
1197             "srv out of recv dataLen=%{public}u, listenerModule=%{public}d, "
1198             "channelId=%{public}d, type=%{public}d", dataLen, (int32_t)module, channelId, type);
1199         return SOFTBUS_TRANS_UNPACK_PACKAGE_HEAD_FAILED;
1200     }
1201 
1202     if (bufLen < dataLen + DC_MSG_PACKET_HEAD_SIZE) {
1203         SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1204         TRANS_LOGE(TRANS_CTRL,
1205             "srv data not enough, recv next time. bufLen=%{public}u, dataLen=%{public}u, headLen=%{public}d "
1206             "listenerModule=%{public}d, channelId=%{public}d, type=%{public}d",
1207             bufLen, dataLen, (int32_t)DC_MSG_PACKET_HEAD_SIZE, (int32_t)module, channelId, type);
1208         return SOFTBUS_DATA_NOT_ENOUGH;
1209     }
1210     DelTrigger(module, node->fd, READ_TRIGGER);
1211     SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1212     return ProcessReceivedData(channelId, type);
1213 }
1214 
TransTdcGetDataBufInfoByChannelId(int32_t channelId,int32_t * fd,size_t * len)1215 static int32_t TransTdcGetDataBufInfoByChannelId(int32_t channelId, int32_t *fd, size_t *len)
1216 {
1217     if (fd == NULL || len == NULL) {
1218         TRANS_LOGW(TRANS_CTRL, "invalid param.");
1219         return SOFTBUS_INVALID_PARAM;
1220     }
1221 
1222     if (g_tcpSrvDataList == NULL) {
1223         TRANS_LOGE(TRANS_CTRL, "tcp srv data list empty.");
1224         return SOFTBUS_NO_INIT;
1225     }
1226 
1227     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
1228         TRANS_LOGE(TRANS_CTRL, "lock failed.");
1229         return SOFTBUS_LOCK_ERR;
1230     }
1231     ServerDataBuf *item = NULL;
1232     LIST_FOR_EACH_ENTRY(item, &(g_tcpSrvDataList->list), ServerDataBuf, node) {
1233         if (item->channelId == channelId) {
1234             *fd = item->fd;
1235             *len = item->size - (item->w - item->data);
1236             (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1237             return SOFTBUS_OK;
1238         }
1239     }
1240     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1241     TRANS_LOGI(TRANS_CTRL, "trans tdc data buf not found. channelId=%{public}d", channelId);
1242     return SOFTBUS_TRANS_TCP_DATABUF_NOT_FOUND;
1243 }
1244 
TransTdcUpdateDataBufWInfo(int32_t channelId,char * recvBuf,int32_t recvLen)1245 static int32_t TransTdcUpdateDataBufWInfo(int32_t channelId, char *recvBuf, int32_t recvLen)
1246 {
1247     if (recvBuf == NULL) {
1248         TRANS_LOGW(TRANS_CTRL, "invalid param.");
1249         return SOFTBUS_INVALID_PARAM;
1250     }
1251     if (g_tcpSrvDataList == NULL) {
1252         TRANS_LOGE(TRANS_CTRL, "srv data list empty.");
1253         return SOFTBUS_NO_INIT;
1254     }
1255     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
1256         TRANS_LOGE(TRANS_CTRL, "lock failed.");
1257         return SOFTBUS_LOCK_ERR;
1258     }
1259 
1260     ServerDataBuf *item = NULL;
1261     ServerDataBuf *nextItem = NULL;
1262     LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &(g_tcpSrvDataList->list), ServerDataBuf, node) {
1263         if (item->channelId != channelId) {
1264             continue;
1265         }
1266         int32_t freeLen = (int32_t)(item->size) - (item->w - item->data);
1267         if (recvLen > freeLen) {
1268             (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1269             TRANS_LOGE(TRANS_CTRL,
1270                 "trans tdc. recvLen=%{public}d, freeLen=%{public}d.", recvLen, freeLen);
1271             return SOFTBUS_TRANS_RECV_DATA_OVER_LEN;
1272         }
1273         if (memcpy_s(item->w, recvLen, recvBuf, recvLen) != EOK) {
1274             (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1275             TRANS_LOGE(TRANS_CTRL, "memcpy_s trans tdc failed. channelId=%{public}d", channelId);
1276             return SOFTBUS_MEM_ERR;
1277         }
1278         item->w += recvLen;
1279         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1280         return SOFTBUS_OK;
1281     }
1282     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1283     TRANS_LOGE(TRANS_CTRL, "trans update tdc databuf not found. channelId=%{public}d", channelId);
1284     return SOFTBUS_TRANS_TCP_DATABUF_NOT_FOUND;
1285 }
1286 
TransRecvTdcSocketData(int32_t channelId,char * buffer,int32_t bufferSize)1287 static int32_t TransRecvTdcSocketData(int32_t channelId, char *buffer, int32_t bufferSize)
1288 {
1289     int32_t fd = -1;
1290     size_t len = 0;
1291     int32_t ret = TransTdcGetDataBufInfoByChannelId(channelId, &fd, &len);
1292     TRANS_CHECK_AND_RETURN_RET_LOGE(
1293         ret == SOFTBUS_OK, SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED, TRANS_CTRL, "get info failed, ret=%{public}d", ret);
1294     TRANS_CHECK_AND_RETURN_RET_LOGE(len >= (size_t)bufferSize, SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED, TRANS_CTRL,
1295         "freeBufferLen=%{public}zu less than bufferSize=%{public}d. channelId=%{public}d", len, bufferSize, channelId);
1296 
1297     int32_t totalRecvLen = 0;
1298     while (totalRecvLen < bufferSize) {
1299         int32_t recvLen = ConnRecvSocketData(fd, buffer, bufferSize - totalRecvLen, 0);
1300         if (recvLen < 0) {
1301             TRANS_LOGE(TRANS_CTRL, "recv tcp data fail, channelId=%{public}d, retLen=%{public}d, total=%{public}d, "
1302                 "totalRecv=%{public}d", channelId, recvLen, bufferSize, totalRecvLen);
1303             return SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED;
1304         } else if (recvLen == 0) {
1305             TRANS_LOGE(TRANS_CTRL, "recv tcp data fail, retLen=0, channelId=%{public}d, total=%{public}d, "
1306                 "totalRecv=%{public}d", channelId, bufferSize, totalRecvLen);
1307             return SOFTBUS_DATA_NOT_ENOUGH;
1308         }
1309 
1310         if (TransTdcUpdateDataBufWInfo(channelId, buffer, recvLen) != SOFTBUS_OK) {
1311             TRANS_LOGE(TRANS_CTRL, "update channel data buf failed. channelId=%{public}d", channelId);
1312             return SOFTBUS_TRANS_UPDATE_DATA_BUF_FAILED;
1313         }
1314         buffer += recvLen;
1315         totalRecvLen += recvLen;
1316     }
1317 
1318     return SOFTBUS_OK;
1319 }
1320 
1321 /*
1322  * The negotiation message may be unpacked, and when obtaining the message,
1323  * it is necessary to first check whether the buffer of the channel already has data.
1324  */
TransReadDataLen(int32_t channelId,int32_t * pktDataLen,int32_t module,int32_t type)1325 static int32_t TransReadDataLen(int32_t channelId, int32_t *pktDataLen, int32_t module, int32_t type)
1326 {
1327     if (g_tcpSrvDataList == NULL) {
1328         TRANS_LOGE(TRANS_CTRL, "tcp srv data list empty channelId=%{public}d %{public}d.", channelId, module);
1329         return SOFTBUS_NO_INIT;
1330     }
1331 
1332     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
1333         TRANS_LOGE(TRANS_CTRL, "lock failed channelId=%{public}d %{public}d.", channelId, module);
1334         return SOFTBUS_LOCK_ERR;
1335     }
1336 
1337     ServerDataBuf *dataBuf = TransSrvGetDataBufNodeById(channelId);
1338     if (dataBuf == NULL) {
1339         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1340         return SOFTBUS_TRANS_TCP_DATABUF_NOT_FOUND;
1341     }
1342 
1343     const uint32_t headSize = sizeof(TdcPacketHead);
1344     uint32_t bufDataLen = dataBuf->w - dataBuf->data;
1345     const uint32_t maxDataLen = dataBuf->size - headSize;
1346 
1347     TdcPacketHead *pktHeadPtr = NULL;
1348     // channel buffer already has header data
1349     if (bufDataLen >= headSize) {
1350         bufDataLen -= headSize;
1351         pktHeadPtr = (TdcPacketHead *)(dataBuf->data);
1352         // obtain the remaining length of data to be read
1353         *pktDataLen = pktHeadPtr->dataLen - bufDataLen;
1354         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1355         return SOFTBUS_OK;
1356     }
1357     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1358 
1359     TdcPacketHead pktHead;
1360     (void)memset_s(&pktHead, sizeof(pktHead), 0, sizeof(pktHead));
1361     int32_t ret = TransRecvTdcSocketData(channelId, (char *)&pktHead, headSize);
1362     if (ret != SOFTBUS_OK) {
1363         return ret;
1364     }
1365 
1366     UnpackTdcPacketHead(&pktHead);
1367     if (pktHead.magicNumber != MAGIC_NUMBER || pktHead.dataLen > maxDataLen || pktHead.dataLen == 0) {
1368         TRANS_LOGE(TRANS_CTRL, "invalid packet head module=%{public}d, channelId=%{public}d, type=%{public}d, "
1369             "magic=%{public}x, len=%{public}d", module, channelId, type, pktHead.magicNumber, pktHead.dataLen);
1370         return SOFTBUS_TRANS_UNPACK_PACKAGE_HEAD_FAILED;
1371     }
1372     *pktDataLen = pktHead.dataLen;
1373 
1374     return SOFTBUS_OK;
1375 }
1376 
TransTdcSrvRecvData(ListenerModule module,int32_t channelId,int32_t type)1377 int32_t TransTdcSrvRecvData(ListenerModule module, int32_t channelId, int32_t type)
1378 {
1379     int32_t dataSize = 0;
1380     int32_t ret = TransReadDataLen(channelId, &dataSize, (int32_t)module, type);
1381     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED,
1382         TRANS_CTRL, "read dataLen failed, ret=%{public}d", ret);
1383 
1384     char *dataBuffer = (char *)SoftBusCalloc(dataSize);
1385     if (dataBuffer == NULL) {
1386         TRANS_LOGE(TRANS_CTRL, "malloc failed. channelId=%{public}d, len=%{public}d", channelId, dataSize);
1387         return SOFTBUS_MALLOC_ERR;
1388     }
1389     ret = TransRecvTdcSocketData(channelId, dataBuffer, dataSize);
1390     if (ret != SOFTBUS_OK) {
1391         SoftBusFree(dataBuffer);
1392         return ret;
1393     }
1394     SoftBusFree(dataBuffer);
1395 
1396     return TransTdcSrvProcData(module, channelId, type);
1397 }
1398