• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "trans_tcp_direct_message.h"
17 
18 #include "cJSON.h"
19 #include <securec.h>
20 #include <string.h>
21 
22 #include "access_control.h"
23 #include "anonymizer.h"
24 #include "auth_interface.h"
25 #include "auth_uk_manager.h"
26 #include "bus_center_manager.h"
27 #include "data_bus_native.h"
28 #include "g_enhance_trans_func_pack.h"
29 #include "legacy/softbus_hisysevt_transreporter.h"
30 #include "lnn_distributed_net_ledger.h"
31 #include "lnn_lane_link.h"
32 #include "lnn_net_builder.h"
33 #include "lnn_ohos_account_adapter.h"
34 #include "softbus_access_token_adapter.h"
35 #include "softbus_adapter_crypto.h"
36 #include "softbus_adapter_mem.h"
37 #include "softbus_adapter_socket.h"
38 #include "softbus_adapter_thread.h"
39 #include "softbus_adapter_timer.h"
40 #include "softbus_app_info.h"
41 #include "softbus_error_code.h"
42 #include "softbus_feature_config.h"
43 #include "softbus_json_utils.h"
44 #include "softbus_message_open_channel.h"
45 #include "softbus_socket.h"
46 #include "softbus_tcp_socket.h"
47 #include "softbus_utils.h"
48 #include "trans_bind_request_manager.h"
49 #include "trans_channel_common.h"
50 #include "trans_channel_manager.h"
51 #include "trans_event.h"
52 #include "trans_lane_manager.h"
53 #include "trans_log.h"
54 #include "trans_session_manager.h"
55 #include "trans_tcp_direct_callback.h"
56 #include "trans_tcp_direct_listener.h"
57 #include "trans_tcp_direct_manager.h"
58 #include "trans_tcp_direct_sessionconn.h"
59 #include "trans_tcp_process_data.h"
60 #include "trans_uk_manager.h"
61 #include "wifi_direct_manager.h"
62 
63 #define MAX_PACKET_SIZE (64 * 1024)
64 #define MIN_META_LEN    6
65 #define META_SESSION    "IShare"
66 #define MAX_ERRDESC_LEN 128
67 #define NCM_DEVICE_TYPE "ncm0"
68 #define NCM_HOST_TYPE   "wwan0"
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     DataBuf *item = NULL;
121     DataBuf *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, DataBuf, node) {
127         ListDelete(&item->node);
128         SoftBusFree(item->data);
129         SoftBusFree(item);
130         g_tcpSrvDataList->cnt--;
131     }
132     (void)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     DataBuf *node = (DataBuf *)SoftBusCalloc(sizeof(DataBuf));
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     (void)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     DataBuf *item = NULL;
186     DataBuf *next = NULL;
187     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
188         return;
189     }
190     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_tcpSrvDataList->list, DataBuf, 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     (void)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     if (cipherFlag & FLAG_SESSION_KEY) {
220         return AUTH_LINK_TYPE_SESSION_KEY;
221     }
222 
223     if (cipherFlag & FLAG_SLE) {
224         return AUTH_LINK_TYPE_SLE;
225     }
226     return AUTH_LINK_TYPE_WIFI;
227 }
228 
PackBytes(int32_t channelId,const char * data,TdcPacketHead * packetHead,char * buffer,uint32_t bufLen)229 static int32_t PackBytes(int32_t channelId, const char *data, TdcPacketHead *packetHead, char *buffer, uint32_t bufLen)
230 {
231     AuthHandle authHandle = { 0 };
232     if (GetAuthHandleByChanId(channelId, &authHandle) != SOFTBUS_OK || authHandle.authId == AUTH_INVALID_ID) {
233         TRANS_LOGE(TRANS_BYTES, "PackBytes get auth id fail");
234         return SOFTBUS_NOT_FIND;
235     }
236 
237     uint8_t *encData = (uint8_t *)buffer + DC_MSG_PACKET_HEAD_SIZE;
238     uint32_t encDataLen = bufLen - DC_MSG_PACKET_HEAD_SIZE;
239     if (AuthEncrypt(&authHandle, (const uint8_t *)data, packetHead->dataLen, encData, &encDataLen) != SOFTBUS_OK) {
240         TRANS_LOGE(TRANS_BYTES, "PackBytes encrypt fail");
241         return SOFTBUS_ENCRYPT_ERR;
242     }
243     packetHead->dataLen = encDataLen;
244 
245     TRANS_LOGI(TRANS_BYTES, "PackBytes: flag=%{public}u, seq=%{public}" PRIu64, packetHead->flags, packetHead->seq);
246     PackTdcPacketHead(packetHead);
247     if (memcpy_s(buffer, bufLen, packetHead, sizeof(TdcPacketHead)) != EOK) {
248         TRANS_LOGE(TRANS_BYTES, "memcpy_s buffer fail");
249         return SOFTBUS_MEM_ERR;
250     }
251     return SOFTBUS_OK;
252 }
253 
TransSrvGetDataBufNodeById(int32_t channelId)254 static DataBuf *TransSrvGetDataBufNodeById(int32_t channelId)
255 {
256     if (g_tcpSrvDataList == NULL) {
257         TRANS_LOGE(TRANS_CTRL, "g_tcpSrvDataList is null");
258         return NULL;
259     }
260 
261     DataBuf *item = NULL;
262     LIST_FOR_EACH_ENTRY(item, &(g_tcpSrvDataList->list), DataBuf, node) {
263         if (item->channelId == channelId) {
264             return item;
265         }
266     }
267     TRANS_LOGE(TRANS_CTRL, "srv tcp direct channelId=%{public}d not exist.", channelId);
268     return NULL;
269 }
270 
TransSrvGetSeqAndFlagsByChannelId(uint64_t * seq,uint32_t * flags,int32_t channelId)271 static int32_t TransSrvGetSeqAndFlagsByChannelId(uint64_t *seq, uint32_t *flags, int32_t channelId)
272 {
273     TRANS_CHECK_AND_RETURN_RET_LOGE(g_tcpSrvDataList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_tcpSrvDataList is null");
274 
275     int32_t ret = SoftBusMutexLock(&g_tcpSrvDataList->lock);
276     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!");
277     DataBuf *node = TransSrvGetDataBufNodeById(channelId);
278     if (node == NULL || node->data == NULL) {
279         TRANS_LOGE(TRANS_CTRL, "node is null.");
280         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
281         return SOFTBUS_TRANS_NODE_IS_NULL;
282     }
283     TdcPacketHead *pktHead = (TdcPacketHead *)(node->data);
284     *seq = pktHead->seq;
285     *flags = pktHead->flags;
286     TRANS_LOGI(TRANS_CTRL, "flags=%{public}d, seq=%{public}" PRIu64, *flags, *seq);
287     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
288     return SOFTBUS_OK;
289 }
290 
SendFailToFlushDevice(SessionConn * conn)291 static void SendFailToFlushDevice(SessionConn *conn)
292 {
293     if (conn->appInfo.routeType == WIFI_STA || conn->appInfo.routeType == WIFI_USB) {
294         char *tmpId = NULL;
295         Anonymize(conn->appInfo.peerData.deviceId, &tmpId);
296         TRANS_LOGE(TRANS_CTRL, "send data fail, do Authflushdevice deviceId=%{public}s", AnonymizeWrapper(tmpId));
297         AnonymizeFree(tmpId);
298         if (AuthFlushDevice(conn->appInfo.peerData.deviceId) != SOFTBUS_OK) {
299             TRANS_LOGE(TRANS_CTRL, "tcp flush failed, wifi will offline");
300             LnnRequestLeaveSpecific(conn->appInfo.peerNetWorkId, CONNECTION_ADDR_WLAN);
301         }
302     }
303 }
304 
TransTdcPostBytes(int32_t channelId,TdcPacketHead * packetHead,const char * data)305 int32_t TransTdcPostBytes(int32_t channelId, TdcPacketHead *packetHead, const char *data)
306 {
307     if (data == NULL || packetHead == NULL || packetHead->dataLen == 0) {
308         TRANS_LOGE(TRANS_BYTES, "Invalid para.");
309         return SOFTBUS_INVALID_PARAM;
310     }
311     AuthHandle authHandle = { 0 };
312     if (GetAuthHandleByChanId(channelId, &authHandle) != SOFTBUS_OK || authHandle.authId == AUTH_INVALID_ID) {
313         TRANS_LOGE(TRANS_BYTES, "get auth id fail, channelId=%{public}d", channelId);
314         return SOFTBUS_TRANS_TCP_GET_AUTHID_FAILED;
315     }
316     uint32_t bufferLen = AuthGetEncryptSize(authHandle.authId, packetHead->dataLen) + DC_MSG_PACKET_HEAD_SIZE;
317     char *buffer = (char *)SoftBusCalloc(bufferLen);
318     if (buffer == NULL) {
319         TRANS_LOGE(TRANS_BYTES, "buffer malloc error.");
320         return SOFTBUS_MALLOC_ERR;
321     }
322     if (PackBytes(channelId, data, packetHead, buffer, bufferLen) != SOFTBUS_OK) {
323         TRANS_LOGE(TRANS_BYTES, "Pack Bytes error.");
324         SoftBusFree(buffer);
325         return SOFTBUS_ENCRYPT_ERR;
326     }
327     SessionConn *conn = (SessionConn *)SoftBusCalloc(sizeof(SessionConn));
328     if (conn == NULL) {
329         TRANS_LOGE(TRANS_BYTES, "malloc conn fail");
330         SoftBusFree(buffer);
331         return SOFTBUS_MALLOC_ERR;
332     }
333     if (GetSessionConnById(channelId, conn) != SOFTBUS_OK) {
334         TRANS_LOGE(TRANS_BYTES, "Get SessionConn fail");
335         SoftBusFree(buffer);
336         SoftBusFree(conn);
337         return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED;
338     }
339     (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
340     SetIpTos(conn->appInfo.fd, FAST_MESSAGE_TOS);
341     if (ConnSendSocketData(conn->appInfo.fd, buffer, bufferLen, 0) != (int)bufferLen) {
342         SendFailToFlushDevice(conn);
343         SoftBusFree(buffer);
344         SoftBusFree(conn);
345         return GetErrCodeBySocketErr(SOFTBUS_TCP_SOCKET_ERR);
346     }
347     SoftBusFree(conn);
348     SoftBusFree(buffer);
349     return SOFTBUS_OK;
350 }
351 
GetChannelInfoFromConn(ChannelInfo * info,SessionConn * conn,int32_t channelId)352 static void GetChannelInfoFromConn(ChannelInfo *info, SessionConn *conn, int32_t channelId)
353 {
354     info->channelId = channelId;
355     info->channelType = CHANNEL_TYPE_TCP_DIRECT;
356     info->isServer = conn->serverSide;
357     info->isEnabled = true;
358     info->fd = conn->appInfo.fd;
359     info->sessionKey = GetCapabilityBit(conn->appInfo.channelCapability, TRANS_CHANNEL_SINK_GENERATE_KEY_OFFSET) ?
360         conn->appInfo.sinkSessionKey :
361         conn->appInfo.sessionKey;
362     info->myHandleId = conn->appInfo.myHandleId;
363     info->peerHandleId = conn->appInfo.peerHandleId;
364     info->peerSessionName = conn->appInfo.peerData.sessionName;
365     info->groupId = conn->appInfo.groupId;
366     info->isEncrypt = true;
367     info->keyLen = SESSION_KEY_LENGTH;
368     info->peerUid = conn->appInfo.peerData.uid;
369     info->peerPid = conn->appInfo.peerData.pid;
370     info->routeType = conn->appInfo.routeType;
371     info->businessType = conn->appInfo.businessType;
372     info->autoCloseTime = conn->appInfo.autoCloseTime;
373     info->peerIp = conn->appInfo.peerData.addr;
374     info->peerPort = conn->appInfo.peerData.port;
375     info->linkType = conn->appInfo.linkType;
376     info->dataConfig = conn->appInfo.myData.dataConfig;
377     info->timeStart = conn->appInfo.timeStart;
378     info->linkType = conn->appInfo.linkType;
379     info->connectType = conn->appInfo.connectType;
380     info->osType = conn->appInfo.osType;
381     info->tokenType = conn->appInfo.myData.tokenType;
382     info->isLowLatency = conn->appInfo.isLowLatency;
383     info->fdProtocol = conn->appInfo.fdProtocol;
384     info->pkgName = conn->appInfo.myData.pkgName;
385     if (conn->appInfo.myData.tokenType > ACCESS_TOKEN_TYPE_HAP && conn->serverSide) {
386         info->peerUserId = conn->appInfo.peerData.userId;
387         info->peerTokenId = conn->appInfo.peerData.tokenId;
388         info->peerExtraAccessInfo = conn->appInfo.extraAccessInfo;
389     }
390 }
391 
GetServerSideIpInfo(const AppInfo * appInfo,char * ip,uint32_t len)392 static int32_t GetServerSideIpInfo(const AppInfo *appInfo, char *ip, uint32_t len)
393 {
394     char myIp[IP_LEN] = { 0 };
395     if (appInfo->routeType == WIFI_STA) {
396         if (LnnGetLocalStrInfoByIfnameIdx(STRING_KEY_IP, myIp, sizeof(myIp), WLAN_IF) != SOFTBUS_OK) {
397             TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get local ip fail");
398             return SOFTBUS_TRANS_GET_LOCAL_IP_FAILED;
399         }
400     } else if (appInfo->routeType == WIFI_P2P) {
401         struct WifiDirectManager *mgr = GetWifiDirectManager();
402         if (mgr == NULL || mgr->getLocalIpByRemoteIp == NULL) {
403             TRANS_LOGE(TRANS_CTRL, "GetWifiDirectManager failed");
404             return SOFTBUS_WIFI_DIRECT_INIT_FAILED;
405         }
406 
407         int32_t ret = mgr->getLocalIpByRemoteIp(appInfo->peerData.addr, myIp, sizeof(myIp));
408         if (ret != SOFTBUS_OK) {
409             TRANS_LOGE(TRANS_CTRL, "get Local Ip fail, ret=%{public}d", ret);
410             return SOFTBUS_TRANS_GET_P2P_INFO_FAILED;
411         }
412 
413         if (LnnSetLocalStrInfo(STRING_KEY_P2P_IP, myIp) != SOFTBUS_OK) {
414             TRANS_LOGW(TRANS_CTRL, "ServerSide set local p2p ip fail");
415         }
416         if (LnnSetDLP2pIp(appInfo->peerData.deviceId, CATEGORY_UUID, appInfo->peerData.addr) != SOFTBUS_OK) {
417             TRANS_LOGW(TRANS_CTRL, "ServerSide set peer p2p ip fail");
418         }
419     } else if (appInfo->routeType == WIFI_USB) {
420         if (LnnGetLocalStrInfoByIfnameIdx(STRING_KEY_IP, myIp, sizeof(myIp), USB_IF) != SOFTBUS_OK) {
421             TRANS_LOGE(TRANS_CTRL, "ServerSide get local usb ip fail");
422             return SOFTBUS_TRANS_GET_LOCAL_IP_FAILED;
423         }
424     }
425     if (strcpy_s(ip, len, myIp) != EOK) {
426         TRANS_LOGE(TRANS_CTRL, "copy str failed");
427         return SOFTBUS_STRCPY_ERR;
428     }
429     return SOFTBUS_OK;
430 }
431 
GetClientSideIpInfo(const AppInfo * appInfo,char * ip,uint32_t len)432 static int32_t GetClientSideIpInfo(const AppInfo *appInfo, char *ip, uint32_t len)
433 {
434     if (appInfo->routeType == WIFI_P2P) {
435         if (LnnSetLocalStrInfo(STRING_KEY_P2P_IP, appInfo->myData.addr) != SOFTBUS_OK) {
436             TRANS_LOGW(TRANS_CTRL, "Client set local p2p ip fail");
437         }
438         if (LnnSetDLP2pIp(appInfo->peerData.deviceId, CATEGORY_UUID, appInfo->peerData.addr) != SOFTBUS_OK) {
439             TRANS_LOGW(TRANS_CTRL, "Client set peer p2p ip fail");
440         }
441     }
442     if (strcpy_s(ip, len, appInfo->myData.addr) != EOK) {
443         TRANS_LOGE(TRANS_CTRL, "copy str failed");
444         return SOFTBUS_STRCPY_ERR;
445     }
446     return SOFTBUS_OK;
447 }
448 
SetByteChannelTos(const AppInfo * info)449 static void SetByteChannelTos(const AppInfo *info)
450 {
451     if (info->businessType == BUSINESS_TYPE_BYTE && info->channelType == CHANNEL_TYPE_TCP_DIRECT) {
452         SetIpTos(info->fd, FAST_BYTE_TOS);
453     }
454     return;
455 }
456 
ClearAppInfoSessionKey(AppInfo * appInfo)457 static void ClearAppInfoSessionKey(AppInfo *appInfo)
458 {
459     (void)memset_s(appInfo->sessionKey, sizeof(appInfo->sessionKey), 0, sizeof(appInfo->sessionKey));
460     (void)memset_s(appInfo->sinkSessionKey, sizeof(appInfo->sinkSessionKey), 0, sizeof(appInfo->sinkSessionKey));
461 }
462 
NotifyChannelOpened(int32_t channelId)463 static int32_t NotifyChannelOpened(int32_t channelId)
464 {
465     SessionConn conn;
466     if (GetSessionConnById(channelId, &conn) != SOFTBUS_OK) {
467         TRANS_LOGE(TRANS_CTRL, "notify channel open failed, get tdcInfo is null");
468         return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED;
469     }
470     char myIp[IP_LEN] = { 0 };
471     int32_t ret = conn.serverSide ? GetServerSideIpInfo(&conn.appInfo, myIp, IP_LEN) :
472                                     GetClientSideIpInfo(&conn.appInfo, myIp, IP_LEN);
473     if (ret != SOFTBUS_OK) {
474         TRANS_LOGE(TRANS_CTRL, "get ip failed, ret=%{public}d.", ret);
475         ClearAppInfoSessionKey(&conn.appInfo);
476         return ret;
477     }
478     ChannelInfo info = { 0 };
479     GetChannelInfoFromConn(&info, &conn, channelId);
480     info.myIp = myIp;
481 
482     char buf[NETWORK_ID_BUF_LEN] = { 0 };
483     ret = LnnGetNetworkIdByUuid(conn.appInfo.peerData.deviceId, buf, NETWORK_ID_BUF_LEN);
484     if (ret != SOFTBUS_OK) {
485         TRANS_LOGE(TRANS_CTRL, "get networkId failed, ret=%{public}d", ret);
486         ClearAppInfoSessionKey(&conn.appInfo);
487         return ret;
488     }
489     info.peerDeviceId = buf;
490     char pkgName[PKG_NAME_SIZE_MAX] = { 0 };
491     ret = TransTdcGetPkgName(conn.appInfo.myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
492     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get pkg name fail.");
493 
494     int32_t uid = 0;
495     int32_t pid = 0;
496     if (TransTdcGetUidAndPid(conn.appInfo.myData.sessionName, &uid, &pid) != SOFTBUS_OK) {
497         TRANS_LOGE(TRANS_CTRL, "get uid and pid fail.");
498         ClearAppInfoSessionKey(&conn.appInfo);
499         return SOFTBUS_TRANS_GET_PID_FAILED;
500     }
501     if (conn.appInfo.fastTransDataSize > 0) {
502         info.isFastData = true;
503     }
504     TransGetLaneIdByChannelId(channelId, &info.laneId);
505     GetOsTypeByNetworkId(info.peerDeviceId, &info.osType);
506     info.isSupportTlv = GetCapabilityBit(conn.appInfo.channelCapability, TRANS_CAPABILITY_TLV_OFFSET);
507     ret = TransTdcOnChannelOpened(pkgName, pid, conn.appInfo.myData.sessionName, &info);
508     ClearAppInfoSessionKey(&conn.appInfo);
509     conn.status = TCP_DIRECT_CHANNEL_STATUS_CONNECTED;
510     SetSessionConnStatusById(channelId, conn.status);
511     return ret;
512 }
513 
NotifyChannelBind(int32_t channelId,SessionConn * conn)514 static int32_t NotifyChannelBind(int32_t channelId, SessionConn *conn)
515 {
516     char pkgName[PKG_NAME_SIZE_MAX] = { 0 };
517     int32_t ret = TransTdcGetPkgName(conn->appInfo.myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
518     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get pkg name fail.");
519 
520     ret = TransTdcOnChannelBind(pkgName, conn->appInfo.myData.pid, channelId);
521     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, ret=%{public}d", channelId, ret);
522     return ret;
523 }
524 
NotifyChannelClosed(const AppInfo * appInfo,int32_t channelId)525 static int32_t NotifyChannelClosed(const AppInfo *appInfo, int32_t channelId)
526 {
527     char pkgName[PKG_NAME_SIZE_MAX] = { 0 };
528     int32_t ret = TransTdcGetPkgName(appInfo->myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
529     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get pkg name fail.");
530     ret = TransTdcOnChannelClosed(pkgName, appInfo->myData.pid, channelId);
531     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, ret=%{public}d", channelId, ret);
532     return ret;
533 }
534 
NotifyChannelOpenFailedBySessionConn(const SessionConn * conn,int32_t errCode)535 int32_t NotifyChannelOpenFailedBySessionConn(const SessionConn *conn, int32_t errCode)
536 {
537     TRANS_CHECK_AND_RETURN_RET_LOGE(conn != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, "invalid param.");
538     int64_t timeDiff = GetSoftbusRecordTimeMillis() - conn->appInfo.timeStart;
539     char localUdid[UDID_BUF_LEN] = { 0 };
540     (void)LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, sizeof(localUdid));
541     TransEventExtra extra = {
542         .calleePkg = NULL,
543         .callerPkg = conn->appInfo.myData.pkgName,
544         .channelId = conn->channelId,
545         .peerNetworkId = conn->appInfo.peerNetWorkId,
546         .socketName = conn->appInfo.myData.sessionName,
547         .linkType = conn->appInfo.connectType,
548         .costTime = timeDiff,
549         .errcode = errCode,
550         .osType = (conn->appInfo.osType < 0) ? UNKNOW_OS_TYPE : (conn->appInfo.osType),
551         .localUdid = localUdid,
552         .peerUdid = conn->appInfo.peerUdid,
553         .peerDevVer = conn->appInfo.peerVersion,
554         .result = EVENT_STAGE_RESULT_FAILED
555     };
556     extra.deviceState = TransGetDeviceState(conn->appInfo.peerNetWorkId);
557     int32_t sceneCommand = conn->serverSide ? EVENT_SCENE_OPEN_CHANNEL_SERVER : EVENT_SCENE_OPEN_CHANNEL;
558     TRANS_EVENT(sceneCommand, EVENT_STAGE_OPEN_CHANNEL_END, extra);
559     TransAlarmExtra extraAlarm = {
560         .conflictName = NULL,
561         .conflictedName = NULL,
562         .occupyedName = NULL,
563         .permissionName = NULL,
564         .linkType = conn->appInfo.linkType,
565         .errcode = errCode,
566         .sessionName = conn->appInfo.myData.sessionName,
567     };
568     TRANS_ALARM(OPEN_SESSION_FAIL_ALARM, CONTROL_ALARM_TYPE, extraAlarm);
569     SoftbusRecordOpenSessionKpi(
570         conn->appInfo.myData.pkgName, conn->appInfo.linkType, SOFTBUS_EVT_OPEN_SESSION_FAIL, timeDiff);
571     char pkgName[PKG_NAME_SIZE_MAX] = { 0 };
572     int32_t ret = TransTdcGetPkgName(conn->appInfo.myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
573     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get pkg name fail.");
574     if (!(conn->serverSide)) {
575         ret = TransTdcOnChannelOpenFailed(
576             conn->appInfo.myData.pkgName, conn->appInfo.myData.pid, conn->channelId, errCode);
577         TRANS_LOGW(TRANS_CTRL, "channelId=%{public}d, ret=%{public}d", conn->channelId, ret);
578         return ret;
579     }
580     return SOFTBUS_OK;
581 }
582 
NotifyChannelOpenFailed(int32_t channelId,int32_t errCode)583 int32_t NotifyChannelOpenFailed(int32_t channelId, int32_t errCode)
584 {
585     SessionConn conn;
586     if (GetSessionConnById(channelId, &conn) != SOFTBUS_OK) {
587         TRANS_LOGE(TRANS_CTRL, "notify channel open failed, get tdcInfo is null");
588         return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED;
589     }
590 
591     (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
592     return NotifyChannelOpenFailedBySessionConn(&conn, errCode);
593 }
594 
TransTdcPostFastData(SessionConn * conn)595 static int32_t TransTdcPostFastData(SessionConn *conn)
596 {
597     TRANS_LOGI(TRANS_CTRL, "enter.");
598     uint32_t outLen = 0;
599     char *buf = TransTdcPackFastData(&(conn->appInfo), &outLen);
600     if (buf == NULL) {
601         TRANS_LOGE(TRANS_CTRL, "failed to pack bytes.");
602         return SOFTBUS_ENCRYPT_ERR;
603     }
604     if (outLen != conn->appInfo.fastTransDataSize + FAST_TDC_EXT_DATA_SIZE) {
605         TRANS_LOGE(TRANS_CTRL, "pack bytes len error, outLen=%{public}d", outLen);
606         SoftBusFree(buf);
607         return SOFTBUS_ENCRYPT_ERR;
608     }
609     uint32_t tos = (conn->appInfo.businessType == BUSINESS_TYPE_BYTE) ? FAST_BYTE_TOS : FAST_MESSAGE_TOS;
610     if (SetIpTos(conn->appInfo.fd, tos) != SOFTBUS_OK) {
611         SoftBusFree(buf);
612         return SOFTBUS_TCP_SOCKET_ERR;
613     }
614     ssize_t ret = ConnSendSocketData(conn->appInfo.fd, buf, outLen, 0);
615     if (ret != (ssize_t)outLen) {
616         TRANS_LOGE(TRANS_CTRL, "failed to send tcp data. ret=%{public}zd", ret);
617         SoftBusFree(buf);
618         return GetErrCodeBySocketErr(SOFTBUS_TRANS_SEND_TCP_DATA_FAILED);
619     }
620     SoftBusFree(buf);
621     buf = NULL;
622     return SOFTBUS_OK;
623 }
624 
625 static const ConfigTypeMap g_configTypeMap[] = {
626     {CHANNEL_TYPE_TCP_DIRECT, BUSINESS_TYPE_BYTE, SOFTBUS_INT_MAX_BYTES_NEW_LENGTH},
627     {CHANNEL_TYPE_TCP_DIRECT, BUSINESS_TYPE_MESSAGE, SOFTBUS_INT_MAX_MESSAGE_NEW_LENGTH},
628 };
629 
FindConfigType(int32_t channelType,int32_t businessType)630 static int32_t FindConfigType(int32_t channelType, int32_t businessType)
631 {
632     uint32_t size = (uint32_t)(sizeof(g_configTypeMap) / sizeof(ConfigTypeMap));
633     for (uint32_t i = 0; i < size; i++) {
634         if ((g_configTypeMap[i].channelType == channelType) && (g_configTypeMap[i].businessType == businessType)) {
635             return g_configTypeMap[i].configType;
636         }
637     }
638     return SOFTBUS_CONFIG_TYPE_MAX;
639 }
640 
TransGetLocalConfig(int32_t channelType,int32_t businessType,uint32_t * len)641 static int32_t TransGetLocalConfig(int32_t channelType, int32_t businessType, uint32_t *len)
642 {
643     ConfigType configType = (ConfigType)FindConfigType(channelType, businessType);
644     if (configType == SOFTBUS_CONFIG_TYPE_MAX) {
645         TRANS_LOGE(TRANS_CTRL, "Invalid channelType=%{public}d, businessType=%{public}d", channelType, businessType);
646         return SOFTBUS_INVALID_PARAM;
647     }
648     uint32_t maxLen = 0;
649     if (SoftbusGetConfig(configType, (unsigned char *)&maxLen, sizeof(maxLen)) != SOFTBUS_OK) {
650         TRANS_LOGE(TRANS_CTRL, "get config failed, configType=%{public}d.", configType);
651         return SOFTBUS_GET_CONFIG_VAL_ERR;
652     }
653 
654     *len = maxLen;
655     TRANS_LOGI(TRANS_CTRL, "get local config len=%{public}d.", *len);
656     return SOFTBUS_OK;
657 }
658 
TransTdcProcessDataConfig(AppInfo * appInfo)659 static int32_t TransTdcProcessDataConfig(AppInfo *appInfo)
660 {
661     if (appInfo == NULL) {
662         TRANS_LOGE(TRANS_CTRL, "appInfo is null");
663         return SOFTBUS_INVALID_PARAM;
664     }
665     if (appInfo->businessType != BUSINESS_TYPE_MESSAGE && appInfo->businessType != BUSINESS_TYPE_BYTE) {
666         TRANS_LOGI(TRANS_CTRL, "invalid businessType=%{public}d", appInfo->businessType);
667         return SOFTBUS_OK;
668     }
669     if (appInfo->peerData.dataConfig != 0) {
670         appInfo->myData.dataConfig = MIN(appInfo->myData.dataConfig, appInfo->peerData.dataConfig);
671         TRANS_LOGI(TRANS_CTRL, "process dataConfig succ. dataConfig=%{public}u", appInfo->myData.dataConfig);
672         return SOFTBUS_OK;
673     }
674     ConfigType configType =
675         appInfo->businessType == BUSINESS_TYPE_BYTE ? SOFTBUS_INT_MAX_BYTES_LENGTH : SOFTBUS_INT_MAX_MESSAGE_LENGTH;
676     int32_t ret =
677         SoftbusGetConfig(configType, (unsigned char *)&appInfo->myData.dataConfig, sizeof(appInfo->myData.dataConfig));
678     if (ret != SOFTBUS_OK) {
679         TRANS_LOGE(TRANS_CTRL, "get config failed, configType=%{public}d", configType);
680         return ret;
681     }
682     TRANS_LOGI(TRANS_CTRL, "process dataConfig=%{public}d", appInfo->myData.dataConfig);
683     return SOFTBUS_OK;
684 }
685 
686 // the channel open failed while be notified when function OpenDataBusReply return ERR
OpenDataBusReply(int32_t channelId,uint64_t seq,const cJSON * reply)687 static int32_t OpenDataBusReply(int32_t channelId, uint64_t seq, const cJSON *reply)
688 {
689     (void)seq;
690     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, seq=%{public}" PRIu64, channelId, seq);
691     SessionConn conn;
692     (void)memset_s(&conn, sizeof(SessionConn), 0, sizeof(SessionConn));
693     TRANS_CHECK_AND_RETURN_RET_LOGE(GetSessionConnById(channelId, &conn) == SOFTBUS_OK,
694         SOFTBUS_TRANS_GET_SESSION_CONN_FAILED, TRANS_CTRL, "notify channel open failed, get tdcInfo is null");
695     int32_t errCode = SOFTBUS_OK;
696     if (UnpackReplyErrCode(reply, &errCode) == SOFTBUS_OK) {
697         TRANS_LOGE(TRANS_CTRL, "receive err reply msg channelId=%{public}d, errCode=%{public}d, seq=%{public}" PRIu64,
698             channelId, errCode, seq);
699         if (errCode == SOFTBUS_TRANS_PEER_SESSION_NOT_CREATED) {
700             (void)TransAddTimestampToList(conn.appInfo.myData.sessionName, conn.appInfo.peerData.sessionName,
701                 conn.appInfo.peerNetWorkId, SoftBusGetSysTimeMs());
702         }
703         return errCode;
704     }
705 
706     uint16_t fastDataSize = 0;
707     TRANS_CHECK_AND_RETURN_RET_LOGE(UnpackReply(reply, &conn.appInfo, &fastDataSize) == SOFTBUS_OK,
708         SOFTBUS_TRANS_UNPACK_REPLY_FAILED, TRANS_CTRL, "UnpackReply failed");
709 
710     int32_t ret = TransTdcProcessDataConfig(&conn.appInfo);
711     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "Trans Tdc process data config failed.");
712 
713     ret = SetAppInfoById(channelId, &conn.appInfo);
714     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "set app info by id failed.");
715     SetByteChannelTos(&conn.appInfo);
716     if ((fastDataSize > 0 && (conn.appInfo.fastTransDataSize == fastDataSize)) || conn.appInfo.fastTransDataSize == 0) {
717         ret = NotifyChannelOpened(channelId);
718         (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
719         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "notify channel open failed");
720     } else {
721         ret = TransTdcPostFastData(&conn);
722         (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
723         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "tdc send fast data failed");
724         ret = NotifyChannelOpened(channelId);
725         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "notify channel open failed");
726     }
727     TransEventExtra extra = {
728         .socketName = NULL,
729         .peerNetworkId = NULL,
730         .calleePkg = NULL,
731         .callerPkg = NULL,
732         .channelId = channelId,
733         .result = EVENT_STAGE_RESULT_OK
734     };
735     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_HANDSHAKE_REPLY, extra);
736     TRANS_LOGD(TRANS_CTRL, "ok");
737     return SOFTBUS_OK;
738 }
739 
TransTdcPostReplyMsg(int32_t channelId,uint64_t seq,uint32_t flags,char * reply)740 static int32_t TransTdcPostReplyMsg(int32_t channelId, uint64_t seq, uint32_t flags, char *reply)
741 {
742     TdcPacketHead packetHead = {
743         .magicNumber = MAGIC_NUMBER,
744         .module = MODULE_SESSION,
745         .seq = seq,
746         .flags = (FLAG_REPLY | flags),
747         .dataLen = strlen(reply),
748     };
749     return TransTdcPostBytes(channelId, &packetHead, reply);
750 }
751 
OpenDataBusRequestReply(const AppInfo * appInfo,int32_t channelId,uint64_t seq,uint32_t flags)752 static int32_t OpenDataBusRequestReply(const AppInfo *appInfo, int32_t channelId, uint64_t seq, uint32_t flags)
753 {
754     char *reply = PackReply(appInfo);
755     if (reply == NULL) {
756         TRANS_LOGE(TRANS_CTRL, "get pack reply err");
757         return SOFTBUS_TRANS_GET_PACK_REPLY_FAILED;
758     }
759 
760     int32_t ret = TransTdcPostReplyMsg(channelId, seq, flags, reply);
761     cJSON_free(reply);
762     return ret;
763 }
764 
OpenDataBusRequestError(int32_t channelId,uint64_t seq,char * errDesc,int32_t errCode,uint32_t flags)765 static int32_t OpenDataBusRequestError(int32_t channelId, uint64_t seq, char *errDesc, int32_t errCode, uint32_t flags)
766 {
767     char *reply = PackError(errCode, errDesc);
768     if (reply == NULL) {
769         TRANS_LOGE(TRANS_CTRL, "get pack reply err");
770         return SOFTBUS_TRANS_GET_PACK_REPLY_FAILED;
771     }
772     int32_t ret = TransTdcPostReplyMsg(channelId, seq, flags, reply);
773     cJSON_free(reply);
774     return ret;
775 }
776 
GetUuidByChanId(int32_t channelId,char * uuid,uint32_t len)777 static int32_t GetUuidByChanId(int32_t channelId, char *uuid, uint32_t len)
778 {
779     int64_t authId = GetAuthIdByChanId(channelId);
780     if (authId == AUTH_INVALID_ID) {
781         TRANS_LOGE(TRANS_CTRL, "get authId fail");
782         return SOFTBUS_TRANS_GET_AUTH_ID_FAILED;
783     }
784     return AuthGetDeviceUuid(authId, uuid, len);
785 }
786 
OpenDataBusRequestOutSessionName(const char * mySessionName,const char * peerSessionName)787 static void OpenDataBusRequestOutSessionName(const char *mySessionName, const char *peerSessionName)
788 {
789     char *tmpMyName = NULL;
790     char *tmpPeerName = NULL;
791     Anonymize(mySessionName, &tmpMyName);
792     Anonymize(peerSessionName, &tmpPeerName);
793     TRANS_LOGI(TRANS_CTRL, "OpenDataBusRequest: mySessionName=%{public}s, peerSessionName=%{public}s",
794         AnonymizeWrapper(tmpMyName), AnonymizeWrapper(tmpPeerName));
795     AnonymizeFree(tmpMyName);
796     AnonymizeFree(tmpPeerName);
797 }
798 
GetSessionConnFromDataBusRequest(int32_t channelId,const cJSON * request)799 static SessionConn *GetSessionConnFromDataBusRequest(int32_t channelId, const cJSON *request)
800 {
801     SessionConn *conn = (SessionConn *)SoftBusCalloc(sizeof(SessionConn));
802     if (conn == NULL) {
803         TRANS_LOGE(TRANS_CTRL, "conn calloc failed");
804         return NULL;
805     }
806     if (GetSessionConnById(channelId, conn) != SOFTBUS_OK) {
807         SoftBusFree(conn);
808         TRANS_LOGE(TRANS_CTRL, "get session conn failed");
809         return NULL;
810     }
811     if (UnpackRequest(request, &conn->appInfo) != SOFTBUS_OK) {
812         (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
813         SoftBusFree(conn);
814         TRANS_LOGE(TRANS_CTRL, "UnpackRequest error");
815         return NULL;
816     }
817     int64_t flIdentity = 0;
818     if (GetJsonObjectNumber64Item(request, "FL_IDENTITY", (int64_t *)&flIdentity)) {
819         ServerUpdateHtpChannelPacked(flIdentity, channelId);
820     }
821     (void)LnnGetNetworkIdByUuid(conn->appInfo.peerData.deviceId, conn->appInfo.peerNetWorkId, NETWORK_ID_BUF_LEN);
822     int32_t osType = 0;
823     (void)GetOsTypeByNetworkId(conn->appInfo.peerNetWorkId, &osType);
824     if (osType != OH_OS_TYPE) {
825         DisableCapabilityBit(&conn->appInfo.channelCapability, TRANS_CHANNEL_SINK_GENERATE_KEY_OFFSET);
826     }
827     if (GetCapabilityBit(conn->appInfo.channelCapability, TRANS_CHANNEL_SINK_GENERATE_KEY_OFFSET)) {
828         if (SoftBusGenerateSessionKey(conn->appInfo.sinkSessionKey, SESSION_KEY_LENGTH) != SOFTBUS_OK) {
829             TRANS_LOGE(TRANS_CTRL, "Generate sink SessionKey failed channelId=%{public}d, fd=%{public}d",
830                 conn->channelId, conn->appInfo.fd);
831             SoftBusFree(conn);
832             return NULL;
833         }
834         EnableCapabilityBit(&conn->appInfo.channelCapability, TRANS_CHANNEL_SINK_KEY_ENCRYPT_OFFSET);
835     }
836     return conn;
837 }
838 
NotifyFastDataRecv(SessionConn * conn,int32_t channelId)839 static void NotifyFastDataRecv(SessionConn *conn, int32_t channelId)
840 {
841     TRANS_LOGI(TRANS_CTRL, "enter.");
842     TransReceiveData receiveData;
843     receiveData.data = (void *)conn->appInfo.fastTransData;
844     receiveData.dataLen = conn->appInfo.fastTransDataSize + FAST_TDC_EXT_DATA_SIZE;
845     if (conn->appInfo.businessType == BUSINESS_TYPE_MESSAGE) {
846         receiveData.dataType = TRANS_SESSION_MESSAGE;
847     } else {
848         receiveData.dataType = TRANS_SESSION_BYTES;
849     }
850     if (TransTdcOnMsgReceived(conn->appInfo.myData.pkgName, conn->appInfo.myData.pid, channelId, &receiveData) !=
851         SOFTBUS_OK) {
852         conn->appInfo.fastTransDataSize = 0;
853         TRANS_LOGE(TRANS_CTRL, "err");
854         return;
855     }
856     TRANS_LOGD(TRANS_CTRL, "ok");
857 }
858 
TransTdcFillDataConfig(AppInfo * appInfo)859 static int32_t TransTdcFillDataConfig(AppInfo *appInfo)
860 {
861     if (appInfo == NULL) {
862         TRANS_LOGE(TRANS_CTRL, "appInfo is null");
863         return SOFTBUS_INVALID_PARAM;
864     }
865     if (appInfo->businessType != BUSINESS_TYPE_BYTE && appInfo->businessType != BUSINESS_TYPE_MESSAGE) {
866         TRANS_LOGI(TRANS_CTRL, "invalid businessType=%{public}d", appInfo->businessType);
867         return SOFTBUS_OK;
868     }
869     if (appInfo->peerData.dataConfig != 0) {
870         uint32_t localDataConfig = 0;
871         int32_t ret = TransGetLocalConfig(CHANNEL_TYPE_TCP_DIRECT, appInfo->businessType, &localDataConfig);
872         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get local config fail");
873         appInfo->myData.dataConfig = MIN(localDataConfig, appInfo->peerData.dataConfig);
874         TRANS_LOGI(TRANS_CTRL, "fill dataConfig succ. dataConfig=%{public}u", appInfo->myData.dataConfig);
875         return SOFTBUS_OK;
876     }
877     ConfigType configType =
878         appInfo->businessType == BUSINESS_TYPE_BYTE ? SOFTBUS_INT_MAX_BYTES_LENGTH : SOFTBUS_INT_MAX_MESSAGE_LENGTH;
879     int32_t ret =
880         SoftbusGetConfig(configType, (unsigned char *)&appInfo->myData.dataConfig, sizeof(appInfo->myData.dataConfig));
881     if (ret != SOFTBUS_OK) {
882         TRANS_LOGE(TRANS_CTRL, "get config failed, configType=%{public}d", configType);
883         return ret;
884     }
885     TRANS_LOGI(TRANS_CTRL, "fill dataConfig=%{public}d", appInfo->myData.dataConfig);
886     return SOFTBUS_OK;
887 }
888 
ReleaseSessionConn(SessionConn * chan)889 static void ReleaseSessionConn(SessionConn *chan)
890 {
891     if (chan == NULL) {
892         return;
893     }
894     if (chan->appInfo.fastTransData != NULL) {
895         SoftBusFree((void *)chan->appInfo.fastTransData);
896     }
897     SoftBusFree(chan);
898 }
899 
ReportTransEventExtra(TransEventExtra * extra,int32_t channelId,SessionConn * conn,NodeInfo * nodeInfo,char * peerUuid)900 static void ReportTransEventExtra(
901     TransEventExtra *extra, int32_t channelId, SessionConn *conn, NodeInfo *nodeInfo, char *peerUuid)
902 {
903     extra->socketName = conn->appInfo.myData.sessionName;
904     extra->calleePkg = NULL;
905     extra->callerPkg = NULL;
906     extra->channelId = channelId;
907     extra->peerChannelId = conn->appInfo.peerData.channelId;
908     extra->socketFd = conn->appInfo.fd;
909     extra->result = EVENT_STAGE_RESULT_OK;
910     bool peerRet = GetUuidByChanId(channelId, peerUuid, DEVICE_ID_SIZE_MAX) == SOFTBUS_OK &&
911         LnnGetRemoteNodeInfoById(peerUuid, CATEGORY_UUID, nodeInfo) == SOFTBUS_OK;
912     if (peerRet) {
913         extra->peerUdid = nodeInfo->deviceInfo.deviceUdid;
914         extra->peerDevVer = nodeInfo->deviceInfo.deviceVersion;
915     }
916     if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, nodeInfo->masterUdid, UDID_BUF_LEN) == SOFTBUS_OK) {
917         extra->localUdid = nodeInfo->masterUdid;
918     }
919     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL_SERVER, EVENT_STAGE_HANDSHAKE_START, *extra);
920 }
921 
CheckServerPermission(AppInfo * appInfo,char * ret)922 static int32_t CheckServerPermission(AppInfo *appInfo, char *ret)
923 {
924     if (appInfo->fdProtocol == LNN_PROTOCOL_HTP && !CheckHtpPermissionPacked(appInfo->myData.uid)) {
925         ret = (char *)"Server not allow using htp";
926         TRANS_LOGE(TRANS_CTRL, "sink uid=%{public}d not allow using htp", appInfo->myData.uid);
927         return SOFTBUS_PERMISSION_SERVER_DENIED;
928     }
929     if (appInfo->callingTokenId != TOKENID_NOT_SET) {
930         (void)LnnGetNetworkIdByUuid(appInfo->peerData.deviceId, appInfo->peerNetWorkId, NETWORK_ID_BUF_LEN);
931         int32_t osType = 0;
932         GetOsTypeByNetworkId(appInfo->peerNetWorkId, &osType);
933         if (osType != OH_OS_TYPE) {
934             TRANS_LOGI(TRANS_CTRL, "not support acl check osType=%{public}d", osType);
935         } else if (GetCapabilityBit(appInfo->channelCapability, TRANS_CHANNEL_ACL_CHECK_OFFSET)) {
936             if (TransCheckServerAccessControl(appInfo) != SOFTBUS_OK) {
937                 ret = (char *)"Server check acl failed";
938                 return SOFTBUS_TRANS_CHECK_ACL_FAILED;
939             }
940         } else {
941             TRANS_LOGI(TRANS_CTRL, "not support acl check");
942         }
943     }
944 
945     if (CheckSecLevelPublic(appInfo->myData.sessionName, appInfo->peerData.sessionName) != SOFTBUS_OK) {
946         ret = (char *)"Server check session name failed";
947         return SOFTBUS_PERMISSION_SERVER_DENIED;
948     }
949 
950     return SOFTBUS_OK;
951 }
952 
TransTdcCheckCollabRelation(const AppInfo * appInfo,int32_t channelId,char * ret)953 static int32_t TransTdcCheckCollabRelation(const AppInfo *appInfo, int32_t channelId, char *ret)
954 {
955     OpenDataBusRequestOutSessionName(appInfo->myData.sessionName, appInfo->peerData.sessionName);
956     TRANS_LOGI(TRANS_CTRL, "OpenDataBusRequest: myPid=%{public}d, peerPid=%{public}d",
957         appInfo->myData.pid, appInfo->peerData.pid);
958 
959     char *errDesc = NULL;
960     int32_t errCode = CheckCollabRelation(appInfo, channelId, CHANNEL_TYPE_TCP_DIRECT);
961     if (errCode == SOFTBUS_TRANS_NOT_NEED_CHECK_RELATION) {
962         errCode = NotifyChannelOpened(channelId);
963         if (errCode != SOFTBUS_OK) {
964             TRANS_LOGE(TRANS_CTRL, "Notify SDK Channel Opened Failed, ret=%{public}d", errCode);
965             errDesc = (char *)"Notify SDK Channel Opened Failed";
966             goto ERR_EXIT;
967         }
968     } else if (errCode != SOFTBUS_OK) {
969         TRANS_LOGE(TRANS_CTRL, "CheckCollabRelation Failed, ret=%{public}d", errCode);
970         errDesc = (char *)"CheckCollabRelation Failed";
971         goto ERR_EXIT;
972     }
973     return SOFTBUS_OK;
974 ERR_EXIT:
975     if (strcpy_s(ret, MAX_ERRDESC_LEN, errDesc) != EOK) {
976         TRANS_LOGW(TRANS_CTRL, "strcpy failed");
977     }
978     return errCode;
979 }
980 
TransTdcFillAppInfoAndNotifyChannel(AppInfo * appInfo,int32_t channelId,char * errDesc)981 static int32_t TransTdcFillAppInfoAndNotifyChannel(AppInfo *appInfo, int32_t channelId, char *errDesc)
982 {
983     char *ret = NULL;
984     int32_t errCode = SOFTBUS_OK;
985     if (TransTdcGetUidAndPid(appInfo->myData.sessionName, &appInfo->myData.uid, &appInfo->myData.pid) != SOFTBUS_OK) {
986         errCode = SOFTBUS_TRANS_PEER_SESSION_NOT_CREATED;
987         ret = (char *)"Peer Device Session Not Create";
988         goto ERR_EXIT;
989     }
990     errCode = GetTokenTypeBySessionName(appInfo->myData.sessionName, &appInfo->myData.tokenType);
991     if (errCode != SOFTBUS_OK) {
992         TRANS_LOGE(TRANS_CTRL, "get tokenType failed.");
993         goto ERR_EXIT;
994     }
995     FillHapSinkAclInfoToAppInfo(appInfo);
996     errCode = GetUuidByChanId(channelId, appInfo->peerData.deviceId, DEVICE_ID_SIZE_MAX);
997     if (errCode != SOFTBUS_OK) {
998         TRANS_LOGE(TRANS_CTRL, "Auth: Get Uuid By ChanId failed.");
999         ret = (char *)"Get Uuid By ChanId failed";
1000         goto ERR_EXIT;
1001     }
1002     errCode = CheckServerPermission(appInfo, ret);
1003     if (errCode != SOFTBUS_OK) {
1004         goto ERR_EXIT;
1005     }
1006     errCode = TransTdcFillDataConfig(appInfo);
1007     if (errCode != SOFTBUS_OK) {
1008         TRANS_LOGE(TRANS_CTRL, "fill data config failed.");
1009         ret = (char *)"fill data config failed";
1010         goto ERR_EXIT;
1011     }
1012     appInfo->myHandleId = 0;
1013     errCode = SetAppInfoById(channelId, appInfo);
1014     if (errCode != SOFTBUS_OK) {
1015         TRANS_LOGE(TRANS_CTRL, "set app info by id failed.");
1016         ret = (char *)"Set App Info By Id Failed";
1017         goto ERR_EXIT;
1018     }
1019     errCode = TransTdcCheckCollabRelation(appInfo, channelId, ret);
1020     if (errCode != SOFTBUS_OK) {
1021         goto ERR_EXIT;
1022     }
1023 
1024     return SOFTBUS_OK;
1025 ERR_EXIT:
1026     if (strcpy_s(errDesc, MAX_ERRDESC_LEN, ret) != EOK) {
1027         TRANS_LOGW(TRANS_CTRL, "strcpy failed");
1028     }
1029     return errCode;
1030 }
1031 
HandleDataBusReply(SessionConn * conn,int32_t channelId,TransEventExtra * extra,uint32_t flags,uint64_t seq)1032 static int32_t HandleDataBusReply(
1033     SessionConn *conn, int32_t channelId, TransEventExtra *extra, uint32_t flags, uint64_t seq)
1034 {
1035     int32_t ret = OpenDataBusRequestReply(&conn->appInfo, channelId, seq, flags);
1036     if (ret != SOFTBUS_OK) {
1037         TRANS_LOGE(TRANS_CTRL, "OpenDataBusRequest reply err");
1038         (void)NotifyChannelClosed(&conn->appInfo, channelId);
1039         return ret;
1040     }
1041     extra->result = EVENT_STAGE_RESULT_OK;
1042     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL_SERVER, EVENT_STAGE_HANDSHAKE_REPLY, *extra);
1043     SetByteChannelTos(&conn->appInfo);
1044     if (conn->appInfo.routeType == WIFI_P2P &&
1045         LnnGetNetworkIdByUuid(conn->appInfo.peerData.deviceId, conn->appInfo.peerNetWorkId, DEVICE_ID_SIZE_MAX) ==
1046         SOFTBUS_OK) {
1047         TRANS_LOGI(TRANS_CTRL, "get networkId by uuid");
1048         LaneUpdateP2pAddressByIp(conn->appInfo.peerData.addr, conn->appInfo.peerNetWorkId);
1049     }
1050     return SOFTBUS_OK;
1051 }
1052 
OpenDataBusRequest(int32_t channelId,uint32_t flags,uint64_t seq,const cJSON * request)1053 static int32_t OpenDataBusRequest(int32_t channelId, uint32_t flags, uint64_t seq, const cJSON *request)
1054 {
1055     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, seq=%{public}" PRIu64, channelId, seq);
1056     SessionConn *conn = GetSessionConnFromDataBusRequest(channelId, request);
1057     TRANS_CHECK_AND_RETURN_RET_LOGE(conn != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, "conn is null");
1058 
1059     TransEventExtra extra;
1060     char peerUuid[DEVICE_ID_SIZE_MAX] = { 0 };
1061     NodeInfo nodeInfo;
1062     (void)memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
1063     ReportTransEventExtra(&extra, channelId, conn, &nodeInfo, peerUuid);
1064 
1065     if ((flags & FLAG_AUTH_META) != 0) {
1066         TRANS_LOGE(TRANS_CTRL, "not support meta auth.");
1067         ReleaseSessionConn(conn);
1068         return SOFTBUS_FUNC_NOT_SUPPORT;
1069     }
1070     char errDesc[MAX_ERRDESC_LEN] = { 0 };
1071     int32_t errCode = TransTdcFillAppInfoAndNotifyChannel(&conn->appInfo, channelId, errDesc);
1072     if (errCode != SOFTBUS_OK) {
1073         if (OpenDataBusRequestError(channelId, seq, errDesc, errCode, flags) != SOFTBUS_OK) {
1074             TRANS_LOGE(TRANS_CTRL, "OpenDataBusRequestError error");
1075         }
1076         (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
1077         (void)TransDelTcpChannelInfoByChannelId(channelId);
1078         TransDelSessionConnById(channelId);
1079         CloseHtpChannelPacked(channelId);
1080     }
1081     ReleaseSessionConn(conn);
1082     return errCode;
1083 }
1084 
ProcessMessage(int32_t channelId,uint32_t flags,uint64_t seq,const char * msg,uint32_t dataLen)1085 static int32_t ProcessMessage(int32_t channelId, uint32_t flags, uint64_t seq, const char *msg, uint32_t dataLen)
1086 {
1087     int32_t ret;
1088     cJSON *json = cJSON_ParseWithLength(msg, dataLen);
1089     if (json == NULL) {
1090         TRANS_LOGE(TRANS_CTRL, "json parse failed.");
1091         return SOFTBUS_PARSE_JSON_ERR;
1092     }
1093     if (flags & FLAG_REPLY) {
1094         ret = OpenDataBusReply(channelId, seq, json);
1095     } else {
1096         ret = OpenDataBusRequest(channelId, flags, seq, json);
1097     }
1098     cJSON_Delete(json);
1099     AppInfo appInfo;
1100     TRANS_CHECK_AND_RETURN_RET_LOGE(
1101         GetAppInfoById(channelId, &appInfo) == SOFTBUS_OK, ret, TRANS_CTRL, "get appInfo fail");
1102     char *tmpNetWorkId = NULL;
1103     char *tmpUdid = NULL;
1104     Anonymize(appInfo.peerNetWorkId, &tmpNetWorkId);
1105     Anonymize(appInfo.peerUdid, &tmpUdid);
1106     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}d, peerNetWorkId=%{public}s, peerUdid=%{public}s, ret=%{public}d",
1107         channelId, AnonymizeWrapper(tmpNetWorkId), AnonymizeWrapper(tmpUdid), ret);
1108     AnonymizeFree(tmpNetWorkId);
1109     AnonymizeFree(tmpUdid);
1110     return ret;
1111 }
1112 
GetAuthIdByChannelInfo(int32_t channelId,uint64_t seq,uint32_t cipherFlag,AuthHandle * authHandle)1113 static int32_t GetAuthIdByChannelInfo(int32_t channelId, uint64_t seq, uint32_t cipherFlag, AuthHandle *authHandle)
1114 {
1115     if (authHandle == NULL) {
1116         TRANS_LOGE(TRANS_CTRL, "authHandle is null");
1117         return SOFTBUS_INVALID_PARAM;
1118     }
1119     if (GetAuthHandleByChanId(channelId, authHandle) == SOFTBUS_OK && authHandle->authId != AUTH_INVALID_ID) {
1120         TRANS_LOGI(TRANS_CTRL, "authId=%{public}" PRId64 " is not AUTH_INVALID_ID", authHandle->authId);
1121         return SOFTBUS_OK;
1122     }
1123 
1124     AppInfo appInfo;
1125     int32_t ret = GetAppInfoById(channelId, &appInfo);
1126     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get appInfo fail");
1127 
1128     bool fromAuthServer = ((seq & AUTH_CONN_SERVER_SIDE) != 0);
1129     char uuid[UUID_BUF_LEN] = { 0 };
1130     struct WifiDirectManager *mgr = GetWifiDirectManager();
1131     if (mgr == NULL || mgr->getRemoteUuidByIp == NULL) {
1132         TRANS_LOGE(TRANS_CTRL, "GetWifiDirectManager failed");
1133         return SOFTBUS_WIFI_DIRECT_INIT_FAILED;
1134     }
1135     ret = mgr->getRemoteUuidByIp(appInfo.peerData.addr, uuid, sizeof(uuid));
1136     (void)memset_s(appInfo.sessionKey, sizeof(appInfo.sessionKey), 0, sizeof(appInfo.sessionKey));
1137     if (ret != SOFTBUS_OK) {
1138         AuthConnInfo connInfo;
1139         TRANS_LOGI(TRANS_CTRL, "protoclType=%{public}d", appInfo.protocol);
1140         connInfo.type = (appInfo.protocol == LNN_PROTOCOL_USB) ? AUTH_LINK_TYPE_USB : AUTH_LINK_TYPE_WIFI;
1141         if (strcpy_s(connInfo.info.ipInfo.ip, IP_LEN, appInfo.peerData.addr) != EOK) {
1142             TRANS_LOGE(TRANS_CTRL, "copy ip addr fail");
1143             return SOFTBUS_MEM_ERR;
1144         }
1145         char *tmpPeerIp = NULL;
1146         Anonymize(appInfo.peerData.addr, &tmpPeerIp);
1147         TRANS_LOGE(TRANS_CTRL, "channelId=%{public}d get remote uuid by Ip=%{public}s failed",
1148             channelId, AnonymizeWrapper(tmpPeerIp));
1149         AnonymizeFree(tmpPeerIp);
1150         authHandle->type = connInfo.type;
1151         authHandle->authId = AuthGetIdByConnInfo(&connInfo, !fromAuthServer, false);
1152         return SOFTBUS_OK;
1153     }
1154 
1155     AuthLinkType linkType = SwitchCipherTypeToAuthLinkType(cipherFlag);
1156     TRANS_LOGI(TRANS_CTRL, "get auth linkType=%{public}d, flag=0x%{public}x", linkType, cipherFlag);
1157     bool isAuthMeta = (cipherFlag & FLAG_AUTH_META) ? true : false;
1158     authHandle->type = linkType;
1159     authHandle->authId = AuthGetIdByUuid(uuid, linkType, !fromAuthServer, isAuthMeta);
1160     return SOFTBUS_OK;
1161 }
1162 
DecryptMessage(int32_t channelId,const TdcPacketHead * pktHead,const uint8_t * pktData,uint8_t ** outData,uint32_t * outDataLen)1163 static int32_t DecryptMessage(
1164     int32_t channelId, const TdcPacketHead *pktHead, const uint8_t *pktData, uint8_t **outData, uint32_t *outDataLen)
1165 {
1166     AuthHandle authHandle = { .authId = AUTH_INVALID_ID };
1167     int32_t ret = GetAuthIdByChannelInfo(channelId, pktHead->seq, pktHead->flags, &authHandle);
1168     if (ret != SOFTBUS_OK || (authHandle.authId == AUTH_INVALID_ID && pktHead->flags == FLAG_P2P)) {
1169         TRANS_LOGW(TRANS_CTRL, "get p2p authId fail, peer device may be legacyOs, retry hml");
1170         // we don't know peer device is legacyOs or not, so retry hml when flag is p2p and get auth failed
1171         ret = GetAuthIdByChannelInfo(channelId, pktHead->seq, FLAG_ENHANCE_P2P, &authHandle);
1172     }
1173     if (ret != SOFTBUS_OK || authHandle.authId == AUTH_INVALID_ID) {
1174         TRANS_LOGE(TRANS_CTRL, "srv process recv data: get authId fail.");
1175         return SOFTBUS_NOT_FIND;
1176     }
1177     ret = SetAuthHandleByChanId(channelId, &authHandle);
1178     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "srv process recv data: set authId fail.");
1179     uint32_t decDataLen = AuthGetDecryptSize(pktHead->dataLen) + 1;
1180     uint8_t *decData = (uint8_t *)SoftBusCalloc(decDataLen);
1181     if (decData == NULL) {
1182         TRANS_LOGE(TRANS_CTRL, "srv process recv data: malloc fail.");
1183         return SOFTBUS_MALLOC_ERR;
1184     }
1185     if (AuthDecrypt(&authHandle, pktData, pktHead->dataLen, decData, &decDataLen) != SOFTBUS_OK) {
1186         TRANS_LOGE(TRANS_CTRL, "srv process recv data: decrypt fail.");
1187         SoftBusFree(decData);
1188         return SOFTBUS_DECRYPT_ERR;
1189     }
1190     *outData = decData;
1191     *outDataLen = decDataLen;
1192     return SOFTBUS_OK;
1193 }
1194 
ProcessReceivedData(int32_t channelId,int32_t type)1195 static int32_t ProcessReceivedData(int32_t channelId, int32_t type)
1196 {
1197     TRANS_CHECK_AND_RETURN_RET_LOGE(
1198         SoftBusMutexLock(&g_tcpSrvDataList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock failed.");
1199     DataBuf *node = TransSrvGetDataBufNodeById(channelId);
1200     if (node == NULL || node->data == NULL) {
1201         TRANS_LOGE(TRANS_CTRL, "node is null.");
1202         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1203         return SOFTBUS_TRANS_NODE_IS_NULL;
1204     }
1205     TdcPacketHead *pktHead = (TdcPacketHead *)(node->data);
1206     uint8_t *pktData = (uint8_t *)(node->data + sizeof(TdcPacketHead));
1207     if (pktHead->module != MODULE_SESSION) {
1208         TRANS_LOGE(TRANS_CTRL, "srv process recv data: illegal module.");
1209         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1210         return SOFTBUS_TRANS_ILLEGAL_MODULE;
1211     }
1212     uint64_t seq = pktHead->seq;
1213     uint32_t flags = pktHead->flags;
1214     uint8_t *data = NULL;
1215     uint32_t dataLen = 0;
1216 
1217     TRANS_LOGI(TRANS_CTRL, "recv tdc packet. channelId=%{public}d, flags=%{public}d, seq=%{public}" PRIu64,
1218         channelId, flags, seq);
1219     if (DecryptMessage(channelId, pktHead, pktData, &data, &dataLen) != SOFTBUS_OK) {
1220         TRANS_LOGE(TRANS_CTRL, "srv process recv data: decrypt fail.");
1221         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1222         return SOFTBUS_DECRYPT_ERR;
1223     }
1224 
1225     char *end = node->data + sizeof(TdcPacketHead) + pktHead->dataLen;
1226     if (memmove_s(node->data, node->size, end, node->w - end) != EOK) {
1227         SoftBusFree(data);
1228         TRANS_LOGE(TRANS_CTRL, "memmove fail.");
1229         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1230         return SOFTBUS_MEM_ERR;
1231     }
1232     node->w = node->w - sizeof(TdcPacketHead) - pktHead->dataLen;
1233     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1234     int32_t ret = ProcessMessage(channelId, flags, seq, (char *)data, dataLen);
1235     SoftBusFree(data);
1236     return ret;
1237 }
1238 
TransTdcSrvProcData(ListenerModule module,int32_t channelId,int32_t type)1239 static int32_t TransTdcSrvProcData(ListenerModule module, int32_t channelId, int32_t type)
1240 {
1241     TRANS_CHECK_AND_RETURN_RET_LOGE(g_tcpSrvDataList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_tcpSrvDataList is NULL");
1242     int32_t ret = SoftBusMutexLock(&g_tcpSrvDataList->lock);
1243     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock failed.");
1244 
1245     DataBuf *node = TransSrvGetDataBufNodeById(channelId);
1246     if (node == NULL) {
1247         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1248         TRANS_LOGE(TRANS_CTRL,
1249             "srv can not get buf node. listenerModule=%{public}d, channelId=%{public}d, type=%{public}d",
1250             (int32_t)module, channelId, type);
1251         return SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED;
1252     }
1253 
1254     uint32_t bufLen = node->w - node->data;
1255     if (bufLen < DC_MSG_PACKET_HEAD_SIZE) {
1256         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1257         TRANS_LOGE(TRANS_CTRL,
1258             "srv head not enough, recv next time. "
1259             "listenerModule=%{public}d, bufLen=%{public}u channelId=%{public}d, type=%{public}d",
1260             (int32_t)module, bufLen, channelId, type);
1261         return SOFTBUS_DATA_NOT_ENOUGH;
1262     }
1263 
1264     TdcPacketHead *pktHead = (TdcPacketHead *)(node->data);
1265     UnpackTdcPacketHead(pktHead);
1266     if (pktHead->magicNumber != MAGIC_NUMBER) {
1267         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1268         TRANS_LOGE(TRANS_CTRL,
1269             "srv recv invalid packet head listenerModule=%{public}d, channelId=%{public}d, type=%{public}d",
1270             (int32_t)module, channelId, type);
1271         return SOFTBUS_TRANS_UNPACK_PACKAGE_HEAD_FAILED;
1272     }
1273 
1274     uint32_t dataLen = pktHead->dataLen;
1275     if (dataLen > node->size - DC_MSG_PACKET_HEAD_SIZE) {
1276         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1277         TRANS_LOGE(TRANS_CTRL,
1278             "srv out of recv dataLen=%{public}u, listenerModule=%{public}d, channelId=%{public}d, type=%{public}d",
1279             dataLen, (int32_t)module, channelId, type);
1280         return SOFTBUS_TRANS_UNPACK_PACKAGE_HEAD_FAILED;
1281     }
1282 
1283     if (bufLen < dataLen + DC_MSG_PACKET_HEAD_SIZE) {
1284         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1285         TRANS_LOGE(TRANS_CTRL,
1286             "srv data not enough, recv next time. bufLen=%{public}u, dataLen=%{public}u, headLen=%{public}d "
1287             "listenerModule=%{public}d, channelId=%{public}d, type=%{public}d",
1288             bufLen, dataLen, (int32_t)DC_MSG_PACKET_HEAD_SIZE, (int32_t)module, channelId, type);
1289         return SOFTBUS_DATA_NOT_ENOUGH;
1290     }
1291     DelTrigger(module, node->fd, READ_TRIGGER);
1292     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1293     return ProcessReceivedData(channelId, type);
1294 }
1295 
TransTdcGetDataBufInfoByChannelId(int32_t channelId,int32_t * fd,size_t * len)1296 static int32_t TransTdcGetDataBufInfoByChannelId(int32_t channelId, int32_t *fd, size_t *len)
1297 {
1298     if (fd == NULL || len == NULL) {
1299         TRANS_LOGW(TRANS_CTRL, "invalid param.");
1300         return SOFTBUS_INVALID_PARAM;
1301     }
1302     if (g_tcpSrvDataList == NULL) {
1303         TRANS_LOGE(TRANS_CTRL, "tcp srv data list empty.");
1304         return SOFTBUS_NO_INIT;
1305     }
1306     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
1307         TRANS_LOGE(TRANS_CTRL, "lock failed.");
1308         return SOFTBUS_LOCK_ERR;
1309     }
1310     DataBuf *item = NULL;
1311     LIST_FOR_EACH_ENTRY(item, &(g_tcpSrvDataList->list), DataBuf, node) {
1312         if (item->channelId == channelId) {
1313             *fd = item->fd;
1314             *len = item->size - (item->w - item->data);
1315             (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1316             return SOFTBUS_OK;
1317         }
1318     }
1319     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1320     TRANS_LOGI(TRANS_CTRL, "trans tdc data buf not found. channelId=%{public}d", channelId);
1321     return SOFTBUS_TRANS_TCP_DATABUF_NOT_FOUND;
1322 }
1323 
TransTdcUpdateDataBufWInfo(int32_t channelId,char * recvBuf,int32_t recvLen)1324 static int32_t TransTdcUpdateDataBufWInfo(int32_t channelId, char *recvBuf, int32_t recvLen)
1325 {
1326     if (recvBuf == NULL) {
1327         TRANS_LOGW(TRANS_CTRL, "invalid param.");
1328         return SOFTBUS_INVALID_PARAM;
1329     }
1330     if (g_tcpSrvDataList == NULL) {
1331         TRANS_LOGE(TRANS_CTRL, "srv data list empty.");
1332         return SOFTBUS_NO_INIT;
1333     }
1334     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
1335         TRANS_LOGE(TRANS_CTRL, "lock failed.");
1336         return SOFTBUS_LOCK_ERR;
1337     }
1338     DataBuf *item = NULL;
1339     DataBuf *nextItem = NULL;
1340     LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &(g_tcpSrvDataList->list), DataBuf, node) {
1341         if (item->channelId != channelId) {
1342             continue;
1343         }
1344         int32_t freeLen = (int32_t)(item->size) - (item->w - item->data);
1345         if (recvLen > freeLen) {
1346             (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1347             TRANS_LOGE(TRANS_CTRL, "trans tdc. recvLen=%{public}d, freeLen=%{public}d.", recvLen, freeLen);
1348             return SOFTBUS_TRANS_RECV_DATA_OVER_LEN;
1349         }
1350         if (memcpy_s(item->w, recvLen, recvBuf, recvLen) != EOK) {
1351             (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1352             TRANS_LOGE(TRANS_CTRL, "memcpy_s trans tdc failed. channelId=%{public}d", channelId);
1353             return SOFTBUS_MEM_ERR;
1354         }
1355         item->w += recvLen;
1356         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1357         return SOFTBUS_OK;
1358     }
1359     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1360     TRANS_LOGE(TRANS_CTRL, "trans update tdc databuf not found. channelId=%{public}d", channelId);
1361     return SOFTBUS_TRANS_TCP_DATABUF_NOT_FOUND;
1362 }
1363 
TransRecvTdcSocketData(int32_t channelId,char * buffer,int32_t bufferSize)1364 static int32_t TransRecvTdcSocketData(int32_t channelId, char *buffer, int32_t bufferSize)
1365 {
1366     int32_t fd = -1;
1367     size_t len = 0;
1368     int32_t ret = TransTdcGetDataBufInfoByChannelId(channelId, &fd, &len);
1369     TRANS_CHECK_AND_RETURN_RET_LOGE(
1370         ret == SOFTBUS_OK, SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED, TRANS_CTRL, "get info failed, ret=%{public}d", ret);
1371     TRANS_CHECK_AND_RETURN_RET_LOGE(len >= (size_t)bufferSize, SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED, TRANS_CTRL,
1372         "freeBufferLen=%{public}zu less than bufferSize=%{public}d. channelId=%{public}d", len, bufferSize, channelId);
1373 
1374     int32_t totalRecvLen = 0;
1375     while (totalRecvLen < bufferSize) {
1376         int32_t recvLen = ConnRecvSocketData(fd, buffer, bufferSize - totalRecvLen, 0);
1377         if (recvLen < 0) {
1378             TRANS_LOGE(TRANS_CTRL,
1379                 "recv tcp data fail, channelId=%{public}d, retLen=%{public}d, total=%{public}d, totalRecv=%{public}d",
1380                 channelId, recvLen, bufferSize, totalRecvLen);
1381             return GetErrCodeBySocketErr(SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED);
1382         } else if (recvLen == 0) {
1383             TRANS_LOGE(TRANS_CTRL,
1384                 "recv tcp data fail, retLen=0, channelId=%{public}d, total=%{public}d, totalRecv=%{public}d",
1385                 channelId, bufferSize, totalRecvLen);
1386             return SOFTBUS_DATA_NOT_ENOUGH;
1387         }
1388 
1389         if (TransTdcUpdateDataBufWInfo(channelId, buffer, recvLen) != SOFTBUS_OK) {
1390             TRANS_LOGE(TRANS_CTRL, "update channel data buf failed. channelId=%{public}d", channelId);
1391             return SOFTBUS_TRANS_UPDATE_DATA_BUF_FAILED;
1392         }
1393         buffer += recvLen;
1394         totalRecvLen += recvLen;
1395     }
1396 
1397     return SOFTBUS_OK;
1398 }
1399 
1400 /*
1401  * The negotiation message may be unpacked, and when obtaining the message,
1402  * it is necessary to first check whether the buffer of the channel already has data.
1403  */
TransReadDataLen(int32_t channelId,int32_t * pktDataLen,int32_t module,int32_t type)1404 static int32_t TransReadDataLen(int32_t channelId, int32_t *pktDataLen, int32_t module, int32_t type)
1405 {
1406     if (g_tcpSrvDataList == NULL) {
1407         TRANS_LOGE(TRANS_CTRL, "tcp srv data list empty channelId=%{public}d %{public}d.", channelId, module);
1408         return SOFTBUS_NO_INIT;
1409     }
1410 
1411     if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) {
1412         TRANS_LOGE(TRANS_CTRL, "lock failed channelId=%{public}d %{public}d.", channelId, module);
1413         return SOFTBUS_LOCK_ERR;
1414     }
1415 
1416     DataBuf *dataBuf = TransSrvGetDataBufNodeById(channelId);
1417     if (dataBuf == NULL) {
1418         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1419         return SOFTBUS_TRANS_TCP_DATABUF_NOT_FOUND;
1420     }
1421 
1422     const uint32_t headSize = sizeof(TdcPacketHead);
1423     uint32_t bufDataLen = dataBuf->w - dataBuf->data;
1424     const uint32_t maxDataLen = dataBuf->size - headSize;
1425 
1426     TdcPacketHead *pktHeadPtr = NULL;
1427     // channel buffer already has header data
1428     if (bufDataLen >= headSize) {
1429         bufDataLen -= headSize;
1430         pktHeadPtr = (TdcPacketHead *)(dataBuf->data);
1431         // obtain the remaining length of data to be read
1432         *pktDataLen = pktHeadPtr->dataLen - bufDataLen;
1433         (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1434         return SOFTBUS_OK;
1435     }
1436     (void)SoftBusMutexUnlock(&g_tcpSrvDataList->lock);
1437 
1438     TdcPacketHead pktHead;
1439     (void)memset_s(&pktHead, sizeof(pktHead), 0, sizeof(pktHead));
1440     int32_t ret = TransRecvTdcSocketData(channelId, (char *)&pktHead, headSize);
1441     if (ret != SOFTBUS_OK) {
1442         return ret;
1443     }
1444 
1445     UnpackTdcPacketHead(&pktHead);
1446     if (pktHead.magicNumber != MAGIC_NUMBER || pktHead.dataLen > maxDataLen || pktHead.dataLen == 0) {
1447         TRANS_LOGE(TRANS_CTRL,
1448             "invalid packet head "
1449             "module=%{public}d, channelId=%{public}d, type=%{public}d, magic=%{public}x, len=%{public}d",
1450             module, channelId, type, pktHead.magicNumber, pktHead.dataLen);
1451         return SOFTBUS_TRANS_UNPACK_PACKAGE_HEAD_FAILED;
1452     }
1453     *pktDataLen = pktHead.dataLen;
1454 
1455     return SOFTBUS_OK;
1456 }
1457 
TransTdcSrvRecvData(ListenerModule module,int32_t channelId,int32_t type)1458 int32_t TransTdcSrvRecvData(ListenerModule module, int32_t channelId, int32_t type)
1459 {
1460     int32_t dataSize = 0;
1461     int32_t ret = TransReadDataLen(channelId, &dataSize, (int32_t)module, type);
1462     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED, TRANS_CTRL,
1463         "read dataLen failed, ret=%{public}d", ret);
1464 
1465     char *dataBuffer = (char *)SoftBusCalloc(dataSize);
1466     if (dataBuffer == NULL) {
1467         TRANS_LOGE(TRANS_CTRL, "malloc failed. channelId=%{public}d, len=%{public}d", channelId, dataSize);
1468         return SOFTBUS_MALLOC_ERR;
1469     }
1470     ret = TransRecvTdcSocketData(channelId, dataBuffer, dataSize);
1471     if (ret != SOFTBUS_OK) {
1472         SoftBusFree(dataBuffer);
1473         return ret;
1474     }
1475     SoftBusFree(dataBuffer);
1476 
1477     return TransTdcSrvProcData(module, channelId, type);
1478 }
1479 
TransCleanTdcSource(int32_t channelId)1480 static void TransCleanTdcSource(int32_t channelId)
1481 {
1482     (void)TransDelTcpChannelInfoByChannelId(channelId);
1483     TransDelSessionConnById(channelId);
1484     TransSrvDelDataBufNode(channelId);
1485 }
1486 
TransProcessAsyncOpenTdcChannelFailed(SessionConn * conn,int32_t openResult,uint64_t seq,uint32_t flags)1487 static void TransProcessAsyncOpenTdcChannelFailed(SessionConn *conn, int32_t openResult, uint64_t seq, uint32_t flags)
1488 {
1489     char errDesc[MAX_ERRDESC_LEN] = { 0 };
1490     char *desc = (char *)"Tdc channel open failed";
1491     if (strcpy_s(errDesc, MAX_ERRDESC_LEN, desc) != EOK) {
1492         TRANS_LOGW(TRANS_CTRL, "strcpy failed");
1493     }
1494     if (OpenDataBusRequestError(conn->channelId, seq, errDesc, openResult, flags) != SOFTBUS_OK) {
1495         TRANS_LOGE(TRANS_CTRL, "OpenDataBusRequestError error");
1496     }
1497     (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
1498     TransCleanTdcSource(conn->channelId);
1499     CloseTcpDirectFd(conn->listenMod, conn->appInfo.fd);
1500 }
1501 
HandleTdcChannelOpenedReply(SessionConn * conn,int32_t channelId,TransEventExtra * extra,uint32_t flags,uint64_t seq)1502 static int32_t HandleTdcChannelOpenedReply(
1503     SessionConn *conn, int32_t channelId, TransEventExtra *extra, uint32_t flags, uint64_t seq)
1504 {
1505     int32_t ret = HandleDataBusReply(conn, channelId, extra, flags, seq);
1506     (void)memset_s(conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey), 0, sizeof(conn->appInfo.sessionKey));
1507     (void)memset_s(
1508         conn->appInfo.sinkSessionKey, sizeof(conn->appInfo.sinkSessionKey), 0, sizeof(conn->appInfo.sinkSessionKey));
1509     TransDelSessionConnById(channelId);
1510     CloseTcpDirectFd(conn->listenMod, conn->appInfo.fd);
1511     if (ret != SOFTBUS_OK) {
1512         (void)TransDelTcpChannelInfoByChannelId(channelId);
1513         TransSrvDelDataBufNode(channelId);
1514         return ret;
1515     }
1516     ret = NotifyChannelBind(channelId, conn);
1517     if (ret != SOFTBUS_OK) {
1518         (void)TransDelTcpChannelInfoByChannelId(channelId);
1519         TransSrvDelDataBufNode(channelId);
1520         return ret;
1521     }
1522     TransSrvDelDataBufNode(channelId);
1523     return SOFTBUS_OK;
1524 }
1525 
HandleTdcGenUkResult(uint32_t requestId,int32_t ukId,int32_t reason)1526 static void HandleTdcGenUkResult(uint32_t requestId, int32_t ukId, int32_t reason)
1527 {
1528     UkRequestNode requestNode;
1529     int32_t ret = TransUkRequestGetRequestInfoByRequestId(requestId, &requestNode);
1530     if (ret != SOFTBUS_OK) {
1531         TRANS_LOGE(TRANS_CTRL, "get uk request info failed.");
1532         (void)TransUkRequestDeleteItem(requestId);
1533         return;
1534     }
1535     int32_t channelId = requestNode.channelId;
1536     SessionConn conn;
1537     (void)memset_s(&conn, sizeof(SessionConn), 0, sizeof(SessionConn));
1538     ret = GetSessionConnById(channelId, &conn);
1539     TRANS_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, TRANS_CTRL, "get sessionConn failed, ret=%{public}d", ret);
1540     uint32_t flags = 0;
1541     uint64_t seq = 0;
1542     ret = TransSrvGetSeqAndFlagsByChannelId(&seq, &flags, channelId);
1543     if (ret != SOFTBUS_OK) {
1544         TRANS_LOGE(TRANS_CTRL, "get seqs and flags failed, channelId=%{public}d, ret=%{public}d", channelId, ret);
1545         return;
1546     }
1547     if (reason != SOFTBUS_OK) {
1548         TRANS_LOGE(TRANS_CTRL, "gen uk failed, channelId=%{public}d, reason=%{public}d", requestNode.channelId, reason);
1549         (void)memset_s(
1550             conn.appInfo.sinkSessionKey, sizeof(conn.appInfo.sinkSessionKey), 0, sizeof(conn.appInfo.sinkSessionKey));
1551         (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
1552         (void)NotifyChannelClosed(&conn.appInfo, channelId);
1553         TransProcessAsyncOpenTdcChannelFailed(&conn, reason, seq, flags);
1554         (void)TransUkRequestDeleteItem(requestId);
1555         return;
1556     }
1557     conn.appInfo.myData.userKeyId = ukId;
1558     TransEventExtra extra;
1559     (void)memset_s(&extra, sizeof(TransEventExtra), 0, sizeof(TransEventExtra));
1560     char peerUuid[DEVICE_ID_SIZE_MAX] = { 0 };
1561     NodeInfo nodeInfo;
1562     (void)memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
1563     ReportTransEventExtra(&extra, channelId, &conn, &nodeInfo, peerUuid);
1564     (void)HandleTdcChannelOpenedReply(&conn, channelId, &extra, flags, seq);
1565     (void)TransUkRequestDeleteItem(requestId);
1566     (void)memset_s(
1567         conn.appInfo.sinkSessionKey, sizeof(conn.appInfo.sinkSessionKey), 0, sizeof(conn.appInfo.sinkSessionKey));
1568     (void)memset_s(conn.appInfo.sessionKey, sizeof(conn.appInfo.sessionKey), 0, sizeof(conn.appInfo.sessionKey));
1569 }
1570 
OnTdcGenUkSuccess(uint32_t requestId,int32_t ukId)1571 static void OnTdcGenUkSuccess(uint32_t requestId, int32_t ukId)
1572 {
1573     HandleTdcGenUkResult(requestId, ukId, SOFTBUS_OK);
1574 }
1575 
OnTdcGenUkFailed(uint32_t requestId,int32_t reason)1576 static void OnTdcGenUkFailed(uint32_t requestId, int32_t reason)
1577 {
1578     HandleTdcGenUkResult(requestId, 0, reason);
1579 }
1580 
1581 static AuthGenUkCallback tdcAuthGenUkCallback = {
1582     .onGenSuccess = OnTdcGenUkSuccess,
1583     .onGenFailed = OnTdcGenUkFailed,
1584 };
1585 
GetSessionConnSeqAndFlagByChannelId(int32_t channelId,SessionConn * conn,uint32_t * flags,uint64_t * seq)1586 static int32_t GetSessionConnSeqAndFlagByChannelId(int32_t channelId, SessionConn *conn, uint32_t *flags, uint64_t *seq)
1587 {
1588     if (conn == NULL || flags == NULL || seq == NULL) {
1589         TRANS_LOGE(TRANS_CTRL, "invalid param");
1590         return SOFTBUS_INVALID_PARAM;
1591     }
1592 
1593     int32_t ret = GetSessionConnById(channelId, conn);
1594     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get sessionConn failed, ret=%{public}d", ret);
1595 
1596     ret = TransTdcUpdateReplyCnt(channelId);
1597     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "update reply cnt failed, ret=%{public}d", ret);
1598 
1599     ret = TransSrvGetSeqAndFlagsByChannelId(seq, flags, channelId);
1600     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL,
1601         "get seqs and flags failed, channelId=%{public}d, ret=%{public}d", channelId, ret);
1602 
1603     return SOFTBUS_OK;
1604 }
1605 
TransDealTdcChannelOpenResult(int32_t channelId,int32_t openResult,const AccessInfo * accessInfo,pid_t callingPid)1606 int32_t TransDealTdcChannelOpenResult(
1607     int32_t channelId, int32_t openResult, const AccessInfo *accessInfo, pid_t callingPid)
1608 {
1609     SessionConn conn = { 0 };
1610     uint32_t flags = 0;
1611     uint64_t seq = 0;
1612     int32_t ret = GetSessionConnSeqAndFlagByChannelId(channelId, &conn, &flags, &seq);
1613     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL,
1614         "get SessionConn or seq or flags failed, channelId=%{public}d, ret=%{public}d", channelId, ret);
1615 
1616     if (callingPid != 0 && conn.appInfo.myData.pid != callingPid) {
1617         TRANS_LOGE(TRANS_CTRL,
1618             "pid does not match callingPid, pid=%{public}d, callingPid=%{public}d, channelId=%{public}d",
1619             conn.appInfo.myData.pid, callingPid, channelId);
1620         return SOFTBUS_TRANS_CHECK_PID_ERROR;
1621     }
1622 
1623     (void)UpdateAccessInfoById(channelId, accessInfo);
1624     ret = GetSessionConnById(channelId, &conn);
1625     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get sessionConn failed, ret=%{public}d", ret);
1626 
1627     TransEventExtra extra = { 0 };
1628     char peerUuid[DEVICE_ID_SIZE_MAX] = { 0 };
1629     NodeInfo nodeInfo;
1630     (void)memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
1631     ReportTransEventExtra(&extra, channelId, &conn, &nodeInfo, peerUuid);
1632 
1633     if (openResult != SOFTBUS_OK) {
1634         TRANS_LOGE(TRANS_CTRL, "Tdc channel open failed, openResult=%{public}d", openResult);
1635         TransProcessAsyncOpenTdcChannelFailed(&conn, openResult, seq, flags);
1636         return SOFTBUS_OK;
1637     }
1638     if (conn.appInfo.fastTransDataSize > 0 && conn.appInfo.fastTransData != NULL) {
1639         NotifyFastDataRecv(&conn, channelId);
1640     }
1641     if (GetCapabilityBit(conn.appInfo.channelCapability, TRANS_CHANNEL_SINK_GENERATE_KEY_OFFSET)) {
1642         if (accessInfo != NULL && accessInfo->userId == INVALID_USER_ID &&
1643             conn.appInfo.myData.tokenType > ACCESS_TOKEN_TYPE_HAP) {
1644             DisableCapabilityBit(&conn.appInfo.channelCapability, TRANS_CHANNEL_SINK_KEY_ENCRYPT_OFFSET);
1645             return HandleTdcChannelOpenedReply(&conn, channelId, &extra, flags, seq);
1646         }
1647         ret = GetUserkeyIdByAClInfo(
1648             &conn.appInfo, channelId, CHANNEL_TYPE_TCP_DIRECT, &conn.appInfo.myData.userKeyId, &tdcAuthGenUkCallback);
1649         if (ret == SOFTBUS_TRANS_GEN_USER_KEY) {
1650             return SOFTBUS_OK;
1651         }
1652         if (ret == SOFTBUS_AUTH_ACL_NOT_FOUND && SoftBusSaCanUseDeviceKey(conn.appInfo.myData.tokenId)) {
1653             DisableCapabilityBit(&conn.appInfo.channelCapability, TRANS_CHANNEL_SINK_KEY_ENCRYPT_OFFSET);
1654             return HandleTdcChannelOpenedReply(&conn, channelId, &extra, flags, seq);
1655         }
1656         if (ret != SOFTBUS_OK) {
1657             (void)NotifyChannelClosed(&conn.appInfo, channelId);
1658             TransProcessAsyncOpenTdcChannelFailed(&conn, ret, seq, flags);
1659             return SOFTBUS_OK;
1660         }
1661     }
1662     return HandleTdcChannelOpenedReply(&conn, channelId, &extra, flags, seq);
1663 }
1664 
TransAsyncTcpDirectChannelTask(int32_t channelId)1665 void TransAsyncTcpDirectChannelTask(int32_t channelId)
1666 {
1667     int32_t curCount = 0;
1668     int32_t ret = TransCheckTdcChannelOpenStatus(channelId, &curCount);
1669     if (ret != SOFTBUS_OK) {
1670         TRANS_LOGE(TRANS_CTRL, "check tdc channel statue failed, channelId=%{public}d, ret=%{public}d", channelId, ret);
1671         return;
1672     }
1673     if (curCount == CHANNEL_OPEN_SUCCESS) {
1674         TRANS_LOGI(TRANS_CTRL, "Open tdc channel success, channelId=%{public}d", channelId);
1675         return;
1676     }
1677     SessionConn connInfo;
1678     (void)memset_s(&connInfo, sizeof(SessionConn), 0, sizeof(SessionConn));
1679     ret = GetSessionConnById(channelId, &connInfo);
1680     if (ret != SOFTBUS_OK) {
1681         TRANS_LOGE(TRANS_CTRL, "get session conn by channelId=%{public}d failed, ret=%{public}d", channelId, ret);
1682         return;
1683     }
1684     if (curCount >= LOOPER_REPLY_CNT_MAX) {
1685         TRANS_LOGE(TRANS_CTRL, "Open Tdc channel timeout, channelId=%{public}d", channelId);
1686         uint32_t flags = 0;
1687         uint64_t seq = 0;
1688         ret = TransSrvGetSeqAndFlagsByChannelId(&seq, &flags, channelId);
1689         if (ret != SOFTBUS_OK) {
1690             CloseTcpDirectFd(connInfo.listenMod, connInfo.appInfo.fd);
1691             TRANS_LOGE(TRANS_CTRL, "get seqs and flags failed, channelId=%{public}d, ret=%{public}d", channelId, ret);
1692             return;
1693         }
1694         char errDesc[MAX_ERRDESC_LEN] = { 0 };
1695         char *desc = (char *)"Open tdc channel time out!";
1696         if (strcpy_s(errDesc, MAX_ERRDESC_LEN, desc) != EOK) {
1697             TRANS_LOGW(TRANS_CTRL, "strcpy failed");
1698         }
1699         if (OpenDataBusRequestError(
1700             channelId, seq, errDesc, SOFTBUS_TRANS_OPEN_CHANNEL_NEGTIATE_TIMEOUT, flags) != SOFTBUS_OK) {
1701             TRANS_LOGE(TRANS_CTRL, "OpenDataBusRequestError error");
1702         }
1703         (void)memset_s(
1704             connInfo.appInfo.sessionKey, sizeof(connInfo.appInfo.sessionKey), 0, sizeof(connInfo.appInfo.sessionKey));
1705         (void)NotifyChannelClosed(&connInfo.appInfo, channelId);
1706         TransCleanTdcSource(channelId);
1707         CloseTcpDirectFd(connInfo.listenMod, connInfo.appInfo.fd);
1708         return;
1709     }
1710     TRANS_LOGI(TRANS_CTRL, "Open channelId=%{public}d not finished, generate new task and waiting", channelId);
1711     uint32_t delayTime = (curCount <= LOOPER_SEPARATE_CNT) ? FAST_INTERVAL_MILLISECOND : SLOW_INTERVAL_MILLISECOND;
1712     TransCheckChannelOpenToLooperDelay(channelId, CHANNEL_TYPE_TCP_DIRECT, delayTime);
1713 }
1714 
TransTdcPostErrorMsg(uint64_t * seq,uint32_t * flags,int32_t channelId,int32_t errCode)1715 static int32_t TransTdcPostErrorMsg(uint64_t *seq, uint32_t *flags, int32_t channelId, int32_t errCode)
1716 {
1717     int32_t ret = TransSrvGetSeqAndFlagsByChannelId(seq, flags, channelId);
1718     if (ret != SOFTBUS_OK) {
1719         TRANS_LOGE(TRANS_CTRL, "get seq and flags by channelId=%{public}d failed.", channelId);
1720         return ret;
1721     }
1722     char *desc = (char *)"Open tdc channel failed.";
1723     if (OpenDataBusRequestError(channelId, *seq, desc, errCode, *flags) != SOFTBUS_OK) {
1724         TRANS_LOGW(TRANS_CTRL, "OpenDataBusRequestError failed.");
1725     }
1726     return SOFTBUS_OK;
1727 }
1728 
TransDealTdcCheckCollabResult(int32_t channelId,int32_t checkResult,pid_t callingPid)1729 int32_t TransDealTdcCheckCollabResult(int32_t channelId, int32_t checkResult, pid_t callingPid)
1730 {
1731     int32_t dmsPid = 0;
1732     char dmsPkgName[PKG_NAME_SIZE_MAX] = { 0 };
1733     (void)TransGetPidAndPkgName(DMS_SESSIONNAME, DMS_UID, &dmsPid, dmsPkgName, PKG_NAME_SIZE_MAX);
1734     if (callingPid != 0 && dmsPid != callingPid) {
1735         TRANS_LOGE(TRANS_CTRL,
1736             "dmsPid does not match callingPid, dmsPid=%{public}d, callingPid=%{public}d", dmsPid, callingPid);
1737         return SOFTBUS_TRANS_CHECK_PID_ERROR;
1738     }
1739 
1740     uint32_t tranFlags = 0;
1741     uint64_t seq = 0;
1742     SessionConn conn = { 0 };
1743     int32_t ret = GetSessionConnById(channelId, &conn);
1744     if (ret != SOFTBUS_OK) {
1745         TRANS_LOGE(TRANS_CTRL, "get session conn by channelId=%{public}d failed.", channelId);
1746         return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED;
1747     }
1748 
1749     ret = TransTdcUpdateReplyCnt(channelId);
1750     if (ret != SOFTBUS_OK) {
1751         TRANS_LOGE(TRANS_CTRL, "update waitOpenReplyCnt failed, channelId=%{public}d.", channelId);
1752         goto ERR_EXIT;
1753     }
1754     // Remove old check tasks.
1755     TransCheckChannelOpenRemoveFromLooper(channelId);
1756     if (checkResult != SOFTBUS_OK) {
1757         TRANS_LOGE(TRANS_CTRL, "check Collab relation failed, checkResult=%{public}d.", checkResult);
1758         ret = checkResult;
1759         goto ERR_EXIT;
1760     }
1761     // Reset the check count to 0.
1762     ret = TransTdcResetReplyCnt(channelId);
1763     if (ret != SOFTBUS_OK) {
1764         goto ERR_EXIT;
1765     }
1766     ret = NotifyChannelOpened(channelId);
1767     if (ret != SOFTBUS_OK) {
1768         TRANS_LOGE(TRANS_CTRL, "Notify sdk channelId=%{public}d opened failed ret=%{public}d.", channelId, ret);
1769         return ret;
1770     }
1771     return SOFTBUS_OK;
1772 
1773 ERR_EXIT:
1774     ret = TransTdcPostErrorMsg(&seq, &tranFlags, channelId, ret);
1775     if (ret != SOFTBUS_OK) {
1776         return ret;
1777     }
1778     CloseTcpDirectFd(conn.listenMod, conn.appInfo.fd);
1779     TransDelSessionConnById(channelId);
1780     return ret;
1781 }
1782