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