1 /******************************************************************************
2  *
3  *  Copyright 1999-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  This file contains L2CAP interface functions
22  *
23  ******************************************************************************/
24 
25 #include <bluetooth/log.h>
26 
27 #include <cstddef>
28 #include <cstdint>
29 
30 #include "common/time_util.h"
31 #include "internal_include/bt_target.h"
32 #include "osi/include/allocator.h"
33 #include "stack/include/bt_hdr.h"
34 #include "stack/include/bt_psm_types.h"
35 #include "stack/include/l2c_api.h"
36 #include "stack/include/l2cdefs.h"
37 #include "stack/rfcomm/port_int.h"
38 #include "stack/rfcomm/rfc_int.h"
39 #include "types/raw_address.h"
40 
41 using namespace bluetooth;
42 
43 /*
44  * Define Callback functions to be called by L2CAP
45 */
46 static void RFCOMM_ConnectInd(const RawAddress& bd_addr, uint16_t lcid,
47                               uint16_t psm, uint8_t id);
48 static void RFCOMM_ConnectCnf(uint16_t lcid, uint16_t err);
49 static void RFCOMM_ConfigInd(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg);
50 static void RFCOMM_ConfigCnf(uint16_t lcid, uint16_t result,
51                              tL2CAP_CFG_INFO* p_cfg);
52 static void RFCOMM_DisconnectInd(uint16_t lcid, bool is_clear);
53 static void RFCOMM_BufDataInd(uint16_t lcid, BT_HDR* p_buf);
54 static void RFCOMM_CongestionStatusInd(uint16_t lcid, bool is_congested);
55 
56 /*******************************************************************************
57  *
58  * Function         rfcomm_l2cap_if_init
59  *
60  * Description      This function is called during the RFCOMM task startup
61  *                  to register interface functions with L2CAP.
62  *
63  ******************************************************************************/
rfcomm_l2cap_if_init(void)64 void rfcomm_l2cap_if_init(void) {
65   tL2CAP_APPL_INFO* p_l2c = &rfc_cb.rfc.reg_info;
66 
67   p_l2c->pL2CA_ConnectInd_Cb = RFCOMM_ConnectInd;
68   p_l2c->pL2CA_ConnectCfm_Cb = RFCOMM_ConnectCnf;
69   p_l2c->pL2CA_ConfigInd_Cb = RFCOMM_ConfigInd;
70   p_l2c->pL2CA_ConfigCfm_Cb = RFCOMM_ConfigCnf;
71   p_l2c->pL2CA_DisconnectInd_Cb = RFCOMM_DisconnectInd;
72   p_l2c->pL2CA_DataInd_Cb = RFCOMM_BufDataInd;
73   p_l2c->pL2CA_CongestionStatus_Cb = RFCOMM_CongestionStatusInd;
74   p_l2c->pL2CA_TxComplete_Cb = NULL;
75   p_l2c->pL2CA_Error_Cb = rfc_on_l2cap_error;
76 
77   if (!L2CA_Register(BT_PSM_RFCOMM, rfc_cb.rfc.reg_info,
78                      true /* enable_snoop */, nullptr, L2CAP_MTU_SIZE, 0, 0)) {
79     log::error("Unable to register with L2CAP profile RFCOMM psm:{}",
80                BT_PSM_RFCOMM);
81   }
82 }
83 
84 /*******************************************************************************
85  *
86  * Function         RFCOMM_ConnectInd
87  *
88  * Description      This is a callback function called by L2CAP when
89  *                  L2CA_ConnectInd received.  Allocate multiplexer control
90  *                  block and dispatch the event to it.
91  *
92  ******************************************************************************/
RFCOMM_ConnectInd(const RawAddress & bd_addr,uint16_t lcid,uint16_t,uint8_t id)93 void RFCOMM_ConnectInd(const RawAddress& bd_addr, uint16_t lcid,
94                        uint16_t /* psm */, uint8_t id) {
95   tRFC_MCB* p_mcb = rfc_alloc_multiplexer_channel(bd_addr, false);
96 
97   if ((p_mcb) && (p_mcb->state != RFC_MX_STATE_IDLE)) {
98     /* if this is collision case */
99     if ((p_mcb->is_initiator) && (p_mcb->state == RFC_MX_STATE_WAIT_CONN_CNF)) {
100       p_mcb->pending_lcid = lcid;
101 
102       /* wait random timeout (2 - 12) to resolve collision */
103       /* if peer gives up then local device rejects incoming connection and
104        * continues as initiator */
105       /* if timeout, local device disconnects outgoing connection and continues
106        * as acceptor */
107       log::verbose(
108           "RFCOMM_ConnectInd start timer for collision, initiator's "
109           "LCID(0x{:x}), acceptor's LCID(0x{:x})",
110           p_mcb->lcid, p_mcb->pending_lcid);
111 
112       rfc_timer_start(
113           p_mcb,
114           (uint16_t)(bluetooth::common::time_get_os_boottime_ms() % 10 + 2));
115       return;
116     } else {
117       /* we cannot accept connection request from peer at this state */
118       /* don't update lcid */
119       p_mcb = nullptr;
120     }
121   } else {
122     /* store mcb even if null */
123     rfc_save_lcid_mcb(p_mcb, lcid);
124   }
125 
126   if (p_mcb == nullptr) {
127     if (!L2CA_DisconnectReq(lcid)) {
128       log::warn("Unable to disconnect L2CAP cid:{}", lcid);
129     }
130     return;
131   }
132   p_mcb->lcid = lcid;
133 
134   rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONN_IND, &id);
135 }
136 
137 /*******************************************************************************
138  *
139  * Function         RFCOMM_ConnectCnf
140  *
141  * Description      This is a callback function called by L2CAP when
142  *                  L2CA_ConnectCnf received.  Save L2CAP handle and dispatch
143  *                  event to the FSM.
144  *
145  ******************************************************************************/
RFCOMM_ConnectCnf(uint16_t lcid,uint16_t result)146 void RFCOMM_ConnectCnf(uint16_t lcid, uint16_t result) {
147   tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
148 
149   if (!p_mcb) {
150     log::error("RFCOMM_ConnectCnf LCID:0x{:x}", lcid);
151     return;
152   }
153 
154   if (p_mcb->pending_lcid) {
155     /* if peer rejects our connect request but peer's connect request is pending
156      */
157     if (result != L2CAP_CONN_OK) {
158       return;
159     } else {
160       log::verbose("RFCOMM_ConnectCnf peer gave up pending LCID(0x{:x})",
161                    p_mcb->pending_lcid);
162 
163       /* Peer gave up its connection request, make sure cleaning up L2CAP
164        * channel */
165       if (!L2CA_DisconnectReq(p_mcb->pending_lcid)) {
166         log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}",
167                   p_mcb->bd_addr, p_mcb->lcid);
168       }
169 
170       p_mcb->pending_lcid = 0;
171     }
172   }
173 
174   /* Save LCID to be used in all consecutive calls to L2CAP */
175   p_mcb->lcid = lcid;
176 
177   rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONN_CNF, &result);
178 }
179 
180 /*******************************************************************************
181  *
182  * Function         RFCOMM_ConfigInd
183  *
184  * Description      This is a callback function called by L2CAP when
185  *                  L2CA_ConfigInd received.  Save parameters in the control
186  *                  block and dispatch event to the FSM.
187  *
188  ******************************************************************************/
RFCOMM_ConfigInd(uint16_t lcid,tL2CAP_CFG_INFO * p_cfg)189 void RFCOMM_ConfigInd(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) {
190   if (p_cfg == nullptr) {
191     log::error("Received l2cap configuration info with nullptr");
192     return;
193   }
194 
195   tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
196 
197   if (!p_mcb) {
198     log::error("RFCOMM_ConfigInd LCID:0x{:x}", lcid);
199     for (auto& [cid, mcb] : rfc_lcid_mcb) {
200       if (mcb != nullptr && mcb->pending_lcid == lcid) {
201         tL2CAP_CFG_INFO l2cap_cfg_info(*p_cfg);
202         mcb->pending_configure_complete = true;
203         mcb->pending_cfg_info = l2cap_cfg_info;
204         return;
205       }
206     }
207     return;
208   }
209 
210   rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONF_IND, (void*)p_cfg);
211 }
212 
213 /*******************************************************************************
214  *
215  * Function         RFCOMM_ConfigCnf
216  *
217  * Description      This is a callback function called by L2CAP when
218  *                  L2CA_ConfigCnf received.  Save L2CAP handle and dispatch
219  *                  event to the FSM.
220  *
221  ******************************************************************************/
RFCOMM_ConfigCnf(uint16_t lcid,uint16_t,tL2CAP_CFG_INFO * p_cfg)222 void RFCOMM_ConfigCnf(uint16_t lcid, uint16_t /* initiator */,
223                       tL2CAP_CFG_INFO* p_cfg) {
224   RFCOMM_ConfigInd(lcid, p_cfg);
225 
226   tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
227 
228   if (!p_mcb) {
229     log::error("RFCOMM_ConfigCnf no MCB LCID:0x{:x}", lcid);
230     return;
231   }
232   uintptr_t result_as_ptr = L2CAP_CFG_OK;
233   rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONF_CNF, (void*)result_as_ptr);
234 }
235 
236 /*******************************************************************************
237  *
238  * Function         RFCOMM_DisconnectInd
239  *
240  * Description      This is a callback function called by L2CAP when
241  *                  L2CA_DisconnectInd received.  Dispatch event to the FSM.
242  *
243  ******************************************************************************/
RFCOMM_DisconnectInd(uint16_t lcid,bool is_conf_needed)244 void RFCOMM_DisconnectInd(uint16_t lcid, bool is_conf_needed) {
245   log::verbose("lcid:0x{:x}, is_conf_needed:{}", lcid, is_conf_needed);
246   tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
247   if (!p_mcb) {
248     log::warn("no mcb for lcid 0x{:x}", lcid);
249     return;
250   }
251   rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_DISC_IND, nullptr);
252 }
253 
254 /*******************************************************************************
255  *
256  * Function         RFCOMM_BufDataInd
257  *
258  * Description      This is a callback function called by L2CAP when
259  *                  data RFCOMM frame is received.  Parse the frames, check
260  *                  the checksum and dispatch event to multiplexer or port
261  *                  state machine depending on the frame destination.
262  *
263  ******************************************************************************/
RFCOMM_BufDataInd(uint16_t lcid,BT_HDR * p_buf)264 void RFCOMM_BufDataInd(uint16_t lcid, BT_HDR* p_buf) {
265   tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
266 
267   if (!p_mcb) {
268     log::warn("Cannot find RFCOMM multiplexer for lcid 0x{:x}", lcid);
269     osi_free(p_buf);
270     return;
271   }
272 
273   tRFC_EVENT event = rfc_parse_data(p_mcb, &rfc_cb.rfc.rx_frame, p_buf);
274 
275   /* If the frame did not pass validation just ignore it */
276   if (event == RFC_EVENT_BAD_FRAME) {
277     log::warn("Bad RFCOMM frame from lcid=0x{:x}, bd_addr={}, p_mcb={}", lcid,
278               p_mcb->bd_addr, fmt::ptr(p_mcb));
279     osi_free(p_buf);
280     return;
281   }
282 
283   if (rfc_cb.rfc.rx_frame.dlci == RFCOMM_MX_DLCI) {
284     log::verbose("handle multiplexer event {}, p_mcb={}", event,
285                  fmt::ptr(p_mcb));
286     /* Take special care of the Multiplexer Control Messages */
287     if (event == RFC_EVENT_UIH) {
288       rfc_process_mx_message(p_mcb, p_buf);
289       return;
290     }
291 
292     /* Other multiplexer events go to state machine */
293     rfc_mx_sm_execute(p_mcb, static_cast<tRFC_MX_EVENT>(event), nullptr);
294     osi_free(p_buf);
295     return;
296   }
297 
298   /* The frame was received on the data channel DLCI, verify that DLC exists */
299   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, rfc_cb.rfc.rx_frame.dlci);
300   if (p_port == nullptr || !p_port->rfc.p_mcb) {
301     /* If this is a SABME on new port, check if any app is waiting for it */
302     if (event != RFC_EVENT_SABME) {
303       log::warn("no for none-SABME event, lcid=0x{:x}, bd_addr={}, p_mcb={}",
304                 lcid, p_mcb->bd_addr, fmt::ptr(p_mcb));
305       if ((p_mcb->is_initiator && !rfc_cb.rfc.rx_frame.cr) ||
306           (!p_mcb->is_initiator && rfc_cb.rfc.rx_frame.cr)) {
307         log::error("Disconnecting RFCOMM, lcid=0x{:x}, bd_addr={}, p_mcb={}",
308                    lcid, p_mcb->bd_addr, fmt::ptr(p_mcb));
309         rfc_send_dm(p_mcb, rfc_cb.rfc.rx_frame.dlci, rfc_cb.rfc.rx_frame.pf);
310       }
311       osi_free(p_buf);
312       return;
313     }
314 
315     p_port = port_find_dlci_port(rfc_cb.rfc.rx_frame.dlci);
316     if (p_port == nullptr) {
317       log::error(
318           "Disconnecting RFCOMM, no port for dlci {}, lcid=0x{:x}, bd_addr={}, "
319           "p_mcb={}",
320           rfc_cb.rfc.rx_frame.dlci, lcid, p_mcb->bd_addr, fmt::ptr(p_mcb));
321       rfc_send_dm(p_mcb, rfc_cb.rfc.rx_frame.dlci, true);
322       osi_free(p_buf);
323       return;
324     }
325     log::verbose("port_handles[dlci={}]:{}->{}, p_mcb={}",
326                  rfc_cb.rfc.rx_frame.dlci,
327                  p_mcb->port_handles[rfc_cb.rfc.rx_frame.dlci], p_port->handle,
328                  fmt::ptr(p_mcb));
329     p_mcb->port_handles[rfc_cb.rfc.rx_frame.dlci] = p_port->handle;
330     p_port->rfc.p_mcb = p_mcb;
331   }
332 
333   if (event == RFC_EVENT_UIH) {
334     log::verbose("Handling UIH event, buf_len={}, credit={}", p_buf->len,
335                  rfc_cb.rfc.rx_frame.credit);
336     if (p_buf->len > 0) {
337       rfc_port_sm_execute(p_port, static_cast<tRFC_PORT_EVENT>(event), p_buf);
338     } else {
339       osi_free(p_buf);
340     }
341 
342     if (rfc_cb.rfc.rx_frame.credit != 0) {
343       rfc_inc_credit(p_port, rfc_cb.rfc.rx_frame.credit);
344     }
345 
346     return;
347   }
348   rfc_port_sm_execute(p_port, static_cast<tRFC_PORT_EVENT>(event), nullptr);
349   osi_free(p_buf);
350 }
351 
352 /*******************************************************************************
353  *
354  * Function         RFCOMM_CongestionStatusInd
355  *
356  * Description      This is a callback function called by L2CAP when
357  *                  data RFCOMM L2CAP congestion status changes
358  *
359  ******************************************************************************/
RFCOMM_CongestionStatusInd(uint16_t lcid,bool is_congested)360 void RFCOMM_CongestionStatusInd(uint16_t lcid, bool is_congested) {
361   tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
362 
363   if (!p_mcb) {
364     log::error("RFCOMM_CongestionStatusInd dropped LCID:0x{:x}", lcid);
365     return;
366   } else {
367     log::verbose("RFCOMM_CongestionStatusInd LCID:0x{:x}", lcid);
368   }
369   rfc_process_l2cap_congestion(p_mcb, is_congested);
370 }
371 
372 /*******************************************************************************
373  *
374  * Function         rfc_find_lcid_mcb
375  *
376  * Description      This function returns MCB block supporting local cid
377  *
378  ******************************************************************************/
rfc_find_lcid_mcb(uint16_t lcid)379 tRFC_MCB* rfc_find_lcid_mcb(uint16_t lcid) {
380   tRFC_MCB* p_mcb = rfc_lcid_mcb[lcid];
381   if (p_mcb != nullptr) {
382     if (p_mcb->lcid != lcid) {
383       log::warn("LCID reused lcid=:0x{:x}, current_lcid=0x{:x}", lcid,
384                 p_mcb->lcid);
385       return nullptr;
386     }
387   }
388   return p_mcb;
389 }
390 
391 /*******************************************************************************
392  *
393  * Function         rfc_save_lcid_mcb
394  *
395  * Description      This function returns MCB block supporting local cid
396  *
397  ******************************************************************************/
rfc_save_lcid_mcb(tRFC_MCB * p_mcb,uint16_t lcid)398 void rfc_save_lcid_mcb(tRFC_MCB* p_mcb, uint16_t lcid) {
399   auto mcb_index = static_cast<size_t>(lcid);
400   rfc_lcid_mcb[mcb_index] = p_mcb;
401 }
402