• 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_channel_manager.h"
17 
18 #include <securec.h>
19 
20 #include "access_control.h"
21 #include "anonymizer.h"
22 #include "bus_center_manager.h"
23 
24 #include "g_enhance_lnn_func.h"
25 #include "g_enhance_lnn_func_pack.h"
26 #include "g_enhance_trans_func.h"
27 #include "g_enhance_trans_func_pack.h"
28 #include "legacy/softbus_adapter_hitrace.h"
29 #include "legacy/softbus_hisysevt_transreporter.h"
30 #include "lnn_distributed_net_ledger.h"
31 #include "message_handler.h"
32 #include "session.h"
33 #include "softbus_adapter_mem.h"
34 #include "softbus_conn_interface.h"
35 #include "softbus_def.h"
36 #include "softbus_error_code.h"
37 #include "softbus_proxychannel_manager.h"
38 #include "softbus_proxychannel_session.h"
39 #include "softbus_proxychannel_transceiver.h"
40 #include "softbus_utils.h"
41 #include "softbus_init_common.h"
42 #include "trans_auth_lane_pending_ctl.h"
43 #include "trans_auth_manager.h"
44 #include "trans_auth_negotiation.h"
45 #include "trans_bind_request_manager.h"
46 #include "trans_channel_callback.h"
47 #include "trans_channel_common.h"
48 #include "trans_event.h"
49 #include "trans_ipc_adapter.h"
50 #include "trans_lane_manager.h"
51 #include "trans_lane_pending_ctl.h"
52 #include "trans_link_listener.h"
53 #include "trans_log.h"
54 #include "trans_network_statistics.h"
55 #include "trans_session_manager.h"
56 #include "trans_tcp_direct_manager.h"
57 #include "trans_tcp_direct_message.h"
58 #include "trans_tcp_direct_sessionconn.h"
59 #include "trans_udp_channel_manager.h"
60 #include "trans_udp_negotiation.h"
61 #include "trans_uk_manager.h"
62 
63 #define MAX_PROXY_CHANNEL_ID 0x00000800
64 #define MAX_TDC_CHANNEL_ID 0x7FFFFFFF
65 #define MIN_FD_ID 1025
66 #define MAX_FD_ID 2048
67 #define MAX_PROXY_CHANNEL_ID_COUNT 1024
68 #define ID_NOT_USED 0
69 #define ID_USED 1UL
70 #define BIT_NUM 8
71 #define REPORT_UDP_INFO_SIZE 4
72 #define ACCESS_INFO_PARAM_NUM 3
73 
74 static int32_t g_allocTdcChannelId = MAX_PROXY_CHANNEL_ID;
75 static SoftBusMutex g_myIdLock;
76 static unsigned long g_proxyChanIdBits[MAX_PROXY_CHANNEL_ID_COUNT / BIT_NUM / sizeof(long)] = {0};
77 static uint32_t g_proxyIdMark = 0;
78 static uint32_t g_channelIdCount = 0;
79 
80 const char *g_channelResultLoopName = "transChannelResultLoopName";
81 SoftBusHandler g_channelResultHandler = { 0 };
82 
83 typedef enum {
84     LOOP_CHANNEL_OPEN_MSG,
85     LOOP_LIMIT_CHANGE_MSG,
86 } ChannelResultLoopMsg;
87 
88 typedef struct {
89     int32_t channelId;
90     int32_t channelType;
91     int32_t openResult;
92 } OpenChannelResult;
93 
94 typedef struct {
95     ListNode node;
96     int32_t pid;
97     char pkgName[PKG_NAME_SIZE_MAX];
98 } PrivilegeCloseChannelInfo;
99 
GenerateTdcChannelId()100 static int32_t GenerateTdcChannelId()
101 {
102     int32_t channelId;
103     if (SoftBusMutexLock(&g_myIdLock) != SOFTBUS_OK) {
104         TRANS_LOGE(TRANS_CTRL, "lock mutex fail!");
105         return SOFTBUS_LOCK_ERR;
106     }
107     channelId = g_allocTdcChannelId++;
108     if (g_allocTdcChannelId >= MAX_TDC_CHANNEL_ID) {
109         g_allocTdcChannelId = MAX_PROXY_CHANNEL_ID;
110     }
111     SoftBusMutexUnlock(&g_myIdLock);
112     return channelId;
113 }
114 
GenerateProxyChannelId()115 static int32_t GenerateProxyChannelId()
116 {
117     if (SoftBusMutexLock(&g_myIdLock) != SOFTBUS_OK) {
118         TRANS_LOGE(TRANS_CTRL, "lock mutex fail!");
119         return SOFTBUS_LOCK_ERR;
120     }
121 
122     if (g_channelIdCount >= MAX_PROXY_CHANNEL_ID_COUNT) {
123         TRANS_LOGE(TRANS_CTRL, "No more channel Ids(1024) can be applied");
124         SoftBusMutexUnlock(&g_myIdLock);
125         return INVALID_CHANNEL_ID;
126     }
127 
128     for (uint32_t id = g_proxyIdMark + 1; id != g_proxyIdMark; id++) {
129         id = id % MAX_PROXY_CHANNEL_ID_COUNT;
130         uint32_t index = id / (BIT_NUM * sizeof(long));
131         uint32_t bit = id % (BIT_NUM * sizeof(long));
132         if ((g_proxyChanIdBits[index] & (ID_USED << bit)) == ID_NOT_USED) {
133             g_proxyChanIdBits[index] |= (ID_USED << bit);
134             g_proxyIdMark = id;
135             g_channelIdCount++;
136             SoftBusMutexUnlock(&g_myIdLock);
137             return (int32_t)id + MIN_FD_ID;
138         }
139     }
140     SoftBusMutexUnlock(&g_myIdLock);
141     return INVALID_CHANNEL_ID;
142 }
143 
ReleaseProxyChannelId(int32_t channelId)144 void ReleaseProxyChannelId(int32_t channelId)
145 {
146     if (channelId < MIN_FD_ID || channelId > MAX_FD_ID) {
147         return;
148     }
149     if (SoftBusMutexLock(&g_myIdLock) != SOFTBUS_OK) {
150         TRANS_LOGE(TRANS_CTRL, "lock mutex fail");
151         return;
152     }
153     if (g_channelIdCount >= ID_USED) {
154         g_channelIdCount--;
155     } else {
156         TRANS_LOGE(TRANS_CTRL, "g_channelIdCount error");
157     }
158     uint32_t id = (uint32_t)channelId - MIN_FD_ID;
159     uint32_t dex = id / (8 * sizeof(long));
160     uint32_t bit = id % (8 * sizeof(long));
161     g_proxyChanIdBits[dex] &= (~(ID_USED << bit));
162     SoftBusMutexUnlock(&g_myIdLock);
163 }
164 
GenerateChannelId(bool isTdcChannel)165 int32_t GenerateChannelId(bool isTdcChannel)
166 {
167     return isTdcChannel ? GenerateTdcChannelId() : GenerateProxyChannelId();
168 }
169 
TransAsyncChannelOpenTaskManager(int32_t channelId,int32_t channelType)170 void TransAsyncChannelOpenTaskManager(int32_t channelId, int32_t channelType)
171 {
172     switch (channelType) {
173         case CHANNEL_TYPE_PROXY:
174             TransAsyncProxyChannelTask(channelId);
175             break;
176         case CHANNEL_TYPE_TCP_DIRECT:
177             TransAsyncTcpDirectChannelTask(channelId);
178             break;
179         case CHANNEL_TYPE_UDP:
180             TransAsyncUdpChannelTask(channelId);
181             break;
182         case CHANNEL_TYPE_AUTH:
183             TransAsyncAuthChannelTask(channelId);
184             break;
185         default:
186             TRANS_LOGE(TRANS_CTRL, "channelType=%{public}d is error!", channelType);
187     }
188 }
189 
TransChannelResultLoopMsgHandler(SoftBusMessage * msg)190 static void TransChannelResultLoopMsgHandler(SoftBusMessage *msg)
191 {
192     TRANS_CHECK_AND_RETURN_LOGE(msg != NULL, TRANS_MSG, "param msg is invalid");
193     int32_t channelId;
194     int32_t channelType;
195     if (msg->what == LOOP_CHANNEL_OPEN_MSG) {
196         channelId = (int32_t)msg->arg1;
197         channelType = (int32_t)msg->arg2;
198         TransAsyncChannelOpenTaskManager(channelId, channelType);
199     }
200 }
201 
TransChannelResultLoopInit(void)202 int32_t TransChannelResultLoopInit(void)
203 {
204     g_channelResultHandler.name = (char *)g_channelResultLoopName;
205     g_channelResultHandler.looper = GetLooper(LOOP_TYPE_DEFAULT);
206     if (g_channelResultHandler.looper == NULL) {
207         return SOFTBUS_TRANS_INIT_FAILED;
208     }
209     g_channelResultHandler.HandleMessage = TransChannelResultLoopMsgHandler;
210     return SOFTBUS_OK;
211 }
212 
TransChannelResultFreeLoopMsg(SoftBusMessage * msg)213 static void TransChannelResultFreeLoopMsg(SoftBusMessage *msg)
214 {
215     if (msg != NULL) {
216         if (msg->obj != NULL) {
217             SoftBusFree(msg->obj);
218         }
219         SoftBusFree((void *)msg);
220     }
221 }
222 
TransChannelResultCreateLoopMsg(int32_t what,uint64_t arg1,uint64_t arg2,char * data)223 static SoftBusMessage *TransChannelResultCreateLoopMsg(int32_t what, uint64_t arg1, uint64_t arg2, char *data)
224 {
225     SoftBusMessage *msg = (SoftBusMessage *)SoftBusCalloc(sizeof(SoftBusMessage));
226     if (msg == NULL) {
227         TRANS_LOGE(TRANS_MSG, "msg calloc failed");
228         return NULL;
229     }
230     msg->what = what;
231     msg->arg1 = arg1;
232     msg->arg2 = arg2;
233     msg->handler = &g_channelResultHandler;
234     msg->FreeMessage = TransChannelResultFreeLoopMsg;
235     msg->obj = (void *)data;
236     return msg;
237 }
238 
TransCheckChannelOpenToLooperDelay(int32_t channelId,int32_t channelType,uint32_t delayTime)239 void TransCheckChannelOpenToLooperDelay(int32_t channelId, int32_t channelType, uint32_t delayTime)
240 {
241     SoftBusMessage *msg  = TransChannelResultCreateLoopMsg(LOOP_CHANNEL_OPEN_MSG, channelId, channelType, NULL);
242     TRANS_CHECK_AND_RETURN_LOGE(msg != NULL, TRANS_MSG, "msg create failed");
243 
244     g_channelResultHandler.looper->PostMessageDelay(g_channelResultHandler.looper, msg, delayTime);
245 }
246 
RemoveMessageDestroy(const SoftBusMessage * msg,void * data)247 static int32_t RemoveMessageDestroy(const SoftBusMessage *msg, void *data)
248 {
249     int32_t channelId = *(int32_t *)data;
250     if (msg->what == LOOP_CHANNEL_OPEN_MSG && channelId == (int32_t)msg->arg1) {
251         TRANS_LOGE(TRANS_CTRL, "remove delay check channel opened message succ, channelId=%{public}d.", channelId);
252         return SOFTBUS_OK;
253     }
254     return SOFTBUS_INVALID_PARAM;
255 }
256 
TransCheckChannelOpenRemoveFromLooper(int32_t channelId)257 void TransCheckChannelOpenRemoveFromLooper(int32_t channelId)
258 {
259     g_channelResultHandler.looper->RemoveMessageCustom(
260         g_channelResultHandler.looper, &g_channelResultHandler, RemoveMessageDestroy, &channelId);
261 }
262 
TransChannelInit(void)263 int32_t TransChannelInit(void)
264 {
265     IServerChannelCallBack *cb = TransServerGetChannelCb();
266     TRANS_CHECK_AND_RETURN_RET_LOGE(cb != NULL, SOFTBUS_NO_INIT, TRANS_INIT, "cd is null.");
267 
268     int32_t ret = TransLaneMgrInit();
269     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans lane manager init failed.");
270 
271     ret = TransSocketLaneMgrInit();
272     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans socket lane manager init failed.");
273 
274     ret = TransAuthInit(cb);
275     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans auth init failed.");
276 
277     ret = TransProxyManagerInit(cb);
278     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans proxy manager init failed.");
279 
280     ret = TransTcpDirectInit(cb);
281     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans tcp direct init failed.");
282 
283     ret = TransUdpChannelInit(cb);
284     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans udp channel init failed.");
285 
286     ret = TransBindRequestManagerInit();
287     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans bind request manager init failed.");
288 
289     ret = TransReqLanePendingInit();
290     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans req lane pending init failed.");
291 
292     ret = TransNetworkStatisticsInit();
293     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans network statistics init failed.");
294 
295     ret = TransAsyncReqLanePendingInit();
296     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans async req lane pending init failed.");
297 
298     ret = TransUkRequestMgrInit();
299     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans uk request manager init failed.");
300 
301     ret = TransReqAuthPendingInit();
302     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans auth request pending init failed.");
303     ret = TransAuthWithParaReqLanePendingInit();
304     TRANS_CHECK_AND_RETURN_RET_LOGE(
305         ret == SOFTBUS_OK, ret, TRANS_INIT, "trans auth with para req lane pending init failed.");
306 
307     ret = TransFreeLanePendingInit();
308     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans free lane pending init failed.");
309 
310     ret = TransChannelResultLoopInit();
311     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "trans channel result loop init failed.");
312 
313     ReqLinkListener();
314     ret = SoftBusMutexInit(&g_myIdLock, NULL);
315     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_INIT, "init lock failed.");
316     return SOFTBUS_OK;
317 }
318 
TransChannelDeinit(void)319 void TransChannelDeinit(void)
320 {
321     TransLaneMgrDeinit();
322     TransSocketLaneMgrDeinit();
323     TransAuthDeinit();
324     TransProxyManagerDeinit();
325     TransTcpDirectDeinit();
326     TransUdpChannelDeinit();
327     TransReqLanePendingDeinit();
328     TransAsyncReqLanePendingDeinit();
329     TransNetworkStatisticsDeinit();
330     TransReqAuthPendingDeinit();
331     TransAuthWithParaReqLanePendingDeinit();
332     TransFreeLanePendingDeinit();
333     TransBindRequestManagerDeinit();
334     TransUkRequestMgrDeinit();
335     SoftBusMutexDestroy(&g_myIdLock);
336 }
337 
TransSetFirstTokenInfo(AppInfo * appInfo,TransEventExtra * event)338 static void TransSetFirstTokenInfo(AppInfo *appInfo, TransEventExtra *event)
339 {
340     event->firstTokenId = TransAclGetFirstTokenID();
341     if (event->firstTokenId == TOKENID_NOT_SET) {
342         event->firstTokenId = appInfo->callingTokenId;
343     }
344     TransGetTokenInfo(event->firstTokenId, appInfo->tokenName, sizeof(appInfo->tokenName), &event->firstTokenType);
345     event->firstTokenName = appInfo->tokenName;
346 }
347 
TransSetQosInfo(const QosTV * qos,uint32_t qosCount,TransEventExtra * extra)348 static void TransSetQosInfo(const QosTV *qos, uint32_t qosCount, TransEventExtra *extra)
349 {
350     if (qosCount > QOS_TYPE_BUTT) {
351         TRANS_LOGE(TRANS_CTRL, "qos count error, qosCount=%{public}" PRIu32, qosCount);
352         return;
353     }
354 
355     for (uint32_t i = 0; i < qosCount; i++) {
356         switch (qos[i].qos) {
357             case QOS_TYPE_MIN_BW:
358                 extra->minBW = qos[i].value;
359                 break;
360             case QOS_TYPE_MAX_LATENCY:
361                 extra->maxLatency = qos[i].value;
362                 break;
363             case QOS_TYPE_MIN_LATENCY:
364                 extra->minLatency = qos[i].value;
365                 break;
366             default:
367                 break;
368         }
369     }
370 }
371 
IsLaneModuleError(int32_t errcode)372 static bool IsLaneModuleError(int32_t errcode)
373 {
374     if (errcode >= SOFTBUS_LANE_ERR_BASE && errcode < SOFTBUS_CONN_ERR_BASE) {
375         return true;
376     }
377     return false;
378 }
379 
TransFreeLaneInner(uint32_t laneHandle,bool isQosLane,bool isAsync)380 static void TransFreeLaneInner(uint32_t laneHandle, bool isQosLane, bool isAsync)
381 {
382     if (isQosLane) {
383         TransFreeLaneByLaneHandle(laneHandle, isAsync);
384     } else {
385         LnnFreeLane(laneHandle);
386     }
387 }
388 
TransOpenChannel(const SessionParam * param,TransInfo * transInfo)389 int32_t TransOpenChannel(const SessionParam *param, TransInfo *transInfo)
390 {
391     SoftBusHitraceChainBegin("TransOpenChannel");
392     if (param == NULL || transInfo == NULL) {
393         TRANS_LOGE(TRANS_CTRL, "param invalid");
394         SoftBusHitraceChainEnd();
395         return SOFTBUS_INVALID_PARAM;
396     }
397     if (GetDeniedFlagByPeer(param->sessionName, param->peerSessionName, param->peerDeviceId)) {
398         TRANS_LOGE(TRANS_CTRL, "request denied: sessionId=%{public}d", param->sessionId);
399         SoftBusHitraceChainEnd();
400         return SOFTBUS_TRANS_BIND_REQUEST_DENIED;
401     }
402     char *tmpName = NULL;
403     Anonymize(param->sessionName, &tmpName);
404     TRANS_LOGI(TRANS_CTRL, "server TransOpenChannel, sessionName=%{public}s, socket=%{public}d, actionId=%{public}d, "
405                            "isQosLane=%{public}d, isAsync=%{public}d",
406         AnonymizeWrapper(tmpName), param->sessionId, param->actionId, param->isQosLane, param->isAsync);
407     AnonymizeFree(tmpName);
408     int32_t ret = INVALID_CHANNEL_ID;
409     uint32_t laneHandle = INVALID_LANE_REQ_ID;
410     CoreSessionState state = CORE_SESSION_STATE_INIT;
411     AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo));
412     if (appInfo == NULL) {
413         TRANS_LOGE(TRANS_CTRL, "calloc appInfo failed.");
414         SoftBusHitraceChainEnd();
415         return SOFTBUS_MALLOC_ERR;
416     }
417     ret = TransCommonGetAppInfo(param, appInfo);
418     if (ret != SOFTBUS_OK) {
419         TRANS_LOGE(TRANS_CTRL, "get appinfo failed");
420         TransFreeAppInfo(appInfo);
421         SoftBusHitraceChainEnd();
422         return ret;
423     }
424     ret = TransAddSocketChannelInfo(
425         param->sessionName, param->sessionId, INVALID_CHANNEL_ID, CHANNEL_TYPE_UNDEFINED, CORE_SESSION_STATE_INIT);
426     if (ret != SOFTBUS_OK) {
427         TRANS_LOGE(TRANS_CTRL, "Add socket channel record failed.");
428         TransFreeAppInfo(appInfo);
429         SoftBusHitraceChainEnd();
430         return ret;
431     }
432     NodeInfo nodeInfo;
433     (void)memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
434     int32_t peerRet = LnnGetRemoteNodeInfoById(appInfo->peerNetWorkId, CATEGORY_NETWORK_ID, &nodeInfo);
435     appInfo->osType = nodeInfo.deviceInfo.osType;
436     TransEventExtra extra;
437     (void)memset_s(&extra, sizeof(TransEventExtra), 0, sizeof(TransEventExtra));
438     TransBuildTransOpenChannelStartEvent(&extra, appInfo, &nodeInfo, peerRet);
439     TransSetFirstTokenInfo(appInfo, &extra);
440     TransSetQosInfo(param->qos, param->qosCount, &extra);
441     extra.sessionId = param->sessionId;
442     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_OPEN_CHANNEL_START, extra);
443     if (param->isQosLane) {
444         ret = TransAsyncGetLaneInfo(param, &laneHandle, appInfo->callingTokenId, appInfo->timeStart);
445         if (ret != SOFTBUS_OK) {
446             Anonymize(param->sessionName, &tmpName);
447             TRANS_LOGE(TRANS_CTRL, "Async get Lane failed, sessionName=%{public}s, sessionId=%{public}d",
448                 AnonymizeWrapper(tmpName), param->sessionId);
449             AnonymizeFree(tmpName);
450             if (ret != SOFTBUS_TRANS_STOP_BIND_BY_CANCEL) {
451                 TransFreeLaneInner(laneHandle, param->isQosLane, param->isAsync);
452             }
453             (void)TransDeleteSocketChannelInfoBySession(param->sessionName, param->sessionId);
454         }
455         TransFreeAppInfo(appInfo);
456         SoftBusHitraceChainEnd();
457         return ret;
458     }
459     transInfo->channelId = INVALID_CHANNEL_ID;
460     transInfo->channelType = CHANNEL_TYPE_BUTT;
461     LaneConnInfo connInfo;
462     ConnectOption connOpt;
463     (void)memset_s(&connOpt, sizeof(ConnectOption), 0, sizeof(ConnectOption));
464     ret = TransGetLaneInfo(param, &connInfo, &laneHandle);
465     if (ret != SOFTBUS_OK) {
466         SoftbusReportTransErrorEvt(SOFTBUS_TRANS_GET_LANE_INFO_ERR);
467         goto EXIT_ERR;
468     }
469     Anonymize(param->sessionName, &tmpName);
470     TRANS_LOGI(TRANS_CTRL,
471         "sessionName=%{public}s, socket=%{public}d, laneHandle=%{public}u, linkType=%{public}u.",
472         AnonymizeWrapper(tmpName), param->sessionId, laneHandle, connInfo.type);
473     AnonymizeFree(tmpName);
474     ret = TransGetConnectOptByConnInfo(&connInfo, &connOpt);
475     if (ret != SOFTBUS_OK) {
476         SoftbusRecordOpenSessionKpi(appInfo->myData.pkgName, connInfo.type,
477             SOFTBUS_EVT_OPEN_SESSION_FAIL, GetSoftbusRecordTimeMillis() - appInfo->timeStart);
478         goto EXIT_ERR;
479     }
480     appInfo->connectType = connOpt.type;
481     extra.linkType = connOpt.type;
482     extra.deviceState = TransGetDeviceState(param->peerDeviceId);
483     FillAppInfo(appInfo, param, transInfo, &connInfo);
484     TransOpenChannelSetModule(transInfo->channelType, &connOpt);
485     TRANS_LOGI(TRANS_CTRL, "laneHandle=%{public}u, channelType=%{public}u", laneHandle, transInfo->channelType);
486     TransGetSocketChannelStateBySession(param->sessionName, param->sessionId, &state);
487     if (state == CORE_SESSION_STATE_CANCELLING) {
488         goto EXIT_CANCEL;
489     }
490     TransSetSocketChannelStateBySession(param->sessionName, param->sessionId, CORE_SESSION_STATE_LAN_COMPLETE);
491     ret = TransOpenChannelProc((ChannelType)transInfo->channelType, appInfo, &connOpt,
492         &(transInfo->channelId));
493     (void)memset_s(appInfo->sessionKey, sizeof(appInfo->sessionKey), 0, sizeof(appInfo->sessionKey));
494     if (ret != SOFTBUS_OK) {
495         SoftbusReportTransErrorEvt(SOFTBUS_TRANS_CREATE_CHANNEL_ERR);
496         SoftbusRecordOpenSessionKpi(appInfo->myData.pkgName,
497             appInfo->linkType, SOFTBUS_EVT_OPEN_SESSION_FAIL, GetSoftbusRecordTimeMillis() - appInfo->timeStart);
498         goto EXIT_ERR;
499     }
500     if (TransUpdateSocketChannelInfoBySession(
501         param->sessionName, param->sessionId, transInfo->channelId, transInfo->channelType) != SOFTBUS_OK) {
502         SoftbusRecordOpenSessionKpi(appInfo->myData.pkgName, appInfo->linkType, SOFTBUS_EVT_OPEN_SESSION_FAIL,
503             GetSoftbusRecordTimeMillis() - appInfo->timeStart);
504         TransCloseChannel(NULL, transInfo->channelId, transInfo->channelType);
505         goto EXIT_ERR;
506     }
507     TransSetSocketChannelStateByChannel(
508         transInfo->channelId, transInfo->channelType, CORE_SESSION_STATE_CHANNEL_OPENED);
509     if (TransLaneMgrAddLane(transInfo, &connInfo, laneHandle, param->isQosLane, &appInfo->myData) != SOFTBUS_OK) {
510         SoftbusRecordOpenSessionKpi(appInfo->myData.pkgName, appInfo->linkType, SOFTBUS_EVT_OPEN_SESSION_FAIL,
511             GetSoftbusRecordTimeMillis() - appInfo->timeStart);
512         TransCloseChannel(NULL, transInfo->channelId, transInfo->channelType);
513         goto EXIT_ERR;
514     }
515     AddChannelStatisticsInfo(transInfo->channelId, transInfo->channelType);
516     TransFreeAppInfo(appInfo);
517     TRANS_LOGI(TRANS_CTRL,
518         "server TransOpenChannel ok: socket=%{public}d, channelId=%{public}d, channelType=%{public}d, "
519         "laneHandle=%{public}u",
520         param->sessionId, transInfo->channelId, transInfo->channelType, laneHandle);
521     SoftBusHitraceChainEnd();
522     return SOFTBUS_OK;
523 EXIT_ERR:
524     extra.linkType = IsLaneModuleError(ret) ? extra.linkType : CONNECT_HML;
525     TransBuildTransOpenChannelEndEvent(&extra, transInfo, appInfo->timeStart, ret);
526     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_OPEN_CHANNEL_END, extra);
527     TransAlarmExtra extraAlarm;
528     TransBuildTransAlarmEvent(&extraAlarm, appInfo, ret);
529     TRANS_ALARM(OPEN_SESSION_FAIL_ALARM, CONTROL_ALARM_TYPE, extraAlarm);
530     TransFreeAppInfo(appInfo);
531     if (ret != SOFTBUS_TRANS_STOP_BIND_BY_CANCEL || laneHandle != INVALID_LANE_REQ_ID) {
532         TransFreeLaneInner(laneHandle, param->isQosLane, param->isAsync);
533     }
534     (void)TransDeleteSocketChannelInfoBySession(param->sessionName, param->sessionId);
535     TRANS_LOGE(TRANS_SVC, "server TransOpenChannel err, socket=%{public}d, ret=%{public}d", param->sessionId, ret);
536     SoftBusHitraceChainEnd();
537     return ret;
538 EXIT_CANCEL:
539     TransBuildTransOpenChannelCancelEvent(&extra, transInfo, appInfo->timeStart, SOFTBUS_TRANS_STOP_BIND_BY_CANCEL);
540     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_OPEN_CHANNEL_END, extra);
541     TransFreeAppInfo(appInfo);
542     TransFreeLaneInner(laneHandle, param->isQosLane, param->isAsync);
543     (void)TransDeleteSocketChannelInfoBySession(param->sessionName, param->sessionId);
544     TRANS_LOGE(TRANS_SVC, "server open channel cancel, socket=%{public}d", param->sessionId);
545     SoftBusHitraceChainEnd();
546     return SOFTBUS_TRANS_STOP_BIND_BY_CANCEL;
547 }
548 
GetAuthAppInfo(const char * mySessionName)549 static AppInfo *GetAuthAppInfo(const char *mySessionName)
550 {
551     TRANS_LOGD(TRANS_CTRL, "enter.");
552     AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo));
553     if (appInfo == NULL) {
554         return NULL;
555     }
556     appInfo->appType = APP_TYPE_AUTH;
557     appInfo->myData.apiVersion = API_V2;
558     appInfo->autoCloseTime = 0;
559     appInfo->businessType = BUSINESS_TYPE_BYTE;
560     appInfo->channelType = CHANNEL_TYPE_AUTH;
561     appInfo->timeStart = GetSoftbusRecordTimeMillis();
562     appInfo->isClient = true;
563     if (TransGetUidAndPid(mySessionName, &appInfo->myData.uid, &appInfo->myData.pid) != SOFTBUS_OK) {
564         TRANS_LOGE(TRANS_CTRL, "GetAuthAppInfo GetUidAndPid failed");
565         goto EXIT_ERR;
566     }
567     if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, appInfo->myData.deviceId,
568         sizeof(appInfo->myData.deviceId)) != SOFTBUS_OK) {
569         TRANS_LOGE(TRANS_CTRL, "GetAuthAppInfo get deviceId failed");
570         goto EXIT_ERR;
571     }
572     if (strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), mySessionName) != EOK) {
573         TRANS_LOGE(TRANS_CTRL, "GetAuthAppInfo strcpy_s mySessionName failed");
574         goto EXIT_ERR;
575     }
576     if (strcpy_s(appInfo->peerData.sessionName, sizeof(appInfo->peerData.sessionName), mySessionName) != EOK) {
577         TRANS_LOGE(TRANS_CTRL, "GetAuthAppInfo strcpy_s peerSessionName failed");
578         goto EXIT_ERR;
579     }
580     if (TransGetPkgNameBySessionName(mySessionName, appInfo->myData.pkgName, PKG_NAME_SIZE_MAX) != SOFTBUS_OK) {
581         TRANS_LOGE(TRANS_CTRL, "GetAuthAppInfo get PkgName failed");
582         goto EXIT_ERR;
583     }
584     if (TransCommonGetLocalConfig(appInfo->channelType, appInfo->businessType, &appInfo->myData.dataConfig) !=
585         SOFTBUS_OK) {
586         TRANS_LOGE(TRANS_CTRL, "GetAuthAppInfo get local data config failed");
587         goto EXIT_ERR;
588     }
589 
590     TRANS_LOGD(TRANS_CTRL, "ok");
591     return appInfo;
592 EXIT_ERR:
593     SoftBusFree(appInfo);
594     return NULL;
595 }
596 
TransOpenAuthChannel(const char * sessionName,const ConnectOption * connOpt,const char * reqId,const ConnectParam * param)597 int32_t TransOpenAuthChannel(const char *sessionName, const ConnectOption *connOpt,
598     const char *reqId, const ConnectParam *param)
599 {
600     SoftBusHitraceChainBegin("TransOpenAuthChannel");
601     int32_t channelId = INVALID_CHANNEL_ID;
602     if (!IsValidString(sessionName, SESSION_NAME_SIZE_MAX) || connOpt == NULL || param == NULL) {
603         SoftBusHitraceChainEnd();
604         return channelId;
605     }
606     char callerPkg[PKG_NAME_SIZE_MAX] = {0};
607     char localUdid[UDID_BUF_LEN] = {0};
608     TransEventExtra extra;
609     (void)memset_s(&extra, sizeof(TransEventExtra), 0, sizeof(TransEventExtra));
610     TransBuildOpenAuthChannelStartEvent(&extra, sessionName, connOpt, localUdid, callerPkg);
611     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_OPEN_CHANNEL_START, extra);
612     if (connOpt->type == CONNECT_TCP) {
613         if (TransOpenAuthMsgChannel(sessionName, connOpt, &channelId, reqId) != SOFTBUS_OK) {
614             goto EXIT_ERR;
615         }
616     } else if (connOpt->type == CONNECT_BR || connOpt->type == CONNECT_BLE) {
617         AppInfo *appInfo = GetAuthAppInfo(sessionName);
618         if (appInfo == NULL) {
619             TRANS_LOGE(TRANS_CTRL, "GetAuthAppInfo failed");
620             goto EXIT_ERR;
621         }
622         appInfo->blePriority = param->blePriority;
623         appInfo->connectType = connOpt->type;
624         if (strcpy_s(appInfo->reqId, REQ_ID_SIZE_MAX, reqId) != EOK) {
625             TRANS_LOGE(TRANS_CTRL, "strcpy_s reqId failed");
626             SoftBusFree(appInfo);
627             goto EXIT_ERR;
628         }
629         if (TransProxyOpenProxyChannel(appInfo, connOpt, &channelId) != SOFTBUS_OK) {
630             TRANS_LOGE(TRANS_CTRL, "proxy channel err");
631             SoftBusFree(appInfo);
632             goto EXIT_ERR;
633         }
634         SoftBusFree(appInfo);
635     } else {
636         goto EXIT_ERR;
637     }
638     SoftBusHitraceChainEnd();
639     return channelId;
640 EXIT_ERR:
641     extra.result = EVENT_STAGE_RESULT_FAILED;
642     extra.errcode = SOFTBUS_TRANS_AUTH_CHANNEL_NOT_FOUND;
643     TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_OPEN_CHANNEL_END, extra);
644     SoftBusHitraceChainEnd();
645     return INVALID_CHANNEL_ID;
646 }
647 
MergeStatsInterval(const uint32_t * data,uint32_t left,uint32_t right)648 static uint32_t MergeStatsInterval(const uint32_t *data, uint32_t left, uint32_t right)
649 {
650     uint32_t result = 0;
651     while (left <= right) {
652         result += data[left];
653         left++;
654     }
655     return result;
656 }
657 
ConvertStreamStats(const StreamSendStats * src,FrameSendStats * dest)658 static void ConvertStreamStats(const StreamSendStats *src, FrameSendStats *dest)
659 {
660     uint32_t *srcCostCnt = (uint32_t *)(src->costTimeStatsCnt);
661     uint32_t *srcBitRate = (uint32_t *)(src->sendBitRateStatsCnt);
662     uint32_t *destCostCnt = dest->costTimeStatsCnt;
663     uint32_t *destBitRate = dest->sendBitRateStatsCnt;
664     destCostCnt[FRAME_COST_TIME_SMALL] = srcCostCnt[FRAME_COST_LT10MS];
665     destCostCnt[FRAME_COST_TIME_MEDIUM] = MergeStatsInterval(srcCostCnt, FRAME_COST_LT30MS, FRAME_COST_LT100MS);
666     destCostCnt[FRAME_COST_TIME_LARGE] = srcCostCnt[FRAME_COST_LT120MS] + srcCostCnt[FRAME_COST_GE120MS];
667     destBitRate[FRAME_BIT_RATE_SMALL] = srcBitRate[FRAME_BIT_RATE_LT3M];
668     destBitRate[FRAME_BIT_RATE_MEDIUM] = MergeStatsInterval(srcBitRate, FRAME_BIT_RATE_LT6M, FRAME_BIT_RATE_LT30M);
669     destBitRate[FRAME_BIT_RATE_LARGE] = srcBitRate[FRAME_BIT_RATE_GE30M];
670 }
671 
TransStreamStats(int32_t channelId,int32_t channelType,const StreamSendStats * data)672 int32_t TransStreamStats(int32_t channelId, int32_t channelType, const StreamSendStats *data)
673 {
674     (void)channelType;
675     if (data == NULL) {
676         TRANS_LOGE(TRANS_STREAM, "streamStats data is null");
677         return SOFTBUS_INVALID_PARAM;
678     }
679     uint32_t laneHandle;
680     int32_t ret = TransGetLaneHandleByChannelId(channelId, &laneHandle);
681     if (ret != SOFTBUS_OK) {
682         TRANS_LOGE(TRANS_STREAM, "get laneHandle fail, streamStatsInfo cannot be processed");
683         return ret;
684     }
685     TRANS_LOGI(TRANS_STREAM, "transStreamStats channelId=%{public}d, laneHandle=0x%{public}x", channelId, laneHandle);
686     // modify with laneId
687     uint64_t laneId = INVALID_LANE_ID;
688     LaneIdStatsInfo info;
689     (void)memset_s(&info, sizeof(info), 0, sizeof(info));
690     info.laneId = laneId;
691     info.statsType = LANE_T_COMMON_VIDEO;
692     FrameSendStats *stats = &info.statsInfo.stream.frameStats;
693     ConvertStreamStats(data, stats);
694     LnnReportLaneIdStatsInfoPacked(&info, 1); /* only report stream stats */
695     return SOFTBUS_OK;
696 }
697 
TransRequestQos(int32_t channelId,int32_t chanType,int32_t appType,int32_t quality)698 int32_t TransRequestQos(int32_t channelId, int32_t chanType, int32_t appType, int32_t quality)
699 {
700     (void)chanType;
701     (void)appType;
702     uint32_t laneHandle;
703     int32_t ret = TransGetLaneHandleByChannelId(channelId, &laneHandle);
704     if (ret != SOFTBUS_OK) {
705         TRANS_LOGE(TRANS_QOS, "get laneHandle fail, transRequestQos cannot be processed");
706         return ret;
707     }
708     // modify with laneId
709     uint64_t laneId = INVALID_LANE_ID;
710     int32_t result = 0;
711     if (quality == QOS_IMPROVE) {
712         TRANS_LOGI(TRANS_QOS, "trans requestQos");
713         ret = LnnRequestQosOptimizationPacked(&laneId, 1, &result, 1);
714     } else if (quality == QOS_RECOVER) {
715         TRANS_LOGI(TRANS_QOS, "trans cancel Qos");
716         LnnCancelQosOptimizationPacked(&laneId, 1);
717         ret = SOFTBUS_OK;
718     } else {
719         TRANS_LOGE(TRANS_QOS, "requestQos invalid. quality=%{public}d", quality);
720         ret = SOFTBUS_TRANS_REQUEST_QOS_INVALID;
721     }
722 
723     if (ret != SOFTBUS_OK) {
724         TRANS_LOGE(TRANS_QOS, "request Qos fail, quality=%{public}d, ret=%{public}d", quality, ret);
725         return SOFTBUS_TRANS_REQUEST_QOS_FAILED;
726     }
727     return SOFTBUS_OK;
728 }
729 
TransRippleStats(int32_t channelId,int32_t channelType,const TrafficStats * data)730 int32_t TransRippleStats(int32_t channelId, int32_t channelType, const TrafficStats *data)
731 {
732     (void)channelType;
733     if (data == NULL) {
734         TRANS_LOGE(TRANS_CTRL, "rippleStats data is null");
735         return SOFTBUS_INVALID_PARAM;
736     }
737     uint32_t laneHandle;
738     int32_t ret = TransGetLaneHandleByChannelId(channelId, &laneHandle);
739     if (ret != SOFTBUS_OK) {
740         TRANS_LOGE(TRANS_CTRL, "get laneHandle fail, streamStatsInfo cannot be processed, ret=%{public}d", ret);
741         return ret;
742     }
743     TRANS_LOGI(TRANS_CTRL, "transRippleStats channelId=%{public}d, laneHandle=0x%{public}x", channelId, laneHandle);
744     LnnRippleData rptdata;
745     (void)memset_s(&rptdata, sizeof(rptdata), 0, sizeof(rptdata));
746     if (memcpy_s(&rptdata.stats, sizeof(rptdata.stats), data->stats, sizeof(data->stats)) != EOK) {
747         TRANS_LOGE(TRANS_CTRL, "memcpy fail");
748         return SOFTBUS_MEM_ERR;
749     }
750     // modify with laneId
751     uint64_t laneId = INVALID_LANE_ID;
752     LnnReportRippleDataPacked(laneId, &rptdata);
753     return SOFTBUS_OK;
754 }
755 
TransNotifyAuthSuccess(int32_t channelId,int32_t channelType)756 int32_t TransNotifyAuthSuccess(int32_t channelId, int32_t channelType)
757 {
758     int32_t ret = SOFTBUS_TRANS_INVALID_CHANNEL_TYPE;
759     ConnectOption connOpt;
760     switch (channelType) {
761         case CHANNEL_TYPE_AUTH:
762             ret = TransAuthGetConnOptionByChanId(channelId, &connOpt);
763             break;
764         case CHANNEL_TYPE_PROXY:
765             ret = TransProxyGetConnOptionByChanId(channelId, &connOpt);
766             break;
767         default:
768             ret = SOFTBUS_TRANS_INVALID_CHANNEL_TYPE;
769             TRANS_LOGE(TRANS_CTRL, "invalid. channelId=%{public}d, channelType=%{public}d.", channelId, channelType);
770     }
771     if (ret != SOFTBUS_OK) {
772         TRANS_LOGE(TRANS_CTRL,
773             "notfiy auth success. channelId=%{public}d, channelType=%{public}d, ret=%{public}d",
774             channelId, channelType, ret);
775         return ret;
776     }
777     return TransNotifyAuthDataSuccess(channelId, &connOpt);
778 }
779 
TransReleaseUdpResources(int32_t channelId)780 int32_t TransReleaseUdpResources(int32_t channelId)
781 {
782     TRANS_LOGI(TRANS_CTRL, "release Udp channel resources: channelId=%{public}d", channelId);
783     NotifyQosChannelClosedPacked(channelId, CHANNEL_TYPE_UDP);
784     (void)TransLaneMgrDelLane(channelId, CHANNEL_TYPE_UDP, false);
785     (void)TransDelUdpChannel(channelId);
786     return SOFTBUS_OK;
787 }
788 
TransCloseChannel(const char * sessionName,int32_t channelId,int32_t channelType)789 int32_t TransCloseChannel(const char *sessionName, int32_t channelId, int32_t channelType)
790 {
791     SoftBusHitraceChainBegin("TransCloseChannel");
792     int32_t ret = TransCommonCloseChannel(sessionName, channelId, channelType);
793     SoftBusHitraceChainEnd();
794     return ret;
795 }
796 
TransCloseChannelWithStatistics(int32_t channelId,int32_t channelType,uint64_t laneId,const void * dataInfo,uint32_t len)797 int32_t TransCloseChannelWithStatistics(int32_t channelId, int32_t channelType, uint64_t laneId,
798     const void *dataInfo, uint32_t len)
799 {
800     UpdateNetworkResourceByLaneId(channelId, channelType, laneId, dataInfo, len);
801     return SOFTBUS_OK;
802 }
803 
TransSendMsg(int32_t channelId,int32_t channelType,const void * data,uint32_t len,int32_t msgType)804 int32_t TransSendMsg(int32_t channelId, int32_t channelType, const void *data, uint32_t len,
805     int32_t msgType)
806 {
807     int32_t ret = SOFTBUS_OK;
808     switch (channelType) {
809         case CHANNEL_TYPE_AUTH:
810             TRANS_LOGI(TRANS_MSG,
811                 "send msg auth channelType. channelId=%{public}d, channelType=%{public}d", channelId, channelType);
812             ret = TransSendAuthMsg(channelId, (char*)data, (int32_t)len);
813             break;
814         case CHANNEL_TYPE_PROXY:
815             TRANS_LOGD(TRANS_MSG,
816                 "send msg proxy channelType. channelId=%{public}d, channelType=%{public}d", channelId, channelType);
817             ret = TransProxyPostSessionData(channelId, (unsigned char*)data, len, (SessionPktType)msgType);
818             break;
819         default:
820             TRANS_LOGE(TRANS_MSG,
821                 "send msg invalid channelType. channelId=%{public}d, channelType=%{public}d", channelId, channelType);
822             ret = SOFTBUS_TRANS_CHANNEL_TYPE_INVALID;
823             break;
824     }
825     return ret;
826 }
827 
TransChannelDeathCallback(const char * pkgName,int32_t pid)828 void TransChannelDeathCallback(const char *pkgName, int32_t pid)
829 {
830     TransProxyDeathCallback(pkgName, pid);
831     TransTdcDeathCallback(pkgName, pid);
832     TransTdcChannelInfoDeathCallback(pkgName, pid);
833     TransLaneMgrDeathCallback(pkgName, pid);
834     TransUdpDeathCallback(pkgName, pid);
835     TransAuthDeathCallback(pkgName, pid);
836 }
837 
TransGetNameByChanId(const TransInfo * info,char * pkgName,char * sessionName,uint16_t pkgLen,uint16_t sessionNameLen)838 int32_t TransGetNameByChanId(const TransInfo *info, char *pkgName, char *sessionName,
839     uint16_t pkgLen, uint16_t sessionNameLen)
840 {
841     if (info == NULL || pkgName == NULL || sessionName == NULL) {
842         TRANS_LOGE(TRANS_CTRL, "invalid param");
843         return SOFTBUS_INVALID_PARAM;
844     }
845     switch ((ChannelType)info->channelType) {
846         case CHANNEL_TYPE_PROXY:
847             return TransProxyGetNameByChanId(info->channelId, pkgName, sessionName, pkgLen, sessionNameLen);
848         case CHANNEL_TYPE_UDP:
849             return TransUdpGetNameByChanId(info->channelId, pkgName, sessionName, pkgLen, sessionNameLen);
850         case CHANNEL_TYPE_AUTH:
851             return TransAuthGetNameByChanId(info->channelId, pkgName, sessionName, pkgLen, sessionNameLen);
852         default:
853             return SOFTBUS_INVALID_PARAM;
854     }
855 }
856 
TransGetAndComparePid(pid_t pid,int32_t channelId,int32_t channelType)857 int32_t TransGetAndComparePid(pid_t pid, int32_t channelId, int32_t channelType)
858 {
859     int32_t curChannelPid = 0;
860     int32_t ret = SOFTBUS_OK;
861     AppInfo appInfo;
862     ret = TransGetAppInfoByChanId(channelId, channelType, &appInfo);
863     (void)memset_s(appInfo.sessionKey, sizeof(appInfo.sessionKey), 0, sizeof(appInfo.sessionKey));
864     if (ret != SOFTBUS_OK && (ChannelType)channelType == CHANNEL_TYPE_TCP_DIRECT) {
865         ret = TransGetPidByChanId(channelId, channelType, &curChannelPid);
866     }
867     if (ret != SOFTBUS_OK) {
868         TRANS_LOGE(TRANS_CTRL, "get appInfo by channelId failed, channelId=%{public}d, ret=%{public}d",
869             channelId, ret);
870         return ret;
871     }
872     if (curChannelPid == 0) {
873         curChannelPid = appInfo.myData.pid;
874     }
875     if (pid != (pid_t)curChannelPid) {
876         TRANS_LOGE(TRANS_CTRL, "callingPid=%{public}d not equal curChannelPid=%{public}d", pid, curChannelPid);
877         return SOFTBUS_TRANS_CHECK_PID_ERROR;
878     }
879     return SOFTBUS_OK;
880 }
881 
TransGetAndComparePidBySession(pid_t pid,const char * sessionName,int32_t sessionlId)882 int32_t TransGetAndComparePidBySession(pid_t pid, const char *sessionName, int32_t sessionlId)
883 {
884     pid_t curSessionPid;
885     int32_t ret = TransGetPidFromSocketChannelInfoBySession(sessionName, sessionlId, &curSessionPid);
886     if (ret != SOFTBUS_OK) {
887         TRANS_LOGE(TRANS_CTRL, "get pid by session failed, ret=%{public}d", ret);
888         return ret;
889     }
890     if (pid != curSessionPid) {
891         TRANS_LOGE(TRANS_CTRL, "callingPid=%{public}d not equal curSessionPid=%{public}d", pid, curSessionPid);
892         return SOFTBUS_TRANS_CHECK_PID_ERROR;
893     }
894     return SOFTBUS_OK;
895 }
896 
TransGetAppInfoByChanId(int32_t channelId,int32_t channelType,AppInfo * appInfo)897 int32_t TransGetAppInfoByChanId(int32_t channelId, int32_t channelType, AppInfo* appInfo)
898 {
899     if (appInfo == NULL) {
900         return SOFTBUS_INVALID_PARAM;
901     }
902     switch ((ChannelType)channelType) {
903         case CHANNEL_TYPE_TCP_DIRECT:
904             return TcpTranGetAppInfobyChannelId(channelId, appInfo);
905         case CHANNEL_TYPE_PROXY:
906             return TransProxyGetAppInfoByChanId(channelId, appInfo);
907         case CHANNEL_TYPE_UDP:
908             return TransGetUdpAppInfoByChannelId(channelId, appInfo);
909         case CHANNEL_TYPE_AUTH:
910             return TransAuthGetAppInfoByChanId(channelId, appInfo);
911         default:
912             return SOFTBUS_INVALID_PARAM;
913     }
914 }
915 
TransGetConnByChanId(int32_t channelId,int32_t channelType,int32_t * connId)916 int32_t TransGetConnByChanId(int32_t channelId, int32_t channelType, int32_t* connId)
917 {
918     int32_t ret;
919 
920     switch (channelType) {
921         case CHANNEL_TYPE_PROXY:
922             ret = TransProxyGetConnIdByChanId(channelId, connId);
923             break;
924         case CHANNEL_TYPE_AUTH:
925             ret = TransAuthGetConnIdByChanId(channelId, connId);
926             break;
927         default:
928             TRANS_LOGE(TRANS_CTRL, "channelType=%{public}d error", channelType);
929             ret = SOFTBUS_TRANS_INVALID_CHANNEL_TYPE;
930     }
931     if (ret != SOFTBUS_OK) {
932         TRANS_LOGE(TRANS_MSG, "get connId failed, channelId=%{public}d, channelType=%{public}d",
933             channelId, channelType);
934     }
935 
936     return ret;
937 }
938 
CheckAuthChannelIsExit(ConnectOption * connInfo)939 int32_t CheckAuthChannelIsExit(ConnectOption *connInfo)
940 {
941     if (connInfo == NULL) {
942         TRANS_LOGE(TRANS_CTRL, "invalid param");
943         return SOFTBUS_INVALID_PARAM;
944     }
945 
946     int32_t ret = SOFTBUS_TRANS_NOT_MATCH;
947     if (connInfo->type == CONNECT_TCP) {
948         ret = CheckIsWifiAuthChannel(connInfo);
949     } else if (connInfo->type == CONNECT_BR || connInfo->type == CONNECT_BLE) {
950         ret = CheckIsProxyAuthChannel(connInfo);
951     }
952     TRANS_LOGW(TRANS_CTRL, "connInfo type=%{public}d, ret=%{public}d", connInfo->type, ret);
953     return ret;
954 }
955 
ReadAccessInfo(uint8_t * buf,uint32_t len,int32_t * offset,AccessInfo * accessInfo)956 static int32_t ReadAccessInfo(uint8_t *buf, uint32_t len, int32_t *offset, AccessInfo *accessInfo)
957 {
958     int32_t ret = ReadInt32FromBuf(buf, len, offset, &accessInfo->userId);
959     if (ret != SOFTBUS_OK) {
960         TRANS_LOGE(TRANS_CTRL, "get userId from buf failed.");
961         return ret;
962     }
963     ret = ReadUint64FromBuf(buf, len, offset, &accessInfo->localTokenId);
964     if (ret != SOFTBUS_OK) {
965         TRANS_LOGE(TRANS_CTRL, "get tokenId from buf failed.");
966         return ret;
967     }
968     return SOFTBUS_OK;
969 }
970 
GetChannelInfoFromBuf(uint8_t * buf,uint32_t len,OpenChannelResult * info,AccessInfo * accessInfo)971 static int32_t GetChannelInfoFromBuf(
972     uint8_t *buf, uint32_t len, OpenChannelResult *info, AccessInfo *accessInfo)
973 {
974     int32_t offSet = 0;
975     int32_t ret = SOFTBUS_OK;
976     ret = ReadInt32FromBuf(buf, len, &offSet, &info->channelId);
977     if (ret != SOFTBUS_OK) {
978         TRANS_LOGE(TRANS_CTRL, "get channelId from buf failed!");
979         return ret;
980     }
981     ret = ReadInt32FromBuf(buf, len, &offSet, &info->channelType);
982     if (ret != SOFTBUS_OK) {
983         TRANS_LOGE(TRANS_CTRL, "get channelId from buf failed!");
984         return ret;
985     }
986     ret = ReadInt32FromBuf(buf, len, &offSet, &info->openResult);
987     if (ret != SOFTBUS_OK) {
988         TRANS_LOGE(TRANS_CTRL, "get openResult from buf failed!");
989         return ret;
990     }
991     if (info->channelType != CHANNEL_TYPE_AUTH) {
992         ret = ReadAccessInfo(buf, len, &offSet, accessInfo);
993         if (ret != SOFTBUS_OK) {
994             TRANS_LOGE(TRANS_CTRL, "get access info from buf failed!");
995             return ret;
996         }
997     }
998     return ret;
999 }
1000 
GetUdpChannelInfoFromBuf(uint8_t * buf,uint32_t len,int32_t * udpPort,OpenChannelResult * info,AccessInfo * accessInfo)1001 static int32_t GetUdpChannelInfoFromBuf(
1002     uint8_t *buf, uint32_t len, int32_t *udpPort, OpenChannelResult *info, AccessInfo *accessInfo)
1003 {
1004     int32_t offSet = 0;
1005     int32_t ret = SOFTBUS_OK;
1006     ret = ReadInt32FromBuf(buf, len, &offSet, &info->channelId);
1007     if (ret != SOFTBUS_OK) {
1008         TRANS_LOGE(TRANS_CTRL, "get channelId from buf failed!");
1009         return ret;
1010     }
1011     ret = ReadInt32FromBuf(buf, len, &offSet, &info->channelType);
1012     if (ret != SOFTBUS_OK) {
1013         TRANS_LOGE(TRANS_CTRL, "get channelId from buf failed!");
1014         return ret;
1015     }
1016     ret = ReadInt32FromBuf(buf, len, &offSet, &info->openResult);
1017     if (ret != SOFTBUS_OK) {
1018         TRANS_LOGE(TRANS_CTRL, "get openResult from buf failed!");
1019         return ret;
1020     }
1021     ret = ReadInt32FromBuf(buf, len, &offSet, udpPort);
1022     if (ret != SOFTBUS_OK) {
1023         TRANS_LOGE(TRANS_CTRL, "get udpPort from buf failed!");
1024         return ret;
1025     }
1026     if (info->channelType != CHANNEL_TYPE_AUTH) {
1027         ret = ReadAccessInfo(buf, len, &offSet, accessInfo);
1028         if (ret != SOFTBUS_OK) {
1029             TRANS_LOGE(TRANS_CTRL, "get access info from buf failed!");
1030             return ret;
1031         }
1032     }
1033     return ret;
1034 }
1035 
GetLimitChangeInfoFromBuf(uint8_t * buf,int32_t * channelId,uint8_t * tos,int32_t * limitChangeResult,uint32_t len)1036 static int32_t GetLimitChangeInfoFromBuf(
1037     uint8_t *buf, int32_t *channelId, uint8_t *tos, int32_t *limitChangeResult, uint32_t len)
1038 {
1039     int32_t offSet = 0;
1040     int32_t ret = SOFTBUS_OK;
1041     ret = ReadInt32FromBuf(buf, len, &offSet, channelId);
1042     if (ret != SOFTBUS_OK) {
1043         TRANS_LOGE(TRANS_CTRL, "get channelId from buf failed!");
1044         return ret;
1045     }
1046     ret = ReadUint8FromBuf(buf, len, &offSet, tos);
1047     if (ret != SOFTBUS_OK) {
1048         TRANS_LOGE(TRANS_CTRL, "get tos from buf failed!");
1049         return ret;
1050     }
1051     ret = ReadInt32FromBuf(buf, len, &offSet, limitChangeResult);
1052     if (ret != SOFTBUS_OK) {
1053         TRANS_LOGE(TRANS_CTRL, "get limitChangeResult from buf failed!");
1054         return ret;
1055     }
1056     return ret;
1057 }
1058 
TransReportChannelOpenedInfo(uint8_t * buf,uint32_t len,pid_t callingPid)1059 static int32_t TransReportChannelOpenedInfo(uint8_t *buf, uint32_t len, pid_t callingPid)
1060 {
1061     OpenChannelResult info = { 0 };
1062     AccessInfo accessInfo = { 0 };
1063     int32_t udpPort = 0;
1064     int32_t ret = SOFTBUS_OK;
1065     if (len == sizeof(int32_t) * REPORT_UDP_INFO_SIZE ||
1066         len == sizeof(int32_t) * (REPORT_UDP_INFO_SIZE + ACCESS_INFO_PARAM_NUM)) {
1067         ret = GetUdpChannelInfoFromBuf(buf, len, &udpPort, &info, &accessInfo);
1068     } else {
1069         ret = GetChannelInfoFromBuf(buf, len, &info, &accessInfo);
1070     }
1071     if (ret != SOFTBUS_OK) {
1072         return ret;
1073     }
1074     switch (info.channelType) {
1075         case CHANNEL_TYPE_PROXY:
1076             ret = TransDealProxyChannelOpenResult(info.channelId, info.openResult, &accessInfo, callingPid);
1077             break;
1078         case CHANNEL_TYPE_TCP_DIRECT:
1079             ret = TransDealTdcChannelOpenResult(info.channelId, info.openResult, &accessInfo, callingPid);
1080             break;
1081         case CHANNEL_TYPE_UDP:
1082             ret = TransDealUdpChannelOpenResult(info.channelId, info.openResult, udpPort, &accessInfo, callingPid);
1083             break;
1084         case CHANNEL_TYPE_AUTH:
1085             ret = TransDealAuthChannelOpenResult(info.channelId, info.openResult, callingPid);
1086             break;
1087         default:
1088             TRANS_LOGE(TRANS_CTRL, "channelType=%{public}d is error", info.channelType);
1089             ret = SOFTBUS_TRANS_INVALID_CHANNEL_TYPE;
1090     }
1091     if (ret != SOFTBUS_OK) {
1092         TRANS_LOGE(TRANS_CTRL, "report Event channel opened info failed");
1093     }
1094     return ret;
1095 }
1096 
TransReportLimitChangeInfo(uint8_t * buf,uint32_t len,pid_t callingPid)1097 static void TransReportLimitChangeInfo(uint8_t *buf, uint32_t len, pid_t callingPid)
1098 {
1099     int32_t channelId = 0;
1100     uint8_t tos = 0;
1101     int32_t limitChangeResult = 0;
1102     int32_t ret = SOFTBUS_OK;
1103     ret = GetLimitChangeInfoFromBuf(buf, &channelId, &tos, &limitChangeResult, len);
1104     if (ret != SOFTBUS_OK) {
1105         TRANS_LOGE(TRANS_CTRL, "GetLimitChangeInfoFromBuf failed, ret=%{public}d", ret);
1106     }
1107     if (limitChangeResult != SOFTBUS_OK) {
1108         TRANS_LOGE(TRANS_CTRL, "limitChangeResult is failed, limitChangeResult=%{public}d", limitChangeResult);
1109     }
1110     ret = TransSetTos(channelId, tos, callingPid);
1111     if (ret != SOFTBUS_OK) {
1112         TRANS_LOGE(TRANS_CTRL, "Set limit change event failed, ret=%{public}d", ret);
1113     }
1114 }
1115 
GetCollabCheckResultFromBuf(uint8_t * buf,int32_t * channelId,int32_t * channelType,int32_t * checkResult,uint32_t len)1116 static int32_t GetCollabCheckResultFromBuf(uint8_t *buf,
1117     int32_t *channelId, int32_t *channelType, int32_t *checkResult, uint32_t len)
1118 {
1119     int32_t offset = 0;
1120     int32_t ret = ReadInt32FromBuf(buf, len, &offset, channelId);
1121     if (ret != SOFTBUS_OK) {
1122         TRANS_LOGE(TRANS_CTRL, "get channelId from buf failed.");
1123         return ret;
1124     }
1125     ret = ReadInt32FromBuf(buf, len, &offset, channelType);
1126     if (ret != SOFTBUS_OK) {
1127         TRANS_LOGE(TRANS_CTRL, "get channelType from buf failed.");
1128         return ret;
1129     }
1130     ret = ReadInt32FromBuf(buf, len, &offset, checkResult);
1131     if (ret != SOFTBUS_OK) {
1132         TRANS_LOGE(TRANS_CTRL, "get checkResult from buf failed.");
1133         return ret;
1134     }
1135     return ret;
1136 }
1137 
TransReportCheckCollabInfo(uint8_t * buf,uint32_t len,pid_t callingPid)1138 static int32_t TransReportCheckCollabInfo(uint8_t *buf, uint32_t len, pid_t callingPid)
1139 {
1140     int32_t channelId = 0;
1141     int32_t channelType = 0;
1142     int32_t checkResult = 0;
1143     int32_t ret = GetCollabCheckResultFromBuf(buf, &channelId, &channelType, &checkResult, len);
1144     if (ret != SOFTBUS_OK) {
1145         return ret;
1146     }
1147     switch (channelType) {
1148         case CHANNEL_TYPE_PROXY:
1149             ret = TransDealProxyCheckCollabResult(channelId, checkResult, callingPid);
1150             break;
1151         case CHANNEL_TYPE_TCP_DIRECT:
1152             ret = TransDealTdcCheckCollabResult(channelId, checkResult, callingPid);
1153             break;
1154         case CHANNEL_TYPE_UDP:
1155             ret = TransDealUdpCheckCollabResult(channelId, checkResult, callingPid);
1156             break;
1157         default:
1158             TRANS_LOGE(TRANS_CTRL, "channelType=%{public}d is error.", channelType);
1159             ret = SOFTBUS_TRANS_INVALID_CHANNEL_TYPE;
1160     }
1161     return ret;
1162 }
1163 
TransSetAccessInfo(uint8_t * buf,uint32_t len,pid_t callingPid)1164 static int32_t TransSetAccessInfo(uint8_t *buf, uint32_t len, pid_t callingPid)
1165 {
1166     char sessionName[SESSION_NAME_SIZE_MAX] = { 0 };
1167     char extraAccessInfo[EXTRA_ACCESS_INFO_LEN_MAX] = { 0 };
1168     int32_t offset = 0;
1169     int32_t userId = -1;
1170     uint64_t tokenId = 0;
1171     int32_t ret = ReadInt32FromBuf(buf, len, &offset, &userId);
1172     if (ret != SOFTBUS_OK) {
1173         TRANS_LOGE(TRANS_CTRL, "get userId from buf failed.");
1174         return ret;
1175     }
1176     ret = ReadUint64FromBuf(buf, len, &offset, &tokenId);
1177     if (ret != SOFTBUS_OK) {
1178         TRANS_LOGE(TRANS_CTRL, "get tokenId from buf failed.");
1179         return ret;
1180     }
1181     ret = ReadStringFromBuf(buf, len, &offset, sessionName, SESSION_NAME_SIZE_MAX);
1182     if (ret != SOFTBUS_OK) {
1183         TRANS_LOGE(TRANS_CTRL, "get sessionName from buf failed.");
1184         return ret;
1185     }
1186     ret = ReadStringFromBuf(buf, len, &offset, extraAccessInfo, EXTRA_ACCESS_INFO_LEN_MAX);
1187     if (ret != SOFTBUS_OK) {
1188         TRANS_LOGE(TRANS_CTRL, "get extraInfo from buf failed.");
1189         return ret;
1190     }
1191     AccessInfo accessInfo = {
1192         .userId = userId,
1193         .localTokenId = tokenId,
1194         .extraAccessInfo = extraAccessInfo,
1195     };
1196     ret = AddAccessInfoBySessionName(sessionName, &accessInfo, callingPid);
1197     if (ret != SOFTBUS_OK) {
1198         TRANS_LOGE(TRANS_CTRL, "add accessInfo by sessionName failed.");
1199     }
1200     return ret;
1201 }
1202 
TransProcessInnerEvent(int32_t eventType,uint8_t * buf,uint32_t len)1203 int32_t TransProcessInnerEvent(int32_t eventType, uint8_t *buf, uint32_t len)
1204 {
1205     SoftBusHitraceChainBegin("TransProcessInnerEvent");
1206     if (buf == NULL) {
1207         TRANS_LOGE(TRANS_CTRL, "process inner event buf is null");
1208         SoftBusHitraceChainEnd();
1209         return SOFTBUS_INVALID_PARAM;
1210     }
1211 
1212     pid_t callingPid = TransGetCallingPid();
1213     int32_t ret = SOFTBUS_OK;
1214     switch (eventType) {
1215         case EVENT_TYPE_CHANNEL_OPENED:
1216             ret = TransReportChannelOpenedInfo(buf, len, callingPid);
1217             break;
1218         case EVENT_TYPE_TRANS_LIMIT_CHANGE:
1219             TransReportLimitChangeInfo(buf, len, callingPid);
1220             break;
1221         case EVENT_TYPE_COLLAB_CHECK:
1222             ret = TransReportCheckCollabInfo(buf, len, callingPid);
1223             break;
1224         case EVENT_TYPE_SET_ACCESS_INFO:
1225             ret = TransSetAccessInfo(buf, len, callingPid);
1226             break;
1227         default:
1228             TRANS_LOGE(TRANS_CTRL, "eventType=%{public}d error", eventType);
1229             ret = SOFTBUS_TRANS_MSG_INVALID_EVENT_TYPE;
1230     }
1231     if (ret != SOFTBUS_OK) {
1232         TRANS_LOGE(TRANS_CTRL, "report event failed, eventType=%{public}d", eventType);
1233     }
1234     SoftBusHitraceChainEnd();
1235     return ret;
1236 }
1237 
TransPrivilegeCloseChannel(uint64_t tokenId,int32_t pid,const char * peerNetworkId)1238 int32_t TransPrivilegeCloseChannel(uint64_t tokenId, int32_t pid, const char *peerNetworkId)
1239 {
1240 #define PRIVILEGE_CLOSE_OFFSET 11
1241     if (peerNetworkId == NULL) {
1242         TRANS_LOGE(TRANS_CTRL, "invalid param");
1243         return SOFTBUS_INVALID_PARAM;
1244     }
1245     ListNode privilegeCloseList;
1246     ListInit(&privilegeCloseList);
1247     (void)TransTcpGetPrivilegeCloseList(&privilegeCloseList, tokenId, pid);
1248     (void)TransProxyGetPrivilegeCloseList(&privilegeCloseList, tokenId, pid);
1249     (void)TransUdpGetPrivilegeCloseList(&privilegeCloseList, tokenId, pid);
1250     LinkDownInfo info = {
1251         .uuid = "",
1252         .udid = "",
1253         .peerIp = "",
1254         .networkId = peerNetworkId,
1255         .routeType = ROUTE_TYPE_ALL | 1 << PRIVILEGE_CLOSE_OFFSET,
1256     };
1257     PrivilegeCloseChannelInfo *pos = NULL;
1258     PrivilegeCloseChannelInfo *tmp = NULL;
1259     LIST_FOR_EACH_ENTRY_SAFE(pos, tmp, &privilegeCloseList, PrivilegeCloseChannelInfo, node) {
1260         (void)TransServerOnChannelLinkDown(pos->pkgName, pos->pid, &info);
1261         ListDelete(&(pos->node));
1262         SoftBusFree(pos);
1263     }
1264     return SOFTBUS_OK;
1265 }
1266 
PrivilegeCloseListAddItem(ListNode * privilegeCloseList,int32_t pid,const char * pkgName)1267 int32_t PrivilegeCloseListAddItem(ListNode *privilegeCloseList, int32_t pid, const char *pkgName)
1268 {
1269     if (privilegeCloseList == NULL || pkgName == NULL) {
1270         TRANS_LOGE(TRANS_CTRL, "invalid param");
1271         return SOFTBUS_INVALID_PARAM;
1272     }
1273     PrivilegeCloseChannelInfo *exitItem = NULL;
1274     LIST_FOR_EACH_ENTRY(exitItem, privilegeCloseList, PrivilegeCloseChannelInfo, node) {
1275         if (strcmp(exitItem->pkgName, pkgName) == 0 && exitItem->pid == pid) {
1276             return SOFTBUS_OK;
1277         }
1278     }
1279     PrivilegeCloseChannelInfo *item = (PrivilegeCloseChannelInfo *)SoftBusCalloc(sizeof(PrivilegeCloseChannelInfo));
1280     TRANS_CHECK_AND_RETURN_RET_LOGE(item != NULL, SOFTBUS_MALLOC_ERR, TRANS_CTRL, "calloc failed");
1281     if (strcpy_s(item->pkgName, PKG_NAME_SIZE_MAX, pkgName) != EOK) {
1282         SoftBusFree(item);
1283         return SOFTBUS_STRCPY_ERR;
1284     }
1285     item->pid = pid;
1286     ListInit(&(item->node));
1287     ListAdd(privilegeCloseList, &(item->node));
1288     TRANS_LOGI(TRANS_CTRL, "add success, pkgName=%{public}s, pid=%{public}d", pkgName, pid);
1289     return SOFTBUS_OK;
1290 }