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