• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 <sys/prctl.h>
17 
18 #include "br_connection_manager.h"
19 #include "br_connection_queue.h"
20 #include "br_pending_packet.h"
21 #include "br_trans_manager.h"
22 #include "common_list.h"
23 #include "message_handler.h"
24 #include "securec.h"
25 #include "softbus_hisysevt_connreporter.h"
26 #include "softbus_adapter_mem.h"
27 #include "softbus_adapter_timer.h"
28 #include "softbus_conn_manager.h"
29 #include "softbus_def.h"
30 #include "softbus_errcode.h"
31 #include "softbus_feature_config.h"
32 #include "softbus_json_utils.h"
33 #include "softbus_log.h"
34 #include "softbus_type_def.h"
35 #include "softbus_utils.h"
36 #include "stdbool.h"
37 #include "string.h"
38 #include "time.h"
39 #include "unistd.h"
40 #include "wrapper_br_interface.h"
41 
42 
43 #define DISCONN_DELAY_TIME 200
44 #define BR_ACCEPET_WAIT_TIME 1000
45 #define CONNECT_REF_INCRESE 1
46 #define CONNECT_REF_DECRESE (-1)
47 #define BR_SEND_THREAD_STACK 5120
48 #define BR_RECE_THREAD_STACK 4096
49 #define MAX_BR_SIZE (40 * 1000)
50 #define MAX_BR_PEER_SIZE (3*1024)
51 #define INVALID_LENGTH (-1)
52 #define INVALID_SOCKET (-1)
53 #define WINDOWS_ACK_FAILED_TIMES 3
54 #define WAIT_ACK_TIMES 100
55 
56 #define BR_SERVER_NAME_LEN 24
57 #define UUID "8ce255c0-200a-11e0-ac64-0800200c9a66"
58 
59 #define BR_CLOSE_TIMEOUT (5 * 1000)
60 
61 static pthread_mutex_t g_brConnLock;
62 static int32_t g_brMaxConnCount;
63 
64 static SoftBusHandler g_brAsyncHandler = {
65     .name = (char *)"g_brAsyncHandler"
66 };
67 
68 static int32_t ConnectDevice(const ConnectOption *option, uint32_t requestId, const ConnectResult *result);
69 
70 static int32_t DisconnectDevice(uint32_t connectionId);
71 
72 static int32_t DisconnectDeviceNow(const ConnectOption *option);
73 
74 static int32_t StartLocalListening(const LocalListenerInfo *info);
75 
76 static int32_t StopLocalListening(const LocalListenerInfo *info);
77 
78 static int32_t PostBytes(uint32_t connectionId, const char *data, int32_t len, int32_t pid, int32_t flag);
79 
80 static ConnectFuncInterface g_brInterface = {
81     .ConnectDevice = ConnectDevice,
82     .PostBytes = PostBytes,
83     .DisconnectDevice = DisconnectDevice,
84     .DisconnectDeviceNow = DisconnectDeviceNow,
85     .GetConnectionInfo = GetConnectionInfo,
86     .StartLocalListening = StartLocalListening,
87     .StopLocalListening = StopLocalListening,
88     .CheckActiveConnection = BrCheckActiveConnection,
89     .UpdateConnection = NULL,
90 };
91 
92 static SppSocketDriver *g_sppDriver = NULL;
93 static ConnectCallback *g_connectCallback = NULL;
94 
95 static int32_t g_brBuffSize;
96 static int32_t g_brSendPeerLen;
97 static int32_t g_brSendQueueMaxLen;
98 
99 static SoftBusBtStateListener g_sppBrCallback;
100 static bool g_startListenFlag = false;
101 static int32_t g_brEnable = SOFTBUS_BR_STATE_TURN_OFF;
102 
BrFreeMessage(SoftBusMessage * msg)103 static void BrFreeMessage(SoftBusMessage *msg)
104 {
105     if (msg->obj != NULL) {
106         SoftBusFree(msg->obj);
107     }
108     SoftBusFree((void *)msg);
109 }
110 
BrConnCreateLoopMsg(BrConnLoopMsgType what,uint64_t arg1,uint64_t arg2,const char * data)111 static SoftBusMessage *BrConnCreateLoopMsg(BrConnLoopMsgType what, uint64_t arg1, uint64_t arg2, const char *data)
112 {
113     SoftBusMessage *msg = NULL;
114     msg = (SoftBusMessage *)SoftBusCalloc(sizeof(SoftBusMessage));
115     if (msg == NULL) {
116         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrConnCreateLoopMsg SoftBusCalloc failed");
117         return NULL;
118     }
119     msg->what = what;
120     msg->arg1 = arg1;
121     msg->arg2 = arg2;
122     msg->handler = &g_brAsyncHandler;
123     msg->FreeMessage = BrFreeMessage;
124     msg->obj = (void *)data;
125     return msg;
126 }
127 
PostBytesInnerListener(uint32_t connId,uint64_t seq,int32_t module,int32_t result)128 static void PostBytesInnerListener(uint32_t connId, uint64_t seq, int32_t module, int32_t result)
129 {
130     if (result != SOFTBUS_OK) {
131         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR,
132             "PostInner failed, connId:%u, seq:%" PRIu64 ", module:%d, result:%d", connId, seq, module, result);
133     } else {
134         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "PostInner success, connId:%u, seq:%" PRIu64 ", module:%d",
135             connId, seq, module);
136     }
137 }
138 
PostBytesInner(uint32_t connectionId,int32_t module,const char * data,uint32_t len)139 static int32_t PostBytesInner(uint32_t connectionId, int32_t module, const char *data, uint32_t len)
140 {
141     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
142         "PostBytesInner connectionId=%u,len=%u,module=%d", connectionId, len, module);
143 
144     // control message need be sent when closing
145     int32_t state = GetBrConnStateByConnectionId(connectionId);
146     if (state != BR_CONNECTION_STATE_CLOSING && state != BR_CONNECTION_STATE_CONNECTED) {
147         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "connectionId(%u) device is not ready, state: %d",
148             connectionId, state);
149         SoftBusFree((void *)data);
150         return SOFTBUS_BRCONNECTION_POSTBYTES_ERROR;
151     }
152 
153     SendBrQueueNode *node = (SendBrQueueNode *)SoftBusCalloc(sizeof(SendBrQueueNode));
154     if (node == NULL) {
155         SoftBusFree((void *)data);
156         return SOFTBUS_MALLOC_ERR;
157     }
158     node->connectionId = connectionId;
159     node->len = len;
160     node->data = data;
161     node->module = module;
162     node->isInner = true;
163     node->pid = 0;
164     node->flag = CONN_HIGH;
165     node->listener = PostBytesInnerListener;
166     int32_t ret = BrEnqueueNonBlock((const void *)node);
167     if (ret != SOFTBUS_OK) {
168         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Br PostBytesInner enqueue failed, ret: %d", ret);
169         SoftBusFree((void *)data);
170         SoftBusFree(node);
171         return ret;
172     }
173     return SOFTBUS_OK;
174 }
175 
PostClosingTimeoutEvent(uint32_t connectionId)176 static int32_t PostClosingTimeoutEvent(uint32_t connectionId)
177 {
178     SoftBusMessage *msg = BrConnCreateLoopMsg(ADD_CONN_BR_CLOSING_TIMEOUT_MSG, (uint64_t)connectionId, 0, NULL);
179     if (msg == NULL) {
180         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[PostClosingTimeoutEvent] BrConnCreateLoopMsg failed, "
181         "connection id: %u", connectionId);
182         return SOFTBUS_ERR;
183     }
184     g_brAsyncHandler.looper->PostMessageDelay(g_brAsyncHandler.looper, msg, BR_CLOSE_TIMEOUT);
185     return SOFTBUS_OK;
186 }
187 
PackRequest(int32_t delta,uint32_t connectionId)188 static void PackRequest(int32_t delta, uint32_t connectionId)
189 {
190     int32_t refCount = -1;
191     int32_t state = SetRefCountByConnId(delta, &refCount, connectionId);
192     if (state != BR_CONNECTION_STATE_CONNECTED && state != BR_CONNECTION_STATE_CLOSING) {
193         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br connection %u not connected ever!", connectionId);
194         return;
195     }
196 
197     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
198         "br pack request: delta:%d, ref:%d, connectionId:%u, state:%d", delta, refCount, connectionId, state);
199 
200     if (state == BR_CONNECTION_STATE_CLOSING) {
201         int32_t ret = PostClosingTimeoutEvent(connectionId);
202         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "post close %u connection timeout event, ret: %d",
203             connectionId, ret);
204         // continue, anyway
205     }
206 
207     int32_t dataLen = 0;
208     char *buf = BrPackRequestOrResponse(METHOD_NOTIFY_REQUEST, delta, refCount, &dataLen);
209     if (buf != NULL) {
210         (void)PostBytesInner(connectionId, METHOD_NOTIFY_REQUEST, buf, dataLen);
211     }
212 }
213 
DeviceConnectPackRequest(int32_t value,uint32_t connectionId)214 static void DeviceConnectPackRequest(int32_t value, uint32_t connectionId)
215 {
216     int32_t data = value;
217     while (--data > 0) {
218         (void)PackRequest(CONNECT_REF_INCRESE, connectionId);
219     }
220 }
221 
ClientOnBrConnectDevice(int32_t connId,int32_t * outSocketFd)222 static int32_t ClientOnBrConnectDevice(int32_t connId, int32_t *outSocketFd)
223 {
224     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "sppDriver connect start, connId:%d", connId);
225     BrConnectionInfo *brConn = GetConnectionRef(connId);
226     if (brConn == NULL) {
227         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BrClient not find connInfo.");
228         return SOFTBUS_BRCONNECTION_GETCONNINFO_ERROR;
229     }
230     if (brConn->sideType != BR_CLIENT_TYPE) {
231         ReleaseConnectionRef(brConn);
232         return SOFTBUS_INVALID_PARAM;
233     }
234     uint8_t btAddr[BT_ADDR_LEN];
235     if (ConvertBtMacToBinary(brConn->mac, BT_MAC_LEN, btAddr, BT_ADDR_LEN) != SOFTBUS_OK) {
236         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "convert bt mac to binary fail.");
237         ReleaseConnectionRef(brConn);
238         return SOFTBUS_ERR;
239     }
240     int32_t socketFd = SOFTBUS_ERR;
241     if (g_sppDriver != NULL) {
242         socketFd = g_sppDriver->Connect(UUID, btAddr);
243     }
244     if (socketFd == SOFTBUS_ERR) {
245         ReleaseConnectionRef(brConn);
246         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "sppDriver connect failed, connId:%d", connId);
247         return SOFTBUS_BRCONNECTION_CONNECTDEVICE_GETSOCKETIDFAIL;
248     }
249     brConn->socketFd = socketFd;
250     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br connection ok, Id=%d, socket=%d", connId, socketFd);
251     if (g_sppDriver->IsConnected(socketFd)) {
252         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "sppDriver IsConnected true.");
253     }
254     if (brConn->state == BR_CONNECTION_STATE_CLOSED || brConn->state == BR_CONNECTION_STATE_CLOSING) {
255         g_sppDriver->DisConnect(socketFd);
256         ReleaseConnectionRef(brConn);
257         return SOFTBUS_ERR;
258     }
259     brConn->state = BR_CONNECTION_STATE_CONNECTED;
260     *outSocketFd = socketFd;
261     ReleaseConnectionRef(brConn);
262     return SOFTBUS_OK;
263 }
264 
ClientNoticeResultBrConnect(uint32_t connId,bool result,int32_t value)265 static void ClientNoticeResultBrConnect(uint32_t connId, bool result, int32_t value)
266 {
267     ListNode notifyList;
268     ListInit(&notifyList);
269     ListNode *item = NULL;
270     ListNode *itemNext = NULL;
271     RequestInfo *requestInfo = NULL;
272     ConnectionInfo connectionInfo;
273     if (!result) {
274         SetBrConnStateByConnId(connId, BR_CONNECTION_STATE_CLOSING);
275     }
276     int32_t sideType = BR_CLIENT_TYPE;
277     int32_t packRequestFlag = GetBrRequestListByConnId(connId, &notifyList, &connectionInfo, &sideType);
278     if (packRequestFlag != 0) {
279         if (result) {
280             connectionInfo.isAvailable = 1;
281             DeviceConnectPackRequest(packRequestFlag, connId);
282         }
283         LIST_FOR_EACH_SAFE(item, itemNext, &notifyList) {
284             requestInfo = LIST_ENTRY(item, RequestInfo, node);
285             if (result) {
286                 if (requestInfo->callback.OnConnectSuccessed != NULL) {
287                     requestInfo->callback.OnConnectSuccessed(requestInfo->requestId, connId, &connectionInfo);
288                 }
289             } else {
290                 if (requestInfo->callback.OnConnectFailed != NULL) {
291                     requestInfo->callback.OnConnectFailed(requestInfo->requestId, value);
292                 }
293             }
294             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
295                 "connnect notify, result:%d, connectionId:%u, requestId:%u", result, connId, requestInfo->requestId);
296             ListDelete(&requestInfo->node);
297             SoftBusFree(requestInfo);
298         }
299     }
300 }
301 
ClientOnBrConnect(int32_t connId)302 static int32_t ClientOnBrConnect(int32_t connId)
303 {
304     int32_t socketFd = INVALID_SOCKET;
305     bool isSuccess = true;
306     if (ClientOnBrConnectDevice(connId, &socketFd) != SOFTBUS_OK) {
307         isSuccess = false;
308     }
309     ClientNoticeResultBrConnect(connId, isSuccess, socketFd);
310     if (!isSuccess) {
311         ReleaseConnectionRefByConnId(connId);
312     }
313     return socketFd;
314 }
315 
NotifyDisconnect(const ListNode * notifyList,int32_t connectionId,ConnectionInfo connectionInfo,int32_t value,int32_t sideType)316 static void NotifyDisconnect(const ListNode *notifyList, int32_t connectionId,
317     ConnectionInfo connectionInfo, int32_t value, int32_t sideType)
318 {
319     ListNode *item = NULL;
320     ListNode *itemNext = NULL;
321     if (IsListEmpty(notifyList) != true) {
322         LIST_FOR_EACH_SAFE(item, itemNext, notifyList) {
323             RequestInfo *requestInfo = LIST_ENTRY(item, RequestInfo, node);
324             if (requestInfo->callback.OnConnectFailed != NULL) {
325                 SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "notify disconn connectionId=%d", connectionId);
326                 requestInfo->callback.OnConnectFailed(requestInfo->requestId, value);
327             }
328             ListDelete(&requestInfo->node);
329             SoftBusFree(requestInfo);
330         }
331     }
332     (void)sideType;
333     if (g_connectCallback != NULL) {
334         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ClientOnEvent] disconn connectionId=%d", connectionId);
335         g_connectCallback->OnDisconnected(connectionId, &connectionInfo);
336     }
337 }
338 
NotifyServerConn(int connectionId,const char * mac,int32_t sideType)339 static int32_t NotifyServerConn(int connectionId, const char *mac, int32_t sideType)
340 {
341     ConnectionInfo connectionInfo;
342     connectionInfo.isAvailable = 1;
343     connectionInfo.isServer = sideType;
344     connectionInfo.type = CONNECT_BR;
345     if (strcpy_s(connectionInfo.brInfo.brMac, BT_MAC_LEN, mac) != EOK) {
346         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "NotifyServerConn scpy error");
347         return SOFTBUS_ERR;
348     }
349     g_connectCallback->OnConnected(connectionId, &connectionInfo);
350     return SOFTBUS_OK;
351 }
352 
FreeSendNode(SendBrQueueNode * node)353 static void FreeSendNode(SendBrQueueNode *node)
354 {
355     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[FreeSendNode]");
356     if (node == NULL) {
357         return;
358     }
359     if (node->data != NULL) {
360         SoftBusFree((void *)node->data);
361     }
362     SoftBusFree((void *)node);
363 }
364 
BrDisconnect(int32_t socketFd,int32_t value)365 static void BrDisconnect(int32_t socketFd, int32_t value)
366 {
367     ListNode notifyList;
368     ListInit(&notifyList);
369     ListNode pendingList;
370     ListInit(&pendingList);
371     ConnectionInfo connectionInfo;
372     int32_t sideType = BR_CLIENT_TYPE;
373     int32_t perState = BR_CONNECTION_STATE_CLOSED;
374     uint32_t connectionId = SetBrConnStateBySocket(socketFd, BR_CONNECTION_STATE_CLOSED, &perState);
375     if (connectionId != 0) {
376         (void)GetBrRequestListByConnId(connectionId, &notifyList, &connectionInfo, &sideType);
377         (void)GetAndRemovePendingRequestByConnId(connectionId, &pendingList);
378         if (perState != BR_CONNECTION_STATE_CLOSED) {
379             NotifyDisconnect(&notifyList, connectionId, connectionInfo, value, sideType);
380             ReleaseConnectionRefByConnId(connectionId);
381         }
382 
383         ConnectOption option;
384         option.type = CONNECT_BR;
385         option.brOption.sideType = CONN_SIDE_CLIENT;
386         if (strcpy_s(option.brOption.brMac, BT_MAC_LEN, connectionInfo.brInfo.brMac) != EOK) {
387             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "restore connection failed, strcpy_s failed, "
388                 "connectionId: %u", connectionId);
389             return;
390         }
391 
392         ListNode *it = NULL;
393         ListNode *itNext = NULL;
394         LIST_FOR_EACH_SAFE(it, itNext, &pendingList) {
395             RequestInfo *request = LIST_ENTRY(it, RequestInfo, node);
396             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "connection %u closed, restore connect request: %u",
397                 connectionId, request->requestId);
398             ConnConnectDevice(&option, request->requestId, &request->callback);
399             ListDelete(&request->node);
400             SoftBusFree(request);
401         }
402     }
403 }
404 
ConnBrOnEvent(BrConnLoopMsgType type,int32_t socketFd,int32_t value)405 int32_t ConnBrOnEvent(BrConnLoopMsgType type, int32_t socketFd, int32_t value)
406 {
407     if (type >= ADD_CONN_BR_MAX || type <= ADD_CONN_BR_INVALID) {
408         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrOnEvent] type(%d) failed", type);
409         return SOFTBUS_ERR;
410     }
411     if (type == ADD_CONN_BR_CONGEST_MSG) {
412         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrOnEvent] ADD_CONN_BR_CONGEST_MSG");
413         RfcomCongestEvent(socketFd, value);
414         return SOFTBUS_ERR;
415     }
416 
417     SoftBusMessage *msg = BrConnCreateLoopMsg(type, (uint64_t)socketFd, (uint64_t)value, NULL);
418     if (msg == NULL) {
419         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrOnEvent] BrConnCreateLoopMsg failed");
420         return SOFTBUS_ERR;
421     }
422     g_brAsyncHandler.looper->PostMessage(g_brAsyncHandler.looper, msg);
423     return SOFTBUS_OK;
424 }
425 
ConnectDeviceExist(uint32_t connId,uint32_t requestId,const ConnectResult * result)426 static void ConnectDeviceExist(uint32_t connId, uint32_t requestId, const ConnectResult *result)
427 {
428     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ConnectDeviceExit]");
429     BrConnectionInfo *connInfo = GetConnectionRef(connId);
430     if (connInfo == NULL) {
431         return;
432     }
433     ConnectionInfo connectionInfo;
434     connectionInfo.isAvailable = 1;
435     connectionInfo.isServer = connInfo->sideType;
436     connectionInfo.type = CONNECT_BR;
437     if (strcpy_s(connectionInfo.brInfo.brMac, BT_MAC_LEN, connInfo->mac) != EOK) {
438         ReleaseConnectionRef(connInfo);
439         return;
440     }
441     ReleaseConnectionRef(connInfo);
442 
443     if (result->OnConnectSuccessed != NULL) {
444         result->OnConnectSuccessed(requestId, connId, &connectionInfo);
445     }
446     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
447         "connnect notify connected, connectionId:%u, requestId:%u", connId, requestId);
448 
449     (void)PackRequest(CONNECT_REF_INCRESE, connId);
450 }
451 
ConnectDeviceStateConnecting(uint32_t connId,uint32_t requestId,const ConnectResult * result)452 static int32_t ConnectDeviceStateConnecting(uint32_t connId, uint32_t requestId, const ConnectResult *result)
453 {
454     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ConnectDeviceStateConnecting]");
455     RequestInfo *requestInfo = (RequestInfo *)SoftBusMalloc(sizeof(RequestInfo));
456     if (requestInfo == NULL) {
457         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SoftBusMalloc failed");
458         return SOFTBUS_ERR;
459     }
460     (void)memset_s(requestInfo, sizeof(RequestInfo), 0, sizeof(RequestInfo));
461     ListInit(&requestInfo->node);
462     requestInfo->requestId = requestId;
463     if (memcpy_s(&requestInfo->callback, sizeof(requestInfo->callback), result, sizeof(*result)) != EOK) {
464         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "AddRequestByConnId memcpy_s fail");
465         SoftBusFree(requestInfo);
466         return SOFTBUS_ERR;
467     }
468     if (AddRequestByConnId(connId, requestInfo) != SOFTBUS_OK) {
469         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "AddRequestByConnId failed");
470         SoftBusFree(requestInfo);
471         return SOFTBUS_ERR;
472     }
473     return SOFTBUS_OK;
474 }
475 
ConnectDeviceStateClosing(uint32_t connId,uint32_t requestId,const ConnectResult * result)476 static int32_t ConnectDeviceStateClosing(uint32_t connId, uint32_t requestId, const ConnectResult *result)
477 {
478     RequestInfo *requestInfo = (RequestInfo *)SoftBusCalloc(sizeof(RequestInfo));
479     if (requestInfo == NULL) {
480         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "add pending request %u failed, malloc failed, connection: %u",
481             requestId, connId);
482         return SOFTBUS_ERR;
483     }
484 
485     ListInit(&requestInfo->node);
486     requestInfo->requestId = requestId;
487     requestInfo->callback = *result;
488     if (AddPendingRequestByConnId(connId, requestInfo) != SOFTBUS_OK) {
489         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "add pending request %u failed, connection: %u",
490             requestId, connId);
491         SoftBusFree(requestInfo);
492         return SOFTBUS_ERR;
493     }
494     return SOFTBUS_OK;
495 }
496 
ConnectDeviceFirstTime(const ConnectOption * option,uint32_t requestId,const ConnectResult * result)497 static int32_t ConnectDeviceFirstTime(const ConnectOption *option, uint32_t requestId, const ConnectResult *result)
498 {
499     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ConnectDeviceFirstTime]");
500     if (g_sppDriver == NULL) {
501         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[sppDriver null]");
502         return SOFTBUS_ERR;
503     }
504     BrConnectionInfo *newConnInfo = CreateBrconnectionNode(true);
505     if (newConnInfo == NULL) {
506         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[client node create fail]");
507         return SOFTBUS_ERR;
508     }
509     RequestInfo *requestInfo = (RequestInfo *)SoftBusCalloc(sizeof(RequestInfo));
510     if (requestInfo == NULL) {
511         ReleaseBrconnectionNode(newConnInfo);
512         return SOFTBUS_ERR;
513     }
514     ListInit(&requestInfo->node);
515     requestInfo->requestId = requestId;
516     if (memcpy_s(&requestInfo->callback, sizeof(requestInfo->callback), result, sizeof(*result)) != EOK) {
517         ReleaseBrconnectionNode(newConnInfo);
518         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnectDeviceFirstTime memcpy_s fail");
519         return SOFTBUS_ERR;
520     }
521     ListAdd(&newConnInfo->requestList, &requestInfo->node);
522     if (strcpy_s(newConnInfo->mac, BT_MAC_LEN, option->brOption.brMac) != EOK) {
523         ReleaseBrconnectionNode(newConnInfo);
524         return SOFTBUS_ERR;
525     }
526     uint32_t connId = newConnInfo->connectionId;
527     if (AddConnectionList(newConnInfo) != SOFTBUS_OK) {
528         ReleaseBrconnectionNode(newConnInfo);
529         return SOFTBUS_ERR;
530     }
531     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnectDeviceFirstTime connId:%d, requestId:%d", connId, requestId);
532     if (ConnBrOnEvent(ADD_CONN_BR_CLIENT_CONNECTED_MSG, (int32_t)connId, (int32_t)connId) != SOFTBUS_OK) {
533         ReleaseConnectionRef(newConnInfo);
534         SoftbusRecordConnInfo(SOFTBUS_HISYSEVT_CONN_MEDIUM_BR, SOFTBUS_EVT_CONN_FAIL, 0);
535         return SOFTBUS_ERR;
536     }
537     return SOFTBUS_OK;
538 }
539 
ConnectDevice(const ConnectOption * option,uint32_t requestId,const ConnectResult * result)540 static int32_t ConnectDevice(const ConnectOption *option, uint32_t requestId, const ConnectResult *result)
541 {
542     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br connect device, requestId:%u", requestId);
543     if (HasDiffMacDeviceExit(option)) {
544         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[has diff mac device]");
545     }
546     uint32_t connId = 0;
547     uint32_t connectingReqId = 0;
548     int32_t ret = SOFTBUS_OK;
549     if (pthread_mutex_lock(&g_brConnLock) != 0) {
550         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed");
551         return SOFTBUS_ERR;
552     }
553     int32_t connState = GetBrConnStateByConnOption(option, &connId, &connectingReqId);
554     if (connState == BR_CONNECTION_STATE_CONNECTED) {
555         ConnectDeviceExist(connId, requestId, result);
556     } else if (connState == BR_CONNECTION_STATE_CONNECTING) {
557         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "device is connecting:%u, current:%u, connecting:%u", connId,
558             requestId, connectingReqId);
559         ret = ConnectDeviceStateConnecting(connId, requestId, result);
560     } else if (connState == BR_CONNECTION_STATE_CLOSING) {
561         ret = ConnectDeviceStateClosing(connId, requestId, result);
562         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "device is closing:%u, current:%u, try pending request, ret: %d",
563             connId, requestId, ret);
564     } else if (connState == BR_CONNECTION_STATE_CLOSED) {
565         int32_t connCount = GetBrConnectionCount();
566         if (connCount == SOFTBUS_ERR || connCount > g_brMaxConnCount) {
567             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
568                 "br connect device failed: connected device %d exceed than limit %d, requestId: %u",
569                     connCount, g_brMaxConnCount, requestId);
570             result->OnConnectFailed(requestId, 0);
571             SoftbusRecordConnInfo(SOFTBUS_HISYSEVT_CONN_MEDIUM_BR, SOFTBUS_EVT_CONN_FAIL, 0);
572             ret = SOFTBUS_ERR;
573         } else {
574             ret = ConnectDeviceFirstTime(option, requestId, result);
575         }
576     }
577     (void)pthread_mutex_unlock(&g_brConnLock);
578     return ret;
579 }
580 
ServerOnBrConnect(int32_t socketFd)581 static uint32_t ServerOnBrConnect(int32_t socketFd)
582 {
583     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[new connection, socket = %d]", socketFd);
584     if (IsExitBrConnectByFd(socketFd)) {
585         return SOFTBUS_ERR;
586     }
587     uint32_t connectionId = 0;
588     BrConnectionInfo *newConnectionInfo = CreateBrconnectionNode(false);
589     if (newConnectionInfo == NULL) {
590         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[service node create fail]");
591         g_sppDriver->DisConnect(socketFd);
592         return connectionId;
593     }
594     RequestInfo *requestInfo = (RequestInfo *)SoftBusCalloc(sizeof(RequestInfo));
595     if (requestInfo == NULL) {
596         ReleaseBrconnectionNode(newConnectionInfo);
597         g_sppDriver->DisConnect(socketFd);
598         return connectionId;
599     }
600     ListInit(&requestInfo->node);
601     ListAdd(&newConnectionInfo->requestList, &requestInfo->node);
602     BluetoothRemoteDevice deviceInfo;
603     if (g_sppDriver->GetRemoteDeviceInfo(socketFd, &deviceInfo) != SOFTBUS_OK) {
604         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetRemoteDeviceInfo fail");
605         ReleaseBrconnectionNode(newConnectionInfo);
606         g_sppDriver->DisConnect(socketFd);
607         return connectionId;
608     }
609     if (ConvertBtMacToStr(newConnectionInfo->mac, BT_MAC_LEN, (uint8_t *)deviceInfo.mac, BT_ADDR_LEN) != SOFTBUS_OK) {
610         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrServer convert bt mac to str fail");
611         ReleaseBrconnectionNode(newConnectionInfo);
612         g_sppDriver->DisConnect(socketFd);
613         return connectionId;
614     }
615     newConnectionInfo->socketFd = socketFd;
616     newConnectionInfo->state = BR_CONNECTION_STATE_CONNECTED;
617     connectionId = newConnectionInfo->connectionId;
618     char mac[BT_MAC_LEN] = {0};
619     if (memcpy_s(mac, BT_MAC_LEN, newConnectionInfo->mac, BT_MAC_LEN) != EOK) {
620         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrServer memcpy mac fail");
621         ReleaseBrconnectionNode(newConnectionInfo);
622         g_sppDriver->DisConnect(socketFd);
623         return 0;
624     }
625     if (AddConnectionList(newConnectionInfo) != SOFTBUS_OK) {
626         ListDelete(&newConnectionInfo->node);
627         ReleaseBrconnectionNode(newConnectionInfo);
628         g_sppDriver->DisConnect(socketFd);
629         return connectionId;
630     }
631     if (NotifyServerConn(connectionId, mac, BR_SERVICE_TYPE) != SOFTBUS_OK) {
632         g_sppDriver->DisConnect(socketFd);
633         ReleaseConnectionRefByConnId(connectionId);
634         connectionId = 0;
635     }
636     return connectionId;
637 }
638 
PostBytes(uint32_t connectionId,const char * data,int32_t len,int32_t pid,int32_t flag)639 static int32_t PostBytes(uint32_t connectionId, const char *data, int32_t len, int32_t pid, int32_t flag)
640 {
641     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
642         "PostBytes connectionId=%u,pid=%d,len=%d flag=%d", connectionId, pid, len, flag);
643 
644     int32_t state = GetBrConnStateByConnectionId(connectionId);
645     if (state != BR_CONNECTION_STATE_CONNECTED) {
646         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "connectionId(%u) device is not ready, state: %d",
647             connectionId, state);
648         SoftBusFree((void *)data);
649         return SOFTBUS_BRCONNECTION_POSTBYTES_ERROR;
650     }
651 
652     SendBrQueueNode *node = (SendBrQueueNode *)SoftBusCalloc(sizeof(SendBrQueueNode));
653     if (node == NULL) {
654         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "PostBytes SoftBusCalloc failed");
655         return SOFTBUS_MALLOC_ERR;
656     }
657     node->connectionId = connectionId;
658     node->pid = pid;
659     node->flag = flag;
660     node->len = (uint32_t)len;
661     node->data = data;
662     node->isInner = ((pid == 0) ? true : false);
663     node->listener = NULL;
664     int32_t ret = BrEnqueueNonBlock((const void *)node);
665     if (ret != SOFTBUS_OK) {
666         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Br enqueue failed, ret: %d", ret);
667         SoftBusFree((void *)data);
668         SoftBusFree(node);
669         return ret;
670     }
671     return SOFTBUS_OK;
672 }
673 
DisconnectDevice(uint32_t connectionId)674 static int32_t DisconnectDevice(uint32_t connectionId)
675 {
676     if (!IsExitConnectionById(connectionId)) {
677         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR,
678             "br disconnect device failed: not find connection: %u", connectionId);
679         return SOFTBUS_BRCONNECTION_DISCONNECT_NOTFIND;
680     }
681     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br disconnect device, connectionId:%u", connectionId);
682     (void)PackRequest(CONNECT_REF_DECRESE, connectionId);
683     return SOFTBUS_OK;
684 }
685 
DisconnectDeviceNow(const ConnectOption * option)686 static int32_t DisconnectDeviceNow(const ConnectOption *option)
687 {
688     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDeviceNow]");
689     if (option == NULL || option->type != CONNECT_BR) {
690         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "option check fail");
691         return SOFTBUS_ERR;
692     }
693     int32_t socketFd = INVALID_SOCKET;
694     int32_t sideType;
695     if (BrClosingByConnOption(option, &socketFd, &sideType) != SOFTBUS_OK) {
696         return SOFTBUS_ERR;
697     }
698     if (!IsBrQueueEmpty()) {
699         SoftBusSleepMs(DISCONN_DELAY_TIME);
700     }
701     if (sideType == BR_SERVICE_TYPE) {
702         return ConnBrOnEvent(ADD_CONN_BR_SERVICE_DISCONNECTED_MSG, socketFd, socketFd);
703     } else {
704         return ConnBrOnEvent(ADD_CONN_BR_CLIENT_DISCONNECTED_MSG, socketFd, socketFd);
705     }
706     return SOFTBUS_ERR;
707 }
708 
SendAck(BrConnectionInfo * brConnInfo,uint32_t windows,uint64_t seq)709 static int32_t SendAck(BrConnectionInfo *brConnInfo, uint32_t windows, uint64_t seq)
710 {
711     int32_t dataLen = 0;
712     char *buf = BrPackRequestOrResponse(METHOD_NOTIFY_ACK, (int32_t)windows, seq, &dataLen);
713     if (buf == NULL) {
714         return SOFTBUS_ERR;
715     }
716     int32_t ret = CreateBrPendingPacket(brConnInfo->connectionId, seq);
717     if (ret != SOFTBUS_OK) {
718         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_WARN, "create pending failed id: %u, seq: %" PRIu64 ", ret: %d",
719             brConnInfo->connectionId, seq, ret);
720         SoftBusFree(buf);
721         return ret;
722     }
723     ret = BrTransSend(brConnInfo, g_sppDriver, g_brSendPeerLen, buf, dataLen);
724     if (ret != SOFTBUS_OK) {
725         DelBrPendingPacket(brConnInfo->connectionId, seq);
726     }
727     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "send ack connectId: %u, seq: %" PRIu64 ", result: %d",
728         brConnInfo->connectionId, seq, ret);
729     SoftBusFree(buf);
730     return ret;
731 }
732 
WaitAck(BrConnectionInfo * brConnInfo,uint64_t seq)733 static void WaitAck(BrConnectionInfo *brConnInfo, uint64_t seq)
734 {
735     char *data = NULL;
736     int32_t ret = GetBrPendingPacket(brConnInfo->connectionId, seq, WAIT_ACK_TIMES, (void **)&data);
737     if (ret == SOFTBUS_ALREADY_TRIGGERED) {
738         brConnInfo->ackTimeoutCount = 0;
739         if (brConnInfo->windows < MAX_WINDOWS) {
740             brConnInfo->windows = brConnInfo->windows + 1;
741         }
742         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "GetBrPending(%u) TRIGGERED seq:%" PRIu64 ", windows: %u",
743             brConnInfo->connectionId, seq, brConnInfo->windows);
744         SoftBusFree(data);
745         return;
746     } else if (ret == SOFTBUS_TIMOUT) {
747         brConnInfo->ackTimeoutCount = brConnInfo->ackTimeoutCount + 1;
748         if (brConnInfo->windows > MIN_WINDOWS && ((brConnInfo->ackTimeoutCount & 0x01) == 0)) {
749             brConnInfo->windows = brConnInfo->windows - 1;
750         }
751         if (brConnInfo->ackTimeoutCount > WINDOWS_ACK_FAILED_TIMES && brConnInfo->windows < DEFAULT_WINDOWS) {
752             brConnInfo->windows = DEFAULT_WINDOWS;
753         }
754         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "GetBrPending(%u) TIMOUT seq:%" PRIu64 ", windows: %u",
755             brConnInfo->connectionId, seq, brConnInfo->windows);
756         return;
757     } else if (ret == SOFTBUS_OK) {
758         brConnInfo->ackTimeoutCount = 0;
759         SoftBusFree(data);
760         return;
761     }
762     brConnInfo->ackTimeoutCount = 0;
763 }
764 
UpdataSeq(BrConnectionInfo * brConnInfo)765 static uint64_t UpdataSeq(BrConnectionInfo *brConnInfo)
766 {
767     brConnInfo->seq = brConnInfo->seq + 1;
768     if (brConnInfo->seq == 0) {
769         brConnInfo->seq = 1;
770     }
771     return brConnInfo->seq;
772 }
773 
SendHandlerLoop(void * arg)774 void *SendHandlerLoop(void *arg)
775 {
776 #define WAIT_TIME 10
777     SendBrQueueNode *sendNode = NULL;
778     while (1) {
779         int32_t ret = BrDequeueBlock((void **)(&sendNode));
780         if (ret != SOFTBUS_OK) {
781             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "br dequeue send node failed, error=%d", ret);
782             SoftBusSleepMs(WAIT_TIME);
783             continue;
784         }
785         uint32_t connId = sendNode->connectionId;
786         BrConnectionInfo *brConnInfo = GetConnectionRef(connId);
787         if (brConnInfo == NULL) {
788             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_WARN, "[SendLoop] connId: %u, not fount failed", connId);
789             FreeSendNode(sendNode);
790             continue;
791         }
792         if (brConnInfo->socketFd == INVALID_SOCKET) {
793             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_WARN, "[SendLoop] connId: %u, invalid socket", connId);
794             ReleaseConnectionRef(brConnInfo);
795             FreeSendNode(sendNode);
796             continue;
797         }
798         uint64_t seq = UpdataSeq(brConnInfo);
799         uint32_t windows = brConnInfo->windows;
800         if (seq % windows == 0) {
801             if (SendAck(brConnInfo, windows, seq) == SOFTBUS_OK) {
802                 brConnInfo->waitSeq = seq;
803             }
804         }
805         sendNode->seq = seq;
806         if (brConnInfo->waitSeq != 0 && windows > 1 && (seq % windows == (windows - 1))) {
807             WaitAck(brConnInfo, brConnInfo->waitSeq);
808             brConnInfo->waitSeq = 0;
809         }
810         ret = BrTransSend(brConnInfo, g_sppDriver, g_brSendPeerLen, sendNode->data, sendNode->len);
811         if (ret != SOFTBUS_OK) {
812             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrTransSend fail. connId:%u, seq: %" PRIu64, connId, seq);
813         }
814         ReleaseConnectionRef(brConnInfo);
815         if (sendNode->listener != NULL) {
816             sendNode->listener(connId, seq, sendNode->module, ret);
817         }
818         FreeSendNode(sendNode);
819         sendNode = NULL;
820     }
821     return NULL;
822 }
823 
InitDataQueue(void)824 static int32_t InitDataQueue(void)
825 {
826     pthread_t tid;
827     if (pthread_create(&tid, NULL, SendHandlerLoop, NULL) != 0) {
828         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create DeathProcTask failed");
829         return SOFTBUS_ERR;
830     }
831     return SOFTBUS_OK;
832 }
833 
ConnBrAccept(void * arg)834 void *ConnBrAccept(void *arg)
835 {
836 #define TRY_OPEN_SERVER_COUNT 5
837     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnBrAccept start\n");
838     int32_t serverId;
839     int32_t clientId;
840     char name[BR_SERVER_NAME_LEN] = {0};
841     int32_t ret;
842     int32_t num = 0;
843     int32_t tryCount = 0;
844     while (tryCount < TRY_OPEN_SERVER_COUNT) {
845         if (g_sppDriver == NULL || !g_startListenFlag || g_brEnable != SOFTBUS_BR_STATE_TURN_ON) {
846             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "g_sppDriver failed EXIT!");
847             break;
848         }
849         int32_t connCount = GetBrConnectionCount();
850         if (connCount == SOFTBUS_ERR || connCount > g_brMaxConnCount) {
851             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "connCount: %d", connCount);
852             SoftBusSleepMs(BR_ACCEPET_WAIT_TIME);
853             continue;
854         }
855         (void)memset_s(name, sizeof(name), 0, sizeof(name));
856         ret = sprintf_s(name, BR_SERVER_NAME_LEN, "SOFTBUS_BR_%d", num);
857         if (ret <= 0) {
858             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ConnBrAccept sprintf_s failed %d", num);
859             SoftBusSleepMs(BR_ACCEPET_WAIT_TIME);
860             tryCount++;
861             continue;
862         }
863         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "OpenSppServer %s start", name);
864         serverId = g_sppDriver->OpenSppServer(name, strlen(name), UUID, 0);
865         if (serverId == SOFTBUS_ERR) {
866             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "OpenSppServer name %s failed", name);
867             SoftBusSleepMs(BR_ACCEPET_WAIT_TIME);
868             tryCount++;
869             continue;
870         }
871         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "OpenSppServer ok");
872         clientId = g_sppDriver->Accept(serverId);
873         if (clientId != SOFTBUS_ERR && g_brEnable == SOFTBUS_BR_STATE_TURN_ON) {
874             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "Accept ok clientId: %d", clientId);
875             ConnBrOnEvent(ADD_CONN_BR_SERVICE_CONNECTED_MSG, clientId, clientId);
876         } else {
877             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "spp Accept %s failed, clientId: %d", name, clientId);
878         }
879         g_sppDriver->CloseSppServer(serverId);
880         num++;
881         tryCount = 0;
882     }
883     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "OpenSppServer failed EXIT!");
884     return NULL;
885 }
886 
StartLocalListening(const LocalListenerInfo * info)887 static int32_t StartLocalListening(const LocalListenerInfo *info)
888 {
889     if (g_sppDriver == NULL || info->type != CONNECT_BR) {
890         return SOFTBUS_ERR;
891     }
892 
893     if (g_startListenFlag) {
894         return SOFTBUS_OK;
895     }
896 
897     pthread_t tid;
898     pthread_attr_t threadAttr;
899     pthread_attr_init(&threadAttr);
900     if (pthread_create(&tid, &threadAttr, ConnBrAccept, NULL) != 0) {
901         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create ConnBrAccept failed");
902         pthread_attr_destroy(&threadAttr);
903         return SOFTBUS_ERR;
904     }
905     g_startListenFlag = true;
906     pthread_attr_destroy(&threadAttr);
907     return SOFTBUS_OK;
908 }
909 
StopLocalListening(const LocalListenerInfo * info)910 static int32_t StopLocalListening(const LocalListenerInfo *info)
911 {
912     if (g_sppDriver == NULL || info->type != CONNECT_BR) {
913         return SOFTBUS_ERR;
914     }
915     g_startListenFlag = false;
916     return SOFTBUS_OK;
917 }
918 
InitProperty()919 static int32_t InitProperty()
920 {
921     g_brBuffSize = INVALID_LENGTH;
922     g_brSendPeerLen = INVALID_LENGTH;
923     g_brMaxConnCount = INVALID_LENGTH;
924     if (SoftbusGetConfig(SOFTBUS_INT_CONN_BR_MAX_DATA_LENGTH,
925         (unsigned char*)&g_brBuffSize, sizeof(g_brBuffSize)) != SOFTBUS_OK) {
926         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get br BuffSize fail");
927     }
928     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br BuffSize is %u", g_brBuffSize);
929     if (SoftbusGetConfig(SOFTBUS_INT_CONN_RFCOM_SEND_MAX_LEN,
930         (unsigned char*)&g_brSendPeerLen, sizeof(g_brSendPeerLen)) != SOFTBUS_OK) {
931         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get br SendPeerLen fail");
932     }
933     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br SendPeerLen is %u", g_brSendPeerLen);
934     if (SoftbusGetConfig(SOFTBUS_INT_CONN_BR_RECEIVE_MAX_LEN,
935         (unsigned char*)&g_brSendQueueMaxLen, sizeof(g_brSendQueueMaxLen)) != SOFTBUS_OK) {
936         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get br SendQueueMaxLen fail");
937     }
938     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br SendQueueMaxLen is %u", g_brSendQueueMaxLen);
939     if (SoftbusGetConfig(SOFTBUS_INT_CONN_BR_MAX_CONN_NUM,
940         (unsigned char*)&g_brMaxConnCount, sizeof(g_brMaxConnCount)) != SOFTBUS_OK) {
941         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get br MaxConnCount fail");
942     }
943     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br MaxConnCount is %d", g_brMaxConnCount);
944     if (g_brBuffSize == INVALID_LENGTH || g_brBuffSize > MAX_BR_SIZE) {
945         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot get brBuffSize");
946         return SOFTBUS_ERR;
947     }
948     if (g_brSendPeerLen == INVALID_LENGTH || g_brSendPeerLen > MAX_BR_PEER_SIZE) {
949         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot get brSendPeerLen");
950         return SOFTBUS_ERR;
951     }
952     if (g_brSendQueueMaxLen == SOFTBUS_ERR || g_brSendQueueMaxLen > MAX_BR_PEER_SIZE) {
953         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot get brSendQueueMaxLen");
954         return SOFTBUS_ERR;
955     }
956     if (g_brMaxConnCount == INVALID_LENGTH) {
957         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot get brMaxConnCount");
958         return SOFTBUS_ERR;
959     }
960     return SOFTBUS_OK;
961 }
962 
963 typedef struct BrReadThreadParams {
964     uint32_t connInfoId;
965     int32_t socketFd;
966 } BrReadThreadParams;
967 
ConnBrRead(void * arg)968 void *ConnBrRead(void *arg)
969 {
970     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnBrRead start");
971     if (arg == NULL) {
972         return NULL;
973     }
974     BrReadThreadParams *values = (BrReadThreadParams *)arg;
975     uint32_t connId = values->connInfoId;
976     int32_t socketFd = values->socketFd;
977     SoftBusFree(arg);
978 
979     if (socketFd == INVALID_SOCKET) {
980         socketFd = ClientOnBrConnect(connId);
981         if (socketFd == INVALID_SOCKET) {
982             return NULL;
983         }
984     }
985     while (1) {
986         char *outBuf = NULL;
987         int32_t packLen = BrTransReadOneFrame(connId, g_sppDriver, socketFd, &outBuf);
988         if (packLen == BR_READ_SOCKET_CLOSED) {
989             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrRead] failed socket close");
990             g_sppDriver->DisConnect(socketFd);
991             BrDisconnect(socketFd, socketFd);
992             return NULL;
993         }
994         if (packLen == BR_READ_FAILED) {
995             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrRead] failed");
996             g_sppDriver->DisConnect(socketFd);
997             BrDisconnect(socketFd, socketFd);
998             return NULL;
999         }
1000         if (outBuf == NULL) {
1001             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrRead] outBuf null");
1002             continue;
1003         }
1004         SoftBusMessage *msg = BrConnCreateLoopMsg(ADD_CONN_BR_RECV_MSG, (uint64_t)connId, (uint64_t)packLen, outBuf);
1005         if (msg == NULL) {
1006             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrRead] BrConnCreateLoopMsg failed");
1007             SoftBusFree(outBuf);
1008             continue;
1009         }
1010         g_brAsyncHandler.looper->PostMessage(g_brAsyncHandler.looper, msg);
1011     }
1012     return NULL;
1013 }
1014 
BrConnectedEventHandle(bool isClient,uint32_t value)1015 void BrConnectedEventHandle(bool isClient, uint32_t value)
1016 {
1017     uint32_t connInfoId;
1018     int32_t socketFd = INVALID_SOCKET;
1019     if (isClient) {
1020         connInfoId = value;
1021     } else {
1022         socketFd = (int32_t)value;
1023         connInfoId = ServerOnBrConnect(socketFd);
1024     }
1025     if (connInfoId == 0) {
1026         return;
1027     }
1028     pthread_t tid;
1029     BrReadThreadParams *args = (BrReadThreadParams *)SoftBusCalloc(sizeof(BrReadThreadParams));
1030     if (args == NULL) {
1031         goto EXIT;
1032     }
1033     args->connInfoId = connInfoId;
1034     args->socketFd = socketFd;
1035     if (pthread_create(&tid, NULL, ConnBrRead, (void *)args) != 0) {
1036         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create ConnBrRead failed");
1037         SoftBusFree(args);
1038         goto EXIT;
1039     }
1040     return;
1041 EXIT:
1042     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrConnectedEventHandle EXIT");
1043     if (!isClient) {
1044         ConnBrOnEvent(ADD_CONN_BR_SERVICE_DISCONNECTED_MSG, socketFd, socketFd);
1045     } else {
1046         ClientNoticeResultBrConnect(connInfoId, false, socketFd);
1047         ReleaseConnectionRefByConnId(connInfoId);
1048     }
1049     return;
1050 }
1051 
Resume(uint32_t connectionId)1052 static void Resume(uint32_t connectionId)
1053 {
1054     ListNode pendings;
1055     ListInit(&pendings);
1056 
1057     if (ResumeConnection(connectionId, &pendings) != SOFTBUS_OK) {
1058         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "resume pending connection %u failed", connectionId);
1059         return;
1060     }
1061 
1062     ListNode *it = NULL;
1063     ListNode *itNext = NULL;
1064     LIST_FOR_EACH_SAFE(it, itNext, &pendings) {
1065         RequestInfo *request = LIST_ENTRY(it, RequestInfo, node);
1066         ConnectDeviceExist(connectionId, request->requestId, &request->callback);
1067         ListDelete(&request->node);
1068         SoftBusFree(request);
1069     }
1070 }
1071 
OnPackResponse(int32_t delta,int32_t peerRef,uint32_t connectionId)1072 static void OnPackResponse(int32_t delta, int32_t peerRef, uint32_t connectionId)
1073 {
1074     BrConnectionInfo *connInfo = GetConnectionRef(connectionId);
1075     if (connInfo == NULL) {
1076         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR,
1077             "br OnPackResponse failed: not find device, connectionId: %u", connectionId);
1078         return;
1079     }
1080     connInfo->refCount += delta;
1081     int32_t myRefCount = connInfo->refCount;
1082     int32_t mySocketFd = connInfo->socketFd;
1083     int32_t sideType = connInfo->sideType;
1084     ReleaseConnectionRef(connInfo);
1085 
1086     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
1087         "br OnPackResponse: delta=%d, remoteRef=%d, myRef:%d, connectionId=%u",
1088             delta, peerRef, myRefCount, connectionId);
1089     if (peerRef > 0) {
1090         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[remote device Ref is > 0, do not reply]");
1091         // resume connection when peer reference is larger than 0
1092         Resume(connectionId);
1093         return;
1094     }
1095     if (myRefCount <= 0) {
1096         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
1097             "br OnPackResponse local device ref <= 0, and remote ref <=0 close connection now");
1098         SetBrConnStateByConnId(connectionId, BR_CONNECTION_STATE_CLOSING);
1099         if (sideType == BR_SERVICE_TYPE) {
1100             ConnBrOnEvent(ADD_CONN_BR_SERVICE_DISCONNECTED_MSG, mySocketFd, mySocketFd);
1101         } else {
1102             ConnBrOnEvent(ADD_CONN_BR_CLIENT_DISCONNECTED_MSG, mySocketFd, mySocketFd);
1103         }
1104         return;
1105     }
1106     int32_t outLen = INVALID_LENGTH;
1107     char *buf = BrPackRequestOrResponse(METHOD_NOTIFY_RESPONSE, delta, myRefCount, &outLen);
1108     if (buf == NULL) {
1109         return;
1110     }
1111     (void)PostBytesInner(connectionId, METHOD_NOTIFY_RESPONSE, buf, outLen);
1112 }
1113 
OnAck(uint32_t connectionId,uint32_t localWindows,uint64_t remoteSeq)1114 static int32_t OnAck(uint32_t connectionId, uint32_t localWindows, uint64_t remoteSeq)
1115 {
1116     int32_t dataLen = 0;
1117     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "send ack seq: %" PRIu64 " respone", remoteSeq);
1118     char *buf = BrPackRequestOrResponse(METHOD_ACK_RESPONSE, (int32_t)localWindows, remoteSeq, &dataLen);
1119     if (buf != NULL) {
1120         return PostBytesInner(connectionId, METHOD_ACK_RESPONSE, buf, dataLen);
1121     }
1122     return SOFTBUS_ERR;
1123 }
1124 
BrConnectedComdHandl(uint32_t connectionId,const cJSON * data)1125 static void BrConnectedComdHandl(uint32_t connectionId, const cJSON *data)
1126 {
1127     int32_t keyMethod = 0;
1128     int32_t keyDelta = 0;
1129     int32_t keyReferenceNum = 0;
1130 
1131     if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod)) {
1132         return;
1133     }
1134     if (keyMethod == METHOD_NOTIFY_REQUEST) {
1135         if (!GetJsonObjectSignedNumberItem(data, KEY_DELTA, &keyDelta) ||
1136             !GetJsonObjectSignedNumberItem(data, KEY_REFERENCE_NUM, &keyReferenceNum)) {
1137             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "REQUEST fail");
1138             return;
1139         }
1140         OnPackResponse(keyDelta, keyReferenceNum, connectionId);
1141     } else if (keyMethod == METHOD_NOTIFY_RESPONSE) {
1142         if (!GetJsonObjectSignedNumberItem(data, KEY_REFERENCE_NUM, &keyReferenceNum)) {
1143             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RESPONSE fail");
1144             return;
1145         }
1146         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO,
1147             "br NOTIFY_RESPONSE, connectionId:%u, remote ref:%d", connectionId, keyReferenceNum);
1148         SetBrConnStateByConnId(connectionId, BR_CONNECTION_STATE_CONNECTED);
1149     } else if (keyMethod == METHOD_NOTIFY_ACK) {
1150         int32_t remoteWindows;
1151         int64_t remoteSeq;
1152         if (!GetJsonObjectSignedNumberItem(data, KEY_WINDOWS, &remoteWindows) ||
1153             !GetJsonObjectNumber64Item(data, KEY_ACK_SEQ_NUM, &remoteSeq)) {
1154             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ACK REQUEST fail");
1155             return;
1156         }
1157         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "recv ACK REQUEST(%u) remote seq: %" PRIu64 ", windows: %d",
1158             connectionId, remoteSeq, remoteWindows);
1159         OnAck(connectionId, GetLocalWindowsByConnId(connectionId), (uint64_t)remoteSeq);
1160     } else if (keyMethod == METHOD_ACK_RESPONSE) {
1161         int32_t remoteWindows;
1162         int64_t remoteSeq;
1163         if (!GetJsonObjectSignedNumberItem(data, KEY_WINDOWS, &remoteWindows) ||
1164             !GetJsonObjectNumber64Item(data, KEY_ACK_SEQ_NUM, &remoteSeq)) {
1165             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ACK RESPONSE fail");
1166             return;
1167         }
1168         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "recv ACK RESPONSE(%u) remote seq: %" PRId64 ", windows: %d",
1169             connectionId, remoteSeq, remoteWindows);
1170         if (SetBrPendingPacket(connectionId, (uint64_t)remoteSeq, NULL) != SOFTBUS_OK) {
1171             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SetBrPendingPacket(%u) failed seq: %" PRId64,
1172                 connectionId, remoteSeq);
1173         }
1174     }
1175 }
1176 
BrRecvDataHandle(uint32_t connectionId,const char * buf,int32_t len)1177 static void BrRecvDataHandle(uint32_t connectionId, const char *buf, int32_t len)
1178 {
1179     if (len - (int32_t)sizeof(ConnPktHead) <= 0) {
1180         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "br recv data illegal data size: %d", len);
1181         return;
1182     }
1183     ConnPktHead *head = (ConnPktHead *)buf;
1184     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BrRecvDataHandle module: %d", head->module);
1185     if (head->module == MODULE_CONNECTION) {
1186         cJSON *data = NULL;
1187         data = cJSON_ParseWithLength(buf + sizeof(ConnPktHead), len - (int32_t)sizeof(ConnPktHead));
1188         if (data == NULL) {
1189             SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "br recv data invalid");
1190             return;
1191         }
1192         BrConnectedComdHandl(connectionId, (const cJSON *)data);
1193         cJSON_Delete(data);
1194     } else {
1195         if (g_connectCallback != NULL) {
1196             g_connectCallback->OnDataReceived(connectionId, (ConnModule)head->module, head->seq, (char *)buf, len);
1197         }
1198     }
1199 }
1200 
BrConnMsgHandler(SoftBusMessage * msg)1201 static void BrConnMsgHandler(SoftBusMessage *msg)
1202 {
1203     if (msg == NULL) {
1204         return;
1205     }
1206     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br conn loop process msg type %d", msg->what);
1207     switch (msg->what) {
1208         case ADD_CONN_BR_CLIENT_CONNECTED_MSG:
1209             BrConnectedEventHandle(true, msg->arg1);
1210             break;
1211         case ADD_CONN_BR_SERVICE_CONNECTED_MSG:
1212             BrConnectedEventHandle(false, msg->arg1);
1213             break;
1214         case ADD_CONN_BR_CLIENT_DISCONNECTED_MSG:
1215         case ADD_CONN_BR_SERVICE_DISCONNECTED_MSG:
1216             g_sppDriver->DisConnect(msg->arg1);
1217             BrDisconnect(msg->arg1, msg->arg2);
1218             break;
1219         case ADD_CONN_BR_RECV_MSG: {
1220             uint32_t connId = (uint32_t)msg->arg1;
1221             int32_t len = (int32_t)msg->arg2;
1222             BrRecvDataHandle(connId, (const char *)msg->obj, len);
1223             SoftBusFree((void *)msg->obj);
1224             msg->obj = NULL;
1225             break;
1226         }
1227         case ADD_CONN_BR_CLOSING_TIMEOUT_MSG:
1228             // resume connection when close timeout
1229             Resume((uint32_t)msg->arg1);
1230             break;
1231         default:
1232             break;
1233     }
1234 }
1235 
BrConnLooperInit(void)1236 static int32_t BrConnLooperInit(void)
1237 {
1238     g_brAsyncHandler.looper = CreateNewLooper("brRecv_looper");
1239     if (g_brAsyncHandler.looper == NULL) {
1240         SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrConnLooperInit failed");
1241         return SOFTBUS_ERR;
1242     }
1243     g_brAsyncHandler.HandleMessage = BrConnMsgHandler;
1244     return SOFTBUS_OK;
1245 }
1246 
StateChangedCallback(int32_t listenerId,int32_t status)1247 static void StateChangedCallback(int32_t listenerId, int32_t status)
1248 {
1249     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "StateChanged id: %d, status: %d", listenerId, status);
1250 
1251     LocalListenerInfo info;
1252     info.type = CONNECT_BR;
1253     if (status == SOFTBUS_BR_STATE_TURN_ON) {
1254         g_brEnable = status;
1255         (void)StartLocalListening(&info);
1256     } else if (status == SOFTBUS_BR_STATE_TURN_OFF) {
1257         g_brEnable = status;
1258         (void)StopLocalListening(&info);
1259     }
1260 }
1261 
SppRegisterConnCallback(void)1262 static int32_t SppRegisterConnCallback(void)
1263 {
1264     (void)memset_s(&g_sppBrCallback, sizeof(g_sppBrCallback), 0, sizeof(g_sppBrCallback));
1265     g_sppBrCallback.OnBtStateChanged = StateChangedCallback;
1266     return SppGattsRegisterHalCallback(&g_sppBrCallback);
1267 }
1268 
ConnInitBr(const ConnectCallback * callback)1269 ConnectFuncInterface *ConnInitBr(const ConnectCallback *callback)
1270 {
1271     SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[InitBR]");
1272     if (InitProperty() != SOFTBUS_OK) {
1273         return NULL;
1274     }
1275     g_sppDriver = InitSppSocketDriver();
1276     if (g_sppDriver == NULL) {
1277         return NULL;
1278     }
1279     InitBrConnectionManager(g_brBuffSize);
1280     if (InitBrPendingPacket() != SOFTBUS_OK) {
1281         return NULL;
1282     }
1283     if (BrInnerQueueInit() != SOFTBUS_OK) {
1284         DestroyBrPendingPacket();
1285         return NULL;
1286     }
1287     if (InitDataQueue() != SOFTBUS_OK) {
1288         DestroyBrPendingPacket();
1289         BrInnerQueueDeinit();
1290         return NULL;
1291     }
1292     if (BrConnLooperInit() != SOFTBUS_OK) {
1293         BrInnerQueueDeinit();
1294         DestroyBrPendingPacket();
1295         return NULL;
1296     }
1297     if (SppRegisterConnCallback() != SOFTBUS_OK) {
1298         BrInnerQueueDeinit();
1299         DestroyBrPendingPacket();
1300         DestroyLooper(g_brAsyncHandler.looper);
1301         return NULL;
1302     }
1303     pthread_mutex_init(&g_brConnLock, NULL);
1304     g_connectCallback = (ConnectCallback *)callback;
1305     return &g_brInterface;
1306 }
1307