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_udp_negotiation.h"
17 
18 #include "access_control.h"
19 #include "auth_interface.h"
20 #include "bus_center_event.h"
21 #include "bus_center_info_key.h"
22 #include "bus_center_manager.h"
23 #include "lnn_distributed_net_ledger.h"
24 #include "securec.h"
25 #include "softbus_adapter_crypto.h"
26 #include "softbus_adapter_hitrace.h"
27 #include "softbus_adapter_mem.h"
28 #include "softbus_adapter_thread.h"
29 #include "softbus_conn_interface.h"
30 #include "softbus_def.h"
31 #include "softbus_errcode.h"
32 #include "softbus_hisysevt_transreporter.h"
33 #include "softbus_scenario_manager.h"
34 #include "trans_channel_common.h"
35 #include "trans_event.h"
36 #include "trans_lane_manager.h"
37 #include "trans_lane_pending_ctl.h"
38 #include "trans_log.h"
39 #include "trans_udp_channel_manager.h"
40 #include "trans_udp_negotiation_exchange.h"
41 #include "wifi_direct_manager.h"
42 
43 #define ID_NOT_USED 0
44 #define ID_USED 1
45 #define INVALID_ID (-1)
46 #define IVALID_SEQ (-1)
47 #define SEQ_OFFSET 2
48 
49 #define FLAG_REQUEST 0
50 #define FLAG_REPLY 1
51 #define ID_OFFSET (1)
52 #define MAX_ERRDESC_LEN 128
53 
54 static int64_t g_seq = 0;
55 static uint64_t g_channelIdFlagBitsMap = 0;
56 static IServerChannelCallBack *g_channelCb = NULL;
57 static SoftBusMutex g_udpNegLock;
58 static uint32_t g_idMark = 0;
59 
60 // it's fake, gona replaced by wifi interface
61 const char *LOCAL_MAC_1 = "18:65";
62 const char *PEER_MAC_1 = "de:4f";
63 
GenerateUdpChannelId(void)64 static int32_t GenerateUdpChannelId(void)
65 {
66     if (SoftBusMutexLock(&g_udpNegLock) != SOFTBUS_OK) {
67         TRANS_LOGE(TRANS_CTRL, "generate udp channel id lock failed");
68         return SOFTBUS_LOCK_ERR;
69     }
70     for (uint32_t id = g_idMark + 1, cnt = 0; id != g_idMark && cnt < MAX_UDP_CHANNEL_ID_COUNT; id++, cnt++) {
71         id = id % MAX_UDP_CHANNEL_ID_COUNT;
72         if (((g_channelIdFlagBitsMap >> id) & ID_USED) == ID_NOT_USED) {
73             g_channelIdFlagBitsMap |= (ID_USED << id);
74             g_idMark = id;
75             SoftBusMutexUnlock(&g_udpNegLock);
76             return (int32_t)id;
77         }
78     }
79     SoftBusMutexUnlock(&g_udpNegLock);
80     return INVALID_ID;
81 }
82 
ReleaseUdpChannelId(int32_t channelId)83 void ReleaseUdpChannelId(int32_t channelId)
84 {
85     if (SoftBusMutexLock(&g_udpNegLock) != SOFTBUS_OK) {
86         TRANS_LOGE(TRANS_CTRL, "release udp channel id lock failed");
87         return;
88     }
89     uint32_t id = (uint32_t)channelId;
90     if (id >= MAX_UDP_CHANNEL_ID_COUNT) {
91         TRANS_LOGE(TRANS_CTRL, "id invalid, release udp channelId failed, channelId=%{public}d", channelId);
92         (void)SoftBusMutexUnlock(&g_udpNegLock);
93         return;
94     }
95     g_channelIdFlagBitsMap &= (~(ID_USED << id));
96     (void)SoftBusMutexUnlock(&g_udpNegLock);
97 }
98 
GenerateSeq(bool isServer)99 static int64_t GenerateSeq(bool isServer)
100 {
101     if (SoftBusMutexLock(&g_udpNegLock) != SOFTBUS_OK) {
102         TRANS_LOGE(TRANS_CTRL, "generate seq lock failed");
103         return SOFTBUS_LOCK_ERR;
104     }
105     if (g_seq > INT64_MAX - SEQ_OFFSET) {
106         g_seq = 0;
107     }
108     int64_t seq = g_seq + SEQ_OFFSET;
109     g_seq += SEQ_OFFSET;
110     if (isServer) {
111         seq++;
112     }
113     SoftBusMutexUnlock(&g_udpNegLock);
114     return seq;
115 }
116 
NotifyUdpChannelOpened(const AppInfo * appInfo,bool isServerSide)117 static int32_t NotifyUdpChannelOpened(const AppInfo *appInfo, bool isServerSide)
118 {
119     TRANS_LOGI(TRANS_CTRL, "enter.");
120     ChannelInfo info = {0};
121     char networkId[NETWORK_ID_BUF_LEN] = {0};
122     info.myHandleId = appInfo->myHandleId;
123     info.peerHandleId = appInfo->peerHandleId;
124     info.channelId = appInfo->myData.channelId;
125     info.channelType = CHANNEL_TYPE_UDP;
126     info.isServer = isServerSide;
127     info.businessType = appInfo->businessType;
128     info.myIp = (char*)appInfo->myData.addr;
129     info.sessionKey = (char*)appInfo->sessionKey;
130     info.keyLen = SESSION_KEY_LENGTH;
131     info.groupId = (char*)appInfo->groupId;
132     info.isEncrypt = true;
133     int32_t ret = LnnGetNetworkIdByUuid((const char *)appInfo->peerData.deviceId, networkId, NETWORK_ID_BUF_LEN);
134     if (ret != SOFTBUS_OK) {
135         TRANS_LOGE(TRANS_CTRL, "get network id by uuid failed.");
136         return ret;
137     }
138     info.peerDeviceId = (char*)networkId;
139     info.peerSessionName = (char*)appInfo->peerData.sessionName;
140     info.routeType = (int32_t)appInfo->routeType;
141     info.streamType = (int32_t)appInfo->streamType;
142     info.isUdpFile = appInfo->fileProtocol == APP_INFO_UDP_FILE_PROTOCOL ? true : false;
143     info.peerIp = (char*)appInfo->peerData.addr;
144     if (!isServerSide) {
145         info.peerPort = appInfo->peerData.port;
146     }
147     info.autoCloseTime = appInfo->autoCloseTime;
148     info.timeStart = appInfo->timeStart;
149     info.linkType = appInfo->linkType;
150     info.connectType = appInfo->connectType;
151     TransGetLaneIdByChannelId(appInfo->myData.channelId, &info.laneId);
152     ret = g_channelCb->GetPkgNameBySessionName(appInfo->myData.sessionName,
153         (char*)appInfo->myData.pkgName, PKG_NAME_SIZE_MAX);
154     if (ret != SOFTBUS_OK) {
155         TRANS_LOGE(TRANS_CTRL, "get pkg name fail.");
156         return ret;
157     }
158     return g_channelCb->OnChannelOpened(appInfo->myData.pkgName, appInfo->myData.pid,
159         appInfo->myData.sessionName, &info);
160 }
161 
NotifyUdpChannelClosed(const AppInfo * info,int32_t messageType)162 int32_t NotifyUdpChannelClosed(const AppInfo *info, int32_t messageType)
163 {
164     if (info == NULL) {
165         TRANS_LOGE(TRANS_CTRL, "appInfo is null.");
166         return SOFTBUS_INVALID_PARAM;
167     }
168 
169     TRANS_LOGI(TRANS_CTRL, "pkgName=%{public}s.", info->myData.pkgName);
170     int32_t ret = g_channelCb->OnChannelClosed(info->myData.pkgName, info->myData.pid,
171         (int32_t)(info->myData.channelId), CHANNEL_TYPE_UDP, messageType);
172     if (ret != SOFTBUS_OK) {
173         TRANS_LOGE(TRANS_CTRL, "on channel closed failed, ret=%{public}d.", ret);
174         return ret;
175     }
176     return SOFTBUS_OK;
177 }
178 
NotifyUdpChannelBind(const AppInfo * info)179 static int32_t NotifyUdpChannelBind(const AppInfo *info)
180 {
181     if (info == NULL) {
182         TRANS_LOGE(TRANS_CTRL, "appInfo is null.");
183         return SOFTBUS_INVALID_PARAM;
184     }
185     TRANS_LOGI(TRANS_CTRL, "channelId=%{public}" PRId64, info->myData.channelId);
186     int32_t ret = g_channelCb->OnChannelBind(info->myData.pkgName, info->myData.pid,
187         (int32_t)(info->myData.channelId), CHANNEL_TYPE_UDP);
188     if (ret != SOFTBUS_OK) {
189         TRANS_LOGE(TRANS_CTRL, "on channel bind failed, ret=%{public}d, channelId=%{public}" PRId64, ret,
190             info->myData.channelId);
191         return ret;
192     }
193     return SOFTBUS_OK;
194 }
195 
NotifyUdpChannelOpenFailed(const AppInfo * info,int32_t errCode)196 int32_t NotifyUdpChannelOpenFailed(const AppInfo *info, int32_t errCode)
197 {
198     TRANS_LOGW(TRANS_CTRL, "enter.");
199     if (info == NULL) {
200         TRANS_LOGE(TRANS_CTRL, "appInfo is null.");
201         return SOFTBUS_INVALID_PARAM;
202     }
203 
204     int64_t timeStart = info->timeStart;
205     int64_t timediff = GetSoftbusRecordTimeMillis() - timeStart;
206     char localUdid[UDID_BUF_LEN] = { 0 };
207     (void)LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, sizeof(localUdid));
208     TransEventExtra extra = {
209         .calleePkg = NULL,
210         .callerPkg = info->myData.pkgName,
211         .channelId = info->myData.channelId,
212         .peerNetworkId = info->peerNetWorkId,
213         .socketName = info->myData.sessionName,
214         .linkType = info->connectType,
215         .costTime = timediff,
216         .errcode = errCode,
217         .osType = (info->osType < 0) ? UNKNOW_OS_TYPE : info->osType,
218         .localUdid = localUdid,
219         .peerUdid = info->peerUdid,
220         .peerDevVer = info->peerVersion,
221         .result = EVENT_STAGE_RESULT_FAILED
222     };
223     extra.deviceState = TransGetDeviceState(info->peerNetWorkId);
224     if (info->isClient) {
225         TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_OPEN_CHANNEL_END, extra);
226     } else {
227         TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL_SERVER, EVENT_STAGE_OPEN_CHANNEL_END, extra);
228     }
229 
230     TransAlarmExtra extraAlarm = {
231         .conflictName = NULL,
232         .conflictedName = NULL,
233         .occupyedName = NULL,
234         .permissionName = NULL,
235         .linkType = info->linkType,
236         .errcode = errCode,
237         .sessionName = info->myData.sessionName,
238     };
239     TRANS_ALARM(OPEN_SESSION_FAIL_ALARM, CONTROL_ALARM_TYPE, extraAlarm);
240 
241     SoftbusRecordOpenSessionKpi(info->myData.pkgName, info->linkType, SOFTBUS_EVT_OPEN_SESSION_FAIL, timediff);
242     int ret = g_channelCb->OnChannelOpenFailed(info->myData.pkgName, info->myData.pid,
243         (int32_t)(info->myData.channelId), CHANNEL_TYPE_UDP, errCode);
244     if (ret != SOFTBUS_OK) {
245         TRANS_LOGE(TRANS_CTRL, "notify udp channel open failed err.");
246     }
247     return ret;
248 }
249 
NotifyUdpQosEvent(const AppInfo * info,int32_t eventId,int32_t tvCount,const QosTv * tvList)250 int32_t NotifyUdpQosEvent(const AppInfo *info, int32_t eventId, int32_t tvCount, const QosTv *tvList)
251 {
252     TRANS_LOGI(TRANS_QOS, "notify udp qos eventId=%{public}d.", eventId);
253     char pkgName[PKG_NAME_SIZE_MAX] = {0};
254     int32_t ret = g_channelCb->GetPkgNameBySessionName(info->myData.sessionName, pkgName, PKG_NAME_SIZE_MAX);
255     if (ret != SOFTBUS_OK) {
256         TRANS_LOGE(TRANS_QOS, "get pkg name fail.");
257         return ret;
258     }
259     QosParam param;
260     param.channelId = (int32_t)(info->myData.channelId);
261     param.channelType = CHANNEL_TYPE_UDP;
262     param.eventId = eventId;
263     param.tvCount = tvCount;
264     param.tvList = tvList;
265     param.pid = info->myData.pid;
266     return g_channelCb->OnQosEvent(pkgName, &param);
267 }
268 
CopyAppInfoFastTransData(UdpChannelInfo * newChannel,const AppInfo * appInfo)269 static int32_t CopyAppInfoFastTransData(UdpChannelInfo *newChannel, const AppInfo *appInfo)
270 {
271     if (appInfo->fastTransData != NULL && appInfo->fastTransDataSize > 0) {
272         uint8_t *fastTransData = (uint8_t *)SoftBusCalloc(appInfo->fastTransDataSize);
273         if (fastTransData == NULL) {
274             return SOFTBUS_MALLOC_ERR;
275         }
276         if (memcpy_s((char *)fastTransData, appInfo->fastTransDataSize, (const char *)appInfo->fastTransData,
277             appInfo->fastTransDataSize) != EOK) {
278             TRANS_LOGE(TRANS_CTRL, "memcpy fastTransData fail");
279             SoftBusFree(fastTransData);
280             return SOFTBUS_MEM_ERR;
281         }
282         newChannel->info.fastTransData = fastTransData;
283     }
284     return SOFTBUS_OK;
285 }
286 
NewUdpChannelByAppInfo(const AppInfo * info)287 static UdpChannelInfo *NewUdpChannelByAppInfo(const AppInfo *info)
288 {
289     UdpChannelInfo *newChannel = (UdpChannelInfo *)SoftBusCalloc(sizeof(UdpChannelInfo));
290     if (newChannel == NULL) {
291         TRANS_LOGE(TRANS_CTRL, "new udp channel failed.");
292         return NULL;
293     }
294 
295     if (memcpy_s(&(newChannel->info), sizeof(newChannel->info), info, sizeof(AppInfo)) != EOK) {
296         TRANS_LOGE(TRANS_CTRL, "memcpy_s failed.");
297         SoftBusFree(newChannel);
298         return NULL;
299     }
300     if (CopyAppInfoFastTransData(newChannel, info) != SOFTBUS_OK) {
301         (void)memset_s(newChannel->info.sessionKey, sizeof(newChannel->info.sessionKey), 0,
302             sizeof(newChannel->info.sessionKey));
303         SoftBusFree(newChannel);
304         TRANS_LOGE(TRANS_CTRL, "copy appinfo fast trans data fail");
305         return NULL;
306     }
307     return newChannel;
308 }
309 
AcceptUdpChannelAsServer(AppInfo * appInfo)310 static int32_t AcceptUdpChannelAsServer(AppInfo *appInfo)
311 {
312     TRANS_LOGI(TRANS_CTRL, "process udp channel open state[as server].");
313     int32_t udpChannelId = GenerateUdpChannelId();
314     if (udpChannelId == INVALID_ID) {
315         TRANS_LOGE(TRANS_CTRL, "generate udp channel id failed.");
316         return SOFTBUS_TRANS_UDP_INVALID_CHANNEL_ID;
317     }
318     appInfo->myData.channelId = udpChannelId;
319     int32_t udpPort = NotifyUdpChannelOpened(appInfo, true);
320     if (udpPort <= 0) {
321         TRANS_LOGE(TRANS_CTRL, "get udp listen port failed udpPort=%{public}d.", udpPort);
322         ReleaseUdpChannelId(appInfo->myData.channelId);
323         return udpPort;
324     }
325     int32_t ret = LnnGetNetworkIdByUuid(
326         (const char *)appInfo->peerData.deviceId, appInfo->peerNetWorkId, DEVICE_ID_SIZE_MAX);
327     if (ret != SOFTBUS_OK) {
328         TRANS_LOGE(TRANS_CTRL, "get network id by uuid failed.");
329     }
330     appInfo->myData.port = udpPort;
331     UdpChannelInfo *newChannel = NewUdpChannelByAppInfo(appInfo);
332     if (newChannel == NULL) {
333         ReleaseUdpChannelId(appInfo->myData.channelId);
334         return SOFTBUS_MEM_ERR;
335     }
336     newChannel->seq = GenerateSeq(true);
337     newChannel->status = UDP_CHANNEL_STATUS_INIT;
338     if (TransAddUdpChannel(newChannel) != SOFTBUS_OK) {
339         TRANS_LOGE(TRANS_CTRL, "add new udp channel failed.");
340         ReleaseUdpChannelId(appInfo->myData.channelId);
341         SoftBusFree(newChannel);
342         return SOFTBUS_TRANS_UDP_SERVER_ADD_CHANNEL_FAILED;
343     }
344     return SOFTBUS_OK;
345 }
346 
AcceptUdpChannelAsClient(AppInfo * appInfo)347 static int32_t AcceptUdpChannelAsClient(AppInfo *appInfo)
348 {
349     TRANS_LOGI(TRANS_CTRL, "process udp channel open state[as client].");
350     int32_t ret = NotifyUdpChannelOpened(appInfo, false);
351     if (ret != SOFTBUS_OK) {
352         TRANS_LOGE(TRANS_CTRL, "notify app udp channel opened failed.");
353         return ret;
354     }
355     return SOFTBUS_OK;
356 }
357 
CloseUdpChannel(AppInfo * appInfo,bool isServerSide)358 static int32_t CloseUdpChannel(AppInfo *appInfo, bool isServerSide)
359 {
360     TRANS_LOGI(TRANS_CTRL, "process udp channel close state");
361     if (TransDelUdpChannel(appInfo->myData.channelId) != SOFTBUS_OK) {
362         TRANS_LOGE(TRANS_CTRL, "delete udp channel failed.");
363     }
364     int32_t messageType = isServerSide ? MESSAGE_TYPE_NOMAL : MESSAGE_TYPE_CLOSE_ACK;
365     if (NotifyUdpChannelClosed(appInfo, messageType) != SOFTBUS_OK) {
366         TRANS_LOGE(TRANS_CTRL, "notify app udp channel closed failed.");
367     }
368     return SOFTBUS_OK;
369 }
370 
NotifyWifiByAddScenario(StreamType streamType,int32_t pid)371 void NotifyWifiByAddScenario(StreamType streamType, int32_t pid)
372 {
373     if (streamType == COMMON_AUDIO_STREAM || streamType == COMMON_VIDEO_STREAM) {
374         if (AddScenario(LOCAL_MAC_1, PEER_MAC_1, pid, SM_AUDIO_TYPE) !=0) {
375             TRANS_LOGE(TRANS_CTRL, "notify wifi scan failed!");
376         } else {
377             TRANS_LOGI(TRANS_CTRL, "notify wifi scan success!");
378         }
379     }
380 }
381 
NotifyWifiByDelScenario(StreamType streamType,int32_t pid)382 void NotifyWifiByDelScenario(StreamType streamType, int32_t pid)
383 {
384     if (streamType == COMMON_AUDIO_STREAM || streamType == COMMON_VIDEO_STREAM) {
385         if (DelScenario(LOCAL_MAC_1, PEER_MAC_1, pid, SM_AUDIO_TYPE) !=0) {
386             TRANS_LOGE(TRANS_CTRL, "recover wifi scan failed");
387         } else {
388             TRANS_LOGI(TRANS_CTRL, "recover wifi scan success!");
389         }
390     }
391 }
392 
ProcessUdpChannelState(AppInfo * appInfo,bool isServerSide)393 static int32_t ProcessUdpChannelState(AppInfo *appInfo, bool isServerSide)
394 {
395     int32_t ret = SOFTBUS_OK;
396     switch (appInfo->udpChannelOptType) {
397         case TYPE_UDP_CHANNEL_OPEN:
398             NotifyWifiByAddScenario(appInfo->streamType, appInfo->myData.pid);
399             if (isServerSide) {
400                 ret = AcceptUdpChannelAsServer(appInfo);
401             } else {
402                 ret = AcceptUdpChannelAsClient(appInfo);
403             }
404             return ret;
405         case TYPE_UDP_CHANNEL_CLOSE:
406             NotifyWifiByDelScenario(appInfo->streamType, appInfo->myData.pid);
407             ret = CloseUdpChannel(appInfo, isServerSide);
408             break;
409         default:
410             TRANS_LOGE(TRANS_CTRL, "invalid udp channel type.");
411             return SOFTBUS_TRANS_INVALID_CHANNEL_TYPE;
412     }
413     return SOFTBUS_OK;
414 }
415 
SendUdpInfo(cJSON * replyMsg,AuthHandle authHandle,int64_t seq)416 static int32_t SendUdpInfo(cJSON *replyMsg, AuthHandle authHandle, int64_t seq)
417 {
418     char *msgStr = cJSON_PrintUnformatted(replyMsg);
419     if (msgStr == NULL) {
420         return SOFTBUS_PARSE_JSON_ERR;
421     }
422     AuthTransData dataInfo = {
423         .module = MODULE_UDP_INFO,
424         .flag = FLAG_REPLY,
425         .seq = seq,
426         .len = strlen(msgStr) + 1,
427         .data = (const uint8_t *)msgStr,
428     };
429 
430     int32_t ret = AuthPostTransData(authHandle, &dataInfo);
431     cJSON_free(msgStr);
432     return ret;
433 }
434 
SendReplyErrInfo(int errCode,char * errDesc,AuthHandle authHandle,int64_t seq)435 static int32_t SendReplyErrInfo(int errCode, char* errDesc, AuthHandle authHandle, int64_t seq)
436 {
437     TRANS_LOGI(TRANS_CTRL, "udp send reply info in.");
438     cJSON *replyMsg = cJSON_CreateObject();
439     TRANS_CHECK_AND_RETURN_RET_LOGE(replyMsg != NULL, SOFTBUS_CREATE_JSON_ERR,
440         TRANS_CTRL, "create cjson object failed.");
441     int32_t ret = TransPackReplyErrInfo(replyMsg, errCode, errDesc);
442     if (ret != SOFTBUS_OK) {
443         TRANS_LOGE(TRANS_CTRL, "pack request udp info failed.");
444         cJSON_Delete(replyMsg);
445         return ret;
446     }
447     ret = SendUdpInfo(replyMsg, authHandle, seq);
448     if (ret != SOFTBUS_OK) {
449         TRANS_LOGE(TRANS_CTRL, "SendReplyeErrInfo failed.");
450         cJSON_Delete(replyMsg);
451         return ret;
452     }
453     cJSON_Delete(replyMsg);
454     TRANS_LOGE(TRANS_CTRL, "udp send reply error info out.");
455     return SOFTBUS_OK;
456 }
457 
SendReplyUdpInfo(AppInfo * appInfo,AuthHandle authHandle,int64_t seq)458 static int32_t SendReplyUdpInfo(AppInfo *appInfo, AuthHandle authHandle, int64_t seq)
459 {
460     TRANS_LOGI(TRANS_CTRL, "udp send reply info in.");
461     cJSON *replyMsg = cJSON_CreateObject();
462     TRANS_CHECK_AND_RETURN_RET_LOGE(replyMsg != NULL, SOFTBUS_CREATE_JSON_ERR,
463         TRANS_CTRL, "create cjson object failed.");
464     int32_t ret = TransPackReplyUdpInfo(replyMsg, appInfo);
465     if (ret != SOFTBUS_OK) {
466         TRANS_LOGE(TRANS_CTRL, "pack request udp info failed.");
467         cJSON_Delete(replyMsg);
468         return ret;
469     }
470     ret = SendUdpInfo(replyMsg, authHandle, seq);
471     if (ret != SOFTBUS_OK) {
472         TRANS_LOGE(TRANS_CTRL, "SendReplyeErrInfo failed.");
473         cJSON_Delete(replyMsg);
474         return ret;
475     }
476 
477     cJSON_Delete(replyMsg);
478     TRANS_LOGI(TRANS_CTRL, "udp send reply info out.");
479     return SOFTBUS_OK;
480 }
481 
SetPeerDeviceIdByAuth(AuthHandle authHandle,AppInfo * appInfo)482 static int32_t SetPeerDeviceIdByAuth(AuthHandle authHandle, AppInfo *appInfo)
483 {
484     char peerUuid[UUID_BUF_LEN] = { 0 };
485     int32_t ret = AuthGetDeviceUuid(authHandle.authId, peerUuid, sizeof(peerUuid));
486     if (ret != SOFTBUS_OK) {
487         TRANS_LOGE(TRANS_CTRL, "get peer uuid by auth id failed, ret=%{public}d.", ret);
488         return ret;
489     }
490 
491     if (memcpy_s(appInfo->peerData.deviceId, sizeof(appInfo->peerData.deviceId),
492         peerUuid, sizeof(peerUuid)) != EOK) {
493         TRANS_LOGE(TRANS_CTRL, "memcpy_s network id failed.");
494         return SOFTBUS_MEM_ERR;
495     }
496 
497     return SOFTBUS_OK;
498 }
499 
TransSetUdpConnectTypeByAuthType(int32_t * connectType,AuthHandle authHandle)500 static void TransSetUdpConnectTypeByAuthType(int32_t *connectType, AuthHandle authHandle)
501 {
502     switch (authHandle.type) {
503         case AUTH_LINK_TYPE_P2P:
504             *connectType = CONNECT_P2P;
505             break;
506         case AUTH_LINK_TYPE_ENHANCED_P2P:
507             *connectType = CONNECT_HML;
508             break;
509         case AUTH_LINK_TYPE_WIFI:
510             *connectType = CONNECT_TCP;
511             break;
512         default:
513             break;
514     }
515 }
516 
ParseRequestAppInfo(AuthHandle authHandle,const cJSON * msg,AppInfo * appInfo)517 static int32_t ParseRequestAppInfo(AuthHandle authHandle, const cJSON *msg, AppInfo *appInfo)
518 {
519     int32_t ret = TransUnpackRequestUdpInfo(msg, appInfo);
520     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "unpack request udp info failed.");
521 
522     if (appInfo->callingTokenId != TOKENID_NOT_SET &&
523         TransCheckServerAccessControl(appInfo->callingTokenId) != SOFTBUS_OK) {
524         return SOFTBUS_TRANS_CHECK_ACL_FAILED;
525     }
526     if (CheckSecLevelPublic(appInfo->myData.sessionName, appInfo->peerData.sessionName) != SOFTBUS_OK) {
527         return SOFTBUS_PERMISSION_SERVER_DENIED;
528     }
529     appInfo->myHandleId = -1;
530     appInfo->peerHandleId = -1;
531     ret = g_channelCb->GetPkgNameBySessionName(appInfo->myData.sessionName,
532         appInfo->myData.pkgName, PKG_NAME_SIZE_MAX);
533     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK,
534         SOFTBUS_TRANS_PEER_SESSION_NOT_CREATED, TRANS_CTRL, "get pkgName failed, ret=%{public}d", ret);
535 
536     ret = g_channelCb->GetUidAndPidBySessionName(appInfo->myData.sessionName, &appInfo->myData.uid,
537         &appInfo->myData.pid);
538     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK,
539         SOFTBUS_TRANS_PEER_SESSION_NOT_CREATED, TRANS_CTRL, "get uid and pid failed, ret=%{public}d", ret);
540 
541     if (appInfo->udpChannelOptType != TYPE_UDP_CHANNEL_OPEN) {
542         return SOFTBUS_OK;
543     }
544 
545     TransSetUdpConnectTypeByAuthType(&appInfo->connectType, authHandle);
546 
547     ret = SetPeerDeviceIdByAuth(authHandle, appInfo);
548     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_PEER_PROC_ERR, TRANS_CTRL, "set deviceId failed.");
549 
550     char localIp[IP_LEN] = { 0 };
551     if (appInfo->udpConnType == UDP_CONN_TYPE_WIFI) {
552         appInfo->routeType = WIFI_STA;
553         ret = LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, localIp, sizeof(localIp));
554         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get local strInfo failed.");
555     } else {
556         appInfo->routeType = WIFI_P2P;
557         struct WifiDirectManager *mgr = GetWifiDirectManager();
558         TRANS_CHECK_AND_RETURN_RET_LOGE(mgr != NULL && mgr->getLocalIpByRemoteIp != NULL,
559             SOFTBUS_WIFI_DIRECT_INIT_FAILED, TRANS_CTRL, "get mgr obj failed.");
560 
561         ret = mgr->getLocalIpByRemoteIp(appInfo->peerData.addr, localIp, sizeof(localIp));
562         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get localIp failed, ret=%{public}d", ret);
563     }
564     ret = strcpy_s(appInfo->myData.addr, sizeof(appInfo->myData.addr), localIp);
565     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == EOK, SOFTBUS_STRCPY_ERR, TRANS_CTRL, "strcpy_s my ip addr failed.");
566 
567     return SOFTBUS_OK;
568 }
569 
570 /**
571  * don't care release resources when close status, after invoking process udp channel status.
572  * */
ProcessAbnormalUdpChannelState(const AppInfo * info,int32_t errCode,bool needClose)573 static void ProcessAbnormalUdpChannelState(const AppInfo *info, int32_t errCode, bool needClose)
574 {
575     if (info->udpChannelOptType == TYPE_UDP_CHANNEL_OPEN) {
576         (void)NotifyUdpChannelOpenFailed(info, errCode);
577         (void)TransDelUdpChannel(info->myData.channelId);
578     } else if (needClose) {
579         NotifyUdpChannelClosed(info, MESSAGE_TYPE_NOMAL);
580         (void)TransDelUdpChannel(info->myData.channelId);
581     }
582 }
583 
TransOnExchangeUdpInfoReply(int64_t authId,int64_t seq,const cJSON * msg)584 static void TransOnExchangeUdpInfoReply(int64_t authId, int64_t seq, const cJSON *msg)
585 {
586     /* receive reply message */
587     TRANS_LOGI(TRANS_CTRL, "receive reply udp negotiation info.");
588     UdpChannelInfo channel;
589     (void)memset_s(&channel, sizeof(channel), 0, sizeof(channel));
590 
591     if (TransSetUdpChannelStatus(seq, UDP_CHANNEL_STATUS_DONE) != SOFTBUS_OK) {
592         TRANS_LOGE(TRANS_CTRL, "set udp channel negotiation status done failed.");
593         return;
594     }
595     if (TransGetUdpChannelBySeq(seq, &channel) != SOFTBUS_OK) {
596         TRANS_LOGE(TRANS_CTRL, "get udp channel by seq failed.");
597         return;
598     }
599     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)(channel.info.myData.channelId + ID_OFFSET));
600     int32_t errCode = SOFTBUS_OK;
601     if (TransUnpackReplyErrInfo(msg, &errCode) == SOFTBUS_OK) {
602         TRANS_LOGE(TRANS_CTRL, "receive err reply info, channelId=%{public}" PRId64, channel.info.myData.channelId);
603         ProcessAbnormalUdpChannelState(&(channel.info), errCode, true);
604         return;
605     }
606     int32_t ret = TransUnpackReplyUdpInfo(msg, &(channel.info));
607     if (ret != SOFTBUS_OK) {
608         TRANS_LOGE(TRANS_CTRL, "unpack reply udp info fail channelId=%{public}" PRId64, channel.info.myData.channelId);
609         ProcessAbnormalUdpChannelState(&(channel.info), ret, true);
610         return;
611     }
612     TransUpdateUdpChannelInfo(seq, &(channel.info));
613     ret = ProcessUdpChannelState(&(channel.info), false);
614     (void)memset_s(channel.info.sessionKey, sizeof(channel.info.sessionKey), 0, sizeof(channel.info.sessionKey));
615     if (ret != SOFTBUS_OK) {
616         TRANS_LOGE(TRANS_CTRL,
617             "process udp channelId=%{public}" PRId64 " failed, close peer", channel.info.myData.channelId);
618         (void)TransCloseUdpChannel(channel.info.myData.channelId);
619         ProcessAbnormalUdpChannelState(&(channel.info), ret, false);
620         return;
621     }
622     TransEventExtra extra = {
623         .socketName = NULL,
624         .peerNetworkId = NULL,
625         .calleePkg = NULL,
626         .callerPkg = NULL,
627         .channelId = channel.info.myData.channelId,
628         .authId = authId,
629         .result = EVENT_STAGE_RESULT_OK
630     };
631     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_HANDSHAKE_REPLY, extra);
632 }
633 
ReportUdpRequestHandShakeStartEvent(const AppInfo * info,NodeInfo * nodeInfo,TransEventExtra * extra,int64_t authId)634 static void ReportUdpRequestHandShakeStartEvent(
635     const AppInfo *info, NodeInfo *nodeInfo, TransEventExtra *extra, int64_t authId)
636 {
637     extra->channelType = CHANNEL_TYPE_UDP;
638     extra->authId = authId;
639     if (info->udpChannelOptType != TYPE_UDP_CHANNEL_OPEN) {
640         return;
641     }
642 
643     if (LnnGetRemoteNodeInfoById(info->peerData.deviceId, CATEGORY_UUID, nodeInfo) == SOFTBUS_OK) {
644         extra->peerUdid = nodeInfo->deviceInfo.deviceUdid;
645         extra->peerDevVer = nodeInfo->deviceInfo.deviceVersion;
646     }
647     if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, nodeInfo->masterUdid, UDID_BUF_LEN) == SOFTBUS_OK) {
648         extra->localUdid = nodeInfo->masterUdid;
649     }
650     extra->socketName = info->myData.sessionName;
651     extra->peerChannelId = info->peerData.channelId;
652     extra->result = EVENT_STAGE_RESULT_OK;
653     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL_SERVER, EVENT_STAGE_HANDSHAKE_START, *extra);
654 }
655 
ReportUdpRequestHandShakeReplyEvent(const AppInfo * info,TransEventExtra * extra,int32_t result,int32_t errCode)656 static void ReportUdpRequestHandShakeReplyEvent(
657     const AppInfo *info, TransEventExtra *extra, int32_t result, int32_t errCode)
658 {
659     if (extra->socketName != NULL && info->udpChannelOptType == TYPE_UDP_CHANNEL_OPEN) {
660         extra->result = result;
661         extra->errcode = errCode;
662         TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL_SERVER, EVENT_STAGE_HANDSHAKE_REPLY, *extra);
663     }
664 }
665 
TransOnExchangeUdpInfoRequest(AuthHandle authHandle,int64_t seq,const cJSON * msg)666 static void TransOnExchangeUdpInfoRequest(AuthHandle authHandle, int64_t seq, const cJSON *msg)
667 {
668     /* receive request message */
669     TRANS_LOGI(TRANS_CTRL, "receive request udp negotiation info.");
670     AppInfo info;
671     (void)memset_s(&info, sizeof(info), 0, sizeof(info));
672     info.myData.channelId = INVALID_CHANNEL_ID;
673     char *errDesc = NULL;
674 
675     TransEventExtra extra;
676     (void)memset_s(&extra, sizeof(TransEventExtra), 0, sizeof(TransEventExtra));
677     NodeInfo nodeInfo;
678     (void)memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
679     int32_t ret = ParseRequestAppInfo(authHandle, msg, &info);
680     if (ret != SOFTBUS_OK) {
681         TRANS_LOGE(TRANS_CTRL, "get appinfo failed. ret=%{public}d", ret);
682         errDesc = (char *)"peer device session name not create";
683         goto ERR_EXIT;
684     }
685 
686     ReportUdpRequestHandShakeStartEvent(&info, &nodeInfo, &extra, authHandle.authId);
687     ret = ProcessUdpChannelState(&info, true);
688     if (ret != SOFTBUS_OK) {
689         TRANS_LOGE(TRANS_CTRL, "process udp channel state failed. ret=%{public}d", ret);
690         errDesc = (char *)"notify app error";
691         ProcessAbnormalUdpChannelState(&info, ret, false);
692         goto ERR_EXIT;
693     }
694     ret = SendReplyUdpInfo(&info, authHandle, seq);
695     if (ret != SOFTBUS_OK) {
696         TRANS_LOGE(TRANS_CTRL, "send reply udp info failed. ret=%{public}d.", ret);
697         errDesc = (char *)"send reply error";
698         ProcessAbnormalUdpChannelState(&info, ret, false);
699         goto ERR_EXIT;
700     }
701     if (info.udpChannelOptType == TYPE_UDP_CHANNEL_OPEN) {
702         ret = NotifyUdpChannelBind(&info);
703         if (ret != SOFTBUS_OK) {
704             TRANS_LOGE(
705                 TRANS_CTRL, "notify bind fail ret=%{public}d, channelId=%{public}" PRId64, ret, info.myData.channelId);
706             errDesc = (char *)"notify OnBind failed";
707             ProcessAbnormalUdpChannelState(&info, ret, false);
708             goto ERR_EXIT;
709         }
710     }
711     ReportUdpRequestHandShakeReplyEvent(&info, &extra, EVENT_STAGE_RESULT_OK, SOFTBUS_OK);
712     return;
713 
714 ERR_EXIT:
715     ReportUdpRequestHandShakeReplyEvent(&info, &extra, EVENT_STAGE_RESULT_FAILED, ret);
716     if (SendReplyErrInfo(ret, errDesc, authHandle, seq) != SOFTBUS_OK) {
717         TRANS_LOGE(TRANS_CTRL, "send reply error info failed.");
718     }
719 }
720 
TransOnExchangeUdpInfo(AuthHandle authHandle,int32_t isReply,int64_t seq,const cJSON * msg)721 static void TransOnExchangeUdpInfo(AuthHandle authHandle, int32_t isReply, int64_t seq, const cJSON *msg)
722 {
723     if (isReply) {
724         TransOnExchangeUdpInfoReply(authHandle.authId, seq, msg);
725     } else {
726         TransOnExchangeUdpInfoRequest(authHandle, seq, msg);
727     }
728 }
729 
StartExchangeUdpInfo(UdpChannelInfo * channel,AuthHandle authHandle,int64_t seq)730 static int32_t StartExchangeUdpInfo(UdpChannelInfo *channel, AuthHandle authHandle, int64_t seq)
731 {
732     TRANS_LOGI(TRANS_CTRL,
733         "start exchange udp info: channelId=%{public}" PRId64 ", authId=%{public}" PRId64 ", streamType=%{public}d",
734         channel->info.myData.channelId, authHandle.authId, channel->info.streamType);
735     cJSON *requestMsg = cJSON_CreateObject();
736     if (requestMsg == NULL) {
737         TRANS_LOGE(TRANS_CTRL, "create cjson object failed.");
738         return SOFTBUS_MEM_ERR;
739     }
740 
741     if (TransPackRequestUdpInfo(requestMsg, &(channel->info)) != SOFTBUS_OK) {
742         TRANS_LOGE(TRANS_CTRL, "pack request udp info failed.");
743         cJSON_Delete(requestMsg);
744         return SOFTBUS_TRANS_UDP_PACK_INFO_FAILED;
745     }
746     char *msgStr = cJSON_PrintUnformatted(requestMsg);
747     cJSON_Delete(requestMsg);
748     if (msgStr == NULL) {
749         TRANS_LOGE(TRANS_CTRL, "cjson unformatted failed.");
750         return SOFTBUS_PARSE_JSON_ERR;
751     }
752     AuthTransData dataInfo = {
753         .module = MODULE_UDP_INFO,
754         .flag = FLAG_REQUEST,
755         .seq = seq,
756         .len = strlen(msgStr) + 1,
757         .data = (const uint8_t *)msgStr,
758     };
759     int32_t ret = SOFTBUS_AUTH_REG_DATA_FAIL;
760     ret = AuthPostTransData(authHandle, &dataInfo);
761     if (ret != SOFTBUS_OK) {
762         TRANS_LOGE(TRANS_CTRL, "AuthPostTransData failed.");
763         cJSON_free(msgStr);
764         return ret;
765     }
766     cJSON_free(msgStr);
767     if (TransSetUdpChannelStatus(seq, UDP_CHANNEL_STATUS_NEGING) != SOFTBUS_OK) {
768         TRANS_LOGE(TRANS_CTRL, "set udp channel negotiation status neging failed.");
769     }
770     TransEventExtra extra = {
771         .socketName = NULL,
772         .peerNetworkId = NULL,
773         .calleePkg = NULL,
774         .callerPkg = NULL,
775         .channelId = (int32_t)channel->info.myData.channelId,
776         .authId = (int32_t)authHandle.authId,
777         .result = EVENT_STAGE_RESULT_OK
778     };
779     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_HANDSHAKE_START, extra);
780     return SOFTBUS_OK;
781 }
782 
UdpOnAuthConnOpened(uint32_t requestId,AuthHandle authHandle)783 static void UdpOnAuthConnOpened(uint32_t requestId, AuthHandle authHandle)
784 {
785     TransEventExtra extra = {
786         .socketName = NULL,
787         .peerNetworkId = NULL,
788         .calleePkg = NULL,
789         .callerPkg = NULL,
790         .requestId = (int32_t)requestId,
791         .authId = (int32_t)authHandle.authId,
792         .result = EVENT_STAGE_RESULT_OK
793     };
794     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_START_CONNECT, extra);
795     TRANS_LOGI(
796         TRANS_CTRL, "reqId=%{public}u, authId=%{public}" PRId64, requestId, authHandle.authId);
797     int32_t ret = SOFTBUS_MALLOC_ERR;
798     UdpChannelInfo *channel = (UdpChannelInfo *)SoftBusCalloc(sizeof(UdpChannelInfo));
799     if (channel == NULL) {
800         ret = SOFTBUS_MALLOC_ERR;
801         goto EXIT_ERR;
802     }
803     if (TransGetUdpChannelByRequestId(requestId, channel) != SOFTBUS_OK) {
804         ret = SOFTBUS_TRANS_UDP_GET_CHANNEL_FAILED;
805         TRANS_LOGE(TRANS_CTRL, "get channel fail");
806         goto EXIT_ERR;
807     }
808     extra.channelId = (int32_t)channel->info.myData.channelId;
809     ret = StartExchangeUdpInfo(channel, authHandle, channel->seq);
810     (void)memset_s(channel->info.sessionKey, sizeof(channel->info.sessionKey), 0,
811         sizeof(channel->info.sessionKey));
812     if (ret != SOFTBUS_OK) {
813         channel->errCode = ret;
814         TRANS_LOGE(TRANS_CTRL, "neg fail");
815         ProcessAbnormalUdpChannelState(&channel->info, SOFTBUS_TRANS_HANDSHAKE_ERROR, true);
816         extra.socketName = channel->info.myData.sessionName;
817         extra.channelId = channel->info.myData.channelId;
818         goto EXIT_ERR;
819     }
820 
821     SoftBusFree(channel);
822     TRANS_LOGD(TRANS_CTRL, "ok");
823     return;
824 EXIT_ERR:
825     extra.channelType = CHANNEL_TYPE_UDP;
826     extra.requestId = (int32_t)requestId;
827     extra.authId = authHandle.authId;
828     extra.errcode = ret;
829     extra.result = EVENT_STAGE_RESULT_FAILED;
830     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_HANDSHAKE_START, extra);
831     SoftBusFree(channel);
832     TRANS_LOGE(TRANS_CTRL, "proc fail");
833     AuthCloseConn(authHandle);
834 }
835 
UdpOnAuthConnOpenFailed(uint32_t requestId,int32_t reason)836 static void UdpOnAuthConnOpenFailed(uint32_t requestId, int32_t reason)
837 {
838     TRANS_LOGW(TRANS_CTRL, "reqId=%{public}u, reason=%{public}d", requestId, reason);
839     UdpChannelInfo *channel = (UdpChannelInfo *)SoftBusCalloc(sizeof(UdpChannelInfo));
840     if (channel == NULL) {
841         TRANS_LOGE(TRANS_CTRL, "malloc fail");
842         return;
843     }
844     int32_t ret = TransGetUdpChannelByRequestId(requestId, channel);
845     (void)memset_s(channel->info.sessionKey, sizeof(channel->info.sessionKey), 0,
846         sizeof(channel->info.sessionKey));
847     if (ret != SOFTBUS_OK) {
848         TRANS_LOGE(TRANS_CTRL, "UdpOnAuthConnOpened get channel fail");
849         SoftBusFree(channel);
850         return;
851     }
852     ProcessAbnormalUdpChannelState(&channel->info, SOFTBUS_TRANS_OPEN_AUTH_CONN_FAILED, true);
853     TransEventExtra extra = {
854         .peerNetworkId = NULL,
855         .calleePkg = NULL,
856         .callerPkg = NULL,
857         .socketName = channel->info.myData.sessionName,
858         .channelType = CHANNEL_TYPE_UDP,
859         .channelId = channel->info.myData.channelId,
860         .requestId = requestId,
861         .errcode = reason,
862         .result = EVENT_STAGE_RESULT_FAILED
863     };
864     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_START_CONNECT, extra);
865     SoftBusFree(channel);
866     TRANS_LOGW(TRANS_CTRL, "ok");
867 }
868 
TransCloseUdpChannelByRequestId(uint32_t requestId)869 static void TransCloseUdpChannelByRequestId(uint32_t requestId)
870 {
871     TRANS_LOGD(TRANS_CTRL, "reqId=%{public}u", requestId);
872     UdpChannelInfo *channel = (UdpChannelInfo *)SoftBusCalloc(sizeof(UdpChannelInfo));
873     if (channel == NULL) {
874         TRANS_LOGE(TRANS_CTRL, "malloc fail");
875         return;
876     }
877     if (TransGetUdpChannelByRequestId(requestId, channel) != SOFTBUS_OK) {
878         TRANS_LOGE(TRANS_CTRL, "get channel fail");
879         SoftBusFree(channel);
880         return;
881     }
882     (void)memset_s(channel->info.sessionKey, sizeof(channel->info.sessionKey), 0,
883         sizeof(channel->info.sessionKey));
884     ProcessAbnormalUdpChannelState(&channel->info, SOFTBUS_TRANS_OPEN_AUTH_CONN_FAILED, true);
885     SoftBusFree(channel);
886     TRANS_LOGD(TRANS_CTRL, "ok");
887 }
888 
CheckAuthConnStatus(const uint32_t requestId)889 static int32_t CheckAuthConnStatus(const uint32_t requestId)
890 {
891     UdpChannelInfo channel;
892     if (TransGetUdpChannelByRequestId(requestId, &channel) != SOFTBUS_OK) {
893         TRANS_LOGE(TRANS_CTRL, "get channel fail");
894         return SOFTBUS_TRANS_UDP_GET_CHANNEL_FAILED;
895     }
896     (void)memset_s(channel.info.sessionKey, sizeof(channel.info.sessionKey), 0, sizeof(channel.info.sessionKey));
897     return channel.errCode;
898 }
899 
UdpOpenAuthConn(const char * peerUdid,uint32_t requestId,bool isMeta,int32_t linkType)900 static int32_t UdpOpenAuthConn(const char *peerUdid, uint32_t requestId, bool isMeta, int32_t linkType)
901 {
902     AuthConnInfo auth;
903     (void)memset_s(&auth, sizeof(AuthConnInfo), 0, sizeof(AuthConnInfo));
904     AuthConnCallback cb = {0};
905     int32_t ret = SOFTBUS_TRANS_OPEN_AUTH_CONN_FAILED;
906     if (linkType == LANE_HML || linkType == LANE_P2P_REUSE) {
907         TRANS_LOGI(TRANS_CTRL, "get AuthConnInfo, linkType=%{public}d", linkType);
908         ret = AuthGetHmlConnInfo(peerUdid, &auth, isMeta);
909     }
910     if (ret != SOFTBUS_OK && (linkType == LANE_P2P || linkType == LANE_P2P_REUSE)) {
911         TRANS_LOGI(TRANS_CTRL, "get AuthConnInfo, linkType=%{public}d", linkType);
912         ret = AuthGetP2pConnInfo(peerUdid, &auth, isMeta);
913     }
914     if (ret != SOFTBUS_OK) {
915         ret = AuthGetPreferConnInfo(peerUdid, &auth, isMeta);
916     }
917     if (ret != SOFTBUS_OK) {
918         ret = AuthGetPreferConnInfo(peerUdid, &auth, true);
919         isMeta = true;
920     }
921     if (ret != SOFTBUS_OK) {
922         TRANS_LOGE(TRANS_CTRL, "get info fail: ret=%{public}d", ret);
923         TransCloseUdpChannelByRequestId(requestId);
924         return ret;
925     }
926 
927     cb.onConnOpened = UdpOnAuthConnOpened;
928     cb.onConnOpenFailed = UdpOnAuthConnOpenFailed;
929     ret = AuthOpenConn(&auth, requestId, &cb, isMeta);
930     if (ret != SOFTBUS_OK) {
931         TRANS_LOGE(TRANS_CTRL, "open fail: ret=%{public}d", ret);
932         return ret;
933     }
934     ret = CheckAuthConnStatus(requestId);
935     if (ret != SOFTBUS_OK) {
936         TRANS_LOGE(TRANS_CTRL, "status check failed: ret=%{public}d", ret);
937         return ret;
938     }
939 
940     TRANS_LOGI(TRANS_CTRL, "ok: reqId=%{public}u", requestId);
941     return SOFTBUS_OK;
942 }
943 
TransUdpGetAuthType(const char * peerNetWorkId,const char * mySessionName)944 static bool TransUdpGetAuthType(const char *peerNetWorkId, const char *mySessionName)
945 {
946     if (IsIShareSession(mySessionName) && IsAvailableMeta(peerNetWorkId)) {
947         return true;
948     }
949     return TransGetAuthTypeByNetWorkId(peerNetWorkId);
950 }
951 
OpenAuthConnForUdpNegotiation(UdpChannelInfo * channel)952 static int32_t OpenAuthConnForUdpNegotiation(UdpChannelInfo *channel)
953 {
954     TRANS_LOGD(TRANS_CTRL, "enter.");
955     if (channel == NULL) {
956         return SOFTBUS_INVALID_PARAM;
957     }
958     uint32_t requestId = AuthGenRequestId();
959 
960     if (GetUdpChannelLock() != SOFTBUS_OK) {
961         return SOFTBUS_LOCK_ERR;
962     }
963     UdpChannelInfo *channelObj = TransGetChannelObj(channel->info.myData.channelId);
964     if (channelObj == NULL) {
965         ReleaseUdpChannelLock();
966         return SOFTBUS_NOT_FIND;
967     }
968     channelObj->requestId = requestId;
969     channelObj->status = UDP_CHANNEL_STATUS_OPEN_AUTH;
970     bool isMeta = TransUdpGetAuthType(channel->info.peerNetWorkId, channel->info.myData.sessionName);
971     ReleaseUdpChannelLock();
972 
973     TransEventExtra extra = {
974         .calleePkg = NULL,
975         .callerPkg = NULL,
976         .socketName = channel->info.myData.sessionName,
977         .channelType = CHANNEL_TYPE_UDP,
978         .channelId = channel->info.myData.channelId,
979         .requestId = requestId,
980         .peerNetworkId = channel->info.peerNetWorkId
981     };
982     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_START_CONNECT, extra);
983     int32_t ret = UdpOpenAuthConn(channel->info.peerData.deviceId, requestId, isMeta, channel->info.linkType);
984     if (ret != SOFTBUS_OK) {
985         extra.errcode = ret;
986         extra.result = EVENT_STAGE_RESULT_FAILED;
987         TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_START_CONNECT, extra);
988         TRANS_LOGE(TRANS_CTRL, "open auth conn fail");
989         return SOFTBUS_TRANS_OPEN_AUTH_CHANNEL_FAILED;
990     }
991     TRANS_LOGD(TRANS_CTRL, "ok");
992     return SOFTBUS_OK;
993 }
994 
PrepareAppInfoForUdpOpen(const ConnectOption * connOpt,AppInfo * appInfo,int32_t * channelId)995 static int32_t PrepareAppInfoForUdpOpen(const ConnectOption *connOpt, AppInfo *appInfo, int32_t *channelId)
996 {
997     appInfo->peerData.port = connOpt->socketOption.port;
998     if (strcpy_s(appInfo->peerData.addr, sizeof(appInfo->peerData.addr), connOpt->socketOption.addr) != EOK) {
999         return SOFTBUS_STRCPY_ERR;
1000     }
1001     int32_t ret = SoftBusGenerateSessionKey(appInfo->sessionKey, sizeof(appInfo->sessionKey));
1002     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "generate session key failed.");
1003 
1004     int32_t connType = connOpt->type;
1005     switch (connType) {
1006         case CONNECT_TCP:
1007             appInfo->udpConnType = UDP_CONN_TYPE_WIFI;
1008             appInfo->routeType = WIFI_STA;
1009             ret = LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, appInfo->myData.addr, sizeof(appInfo->myData.addr));
1010             TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get local ip fail");
1011             appInfo->protocol = connOpt->socketOption.protocol;
1012             break;
1013         case CONNECT_P2P:
1014         case CONNECT_P2P_REUSE:
1015         case CONNECT_HML:
1016             appInfo->udpConnType = UDP_CONN_TYPE_P2P;
1017             appInfo->routeType = WIFI_P2P;
1018             appInfo->protocol = connOpt->socketOption.protocol;
1019             break;
1020         default:
1021             TRANS_LOGE(TRANS_CTRL, "invalid connType.");
1022             return SOFTBUS_CONN_INVALID_CONN_TYPE;
1023     }
1024 
1025     int32_t id = GenerateUdpChannelId();
1026     if (id == INVALID_ID) {
1027         TRANS_LOGE(TRANS_CTRL, "generate udp channel id failed.");
1028         return SOFTBUS_TRANS_UDP_INVALID_CHANNEL_ID;
1029     }
1030     *channelId = id;
1031     appInfo->myData.channelId = id;
1032     appInfo->udpChannelOptType = TYPE_UDP_CHANNEL_OPEN;
1033     return SOFTBUS_OK;
1034 }
1035 
TransUdpGetChannelAndOpenConn(int32_t channelId)1036 static int32_t TransUdpGetChannelAndOpenConn(int32_t channelId)
1037 {
1038     UdpChannelInfo udpChannel;
1039     (void)memset_s(&udpChannel, sizeof(udpChannel), 0, sizeof(udpChannel));
1040     int32_t ret = TransGetUdpChannelById(channelId, &udpChannel);
1041     (void)memset_s(udpChannel.info.sessionKey, sizeof(udpChannel.info.sessionKey), 0,
1042         sizeof(udpChannel.info.sessionKey));
1043     if (ret != SOFTBUS_OK) {
1044         TRANS_LOGE(TRANS_CTRL, "get udp channel by channel id failed. channelId=%{public}d", channelId);
1045         ReleaseUdpChannelId(channelId);
1046         return ret;
1047     }
1048     ret = OpenAuthConnForUdpNegotiation(&udpChannel);
1049     if (ret != SOFTBUS_OK) {
1050         TRANS_LOGE(TRANS_CTRL, "open udp negotiation failed. channelId=%{public}d", channelId);
1051         ReleaseUdpChannelId(channelId);
1052         TransDelUdpChannel(channelId);
1053         return ret;
1054     }
1055     return SOFTBUS_OK;
1056 }
1057 
TransOpenUdpChannel(AppInfo * appInfo,const ConnectOption * connOpt,int32_t * channelId)1058 int32_t TransOpenUdpChannel(AppInfo *appInfo, const ConnectOption *connOpt, int32_t *channelId)
1059 {
1060     TRANS_LOGI(TRANS_CTRL, "server trans open udp channel.");
1061     if (appInfo == NULL || connOpt == NULL || channelId == NULL) {
1062         TRANS_LOGE(TRANS_CTRL, "invaild param.");
1063         return SOFTBUS_INVALID_PARAM;
1064     }
1065     int32_t id;
1066     if (PrepareAppInfoForUdpOpen(connOpt, appInfo, &id) != SOFTBUS_OK) {
1067         TRANS_LOGE(TRANS_CTRL, "prepare app info for opening udp channel.");
1068         return SOFTBUS_TRANS_UDP_PREPARE_APP_INFO_FAILED;
1069     }
1070     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)(id + ID_OFFSET));
1071     TRANS_LOGI(TRANS_CTRL,
1072         "SoftbusHitraceChainBegin: set HitraceId=%{public}" PRIu64, (uint64_t)(id + ID_OFFSET));
1073     UdpChannelInfo *newChannel = NewUdpChannelByAppInfo(appInfo);
1074     if (newChannel == NULL) {
1075         TRANS_LOGE(TRANS_CTRL, "new udp channel failed.");
1076         ReleaseUdpChannelId(id);
1077         return SOFTBUS_MEM_ERR;
1078     }
1079     newChannel->seq = GenerateSeq(false);
1080     newChannel->status = UDP_CHANNEL_STATUS_INIT;
1081     int32_t ret = TransAddUdpChannel(newChannel);
1082     if (ret != SOFTBUS_OK) {
1083         TRANS_LOGE(TRANS_CTRL, "add new udp channel failed.");
1084         ReleaseUdpChannelId(id);
1085         if (newChannel->info.fastTransData != NULL) {
1086             SoftBusFree((void *)newChannel->info.fastTransData);
1087         }
1088         (void)memset_s(newChannel->info.sessionKey, sizeof(newChannel->info.sessionKey), 0,
1089             sizeof(newChannel->info.sessionKey));
1090         SoftBusFree(newChannel);
1091         return ret;
1092     }
1093 
1094     ret = TransUdpGetChannelAndOpenConn(id);
1095     if (ret != SOFTBUS_OK) {
1096         TRANS_LOGE(TRANS_CTRL, "set udp channel by channel id failed. channelId=%{public}d", id);
1097         return ret;
1098     }
1099     *channelId = id;
1100     return SOFTBUS_OK;
1101 }
1102 
TransCloseUdpChannel(int32_t channelId)1103 int32_t TransCloseUdpChannel(int32_t channelId)
1104 {
1105     TRANS_LOGI(TRANS_CTRL, "server trans close udp channel.");
1106     UdpChannelInfo channel;
1107     (void)memset_s(&channel, sizeof(channel), 0, sizeof(channel));
1108 
1109     int32_t ret = TransSetUdpChannelOptType(channelId, TYPE_UDP_CHANNEL_CLOSE);
1110     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "set udp channel close type failed.");
1111 
1112     ret = TransGetUdpChannelById(channelId, &channel);
1113     (void)memset_s(channel.info.sessionKey, sizeof(channel.info.sessionKey), 0, sizeof(channel.info.sessionKey));
1114     if (ret != SOFTBUS_OK) {
1115         TRANS_LOGE(TRANS_CTRL, "get udp channel by channel id failed. channelId=%{public}d", channelId);
1116         return ret;
1117     }
1118     NotifyWifiByDelScenario(channel.info.streamType, channel.info.myData.pid);
1119     ret = OpenAuthConnForUdpNegotiation(&channel);
1120     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "open udp negotiation failed.");
1121 
1122     return SOFTBUS_OK;
1123 }
1124 
UdpModuleCb(AuthHandle authHandle,const AuthTransData * data)1125 static void UdpModuleCb(AuthHandle authHandle, const AuthTransData *data)
1126 {
1127     if (data == NULL || data->data == NULL || data->len < 1) {
1128         TRANS_LOGW(TRANS_CTRL, "invalid param.");
1129         return;
1130     }
1131     if (authHandle.type < AUTH_LINK_TYPE_WIFI || authHandle.type >= AUTH_LINK_TYPE_MAX) {
1132         TRANS_LOGW(TRANS_CTRL, "authHandle type error");
1133         return;
1134     }
1135     TRANS_LOGI(TRANS_CTRL,
1136         "udp module callback enter: module=%{public}d, seq=%{public}" PRId64 ", len=%{public}u.",
1137         data->module, data->seq, data->len);
1138     cJSON *json = cJSON_ParseWithLength((char *)data->data, data->len);
1139     if (json == NULL) {
1140         TRANS_LOGE(TRANS_CTRL, "cjson parse failed!");
1141         return;
1142     }
1143     TransOnExchangeUdpInfo(authHandle, data->flag, data->seq, json);
1144     cJSON_Delete(json);
1145 
1146     if (data->flag) {
1147         AuthCloseConn(authHandle);
1148     }
1149 }
1150 
TransUdpNodeOffLineProc(const LnnEventBasicInfo * info)1151 void TransUdpNodeOffLineProc(const LnnEventBasicInfo *info)
1152 {
1153     if ((info == NULL) || (info->event != LNN_EVENT_NODE_ONLINE_STATE_CHANGED)) {
1154         return;
1155     }
1156 
1157     LnnOnlineStateEventInfo *onlineStateInfo = (LnnOnlineStateEventInfo*)info;
1158     if (onlineStateInfo->isOnline == true) {
1159         return;
1160     }
1161 
1162     TransCloseUdpChannelByNetWorkId(onlineStateInfo->networkId);
1163 }
1164 
TransUdpChannelInit(IServerChannelCallBack * callback)1165 int32_t TransUdpChannelInit(IServerChannelCallBack *callback)
1166 {
1167     g_channelCb = callback;
1168     int32_t ret = SoftBusMutexInit(&g_udpNegLock, NULL);
1169     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_TRANS_INIT_FAILED,
1170         TRANS_INIT, "g_udpNegLock init failed.");
1171 
1172     ret = TransUdpChannelMgrInit();
1173     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans udp channel manager init failed.");
1174 
1175     AuthTransListener transUdpCb = {
1176         .onDataReceived = UdpModuleCb,
1177         .onDisconnected = NULL,
1178         .onException = NULL,
1179     };
1180 
1181     ret = RegAuthTransListener(MODULE_UDP_INFO, &transUdpCb);
1182     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "register udp callback to auth failed.");
1183 
1184     TRANS_LOGI(TRANS_INIT, "server trans udp channel init success.");
1185     return SOFTBUS_OK;
1186 }
1187 
TransUdpChannelDeinit(void)1188 void TransUdpChannelDeinit(void)
1189 {
1190     TransUdpChannelMgrDeinit();
1191     UnregAuthTransListener(MODULE_UDP_INFO);
1192 
1193     g_channelCb = NULL;
1194     TRANS_LOGI(TRANS_INIT, "server trans udp channel deinit success.");
1195 }
1196 
TransUdpDeathCallback(const char * pkgName,int32_t pid)1197 void TransUdpDeathCallback(const char *pkgName, int32_t pid)
1198 {
1199     if (pkgName == NULL) {
1200         TRANS_LOGE(TRANS_CTRL, "param invalid");
1201         return;
1202     }
1203 
1204     if (GetUdpChannelLock() != SOFTBUS_OK) {
1205         TRANS_LOGE(TRANS_CTRL, "lock failed");
1206         return;
1207     }
1208     ListNode destroyList;
1209     ListInit(&destroyList);
1210 
1211     SoftBusList *udpChannelList = GetUdpChannelMgrHead();
1212     UdpChannelInfo *udpChannelNode = NULL;
1213     LIST_FOR_EACH_ENTRY(udpChannelNode, &(udpChannelList->list), UdpChannelInfo, node) {
1214         if ((strcmp(udpChannelNode->info.myData.pkgName, pkgName) == 0) && (udpChannelNode->info.myData.pid == pid)) {
1215             udpChannelNode->info.udpChannelOptType = TYPE_UDP_CHANNEL_CLOSE;
1216             UdpChannelInfo *tempNode = (UdpChannelInfo*)SoftBusMalloc(sizeof(UdpChannelInfo));
1217             if (tempNode == NULL) {
1218                 continue;
1219             }
1220             *tempNode = *udpChannelNode;
1221             ListAdd(&destroyList, &tempNode->node);
1222             char *anonymizePkgName = NULL;
1223             Anonymize(pkgName, &anonymizePkgName);
1224             TRANS_LOGW(TRANS_CTRL, "add pkgName=%{public}s, pid=%{public}d", anonymizePkgName, pid);
1225             AnonymizeFree(anonymizePkgName);
1226         }
1227     }
1228     (void)ReleaseUdpChannelLock();
1229 
1230     UdpChannelInfo *udpChannelNodeNext = NULL;
1231     LIST_FOR_EACH_ENTRY_SAFE(udpChannelNode, udpChannelNodeNext, (&destroyList), UdpChannelInfo, node) {
1232         if (OpenAuthConnForUdpNegotiation(udpChannelNode) != SOFTBUS_OK) {
1233             TRANS_LOGE(TRANS_CTRL, "open udp negotiation failed.");
1234         }
1235         NotifyWifiByDelScenario(udpChannelNode->info.streamType, pid);
1236         ListDelete(&udpChannelNode->node);
1237         SoftBusFree(udpChannelNode);
1238     }
1239     return;
1240 }